diff --git a/migrations/school/20260917000003_podcast.sql b/migrations/school/20260917000003_podcast.sql new file mode 100644 index 0000000..1a96d8b --- /dev/null +++ b/migrations/school/20260917000003_podcast.sql @@ -0,0 +1,84 @@ +-- The podcast job table: the backend-owned record of every episode the podcast +-- service was asked to produce. +-- +-- WHERE THIS FILE BELONGS: `migrations/school/` in the backend repo, applied by +-- `Migrator::new(migrations/school)` to the template at boot and to every school +-- database at create. APPEND-ONLY relative to the existing school migrations: it +-- creates one new table and touches none of them. +-- +-- WHY THE BACKEND HOLDS IT: until now the job record lived only in the service's +-- own volume (`jobs.py`'s per-job JSON files), which made a service restart or a +-- wiped volume lose every in-flight job the caller was polling — and the produced +-- mp3 with it. The backend now mints the job id, writes the row before it +-- dispatches, answers `podcast.status`/`podcast.result` from it, and stores the +-- uploaded audio in the school's own blob directory. The service reports each +-- transition back over the bridge (`podcast.report`) and uploads the finished +-- mp3. A service that vanishes therefore costs liveness — the read side projects +-- a job nobody is updating as failed after a bounded window — never the record. +-- +-- NO `school` COLUMN: each school already lives in its own database, so the +-- tenant IS the database (the same rule every `zeka_*`/`rag_*` table follows). +-- The row's tenancy is the pair (this database, `user_id`), and the web layer +-- checks both: a foreign user's id reads as absent, exactly like `rag_thread`. +-- +-- Translation rules inherited from the school schema's other parts: +-- * entity ids are app-minted uuid v7 (`domain::monotonic_id::next_uuid`), +-- never a DB default; +-- * timestamps are BIGINT unix-ms UTC, never `timestamptz`; +-- * FKs point outward, one direction only, all `ON DELETE NO ACTION`. +-- +-- The state vocabulary and the transition table are the service's own +-- (`jobs.py`): queued -> running -> done|failed|cancelled, plus +-- queued -> cancelled|failed. The CHECK is the backstop under the Rust enum, +-- which is the source. + +CREATE TABLE podcast_job ( + id uuid PRIMARY KEY, + -- Who submitted it. The ownership guard: every read door answers 404 for a + -- row whose user_id is not the caller. + user_id uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + -- The source the service narrates, verbatim as submitted — the backend id + -- of a course note today. No FK: `source_id` is the service's own handle on + -- shared media, and the backend cannot say what it names. + source_id TEXT NOT NULL, + -- The narration format. NULL until a report resolves it: the service applies + -- its own default (and refuses formats that need an LLM key it lacks), so + -- this column records the service's verdict, never a guess of ours. + format TEXT NULL, + -- 'queued' | 'running' | 'done' | 'failed' | 'cancelled' (jobs.py STATES). + state TEXT NOT NULL + CHECK (state IN ('queued', 'running', 'done', 'failed', 'cancelled')), + -- The pipeline stage inside `running` (the service's SIMULATED_STAGES or its + -- real ones); '' outside it. + stage TEXT NOT NULL DEFAULT '', + -- Fraction complete, 0.0..=1.0. The service rounds to 4 decimals; the + -- CHECK is the bound, not the rounding. + progress DOUBLE PRECISION NOT NULL DEFAULT 0 + CHECK (progress BETWEEN 0 AND 1), + -- Set on `failed`: the service's own short error code, or `interrupted` when + -- the backend projected a dead job or the dispatch never reached a worker. + error_code TEXT NULL, + -- The uploaded episode, when one landed (see `web::podcast`'s ingest + -- handshake): the blob key under the school's files root, plus the metadata + -- the audio door replays as headers. All NULL until an upload. + audio_key TEXT NULL, + audio_name TEXT NULL, + audio_type TEXT NULL, + audio_bytes BIGINT NULL, + duration_secs DOUBLE PRECISION NULL, + -- The service's own ETA from the submit receipt. Drives the read-side + -- staleness window (a long job is not projected dead mid-flight) and is + -- echoed in the submit receipt. + eta_secs BIGINT NULL, + created_at BIGINT NOT NULL, + updated_at BIGINT NOT NULL, + -- A deferred upload's key is set in the same statement that reports it, so + -- "done" and "has audio" can never disagree: the report that says done + -- requires `audio_key` to be non-NULL. + CONSTRAINT podcast_job_done_has_audio + CHECK (state <> 'done' OR audio_key IS NOT NULL) +); + +-- The list view's sort key (a user's own jobs, newest first) and the sweep's. +CREATE INDEX podcast_job_user_created ON podcast_job (user_id, created_at); +CREATE INDEX podcast_job_created ON podcast_job (created_at); diff --git a/src/ai/insight.rs b/src/ai/insight.rs index 2bc0409..0e3f25b 100644 --- a/src/ai/insight.rs +++ b/src/ai/insight.rs @@ -329,7 +329,7 @@ pub async fn serve( )); } let db = &tenant.db; - let answer = match capability { + match capability { AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY => { let request: SummaryWriteRequest = decode(payload)?; encode(&db::insight::write_summaries(db, request.rows).await.map_err(refusal)?) @@ -374,14 +374,11 @@ pub async fn serve( // `scope_of` matched above, so the table and this match agree; the // arm exists so a table entry without an operation is a compile-time // miss instead of a runtime surprise. - other => { - return Err(( - "unknown_capability", - format!("the backend serves no `{other}` operation"), - )); - } - }; - answer + other => Err(( + "unknown_capability", + format!("the backend serves no `{other}` operation"), + )), + } } /// Decode one payload into the operation's own type. A payload that does not diff --git a/src/ai/mod.rs b/src/ai/mod.rs index 4cc4b8d..6350677 100644 --- a/src/ai/mod.rs +++ b/src/ai/mod.rs @@ -13,10 +13,12 @@ //! //! * [`api`] — which REST paths a service may read back through the bridge //! * [`protocol`] — frames on the wire +//! * [`capability`] — the capabilities the **backend** serves, and their scopes //! * [`chat`] — the JSON payloads carried for the `chat.reply` capability //! * [`rag`] — the `rag.index` payloads, and the course-note dispatch behind them //! * [`rag_chat`] — the `rag.chat` payloads: a scoped question and the citations behind its answer -//! * [`podcast`] — the `podcast.*` job payloads, and the relay behind them +//! * [`podcast`] — the `podcast.*` job payloads, the relay behind submit/cancel, +//! and the job-state report the service calls back //! * [`server`] — the listener, handshake, and [`server::AiBridge::dispatch`] //! * [`registry`] — who is connected here, and who gets the next request //! * [`tls`] — the listener's certificate @@ -24,10 +26,11 @@ //! The transport is generic; the features land on top of it. So far that is //! the chatbot (`web::chatbot`), which routes on the `chat.reply` capability, //! course-note indexing (`web::course_notes`), which routes on `rag.index`, -//! and the podcast relay (`web::podcast`), which routes on the four -//! `podcast.*` capabilities and streams the audio they produce. +//! and the podcast relay (`web::podcast`), which dispatches `podcast.submit`/ +//! `podcast.cancel`, serves `podcast.report`, and streams the ingested audio. pub mod api; +pub mod capability; pub mod chat; pub mod error; pub mod insight; diff --git a/src/ai/podcast.rs b/src/ai/podcast.rs index 160ef5c..00ba3e9 100644 --- a/src/ai/podcast.rs +++ b/src/ai/podcast.rs @@ -1,143 +1,117 @@ -//! Payload contract for the `podcast.*` capabilities, and the dispatch behind -//! them. +//! Payload contract for the `podcast.*` capabilities and the audio ingest — +//! both directions of the podcast seam. //! //! The podcast service turns one stored source — a course note's PDF — into an -//! audio episode, and that is a *job*: submit enqueues it, status and result -//! read it back minutes later, cancel stops it. So these are four verbs on one -//! record that the **service** owns, not four steps of one backend request, -//! and the backend relays each call to the worker declaring the matching -//! capability. +//! audio episode. Since 2026-09-17 the **backend owns that job's record**: the +//! submit door mints the job id, writes the row, and then dispatches +//! `podcast.submit` with that id; the service reports every transition back +//! through the client-initiated `podcast.report` capability, and uploads the +//! finished mp3 as raw bytes on a `BlobUploadRequest` stream. Status and +//! result answer from the backend's own row — they are not capabilities any +//! more, because a service restart (or a wiped service volume) must cost +//! nothing but the liveness the read-side projection already covers. //! -//! Nothing here is spawned, unlike [`chat`](crate::ai::chat) and -//! [`rag_chat`](crate::ai::rag_chat): every one of the four calls answers -//! immediately — a queued receipt, a status snapshot, a finished job, a cancel -//! verdict — while the pipeline itself runs in the service's own worker pool. -//! That is also why the four ride the bridge's ordinary request deadline -//! ([`AI_DEFAULT_REQUEST_TIMEOUT_SECS`](crate::constant::AI_DEFAULT_REQUEST_TIMEOUT_SECS)) -//! rather than a per-capability one: no call waits on a model. +//! What remains **server-initiated** are the two calls that must reach a live +//! worker: //! -//! Tenancy is the transport's job: [`crate::ai::server`] stamps the caller's -//! school onto every `hab/2` request; it does **not** verify the echo on -//! replies (the bridge correlates answers by frame id alone), so the wall is -//! the stamp plus the service's own honesty — and it holds even though the -//! job records themselves live outside the backend's databases. +//! * [`submit`] — `podcast.submit`, whose payload carries the backend-minted +//! `job_id` and the submitting `user_id` (the service stores both; its own +//! record is keyed by the id the backend will keep asking about). +//! * [`cancel`] — `podcast.cancel`, unchanged: a write on the service's queue, +//! and the capability is what decides whether a deployment offers the door. //! -//! The produced audio does not cross the bridge. `podcast.result` answers an -//! `audio_id` that is a path *relative* to the service's -//! `PODCAST_OUTPUT_ROOT`, which the deployment points at the school's own -//! files directory on this host (`FILES_PATH/`, the same volume every -//! upload lands in); the browser then fetches it from `GET /podcast/audio`, -//! which resolves it under that directory and refuses everything that would -//! escape it — see [`crate::web::podcast`]. +//! Tenancy is the transport's job: [`crate::ai::server`] stamps the caller's +//! school onto every `hab/2` request and resolves the frame's school on every +//! client-initiated one; this module never re-derives a school. use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; +use serde_json::Value; -use crate::ai::{AiBridge, AiError}; +use crate::ai::AiBridge; +use crate::ai::error::AiError; +use crate::database::Database; +use crate::domain::podcast_job::PodcastJobId; +use crate::service::podcast_job::{PodcastRefusal, ReportInput}; use crate::tenant::Slug; /// The capability strings, re-exported so a reader of the payload contract /// finds them next to the payloads — the same shape as /// [`crate::ai::rag`](crate::ai::rag). pub use crate::constant::{ - AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_RESULT_CAPABILITY, AI_PODCAST_STATUS_CAPABILITY, - AI_PODCAST_SUBMIT_CAPABILITY, + AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_REPORT_CAPABILITY, AI_PODCAST_SUBMIT_CAPABILITY, }; -/// What the backend asks a podcast service to start. +/// What the backend asks a podcast service to start. The `job_id` is the +/// backend's own minted id — the service keys its record by it and echoes it +/// in every report, so the two stores can never disagree about which job a +/// record is. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PodcastSubmitPayload { - /// The backend's record id for the source to narrate — a course note id, - /// never a file path. The service resolves it against its own media root, - /// which the deployment points at this backend's files volume. + pub job_id: String, pub source_id: String, - /// Which narration to produce. `duz_okuma` (plain reading) is the - /// service's default and the only one that needs no LLM key; - /// `tek_ogretici` and `ogrenci_hoca` are refused by the service with - /// `llm_unavailable` when the key is missing. Sent verbatim — the - /// service's closed set is what validates it. - #[serde(skip_serializing_if = "Option::is_none")] + /// `None` means the service applies its own default (`duz_okuma` today). + #[serde(default, skip_serializing_if = "Option::is_none")] pub format: Option, + /// The submitting user, so the service's own record carries the same + /// owner the backend row does. + pub user_id: String, } -/// The receipt for an accepted job, echoed straight to the caller. +/// The receipt for an accepted job. `job_id` must echo the request's — the +/// backend checks, because the id is the only handle it will keep polling by. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PodcastSubmitReply { - /// The id the service minted for the job. Every later call names it. pub job_id: String, - /// The job's state right after submission (`queued`). + /// `queued` on a fresh job. pub state: String, - /// The service's own estimate of how long the job will take, in seconds. + /// The service's own estimate of the job's duration, in seconds. pub eta_secs: i64, } -/// What the backend asks about one job's progress. +/// What the backend asks to cancel. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct PodcastStatusPayload { +pub struct PodcastCancelPayload { pub job_id: String, } -/// One job's state, as of now. -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct PodcastStatusReply { - pub job_id: String, - /// `queued`, `running`, `done`, `failed` or `cancelled` — the service's own - /// vocabulary, passed through rather than mapped, so a state added there - /// needs no change here. - pub state: String, - /// The pipeline stage the job is in, as prose from the service. - pub stage: String, - /// Fraction complete, `0.0..=1.0`. - pub progress: f64, - /// The failure code when `state` is `failed`, null otherwise. - #[serde(default)] - pub error_code: Option, -} - -/// What the backend asks for a finished job's artifacts. +/// The verdict on a cancel: `cancelled` is "this call cancelled something", +/// not "the job is cancelled" — cancelling an already-finished job answers +/// `false`, and so does cancelling one that was already cancelled. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct PodcastResultPayload { +pub struct PodcastCancelReply { pub job_id: String, + pub cancelled: bool, } -/// A finished job's artifacts. Only a `done` job answers this: the service -/// refuses any other state with `not_ready`, so nothing here is nullable — a -/// reply missing `audio_id` is an unreadable answer, not a half-finished job. +/// One state report from the service — the payload of a client-initiated +/// [`AI_PODCAST_REPORT_CAPABILITY`] call. The service sends one per +/// transition, in order (it awaits each answer before sending the next), and +/// echoes the job's own identity so the backend can refuse a report that +/// describes a different job than the row holds. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct PodcastResultReply { +pub struct PodcastReportPayload { pub job_id: String, - /// The produced audio, as a path **relative** to `PODCAST_OUTPUT_ROOT` on - /// this host. Never absolute, never containing `..` — and - /// [`crate::web::podcast`] refuses one that is, whatever the service sent. - pub audio_id: String, - /// The audio's length in seconds. - pub duration_secs: f64, - /// The script the narration was read from. - pub script_id: String, - /// One entry per produced chapter, when the job was sliced into several; - /// usually `[audio_id]`. + pub source_id: String, #[serde(default)] - pub audio_ids: Vec, - /// One entry per script the audio was aligned to. + pub format: Option, + pub user_id: String, + /// `queued` | `running` | `done` | `failed` | `cancelled`. + pub state: String, #[serde(default)] - pub script_ids: Vec, - /// The narration format the job was produced with. - pub format: String, -} - -/// What the backend asks to cancel. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct PodcastCancelPayload { - pub job_id: String, + pub stage: String, + #[serde(default)] + pub progress: f64, + #[serde(default)] + pub error_code: Option, } -/// The verdict on a cancel: `cancelled` is "this call cancelled something", -/// not "the job is cancelled" — cancelling an already-finished job answers -/// `false`, and so does cancelling one that was already cancelled. +/// The answer to one report. `stored` is always `true` on an `Ok` — an +/// unstored report is a refusal, never a quiet success. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct PodcastCancelReply { +pub struct PodcastReportReply { pub job_id: String, - pub cancelled: bool, + pub stored: bool, } /// Start one job. `Err` is a short, stable code — see [`failure_code`]. @@ -149,24 +123,6 @@ pub async fn submit( dispatch(bridge, slug, AI_PODCAST_SUBMIT_CAPABILITY, payload).await } -/// Read one job's progress. -pub async fn status( - bridge: &AiBridge, - slug: &Slug, - payload: PodcastStatusPayload, -) -> Result { - dispatch(bridge, slug, AI_PODCAST_STATUS_CAPABILITY, payload).await -} - -/// Read one finished job's artifacts. -pub async fn result( - bridge: &AiBridge, - slug: &Slug, - payload: PodcastResultPayload, -) -> Result { - dispatch(bridge, slug, AI_PODCAST_RESULT_CAPABILITY, payload).await -} - /// Cancel one job. pub async fn cancel( bridge: &AiBridge, @@ -176,14 +132,155 @@ pub async fn cancel( dispatch(bridge, slug, AI_PODCAST_CANCEL_CAPABILITY, payload).await } +/// Handle one client-initiated `podcast.report` call: decode the payload, +/// hand it to the workflow layer (which owns every check), and answer the +/// reply payload — or the flat `(code, message)` refusal the bridge frames. +/// +/// The decode is deliberately strict: a payload that does not fit +/// [`PodcastReportPayload`] is `invalid_payload`, never coerced into a +/// half-filled report. +pub async fn report(db: &Database, payload: Value) -> Result { + let report: PodcastReportPayload = serde_json::from_value(payload).map_err(|err| { + ( + "invalid_payload", + format!("the report payload does not fit the contract: {err}"), + ) + })?; + let input = ReportInput { + job_id: &report.job_id, + source_id: &report.source_id, + format: report.format.as_deref(), + user_id: &report.user_id, + state: &report.state, + stage: &report.stage, + progress: report.progress, + error_code: report.error_code.as_deref(), + }; + match crate::service::podcast_job::report(db, &input).await { + Ok(job) => Ok(serde_json::to_value(PodcastReportReply { + job_id: job.get_id().key(), + stored: true, + }) + .expect("a report reply is always encodable")), + Err(refusal) => Err((refusal.code(), refusal.message())), + } +} + +/// A [`PodcastRefusal`] as the capability frame's flat `(code, message)`. +pub fn refusal(refusal: &PodcastRefusal) -> (&'static str, String) { + (refusal.code(), refusal.message()) +} + +/// Ingest one uploaded episode: validate the frame's metadata, check the job, +/// read exactly `size` bytes into a temp file under the school's blob root, +/// rename it into place, and stamp the row. +/// +/// `files_root` is **the school's own** directory (the caller resolves the +/// slug); the file lands under its `podcast/` subdirectory, keyed by the job +/// id, which is what the job row's own `audio_key` then publishes. +/// +/// The order is the point, and the same one the HTTP doors hold: a refusal +/// must cost the sender nothing, so metadata and the job's existence are +/// checked before a byte is read; the bytes are complete on disk (renamed, +/// never half-written) before the row names them; and a row write that finds +/// the job gone deletes the file it just stored rather than leaving an orphan. +pub async fn ingest( + db: &Database, + files_root: &std::path::Path, + request: &crate::ai::protocol::BlobUploadRequest, + body: &mut R, +) -> Result<(String, u64), PodcastRefusal> +where + R: tokio::io::AsyncRead + Unpin, +{ + use tokio::io::AsyncWriteExt as _; + + crate::service::podcast_job::validate_audio( + &request.name, + &request.content_type, + request.size, + )?; + let id = PodcastJobId::from_key(&request.job_id); + let Some(job) = crate::db::podcast_job::read(db, &id).await? else { + return Err(PodcastRefusal::UnknownJob); + }; + if job.is_expired() { + return Err(PodcastRefusal::Expired); + } + + let key = crate::service::podcast_job::audio_key(&id, &request.name, &request.content_type); + let dir = files_root.join("podcast"); + tokio::fs::create_dir_all(&dir).await.map_err(|err| { + PodcastRefusal::Unavailable(format!("could not create the podcast blob directory: {err}")) + })?; + let temp = dir.join(format!(".upload-{}.tmp", crate::domain::monotonic_id::next_uuid())); + let mut file = tokio::fs::File::create(&temp).await.map_err(|err| { + PodcastRefusal::Unavailable(format!("could not open the upload's temp file: {err}")) + })?; + + let mut remaining = request.size; + let mut buf = [0u8; 64 * 1024]; + while remaining > 0 { + let want = remaining.min(buf.len() as u64) as usize; + let read = match tokio::io::AsyncReadExt::read(body, &mut buf[..want]).await { + Ok(0) => { + let _ = tokio::fs::remove_file(&temp).await; + return Err(PodcastRefusal::InvalidPayload( + "the stream ended before `size` bytes arrived".to_string(), + )); + } + Ok(n) => n, + Err(err) => { + let _ = tokio::fs::remove_file(&temp).await; + return Err(PodcastRefusal::Unavailable(format!( + "reading the upload failed: {err}" + ))); + } + }; + if let Err(err) = file.write_all(&buf[..read]).await { + let _ = tokio::fs::remove_file(&temp).await; + return Err(PodcastRefusal::Unavailable(format!( + "writing the upload failed: {err}" + ))); + } + remaining -= read as u64; + } + file.flush() + .await + .map_err(|err| PodcastRefusal::Unavailable(format!("flushing the upload failed: {err}")))?; + drop(file); + let final_path = files_root.join(&key); + tokio::fs::rename(&temp, &final_path).await.map_err(|err| { + PodcastRefusal::Unavailable(format!("could not move the upload into place: {err}")) + })?; + + match crate::service::podcast_job::set_audio( + db, + &id, + &key, + &request.name, + &request.content_type, + request.size as i64, + request.duration_secs, + ) + .await + { + Ok(Some(_)) => Ok((key, request.size)), + // The job vanished between the check above and the row write: take the + // bytes back out rather than leaving a file nothing names. + Ok(None) => { + let _ = tokio::fs::remove_file(&final_path).await; + Err(PodcastRefusal::UnknownJob) + } + Err(err) => { + let _ = tokio::fs::remove_file(&final_path).await; + Err(err.into()) + } + } +} + /// One `podcast.*` round trip: encode, dispatch, decode. Every capability /// travels this path, so the encode/decode failure vocabulary is written once. -/// -/// The reply is decoded into the *typed* contract rather than handed back as -/// [`serde_json::Value`]: the service is a trust boundary, and a field the -/// backend then acts on (above all `audio_id`, which becomes a path under a -/// school's files directory) must exist and be a string before anything uses -/// it. async fn dispatch( bridge: &AiBridge, slug: &Slug, diff --git a/src/ai/server.rs b/src/ai/server.rs index 5e343d8..d94674b 100644 --- a/src/ai/server.rs +++ b/src/ai/server.rs @@ -646,12 +646,7 @@ async fn serve_upload( // sender so its write stops rather than filling a stream nobody // reads. let _ = recv.stop(1u32.into()); - upload_refusal( - request.id.clone(), - request.school.clone(), - &code, - message, - ) + upload_refusal(request.id.clone(), request.school.clone(), code, message) } }; if let Err(e) = write_frame(send, &response).await { @@ -1092,7 +1087,7 @@ async fn serve_capability(inner: &Inner, request: CapabilityRequest) -> Capabili let call = capability::serve( &request.capability, tenant.as_ref(), - &control, + control, &request.payload, ); match tokio::time::timeout(inner.request_timeout, call).await { diff --git a/src/db/podcast_job.rs b/src/db/podcast_job.rs new file mode 100644 index 0000000..11872b8 --- /dev/null +++ b/src/db/podcast_job.rs @@ -0,0 +1,450 @@ +//! The `podcast_job` table: one row per submitted episode, written by the +//! submit door before it dispatches and updated by the service's own +//! `podcast.report` calls. The entity, its state enum and the read-side +//! projection live in [`crate::domain::podcast_job`]; this module is where the +//! rows are read and written. +//! +//! Every write here is a single conditional statement, never a read-then-write: +//! the report path passes the state it validated against (`from`) and matches +//! zero rows when a concurrent cancel moved the row first — the caller re-reads +//! and answers what actually happened. The transition *table* therefore lives +//! in exactly one place (the domain enum); SQL only guards the race. +//! +//! `done` can never be stored without an audio key: the column CHECK +//! (`podcast_job_done_has_audio`) backstops the service layer's refusal, so a +//! result door can trust every `done` row to name a blob. + +use crate::database::Database; +use crate::db::page::PagedList; +use crate::domain::podcast_job::{PodcastJob, PodcastJobId, PodcastJobState}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; +use sqlx::query_as; + +/// Write one freshly minted job. The id and timestamps are the caller's — the +/// service is handed the id this statement stores, so the row and the +/// service's record can never start out disagreeing. +pub async fn insert(db: &Database, job: &PodcastJob) -> Result { + Ok(query_as!( + PodcastJob, + "INSERT INTO podcast_job (id, user_id, source_id, format, state, stage, progress, \ + error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, \ + eta_secs, created_at, updated_at) \ + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $15) \ + RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", \ + source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, \ + audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \ + created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", + job.get_id().uuid(), + job.get_user_id().uuid(), + job.get_source_id(), + job.get_format(), + job.get_state().as_str(), + job.get_stage(), + job.get_progress(), + job.get_error_code(), + job.get_audio_key(), + job.get_audio_name(), + job.get_audio_type(), + job.get_audio_bytes(), + job.get_duration_secs(), + job.get_eta_secs(), + job.get_created_at().as_millis(), + ) + .fetch_one(db) + .await?) +} + +/// Read one job by id, whoever owns it — the report path only, which has +/// already checked that the reporting user is the row's own. +pub async fn read(db: &Database, id: &PodcastJobId) -> Result, AppError> { + Ok(query_as!( + PodcastJob, + "SELECT id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", \ + source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, \ + audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \ + created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\" \ + FROM podcast_job WHERE id = $1", + id.uuid(), + ) + .fetch_optional(db) + .await?) +} + +/// Read a job only if `user` owns it — a foreign id reads as absent, so every +/// HTTP door answers 404 rather than leaking that it exists. The filter is in +/// the statement, not applied after the read, so the row never leaves the +/// database on a foreign caller's behalf. +pub async fn read_for( + db: &Database, + id: &PodcastJobId, + user: &UserId, +) -> Result, AppError> { + Ok(query_as!( + PodcastJob, + "SELECT id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", \ + source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, \ + audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \ + created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\" \ + FROM podcast_job WHERE id = $1 AND user_id = $2", + id.uuid(), + user.uuid(), + ) + .fetch_optional(db) + .await?) +} + +/// A user's jobs, newest first — the sort `podcast_job_user_created` exists +/// for. +pub async fn list_for_user( + db: &Database, + user: &UserId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new( + "podcast_job WHERE user_id = $1", + "ORDER BY created_at DESC, id DESC", + ) + .bind(user.uuid()) + .run(limit, offset, db) + .await +} + +/// Apply one validated report: `from` is the state the service layer read and +/// checked the transition against, and the statement moves the row only if it +/// still holds that state. `None` therefore means either the row is gone or a +/// concurrent write (a cancel, another report) moved it first — the caller +/// re-reads and answers the truth. +/// +/// `format` fills the column once and never rewrites it: the service's default +/// resolution arrives on the first report, and a later report disagreeing with +/// it is refused by the service layer, not silently stored. +#[allow(clippy::too_many_arguments)] +pub async fn report( + db: &Database, + id: &PodcastJobId, + from: PodcastJobState, + to: PodcastJobState, + stage: &str, + progress: f64, + error_code: Option<&str>, + format: Option<&str>, +) -> Result, AppError> { + let now = Timestamp::now().as_millis(); + Ok(query_as!( + PodcastJob, + "UPDATE podcast_job SET state = $3, stage = $4, progress = $5, error_code = $6, \ + format = COALESCE(format, $7::text), updated_at = $8 \ + WHERE id = $1 AND state = $2 \ + RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", \ + source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, \ + audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \ + created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", + id.uuid(), + from.as_str(), + to.as_str(), + stage, + progress, + error_code, + format, + now, + ) + .fetch_optional(db) + .await?) +} + +/// Mark a live job cancelled — the backend's own write behind the cancel +/// verdict, taken the moment the service confirms it. `None` means the row was +/// not live (already terminal, or gone), which is exactly the `cancelled: +/// false` verdict. +pub async fn set_cancelled( + db: &Database, + id: &PodcastJobId, +) -> Result, AppError> { + let now = Timestamp::now().as_millis(); + Ok(query_as!( + PodcastJob, + "UPDATE podcast_job SET state = 'cancelled', stage = '', updated_at = $2 \ + WHERE id = $1 AND state IN ('queued', 'running') \ + RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", \ + source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, \ + audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \ + created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", + id.uuid(), + now, + ) + .fetch_optional(db) + .await?) +} + +/// Mark a live job failed with the backend's own reason code — a dispatch that +/// never reached a worker, or a service that answered `not_found` for a job +/// whose row still says it is running. Same `None` contract as +/// [`set_cancelled`]. +pub async fn set_failed( + db: &Database, + id: &PodcastJobId, + error_code: &str, +) -> Result, AppError> { + let now = Timestamp::now().as_millis(); + Ok(query_as!( + PodcastJob, + "UPDATE podcast_job SET state = 'failed', error_code = $2, stage = '', updated_at = $3 \ + WHERE id = $1 AND state IN ('queued', 'running') \ + RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", \ + source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, \ + audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \ + created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", + id.uuid(), + error_code, + now, + ) + .fetch_optional(db) + .await?) +} + +/// Record the uploaded episode on its job: the blob key plus the metadata the +/// audio door replays as headers. One statement, so "the bytes are stored" and +/// "the row names them" land together; a job that is gone answers `None`. +#[allow(clippy::too_many_arguments)] +pub async fn set_audio( + db: &Database, + id: &PodcastJobId, + key: &str, + name: &str, + content_type: &str, + bytes: i64, + duration_secs: Option, +) -> Result, AppError> { + let now = Timestamp::now().as_millis(); + Ok(query_as!( + PodcastJob, + "UPDATE podcast_job SET audio_key = $2, audio_name = $3, audio_type = $4, \ + audio_bytes = $5, duration_secs = $6, updated_at = $7 \ + WHERE id = $1 \ + RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", \ + source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, \ + audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \ + created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", + id.uuid(), + key, + name, + content_type, + bytes, + duration_secs, + now, + ) + .fetch_optional(db) + .await?) +} + +/// Store the service's own ETA estimate on a job it has just accepted — the +/// number the read-side staleness window is scaled by and the submit receipt +/// echoes. A job that is gone answers `None`. +pub async fn set_eta( + db: &Database, + id: &PodcastJobId, + eta_secs: i64, +) -> Result, AppError> { + Ok(query_as!( + PodcastJob, + "UPDATE podcast_job SET eta_secs = $2 WHERE id = $1 \ + RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", \ + source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, \ + audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \ + created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", + id.uuid(), + eta_secs, + ) + .fetch_optional(db) + .await?) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::monotonic_id::next_uuid; + + /// A leased school database with one app_user row, and that user's id. + async fn fixture() -> (Database, crate::database::TestDatabases, UserId) { + let (db, leases) = crate::database::init_test_db().await; + let user = UserId::from_key(&next_uuid().to_string()); + insert_user(&db, &user).await; + (db, leases, user) + } + + async fn insert_user(db: &Database, user: &UserId) { + // A monotonic counter, not a slice of the id: two UUIDv7s minted in + // the same millisecond share their first hex digits. + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, $2, 0)") + .bind(user.uuid()) + .bind(format!("test-user-{n}")) + .execute(db) + .await + .expect("insert user"); + } + + /// A minimal queued row for the statement tests below. + fn job(user: &UserId) -> PodcastJob { + let now = Timestamp::now(); + PodcastJob { + id: PodcastJobId::generate(), + user_id: *user, + source_id: "src".to_string(), + format: None, + state: PodcastJobState::Queued, + stage: String::new(), + progress: 0.0, + error_code: None, + audio_key: None, + audio_name: None, + audio_type: None, + audio_bytes: None, + duration_secs: None, + eta_secs: Some(30), + created_at: now, + updated_at: now, + } + } + + /// The report write is conditional on the state the caller validated + /// against, so a cancel and a late report cannot both win: whoever lands + /// second matches nothing and the caller re-reads. + #[tokio::test] + async fn a_report_is_guarded_by_the_state_it_validated_against() { + let (db, _leases, user) = fixture().await; + let row = insert(&db, &job(&user)).await.expect("insert"); + let id = row.get_id().clone(); + + // The running report lands, and carries the resolved format with it. + let running = report( + &db, + &id, + PodcastJobState::Queued, + PodcastJobState::Running, + "script", + 0.25, + None, + Some("duz_okuma"), + ) + .await + .expect("report") + .expect("row was queued"); + assert_eq!(running.get_state(), PodcastJobState::Running); + assert_eq!(running.get_format(), Some("duz_okuma")); + + // A second report claiming the row is still queued matches nothing. + let stale = report( + &db, + &id, + PodcastJobState::Queued, + PodcastJobState::Running, + "script", + 0.5, + None, + None, + ) + .await + .expect("report"); + assert!(stale.is_none()); + + // A cancel moves it; the done report that raced it matches nothing. + assert!(set_cancelled(&db, &id).await.expect("cancel").is_some()); + let done = report( + &db, + &id, + PodcastJobState::Running, + PodcastJobState::Done, + "done", + 1.0, + None, + None, + ) + .await + .expect("report"); + assert!(done.is_none()); + assert_eq!( + read(&db, &id).await.expect("read").unwrap().get_state(), + PodcastJobState::Cancelled + ); + // A terminal row refuses the backend's own writes too. + assert!(set_failed(&db, &id, "interrupted").await.unwrap().is_none()); + } + + /// A foreign user's id reads as absent — the query itself filters, so the + /// row never leaves the database on the stranger's behalf. + #[tokio::test] + async fn a_foreign_user_reads_no_row() { + let (db, _leases, owner) = fixture().await; + let row = insert(&db, &job(&owner)).await.expect("insert"); + let id = row.get_id().clone(); + let stranger = UserId::from_key(&next_uuid().to_string()); + insert_user(&db, &stranger).await; + assert!( + read_for(&db, &id, &stranger) + .await + .expect("read") + .is_none() + ); + assert!( + read_for(&db, &id, row.get_user_id()) + .await + .expect("read") + .is_some() + ); + } + + /// `done` and "has audio" can never disagree: the schema refuses a done + /// report before an upload landed, and accepts it after. + #[tokio::test] + async fn done_cannot_be_stored_without_an_audio_key() { + let (db, _leases, user) = fixture().await; + let row = insert(&db, &job(&user)).await.expect("insert"); + let id = row.get_id().clone(); + let refused = report( + &db, + &id, + PodcastJobState::Queued, + PodcastJobState::Done, + "done", + 1.0, + None, + None, + ) + .await; + assert!(refused.is_err(), "the CHECK backstops the service layer"); + set_audio( + &db, + &id, + "podcast/x.mp3", + "episode.mp3", + "audio/mpeg", + 12, + Some(3.5), + ) + .await + .expect("upload") + .expect("row"); + let done = report( + &db, + &id, + PodcastJobState::Queued, + PodcastJobState::Done, + "done", + 1.0, + None, + None, + ) + .await + .expect("report") + .expect("row"); + assert_eq!(done.get_state(), PodcastJobState::Done); + assert_eq!(done.get_audio_key(), Some("podcast/x.mp3")); + assert_eq!(done.get_duration_secs(), Some(3.5)); + assert_eq!(done.get_audio_bytes(), Some(12)); + } +} diff --git a/src/domain/mod.rs b/src/domain/mod.rs index 86d214b..80d4c2b 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -53,6 +53,7 @@ pub mod note_file; pub mod parent_link; pub mod payment_ledger; pub mod person; +pub mod podcast_job; pub mod pomodoro; pub mod pool_question; pub mod pool_question_image; diff --git a/src/domain/podcast_job.rs b/src/domain/podcast_job.rs new file mode 100644 index 0000000..a06f13d --- /dev/null +++ b/src/domain/podcast_job.rs @@ -0,0 +1,343 @@ +//! One podcast job — the record the backend owns from the moment a caller +//! submits to the moment the audio is collected, plus its read-time +//! presentation. +//! +//! The service reports every transition back over the bridge +//! (`podcast.report`), but the row is written *first*, by the submit handler, +//! and every read door (`podcast.status`, `podcast.result`, the audio stream) +//! answers from this table alone. That is the whole point of the row: a +//! service restart — or a wiped service volume — costs no record, no job id, +//! and no audio bytes. +//! +//! A service that dies *without* reporting is what [`PodcastJob::projected`] +//! answers: a job left `queued`/`running` longer than its own ETA allows is +//! presented as `failed`/`interrupted` — on the read side only, never written — +//! the same device [`crate::domain::rag_message`] uses for a stranded turn. +//! The durable repair still belongs to the service: it sweeps its own store at +//! boot and reports each swept job, which overwrites the projection. +//! +//! The state vocabulary and the transition table are the service's own +//! (`jobs.py`'s `STATES`/`TRANSITIONS`), mirrored here so a report the service +//! could not have produced is refused instead of stored. + +use crate::constant::{ + PODCAST_INTERRUPTED_CODE, PODCAST_JOB_RETENTION_SECS, PODCAST_JOB_STALE_ETA_FACTOR, + PODCAST_JOB_STALE_FLOOR_SECS, +}; +use crate::domain::monotonic_id::next_uuid; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; + +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct PodcastJobId(uuid::Uuid); + +impl PodcastJobId { + /// Mints from the process-wide monotonic generator: job ids are also the + /// service's record keys and the audio blob's file name, and a monotonic + /// UUID keeps a directory listing of episodes in submit order. + pub fn generate() -> Self { + Self(next_uuid()) + } + + /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that + /// cannot take the newtype. Static `query!` binds take `self` directly. + pub fn uuid(&self) -> uuid::Uuid { + self.0 + } + + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row — the same rule every other id in the codebase + /// follows. + pub fn from_key(key: &str) -> Self { + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) + } + + /// The wire form: the standard hyphenated lowercase string. This is also + /// the chain the service stores its own record under and the audio blob's + /// stem, so it must stay byte-stable across every surface. + pub fn key(&self) -> String { + self.0.to_string() + } +} + +/// Where a job is in its lifecycle. Stored as the bare lowercase string the +/// `state` column's CHECK allows; a value the enum doesn't know comes back as +/// a decode error, never a panic. +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] +pub enum PodcastJobState { + Queued, + Running, + Done, + Failed, + Cancelled, +} + +impl PodcastJobState { + /// The wire/storage form. Must stay in lockstep with `rename_all`. + pub fn as_str(self) -> &'static str { + match self { + PodcastJobState::Queued => "queued", + PodcastJobState::Running => "running", + PodcastJobState::Done => "done", + PodcastJobState::Failed => "failed", + PodcastJobState::Cancelled => "cancelled", + } + } + + /// Parses a report's own `state` string. `None` is a value the service + /// should never have produced — the report is refused, not coerced. + pub fn parse(value: &str) -> Option { + match value { + "queued" => Some(PodcastJobState::Queued), + "running" => Some(PodcastJobState::Running), + "done" => Some(PodcastJobState::Done), + "failed" => Some(PodcastJobState::Failed), + "cancelled" => Some(PodcastJobState::Cancelled), + _ => None, + } + } + + /// Done, failed or cancelled — the states a job never leaves. + pub fn is_terminal(self) -> bool { + matches!( + self, + PodcastJobState::Done | PodcastJobState::Failed | PodcastJobState::Cancelled + ) + } + + /// Can a report move a row from `self` to `target`? `jobs.py`'s + /// `TRANSITIONS`, plus the identity transition: a report may repeat the + /// state it last reported (a bridge round trip can time out after the + /// service committed, and the retry must not be a refusal). + pub fn can_transition_to(self, target: PodcastJobState) -> bool { + if target == self { + return true; + } + match self { + PodcastJobState::Queued => matches!( + target, + PodcastJobState::Running | PodcastJobState::Cancelled | PodcastJobState::Failed + ), + PodcastJobState::Running => matches!( + target, + PodcastJobState::Done | PodcastJobState::Failed | PodcastJobState::Cancelled + ), + PodcastJobState::Done | PodcastJobState::Failed | PodcastJobState::Cancelled => false, + } + } +} + +#[derive(Debug, Clone, sqlx::FromRow)] +pub struct PodcastJob { + pub(crate) id: PodcastJobId, + /// The submitting user. The ownership guard every read door applies. + pub(crate) user_id: UserId, + pub(crate) source_id: String, + pub(crate) format: Option, + pub(crate) state: PodcastJobState, + pub(crate) stage: String, + pub(crate) progress: f64, + pub(crate) error_code: Option, + pub(crate) audio_key: Option, + pub(crate) audio_name: Option, + pub(crate) audio_type: Option, + pub(crate) audio_bytes: Option, + pub(crate) duration_secs: Option, + pub(crate) eta_secs: Option, + pub(crate) created_at: Timestamp, + pub(crate) updated_at: Timestamp, +} + +impl PodcastJob { + pub fn get_id(&self) -> &PodcastJobId { + &self.id + } + + pub fn get_user_id(&self) -> &UserId { + &self.user_id + } + + pub fn get_source_id(&self) -> &str { + &self.source_id + } + + pub fn get_format(&self) -> Option<&str> { + self.format.as_deref() + } + + pub fn get_state(&self) -> PodcastJobState { + self.state + } + + pub fn get_stage(&self) -> &str { + &self.stage + } + + pub fn get_progress(&self) -> f64 { + self.progress + } + + pub fn get_error_code(&self) -> Option<&str> { + self.error_code.as_deref() + } + + pub fn get_audio_key(&self) -> Option<&str> { + self.audio_key.as_deref() + } + + pub fn get_audio_name(&self) -> Option<&str> { + self.audio_name.as_deref() + } + + pub fn get_audio_type(&self) -> Option<&str> { + self.audio_type.as_deref() + } + + pub fn get_audio_bytes(&self) -> Option { + self.audio_bytes + } + + pub fn get_duration_secs(&self) -> Option { + self.duration_secs + } + + pub fn get_eta_secs(&self) -> Option { + self.eta_secs + } + + pub fn get_created_at(&self) -> Timestamp { + self.created_at + } + + pub fn get_updated_at(&self) -> Timestamp { + self.updated_at + } + + /// The job as a read should present it, with no write behind it: a + /// `queued`/`running` row nobody has updated inside its own staleness + /// window is presented as `failed`/`interrupted`. The window scales with + /// the service's own ETA — `max(floor, eta_secs × factor)` — so a long + /// episode (or a queue of them) is never declared dead mid-flight, while a + /// service that died takes its jobs down with it within a bounded, + /// ETA-aware time. + /// + /// Only the returned copy is projected; the row is untouched, and the + /// service's next report overwrites the projection the moment it lands. + pub fn projected(mut self) -> Self { + if self.state.is_terminal() { + return self; + } + let eta_secs = self.eta_secs.unwrap_or(0).max(0); + let window_ms = eta_secs + .saturating_mul(PODCAST_JOB_STALE_ETA_FACTOR) + .max(PODCAST_JOB_STALE_FLOOR_SECS) + * 1_000; + if Timestamp::now().as_millis() > self.updated_at.as_millis() + window_ms { + self.state = PodcastJobState::Failed; + self.error_code = Some(PODCAST_INTERRUPTED_CODE.to_string()); + self.stage = String::new(); + } + self + } + + /// Has this job aged out of the retention window? Terminal rows older than + /// [`PODCAST_JOB_RETENTION_SECS`] — measured from the write that finished + /// them — are refused `410`, and the audio door will not stream their blob. + /// A read-side test only; nothing is swept on the read path. + pub fn is_expired(&self) -> bool { + self.state.is_terminal() + && Timestamp::now().as_millis() - self.updated_at.as_millis() + > PODCAST_JOB_RETENTION_SECS * 1_000 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_transition_table_is_the_services_own() { + use PodcastJobState::*; + assert!(Queued.can_transition_to(Running)); + assert!(Queued.can_transition_to(Cancelled)); + assert!(Queued.can_transition_to(Failed)); + assert!(!Queued.can_transition_to(Done)); + assert!(Running.can_transition_to(Done)); + assert!(Running.can_transition_to(Failed)); + assert!(Running.can_transition_to(Cancelled)); + assert!(!Running.can_transition_to(Queued)); + for terminal in [Done, Failed, Cancelled] { + for target in [Queued, Running, Done, Failed, Cancelled] { + assert_eq!( + terminal.can_transition_to(target), + terminal == target, + "{terminal:?} -> {target:?}" + ); + } + } + } + + #[test] + fn a_projected_job_is_failed_interrupted_but_a_long_eta_is_respected() { + let mut job = dead_job(PodcastJobState::Running, 3_600); + job.updated_at = Timestamp::from_millis(Timestamp::now().as_millis() - 2_000_000); + // Two million ms stale on a one-hour ETA: the window is 3h, so the job + // is still believed to be running. + assert_eq!(job.clone().projected().get_state(), PodcastJobState::Running); + // Past 3h, the projection fires. + job.updated_at = Timestamp::from_millis(Timestamp::now().as_millis() - 11_000_000); + let projected = job.projected(); + assert_eq!(projected.get_state(), PodcastJobState::Failed); + assert_eq!(projected.get_error_code(), Some(PODCAST_INTERRUPTED_CODE)); + } + + #[test] + fn a_fresh_job_and_a_terminal_job_are_never_projected() { + let fresh = dead_job(PodcastJobState::Queued, 5); + assert_eq!(fresh.clone().projected().get_state(), PodcastJobState::Queued); + let done = dead_job(PodcastJobState::Done, 0); + assert_eq!(done.clone().projected().get_state(), PodcastJobState::Done); + assert_eq!(done.projected().get_error_code(), None); + } + + #[test] + fn retention_counts_only_terminal_rows_past_the_window() { + let mut done = dead_job(PodcastJobState::Done, 0); + assert!(!done.is_expired()); + done.updated_at = Timestamp::from_millis( + Timestamp::now().as_millis() - (PODCAST_JOB_RETENTION_SECS + 60) * 1_000, + ); + assert!(done.is_expired()); + // A non-terminal row is the projection's business, not expiry's. + let mut running = dead_job(PodcastJobState::Running, 0); + running.updated_at = Timestamp::from_millis( + Timestamp::now().as_millis() - (PODCAST_JOB_RETENTION_SECS + 60) * 1_000, + ); + assert!(!running.is_expired()); + } + + /// A row with every field filled, for the projection/expiry tests only. + fn dead_job(state: PodcastJobState, eta_secs: i64) -> PodcastJob { + let now = Timestamp::now(); + PodcastJob { + id: PodcastJobId::generate(), + user_id: UserId::from_key("00000000-0000-7000-8000-000000000000"), + source_id: "src".to_string(), + format: None, + state, + stage: String::new(), + progress: 0.0, + error_code: None, + audio_key: None, + audio_name: None, + audio_type: None, + audio_bytes: None, + duration_secs: None, + eta_secs: Some(eta_secs), + created_at: now, + updated_at: now, + } + } +} diff --git a/src/error.rs b/src/error.rs index eee334f..8e36523 100644 --- a/src/error.rs +++ b/src/error.rs @@ -63,6 +63,13 @@ pub enum AppError { Validation(#[from] ValidationError), #[error("not found")] NotFound, + /// The resource existed, its retention window has passed, and nothing + /// about it is served any more — a podcast job older than + /// [`crate::constant::PODCAST_JOB_RETENTION_SECS`] today. A dedicated + /// `410` so a client can tell "gone for good" from "never existed" (`404`) + /// and from "not written yet" (`409`) without parsing a sentence. + #[error("expired: {0}")] + Expired(&'static str), #[error("unauthorized")] Unauthorized, #[error("forbidden: {0}")] @@ -152,6 +159,7 @@ impl AppError { match self { AppError::Validation(_) => "validation", AppError::NotFound => "not_found", + AppError::Expired(_) => "expired", AppError::Unauthorized => "unauthorized", AppError::Forbidden(_) => "forbidden", AppError::ModuleDisabled(_) => "module_disabled", @@ -266,6 +274,7 @@ impl AppError { } AppError::Validation(v) => (StatusCode::BAD_REQUEST, v.to_string()), AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()), + AppError::Expired(m) => (StatusCode::GONE, m.to_string()), AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()), AppError::Forbidden(m) => (StatusCode::FORBIDDEN, m.to_string()), AppError::Conflict(m) => (StatusCode::CONFLICT, m.to_string()), diff --git a/src/service/mod.rs b/src/service/mod.rs index 94cd31d..aac82fb 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -47,6 +47,7 @@ pub mod note_file; pub mod parent_link; pub mod payment_ledger; pub mod person; +pub mod podcast_job; pub mod pomodoro; pub mod pool_question; pub mod pool_question_image; diff --git a/src/service/podcast_job.rs b/src/service/podcast_job.rs new file mode 100644 index 0000000..4ed0421 --- /dev/null +++ b/src/service/podcast_job.rs @@ -0,0 +1,342 @@ +//! Podcast job workflows: the submit write that mints a job, the report write +//! the service's `podcast.report` calls land through, the cancel/fail writes +//! behind the HTTP verdicts, and the audio reference an ingest stamps. +//! +//! The queries live in [`crate::db::podcast_job`]. Everything that decides +//! *whether* a write may happen lives here: the report path is the trust +//! boundary between the service and this table, so it validates the sender's +//! echo (user, source), the transition (`jobs.py`'s table, via the domain +//! enum), the retention window, and the "done means audio" rule — in that +//! order — before a single statement runs. + +use crate::database::Database; +use crate::db::podcast_job; +use crate::domain::podcast_job::{PodcastJob, PodcastJobId, PodcastJobState}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; +use crate::validate::validate_required; + +/// The most characters a report may put in `stage` / `error_code`. Generous +/// for the service's own short codes and stage names; the bound exists so a +/// service cannot write a paragraph into a column a UI renders inline. +const MAX_CODE_LEN: usize = 64; + +/// Why one `podcast.report` (or an audio ingest) was refused. `code()` is the +/// flat, stable, machine-readable string the bridge answers in the +/// capability's `code` field — the same vocabulary the protocol's other +/// refusals use. Never nested, never localized. +#[derive(Debug)] +pub enum PodcastRefusal { + /// No job with that id exists in the school the frame named — including a + /// real id belonging to another school, which reads the same on purpose. + UnknownJob, + /// The report does not describe a state this service could have produced: + /// an unknown state name, an out-of-range progress, an over-long code, or + /// a transition the state machine forbids. + InvalidPayload(String), + /// The sender's echo of the job disagrees with the row — a report for a + /// job under a different user or source. + NotPermitted(String), + /// A `done` report arrived before its audio was ingested. The row must + /// never claim a finished episode whose bytes are not there. + AudioMissing, + /// The job aged out of the retention window; its blob is no longer served + /// and its state is frozen history. + Expired, + /// The store itself refused — nothing the service can fix by retrying + /// differently. + Unavailable(String), +} + +impl PodcastRefusal { + pub fn code(&self) -> &'static str { + match self { + PodcastRefusal::UnknownJob => "unknown_job", + PodcastRefusal::InvalidPayload(_) => "invalid_payload", + PodcastRefusal::NotPermitted(_) => "not_permitted", + PodcastRefusal::AudioMissing => "audio_missing", + PodcastRefusal::Expired => "expired", + PodcastRefusal::Unavailable(_) => "unavailable", + } + } + + pub fn message(&self) -> String { + match self { + PodcastRefusal::UnknownJob => "no such podcast job".to_string(), + PodcastRefusal::InvalidPayload(why) => why.clone(), + PodcastRefusal::NotPermitted(why) => why.clone(), + PodcastRefusal::AudioMissing => { + "a done report requires the episode to be uploaded first".to_string() + } + PodcastRefusal::Expired => "this podcast job has expired".to_string(), + PodcastRefusal::Unavailable(why) => why.clone(), + } + } +} + +impl From for PodcastRefusal { + fn from(err: AppError) -> Self { + PodcastRefusal::Unavailable(err.to_string()) + } +} + +/// One state report from the service, as [`crate::ai::podcast`] decoded it. +/// The borrowed strings are the wire's own; nothing here is trusted until +/// [`report`] has checked it against the row. +#[derive(Debug)] +pub struct ReportInput<'a> { + pub job_id: &'a str, + pub source_id: &'a str, + pub format: Option<&'a str>, + pub user_id: &'a str, + pub state: &'a str, + pub stage: &'a str, + pub progress: f64, + pub error_code: Option<&'a str>, +} + +/// Mint and store one freshly submitted job. The id is the backend's (the +/// service is handed it in the submit payload), and the row starts `queued` +/// with no ETA — the service's own estimate lands a moment later, with +/// [`set_eta`], once it has accepted the job. +pub async fn create( + db: &Database, + user: &UserId, + source_id: &str, + format: Option<&str>, +) -> Result { + let now = Timestamp::now(); + let job = PodcastJob { + id: PodcastJobId::generate(), + user_id: *user, + source_id: source_id.to_string(), + format: format.map(str::to_string), + state: PodcastJobState::Queued, + stage: String::new(), + progress: 0.0, + error_code: None, + audio_key: None, + audio_name: None, + audio_type: None, + audio_bytes: None, + duration_secs: None, + eta_secs: None, + created_at: now, + updated_at: now, + }; + podcast_job::insert(db, &job).await +} + +/// Store the service's own ETA on the job it just accepted — the number the +/// read-side staleness window is scaled by, echoed back to the submitter. +pub async fn set_eta( + db: &Database, + id: &PodcastJobId, + eta_secs: i64, +) -> Result, AppError> { + podcast_job::set_eta(db, id, eta_secs.max(0)).await +} + +/// Read a job only if `user` owns it — a foreign id reads as absent, so the +/// HTTP doors answer 404 rather than leaking that it exists. +pub async fn read_for( + db: &Database, + id: &PodcastJobId, + user: &UserId, +) -> Result, AppError> { + podcast_job::read_for(db, id, user).await +} + +/// A user's own jobs, newest first. +pub async fn list_for_user( + db: &Database, + user: &UserId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + podcast_job::list_for_user(db, user, limit, offset).await +} + +/// Apply one report from the service. The order of the checks is the point: +/// shape first (so nothing malformed reaches a query), then existence, then +/// the sender's own echo, then the retention window, then the transition, and +/// finally "done means audio" — the rule the schema's CHECK also backstops. +/// +/// The write itself is conditional on the state just read (`from`), so a +/// cancel racing this report cannot be overwritten by it; when the condition +/// loses, the refusal names the state that actually holds. +pub async fn report( + db: &Database, + input: &ReportInput<'_>, +) -> Result { + let id = PodcastJobId::from_key(input.job_id); + let Some(target) = PodcastJobState::parse(input.state) else { + return Err(PodcastRefusal::InvalidPayload(format!( + "`{}` is not a known job state", + input.state + ))); + }; + if !input.progress.is_finite() || !(0.0..=1.0).contains(&input.progress) { + return Err(PodcastRefusal::InvalidPayload( + "progress must be a fraction between 0 and 1".to_string(), + )); + } + if input.stage.chars().count() > MAX_CODE_LEN { + return Err(PodcastRefusal::InvalidPayload( + "stage is longer than 64 characters".to_string(), + )); + } + if let Some(code) = input.error_code + && code.chars().count() > MAX_CODE_LEN + { + return Err(PodcastRefusal::InvalidPayload( + "error_code is longer than 64 characters".to_string(), + )); + } + + let Some(row) = podcast_job::read(db, &id).await? else { + return Err(PodcastRefusal::UnknownJob); + }; + if row.get_user_id().key() != input.user_id { + return Err(PodcastRefusal::NotPermitted( + "the job belongs to another user".to_string(), + )); + } + if row.get_source_id() != input.source_id { + return Err(PodcastRefusal::NotPermitted( + "the job's source does not match this report".to_string(), + )); + } + if let (Some(stored), Some(reported)) = (row.get_format(), input.format) + && stored != reported + { + return Err(PodcastRefusal::NotPermitted( + "the job's format was already resolved and this report disagrees".to_string(), + )); + } + if row.is_expired() { + return Err(PodcastRefusal::Expired); + } + if !row.get_state().can_transition_to(target) { + return Err(PodcastRefusal::InvalidPayload(format!( + "`{}` cannot move to `{}`", + row.get_state().as_str(), + target.as_str() + ))); + } + if target == PodcastJobState::Done && row.get_audio_key().is_none() { + return Err(PodcastRefusal::AudioMissing); + } + + match podcast_job::report( + db, + &id, + row.get_state(), + target, + input.stage, + input.progress, + input.error_code, + input.format, + ) + .await? + { + Some(updated) => Ok(updated), + // The row moved between the read and the write (a cancel, most + // likely). Nothing was stored; name the state that actually holds. + None => match podcast_job::read(db, &id).await? { + Some(current) => Err(PodcastRefusal::InvalidPayload(format!( + "the job moved to `{}` while this report was in flight", + current.get_state().as_str() + ))), + None => Err(PodcastRefusal::UnknownJob), + }, + } +} + +/// Take the backend's own cancel write: only a live row moves, and `None` +/// (already terminal, or gone) is the `cancelled: false` verdict. +pub async fn mark_cancelled( + db: &Database, + id: &PodcastJobId, +) -> Result, AppError> { + podcast_job::set_cancelled(db, id).await +} + +/// Mark a live job failed with a backend-side reason code — a dispatch that +/// never reached a worker, or a service that lost a job its row still calls +/// live. +pub async fn mark_failed( + db: &Database, + id: &PodcastJobId, + error_code: &str, +) -> Result, AppError> { + podcast_job::set_failed(db, id, error_code).await +} + +/// Validate one upload's metadata before a byte is written: the name and +/// content type a browser will see, and the size bound. `Err` carries the flat +/// refusal code the bridge answers. +pub fn validate_audio( + name: &str, + content_type: &str, + size: u64, +) -> Result<(), PodcastRefusal> { + if let Err(why) = validate_required("name", name, 200) { + return Err(PodcastRefusal::InvalidPayload(why.to_string())); + } + if !content_type.starts_with("audio/") { + return Err(PodcastRefusal::InvalidPayload(format!( + "`{content_type}` is not an audio content type" + ))); + } + if size == 0 { + return Err(PodcastRefusal::InvalidPayload( + "an empty episode is not an episode".to_string(), + )); + } + if size > crate::constant::PODCAST_AUDIO_MAX_BYTES as u64 { + return Err(PodcastRefusal::InvalidPayload(format!( + "the upload is larger than {} bytes", + crate::constant::PODCAST_AUDIO_MAX_BYTES + ))); + } + Ok(()) +} + +/// The blob key an uploaded episode is stored under: `podcast/.`. +/// The extension comes off the service's own file name when it is a short, +/// boring one, and is otherwise derived from the content type — never copied +/// verbatim, so nothing the service sends can shape a path. +pub fn audio_key(job_id: &PodcastJobId, name: &str, content_type: &str) -> String { + let extension = name + .rsplit_once('.') + .map(|(_, ext)| ext) + .filter(|ext| { + (1..=5).contains(&ext.len()) && ext.chars().all(|c| c.is_ascii_alphanumeric()) + }) + .map(|ext| ext.to_ascii_lowercase()) + .unwrap_or_else(|| match content_type { + "audio/mpeg" => "mp3".to_string(), + "audio/mp4" => "m4a".to_string(), + "audio/aac" => "aac".to_string(), + "audio/wav" | "audio/x-wav" => "wav".to_string(), + "audio/ogg" => "ogg".to_string(), + "audio/opus" => "opus".to_string(), + _ => "bin".to_string(), + }); + format!("podcast/{}.{extension}", job_id.key()) +} + +/// Stamp the ingested episode onto its row, after the bytes are on disk. +pub async fn set_audio( + db: &Database, + id: &PodcastJobId, + key: &str, + name: &str, + content_type: &str, + bytes: i64, + duration_secs: Option, +) -> Result, AppError> { + podcast_job::set_audio(db, id, key, name, content_type, bytes, duration_secs).await +} diff --git a/src/web/board_ws.rs b/src/web/board_ws.rs index d4cfb63..dd8d08b 100644 --- a/src/web/board_ws.rs +++ b/src/web/board_ws.rs @@ -585,6 +585,7 @@ fn error_frame(err: &AppError, client_seq: Option) -> Value { AppError::Conflict(_) | AppError::ConflictOwned(_) => "conflict", AppError::Validation(_) | AppError::PayloadTooLarge(_) => "invalid", AppError::NotFound => "not_found", + AppError::Expired(_) => "expired", // See `room::public_message`: the gate refuses the upgrade first. AppError::ModuleDisabled(_) => "module_disabled", AppError::Unauthorized => "unauthorized", diff --git a/src/web/podcast.rs b/src/web/podcast.rs index 074a918..6a6d093 100644 --- a/src/web/podcast.rs +++ b/src/web/podcast.rs @@ -1,75 +1,67 @@ //! The podcast nest: browser ⇄ backend ⇄ the podcast service (over the QUIC -//! bridge), plus the door that hands back the produced audio. +//! bridge), plus the doors that hand back the produced audio. //! -//! The relay contract is the chatbot's and the RAG nest's, shape for shape: -//! the backend owns authentication and the thin HTTP surface, the **service** -//! owns the job. Four doors map one-to-one onto the four `podcast.*` -//! capabilities — `POST /jobs` (submit), `GET /jobs/{id}` (status), -//! `GET /jobs/{id}/result` (result) and `POST /jobs/{id}/cancel` (cancel) — -//! each refusing `503` when no worker declares its capability, and each -//! relaying what the service answered: the receipt, the status snapshot, the -//! artifacts, the cancel verdict. A service-side refusal keeps its own code -//! (`not_found`, `not_ready`, `busy`, …) and decides the HTTP status, so a -//! client branches on the same vocabulary the bridge speaks. +//! The **backend owns the job**. `POST /podcast/jobs` mints the id, writes the +//! row, and only then dispatches `podcast.submit`; the service reports every +//! transition back (`podcast.report`) and uploads the finished mp3 +//! (`BlobUploadRequest`), which lands under **this school's** blob directory. +//! `GET /podcast/jobs/{id}` and `.../result` therefore answer from +//! [`crate::db::podcast_job`] alone — no worker, no service, no second store +//! that a restart or a wiped volume could take down with it. The service's own +//! record is a mirror the pipeline works against, not the source of truth. //! -//! The fifth door is the audio itself. `podcast.result` answers an `audio_id` -//! that is a path *relative* to the school's output root on this host — the -//! service's `PODCAST_OUTPUT_ROOT`, which the deployment points at this -//! school's own directory under `FILES_PATH` — so -//! `GET /podcast/audio?path=…` streams those bytes back. It is the one place -//! a caller names a path, so it is also the one place a path is treated as -//! hostile: absolute paths, `.`/`..` segments, backslashes, drive colons and -//! symlinks that resolve out of the school's directory are all refused with a -//! `400` — "this backend will not resolve that" — never a `404` that would -//! hide the difference from the caller probing it. +//! Five doors: //! -//! Every door is school-scoped twice: the session resolves the school, and the -//! audio door resolves the path under *that* school's directory, so a caller -//! cannot reach another school's episode even knowing its exact path. +//! * `POST /podcast/jobs` — write the row, dispatch `podcast.submit` +//! * `GET /podcast/jobs/{id}` — the row's snapshot (projected, see below) +//! * `GET /podcast/jobs/{id}/result` — a finished job's artifact references +//! * `GET /podcast/jobs/{id}/audio` — streams the ingested episode +//! * `POST /podcast/jobs/{id}/cancel` — forward the cancel, stamp the verdict //! -//! None of the four dispatching doors writes a row: the job record and the -//! produced files live in the service. That is also why they are synchronous — -//! every capability answers immediately (the pipeline runs in the service's own -//! pool), so there is nothing here to await off the request path. +//! The two dispatching doors (`submit`, `cancel`) refuse `503` when no worker +//! declares their capability; the three reading doors need no service at all. +//! A relayed failure keeps the service's own code and decides the HTTP status +//! (`failure`), so a client branches on the same vocabulary the bridge speaks. //! -//! What the backend can and cannot judge, stated plainly: the gate is a -//! session — any authenticated member of the school may use the doors, the same -//! floor `/chatbot` and `/rag` hold — and the school wall is the bridge's -//! (`hab/2` stamps the caller's school onto every request; the bridge does -//! not verify the echo on replies — answers are correlated by frame id -//! alone). It cannot scope -//! *which* sources a caller may narrate: `source_id` is the service's own -//! record, and no backend query can say what it names. That is a property of -//! the wire the two sides share, not an oversight — the service resolves the -//! id against the shared media volume and the backend enforces the tenant. +//! Every door is school-scoped twice: the session resolves the school's +//! database (`st.db`) and the school's blob directory (`st.files_path`), and +//! every read is filtered by the submitting user in the statement itself — a +//! foreign id is a plain `404`, never a hint that it exists. Terminal rows +//! older than the retention window answer `410`. +//! +//! A job nobody is updating — the service died mid-pipeline — is *presented* +//! as `failed`/`interrupted` by the read path after a bounded, ETA-scaled +//! window (see [`PodcastJob::projected`]): the projection writes nothing, and +//! the service's next report overwrites it. And what the backend still cannot +//! judge is stated plainly: `source_id` is the service's own handle on shared +//! media, so no backend query can say what it names — the service resolves it, +//! the backend enforces the tenant. use axum::Json; use axum::body::{Body, Bytes}; -use axum::extract::{Path, Query}; +use axum::extract::Path; use axum::http::HeaderValue; use axum::http::StatusCode; use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS}; use axum::response::{IntoResponse, Response}; use serde::{Deserialize, Serialize}; use serde_json::json; -use tokio::io::AsyncReadExt; use tokio::sync::mpsc; use tokio_stream::Stream; use tokio_stream::wrappers::ReceiverStream; -use utoipa::{IntoParams, ToSchema}; +use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::ai::AiBridge; -use crate::ai::podcast::{ - self, PodcastCancelPayload, PodcastCancelReply, PodcastResultPayload, PodcastResultReply, - PodcastStatusPayload, PodcastStatusReply, PodcastSubmitPayload, PodcastSubmitReply, -}; +use crate::ai::podcast::{self, PodcastCancelPayload, PodcastSubmitPayload}; use crate::constant::{ - AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_RESULT_CAPABILITY, AI_PODCAST_STATUS_CAPABILITY, - AI_PODCAST_SUBMIT_CAPABILITY, + AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_SUBMIT_CAPABILITY, PODCAST_INTERRUPTED_CODE, }; +use crate::domain::podcast_job::{PodcastJob, PodcastJobId}; +use crate::domain::user::User; use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::service::podcast_job as jobs; use crate::state::AppState; use crate::web::tenant_state::{SchoolSlug, State}; @@ -86,8 +78,8 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(submit)) .routes(routes!(status)) .routes(routes!(result)) - .routes(routes!(cancel)) .routes(routes!(audio)) + .routes(routes!(cancel)) } #[derive(Deserialize, ToSchema)] @@ -104,10 +96,13 @@ struct SubmitPodcast { format: Option, } -/// The service's receipt for an accepted job, passed through verbatim. +/// The receipt for an accepted job: the backend's own row plus the service's +/// ETA. `state` is always `queued` here — the row was just written. #[derive(Serialize, ToSchema)] struct JobReceipt { - /// The job id the service minted — every other door names it. + /// The backend-minted job id — every other door names it, and the service + /// keys its own record by it. + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] job_id: String, /// `queued` on a fresh job. state: String, @@ -115,7 +110,7 @@ struct JobReceipt { eta_secs: i64, } -/// One job's state, passed through verbatim. +/// One job's state, from the backend's own row. #[derive(Serialize, ToSchema)] struct JobStatus { job_id: String, @@ -129,21 +124,17 @@ struct JobStatus { error_code: Option, } -/// A finished job's artifacts, passed through verbatim. +/// A finished job's artifacts. #[derive(Serialize, ToSchema)] struct JobArtifacts { job_id: String, - /// The produced audio, as a path relative to the school's podcast output - /// root — feed it straight to `GET /podcast/audio?path=…`. - #[schema(example = "ses/duz_okuma/019732e3-7b00-7000-8000-00000000dead/episode.mp3")] + /// The produced audio, as the blob key `GET /podcast/jobs/{id}/audio` + /// streams — informational, never a path the caller resolves itself. + #[schema(example = "podcast/019732e3-7b00-7000-8000-00000000dead.mp3")] audio_id: String, - duration_secs: f64, - script_id: String, - /// One entry per produced chapter; usually `[audio_id]`. - audio_ids: Vec, - /// One entry per script the audio was aligned to. - script_ids: Vec, - format: String, + duration_secs: Option, + /// The resolved narration format. + format: Option, } /// The verdict on a cancel. @@ -155,9 +146,14 @@ struct CancelVerdict { cancelled: bool, } -/// Start one podcast job. Answers `202` with the service's receipt the moment -/// the service accepts it; the pipeline then runs in the service's own worker -/// pool, so poll `GET /jobs/{id}` for progress. +/// Start one podcast job. Answers `202` with the backend's own receipt the +/// moment the service accepts it. +/// +/// The row is written **before** the dispatch, so a poll that races the submit +/// finds the job rather than a `404`; and every dispatch outcome that is not an +/// acceptance leaves the row `failed` with a reason code rather than claiming +/// `queued` forever. With no worker connected the row is not written at all — +/// the `503` is the whole answer. #[utoipa::path( post, path = "/jobs", @@ -175,7 +171,7 @@ struct CancelVerdict { async fn submit( State(st): State, SchoolSlug(slug): SchoolSlug, - CurrentUser(_user): CurrentUser, + CurrentUser(user): CurrentUser, Json(req): Json, ) -> Result { let bridge = match worker_for(&st, AI_PODCAST_SUBMIT_CAPABILITY) { @@ -193,18 +189,53 @@ async fn submit( })); } + let job = jobs::create(&st.db, user.get_id(), source_id, req.format.as_deref()).await?; + let job_id = job.get_id().key(); let payload = PodcastSubmitPayload { + job_id: job_id.clone(), source_id: source_id.to_string(), - format: req.format, + format: req.format.clone(), + user_id: user.get_id().key(), }; match podcast::submit(&bridge, &slug, payload).await { - Ok(reply) => Ok((StatusCode::ACCEPTED, Json(receipt(reply))).into_response()), - Err(code) => Ok(failure(&code)), + // The echo is checked, not trusted: this id is the only handle every + // later call uses, so an answer about some other job is a protocol + // failure, not a receipt. + Ok(reply) if reply.job_id == job_id => { + let eta_secs = reply.eta_secs; + jobs::set_eta(&st.db, job.get_id(), eta_secs).await?; + Ok(( + StatusCode::ACCEPTED, + Json(JobReceipt { + job_id, + state: reply.state, + eta_secs, + }), + ) + .into_response()) + } + Ok(reply) => { + tracing::warn!( + "AI podcast service accepted job {} under the id {}", + job_id, + reply.job_id + ); + jobs::mark_failed(&st.db, job.get_id(), "bad_reply").await?; + Ok(failure("bad_reply")) + } + // The service refused the job: the row is the record of that, and the + // refusal reaches the caller with its own status. + Err(code) => { + jobs::mark_failed(&st.db, job.get_id(), &code).await?; + Ok(failure(&code)) + } } } -/// One job's current state. Poll this; the answer is the service's own -/// snapshot. +/// One job's current state — the backend's own row, so this door answers with +/// the service down, restarted, or never connected at all. A job nobody has +/// updated inside its ETA-scaled window reads as `failed`/`interrupted`; that +/// projection is read-side only and never written. #[utoipa::path( get, path = "/jobs/{id}", @@ -214,29 +245,28 @@ async fn submit( responses( (status = 200, description = "The job as of now", body = JobStatus), (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 404, description = "No such job (the service answered `not_found`)", body = ErrorResponse), - (status = 503, description = "No AI service offers `podcast.status`", body = ErrorResponse), + (status = 404, description = "No such job for this caller (unknown id, or another user's)", body = ErrorResponse), + (status = 410, description = "The job is past its retention window", body = ErrorResponse), ), )] async fn status( State(st): State, - SchoolSlug(slug): SchoolSlug, - CurrentUser(_user): CurrentUser, + CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result { - let bridge = match worker_for(&st, AI_PODCAST_STATUS_CAPABILITY) { - Ok(bridge) => bridge, - Err(no_worker) => return Ok(no_worker.refusal()), - }; - match podcast::status(&bridge, &slug, PodcastStatusPayload { job_id: id }).await { - Ok(reply) => Ok(Json(snapshot(reply)).into_response()), - Err(code) => Ok(failure(&code)), - } + let job = owned(&st, &user, &id).await?; + Ok(Json(JobStatus { + job_id: job.get_id().key(), + state: job.get_state().as_str().to_string(), + stage: job.get_stage().to_string(), + progress: job.get_progress(), + error_code: job.get_error_code().map(str::to_string), + }) + .into_response()) } -/// A finished job's artifacts — above all the `audio_id` the audio door -/// streams. A job that has not finished yet is refused by the service with -/// `not_ready` (409); one it has never heard of with `not_found` (404). +/// A finished job's artifact references. A job that has not finished is a +/// `409 not_ready`; one the caller does not own, a `404`. #[utoipa::path( get, path = "/jobs/{id}/result", @@ -246,109 +276,94 @@ async fn status( responses( (status = 200, description = "The finished job's artifacts", body = JobArtifacts), (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 404, description = "No such job (the service answered `not_found`)", body = ErrorResponse), - (status = 409, description = "The job has not finished (the service answered `not_ready`)", body = ErrorResponse), - (status = 503, description = "No AI service offers `podcast.result`", body = ErrorResponse), + (status = 404, description = "No such job for this caller", body = ErrorResponse), + (status = 409, description = "The job has not finished (`code: not_ready`)", body = ErrorResponse), + (status = 410, description = "The job is past its retention window", body = ErrorResponse), ), )] async fn result( State(st): State, - SchoolSlug(slug): SchoolSlug, - CurrentUser(_user): CurrentUser, + CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result { - let bridge = match worker_for(&st, AI_PODCAST_RESULT_CAPABILITY) { - Ok(bridge) => bridge, - Err(no_worker) => return Ok(no_worker.refusal()), - }; - match podcast::result(&bridge, &slug, PodcastResultPayload { job_id: id }).await { - Ok(reply) => Ok(Json(artifacts(reply)).into_response()), - Err(code) => Ok(failure(&code)), - } -} - -/// Cancel one job. `cancelled` says whether *this call* stopped work — a job -/// that had already finished, or was already cancelled, answers `false` and is -/// not an error. -#[utoipa::path( - post, - path = "/jobs/{id}/cancel", - tag = "podcast", - security(("session_cookie" = [])), - params(("id" = String, Path, description = "Job id from `POST /podcast/jobs`")), - responses( - (status = 200, description = "The cancel verdict", body = CancelVerdict), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 404, description = "No such job (the service answered `not_found`)", body = ErrorResponse), - (status = 503, description = "No AI service offers `podcast.cancel`", body = ErrorResponse), - ), -)] -async fn cancel( - State(st): State, - SchoolSlug(slug): SchoolSlug, - CurrentUser(_user): CurrentUser, - Path(id): Path, -) -> Result { - let bridge = match worker_for(&st, AI_PODCAST_CANCEL_CAPABILITY) { - Ok(bridge) => bridge, - Err(no_worker) => return Ok(no_worker.refusal()), + let job = owned(&st, &user, &id).await?; + let audio_id = match job.get_state() { + crate::domain::podcast_job::PodcastJobState::Done => job + .get_audio_key() + .expect("a done row always carries its audio (schema CHECK)") + .to_string(), + _ => { + return Err(AppError::ConflictCoded { + code: "not_ready", + message: format!("job `{}` is {}", job.get_id().key(), job.get_state().as_str()), + }); + } }; - match podcast::cancel(&bridge, &slug, PodcastCancelPayload { job_id: id }).await { - Ok(reply) => Ok(Json(verdict(reply)).into_response()), - Err(code) => Ok(failure(&code)), - } -} - -/// The query behind the audio door. -#[derive(Deserialize, IntoParams)] -struct AudioQuery { - /// The `audio_id` from `GET /podcast/jobs/{id}/result`, **verbatim**: a - /// path relative to this school's podcast output root. - #[param(example = "ses/duz_okuma/019732e3-7b00-7000-8000-00000000dead/episode.mp3")] - path: String, + Ok(Json(JobArtifacts { + job_id: job.get_id().key(), + audio_id, + duration_secs: job.get_duration_secs(), + format: job.get_format().map(str::to_string), + }) + .into_response()) } -/// Stream one produced audio file. `path` is the `audio_id` -/// `podcast.result` answered, resolved under **this caller's school** output -/// directory — the same directory the service's `PODCAST_OUTPUT_ROOT` points -/// at — and streamed in 64 KiB chunks, so a long episode costs the backend a -/// bounded buffer rather than its whole length in memory. +/// Stream one produced episode. The bytes are this school's own — ingested +/// under this school's blob directory — and the content type is the one the +/// upload declared, replayed from the row. /// -/// The path is hostile input: a leading `/`, any `.`/`..` segment, a -/// backslash, a drive colon, or a symlink whose target resolves outside the -/// school's directory is a `400` (a path this backend will not resolve), not a -/// `404` — a caller probing the boundary gets the truth, and a caller with a -/// legitimate `audio_id` never sees either. +/// A job that is not `done` is a `409 not_ready`; a row whose blob is missing +/// from the host is a `409 audio_missing` (the row is intact, the bytes are +/// not — a state a client can report, unlike a generic `500`). #[utoipa::path( get, - path = "/audio", + path = "/jobs/{id}/audio", tag = "podcast", security(("session_cookie" = [])), + params(("id" = String, Path, description = "Job id from `POST /podcast/jobs`")), responses( (status = 200, description = "The audio bytes", content_type = "audio/mpeg"), - (status = 400, description = "`path` is not a relative path inside this school's podcast output", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 404, description = "No such file in this school's podcast output", body = ErrorResponse), + (status = 404, description = "No such job for this caller", body = ErrorResponse), + (status = 409, description = "Not finished yet (`not_ready`), or its blob is missing from this host (`audio_missing`)", body = ErrorResponse), + (status = 410, description = "The job is past its retention window", body = ErrorResponse), ), )] async fn audio( State(st): State, - CurrentUser(_user): CurrentUser, - Query(query): Query, + CurrentUser(user): CurrentUser, + Path(id): Path, ) -> Result { - // The school-scoped `State` has already narrowed `files_path` to the - // caller's own directory under `FILES_PATH` — the very directory the - // service's `PODCAST_OUTPUT_ROOT` points at — so the containment root here - // needs no school arithmetic of its own, and cannot drift from the one - // every other blob route uses. - let file_path = resolve_audio(&st.files_path, &query.path).await?; - let file = tokio::fs::File::open(&file_path) - .await - .map_err(|_| AppError::NotFound)?; + let job = owned(&st, &user, &id).await?; + let key = match job.get_state() { + crate::domain::podcast_job::PodcastJobState::Done => job + .get_audio_key() + .expect("a done row always carries its audio (schema CHECK)") + .to_string(), + _ => { + return Err(AppError::ConflictCoded { + code: "not_ready", + message: format!("job `{}` is {}", job.get_id().key(), job.get_state().as_str()), + }); + } + }; + let path = crate::web::blob_path(&st.files_path, &key); + let file = tokio::fs::File::open(&path).await.map_err(|err| { + tracing::error!("missing blob for podcast job {}: {err}", job.get_id().key()); + AppError::ConflictCoded { + code: "audio_missing", + message: "the episode's file is missing on this host".to_string(), + } + })?; + let content_type = job.get_audio_type().unwrap_or("application/octet-stream"); Ok(( [ - (CONTENT_TYPE, HeaderValue::from_static(audio_content_type(&file_path))), + ( + CONTENT_TYPE, + HeaderValue::from_str(content_type) + .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream")), + ), (X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")), (CACHE_CONTROL, HeaderValue::from_static("private, no-store")), ], @@ -357,84 +372,91 @@ async fn audio( .into_response()) } -/// Resolve one `audio_id` into a real file under `root`, or refuse it. -/// -/// The order is the point: shape first (so an absolute path or a `..` segment -/// never reaches the filesystem), then canonicalization — which follows every -/// symlink, so a link that only *looks* like it lives under the root resolves -/// out of it and is refused by the containment check rather than served. -async fn resolve_audio( - root: &std::path::Path, - relative: &str, -) -> Result { - let refused = || { - AppError::Validation(ValidationError::Invalid { - field: "path", - reason: "must be a relative path inside this school's podcast output", +/// Cancel one job. `cancelled` says whether *this call* stopped work — a job +/// that had already finished, or was already cancelled, answers `false` and is +/// not an error. Only a live job needs the service; a terminal one is answered +/// from the row without a worker. A service that has never heard of a live job +/// (its store was wiped) leaves the row `failed`/`interrupted`: the job cannot +/// finish, and the row says so. +#[utoipa::path( + post, + path = "/jobs/{id}/cancel", + tag = "podcast", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Job id from `POST /podcast/jobs`")), + responses( + (status = 200, description = "The cancel verdict", body = CancelVerdict), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "No such job for this caller", body = ErrorResponse), + (status = 410, description = "The job is past its retention window", body = ErrorResponse), + (status = 503, description = "The job is live but no AI service offers `podcast.cancel`", body = ErrorResponse), + ), +)] +async fn cancel( + State(st): State, + SchoolSlug(slug): SchoolSlug, + CurrentUser(user): CurrentUser, + Path(id): Path, +) -> Result { + let job = owned(&st, &user, &id).await?; + let job_id = job.get_id().key(); + if job.get_state().is_terminal() { + return Ok(Json(CancelVerdict { + job_id, + cancelled: false, }) - }; - - if relative.is_empty() || relative.starts_with('/') { - return Err(refused()); - } - // Neither byte appears in a path this backend produced: `\` is a separator - // on another platform, `:` is a drive designator there — and a NUL could - // only truncate the path inside the OS. Refused here, not left to the - // platform's rules. - if relative.contains('\\') || relative.contains(':') || relative.contains('\0') { - return Err(refused()); - } - // Any `.`/`..` segment, or an empty one (`a//b`): the shape a traversal - // needs, refused before anything is joined. - if relative - .split('/') - .any(|segment| segment.is_empty() || segment == "." || segment == "..") - { - return Err(refused()); + .into_response()); } - - // The root is canonicalized too: `FILES_PATH` may itself be reached - // through a symlink, and containment must compare real paths. - let root = tokio::fs::canonicalize(root) - .await - .map_err(|_| AppError::NotFound)?; - let target = tokio::fs::canonicalize(root.join(relative)) - .await - .map_err(|_| AppError::NotFound)?; - - // Symlink escape: `canonicalize` follows links, so a target that resolves - // outside the school's directory lands here, whatever the link looked like. - if !target.starts_with(&root) { - return Err(refused()); - } - // A directory is not an audio file — and serving `read` on it would be an - // I/O error at best. - if !tokio::fs::metadata(&target) - .await - .map(|meta| meta.is_file()) - .unwrap_or(false) + let bridge = match worker_for(&st, AI_PODCAST_CANCEL_CAPABILITY) { + Ok(bridge) => bridge, + Err(no_worker) => return Ok(no_worker.refusal()), + }; + let verdict = |cancelled: bool| { + Json(CancelVerdict { + job_id: job.get_id().key(), + cancelled, + }) + .into_response() + }; + match podcast::cancel( + &bridge, + &slug, + PodcastCancelPayload { + job_id: job_id.clone(), + }, + ) + .await { - return Err(AppError::NotFound); + Ok(reply) if reply.cancelled => { + jobs::mark_cancelled(&st.db, job.get_id()).await?; + Ok(verdict(true)) + } + // Not cancelled by this call: either it finished first (its terminal + // report is on its way) or it was already cancelled. + Ok(_) => Ok(verdict(false)), + // The service has never heard of a job the row calls live — its store + // was wiped or rolled back. The row records the truth: it cannot finish. + Err(code) if code == "not_found" => { + tracing::warn!("AI podcast service lost live job {job_id}"); + jobs::mark_failed(&st.db, job.get_id(), PODCAST_INTERRUPTED_CODE).await?; + Ok(verdict(false)) + } + Err(code) => Ok(failure(&code)), } - Ok(target) } -/// The content type for a produced artifact, by extension. `mp3` is what the -/// pipeline writes today; the rest of the set is here so a format switch on the -/// service side still serves as audio rather than as an opaque download. -fn audio_content_type(path: &std::path::Path) -> &'static str { - match path - .extension() - .and_then(|ext| ext.to_str()) - .map(str::to_ascii_lowercase) - .as_deref() - { - Some("mp3") => "audio/mpeg", - Some("wav") => "audio/wav", - Some("m4a") | Some("mp4") => "audio/mp4", - Some("ogg") | Some("oga") | Some("opus") => "audio/ogg", - _ => "application/octet-stream", +/// Read one job for this caller, projected and expiry-checked — the three +/// reading doors' shared first act. A foreign id and an unknown id are the +/// same `404`; a job past its retention window is a `410`. +async fn owned(st: &AppState, user: &User, id: &str) -> Result { + let job = jobs::read_for(&st.db, &PodcastJobId::from_key(id), user.get_id()) + .await? + .ok_or(AppError::NotFound)? + .projected(); + if job.is_expired() { + return Err(AppError::Expired("this podcast job has expired")); } + Ok(job) } /// A file as a byte stream: a reader task hands chunks to the body over a @@ -442,19 +464,15 @@ fn audio_content_type(path: &std::path::Path) -> &'static str { /// send instead of pinning the whole file in memory, and a closed body ends the /// task by itself. fn pump(file: tokio::fs::File) -> impl Stream> + Send + 'static { - let (tx, rx) = mpsc::channel(AUDIO_CHUNKS_IN_FLIGHT); + let (tx, rx) = mpsc::channel::>(AUDIO_CHUNKS_IN_FLIGHT); tokio::spawn(async move { let mut file = file; - let mut buffer = vec![0u8; AUDIO_CHUNK_BYTES]; + let mut buf = vec![0u8; AUDIO_CHUNK_BYTES]; loop { - match file.read(&mut buffer).await { + match tokio::io::AsyncReadExt::read(&mut file, &mut buf).await { Ok(0) => break, - Ok(read) => { - if tx - .send(Ok(Bytes::copy_from_slice(&buffer[..read]))) - .await - .is_err() - { + Ok(n) => { + if tx.send(Ok(Bytes::copy_from_slice(&buf[..n]))).await.is_err() { break; } } @@ -490,7 +508,7 @@ impl NoWorker { } } -/// The 503 gate every dispatching door shares: no bridge configured, or no +/// The 503 gate the two dispatching doors share: no bridge configured, or no /// worker declaring this door's capability. `has_capability` is documented /// racy — fine here: it never guards a write, and the dispatch that follows /// re-checks for real; this only spares a caller a round trip into a service @@ -523,40 +541,3 @@ fn failure(code: &str) -> Response { }; (status, Json(json!({ "error": code }))).into_response() } - -fn receipt(reply: PodcastSubmitReply) -> JobReceipt { - JobReceipt { - job_id: reply.job_id, - state: reply.state, - eta_secs: reply.eta_secs, - } -} - -fn snapshot(reply: PodcastStatusReply) -> JobStatus { - JobStatus { - job_id: reply.job_id, - state: reply.state, - stage: reply.stage, - progress: reply.progress, - error_code: reply.error_code, - } -} - -fn artifacts(reply: PodcastResultReply) -> JobArtifacts { - JobArtifacts { - job_id: reply.job_id, - audio_id: reply.audio_id, - duration_secs: reply.duration_secs, - script_id: reply.script_id, - audio_ids: reply.audio_ids, - script_ids: reply.script_ids, - format: reply.format, - } -} - -fn verdict(reply: PodcastCancelReply) -> CancelVerdict { - CancelVerdict { - job_id: reply.job_id, - cancelled: reply.cancelled, - } -} diff --git a/src/web/room.rs b/src/web/room.rs index a47c429..0d2068f 100644 --- a/src/web/room.rs +++ b/src/web/room.rs @@ -120,6 +120,7 @@ pub(crate) fn public_message(err: &AppError, room: &str) -> String { match err { AppError::Validation(err) => err.to_string(), AppError::NotFound => "not found".to_string(), + AppError::Expired(message) => (*message).to_string(), AppError::Unauthorized => "unauthorized".to_string(), AppError::Forbidden(message) => (*message).to_string(), AppError::Conflict(message) => (*message).to_string(), diff --git a/tests/integration.rs b/tests/integration.rs index 3755559..3e2db3b 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -434,7 +434,7 @@ async fn protected_routes_require_session() { /// Floor on the number of protected operations swept. It only ever goes /// up: raise it when routes are added. Without it, deleting a route family /// would delete its own coverage and still pass. - const MIN_PROTECTED: usize = 323; + const MIN_PROTECTED: usize = 337; let app = mem_app().await; let spec = send(&app, "GET", "/api-docs/openapi.json", None, None) diff --git a/tests/podcast.rs b/tests/podcast.rs index 9ff4162..f75bf17 100644 --- a/tests/podcast.rs +++ b/tests/podcast.rs @@ -2,16 +2,18 @@ //! //! Everything here runs over a real QUIC socket on loopback — a real //! handshake, real TLS, real streams — with [`Behaviour::Podcast`] standing in -//! for what the service would do with a request. The four dispatching doors -//! are driven through the real router, so what they assert is what a browser -//! would receive, and the fake service's `seen` log is what the *service* -//! received. +//! for what the service does with a request. The **backend owns the job**: the +//! submit door mints the id, writes the `podcast_job` row, and only then +//! dispatches `podcast.submit`; the three reading doors answer from that row +//! alone; and the service reports every transition and uploads the finished +//! episode on its own client-initiated streams — the same connection it +//! registered with, exactly the shape `tests/ai_bridge.rs` drives. //! -//! The audio door is tested against a real directory tree — the same -//! `FILES_PATH` layout the deployment uses — because its whole job is refusing -//! paths that escape a school's directory. Every refusal test first proves the -//! target file exists, so a pass cannot come from the file simply being -//! missing. +//! The assertions therefore split in two: what a browser gets from the real +//! router, and what the *service* received ([`FakeService::seen`]) or what the +//! school's own database and blob directory hold. A reading door that quietly +//! round-tripped to the service would fail the `seen` assertions; a submit that +//! did not write its row first would fail the database ones. mod common; @@ -19,35 +21,40 @@ use std::sync::{Arc, Mutex}; use std::time::Duration; use axum::Router; -use axum::http::StatusCode; +use axum::http::{HeaderMap, StatusCode}; use hezarfen_backend::ai::protocol::{ Greeting, Hello, Request, Response, read_frame, write_frame, }; use hezarfen_backend::ai::{AiBridge, BridgeConfig}; use hezarfen_backend::constant::{ - AI_ALPN, AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_RESULT_CAPABILITY, - AI_PODCAST_STATUS_CAPABILITY, AI_PODCAST_SUBMIT_CAPABILITY, AI_PROTOCOL, + AI_ALPN, AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_SUBMIT_CAPABILITY, AI_PROTOCOL, + PODCAST_JOB_RETENTION_SECS, PODCAST_JOB_STALE_FLOOR_SECS, }; +use hezarfen_backend::database::Database; +use hezarfen_backend::domain::timestamp::Timestamp; use hezarfen_backend::module::{Module, ModuleSet}; use hezarfen_backend::tenant::{DEMO_SLUG, Slug}; use serde_json::{Value, json}; +use uuid::Uuid; const TOKEN: &str = "shared-ai-token"; -/// The four capabilities one podcast service declares. -const CAPABILITIES: [&str; 4] = [ - AI_PODCAST_SUBMIT_CAPABILITY, - AI_PODCAST_STATUS_CAPABILITY, - AI_PODCAST_RESULT_CAPABILITY, - AI_PODCAST_CANCEL_CAPABILITY, -]; - -/// The job id the fake service mints, and the `audio_id` it answers — a path -/// relative to the school's output root, exactly as the real service writes it. -const JOB_ID: &str = "job-1"; -const AUDIO_ID: &str = "ses/duz_okuma/bolum-1/episode.mp3"; +/// The two capabilities a live podcast worker offers. Status and result are +/// not capabilities any more — the backend answers those from its own row — so +/// a service declaring only these serves every reading door. +const CAPABILITIES: [&str; 2] = [AI_PODCAST_SUBMIT_CAPABILITY, AI_PODCAST_CANCEL_CAPABILITY]; + /// A source id shaped like the backend ids the service is handed. const SOURCE_ID: &str = "019732e3-7b00-7000-8000-00000000dead"; +/// The narration the caller asks for; the reports echo the same value, as the +/// service's first report resolves it. +const FORMAT: &str = "duz_okuma"; +/// The estimate the fake service answers a submit with. +const ETA_SECS: i64 = 2700; +/// What the fake service says its uploaded episode runs for. +const DURATION_SECS: f64 = 12.5; +const AUDIO_NAME: &str = "bolum-1.mp3"; +const AUDIO_TYPE: &str = "audio/mpeg"; // ---------------------------------------------------------------- harness -- @@ -103,10 +110,13 @@ fn hello(service: &str, capabilities: &[&str]) -> Hello { } /// A connected fake service. Holding it keeps the connection (and so the -/// registration) alive; dropping it is how a test simulates a crash. +/// registration) alive; dropping it is how a test simulates a crash. `conn` is +/// the registration connection itself — the one a real service opens its own +/// streams on when it reports a transition or uploads an episode. struct FakeService { _endpoint: quinn::Endpoint, _control: (quinn::SendStream, quinn::RecvStream), + conn: quinn::Connection, /// Every request this service received, in arrival order. seen: Arc>>, } @@ -120,10 +130,12 @@ impl FakeService { /// What the fake service does with each request it receives. #[derive(Clone)] enum Behaviour { - /// Answer like the podcast service: a queued receipt, a status snapshot, a - /// finished job's artifacts, a cancel verdict — each echoing the job id it - /// was asked about, so a mis-routed id shows up in the answer. + /// Answer like the podcast service: a receipt echoing the backend's own + /// job id, and a cancel verdict. Podcast, + /// Accept the job under an id of the service's own choosing — the one + /// answer the submit door must not trust. + WrongEcho, /// Answer with a handled failure. Fail { code: String, message: String }, } @@ -149,6 +161,7 @@ async fn connect_service(bridge: &AiBridge, hello: Hello, behaviour: Behaviour) FakeService { _endpoint: endpoint, _control: (send, recv), + conn, seen, } } @@ -165,23 +178,26 @@ fn serve(conn: quinn::Connection, behaviour: Behaviour, seen: Arc Some(Response::Ok { + Behaviour::Podcast => Response::Ok { id: request.id.clone(), school: request.school.clone(), payload: podcast_answer(&request), - }), - Behaviour::Fail { code, message } => Some(Response::Err { + }, + Behaviour::WrongEcho => Response::Ok { + id: request.id.clone(), + school: request.school.clone(), + payload: wrong_echo_answer(), + }, + Behaviour::Fail { code, message } => Response::Err { id: request.id.clone(), school: request.school.clone(), code, message, - }), + }, }; - if let Some(response) = response { - let _ = write_frame(&mut send, &response).await; - let _ = send.finish(); - let _ = send.stopped().await; - } + let _ = write_frame(&mut send, &response).await; + let _ = send.finish(); + let _ = send.stopped().await; }); } }); @@ -189,36 +205,27 @@ fn serve(conn: quinn::Connection, behaviour: Behaviour, seen: Arc Value { - let job_id = request - .payload - .get("job_id") - .cloned() - .unwrap_or_else(|| json!(JOB_ID)); match request.capability.as_str() { - AI_PODCAST_SUBMIT_CAPABILITY => { - json!({ "job_id": JOB_ID, "state": "queued", "eta_secs": 2700 }) - } - AI_PODCAST_STATUS_CAPABILITY => json!({ - "job_id": job_id, - "state": "running", - "stage": "tts", - "progress": 0.5, - "error_code": null, + // The receipt must echo the backend's own job id — the id every later + // call names — so the fake echoes the payload it was handed. + AI_PODCAST_SUBMIT_CAPABILITY => json!({ + "job_id": request.payload["job_id"], + "state": "queued", + "eta_secs": ETA_SECS, }), - AI_PODCAST_RESULT_CAPABILITY => json!({ - "job_id": job_id, - "audio_id": AUDIO_ID, - "duration_secs": 12.5, - "script_id": "script-1", - "audio_ids": [AUDIO_ID], - "script_ids": ["script-1"], - "format": "duz_okuma", + AI_PODCAST_CANCEL_CAPABILITY => json!({ + "job_id": request.payload["job_id"], + "cancelled": true, }), - AI_PODCAST_CANCEL_CAPABILITY => json!({ "job_id": job_id, "cancelled": true }), other => panic!("the fake podcast service was asked for `{other}`"), } } +/// The receipt of a service that keyed the job by an id it minted itself. +fn wrong_echo_answer() -> Value { + json!({ "job_id": "019732e3-7b00-7000-8000-00000000beef", "state": "queued", "eta_secs": 60 }) +} + /// Registration completes asynchronously after the welcome is on the wire, so /// tests that assert on the registry wait for it rather than racing it. async fn await_workers(bridge: &AiBridge, expected: usize) { @@ -234,9 +241,11 @@ async fn await_workers(bridge: &AiBridge, expected: usize) { ); } -/// A registered podcast service offering all four capabilities, the router -/// wired to its bridge, and a logged-in student's cookie. -async fn podcast_app() -> (FakeService, Router, String) { +/// A registered podcast service offering the two capabilities a live worker +/// needs, the router wired to its bridge, a logged-in student's cookie, and +/// the school's database handle — the fixture every round-trip test starts +/// from. +async fn podcast_app() -> (FakeService, Router, String, Database) { let bridge = bridge().await; let service = connect_service( &bridge, @@ -245,39 +254,347 @@ async fn podcast_app() -> (FakeService, Router, String) { ) .await; await_workers(&bridge, 1).await; - let (app, _db) = common::app_with_ai(Some(bridge)).await; + let (app, db) = common::app_with_ai(Some(bridge)).await; let cookie = common::login(&app, "ali").await; - (service, app, cookie) + (service, app, cookie, db) } +/// A logged-in caller and the school's database, with **no AI service in the +/// picture at all**: the reading doors answer from the row, so the lifetime +/// rules and the read refusals need no worker — and a dispatch would be +/// impossible. +async fn app_without_ai() -> (Router, String, Database) { + let (app, db) = common::app_and_db().await; + let cookie = common::login(&app, "ali").await; + (app, cookie, db) +} + +// ------------------------------------------------------------- http doors -- + /// Submit one job and return the response. async fn submit(app: &Router, cookie: &str, body: Value) -> common::Res { common::send(app, "POST", "/podcast/jobs", Some(cookie), Some(body)).await } +/// Submit one job with the standard body (asserting the `202`) and hand back +/// the backend-minted id every other door names. +async fn submit_job(app: &Router, cookie: &str) -> String { + let res = submit( + app, + cookie, + json!({ "source_id": SOURCE_ID, "format": FORMAT }), + ) + .await; + assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); + res.body["job_id"] + .as_str() + .expect("the receipt names the job") + .to_string() +} + +/// One `GET /podcast/jobs/{id}`. +async fn status_of(app: &Router, cookie: &str, id: &str) -> common::Res { + common::send(app, "GET", &format!("/podcast/jobs/{id}"), Some(cookie), None).await +} + +/// One `GET /podcast/jobs/{id}/result`. +async fn result_of(app: &Router, cookie: &str, id: &str) -> common::Res { + common::send( + app, + "GET", + &format!("/podcast/jobs/{id}/result"), + Some(cookie), + None, + ) + .await +} + +/// One `POST /podcast/jobs/{id}/cancel`. +async fn cancel_of(app: &Router, cookie: &str, id: &str) -> common::Res { + common::send( + app, + "POST", + &format!("/podcast/jobs/{id}/cancel"), + Some(cookie), + None, + ) + .await +} + +/// One `GET /podcast/jobs/{id}/audio`, raw — the body is audio bytes or a JSON +/// refusal, never a parsed envelope. +async fn audio_of(app: &Router, cookie: &str, id: &str) -> (StatusCode, HeaderMap, Vec) { + common::send_raw( + app, + "GET", + &format!("/podcast/jobs/{id}/audio"), + Some(cookie), + None, + Vec::new(), + ) + .await +} + +// ------------------------------------------------------------ service i/o -- + +/// One `podcast.report` call, exactly as the real service writes it: a +/// client-initiated capability frame on the connection it registered with, +/// echoing the job's own identity — the backend refuses a report that +/// describes a different job. +fn report_frame(job_id: &str, user_id: &str, state: &str, stage: &str, progress: f64) -> Value { + json!({ + "id": format!("report-{state}"), + "school": DEMO_SLUG, + "capability": "podcast.report", + "payload": { + "job_id": job_id, + "source_id": SOURCE_ID, + "format": FORMAT, + "user_id": user_id, + "state": state, + "stage": stage, + "progress": progress, + "error_code": null, + }, + }) +} + +/// One `BlobUploadRequest` for `job_id`, declaring the header of the bytes +/// that follow it on the same stream. +fn upload_frame(job_id: &str, name: &str, content_type: &str, size: usize) -> Value { + json!({ + "id": format!("upload-{job_id}"), + "upload": true, + "school": DEMO_SLUG, + "job_id": job_id, + "name": name, + "content_type": content_type, + "size": size, + "duration_secs": DURATION_SECS, + }) +} + +/// Send one client-initiated frame and read the one frame the backend answers +/// with — the shape every service→backend call rides. +async fn capability_call(conn: &quinn::Connection, request: Value) -> Value { + let (mut send, mut recv) = conn.open_bi().await.expect("client-initiated stream"); + write_frame(&mut send, &request).await.expect("write the call"); + let _ = send.finish(); + read_frame::<_, Value>(&mut recv).await.expect("read the answer") +} + +/// One audio upload on a fresh client-initiated stream: the header frame, +/// exactly `body.len()` raw bytes, FIN — then the backend's one answer frame. +async fn blob_upload(conn: &quinn::Connection, frame: Value, body: &[u8]) -> Value { + let (mut send, mut recv) = conn.open_bi().await.expect("upload stream"); + write_frame(&mut send, &frame) + .await + .expect("write the upload frame"); + send.write_all(body).await.expect("write the audio bytes"); + let _ = send.finish(); + read_frame::<_, Value>(&mut recv) + .await + .expect("read the upload answer") +} + +/// Assert one report was stored: the answer's payload echoes the job and says +/// `stored` — an unstored report is a refusal, never a quiet success. +fn assert_report_stored(answer: &Value, job_id: &str) { + assert_eq!(answer["status"], "ok", "{answer}"); + assert_eq!(answer["payload"]["job_id"], job_id); + assert_eq!(answer["payload"]["stored"], true); +} + +/// The flat refusal code out of one capability answer frame. +fn refusal_code(answer: &Value) -> String { + assert_eq!(answer["status"], "err", "{answer}"); + answer["code"] + .as_str() + .expect("a refusal carries its code") + .to_string() +} + +// ------------------------------------------------------------------- rows -- + +fn uuid_of(key: &str) -> Uuid { + Uuid::parse_str(key).expect("a uuid key") +} + +/// The wall clock in unix milliseconds — the unit every timestamp column here +/// stores. +fn now_ms() -> i64 { + Timestamp::now().as_millis() +} + +/// How many podcast jobs this user has on the books. +async fn rows_for(db: &Database, user: &str) -> i64 { + sqlx::query_scalar("SELECT count(*) FROM podcast_job WHERE user_id = $1") + .bind(uuid_of(user)) + .fetch_one(db) + .await + .expect("count the user's jobs") +} + +/// Write one job row by hand. The shapes the reading doors' own lifetime rules +/// are about — untouched past the staleness window, aged out of retention — +/// are ones no door can mint, so the fixture writes them directly. +async fn seed_job( + db: &Database, + job: Uuid, + user: &str, + state: &str, + eta_secs: Option, + updated_at: i64, +) -> Uuid { + sqlx::query( + "INSERT INTO podcast_job (id, user_id, source_id, state, stage, progress, \ + eta_secs, created_at, updated_at) \ + VALUES ($1, $2, $3, $4, '', 0, $5, $6, $6)", + ) + .bind(job) + .bind(uuid_of(user)) + .bind(SOURCE_ID) + .bind(state) + .bind(eta_secs) + .bind(updated_at) + .execute(db) + .await + .expect("seed the job row"); + job +} + +/// The same, but `done` and naming an artifact: the row shape the audio door +/// reads its key and headers from, whether or not the bytes are still on disk. +async fn seed_done_job( + db: &Database, + job: Uuid, + user: &str, + key: &str, + bytes: i64, + updated_at: i64, +) -> Uuid { + sqlx::query( + "INSERT INTO podcast_job (id, user_id, source_id, state, stage, progress, \ + audio_key, audio_name, audio_type, audio_bytes, duration_secs, \ + created_at, updated_at) \ + VALUES ($1, $2, $3, 'done', '', 1, $4, $5, $6, $7, $8, $9, $9)", + ) + .bind(job) + .bind(uuid_of(user)) + .bind(SOURCE_ID) + .bind(key) + .bind(AUDIO_NAME) + .bind(AUDIO_TYPE) + .bind(bytes) + .bind(DURATION_SECS) + .bind(updated_at) + .execute(db) + .await + .expect("seed the done row"); + job +} + +/// Write `bytes` at `key` under the demo school's blob directory — the layout +/// an ingested episode lands in, and the only place the audio door reads. +fn write_blob(key: &str, bytes: &[u8]) { + let path = common::blob_dir().join(key); + std::fs::create_dir_all(path.parent().expect("parent dir")).expect("create the blob tree"); + std::fs::write(&path, bytes).expect("write the blob"); + assert!(path.is_file(), "the fixture blob really landed"); +} + +/// Deterministic pseudo-random episode bytes, past one 64 KiB read chunk so a +/// passing door proves it streamed the body rather than fitting one write. +fn episode_bytes() -> Vec { + let mut state = 0x2545_F491_4F6C_DD1Du64; + (0..128 * 1024) + .map(|_| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state as u8 + }) + .collect() +} + // ------------------------------------------------------------ round trips -- +/// The submit door writes the row before it dispatches, and hands the service +/// the id it minted — the one handle every later call names. A service keying +/// its own record by what it was sent can therefore never disagree with the +/// row, and the receipt carries the service's own ETA. #[tokio::test] -async fn a_submit_round_trips_the_source_and_format_to_the_service() { - let (service, app, cookie) = podcast_app().await; +async fn a_submit_writes_the_row_and_hands_the_service_its_own_job_id() { + let (service, app, cookie, db) = podcast_app().await; + let user = common::me_id(&app, &cookie).await; let res = submit( &app, &cookie, - json!({ "source_id": SOURCE_ID, "format": "duz_okuma" }), + json!({ "source_id": SOURCE_ID, "format": FORMAT }), ) .await; assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); - assert_eq!(res.body["job_id"], JOB_ID); assert_eq!(res.body["state"], "queued"); - assert_eq!(res.body["eta_secs"], 2700); + assert_eq!(res.body["eta_secs"], ETA_SECS); + let job_id = res.body["job_id"] + .as_str() + .expect("the receipt names the job") + .to_string(); let seen = service.seen(); assert_eq!(seen.len(), 1, "exactly one dispatch"); assert_eq!(seen[0].capability, AI_PODCAST_SUBMIT_CAPABILITY); assert_eq!(seen[0].school, DEMO_SLUG, "the school rides the frame"); + assert_eq!( + seen[0].payload["job_id"], job_id, + "the service was handed the row's own id" + ); assert_eq!(seen[0].payload["source_id"], SOURCE_ID); - assert_eq!(seen[0].payload["format"], "duz_okuma"); + assert_eq!(seen[0].payload["format"], FORMAT); + assert_eq!(seen[0].payload["user_id"], user); + + let (state, eta, source): (String, Option, String) = + sqlx::query_as("SELECT state, eta_secs, source_id FROM podcast_job WHERE id = $1") + .bind(uuid_of(&job_id)) + .fetch_one(&db) + .await + .expect("the row is on the books"); + assert_eq!(state, "queued"); + assert_eq!(eta, Some(ETA_SECS), "the service's estimate landed on the row"); + assert_eq!(source, SOURCE_ID); +} + +/// A service that accepts the job under an id of its own has answered about a +/// different job: the echo is checked, not trusted, because the backend's id is +/// the only handle every later call uses. The refusal is a `502` — the backend +/// cannot vouch for an answer it did not understand — and the row is +/// tombstoned rather than left claiming `queued` forever. +#[tokio::test] +async fn a_submit_that_echoes_another_job_id_is_a_bad_gateway() { + let bridge = bridge().await; + let _service = + connect_service(&bridge, hello("podcast", &CAPABILITIES), Behaviour::WrongEcho).await; + await_workers(&bridge, 1).await; + let (app, db) = common::app_with_ai(Some(bridge)).await; + let cookie = common::login(&app, "ali").await; + let user = common::me_id(&app, &cookie).await; + + let res = submit(&app, &cookie, json!({ "source_id": SOURCE_ID })).await; + assert_eq!(res.status, StatusCode::BAD_GATEWAY, "{}", res.body); + assert_eq!(res.body["error"], "bad_reply"); + + let rows: Vec<(String, Option)> = + sqlx::query_as("SELECT state, error_code FROM podcast_job WHERE user_id = $1") + .bind(uuid_of(&user)) + .fetch_all(&db) + .await + .expect("read back the tombstone"); + assert_eq!( + rows, + vec![("failed".to_string(), Some("bad_reply".to_string()))], + "exactly one row, and it records why" + ); } /// The format is optional and the service applies its own default: an omitted @@ -285,7 +602,7 @@ async fn a_submit_round_trips_the_source_and_format_to_the_service() { /// distinguish "absent" from "empty". #[tokio::test] async fn an_omitted_format_is_not_sent_at_all() { - let (service, app, cookie) = podcast_app().await; + let (service, app, cookie, _db) = podcast_app().await; let res = submit(&app, &cookie, json!({ "source_id": SOURCE_ID })).await; assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); @@ -299,375 +616,513 @@ async fn an_omitted_format_is_not_sent_at_all() { ); } -/// A blank source id is refused here, before the bridge: the service would -/// refuse it too, and a round trip to learn that is a round trip wasted. +/// A blank source id is refused here, before the bridge and before the row: +/// the service would refuse it too, and a round trip to learn that is a round +/// trip wasted. #[tokio::test] -async fn a_blank_source_id_is_refused_before_dispatch() { - let (service, app, cookie) = podcast_app().await; +async fn a_blank_source_id_is_refused_before_anything_is_written() { + let (service, app, cookie, db) = podcast_app().await; + let user = common::me_id(&app, &cookie).await; let res = submit(&app, &cookie, json!({ "source_id": " " })).await; assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); assert!(service.seen().is_empty(), "nothing reaches the service"); + assert_eq!(rows_for(&db, &user).await, 0, "and no row is written"); } +/// A report lands on the row, and the reading doors answer from it: the +/// service's `seen` log must not grow, because `podcast.status` and +/// `podcast.result` are not calls the backend makes any more — a relayed read +/// would show up here as a second request. #[tokio::test] -async fn a_status_read_round_trips_the_job_id() { - let (service, app, cookie) = podcast_app().await; +async fn a_running_report_lands_on_the_row_and_the_reads_stay_off_the_service() { + let (service, app, cookie, db) = podcast_app().await; + let user = common::me_id(&app, &cookie).await; + let job_id = submit_job(&app, &cookie).await; + + assert_report_stored( + &capability_call( + &service.conn, + report_frame(&job_id, &user, "running", "tts", 0.5), + ) + .await, + &job_id, + ); - let res = common::send( - &app, - "GET", - &format!("/podcast/jobs/{JOB_ID}"), - Some(&cookie), - None, - ) - .await; + let res = status_of(&app, &cookie, &job_id).await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert_eq!(res.body["job_id"], JOB_ID); + assert_eq!(res.body["job_id"], job_id); assert_eq!(res.body["state"], "running"); assert_eq!(res.body["stage"], "tts"); assert_eq!(res.body["progress"], 0.5); assert!(res.body["error_code"].is_null()); - let seen = service.seen(); - assert_eq!(seen.len(), 1); - assert_eq!(seen[0].capability, AI_PODCAST_STATUS_CAPABILITY); - assert_eq!(seen[0].payload["job_id"], JOB_ID); + let state: String = sqlx::query_scalar("SELECT state FROM podcast_job WHERE id = $1") + .bind(uuid_of(&job_id)) + .fetch_one(&db) + .await + .expect("the report really landed"); + assert_eq!(state, "running"); + assert_eq!( + service.seen().len(), + 1, + "the reads answered from the row, not the service" + ); } +/// The whole pipeline, end to end: submit, a running report, the finished mp3 +/// uploaded as raw bytes, the done report, then the result door naming the +/// artifact and the audio door streaming the very bytes that were uploaded — +/// with the content type the row recorded. #[tokio::test] -async fn a_result_read_round_trips_the_artifacts() { - let (service, app, cookie) = podcast_app().await; +async fn a_finished_job_serves_the_uploaded_bytes() { + let (service, app, cookie, _db) = podcast_app().await; + let user = common::me_id(&app, &cookie).await; + let job_id = submit_job(&app, &cookie).await; + + assert_report_stored( + &capability_call( + &service.conn, + report_frame(&job_id, &user, "running", "tts", 0.25), + ) + .await, + &job_id, + ); - let res = common::send( - &app, - "GET", - &format!("/podcast/jobs/{JOB_ID}/result"), - Some(&cookie), - None, + let bytes = episode_bytes(); + let answer = blob_upload( + &service.conn, + upload_frame(&job_id, AUDIO_NAME, AUDIO_TYPE, bytes.len()), + &bytes, ) .await; + assert_eq!(answer["status"], "ok", "{answer}"); + assert_eq!(answer["key"], format!("podcast/{job_id}.mp3")); + assert_eq!(answer["size"], bytes.len() as u64); + + assert_report_stored( + &capability_call( + &service.conn, + report_frame(&job_id, &user, "done", "", 1.0), + ) + .await, + &job_id, + ); + + let res = result_of(&app, &cookie, &job_id).await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert_eq!(res.body["job_id"], JOB_ID); - assert_eq!(res.body["audio_id"], AUDIO_ID); - assert_eq!(res.body["duration_secs"], 12.5); - assert_eq!(res.body["script_id"], "script-1"); - assert_eq!(res.body["audio_ids"], json!([AUDIO_ID])); - assert_eq!(res.body["script_ids"], json!(["script-1"])); - assert_eq!(res.body["format"], "duz_okuma"); + assert_eq!(res.body["job_id"], job_id); + assert_eq!(res.body["audio_id"], format!("podcast/{job_id}.mp3")); + assert_eq!(res.body["duration_secs"], DURATION_SECS); + assert_eq!(res.body["format"], FORMAT); + + let (status, headers, body) = audio_of(&app, &cookie, &job_id).await; + assert_eq!(status, StatusCode::OK, "{:?}", String::from_utf8_lossy(&body)); + assert_eq!(headers["content-type"], AUDIO_TYPE, "the row's own type"); + assert_eq!(headers["x-content-type-options"], "nosniff"); + assert_eq!(headers["cache-control"], "private, no-store"); + assert_eq!(body, bytes, "the door streams the uploaded bytes, unchanged"); - let seen = service.seen(); - assert_eq!(seen.len(), 1); - assert_eq!(seen[0].capability, AI_PODCAST_RESULT_CAPABILITY); - assert_eq!(seen[0].payload["job_id"], JOB_ID); + assert_eq!( + service.seen().len(), + 1, + "the upload and the reports are the service's own calls, not dispatches" + ); } +/// Cancelling a live job reaches the worker that owns the queue and stamps the +/// verdict on the row — the row then records that the job stopped, so a poll +/// after the service is gone still reads the truth. #[tokio::test] -async fn a_cancel_round_trips_the_verdict() { - let (service, app, cookie) = podcast_app().await; +async fn a_cancel_of_a_live_job_stops_it() { + let (service, app, cookie, db) = podcast_app().await; + let job_id = submit_job(&app, &cookie).await; - let res = common::send( - &app, - "POST", - &format!("/podcast/jobs/{JOB_ID}/cancel"), - Some(&cookie), - None, - ) - .await; + let res = cancel_of(&app, &cookie, &job_id).await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert_eq!(res.body["job_id"], JOB_ID); + assert_eq!(res.body["job_id"], job_id); assert_eq!(res.body["cancelled"], true); let seen = service.seen(); - assert_eq!(seen.len(), 1); - assert_eq!(seen[0].capability, AI_PODCAST_CANCEL_CAPABILITY); - assert_eq!(seen[0].payload["job_id"], JOB_ID); + assert_eq!(seen.len(), 2, "the cancel rode a second dispatch"); + assert_eq!(seen[1].capability, AI_PODCAST_CANCEL_CAPABILITY); + assert_eq!(seen[1].payload["job_id"], job_id); + + let state: String = sqlx::query_scalar("SELECT state FROM podcast_job WHERE id = $1") + .bind(uuid_of(&job_id)) + .fetch_one(&db) + .await + .expect("the row records the verdict"); + assert_eq!(state, "cancelled"); +} + +/// A job that already stopped is not an error to cancel: the verdict is +/// `false` — this call cancelled nothing — and no worker is needed at all, +/// because the row is terminal and the door answers before it looks for one. +#[tokio::test] +async fn a_cancel_of_a_terminal_job_answers_false_without_the_service() { + let (service, app, cookie, db) = podcast_app().await; + let user = common::me_id(&app, &cookie).await; + let job_id = submit_job(&app, &cookie).await; + assert_report_stored( + &capability_call( + &service.conn, + report_frame(&job_id, &user, "failed", "", 0.0), + ) + .await, + &job_id, + ); + + // The pipeline is gone by the time the caller gives up on it. + drop(service); + + let res = cancel_of(&app, &cookie, &job_id).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["job_id"], job_id); + assert_eq!(res.body["cancelled"], false); + + let state: String = sqlx::query_scalar("SELECT state FROM podcast_job WHERE id = $1") + .bind(uuid_of(&job_id)) + .fetch_one(&db) + .await + .expect("the row is still there"); + assert_eq!(state, "failed", "the verdict never rewrites a terminal row"); } // --------------------------------------------------------------- refusals -- -/// With a bridge but no worker, every door answers the shared AI-unavailable -/// `503` — never a `500`, and never a dispatch into nothing. The audio door is -/// not in this list on purpose: it reads a local file and needs no service. +/// A submit that reaches no service writes nothing: the `503` is the whole +/// answer, so a poll can never find a job nobody will ever work on. Both +/// shapes of "nobody to ask" answer that `503` with their own message — a +/// configured-but-unconnected bridge, and a deployment with no bridge at all. #[tokio::test] -async fn every_dispatching_door_is_503_with_no_worker_registered() { - let bridge = bridge().await; - let (app, _db) = common::app_with_ai(Some(bridge)).await; +async fn a_submit_that_reaches_no_service_is_503_and_writes_no_row() { + let (app, db) = common::app_with_ai(Some(bridge().await)).await; let cookie = common::login(&app, "ali").await; + let user = common::me_id(&app, &cookie).await; + let res = submit(&app, &cookie, json!({ "source_id": SOURCE_ID })).await; + assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body); + assert_eq!(res.body["error"], "no AI service is connected right now"); + assert_eq!(rows_for(&db, &user).await, 0, "no worker, no row"); - let doors = [ - ("POST", "/podcast/jobs".to_string(), true), - ("GET", format!("/podcast/jobs/{JOB_ID}"), false), - ("GET", format!("/podcast/jobs/{JOB_ID}/result"), false), - ("POST", format!("/podcast/jobs/{JOB_ID}/cancel"), false), - ]; - for (method, uri, body) in doors { - let res = common::send( - &app, - method, - &uri, - Some(&cookie), - body.then(|| json!({ "source_id": SOURCE_ID })), - ) - .await; - assert_eq!( - res.status, - StatusCode::SERVICE_UNAVAILABLE, - "{method} {uri}: {}", - res.body - ); - assert_eq!(res.body["error"], "no AI service is connected right now"); - } + // The deployment never set `AI_QUIC_ADDR`: there is no bridge at all. + let (app, db) = common::app_with_ai(None).await; + let cookie = common::login(&app, "ali").await; + let user = common::me_id(&app, &cookie).await; + let res = submit(&app, &cookie, json!({ "source_id": SOURCE_ID })).await; + assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body); + assert_eq!( + res.body["error"], + "the AI service is not enabled on this deployment" + ); + assert_eq!(rows_for(&db, &user).await, 0); } -/// The same doors with no bridge at all (the deployment never set -/// `AI_QUIC_ADDR`): still a `503`, with the other message. +/// A service that refuses the job — at capacity, say — leaves the row as the +/// record of that: exactly one row, `failed` with the service's own code, and +/// the refusal reaches the caller with its own status. #[tokio::test] -async fn every_dispatching_door_is_503_when_the_bridge_is_off() { - let (app, _db) = common::app_with_ai(None).await; +async fn a_refusing_service_tombstones_the_row() { + let bridge = bridge().await; + let _service = connect_service( + &bridge, + hello("podcast", &CAPABILITIES), + Behaviour::Fail { + code: "busy".to_string(), + message: "the queue is at capacity".to_string(), + }, + ) + .await; + await_workers(&bridge, 1).await; + let (app, db) = common::app_with_ai(Some(bridge)).await; let cookie = common::login(&app, "ali").await; + let user = common::me_id(&app, &cookie).await; let res = submit(&app, &cookie, json!({ "source_id": SOURCE_ID })).await; assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body); + assert_eq!(res.body["error"], "busy"); + + let rows: Vec<(String, Option)> = + sqlx::query_as("SELECT state, error_code FROM podcast_job WHERE user_id = $1") + .bind(uuid_of(&user)) + .fetch_all(&db) + .await + .expect("read back the tombstone"); assert_eq!( - res.body["error"], - "the AI service is not enabled on this deployment" + rows, + vec![("failed".to_string(), Some("busy".to_string()))], + "exactly one row, and it records the refusal" ); } -/// The service's own refusal code decides the HTTP status, so a client can -/// branch the same way it does on the bridge: `busy` is the service at -/// capacity (transient, `503`), `not_found` is a job it never had (`404`), and -/// `not_ready` is a job that has not finished (`409`). +/// A foreign job id reads as absent on every door — the same `404` an id that +/// never existed earns, so the answer leaks nothing about somebody else's job. +/// The cancel is the sharp one: it must not reach the service on a foreign id +/// either. #[tokio::test] -async fn a_service_refusal_keeps_its_code_and_status() { - let cases = [ - ("busy", StatusCode::SERVICE_UNAVAILABLE), - ("not_found", StatusCode::NOT_FOUND), - ("not_ready", StatusCode::CONFLICT), +async fn another_users_job_reads_as_absent() { + let (service, app, ali, _db) = podcast_app().await; + let job_id = submit_job(&app, &ali).await; + let seen_before = service.seen().len(); + + let ayse = common::login(&app, "ayse").await; + let doors = [ + ("GET", format!("/podcast/jobs/{job_id}")), + ("GET", format!("/podcast/jobs/{job_id}/result")), + ("GET", format!("/podcast/jobs/{job_id}/audio")), + ("POST", format!("/podcast/jobs/{job_id}/cancel")), ]; - for (code, expected) in cases { - let bridge = bridge().await; - let _service = connect_service( - &bridge, - hello("podcast", &CAPABILITIES), - Behaviour::Fail { - code: code.to_string(), - message: format!("the service refused with {code}"), - }, - ) - .await; - await_workers(&bridge, 1).await; - let (app, _db) = common::app_with_ai(Some(bridge)).await; - let cookie = common::login(&app, "ali").await; - - let res = common::send( - &app, - "GET", - &format!("/podcast/jobs/{JOB_ID}"), - Some(&cookie), - None, - ) - .await; - assert_eq!(res.status, expected, "{code}: {}", res.body); - assert_eq!(res.body["error"], code); + for (method, uri) in doors { + let res = common::send(&app, method, &uri, Some(&ayse), None).await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "{method} {uri}: {}", res.body); + assert_eq!(res.body["error"], "not found"); } + assert_eq!( + service.seen().len(), + seen_before, + "nothing about a foreign job was dispatched" + ); } -/// The nest sits behind the school's `chatbot` module — the AI package's only -/// module — exactly like `/chatbot` and `/rag`: with the module off the whole -/// URL space answers the disabled refusal, never a handler. +/// A terminal job past its retention window is gone for good: `410`, not the +/// `404` of a job that never existed — the row is still there, but nothing +/// about it is served any more. #[tokio::test] -async fn a_school_without_the_chatbot_module_has_no_podcast_nest() { - let bridge = bridge().await; - let (app, _db, tenants) = common::app_with_ai_tenants(Some(bridge)).await; - let cookie = common::login(&app, "ali").await; +async fn an_expired_job_reads_as_gone() { + let (app, cookie, db) = app_without_ai().await; + let user = common::me_id(&app, &cookie).await; + let job = Uuid::now_v7(); + let key = format!("podcast/{job}.mp3"); + // Terminal, with its artifact named (the schema's `done` CHECK), and one + // minute past the retention window. + let aged = now_ms() - (PODCAST_JOB_RETENTION_SECS + 60) * 1_000; + seed_done_job(&db, job, &user, &key, 41, aged).await; + + let res = status_of(&app, &cookie, &job.to_string()).await; + assert_eq!(res.status, StatusCode::GONE, "{}", res.body); + assert_eq!(res.body["error"], "this podcast job has expired"); +} - let mut modules = ModuleSet::all(); - modules.remove(Module::Chatbot); - modules.validate().expect("the narrowed set is satisfiable"); - tenants - .set_modules(&demo(), &modules) - .await - .expect("narrow the demo school"); +/// A job nobody has updated inside its own ETA-scaled window is presented as +/// `failed`/`interrupted` — and the projection is read-side only: the row the +/// database holds still says `running`, so the service's next report (or its +/// own sweep) is what actually repairs it. +#[tokio::test] +async fn a_stale_job_reads_as_interrupted_but_the_row_is_untouched() { + let (app, cookie, db) = app_without_ai().await; + let user = common::me_id(&app, &cookie).await; + let job = Uuid::now_v7(); + // Past the staleness floor (the window a small ETA resolves to), far + // inside the retention window. + let aged = now_ms() - (PODCAST_JOB_STALE_FLOOR_SECS + 100) * 1_000; + seed_job(&db, job, &user, "running", Some(5), aged).await; + + let res = status_of(&app, &cookie, &job.to_string()).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["state"], "failed"); + assert_eq!(res.body["error_code"], "interrupted"); - let res = common::send( - &app, - "GET", - &format!("/podcast/jobs/{JOB_ID}"), - Some(&cookie), - None, - ) - .await; - assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); - assert_eq!(res.body["module"], "chatbot"); + let stored: String = sqlx::query_scalar("SELECT state FROM podcast_job WHERE id = $1") + .bind(job) + .fetch_one(&db) + .await + .expect("the row is still there"); + assert_eq!(stored, "running", "the projection wrote nothing"); } -/// Authentication is the whole gate for the dispatching doors: no cookie is a -/// `401`, not a dispatch under somebody else's name. +/// Neither the result nor the bytes exist before the job is done: both reading +/// doors answer `409` with `not_ready`, so a client branches on the code +/// instead of parsing the sentence. #[tokio::test] -async fn the_dispatching_doors_require_a_session() { - let (service, app, _cookie) = podcast_app().await; +async fn the_result_and_audio_doors_are_not_ready_before_done() { + let (service, app, cookie, _db) = podcast_app().await; + let user = common::me_id(&app, &cookie).await; + let job_id = submit_job(&app, &cookie).await; + assert_report_stored( + &capability_call( + &service.conn, + report_frame(&job_id, &user, "running", "tts", 0.5), + ) + .await, + &job_id, + ); - let res = common::send( - &app, - "POST", - "/podcast/jobs", - None, - Some(json!({ "source_id": SOURCE_ID })), - ) - .await; - assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{}", res.body); - assert!(service.seen().is_empty(), "an anonymous call dispatches nothing"); + let res = result_of(&app, &cookie, &job_id).await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + assert_eq!(res.body["code"], "not_ready"); + + let (status, _, body) = audio_of(&app, &cookie, &job_id).await; + assert_eq!( + status, + StatusCode::CONFLICT, + "{:?}", + String::from_utf8_lossy(&body) + ); + let refusal: Value = serde_json::from_slice(&body).expect("a JSON refusal"); + assert_eq!(refusal["code"], "not_ready"); } -// -------------------------------------------------------------- audio door -- +/// A `done` report that arrives before its audio was uploaded is refused +/// `audio_missing`: the row must never claim a finished episode whose bytes are +/// not there (the schema's own CHECK backstops the same rule), and the row +/// stays `running` so the service can upload and report again. +#[tokio::test] +async fn a_done_report_before_the_upload_is_refused() { + let (service, app, cookie, db) = podcast_app().await; + let user = common::me_id(&app, &cookie).await; + let job_id = submit_job(&app, &cookie).await; + assert_report_stored( + &capability_call( + &service.conn, + report_frame(&job_id, &user, "running", "tts", 0.5), + ) + .await, + &job_id, + ); -/// Write `bytes` at `relative` under the demo school's blob directory and -/// return the absolute path it landed at. -fn school_file(relative: &str, bytes: &[u8]) -> std::path::PathBuf { - let path = common::blob_dir().join(relative); - std::fs::create_dir_all(path.parent().expect("parent dir")).expect("create the directory tree"); - std::fs::write(&path, bytes).expect("write the file"); - path -} + let answer = capability_call( + &service.conn, + report_frame(&job_id, &user, "done", "", 1.0), + ) + .await; + assert_eq!(refusal_code(&answer), "audio_missing"); -/// One raw `GET /podcast/audio?path=…`. -async fn fetch_audio( - app: &Router, - cookie: Option<&str>, - path: &str, -) -> (StatusCode, axum::http::HeaderMap, Vec) { - let uri = format!("/podcast/audio?path={path}"); - common::send_raw(app, "GET", &uri, cookie, None, Vec::new()).await + let state: String = sqlx::query_scalar("SELECT state FROM podcast_job WHERE id = $1") + .bind(uuid_of(&job_id)) + .fetch_one(&db) + .await + .expect("the row is still there"); + assert_eq!(state, "running", "the refusal wrote nothing"); } -/// The happy path: a file under the school's own directory streams back with -/// its bytes and an audio content type. +/// A `done` row whose blob is gone from the host answers `409 audio_missing`: +/// the record is intact and the bytes are not — a state a client can report, +/// unlike a generic `500`. The result door still names the artifact, so the +/// row itself is provably fine and only the file is missing. #[tokio::test] -async fn the_audio_door_serves_a_file_under_the_schools_directory() { - let (app, _db) = common::app_and_db().await; - let cookie = common::login(&app, "ali").await; - let bytes = b"ID3\x03\x00\x00\x00fake-mp3-bytes".to_vec(); - school_file("podcast/serve/ok.mp3", &bytes); +async fn the_audio_door_reports_a_missing_blob() { + let (app, cookie, db) = app_without_ai().await; + let user = common::me_id(&app, &cookie).await; + let job = Uuid::now_v7(); + let key = format!("podcast/{job}.mp3"); + seed_done_job(&db, job, &user, &key, 41, now_ms()).await; + assert!( + !common::blob_dir().join(&key).exists(), + "the blob really is gone" + ); - let (status, headers, body) = fetch_audio(&app, Some(&cookie), "podcast/serve/ok.mp3").await; - assert_eq!(status, StatusCode::OK); - assert_eq!(headers["content-type"], "audio/mpeg"); - assert_eq!(headers["x-content-type-options"], "nosniff"); - assert_eq!(headers["cache-control"], "private, no-store"); - assert_eq!(body, bytes, "the bytes are the file's, unchanged"); + let res = result_of(&app, &cookie, &job.to_string()).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["audio_id"], key); + + let (status, _, body) = audio_of(&app, &cookie, &job.to_string()).await; + assert_eq!( + status, + StatusCode::CONFLICT, + "{:?}", + String::from_utf8_lossy(&body) + ); + let refusal: Value = serde_json::from_slice(&body).expect("a JSON refusal"); + assert_eq!(refusal["code"], "audio_missing"); } -/// Without a session the door is a `401` — and the very same path serves `200` -/// with one, so the refusal is authorization and not a missing file. +/// The reading doors need no AI service at all: a finished job's row and its +/// blob are served with no bridge configured — which is the whole reason the +/// row exists (a restarted service, or a wiped service volume, costs nothing +/// but the liveness the row's own projection already covers). #[tokio::test] -async fn the_audio_door_refuses_an_unauthenticated_caller() { - let (app, _db) = common::app_and_db().await; - let cookie = common::login(&app, "ali").await; - let bytes = b"authorized-only".to_vec(); - school_file("podcast/auth/only.mp3", &bytes); +async fn the_reading_doors_need_no_service() { + let (app, cookie, db) = app_without_ai().await; + let user = common::me_id(&app, &cookie).await; + let job = Uuid::now_v7(); + let key = format!("podcast/{job}.mp3"); + let bytes = episode_bytes(); + write_blob(&key, &bytes); + seed_done_job(&db, job, &user, &key, bytes.len() as i64, now_ms()).await; + + let res = status_of(&app, &cookie, &job.to_string()).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["state"], "done"); - let (anonymous, _, _) = fetch_audio(&app, None, "podcast/auth/only.mp3").await; - assert_eq!(anonymous, StatusCode::UNAUTHORIZED); + let res = result_of(&app, &cookie, &job.to_string()).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["audio_id"], key); - let (authorized, _, body) = fetch_audio(&app, Some(&cookie), "podcast/auth/only.mp3").await; - assert_eq!(authorized, StatusCode::OK); + let (status, headers, body) = audio_of(&app, &cookie, &job.to_string()).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(headers["content-type"], AUDIO_TYPE); assert_eq!(body, bytes); } -/// A `..` segment is refused even though the file it names exists and the file -/// *inside* the school's directory is served — the refusal is the shape check, -/// not a missing target. -#[tokio::test] -async fn the_audio_door_refuses_a_dotdot_segment_to_an_existing_file() { - let (app, _db) = common::app_and_db().await; - let cookie = common::login(&app, "ali").await; - let inside = b"inside the school".to_vec(); - let outside = b"outside the school".to_vec(); - school_file("podcast/traversal/inside.mp3", &inside); - // What `../` would reach: the deployment-wide files root, one level above - // the school's own directory. - let escaped = common::files_dir().join("traversal-outside.mp3"); - std::fs::write(&escaped, &outside).expect("write the outside file"); - assert!(escaped.is_file(), "the traversal target really exists"); - - let (served, _, body) = fetch_audio(&app, Some(&cookie), "podcast/traversal/inside.mp3").await; - assert_eq!(served, StatusCode::OK); - assert_eq!(body, inside); - - let (refused, _, body) = - fetch_audio(&app, Some(&cookie), "podcast/traversal/../../traversal-outside.mp3").await; - assert_eq!(refused, StatusCode::BAD_REQUEST, "{:?}", String::from_utf8_lossy(&body)); - assert_ne!(body, outside, "the escaped file's bytes never came back"); -} - -/// An absolute path is refused even though the file it names exists — and a -/// naive `root.join(path)` would have *served* it, since joining an absolute -/// path replaces the base. +/// The old `GET /podcast/audio?path=…` door is gone with the caller-chosen path +/// it resolved: it could not be owner-scoped, so the whole route is a `404` — +/// the per-job door is the only audio door, and it streams what the school's +/// own row names. The fixture proves the file exists, so the answer is the +/// missing route, not a missing target. #[tokio::test] -async fn the_audio_door_refuses_an_absolute_path_to_an_existing_file() { - let (app, _db) = common::app_and_db().await; - let cookie = common::login(&app, "ali").await; - let outside = common::files_dir().join("absolute-outside.mp3"); - std::fs::write(&outside, b"not for the audio door").expect("write the outside file"); +async fn the_old_path_audio_door_is_gone() { + let (app, cookie, _db) = app_without_ai().await; + write_blob("podcast/escape/kept.mp3", b"bytes the old door would have served"); - let (status, _, body) = fetch_audio( + let res = common::send( &app, + "GET", + "/podcast/audio?path=podcast/escape/kept.mp3", Some(&cookie), - outside.to_str().expect("a UTF-8 temp path"), + None, ) .await; - assert_eq!(status, StatusCode::BAD_REQUEST, "{:?}", String::from_utf8_lossy(&body)); - assert_ne!(body, b"not for the audio door"); + assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); } -/// A symlink inside the school's directory is refused when it resolves out of -/// it — the escape a plain "does the path start with the root" prefix check -/// would miss, since the link itself sits inside the root. -#[tokio::test] -async fn the_audio_door_refuses_a_symlink_that_escapes_the_school() { - let (app, _db) = common::app_and_db().await; - let cookie = common::login(&app, "ali").await; - let target = common::files_dir().join("symlink-outside.mp3"); - std::fs::write(&target, b"reached through a link").expect("write the target"); - let link = common::blob_dir().join("podcast/symlink/escape.mp3"); - std::fs::create_dir_all(link.parent().expect("parent dir")).expect("create the directory tree"); - let _ = std::fs::remove_file(&link); - std::os::unix::fs::symlink(&target, &link).expect("create the symlink"); - assert!(target.is_file(), "the link's target really exists"); - - let (status, _, body) = fetch_audio(&app, Some(&cookie), "podcast/symlink/escape.mp3").await; - assert_eq!(status, StatusCode::BAD_REQUEST, "{:?}", String::from_utf8_lossy(&body)); - assert_ne!(body, b"reached through a link"); -} - -/// Another school's episode is invisible even when the caller knows its exact -/// path: the demo caller's request resolves under the *demo* directory, where -/// that path does not exist — though the file itself does, one school over. +/// Authentication is the whole gate on every door: no cookie is a `401`, not a +/// handler — and not a dispatch under somebody else's name either. #[tokio::test] -async fn the_audio_door_never_reaches_another_schools_file() { - let (app, _db) = common::app_and_db().await; - let cookie = common::login(&app, "ali").await; - let other = common::files_dir().join("baska-okul/podcast/ses/episode.mp3"); - std::fs::create_dir_all(other.parent().expect("parent dir")).expect("create the directory tree"); - std::fs::write(&other, b"the other school's episode").expect("write the file"); - assert!(other.is_file()); +async fn every_door_requires_a_session() { + let (service, app, _cookie, _db) = podcast_app().await; + let id = common::GHOST_ID; - let (status, _, _) = fetch_audio(&app, Some(&cookie), "podcast/ses/episode.mp3").await; - assert_eq!(status, StatusCode::NOT_FOUND); + let doors = [ + ("POST", "/podcast/jobs".to_string(), Some(json!({ "source_id": SOURCE_ID }))), + ("GET", format!("/podcast/jobs/{id}"), None), + ("GET", format!("/podcast/jobs/{id}/result"), None), + ("GET", format!("/podcast/jobs/{id}/audio"), None), + ("POST", format!("/podcast/jobs/{id}/cancel"), None), + ]; + for (method, uri, body) in doors { + let res = common::send(&app, method, &uri, None, body).await; + assert_eq!( + res.status, + StatusCode::UNAUTHORIZED, + "{method} {uri}: {}", + res.body + ); + assert_eq!(res.body["error"], "unauthorized"); + } + assert!( + service.seen().is_empty(), + "an anonymous call dispatches nothing" + ); } -/// The door needs no AI bridge at all: a produced file is served with the -/// service long gone. +/// The nest sits behind the school's `chatbot` module — the AI package's only +/// module — exactly like `/chatbot` and `/rag`: with the module off the whole +/// URL space answers the disabled refusal, never a handler. #[tokio::test] -async fn the_audio_door_needs_no_service() { - let (app, _db) = common::app_with_ai(None).await; +async fn a_school_without_the_chatbot_module_has_no_podcast_nest() { + let bridge = bridge().await; + let (app, _db, tenants) = common::app_with_ai_tenants(Some(bridge)).await; let cookie = common::login(&app, "ali").await; - let bytes = b"produced before the service left".to_vec(); - school_file("podcast/offline/episode.mp3", &bytes); - let (status, _, body) = fetch_audio(&app, Some(&cookie), "podcast/offline/episode.mp3").await; - assert_eq!(status, StatusCode::OK); - assert_eq!(body, bytes); + let mut modules = ModuleSet::all(); + modules.remove(Module::Chatbot); + modules.validate().expect("the narrowed set is satisfiable"); + tenants + .set_modules(&demo(), &modules) + .await + .expect("narrow the demo school"); + + let res = status_of(&app, &cookie, common::GHOST_ID).await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + assert_eq!(res.body["module"], "chatbot"); }