//! Groups (InbredSet) domain endpoints: read-only access to the //! InbredSet table and its strains. use axum::Json; use axum::extract::{Path, Query}; use axum::http::StatusCode; use serde::Deserialize; 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}; /// 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, /// Keep groups of this species, by the short name /species lists /// (case-insensitive), e.g. "mouse". pub species: Option, /// Keep groups whose name, display name or full name contains this /// text, case-insensitively, e.g. "alzheimer". pub q: Option, } fn contains_ci(field: &Option, 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 = Envelope>), Unauthorized, (status = 500, description = "Database error", body = ApiError) ))] #[gnauth(token_only)] pub async fn groups( ctx: Ctx, _token: AuthToken, Query(params): Query, ) -> Result>>, ApiError> { let rid = ctx.request_info(); tokio::task::spawn_blocking(db::get_all_groups) .await .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "internal_error", "Internal error", e.to_string(), "groups", ) .with_request_id(rid.clone()) })? .map(|groups| { let groups: Vec = 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(); Json(ctx.envelope(groups).with_next( "/species", "The species the groups belong to (filter groups with ?species=)", )) }) .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "database_error", "Database error", e.to_string(), "groups", ) .with_request_id(rid) }) } #[utoipa::path(get, path = "/groups/{group}", summary = "Get one group's full record by name or numeric id", params( ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id") ), responses( (status = 200, description = "The matching row of the InbredSet table", body = Envelope), Unauthorized, (status = 404, description = "No matching group", body = ApiError), (status = 500, description = "Database error", body = ApiError) ))] #[gnauth(token_only)] pub async fn group_by_name( ctx: Ctx, Path(group): Path, _token: AuthToken, ) -> Result>, ApiError> { let rid = ctx.request_info(); let not_found_name = group.clone(); tokio::task::spawn_blocking(move || db::get_group_by_name(&group)) .await .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "internal_error", "Internal error", e.to_string(), "group_by_name", ) .with_request_id(rid.clone()) })? .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "database_error", "Database error", e.to_string(), "group_by_name", ) .with_request_id(rid.clone()) })? .map(|detail| { let name = path_segment(&detail.name); Json( ctx.envelope(detail) .with_next(&format!("/groups/{name}/strains"), "The group's strains/samples") .with_next( &format!("/groups/{name}/case-attributes"), "Case-attribute names and per-strain values", ) .with_next( &format!("/groups/{name}/datasets"), "Expression (ProbeSet) datasets of the group", ) .with_next( &format!("/groups/{name}/traits"), "Published (phenotype) traits of the group (can be very large)", ), ) }) .ok_or_else(|| { ApiError::new( StatusCode::NOT_FOUND, "group_not_found", "Group not found", format!("No group matching '{not_found_name}'."), "group_by_name", ) .with_request_id(rid) .with_next("/groups") }) } #[derive(serde::Deserialize)] pub struct GroupStrainsParams { used_for_mapping: Option, } #[utoipa::path(get, path = "/groups/{group}/strains", summary = "List the strains/samples belonging to a group", params( ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id"), ("used_for_mapping" = Option, Query, description = "Only strains/samples used for mapping") ), responses( (status = 200, description = "The strains/samples belonging to the group", body = Envelope>), Unauthorized, (status = 404, description = "No matching group", body = ApiError), (status = 500, description = "Database error", body = ApiError) ))] #[gnauth(token_only)] pub async fn group_strains( ctx: Ctx, Path(group): Path, Query(params): Query, _token: AuthToken, ) -> Result>>, ApiError> { let rid = ctx.request_info(); let not_found_name = group.clone(); let used_for_mapping = params.used_for_mapping; tokio::task::spawn_blocking(move || { db::get_group_by_name(&group).and_then(|group| match group { Some(group) => db::get_group_strains(group.id, used_for_mapping).map(Some), None => Ok(None), }) }) .await .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "internal_error", "Internal error", e.to_string(), "group_strains", ) .with_request_id(rid.clone()) })? .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "database_error", "Database error", e.to_string(), "group_strains", ) .with_request_id(rid.clone()) })? .map(|strains| { let group = path_segment(¬_found_name); Json( ctx.envelope(strains) .with_next(&format!("/groups/{group}"), "The group these strains belong to") .with_next( &format!("/groups/{group}/case-attributes"), "Case-attribute names and per-strain values", ), ) }) .ok_or_else(|| { ApiError::new( StatusCode::NOT_FOUND, "group_not_found", "Group not found", format!("No group matching '{not_found_name}'."), "group_strains", ) .with_request_id(rid) .with_next("/groups") }) } /// What looking up a trait within a group found, shared by /// group_trait_values and group_trait_info so each can tell a missing /// group from a missing trait and return the right 404. `Forbidden` /// mirrors src/routes/traits.rs and src/routes/datasets.rs: the same /// published (phenotype) data is reachable there via /// /traits/{dataset}/... with a gn-auth check, so it needs one here /// too (this was a known gap -- see docs/gn-auth.md). enum GroupTraitLookup { GroupNotFound, TraitNotFound, Forbidden, Found(Authorized, T), } /// Either a database error, or a failure to reach/parse gn-auth's /// answer while checking authorization for a non-public group. enum GroupAuthError { Db(mysql::Error), Auth(String), } impl From for GroupAuthError { fn from(e: mysql::Error) -> Self { GroupAuthError::Db(e) } } /// Resolve `group`'s PublishFreeze row and run the same /// public/confidentiality/create_time-gated gn-auth check /// src/routes/traits.rs applies when the same data is reached via /// /traits/{dataset}/... When a group has published traits /// (PublishXRef rows) with no PublishFreeze row to check -- not /// expected, but PublishXRef/PublishFreeze aren't tied by a foreign /// key -- this denies rather than treating ungated data as public. fn check_group_trait_authorized( group: &db::GroupDetail, trait_name: Option<&str>, auth_server_url: &str, token: &AuthToken, ) -> Result, GroupAuthError> { let Some(pf) = db::get_publish_freeze_by_name(&group.name)? else { return Ok(None); }; auth::check( auth_server_url, token, &pf.name, trait_name, pf.public, pf.confidentiality, &pf.create_time, ) .map_err(GroupAuthError::Auth) } fn get_group_trait_values_result( group: &str, trait_id: u32, auth_server_url: &str, token: &AuthToken, ) -> Result>, GroupAuthError> { let Some(group) = db::get_group_by_name(group)? else { return Ok(GroupTraitLookup::GroupNotFound); }; let values = db::get_group_trait_values(group.id, trait_id)?; if values.is_empty() { return Ok(GroupTraitLookup::TraitNotFound); } let trait_id_string = trait_id.to_string(); let Some(auth) = check_group_trait_authorized(&group, Some(&trait_id_string), auth_server_url, token)? else { return Ok(GroupTraitLookup::Forbidden); }; Ok(GroupTraitLookup::Found(auth, values)) } #[utoipa::path(get, path = "/groups/{group}/traits/{trait_id}/values", summary = "Get one published trait's value in each of a group's strains", params( ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id"), ("trait_id" = u32, Path, description = "PublishXRef.Id of a published (phenotype) trait") ), responses( (status = 200, description = "The group's per-strain values for the trait", body = Envelope>), Unauthorized, (status = 403, description = "The trait's dataset isn't public, and the caller isn't authorized for it", body = ApiError), (status = 404, description = "No matching group, or no matching trait in that group", 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 group_trait_values( ctx: Ctx, Path((group, trait_id)): Path<(String, u32)>, token: AuthToken, ) -> Result>>, ApiError> { let rid = ctx.request_info(); let not_found_group = group.clone(); let auth_server_url = Config::load().auth_server_url.clone(); tokio::task::spawn_blocking(move || { get_group_trait_values_result(&group, trait_id, &auth_server_url, &token) }) .await .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "internal_error", "Internal error", e.to_string(), "group_trait_values", ) .with_request_id(rid.clone()) })? .map_err(|e| match e { GroupAuthError::Db(e) => ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "database_error", "Database error", e.to_string(), "group_trait_values", ) .with_request_id(rid.clone()), GroupAuthError::Auth(e) => ApiError::new( StatusCode::BAD_GATEWAY, "auth_server_error", "Could not check authorization", e, "group_trait_values", ) .with_request_id(rid.clone()), }) .and_then(|lookup| match lookup { GroupTraitLookup::Found(authorized, values) => { let _: Authorized = authorized; let group = path_segment(¬_found_group); Ok(Json(ctx.envelope(values).with_next( &format!("/groups/{group}/traits/{trait_id}"), "The trait's metadata", ))) } GroupTraitLookup::Forbidden => Err(ApiError::new( StatusCode::FORBIDDEN, "forbidden", "Not authorized", format!( "Trait {trait_id} in group '{not_found_group}' is not public, \ and you are not authorized to view it." ), "group_trait_values", ) .with_request_id(rid.clone())), GroupTraitLookup::GroupNotFound => Err(ApiError::new( StatusCode::NOT_FOUND, "group_not_found", "Group not found", format!("No group matching '{not_found_group}'."), "group_trait_values", ) .with_request_id(rid.clone()) .with_next("/groups")), GroupTraitLookup::TraitNotFound => Err(ApiError::new( StatusCode::NOT_FOUND, "trait_not_found", "Trait not found", format!("No trait {trait_id} in group '{not_found_group}'."), "group_trait_values", ) .with_request_id(rid)), }) } fn get_group_trait_info_result( group: &str, trait_id: u32, auth_server_url: &str, token: &AuthToken, ) -> Result, GroupAuthError> { let Some(group) = db::get_group_by_name(group)? else { return Ok(GroupTraitLookup::GroupNotFound); }; let Some(info) = db::get_group_trait_info(group.id, trait_id)? else { return Ok(GroupTraitLookup::TraitNotFound); }; let trait_id_string = trait_id.to_string(); let Some(auth) = check_group_trait_authorized(&group, Some(&trait_id_string), auth_server_url, token)? else { return Ok(GroupTraitLookup::Forbidden); }; Ok(GroupTraitLookup::Found(auth, info)) } #[utoipa::path(get, path = "/groups/{group}/traits/{trait_id}", summary = "Get one published trait's PublishXRef/Phenotype/Publication metadata", params( ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id"), ("trait_id" = u32, Path, description = "PublishXRef.Id of a published (phenotype) trait") ), responses( (status = 200, description = "The trait's PublishXRef/Phenotype/Publication metadata", body = Envelope), Unauthorized, (status = 403, description = "The trait's dataset isn't public, and the caller isn't authorized for it", body = ApiError), (status = 404, description = "No matching group, or no matching trait in that group", 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 group_trait_info( ctx: Ctx, Path((group, trait_id)): Path<(String, u32)>, token: AuthToken, ) -> Result>, ApiError> { let rid = ctx.request_info(); let not_found_group = group.clone(); let auth_server_url = Config::load().auth_server_url.clone(); tokio::task::spawn_blocking(move || { get_group_trait_info_result(&group, trait_id, &auth_server_url, &token) }) .await .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "internal_error", "Internal error", e.to_string(), "group_trait_info", ) .with_request_id(rid.clone()) })? .map_err(|e| match e { GroupAuthError::Db(e) => ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "database_error", "Database error", e.to_string(), "group_trait_info", ) .with_request_id(rid.clone()), GroupAuthError::Auth(e) => ApiError::new( StatusCode::BAD_GATEWAY, "auth_server_error", "Could not check authorization", e, "group_trait_info", ) .with_request_id(rid.clone()), }) .and_then(|lookup| match lookup { GroupTraitLookup::Found(_authorized, info) => { let group = path_segment(¬_found_group); let pubmed_id = info.pubmed_id; let mut envelope = ctx .envelope(info) .with_note(db::LOD_NOTE) .with_next( &format!("/groups/{group}/traits/{trait_id}/values"), "The trait's value in each strain", ) .with_next(&format!("/groups/{group}"), "The group this trait belongs to"); 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)) } GroupTraitLookup::Forbidden => Err(ApiError::new( StatusCode::FORBIDDEN, "forbidden", "Not authorized", format!( "Trait {trait_id} in group '{not_found_group}' is not public, \ and you are not authorized to view it." ), "group_trait_info", ) .with_request_id(rid.clone())), GroupTraitLookup::GroupNotFound => Err(ApiError::new( StatusCode::NOT_FOUND, "group_not_found", "Group not found", format!("No group matching '{not_found_group}'."), "group_trait_info", ) .with_request_id(rid.clone()) .with_next("/groups")), GroupTraitLookup::TraitNotFound => Err(ApiError::new( StatusCode::NOT_FOUND, "trait_not_found", "Trait not found", format!("No trait {trait_id} in group '{not_found_group}'."), "group_trait_info", ) .with_request_id(rid)), }) } /// 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, } enum GroupTraitsLookup { GroupNotFound, Forbidden, Found(Vec), } fn get_group_traits_result( group: &str, abbreviation: Option<&str>, auth_server_url: &str, token: &AuthToken, ) -> Result { let Some(group) = db::get_group_by_name(group)? else { return Ok(GroupTraitsLookup::GroupNotFound); }; let traits = match abbreviation { Some(abbreviation) => db::get_group_traits_by_abbreviation(group.id, abbreviation)?, None => db::get_group_traits(group.id)?, }; // Most groups have no published (phenotype) dataset at all -- // nothing here to protect, so don't spend a gn-auth round trip // (or deny) on an empty list. if traits.is_empty() { return Ok(GroupTraitsLookup::Found(traits)); } let Some(_auth) = check_group_trait_authorized(&group, None, auth_server_url, token)? else { return Ok(GroupTraitsLookup::Forbidden); }; Ok(GroupTraitsLookup::Found(traits)) } #[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"), GroupTraitsParams ), responses( (status = 200, description = "The published traits belonging to the group", body = Envelope>), Unauthorized, (status = 403, description = "The group's published data isn't public, and the caller isn't authorized for it", body = ApiError), (status = 404, description = "No matching group", 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 group_traits( ctx: Ctx, Path(group): Path, token: AuthToken, Query(params): Query, ) -> Result>>, ApiError> { let rid = ctx.request_info(); let not_found_name = group.clone(); let auth_server_url = Config::load().auth_server_url.clone(); tokio::task::spawn_blocking(move || { get_group_traits_result(&group, params.abbreviation.as_deref(), &auth_server_url, &token) }) .await .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "internal_error", "Internal error", e.to_string(), "group_traits", ) .with_request_id(rid.clone()) })? .map_err(|e| match e { GroupAuthError::Db(e) => ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "database_error", "Database error", e.to_string(), "group_traits", ) .with_request_id(rid.clone()), GroupAuthError::Auth(e) => ApiError::new( StatusCode::BAD_GATEWAY, "auth_server_error", "Could not check authorization", e, "group_traits", ) .with_request_id(rid.clone()), }) .and_then(|lookup| match lookup { GroupTraitsLookup::Found(traits) => { let group = path_segment(¬_found_name); Ok(Json( ctx.envelope(traits) .with_note(db::LOD_NOTE) .with_next(&format!("/groups/{group}"), "The group these traits belong to"), )) } GroupTraitsLookup::Forbidden => Err(ApiError::new( StatusCode::FORBIDDEN, "forbidden", "Not authorized", format!( "Group '{not_found_name}' published data is not public, \ and you are not authorized to view it." ), "group_traits", ) .with_request_id(rid.clone())), GroupTraitsLookup::GroupNotFound => Err(ApiError::new( StatusCode::NOT_FOUND, "group_not_found", "Group not found", format!("No group matching '{not_found_name}'."), "group_traits", ) .with_request_id(rid) .with_next("/groups")), }) } #[utoipa::path(get, path = "/groups/{group}/case-attributes", summary = "Get a group's case attributes: defined attribute names and every strain's values", params( ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id") ), responses( (status = 200, description = "The group's case-attribute names and per-strain values", body = Envelope), Unauthorized, (status = 404, description = "No matching group", body = ApiError), (status = 500, description = "Database error", body = ApiError) ))] #[gnauth(token_only)] pub async fn group_case_attributes( ctx: Ctx, Path(group): Path, _token: AuthToken, ) -> Result>, ApiError> { let rid = ctx.request_info(); 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_case_attributes(group.id).map(Some), None => Ok(None), }) }) .await .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "internal_error", "Internal error", e.to_string(), "group_case_attributes", ) .with_request_id(rid.clone()) })? .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "database_error", "Database error", e.to_string(), "group_case_attributes", ) .with_request_id(rid.clone()) })? .map(|case_attributes| { Json(ctx.envelope(case_attributes).with_next( &format!("/groups/{}/strains", path_segment(¬_found_name)), "The group's strains/samples", )) }) .ok_or_else(|| { ApiError::new( StatusCode::NOT_FOUND, "group_not_found", "Group not found", format!("No group matching '{not_found_name}'."), "group_case_attributes", ) .with_request_id(rid) .with_next("/groups") }) } #[utoipa::path(get, path = "/groups/{group}/datasets", summary = "List the expression (ProbeSet) datasets belonging to a group", params( ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id") ), responses( (status = 200, description = "The expression (ProbeSet) datasets belonging to the group", body = Envelope>), Unauthorized, (status = 404, description = "No matching group", body = ApiError), (status = 500, description = "Database error", body = ApiError) ))] #[gnauth(token_only)] pub async fn group_datasets( ctx: Ctx, Path(group): Path, _token: AuthToken, ) -> Result>>, ApiError> { let rid = ctx.request_info(); 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_datasets(group.id).map(Some), None => Ok(None), }) }) .await .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "internal_error", "Internal error", e.to_string(), "group_datasets", ) .with_request_id(rid.clone()) })? .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "database_error", "Database error", e.to_string(), "group_datasets", ) .with_request_id(rid.clone()) })? .map(|datasets| { Json(ctx.envelope(datasets).with_next( &format!("/groups/{}", path_segment(¬_found_name)), "The group these datasets belong to", )) }) .ok_or_else(|| { ApiError::new( StatusCode::NOT_FOUND, "group_not_found", "Group not found", format!("No group matching '{not_found_name}'."), "group_datasets", ) .with_request_id(rid) .with_next("/groups") }) }