diff options
| author | Pjotr <wrk@bosa.lan> | 2026-11-10 19:03:50 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-11-10 19:03:50 +0000 |
| commit | bb3a5454c76d9ad7542f884fb14f89998d978553 (patch) | |
| tree | c5601c2cf9a0b65b0e68882418a9906b6e2b44b0 /src | |
| parent | fc99de3a5e8dfe2f54ac7e34e7422672baaa97bc (diff) | |
| download | genenetwork4-bb3a5454c76d9ad7542f884fb14f89998d978553.tar.gz | |
baskets: a user's own column of values, in their own SQLite file
The next phase is changing data, and the constraint is that MariaDB is
never written to. A basket is the storage half of that: take a trait's
values, edit some of them (or build a covariate column that does not
exist), keep the column under a name, and map that instead.
* POST /baskets stores a complete column; GET /baskets lists yours;
GET /baskets/{name} its metadata; GET /baskets/{name}/values the
cells; PATCH /baskets/{name} replaces the column with a new revision;
DELETE removes it.
* POST /compute/qtl2 takes "basket": "<name>" in place of `samples`,
and both at once is a 422 rather than a silent choice. The mapping
code below it is untouched -- a basket resolves to the same
(name, value) pairs a client would have posted.
* One SQLite file per user: BASKET_DIR/<sha256(token sub)>.sqlite, 0600,
WAL, busy_timeout. `GET /baskets` only ever lists the caller's own;
the file name is a hash, so a directory listing does not name users.
* The full column is stored, not a diff -- the caller has the original
beside it, and a mapping needs one complete column.
* Text with a parsed copy beside it: raw (what was typed), value (the
number or NULL), status (ok/missing/bad). "NA" and 0 stay different
claims, and a column with something that is neither a number nor a
missing marker (NA, x, -, ., ?) is refused with the samples named --
silently dropping it would change a trait without saying so.
* A revision and a digest: an edit bumps the revision and changes the
digest, and a mapping reply records both ("Basket 'wbc-edit'
revision 2 (digest 9559a70e...)"), so two runs on one name cannot
look alike. A result cache must key on the digest, not the name.
The loop, end to end on BXD trait 10001: 34 values posted as a basket,
one bumped by 5 and one marked NA, revision 2 mapped with /compute/qtl2
-- 3730 rows, peak chr8 112.9 Mb, and the reply's note naming the
revision and digest.
tests/baskets.rs walks that loop (create, list, values, patch, map by
name, delete) and the refusals: a non-number named in the error, a name
that cannot become a path, an unknown basket, and basket-plus-samples.
Unit tests cover parsing (NA/x/-/. vs NaN/inf vs "twelve"), the digest
changing on edit, per-user isolation, and name validation.
rqtl/gemma take the same 10-line change next -- their `samples` shapes
differ, so they are a separate commit rather than a rushed one.
Diffstat (limited to 'src')
| -rw-r--r-- | src/baskets.rs | 632 | ||||
| -rw-r--r-- | src/config.rs | 15 | ||||
| -rw-r--r-- | src/lib.rs | 7 | ||||
| -rw-r--r-- | src/routes/baskets.rs | 376 | ||||
| -rw-r--r-- | src/routes/mod.rs | 1 | ||||
| -rw-r--r-- | src/routes/qtl2.rs | 76 |
6 files changed, 1106 insertions, 1 deletions
diff --git a/src/baskets.rs b/src/baskets.rs new file mode 100644 index 0000000..a3820c5 --- /dev/null +++ b/src/baskets.rs @@ -0,0 +1,632 @@ +//! Per-user baskets: a full column of values a user may edit, kept in their +//! own SQLite file so MariaDB is never written to. +//! +//! A basket is a *named column* -- a trait's values, or a covariate's -- that +//! a user can change and then map. The mapping endpoints already take values +//! per sample (`samples`), so a basket is storage, not a new compute path: +//! [`resolve`] hands back the same `(name, value)` pairs the client would +//! otherwise have posted. +//! +//! Storage choices, and why: +//! +//! * **Full vector, not a diff.** The caller keeps the original alongside the +//! edited column, so the comparison is theirs to make; the server keeps one +//! column, which is what a mapping needs and what an export should contain. +//! * **Text, with a parsed copy beside it.** `raw` is what the user typed +//! (`5.2`, `NA`, `x`), `value` is the number or NULL, and `status` says +//! which. Parsing once, at creation, is what lets a basket be *refused* with +//! a line number instead of silently mapping something the user did not +//! mean -- `NA` and `0` are different claims, as GEMMA's own handling of +//! them showed. +//! * **A revision and a digest.** A basket is mutable, so every mapping names +//! the revision it used and the reply carries the digest: two runs on one +//! name must not be able to differ silently. +//! +//! One SQLite file per user (`<BASKET_DIR>/<sha256(sub)>.sqlite`, 0600, WAL), +//! created on first write. The `sub` from the token is the owner: tokens +//! rotate, users do not. + +use std::path::{Path, PathBuf}; + +use rusqlite::{Connection, OptionalExtension, params}; + +use crate::indexer::sha256::hex_digest; + +/// What a basket holds: a trait's column or a covariate's. +pub const KINDS: [&str; 2] = ["trait", "covariate"]; + +/// Text that means "no value" rather than "a number". The same set the +/// compute endpoints accept, plus what spreadsheets export. +const MISSING: [&str; 9] = ["", "na", "n/a", "null", "nan-ish", "x", "-", ".", "?"]; + +/// One cell: what was typed, what it parsed to, and which of the two it is. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)] +pub struct Cell { + pub sample: String, + /// As the user gave it. `null` means an explicit missing. + #[serde(skip_serializing_if = "Option::is_none")] + pub raw: Option<String>, + /// The parsed number, when it is one. + #[serde(skip_serializing_if = "Option::is_none")] + pub value: Option<f64>, + /// `ok`, `missing` or `bad`. + pub status: String, +} + +/// A basket without its column (the listing shape). +#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)] +pub struct BasketInfo { + pub name: String, + /// `trait` or `covariate`. + pub kind: String, + /// Where the column came from, when it came from a published trait. + #[serde(skip_serializing_if = "Option::is_none")] + pub base_dataset: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub base_trait: Option<u32>, + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<String>, + /// Bumped by every edit; a mapping names the one it used. + pub revision: i64, + /// sha256 over (name, revision, sample, raw) -- the identity of these + /// values, so a reply can be reproduced after an edit. + pub digest: String, + /// Cells carrying a number, and cells marked missing. + pub values: usize, + pub missing: usize, + pub created_at: i64, + pub updated_at: i64, +} + +/// Why a basket operation failed. +#[derive(Debug)] +pub enum BasketError { + /// No basket with that name for this user. + NotFound(String), + /// The request could not be stored as asked (a bad name, a bad value). + Invalid(String), + /// The store itself failed. + Store(String), +} + +impl std::fmt::Display for BasketError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + BasketError::NotFound(what) | BasketError::Invalid(what) | BasketError::Store(what) => { + write!(f, "{what}") + } + } + } +} + +fn now() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|elapsed| elapsed.as_secs() as i64) + .unwrap_or(0) +} + +/// The per-user database file. The `sub` is hashed so a token's subject never +/// appears as a path a filesystem listing can read. +pub fn database(dir: &Path, owner: &str) -> PathBuf { + dir.join(format!("{}.sqlite", hex_digest(owner.as_bytes()))) +} + +/// Parse one cell. Returns the parsed number, or `None` for a missing value, +/// and the status to record. +pub fn parse(raw: Option<&str>) -> (Option<f64>, &'static str) { + let Some(raw) = raw else { return (None, "missing") }; + let trimmed = raw.trim(); + if MISSING.contains(&trimmed.to_lowercase().as_str()) { + return (None, "missing"); + } + match trimmed.parse::<f64>() { + // A NaN or an infinity is not a measurement; refuse it by name. + Ok(value) if value.is_finite() => (Some(value), "ok"), + _ => (None, "bad"), + } +} + +/// A basket name must be usable in a URL and readable in a reply. +pub fn validate_name(name: &str) -> Result<(), BasketError> { + let name = name.trim(); + if name.is_empty() || name.len() > 64 { + return Err(BasketError::Invalid( + "a basket name must be 1 to 64 characters".to_string(), + )); + } + if !name + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) + { + return Err(BasketError::Invalid(format!( + "'{name}': a basket name may hold letters, digits, '-', '_' and '.'" + ))); + } + Ok(()) +} + +fn open(dir: &Path, owner: &str) -> Result<Connection, BasketError> { + std::fs::create_dir_all(dir) + .map_err(|error| BasketError::Store(format!("{}: {error}", dir.display())))?; + let path = database(dir, owner); + let connection = Connection::open(&path) + .map_err(|error| BasketError::Store(format!("{}: {error}", path.display())))?; + // One writer per user, and a reader must not fail because of it. + connection + .busy_timeout(std::time::Duration::from_secs(5)) + .and_then(|_| connection.pragma_update(None, "journal_mode", "WAL")) + .map_err(|error| BasketError::Store(format!("{}: {error}", path.display())))?; + connection + .execute_batch( + "CREATE TABLE IF NOT EXISTS basket ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL UNIQUE, + kind TEXT NOT NULL, + base_dataset TEXT, + base_trait INTEGER, + description TEXT, + revision INTEGER NOT NULL, + digest TEXT NOT NULL, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS cell ( + basket_id INTEGER NOT NULL REFERENCES basket(id) ON DELETE CASCADE, + sample TEXT NOT NULL, + raw TEXT, + value REAL, + status TEXT NOT NULL, + PRIMARY KEY (basket_id, sample) + );", + ) + .map_err(|error| BasketError::Store(error.to_string()))?; + // 0600: a user's column is theirs. + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)); + } + Ok(connection) +} + +/// The digest that identifies these exact values. +fn digest(name: &str, revision: i64, cells: &[Cell]) -> String { + let mut ordered: Vec<&Cell> = cells.iter().collect(); + ordered.sort_by(|left, right| left.sample.cmp(&right.sample)); + let mut text = format!("{name}\u{0}{revision}\u{0}"); + for cell in ordered { + text.push_str(&cell.sample); + text.push('\u{0}'); + text.push_str(cell.raw.as_deref().unwrap_or("\u{1}")); + text.push('\u{0}'); + } + hex_digest(text.as_bytes()) +} + +/// Parse and validate a column, refusing it whole if any cell is not a number +/// and not a missing marker. +pub fn cells(named: &[(String, Option<String>)]) -> Result<Vec<Cell>, BasketError> { + if named.is_empty() { + return Err(BasketError::Invalid( + "a basket needs at least one value".to_string(), + )); + } + let mut seen = std::collections::HashSet::new(); + let mut parsed = Vec::with_capacity(named.len()); + let mut bad = Vec::new(); + for (sample, raw) in named { + if !seen.insert(sample.as_str()) { + return Err(BasketError::Invalid(format!( + "'{sample}' appears twice in the column" + ))); + } + let (value, status) = parse(raw.as_deref()); + if status == "bad" { + bad.push(format!( + "{sample}: '{}'", + raw.as_deref().unwrap_or_default() + )); + } + parsed.push(Cell { + sample: sample.clone(), + raw: raw.clone(), + value, + status: status.to_string(), + }); + } + if !bad.is_empty() { + return Err(BasketError::Invalid(format!( + "not a number and not a missing marker (NA, x, -, ., ?): {}", + bad.iter().take(5).cloned().collect::<Vec<_>>().join(", ") + ))); + } + Ok(parsed) +} + +/// Create a basket. `kind` is one of [`KINDS`]. +#[allow(clippy::too_many_arguments)] +pub fn create( + dir: &Path, + owner: &str, + name: &str, + kind: &str, + base: Option<(&str, u32)>, + description: Option<&str>, + cells: &[Cell], +) -> Result<BasketInfo, BasketError> { + validate_name(name)?; + let name = name.trim(); + if !KINDS.contains(&kind) { + return Err(BasketError::Invalid(format!( + "kind '{kind}' not recognized; use 'trait' or 'covariate'" + ))); + } + let mut connection = open(dir, owner)?; + let exists: Option<i64> = connection + .query_row( + "SELECT id FROM basket WHERE name = ?1", + params![name], + |row| row.get(0), + ) + .optional() + .map_err(|error| BasketError::Store(error.to_string()))?; + if exists.is_some() { + return Err(BasketError::Invalid(format!( + "a basket named '{name}' already exists; PATCH it, or pick another name" + ))); + } + let revision = 1; + let digest = digest(name, revision, cells); + let at = now(); + let transaction = connection + .transaction() + .map_err(|error| BasketError::Store(error.to_string()))?; + transaction + .execute( + "INSERT INTO basket (name, kind, base_dataset, base_trait, description, revision, \ + digest, created_at, updated_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?8)", + params![ + name, + kind, + base.map(|(dataset, _)| dataset), + base.map(|(_, trait_id)| trait_id), + description, + revision, + digest, + at + ], + ) + .map_err(|error| BasketError::Store(error.to_string()))?; + let id = transaction.last_insert_rowid(); + for cell in cells { + transaction + .execute( + "INSERT INTO cell (basket_id, sample, raw, value, status) \ + VALUES (?1, ?2, ?3, ?4, ?5)", + params![id, cell.sample, cell.raw, cell.value, cell.status], + ) + .map_err(|error| BasketError::Store(error.to_string()))?; + } + transaction + .commit() + .map_err(|error| BasketError::Store(error.to_string()))?; + get(dir, owner, name, false) +} + +/// Replace a basket's column, bumping its revision. +pub fn revise( + dir: &Path, + owner: &str, + name: &str, + cells: &[Cell], +) -> Result<BasketInfo, BasketError> { + let mut connection = open(dir, owner)?; + let current: Option<(i64, i64)> = connection + .query_row( + "SELECT id, revision FROM basket WHERE name = ?1", + params![name], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .optional() + .map_err(|error| BasketError::Store(error.to_string()))?; + let Some((id, revision)) = current else { + return Err(BasketError::NotFound(format!("no basket named '{name}'"))); + }; + let revision = revision + 1; + let digest = digest(name, revision, cells); + let transaction = connection + .transaction() + .map_err(|error| BasketError::Store(error.to_string()))?; + transaction + .execute("DELETE FROM cell WHERE basket_id = ?1", params![id]) + .map_err(|error| BasketError::Store(error.to_string()))?; + for cell in cells { + transaction + .execute( + "INSERT INTO cell (basket_id, sample, raw, value, status) \ + VALUES (?1, ?2, ?3, ?4, ?5)", + params![id, cell.sample, cell.raw, cell.value, cell.status], + ) + .map_err(|error| BasketError::Store(error.to_string()))?; + } + transaction + .execute( + "UPDATE basket SET revision = ?2, digest = ?3, updated_at = ?4 WHERE id = ?1", + params![id, revision, digest, now()], + ) + .map_err(|error| BasketError::Store(error.to_string()))?; + transaction + .commit() + .map_err(|error| BasketError::Store(error.to_string()))?; + get(dir, owner, name, false) +} + +/// One basket, with or without its column. +pub fn get( + dir: &Path, + owner: &str, + name: &str, + with_cells: bool, +) -> Result<BasketInfo, BasketError> { + let connection = open(dir, owner)?; + let row: Option<(i64, String, String, Option<String>, Option<u32>, Option<String>, i64, String, i64, i64)> = + connection + .query_row( + "SELECT id, name, kind, base_dataset, base_trait, description, revision, digest, \ + created_at, updated_at \ + FROM basket WHERE name = ?1", + params![name.trim()], + |row| { + Ok(( + row.get(0)?, + row.get(1)?, + row.get(2)?, + row.get(3)?, + row.get(4)?, + row.get(5)?, + row.get(6)?, + row.get(7)?, + row.get(8)?, + row.get(9)?, + )) + }, + ) + .optional() + .map_err(|error| BasketError::Store(error.to_string()))?; + let Some((id, name, kind, base_dataset, base_trait, description, revision, digest, created_at, updated_at)) = + row + else { + return Err(BasketError::NotFound(format!("no basket named '{name}'"))); + }; + let counts: (i64, i64) = connection + .query_row( + "SELECT COALESCE(SUM(status = 'ok'), 0), COALESCE(SUM(status = 'missing'), 0) \ + FROM cell WHERE basket_id = ?1", + params![id], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .map_err(|error| BasketError::Store(error.to_string()))?; + let _ = with_cells; + Ok(BasketInfo { + name, + kind, + base_dataset, + base_trait, + description, + revision, + digest, + values: counts.0 as usize, + missing: counts.1 as usize, + created_at, + updated_at, + }) +} + +/// Every basket this user has, newest first. +pub fn list(dir: &Path, owner: &str) -> Result<Vec<BasketInfo>, BasketError> { + let names: Vec<String> = { + let connection = open(dir, owner)?; + let mut statement = connection + .prepare("SELECT name FROM basket ORDER BY updated_at DESC, name") + .map_err(|error| BasketError::Store(error.to_string()))?; + let rows = statement + .query_map([], |row| row.get::<_, String>(0)) + .map_err(|error| BasketError::Store(error.to_string()))?; + rows.collect::<Result<Vec<_>, _>>() + .map_err(|error| BasketError::Store(error.to_string()))? + }; + names + .into_iter() + .map(|name| get(dir, owner, &name, false)) + .collect() +} + +/// A basket's column, in the order its samples were stored. +pub fn cells_of(dir: &Path, owner: &str, name: &str) -> Result<Vec<Cell>, BasketError> { + let connection = open(dir, owner)?; + let id: Option<i64> = connection + .query_row( + "SELECT id FROM basket WHERE name = ?1", + params![name.trim()], + |row| row.get(0), + ) + .optional() + .map_err(|error| BasketError::Store(error.to_string()))?; + let Some(id) = id else { + return Err(BasketError::NotFound(format!("no basket named '{name}'"))); + }; + let mut statement = connection + .prepare("SELECT sample, raw, value, status FROM cell WHERE basket_id = ?1 ORDER BY rowid") + .map_err(|error| BasketError::Store(error.to_string()))?; + let rows = statement + .query_map(params![id], |row| { + Ok(Cell { + sample: row.get(0)?, + raw: row.get(1)?, + value: row.get(2)?, + status: row.get(3)?, + }) + }) + .map_err(|error| BasketError::Store(error.to_string()))?; + rows.collect::<Result<Vec<_>, _>>() + .map_err(|error| BasketError::Store(error.to_string())) +} + +/// Delete a basket. +pub fn delete(dir: &Path, owner: &str, name: &str) -> Result<(), BasketError> { + let connection = open(dir, owner)?; + let changed = connection + .execute("DELETE FROM basket WHERE name = ?1", params![name.trim()]) + .map_err(|error| BasketError::Store(error.to_string()))?; + if changed == 0 { + return Err(BasketError::NotFound(format!("no basket named '{name}'"))); + } + // The values go with it; there is no reason to keep a column nobody can + // name. + let _ = connection.execute( + "DELETE FROM cell WHERE basket_id NOT IN (SELECT id FROM basket)", + [], + ); + Ok(()) +} + +/// What a mapping gets: the same `(name, value)` pairs it would have been +/// posted, plus the revision and digest to record in the reply. +pub struct Resolved { + pub name: String, + pub revision: i64, + pub digest: String, + pub values: Vec<(String, Option<f64>)>, + pub missing: usize, +} + +/// Resolve a basket for a mapping. +pub fn resolve(dir: &Path, owner: &str, name: &str) -> Result<Resolved, BasketError> { + let info = get(dir, owner, name, false)?; + let cells = cells_of(dir, owner, name)?; + Ok(Resolved { + name: info.name, + revision: info.revision, + digest: info.digest, + missing: cells.iter().filter(|cell| cell.value.is_none()).count(), + values: cells + .into_iter() + .map(|cell| (cell.sample, cell.value)) + .collect(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn scratch() -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "gn4-baskets-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|elapsed| elapsed.as_nanos()) + .unwrap_or(0) + )); + let _ = std::fs::remove_dir_all(&dir); + dir + } + + fn column(pairs: &[(&str, Option<&str>)]) -> Vec<Cell> { + let named: Vec<(String, Option<String>)> = pairs + .iter() + .map(|(sample, raw)| (sample.to_string(), raw.map(str::to_string))) + .collect(); + cells(&named).unwrap() + } + + #[test] + fn cells_parse_numbers_missing_and_refuse_the_rest() { + assert_eq!(parse(Some("5.2")), (Some(5.2), "ok")); + assert_eq!(parse(Some(" -3.5e2 ")), (Some(-350.0), "ok")); + for missing in ["", "NA", "na", "N/A", "null", "x", "X", "-", ".", "?"] { + assert_eq!(parse(Some(missing)), (None, "missing"), "{missing}"); + } + assert_eq!(parse(None), (None, "missing")); + assert_eq!(parse(Some("n/a-ish")), (None, "bad")); + assert_eq!(parse(Some("12abc")), (None, "bad")); + assert_eq!(parse(Some("NaN")), (None, "bad")); + assert_eq!(parse(Some("inf")), (None, "bad")); + } + + #[test] + fn a_bad_cell_is_refused_with_the_sample_named() { + let error = cells(&[ + ("BXD1".to_string(), Some("1.0".to_string())), + ("BXD2".to_string(), Some("not a number".to_string())), + ]) + .unwrap_err() + .to_string(); + assert!(error.contains("BXD2"), "{error}"); + assert!(error.contains("not a number"), "{error}"); + // Duplicates are a mistake, not a merge. + let duplicate = cells(&[ + ("BXD1".to_string(), Some("1.0".to_string())), + ("BXD1".to_string(), Some("2.0".to_string())), + ]) + .unwrap_err() + .to_string(); + assert!(duplicate.contains("twice"), "{duplicate}"); + } + + #[test] + fn a_basket_round_trips_and_a_revision_changes_the_digest() { + let dir = scratch(); + let first = column(&[ + ("BXD1", Some("1.0")), + ("BXD2", Some("2.5")), + ("BXD3", Some("NA")), + ]); + let created = create(&dir, "user-a", "wbc-edit", "trait", Some(("BXD", 10001)), Some("two values"), &first).unwrap(); + assert_eq!(created.revision, 1); + assert_eq!(created.values, 2); + assert_eq!(created.missing, 1); + assert_eq!(created.base_trait, Some(10001)); + let before = created.digest.clone(); + + // An edit is a new revision, and a new identity. + let second = column(&[("BXD1", Some("1.6")), ("BXD2", Some("2.5")), ("BXD3", Some("NA"))]); + let revised = revise(&dir, "user-a", "wbc-edit", &second).unwrap(); + assert_eq!(revised.revision, 2); + assert_ne!(revised.digest, before); + let cells = cells_of(&dir, "user-a", "wbc-edit").unwrap(); + assert_eq!(cells[0].value, Some(1.6)); + assert_eq!(cells[0].raw.as_deref(), Some("1.6"), "the text is kept"); + assert_eq!(cells[2].status, "missing"); + + let resolved = resolve(&dir, "user-a", "wbc-edit").unwrap(); + assert_eq!(resolved.values.len(), 3); + assert_eq!(resolved.missing, 1); + assert_eq!(resolved.revision, 2); + + // Another user cannot see it: the file is theirs. + assert!(matches!( + get(&dir, "user-b", "wbc-edit", false).unwrap_err(), + BasketError::NotFound(_) + )); + assert!(list(&dir, "user-b").unwrap().is_empty()); + assert_eq!(list(&dir, "user-a").unwrap().len(), 1); + + delete(&dir, "user-a", "wbc-edit").unwrap(); + assert!(list(&dir, "user-a").unwrap().is_empty()); + std::fs::remove_dir_all(&dir).ok(); + } + + #[test] + fn names_are_url_safe_and_short() { + assert!(validate_name("wbc-edit").is_ok()); + assert!(validate_name("my.basket_2").is_ok()); + assert!(validate_name("").is_err()); + assert!(validate_name("has space").is_err()); + assert!(validate_name("../etc/passwd").is_err()); + assert!(validate_name(&"x".repeat(65)).is_err()); + } +} diff --git a/src/config.rs b/src/config.rs index e744075..b0ab030 100644 --- a/src/config.rs +++ b/src/config.rs @@ -143,6 +143,9 @@ pub struct Config { /// refetched; if Wikidata is unreachable the old value is served and /// marked stale. pub wikidata_ttl: i64, + /// Directory holding one SQLite file per user's baskets (`BASKET_DIR`), + /// named by a hash of the token's subject. See src/baskets.rs. + pub basket_dir: String, /// Directory holding the genotype files (`GENOTYPE_FILES`): GN2's /// layout -- `genotype/<Group>.json` for the version list, /// `genotype/<stem>.geno`, `genotype/bimbam/<stem>_geno.txt` and @@ -306,6 +309,15 @@ impl Config { "https://query.wikidata.org/sparql".to_string(), ); values.insert("WIKIDATA_TTL_SECONDS".to_string(), "604800".to_string()); + // Per-user baskets: one SQLite file each (src/baskets.rs). Never + // MariaDB -- a user's edited column is theirs. + values.insert( + "BASKET_DIR".to_string(), + std::env::temp_dir() + .join("gn4-baskets") + .to_string_lossy() + .into_owned(), + ); // Layers 2 and 3: config files, in increasing priority. for env_key in ["GN4_CONF", "GN4_SECRETS"] { @@ -359,6 +371,7 @@ impl Config { "WIKIDATA_CACHE_DIR", "WIKIDATA_ENDPOINT", "WIKIDATA_TTL_SECONDS", + "BASKET_DIR", ] { if let Ok(value) = std::env::var(key) { values.insert(key.to_string(), value); @@ -403,6 +416,7 @@ impl Config { wikidata_cache_dir: values["WIKIDATA_CACHE_DIR"].clone(), wikidata_endpoint: values["WIKIDATA_ENDPOINT"].clone(), wikidata_ttl: values["WIKIDATA_TTL_SECONDS"].parse().unwrap_or(604800), + basket_dir: values["BASKET_DIR"].clone(), genotype_files_dir: values["GENOTYPE_FILES"].clone(), sql_check_health: parse_switch(&values["SQL_CHECK_HEALTH"]), rqtl_max_concurrent: values["RQTL_MAX_CONCURRENT"] @@ -650,6 +664,7 @@ mod tests { "WIKIDATA_CACHE_DIR", "WIKIDATA_ENDPOINT", "WIKIDATA_TTL_SECONDS", + "BASKET_DIR", ] { if std::env::var(key).is_ok() { eprintln!("skipping: {key} is set in the environment"); diff --git a/src/lib.rs b/src/lib.rs index 62317eb..3740532 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7,6 +7,7 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; pub mod auth; +pub mod baskets; pub mod compute_gate; pub mod covariates; pub mod config; @@ -121,6 +122,12 @@ pub fn app() -> Router { .routes(routes!(routes::publications::publication_traits)) .routes(routes!(routes::search::search)) .routes(routes!(routes::correlation::correlation)) + .routes(routes!(routes::baskets::list_baskets)) + .routes(routes!(routes::baskets::create_basket)) + .routes(routes!(routes::baskets::get_basket)) + .routes(routes!(routes::baskets::basket_values)) + .routes(routes!(routes::baskets::revise_basket)) + .routes(routes!(routes::baskets::delete_basket)) .routes(routes!(routes::probesets::probeset_by_name)) .routes(routes!(routes::probesets::gene_traits)) .routes(routes!(routes::probesets::gene_aliases)) diff --git a/src/routes/baskets.rs b/src/routes/baskets.rs new file mode 100644 index 0000000..7ae3055 --- /dev/null +++ b/src/routes/baskets.rs @@ -0,0 +1,376 @@ +//! `GET|POST /baskets`, `GET|PATCH|DELETE /baskets/{name}`: a user's own +//! column of values, in their own SQLite file. +//! +//! A basket is how a user changes data without changing the database: take a +//! trait's values, edit one or more of them (or build a covariate column that +//! does not exist), keep it under a name, and map *that* instead. MariaDB is +//! never written to; the only thing that grows is a per-user SQLite file +//! (`BASKET_DIR/<sha256(sub)>.sqlite`, 0600). +//! +//! The full column is stored, not a diff: the client has the original beside +//! it and the comparison is its business, while a mapping needs one complete +//! column. Values are kept as text with a parsed copy beside them, so `NA` and +//! `0` stay different claims, and a column with something that is neither a +//! number nor a missing marker is refused by name rather than silently +//! dropped. +//! +//! Every edit bumps `revision` and changes `digest`; a mapping reply records +//! both, so two runs on one basket name can never differ silently. + +use axum::Json; +use axum::extract::{Path, Query}; +use axum::http::StatusCode; +use serde::Deserialize; +use serde_json::Value; + +use gnauth_macros::gnauth; + +use crate::auth::AuthToken; +use crate::baskets::{self, BasketError, BasketInfo}; +use crate::config::Config; +use crate::error::{ApiError, Unauthorized}; +use crate::response::{Ctx, Envelope, RequestInfo}; + +/// One value as posted: a number, a string (`"NA"`), or null for missing. +#[derive(Deserialize, utoipa::ToSchema)] +pub struct PostedValue { + pub name: String, + #[schema(value_type = Object)] + pub value: Option<Value>, +} + +#[derive(Deserialize, utoipa::ToSchema)] +pub struct CreateBasket { + /// URL-safe, unique per user: letters, digits, `-`, `_`, `.`. + pub name: String, + /// `trait` (default) or `covariate`. + pub kind: Option<String>, + /// What this column is and why it was changed. + pub description: Option<String>, + /// The column itself: one value per sample. + pub values: Vec<PostedValue>, + /// Where the column came from, for provenance (`/baskets/{name}` echoes + /// it): the published trait it started as. + pub base_dataset: Option<String>, + pub base_trait: Option<u32>, +} + +#[derive(Deserialize, utoipa::ToSchema)] +pub struct ReviseBasket { + /// The complete replacement column: a revision replaces, it does not + /// merge, so a caller cannot silently keep a value it meant to drop. + pub values: Vec<PostedValue>, +} + +#[derive(Deserialize, utoipa::IntoParams)] +pub struct BasketQuery { + /// Include the column? `/baskets/{name}/values` is the shaped way to ask. + #[serde(default)] + pub values: Option<bool>, +} + +/// Turn posted values into the text the store keeps. +fn posted(values: &[PostedValue]) -> Result<Vec<(String, Option<String>)>, ApiError> { + let mut named = Vec::with_capacity(values.len()); + for posted in values { + let raw = match &posted.value { + None | Some(Value::Null) => None, + Some(Value::Number(number)) => Some(number.to_string()), + Some(Value::String(text)) => Some(text.clone()), + Some(other) => { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_value", + "Invalid value", + format!( + "'{}': a value must be a number, a string or null (for missing), not {other}", + posted.name + ), + "baskets", + )); + } + }; + named.push((posted.name.clone(), raw)); + } + Ok(named) +} + +fn map_error(error: BasketError, rid: RequestInfo) -> ApiError { + match error { + BasketError::NotFound(message) => ApiError::new( + StatusCode::NOT_FOUND, + "basket_not_found", + "Basket not found", + message, + "baskets", + ) + .with_request_id(rid), + BasketError::Invalid(message) => ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_basket", + "Invalid basket", + message, + "baskets", + ) + .with_request_id(rid), + BasketError::Store(message) => ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "basket_store_error", + "The basket store failed", + message, + "baskets", + ) + .with_request_id(rid), + } +} + +#[utoipa::path(get, path = "/baskets", + summary = "This user's baskets, newest first", + description = "The columns this token's user has stored: a name, whether it is a trait or a \ +covariate column, where it came from, its description, its revision and the digest of its \ +values. Baskets are private to their owner -- each user has their own SQLite file -- and no \ +other user's baskets are visible here.", + responses( + (status = 200, description = "Every basket of this user", body = Envelope<Vec<BasketInfo>>), + Unauthorized + ) +)] +#[gnauth(token_only)] +pub async fn list_baskets( + ctx: Ctx, + _token: AuthToken, +) -> Result<Json<Envelope<Vec<BasketInfo>>>, ApiError> { + let rid = ctx.request_info(); + let owner = _token.sub.clone(); + let dir = Config::load().basket_dir; + let baskets = tokio::task::spawn_blocking(move || { + baskets::list(std::path::Path::new(&dir), &owner) + }) + .await + .map_err(|error| map_error(BasketError::Store(error.to_string()), rid.clone()))? + .map_err(|error| map_error(error, rid.clone()))?; + let mut envelope = ctx + .envelope(baskets) + .with_note("Baskets are yours: they live in your own SQLite file, not in GeneNetwork's \ + database.") + .with_note("A mapping can name one instead of posting values: POST /compute/qtl2 with \ + \"basket\": \"<name>\"."); + envelope = envelope.with_links(crate::suggest::root_links()); + Ok(Json(envelope)) +} + +#[utoipa::path(post, path = "/baskets", + summary = "Create a basket from a column of values", + description = "Store a complete column -- a trait's values with some of them changed, or a \ +covariate -- under a name. Values are kept as text with a parsed copy, so \"NA\" and 0 stay \ +different claims; a column containing something that is neither a number nor a missing marker \ +(NA, x, -, ., ?) is refused with the offending samples named.", + request_body = CreateBasket, + responses( + (status = 201, description = "The stored basket", body = Envelope<BasketInfo>), + Unauthorized, + (status = 422, description = "An invalid name or value", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn create_basket( + ctx: Ctx, + token: AuthToken, + Json(request): Json<CreateBasket>, +) -> Result<(StatusCode, Json<Envelope<BasketInfo>>), ApiError> { + let rid = ctx.request_info(); + let owner = token.sub.clone(); + let dir = Config::load().basket_dir; + let named = posted(&request.values)?; + let kind = request.kind.clone().unwrap_or_else(|| "trait".to_string()); + let cells = baskets::cells(&named).map_err(|error| map_error(error, rid.clone()))?; + let name = request.name.clone(); + let description = request.description.clone(); + let base = request + .base_dataset + .clone() + .map(|dataset| (dataset, request.base_trait.unwrap_or_default())); + let stored = tokio::task::spawn_blocking(move || { + baskets::create( + std::path::Path::new(&dir), + &owner, + &name, + &kind, + base.as_ref().map(|(dataset, trait_id)| (dataset.as_str(), *trait_id)), + description.as_deref(), + &cells, + ) + }) + .await + .map_err(|error| map_error(BasketError::Store(error.to_string()), rid.clone()))? + .map_err(|error| map_error(error, rid.clone()))?; + let mut envelope = ctx.envelope(stored).with_note( + "Stored. Edit it with PATCH (a new revision, a new digest) and map it with \ + POST /compute/qtl2 {\"basket\": \"<name>\"}.", + ); + envelope = envelope.with_links(crate::suggest::root_links()); + Ok((StatusCode::CREATED, Json(envelope))) +} + +#[utoipa::path(get, path = "/baskets/{name}", + summary = "One basket's metadata", + description = "The name, kind, provenance, description, revision, digest and cell counts. \ +The values themselves are at /baskets/{name}/values.", + params(("name" = String, Path, description = "Basket name"), BasketQuery), + responses( + (status = 200, description = "The basket", body = Envelope<BasketInfo>), + Unauthorized, + (status = 404, description = "No such basket for this user", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn get_basket( + ctx: Ctx, + token: AuthToken, + Path(name): Path<String>, +) -> Result<Json<Envelope<BasketInfo>>, ApiError> { + let rid = ctx.request_info(); + let owner = token.sub.clone(); + let dir = Config::load().basket_dir; + let wanted = name.clone(); + let stored = tokio::task::spawn_blocking(move || { + baskets::get(std::path::Path::new(&dir), &owner, &wanted, false) + }) + .await + .map_err(|error| map_error(BasketError::Store(error.to_string()), rid.clone()))? + .map_err(|error| map_error(error, rid.clone()))?; + let links = vec![( + format!("/baskets/{}/values", crate::response::path_segment(&name)), + "This basket's column (sample, raw, value, status)", + )]; + let mut envelope = ctx + .envelope(stored) + .with_note("`revision` and `digest` identify these exact values: a mapping reply records \ + them, so an edit cannot make two runs look alike.") + .with_note("Map it: POST /compute/qtl2 with \"basket\": \"<name>\" in place of `samples`."); + envelope = envelope.with_links(links); + Ok(Json(envelope)) +} + +#[utoipa::path(get, path = "/baskets/{name}/values", + summary = "One basket's column", + description = "The stored cells: sample, what was typed (`raw`, absent when explicitly \ +missing), the parsed number and the status (`ok`, `missing`). Positional rows; meta.columns \ +names them.", + params(("name" = String, Path, description = "Basket name")), + responses( + (status = 200, description = "The cells, positional (meta.columns names them)", body = Envelope<Value>), + Unauthorized, + (status = 404, description = "No such basket for this user", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn basket_values( + ctx: Ctx, + token: AuthToken, + Path(name): Path<String>, +) -> Result<Json<Envelope<Value>>, ApiError> { + let rid = ctx.request_info(); + let owner = token.sub.clone(); + let dir = Config::load().basket_dir; + let wanted = name.clone(); + let cells = tokio::task::spawn_blocking(move || { + baskets::cells_of(std::path::Path::new(&dir), &owner, &wanted) + }) + .await + .map_err(|error| map_error(BasketError::Store(error.to_string()), rid.clone()))? + .map_err(|error| map_error(error, rid.clone()))?; + let rows: Vec<Value> = cells + .iter() + .map(|cell| { + serde_json::json!([cell.sample, cell.raw, cell.value, cell.status]) + }) + .collect(); + let num_rows = rows.len(); + let mut envelope = ctx + .envelope(Value::Array(rows)) + .with_columns( + ["sample", "raw", "value", "status"] + .iter() + .map(|name| name.to_string()) + .collect(), + num_rows, + ) + .with_note("`raw` is what was typed, `value` the parsed number, `status` which it is."); + envelope = envelope.with_next( + &format!("/baskets/{}", crate::response::path_segment(&name)), + "This basket's metadata (revision, digest)", + ); + Ok(Json(envelope)) +} + +#[utoipa::path(patch, path = "/baskets/{name}", + summary = "Replace a basket's column with a new revision", + description = "The complete new column. A revision replaces, it does not merge: a caller \ +cannot keep a value by leaving it out. The basket's revision is bumped and its digest changes, \ +which is what keeps two mappings on one name distinguishable.", + params(("name" = String, Path, description = "Basket name")), + request_body = ReviseBasket, + responses( + (status = 200, description = "The revised basket", body = Envelope<BasketInfo>), + Unauthorized, + (status = 404, description = "No such basket for this user", body = ApiError), + (status = 422, description = "An invalid value", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn revise_basket( + ctx: Ctx, + token: AuthToken, + Path(name): Path<String>, + Json(request): Json<ReviseBasket>, +) -> Result<Json<Envelope<BasketInfo>>, ApiError> { + let rid = ctx.request_info(); + let owner = token.sub.clone(); + let dir = Config::load().basket_dir; + let named = posted(&request.values)?; + let cells = baskets::cells(&named).map_err(|error| map_error(error, rid.clone()))?; + let wanted = name.clone(); + let stored = tokio::task::spawn_blocking(move || { + baskets::revise(std::path::Path::new(&dir), &owner, &wanted, &cells) + }) + .await + .map_err(|error| map_error(BasketError::Store(error.to_string()), rid.clone()))? + .map_err(|error| map_error(error, rid.clone()))?; + let mut envelope = ctx.envelope(stored).with_note( + "The revision moved, so this is a new column as far as a mapping is concerned: the old \ + revision's digest is not this one's.", + ); + envelope = envelope.with_links(crate::suggest::root_links()); + Ok(Json(envelope)) +} + +#[utoipa::path(delete, path = "/baskets/{name}", + summary = "Delete a basket", + description = "Removes the basket and its column. A mapping that named it can no longer be \ +reproduced, so export the values first if that matters.", + params(("name" = String, Path, description = "Basket name")), + responses( + (status = 204, description = "Deleted"), + Unauthorized, + (status = 404, description = "No such basket for this user", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn delete_basket( + ctx: Ctx, + token: AuthToken, + Path(name): Path<String>, +) -> Result<StatusCode, ApiError> { + let rid = ctx.request_info(); + let owner = token.sub.clone(); + let dir = Config::load().basket_dir; + let wanted = name.clone(); + tokio::task::spawn_blocking(move || { + baskets::delete(std::path::Path::new(&dir), &owner, &wanted) + }) + .await + .map_err(|error| map_error(BasketError::Store(error.to_string()), rid.clone()))? + .map_err(|error| map_error(error, rid.clone()))?; + Ok(StatusCode::NO_CONTENT) +} diff --git a/src/routes/mod.rs b/src/routes/mod.rs index 388894f..5055acf 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -4,6 +4,7 @@ //! on the router. pub mod accessions; +pub mod baskets; pub mod correlation; pub mod datasets; pub mod dev; diff --git a/src/routes/qtl2.rs b/src/routes/qtl2.rs index 45aa4b5..76932ae 100644 --- a/src/routes/qtl2.rs +++ b/src/routes/qtl2.rs @@ -65,6 +65,10 @@ pub struct Qtl2Request { /// The trait's values by individual name, or `trait_values` positionally /// in the genotype file's order. pub samples: Option<Vec<Qtl2Sample>>, + /// A basket from `/baskets`: a stored column of values to map instead of + /// posting `samples`. Its revision and digest are recorded in `notes`, so + /// a run on an edited basket is distinguishable from an earlier one. + pub basket: Option<String>, /// Positional values, for a `genotype_file` request. pub trait_values: Option<Vec<Option<f64>>>, /// Label for the trait, e.g. "DOL::10003"; reported in `notes`. @@ -110,7 +114,7 @@ pub async fn compute_qtl2( ctx: Ctx, token: AuthToken, Query(params): Query<ComputeQtl2Params>, - Json(request): Json<Qtl2Request>, + Json(mut request): Json<Qtl2Request>, ) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { let rid = ctx.request_info(); let config = Config::load(); @@ -169,6 +173,73 @@ pub async fn compute_qtl2( /// A cross that ships a qtl2 control file of its own. Control(String), } + // A basket is another source for `samples`, resolved before anything else + // looks at them: a stored column and a posted one are the same thing to + // the mapping code below. + let mut basket_note: Option<String> = None; + if let Some(name) = request.basket.clone() { + if request.samples.is_some() { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "ambiguous_samples", + "Ambiguous values", + "give `basket` or `samples`, not both: a basket already is a column of values." + .to_string(), + "compute_qtl2", + ) + .with_request_id(rid)); + } + let dir = config.basket_dir.clone(); + let owner = token.sub.clone(); + let wanted = name.clone(); + let resolved = tokio::task::spawn_blocking(move || { + crate::baskets::resolve(std::path::Path::new(&dir), &owner, &wanted) + }) + .await + .map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Internal error", + error.to_string(), + "compute_qtl2", + ) + .with_request_id(rid.clone()) + })? + .map_err(|error| match error { + crate::baskets::BasketError::NotFound(detail) => ApiError::new( + StatusCode::NOT_FOUND, + "basket_not_found", + "Basket not found", + format!("{detail}; see /baskets"), + "compute_qtl2", + ) + .with_request_id(rid.clone()), + other => ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "basket_store_error", + "The basket store failed", + other.to_string(), + "compute_qtl2", + ) + .with_request_id(rid.clone()), + })?; + basket_note = Some(format!( + "Basket '{}' revision {} (digest {}): {} value(s), {} missing. These values come \ + from the basket, not from a published trait -- report the revision with the result.", + resolved.name, resolved.revision, resolved.digest, resolved.values.len(), resolved.missing + )); + request.samples = Some( + resolved + .values + .iter() + .map(|(name, value)| Qtl2Sample { + name: name.clone(), + value: *value, + }) + .collect(), + ); + } let (source, samples) = if let Some(name) = request.rqtl2_cross.clone() { if request.group.is_some() || request.genotype_file.is_some() { return Err(ApiError::new( @@ -502,6 +573,9 @@ pub async fn compute_qtl2( cross_note.push(')'); notes.push(cross_note); + if let Some(note) = basket_note { + notes.push(note); + } // A multiparent cross is fitted per founder allele: the DO's scan is // eight times the work of the same panel scanned biallelically, so the // gate is handed that weight rather than the individual count. |
