//! NO-DB graceful-degradation gate (lane gn4-devdb, gate 4). //! //! Pinned no-DB arrangement: `SQL_URI` points at a CLOSED port //! (`127.0.0.1:1`), never the hardcoded default (`127.0.0.1/db_webqtl`) //! and never an unset SQL_URI that could reach a live DB. The pool build //! therefore fails and `db::pool()` mints `DbError::Unavailable`, which //! is what the routes must translate: DB-backed routes -> typed //! `503 db_unavailable`; /search still returns hits, with the //! PublishXRef enrichment omitted (never a 500). //! //! gn3 and gn-auth are stubbed exactly as in tests/search.rs, so no //! network is needed. This file is its own test binary (its own //! process), so the shared connection pool is fresh and SQL_URI is set //! before the first DB touch; the env keys it writes belong to this //! single-threaded sequence only. use axum::Router; use axum::body::Body; use axum::http::{Request, StatusCode}; use axum::routing::get; use http_body_util::BodyExt; use jsonwebtoken::{Algorithm, EncodingKey, Header, encode}; use serde_json::{Value, json}; use tower::ServiceExt; const TEST_JWKS: &str = include_str!("../test/data/test_jwks.json"); const TEST_PRIVATE_KEY: &str = include_str!("../test/data/test_rsa_private.pem"); /// The pinned no-DB SQL_URI: a port nothing listens on. const CLOSED_PORT_SQL_URI: &str = "mysql://webqtlout:webqtlout@127.0.0.1:1/db_webqtl"; async fn serve_gn3() -> (StatusCode, String) { // One phenotype hit whose dataset ends in "Publish": the enrichment // path will try the database for locus/abbreviation. ( StatusCode::OK, json!([{"name": "10199", "dataset": "BXDPublish", "lrs": 5.0}]).to_string(), ) } async fn gn3_stub_url() -> String { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let port = listener.local_addr().unwrap().port(); let app = Router::new().route("/api/search/", get(serve_gn3)); tokio::spawn(async move { axum::serve(listener, app).await.unwrap(); }); format!("http://127.0.0.1:{port}/api/") } async fn serve_jwks() -> (StatusCode, &'static str) { (StatusCode::OK, TEST_JWKS) } async fn gn_auth_stub_url() -> String { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let port = listener.local_addr().unwrap().port(); let app = Router::new().route("/auth/public-jwks", get(serve_jwks)); tokio::spawn(async move { axum::serve(listener, app).await.unwrap(); }); format!("http://127.0.0.1:{port}") } fn sign_test_token(issuer: &str) -> String { #[derive(serde::Serialize)] struct Claims { sub: String, scope: String, iss: String, iat: u64, exp: u64, } let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_secs(); let claims = Claims { sub: "no-db-test-user".to_string(), scope: "profile".to_string(), iss: issuer.to_string(), iat: now, exp: now + 3600, }; let key = EncodingKey::from_rsa_pem(TEST_PRIVATE_KEY.as_bytes()).unwrap(); encode(&Header::new(Algorithm::RS256), &claims, &key).unwrap() } fn set(key: &str, value: &str) { // SAFETY: single-threaded env sequence in this dedicated test binary. unsafe { std::env::set_var(key, value) }; } async fn get_json(uri: &str, token: &str) -> (StatusCode, Value) { let response = genenetwork4::app() .oneshot( Request::builder() .uri(uri) .header("Authorization", format!("Bearer {token}")) .body(Body::empty()) .unwrap(), ) .await .unwrap(); let status = response.status(); let body = response.into_body().collect().await.unwrap().to_bytes(); (status, serde_json::from_slice(&body).unwrap()) } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn no_db_mode_degrades_gracefully() { // Pin the no-DB arrangement BEFORE anything can build a pool. set("SQL_URI", CLOSED_PORT_SQL_URI); set("GN3_URL", &gn3_stub_url().await); let gn_auth_stub = gn_auth_stub_url().await; set("AUTH_SERVER_URL", &gn_auth_stub); let token = sign_test_token(&gn_auth_stub); // A DB-backed route answers the typed 503, not a 500: db::pool()'s // Unavailable is minted for exactly this. let (status, body) = get_json("/species", &token).await; assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); assert_eq!(body["code"], "db_unavailable"); assert_eq!(body["status"], 503); // Unknown names cannot be distinguished from known ones without a // database, so a name lookup is also 503 here (the 404-vs-503 // distinction is preserved only when the DB is reachable; see gate 3 // and REPORT.md). let (status, body) = get_json("/species/NoSuchSpecies", &token).await; assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); assert_eq!(body["code"], "db_unavailable"); // /search still works: hits are returned, enrichment fields are // null, and the response is marked partial -- never a 500. let (status, body) = get_json("/search?q=alcohol&type=phenotype&limit=5", &token).await; assert_eq!(status, StatusCode::OK); assert_eq!(body["meta"]["state"], "partial"); let hits = body["data"].as_array().unwrap(); // How many hits the index holds for "alcohol" is a property of the // index, not of this behaviour: assert that it answered from the index // alone (at least one hit, within the limit), and that the DB-backed // fields are absent rather than wrong. assert!(!hits.is_empty(), "the index still answers without a database"); assert!(hits.len() <= 5, "and respects the limit: {hits:?}"); for hit in hits { assert!(hit["locus"].is_null(), "no enrichment without a database: {hit}"); assert!(hit["abbreviation"].is_null(), "{hit}"); } let notes = body["notes"].as_array().unwrap(); assert!( notes .iter() .any(|n| n.as_str().unwrap_or("").contains("database unavailable")), "expected a partial note about the database, got {notes:?}" ); }