diff options
| author | Pjotr <wrk@bosa.lan> | 2026-10-08 06:53:15 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-10-08 06:53:15 +0000 |
| commit | 54f138802bed2040531b3da3df0b30895d881bc8 (patch) | |
| tree | f334657d04e488f808d2d1bcd7931755427b299d /src | |
| parent | dfd4bf042cce290a103f83ce19df5a4781e51c17 (diff) | |
| download | genenetwork4-54f138802bed2040531b3da3df0b30895d881bc8.tar.gz | |
* src/routes/publications.rs: add GET /publications/{pubmed_id}/traits.
Lists the published traits (across groups) a publication reports.
Datasets the caller may not view are left out, using the same check as
GET /traits/{dataset} (traits.rs is_authorised is now pub(crate)).
* src/db.rs (TraitInfo, trait_info_sql): TraitInfo gains `dataset`,
`abbreviation` (Phenotype.Post_publication_abbreviation, else Pre) and
`url` (the GeneNetwork show_trait page). The three TraitInfo queries
now share one SELECT. New get_group_traits_by_abbreviation and
get_publication_traits.
* src/routes/groups.rs (group_traits): add ?abbreviation= filter.
* src/db.rs (Group), src/routes/groups.rs (groups): groups carry
`family` and `species`; add family, species and q filters.
* src/routes/search.rs (search): add `page` (gn3's page unsorted, a
page of the ranked list with `sort`); declare `pubmed_id`; hits gain
`abbreviation` next to `locus` (get_publish_annotations).
* src/db.rs (LRS_PER_LOD): LOD = LRS / 4.604, the divisor the
benchmark's RDF data uses (was 4.61).
* tests, test/python, test/data/benchmark_search.json, README.md: cover
all of the above; tests/benchmark.rs now also answers rows 11, 16, 25,
30, 34 and 37 of small_benchmark.csv, and compares LOD exactly.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Diffstat (limited to 'src')
| -rw-r--r-- | src/db.rs | 187 | ||||
| -rw-r--r-- | src/lib.rs | 1 | ||||
| -rw-r--r-- | src/routes/groups.rs | 69 | ||||
| -rw-r--r-- | src/routes/mod.rs | 1 | ||||
| -rw-r--r-- | src/routes/publications.rs | 130 | ||||
| -rw-r--r-- | src/routes/search.rs | 71 | ||||
| -rw-r--r-- | src/routes/traits.rs | 2 |
7 files changed, 373 insertions, 88 deletions
diff --git a/src/db.rs b/src/db.rs index edc96e0..dca7c29 100644 --- a/src/db.rs +++ b/src/db.rs @@ -37,11 +37,11 @@ fn pool() -> Result<Pool, mysql::Error> { Ok(new_pool) } -/// GeneNetwork stores LRS (likelihood ratio statistic); LOD = LRS / 4.61 -/// (4.61 ~ 2 ln 10). Every `lod` the API reports is derived with this one -/// constant -- in SQL for rows read from the database, via `lod` for +/// 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 /// values that arrive as LRS (gn3 search hits). -pub const LRS_PER_LOD: f64 = 4.61; +pub const LRS_PER_LOD: f64 = 4.604; /// LOD score for an LRS value; see LRS_PER_LOD. pub fn lod(lrs: f64) -> f64 { @@ -157,17 +157,25 @@ pub struct Group { pub public: Option<u8>, pub mapping_method_id: Option<String>, pub genetic_type: Option<String>, + /// The population category, e.g. "Reference Populations (replicate + /// average, SE, N)". + pub family: Option<String>, + /// The species' short name, e.g. "mouse" (as listed by /species). + pub species: Option<String>, } -/// Mirrors GeneNetwork2's wqflask.api.router.get_groups_list (no -/// species filter yet). +/// 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> { let pool = pool()?; let mut conn = pool.get_conn()?; conn.query_map( - "SELECT InbredSetId, SpeciesId, InbredSetName, Name, FullName, \ - public, MappingMethodId, GeneticType \ - FROM InbredSet ORDER BY Name ASC", + "SELECT InbredSet.InbredSetId, InbredSet.SpeciesId, InbredSet.InbredSetName, \ + InbredSet.Name, InbredSet.FullName, InbredSet.public, \ + InbredSet.MappingMethodId, InbredSet.GeneticType, InbredSet.Family, \ + Species.Name \ + FROM InbredSet LEFT JOIN Species ON Species.Id = InbredSet.SpeciesId \ + ORDER BY InbredSet.Name ASC", |( id, species_id, @@ -177,6 +185,8 @@ pub fn get_all_groups() -> Result<Vec<Group>, mysql::Error> { public, mapping_method_id, genetic_type, + family, + species, )| { Group { id, @@ -187,6 +197,8 @@ pub fn get_all_groups() -> Result<Vec<Group>, mysql::Error> { public, mapping_method_id, genetic_type, + family, + species, } }, ) @@ -353,20 +365,29 @@ pub struct TraitInfo { pub pages: Option<String>, pub month: Option<String>, pub year: Option<String>, + /// The PublishFreeze this trait belongs to, e.g. "BXDPublish". + pub dataset: Option<String>, + /// The trait's short name (Phenotype.Post_publication_abbreviation, + /// else Pre_publication_abbreviation), e.g. "5HT_MB_M". + pub abbreviation: Option<String>, + /// The trait's page on GeneNetwork's website. + pub url: Option<String>, } -/// Fetch one published trait's metadata (see TraitInfo) within a -/// group. Like get_group_trait_values, PublishXRef.Id alone isn't -/// unique across groups, so group_id is required. -pub fn get_group_trait_info( - group_id: u16, - trait_id: u32, -) -> Result<Option<TraitInfo>, mysql::Error> { - let pool = pool()?; - let mut conn = pool.get_conn()?; - conn.exec_first( - format!( - "SELECT PublishXRef.Id AS Id, PublishXRef.PhenotypeId AS PhenotypeId, \ +/// Where GeneNetwork's website shows one trait; see TraitInfo::url. +const GN_SHOW_TRAIT_URL: &str = "https://genenetwork.org/show_trait"; + +/// A published trait's short name; shared by every query that reports +/// or filters on it. +const ABBREVIATION_SQL: &str = + "COALESCE(NULLIF(Phenotype.Post_publication_abbreviation, ''), Phenotype.Pre_publication_abbreviation)"; + +/// The SELECT behind every TraitInfo row; callers add the WHERE +/// `filter` and the ORDER BY. PublishFreeze is joined on InbredSetId, +/// i.e. one dataset per group, as everywhere else in this API. +fn trait_info_sql(filter: &str, order_by: &str) -> String { + format!( + "SELECT PublishXRef.Id AS Id, PublishXRef.PhenotypeId AS PhenotypeId, \ PublishXRef.PublicationId AS PublicationId, PublishXRef.mean AS Mean, \ PublishXRef.Locus AS Locus, PublishXRef.LRS AS Lrs, \ PublishXRef.LRS / {LRS_PER_LOD} AS Lod, \ @@ -378,11 +399,33 @@ pub fn get_group_trait_info( Publication.PubMed_ID AS PubmedId, Publication.Title AS Title, \ Publication.Authors AS Authors, Publication.Journal AS Journal, \ Publication.Volume AS Volume, Publication.Pages AS Pages, \ - Publication.Month AS Month, Publication.Year AS Year \ + Publication.Month AS Month, Publication.Year AS Year, \ + PublishFreeze.Name AS Dataset, \ + {ABBREVIATION_SQL} AS Abbreviation, \ + CONCAT('{GN_SHOW_TRAIT_URL}?trait_id=', PublishXRef.Id, '&dataset=', \ + PublishFreeze.Name) AS Url \ FROM PublishXRef \ LEFT JOIN Phenotype ON Phenotype.Id = PublishXRef.PhenotypeId \ LEFT JOIN Publication ON Publication.Id = PublishXRef.PublicationId \ - WHERE PublishXRef.InbredSetId = :group_id AND PublishXRef.Id = :trait_id" + LEFT JOIN PublishFreeze ON PublishFreeze.InbredSetId = PublishXRef.InbredSetId \ + WHERE {filter} \ + ORDER BY {order_by}" + ) +} + +/// Fetch one published trait's metadata (see TraitInfo) within a +/// group. Like get_group_trait_values, PublishXRef.Id alone isn't +/// unique across groups, so group_id is required. +pub fn get_group_trait_info( + group_id: u16, + trait_id: u32, +) -> Result<Option<TraitInfo>, mysql::Error> { + let pool = pool()?; + let mut conn = pool.get_conn()?; + conn.exec_first( + trait_info_sql( + "PublishXRef.InbredSetId = :group_id AND PublishXRef.Id = :trait_id", + "PublishXRef.Id", ), mysql::params! { "group_id" => group_id, "trait_id" => trait_id }, ) @@ -394,46 +437,76 @@ pub fn get_group_traits(group_id: u16) -> Result<Vec<TraitInfo>, mysql::Error> { let pool = pool()?; let mut conn = pool.get_conn()?; conn.exec( - format!( - "SELECT PublishXRef.Id AS Id, PublishXRef.PhenotypeId AS PhenotypeId, \ - PublishXRef.PublicationId AS PublicationId, PublishXRef.mean AS Mean, \ - PublishXRef.Locus AS Locus, PublishXRef.LRS AS Lrs, \ - PublishXRef.LRS / {LRS_PER_LOD} AS Lod, \ - PublishXRef.additive AS Additive, PublishXRef.NSamples AS Nsamples, \ - Phenotype.Pre_publication_description AS PrePublicationDescription, \ - Phenotype.Post_publication_description AS PostPublicationDescription, \ - Phenotype.Original_description AS OriginalDescription, \ - Phenotype.Units AS Units, \ - Publication.PubMed_ID AS PubmedId, Publication.Title AS Title, \ - Publication.Authors AS Authors, Publication.Journal AS Journal, \ - Publication.Volume AS Volume, Publication.Pages AS Pages, \ - Publication.Month AS Month, Publication.Year AS Year \ - FROM PublishXRef \ - LEFT JOIN Phenotype ON Phenotype.Id = PublishXRef.PhenotypeId \ - LEFT JOIN Publication ON Publication.Id = PublishXRef.PublicationId \ - WHERE PublishXRef.InbredSetId = :group_id \ - ORDER BY PublishXRef.Id" - ), + trait_info_sql("PublishXRef.InbredSetId = :group_id", "PublishXRef.Id"), mysql::params! { "group_id" => group_id }, ) } -/// Peak marker names for published traits, keyed by (dataset name, -/// PublishXRef.Id), in one query. Traits with no recorded Locus are -/// absent from the result. -pub fn get_publish_loci( +/// The traits of a group whose short name (either the post- or the +/// pre-publication abbreviation) is `abbreviation`. +pub fn get_group_traits_by_abbreviation( + group_id: u16, + abbreviation: &str, +) -> Result<Vec<TraitInfo>, mysql::Error> { + let pool = pool()?; + let mut conn = pool.get_conn()?; + conn.exec( + trait_info_sql( + "PublishXRef.InbredSetId = :group_id \ + AND (Phenotype.Post_publication_abbreviation = :abbreviation \ + OR Phenotype.Pre_publication_abbreviation = :abbreviation)", + "PublishXRef.Id", + ), + mysql::params! { "group_id" => group_id, "abbreviation" => abbreviation }, + ) +} + +/// 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> { + let pool = pool()?; + let mut conn = pool.get_conn()?; + let exists: Option<u32> = conn.exec_first( + "SELECT Id FROM Publication WHERE PubMed_ID = :pubmed_id LIMIT 1", + mysql::params! { "pubmed_id" => pubmed_id }, + )?; + if exists.is_none() { + return Ok(None); + } + conn.exec( + trait_info_sql( + "Publication.PubMed_ID = :pubmed_id", + "PublishFreeze.Name, PublishXRef.Id", + ), + mysql::params! { "pubmed_id" => pubmed_id }, + ) + .map(Some) +} + +/// What search hits are annotated with from PublishXRef/Phenotype +/// (gn3's hits carry neither). +#[derive(Default, Clone)] +pub struct PublishAnnotation { + pub locus: Option<String>, + pub abbreviation: Option<String>, +} + +/// Peak marker names and short names for published traits, keyed by +/// (dataset name, PublishXRef.Id), in one query. Traits that don't +/// exist are absent from the result. +pub fn get_publish_annotations( keys: &[(String, u32)], -) -> Result<std::collections::HashMap<(String, u32), String>, mysql::Error> { +) -> Result<std::collections::HashMap<(String, u32), PublishAnnotation>, mysql::Error> { let pool = pool()?; let mut conn = pool.get_conn()?; let pairs = vec!["(?, ?)"; keys.len()].join(", "); - let rows: Vec<(String, u32, String)> = conn.exec( + let rows: Vec<(String, u32, Option<String>, Option<String>)> = conn.exec( format!( - "SELECT PublishFreeze.Name, PublishXRef.Id, PublishXRef.Locus \ + "SELECT PublishFreeze.Name, PublishXRef.Id, PublishXRef.Locus, {ABBREVIATION_SQL} \ FROM PublishXRef \ JOIN PublishFreeze ON PublishFreeze.InbredSetId = PublishXRef.InbredSetId \ - WHERE PublishXRef.Locus IS NOT NULL \ - AND (PublishFreeze.Name, PublishXRef.Id) IN ({pairs})" + LEFT JOIN Phenotype ON Phenotype.Id = PublishXRef.PhenotypeId \ + WHERE (PublishFreeze.Name, PublishXRef.Id) IN ({pairs})" ), keys.iter() .flat_map(|(dataset, id)| [mysql::Value::from(dataset), mysql::Value::from(*id)]) @@ -441,7 +514,15 @@ pub fn get_publish_loci( )?; Ok(rows .into_iter() - .map(|(dataset, id, locus)| ((dataset, id), locus)) + .map(|(dataset, id, locus, abbreviation)| { + ( + (dataset, id), + PublishAnnotation { + locus, + abbreviation, + }, + ) + }) .collect()) } diff --git a/src/lib.rs b/src/lib.rs index 46c4211..acfd891 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -71,6 +71,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::publications::publication_traits)) .routes(routes!(routes::search::search)) .routes(routes!(routes::correlation::correlation)); // Only registered -- so only ever reachable, and only ever diff --git a/src/routes/groups.rs b/src/routes/groups.rs index 12652ec..90e22f7 100644 --- a/src/routes/groups.rs +++ b/src/routes/groups.rs @@ -4,6 +4,7 @@ use axum::Json; use axum::extract::{Extension, Path, Query}; use axum::http::StatusCode; +use serde::Deserialize; use tower_http::request_id::RequestId; use crate::auth::AuthToken; @@ -11,14 +12,35 @@ use crate::db; use crate::error::{ApiError, Unauthorized}; use crate::request_id_string; -#[utoipa::path(get, path = "/groups", summary = "List all groups (populations; InbredSet rows)", responses( - (status = 200, description = "All groups (InbredSet rows) in the database", body = Vec<db::Group>), +/// Query parameters for `GET /groups`; all optional, combined with AND. +#[derive(Deserialize, utoipa::IntoParams)] +pub struct GroupsParams { + /// Keep groups whose family contains this text, case-insensitively, + /// e.g. "Reference Populations". + pub family: Option<String>, + /// Keep groups of this species, by the short name /species lists + /// (case-insensitive), e.g. "mouse". + pub species: Option<String>, + /// Keep groups whose name, display name or full name contains this + /// text, case-insensitively, e.g. "alzheimer". + pub q: Option<String>, +} + +fn contains_ci(field: &Option<String>, needle: &str) -> bool { + field + .as_deref() + .is_some_and(|f| f.to_lowercase().contains(&needle.to_lowercase())) +} + +#[utoipa::path(get, path = "/groups", summary = "List all groups (populations; InbredSet rows), optionally filtered", params(GroupsParams), responses( + (status = 200, description = "The groups (InbredSet rows), with family and species name", body = Vec<db::Group>), Unauthorized, (status = 500, description = "Database error", body = ApiError) ))] pub async fn groups( Extension(request_id): Extension<RequestId>, _token: AuthToken, + Query(params): Query<GroupsParams>, ) -> Result<Json<Vec<db::Group>>, ApiError> { let rid = request_id_string(&request_id); tokio::task::spawn_blocking(db::get_all_groups) @@ -33,7 +55,27 @@ pub async fn groups( ) .with_request_id(rid.clone()) })? - .map(Json) + .map(|groups| { + Json( + groups + .into_iter() + .filter(|g| params.family.as_ref().is_none_or(|f| contains_ci(&g.family, f))) + .filter(|g| { + params + .species + .as_ref() + .is_none_or(|s| g.species.as_deref().is_some_and(|n| n.eq_ignore_ascii_case(s))) + }) + .filter(|g| { + params.q.as_ref().is_none_or(|q| { + contains_ci(&Some(g.name.clone()), q) + || contains_ci(&g.display_name, q) + || contains_ci(&g.full_name, q) + }) + }) + .collect(), + ) + }) .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, @@ -320,8 +362,17 @@ pub async fn group_trait_info( }) } +/// Query parameters for `GET /groups/{group}/traits`. +#[derive(Deserialize, utoipa::IntoParams)] +pub struct GroupTraitsParams { + /// Only the traits with this short name (abbreviation), e.g. + /// "5HT_MB_M" or "3NP_Tox". + pub abbreviation: Option<String>, +} + #[utoipa::path(get, path = "/groups/{group}/traits", summary = "List the published (phenotype) traits belonging to a group", params( - ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id") + ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id"), + GroupTraitsParams ), responses( (status = 200, description = "The published traits belonging to the group", body = Vec<db::TraitInfo>), Unauthorized, @@ -332,13 +383,17 @@ pub async fn group_traits( Extension(request_id): Extension<RequestId>, Path(group): Path<String>, _token: AuthToken, + Query(params): Query<GroupTraitsParams>, ) -> Result<Json<Vec<db::TraitInfo>>, ApiError> { let rid = request_id_string(&request_id); let not_found_name = group.clone(); tokio::task::spawn_blocking(move || { - db::get_group_by_name(&group).and_then(|group| match group { - Some(group) => db::get_group_traits(group.id).map(Some), - None => Ok(None), + db::get_group_by_name(&group).and_then(|group| match (group, params.abbreviation) { + (Some(group), Some(abbreviation)) => { + db::get_group_traits_by_abbreviation(group.id, &abbreviation).map(Some) + } + (Some(group), None) => db::get_group_traits(group.id).map(Some), + (None, _) => Ok(None), }) }) .await diff --git a/src/routes/mod.rs b/src/routes/mod.rs index fd1ef4a..0362206 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -7,6 +7,7 @@ pub mod correlation; pub mod datasets; pub mod dev; pub mod groups; +pub mod publications; pub mod search; pub mod species; pub mod traits; diff --git a/src/routes/publications.rs b/src/routes/publications.rs new file mode 100644 index 0000000..2f6fab4 --- /dev/null +++ b/src/routes/publications.rs @@ -0,0 +1,130 @@ +//! Publications domain endpoint: which traits a paper reports. + +use axum::Json; +use axum::extract::{Extension, Path}; +use axum::http::StatusCode; +use std::collections::HashMap; +use tower_http::request_id::RequestId; + +use crate::auth::AuthToken; +use crate::config::Config; +use crate::db; +use crate::error::{ApiError, Unauthorized}; +use crate::request_id_string; +use crate::routes::traits::is_authorised; + +enum PublicationTraits { + NotFound, + Found(Vec<db::TraitInfo>), +} + +enum LookupError { + Db(mysql::Error), + Auth(String), +} + +impl From<mysql::Error> for LookupError { + fn from(e: mysql::Error) -> Self { + LookupError::Db(e) + } +} + +/// The publication's traits, minus those of datasets the caller may +/// not view (each dataset is checked once, as in GET /traits/{dataset}). +fn get_publication_traits_result( + pubmed_id: u32, + auth_server_url: &str, + token: &AuthToken, +) -> Result<PublicationTraits, LookupError> { + let Some(traits) = db::get_publication_traits(pubmed_id)? else { + return Ok(PublicationTraits::NotFound); + }; + let mut readable: HashMap<String, bool> = HashMap::new(); + let mut visible = Vec::new(); + for info in traits { + let Some(dataset) = info.dataset.clone() else { + continue; + }; + if !readable.contains_key(&dataset) { + let allowed = match db::get_publish_freeze_by_name(&dataset)? { + Some(pf) => is_authorised( + auth_server_url, + token, + &pf.name, + None, + pf.public, + pf.confidentiality, + &pf.create_time, + ) + .map_err(LookupError::Auth)?, + None => false, + }; + readable.insert(dataset.clone(), allowed); + } + if readable[&dataset] { + visible.push(info); + } + } + Ok(PublicationTraits::Found(visible)) +} + +#[utoipa::path(get, path = "/publications/{pubmed_id}/traits", summary = "List the published traits a publication reports", description = "Every published (phenotype) trait, across groups and datasets, whose publication has this PubMed id. Traits of datasets the caller isn't authorized to view are left out.", params( + ("pubmed_id" = u32, Path, description = "The publication's PubMed id, e.g. 31634382") +), responses( + (status = 200, description = "The publication's traits (possibly none)", body = Vec<db::TraitInfo>), + Unauthorized, + (status = 404, description = "No publication with this PubMed id", body = ApiError), + (status = 500, description = "Database error", body = ApiError), + (status = 502, description = "Could not reach gn-auth to check authorization", body = ApiError) +))] +pub async fn publication_traits( + Extension(request_id): Extension<RequestId>, + Path(pubmed_id): Path<u32>, + token: AuthToken, +) -> Result<Json<Vec<db::TraitInfo>>, ApiError> { + let rid = request_id_string(&request_id); + let auth_server_url = Config::load().auth_server_url.clone(); + tokio::task::spawn_blocking(move || { + get_publication_traits_result(pubmed_id, &auth_server_url, &token) + }) + .await + .map_err(|e| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Internal error", + e.to_string(), + "publication_traits", + ) + .with_request_id(rid.clone()) + })? + .map_err(|e| match e { + LookupError::Db(e) => ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "database_error", + "Database error", + e.to_string(), + "publication_traits", + ) + .with_request_id(rid.clone()), + LookupError::Auth(e) => ApiError::new( + StatusCode::BAD_GATEWAY, + "auth_server_error", + "Could not check authorization", + e, + "publication_traits", + ) + .with_request_id(rid.clone()), + }) + .and_then(|lookup| match lookup { + PublicationTraits::Found(traits) => Ok(Json(traits)), + PublicationTraits::NotFound => Err(ApiError::new( + StatusCode::NOT_FOUND, + "publication_not_found", + "Publication not found", + format!("No publication with PubMed id {pubmed_id}."), + "publication_traits", + ) + .with_request_id(rid)), + }) +} diff --git a/src/routes/search.rs b/src/routes/search.rs index 78e3b7c..57e84df 100644 --- a/src/routes/search.rs +++ b/src/routes/search.rs @@ -3,9 +3,10 @@ //! 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, plus three -//! additions gn3's hits lack: `lod` (derived from `lrs`), `locus` (the -//! peak marker's name, looked up in PublishXRef) and `sort`/`order`. +//! gn4 contributes boundary validation and the contract, plus what +//! gn3's hits lack: `lod` (derived from `lrs`), `locus` and +//! `abbreviation` (looked up in PublishXRef/Phenotype), and +//! `sort`/`order`/`page`. use axum::Json; use axum::extract::{Extension, Query}; @@ -58,6 +59,10 @@ pub struct SearchParams { pub sort: Option<String>, /// "desc" (default) or "asc"; only meaningful with `sort`. pub order: Option<String>, + /// Which page of `limit` hits to return (default 1). With `sort`, + /// pages are taken from the ranked list, so they reach past the + /// first `limit` best hits (up to the first 1000 matches). + pub page: Option<u64>, } /// With `sort`, gn3 is asked for this many hits (not just `limit`) so @@ -83,15 +88,18 @@ pub struct SearchHit { pub mean: Option<f64>, pub additive: Option<f64>, pub lrs: Option<f64>, - /// LOD score, LRS / 4.61; computed here from `lrs`. + /// LOD score, LRS / 4.604; computed here from `lrs`. pub lod: Option<f64>, /// Name of the peak marker (a Geno.Name such as "rsm10000012461"), /// looked up in PublishXRef for phenotype hits; null for other /// hits, or when the database is unavailable. pub locus: Option<String>, + /// The trait's short name (e.g. "5HT_MB_M"), looked up like `locus`. + pub abbreviation: Option<String>, pub geno_chr: Option<String>, pub geno_mb: Option<f64>, pub inbredsetcode: Option<String>, + pub pubmed_id: Option<u32>, #[serde(flatten)] #[schema(value_type = Option<std::collections::BTreeMap<String, String>>)] pub extra: std::collections::BTreeMap<String, serde_json::Value>, @@ -109,32 +117,30 @@ fn sort_by_lrs(hits: &mut [SearchHit], ascending: bool) { }); } -/// Fills in `locus` for phenotype hits from one PublishXRef lookup. -/// A database failure leaves `locus` null rather than failing the -/// search: the hits are still correct, and the marker is also on +/// Fills in `locus` and `abbreviation` for phenotype hits from one +/// PublishXRef lookup. A database failure leaves them null rather than +/// failing the search: the hits are still correct, and both are also on /// GET /traits/{dataset}/{trait}. -async fn add_loci(hits: &mut [SearchHit]) { - let keys: Vec<(String, u32)> = hits - .iter() - .filter_map(|hit| { - let dataset = hit.dataset.as_deref().filter(|d| d.ends_with("Publish"))?; - Some((dataset.to_string(), hit.name.as_deref()?.parse().ok()?)) - }) - .collect(); +async fn add_publish_annotations(hits: &mut [SearchHit]) { + let key = |hit: &SearchHit| -> Option<(String, u32)> { + let dataset = hit.dataset.as_deref().filter(|d| d.ends_with("Publish"))?; + Some((dataset.to_string(), hit.name.as_deref()?.parse().ok()?)) + }; + let keys: Vec<(String, u32)> = hits.iter().filter_map(key).collect(); if keys.is_empty() { return; } - let loci: HashMap<(String, u32), String> = - match tokio::task::spawn_blocking(move || db::get_publish_loci(&keys)).await { - Ok(Ok(loci)) => loci, + let annotations: HashMap<(String, u32), db::PublishAnnotation> = + match tokio::task::spawn_blocking(move || db::get_publish_annotations(&keys)).await { + Ok(Ok(annotations)) => annotations, _ => return, }; for hit in hits { - let key = ( - hit.dataset.clone().unwrap_or_default(), - hit.name.as_deref().and_then(|n| n.parse().ok()).unwrap_or(0), - ); - hit.locus = loci.get(&key).cloned(); + let annotation = key(hit) + .and_then(|key| annotations.get(&key).cloned()) + .unwrap_or_default(); + hit.locus = annotation.locus; + hit.abbreviation = annotation.abbreviation; } } @@ -193,10 +199,16 @@ pub async fn search( Some("asc") => true, Some(_) => return Err(bad_request("order must be \"asc\" or \"desc\"")), }; - let fetch_limit = if params.sort.is_some() { - SORT_FETCH_LIMIT + let page = params.page.unwrap_or(1); + if page < 1 { + return Err(bad_request("page must be at least 1")); + } + // Unsorted: gn3 pages for us. Sorted: gn3 is asked for one wide + // first page and the pages are taken from the ranked list. + let (fetch_limit, gn3_page) = if params.sort.is_some() { + (SORT_FETCH_LIMIT, 1) } else { - limit + (limit, page) }; // Every gn3-side failure maps to one 502 shape; the caller can tell @@ -219,6 +231,7 @@ pub async fn search( ("query", q), ("type", search_type), ("per_page", &fetch_limit.to_string()), + ("page", &gn3_page.to_string()), ], ) .map_err(|e| { @@ -279,9 +292,13 @@ pub async fn search( } if params.sort.is_some() { sort_by_lrs(&mut hits, ascending); + hits = hits + .into_iter() + .skip((page - 1).saturating_mul(limit) as usize) + .collect(); } hits.truncate(limit as usize); - add_loci(&mut hits).await; + add_publish_annotations(&mut hits).await; Ok(Json(Envelope::of(hits))) } diff --git a/src/routes/traits.rs b/src/routes/traits.rs index fea6eb3..97dfbf5 100644 --- a/src/routes/traits.rs +++ b/src/routes/traits.rs @@ -59,7 +59,7 @@ impl From<mysql::Error> for TraitAuthError { /// Shared by all three handlers below so the ProbeSet and Publish /// branches of each only differ in which db:: functions they call, not /// in how they're gated. -fn is_authorised( +pub(crate) fn is_authorised( auth_server_url: &str, token: &AuthToken, dataset_name: &str, |
