//! Trait domain endpoints spanning both ProbeSet (expression) and //! Publish (phenotype) data: a trait is a trait is a trait, addressed //! the same way as GeneNetwork2's own generic //! `wqflask.api.router.trait_sample_data`/`get_trait_info` -- //! `(dataset, trait)` -- rather than category-specific paths. See //! docs/gn-auth.md for why `dataset` is resolved across categories //! before `trait` is ever looked up (avoids ever having to guess which //! category a bare trait name/id belongs to). //! //! `/groups/{group}/traits...` and `/datasets/{dataset}/probesets...` //! (src/routes/groups.rs, src/routes/datasets.rs) are untouched by //! this -- this is an additional, category-spanning way to reach the //! same underlying data, not a replacement. use axum::Json; use axum::extract::Path; use axum::http::StatusCode; use serde::Serialize; use gnauth_macros::gnauth; use crate::auth::{self, AuthToken, Authorized}; use crate::config::Config; use crate::db; use crate::error::{ApiError, Unauthorized}; use crate::response::{Ctx, Envelope, path_segment}; use crate::suggest; /// One trait's metadata, tagged by which category its dataset resolved /// to (db::resolve_trait_dataset). ProbeSetInfo and TraitInfo share /// little beyond mean/locus/lrs/additive -- gene annotation vs. /// publication reference -- so this keeps both fully typed rather than /// collapsing to a lossy common subset. #[derive(Serialize, utoipa::ToSchema)] #[serde(tag = "category", rename_all = "snake_case")] pub enum TraitInfoResponse { Probeset(db::ProbeSetInfo), Publish(db::TraitInfo), } /// Either a database error, or a failure to reach/parse gn-auth's /// answer while checking authorization for a non-public dataset. Same /// shape as routes::datasets::DatasetAuthError; not shared with it, /// matching this codebase's existing per-module lookup/error types /// (see e.g. GroupTraitLookup vs DatasetProbesetLookup). enum TraitAuthError { Db(db::DbError), Auth(String), } impl From for TraitAuthError { fn from(e: db::DbError) -> Self { TraitAuthError::Db(e) } } enum TraitsLookup { DatasetNotFound, Forbidden, Found(Authorized, Vec), } fn get_traits_result( dataset: &str, auth_server_url: &str, token: &AuthToken, ) -> Result { let dataset = match db::resolve_trait_dataset(dataset)? { None => return Ok(TraitsLookup::DatasetNotFound), Some(dataset) => dataset, }; match dataset { db::TraitDataset::ProbeSet(ds) => { let Some(auth) = auth::check( auth_server_url, token, &ds.name, None, ds.public, ds.confidentiality, &ds.create_time, ) .map_err(TraitAuthError::Auth)? else { return Ok(TraitsLookup::Forbidden); }; Ok(TraitsLookup::Found( auth, db::get_dataset_probesets(ds.id)? .into_iter() .map(TraitInfoResponse::Probeset) .collect(), )) } db::TraitDataset::Publish(pf) => { let Some(auth) = auth::check( auth_server_url, token, &pf.name, None, pf.public, pf.confidentiality, &pf.create_time, ) .map_err(TraitAuthError::Auth)? else { return Ok(TraitsLookup::Forbidden); }; Ok(TraitsLookup::Found( auth, db::get_group_traits(pf.inbred_set_id)? .into_iter() .map(TraitInfoResponse::Publish) .collect(), )) } } } #[utoipa::path(get, path = "/traits/{dataset}", summary = "List every trait in a dataset, across ProbeSet and Publish categories", params( ("dataset" = String, Path, description = "ProbeSetFreeze Name/Name2/FullName/ShortName/Id, or PublishFreeze Name/ShortName/Id, or (for Publish data) the owning group's Name/InbredSetName/FullName/Id") ), responses( (status = 200, description = "Every trait in the dataset, tagged by category", body = Envelope>), Unauthorized, (status = 403, description = "The dataset isn't public, and the caller isn't authorized for it", body = ApiError), (status = 404, description = "No matching dataset", 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 traits( ctx: Ctx, Path(dataset): Path, token: AuthToken, ) -> Result>>, ApiError> { let rid = ctx.request_info(); let not_found_name = dataset.clone(); let auth_server_url = Config::load().auth_server_url.clone(); tokio::task::spawn_blocking(move || get_traits_result(&dataset, &auth_server_url, &token)) .await .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "internal_error", "Internal error", e.to_string(), "traits", ) .with_request_id(rid.clone()) })? .map_err(|e| match e { TraitAuthError::Db(e) => { ApiError::from_db(e, "traits").with_request_id(rid.clone()) } TraitAuthError::Auth(e) => ApiError::new( StatusCode::BAD_GATEWAY, "auth_server_error", "Could not check authorization", e, "traits", ) .with_request_id(rid.clone()), }) .and_then(|lookup| match lookup { TraitsLookup::Found(_authorized, traits) => { Ok(Json( ctx.envelope(traits) .with_note(db::LOD_NOTE) .with_links(crate::suggest::root_links()), )) } TraitsLookup::Forbidden => Err(ApiError::new( StatusCode::FORBIDDEN, "forbidden", "Not authorized", format!( "Dataset '{not_found_name}' is not public, and you are not authorized to view it." ), "traits", ) .with_request_id(rid.clone())), TraitsLookup::DatasetNotFound => Err(ApiError::new( StatusCode::NOT_FOUND, "dataset_not_found", "Dataset not found", format!("No dataset matching '{not_found_name}'."), "traits", ) .with_request_id(rid)), }) } enum TraitInfoLookup { DatasetNotFound, TraitNotFound, Forbidden, Found(Authorized, Box), } fn get_trait_info_result( dataset: &str, trait_name: &str, auth_server_url: &str, token: &AuthToken, ) -> Result { let dataset = match db::resolve_trait_dataset(dataset)? { None => return Ok(TraitInfoLookup::DatasetNotFound), Some(dataset) => dataset, }; match dataset { db::TraitDataset::ProbeSet(ds) => { let info = match db::get_dataset_probeset_info(ds.id, trait_name)? { None => return Ok(TraitInfoLookup::TraitNotFound), Some(info) => info, }; let Some(auth) = auth::check( auth_server_url, token, &ds.name, Some(trait_name), ds.public, ds.confidentiality, &ds.create_time, ) .map_err(TraitAuthError::Auth)? else { return Ok(TraitInfoLookup::Forbidden); }; Ok(TraitInfoLookup::Found( auth, Box::new(TraitInfoResponse::Probeset(info)), )) } db::TraitDataset::Publish(pf) => { let Ok(trait_id) = trait_name.parse::() else { return Ok(TraitInfoLookup::TraitNotFound); }; let info = match db::get_group_trait_info(pf.inbred_set_id, trait_id)? { None => return Ok(TraitInfoLookup::TraitNotFound), Some(info) => info, }; let Some(auth) = auth::check( auth_server_url, token, &pf.name, Some(trait_name), pf.public, pf.confidentiality, &pf.create_time, ) .map_err(TraitAuthError::Auth)? else { return Ok(TraitInfoLookup::Forbidden); }; Ok(TraitInfoLookup::Found( auth, Box::new(TraitInfoResponse::Publish(info)), )) } } } #[utoipa::path(get, path = "/traits/{dataset}/{trait}", summary = "Get one trait's metadata, across ProbeSet and Publish categories", params( ("dataset" = String, Path, description = "ProbeSetFreeze Name/Name2/FullName/ShortName/Id, or PublishFreeze Name/ShortName/Id, or (for Publish data) the owning group's Name/InbredSetName/FullName/Id"), ("trait" = String, Path, description = "ProbeSet.Name (ProbeSet category) or PublishXRef.Id (Publish category)") ), responses( (status = 200, description = "The trait's metadata, tagged by category", body = Envelope), Unauthorized, (status = 403, description = "The dataset isn't public, and the caller isn't authorized for it", body = ApiError), (status = 404, description = "No matching dataset, or no matching trait in that dataset", 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 trait_info( ctx: Ctx, Path((dataset, trait_name)): Path<(String, String)>, token: AuthToken, ) -> Result>, ApiError> { let rid = ctx.request_info(); let not_found_dataset = dataset.clone(); let not_found_trait = trait_name.clone(); let auth_server_url = Config::load().auth_server_url.clone(); tokio::task::spawn_blocking(move || { get_trait_info_result(&dataset, &trait_name, &auth_server_url, &token) }) .await .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "internal_error", "Internal error", e.to_string(), "trait_info", ) .with_request_id(rid.clone()) })? .map_err(|e| match e { TraitAuthError::Db(e) => ApiError::from_db(e, "trait_info").with_request_id(rid.clone()), TraitAuthError::Auth(e) => ApiError::new( StatusCode::BAD_GATEWAY, "auth_server_error", "Could not check authorization", e, "trait_info", ) .with_request_id(rid.clone()), }) .and_then(|lookup| match lookup { TraitInfoLookup::Found(_authorized, info) => { let base = format!( "/traits/{}/{}", path_segment(¬_found_dataset), path_segment(¬_found_trait) ); let pubmed_id = match &*info { TraitInfoResponse::Publish(info) => info.pubmed_id, TraitInfoResponse::Probeset(_) => None, }; let mut envelope = ctx.envelope(*info).with_note(db::LOD_NOTE).with_next( &format!("{base}/values"), "The trait's value in each strain", ); if let Some(pubmed_id) = pubmed_id { envelope = envelope.with_next( &format!("/publications/{pubmed_id}/traits"), "Every trait reported by this trait's publication", ); } Ok(Json(envelope.with_links(crate::suggest::root_links()))) } TraitInfoLookup::Forbidden => Err(ApiError::new( StatusCode::FORBIDDEN, "forbidden", "Not authorized", format!( "'{not_found_trait}' in dataset '{not_found_dataset}' is not public, \ and you are not authorized to view it." ), "trait_info", ) .with_request_id(rid.clone())), TraitInfoLookup::DatasetNotFound => Err(ApiError::new( StatusCode::NOT_FOUND, "dataset_not_found", "Dataset not found", format!("No dataset matching '{not_found_dataset}'."), "trait_info", ) .with_request_id(rid.clone())), TraitInfoLookup::TraitNotFound => Err(ApiError::new( StatusCode::NOT_FOUND, "trait_not_found", "Trait not found", format!("No trait '{not_found_trait}' in dataset '{not_found_dataset}'."), "trait_info", ) .with_request_id(rid)), }) } enum TraitValuesLookup { DatasetNotFound, TraitNotFound, Forbidden, /// The values, plus the owning group's name when the dataset belongs to /// one -- the links offered are `/groups/...` paths, and a dataset name is /// not a group name (BXDPublish's traits live in BXD). Found(Authorized, Vec, Option), } fn get_trait_values_result( dataset: &str, trait_name: &str, auth_server_url: &str, token: &AuthToken, ) -> Result { let dataset = match db::resolve_trait_dataset(dataset)? { None => return Ok(TraitValuesLookup::DatasetNotFound), Some(dataset) => dataset, }; match dataset { db::TraitDataset::ProbeSet(ds) => { let values = db::get_dataset_probeset_values(ds.id, trait_name)?; if values.is_empty() { return Ok(TraitValuesLookup::TraitNotFound); } let Some(auth) = auth::check( auth_server_url, token, &ds.name, Some(trait_name), ds.public, ds.confidentiality, &ds.create_time, ) .map_err(TraitAuthError::Auth)? else { return Ok(TraitValuesLookup::Forbidden); }; Ok(TraitValuesLookup::Found( auth, values .into_iter() .map(|v| db::TraitValue { name: v.name, value: v.value, }) .collect(), Some(ds.name.clone()), )) } db::TraitDataset::Publish(pf) => { let Ok(trait_id) = trait_name.parse::() else { return Ok(TraitValuesLookup::TraitNotFound); }; let values = db::get_group_trait_values(pf.inbred_set_id, trait_id)?; if values.is_empty() { return Ok(TraitValuesLookup::TraitNotFound); } let Some(auth) = auth::check( auth_server_url, token, &pf.name, Some(trait_name), pf.public, pf.confidentiality, &pf.create_time, ) .map_err(TraitAuthError::Auth)? else { return Ok(TraitValuesLookup::Forbidden); }; let group = db::get_group_name(pf.inbred_set_id)?; Ok(TraitValuesLookup::Found(auth, values, group)) } } } #[utoipa::path(get, path = "/traits/{dataset}/{trait}/values", summary = "Get one trait's value in each strain, across ProbeSet and Publish categories", params( ("dataset" = String, Path, description = "ProbeSetFreeze Name/Name2/FullName/ShortName/Id, or PublishFreeze Name/ShortName/Id, or (for Publish data) the owning group's Name/InbredSetName/FullName/Id"), ("trait" = String, Path, description = "ProbeSet.Name (ProbeSet category) or PublishXRef.Id (Publish category)") ), responses( (status = 200, description = "The trait's per-strain values", body = Envelope>), Unauthorized, (status = 403, description = "The dataset isn't public, and the caller isn't authorized for it", body = ApiError), (status = 404, description = "No matching dataset, or no matching trait in that dataset", body = ApiError), (status = 500, description = "Database error", body = ApiError), (status = 502, description = "Could not reach gn-auth to check authorization", body = ApiError) ))] #[gnauth(secured)] pub async fn trait_values( ctx: Ctx, Path((dataset, trait_name)): Path<(String, String)>, token: AuthToken, ) -> Result>>, ApiError> { let rid = ctx.request_info(); let not_found_dataset = dataset.clone(); let not_found_trait = trait_name.clone(); let auth_server_url = Config::load().auth_server_url.clone(); tokio::task::spawn_blocking(move || { get_trait_values_result(&dataset, &trait_name, &auth_server_url, &token) }) .await .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "internal_error", "Internal error", e.to_string(), "trait_values", ) .with_request_id(rid.clone()) })? .map_err(|e| match e { TraitAuthError::Db(e) => ApiError::from_db(e, "trait_values").with_request_id(rid.clone()), TraitAuthError::Auth(e) => ApiError::new( StatusCode::BAD_GATEWAY, "auth_server_error", "Could not check authorization", e, "trait_values", ) .with_request_id(rid.clone()), }) .and_then(|lookup| match lookup { TraitValuesLookup::Found(authorized, values, group) => { let _: Authorized = authorized; let actions = suggest::mapping_actions_for( &values, &format!("{}::{}", not_found_dataset, not_found_trait), ); // Group paths take the group's own name, not the dataset's: the // dataset here may be BXDPublish, whose group is BXD, and // `/groups/BXDPublish/phewas` is a 404 (no genotype files for it). // When the dataset has no group at all (a ProbeSet dataset whose // ProbeFreeze names none), the group links are simply absent. let group_links: Vec = group .as_deref() .map(|group| { vec![ ( // A bare `/phewas` is a 422 (`give either locus, // or chr and mb`), so the link is a shape with // placeholders -- the same convention as // `/markers/{marker}/classes?trait={trait_id}`: // the description says what to fill in, and // tests/envelope.rs skips hrefs with braces on // that condition. format!( "/groups/{}/phewas?chr={{chr}}&mb={{mb}}", path_segment(group) ), "PheWAS: this group's traits peaking near one locus; fill in chr \ and mb (e.g. chr=1&mb=50)", ), ( format!("/groups/{}/genotypes", path_segment(group)), "The genotype versions these values can be mapped against", ), ( format!("/groups/{}/traits", path_segment(group)), "The group's other published traits", ), ] }) .unwrap_or_default(); // No `next` link for correlation: it is a POST // (`/compute/correlation`) and this reply already carries it in // `actions`. A GET `next` here was a 404 -- `tests/envelope.rs` // follows every link offered. Ok(Json( ctx.envelope(values) .with_actions(actions) .with_next( &format!( "/traits/{}/{}", path_segment(¬_found_dataset), path_segment(¬_found_trait) ), "The trait's metadata", ) .with_links(group_links) .with_links(crate::suggest::root_links()), )) } TraitValuesLookup::Forbidden => Err(ApiError::new( StatusCode::FORBIDDEN, "forbidden", "Not authorized", format!( "'{not_found_trait}' in dataset '{not_found_dataset}' is not public, \ and you are not authorized to view it." ), "trait_values", ) .with_request_id(rid.clone())), TraitValuesLookup::DatasetNotFound => Err(ApiError::new( StatusCode::NOT_FOUND, "dataset_not_found", "Dataset not found", format!("No dataset matching '{not_found_dataset}'."), "trait_values", ) .with_request_id(rid.clone())), TraitValuesLookup::TraitNotFound => Err(ApiError::new( StatusCode::NOT_FOUND, "trait_not_found", "Trait not found", format!("No trait '{not_found_trait}' in dataset '{not_found_dataset}'."), "trait_values", ) .with_request_id(rid)), }) }