//! Expression (ProbeSet) dataset domain endpoints: read-only access to //! the ProbeSetFreeze/ProbeSetXRef/ProbeSet tables. use axum::Json; use axum::extract::Path; use axum::http::StatusCode; 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; #[utoipa::path(get, path = "/datasets/{dataset}", summary = "Get one expression dataset's full record by name or numeric id", params( ("dataset" = String, Path, description = "Dataset Name, Name2, FullName, ShortName or numeric Id") ), responses( (status = 200, description = "The matching row of the ProbeSetFreeze table", body = Envelope), Unauthorized, (status = 404, description = "No matching dataset", body = ApiError), (status = 500, description = "Database error", body = ApiError) ))] #[gnauth(token_only)] pub async fn dataset_by_name( ctx: Ctx, Path(dataset): Path, _token: AuthToken, ) -> Result>, ApiError> { let rid = ctx.request_info(); let not_found_name = dataset.clone(); tokio::task::spawn_blocking(move || db::get_dataset_by_name(&dataset)) .await .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "internal_error", "Internal error", e.to_string(), "dataset_by_name", ) .with_request_id(rid.clone()) })? .map_err(|e| ApiError::from_db(e, "dataset_by_name").with_request_id(rid.clone()))? .map(|dataset| { Json( ctx.envelope(dataset) .with_next( &format!("/datasets/{}/probesets", path_segment(¬_found_name)), "The expression traits (probesets) of this dataset (can be very \ large); append / to one of them for its metadata", ) .with_links(crate::suggest::root_links()), ) }) .ok_or_else(|| { ApiError::new( StatusCode::NOT_FOUND, "dataset_not_found", "Dataset not found", format!("No dataset matching '{not_found_name}'."), "dataset_by_name", ) .with_request_id(rid) }) } /// What looking up and authorizing a dataset's probeset listing found. /// Unlike [`DatasetProbesetLookup`], there's no single probeset to miss /// -- a dataset with zero probesets is just an empty `Found(vec![])` -- /// but there is still a dataset-level `Forbidden` outcome. enum DatasetProbesetsLookup { DatasetNotFound, Forbidden, Found(Authorized, Vec), } fn get_dataset_probesets_result( dataset: &str, auth_server_url: &str, token: &AuthToken, ) -> Result { let dataset = match db::get_dataset_by_name(dataset)? { None => return Ok(DatasetProbesetsLookup::DatasetNotFound), Some(dataset) => dataset, }; let Some(auth) = auth::check( auth_server_url, token, &dataset.name, None, dataset.public, dataset.confidentiality, &dataset.create_time, ) .map_err(DatasetAuthError::Auth)? else { return Ok(DatasetProbesetsLookup::Forbidden); }; Ok(DatasetProbesetsLookup::Found( auth, db::get_dataset_probesets(dataset.id)?, )) } #[utoipa::path(get, path = "/datasets/{dataset}/probesets", summary = "List the expression (ProbeSet) traits belonging to a dataset", params( ("dataset" = String, Path, description = "Dataset Name, Name2, FullName, ShortName or numeric Id") ), responses( (status = 200, description = "The probesets' ProbeSetXRef/ProbeSet metadata", 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 dataset_probesets( 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_dataset_probesets_result(&dataset, &auth_server_url, &token) }) .await .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "internal_error", "Internal error", e.to_string(), "dataset_probesets", ) .with_request_id(rid.clone()) })? .map_err(|e| match e { DatasetAuthError::Db(e) => { ApiError::from_db(e, "dataset_probesets").with_request_id(rid.clone()) } DatasetAuthError::Auth(e) => ApiError::new( StatusCode::BAD_GATEWAY, "auth_server_error", "Could not check authorization", e, "dataset_probesets", ) .with_request_id(rid.clone()), }) .and_then(|lookup| match lookup { DatasetProbesetsLookup::Found(_authorized, probesets) => Ok(Json( ctx.envelope(probesets) .with_note(db::LOD_NOTE) .with_next( &format!("/datasets/{}", path_segment(¬_found_name)), "The dataset these probesets belong to", ) .with_next( &format!("/datasets/{}/probesets/{{probeset}}/values", path_segment(¬_found_name)), "One probeset's value per strain, with the mapping suggestions", ) .with_links(crate::suggest::root_links()), )), DatasetProbesetsLookup::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." ), "dataset_probesets", ) .with_request_id(rid.clone())), DatasetProbesetsLookup::DatasetNotFound => Err(ApiError::new( StatusCode::NOT_FOUND, "dataset_not_found", "Dataset not found", format!("No dataset matching '{not_found_name}'."), "dataset_probesets", ) .with_request_id(rid)), }) } /// What looking up and authorizing a probeset trait within a dataset /// found, the expression-dataset equivalent of GroupTraitLookup above. /// `Forbidden` covers "the dataset isn't public and the caller isn't /// authorized for it" -- both `dataset_probeset_info` and /// `dataset_probeset_values` gate on gn-auth. enum DatasetProbesetLookup { DatasetNotFound, ProbesetNotFound, 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 dataset. enum DatasetAuthError { Db(db::DbError), Auth(String), } impl From for DatasetAuthError { fn from(e: db::DbError) -> Self { DatasetAuthError::Db(e) } } fn get_dataset_probeset_info_result( dataset: &str, probeset: &str, auth_server_url: &str, token: &AuthToken, ) -> Result, DatasetAuthError> { let dataset = match db::get_dataset_by_name(dataset)? { None => return Ok(DatasetProbesetLookup::DatasetNotFound), Some(dataset) => dataset, }; let info = match db::get_dataset_probeset_info(dataset.id, probeset)? { None => return Ok(DatasetProbesetLookup::ProbesetNotFound), Some(info) => info, }; let Some(auth) = auth::check( auth_server_url, token, &dataset.name, Some(&info.name), dataset.public, dataset.confidentiality, &dataset.create_time, ) .map_err(DatasetAuthError::Auth)? else { return Ok(DatasetProbesetLookup::Forbidden); }; Ok(DatasetProbesetLookup::Found(auth, info)) } #[utoipa::path(get, path = "/datasets/{dataset}/probesets/{probeset}", summary = "Get one expression trait's ProbeSetXRef/ProbeSet metadata", params( ("dataset" = String, Path, description = "Dataset Name, Name2, FullName, ShortName or numeric Id"), ("probeset" = String, Path, description = "ProbeSet.Name within the dataset") ), responses( (status = 200, description = "The probeset's ProbeSetXRef/ProbeSet metadata", 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 probeset 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 dataset_probeset_info( ctx: Ctx, Path((dataset, probeset)): Path<(String, String)>, token: AuthToken, ) -> Result>, ApiError> { let rid = ctx.request_info(); let not_found_dataset = dataset.clone(); let not_found_probeset = probeset.clone(); let auth_server_url = Config::load().auth_server_url.clone(); tokio::task::spawn_blocking(move || { get_dataset_probeset_info_result(&dataset, &probeset, &auth_server_url, &token) }) .await .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "internal_error", "Internal error", e.to_string(), "dataset_probeset_info", ) .with_request_id(rid.clone()) })? .map_err(|e| match e { DatasetAuthError::Db(e) => { ApiError::from_db(e, "dataset_probeset_info").with_request_id(rid.clone()) } DatasetAuthError::Auth(e) => ApiError::new( StatusCode::BAD_GATEWAY, "auth_server_error", "Could not check authorization", e, "dataset_probeset_info", ) .with_request_id(rid.clone()), }) .and_then(|lookup| match lookup { DatasetProbesetLookup::Found(_authorized, info) => { let dataset = path_segment(¬_found_dataset); let probeset = path_segment(¬_found_probeset); Ok(Json( ctx.envelope(info) .with_note(db::LOD_NOTE) .with_next( &format!("/datasets/{dataset}/probesets/{probeset}/values"), "The probeset's value in each strain", ) .with_next( &format!("/datasets/{dataset}"), "The dataset this probeset belongs to", ) .with_next( &format!("/publications/{{pubmed_id}}/traits"), "Every trait this probeset's publication reports", ) .with_links(crate::suggest::root_links()), )) } DatasetProbesetLookup::Forbidden => Err(ApiError::new( StatusCode::FORBIDDEN, "forbidden", "Not authorized", format!( "'{not_found_probeset}' in dataset '{not_found_dataset}' is not public, \ and you are not authorized to view it." ), "dataset_probeset_info", ) .with_request_id(rid.clone())), DatasetProbesetLookup::DatasetNotFound => Err(ApiError::new( StatusCode::NOT_FOUND, "dataset_not_found", "Dataset not found", format!("No dataset matching '{not_found_dataset}'."), "dataset_probeset_info", ) .with_request_id(rid.clone())), DatasetProbesetLookup::ProbesetNotFound => Err(ApiError::new( StatusCode::NOT_FOUND, "probeset_not_found", "Probeset not found", format!("No probeset '{not_found_probeset}' in dataset '{not_found_dataset}'."), "dataset_probeset_info", ) .with_request_id(rid)), }) } fn get_dataset_probeset_values_result( dataset: &str, probeset: &str, auth_server_url: &str, token: &AuthToken, ) -> Result>, DatasetAuthError> { let dataset = match db::get_dataset_by_name(dataset)? { None => return Ok(DatasetProbesetLookup::DatasetNotFound), Some(dataset) => dataset, }; let values = db::get_dataset_probeset_values(dataset.id, probeset)?; if values.is_empty() { return Ok(DatasetProbesetLookup::ProbesetNotFound); } let Some(auth) = auth::check( auth_server_url, token, &dataset.name, Some(probeset), dataset.public, dataset.confidentiality, &dataset.create_time, ) .map_err(DatasetAuthError::Auth)? else { return Ok(DatasetProbesetLookup::Forbidden); }; Ok(DatasetProbesetLookup::Found(auth, values)) } #[utoipa::path(get, path = "/datasets/{dataset}/probesets/{probeset}/values", summary = "Get one expression trait's value in each strain in the dataset", params( ("dataset" = String, Path, description = "Dataset Name, Name2, FullName, ShortName or numeric Id"), ("probeset" = String, Path, description = "ProbeSet.Name within the dataset") ), responses( (status = 200, description = "The dataset's per-strain values for the probeset", 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 probeset 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 dataset_probeset_values( ctx: Ctx, Path((dataset, probeset)): Path<(String, String)>, token: AuthToken, ) -> Result>>, ApiError> { let rid = ctx.request_info(); let not_found_dataset = dataset.clone(); let not_found_probeset = probeset.clone(); let auth_server_url = Config::load().auth_server_url.clone(); tokio::task::spawn_blocking(move || { get_dataset_probeset_values_result(&dataset, &probeset, &auth_server_url, &token) }) .await .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "internal_error", "Internal error", e.to_string(), "dataset_probeset_values", ) .with_request_id(rid.clone()) })? .map_err(|e| match e { DatasetAuthError::Db(e) => { ApiError::from_db(e, "dataset_probeset_values").with_request_id(rid.clone()) } DatasetAuthError::Auth(e) => ApiError::new( StatusCode::BAD_GATEWAY, "auth_server_error", "Could not check authorization", e, "dataset_probeset_values", ) .with_request_id(rid.clone()), }) .and_then(|lookup| match lookup { DatasetProbesetLookup::Found(authorized, values) => { let _: Authorized = authorized; let actions = suggest::mapping_actions_for( &values, &format!("{}::{}", not_found_dataset, not_found_probeset), ); Ok(Json( ctx.envelope(values) .with_actions(actions) .with_next( &format!( "/datasets/{}/probesets/{}", path_segment(¬_found_dataset), path_segment(¬_found_probeset) ), "The probeset's metadata", ) .with_next( &format!("/datasets/{}/probesets", path_segment(¬_found_dataset)), "The other probesets of this dataset", ) .with_links(crate::suggest::root_links()), )) } DatasetProbesetLookup::Forbidden => Err(ApiError::new( StatusCode::FORBIDDEN, "forbidden", "Not authorized", format!( "'{not_found_probeset}' in dataset '{not_found_dataset}' is not public, \ and you are not authorized to view it." ), "dataset_probeset_values", ) .with_request_id(rid.clone())), DatasetProbesetLookup::DatasetNotFound => Err(ApiError::new( StatusCode::NOT_FOUND, "dataset_not_found", "Dataset not found", format!("No dataset matching '{not_found_dataset}'."), "dataset_probeset_values", ) .with_request_id(rid.clone())), DatasetProbesetLookup::ProbesetNotFound => Err(ApiError::new( StatusCode::NOT_FOUND, "probeset_not_found", "Probeset not found", format!("No probeset '{not_found_probeset}' in dataset '{not_found_dataset}'."), "dataset_probeset_values", ) .with_request_id(rid)), }) }