//! Search engine seam: the boundary between gn4's `/search` API surface //! (parameter validation, envelope, error contract) and whatever //! backend actually resolves a query. //! //! `/search` is currently a proxy: the [`Engine`] implementation in //! [`gn3`] forwards to GeneNetwork3's xapian-backed `/api/search/`. //! This module defines the seam so a native engine can be dropped in //! behind it later without touching the route's contract. //! //! # Query grammar //! //! The query language below is the xapian query language as configured //! by gn3 (`gn3/gn3/api/search.py`), reconstructed from source in //! Stage A (see the phase-0 grammar spec). gn4 forwards `q` verbatim; //! it does not clean or rewrite it. Any native engine must accept this //! same grammar. //! //! Parser setup: English stemming (`xapian.Stem("en")`, `STEM_ALL_Z`), //! so free-text terms match stemmed and case-insensitively; species //! index prefix `XS`, chromosome index prefix `XC`. //! //! Boolean prefixes (exact terms, value lowercased before matching - the //! index holds only lowercase boolean terms, so `dataset:BXDPublish` and //! `dataset:bxdpublish` are the same query; see `LowercaseProcessor`): //! //! | Prefix | Field | Term | //! |---|---|---| //! | `author` | authors | `A` + value | //! | `species` | species | `XS` + value | //! | `group` | group | `XG` + value | //! | `tissue` | tissue | `XI` + value | //! | `dataset` | dataset | `XDS` + value | //! | `symbol` | gene symbol | `XY` + value | //! | `chr` | chromosome | `XC` + value | //! | `peakchr` | peak chromosome | `XPC` + value | //! //! Probabilistic (free-text-weighted, BM25-scored) prefixes //! (`add_prefix`), freely mixable with free text: //! `description`, `rif` / `RIF`, `wiki` / `WIKI`. //! //! Numeric range prefixes (`NumberRangeProcessor`): `mean`, `peak`, //! `position` / `pos`, `peakmb`, `additive`, `year`. Values are //! `` or `..`, either end open (`mean:..5`). `position` //! additionally accepts SI suffixes (`k`/`m`/`g`) on base-pair //! coordinates and expands a point location to ±50 kb; `Hs::` //! and `Mm::` are species-location shorthands (human/mouse) //! that AND species + chromosome + position, with `Hs` also trying a //! human→mouse liftover. //! //! Operators: `AND`, `OR`, `NOT`, `XOR`, `NEAR`, `ADJ` (uppercase //! only; lowercase forms are plain terms). There is no `&&` operator -- //! it is malformed and surfaces as a parser error from the backend. //! //! Default `type` values: `/search` defaults to `"phenotype"` (gn3's //! own endpoint defaults to `"gene"`); gn4 accepts only `"phenotype"` //! or `"gene"`. `limit` defaults to 20, capped at 100, and is sent to //! the backend as `per_page`. An empty `q` is rejected by gn4's //! validation (400 `invalid_parameter`) before the engine is reached. //! //! # Error contract //! //! The engine reports failures as [`SearchError`]; the route maps them //! onto the shared `ApiError` shapes, one variant per existing code: //! [`SearchError::InvalidQuery`] → 422 `invalid_query`, //! [`SearchError::Unreachable`] → 502 `backend_unreachable`, //! [`SearchError::Misbehaving`] → 502 `backend_misbehaving`, //! [`SearchError::Backend`] → 502 `backend_error`, and //! [`SearchError::Internal`] → 500 `internal_error`. The 400 //! `invalid_parameter` case is parameter validation and stays in the //! route, before the engine is called. //! //! # Enrichment note //! //! [`SearchHit`]'s computed fields (`mean`, `additive`, `lrs`, //! `geno_chr`/`geno_mb`) are NOT in the xapian index: gn3 fills them //! from the database at query time. Any native engine must port those //! enrichment queries -- that is the bulk of the real work of the port. //! The seam deliberately keeps the shape `(q, type, limit) -> //! Vec`; how a native engine splits retrieval from //! enrichment is its own private design, noted here only so the effort //! estimate prices the enrichment in. //! //! # Trait now, two impls //! //! The phase-2 plan originally said "no trait yet" (a trait with one //! impl is speculation). The overnight schedule overrides that: the //! [`Engine`] trait is defined so the native engine can land behind //! it. The gn3-forwarding implementation ([`gn3::Gn3`]) remains the //! default backend; [`native::Native`] is opt-in via `SEARCH_ENGINE` //! (see [`search`]). use std::future::Future; pub mod gn3; pub mod native; /// Run a search through the configured engine: the gn3 forwarder by /// default, the native xapian engine when `SEARCH_ENGINE=native` /// (PORT-DESIGN §6 wiring). Selecting the engine is a config change, /// so flipping back never needs a rebuild or a redeploy. pub async fn search( q: &str, type_: &str, limit: u64, page: u64, ) -> Result, SearchError> { match crate::config::Config::load().search_engine.as_str() { "native" => native::Native.search(q, type_, limit, page).await, _ => gn3::Gn3.search(q, type_, limit, page).await, } } /// One search hit, in gn3's shape. /// /// Every field is optional because gn3 omits computed values (`lrs`, /// `geno_chr`/`geno_mb`) for traits that don't have them. Fields gn3 /// adds in future pass through via `extra`, keeping the proxy /// transparent without freezing the schema to today's gn3. #[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema)] pub struct SearchHit { pub name: Option, pub dataset: Option, pub dataset_fullname: Option, pub group: Option, pub species: Option, pub authors: Option>, pub year: Option, pub description: Option, pub mean: Option, pub additive: Option, pub lrs: Option, /// LOD score, LRS / `db::LRS_PER_LOD` (4.604); the route computes /// it from `lrs`. pub lod: Option, /// Name of the peak marker (a Geno.Name such as "rsm10000012461"), /// looked up in PublishXRef for phenotype hits; null for other /// hits, or when the database is unavailable. pub locus: Option, /// The trait's short name (e.g. "5HT_MB_M"), looked up like `locus`. pub abbreviation: Option, pub geno_chr: Option, pub geno_mb: Option, pub inbredsetcode: Option, pub pubmed_id: Option, #[serde(flatten)] #[schema(value_type = Option>)] pub extra: std::collections::BTreeMap, } /// A search-engine failure, in the vocabulary of the `/search` error /// contract (see the module doc comment). Each variant carries the /// detail text the route forwards in the `ApiError` body; the route /// supplies the HTTP status, `code`, and title for each. #[derive(Debug)] pub enum SearchError { /// The backend rejected the query and supplied a diagnostic (gn3's /// 4xx with a JSON `"error"` field, or the native engine's own /// guards). Maps to 422 `invalid_query`. `xapian_error_type` is the /// backend's own error classification when it has one (the xapian /// exception class — `QueryParserError` for parser rejections, /// `InvalidOperationError` for the Q42 invalid-location class); /// the route forwards it inside the blessed typed 422 body (the /// 2026-10-06 contract, AMENDMENT E). InvalidQuery { /// The human-readable diagnostic (gn3's `error` field / the /// parser's message). message: String, /// The xapian exception class when known (`None` for a backend /// that did not classify its rejection). xapian_error_type: Option, }, /// The backend could not be reached at all (transport failure). /// Maps to 502 `backend_unreachable`. Unreachable(String), /// The backend answered but the response body could not be read or /// decoded. Maps to 502 `backend_misbehaving`. Misbehaving(String), /// The backend returned a non-success status. Maps to 502 /// `backend_error`. Backend(String), /// Local misconfiguration (e.g. an unparsable backend base URL), /// not a backend fault. Maps to 500 `internal_error`. Internal(String), } /// A search backend: resolves a validated `(q, type, limit)` into hits. /// /// One implementation today ([`gn3::Gn3`]); a native engine will be a /// second. The route owns parameter validation before calling this, and /// maps the returned [`SearchError`] onto the shared `ApiError` shapes. pub trait Engine { /// Search for hits matching `q`. `type_` is one of `"phenotype"` or /// `"gene"` (already validated); `limit` is already capped. Returns /// the hits in gn3's shape, or a [`SearchError`] the route maps onto /// the `/search` error contract. fn search( &self, q: &str, type_: &str, limit: u64, page: u64, ) -> impl Future, SearchError>> + Send; }