//! Publications domain endpoint: which traits a paper reports. use axum::Json; use axum::extract::Path; use axum::http::StatusCode; use std::collections::HashMap; use crate::auth::{AuthToken, is_authorised}; use crate::config::Config; use crate::db; use crate::error::{ApiError, Unauthorized}; use crate::response::{Ctx, Envelope, path_segment}; enum PublicationTraits { NotFound, /// The traits the caller may view, and how many were left out. Found(Vec, usize), } enum LookupError { Db(db::DbError), Auth(String), } impl From for LookupError { fn from(e: db::DbError) -> 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 { let Some(traits) = db::get_publication_traits(pubmed_id)? else { return Ok(PublicationTraits::NotFound); }; let mut readable: HashMap = HashMap::new(); let mut visible = Vec::new(); let mut omitted = 0; for info in traits { let Some(dataset) = info.dataset.clone() else { omitted += 1; 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); } else { omitted += 1; } } Ok(PublicationTraits::Found(visible, omitted)) } #[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 = Envelope>), 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( ctx: Ctx, Path(pubmed_id): Path, token: AuthToken, ) -> Result>>, ApiError> { let rid = ctx.request_info(); 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::from_db(e, "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, omitted) => { let first = traits .first() .and_then(|t| Some((t.dataset.clone()?, t.id))); let mut envelope = ctx.envelope(traits).with_note(db::LOD_NOTE); if omitted > 0 { envelope = envelope.partial(&format!( "{omitted} trait(s) were left out: their datasets are not public \ and you are not authorized to view them." )); } if let Some((dataset, id)) = first { envelope = envelope.with_next( &format!("/traits/{}/{id}", path_segment(&dataset)), "Metadata of the first trait", ); } Ok(Json(envelope.with_links(crate::suggest::root_links()))) } 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)), }) }