about summary refs log tree commit diff
path: root/src/db.rs
diff options
context:
space:
mode:
authorAlexander_Kabui <alexanderkabui@proton.me>2026-10-13 23:36:39 +0300
committerAlexander_Kabui <alexanderkabui@proton.me>2026-10-14 07:28:51 +0300
commit22ff53e2d65e47df27d76aa7420a146074c00282 (patch)
tree07f550107ebb9501b1fa79e8e8d6b2d48210572d /src/db.rs
parenta188b75157516c5e00dd130d9ca8dfbd6cf36679 (diff)
downloadgenenetwork4-22ff53e2d65e47df27d76aa7420a146074c00282.tar.gz
config: GN4_DB_MODE (mariadb optional on dev) + no-DB hardening
* src/config.rs (DbMode, Config.db_mode, parse_db_mode): add
GN4_DB_MODE=dev|production in the layered config; dev runs with no
configured DB; fail-closed parse (a typo refuses).
* src/db.rs (DbError, pool, probe), src/error.rs (ApiError::from_db):
mint a typed 503 db_unavailable at the db::pool() choke point,
distinguishing Unavailable from Query.
* src/main.rs: loud no-DB startup line; production refuses to start
(exit non-zero) before axum::serve.
* src/routes/{accessions,datasets,groups,mapping_methods,publications,species,traits}.rs:
route every DB error through ApiError::from_db.
* src/bin/gn-indexer.rs: refuse to build an index when the DB is unreachable.
* tests/no_db.rs: pin no-DB degradation (search 200 partial, DB routes 503).

His ask (DM 2026-10-12): "Make it an option to switch it off for
development machines? I mean mariadb." The no-DB hardening is ours
(review-driven). Default GN4_DB_MODE left unflipped (=dev); the flip needs
owner sign-off.
Diffstat (limited to 'src/db.rs')
-rw-r--r--src/db.rs126
1 files changed, 99 insertions, 27 deletions
diff --git a/src/db.rs b/src/db.rs
index ba22811..2675875 100644
--- a/src/db.rs
+++ b/src/db.rs
@@ -12,6 +12,42 @@ fn sql_uri() -> String {
     crate::config::Config::load().sql_uri
 }
 
+/// Why a database-backed operation failed.
+///
+/// The distinction is minted at the `pool()` choke point, the single
+/// place a connection is (re)established: `Unavailable` means the pool
+/// could not be built at all, so no configured/reachable database
+/// exists and DB-backed routes are meaningless (they map to a typed
+/// 503 `db_unavailable`). `Query` is any failure on an already-built
+/// pool -- a bad query, or a connection that died after the pool was
+/// built; those keep the existing 500 `database_error` shape. See the
+/// lane REPORT's probe-window limitation.
+#[derive(Debug)]
+pub enum DbError {
+    /// The pool could not be built: `SQL_URI` is unset/unparseable or
+    /// the database is unreachable. Minted only here.
+    Unavailable(String),
+    /// A query (or pool checkout) failed on an established pool.
+    Query(mysql::Error),
+}
+
+impl std::fmt::Display for DbError {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        match self {
+            DbError::Unavailable(detail) => write!(f, "{detail}"),
+            DbError::Query(error) => write!(f, "{error}"),
+        }
+    }
+}
+
+impl std::error::Error for DbError {}
+
+impl From<mysql::Error> for DbError {
+    fn from(error: mysql::Error) -> Self {
+        DbError::Query(error)
+    }
+}
+
 /// The shared connection pool, built once and reused by every query
 /// function below. mysql::Pool::new eagerly opens PoolConstraints::
 /// DEFAULT's 10 connections before returning (about 7s against this
