From 9e03cf40b875790c19d3fa1623297841b72b553e Mon Sep 17 00:00:00 2001 From: Pjotr Date: Sun, 11 Oct 2026 19:49:57 +0000 Subject: gemma: add POST /compute/gemma, backed by the real gemma-wrapper/GEMMA Maps a QTL from a genotype file, a SNP annotation file and trait values, by running gemma-wrapper's K-matrix step then its LMM association step, both synchronously (axum/tokio awaits the subprocess directly, no job queue needed) and returning the parsed .assoc.txt rows in the standard envelope. Both steps use a bare --loco (gemma-wrapper derives the chromosome list from the SNP annotation file). This was arrived at empirically, not from GeneNetwork3's or GeneNetwork2's own gemma code: run for real against the BXD fixtures, - GeneNetwork3's gn3/computations/gemma.py composes a GWA command that always keeps "-gk" alongside "-lmm"; real GEMMA rejects that combination outright ("only one of -gk ... -lmm ... options is allowed"), so none of its gwa-compute/k-gwa-compute endpoints can produce output. Unsurprising: tests/integration/test_gemma.py is entirely @unittest.skip, so this was never exercised. - GeneNetwork2's wqflask/marker_regression/gemma_mapping.py correctly omits "-gk" from the GWA step, but its non-LOCO branch fails too, the same way my own first (non-LOCO) attempt did: gemma-wrapper only ever archives a non-LOCO kinship matrix into a .tar.xz, with no loose file at the path its own non-LOCO GWA code assumes ("Enforce failed for file_kin ... open file"). Only --loco, which gemma-wrapper's own USAGE banner documents and which does unpack that archive, actually works. A --loco run's .assoc.txt files (one per chromosome) are themselves only ever inside gemma-wrapper's own output archive, never loose, so gemma.rs shells out to `tar` (one of gemma-wrapper's own propagated dependencies) to extract them before concatenating all chromosomes' rows into the response. guix.scm now depends on (gn packages gemma) from guix-bioinformatics for gemma-wrapper (propagated-input: it's invoked as a subprocess, not linked, and this makes it land in a consuming profile too, same as GeneNetwork3's and GeneNetwork2's own packages do it). That dependency needed guix-bioinformatics' own gn/packages/gemma.scm fixed first (see that repo's fix/gemma-which-shadowing branch) -- gemma-gn2 would not build at all before that fix. Verified end to end: `cargo test` passes in full, including a real (non-mocked, non-skipped) run of gemma-wrapper/GEMMA against the BXD fixtures copied from genenetwork3/tests/test_data, producing exactly 7320 association rows (one per marker in BXD_snps.txt) in ~19s. Co-Authored-By: Claude Sonnet 5 --- src/lib.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src/lib.rs') diff --git a/src/lib.rs b/src/lib.rs index cfe2c59..ab88fff 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,6 +10,7 @@ pub mod config; mod db; pub mod embedded; mod error; +mod gemma; pub mod response; mod routes; pub mod search; @@ -76,7 +77,8 @@ pub fn app() -> Router { .routes(routes!(routes::traits::trait_values)) .routes(routes!(routes::publications::publication_traits)) .routes(routes!(routes::search::search)) - .routes(routes!(routes::correlation::correlation)); + .routes(routes!(routes::correlation::correlation)) + .routes(routes!(routes::gemma::compute_gemma)); // Registered -- and so reachable and listed in /openapi.json -- unless // GENENETWORK4_TEST_TOKEN switches it off; when registered it decides // per request whether the caller is local. See src/routes/dev.rs. -- cgit 1.4.1 From b04db9ea05a73074afcf88300f8b6aa8c6e28e64 Mon Sep 17 00:00:00 2001 From: Pjotr Date: Mon, 12 Oct 2026 12:19:12 +0000 Subject: gemma: stream gemma-wrapper's progress; add GET /compute/gemma/status /compute/gemma can genuinely take minutes (see the README's ~100K marker caveat), and until now gave no visibility into a run already in flight. Same shape GeneNetwork2/3 use for R/qtl (gn3/computations/streaming.py, gn3/api/streaming.py): the caller picks a run id, passes it as POST /compute/gemma?id=, and polls GET /compute/gemma/status/{id}?peak= on a second connection while the first is still blocked. What's actually tailed is gemma-wrapper's stderr, not stdout: under --json, all of its human-readable progress (banner, chromosome list, "Executing: ...", per-step info) goes to stderr, and stdout carries only the one final JSON record, printed once at the very end -- so there is nothing to stream on stdout. run_streaming() replaces the old buffered Command::output() call with one that reads stderr line by line as the process runs, appending each line to a log file if one was given, across both the kinship and GWA steps into a single continuous log; stdout is still read in full (unchanged, one JSON blob). A completion marker ("GN4: computation complete") is appended once the whole request finishes, the same convention GeneNetwork3 uses ("Done with GN3 Computation" in gn3/api/rqtl2.py) under this project's own name. run_id is validated (1-64 ASCII letters/digits/-/_) before it's ever joined into a path, on both the POST's ?id= and the status endpoint's path segment -- GeneNetwork3's own /api/stream/{run_id} does no such check on its equivalent id, which is not knowingly replicated here. Verified end to end, not just unit tested: the integration test spawns the POST on its own task and polls the status endpoint from this one while the ~19s real computation is still running, asserting it actually observed non-empty progress lines mid-run (not merely after the fact), then checks the finished log for both real gemma-wrapper progress text and the completion marker. cargo test passes in full. Co-Authored-By: Claude Sonnet 5 --- Cargo.toml | 2 +- README.md | 45 +++++++++++++ src/gemma.rs | 182 ++++++++++++++++++++++++++++++++++++++++++++++++---- src/lib.rs | 3 +- src/routes/gemma.rs | 122 +++++++++++++++++++++++++++++++++-- tests/gemma.rs | 154 ++++++++++++++++++++++++++++++++++++++++++-- 6 files changed, 481 insertions(+), 27 deletions(-) (limited to 'src/lib.rs') diff --git a/Cargo.toml b/Cargo.toml index bef2027..805ab58 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ reqwest = { version = "0.12", default-features = false, features = ["rustls-tls" rusqlite = "0.40.2" serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.151" -tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "process"] } +tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "process", "time"] } tower-http = { version = "0.7.1", features = ["request-id", "util"] } ureq = { version = "3.2.1", features = ["json"] } url = "2" diff --git a/README.md b/README.md index 66de220..a8cc7e2 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ A Rust/Axum-based API server for GeneNetwork. | GET | `/traits/{dataset}/{trait}/values` | One trait's per-strain values, either kind. | | POST | `/compute/correlation` | Correlate a trait (STUB: canned data). | | POST | `/compute/gemma` | Map a QTL with GEMMA (real; not feasible yet past ~100K markers -- see below). | +| GET | `/compute/gemma/status/{run_id}` | Poll a `/compute/gemma` call's progress while it's running. | | POST | `/get-test-token` | Local callers only: get a bearer token to test with. | | GET | `/search` | Search traits (free-text; xapian query syntax). | | GET | `/openapi.json` | OpenAPI 3.1 document for all of the above. | @@ -938,6 +939,50 @@ GeneNetwork2's and gn-guile's own convention; see the field's own doc comment in `src/routes/gemma.rs` for what's actually been verified about it.) +#### `/compute/gemma/status/{run_id}` -- polling a run's progress + +Given the endpoint above can genuinely take minutes, pass `?id=` on +the `POST` and poll this on a second connection while it's in flight +to show progress, the same log-tailing shape GeneNetwork2/3 use for +R/qtl (`gn3/computations/streaming.py`, `gn3/api/streaming.py`): the +run's `id` becomes a log file (`{cache_dir}/{id}.log`); gemma-wrapper's +own stderr (its `--json`-mode progress banner, chromosome list, +"Executing: ...", per-step info -- its stdout carries only the one +final JSON record, so there's nothing to stream there) is appended to +it line by line as both the kinship and GWA steps run; once the whole +request finishes, `"GN4: computation complete"` is appended as a +sentinel so a poller can tell "still running" from "done". `run_id` +must be 1-64 ASCII letters/digits/`-`/`_` -- it's a path component, so +this is enforced on both this endpoint and the `?id=` that names it. + +``` +POST /compute/gemma?id=my-run-1 (on one connection; blocks until done) +GET /compute/gemma/status/my-run-1?peak=0 (on another, while the first is in flight) +``` + +```json +{ + "data": { + "run_id": "my-run-1", + "lines": [ + "gemma-wrapper 1.00-pre1 (Ruby 3.3.9) by Pjotr Prins 2017-2024", + "Using GEMMA 0.98.6 (2022-08-05) by Xiang Zhou, Pjotr Prins and team (C) 2012-2022", + "Executing: time -v .../gemma -o ... -g ... -p ... -a ... -gk -outdir ..." + ], + "pointer": 612 + }, + "meta": {"state": "complete", "took_ms": 1, "request_id": "..."}, + "notes": [], + "next": [] +} +``` + +Pass `pointer` back as `?peak=` on the next poll; `lines` is empty +(not an error) when nothing new has been written since. An unknown +`run_id` (never started, or the main request hasn't written its log +yet) is a 404, not an empty response -- genuinely different from +"nothing new yet". + ## OpenAPI `GET /openapi.json` serves an OpenAPI 3.1 document covering every route. diff --git a/src/gemma.rs b/src/gemma.rs index 9c74b30..a42c201 100644 --- a/src/gemma.rs +++ b/src/gemma.rs @@ -12,10 +12,12 @@ //! and `compute` below. use std::io; +use std::io::{Read, Seek, SeekFrom, Write}; use std::path::Path; -use std::process::Output; +use std::process::{Output, Stdio}; use serde_json::Value; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader}; use tokio::process::Command; /// One phenotype value per strain (genotype-file order), or `None` for @@ -72,8 +74,54 @@ pub fn write_pheno_file(path: &Path, values: &TraitValues) -> io::Result<()> { std::fs::write(path, contents) } -async fn run(cmd: &str, args: &[&str]) -> io::Result { - Command::new(cmd).args(args).output().await +/// Run `cmd`, optionally tailing its stderr into `log_path` one line at +/// a time as it runs, and return the same `Output` shape +/// `Command::output()` would have (full stdout, full stderr, exit +/// status) -- callers that don't pass `log_path` see identical +/// behaviour to the plain, non-streaming call it replaces. +/// +/// stderr, not stdout, is what's tailed: gemma-wrapper's own `--json` +/// mode sends all of its human-readable progress (banner, chromosome +/// list, "Executing: ...", per-step info/debug lines) to stderr, and +/// reserves stdout for the one final JSON record, printed once at +/// the very end (`OUTPUT = (options[:json] ? $stderr : $stdout)` in +/// bin/gemma-wrapper) -- so stdout has nothing to stream. +async fn run_streaming(cmd: &str, args: &[&str], log_path: Option<&Path>) -> io::Result { + let mut child = Command::new(cmd) + .args(args) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn()?; + let stdout_handle = child.stdout.take().expect("stdout was piped"); + let stderr_handle = child.stderr.take().expect("stderr was piped"); + + let stdout_task = tokio::spawn(async move { + let mut buf = Vec::new(); + let mut reader = stdout_handle; + let _ = reader.read_to_end(&mut buf).await; + buf + }); + + let log_path = log_path.map(Path::to_path_buf); + let stderr_task = tokio::spawn(async move { + let mut buf = Vec::new(); + let mut lines = BufReader::new(stderr_handle).lines(); + while let Ok(Some(line)) = lines.next_line().await { + if let Some(path) = &log_path { + if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(path) { + let _ = writeln!(f, "{line}"); + } + } + buf.extend_from_slice(line.as_bytes()); + buf.push(b'\n'); + } + buf + }); + + let status = child.wait().await?; + let stdout = stdout_task.await.unwrap_or_default(); + let stderr = stderr_task.await.unwrap_or_default(); + Ok(Output { status, stdout, stderr }) } fn parse_wrapper_output(step: &'static str, output: Output) -> Result { @@ -121,9 +169,10 @@ async fn compute_kinship( genotype_file: &str, pheno_file: &str, snps_file: &str, + log_path: Option<&Path>, ) -> Result { let args = kinship_args(cache_dir, genotype_file, pheno_file, snps_file); - let output = run(gemma_wrapper_cmd, &args) + let output = run_streaming(gemma_wrapper_cmd, &args, log_path) .await .map_err(GemmaError::Io)?; parse_wrapper_output("kinship", output) @@ -155,6 +204,7 @@ async fn compute_gwa( snps_file: &str, lmm: u8, k_json_path: &str, + log_path: Option<&Path>, ) -> Result { let lmm_str = lmm.to_string(); let args = gwa_args( @@ -165,7 +215,7 @@ async fn compute_gwa( &lmm_str, k_json_path, ); - let output = run(gemma_wrapper_cmd, &args) + let output = run_streaming(gemma_wrapper_cmd, &args, log_path) .await .map_err(GemmaError::Io)?; parse_wrapper_output("gwa", output) @@ -229,14 +279,10 @@ fn parse_assoc_file(contents: &str) -> Vec { /// about this between the two steps). async fn extract_archive(cache_dir: &str, archive: &str, dest_dir: &str) -> Result<(), GemmaError> { let archive_path = Path::new(cache_dir).join(archive); - let output = run( + let output = run_streaming( "tar", - &[ - "xJf", - &archive_path.to_string_lossy(), - "-C", - dest_dir, - ], + &["xJf", &archive_path.to_string_lossy(), "-C", dest_dir], + None, ) .await .map_err(GemmaError::Io)?; @@ -327,6 +373,27 @@ fn gwa_args<'a>( /// schema) implements `ToSchema` for `serde_json::Value` itself, but /// `Vec` needs `Value: ComposeSchema`, which it does /// not implement in this utoipa version. +/// `run_id` must be a short token of ASCII letters, digits, `-` or `_` +/// (no path separators or `.`): it is joined straight onto `cache_dir` +/// to name the log file `status` reads back, so an unchecked value +/// would let a caller write/read outside `cache_dir` (the same +/// unchecked-`run_id`-as-path-component GeneNetwork3 does for its own +/// `/api/stream/{run_id}` -- not knowingly replicated here). +pub fn is_valid_run_id(run_id: &str) -> bool { + !run_id.is_empty() + && run_id.len() <= 64 + && run_id + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') +} + +/// The line `compute` appends to the log file once it finishes +/// successfully, so a `status` poller can tell "still running" apart +/// from "done" without needing a separate field -- same convention +/// GeneNetwork3 uses ("Done with GN3 Computation" in gn3/api/rqtl2.py), +/// under this project's own name. +pub const COMPLETION_MARKER: &str = "GN4: computation complete"; + pub async fn compute( gemma_wrapper_cmd: &str, cache_dir: &str, @@ -334,6 +401,7 @@ pub async fn compute( snps_file: &str, trait_values: &TraitValues, lmm: u8, + run_id: Option<&str>, ) -> Result { std::fs::create_dir_all(cache_dir).map_err(GemmaError::Io)?; let unique = format!("{}-{}", std::process::id(), nanos_since_epoch()); @@ -341,6 +409,14 @@ pub async fn compute( write_pheno_file(&pheno_path, trait_values).map_err(GemmaError::Io)?; let pheno_file = pheno_path.to_string_lossy().into_owned(); + // One log file for the whole request (both steps), truncated fresh + // at the start of each run so re-using an id doesn't append stale + // lines from a previous request ahead of this one's. + let log_path = run_id.map(|id| Path::new(cache_dir).join(format!("{id}.log"))); + if let Some(path) = &log_path { + std::fs::write(path, "").map_err(GemmaError::Io)?; + } + let kinship_note = format!( "Kinship: {gemma_wrapper_cmd} {}", kinship_args(cache_dir, genotype_file, &pheno_file, snps_file).join(" ") @@ -351,6 +427,7 @@ pub async fn compute( genotype_file, &pheno_file, snps_file, + log_path.as_deref(), ) .await?; let k_json_path = Path::new(cache_dir).join(format!("{unique}-k.json")); @@ -377,6 +454,7 @@ pub async fn compute( snps_file, lmm, &k_json_path.to_string_lossy(), + log_path.as_deref(), ) .await?; @@ -402,12 +480,50 @@ pub async fn compute( rows.extend(parse_assoc_file(&contents).into_iter().map(Value::Object)); } let _ = std::fs::remove_dir_all(&extract_dir); // best effort; a leftover scratch dir is harmless + + if let Some(path) = &log_path { + if let Ok(mut f) = std::fs::OpenOptions::new().append(true).open(path) { + let _ = writeln!(f, "{COMPLETION_MARKER}"); + } + } + Ok(GemmaOutput { rows: Value::Array(rows), notes: vec![kinship_note, gwa_note], }) } +/// Why `status` (below) couldn't read a run's log. +#[derive(Debug)] +pub enum StatusError { + /// No log file for this `run_id` (unknown id, or the run hasn't + /// written anything yet -- `compute` creates the file before its + /// first subprocess call, but there is a brief window before that). + NotFound, + Io(io::Error), +} + +/// Lines appended to `run_id`'s log since byte offset `peak`, and the +/// new offset to pass as `peak` next time. Mirrors GeneNetwork3's +/// `GET /api/stream/{run_id}?peak=` (gn3/api/streaming.py), stateless +/// in the same way: the caller tracks `peak`, not the server. +pub fn status(cache_dir: &str, run_id: &str, peak: u64) -> Result<(Vec, u64), StatusError> { + let path = Path::new(cache_dir).join(format!("{run_id}.log")); + let mut file = std::fs::File::open(&path).map_err(|e| { + if e.kind() == io::ErrorKind::NotFound { + StatusError::NotFound + } else { + StatusError::Io(e) + } + })?; + file.seek(SeekFrom::Start(peak)).map_err(StatusError::Io)?; + let mut buf = String::new(); + file.read_to_string(&mut buf).map_err(StatusError::Io)?; + let pointer = peak + buf.len() as u64; + let lines = buf.lines().map(str::to_string).collect(); + Ok((lines, pointer)) +} + #[cfg(test)] mod tests { use super::*; @@ -487,4 +603,46 @@ mod tests { ); assert!(!args.contains(&"-gk"), "the GWA step must never carry -gk alongside -lmm"); } + + #[test] + fn is_valid_run_id_accepts_alnum_dash_underscore() { + for ok in ["abc123", "a-b_c", "A1", "x"] { + assert!(is_valid_run_id(ok), "{ok}"); + } + } + + #[test] + fn is_valid_run_id_rejects_path_separators_and_empty() { + for bad in ["", "../etc/passwd", "a/b", "a.b", "a b", &"x".repeat(65)] { + assert!(!is_valid_run_id(bad), "{bad}"); + } + } + + #[test] + fn status_reads_from_peak_and_returns_a_new_pointer() { + let path = std::env::temp_dir().join(format!("gn4-gemma-status-test-{}", std::process::id())); + let cache_dir = path.to_str().unwrap(); + std::fs::create_dir_all(cache_dir).unwrap(); + std::fs::write(Path::new(cache_dir).join("run1.log"), "line one\nline two\n").unwrap(); + + let (lines, pointer) = status(cache_dir, "run1", 0).unwrap(); + assert_eq!(lines, vec!["line one", "line two"]); + + std::fs::OpenOptions::new() + .append(true) + .open(Path::new(cache_dir).join("run1.log")) + .unwrap() + .write_all(b"line three\n") + .unwrap(); + let (more, _) = status(cache_dir, "run1", pointer).unwrap(); + assert_eq!(more, vec!["line three"]); + + std::fs::remove_dir_all(cache_dir).unwrap(); + } + + #[test] + fn status_unknown_run_id_is_not_found() { + let err = status("/tmp", "no-such-gn4-gemma-run-id", 0).unwrap_err(); + assert!(matches!(err, StatusError::NotFound)); + } } diff --git a/src/lib.rs b/src/lib.rs index ab88fff..4d90785 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -78,7 +78,8 @@ pub fn app() -> Router { .routes(routes!(routes::publications::publication_traits)) .routes(routes!(routes::search::search)) .routes(routes!(routes::correlation::correlation)) - .routes(routes!(routes::gemma::compute_gemma)); + .routes(routes!(routes::gemma::compute_gemma)) + .routes(routes!(routes::gemma::gemma_status)); // Registered -- and so reachable and listed in /openapi.json -- unless // GENENETWORK4_TEST_TOKEN switches it off; when registered it decides // per request whether the caller is local. See src/routes/dev.rs. diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index 3df86a7..18423b1 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -1,18 +1,51 @@ //! Compute domain: /compute/gemma invokes gemma-wrapper (and the real //! GEMMA binary it wraps) to map a QTL from a genotype file, a SNP -//! annotation file and a list of trait values. See `crate::gemma` for -//! the invocation itself. +//! annotation file and a list of trait values. `GET +//! /compute/gemma/status/{run_id}` tails that run's progress while it +//! is (or was) in flight, the same shape GeneNetwork2/3 use for R/qtl +//! (gn3/computations/streaming.py, gn3/api/streaming.py): the caller +//! picks a `run_id`, passes it as `?id=` on the POST, and polls the +//! status endpoint with `?peak=` (the byte offset already read) on a +//! second connection while the first is still blocked on the POST. See +//! `crate::gemma` for the invocation and log-writing itself. use axum::Json; +use axum::extract::{Path, Query}; use axum::http::StatusCode; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use crate::auth::AuthToken; use crate::config::Config; use crate::error::{ApiError, Unauthorized}; -use crate::gemma::{self, GemmaError}; +use crate::gemma::{self, GemmaError, StatusError}; use crate::response::{Ctx, Envelope, RequestInfo}; +/// `?id=` on `POST /compute/gemma`: an optional, caller-chosen run id +/// to log this run's progress under and poll back via `GET +/// /compute/gemma/status/{id}`. Omitted entirely, no log is written. +#[derive(Deserialize, utoipa::IntoParams)] +pub struct ComputeGemmaParams { + pub id: Option, +} + +#[derive(Deserialize, utoipa::IntoParams)] +pub struct GemmaStatusParams { + /// Byte offset already read; 0 to read from the start. Echoed back + /// (grown) as `pointer` in the response -- pass that next time. + pub peak: Option, +} + +#[derive(Serialize, utoipa::ToSchema)] +pub struct GemmaStatus { + pub run_id: String, + /// New lines of gemma-wrapper's stderr (its progress output under + /// --json) since `peak`. The last line, once the run has finished, + /// is the completion marker (`gemma::COMPLETION_MARKER`). + pub lines: Vec, + /// The new byte offset; pass this back as `peak` next poll. + pub pointer: u64, +} + #[derive(Deserialize, utoipa::ToSchema)] pub struct GemmaRequest { /// Path to a BIMBAM genotype file (plain text or gzipped), passed @@ -41,17 +74,20 @@ pub struct GemmaRequest { description = "Runs gemma-wrapper's K-matrix step, then its LMM \ association step, over the given genotype and SNP annotation files and \ trait values, and returns the resulting rows of GEMMA's own \ -.assoc.txt output.", +.assoc.txt output. Pass ?id= to log progress for GET \ +/compute/gemma/status/{id} to poll concurrently.", + params(ComputeGemmaParams), request_body = GemmaRequest, responses( (status = 200, description = "Mapped QTL rows from GEMMA's .assoc.txt output, as a JSON array of row objects", body = Envelope), Unauthorized, - (status = 422, description = "lmm not one of the known-working values (1, 2, 3, 4, 9)", body = ApiError), + (status = 422, description = "lmm not one of the known-working values (1, 2, 3, 4, 9), or id not alnum/-/_ (max 64 chars)", body = ApiError), (status = 502, description = "gemma-wrapper or GEMMA failed", body = ApiError) ))] pub async fn compute_gemma( ctx: Ctx, _token: AuthToken, + Query(params): Query, Json(request): Json, ) -> Result>, ApiError> { let rid = ctx.request_info(); @@ -71,6 +107,18 @@ pub async fn compute_gemma( ) .with_request_id(rid)); } + if let Some(id) = ¶ms.id { + if !gemma::is_valid_run_id(id) { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_run_id", + "Invalid id", + "id must be 1-64 ASCII letters, digits, '-' or '_'.".to_string(), + "compute_gemma", + ) + .with_request_id(rid)); + } + } let config = Config::load(); gemma::compute( @@ -80,6 +128,7 @@ pub async fn compute_gemma( &request.snps_file, &request.trait_values, lmm, + params.id.as_deref(), ) .await .map(|output| { @@ -94,6 +143,67 @@ pub async fn compute_gemma( .map_err(|e| gemma_error_to_api_error(e, rid)) } +#[utoipa::path(get, path = "/compute/gemma/status/{run_id}", + summary = "Poll a running (or finished) /compute/gemma call's progress", + description = "Returns the lines gemma-wrapper has written to stderr \ +for this run_id since byte offset `peak`, and a new `pointer` to pass as \ +`peak` next time. Call this on a second connection while the POST is \ +still in flight, the same tail-the-log-file shape GeneNetwork2/3 use for \ +R/qtl.", + params(("run_id" = String, Path, description = "The id passed as ?id= on the POST"), GemmaStatusParams), + responses( + (status = 200, description = "New log lines and the new pointer", body = Envelope), + Unauthorized, + (status = 404, description = "No run with this id (unknown, or not started yet)", body = ApiError), + (status = 422, description = "run_id not alnum/-/_ (max 64 chars)", body = ApiError) + ))] +pub async fn gemma_status( + ctx: Ctx, + _token: AuthToken, + Path(run_id): Path, + Query(params): Query, +) -> Result>, ApiError> { + let rid = ctx.request_info(); + if !gemma::is_valid_run_id(&run_id) { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_run_id", + "Invalid run_id", + "run_id must be 1-64 ASCII letters, digits, '-' or '_'.".to_string(), + "gemma_status", + ) + .with_request_id(rid)); + } + let config = Config::load(); + let peak = params.peak.unwrap_or(0); + gemma::status(&config.gemma_cache_dir, &run_id, peak) + .map(|(lines, pointer)| { + Json(ctx.envelope(GemmaStatus { + run_id: run_id.clone(), + lines, + pointer, + })) + }) + .map_err(|e| match e { + StatusError::NotFound => ApiError::new( + StatusCode::NOT_FOUND, + "run_not_found", + "Run not found", + format!("No run with id '{run_id}' (unknown, or not started yet)."), + "gemma_status", + ) + .with_request_id(rid), + StatusError::Io(err) => ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Internal error", + err.to_string(), + "gemma_status", + ) + .with_request_id(rid), + }) +} + fn gemma_error_to_api_error(error: GemmaError, rid: RequestInfo) -> ApiError { ApiError::new( StatusCode::BAD_GATEWAY, diff --git a/tests/gemma.rs b/tests/gemma.rs index 9aa58d7..0eef57a 100644 --- a/tests/gemma.rs +++ b/tests/gemma.rs @@ -42,22 +42,93 @@ async fn compute_gemma_maps_a_qtl_from_the_bxd_fixtures() { return; }; + let run_id = format!( + "test-{}", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + ); let body = serde_json::json!({ "genotype_file": test_data_path("BXD_geno.txt.gz"), "snps_file": test_data_path("BXD_snps.txt"), "trait_values": bxd_trait_values(), }); - let response = common::post_json_with_token( - "POST /compute/gemma", - "/compute/gemma", - &token, - &body, - ) - .await; + + // Run the POST (which blocks for the whole ~19s computation) on its + // own task, so this test can poll the status endpoint on a second + // connection while it is still in flight -- the real shape a + // browser would use, not just a read of the finished log. + let post_token = token.clone(); + let post_run_id = run_id.clone(); + let post_handle = tokio::spawn(async move { + common::post_json_with_token( + "POST /compute/gemma", + &format!("/compute/gemma?id={post_run_id}"), + &post_token, + &body, + ) + .await + }); + + // Poll until something besides the empty initial log file shows up, + // or the main request finishes first (a fast machine might not + // catch it mid-run; either way, a fresh log with the kinship step's + // output should exist very soon after the POST starts). + let mut saw_progress_while_running = false; + let mut peak = 0u64; + for _ in 0..40 { + if post_handle.is_finished() { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(500)).await; + let response = + common::get_with_token("GET /compute/gemma/status", &format!("/compute/gemma/status/{run_id}?peak={peak}"), &token) + .await; + if response.status() != StatusCode::OK { + continue; // log file not created yet + } + let bytes = response.into_body().collect().await.unwrap().to_bytes(); + let status: Value = common::data(&bytes); + peak = status["pointer"].as_u64().unwrap_or(peak); + if !status["lines"].as_array().unwrap().is_empty() { + saw_progress_while_running = true; + } + } + assert!( + saw_progress_while_running, + "expected at least one non-empty status poll while the computation was still running" + ); + + let response = post_handle.await.unwrap(); let status = response.status(); let bytes = response.into_body().collect().await.unwrap().to_bytes(); assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&bytes)); + // After completion, the log carries the completion marker, and + // real gemma-wrapper progress text (not just the one line written + // at log creation). + let final_response = common::get_with_token( + "GET /compute/gemma/status (final)", + &format!("/compute/gemma/status/{run_id}?peak=0"), + &token, + ) + .await; + assert_eq!(final_response.status(), StatusCode::OK); + let final_bytes = final_response.into_body().collect().await.unwrap().to_bytes(); + let final_status: Value = common::data(&final_bytes); + let lines: Vec<&str> = final_status["lines"] + .as_array() + .unwrap() + .iter() + .map(|l| l.as_str().unwrap()) + .collect(); + assert!(lines.contains(&"GN4: computation complete"), "{lines:?}"); + assert!( + lines.iter().any(|l| l.contains("GEMMA")), + "expected real gemma-wrapper progress text in the log: {lines:?}" + ); + let rows: Value = common::data(&bytes); let rows = rows.as_array().expect("data is a JSON array of rows"); assert!(!rows.is_empty(), "expected at least one mapped marker"); @@ -135,3 +206,72 @@ async fn compute_gemma_requires_a_token() { .unwrap(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); } + +#[tokio::test] +async fn compute_gemma_rejects_an_invalid_run_id() { + let Some(token) = common::auth_token().await else { + eprintln!("skipping compute_gemma_rejects_an_invalid_run_id: no token (see docs/gn-auth.md)"); + return; + }; + + let body = serde_json::json!({ + "genotype_file": test_data_path("BXD_geno.txt.gz"), + "snps_file": test_data_path("BXD_snps.txt"), + "trait_values": [1.0, 2.0], + }); + let response = common::post_json_with_token( + "POST /compute/gemma (bad id)", + "/compute/gemma?id=../etc/passwd", + &token, + &body, + ) + .await; + assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY); +} + +#[tokio::test] +async fn gemma_status_unknown_run_id_returns_404() { + let Some(token) = common::auth_token().await else { + eprintln!("skipping gemma_status_unknown_run_id_returns_404: no token (see docs/gn-auth.md)"); + return; + }; + let response = common::get_with_token( + "GET /compute/gemma/status (unknown)", + "/compute/gemma/status/no-such-gn4-gemma-run?peak=0", + &token, + ) + .await; + assert_eq!(response.status(), StatusCode::NOT_FOUND); +} + +#[tokio::test] +async fn gemma_status_rejects_an_invalid_run_id() { + let Some(token) = common::auth_token().await else { + eprintln!("skipping gemma_status_rejects_an_invalid_run_id: no token (see docs/gn-auth.md)"); + return; + }; + let response = common::get_with_token( + "GET /compute/gemma/status (bad id)", + "/compute/gemma/status/..%2Fetc%2Fpasswd?peak=0", + &token, + ) + .await; + assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY); +} + +#[tokio::test] +async fn gemma_status_requires_a_token() { + let request = axum::http::Request::builder() + .method(axum::http::Method::GET) + .uri("/compute/gemma/status/some-run?peak=0") + .extension(axum::extract::ConnectInfo(std::net::SocketAddr::from(( + [127, 0, 0, 1], + 40000, + )))) + .body(axum::body::Body::empty()) + .unwrap(); + let response = tower::ServiceExt::oneshot(genenetwork4::app(), request) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); +} -- cgit 1.4.1