SPB Git

Repository Public

v2.rs 65.5 KB 1,369 lines rust

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SPSearch9// File             : services/search-api/src/v2.rs10// Module           : services11// Repository       : https://git.spboucher.ai/spweb12// Project Website  : https://search.spboucher.ai13// Created          : 2026-12-0114// Last Modified    : 2026-12-0115//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author           : Simon-Pierre Boucher21// Position         : Professor of Finance22// Institution      : Université du Québec en Outaouais (UQO)23// Department       : Département des sciences administratives24// Organization     : SP Boucher25//26// Website          : https://spboucher.ai27// Git              : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General          : info@spboucher.ai34// Professional     : contact@spboucher.ai35// Direct           : simon@spboucher.ai36// Research         : research@spboucher.ai37// Development      : dev@spboucher.ai38// Support          : support@spboucher.ai39// Security/Admin   : admin@spboucher.ai40// Notifications    : notifications@spboucher.ai41//42// Preferred Contact: contact@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification   : Public67// Distribution     : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License          : None specified (no license file in this repository)81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788//! API de recherche V2 et pipeline SearchRank V2 :89//! compréhension de la requête -> correction orthographique -> candidats (index) -> métadonnées et signaux de90//! texte (catalogue, texte conservé) -> classement -> doublons, diversité, liens de site -> extraits.91//! Le même pipeline sert `/v1/search` (forme de réponse V1) et `/v2/search`.9293use super::*;94use spweb_common::DocId;95use spweb_query::understand::{normalize_input, understand, Understanding};96use spweb_query::ParsedQuery;97use spweb_ranking::v2::{explain, group_lookup, highlights, rank_v2, related, Ctx, RankedV2, WeightsV2, RANKER, SIGNALS};98use std::sync::RwLock;99100pub struct Correction {101    pub applied: bool,102    pub original: String,103    pub suggestion: String,104}105106/// Résultat complet d'une requête (toutes pages), gardé en cache tant que l'index n'a pas changé de version.107pub struct Entry {108    pub at: i64,109    pub version: u64,110    pub ranked: Vec<RankedV2>,111    pub u: Understanding,112    pub parsed: ParsedQuery,113    pub effective: String,114    pub correction: Option<Correction>,115    pub total: u64,116    pub shards_ok: u32,117    pub shards_total: u32,118    pub documents: u64,119    pub relaxed: bool,120    pub degraded: bool,121    pub phrase_unverified: bool,122    pub related: Vec<String>,123    pub retrieval_ms: u64,124    pub rerank_ms: u64,125    pub weights: Arc<WeightsV2>,126}127128pub struct V2State {129    pub weights: RwLock<Arc<WeightsV2>>,130    cache: Mutex<HashMap<String, Arc<Entry>>>,131    spell: Mutex<HashMap<String, (i64, TermInfoV2)>>,132    /// (étiquette, domaine, autorité), triés par étiquette : suggestions de sites.133    pub sites: RwLock<Arc<Vec<(String, String, f32)>>>,134    /// Adresses servies en première page depuis la dernière collecte (Rechecked Engine). Jamais de requête ici.135    served: Mutex<HashMap<String, u32>>,136    favicons: Mutex<HashMap<String, (i64, Option<(bytes::Bytes, &'static str)>)>>,137    news_docs: Mutex<(i64, u64)>,138    favicon_limit: RateLimiter,139    /// Graphie la plus vue (accents) d'un mot replié, apprise des titres servis : « universite » -> « université ».140    surface: Mutex<HashMap<String, (String, i32)>>,141}142143impl V2State {144    pub fn new(w: WeightsV2) -> Self {145        V2State { weights: RwLock::new(Arc::new(w)), cache: Mutex::new(HashMap::new()), spell: Mutex::new(HashMap::new()), sites: RwLock::new(Arc::new(Vec::new())), served: Mutex::new(HashMap::new()), favicons: Mutex::new(HashMap::new()), news_docs: Mutex::new((0, 0)), favicon_limit: RateLimiter::new(Duration::from_secs(60), 50_000), surface: Mutex::new(HashMap::new()) }146    }147}148149/// Charge les pondérations calibrées ; sans fichier (ou fichier invalide), les valeurs par défaut du code.150pub fn load_weights(path: &std::path::Path) -> WeightsV2 {151    if path.as_os_str().is_empty() {152        return WeightsV2::default();153    }154    match std::fs::read_to_string(path).map_err(|e| e.to_string()).and_then(|s| WeightsV2::from_toml(&s)) {155        Ok(w) => w,156        Err(e) => {157            spweb_telemetry::info!("ponderations_invalides", fichier = path.display(), erreur = e);158            WeightsV2::default()159        }160    }161}162163#[derive(serde::Deserialize, Default, Clone)]164pub struct SearchV2Q {165    #[serde(default)]166    pub q: String,167    pub lang: Option<String>,168    pub site: Option<String>,169    pub limit: Option<usize>,170    pub cursor: Option<String>,171    pub from: Option<String>,172    pub to: Option<String>,173    pub fresh: Option<String>,174    pub hl: Option<String>,175    pub region: Option<String>,176    pub vertical: Option<String>,177    pub kind: Option<String>,178    pub correct: Option<String>,179}180181pub struct Prepared {182    pub key: String,183    pub hl: Option<String>,184    pub region: Option<String>,185    pub region_source: &'static str,186    pub kind: Option<String>,187    pub vertical: String,188}189190fn bad(msg: &str, id: &str) -> Response {191    error_response(StatusCode::BAD_REQUEST, "bad_request", msg, id, None)192}193194fn node(app: &App) -> Option<&String> {195    app.cfg.search.index_nodes.first()196}197198/// Fréquences et corrections candidates des termes, avec un cache de dix minutes par terme.199async fn analyze_terms(app: &App, terms: &[String]) -> HashMap<String, TermInfoV2> {200    let now = spweb_common::now();201    let mut out: HashMap<String, TermInfoV2> = HashMap::new();202    let mut missing: Vec<String> = Vec::new();203    {204        let c = app.v2.spell.lock().unwrap();205        for t in terms {206            match c.get(t) {207                Some((at, info)) if now - at < 600 => {208                    out.insert(t.clone(), info.clone());209                }210                _ => missing.push(t.clone()),211            }212        }213    }214    if !missing.is_empty() {215        if let Some(n) = node(app) {216            let req = AnalyzeRequest { terms: missing };217            if let Ok(Ok(resp)) = tokio::time::timeout(Duration::from_millis(250), app.client.post::<_, AnalyzeResponse>(&format!("{}/internal/v2/analyze", n), &req)).await {218                let mut c = app.v2.spell.lock().unwrap();219                if c.len() > 20_000 {220                    c.clear();221                }222                for info in resp.terms {223                    c.insert(info.term.clone(), (now, info.clone()));224                    out.insert(info.term.clone(), info);225                }226            }227        }228    }229    out230}231232fn known_site_label(app: &App, term: &str) -> bool {233    let sites = app.v2.sites.read().unwrap().clone();234    let i = sites.partition_point(|s| s.0.as_str() < term);235    sites.get(i).map(|s| s.0 == term).unwrap_or(false)236}237238/// Décision de correction pour une requête : (requête corrigée, appliquée d'office ?).239/// Appliquée d'office quand le terme tapé est quasi absent des titres et qu'un voisin y est au moins cinquante240/// fois plus fréquent ; simple proposition quand l'écart est moindre.241async fn spell(app: &App, normalized: &str, q: &ParsedQuery) -> Option<(String, bool)> {242    let targets: Vec<String> = q.terms.iter().filter(|t| t.chars().count() >= 4 && t.is_ascii() && !spweb_query::understand::is_stopword(t) && !q.intitle.contains(t)).cloned().collect();243    if targets.is_empty() || q.site.is_some() {244        return None;245    }246    let infos = analyze_terms(app, &targets).await;247    let mut replace: HashMap<String, String> = HashMap::new();248    let mut all_auto = true;249    for t in &targets {250        let Some(info) = infos.get(t) else { continue };251        if known_site_label(app, t) {252            continue;253        }254        // Une distance de 2 coûte un facteur 8 : la correction la plus proche gagne à fréquence comparable.255        let best = info.candidates.iter().map(|c| (c, c.1 as f64 / if c.2 >= 2 { 8.0 } else { 1.0 })).max_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));256        let Some((c, weight)) = best else { continue };257        let df = info.df as f64;258        if weight >= 15.0 * (df + 1.0) {259            let auto = weight >= 50.0 * (df + 1.0) && info.df < 60;260            all_auto &= auto;261            replace.insert(t.clone(), c.0.clone());262        }263    }264    if replace.is_empty() {265        return None;266    }267    // Reconstruit la requête mot à mot : seuls les mots corrigés changent, le reste garde sa forme.268    let fixed: Vec<String> = normalized269        .split(' ')270        .map(|w| {271            let core = w.trim_matches(|c: char| !c.is_alphanumeric());272            match replace.get(&spweb_query::fold(core)) {273                Some(r) if !core.is_empty() && !w.contains(':') && !w.starts_with('-') => w.replace(core, r),274                _ => w.to_string(),275            }276        })277        .collect();278    let fixed = fixed.join(" ");279    if fixed == normalized {280        return None;281    }282    Some((fixed, all_auto))283}284285/// Redonne à une requête corrigée (termes repliés, sans accents) la graphie la plus fréquente dans les titres286/// des meilleurs résultats : « universite laval » -> « université laval ».287fn restore_surface(effective: &str, ranked: &[RankedV2]) -> String {288    let mut forms: HashMap<String, HashMap<String, u32>> = HashMap::new();289    for r in ranked.iter().take(30) {290        for w in r.hit.title.split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()) {291            let lower = w.to_lowercase();292            *forms.entry(spweb_query::fold(&lower)).or_default().entry(lower).or_insert(0) += 1;293        }294    }295    effective296        .split(' ')297        .map(|w| {298            if w.contains(':') || w.chars().any(|c| !c.is_ascii()) {299                return w.to_string();300            }301            match forms.get(&spweb_query::fold(w)).and_then(|m| m.iter().max_by_key(|(k, n)| (**n, std::cmp::Reverse(k.len()))).map(|x| x.0.clone())) {302                Some(s) if s != w && spweb_query::fold(&s) == spweb_query::fold(w) => s,303                _ => w.to_string(),304            }305        })306        .collect::<Vec<_>>()307        .join(" ")308}309310/// Valide les paramètres communs et rend la requête analysée prête à chercher.311pub fn prepare(_app: &App, p: &SearchV2Q, h: &HeaderMap, raw: &str, id: &str) -> Result<(ParsedQuery, Prepared), Response> {312    let mut q = spweb_query::parse(raw).map_err(|e| bad(e.message(), id))?;313    if let Some(l) = p.lang.as_deref().filter(|s| !s.is_empty()) {314        if !(2..=3).contains(&l.len()) || !l.chars().all(|c| c.is_ascii_lowercase()) {315            return Err(bad("paramètre lang invalide", id));316        }317        // Un code à deux lettres doit être un code de langue ISO 639-1 : « zz » rendait zéro résultat sans rien dire.318        const ISO1: &str = "aa ab ae af ak am an ar as av ay az ba be bg bh bi bm bn bo br bs ca ce ch co cr cs cu cv cy da de dv dz ee el en eo es et eu fa ff fi fj fo fr fy ga gd gl gn gu gv ha he hi ho hr ht hu hy hz ia id ie ig ii ik io is it iu ja jv ka kg ki kj kk kl km kn ko kr ks ku kv kw ky la lb lg li ln lo lt lu lv mg mh mi mk ml mn mr ms mt my na nb nd ne ng nl nn no nr nv ny oc oj om or os pa pi pl ps pt qu rm rn ro ru rw sa sc sd se sg si sk sl sm sn so sq sr ss st su sv sw ta te tg th ti tk tl tn to tr ts tt tw ty ug uk ur uz ve vi vo wa wo xh yi yo za zh zu";319        if l.len() == 2 && !ISO1.split(' ').any(|c| c == l) {320            return Err(bad("paramètre lang : code de langue inconnu (ISO 639-1 attendu, par exemple fr, en, de)", id));321        }322        q.lang = Some(l.to_string());323    }324    if let Some(s) = p.site.as_deref().filter(|s| !s.is_empty()) {325        q.site = spweb_query::parse(&format!("x site:{}", s)).map_err(|_| bad("paramètre site invalide", id))?.site;326    }327    for (v, slot, end) in [(p.from.as_deref(), &mut q.from, false), (p.to.as_deref(), &mut q.to, true)] {328        if let Some(d) = v.filter(|s| !s.is_empty()) {329            match spweb_policy::directives::parse_date(d).filter(|_| d.len() == 10) {330                Some(t) => *slot = Some(if end { t + 86_399 } else { t }),331                None => return Err(bad("date invalide (AAAA-MM-JJ)", id)),332            }333        }334    }335    let now = spweb_common::now();336    if let Some(f) = p.fresh.as_deref().filter(|s| !s.is_empty()) {337        let days = match f {338            "day" => 1,339            "week" => 7,340            "month" => 31,341            "year" => 366,342            _ => return Err(bad("paramètre fresh invalide (day, week, month, year)", id)),343        };344        q.from = Some(now - days * 86_400);345    }346    let vertical = match p.vertical.as_deref().unwrap_or("web") {347        "" | "web" => "web",348        "news" => "news",349        _ => return Err(bad("catégorie inconnue (voir /v2/filters)", id)),350    };351    // Actualités : pages dont la date de publication est vérifiée et récente (quatre-vingt-dix jours au plus).352    if vertical == "news" && q.from.is_none() {353        q.from = Some(now - 90 * 86_400);354    }355    let kind = p.kind.as_deref().filter(|k| !k.is_empty()).map(|k| k.to_ascii_lowercase());356    if let Some(k) = &kind {357        if k.len() > 20 || !k.chars().all(|c| c.is_ascii_lowercase()) {358            return Err(bad("paramètre kind invalide", id));359        }360    }361    let hl = p.hl.as_deref().filter(|l| l.len() == 2 && l.chars().all(|c| c.is_ascii_lowercase())).map(|s| s.to_string());362    // Localisation sans pistage : choix explicite d'abord, sinon la région déclarée par le navigateur. Jamais l'IP.363    let valid_region = |r: &str| -> bool {364        let (c, s) = r.split_once('-').unwrap_or((r, ""));365        c.len() == 2 && c.chars().all(|x| x.is_ascii_lowercase()) && s.len() <= 3 && s.chars().all(|x| x.is_ascii_lowercase())366    };367    let (region, region_source): (Option<String>, &'static str) = match p.region.as_deref().map(|r| r.to_ascii_lowercase()) {368        Some(r) if r == "none" => (None, "off"),369        Some(r) if valid_region(&r) => (Some(r), "choice"),370        _ => {371            let from_lang = h.get("accept-language").and_then(|v| v.to_str().ok()).and_then(|v| v.split(',').filter_map(|part| part.split(';').next()).map(|t| t.trim()).find_map(|t| t.split_once('-').map(|x| x.1.to_ascii_lowercase())).filter(|c| c.len() == 2 && c.chars().all(|x| x.is_ascii_lowercase())));372            match from_lang {373                Some(c) => (Some(c), "browser"),374                None => (None, "none"),375            }376        }377    };378    let key = format!("v2|{}|{}|{}|{}|{}", q.cache_key(), hl.as_deref().unwrap_or(""), region.as_deref().unwrap_or(""), vertical, kind.as_deref().unwrap_or(""));379    Ok((q, Prepared { key, hl, region, region_source, kind, vertical: vertical.to_string() }))380}381382/// Exécute le pipeline pour une requête analysée (hors correction). `Err` : index indisponible.383async fn execute(app: &App, effective: &str, q: ParsedQuery, pr: &Prepared, correction: Option<Correction>) -> Option<Entry> {384    let now = spweb_common::now();385    let n = node(app)?;386    let u = understand(effective, &q);387    let t0 = Instant::now();388    let req = SearchV2Request { query: q.clone(), content: u.content.clone(), optional: u.optional.clone(), expansions: u.expansions.clone(), k: app.cfg.search.candidates };389    let timeout = Duration::from_millis(app.cfg.search.shard_timeout_ms + 300);390    let resp: SearchResponse = match tokio::time::timeout(timeout, app.client.post::<_, SearchResponse>(&format!("{}/internal/v2/search", n), &req)).await {391        Ok(Ok(r)) => r,392        _ => return None,393    };394    let retrieval_ms = t0.elapsed().as_millis() as u64;395    spweb_telemetry::observe_ms("v2_retrieval_ms", retrieval_ms);396    let t1 = Instant::now();397    let mut hits = resp.hits;398    {399        let auth = app.authority.read().unwrap().clone();400        if !auth.is_empty() {401            for h in hits.iter_mut() {402                h.authority = auth.get(&h.domain).copied().unwrap_or(0.0);403            }404        }405    }406    // Les candidats qui recevront les signaux de texte : ceux des passes « site » et « titre », puis les407    // meilleurs scores lexicaux.408    let mut order: Vec<usize> = (0..hits.len()).collect();409    order.sort_by(|&a, &b| {410        let ka = (hits[a].site_match || hits[a].title_match) as u8;411        let kb = (hits[b].site_match || hits[b].title_match) as u8;412        kb.cmp(&ka).then(hits[b].bm25.partial_cmp(&hits[a].bm25).unwrap_or(std::cmp::Ordering::Equal))413    });414    let ereq = EnrichV2Request { ids: order.iter().map(|&i| hits[i].doc_id).collect(), text_n: app.cfg.search.text_candidates, content: u.content.clone(), expansions: u.expansions.clone(), phrases: q.phrases.clone() };415    let te = Instant::now();416    let mut degraded = false;417    match tokio::time::timeout(Duration::from_millis(500), app.client.post::<_, EnrichV2Response>(&format!("{}/internal/v2/enrich", n), &ereq)).await {418        Ok(Ok(e)) => {419            let meta: HashMap<DocId, DocMeta> = e.docs.into_iter().map(|m| (m.id, m)).collect();420            hits.retain_mut(|h| match meta.get(&h.doc_id) {421                Some(m) => {422                    h.checked_at = m.checked_at;423                    h.published_at = m.published_at;424                    h.quality = m.quality;425                    h.words = m.words;426                    h.tier = m.tier;427                    h.simhash = m.simhash;428                    h.validation = m.validation;429                    h.text = m.text;430                    true431                }432                // Absent du catalogue : retiré depuis la dernière copie de l'index.433                None => false,434            });435        }436        _ => {437            degraded = true;438            spweb_telemetry::inc("v2_degraded_total");439        }440    }441    spweb_telemetry::observe_ms("v2_enrich_ms", te.elapsed().as_millis() as u64);442    if let Some(k) = &pr.kind {443        hits.retain(|h| spweb_ranking::v2::page_kind(&h.url, &h.domain, h.published_at.is_some()) == k.as_str());444    }445    let want_phrases = q.phrases.iter().any(|p| p.len() >= 2);446    let phrase_unverified = want_phrases && !resp.phrase_supported && (degraded || hits.iter().any(|h| h.text.is_none()));447    let weights = app.v2.weights.read().unwrap().clone();448    let tr = Instant::now();449    let ctx = Ctx { u: &u, phrases: &q.phrases, terms: &q.terms, hl: pr.hl.as_deref(), region: pr.region.as_deref(), now };450    let ranked = rank_v2(hits, &ctx, &weights, None);451    spweb_telemetry::observe_ms("v2_rank_ms", tr.elapsed().as_millis() as u64);452    learn_surface(app, &ranked);453    let (effective, correction) = match correction {454        Some(mut c) => {455            let nice = restore_surface(&c.suggestion, &ranked);456            c.suggestion = nice.clone();457            (if c.applied { nice } else { effective.to_string() }, Some(c))458        }459        None => (effective.to_string(), None),460    };461    let rel = related(&ranked, &u, &effective, 8);462    let rerank_ms = t1.elapsed().as_millis() as u64;463    app.latest_version.fetch_max(resp.index_version, Ordering::Relaxed);464    Some(Entry { at: now, version: resp.index_version, ranked, u, parsed: q, effective, correction, total: resp.total, shards_ok: resp.shards_ok, shards_total: resp.shards_total, documents: resp.documents, relaxed: resp.relaxed, degraded, phrase_unverified, related: rel, retrieval_ms, rerank_ms, weights })465}466467/// Pipeline complet avec cache. `correct` : appliquer la correction orthographique d'office.468pub async fn pipeline(app: &App, p: &SearchV2Q, h: &HeaderMap, correct: bool, id: &str) -> Result<(Arc<Entry>, Prepared, bool), Response> {469    let normalized = normalize_input(&p.q);470    let (q, mut pr) = prepare(app, p, h, &normalized, id)?;471    pr.key.push_str(if correct { "|c1" } else { "|c0" });472    let now = spweb_common::now();473    let latest = app.latest_version.load(Ordering::Relaxed);474    if let Some(e) = app.v2.cache.lock().unwrap().get(&pr.key).filter(|e| now - e.at <= app.cfg.search.cache_ttl_s && e.version == latest && e.shards_ok == e.shards_total && !e.degraded).cloned() {475        spweb_telemetry::inc("cache_hits_total");476        return Ok((e, pr, true));477    }478    let unavailable = || error_response(StatusCode::SERVICE_UNAVAILABLE, "unavailable", "l'index est momentanément indisponible", id, Some(5));479    // Correction orthographique : jamais sur une phrase exacte seule ni quand l'utilisateur la refuse.480    let fix = if q.terms.is_empty() { None } else { spell(app, &normalized, &q).await };481    let entry = match fix {482        Some((fixed, auto)) if auto && correct => match spweb_query::parse(&fixed) {483            Ok(mut fq) => {484                fq.lang = q.lang.clone();485                fq.site = q.site.clone();486                fq.from = q.from;487                fq.to = q.to;488                // Garde-fou : un terme rare n'est pas forcément une faute (« sutton barto », « accèsd »). Si la requête489                // telle que tapée trouve déjà des pages qui contiennent tous ses termes, et que la version corrigée490                // n'en trouve pas massivement plus, on garde la requête d'origine et on propose seulement.491                let original = execute(app, &normalized, q.clone(), &pr, Some(Correction { applied: false, original: normalized.clone(), suggestion: fixed.clone() })).await.ok_or_else(unavailable)?;492                let strict_n = if original.relaxed { 0 } else { original.total };493                let c = Correction { applied: true, original: normalized.clone(), suggestion: fixed.clone() };494                if strict_n < 10 {495                    execute(app, &fixed, fq, &pr, Some(c)).await.ok_or_else(unavailable)?496                } else {497                    let corrected = execute(app, &fixed, fq, &pr, Some(c)).await.ok_or_else(unavailable)?;498                    if !corrected.relaxed && corrected.total >= 30 * strict_n {499                        corrected500                    } else {501                        spweb_telemetry::inc("v2_correction_withheld_total");502                        original503                    }504                }505            }506            Err(_) => execute(app, &normalized, q, &pr, None).await.ok_or_else(unavailable)?,507        },508        Some((fixed, _)) => execute(app, &normalized, q, &pr, Some(Correction { applied: false, original: normalized.clone(), suggestion: fixed })).await.ok_or_else(unavailable)?,509        None => execute(app, &normalized, q, &pr, None).await.ok_or_else(unavailable)?,510    };511    let entry = Arc::new(entry);512    let mut c = app.v2.cache.lock().unwrap();513    if c.len() >= app.cfg.search.cache_entries {514        let ttl = app.cfg.search.cache_ttl_s;515        c.retain(|_, e| now - e.at <= ttl);516        if c.len() >= app.cfg.search.cache_entries {517            c.clear();518        }519    }520    c.insert(pr.key.clone(), entry.clone());521    Ok((entry, pr, false))522}523524/// Extraits adaptés à la requête pour une page de résultats.525async fn page_snippets(app: &App, e: &Entry, page: &[&RankedV2]) -> HashMap<DocId, String> {526    let mut out = HashMap::new();527    let ids: Vec<DocId> = page.iter().filter(|r| r.hit.tier >= 2).map(|r| r.hit.doc_id).collect();528    let (Some(n), false) = (node(app), ids.is_empty()) else { return out };529    let mut content = e.u.content.clone();530    for t in e.parsed.phrases.iter().flatten() {531        if !content.contains(t) {532            content.push(t.clone());533        }534    }535    let req = SnippetV2Request { doc_ids: ids, content, expansions: e.u.expansions.clone(), max_chars: app.cfg.index.snippet_max_chars };536    if let Ok(Ok(resp)) = tokio::time::timeout(Duration::from_millis(350), app.client.post::<_, SnippetResponse>(&format!("{}/internal/v2/snippets", n), &req)).await {537        out.extend(resp.snippets);538    }539    out540}541542fn display_url(url: &str) -> String {543    let s = url.split_once("://").map(|x| x.1).unwrap_or(url);544    let s = s.strip_prefix("www.").unwrap_or(s);545    let (host, path) = s.split_once('/').unwrap_or((s, ""));546    let path = path.split(['?', '#']).next().unwrap_or("").trim_end_matches('/');547    if path.is_empty() {548        return host.to_string();549    }550    let segs: Vec<&str> = path.split('/').filter(|x| !x.is_empty()).collect();551    let shown: Vec<String> = segs.iter().take(3).map(|x| spweb_common::truncate_chars(x, 32)).collect();552    format!("{} › {}{}", host, shown.join(" › "), if segs.len() > 3 { " › …" } else { "" })553}554555/// Retire d'un titre ou d'un extrait les restes de balisage (commentaires HTML, balises, marques d'ancre).556fn clean_text(s: &str) -> String {557    if !s.contains(['<', '', '\\']) {558        return s.to_string();559    }560    let mut out = String::with_capacity(s.len());561    let mut rest = s;562    while let Some(i) = rest.find('<') {563        out.push_str(&rest[..i]);564        let tail = &rest[i..];565        if let Some(t) = tail.strip_prefix("<!--") {566            match t.find("-->") {567                Some(j) => rest = &t[j + 3..],568                None => {569                    rest = "";570                }571            }572            continue;573        }574        // Balise plausible : « < » suivi d'une lettre ou de « / », fermée à moins de 80 caractères.575        let looks = tail[1..].chars().next().map(|c| c.is_ascii_alphabetic() || c == '/').unwrap_or(false);576        match (looks, tail.char_indices().take(80).find(|(_, c)| *c == '>')) {577            (true, Some((j, _))) => rest = &tail[j + 1..],578            _ => {579                out.push('<');580                rest = &tail[1..];581            }582        }583    }584    out.push_str(rest);585    // Sauts de ligne restés sous forme littérale dans la source (« \n\n » d'un gabarit mal échappé).586    let out = out.replace('', " ").replace("\\n", " ").replace("\\r", " ").replace("\\t", " ");587    out.split_whitespace().collect::<Vec<_>>().join(" ")588}589590/// Segments d'un titre autour des séparateurs usuels.591fn title_parts(t: &str) -> Vec<&str> {592    t.split(" | ").flat_map(|x| x.split(" - ")).flat_map(|x| x.split(" – ")).flat_map(|x| x.split(" — ")).flat_map(|x| x.split(" · ")).flat_map(|x| x.split(" :: ")).map(|x| x.trim()).filter(|x| x.chars().count() >= 2).collect()593}594595const GENERIC_TITLES: &[&str] = &["accueil", "home", "bienvenue", "welcome", "homepage", "page d'accueil", "home page", "index", "startseite", "inicio", "start"];596597/// Un segment de titre nomme-t-il le site ? (« Université Laval » pour ulaval.ca, « La Presse » pour lapresse.ca)598fn names_site(seg: &str, label: &str) -> bool {599    let words: Vec<String> = spweb_query::tokenize(seg);600    if words.is_empty() || words.len() > 7 {601        return false;602    }603    let content: Vec<&str> = words.iter().map(|w| w.as_str()).filter(|w| !spweb_query::understand::is_stopword(w)).collect();604    let label = label.replace('-', "");605    let all = words.concat();606    let cc = content.concat();607    if all == label || cc == label {608        return true;609    }610    if label.chars().count() >= 4 && (all.contains(&label) || (cc.chars().count() >= 4 && label.contains(&cc))) {611        return true;612    }613    if content.len() >= 2 {614        let initials: String = content.iter().filter_map(|w| w.chars().next()).collect();615        let all_initials: String = words.iter().filter_map(|w| w.chars().next()).collect();616        let first_rest = format!("{}{}", content[0].chars().take(1).collect::<String>(), content[1..].concat());617        if initials == label || all_initials == label || first_rest == label {618            return true;619        }620    }621    false622}623624/// Nom du site : le segment du titre qui nomme le site ; à défaut, pour une page d'accueil, son segment le plus625/// court qui ne soit pas un mot générique (« Accueil »). `None` : l'interface affiche le domaine.626fn site_name(r: &RankedV2) -> Option<String> {627    let title = clean_text(&r.hit.title);628    let parts = title_parts(&title);629    let label = r.hit.domain.split('.').next().unwrap_or("");630    if let Some(p) = parts.iter().find(|p| p.chars().count() <= 48 && names_site(p, label)) {631        return Some(p.to_string());632    }633    let path = r.hit.url.split_once("://").map(|x| x.1).unwrap_or("").split_once('/').map(|x| x.1).unwrap_or("");634    if !path.trim_matches('/').is_empty() {635        return None;636    }637    parts.into_iter().filter(|x| !GENERIC_TITLES.contains(&spweb_query::fold(x).as_str())).min_by_key(|x| x.chars().count()).filter(|x| x.chars().count() <= 40).map(|x| x.to_string())638}639640/// Titre court d'un lien de site : le premier segment du titre qui ne nomme pas le site.641fn sitelink_title(title: &str, domain: &str) -> String {642    let t = clean_text(title);643    let label = domain.split('.').next().unwrap_or("");644    let parts = title_parts(&t);645    let pick = parts.iter().find(|p| !names_site(p, label) && !GENERIC_TITLES.contains(&spweb_query::fold(p).as_str())).or(parts.first()).map(|p| p.to_string());646    spweb_common::truncate_chars(&pick.unwrap_or(t), 60)647}648649/// Apprend la graphie des mots à partir des titres servis (vote majoritaire à mémoire constante par mot).650fn learn_surface(app: &App, ranked: &[RankedV2]) {651    let mut m = app.v2.surface.lock().unwrap();652    if m.len() > 300_000 {653        m.retain(|_, v| v.1 >= 3);654    }655    for r in ranked.iter().take(40) {656        for w in r.hit.title.split(|c: char| !c.is_alphanumeric()).filter(|w| w.chars().count() >= 3 && w.chars().count() <= 30) {657            let lower = w.to_lowercase();658            let key = spweb_query::fold(&lower);659            match m.get_mut(&key) {660                Some(e) if e.0 == lower => e.1 = (e.1 + 1).min(1_000_000),661                Some(e) => {662                    e.1 -= 1;663                    if e.1 <= 0 {664                        *e = (lower, 1);665                    }666                }667                None => {668                    m.insert(key, (lower, 1));669                }670            }671        }672    }673}674675/// Redonne ses accents à une suggestion repliée : les mots tels que l'utilisateur les a tapés d'abord, puis la676/// graphie apprise ; sinon le mot reste tel quel.677fn surface_text(app: &App, suggestion: &str, typed: &str) -> String {678    let typed_words: HashMap<String, String> = typed.split_whitespace().map(|w| (spweb_query::fold(&w.to_lowercase()), w.to_lowercase())).collect();679    let m = app.v2.surface.lock().unwrap();680    suggestion681        .split(' ')682        .map(|w| {683            if w.contains(':') || w.chars().any(|c| !c.is_ascii()) {684                return w.to_string();685            }686            if let Some(t) = typed_words.get(w) {687                return t.clone();688            }689            match m.get(w) {690                Some((form, n)) if *n >= 2 => form.clone(),691                _ => w.to_string(),692            }693        })694        .collect::<Vec<_>>()695        .join(" ")696}697698fn ranges_json(v: Vec<(usize, usize)>) -> serde_json::Value {699    serde_json::json!(v.into_iter().map(|(a, b)| [a, b]).collect::<Vec<_>>())700}701702fn result_json(r: &RankedV2, snippet: Option<&String>, lookup: &HashMap<String, usize>, degraded: bool) -> serde_json::Value {703    let (snip, source) = match snippet {704        Some(s) => (s.as_str(), "query"),705        None if r.hit.snippet.trim().is_empty() => ("", "none"),706        None => (r.hit.snippet.as_str(), "static"),707    };708    let snip_clean = clean_text(snip);709    let snip = snip_clean.as_str();710    let title = clean_text(&r.hit.title);711    let v = &r.hit.validation;712    let validation = if degraded || v.state == 0 {713        serde_json::json!({"state": "unknown", "validated_at": null, "http_status": null})714    } else {715        serde_json::json!({"state": v.state_str(), "validated_at": if v.validated_at > 0 { Some(v.validated_at) } else { None }, "http_status": if v.http_status > 0 { Some(v.http_status) } else { None }, "first_seen": if v.first_seen > 0 { Some(v.first_seen) } else { None }, "changed_at": if v.changed_at > 0 { Some(v.changed_at) } else { None }})716    };717    serde_json::json!({718        "id": r.hit.doc_id, "title": title, "url": r.hit.url, "display_url": display_url(&r.hit.url), "domain": r.hit.domain,719        "site_name": site_name(r), "favicon": format!("/v2/favicon?domain={}", r.hit.domain),720        "snippet": snip, "snippet_source": source, "highlights": ranges_json(highlights(snip, lookup)), "title_highlights": ranges_json(highlights(&title, lookup)),721        "language": r.hit.lang, "kind": r.kind, "published_at": r.hit.published_at, "checked_at": if r.hit.checked_at > 0 { Some(r.hit.checked_at) } else { None },722        "validation": validation,723        "sitelinks": r.sitelinks.iter().map(|(t, u)| serde_json::json!({"title": sitelink_title(t, &r.hit.domain), "url": u})).collect::<Vec<_>>(),724        "more_from_site": r.more_from_site, "words": r.hit.words, "tier": r.hit.tier, "authority": r.hit.authority,725    })726}727728fn facets(ranked: &[RankedV2]) -> serde_json::Value {729    let facet = |key: &dyn Fn(&RankedV2) -> String, max: usize| -> Vec<serde_json::Value> {730        let mut m: HashMap<String, u64> = HashMap::new();731        for r in ranked.iter() {732            *m.entry(key(r)).or_insert(0) += 1;733        }734        let mut v: Vec<(String, u64)> = m.into_iter().filter(|(k, _)| !k.is_empty()).collect();735        v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));736        v.into_iter().take(max).map(|(k, n)| serde_json::json!({"value": k, "count": n})).collect()737    };738    serde_json::json!({"domains": facet(&|r| r.hit.domain.clone(), 8), "languages": facet(&|r| r.hit.lang.clone(), 8), "kinds": facet(&|r| r.kind.to_string(), 12), "candidates": ranked.len()})739}740741fn record_served(app: &App, page: &[&RankedV2]) {742    let mut s = app.v2.served.lock().unwrap();743    if s.len() > 50_000 {744        return;745    }746    // Seules les adresses dont le dernier contrôle date de plus d'un jour méritent une revalidation.747    let stale = spweb_common::now() - 86_400;748    for r in page {749        if r.hit.checked_at < stale {750            *s.entry(r.hit.url.clone()).or_insert(0) += 1;751        }752    }753}754755/// Revalidation continue (« Rechecked ») : les adresses servies aux utilisateurs et non contrôlées depuis un756/// jour sont proposées au robot, les plus servies d'abord. Le robot les relit avec une requête conditionnelle757/// (ETag / Last-Modified), sous les mêmes règles que toute exploration (robots.txt, politesse) ; une page758/// disparue sort de l'index, une page modifiée est réindexée. Jamais de contrôle HTTP pendant une recherche.759pub async fn revalidation_loop(app: Arc<App>) {760    const PER_ROUND: usize = 200;761    let mut recent: HashMap<String, i64> = HashMap::new();762    loop {763        tokio::time::sleep(Duration::from_secs(300)).await;764        let now = spweb_common::now();765        recent.retain(|_, at| now - *at < 86_400);766        let mut v: Vec<(String, u32)> = {767            let mut m = app.v2.served.lock().unwrap();768            std::mem::take(&mut *m).into_iter().filter(|(u, _)| !recent.contains_key(u)).collect()769        };770        v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));771        let (mut sent, mut refused) = (0u64, 0u64);772        for (url, _) in v.into_iter().take(PER_ROUND) {773            match app.client.post_raw(&format!("{}/internal/v1/submit", app.cfg.worker.coordinator_url), &serde_json::json!({"url": url})).await {774                Ok((202, _)) => {775                    sent += 1;776                    recent.insert(url, now);777                }778                Ok((503, _)) | Err(_) => break, // file pleine ou coordinateur injoignable : on réessaiera779                Ok(_) => {780                    refused += 1;781                    recent.insert(url, now);782                }783            }784        }785        spweb_telemetry::add("revalidation_submitted_total", sent);786        spweb_telemetry::add("revalidation_refused_total", refused);787        spweb_telemetry::set("revalidation_last_round", sent as i64);788    }789}790791struct Paged<'a> {792    page: Vec<&'a RankedV2>,793    next_cursor: Option<String>,794    notices: Vec<&'static str>,795    relation: &'static str,796    total_value: u64,797    partial: bool,798}799800fn paginate<'a>(app: &App, e: &'a Entry, pr: &Prepared, cursor: Option<&str>, limit: usize, id: &str) -> Result<Paged<'a>, Response> {801    let key_hash = spweb_common::hex(&spweb_common::sha256(pr.key.as_bytes())[..8]);802    let now = spweb_common::now();803    let mut notices: Vec<&'static str> = Vec::new();804    let mut offset = 0usize;805    if let Some(c) = cursor.filter(|s| !s.is_empty()) {806        match spweb_common::unseal::<Cursor>(&app.key, c) {807            Some(cur) if cur.k == key_hash && cur.e >= now => offset = cur.o,808            Some(cur) if cur.k == key_hash => notices.push("cursor_expired"),809            _ => return Err(bad("curseur invalide pour cette requête", id)),810        }811    }812    let partial = e.shards_ok < e.shards_total;813    if partial {814        notices.push("partial_shards");815        app.partial.fetch_add(1, Ordering::Relaxed);816        spweb_telemetry::inc("partial_results_total");817    }818    if e.relaxed {819        notices.push("relaxed_to_any_term");820    }821    let page: Vec<&RankedV2> = e.ranked.iter().skip(offset).take(limit).collect();822    let next = offset + limit;823    let depth_cap = app.cfg.search.candidates;824    let next_cursor = if next < e.ranked.len() {825        Some(spweb_common::seal(&app.key, &Cursor { k: key_hash, o: next, e: now + app.cfg.search.cursor_ttl_s }))826    } else {827        if (e.total as usize) > e.ranked.len() && e.ranked.len() >= depth_cap / 2 {828            notices.push("depth_limit");829        }830        None831    };832    let relation = if partial { "gte" } else if (e.total as usize) <= e.ranked.len() { "eq" } else { "estimate" };833    let total_value = if relation == "eq" { e.ranked.len() as u64 } else { e.total };834    Ok(Paged { page, next_cursor, notices, relation, total_value, partial })835}836837pub async fn search_v2(State(app): S, ConnectInfo(peer): ConnectInfo<SocketAddr>, h: HeaderMap, Query(p): Query<SearchV2Q>) -> Response {838    let id = rid();839    let started = Instant::now();840    let ip = client_ip(&h, peer, &app.cfg.search.trusted_proxies);841    if let Some(r) = limited(&app, &ip, &id) {842        return r;843    }844    app.queries.fetch_add(1, Ordering::Relaxed);845    spweb_telemetry::inc("queries_total");846    let correct = p.correct.as_deref() != Some("0");847    let (e, pr, cached) = match pipeline(&app, &p, &h, correct, &id).await {848        Ok(x) => x,849        Err(r) => {850            spweb_telemetry::inc("search_errors_total");851            return r;852        }853    };854    let limit = p.limit.unwrap_or(10).clamp(1, 20);855    let mut pg = match paginate(&app, &e, &pr, p.cursor.as_deref(), limit, &id) {856        Ok(x) => x,857        Err(r) => return r,858    };859    if p.limit.map(|l| l != limit).unwrap_or(false) {860        pg.notices.push("limit_clamped");861    }862    if e.ranked.is_empty() {863        app.queries_no_results.fetch_add(1, Ordering::Relaxed);864        spweb_telemetry::inc("query_no_results_total");865    }866    if e.degraded {867        pg.notices.push("degraded_metadata");868    }869    if e.phrase_unverified {870        pg.notices.push("phrase_unverified");871    }872    let ts = Instant::now();873    let snippets = if e.degraded { HashMap::new() } else { page_snippets(&app, &e, &pg.page).await };874    let snippets_ms = ts.elapsed().as_millis() as u64;875    spweb_telemetry::observe_ms("v2_snippets_ms", snippets_ms);876    let (lookup, _) = group_lookup(&e.u, &e.parsed.phrases);877    let results: Vec<serde_json::Value> = pg.page.iter().map(|r| result_json(r, snippets.get(&r.hit.doc_id), &lookup, e.degraded)).collect();878    if p.cursor.is_none() {879        record_served(&app, &pg.page);880    }881    let correction = e.correction.as_ref().map(|c| serde_json::json!({"applied": c.applied, "original": c.original, "suggestion": c.suggestion}));882    let elapsed = started.elapsed().as_millis() as u64;883    spweb_telemetry::observe_ms("search_ms", elapsed);884    spweb_telemetry::observe_ms("v2_total_ms", elapsed);885    spweb_telemetry::observe_ms(&format!("v2_intent_{}_ms", e.u.intent.as_str()), elapsed);886    let (rl_limit, rl_left, rl_reset) = app.ip_limit.peek(&ip.to_string(), app.cfg.search.per_ip_per_min);887    let mut resp = json_response(888        StatusCode::OK,889        &serde_json::json!({890            "request_id": id, "ranker": RANKER, "weights": e.weights.version,891            "query": {"raw": p.q, "effective": e.effective, "language": e.u.language, "intent": shown_intent(&e), "correction": correction,892                      "terms": e.u.content, "optional": e.u.optional,893                      "expansions": e.u.expansions.iter().map(|(t, a)| serde_json::json!({"term": t, "added": a})).collect::<Vec<_>>(),894                      "geo": e.u.geo},895            "results": results, "related": e.related, "facets": facets(&e.ranked),896            "total": {"value": pg.total_value, "relation": pg.relation}, "next_cursor": pg.next_cursor,897            "coverage": {"documents": e.documents, "shards_ok": e.shards_ok, "shards_total": e.shards_total},898            "region": {"value": pr.region, "source": pr.region_source}, "vertical": pr.vertical,899            "partial": pg.partial, "notices": pg.notices, "index_version": e.version,900            "timing": {"total_ms": elapsed, "retrieval_ms": if cached { 0 } else { e.retrieval_ms }, "rerank_ms": if cached { 0 } else { e.rerank_ms }, "snippets_ms": snippets_ms, "cached": cached},901        }),902    );903    for (k, v) in [("x-ratelimit-limit", rl_limit as u64), ("x-ratelimit-remaining", rl_left as u64), ("x-ratelimit-reset", rl_reset)] {904        if let Ok(hv) = v.to_string().parse() {905            resp.headers_mut().insert(k, hv);906        }907    }908    resp909}910911/// Intention annoncée au client. « navigational » sans indice explicite n'est qu'une hypothèse du pipeline :912/// elle n'est annoncée que si le classement a réellement trouvé un site dont le nom correspond.913fn shown_intent(e: &Entry) -> &'static str {914    if e.u.intent == spweb_query::understand::Intent::Navigational && !e.u.nav_hint {915        let named = |r: &RankedV2| SIGNALS.iter().zip(r.signals.iter()).any(|(n, v)| (*n == "site_strong" || *n == "site_home_auth") && *v > 0.0);916        if !e.ranked.iter().take(3).any(named) {917            return "informational";918        }919    }920    e.u.intent.as_str()921}922923/// `/v1/search` : même pipeline et même classement que la V2, forme de réponse de la V1 (clients existants).924pub async fn search_v1(State(app): S, ConnectInfo(peer): ConnectInfo<SocketAddr>, h: HeaderMap, Query(p): Query<SearchV2Q>) -> Response {925    let id = rid();926    let started = Instant::now();927    let ip = client_ip(&h, peer, &app.cfg.search.trusted_proxies);928    if let Some(r) = limited(&app, &ip, &id) {929        return r;930    }931    app.queries.fetch_add(1, Ordering::Relaxed);932    spweb_telemetry::inc("queries_total");933    // La V1 ne sait pas afficher une correction : la requête est cherchée telle quelle.934    let p = SearchV2Q { vertical: None, kind: None, fresh: None, ..p };935    let (e, pr, _) = match pipeline(&app, &p, &h, false, &id).await {936        Ok(x) => x,937        Err(r) => return r,938    };939    let limit = p.limit.unwrap_or(10).clamp(1, 20);940    let mut pg = match paginate(&app, &e, &pr, p.cursor.as_deref(), limit, &id) {941        Ok(x) => x,942        Err(r) => return r,943    };944    if e.ranked.is_empty() {945        app.queries_no_results.fetch_add(1, Ordering::Relaxed);946        spweb_telemetry::inc("query_no_results_total");947    }948    if e.phrase_unverified {949        pg.notices.push("phrase_unsupported");950    }951    let snippets = if e.degraded { HashMap::new() } else { page_snippets(&app, &e, &pg.page).await };952    let page: Vec<serde_json::Value> = pg953        .page954        .iter()955        .map(|r| {956            let dynamic = snippets.get(&r.hit.doc_id);957            serde_json::json!({"id": r.hit.doc_id, "title": clean_text(&r.hit.title), "url": r.hit.url, "domain": r.hit.domain, "snippet": dynamic.unwrap_or(&r.hit.snippet), "snippet_source": if dynamic.is_some() { "query" } else { "static" }, "tier": r.hit.tier, "language": r.hit.lang, "checked_at": r.hit.checked_at, "published_at": r.hit.published_at, "words": r.hit.words, "kind": r.kind, "authority": r.hit.authority})958        })959        .collect();960    if p.cursor.is_none() {961        record_served(&app, &pg.page);962    }963    let f = facets(&e.ranked);964    let elapsed = started.elapsed().as_millis() as u64;965    spweb_telemetry::observe_ms("search_ms", elapsed);966    json_response(967        StatusCode::OK,968        &serde_json::json!({969            "request_id": id, "results": page, "next_cursor": pg.next_cursor,970            "total": {"value": pg.total_value, "relation": pg.relation},971            "coverage": {"documents": e.documents, "shards_ok": e.shards_ok, "shards_total": e.shards_total, "tier": "B"},972            "partial": pg.partial, "notices": pg.notices, "index_version": e.version, "elapsed_ms": elapsed,973            "facets": {"domains": f["domains"], "languages": f["languages"], "candidates": f["candidates"]},974            "region": {"value": pr.region, "source": pr.region_source},975        }),976    )977}978979fn admin_ok(app: &App, h: &HeaderMap) -> bool {980    let Some(tok) = bearer(h) else { return false };981    let digest = spweb_common::hex(&spweb_common::sha256(tok.as_bytes()));982    app.admin_hashes.iter().any(|k| !k.is_empty() && spweb_common::ct_eq(k.as_bytes(), digest.as_bytes())) || internal_ok(h, &app.internal_token)983}984985/// Search Debugger : chaque candidat avec la valeur, le poids et la contribution de chaque signal.986pub async fn explain_v2(State(app): S, h: HeaderMap, Query(p): Query<SearchV2Q>) -> Response {987    let id = rid();988    if !admin_ok(&app, &h) {989        return error_response(StatusCode::UNAUTHORIZED, "unauthorized", "jeton d'administration requis", &id, None);990    }991    let correct = p.correct.as_deref() != Some("0");992    let (e, pr, _) = match pipeline(&app, &p, &h, correct, &id).await {993        Ok(x) => x,994        Err(r) => return r,995    };996    let limit = p.limit.unwrap_or(30).clamp(1, 400);997    let weights = e.weights.resolve(e.u.intent);998    let rows: Vec<serde_json::Value> = e999        .ranked1000        .iter()1001        .take(limit)1002        .enumerate()1003        .map(|(i, r)| {1004            let ex = explain(r, e.u.intent, &e.weights);1005            serde_json::json!({1006                "rank": i + 1, "id": r.hit.doc_id, "score": r.score, "title": r.hit.title, "url": r.hit.url, "domain": r.hit.domain, "kind": r.kind, "language": r.hit.lang,1007                "bm25": r.hit.bm25, "passes": {"title": r.hit.title_match, "site": r.hit.site_match, "relaxed": r.hit.relaxed},1008                "text": r.hit.text, "validation": r.hit.validation, "quality": r.hit.quality, "authority": r.hit.authority, "tier": r.hit.tier, "words": r.hit.words,1009                "published_at": r.hit.published_at, "checked_at": r.hit.checked_at,1010                "signals": ex.iter().filter(|x| x.1 != 0.0).map(|x| serde_json::json!({"signal": x.0, "value": x.1, "weight": x.2, "contribution": x.3})).collect::<Vec<_>>(),1011                "vector": r.signals,1012            })1013        })1014        .collect();1015    json_response(1016        StatusCode::OK,1017        &serde_json::json!({1018            "request_id": id, "ranker": RANKER, "weights_version": e.weights.version, "signal_names": SIGNALS, "weights": weights.to_vec(),1019            "query": {"raw": p.q, "effective": e.effective, "language": e.u.language, "intent": e.u.intent.as_str(), "content": e.u.content, "optional": e.u.optional, "expansions": e.u.expansions, "geo": e.u.geo, "fresh": e.u.fresh, "nav_hint": e.u.nav_hint},1020            "region": pr.region, "candidates": e.ranked.len(), "total": e.total, "degraded": e.degraded, "timing": {"retrieval_ms": e.retrieval_ms, "rerank_ms": e.rerank_ms},1021            "results": rows,1022        }),1023    )1024}10251026#[derive(serde::Deserialize)]1027pub struct QOnly {1028    #[serde(default)]1029    q: String,1030}10311032/// Suggestions de sites : domaines dont l'étiquette commence par le préfixe, les plus autorisés d'abord.1033fn site_suggestions(app: &App, prefix: &str, max: usize) -> Vec<(String, f32)> {1034    let sites = app.v2.sites.read().unwrap().clone();1035    let start = sites.partition_point(|s| s.0.as_str() < prefix);1036    let mut v: Vec<(String, f32)> = sites[start..].iter().take_while(|s| s.0.starts_with(prefix)).take(4000).map(|s| (s.1.clone(), s.2)).collect();1037    v.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal).then(a.0.len().cmp(&b.0.len())));1038    v.truncate(max);1039    v1040}10411042pub async fn autocomplete(State(app): S, ConnectInfo(peer): ConnectInfo<SocketAddr>, h: HeaderMap, Query(p): Query<QOnly>) -> Response {1043    let started = Instant::now();1044    let ip = client_ip(&h, peer, &app.cfg.search.trusted_proxies);1045    let empty = || json_response(StatusCode::OK, &serde_json::json!({"suggestions": []}));1046    let q = normalize_input(&p.q);1047    if app.ip_limit.check(&format!("s{}", ip), app.cfg.search.per_ip_per_min * 6).is_err() || q.chars().count() < 2 || q.len() > 100 {1048        return empty();1049    }1050    let Some(n) = node(&app) else { return empty() };1051    let enc: String = url::form_urlencoded::byte_serialize(q.as_bytes()).collect();1052    let completions: Vec<String> = match tokio::time::timeout(Duration::from_millis(90), app.client.get::<serde_json::Value>(&format!("{}/internal/v2/complete?q={}", n, enc))).await {1053        Ok(Ok(v)) => v["suggestions"].as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(|s| s.to_string())).collect()).unwrap_or_default(),1054        _ => Vec::new(),1055    };1056    let mut out: Vec<serde_json::Value> = Vec::new();1057    // Un seul mot d'au moins trois lettres : proposer aussi les sites dont le nom commence ainsi.1058    let folded = spweb_query::fold(&q);1059    if !folded.contains(' ') && folded.chars().count() >= 3 && folded.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.') {1060        let label = folded.split('.').next().unwrap_or("");1061        for (domain, auth) in site_suggestions(&app, label, 2) {1062            if auth >= 0.5 {1063                out.push(serde_json::json!({"text": domain, "title": domain, "type": "site", "url": format!("https://{}/", domain)}));1064            }1065        }1066    }1067    for c in completions.into_iter().take(8 - out.len().min(8)) {1068        if c != folded {1069            out.push(serde_json::json!({"text": surface_text(&app, &c, &q), "type": "completion"}));1070        }1071    }1072    // Rien à compléter : la saisie contient peut-être une faute.1073    if out.is_empty() && folded.chars().count() >= 4 {1074        if let Ok(pq) = spweb_query::parse(&q) {1075            if let Some((fixed, _)) = spell(&app, &q, &pq).await {1076                out.push(serde_json::json!({"text": surface_text(&app, &fixed, &q), "type": "correction"}));1077            }1078        }1079    }1080    spweb_telemetry::observe_ms("v2_autocomplete_ms", started.elapsed().as_millis() as u64);1081    json_response(StatusCode::OK, &serde_json::json!({"suggestions": out}))1082}10831084pub async fn spell_v2(State(app): S, ConnectInfo(peer): ConnectInfo<SocketAddr>, h: HeaderMap, Query(p): Query<QOnly>) -> Response {1085    let id = rid();1086    let ip = client_ip(&h, peer, &app.cfg.search.trusted_proxies);1087    if let Some(r) = limited(&app, &ip, &id) {1088        return r;1089    }1090    let q = normalize_input(&p.q);1091    let pq = match spweb_query::parse(&q) {1092        Ok(x) => x,1093        Err(e) => return bad(e.message(), &id),1094    };1095    let fixed = spell(&app, &q, &pq).await.map(|x| surface_text(&app, &x.0, &q));1096    json_response(StatusCode::OK, &serde_json::json!({"original": q, "suggestion": fixed, "changed": fixed.is_some()}))1097}10981099pub async fn related_v2(State(app): S, ConnectInfo(peer): ConnectInfo<SocketAddr>, h: HeaderMap, Query(p): Query<SearchV2Q>) -> Response {1100    let id = rid();1101    let ip = client_ip(&h, peer, &app.cfg.search.trusted_proxies);1102    if let Some(r) = limited(&app, &ip, &id) {1103        return r;1104    }1105    match pipeline(&app, &p, &h, true, &id).await {1106        Ok((e, _, _)) => json_response(StatusCode::OK, &serde_json::json!({"related": e.related})),1107        Err(r) => r,1108    }1109}11101111async fn news_documents(app: &App) -> u64 {1112    let now = spweb_common::now();1113    {1114        let c = app.v2.news_docs.lock().unwrap();1115        if now - c.0 < 900 {1116            return c.1;1117        }1118    }1119    let Some(n) = node(app) else { return 0 };1120    let v = app.client.get::<serde_json::Value>(&format!("{}/internal/v2/count-published?from={}&to={}", n, now - 90 * 86_400, now + 86_400)).await.ok().and_then(|v| v["documents"].as_u64()).unwrap_or(0);1121    *app.v2.news_docs.lock().unwrap() = (now, v);1122    v1123}11241125/// Ce que l'index permet réellement de filtrer : les catégories vides ne sont pas annoncées.1126pub async fn filters_v2(State(app): S) -> Response {1127    let id = rid();1128    let Some(st) = index_stats(&app).await else { return error_response(StatusCode::SERVICE_UNAVAILABLE, "unavailable", "statistiques indisponibles", &id, Some(10)) };1129    let mut verticals = vec![serde_json::json!({"id": "web", "documents": st["documents"]})];1130    let news = news_documents(&app).await;1131    if news >= 1000 {1132        verticals.push(serde_json::json!({"id": "news", "documents": news}));1133    }1134    let languages: Vec<serde_json::Value> = st["languages"].as_array().map(|a| a.iter().filter(|l| l["language"] != "und").take(20).map(|l| serde_json::json!({"value": l["language"], "documents": l["documents"]})).collect()).unwrap_or_default();1135    json_response(1136        StatusCode::OK,1137        &serde_json::json!({1138            "verticals": verticals, "languages": languages,1139            "kinds": ["encyclopedia", "documentation", "forum", "shop", "blog", "news", "government", "university", "home", "article", "organisation", "page"],1140            "regions": ["ca", "ca-qc", "fr", "be", "ch", "lu", "us", "gb", "de", "es", "it", "nl", "au"],1141            "fresh": ["day", "week", "month", "year"],1142        }),1143    )1144}11451146pub async fn stats_v2(State(app): S) -> Response {1147    let id = rid();1148    match index_stats(&app).await {1149        Some(st) => {1150            let t = &st["tiers"];1151            json_response(1152                StatusCode::OK,1153                &serde_json::json!({1154                    "documents": st["documents"], "domains": st["domains"], "languages": st["languages"], "index_bytes": st["physical_bytes"], "bytes_per_doc": st["bytes_per_doc"],1155                    "updated_at": st["updated_at"], "index_version": st["index_version"],1156                    "tiers": {"sparse": t[1], "standard": t[2], "premium": t[3]},1157                    "freshness": {"median_age_s": st["median_age_s"], "p90_age_s": st["p90_age_s"]},1158                    "text": {"documents": st["text_docs"], "bytes": st["text_bytes"]},1159                }),1160            )1161        }1162        None => error_response(StatusCode::SERVICE_UNAVAILABLE, "unavailable", "statistiques indisponibles", &id, Some(10)),1163    }1164}11651166/// État public des services. `index_primary` est déduit de la dernière requête d'enrichissement.1167pub async fn status_v2(State(app): S) -> Response {1168    let now = spweb_common::now();1169    let st = index_stats(&app).await;1170    let replica = if st.is_some() { "ok" } else { "down" };1171    let snap = spweb_telemetry::registry().snapshot();1172    // Le primaire est jugé sur l'âge de l'index : la réplique reçoit une copie chaque minute quand il vit.1173    let updated = st.as_ref().and_then(|s| s["updated_at"].as_i64()).unwrap_or(0);1174    let primary = match (st.as_ref(), now - updated) {1175        (None, _) => "down",1176        (Some(_), age) if age < 900 => "ok",1177        (Some(_), age) if age < 7200 => "degraded",1178        _ => "down",1179    };1180    let status = if replica == "down" { "down" } else if primary != "ok" { "degraded" } else { "ok" };1181    let index = match &st {1182        Some(s) => serde_json::json!({"documents": s["documents"], "domains": s["domains"], "version": s["index_version"], "updated_at": s["updated_at"], "median_age_s": s["median_age_s"], "p90_age_s": s["p90_age_s"]}),1183        None => serde_json::Value::Null,1184    };1185    json_response(1186        StatusCode::OK,1187        &serde_json::json!({1188            "status": status, "ranker": RANKER, "weights": app.v2.weights.read().unwrap().version, "index": index,1189            "services": {"search": "ok", "index_replica": replica, "index_primary": primary, "semantic": "off"},1190            "queries": snap.get("queries_total").copied().unwrap_or(0), "time": now,1191        }),1192    )1193}11941195#[derive(serde::Deserialize)]1196pub struct FaviconQ {1197    #[serde(default)]1198    domain: String,1199}12001201fn image_type(b: &[u8]) -> Option<&'static str> {1202    if b.starts_with(&[0x89, b'P', b'N', b'G']) {1203        Some("image/png")1204    } else if b.starts_with(&[0, 0, 1, 0]) {1205        Some("image/x-icon")1206    } else if b.starts_with(b"GIF8") {1207        Some("image/gif")1208    } else if b.starts_with(&[0xFF, 0xD8, 0xFF]) {1209        Some("image/jpeg")1210    } else {1211        None1212    }1213}12141215/// Icône d'un site, relayée : le navigateur de l'utilisateur ne contacte jamais le site tiers avant un clic.1216/// Mêmes gardes que le robot (adresse publique, robots.txt, taille), formats matriciels seulement, cache borné.1217pub async fn favicon(State(app): S, ConnectInfo(peer): ConnectInfo<SocketAddr>, h: HeaderMap, Query(p): Query<FaviconQ>) -> Response {1218    let not_found = || {1219        let mut r = Response::new(axum::body::Body::empty());1220        *r.status_mut() = StatusCode::NOT_FOUND;1221        r.headers_mut().insert("cache-control", "public, max-age=86400".parse().unwrap());1222        security_headers(r.headers_mut());1223        r1224    };1225    let serve = |bytes: bytes::Bytes, ct: &'static str| {1226        let mut r = Response::new(axum::body::Body::from(bytes));1227        r.headers_mut().insert("content-type", ct.parse().unwrap());1228        r.headers_mut().insert("cache-control", "public, max-age=604800".parse().unwrap());1229        r.headers_mut().insert("x-content-type-options", "nosniff".parse().unwrap());1230        security_headers(r.headers_mut());1231        r1232    };1233    let domain = p.domain.trim().trim_start_matches("www.").to_ascii_lowercase();1234    if domain.len() > 253 || !domain.contains('.') || !domain.split('.').all(|l| !l.is_empty() && l.len() <= 63 && l.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')) {1235        return not_found();1236    }1237    let now = spweb_common::now();1238    {1239        let c = app.v2.favicons.lock().unwrap();1240        if let Some((at, v)) = c.get(&domain) {1241            if now - at < if v.is_some() { 7 * 86_400 } else { 86_400 } {1242                return match v {1243                    Some((b, ct)) => serve(b.clone(), ct),1244                    None => not_found(),1245                };1246            }1247        }1248    }1249    // Seuls les sites présents dans l'index sont relayés : ce n'est pas un mandataire ouvert.1250    if !app.authority.read().unwrap().contains_key(&domain) && !app.cfg.test_mode() {1251        return not_found();1252    }1253    let ip = client_ip(&h, peer, &app.cfg.search.trusted_proxies);1254    if app.v2.favicon_limit.check(&ip.to_string(), 240).is_err() {1255        return not_found();1256    }1257    // Marque l'essai en cours : une rafale de pages ne lance qu'une lecture par site.1258    {1259        let mut c = app.v2.favicons.lock().unwrap();1260        if c.len() > 20_000 {1261            c.retain(|_, (at, _)| now - *at < 86_400);1262            if c.len() > 20_000 {1263                c.clear();1264            }1265        }1266        c.insert(domain.clone(), (now, None));1267    }1268    let fetched = fetch_favicon(&app, &domain).await;1269    app.v2.favicons.lock().unwrap().insert(domain, (now, fetched.clone()));1270    match fetched {1271        Some((b, ct)) => serve(b, ct),1272        None => not_found(),1273    }1274}12751276async fn fetch_favicon(app: &App, domain: &str) -> Option<(bytes::Bytes, &'static str)> {1277    let opts = spweb_urlnorm::Opts { allow_test_hosts: app.cfg.test_mode(), allow_any_ext: true };1278    let n = spweb_urlnorm::normalize(&format!("https://{}/favicon.ico", domain), None, opts).ok()?;1279    let url = url::Url::parse(&n.url).ok()?;1280    let cached = { app.live_robots.lock().unwrap().get(&n.authority).filter(|e| e.0.elapsed() < Duration::from_secs(86_400)).map(|e| e.1.clone()) };1281    let rules = match cached {1282        Some(r) => r,1283        None => {1284            let (out, body, _) = spweb_fetcher::fetch_robots(&app.fetcher, &n.authority).await;1285            let r = match out {1286                RobotsFetchOutcome::Parse => Some(Robots::parse(body.as_bytes(), spweb_common::ROBOTS_TOKEN)),1287                RobotsFetchOutcome::AllowAll => Some(Robots::allow_all()),1288                RobotsFetchOutcome::Suspend => None,1289            };1290            {1291                let mut m = app.live_robots.lock().unwrap();1292                if m.len() > 5000 {1293                    m.clear();1294                }1295                m.insert(n.authority.clone(), (Instant::now(), r.clone()));1296            }1297            tokio::time::sleep(Duration::from_millis(app.cfg.coordinator.min_delay_ms.min(2000))).await;1298            r1299        }1300    };1301    let rules = rules?;1302    if !rules.allowed("/favicon.ico") {1303        return None;1304    }1305    let reg = n.domain.clone();1306    let test = app.cfg.test_mode();1307    let allow_hop = move |t: &url::Url| spweb_urlnorm::normalize(t.as_str(), None, spweb_urlnorm::Opts { allow_test_hosts: test, allow_any_ext: true }).map(|x| x.domain == reg).unwrap_or(false);1308    let f = app.fetcher.get(&url, None, "image/png,image/x-icon,image/*;q=0.8", 96 * 1024, &allow_hop).await.ok()?;1309    spweb_telemetry::inc("favicon_fetch_total");1310    if f.status != 200 || f.truncated || f.body.len() < 16 {1311        return None;1312    }1313    let ct = image_type(&f.body)?;1314    Some((f.body, ct))1315}13161317/// Mesures internes : quantiles de latence par étape, taux de cache, requêtes sans résultat.1318pub async fn metrics_v2(State(app): S, h: HeaderMap) -> Response {1319    if !internal_ok(&h, &app.internal_token) && !admin_ok(&app, &h) {1320        return json_response(StatusCode::UNAUTHORIZED, &serde_json::json!({"error": "non autorisé"}));1321    }1322    let reg = spweb_telemetry::registry();1323    let snap = reg.snapshot();1324    let mut lat = serde_json::Map::new();1325    for name in ["v2_total_ms", "v2_retrieval_ms", "v2_enrich_ms", "v2_rank_ms", "v2_snippets_ms", "v2_autocomplete_ms", "search_ms", "v2_intent_navigational_ms", "v2_intent_informational_ms", "v2_intent_commercial_ms", "v2_intent_local_ms", "v2_intent_scientific_ms", "v2_intent_news_ms", "v2_intent_documentary_ms", "v2_intent_technical_ms"] {1326        let hst = reg.histogram(name);1327        let (p50, p95, p99) = hst.quantiles();1328        lat.insert(name.to_string(), serde_json::json!({"count": hst.count(), "p50": p50, "p95": p95, "p99": p99}));1329    }1330    let g = |k: &str| snap.get(k).copied().unwrap_or(0);1331    let queries = g("queries_total").max(1);1332    json_response(1333        StatusCode::OK,1334        &serde_json::json!({1335            "ranker": RANKER, "weights": app.v2.weights.read().unwrap().version, "latency_ms": lat,1336            "queries": g("queries_total"), "cache_hits": g("cache_hits_total"), "cache_rate": g("cache_hits_total") as f64 / queries as f64,1337            "no_results": g("query_no_results_total"), "no_result_rate": g("query_no_results_total") as f64 / queries as f64,1338            "errors": g("search_errors_total"), "degraded": g("v2_degraded_total"), "partial": g("partial_results_total"), "rate_limited": g("rate_limited_total"),1339            "favicon_fetches": g("favicon_fetch_total"), "served_pending": app.v2.served.lock().unwrap().len(),1340            "rss_bytes": spweb_telemetry::rss_bytes(),1341        }),1342    )1343}13441345/// Rechecked Engine : rend puis vide la liste des adresses servies en première page (avec leur nombre1346/// d'affichages), pour que le robot les revalide en priorité. Aucune requête d'utilisateur n'y figure.1347pub async fn served_drain(State(app): S, h: HeaderMap) -> Response {1348    if !internal_ok(&h, &app.internal_token) {1349        return json_response(StatusCode::UNAUTHORIZED, &serde_json::json!({"error": "non autorisé"}));1350    }1351    let m = std::mem::take(&mut *app.v2.served.lock().unwrap());1352    let mut v: Vec<(String, u32)> = m.into_iter().collect();1353    v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));1354    v.truncate(5000);1355    json_response(StatusCode::OK, &serde_json::json!({"urls": v}))1356}13571358pub async fn aasa(State(app): S) -> Response {1359    match tokio::fs::read(app.cfg.search.web_dir.join(".well-known/apple-app-site-association")).await {1360        Ok(b) => {1361            let mut r = Response::new(axum::body::Body::from(b));1362            r.headers_mut().insert("content-type", "application/json".parse().unwrap());1363            r.headers_mut().insert("cache-control", "public, max-age=3600".parse().unwrap());1364            r1365        }1366        Err(_) => error_response(StatusCode::NOT_FOUND, "not_found", "introuvable", &rid(), None),1367    }1368}1369
Files main
Menu

Theme