diff options
| author | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-10-03 16:14:49 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-10-04 06:31:16 +0000 |
| commit | e7191463db66fcc3c2618ccdf004e798e1d3ac6a (patch) | |
| tree | 2e76f71985ee8b6a49c49c1c17606fffbceb056f | |
| parent | 0980c21ff71bf4c8fa73d3193460f7b7f69d9f6b (diff) | |
| download | genenetwork4-e7191463db66fcc3c2618ccdf004e798e1d3ac6a.tar.gz | |
Add ProbeSetXRef endpoints: datasets, probesets, probeset values.
The expression (ProbeSet) counterpart to the PublishXRef endpoints:
ProbeSetXRef has no single Id column of its own (its primary key is
DataId; the natural key is the pair (ProbeSetFreezeId, ProbeSetId)),
so a trait here is addressed by dataset name plus ProbeSet.Name
instead of a single numeric trait id.
* src/db.rs (Dataset): New struct, one ProbeSetFreeze row.
(get_group_datasets): New function. Joins ProbeSetFreeze and
ProbeFreeze by group Id, matching GeneNetwork2's
wqflask.api.router.get_datasets_for_group.
(get_dataset_by_name): New function. Matches Name, Name2, FullName,
ShortName or numeric Id, matching
wqflask.api.router.get_dataset_info's ProbeSet-branch matching logic.
A dataset name is globally unique on its own, unlike a group's
traits, so this isn't scoped by group.
(ProbeSetInfo): New struct, a probe's ProbeSetXRef mapping stats plus
its ProbeSet gene annotation.
(get_dataset_probeset_info): New function, matching
wqflask.api.router.get_trait_info's ProbeSet branch.
(ProbeSetValue): New struct.
(get_dataset_probeset_values): New function, matching
wqflask.api.router.trait_sample_data's ProbeSet branch.
* src/lib.rs (DatasetProbesetLookup): New enum, the expression-dataset
equivalent of GroupTraitLookup -- distinguishes a missing dataset from
a missing probeset in an existing dataset.
(group_datasets): New handler for GET /groups/{group}/datasets.
(dataset_by_name): New handler for GET /datasets/{dataset}.
(get_dataset_probeset_info_result, dataset_probeset_info): New
function and handler for GET /datasets/{dataset}/probesets/{probeset}.
(get_dataset_probeset_values_result, dataset_probeset_values): New
function and handler for
GET /datasets/{dataset}/probesets/{probeset}/values.
(app): Register all four.
* tests/group_datasets.rs, tests/dataset_by_name.rs,
tests/dataset_probeset_info.rs, tests/dataset_probeset_values.rs,
test/python/test_group_datasets.py, test/python/test_dataset_by_name.py,
test/python/test_dataset_probeset_info.py,
test/python/test_dataset_probeset_values.py: New files. Br_U_0803_M
(dataset) / 100001_at (probeset, gene symbol Cd3g) in BXD are real rows
used as fixtures.
* tests/openapi.rs, test/python/test_openapi.py: Check the four new
paths are in the generated spec.
* README.md: Document the four new endpoints and list the new test
files.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XDDpXvZBQat9uSgDeEMJ8d
| -rw-r--r-- | README.md | 74 | ||||
| -rw-r--r-- | src/db.rs | 184 | ||||
| -rw-r--r-- | src/lib.rs | 4 | ||||
| -rw-r--r-- | src/routes/datasets.rs | 213 | ||||
| -rw-r--r-- | src/routes/groups.rs | 55 | ||||
| -rw-r--r-- | src/routes/mod.rs | 1 | ||||
| -rw-r--r-- | test/python/test_dataset_by_name.py | 61 | ||||
| -rw-r--r-- | test/python/test_dataset_probeset_info.py | 79 | ||||
| -rw-r--r-- | test/python/test_dataset_probeset_values.py | 79 | ||||
| -rw-r--r-- | test/python/test_group_datasets.py | 62 | ||||
| -rw-r--r-- | test/python/test_openapi.py | 4 | ||||
| -rw-r--r-- | tests/dataset_by_name.rs | 58 | ||||
| -rw-r--r-- | tests/dataset_probeset_info.rs | 82 | ||||
| -rw-r--r-- | tests/dataset_probeset_values.rs | 83 | ||||
| -rw-r--r-- | tests/group_datasets.rs | 56 | ||||
| -rw-r--r-- | tests/openapi.rs | 4 |
16 files changed, 1095 insertions, 4 deletions
diff --git a/README.md b/README.md index 3e45cfa..5ea0b7d 100644 --- a/README.md +++ b/README.md @@ -157,6 +157,68 @@ A Rust/Axum-based API server for GeneNetwork. Needs `SQL_URI`, same as `/species` above. +- `GET /groups/{group}/datasets` - returns the expression (ProbeSet) + datasets belonging to a group, matching GeneNetwork2's + `wqflask.api.router.get_datasets_for_group`. 404 if no group + matches. Needs `SQL_URI`, same as `/species` above. + + ```json + [ + {"id": 1, "probe_freeze_id": 10, "name": "Br_U_0803_M", + "name2": "BXDMicroArray_ProbeSet_August03", + "full_name": "Brain U74Av2 08/03 MAS5", + "short_name": "Brain U74Av2 08/03 MAS5", "create_time": "2003-08-01", + "public": 0, "confidentiality": 0, "data_scale": "log2"}, + ... + ] + ``` + +- `GET /datasets/{dataset}` - returns every column of the matching row + of the `ProbeSetFreeze` table, matched against `Name`, `Name2`, + `FullName`, `ShortName` or numeric `Id` (matching GeneNetwork2's + `wqflask.api.router.get_dataset_info`'s matching logic for its + ProbeSet branch). 404 if no dataset matches. A dataset name is + globally unique on its own (unlike a group's traits), so this + endpoint isn't scoped under `/groups/{group}`. Needs `SQL_URI`, same + as `/species` above. + +- `GET /datasets/{dataset}/probesets/{probeset}` - returns one + expression (ProbeSet) trait's `ProbeSetXRef` mapping stats plus its + `ProbeSet` gene annotation, matching GeneNetwork2's + `wqflask.api.router.get_trait_info`'s ProbeSet branch. `ProbeSetXRef` + has no single Id column of its own (its primary key is `DataId`; the + natural key is the pair `(ProbeSetFreezeId, ProbeSetId)`), so a trait + here is identified by dataset name plus `ProbeSet.Name` rather than a + single numeric id, unlike `/groups/{group}/traits/{trait_id}`. 404 if + no dataset matches, or if the dataset has no such probeset. + + ```json + {"probeset_id": 1, "name": "100001_at", "symbol": "Cd3g", + "description": "...", "chr": "9", "mb": 44.96, + "mean": 5.487942857142857, "locus": "rs13480619", + "lrs": 12.590069931048, "p_value": 0.269, + "additive": -0.28515625} + ``` + + Needs `SQL_URI`, same as `/species` above. + +- `GET /datasets/{dataset}/probesets/{probeset}/values` - returns one + expression trait's value in each strain in the dataset, matching + GeneNetwork2's `wqflask.api.router.trait_sample_data`'s ProbeSet + branch, addressed the same way as + `/datasets/{dataset}/probesets/{probeset}`. 404 if no dataset + matches, or if the dataset has no such probeset. + + ```json + [ + {"name": "B6D2F1", "value": 5.742}, + {"name": "BXD1", "value": 6.414}, + ... + ] + ``` + + Needs `SQL_URI`, same as `/species` above. + - `GET /openapi.json` - returns an OpenAPI 3.1 document describing the endpoints above; see [OpenAPI](#openapi) below. @@ -323,10 +385,14 @@ Both suites also run automatically as part of `guix build -f guix.scm` `test_species_by_name.py`, `groups.rs`/`test_groups.py`, `group_by_name.rs`/`test_group_by_name.py`, `group_strains.rs`/ `test_group_strains.py`, `group_trait_values.rs`/ -`test_group_trait_values.py` and `group_trait_info.rs`/ -`test_group_trait_info.py` need a live MariaDB on `127.0.0.1:3306` -(see `SQL_URI` above); unlike the other tests they check for that -connection first and skip with a message rather than +`test_group_trait_values.py`, `group_trait_info.rs`/ +`test_group_trait_info.py`, `group_datasets.rs`/ +`test_group_datasets.py`, `dataset_by_name.rs`/ +`test_dataset_by_name.py`, `dataset_probeset_info.rs`/ +`test_dataset_probeset_info.py` and `dataset_probeset_values.rs`/ +`test_dataset_probeset_values.py` need a live MariaDB on +`127.0.0.1:3306` (see `SQL_URI` above); unlike the other tests they +check for that connection first and skip with a message rather than fail when none is reachable, since the Guix build sandbox has no network/database access. diff --git a/src/db.rs b/src/db.rs index 64a2c4c..223bcde 100644 --- a/src/db.rs +++ b/src/db.rs @@ -365,3 +365,187 @@ pub fn get_group_trait_info(group_id: u16, trait_id: u32) -> Result<Option<Trait mysql::params! { "group_id" => group_id, "trait_id" => trait_id }, ) } + +/// One expression (ProbeSet) dataset: a ProbeSetFreeze row, matching +/// the shape of GeneNetwork2's GET /api/v_pre1/datasets/<group_name> +/// response (field names there: Id, ProbeFreezeId, AvgID, +/// Short_Abbreviation, Long_Abbreviation, FullName, ShortName, +/// CreateTime, public, confidentiality, DataScale -- renamed here the +/// same way GroupDetail renames away from "inbred_set": Name/Name2 are +/// clearer than GN2's legacy "Short_Abbreviation"/"Long_Abbreviation"). +#[derive(Serialize, utoipa::ToSchema)] +pub struct Dataset { + pub id: u16, + pub probe_freeze_id: u16, + pub name: String, + pub name2: Option<String>, + pub full_name: String, + pub short_name: String, + pub create_time: String, + pub public: u8, + pub confidentiality: u8, + pub data_scale: String, +} + +/// Fetch the expression datasets belonging to a group. Mirrors +/// GeneNetwork2's wqflask.api.router.get_datasets_for_group (without +/// its species-scoped variant, which this API doesn't need: a group +/// name alone already picks one species). +pub fn get_group_datasets(group_id: u16) -> Result<Vec<Dataset>, mysql::Error> { + let pool = pool()?; + let mut conn = pool.get_conn()?; + conn.exec_map( + "SELECT ProbeSetFreeze.Id, ProbeSetFreeze.ProbeFreezeId, ProbeSetFreeze.Name, \ + ProbeSetFreeze.Name2, ProbeSetFreeze.FullName, ProbeSetFreeze.ShortName, \ + CAST(ProbeSetFreeze.CreateTime AS CHAR), ProbeSetFreeze.public, \ + ProbeSetFreeze.confidentiality, ProbeSetFreeze.DataScale \ + FROM ProbeSetFreeze \ + JOIN ProbeFreeze ON ProbeFreeze.ProbeFreezeId = ProbeSetFreeze.ProbeFreezeId \ + WHERE ProbeFreeze.InbredSetId = :group_id \ + ORDER BY ProbeSetFreeze.Name", + mysql::params! { "group_id" => group_id }, + |(id, probe_freeze_id, name, name2, full_name, short_name, create_time, public, confidentiality, data_scale)| { + Dataset { + id, + probe_freeze_id, + name, + name2, + full_name, + short_name, + create_time, + public, + confidentiality, + data_scale, + } + }, + ) +} + +/// Fetch one dataset by Name, Name2, FullName, ShortName or numeric +/// Id, matching GeneNetwork2's wqflask.api.router.get_dataset_info's +/// matching logic for its ProbeSet (mRNA expression) branch. +pub fn get_dataset_by_name(name: &str) -> Result<Option<Dataset>, mysql::Error> { + let pool = pool()?; + let mut conn = pool.get_conn()?; + conn.exec_first( + "SELECT Id, ProbeFreezeId, Name, Name2, FullName, ShortName, \ + CAST(CreateTime AS CHAR), public, confidentiality, DataScale \ + FROM ProbeSetFreeze \ + WHERE Name = :name OR Name2 = :name OR FullName = :name \ + OR ShortName = :name OR CAST(Id AS CHAR) = :name", + mysql::params! { "name" => name }, + ) + .map(|row: Option<(u16, u16, String, Option<String>, String, String, String, u8, u8, String)>| { + row.map( + |(id, probe_freeze_id, name, name2, full_name, short_name, create_time, public, confidentiality, data_scale)| { + Dataset { + id, + probe_freeze_id, + name, + name2, + full_name, + short_name, + create_time, + public, + confidentiality, + data_scale, + } + }, + ) + }) +} + +/// One expression (ProbeSet) trait's metadata: its ProbeSetXRef +/// mapping stats plus its ProbeSet gene annotation. The expression +/// equivalent of TraitInfo (for Publish/phenotype traits) above, but +/// addressed differently: ProbeSetXRef has no single Id column of its +/// own (its primary key is DataId; the natural key is the pair +/// (ProbeSetFreezeId, ProbeSetId)), so a trait here is identified by +/// dataset name plus ProbeSet.Name rather than a single numeric id. +#[derive(Serialize, utoipa::ToSchema)] +pub struct ProbeSetInfo { + pub probeset_id: u32, + pub name: String, + pub symbol: Option<String>, + pub description: Option<String>, + pub chr: Option<String>, + pub mb: Option<f64>, + pub mean: Option<f64>, + pub locus: Option<String>, + pub lrs: Option<f64>, + pub p_value: Option<f64>, + pub additive: Option<f64>, +} + +/// Fetch one expression trait's metadata (see ProbeSetInfo) within a +/// dataset, matching GeneNetwork2's wqflask.api.router.get_trait_info's +/// ProbeSet branch (which additionally takes a Mb/Chr pair from +/// ProbeSet, as done here, though GN2 doesn't join ProbeSetXRef's +/// pValue). +pub fn get_dataset_probeset_info( + dataset_id: u16, + probeset_name: &str, +) -> Result<Option<ProbeSetInfo>, mysql::Error> { + let pool = pool()?; + let mut conn = pool.get_conn()?; + conn.exec_first( + "SELECT ProbeSet.Id, ProbeSet.Name, ProbeSet.Symbol, ProbeSet.description, \ + ProbeSet.Chr, ProbeSet.Mb, ProbeSetXRef.mean, ProbeSetXRef.Locus, \ + ProbeSetXRef.LRS, ProbeSetXRef.pValue, ProbeSetXRef.additive \ + FROM ProbeSet \ + JOIN ProbeSetXRef ON ProbeSetXRef.ProbeSetId = ProbeSet.Id \ + WHERE ProbeSetXRef.ProbeSetFreezeId = :dataset_id AND ProbeSet.Name = :probeset_name", + mysql::params! { "dataset_id" => dataset_id, "probeset_name" => probeset_name }, + ) + .map( + |row: Option<(u32, String, Option<String>, Option<String>, Option<String>, Option<f64>, Option<f64>, Option<String>, Option<f64>, Option<f64>, Option<f64>)>| { + row.map( + |(probeset_id, name, symbol, description, chr, mb, mean, locus, lrs, p_value, additive)| { + ProbeSetInfo { + probeset_id, + name, + symbol, + description, + chr, + mb, + mean, + locus, + lrs, + p_value, + additive, + } + }, + ) + }, + ) +} + +/// One strain's value for an expression (ProbeSet) trait, matching +/// GeneNetwork2's wqflask.api.router.trait_sample_data (the ProbeSet +/// branch, trimmed to just name and value); the expression equivalent +/// of TraitValue (for Publish/phenotype traits) above. +#[derive(Serialize, utoipa::ToSchema)] +pub struct ProbeSetValue { + pub name: String, + pub value: Option<f64>, +} + +/// Fetch the per-strain values of one expression trait within a +/// dataset, addressed the same way as get_dataset_probeset_info. +pub fn get_dataset_probeset_values( + dataset_id: u16, + probeset_name: &str, +) -> Result<Vec<ProbeSetValue>, mysql::Error> { + let pool = pool()?; + let mut conn = pool.get_conn()?; + conn.exec_map( + "SELECT Strain.Name, ProbeSetData.value \ + FROM ProbeSetData, Strain, ProbeSetXRef, ProbeSet \ + WHERE ProbeSetXRef.ProbeSetFreezeId = :dataset_id AND ProbeSet.Name = :probeset_name \ + AND ProbeSetXRef.ProbeSetId = ProbeSet.Id \ + AND ProbeSetXRef.DataId = ProbeSetData.Id AND ProbeSetData.StrainId = Strain.Id \ + ORDER BY Strain.Name", + mysql::params! { "dataset_id" => dataset_id, "probeset_name" => probeset_name }, + |(name, value)| ProbeSetValue { name, value }, + ) +} diff --git a/src/lib.rs b/src/lib.rs index 93485a8..6b1d3a6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -36,6 +36,10 @@ pub fn app() -> Router { .routes(routes!(routes::groups::group_strains)) .routes(routes!(routes::groups::group_trait_values)) .routes(routes!(routes::groups::group_trait_info)) + .routes(routes!(routes::groups::group_datasets)) + .routes(routes!(routes::datasets::dataset_by_name)) + .routes(routes!(routes::datasets::dataset_probeset_info)) + .routes(routes!(routes::datasets::dataset_probeset_values)) .routes(routes!(routes::correlation::correlation)) .split_for_parts(); router diff --git a/src/routes/datasets.rs b/src/routes/datasets.rs new file mode 100644 index 0000000..f1b5671 --- /dev/null +++ b/src/routes/datasets.rs @@ -0,0 +1,213 @@ +//! Expression (ProbeSet) dataset domain endpoints: read-only access to +//! the ProbeSetFreeze/ProbeSetXRef/ProbeSet tables. + +use axum::Json; +use axum::extract::{Extension, Path}; +use axum::http::StatusCode; +use tower_http::request_id::RequestId; + +use crate::db; +use crate::error::ApiError; +use crate::request_id_string; + +#[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 = db::Dataset), + (status = 404, description = "No matching dataset", body = ApiError), + (status = 500, description = "Database error", body = ApiError) +))] +pub async fn dataset_by_name( + Extension(request_id): Extension<RequestId>, + Path(dataset): Path<String>, +) -> Result<Json<db::Dataset>, ApiError> { + let rid = request_id_string(&request_id); + 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::new( + StatusCode::INTERNAL_SERVER_ERROR, + "database_error", + "Database error", + e.to_string(), + "dataset_by_name", + ) + .with_request_id(rid.clone()) + })? + .map(Json) + .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 a probeset trait within a dataset found, the +/// expression-dataset equivalent of GroupTraitLookup above. +enum DatasetProbesetLookup<T> { + DatasetNotFound, + ProbesetNotFound, + Found(T), +} + +fn get_dataset_probeset_info_result( + dataset: &str, + probeset: &str, +) -> Result<DatasetProbesetLookup<db::ProbeSetInfo>, mysql::Error> { + match db::get_dataset_by_name(dataset)? { + None => Ok(DatasetProbesetLookup::DatasetNotFound), + Some(dataset) => match db::get_dataset_probeset_info(dataset.id, probeset)? { + None => Ok(DatasetProbesetLookup::ProbesetNotFound), + Some(info) => Ok(DatasetProbesetLookup::Found(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 = db::ProbeSetInfo), + (status = 404, description = "No matching dataset, or no matching probeset in that dataset", body = ApiError), + (status = 500, description = "Database error", body = ApiError) +))] +pub async fn dataset_probeset_info( + Extension(request_id): Extension<RequestId>, + Path((dataset, probeset)): Path<(String, String)>, +) -> Result<Json<db::ProbeSetInfo>, ApiError> { + let rid = request_id_string(&request_id); + let not_found_dataset = dataset.clone(); + let not_found_probeset = probeset.clone(); + tokio::task::spawn_blocking(move || get_dataset_probeset_info_result(&dataset, &probeset)) + .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| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "database_error", + "Database error", + e.to_string(), + "dataset_probeset_info", + ) + .with_request_id(rid.clone()) + }) + .and_then(|lookup| match lookup { + DatasetProbesetLookup::Found(info) => Ok(Json(info)), + 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, +) -> Result<DatasetProbesetLookup<Vec<db::ProbeSetValue>>, mysql::Error> { + match db::get_dataset_by_name(dataset)? { + None => Ok(DatasetProbesetLookup::DatasetNotFound), + Some(dataset) => { + let values = db::get_dataset_probeset_values(dataset.id, probeset)?; + if values.is_empty() { + Ok(DatasetProbesetLookup::ProbesetNotFound) + } else { + Ok(DatasetProbesetLookup::Found(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 = Vec<db::ProbeSetValue>), + (status = 404, description = "No matching dataset, or no matching probeset in that dataset", body = ApiError), + (status = 500, description = "Database error", body = ApiError) +))] +pub async fn dataset_probeset_values( + Extension(request_id): Extension<RequestId>, + Path((dataset, probeset)): Path<(String, String)>, +) -> Result<Json<Vec<db::ProbeSetValue>>, ApiError> { + let rid = request_id_string(&request_id); + let not_found_dataset = dataset.clone(); + let not_found_probeset = probeset.clone(); + tokio::task::spawn_blocking(move || get_dataset_probeset_values_result(&dataset, &probeset)) + .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| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "database_error", + "Database error", + e.to_string(), + "dataset_probeset_values", + ) + .with_request_id(rid.clone()) + }) + .and_then(|lookup| match lookup { + DatasetProbesetLookup::Found(values) => Ok(Json(values)), + 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)), + }) +} diff --git a/src/routes/groups.rs b/src/routes/groups.rs index 652940d..18a6f66 100644 --- a/src/routes/groups.rs +++ b/src/routes/groups.rs @@ -308,3 +308,58 @@ pub async fn group_trait_info( .with_request_id(rid)), }) } + +#[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 = Vec<db::Dataset>), + (status = 404, description = "No matching group", body = ApiError), + (status = 500, description = "Database error", body = ApiError) +))] +pub async fn group_datasets( + Extension(request_id): Extension<RequestId>, + Path(group): Path<String>, +) -> Result<Json<Vec<db::Dataset>>, 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_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(Json) + .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") + }) +} + diff --git a/src/routes/mod.rs b/src/routes/mod.rs index 4cd3f7b..578761a 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -4,5 +4,6 @@ //! on the router. pub mod correlation; +pub mod datasets; pub mod groups; pub mod species; diff --git a/test/python/test_dataset_by_name.py b/test/python/test_dataset_by_name.py new file mode 100644 index 0000000..082f758 --- /dev/null +++ b/test/python/test_dataset_by_name.py @@ -0,0 +1,61 @@ +"""Mirrors tests/dataset_by_name.rs. Needs a live MariaDB (SQL_URI); +skips with a message rather than failing when none is reachable, same as +test_group_by_name.py. +""" + +import http.client +import json +import socket +import unittest + +from server_test_case import HOST, PORT, ServerTestCase + + +def database_reachable(): + try: + with socket.create_connection(("127.0.0.1", 3306), timeout=0.5): + return True + except OSError: + return False + + +class DatasetByNameTest(ServerTestCase): + def test_dataset_by_name_returns_dataset_row(self): + if not database_reachable(): + self.skipTest("no database on 127.0.0.1:3306") + + conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10) + try: + conn.request("GET", "/datasets/Br_U_0803_M") + response = conn.getresponse() + body = response.read() + finally: + conn.close() + self.assertEqual(response.status, 200) + + dataset = json.loads(body) + self.assertEqual(dataset["name"], "Br_U_0803_M") + self.assertEqual(dataset["full_name"], "Brain U74Av2 08/03 MAS5") + self.assertEqual(dataset["data_scale"], "log2") + + def test_dataset_by_name_unknown_dataset_returns_404(self): + if not database_reachable(): + self.skipTest("no database on 127.0.0.1:3306") + + conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10) + try: + conn.request("GET", "/datasets/not-a-real-dataset") + response = conn.getresponse() + body = response.read() + finally: + conn.close() + self.assertEqual(response.status, 404) + + error = json.loads(body) + self.assertEqual(error["status"], 404) + self.assertEqual(error["code"], "dataset_not_found") + self.assertEqual(error["operation_id"], "dataset_by_name") + + +if __name__ == "__main__": + unittest.main() diff --git a/test/python/test_dataset_probeset_info.py b/test/python/test_dataset_probeset_info.py new file mode 100644 index 0000000..cfb219c --- /dev/null +++ b/test/python/test_dataset_probeset_info.py @@ -0,0 +1,79 @@ +"""Mirrors tests/dataset_probeset_info.rs. Needs a live MariaDB +(SQL_URI); skips with a message rather than failing when none is +reachable, same as test_group_by_name.py. +""" + +import http.client +import json +import socket +import unittest + +from server_test_case import HOST, PORT, ServerTestCase + + +def database_reachable(): + try: + with socket.create_connection(("127.0.0.1", 3306), timeout=0.5): + return True + except OSError: + return False + + +class DatasetProbesetInfoTest(ServerTestCase): + def test_dataset_probeset_info_returns_gene_annotation(self): + if not database_reachable(): + self.skipTest("no database on 127.0.0.1:3306") + + conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10) + try: + conn.request("GET", "/datasets/Br_U_0803_M/probesets/100001_at") + response = conn.getresponse() + body = response.read() + finally: + conn.close() + self.assertEqual(response.status, 200) + + info = json.loads(body) + self.assertEqual(info["name"], "100001_at") + self.assertEqual(info["symbol"], "Cd3g") + self.assertIsInstance(info["mean"], float) + + def test_dataset_probeset_info_unknown_dataset_returns_404(self): + if not database_reachable(): + self.skipTest("no database on 127.0.0.1:3306") + + conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10) + try: + conn.request("GET", "/datasets/not-a-real-dataset/probesets/100001_at") + response = conn.getresponse() + body = response.read() + finally: + conn.close() + self.assertEqual(response.status, 404) + + error = json.loads(body) + self.assertEqual(error["status"], 404) + self.assertEqual(error["code"], "dataset_not_found") + self.assertEqual(error["operation_id"], "dataset_probeset_info") + + def test_dataset_probeset_info_unknown_probeset_in_dataset_returns_404(self): + if not database_reachable(): + self.skipTest("no database on 127.0.0.1:3306") + + conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10) + try: + conn.request("GET", "/datasets/Br_U_0803_M/probesets/not-a-real-probeset") + response = conn.getresponse() + body = response.read() + finally: + conn.close() + self.assertEqual(response.status, 404) + + error = json.loads(body) + self.assertEqual(error["status"], 404) + self.assertEqual(error["code"], "probeset_not_found") + self.assertEqual(error["operation_id"], "dataset_probeset_info") + + +if __name__ == "__main__": + unittest.main() diff --git a/test/python/test_dataset_probeset_values.py b/test/python/test_dataset_probeset_values.py new file mode 100644 index 0000000..3477fa7 --- /dev/null +++ b/test/python/test_dataset_probeset_values.py @@ -0,0 +1,79 @@ +"""Mirrors tests/dataset_probeset_values.rs. Needs a live MariaDB +(SQL_URI); skips with a message rather than failing when none is +reachable, same as test_group_by_name.py. +""" + +import http.client +import json +import socket +import unittest + +from server_test_case import HOST, PORT, ServerTestCase + + +def database_reachable(): + try: + with socket.create_connection(("127.0.0.1", 3306), timeout=0.5): + return True + except OSError: + return False + + +class DatasetProbesetValuesTest(ServerTestCase): + def test_dataset_probeset_values_returns_strain_values(self): + if not database_reachable(): + self.skipTest("no database on 127.0.0.1:3306") + + conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10) + try: + conn.request("GET", "/datasets/Br_U_0803_M/probesets/100001_at/values") + response = conn.getresponse() + body = response.read() + finally: + conn.close() + self.assertEqual(response.status, 200) + + values = json.loads(body) + self.assertTrue(values) + bxd1 = next(v for v in values if v["name"] == "BXD1") + self.assertIsInstance(bxd1["value"], float) + + def test_dataset_probeset_values_unknown_dataset_returns_404(self): + if not database_reachable(): + self.skipTest("no database on 127.0.0.1:3306") + + conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10) + try: + conn.request("GET", "/datasets/not-a-real-dataset/probesets/100001_at/values") + response = conn.getresponse() + body = response.read() + finally: + conn.close() + self.assertEqual(response.status, 404) + + error = json.loads(body) + self.assertEqual(error["status"], 404) + self.assertEqual(error["code"], "dataset_not_found") + self.assertEqual(error["operation_id"], "dataset_probeset_values") + + def test_dataset_probeset_values_unknown_probeset_in_dataset_returns_404(self): + if not database_reachable(): + self.skipTest("no database on 127.0.0.1:3306") + + conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10) + try: + conn.request("GET", "/datasets/Br_U_0803_M/probesets/not-a-real-probeset/values") + response = conn.getresponse() + body = response.read() + finally: + conn.close() + self.assertEqual(response.status, 404) + + error = json.loads(body) + self.assertEqual(error["status"], 404) + self.assertEqual(error["code"], "probeset_not_found") + self.assertEqual(error["operation_id"], "dataset_probeset_values") + + +if __name__ == "__main__": + unittest.main() diff --git a/test/python/test_group_datasets.py b/test/python/test_group_datasets.py new file mode 100644 index 0000000..d338075 --- /dev/null +++ b/test/python/test_group_datasets.py @@ -0,0 +1,62 @@ +"""Mirrors tests/group_datasets.rs. Needs a live MariaDB (SQL_URI); +skips with a message rather than failing when none is reachable, same as +test_group_by_name.py. +""" + +import http.client +import json +import socket +import unittest + +from server_test_case import HOST, PORT, ServerTestCase + + +def database_reachable(): + try: + with socket.create_connection(("127.0.0.1", 3306), timeout=0.5): + return True + except OSError: + return False + + +class GroupDatasetsTest(ServerTestCase): + def test_group_datasets_bxd_returns_datasets(self): + if not database_reachable(): + self.skipTest("no database on 127.0.0.1:3306") + + conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10) + try: + conn.request("GET", "/groups/BXD/datasets") + response = conn.getresponse() + body = response.read() + finally: + conn.close() + self.assertEqual(response.status, 200) + + datasets = json.loads(body) + self.assertTrue(datasets) + names = {record["name"] for record in datasets} + self.assertIn("Br_U_0803_M", names) + + def test_group_datasets_unknown_group_returns_404(self): + if not database_reachable(): + self.skipTest("no database on 127.0.0.1:3306") + + conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10) + try: + conn.request("GET", "/groups/not-a-real-group/datasets") + response = conn.getresponse() + body = response.read() + finally: + conn.close() + self.assertEqual(response.status, 404) + + error = json.loads(body) + self.assertEqual(error["status"], 404) + self.assertEqual(error["code"], "group_not_found") + self.assertEqual(error["operation_id"], "group_datasets") + self.assertEqual(error["next"], "/groups") + + +if __name__ == "__main__": + unittest.main() diff --git a/test/python/test_openapi.py b/test/python/test_openapi.py index 3b4b704..c66a0c8 100644 --- a/test/python/test_openapi.py +++ b/test/python/test_openapi.py @@ -30,6 +30,10 @@ class OpenApiTest(ServerTestCase): "/groups/{group}/strains", "/groups/{group}/traits/{trait_id}", "/groups/{group}/traits/{trait_id}/values", + "/groups/{group}/datasets", + "/datasets/{dataset}", + "/datasets/{dataset}/probesets/{probeset}", + "/datasets/{dataset}/probesets/{probeset}/values", ): self.assertIn(path, doc["paths"]) diff --git a/tests/dataset_by_name.rs b/tests/dataset_by_name.rs new file mode 100644 index 0000000..48208e6 --- /dev/null +++ b/tests/dataset_by_name.rs @@ -0,0 +1,58 @@ +use axum::http::StatusCode; +use http_body_util::BodyExt; +use serde_json::Value; + +mod common; + +/// Needs a live MariaDB connection (SQL_URI, see src/db.rs); skips rather +/// than fails when none is reachable, same as group_by_name.rs. +/// Br_U_0803_M is a real ProbeSetFreeze row in BXD, used here as a +/// fixture the same way BXD itself is used elsewhere. +#[tokio::test] +async fn dataset_by_name_returns_dataset_row() { + if !common::db_available() { + eprintln!( + "skipping dataset_by_name_returns_dataset_row: no usable database (check SQL_URI credentials)" + ); + return; + } + + let response = common::get( + "GET /datasets/Br_U_0803_M", + "/datasets/Br_U_0803_M", + ) + .await; + + assert_eq!(response.status(), StatusCode::OK); + + let body = response.into_body().collect().await.unwrap().to_bytes(); + let dataset: Value = serde_json::from_slice(&body).unwrap(); + + assert_eq!(dataset["name"], "Br_U_0803_M"); + assert_eq!(dataset["full_name"], "Brain U74Av2 08/03 MAS5"); + assert_eq!(dataset["data_scale"], "log2"); +} + +#[tokio::test] +async fn dataset_by_name_unknown_dataset_returns_404() { + if !common::db_available() { + eprintln!( + "skipping dataset_by_name_unknown_dataset_returns_404: no usable database (check SQL_URI credentials)" + ); + return; + } + + let response = common::get( + "GET /datasets/not-a-real-dataset", + "/datasets/not-a-real-dataset", + ) + .await; + + assert_eq!(response.status(), StatusCode::NOT_FOUND); + let body = response.into_body().collect().await.unwrap().to_bytes(); + let error: Value = serde_json::from_slice(&body).unwrap(); + + assert_eq!(error["status"], 404); + assert_eq!(error["code"], "dataset_not_found"); + assert_eq!(error["operation_id"], "dataset_by_name"); +} diff --git a/tests/dataset_probeset_info.rs b/tests/dataset_probeset_info.rs new file mode 100644 index 0000000..eb0224b --- /dev/null +++ b/tests/dataset_probeset_info.rs @@ -0,0 +1,82 @@ +use axum::http::StatusCode; +use http_body_util::BodyExt; +use serde_json::Value; + +mod common; + +/// Needs a live MariaDB connection (SQL_URI, see src/db.rs); skips rather +/// than fails when none is reachable, same as group_by_name.rs. +/// Probeset 100001_at (gene symbol Cd3g) in dataset Br_U_0803_M is a +/// real row in the database. +#[tokio::test] +async fn dataset_probeset_info_returns_gene_annotation() { + if !common::db_available() { + eprintln!( + "skipping dataset_probeset_info_returns_gene_annotation: no usable database (check SQL_URI credentials)" + ); + return; + } + + let response = common::get( + "GET /datasets/Br_U_0803_M/probesets/100001_at", + "/datasets/Br_U_0803_M/probesets/100001_at", + ) + .await; + + assert_eq!(response.status(), StatusCode::OK); + + let body = response.into_body().collect().await.unwrap().to_bytes(); + let info: Value = serde_json::from_slice(&body).unwrap(); + + assert_eq!(info["name"], "100001_at"); + assert_eq!(info["symbol"], "Cd3g"); + assert!(info["mean"].as_f64().is_some()); +} + +#[tokio::test] +async fn dataset_probeset_info_unknown_dataset_returns_404() { + if !common::db_available() { + eprintln!( + "skipping dataset_probeset_info_unknown_dataset_returns_404: no usable database (check SQL_URI credentials)" + ); + return; + } + + let response = common::get( + "GET /datasets/not-a-real-dataset/probesets/100001_at", + "/datasets/not-a-real-dataset/probesets/100001_at", + ) + .await; + + assert_eq!(response.status(), StatusCode::NOT_FOUND); + let body = response.into_body().collect().await.unwrap().to_bytes(); + let error: Value = serde_json::from_slice(&body).unwrap(); + + assert_eq!(error["status"], 404); + assert_eq!(error["code"], "dataset_not_found"); + assert_eq!(error["operation_id"], "dataset_probeset_info"); +} + +#[tokio::test] +async fn dataset_probeset_info_unknown_probeset_in_dataset_returns_404() { + if !common::db_available() { + eprintln!( + "skipping dataset_probeset_info_unknown_probeset_in_dataset_returns_404: no usable database (check SQL_URI credentials)" + ); + return; + } + + let response = common::get( + "GET /datasets/Br_U_0803_M/probesets/not-a-real-probeset", + "/datasets/Br_U_0803_M/probesets/not-a-real-probeset", + ) + .await; + + assert_eq!(response.status(), StatusCode::NOT_FOUND); + let body = response.into_body().collect().await.unwrap().to_bytes(); + let error: Value = serde_json::from_slice(&body).unwrap(); + + assert_eq!(error["status"], 404); + assert_eq!(error["code"], "probeset_not_found"); + assert_eq!(error["operation_id"], "dataset_probeset_info"); +} diff --git a/tests/dataset_probeset_values.rs b/tests/dataset_probeset_values.rs new file mode 100644 index 0000000..4ff8d08 --- /dev/null +++ b/tests/dataset_probeset_values.rs @@ -0,0 +1,83 @@ +use axum::http::StatusCode; +use http_body_util::BodyExt; +use serde_json::Value; + +mod common; + +/// Needs a live MariaDB connection (SQL_URI, see src/db.rs); skips rather +/// than fails when none is reachable, same as group_by_name.rs. +#[tokio::test] +async fn dataset_probeset_values_returns_strain_values() { + if !common::db_available() { + eprintln!( + "skipping dataset_probeset_values_returns_strain_values: no usable database (check SQL_URI credentials)" + ); + return; + } + + let response = common::get( + "GET /datasets/Br_U_0803_M/probesets/100001_at/values", + "/datasets/Br_U_0803_M/probesets/100001_at/values", + ) + .await; + + assert_eq!(response.status(), StatusCode::OK); + + let body = response.into_body().collect().await.unwrap().to_bytes(); + let values: Vec<Value> = serde_json::from_slice(&body).unwrap(); + + assert!(!values.is_empty()); + let bxd1 = values + .iter() + .find(|v| v["name"] == "BXD1") + .expect("BXD1 in /datasets/Br_U_0803_M/probesets/100001_at/values"); + assert!(bxd1["value"].as_f64().is_some()); +} + +#[tokio::test] +async fn dataset_probeset_values_unknown_dataset_returns_404() { + if !common::db_available() { + eprintln!( + "skipping dataset_probeset_values_unknown_dataset_returns_404: no usable database (check SQL_URI credentials)" + ); + return; + } + + let response = common::get( + "GET /datasets/not-a-real-dataset/probesets/100001_at/values", + "/datasets/not-a-real-dataset/probesets/100001_at/values", + ) + .await; + + assert_eq!(response.status(), StatusCode::NOT_FOUND); + let body = response.into_body().collect().await.unwrap().to_bytes(); + let error: Value = serde_json::from_slice(&body).unwrap(); + + assert_eq!(error["status"], 404); + assert_eq!(error["code"], "dataset_not_found"); + assert_eq!(error["operation_id"], "dataset_probeset_values"); +} + +#[tokio::test] +async fn dataset_probeset_values_unknown_probeset_in_dataset_returns_404() { + if !common::db_available() { + eprintln!( + "skipping dataset_probeset_values_unknown_probeset_in_dataset_returns_404: no usable database (check SQL_URI credentials)" + ); + return; + } + + let response = common::get( + "GET /datasets/Br_U_0803_M/probesets/not-a-real-probeset/values", + "/datasets/Br_U_0803_M/probesets/not-a-real-probeset/values", + ) + .await; + + assert_eq!(response.status(), StatusCode::NOT_FOUND); + let body = response.into_body().collect().await.unwrap().to_bytes(); + let error: Value = serde_json::from_slice(&body).unwrap(); + + assert_eq!(error["status"], 404); + assert_eq!(error["code"], "probeset_not_found"); + assert_eq!(error["operation_id"], "dataset_probeset_values"); +} diff --git a/tests/group_datasets.rs b/tests/group_datasets.rs new file mode 100644 index 0000000..6d7d961 --- /dev/null +++ b/tests/group_datasets.rs @@ -0,0 +1,56 @@ +use axum::http::StatusCode; +use http_body_util::BodyExt; +use serde_json::Value; + +mod common; + +/// Needs a live MariaDB connection (SQL_URI, see src/db.rs); skips rather +/// than fails when none is reachable, same as group_by_name.rs. +#[tokio::test] +async fn group_datasets_bxd_returns_datasets() { + if !common::db_available() { + eprintln!( + "skipping group_datasets_bxd_returns_datasets: no usable database (check SQL_URI credentials)" + ); + return; + } + + let response = common::get("GET /groups/BXD/datasets", "/groups/BXD/datasets").await; + + assert_eq!(response.status(), StatusCode::OK); + + let body = response.into_body().collect().await.unwrap().to_bytes(); + let datasets: Vec<Value> = serde_json::from_slice(&body).unwrap(); + + assert!(!datasets.is_empty()); + let names: Vec<&str> = datasets + .iter() + .map(|record| record["name"].as_str().unwrap()) + .collect(); + assert!(names.contains(&"Br_U_0803_M")); +} + +#[tokio::test] +async fn group_datasets_unknown_group_returns_404() { + if !common::db_available() { + eprintln!( + "skipping group_datasets_unknown_group_returns_404: no usable database (check SQL_URI credentials)" + ); + return; + } + + let response = common::get( + "GET /groups/not-a-real-group/datasets", + "/groups/not-a-real-group/datasets", + ) + .await; + + assert_eq!(response.status(), StatusCode::NOT_FOUND); + let body = response.into_body().collect().await.unwrap().to_bytes(); + let error: Value = serde_json::from_slice(&body).unwrap(); + + assert_eq!(error["status"], 404); + assert_eq!(error["code"], "group_not_found"); + assert_eq!(error["operation_id"], "group_datasets"); + assert_eq!(error["next"], "/groups"); +} diff --git a/tests/openapi.rs b/tests/openapi.rs index d2d75c0..8cb6dc1 100644 --- a/tests/openapi.rs +++ b/tests/openapi.rs @@ -34,6 +34,10 @@ async fn openapi_json_describes_all_endpoints() { "/groups/{group}/strains", "/groups/{group}/traits/{trait_id}", "/groups/{group}/traits/{trait_id}/values", + "/groups/{group}/datasets", + "/datasets/{dataset}", + "/datasets/{dataset}/probesets/{probeset}", + "/datasets/{dataset}/probesets/{probeset}/values", ] { assert!(paths.contains_key(path), "missing path: {path}"); } |
