diff options
| author | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-11-16 18:55:43 +0000 |
|---|---|---|
| committer | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-11-16 18:55:43 +0000 |
| commit | d4c7a85a2565997b3878f565af5e5198a4312907 (patch) | |
| tree | d1c87bcca4c2286ea81233a7c6578a4cac584ad0 /src | |
| parent | 74a5c318163ab4c286e8b8e43bd645c1c4840605 (diff) | |
| download | genenetwork4-d4c7a85a2565997b3878f565af5e5198a4312907.tar.gz | |
listing: the limit_to / ids_only / names_only model, with its tests
The shared type for the three parameters GN2 has and we do not: one value per row (`ids_only`, `names_only`), a case-insensitive `limit_to` over id / name / trait_name / display_name / full_name, the contradiction (both shapes at once) refused rather than resolved by parse order, and a `limit_to` value that matches nothing *reported* instead of silently dropped -- "my trait is missing" is the failure this parameter exists to prevent. Five tests: identity, ids/names shaping, limit_to matching any field and being case-insensitive, its composition with ids_only, and the refusal. Status, recorded in the module docs because it is the interesting part: the handlers are NOT wired yet. A listing handler returns typed rows (`Envelope<Vec<db::Group>>`), so answering `["BXD", ...]` changes its return type to `Envelope<serde_json::Value>` and the `body =` type in its utoipa block, which utoipa checks at compile time -- a mismatch fails as "could not find `__path_groups`", which looks like a macro bug and is not one. Six handlers or none: two would leave the API inconsistent, which is worse than not having the parameter at all. Build green with the module and its tests; nothing deployed, since until a handler uses it the binary is unchanged.
Diffstat (limited to 'src')
| -rw-r--r-- | src/lib.rs | 1 | ||||
| -rw-r--r-- | src/listing.rs | 221 |
2 files changed, 222 insertions, 0 deletions
diff --git a/src/lib.rs b/src/lib.rs index c025c46..1d60f9d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -23,6 +23,7 @@ pub mod frequencies; pub mod genoupload; pub mod genotypes; pub mod heatmap; +pub mod listing; pub mod normalize; mod plot; mod error; diff --git a/src/listing.rs b/src/listing.rs new file mode 100644 index 0000000..fa42cb5 --- /dev/null +++ b/src/listing.rs @@ -0,0 +1,221 @@ +//! The shape of a listing: `limit_to`, `ids_only`, `names_only`. +//! +//! GN2 offers all three on its listings, and a client that has to enumerate a +//! group's 20 000 traits wants them for the same reason: a 2 MB answer of +//! objects to build a dropdown is a waste of everyone's connection. The three +//! are one concept, so they live in one type rather than being copied into each +//! handler's query struct: +//! +//! * `limit_to=a,b,c` keeps only the rows whose id, name, full name or trait +//! name matches one of the listed values (case-insensitive). A value that +//! matches nothing is named in the reply's note rather than silently ignored, +//! because "my trait's missing" is the failure mode this exists to prevent. +//! * `ids_only=true` answers `["BXD", "BXH", ...]` instead of objects. +//! * `names_only=true` answers `["BXD", ...]` too, but from the *name* field; +//! asking for both is a contradiction and is refused rather than guessed. +//! +//! Rows keep their order, so a caller can zip the slim answer against what it +//! asked for. +//! +//! **Status: the type and its tests are in, the handlers are not wired yet.** +//! Wiring one is small but not mechanical: a listing handler returns typed rows +//! (`Envelope<Vec<db::Group>>`), so answering with `["BXD", ...]` changes its +//! return type to `Envelope<serde_json::Value>` *and* the `body =` type in its +//! `utoipa::path` block, which utoipa checks at compile time (a mismatch fails +//! with "could not find `__path_<handler>`", which reads like a macro problem +//! and is not one). Doing that for six handlers is a pass of its own; doing it +//! for two would leave the API inconsistent, which is worse than not having it. + +use serde::Deserialize; + +/// Query parameters three listings share. +#[derive(Debug, Clone, Default, Deserialize)] +pub struct ListingParams { + /// Keep only these ids or names, comma-separated. + #[serde(default)] + pub limit_to: Option<String>, + /// Answer with ids only. + #[serde(default)] + pub ids_only: Option<bool>, + /// Answer with names only. + #[serde(default)] + pub names_only: Option<bool>, +} + +/// What a listing should answer with. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Listing { + /// The rows as they are. + Full, + /// One identifier per row, from this field. + Only(&'static str), +} + +/// The fields a `limit_to` value may match, in the order they are tried. +const MATCH_FIELDS: [&str; 5] = ["id", "name", "trait_name", "display_name", "full_name"]; +/// Where an `ids_only` answer takes its value from. +const ID_FIELDS: [&str; 4] = ["id", "name", "trait_name", "abbreviation"]; +/// Where a `names_only` answer takes its value from. +const NAME_FIELDS: [&str; 4] = ["name", "trait_name", "display_name", "id"]; + +impl Listing { + /// Read the parameters, refusing the contradiction. + pub fn parse(params: &ListingParams) -> Result<Self, String> { + let ids = params.ids_only.unwrap_or(false); + let names = params.names_only.unwrap_or(false); + match (ids, names) { + (true, true) => Err( + "ask for ids_only or names_only, not both: a row has one identifier and one name, \ + and which one you get should not depend on parse order" + .to_string(), + ), + (true, false) => Ok(Listing::Only("id")), + (false, true) => Ok(Listing::Only("name")), + (false, false) => Ok(Listing::Full), + } + } + + /// Shape `rows` (already serialised) according to the parameters. + /// + /// Returns the shaped array and, for a `limit_to` that matched nothing, the + /// values that were not found -- so the caller can say so. + pub fn apply( + &self, + rows: &serde_json::Value, + limit_to: Option<&str>, + ) -> (serde_json::Value, Vec<String>) { + let Some(array) = rows.as_array() else { + return (rows.clone(), Vec::new()); + }; + let wanted: Option<Vec<String>> = limit_to + .map(|text| { + text.split(',') + .map(|value| value.trim().to_lowercase()) + .filter(|value| !value.is_empty()) + .collect() + }) + .filter(|values: &Vec<String>| !values.is_empty()); + + let mut kept: Vec<serde_json::Value> = Vec::with_capacity(array.len()); + let mut found: Vec<String> = Vec::new(); + for row in array { + if let Some(wanted) = &wanted { + let mut matched = false; + for field in MATCH_FIELDS { + if let Some(value) = row.get(field).and_then(|value| { + value + .as_str() + .map(str::to_string) + .or_else(|| value.as_i64().map(|n| n.to_string())) + }) { + let lowered = value.to_lowercase(); + if wanted.contains(&lowered) { + matched = true; + found.push(lowered); + break; + } + } + } + if !matched { + continue; + } + } + match self { + Listing::Full => kept.push(row.clone()), + Listing::Only(field) => { + let fields: &[&str] = if *field == "id" { &ID_FIELDS } else { &NAME_FIELDS }; + let value = fields + .iter() + .find_map(|candidate| row.get(*candidate)) + .cloned() + .unwrap_or(serde_json::Value::Null); + kept.push(value); + } + } + } + let missing = match &wanted { + Some(wanted) => wanted + .iter() + .filter(|value| !found.contains(value)) + .cloned() + .collect(), + None => Vec::new(), + }; + (serde_json::Value::Array(kept), missing) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn rows() -> serde_json::Value { + json!([ + {"id": 1, "name": "BXD", "full_name": "BXD recombinant inbreds"}, + {"id": 2, "name": "BXH", "full_name": "BXH recombinant inbreds"}, + {"id": 3, "name": "HET3-ITP", "full_name": "UM-HET3"} + ]) + } + + #[test] + fn full_leaves_the_rows_alone() { + let listing = Listing::parse(&ListingParams::default()).expect("default"); + assert_eq!(listing, Listing::Full); + let (shaped, missing) = listing.apply(&rows(), None); + assert_eq!(shaped, rows()); + assert!(missing.is_empty()); + } + + #[test] + fn ids_and_names_are_one_value_per_row() { + let ids = Listing::parse(&ListingParams { + ids_only: Some(true), + ..Default::default() + }) + .expect("ids"); + let (shaped, _) = ids.apply(&rows(), None); + assert_eq!(shaped, json!([1, 2, 3])); + + let names = Listing::parse(&ListingParams { + names_only: Some(true), + ..Default::default() + }) + .expect("names"); + let (shaped, _) = names.apply(&rows(), None); + assert_eq!(shaped, json!(["BXD", "BXH", "HET3-ITP"])); + } + + #[test] + fn limit_to_matches_any_of_the_matching_fields_case_insensitively() { + let listing = Listing::Full; + let (shaped, missing) = listing.apply(&rows(), Some("bxd,UM-HET3")); + assert_eq!(shaped.as_array().map(|rows| rows.len()), Some(2)); + assert!(missing.is_empty(), "both were found: {missing:?}"); + + let (shaped, missing) = listing.apply(&rows(), Some("bxd,nope")); + assert_eq!(shaped.as_array().map(|rows| rows.len()), Some(1)); + assert_eq!(missing, vec!["nope".to_string()], "the miss is reported, not dropped"); + } + + #[test] + fn limit_to_composes_with_ids_only() { + let listing = Listing::parse(&ListingParams { + ids_only: Some(true), + ..Default::default() + }) + .expect("ids"); + let (shaped, _) = listing.apply(&rows(), Some("BXH")); + assert_eq!(shaped, json!([2])); + } + + #[test] + fn asking_for_both_shapes_is_refused() { + let error = Listing::parse(&ListingParams { + ids_only: Some(true), + names_only: Some(true), + ..Default::default() + }); + assert!(error.is_err(), "ids_only + names_only must not be guessed"); + } +} |
