diff options
| author | Alexander_Kabui <alexanderkabua@gmail.com> | 2026-10-04 11:31:28 +0300 |
|---|---|---|
| committer | Alexander_Kabui <alexanderkabua@gmail.com> | 2026-10-05 21:53:57 +0300 |
| commit | a6a4a0efd270e8aa32a8f45eb6cc0203af240528 (patch) | |
| tree | daaa47fc651f534482c4160f832d022b5788a93d /src | |
| parent | a96a50963a7830cdc257a7452f15a6964262b947 (diff) | |
| download | genenetwork4-a6a4a0efd270e8aa32a8f45eb6cc0203af240528.tar.gz | |
* src/routes/search.rs (search): add GET /search, the phase-A gn3
search proxy.
Validates q/type/limit at the boundary (400 with suggestions; limit
capped at 100), forwards to {GN3_URL}/search/ with proper
percent-encoding, and re-wraps hits in the descriptive envelope.
Hits are typed as SearchHit (all 14 gn3 fields optional, unknown
fields preserved via serde flatten) so /openapi.json documents a
real schema while staying transparent to gn3 shape changes. gn3's
400+parsererror becomes 422 invalid_query carrying gn3's own
diagnostic; every other backend failure is one 502 shape
distinguished by code.
* src/lib.rs, src/routes/mod.rs (routes): register the search route.
* tests/search.rs, test/data/search_alcohol_phenotype.json (tests):
in-process gn3 stub replays the recorded production fixture; four
scenarios run offline -- passthrough+envelope, validation, 422
forwarding, limit cap.
Diffstat (limited to 'src')
| -rw-r--r-- | src/lib.rs | 1 | ||||
| -rw-r--r-- | src/routes/mod.rs | 1 | ||||
| -rw-r--r-- | src/routes/search.rs | 185 |
3 files changed, 187 insertions, 0 deletions
diff --git a/src/lib.rs b/src/lib.rs index b1f004c..f524429 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -70,6 +70,7 @@ pub fn app() -> Router { .routes(routes!(routes::traits::traits)) .routes(routes!(routes::traits::trait_info)) .routes(routes!(routes::traits::trait_values)) + .routes(routes!(routes::search::search)) .routes(routes!(routes::correlation::correlation)); // Only registered -- so only ever reachable, and only ever // documented in /openapi.json -- when config says this is a diff --git a/src/routes/mod.rs b/src/routes/mod.rs index 7a7a01a..fd1ef4a 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -7,5 +7,6 @@ pub mod correlation; pub mod datasets; pub mod dev; pub mod groups; +pub mod search; pub mod species; pub mod traits; diff --git a/src/routes/search.rs b/src/routes/search.rs new file mode 100644 index 0000000..9ae568f --- /dev/null +++ b/src/routes/search.rs @@ -0,0 +1,185 @@ +//! Search domain endpoint. +//! +//! Phase A (gn4-api-foundation.gmi "Pilot: search"): proxies gn3's +//! /api/search (xapian-backed) and re-wraps the hits in the +//! descriptive envelope. gn3's hit objects pass through untouched; +//! gn4 contributes boundary validation and the contract. + +use axum::Json; +use axum::extract::{Extension, Query}; +use axum::http::StatusCode; +use serde::Deserialize; +use tower_http::request_id::RequestId; + +use crate::error::ApiError; +use crate::request_id_string; +use crate::response::Envelope; + +/// Query parameters for `GET /search`. +/// +/// Named for LLM callers (`q`, `type`, `limit`) rather than gn3's +/// (`query`, `target`, `per_page`); the handler translates. +#[derive(Deserialize, utoipa::IntoParams)] +pub struct SearchParams { + /// Free-text query, e.g. "alcohol". Xapian query syntax is accepted. + pub q: String, + /// What to search: "phenotype" (default) or "gene". + #[param(value_type = Option<String>)] + pub r#type: Option<String>, + /// Maximum hits to return (default 20, capped at 100). + pub limit: Option<u64>, +} + +/// 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<String>, + pub dataset: Option<String>, + pub dataset_fullname: Option<String>, + pub group: Option<String>, + pub species: Option<String>, + pub authors: Option<Vec<String>>, + pub year: Option<u16>, + pub description: Option<String>, + pub mean: Option<f64>, + pub additive: Option<f64>, + pub lrs: Option<f64>, + pub geno_chr: Option<String>, + pub geno_mb: Option<f64>, + pub inbredsetcode: Option<String>, + #[serde(flatten)] + #[schema(value_type = Option<std::collections::BTreeMap<String, String>>)] + pub extra: std::collections::BTreeMap<String, serde_json::Value>, +} + +/// gn3's error body for unparseable queries. +#[derive(Deserialize)] +struct Gn3ParseError { + error: String, + #[serde(rename = "error_message")] + error_message: String, +} + +#[utoipa::path(get, path = "/search", + summary = "Search traits across GN datasets", + description = "Proxies GeneNetwork3's xapian search (phase A; see \ +topics/gn4/gn4-api-foundation.gmi). Hits are gn3's trait objects passed \ +through unchanged, wrapped in the descriptive envelope. Malformed \ +queries forward gn3's parser diagnostic as a 422.", + params(SearchParams), + responses( + (status = 200, description = "Matching traits, gn3 shape", body = Envelope<Vec<SearchHit>>), + (status = 400, description = "Missing or invalid parameter", body = ApiError), + (status = 422, description = "Query unparsable by the search backend; carries gn3's diagnostic", body = ApiError), + (status = 502, description = "Search backend unreachable or misbehaving", body = ApiError) +))] +pub async fn search( + Extension(request_id): Extension<RequestId>, + Query(params): Query<SearchParams>, +) -> Result<Json<Envelope<Vec<SearchHit>>>, ApiError> { + let rid = request_id_string(&request_id); + let bad_request = |detail: &str| { + ApiError::new( + StatusCode::BAD_REQUEST, + "invalid_parameter", + "Invalid parameter", + detail.to_string(), + "search", + ) + .with_request_id(rid.clone()) + }; + + let q = params.q.trim(); + if q.is_empty() { + return Err(bad_request("q must not be empty")); + } + let search_type = params.r#type.as_deref().unwrap_or("phenotype"); + if !matches!(search_type, "phenotype" | "gene") { + return Err(bad_request( + "type must be \"phenotype\" or \"gene\"; see /openapi.json", + )); + } + let limit = params.limit.unwrap_or(20).min(100); + + // Every gn3-side failure maps to one 502 shape; the caller can tell + // connectivity, protocol, and backend errors apart by `code`. + let backend_error = |code: &str, detail: String| { + ApiError::new( + StatusCode::BAD_GATEWAY, + code, + "Search backend failure", + detail, + "search", + ) + .with_request_id(rid.clone()) + }; + + let gn3_url = crate::config::Config::load().gn3_url; + let url = url::Url::parse_with_params( + &format!("{}search/", gn3_url), + [ + ("query", q), + ("type", search_type), + ("per_page", &limit.to_string()), + ], + ) + .map_err(|e| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Internal error", + format!("GN3_URL {gn3_url} is not a valid base URL: {e}"), + "search", + ) + .with_request_id(rid.clone()) + })?; + + let response = reqwest::get(url) + .await + .map_err(|e| backend_error("backend_unreachable", e.to_string()))?; + + let status = response.status(); + let body = response + .text() + .await + .map_err(|e| backend_error("backend_misbehaving", e.to_string()))?; + + if status == reqwest::StatusCode::BAD_REQUEST { + // gn3 signals unparseable xapian queries as 400 + parsererror; + // forward its diagnostic so the caller can fix the query + // (assigned issue: report-invalid-search-queries-over-api). + if let Ok(Gn3ParseError { + error, + error_message, + }) = serde_json::from_str::<Gn3ParseError>(&body) + { + if error == "parsererror" { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_query", + "Query rejected by the search backend", + error_message, + "search", + ) + .with_request_id(rid)); + } + } + } + + if !status.is_success() { + return Err(backend_error( + "backend_error", + format!("gn3 search returned HTTP {status}: {body}"), + )); + } + + let hits: Vec<SearchHit> = serde_json::from_str(&body) + .map_err(|e| backend_error("backend_misbehaving", e.to_string()))?; + + Ok(Json(Envelope::of(hits))) +} |
