about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorAlexander_Kabui <alexanderkabua@gmail.com>2026-10-06 06:42:30 +0300
committerAlexander_Kabui <alexanderkabua@gmail.com>2026-10-06 06:50:16 +0300
commit5b8f8c3be0a593fb1feaf0cbe91dd481e09365d5 (patch)
tree8cccfa8e41ad5e709d99ccce1f470e40048f8021 /src
parent7d195d5c9854247961352acf49098ea8e0443136 (diff)
downloadgenenetwork4-5b8f8c3be0a593fb1feaf0cbe91dd481e09365d5.tar.gz
* src/routes/search.rs (search): delegate /search to the engine seam.
Parameter validation, envelope wrapping, and the auth contract stay
in the handler; the backend call and its error mapping move behind
the Engine trait. SearchHit now comes from crate::search, so a
native engine can replace the gn3 proxy without any route change.
Diffstat (limited to 'src')
-rw-r--r--src/routes/search.rs221
1 files changed, 100 insertions, 121 deletions
diff --git a/src/routes/search.rs b/src/routes/search.rs
index 0a61878..8d4841b 100644
--- a/src/routes/search.rs
+++ b/src/routes/search.rs
@@ -4,36 +4,23 @@
 //! /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.
+//!
+//! The backend itself lives behind the search engine seam (see
+//! `crate::search`); this handler validates parameters, delegates to
+//! the [`Engine`], and maps the engine's [`SearchError`] onto the
+//! existing [`ApiError`] shapes.
 
 use axum::Json;
 use axum::extract::{Extension, Query};
 use axum::http::StatusCode;
 use serde::Deserialize;
-use std::sync::OnceLock;
-use std::time::Duration;
 use tower_http::request_id::RequestId;
 
 use crate::auth::AuthToken;
 use crate::error::{ApiError, Unauthorized};
 use crate::request_id_string;
 use crate::response::Envelope;
-
-/// Shared HTTP client for gn3 upstream calls: one connection pool
-/// (keepalive across queries) instead of reqwest::get's fresh client
-/// per request, and a total timeout -- gn3 sets none of its own, so
-/// without this a stalled upstream hangs the handler past any
-/// front-proxy timeout. The timeout is the GN3_TIMEOUT_SECS config key.
-static GN3_CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
-
-fn gn3_client() -> &'static reqwest::Client {
-    GN3_CLIENT.get_or_init(|| {
-        let timeout = Duration::from_secs(crate::config::Config::load().gn3_timeout_secs);
-        reqwest::Client::builder()
-            .timeout(timeout)
-            .build()
-            .expect("gn3 client builds")
-    })
-}
+use crate::search::{Engine, SearchError, SearchHit, gn3::Gn3};
 
 /// Query parameters for `GET /search`.
 ///
@@ -50,37 +37,45 @@ pub struct SearchParams {
     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>,
-}
+/// Map a [`SearchError`] onto the `/search` error contract: one
+/// `ApiError` per engine failure class, carrying the engine's own
+/// diagnostic as `detail`. See `crate::search` for the mapping table.
+fn engine_error(error: SearchError, rid: Option<String>) -> ApiError {
+    // 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())
+    };
 
-/// gn3's error body for rejected queries: {"error": "<diagnostic>",
-/// "error_type": "..."}. The diagnostic lives under "error";
-/// "error_type" leaks Python reprs (e.g. "b'QueryParserError'"), so
-/// only "error" is load-bearing.
+    match error {
+        SearchError::InvalidQuery(detail) => ApiError::new(
+            StatusCode::UNPROCESSABLE_ENTITY,
+            "invalid_query",
+            "Query rejected by the search backend",
+            detail,
+            "search",
+        )
+        .with_request_id(rid),
+        SearchError::Unreachable(detail) => backend_error("backend_unreachable", detail),
+        SearchError::Misbehaving(detail) => backend_error("backend_misbehaving", detail),
+        SearchError::Backend(detail) => backend_error("backend_error", detail),
+        SearchError::Internal(detail) => ApiError::new(
+            StatusCode::INTERNAL_SERVER_ERROR,
+            "internal_error",
+            "Internal error",
+            detail,
+            "search",
+        )
+        .with_request_id(rid),
+    }
+}
 
 #[utoipa::path(get, path = "/search",
     summary = "Search traits across GN datasets",
@@ -125,81 +120,65 @@ pub async fn search(
     }
     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 = gn3_client()
-        .get(url)
-        .send()
+    let hits = Gn3
+        .search(q, search_type, limit)
         .await
-        .map_err(|e| backend_error("backend_unreachable", e.to_string()))?;
+        .map_err(|e| engine_error(e, rid))?;
 
-    let status = response.status();
-    let body = response
-        .text()
-        .await
-        .map_err(|e| backend_error("backend_misbehaving", e.to_string()))?;
+    Ok(Json(Envelope::of(hits)))
+}
 
-    if status.is_client_error() {
-        // gn3 signals rejected queries (xapian syntax errors, unknown
-        // type, ...) as 4xx with a JSON diagnostic; forward it as 422
-        // invalid_query so the caller can fix the query (assigned issue:
-        // report-invalid-search-queries-over-api). Match on the presence
-        // of "error" alone -- production's "error_type" leaks Python
-        // reprs, so token-matching on it is fragile.
-        if let Ok(v) = serde_json::from_str::<serde_json::Value>(&body) {
-            if let Some(diag) = v.get("error").and_then(|e| e.as_str()) {
-                return Err(ApiError::new(
-                    StatusCode::UNPROCESSABLE_ENTITY,
-                    "invalid_query",
-                    "Query rejected by the search backend",
-                    diag.to_string(),
-                    "search",
-                )
-                .with_request_id(rid));
-            }
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    /// Each `SearchError` class keeps its existing status/code/title,
+    /// carrying the engine's diagnostic as `detail`, with the request
+    /// id threaded through.
+    #[test]
+    fn engine_error_preserves_the_existing_contract() {
+        let rid = Some("req-1".to_string());
+        let cases = [
+            (
+                SearchError::InvalidQuery("detail".to_string()),
+                StatusCode::UNPROCESSABLE_ENTITY,
+                "invalid_query",
+                "Query rejected by the search backend",
+            ),
+            (
+                SearchError::Unreachable("detail".to_string()),
+                StatusCode::BAD_GATEWAY,
+                "backend_unreachable",
+                "Search backend failure",
+            ),
+            (
+                SearchError::Misbehaving("detail".to_string()),
+                StatusCode::BAD_GATEWAY,
+                "backend_misbehaving",
+                "Search backend failure",
+            ),
+            (
+                SearchError::Backend("detail".to_string()),
+                StatusCode::BAD_GATEWAY,
+                "backend_error",
+                "Search backend failure",
+            ),
+            (
+                SearchError::Internal("detail".to_string()),
+                StatusCode::INTERNAL_SERVER_ERROR,
+                "internal_error",
+                "Internal error",
+            ),
+        ];
+        for (error, status, code, title) in cases {
+            let api_error = engine_error(error, rid.clone());
+            assert_eq!(api_error.status, status.as_u16());
+            assert_eq!(api_error.code, code);
+            assert_eq!(api_error.title, title);
+            assert_eq!(api_error.detail, "detail");
+            assert_eq!(api_error.operation_id, "search");
+            assert_eq!(api_error.r#type, format!("/errors/{code}"));
+            assert_eq!(api_error.request_id.as_deref(), Some("req-1"));
         }
     }
-
-    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)))
 }