@@ -37,22 +73,39 @@ fn sql_uri() -> String {
 /// and the ping only protects against a connection the server closed
 /// while idle -- which would now surface as a database error on the
 /// next query using it (the pool then drops that connection).
-fn pool() -> Result<Pool, mysql::Error> {
+fn pool() -> Result<Pool, DbError> {
     static POOL: OnceLock<Mutex<Option<Pool>>> = OnceLock::new();
     let mut guard = POOL.get_or_init(|| Mutex::new(None)).lock().unwrap();
     if let Some(pool) = guard.as_ref() {
         return Ok(pool.clone());
     }
-    let opts = OptsBuilder::from_opts(Opts::from_url(&sql_uri())?).pool_opts(
+    let opts = OptsBuilder::from_opts(
+        Opts::from_url(&sql_uri()).map_err(|e| DbError::Unavailable(e.to_string()))?,
+    )
+    .pool_opts(
         PoolOpts::default()
             .with_reset_connection(false)
             .with_check_health(false),
     );
-    let new_pool = Pool::new(opts)?;
+    let new_pool = Pool::new(opts).map_err(|e| DbError::Unavailable(e.to_string()))?;
     *guard = Some(new_pool.clone());
     Ok(new_pool)
 }
 
+/// Startup reachability probe: builds the shared pool (connecting to
+/// `SQL_URI`) and runs `SELECT 1`. `Ok(())` means the database is
+/// reachable; an `Err` is exactly what makes DB-backed routes answer
+/// 503. Used by src/main.rs to refuse (`production`) or warn loudly
+/// (`dev`) before serving, and by gn-indexer to refuse before touching
+/// an index. The built pool is cached, so a successful probe warms the
+/// pool the routes then reuse.
+pub fn probe() -> Result<(), DbError> {
+    let pool = pool()?;
+    let mut conn = pool.get_conn()?;
+    conn.query_drop("SELECT 1")?;
+    Ok(())
+}
+
 /// GeneNetwork stores LRS (likelihood ratio statistic); LOD = LRS / 4.604
 /// (the divisor GeneNetwork's RDF data uses; 2 ln 10 is 4.605). Every
 /// `lod` the API reports is derived with this one constant -- in SQL for rows read from the database, via `lod` for
@@ -75,7 +128,7 @@ pub struct Species {
 }
 
 /// Mirrors GeneNetwork3's gn3.db.species.get_all_species.
-pub fn get_all_species() -> Result<Vec<Species>, mysql::Error> {
+pub fn get_all_species() -> Result<Vec<Species>, DbError> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.query_map(
@@ -88,6 +141,7 @@ pub fn get_all_species() -> Result<Vec<Species>, mysql::Error> {
             family,
         },
     )
+    .map_err(DbError::from)
 }
 
 /// One full row of the Species table.
@@ -122,7 +176,7 @@ type SpeciesRow = (
 /// Fetch one species by Name, FullName or SpeciesName, matching
 /// GeneNetwork2's wqflask.api.router.get_species_info, but returning
 /// every column of the Species table rather than a fixed subset.
-pub fn get_species_by_name(name: &str) -> Result<Option<SpeciesDetail>, mysql::Error> {
+pub fn get_species_by_name(name: &str) -> Result<Option<SpeciesDetail>, DbError> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec_first(
@@ -161,6 +215,7 @@ pub fn get_species_by_name(name: &str) -> Result<Option<SpeciesDetail>, mysql::E
             },
         )
     })
+    .map_err(DbError::from)
 }
 
 /// Summary of one InbredSet row, matching the shape of GeneNetwork2's
@@ -189,7 +244,7 @@ pub struct Group {
 
 /// Mirrors GeneNetwork2's wqflask.api.router.get_groups_list, plus the
 /// family and species name (filtering is done by the handler).
-pub fn get_all_groups() -> Result<Vec<Group>, mysql::Error> {
+pub fn get_all_groups() -> Result<Vec<Group>, DbError> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.query_map(
@@ -229,6 +284,7 @@ pub fn get_all_groups() -> Result<Vec<Group>, mysql::Error> {
             }
         },
     )
+    .map_err(DbError::from)
 }
 
 /// One mapping tool GeneNetwork offers (a MappingMethod row), e.g.
@@ -241,13 +297,14 @@ pub struct MappingMethod {
     pub name: String,
 }
 
-pub fn get_mapping_methods() -> Result<Vec<MappingMethod>, mysql::Error> {
+pub fn get_mapping_methods() -> Result<Vec<MappingMethod>, DbError> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.query_map(
         "SELECT Id, Name FROM MappingMethod ORDER BY Id",
         |(id, name)| MappingMethod { id, name },
     )
+    .map_err(DbError::from)
 }
 
 /// A GeneNetwork accession number (the "GN602" of a dataset's page): an
@@ -270,7 +327,7 @@ pub struct Accession {
 /// Resolve an accession number: its InfoFiles row, then the dataset of
 /// that name (PublishFreeze, else ProbeSetFreeze) for its category and
 /// group. None when no InfoFiles row has the accession.
-pub fn get_accession(accession: u32) -> Result<Option<Accession>, mysql::Error> {
+pub fn get_accession(accession: u32) -> Result<Option<Accession>, DbError> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     let row: Option<(String, Option<String>)> = conn.exec_first(
@@ -351,7 +408,7 @@ pub struct GroupDetail {
 /// doesn't match by Id) plus gn-guile's gn.data.population:population-info
 /// (which only matches by Id), returning every column of the InbredSet
 /// table rather than a fixed subset.
-pub fn get_group_by_name(name: &str) -> Result<Option<GroupDetail>, mysql::Error> {
+pub fn get_group_by_name(name: &str) -> Result<Option<GroupDetail>, DbError> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec_first(
@@ -366,6 +423,7 @@ pub fn get_group_by_name(name: &str) -> Result<Option<GroupDetail>, mysql::Error
                 OR InbredSet.FullName = :name OR CAST(InbredSet.Id AS CHAR) = :name",
         mysql::params! { "name" => name },
     )
+    .map_err(DbError::from)
 }
 
 /// One strain/sample belonging to a group, matching gn-guile's
@@ -385,7 +443,7 @@ pub struct Strain {
 pub fn get_group_strains(
     group_id: u16,
     used_for_mapping: Option<bool>,
-) -> Result<Vec<Strain>, mysql::Error> {
+) -> Result<Vec<Strain>, DbError> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec_map(
@@ -402,6 +460,7 @@ pub fn get_group_strains(
             used_for_mapping: used_for_mapping == "Y",
         },
     )
+    .map_err(DbError::from)
 }
 
 /// One strain's value for a published (phenotype) trait, matching
@@ -424,7 +483,7 @@ pub struct TraitValue {
 pub fn get_group_trait_values(
     group_id: u16,
     trait_id: u32,
-) -> Result<Vec<TraitValue>, mysql::Error> {
+) -> Result<Vec<TraitValue>, DbError> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec_map(
@@ -436,6 +495,7 @@ pub fn get_group_trait_values(
         mysql::params! { "group_id" => group_id, "trait_id" => trait_id },
         |(name, value)| TraitValue { name, value },
     )
+    .map_err(DbError::from)
 }
 
 /// One published (phenotype) trait's metadata: its PublishXRef mapping
@@ -534,7 +594,7 @@ fn trait_info_sql(filter: &str, order_by: &str) -> String {
 pub fn get_group_trait_info(
     group_id: u16,
     trait_id: u32,
-) -> Result<Option<TraitInfo>, mysql::Error> {
+) -> Result<Option<TraitInfo>, DbError> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec_first(
@@ -544,17 +604,19 @@ pub fn get_group_trait_info(
         ),
         mysql::params! { "group_id" => group_id, "trait_id" => trait_id },
     )
+    .map_err(DbError::from)
 }
 
 /// Fetch every published trait's metadata (see TraitInfo) within a
 /// group, the listing equivalent of get_group_trait_info.
-pub fn get_group_traits(group_id: u16) -> Result<Vec<TraitInfo>, mysql::Error> {
+pub fn get_group_traits(group_id: u16) -> Result<Vec<TraitInfo>, DbError> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec(
         trait_info_sql("PublishXRef.InbredSetId = :group_id", "PublishXRef.Id"),
         mysql::params! { "group_id" => group_id },
     )
+    .map_err(DbError::from)
 }
 
 /// The traits of a group whose short name (either the post- or the
@@ -562,7 +624,7 @@ pub fn get_group_traits(group_id: u16) -> Result<Vec<TraitInfo>, mysql::Error> {
 pub fn get_group_traits_by_abbreviation(
     group_id: u16,
     abbreviation: &str,
-) -> Result<Vec<TraitInfo>, mysql::Error> {
+) -> Result<Vec<TraitInfo>, DbError> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec(
@@ -574,11 +636,12 @@ pub fn get_group_traits_by_abbreviation(
         ),
         mysql::params! { "group_id" => group_id, "abbreviation" => abbreviation },
     )
+    .map_err(DbError::from)
 }
 
 /// Every published trait (across groups) reported in the publication
 /// with this PubMed id, or None when no such publication exists.
-pub fn get_publication_traits(pubmed_id: u32) -> Result<Option<Vec<TraitInfo>>, mysql::Error> {
+pub fn get_publication_traits(pubmed_id: u32) -> Result<Option<Vec<TraitInfo>>, DbError> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     let exists: Option<u32> = conn.exec_first(
@@ -596,6 +659,7 @@ pub fn get_publication_traits(pubmed_id: u32) -> Result<Option<Vec<TraitInfo>>,
         mysql::params! { "pubmed_id" => pubmed_id },
     )
     .map(Some)
+    .map_err(DbError::from)
 }
 
 /// What search hits are annotated with from PublishXRef/Phenotype
@@ -611,7 +675,7 @@ pub struct PublishAnnotation {
 /// exist are absent from the result.
 pub fn get_publish_annotations(
     keys: &[(String, u32)],
-) -> Result<std::collections::HashMap<(String, u32), PublishAnnotation>, mysql::Error> {
+) -> Result<std::collections::HashMap<(String, u32), PublishAnnotation>, DbError> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     let pairs = vec!["(?, ?)"; keys.len()].join(", ");
@@ -669,7 +733,7 @@ pub struct Dataset {
 /// GeneNetwork2's wqflask.api.router.get_datasets_for_group (without
 /// its species-scoped variant, which this API doesn't need: a group
 /// name alone already picks one species).
-pub fn get_group_datasets(group_id: u16) -> Result<Vec<Dataset>, mysql::Error> {
+pub fn get_group_datasets(group_id: u16) -> Result<Vec<Dataset>, DbError> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec_map(
@@ -711,6 +775,7 @@ pub fn get_group_datasets(group_id: u16) -> Result<Vec<Dataset>, mysql::Error> {
             }
         },
     )
+    .map_err(DbError::from)
 }
 
 /// One strain's case-attribute values within a group: extra per-strain
@@ -743,13 +808,14 @@ pub struct CaseAttributes {
 /// (trimmed to just the name -- Description isn't used by genenetwork4
 /// yet, and CaseAttributeId/InbredSetId are already implied by this
 /// being scoped to one group).
-fn get_group_case_attribute_names(group_id: u16) -> Result<Vec<String>, mysql::Error> {
+fn get_group_case_attribute_names(group_id: u16) -> Result<Vec<String>, DbError> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec(
         "SELECT Name FROM CaseAttribute WHERE InbredSetId = :group_id ORDER BY Name",
         mysql::params! { "group_id" => group_id },
     )
+    .map_err(DbError::from)
 }
 
 /// Fetch every strain's case-attribute values for a group, based on
@@ -769,7 +835,7 @@ fn get_group_case_attribute_names(group_id: u16) -> Result<Vec<String>, mysql::E
 /// ordered by strain name, so adjacent rows for the same strain are
 /// folded into one `StrainCaseAttributes` as they're read rather than
 /// grouped afterwards.
-fn get_group_case_attribute_values(group_id: u16) -> Result<Vec<StrainCaseAttributes>, mysql::Error> {
+fn get_group_case_attribute_values(group_id: u16) -> Result<Vec<StrainCaseAttributes>, DbError> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     let rows: Vec<(String, String, String)> = conn.exec(
@@ -804,7 +870,7 @@ fn get_group_case_attribute_values(group_id: u16) -> Result<Vec<StrainCaseAttrib
 
 /// Fetch a group's case attributes: every attribute name defined for
 /// it, and every strain's values for them. See `CaseAttributes`.
-pub fn get_group_case_attributes(group_id: u16) -> Result<CaseAttributes, mysql::Error> {
+pub fn get_group_case_attributes(group_id: u16) -> Result<CaseAttributes, DbError> {
     Ok(CaseAttributes {
         names: get_group_case_attribute_names(group_id)?,
         values: get_group_case_attribute_values(group_id)?,
@@ -816,7 +882,7 @@ pub fn get_group_case_attributes(group_id: u16) -> Result<CaseAttributes, mysql:
 /// GeneNetwork2's own species-scoped variant of
 /// wqflask.api.router.get_datasets_for_group still requires a group
 /// name (species only disambiguates it); this doesn't need one.
-pub fn get_species_datasets(species_id: u16) -> Result<Vec<Dataset>, mysql::Error> {
+pub fn get_species_datasets(species_id: u16) -> Result<Vec<Dataset>, DbError> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec_map(
@@ -859,6 +925,7 @@ pub fn get_species_datasets(species_id: u16) -> Result<Vec<Dataset>, mysql::Erro
             }
         },
     )
+    .map_err(DbError::from)
 }
 
 /// Columns of the Dataset row, in SELECT order.
@@ -879,7 +946,7 @@ type DatasetRow = (
 /// Fetch one dataset by Name, Name2, FullName, ShortName or numeric
 /// Id, matching GeneNetwork2's wqflask.api.router.get_dataset_info's
 /// matching logic for its ProbeSet (mRNA expression) branch.
-pub fn get_dataset_by_name(name: &str) -> Result<Option<Dataset>, mysql::Error> {
+pub fn get_dataset_by_name(name: &str) -> Result<Option<Dataset>, DbError> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec_first(
@@ -926,6 +993,7 @@ pub fn get_dataset_by_name(name: &str) -> Result<Option<Dataset>, mysql::Error>
             },
         )
     })
+    .map_err(DbError::from)
 }
 
 /// One row of the PublishFreeze table -- the Publish/phenotype
@@ -954,7 +1022,7 @@ pub struct PublishDataset {
 /// owning group's Id/Name/InbredSetName/FullName -- mirroring
 /// GeneNetwork2's wqflask.api.router.trait_sample_data's Publish
 /// branch, which accepts either (e.g. "BXDPublish" or plain "BXD").
-pub fn get_publish_freeze_by_name(name: &str) -> Result<Option<PublishDataset>, mysql::Error> {
+pub fn get_publish_freeze_by_name(name: &str) -> Result<Option<PublishDataset>, DbError> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec_first(
@@ -970,6 +1038,7 @@ pub fn get_publish_freeze_by_name(name: &str) -> Result<Option<PublishDataset>,
                 OR InbredSet.FullName = :name OR CAST(InbredSet.Id AS CHAR) = :name",
         mysql::params! { "name" => name },
     )
+    .map_err(DbError::from)
 }
 
 /// Which category a `/traits/{dataset}/...` request's dataset resolved
@@ -984,7 +1053,7 @@ pub enum TraitDataset {
 /// then PublishFreeze (a dataset name is expected to match at most one
 /// of these). Geno/GenoFreeze isn't supported yet, matching the rest
 /// of this API.
-pub fn resolve_trait_dataset(name: &str) -> Result<Option<TraitDataset>, mysql::Error> {
+pub fn resolve_trait_dataset(name: &str) -> Result<Option<TraitDataset>, DbError> {
     if let Some(dataset) = get_dataset_by_name(name)? {
         return Ok(Some(TraitDataset::ProbeSet(dataset)));
     }
@@ -1041,7 +1110,7 @@ type ProbeSetInfoRow = (
 pub fn get_dataset_probeset_info(
     dataset_id: u16,
     probeset_name: &str,
-) -> Result<Option<ProbeSetInfo>, mysql::Error> {
+) -> Result<Option<ProbeSetInfo>, DbError> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec_first(
@@ -1089,12 +1158,13 @@ pub fn get_dataset_probeset_info(
             },
         )
     })
+    .map_err(DbError::from)
 }
 
 /// Fetch every expression (ProbeSet) trait's metadata (see
 /// ProbeSetInfo) within a dataset, the listing equivalent of
 /// get_dataset_probeset_info.
-pub fn get_dataset_probesets(dataset_id: u16) -> Result<Vec<ProbeSetInfo>, mysql::Error> {
+pub fn get_dataset_probesets(dataset_id: u16) -> Result<Vec<ProbeSetInfo>, DbError> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec_map(
@@ -1139,6 +1209,7 @@ pub fn get_dataset_probesets(dataset_id: u16) -> Result<Vec<ProbeSetInfo>, mysql
             }
         },
     )
+    .map_err(DbError::from)
 }
 
 /// One strain's value for an expression (ProbeSet) trait, matching
@@ -1156,7 +1227,7 @@ pub struct ProbeSetValue {
 pub fn get_dataset_probeset_values(
     dataset_id: u16,
     probeset_name: &str,
-) -> Result<Vec<ProbeSetValue>, mysql::Error> {
+) -> Result<Vec<ProbeSetValue>, DbError> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec_map(
@@ -1169,4 +1240,5 @@ pub fn get_dataset_probeset_values(
         mysql::params! { "dataset_id" => dataset_id, "probeset_name" => probeset_name },
         |(name, value)| ProbeSetValue { name, value },
     )
+    .map_err(DbError::from)
 }