forge
Explore
Log in

Don't you dare go Hollow

The podcast job's row and audio now live in the backend - backend-owned row, mp3 ingest, read gates without the service

Browse files at this commit

c44f362e4d7a67312d39070400a87557d6366d06Ahmet Kaan GümüşParent: 7c96e47
  • feat
    • the podcast job's row and audio now live in the backend - backend-owned row, mp3 ingest, read gates without the service
Show full message
✨ feat: the podcast job's row and audio now live in the backend - backend-owned row, mp3 ingest, read gates without the service

The job record lived only in the podcast service's own volume, so a restart
or a wiped volume lost every in-flight job a caller was polling and the mp3 it
was about to download. The backend now owns both ends of that state:

* `migrations/school/20260917000003_podcast.sql` — `podcast_job`, the job's
  own row (user/source/format/state/stage/progress/error_code/audio_*/
  duration/eta/created/updated). No `school` column: the school IS the
  database, and the row's tenancy is (this database, user_id).
* `POST /podcast/jobs` mints the id, writes the row, THEN dispatches
  `podcast.submit` with `{job_id, source_id, format, user_id}`; the service
  echoes that id in its receipt (mismatch = 502 + a failed/bad_reply row).
  No worker = 503 and no row; a refusal or transport failure tombstones the
  row with the reason code — nothing is left claiming `queued`.
* The service reports every transition back through `podcast.report` (the new
  client-initiated capability call, School-scoped, wired through
  `src/ai/capability.rs`), which validates the echo, the jobs.py transition
  table, the retention window and the done-means-audio rule before one
  conditional UPDATE keyed on the state it read.
* The finished mp3 arrives as a `BlobUploadRequest` stream (exactly `size`
  raw bytes), lands under the school's own blob root at
  `podcast/<job-id>.<ext>` (temp+rename, row stamped in the same act, file
  removed again if the row write finds the job gone), and `POST`ing a done
  report before it is refused `audio_missing`.
* The read doors — `GET /podcast/jobs/{id}`, `.../result`,
  `.../audio` — answer from the row with no service round trip: 404 for an
  unknown or foreign job (foreign ids read as absent), 409 `not_ready` /
  `audio_missing`, 410 past PODCAST_JOB_RETENTION_SECS, and a read-side-only
  projection that presents a queued/running row nobody has updated inside its
  ETA-scaled window as failed/interrupted — the GET writes nothing and a real
  report overwrites it. `podcast.status`/`podcast.result` capabilities are
  deleted with their payloads; the old `GET /podcast/audio?path=…` door is
  gone (it named a cross-volume path and could not be owner-scoped).

Also: `AppError::Expired` (410) + the two room matches that needed it,
MIN_PROTECTED 323 -> 337 (real swept count), the three clippy fixes on the
committed tree, README regenerated, and the .sqlx entries for both lanes'
queries. This commit completes the tree that 7c96e47 half-staged: that commit
took the shared files (server/protocol/constant/db-mod/ai-capability) while
leaving `src/ai/podcast.rs`, `src/web/podcast.rs` and `tests/podcast.rs` at
their old versions, so main did not compile until this one.

16 changed files +2531 -771

migrations/school/20260917000003_podcast.sqladded+84 -0
@@ -0,0 +1,84 @@
1+-- The podcast job table: the backend-owned record of every episode the podcast
2+-- service was asked to produce.
3+--
4+-- WHERE THIS FILE BELONGS: `migrations/school/` in the backend repo, applied by
5+-- `Migrator::new(migrations/school)` to the template at boot and to every school
6+-- database at create. APPEND-ONLY relative to the existing school migrations: it
7+-- creates one new table and touches none of them.
8+--
9+-- WHY THE BACKEND HOLDS IT: until now the job record lived only in the service's
10+-- own volume (`jobs.py`'s per-job JSON files), which made a service restart or a
11+-- wiped volume lose every in-flight job the caller was polling — and the produced
12+-- mp3 with it. The backend now mints the job id, writes the row before it
13+-- dispatches, answers `podcast.status`/`podcast.result` from it, and stores the
14+-- uploaded audio in the school's own blob directory. The service reports each
15+-- transition back over the bridge (`podcast.report`) and uploads the finished
16+-- mp3. A service that vanishes therefore costs liveness — the read side projects
17+-- a job nobody is updating as failed after a bounded window — never the record.
18+--
19+-- NO `school` COLUMN: each school already lives in its own database, so the
20+-- tenant IS the database (the same rule every `zeka_*`/`rag_*` table follows).
21+-- The row's tenancy is the pair (this database, `user_id`), and the web layer
22+-- checks both: a foreign user's id reads as absent, exactly like `rag_thread`.
23+--
24+-- Translation rules inherited from the school schema's other parts:
25+-- * entity ids are app-minted uuid v7 (`domain::monotonic_id::next_uuid`),
26+-- never a DB default;
27+-- * timestamps are BIGINT unix-ms UTC, never `timestamptz`;
28+-- * FKs point outward, one direction only, all `ON DELETE NO ACTION`.
29+--
30+-- The state vocabulary and the transition table are the service's own
31+-- (`jobs.py`): queued -> running -> done|failed|cancelled, plus
32+-- queued -> cancelled|failed. The CHECK is the backstop under the Rust enum,
33+-- which is the source.
34+
35+CREATE TABLE podcast_job (
36+ id uuid PRIMARY KEY,
37+ -- Who submitted it. The ownership guard: every read door answers 404 for a
38+ -- row whose user_id is not the caller.
39+ user_id uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
40+ -- The source the service narrates, verbatim as submitted — the backend id
41+ -- of a course note today. No FK: `source_id` is the service's own handle on
42+ -- shared media, and the backend cannot say what it names.
43+ source_id TEXT NOT NULL,
44+ -- The narration format. NULL until a report resolves it: the service applies
45+ -- its own default (and refuses formats that need an LLM key it lacks), so
46+ -- this column records the service's verdict, never a guess of ours.
47+ format TEXT NULL,
48+ -- 'queued' | 'running' | 'done' | 'failed' | 'cancelled' (jobs.py STATES).
49+ state TEXT NOT NULL
50+ CHECK (state IN ('queued', 'running', 'done', 'failed', 'cancelled')),
51+ -- The pipeline stage inside `running` (the service's SIMULATED_STAGES or its
52+ -- real ones); '' outside it.
53+ stage TEXT NOT NULL DEFAULT '',
54+ -- Fraction complete, 0.0..=1.0. The service rounds to 4 decimals; the
55+ -- CHECK is the bound, not the rounding.
56+ progress DOUBLE PRECISION NOT NULL DEFAULT 0
57+ CHECK (progress BETWEEN 0 AND 1),
58+ -- Set on `failed`: the service's own short error code, or `interrupted` when
59+ -- the backend projected a dead job or the dispatch never reached a worker.
60+ error_code TEXT NULL,
61+ -- The uploaded episode, when one landed (see `web::podcast`'s ingest
62+ -- handshake): the blob key under the school's files root, plus the metadata
63+ -- the audio door replays as headers. All NULL until an upload.
64+ audio_key TEXT NULL,
65+ audio_name TEXT NULL,
66+ audio_type TEXT NULL,
67+ audio_bytes BIGINT NULL,
68+ duration_secs DOUBLE PRECISION NULL,
69+ -- The service's own ETA from the submit receipt. Drives the read-side
70+ -- staleness window (a long job is not projected dead mid-flight) and is
71+ -- echoed in the submit receipt.
72+ eta_secs BIGINT NULL,
73+ created_at BIGINT NOT NULL,
74+ updated_at BIGINT NOT NULL,
75+ -- A deferred upload's key is set in the same statement that reports it, so
76+ -- "done" and "has audio" can never disagree: the report that says done
77+ -- requires `audio_key` to be non-NULL.
78+ CONSTRAINT podcast_job_done_has_audio
79+ CHECK (state <> 'done' OR audio_key IS NOT NULL)
80+);
81+
82+-- The list view's sort key (a user's own jobs, newest first) and the sweep's.
83+CREATE INDEX podcast_job_user_created ON podcast_job (user_id, created_at);
84+CREATE INDEX podcast_job_created ON podcast_job (created_at);
src/ai/insight.rsmodified+6 -9
@@ -329,7 +329,7 @@ pub async fn serve(
329 ));329 ));
330 }330 }
331 let db = &tenant.db;331 let db = &tenant.db;
332- let answer = match capability {332+ match capability {
333 AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY => {333 AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY => {
334 let request: SummaryWriteRequest = decode(payload)?;334 let request: SummaryWriteRequest = decode(payload)?;
335 encode(&db::insight::write_summaries(db, request.rows).await.map_err(refusal)?)335 encode(&db::insight::write_summaries(db, request.rows).await.map_err(refusal)?)
@@ -374,14 +374,11 @@ pub async fn serve(
374 // `scope_of` matched above, so the table and this match agree; the374 // `scope_of` matched above, so the table and this match agree; the
375 // arm exists so a table entry without an operation is a compile-time375 // arm exists so a table entry without an operation is a compile-time
376 // miss instead of a runtime surprise.376 // miss instead of a runtime surprise.
377- other => {377+ other => Err((
378- return Err((378+ "unknown_capability",
379- "unknown_capability",379+ format!("the backend serves no `{other}` operation"),
380- format!("the backend serves no `{other}` operation"),380+ )),
381- ));381+ }
382- }
383- };
384- answer
385 }382 }
386 383
387 /// Decode one payload into the operation's own type. A payload that does not384 /// Decode one payload into the operation's own type. A payload that does not
src/ai/mod.rsmodified+6 -3
@@ -13,10 +13,12 @@
13 //!13 //!
14 //! * [`api`] — which REST paths a service may read back through the bridge14 //! * [`api`] — which REST paths a service may read back through the bridge
15 //! * [`protocol`] — frames on the wire15 //! * [`protocol`] — frames on the wire
16+//! * [`capability`] — the capabilities the **backend** serves, and their scopes
16 //! * [`chat`] — the JSON payloads carried for the `chat.reply` capability17 //! * [`chat`] — the JSON payloads carried for the `chat.reply` capability
17 //! * [`rag`] — the `rag.index` payloads, and the course-note dispatch behind them18 //! * [`rag`] — the `rag.index` payloads, and the course-note dispatch behind them
18 //! * [`rag_chat`] — the `rag.chat` payloads: a scoped question and the citations behind its answer19 //! * [`rag_chat`] — the `rag.chat` payloads: a scoped question and the citations behind its answer
19-//! * [`podcast`] — the `podcast.*` job payloads, and the relay behind them20+//! * [`podcast`] — the `podcast.*` job payloads, the relay behind submit/cancel,
21+//! and the job-state report the service calls back
20 //! * [`server`] — the listener, handshake, and [`server::AiBridge::dispatch`]22 //! * [`server`] — the listener, handshake, and [`server::AiBridge::dispatch`]
21 //! * [`registry`] — who is connected here, and who gets the next request23 //! * [`registry`] — who is connected here, and who gets the next request
22 //! * [`tls`] — the listener's certificate24 //! * [`tls`] — the listener's certificate
@@ -24,10 +26,11 @@
24 //! The transport is generic; the features land on top of it. So far that is26 //! The transport is generic; the features land on top of it. So far that is
25 //! the chatbot (`web::chatbot`), which routes on the `chat.reply` capability,27 //! the chatbot (`web::chatbot`), which routes on the `chat.reply` capability,
26 //! course-note indexing (`web::course_notes`), which routes on `rag.index`,28 //! course-note indexing (`web::course_notes`), which routes on `rag.index`,
27-//! and the podcast relay (`web::podcast`), which routes on the four29+//! and the podcast relay (`web::podcast`), which dispatches `podcast.submit`/
28-//! `podcast.*` capabilities and streams the audio they produce.30+//! `podcast.cancel`, serves `podcast.report`, and streams the ingested audio.
29 31
30 pub mod api;32 pub mod api;
33+pub mod capability;
31 pub mod chat;34 pub mod chat;
32 pub mod error;35 pub mod error;
33 pub mod insight;36 pub mod insight;
src/ai/podcast.rsmodified+215 -118
@@ -1,143 +1,117 @@
1-//! Payload contract for the `podcast.*` capabilities, and the dispatch behind1+//! Payload contract for the `podcast.*` capabilities and the audio ingest —
2-//! them.2+//! both directions of the podcast seam.
3 //!3 //!
4 //! The podcast service turns one stored source — a course note's PDF — into an4 //! The podcast service turns one stored source — a course note's PDF — into an
5-//! audio episode, and that is a *job*: submit enqueues it, status and result5+//! audio episode. Since 2026-09-17 the **backend owns that job's record**: the
6-//! read it back minutes later, cancel stops it. So these are four verbs on one6+//! submit door mints the job id, writes the row, and then dispatches
7-//! record that the **service** owns, not four steps of one backend request,7+//! `podcast.submit` with that id; the service reports every transition back
8-//! and the backend relays each call to the worker declaring the matching8+//! through the client-initiated `podcast.report` capability, and uploads the
9-//! capability.9+//! finished mp3 as raw bytes on a `BlobUploadRequest` stream. Status and
10+//! result answer from the backend's own row — they are not capabilities any
11+//! more, because a service restart (or a wiped service volume) must cost
12+//! nothing but the liveness the read-side projection already covers.
10 //!13 //!
11-//! Nothing here is spawned, unlike [`chat`](crate::ai::chat) and14+//! What remains **server-initiated** are the two calls that must reach a live
12-//! [`rag_chat`](crate::ai::rag_chat): every one of the four calls answers15+//! worker:
13-//! immediately — a queued receipt, a status snapshot, a finished job, a cancel
14-//! verdict — while the pipeline itself runs in the service's own worker pool.
15-//! That is also why the four ride the bridge's ordinary request deadline
16-//! ([`AI_DEFAULT_REQUEST_TIMEOUT_SECS`](crate::constant::AI_DEFAULT_REQUEST_TIMEOUT_SECS))
17-//! rather than a per-capability one: no call waits on a model.
18 //!16 //!
19-//! Tenancy is the transport's job: [`crate::ai::server`] stamps the caller's17+//! * [`submit`] — `podcast.submit`, whose payload carries the backend-minted
20-//! school onto every `hab/2` request; it does **not** verify the echo on18+//! `job_id` and the submitting `user_id` (the service stores both; its own
21-//! replies (the bridge correlates answers by frame id alone), so the wall is19+//! record is keyed by the id the backend will keep asking about).
22-//! the stamp plus the service's own honesty — and it holds even though the20+//! * [`cancel`] — `podcast.cancel`, unchanged: a write on the service's queue,
23-//! job records themselves live outside the backend's databases.21+//! and the capability is what decides whether a deployment offers the door.
24 //!22 //!
25-//! The produced audio does not cross the bridge. `podcast.result` answers an23+//! Tenancy is the transport's job: [`crate::ai::server`] stamps the caller's
26-//! `audio_id` that is a path *relative* to the service's24+//! school onto every `hab/2` request and resolves the frame's school on every
27-//! `PODCAST_OUTPUT_ROOT`, which the deployment points at the school's own25+//! client-initiated one; this module never re-derives a school.
28-//! files directory on this host (`FILES_PATH/<slug>`, the same volume every
29-//! upload lands in); the browser then fetches it from `GET /podcast/audio`,
30-//! which resolves it under that directory and refuses everything that would
31-//! escape it — see [`crate::web::podcast`].
32 26
33 use serde::de::DeserializeOwned;27 use serde::de::DeserializeOwned;
34 use serde::{Deserialize, Serialize};28 use serde::{Deserialize, Serialize};
29+use serde_json::Value;
35 30
36-use crate::ai::{AiBridge, AiError};31+use crate::ai::AiBridge;
32+use crate::ai::error::AiError;
33+use crate::database::Database;
34+use crate::domain::podcast_job::PodcastJobId;
35+use crate::service::podcast_job::{PodcastRefusal, ReportInput};
37 use crate::tenant::Slug;36 use crate::tenant::Slug;
38 37
39 /// The capability strings, re-exported so a reader of the payload contract38 /// The capability strings, re-exported so a reader of the payload contract
40 /// finds them next to the payloads — the same shape as39 /// finds them next to the payloads — the same shape as
41 /// [`crate::ai::rag`](crate::ai::rag).40 /// [`crate::ai::rag`](crate::ai::rag).
42 pub use crate::constant::{41 pub use crate::constant::{
43- AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_RESULT_CAPABILITY, AI_PODCAST_STATUS_CAPABILITY,42+ AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_REPORT_CAPABILITY, AI_PODCAST_SUBMIT_CAPABILITY,
44- AI_PODCAST_SUBMIT_CAPABILITY,
45 };43 };
46 44
47-/// What the backend asks a podcast service to start.45+/// What the backend asks a podcast service to start. The `job_id` is the
46+/// backend's own minted id — the service keys its record by it and echoes it
47+/// in every report, so the two stores can never disagree about which job a
48+/// record is.
48 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]49 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
49 pub struct PodcastSubmitPayload {50 pub struct PodcastSubmitPayload {
50- /// The backend's record id for the source to narrate — a course note id,51+ pub job_id: String,
51- /// never a file path. The service resolves it against its own media root,
52- /// which the deployment points at this backend's files volume.
53 pub source_id: String,52 pub source_id: String,
54- /// Which narration to produce. `duz_okuma` (plain reading) is the53+ /// `None` means the service applies its own default (`duz_okuma` today).
55- /// service's default and the only one that needs no LLM key;54+ #[serde(default, skip_serializing_if = "Option::is_none")]
56- /// `tek_ogretici` and `ogrenci_hoca` are refused by the service with
57- /// `llm_unavailable` when the key is missing. Sent verbatim — the
58- /// service's closed set is what validates it.
59- #[serde(skip_serializing_if = "Option::is_none")]
60 pub format: Option<String>,55 pub format: Option<String>,
56+ /// The submitting user, so the service's own record carries the same
57+ /// owner the backend row does.
58+ pub user_id: String,
61 }59 }
62 60
63-/// The receipt for an accepted job, echoed straight to the caller.61+/// The receipt for an accepted job. `job_id` must echo the request's — the
62+/// backend checks, because the id is the only handle it will keep polling by.
64 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]63 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
65 pub struct PodcastSubmitReply {64 pub struct PodcastSubmitReply {
66- /// The id the service minted for the job. Every later call names it.
67 pub job_id: String,65 pub job_id: String,
68- /// The job's state right after submission (`queued`).66+ /// `queued` on a fresh job.
69 pub state: String,67 pub state: String,
70- /// The service's own estimate of how long the job will take, in seconds.68+ /// The service's own estimate of the job's duration, in seconds.
71 pub eta_secs: i64,69 pub eta_secs: i64,
72 }70 }
73 71
74-/// What the backend asks about one job's progress.72+/// What the backend asks to cancel.
75 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]73 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76-pub struct PodcastStatusPayload {74+pub struct PodcastCancelPayload {
77 pub job_id: String,75 pub job_id: String,
78 }76 }
79 77
80-/// One job's state, as of now.78+/// The verdict on a cancel: `cancelled` is "this call cancelled something",
81-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]79+/// not "the job is cancelled" — cancelling an already-finished job answers
82-pub struct PodcastStatusReply {80+/// `false`, and so does cancelling one that was already cancelled.
83- pub job_id: String,
84- /// `queued`, `running`, `done`, `failed` or `cancelled` — the service's own
85- /// vocabulary, passed through rather than mapped, so a state added there
86- /// needs no change here.
87- pub state: String,
88- /// The pipeline stage the job is in, as prose from the service.
89- pub stage: String,
90- /// Fraction complete, `0.0..=1.0`.
91- pub progress: f64,
92- /// The failure code when `state` is `failed`, null otherwise.
93- #[serde(default)]
94- pub error_code: Option<String>,
95-}
96-
97-/// What the backend asks for a finished job's artifacts.
98 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]81 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
99-pub struct PodcastResultPayload {82+pub struct PodcastCancelReply {
100 pub job_id: String,83 pub job_id: String,
84+ pub cancelled: bool,
101 }85 }
102 86
103-/// A finished job's artifacts. Only a `done` job answers this: the service87+/// One state report from the service — the payload of a client-initiated
104-/// refuses any other state with `not_ready`, so nothing here is nullable — a88+/// [`AI_PODCAST_REPORT_CAPABILITY`] call. The service sends one per
105-/// reply missing `audio_id` is an unreadable answer, not a half-finished job.89+/// transition, in order (it awaits each answer before sending the next), and
90+/// echoes the job's own identity so the backend can refuse a report that
91+/// describes a different job than the row holds.
106 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]92 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
107-pub struct PodcastResultReply {93+pub struct PodcastReportPayload {
108 pub job_id: String,94 pub job_id: String,
109- /// The produced audio, as a path **relative** to `PODCAST_OUTPUT_ROOT` on95+ pub source_id: String,
110- /// this host. Never absolute, never containing `..` — and
111- /// [`crate::web::podcast`] refuses one that is, whatever the service sent.
112- pub audio_id: String,
113- /// The audio's length in seconds.
114- pub duration_secs: f64,
115- /// The script the narration was read from.
116- pub script_id: String,
117- /// One entry per produced chapter, when the job was sliced into several;
118- /// usually `[audio_id]`.
119 #[serde(default)]96 #[serde(default)]
120- pub audio_ids: Vec<String>,97+ pub format: Option<String>,
121- /// One entry per script the audio was aligned to.98+ pub user_id: String,
99+ /// `queued` | `running` | `done` | `failed` | `cancelled`.
100+ pub state: String,
122 #[serde(default)]101 #[serde(default)]
123- pub script_ids: Vec<String>,102+ pub stage: String,
124- /// The narration format the job was produced with.103+ #[serde(default)]
125- pub format: String,104+ pub progress: f64,
126-}105+ #[serde(default)]
127-106+ pub error_code: Option<String>,
128-/// What the backend asks to cancel.
129-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
130-pub struct PodcastCancelPayload {
131- pub job_id: String,
132 }107 }
133 108
134-/// The verdict on a cancel: `cancelled` is "this call cancelled something",109+/// The answer to one report. `stored` is always `true` on an `Ok` — an
135-/// not "the job is cancelled" — cancelling an already-finished job answers110+/// unstored report is a refusal, never a quiet success.
136-/// `false`, and so does cancelling one that was already cancelled.
137 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]111 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
138-pub struct PodcastCancelReply {112+pub struct PodcastReportReply {
139 pub job_id: String,113 pub job_id: String,
140- pub cancelled: bool,114+ pub stored: bool,
141 }115 }
142 116
143 /// Start one job. `Err` is a short, stable code — see [`failure_code`].117 /// Start one job. `Err` is a short, stable code — see [`failure_code`].
@@ -149,24 +123,6 @@ pub async fn submit(
149 dispatch(bridge, slug, AI_PODCAST_SUBMIT_CAPABILITY, payload).await123 dispatch(bridge, slug, AI_PODCAST_SUBMIT_CAPABILITY, payload).await
150 }124 }
151 125
152-/// Read one job's progress.
153-pub async fn status(
154- bridge: &AiBridge,
155- slug: &Slug,
156- payload: PodcastStatusPayload,
157-) -> Result<PodcastStatusReply, String> {
158- dispatch(bridge, slug, AI_PODCAST_STATUS_CAPABILITY, payload).await
159-}
160-
161-/// Read one finished job's artifacts.
162-pub async fn result(
163- bridge: &AiBridge,
164- slug: &Slug,
165- payload: PodcastResultPayload,
166-) -> Result<PodcastResultReply, String> {
167- dispatch(bridge, slug, AI_PODCAST_RESULT_CAPABILITY, payload).await
168-}
169-
170 /// Cancel one job.126 /// Cancel one job.
171 pub async fn cancel(127 pub async fn cancel(
172 bridge: &AiBridge,128 bridge: &AiBridge,
@@ -176,14 +132,155 @@ pub async fn cancel(
176 dispatch(bridge, slug, AI_PODCAST_CANCEL_CAPABILITY, payload).await132 dispatch(bridge, slug, AI_PODCAST_CANCEL_CAPABILITY, payload).await
177 }133 }
178 134
135+/// Handle one client-initiated `podcast.report` call: decode the payload,
136+/// hand it to the workflow layer (which owns every check), and answer the
137+/// reply payload — or the flat `(code, message)` refusal the bridge frames.
138+///
139+/// The decode is deliberately strict: a payload that does not fit
140+/// [`PodcastReportPayload`] is `invalid_payload`, never coerced into a
141+/// half-filled report.
142+pub async fn report(db: &Database, payload: Value) -> Result<Value, (&'static str, String)> {
143+ let report: PodcastReportPayload = serde_json::from_value(payload).map_err(|err| {
144+ (
145+ "invalid_payload",
146+ format!("the report payload does not fit the contract: {err}"),
147+ )
148+ })?;
149+ let input = ReportInput {
150+ job_id: &report.job_id,
151+ source_id: &report.source_id,
152+ format: report.format.as_deref(),
153+ user_id: &report.user_id,
154+ state: &report.state,
155+ stage: &report.stage,
156+ progress: report.progress,
157+ error_code: report.error_code.as_deref(),
158+ };
159+ match crate::service::podcast_job::report(db, &input).await {
160+ Ok(job) => Ok(serde_json::to_value(PodcastReportReply {
161+ job_id: job.get_id().key(),
162+ stored: true,
163+ })
164+ .expect("a report reply is always encodable")),
165+ Err(refusal) => Err((refusal.code(), refusal.message())),
166+ }
167+}
168+
169+/// A [`PodcastRefusal`] as the capability frame's flat `(code, message)`.
170+pub fn refusal(refusal: &PodcastRefusal) -> (&'static str, String) {
171+ (refusal.code(), refusal.message())
172+}
173+
174+/// Ingest one uploaded episode: validate the frame's metadata, check the job,
175+/// read exactly `size` bytes into a temp file under the school's blob root,
176+/// rename it into place, and stamp the row.
177+///
178+/// `files_root` is **the school's own** directory (the caller resolves the
179+/// slug); the file lands under its `podcast/` subdirectory, keyed by the job
180+/// id, which is what the job row's own `audio_key` then publishes.
181+///
182+/// The order is the point, and the same one the HTTP doors hold: a refusal
183+/// must cost the sender nothing, so metadata and the job's existence are
184+/// checked before a byte is read; the bytes are complete on disk (renamed,
185+/// never half-written) before the row names them; and a row write that finds
186+/// the job gone deletes the file it just stored rather than leaving an orphan.
187+pub async fn ingest<R>(
188+ db: &Database,
189+ files_root: &std::path::Path,
190+ request: &crate::ai::protocol::BlobUploadRequest,
191+ body: &mut R,
192+) -> Result<(String, u64), PodcastRefusal>
193+where
194+ R: tokio::io::AsyncRead + Unpin,
195+{
196+ use tokio::io::AsyncWriteExt as _;
197+
198+ crate::service::podcast_job::validate_audio(
199+ &request.name,
200+ &request.content_type,
201+ request.size,
202+ )?;
203+ let id = PodcastJobId::from_key(&request.job_id);
204+ let Some(job) = crate::db::podcast_job::read(db, &id).await? else {
205+ return Err(PodcastRefusal::UnknownJob);
206+ };
207+ if job.is_expired() {
208+ return Err(PodcastRefusal::Expired);
209+ }
210+
211+ let key = crate::service::podcast_job::audio_key(&id, &request.name, &request.content_type);
212+ let dir = files_root.join("podcast");
213+ tokio::fs::create_dir_all(&dir).await.map_err(|err| {
214+ PodcastRefusal::Unavailable(format!("could not create the podcast blob directory: {err}"))
215+ })?;
216+ let temp = dir.join(format!(".upload-{}.tmp", crate::domain::monotonic_id::next_uuid()));
217+ let mut file = tokio::fs::File::create(&temp).await.map_err(|err| {
218+ PodcastRefusal::Unavailable(format!("could not open the upload's temp file: {err}"))
219+ })?;
220+
221+ let mut remaining = request.size;
222+ let mut buf = [0u8; 64 * 1024];
223+ while remaining > 0 {
224+ let want = remaining.min(buf.len() as u64) as usize;
225+ let read = match tokio::io::AsyncReadExt::read(body, &mut buf[..want]).await {
226+ Ok(0) => {
227+ let _ = tokio::fs::remove_file(&temp).await;
228+ return Err(PodcastRefusal::InvalidPayload(
229+ "the stream ended before `size` bytes arrived".to_string(),
230+ ));
231+ }
232+ Ok(n) => n,
233+ Err(err) => {
234+ let _ = tokio::fs::remove_file(&temp).await;
235+ return Err(PodcastRefusal::Unavailable(format!(
236+ "reading the upload failed: {err}"
237+ )));
238+ }
239+ };
240+ if let Err(err) = file.write_all(&buf[..read]).await {
241+ let _ = tokio::fs::remove_file(&temp).await;
242+ return Err(PodcastRefusal::Unavailable(format!(
243+ "writing the upload failed: {err}"
244+ )));
245+ }
246+ remaining -= read as u64;
247+ }
248+ file.flush()
249+ .await
250+ .map_err(|err| PodcastRefusal::Unavailable(format!("flushing the upload failed: {err}")))?;
251+ drop(file);
252+ let final_path = files_root.join(&key);
253+ tokio::fs::rename(&temp, &final_path).await.map_err(|err| {
254+ PodcastRefusal::Unavailable(format!("could not move the upload into place: {err}"))
255+ })?;
256+
257+ match crate::service::podcast_job::set_audio(
258+ db,
259+ &id,
260+ &key,
261+ &request.name,
262+ &request.content_type,
263+ request.size as i64,
264+ request.duration_secs,
265+ )
266+ .await
267+ {
268+ Ok(Some(_)) => Ok((key, request.size)),
269+ // The job vanished between the check above and the row write: take the
270+ // bytes back out rather than leaving a file nothing names.
271+ Ok(None) => {
272+ let _ = tokio::fs::remove_file(&final_path).await;
273+ Err(PodcastRefusal::UnknownJob)
274+ }
275+ Err(err) => {
276+ let _ = tokio::fs::remove_file(&final_path).await;
277+ Err(err.into())
278+ }
279+ }
280+}
281+
179 /// One `podcast.*` round trip: encode, dispatch, decode. Every capability282 /// One `podcast.*` round trip: encode, dispatch, decode. Every capability
180 /// travels this path, so the encode/decode failure vocabulary is written once.283 /// travels this path, so the encode/decode failure vocabulary is written once.
181-///
182-/// The reply is decoded into the *typed* contract rather than handed back as
183-/// [`serde_json::Value`]: the service is a trust boundary, and a field the
184-/// backend then acts on (above all `audio_id`, which becomes a path under a
185-/// school's files directory) must exist and be a string before anything uses
186-/// it.
187 async fn dispatch<P, R>(284 async fn dispatch<P, R>(
188 bridge: &AiBridge,285 bridge: &AiBridge,
189 slug: &Slug,286 slug: &Slug,
src/ai/server.rsmodified+2 -7
@@ -646,12 +646,7 @@ async fn serve_upload(
646 // sender so its write stops rather than filling a stream nobody646 // sender so its write stops rather than filling a stream nobody
647 // reads.647 // reads.
648 let _ = recv.stop(1u32.into());648 let _ = recv.stop(1u32.into());
649- upload_refusal(649+ upload_refusal(request.id.clone(), request.school.clone(), code, message)
650- request.id.clone(),
651- request.school.clone(),
652- &code,
653- message,
654- )
655 }650 }
656 };651 };
657 if let Err(e) = write_frame(send, &response).await {652 if let Err(e) = write_frame(send, &response).await {
@@ -1092,7 +1087,7 @@ async fn serve_capability(inner: &Inner, request: CapabilityRequest) -> Capabili
1092 let call = capability::serve(1087 let call = capability::serve(
1093 &request.capability,1088 &request.capability,
1094 tenant.as_ref(),1089 tenant.as_ref(),
1095- &control,1090+ control,
1096 &request.payload,1091 &request.payload,
1097 );1092 );
1098 match tokio::time::timeout(inner.request_timeout, call).await {1093 match tokio::time::timeout(inner.request_timeout, call).await {
src/db/podcast_job.rsadded+450 -0
@@ -0,0 +1,450 @@
1+//! The `podcast_job` table: one row per submitted episode, written by the
2+//! submit door before it dispatches and updated by the service's own
3+//! `podcast.report` calls. The entity, its state enum and the read-side
4+//! projection live in [`crate::domain::podcast_job`]; this module is where the
5+//! rows are read and written.
6+//!
7+//! Every write here is a single conditional statement, never a read-then-write:
8+//! the report path passes the state it validated against (`from`) and matches
9+//! zero rows when a concurrent cancel moved the row first — the caller re-reads
10+//! and answers what actually happened. The transition *table* therefore lives
11+//! in exactly one place (the domain enum); SQL only guards the race.
12+//!
13+//! `done` can never be stored without an audio key: the column CHECK
14+//! (`podcast_job_done_has_audio`) backstops the service layer's refusal, so a
15+//! result door can trust every `done` row to name a blob.
16+
17+use crate::database::Database;
18+use crate::db::page::PagedList;
19+use crate::domain::podcast_job::{PodcastJob, PodcastJobId, PodcastJobState};
20+use crate::domain::timestamp::Timestamp;
21+use crate::domain::user::UserId;
22+use crate::error::AppError;
23+use sqlx::query_as;
24+
25+/// Write one freshly minted job. The id and timestamps are the caller's — the
26+/// service is handed the id this statement stores, so the row and the
27+/// service's record can never start out disagreeing.
28+pub async fn insert(db: &Database, job: &PodcastJob) -> Result<PodcastJob, AppError> {
29+ Ok(query_as!(
30+ PodcastJob,
31+ "INSERT INTO podcast_job (id, user_id, source_id, format, state, stage, progress, \
32+ error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, \
33+ eta_secs, created_at, updated_at) \
34+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $15) \
35+ RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", \
36+ source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, \
37+ audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \
38+ created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
39+ job.get_id().uuid(),
40+ job.get_user_id().uuid(),
41+ job.get_source_id(),
42+ job.get_format(),
43+ job.get_state().as_str(),
44+ job.get_stage(),
45+ job.get_progress(),
46+ job.get_error_code(),
47+ job.get_audio_key(),
48+ job.get_audio_name(),
49+ job.get_audio_type(),
50+ job.get_audio_bytes(),
51+ job.get_duration_secs(),
52+ job.get_eta_secs(),
53+ job.get_created_at().as_millis(),
54+ )
55+ .fetch_one(db)
56+ .await?)
57+}
58+
59+/// Read one job by id, whoever owns it — the report path only, which has
60+/// already checked that the reporting user is the row's own.
61+pub async fn read(db: &Database, id: &PodcastJobId) -> Result<Option<PodcastJob>, AppError> {
62+ Ok(query_as!(
63+ PodcastJob,
64+ "SELECT id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", \
65+ source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, \
66+ audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \
67+ created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\" \
68+ FROM podcast_job WHERE id = $1",
69+ id.uuid(),
70+ )
71+ .fetch_optional(db)
72+ .await?)
73+}
74+
75+/// Read a job only if `user` owns it — a foreign id reads as absent, so every
76+/// HTTP door answers 404 rather than leaking that it exists. The filter is in
77+/// the statement, not applied after the read, so the row never leaves the
78+/// database on a foreign caller's behalf.
79+pub async fn read_for(
80+ db: &Database,
81+ id: &PodcastJobId,
82+ user: &UserId,
83+) -> Result<Option<PodcastJob>, AppError> {
84+ Ok(query_as!(
85+ PodcastJob,
86+ "SELECT id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", \
87+ source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, \
88+ audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \
89+ created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\" \
90+ FROM podcast_job WHERE id = $1 AND user_id = $2",
91+ id.uuid(),
92+ user.uuid(),
93+ )
94+ .fetch_optional(db)
95+ .await?)
96+}
97+
98+/// A user's jobs, newest first — the sort `podcast_job_user_created` exists
99+/// for.
100+pub async fn list_for_user(
101+ db: &Database,
102+ user: &UserId,
103+ limit: Option<i64>,
104+ offset: i64,
105+) -> Result<(Vec<PodcastJob>, i64), AppError> {
106+ PagedList::new(
107+ "podcast_job WHERE user_id = $1",
108+ "ORDER BY created_at DESC, id DESC",
109+ )
110+ .bind(user.uuid())
111+ .run(limit, offset, db)
112+ .await
113+}
114+
115+/// Apply one validated report: `from` is the state the service layer read and
116+/// checked the transition against, and the statement moves the row only if it
117+/// still holds that state. `None` therefore means either the row is gone or a
118+/// concurrent write (a cancel, another report) moved it first — the caller
119+/// re-reads and answers the truth.
120+///
121+/// `format` fills the column once and never rewrites it: the service's default
122+/// resolution arrives on the first report, and a later report disagreeing with
123+/// it is refused by the service layer, not silently stored.
124+#[allow(clippy::too_many_arguments)]
125+pub async fn report(
126+ db: &Database,
127+ id: &PodcastJobId,
128+ from: PodcastJobState,
129+ to: PodcastJobState,
130+ stage: &str,
131+ progress: f64,
132+ error_code: Option<&str>,
133+ format: Option<&str>,
134+) -> Result<Option<PodcastJob>, AppError> {
135+ let now = Timestamp::now().as_millis();
136+ Ok(query_as!(
137+ PodcastJob,
138+ "UPDATE podcast_job SET state = $3, stage = $4, progress = $5, error_code = $6, \
139+ format = COALESCE(format, $7::text), updated_at = $8 \
140+ WHERE id = $1 AND state = $2 \
141+ RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", \
142+ source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, \
143+ audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \
144+ created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
145+ id.uuid(),
146+ from.as_str(),
147+ to.as_str(),
148+ stage,
149+ progress,
150+ error_code,
151+ format,
152+ now,
153+ )
154+ .fetch_optional(db)
155+ .await?)
156+}
157+
158+/// Mark a live job cancelled — the backend's own write behind the cancel
159+/// verdict, taken the moment the service confirms it. `None` means the row was
160+/// not live (already terminal, or gone), which is exactly the `cancelled:
161+/// false` verdict.
162+pub async fn set_cancelled(
163+ db: &Database,
164+ id: &PodcastJobId,
165+) -> Result<Option<PodcastJob>, AppError> {
166+ let now = Timestamp::now().as_millis();
167+ Ok(query_as!(
168+ PodcastJob,
169+ "UPDATE podcast_job SET state = 'cancelled', stage = '', updated_at = $2 \
170+ WHERE id = $1 AND state IN ('queued', 'running') \
171+ RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", \
172+ source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, \
173+ audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \
174+ created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
175+ id.uuid(),
176+ now,
177+ )
178+ .fetch_optional(db)
179+ .await?)
180+}
181+
182+/// Mark a live job failed with the backend's own reason code — a dispatch that
183+/// never reached a worker, or a service that answered `not_found` for a job
184+/// whose row still says it is running. Same `None` contract as
185+/// [`set_cancelled`].
186+pub async fn set_failed(
187+ db: &Database,
188+ id: &PodcastJobId,
189+ error_code: &str,
190+) -> Result<Option<PodcastJob>, AppError> {
191+ let now = Timestamp::now().as_millis();
192+ Ok(query_as!(
193+ PodcastJob,
194+ "UPDATE podcast_job SET state = 'failed', error_code = $2, stage = '', updated_at = $3 \
195+ WHERE id = $1 AND state IN ('queued', 'running') \
196+ RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", \
197+ source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, \
198+ audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \
199+ created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
200+ id.uuid(),
201+ error_code,
202+ now,
203+ )
204+ .fetch_optional(db)
205+ .await?)
206+}
207+
208+/// Record the uploaded episode on its job: the blob key plus the metadata the
209+/// audio door replays as headers. One statement, so "the bytes are stored" and
210+/// "the row names them" land together; a job that is gone answers `None`.
211+#[allow(clippy::too_many_arguments)]
212+pub async fn set_audio(
213+ db: &Database,
214+ id: &PodcastJobId,
215+ key: &str,
216+ name: &str,
217+ content_type: &str,
218+ bytes: i64,
219+ duration_secs: Option<f64>,
220+) -> Result<Option<PodcastJob>, AppError> {
221+ let now = Timestamp::now().as_millis();
222+ Ok(query_as!(
223+ PodcastJob,
224+ "UPDATE podcast_job SET audio_key = $2, audio_name = $3, audio_type = $4, \
225+ audio_bytes = $5, duration_secs = $6, updated_at = $7 \
226+ WHERE id = $1 \
227+ RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", \
228+ source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, \
229+ audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \
230+ created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
231+ id.uuid(),
232+ key,
233+ name,
234+ content_type,
235+ bytes,
236+ duration_secs,
237+ now,
238+ )
239+ .fetch_optional(db)
240+ .await?)
241+}
242+
243+/// Store the service's own ETA estimate on a job it has just accepted — the
244+/// number the read-side staleness window is scaled by and the submit receipt
245+/// echoes. A job that is gone answers `None`.
246+pub async fn set_eta(
247+ db: &Database,
248+ id: &PodcastJobId,
249+ eta_secs: i64,
250+) -> Result<Option<PodcastJob>, AppError> {
251+ Ok(query_as!(
252+ PodcastJob,
253+ "UPDATE podcast_job SET eta_secs = $2 WHERE id = $1 \
254+ RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", \
255+ source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, \
256+ audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \
257+ created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
258+ id.uuid(),
259+ eta_secs,
260+ )
261+ .fetch_optional(db)
262+ .await?)
263+}
264+
265+#[cfg(test)]
266+mod tests {
267+ use super::*;
268+ use crate::domain::monotonic_id::next_uuid;
269+
270+ /// A leased school database with one app_user row, and that user's id.
271+ async fn fixture() -> (Database, crate::database::TestDatabases, UserId) {
272+ let (db, leases) = crate::database::init_test_db().await;
273+ let user = UserId::from_key(&next_uuid().to_string());
274+ insert_user(&db, &user).await;
275+ (db, leases, user)
276+ }
277+
278+ async fn insert_user(db: &Database, user: &UserId) {
279+ // A monotonic counter, not a slice of the id: two UUIDv7s minted in
280+ // the same millisecond share their first hex digits.
281+ static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
282+ let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
283+ sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, $2, 0)")
284+ .bind(user.uuid())
285+ .bind(format!("test-user-{n}"))
286+ .execute(db)
287+ .await
288+ .expect("insert user");
289+ }
290+
291+ /// A minimal queued row for the statement tests below.
292+ fn job(user: &UserId) -> PodcastJob {
293+ let now = Timestamp::now();
294+ PodcastJob {
295+ id: PodcastJobId::generate(),
296+ user_id: *user,
297+ source_id: "src".to_string(),
298+ format: None,
299+ state: PodcastJobState::Queued,
300+ stage: String::new(),
301+ progress: 0.0,
302+ error_code: None,
303+ audio_key: None,
304+ audio_name: None,
305+ audio_type: None,
306+ audio_bytes: None,
307+ duration_secs: None,
308+ eta_secs: Some(30),
309+ created_at: now,
310+ updated_at: now,
311+ }
312+ }
313+
314+ /// The report write is conditional on the state the caller validated
315+ /// against, so a cancel and a late report cannot both win: whoever lands
316+ /// second matches nothing and the caller re-reads.
317+ #[tokio::test]
318+ async fn a_report_is_guarded_by_the_state_it_validated_against() {
319+ let (db, _leases, user) = fixture().await;
320+ let row = insert(&db, &job(&user)).await.expect("insert");
321+ let id = row.get_id().clone();
322+
323+ // The running report lands, and carries the resolved format with it.
324+ let running = report(
325+ &db,
326+ &id,
327+ PodcastJobState::Queued,
328+ PodcastJobState::Running,
329+ "script",
330+ 0.25,
331+ None,
332+ Some("duz_okuma"),
333+ )
334+ .await
335+ .expect("report")
336+ .expect("row was queued");
337+ assert_eq!(running.get_state(), PodcastJobState::Running);
338+ assert_eq!(running.get_format(), Some("duz_okuma"));
339+
340+ // A second report claiming the row is still queued matches nothing.
341+ let stale = report(
342+ &db,
343+ &id,
344+ PodcastJobState::Queued,
345+ PodcastJobState::Running,
346+ "script",
347+ 0.5,
348+ None,
349+ None,
350+ )
351+ .await
352+ .expect("report");
353+ assert!(stale.is_none());
354+
355+ // A cancel moves it; the done report that raced it matches nothing.
356+ assert!(set_cancelled(&db, &id).await.expect("cancel").is_some());
357+ let done = report(
358+ &db,
359+ &id,
360+ PodcastJobState::Running,
361+ PodcastJobState::Done,
362+ "done",
363+ 1.0,
364+ None,
365+ None,
366+ )
367+ .await
368+ .expect("report");
369+ assert!(done.is_none());
370+ assert_eq!(
371+ read(&db, &id).await.expect("read").unwrap().get_state(),
372+ PodcastJobState::Cancelled
373+ );
374+ // A terminal row refuses the backend's own writes too.
375+ assert!(set_failed(&db, &id, "interrupted").await.unwrap().is_none());
376+ }
377+
378+ /// A foreign user's id reads as absent — the query itself filters, so the
379+ /// row never leaves the database on the stranger's behalf.
380+ #[tokio::test]
381+ async fn a_foreign_user_reads_no_row() {
382+ let (db, _leases, owner) = fixture().await;
383+ let row = insert(&db, &job(&owner)).await.expect("insert");
384+ let id = row.get_id().clone();
385+ let stranger = UserId::from_key(&next_uuid().to_string());
386+ insert_user(&db, &stranger).await;
387+ assert!(
388+ read_for(&db, &id, &stranger)
389+ .await
390+ .expect("read")
391+ .is_none()
392+ );
393+ assert!(
394+ read_for(&db, &id, row.get_user_id())
395+ .await
396+ .expect("read")
397+ .is_some()
398+ );
399+ }
400+
401+ /// `done` and "has audio" can never disagree: the schema refuses a done
402+ /// report before an upload landed, and accepts it after.
403+ #[tokio::test]
404+ async fn done_cannot_be_stored_without_an_audio_key() {
405+ let (db, _leases, user) = fixture().await;
406+ let row = insert(&db, &job(&user)).await.expect("insert");
407+ let id = row.get_id().clone();
408+ let refused = report(
409+ &db,
410+ &id,
411+ PodcastJobState::Queued,
412+ PodcastJobState::Done,
413+ "done",
414+ 1.0,
415+ None,
416+ None,
417+ )
418+ .await;
419+ assert!(refused.is_err(), "the CHECK backstops the service layer");
420+ set_audio(
421+ &db,
422+ &id,
423+ "podcast/x.mp3",
424+ "episode.mp3",
425+ "audio/mpeg",
426+ 12,
427+ Some(3.5),
428+ )
429+ .await
430+ .expect("upload")
431+ .expect("row");
432+ let done = report(
433+ &db,
434+ &id,
435+ PodcastJobState::Queued,
436+ PodcastJobState::Done,
437+ "done",
438+ 1.0,
439+ None,
440+ None,
441+ )
442+ .await
443+ .expect("report")
444+ .expect("row");
445+ assert_eq!(done.get_state(), PodcastJobState::Done);
446+ assert_eq!(done.get_audio_key(), Some("podcast/x.mp3"));
447+ assert_eq!(done.get_duration_secs(), Some(3.5));
448+ assert_eq!(done.get_audio_bytes(), Some(12));
449+ }
450+}
src/domain/mod.rsmodified+1 -0
@@ -53,6 +53,7 @@ pub mod note_file;
53 pub mod parent_link;53 pub mod parent_link;
54 pub mod payment_ledger;54 pub mod payment_ledger;
55 pub mod person;55 pub mod person;
56+pub mod podcast_job;
56 pub mod pomodoro;57 pub mod pomodoro;
57 pub mod pool_question;58 pub mod pool_question;
58 pub mod pool_question_image;59 pub mod pool_question_image;
src/domain/podcast_job.rsadded+343 -0
@@ -0,0 +1,343 @@
1+//! One podcast job — the record the backend owns from the moment a caller
2+//! submits to the moment the audio is collected, plus its read-time
3+//! presentation.
4+//!
5+//! The service reports every transition back over the bridge
6+//! (`podcast.report`), but the row is written *first*, by the submit handler,
7+//! and every read door (`podcast.status`, `podcast.result`, the audio stream)
8+//! answers from this table alone. That is the whole point of the row: a
9+//! service restart — or a wiped service volume — costs no record, no job id,
10+//! and no audio bytes.
11+//!
12+//! A service that dies *without* reporting is what [`PodcastJob::projected`]
13+//! answers: a job left `queued`/`running` longer than its own ETA allows is
14+//! presented as `failed`/`interrupted` — on the read side only, never written —
15+//! the same device [`crate::domain::rag_message`] uses for a stranded turn.
16+//! The durable repair still belongs to the service: it sweeps its own store at
17+//! boot and reports each swept job, which overwrites the projection.
18+//!
19+//! The state vocabulary and the transition table are the service's own
20+//! (`jobs.py`'s `STATES`/`TRANSITIONS`), mirrored here so a report the service
21+//! could not have produced is refused instead of stored.
22+
23+use crate::constant::{
24+ PODCAST_INTERRUPTED_CODE, PODCAST_JOB_RETENTION_SECS, PODCAST_JOB_STALE_ETA_FACTOR,
25+ PODCAST_JOB_STALE_FLOOR_SECS,
26+};
27+use crate::domain::monotonic_id::next_uuid;
28+use crate::domain::timestamp::Timestamp;
29+use crate::domain::user::UserId;
30+
31+#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
32+#[sqlx(transparent)]
33+pub struct PodcastJobId(uuid::Uuid);
34+
35+impl PodcastJobId {
36+ /// Mints from the process-wide monotonic generator: job ids are also the
37+ /// service's record keys and the audio blob's file name, and a monotonic
38+ /// UUID keeps a directory listing of episodes in submit order.
39+ pub fn generate() -> Self {
40+ Self(next_uuid())
41+ }
42+
43+ /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
44+ /// cannot take the newtype. Static `query!` binds take `self` directly.
45+ pub fn uuid(&self) -> uuid::Uuid {
46+ self.0
47+ }
48+
49+ /// Parses a wire key. A key that is not a UUID parses as the nil UUID,
50+ /// which matches no row — the same rule every other id in the codebase
51+ /// follows.
52+ pub fn from_key(key: &str) -> Self {
53+ Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil()))
54+ }
55+
56+ /// The wire form: the standard hyphenated lowercase string. This is also
57+ /// the chain the service stores its own record under and the audio blob's
58+ /// stem, so it must stay byte-stable across every surface.
59+ pub fn key(&self) -> String {
60+ self.0.to_string()
61+ }
62+}
63+
64+/// Where a job is in its lifecycle. Stored as the bare lowercase string the
65+/// `state` column's CHECK allows; a value the enum doesn't know comes back as
66+/// a decode error, never a panic.
67+#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)]
68+#[sqlx(type_name = "TEXT", rename_all = "lowercase")]
69+pub enum PodcastJobState {
70+ Queued,
71+ Running,
72+ Done,
73+ Failed,
74+ Cancelled,
75+}
76+
77+impl PodcastJobState {
78+ /// The wire/storage form. Must stay in lockstep with `rename_all`.
79+ pub fn as_str(self) -> &'static str {
80+ match self {
81+ PodcastJobState::Queued => "queued",
82+ PodcastJobState::Running => "running",
83+ PodcastJobState::Done => "done",
84+ PodcastJobState::Failed => "failed",
85+ PodcastJobState::Cancelled => "cancelled",
86+ }
87+ }
88+
89+ /// Parses a report's own `state` string. `None` is a value the service
90+ /// should never have produced — the report is refused, not coerced.
91+ pub fn parse(value: &str) -> Option<Self> {
92+ match value {
93+ "queued" => Some(PodcastJobState::Queued),
94+ "running" => Some(PodcastJobState::Running),
95+ "done" => Some(PodcastJobState::Done),
96+ "failed" => Some(PodcastJobState::Failed),
97+ "cancelled" => Some(PodcastJobState::Cancelled),
98+ _ => None,
99+ }
100+ }
101+
102+ /// Done, failed or cancelled — the states a job never leaves.
103+ pub fn is_terminal(self) -> bool {
104+ matches!(
105+ self,
106+ PodcastJobState::Done | PodcastJobState::Failed | PodcastJobState::Cancelled
107+ )
108+ }
109+
110+ /// Can a report move a row from `self` to `target`? `jobs.py`'s
111+ /// `TRANSITIONS`, plus the identity transition: a report may repeat the
112+ /// state it last reported (a bridge round trip can time out after the
113+ /// service committed, and the retry must not be a refusal).
114+ pub fn can_transition_to(self, target: PodcastJobState) -> bool {
115+ if target == self {
116+ return true;
117+ }
118+ match self {
119+ PodcastJobState::Queued => matches!(
120+ target,
121+ PodcastJobState::Running | PodcastJobState::Cancelled | PodcastJobState::Failed
122+ ),
123+ PodcastJobState::Running => matches!(
124+ target,
125+ PodcastJobState::Done | PodcastJobState::Failed | PodcastJobState::Cancelled
126+ ),
127+ PodcastJobState::Done | PodcastJobState::Failed | PodcastJobState::Cancelled => false,
128+ }
129+ }
130+}
131+
132+#[derive(Debug, Clone, sqlx::FromRow)]
133+pub struct PodcastJob {
134+ pub(crate) id: PodcastJobId,
135+ /// The submitting user. The ownership guard every read door applies.
136+ pub(crate) user_id: UserId,
137+ pub(crate) source_id: String,
138+ pub(crate) format: Option<String>,
139+ pub(crate) state: PodcastJobState,
140+ pub(crate) stage: String,
141+ pub(crate) progress: f64,
142+ pub(crate) error_code: Option<String>,
143+ pub(crate) audio_key: Option<String>,
144+ pub(crate) audio_name: Option<String>,
145+ pub(crate) audio_type: Option<String>,
146+ pub(crate) audio_bytes: Option<i64>,
147+ pub(crate) duration_secs: Option<f64>,
148+ pub(crate) eta_secs: Option<i64>,
149+ pub(crate) created_at: Timestamp,
150+ pub(crate) updated_at: Timestamp,
151+}
152+
153+impl PodcastJob {
154+ pub fn get_id(&self) -> &PodcastJobId {
155+ &self.id
156+ }
157+
158+ pub fn get_user_id(&self) -> &UserId {
159+ &self.user_id
160+ }
161+
162+ pub fn get_source_id(&self) -> &str {
163+ &self.source_id
164+ }
165+
166+ pub fn get_format(&self) -> Option<&str> {
167+ self.format.as_deref()
168+ }
169+
170+ pub fn get_state(&self) -> PodcastJobState {
171+ self.state
172+ }
173+
174+ pub fn get_stage(&self) -> &str {
175+ &self.stage
176+ }
177+
178+ pub fn get_progress(&self) -> f64 {
179+ self.progress
180+ }
181+
182+ pub fn get_error_code(&self) -> Option<&str> {
183+ self.error_code.as_deref()
184+ }
185+
186+ pub fn get_audio_key(&self) -> Option<&str> {
187+ self.audio_key.as_deref()
188+ }
189+
190+ pub fn get_audio_name(&self) -> Option<&str> {
191+ self.audio_name.as_deref()
192+ }
193+
194+ pub fn get_audio_type(&self) -> Option<&str> {
195+ self.audio_type.as_deref()
196+ }
197+
198+ pub fn get_audio_bytes(&self) -> Option<i64> {
199+ self.audio_bytes
200+ }
201+
202+ pub fn get_duration_secs(&self) -> Option<f64> {
203+ self.duration_secs
204+ }
205+
206+ pub fn get_eta_secs(&self) -> Option<i64> {
207+ self.eta_secs
208+ }
209+
210+ pub fn get_created_at(&self) -> Timestamp {
211+ self.created_at
212+ }
213+
214+ pub fn get_updated_at(&self) -> Timestamp {
215+ self.updated_at
216+ }
217+
218+ /// The job as a read should present it, with no write behind it: a
219+ /// `queued`/`running` row nobody has updated inside its own staleness
220+ /// window is presented as `failed`/`interrupted`. The window scales with
221+ /// the service's own ETA — `max(floor, eta_secs × factor)` — so a long
222+ /// episode (or a queue of them) is never declared dead mid-flight, while a
223+ /// service that died takes its jobs down with it within a bounded,
224+ /// ETA-aware time.
225+ ///
226+ /// Only the returned copy is projected; the row is untouched, and the
227+ /// service's next report overwrites the projection the moment it lands.
228+ pub fn projected(mut self) -> Self {
229+ if self.state.is_terminal() {
230+ return self;
231+ }
232+ let eta_secs = self.eta_secs.unwrap_or(0).max(0);
233+ let window_ms = eta_secs
234+ .saturating_mul(PODCAST_JOB_STALE_ETA_FACTOR)
235+ .max(PODCAST_JOB_STALE_FLOOR_SECS)
236+ * 1_000;
237+ if Timestamp::now().as_millis() > self.updated_at.as_millis() + window_ms {
238+ self.state = PodcastJobState::Failed;
239+ self.error_code = Some(PODCAST_INTERRUPTED_CODE.to_string());
240+ self.stage = String::new();
241+ }
242+ self
243+ }
244+
245+ /// Has this job aged out of the retention window? Terminal rows older than
246+ /// [`PODCAST_JOB_RETENTION_SECS`] — measured from the write that finished
247+ /// them — are refused `410`, and the audio door will not stream their blob.
248+ /// A read-side test only; nothing is swept on the read path.
249+ pub fn is_expired(&self) -> bool {
250+ self.state.is_terminal()
251+ && Timestamp::now().as_millis() - self.updated_at.as_millis()
252+ > PODCAST_JOB_RETENTION_SECS * 1_000
253+ }
254+}
255+
256+#[cfg(test)]
257+mod tests {
258+ use super::*;
259+
260+ #[test]
261+ fn the_transition_table_is_the_services_own() {
262+ use PodcastJobState::*;
263+ assert!(Queued.can_transition_to(Running));
264+ assert!(Queued.can_transition_to(Cancelled));
265+ assert!(Queued.can_transition_to(Failed));
266+ assert!(!Queued.can_transition_to(Done));
267+ assert!(Running.can_transition_to(Done));
268+ assert!(Running.can_transition_to(Failed));
269+ assert!(Running.can_transition_to(Cancelled));
270+ assert!(!Running.can_transition_to(Queued));
271+ for terminal in [Done, Failed, Cancelled] {
272+ for target in [Queued, Running, Done, Failed, Cancelled] {
273+ assert_eq!(
274+ terminal.can_transition_to(target),
275+ terminal == target,
276+ "{terminal:?} -> {target:?}"
277+ );
278+ }
279+ }
280+ }
281+
282+ #[test]
283+ fn a_projected_job_is_failed_interrupted_but_a_long_eta_is_respected() {
284+ let mut job = dead_job(PodcastJobState::Running, 3_600);
285+ job.updated_at = Timestamp::from_millis(Timestamp::now().as_millis() - 2_000_000);
286+ // Two million ms stale on a one-hour ETA: the window is 3h, so the job
287+ // is still believed to be running.
288+ assert_eq!(job.clone().projected().get_state(), PodcastJobState::Running);
289+ // Past 3h, the projection fires.
290+ job.updated_at = Timestamp::from_millis(Timestamp::now().as_millis() - 11_000_000);
291+ let projected = job.projected();
292+ assert_eq!(projected.get_state(), PodcastJobState::Failed);
293+ assert_eq!(projected.get_error_code(), Some(PODCAST_INTERRUPTED_CODE));
294+ }
295+
296+ #[test]
297+ fn a_fresh_job_and_a_terminal_job_are_never_projected() {
298+ let fresh = dead_job(PodcastJobState::Queued, 5);
299+ assert_eq!(fresh.clone().projected().get_state(), PodcastJobState::Queued);
300+ let done = dead_job(PodcastJobState::Done, 0);
301+ assert_eq!(done.clone().projected().get_state(), PodcastJobState::Done);
302+ assert_eq!(done.projected().get_error_code(), None);
303+ }
304+
305+ #[test]
306+ fn retention_counts_only_terminal_rows_past_the_window() {
307+ let mut done = dead_job(PodcastJobState::Done, 0);
308+ assert!(!done.is_expired());
309+ done.updated_at = Timestamp::from_millis(
310+ Timestamp::now().as_millis() - (PODCAST_JOB_RETENTION_SECS + 60) * 1_000,
311+ );
312+ assert!(done.is_expired());
313+ // A non-terminal row is the projection's business, not expiry's.
314+ let mut running = dead_job(PodcastJobState::Running, 0);
315+ running.updated_at = Timestamp::from_millis(
316+ Timestamp::now().as_millis() - (PODCAST_JOB_RETENTION_SECS + 60) * 1_000,
317+ );
318+ assert!(!running.is_expired());
319+ }
320+
321+ /// A row with every field filled, for the projection/expiry tests only.
322+ fn dead_job(state: PodcastJobState, eta_secs: i64) -> PodcastJob {
323+ let now = Timestamp::now();
324+ PodcastJob {
325+ id: PodcastJobId::generate(),
326+ user_id: UserId::from_key("00000000-0000-7000-8000-000000000000"),
327+ source_id: "src".to_string(),
328+ format: None,
329+ state,
330+ stage: String::new(),
331+ progress: 0.0,
332+ error_code: None,
333+ audio_key: None,
334+ audio_name: None,
335+ audio_type: None,
336+ audio_bytes: None,
337+ duration_secs: None,
338+ eta_secs: Some(eta_secs),
339+ created_at: now,
340+ updated_at: now,
341+ }
342+ }
343+}
src/error.rsmodified+9 -0
@@ -63,6 +63,13 @@ pub enum AppError {
63 Validation(#[from] ValidationError),63 Validation(#[from] ValidationError),
64 #[error("not found")]64 #[error("not found")]
65 NotFound,65 NotFound,
66+ /// The resource existed, its retention window has passed, and nothing
67+ /// about it is served any more — a podcast job older than
68+ /// [`crate::constant::PODCAST_JOB_RETENTION_SECS`] today. A dedicated
69+ /// `410` so a client can tell "gone for good" from "never existed" (`404`)
70+ /// and from "not written yet" (`409`) without parsing a sentence.
71+ #[error("expired: {0}")]
72+ Expired(&'static str),
66 #[error("unauthorized")]73 #[error("unauthorized")]
67 Unauthorized,74 Unauthorized,
68 #[error("forbidden: {0}")]75 #[error("forbidden: {0}")]
@@ -152,6 +159,7 @@ impl AppError {
152 match self {159 match self {
153 AppError::Validation(_) => "validation",160 AppError::Validation(_) => "validation",
154 AppError::NotFound => "not_found",161 AppError::NotFound => "not_found",
162+ AppError::Expired(_) => "expired",
155 AppError::Unauthorized => "unauthorized",163 AppError::Unauthorized => "unauthorized",
156 AppError::Forbidden(_) => "forbidden",164 AppError::Forbidden(_) => "forbidden",
157 AppError::ModuleDisabled(_) => "module_disabled",165 AppError::ModuleDisabled(_) => "module_disabled",
@@ -266,6 +274,7 @@ impl AppError {
266 }274 }
267 AppError::Validation(v) => (StatusCode::BAD_REQUEST, v.to_string()),275 AppError::Validation(v) => (StatusCode::BAD_REQUEST, v.to_string()),
268 AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()),276 AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()),
277+ AppError::Expired(m) => (StatusCode::GONE, m.to_string()),
269 AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),278 AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),
270 AppError::Forbidden(m) => (StatusCode::FORBIDDEN, m.to_string()),279 AppError::Forbidden(m) => (StatusCode::FORBIDDEN, m.to_string()),
271 AppError::Conflict(m) => (StatusCode::CONFLICT, m.to_string()),280 AppError::Conflict(m) => (StatusCode::CONFLICT, m.to_string()),
src/service/mod.rsmodified+1 -0
@@ -47,6 +47,7 @@ pub mod note_file;
47 pub mod parent_link;47 pub mod parent_link;
48 pub mod payment_ledger;48 pub mod payment_ledger;
49 pub mod person;49 pub mod person;
50+pub mod podcast_job;
50 pub mod pomodoro;51 pub mod pomodoro;
51 pub mod pool_question;52 pub mod pool_question;
52 pub mod pool_question_image;53 pub mod pool_question_image;
src/service/podcast_job.rsadded+342 -0
@@ -0,0 +1,342 @@
1+//! Podcast job workflows: the submit write that mints a job, the report write
2+//! the service's `podcast.report` calls land through, the cancel/fail writes
3+//! behind the HTTP verdicts, and the audio reference an ingest stamps.
4+//!
5+//! The queries live in [`crate::db::podcast_job`]. Everything that decides
6+//! *whether* a write may happen lives here: the report path is the trust
7+//! boundary between the service and this table, so it validates the sender's
8+//! echo (user, source), the transition (`jobs.py`'s table, via the domain
9+//! enum), the retention window, and the "done means audio" rule — in that
10+//! order — before a single statement runs.
11+
12+use crate::database::Database;
13+use crate::db::podcast_job;
14+use crate::domain::podcast_job::{PodcastJob, PodcastJobId, PodcastJobState};
15+use crate::domain::timestamp::Timestamp;
16+use crate::domain::user::UserId;
17+use crate::error::AppError;
18+use crate::validate::validate_required;
19+
20+/// The most characters a report may put in `stage` / `error_code`. Generous
21+/// for the service's own short codes and stage names; the bound exists so a
22+/// service cannot write a paragraph into a column a UI renders inline.
23+const MAX_CODE_LEN: usize = 64;
24+
25+/// Why one `podcast.report` (or an audio ingest) was refused. `code()` is the
26+/// flat, stable, machine-readable string the bridge answers in the
27+/// capability's `code` field — the same vocabulary the protocol's other
28+/// refusals use. Never nested, never localized.
29+#[derive(Debug)]
30+pub enum PodcastRefusal {
31+ /// No job with that id exists in the school the frame named — including a
32+ /// real id belonging to another school, which reads the same on purpose.
33+ UnknownJob,
34+ /// The report does not describe a state this service could have produced:
35+ /// an unknown state name, an out-of-range progress, an over-long code, or
36+ /// a transition the state machine forbids.
37+ InvalidPayload(String),
38+ /// The sender's echo of the job disagrees with the row — a report for a
39+ /// job under a different user or source.
40+ NotPermitted(String),
41+ /// A `done` report arrived before its audio was ingested. The row must
42+ /// never claim a finished episode whose bytes are not there.
43+ AudioMissing,
44+ /// The job aged out of the retention window; its blob is no longer served
45+ /// and its state is frozen history.
46+ Expired,
47+ /// The store itself refused — nothing the service can fix by retrying
48+ /// differently.
49+ Unavailable(String),
50+}
51+
52+impl PodcastRefusal {
53+ pub fn code(&self) -> &'static str {
54+ match self {
55+ PodcastRefusal::UnknownJob => "unknown_job",
56+ PodcastRefusal::InvalidPayload(_) => "invalid_payload",
57+ PodcastRefusal::NotPermitted(_) => "not_permitted",
58+ PodcastRefusal::AudioMissing => "audio_missing",
59+ PodcastRefusal::Expired => "expired",
60+ PodcastRefusal::Unavailable(_) => "unavailable",
61+ }
62+ }
63+
64+ pub fn message(&self) -> String {
65+ match self {
66+ PodcastRefusal::UnknownJob => "no such podcast job".to_string(),
67+ PodcastRefusal::InvalidPayload(why) => why.clone(),
68+ PodcastRefusal::NotPermitted(why) => why.clone(),
69+ PodcastRefusal::AudioMissing => {
70+ "a done report requires the episode to be uploaded first".to_string()
71+ }
72+ PodcastRefusal::Expired => "this podcast job has expired".to_string(),
73+ PodcastRefusal::Unavailable(why) => why.clone(),
74+ }
75+ }
76+}
77+
78+impl From<AppError> for PodcastRefusal {
79+ fn from(err: AppError) -> Self {
80+ PodcastRefusal::Unavailable(err.to_string())
81+ }
82+}
83+
84+/// One state report from the service, as [`crate::ai::podcast`] decoded it.
85+/// The borrowed strings are the wire's own; nothing here is trusted until
86+/// [`report`] has checked it against the row.
87+#[derive(Debug)]
88+pub struct ReportInput<'a> {
89+ pub job_id: &'a str,
90+ pub source_id: &'a str,
91+ pub format: Option<&'a str>,
92+ pub user_id: &'a str,
93+ pub state: &'a str,
94+ pub stage: &'a str,
95+ pub progress: f64,
96+ pub error_code: Option<&'a str>,
97+}
98+
99+/// Mint and store one freshly submitted job. The id is the backend's (the
100+/// service is handed it in the submit payload), and the row starts `queued`
101+/// with no ETA — the service's own estimate lands a moment later, with
102+/// [`set_eta`], once it has accepted the job.
103+pub async fn create(
104+ db: &Database,
105+ user: &UserId,
106+ source_id: &str,
107+ format: Option<&str>,
108+) -> Result<PodcastJob, AppError> {
109+ let now = Timestamp::now();
110+ let job = PodcastJob {
111+ id: PodcastJobId::generate(),
112+ user_id: *user,
113+ source_id: source_id.to_string(),
114+ format: format.map(str::to_string),
115+ state: PodcastJobState::Queued,
116+ stage: String::new(),
117+ progress: 0.0,
118+ error_code: None,
119+ audio_key: None,
120+ audio_name: None,
121+ audio_type: None,
122+ audio_bytes: None,
123+ duration_secs: None,
124+ eta_secs: None,
125+ created_at: now,
126+ updated_at: now,
127+ };
128+ podcast_job::insert(db, &job).await
129+}
130+
131+/// Store the service's own ETA on the job it just accepted — the number the
132+/// read-side staleness window is scaled by, echoed back to the submitter.
133+pub async fn set_eta(
134+ db: &Database,
135+ id: &PodcastJobId,
136+ eta_secs: i64,
137+) -> Result<Option<PodcastJob>, AppError> {
138+ podcast_job::set_eta(db, id, eta_secs.max(0)).await
139+}
140+
141+/// Read a job only if `user` owns it — a foreign id reads as absent, so the
142+/// HTTP doors answer 404 rather than leaking that it exists.
143+pub async fn read_for(
144+ db: &Database,
145+ id: &PodcastJobId,
146+ user: &UserId,
147+) -> Result<Option<PodcastJob>, AppError> {
148+ podcast_job::read_for(db, id, user).await
149+}
150+
151+/// A user's own jobs, newest first.
152+pub async fn list_for_user(
153+ db: &Database,
154+ user: &UserId,
155+ limit: Option<i64>,
156+ offset: i64,
157+) -> Result<(Vec<PodcastJob>, i64), AppError> {
158+ podcast_job::list_for_user(db, user, limit, offset).await
159+}
160+
161+/// Apply one report from the service. The order of the checks is the point:
162+/// shape first (so nothing malformed reaches a query), then existence, then
163+/// the sender's own echo, then the retention window, then the transition, and
164+/// finally "done means audio" — the rule the schema's CHECK also backstops.
165+///
166+/// The write itself is conditional on the state just read (`from`), so a
167+/// cancel racing this report cannot be overwritten by it; when the condition
168+/// loses, the refusal names the state that actually holds.
169+pub async fn report(
170+ db: &Database,
171+ input: &ReportInput<'_>,
172+) -> Result<PodcastJob, PodcastRefusal> {
173+ let id = PodcastJobId::from_key(input.job_id);
174+ let Some(target) = PodcastJobState::parse(input.state) else {
175+ return Err(PodcastRefusal::InvalidPayload(format!(
176+ "`{}` is not a known job state",
177+ input.state
178+ )));
179+ };
180+ if !input.progress.is_finite() || !(0.0..=1.0).contains(&input.progress) {
181+ return Err(PodcastRefusal::InvalidPayload(
182+ "progress must be a fraction between 0 and 1".to_string(),
183+ ));
184+ }
185+ if input.stage.chars().count() > MAX_CODE_LEN {
186+ return Err(PodcastRefusal::InvalidPayload(
187+ "stage is longer than 64 characters".to_string(),
188+ ));
189+ }
190+ if let Some(code) = input.error_code
191+ && code.chars().count() > MAX_CODE_LEN
192+ {
193+ return Err(PodcastRefusal::InvalidPayload(
194+ "error_code is longer than 64 characters".to_string(),
195+ ));
196+ }
197+
198+ let Some(row) = podcast_job::read(db, &id).await? else {
199+ return Err(PodcastRefusal::UnknownJob);
200+ };
201+ if row.get_user_id().key() != input.user_id {
202+ return Err(PodcastRefusal::NotPermitted(
203+ "the job belongs to another user".to_string(),
204+ ));
205+ }
206+ if row.get_source_id() != input.source_id {
207+ return Err(PodcastRefusal::NotPermitted(
208+ "the job's source does not match this report".to_string(),
209+ ));
210+ }
211+ if let (Some(stored), Some(reported)) = (row.get_format(), input.format)
212+ && stored != reported
213+ {
214+ return Err(PodcastRefusal::NotPermitted(
215+ "the job's format was already resolved and this report disagrees".to_string(),
216+ ));
217+ }
218+ if row.is_expired() {
219+ return Err(PodcastRefusal::Expired);
220+ }
221+ if !row.get_state().can_transition_to(target) {
222+ return Err(PodcastRefusal::InvalidPayload(format!(
223+ "`{}` cannot move to `{}`",
224+ row.get_state().as_str(),
225+ target.as_str()
226+ )));
227+ }
228+ if target == PodcastJobState::Done && row.get_audio_key().is_none() {
229+ return Err(PodcastRefusal::AudioMissing);
230+ }
231+
232+ match podcast_job::report(
233+ db,
234+ &id,
235+ row.get_state(),
236+ target,
237+ input.stage,
238+ input.progress,
239+ input.error_code,
240+ input.format,
241+ )
242+ .await?
243+ {
244+ Some(updated) => Ok(updated),
245+ // The row moved between the read and the write (a cancel, most
246+ // likely). Nothing was stored; name the state that actually holds.
247+ None => match podcast_job::read(db, &id).await? {
248+ Some(current) => Err(PodcastRefusal::InvalidPayload(format!(
249+ "the job moved to `{}` while this report was in flight",
250+ current.get_state().as_str()
251+ ))),
252+ None => Err(PodcastRefusal::UnknownJob),
253+ },
254+ }
255+}
256+
257+/// Take the backend's own cancel write: only a live row moves, and `None`
258+/// (already terminal, or gone) is the `cancelled: false` verdict.
259+pub async fn mark_cancelled(
260+ db: &Database,
261+ id: &PodcastJobId,
262+) -> Result<Option<PodcastJob>, AppError> {
263+ podcast_job::set_cancelled(db, id).await
264+}
265+
266+/// Mark a live job failed with a backend-side reason code — a dispatch that
267+/// never reached a worker, or a service that lost a job its row still calls
268+/// live.
269+pub async fn mark_failed(
270+ db: &Database,
271+ id: &PodcastJobId,
272+ error_code: &str,
273+) -> Result<Option<PodcastJob>, AppError> {
274+ podcast_job::set_failed(db, id, error_code).await
275+}
276+
277+/// Validate one upload's metadata before a byte is written: the name and
278+/// content type a browser will see, and the size bound. `Err` carries the flat
279+/// refusal code the bridge answers.
280+pub fn validate_audio(
281+ name: &str,
282+ content_type: &str,
283+ size: u64,
284+) -> Result<(), PodcastRefusal> {
285+ if let Err(why) = validate_required("name", name, 200) {
286+ return Err(PodcastRefusal::InvalidPayload(why.to_string()));
287+ }
288+ if !content_type.starts_with("audio/") {
289+ return Err(PodcastRefusal::InvalidPayload(format!(
290+ "`{content_type}` is not an audio content type"
291+ )));
292+ }
293+ if size == 0 {
294+ return Err(PodcastRefusal::InvalidPayload(
295+ "an empty episode is not an episode".to_string(),
296+ ));
297+ }
298+ if size > crate::constant::PODCAST_AUDIO_MAX_BYTES as u64 {
299+ return Err(PodcastRefusal::InvalidPayload(format!(
300+ "the upload is larger than {} bytes",
301+ crate::constant::PODCAST_AUDIO_MAX_BYTES
302+ )));
303+ }
304+ Ok(())
305+}
306+
307+/// The blob key an uploaded episode is stored under: `podcast/<job-id>.<ext>`.
308+/// The extension comes off the service's own file name when it is a short,
309+/// boring one, and is otherwise derived from the content type — never copied
310+/// verbatim, so nothing the service sends can shape a path.
311+pub fn audio_key(job_id: &PodcastJobId, name: &str, content_type: &str) -> String {
312+ let extension = name
313+ .rsplit_once('.')
314+ .map(|(_, ext)| ext)
315+ .filter(|ext| {
316+ (1..=5).contains(&ext.len()) && ext.chars().all(|c| c.is_ascii_alphanumeric())
317+ })
318+ .map(|ext| ext.to_ascii_lowercase())
319+ .unwrap_or_else(|| match content_type {
320+ "audio/mpeg" => "mp3".to_string(),
321+ "audio/mp4" => "m4a".to_string(),
322+ "audio/aac" => "aac".to_string(),
323+ "audio/wav" | "audio/x-wav" => "wav".to_string(),
324+ "audio/ogg" => "ogg".to_string(),
325+ "audio/opus" => "opus".to_string(),
326+ _ => "bin".to_string(),
327+ });
328+ format!("podcast/{}.{extension}", job_id.key())
329+}
330+
331+/// Stamp the ingested episode onto its row, after the bytes are on disk.
332+pub async fn set_audio(
333+ db: &Database,
334+ id: &PodcastJobId,
335+ key: &str,
336+ name: &str,
337+ content_type: &str,
338+ bytes: i64,
339+ duration_secs: Option<f64>,
340+) -> Result<Option<PodcastJob>, AppError> {
341+ podcast_job::set_audio(db, id, key, name, content_type, bytes, duration_secs).await
342+}
src/web/board_ws.rsmodified+1 -0
@@ -585,6 +585,7 @@ fn error_frame(err: &AppError, client_seq: Option<u64>) -> Value {
585 AppError::Conflict(_) | AppError::ConflictOwned(_) => "conflict",585 AppError::Conflict(_) | AppError::ConflictOwned(_) => "conflict",
586 AppError::Validation(_) | AppError::PayloadTooLarge(_) => "invalid",586 AppError::Validation(_) | AppError::PayloadTooLarge(_) => "invalid",
587 AppError::NotFound => "not_found",587 AppError::NotFound => "not_found",
588+ AppError::Expired(_) => "expired",
588 // See `room::public_message`: the gate refuses the upgrade first.589 // See `room::public_message`: the gate refuses the upgrade first.
589 AppError::ModuleDisabled(_) => "module_disabled",590 AppError::ModuleDisabled(_) => "module_disabled",
590 AppError::Unauthorized => "unauthorized",591 AppError::Unauthorized => "unauthorized",
src/web/podcast.rsmodified+263 -282
@@ -1,75 +1,67 @@
1 //! The podcast nest: browser ⇄ backend ⇄ the podcast service (over the QUIC1 //! The podcast nest: browser ⇄ backend ⇄ the podcast service (over the QUIC
2-//! bridge), plus the door that hands back the produced audio.2+//! bridge), plus the doors that hand back the produced audio.
3 //!3 //!
4-//! The relay contract is the chatbot's and the RAG nest's, shape for shape:4+//! The **backend owns the job**. `POST /podcast/jobs` mints the id, writes the
5-//! the backend owns authentication and the thin HTTP surface, the **service**5+//! row, and only then dispatches `podcast.submit`; the service reports every
6-//! owns the job. Four doors map one-to-one onto the four `podcast.*`6+//! transition back (`podcast.report`) and uploads the finished mp3
7-//! capabilities — `POST /jobs` (submit), `GET /jobs/{id}` (status),7+//! (`BlobUploadRequest`), which lands under **this school's** blob directory.
8-//! `GET /jobs/{id}/result` (result) and `POST /jobs/{id}/cancel` (cancel) —8+//! `GET /podcast/jobs/{id}` and `.../result` therefore answer from
9-//! each refusing `503` when no worker declares its capability, and each9+//! [`crate::db::podcast_job`] alone — no worker, no service, no second store
10-//! relaying what the service answered: the receipt, the status snapshot, the10+//! that a restart or a wiped volume could take down with it. The service's own
11-//! artifacts, the cancel verdict. A service-side refusal keeps its own code11+//! record is a mirror the pipeline works against, not the source of truth.
12-//! (`not_found`, `not_ready`, `busy`, …) and decides the HTTP status, so a
13-//! client branches on the same vocabulary the bridge speaks.
14 //!12 //!
15-//! The fifth door is the audio itself. `podcast.result` answers an `audio_id`13+//! Five doors:
16-//! that is a path *relative* to the school's output root on this host — the
17-//! service's `PODCAST_OUTPUT_ROOT`, which the deployment points at this
18-//! school's own directory under `FILES_PATH` — so
19-//! `GET /podcast/audio?path=…` streams those bytes back. It is the one place
20-//! a caller names a path, so it is also the one place a path is treated as
21-//! hostile: absolute paths, `.`/`..` segments, backslashes, drive colons and
22-//! symlinks that resolve out of the school's directory are all refused with a
23-//! `400` — "this backend will not resolve that" — never a `404` that would
24-//! hide the difference from the caller probing it.
25 //!14 //!
26-//! Every door is school-scoped twice: the session resolves the school, and the15+//! * `POST /podcast/jobs` — write the row, dispatch `podcast.submit`
27-//! audio door resolves the path under *that* school's directory, so a caller16+//! * `GET /podcast/jobs/{id}` — the row's snapshot (projected, see below)
28-//! cannot reach another school's episode even knowing its exact path.17+//! * `GET /podcast/jobs/{id}/result` — a finished job's artifact references
18+//! * `GET /podcast/jobs/{id}/audio` — streams the ingested episode
19+//! * `POST /podcast/jobs/{id}/cancel` — forward the cancel, stamp the verdict
29 //!20 //!
30-//! None of the four dispatching doors writes a row: the job record and the21+//! The two dispatching doors (`submit`, `cancel`) refuse `503` when no worker
31-//! produced files live in the service. That is also why they are synchronous —22+//! declares their capability; the three reading doors need no service at all.
32-//! every capability answers immediately (the pipeline runs in the service's own23+//! A relayed failure keeps the service's own code and decides the HTTP status
33-//! pool), so there is nothing here to await off the request path.24+//! (`failure`), so a client branches on the same vocabulary the bridge speaks.
34 //!25 //!
35-//! What the backend can and cannot judge, stated plainly: the gate is a26+//! Every door is school-scoped twice: the session resolves the school's
36-//! session — any authenticated member of the school may use the doors, the same27+//! database (`st.db`) and the school's blob directory (`st.files_path`), and
37-//! floor `/chatbot` and `/rag` hold — and the school wall is the bridge's28+//! every read is filtered by the submitting user in the statement itself — a
38-//! (`hab/2` stamps the caller's school onto every request; the bridge does29+//! foreign id is a plain `404`, never a hint that it exists. Terminal rows
39-//! not verify the echo on replies — answers are correlated by frame id30+//! older than the retention window answer `410`.
40-//! alone). It cannot scope31+//!
41-//! *which* sources a caller may narrate: `source_id` is the service's own32+//! A job nobody is updating — the service died mid-pipeline — is *presented*
42-//! record, and no backend query can say what it names. That is a property of33+//! as `failed`/`interrupted` by the read path after a bounded, ETA-scaled
43-//! the wire the two sides share, not an oversight — the service resolves the34+//! window (see [`PodcastJob::projected`]): the projection writes nothing, and
44-//! id against the shared media volume and the backend enforces the tenant.35+//! the service's next report overwrites it. And what the backend still cannot
36+//! judge is stated plainly: `source_id` is the service's own handle on shared
37+//! media, so no backend query can say what it names — the service resolves it,
38+//! the backend enforces the tenant.
45 39
46 use axum::Json;40 use axum::Json;
47 use axum::body::{Body, Bytes};41 use axum::body::{Body, Bytes};
48-use axum::extract::{Path, Query};42+use axum::extract::Path;
49 use axum::http::HeaderValue;43 use axum::http::HeaderValue;
50 use axum::http::StatusCode;44 use axum::http::StatusCode;
51 use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS};45 use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS};
52 use axum::response::{IntoResponse, Response};46 use axum::response::{IntoResponse, Response};
53 use serde::{Deserialize, Serialize};47 use serde::{Deserialize, Serialize};
54 use serde_json::json;48 use serde_json::json;
55-use tokio::io::AsyncReadExt;
56 use tokio::sync::mpsc;49 use tokio::sync::mpsc;
57 use tokio_stream::Stream;50 use tokio_stream::Stream;
58 use tokio_stream::wrappers::ReceiverStream;51 use tokio_stream::wrappers::ReceiverStream;
59-use utoipa::{IntoParams, ToSchema};52+use utoipa::ToSchema;
60 use utoipa_axum::router::OpenApiRouter;53 use utoipa_axum::router::OpenApiRouter;
61 use utoipa_axum::routes;54 use utoipa_axum::routes;
62 55
63 use crate::ai::AiBridge;56 use crate::ai::AiBridge;
64-use crate::ai::podcast::{57+use crate::ai::podcast::{self, PodcastCancelPayload, PodcastSubmitPayload};
65- self, PodcastCancelPayload, PodcastCancelReply, PodcastResultPayload, PodcastResultReply,
66- PodcastStatusPayload, PodcastStatusReply, PodcastSubmitPayload, PodcastSubmitReply,
67-};
68 use crate::constant::{58 use crate::constant::{
69- AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_RESULT_CAPABILITY, AI_PODCAST_STATUS_CAPABILITY,59+ AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_SUBMIT_CAPABILITY, PODCAST_INTERRUPTED_CODE,
70- AI_PODCAST_SUBMIT_CAPABILITY,
71 };60 };
61+use crate::domain::podcast_job::{PodcastJob, PodcastJobId};
62+use crate::domain::user::User;
72 use crate::error::{AppError, ErrorResponse, ValidationError};63 use crate::error::{AppError, ErrorResponse, ValidationError};
64+use crate::service::podcast_job as jobs;
73 use crate::state::AppState;65 use crate::state::AppState;
74 use crate::web::tenant_state::{SchoolSlug, State};66 use crate::web::tenant_state::{SchoolSlug, State};
75 67
@@ -86,8 +78,8 @@ pub fn routes() -> OpenApiRouter<AppState> {
86 .routes(routes!(submit))78 .routes(routes!(submit))
87 .routes(routes!(status))79 .routes(routes!(status))
88 .routes(routes!(result))80 .routes(routes!(result))
89- .routes(routes!(cancel))
90 .routes(routes!(audio))81 .routes(routes!(audio))
82+ .routes(routes!(cancel))
91 }83 }
92 84
93 #[derive(Deserialize, ToSchema)]85 #[derive(Deserialize, ToSchema)]
@@ -104,10 +96,13 @@ struct SubmitPodcast {
104 format: Option<String>,96 format: Option<String>,
105 }97 }
106 98
107-/// The service's receipt for an accepted job, passed through verbatim.99+/// The receipt for an accepted job: the backend's own row plus the service's
100+/// ETA. `state` is always `queued` here — the row was just written.
108 #[derive(Serialize, ToSchema)]101 #[derive(Serialize, ToSchema)]
109 struct JobReceipt {102 struct JobReceipt {
110- /// The job id the service minted — every other door names it.103+ /// The backend-minted job id — every other door names it, and the service
104+ /// keys its own record by it.
105+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
111 job_id: String,106 job_id: String,
112 /// `queued` on a fresh job.107 /// `queued` on a fresh job.
113 state: String,108 state: String,
@@ -115,7 +110,7 @@ struct JobReceipt {
115 eta_secs: i64,110 eta_secs: i64,
116 }111 }
117 112
118-/// One job's state, passed through verbatim.113+/// One job's state, from the backend's own row.
119 #[derive(Serialize, ToSchema)]114 #[derive(Serialize, ToSchema)]
120 struct JobStatus {115 struct JobStatus {
121 job_id: String,116 job_id: String,
@@ -129,21 +124,17 @@ struct JobStatus {
129 error_code: Option<String>,124 error_code: Option<String>,
130 }125 }
131 126
132-/// A finished job's artifacts, passed through verbatim.127+/// A finished job's artifacts.
133 #[derive(Serialize, ToSchema)]128 #[derive(Serialize, ToSchema)]
134 struct JobArtifacts {129 struct JobArtifacts {
135 job_id: String,130 job_id: String,
136- /// The produced audio, as a path relative to the school's podcast output131+ /// The produced audio, as the blob key `GET /podcast/jobs/{id}/audio`
137- /// root — feed it straight to `GET /podcast/audio?path=…`.132+ /// streams — informational, never a path the caller resolves itself.
138- #[schema(example = "ses/duz_okuma/019732e3-7b00-7000-8000-00000000dead/episode.mp3")]133+ #[schema(example = "podcast/019732e3-7b00-7000-8000-00000000dead.mp3")]
139 audio_id: String,134 audio_id: String,
140- duration_secs: f64,135+ duration_secs: Option<f64>,
141- script_id: String,136+ /// The resolved narration format.
142- /// One entry per produced chapter; usually `[audio_id]`.137+ format: Option<String>,
143- audio_ids: Vec<String>,
144- /// One entry per script the audio was aligned to.
145- script_ids: Vec<String>,
146- format: String,
147 }138 }
148 139
149 /// The verdict on a cancel.140 /// The verdict on a cancel.
@@ -155,9 +146,14 @@ struct CancelVerdict {
155 cancelled: bool,146 cancelled: bool,
156 }147 }
157 148
158-/// Start one podcast job. Answers `202` with the service's receipt the moment149+/// Start one podcast job. Answers `202` with the backend's own receipt the
159-/// the service accepts it; the pipeline then runs in the service's own worker150+/// moment the service accepts it.
160-/// pool, so poll `GET /jobs/{id}` for progress.151+///
152+/// The row is written **before** the dispatch, so a poll that races the submit
153+/// finds the job rather than a `404`; and every dispatch outcome that is not an
154+/// acceptance leaves the row `failed` with a reason code rather than claiming
155+/// `queued` forever. With no worker connected the row is not written at all —
156+/// the `503` is the whole answer.
161 #[utoipa::path(157 #[utoipa::path(
162 post,158 post,
163 path = "/jobs",159 path = "/jobs",
@@ -175,7 +171,7 @@ struct CancelVerdict {
175 async fn submit(171 async fn submit(
176 State(st): State<AppState>,172 State(st): State<AppState>,
177 SchoolSlug(slug): SchoolSlug,173 SchoolSlug(slug): SchoolSlug,
178- CurrentUser(_user): CurrentUser,174+ CurrentUser(user): CurrentUser,
179 Json(req): Json<SubmitPodcast>,175 Json(req): Json<SubmitPodcast>,
180 ) -> Result<Response, AppError> {176 ) -> Result<Response, AppError> {
181 let bridge = match worker_for(&st, AI_PODCAST_SUBMIT_CAPABILITY) {177 let bridge = match worker_for(&st, AI_PODCAST_SUBMIT_CAPABILITY) {
@@ -193,18 +189,53 @@ async fn submit(
193 }));189 }));
194 }190 }
195 191
192+ let job = jobs::create(&st.db, user.get_id(), source_id, req.format.as_deref()).await?;
193+ let job_id = job.get_id().key();
196 let payload = PodcastSubmitPayload {194 let payload = PodcastSubmitPayload {
195+ job_id: job_id.clone(),
197 source_id: source_id.to_string(),196 source_id: source_id.to_string(),
198- format: req.format,197+ format: req.format.clone(),
198+ user_id: user.get_id().key(),
199 };199 };
200 match podcast::submit(&bridge, &slug, payload).await {200 match podcast::submit(&bridge, &slug, payload).await {
201- Ok(reply) => Ok((StatusCode::ACCEPTED, Json(receipt(reply))).into_response()),201+ // The echo is checked, not trusted: this id is the only handle every
202- Err(code) => Ok(failure(&code)),202+ // later call uses, so an answer about some other job is a protocol
203+ // failure, not a receipt.
204+ Ok(reply) if reply.job_id == job_id => {
205+ let eta_secs = reply.eta_secs;
206+ jobs::set_eta(&st.db, job.get_id(), eta_secs).await?;
207+ Ok((
208+ StatusCode::ACCEPTED,
209+ Json(JobReceipt {
210+ job_id,
211+ state: reply.state,
212+ eta_secs,
213+ }),
214+ )
215+ .into_response())
216+ }
217+ Ok(reply) => {
218+ tracing::warn!(
219+ "AI podcast service accepted job {} under the id {}",
220+ job_id,
221+ reply.job_id
222+ );
223+ jobs::mark_failed(&st.db, job.get_id(), "bad_reply").await?;
224+ Ok(failure("bad_reply"))
225+ }
226+ // The service refused the job: the row is the record of that, and the
227+ // refusal reaches the caller with its own status.
228+ Err(code) => {
229+ jobs::mark_failed(&st.db, job.get_id(), &code).await?;
230+ Ok(failure(&code))
231+ }
203 }232 }
204 }233 }
205 234
206-/// One job's current state. Poll this; the answer is the service's own235+/// One job's current state — the backend's own row, so this door answers with
207-/// snapshot.236+/// the service down, restarted, or never connected at all. A job nobody has
237+/// updated inside its ETA-scaled window reads as `failed`/`interrupted`; that
238+/// projection is read-side only and never written.
208 #[utoipa::path(239 #[utoipa::path(
209 get,240 get,
210 path = "/jobs/{id}",241 path = "/jobs/{id}",
@@ -214,29 +245,28 @@ async fn submit(
214 responses(245 responses(
215 (status = 200, description = "The job as of now", body = JobStatus),246 (status = 200, description = "The job as of now", body = JobStatus),
216 (status = 401, description = "Not authenticated", body = ErrorResponse),247 (status = 401, description = "Not authenticated", body = ErrorResponse),
217- (status = 404, description = "No such job (the service answered `not_found`)", body = ErrorResponse),248+ (status = 404, description = "No such job for this caller (unknown id, or another user's)", body = ErrorResponse),
218- (status = 503, description = "No AI service offers `podcast.status`", body = ErrorResponse),249+ (status = 410, description = "The job is past its retention window", body = ErrorResponse),
219 ),250 ),
220 )]251 )]
221 async fn status(252 async fn status(
222 State(st): State<AppState>,253 State(st): State<AppState>,
223- SchoolSlug(slug): SchoolSlug,254+ CurrentUser(user): CurrentUser,
224- CurrentUser(_user): CurrentUser,
225 Path(id): Path<String>,255 Path(id): Path<String>,
226 ) -> Result<Response, AppError> {256 ) -> Result<Response, AppError> {
227- let bridge = match worker_for(&st, AI_PODCAST_STATUS_CAPABILITY) {257+ let job = owned(&st, &user, &id).await?;
228- Ok(bridge) => bridge,258+ Ok(Json(JobStatus {
229- Err(no_worker) => return Ok(no_worker.refusal()),259+ job_id: job.get_id().key(),
230- };260+ state: job.get_state().as_str().to_string(),
231- match podcast::status(&bridge, &slug, PodcastStatusPayload { job_id: id }).await {261+ stage: job.get_stage().to_string(),
232- Ok(reply) => Ok(Json(snapshot(reply)).into_response()),262+ progress: job.get_progress(),
233- Err(code) => Ok(failure(&code)),263+ error_code: job.get_error_code().map(str::to_string),
234- }264+ })
265+ .into_response())
235 }266 }
236 267
237-/// A finished job's artifacts — above all the `audio_id` the audio door268+/// A finished job's artifact references. A job that has not finished is a
238-/// streams. A job that has not finished yet is refused by the service with269+/// `409 not_ready`; one the caller does not own, a `404`.
239-/// `not_ready` (409); one it has never heard of with `not_found` (404).
240 #[utoipa::path(270 #[utoipa::path(
241 get,271 get,
242 path = "/jobs/{id}/result",272 path = "/jobs/{id}/result",
@@ -246,109 +276,94 @@ async fn status(
246 responses(276 responses(
247 (status = 200, description = "The finished job's artifacts", body = JobArtifacts),277 (status = 200, description = "The finished job's artifacts", body = JobArtifacts),
248 (status = 401, description = "Not authenticated", body = ErrorResponse),278 (status = 401, description = "Not authenticated", body = ErrorResponse),
249- (status = 404, description = "No such job (the service answered `not_found`)", body = ErrorResponse),279+ (status = 404, description = "No such job for this caller", body = ErrorResponse),
250- (status = 409, description = "The job has not finished (the service answered `not_ready`)", body = ErrorResponse),280+ (status = 409, description = "The job has not finished (`code: not_ready`)", body = ErrorResponse),
251- (status = 503, description = "No AI service offers `podcast.result`", body = ErrorResponse),281+ (status = 410, description = "The job is past its retention window", body = ErrorResponse),
252 ),282 ),
253 )]283 )]
254 async fn result(284 async fn result(
255 State(st): State<AppState>,285 State(st): State<AppState>,
256- SchoolSlug(slug): SchoolSlug,286+ CurrentUser(user): CurrentUser,
257- CurrentUser(_user): CurrentUser,
258 Path(id): Path<String>,287 Path(id): Path<String>,
259 ) -> Result<Response, AppError> {288 ) -> Result<Response, AppError> {
260- let bridge = match worker_for(&st, AI_PODCAST_RESULT_CAPABILITY) {289+ let job = owned(&st, &user, &id).await?;
261- Ok(bridge) => bridge,290+ let audio_id = match job.get_state() {
262- Err(no_worker) => return Ok(no_worker.refusal()),291+ crate::domain::podcast_job::PodcastJobState::Done => job
263- };292+ .get_audio_key()
264- match podcast::result(&bridge, &slug, PodcastResultPayload { job_id: id }).await {293+ .expect("a done row always carries its audio (schema CHECK)")
265- Ok(reply) => Ok(Json(artifacts(reply)).into_response()),294+ .to_string(),
266- Err(code) => Ok(failure(&code)),295+ _ => {
267- }296+ return Err(AppError::ConflictCoded {
268-}297+ code: "not_ready",
269-298+ message: format!("job `{}` is {}", job.get_id().key(), job.get_state().as_str()),
270-/// Cancel one job. `cancelled` says whether *this call* stopped work — a job299+ });
271-/// that had already finished, or was already cancelled, answers `false` and is300+ }
272-/// not an error.
273-#[utoipa::path(
274- post,
275- path = "/jobs/{id}/cancel",
276- tag = "podcast",
277- security(("session_cookie" = [])),
278- params(("id" = String, Path, description = "Job id from `POST /podcast/jobs`")),
279- responses(
280- (status = 200, description = "The cancel verdict", body = CancelVerdict),
281- (status = 401, description = "Not authenticated", body = ErrorResponse),
282- (status = 404, description = "No such job (the service answered `not_found`)", body = ErrorResponse),
283- (status = 503, description = "No AI service offers `podcast.cancel`", body = ErrorResponse),
284- ),
285-)]
286-async fn cancel(
287- State(st): State<AppState>,
288- SchoolSlug(slug): SchoolSlug,
289- CurrentUser(_user): CurrentUser,
290- Path(id): Path<String>,
291-) -> Result<Response, AppError> {
292- let bridge = match worker_for(&st, AI_PODCAST_CANCEL_CAPABILITY) {
293- Ok(bridge) => bridge,
294- Err(no_worker) => return Ok(no_worker.refusal()),
295 };301 };
296- match podcast::cancel(&bridge, &slug, PodcastCancelPayload { job_id: id }).await {302+ Ok(Json(JobArtifacts {
297- Ok(reply) => Ok(Json(verdict(reply)).into_response()),303+ job_id: job.get_id().key(),
298- Err(code) => Ok(failure(&code)),304+ audio_id,
299- }305+ duration_secs: job.get_duration_secs(),
300-}306+ format: job.get_format().map(str::to_string),
301-307+ })
302-/// The query behind the audio door.308+ .into_response())
303-#[derive(Deserialize, IntoParams)]
304-struct AudioQuery {
305- /// The `audio_id` from `GET /podcast/jobs/{id}/result`, **verbatim**: a
306- /// path relative to this school's podcast output root.
307- #[param(example = "ses/duz_okuma/019732e3-7b00-7000-8000-00000000dead/episode.mp3")]
308- path: String,
309 }309 }
310 310
311-/// Stream one produced audio file. `path` is the `audio_id`311+/// Stream one produced episode. The bytes are this school's own — ingested
312-/// `podcast.result` answered, resolved under **this caller's school** output312+/// under this school's blob directory — and the content type is the one the
313-/// directory — the same directory the service's `PODCAST_OUTPUT_ROOT` points313+/// upload declared, replayed from the row.
314-/// at — and streamed in 64 KiB chunks, so a long episode costs the backend a
315-/// bounded buffer rather than its whole length in memory.
316 ///314 ///
317-/// The path is hostile input: a leading `/`, any `.`/`..` segment, a315+/// A job that is not `done` is a `409 not_ready`; a row whose blob is missing
318-/// backslash, a drive colon, or a symlink whose target resolves outside the316+/// from the host is a `409 audio_missing` (the row is intact, the bytes are
319-/// school's directory is a `400` (a path this backend will not resolve), not a317+/// not — a state a client can report, unlike a generic `500`).
320-/// `404` — a caller probing the boundary gets the truth, and a caller with a
321-/// legitimate `audio_id` never sees either.
322 #[utoipa::path(318 #[utoipa::path(
323 get,319 get,
324- path = "/audio",320+ path = "/jobs/{id}/audio",
325 tag = "podcast",321 tag = "podcast",
326 security(("session_cookie" = [])),322 security(("session_cookie" = [])),
323+ params(("id" = String, Path, description = "Job id from `POST /podcast/jobs`")),
327 responses(324 responses(
328 (status = 200, description = "The audio bytes", content_type = "audio/mpeg"),325 (status = 200, description = "The audio bytes", content_type = "audio/mpeg"),
329- (status = 400, description = "`path` is not a relative path inside this school's podcast output", body = ErrorResponse),
330 (status = 401, description = "Not authenticated", body = ErrorResponse),326 (status = 401, description = "Not authenticated", body = ErrorResponse),
331- (status = 404, description = "No such file in this school's podcast output", body = ErrorResponse),327+ (status = 404, description = "No such job for this caller", body = ErrorResponse),
328+ (status = 409, description = "Not finished yet (`not_ready`), or its blob is missing from this host (`audio_missing`)", body = ErrorResponse),
329+ (status = 410, description = "The job is past its retention window", body = ErrorResponse),
332 ),330 ),
333 )]331 )]
334 async fn audio(332 async fn audio(
335 State(st): State<AppState>,333 State(st): State<AppState>,
336- CurrentUser(_user): CurrentUser,334+ CurrentUser(user): CurrentUser,
337- Query(query): Query<AudioQuery>,335+ Path(id): Path<String>,
338 ) -> Result<Response, AppError> {336 ) -> Result<Response, AppError> {
339- // The school-scoped `State` has already narrowed `files_path` to the337+ let job = owned(&st, &user, &id).await?;
340- // caller's own directory under `FILES_PATH` — the very directory the338+ let key = match job.get_state() {
341- // service's `PODCAST_OUTPUT_ROOT` points at — so the containment root here339+ crate::domain::podcast_job::PodcastJobState::Done => job
342- // needs no school arithmetic of its own, and cannot drift from the one340+ .get_audio_key()
343- // every other blob route uses.341+ .expect("a done row always carries its audio (schema CHECK)")
344- let file_path = resolve_audio(&st.files_path, &query.path).await?;342+ .to_string(),
345- let file = tokio::fs::File::open(&file_path)343+ _ => {
346- .await344+ return Err(AppError::ConflictCoded {
347- .map_err(|_| AppError::NotFound)?;345+ code: "not_ready",
346+ message: format!("job `{}` is {}", job.get_id().key(), job.get_state().as_str()),
347+ });
348+ }
349+ };
350+ let path = crate::web::blob_path(&st.files_path, &key);
351+ let file = tokio::fs::File::open(&path).await.map_err(|err| {
352+ tracing::error!("missing blob for podcast job {}: {err}", job.get_id().key());
353+ AppError::ConflictCoded {
354+ code: "audio_missing",
355+ message: "the episode's file is missing on this host".to_string(),
356+ }
357+ })?;
358+ let content_type = job.get_audio_type().unwrap_or("application/octet-stream");
348 359
349 Ok((360 Ok((
350 [361 [
351- (CONTENT_TYPE, HeaderValue::from_static(audio_content_type(&file_path))),362+ (
363+ CONTENT_TYPE,
364+ HeaderValue::from_str(content_type)
365+ .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream")),
366+ ),
352 (X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")),367 (X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")),
353 (CACHE_CONTROL, HeaderValue::from_static("private, no-store")),368 (CACHE_CONTROL, HeaderValue::from_static("private, no-store")),
354 ],369 ],
@@ -357,84 +372,91 @@ async fn audio(
357 .into_response())372 .into_response())
358 }373 }
359 374
360-/// Resolve one `audio_id` into a real file under `root`, or refuse it.375+/// Cancel one job. `cancelled` says whether *this call* stopped work — a job
361-///376+/// that had already finished, or was already cancelled, answers `false` and is
362-/// The order is the point: shape first (so an absolute path or a `..` segment377+/// not an error. Only a live job needs the service; a terminal one is answered
363-/// never reaches the filesystem), then canonicalization — which follows every378+/// from the row without a worker. A service that has never heard of a live job
364-/// symlink, so a link that only *looks* like it lives under the root resolves379+/// (its store was wiped) leaves the row `failed`/`interrupted`: the job cannot
365-/// out of it and is refused by the containment check rather than served.380+/// finish, and the row says so.
366-async fn resolve_audio(381+#[utoipa::path(
367- root: &std::path::Path,382+ post,
368- relative: &str,383+ path = "/jobs/{id}/cancel",
369-) -> Result<std::path::PathBuf, AppError> {384+ tag = "podcast",
370- let refused = || {385+ security(("session_cookie" = [])),
371- AppError::Validation(ValidationError::Invalid {386+ params(("id" = String, Path, description = "Job id from `POST /podcast/jobs`")),
372- field: "path",387+ responses(
373- reason: "must be a relative path inside this school's podcast output",388+ (status = 200, description = "The cancel verdict", body = CancelVerdict),
389+ (status = 401, description = "Not authenticated", body = ErrorResponse),
390+ (status = 404, description = "No such job for this caller", body = ErrorResponse),
391+ (status = 410, description = "The job is past its retention window", body = ErrorResponse),
392+ (status = 503, description = "The job is live but no AI service offers `podcast.cancel`", body = ErrorResponse),
393+ ),
394+)]
395+async fn cancel(
396+ State(st): State<AppState>,
397+ SchoolSlug(slug): SchoolSlug,
398+ CurrentUser(user): CurrentUser,
399+ Path(id): Path<String>,
400+) -> Result<Response, AppError> {
401+ let job = owned(&st, &user, &id).await?;
402+ let job_id = job.get_id().key();
403+ if job.get_state().is_terminal() {
404+ return Ok(Json(CancelVerdict {
405+ job_id,
406+ cancelled: false,
374 })407 })
375- };408+ .into_response());
376-
377- if relative.is_empty() || relative.starts_with('/') {
378- return Err(refused());
379- }
380- // Neither byte appears in a path this backend produced: `\` is a separator
381- // on another platform, `:` is a drive designator there — and a NUL could
382- // only truncate the path inside the OS. Refused here, not left to the
383- // platform's rules.
384- if relative.contains('\\') || relative.contains(':') || relative.contains('\0') {
385- return Err(refused());
386- }
387- // Any `.`/`..` segment, or an empty one (`a//b`): the shape a traversal
388- // needs, refused before anything is joined.
389- if relative
390- .split('/')
391- .any(|segment| segment.is_empty() || segment == "." || segment == "..")
392- {
393- return Err(refused());
394 }409 }
395-410+ let bridge = match worker_for(&st, AI_PODCAST_CANCEL_CAPABILITY) {
396- // The root is canonicalized too: `FILES_PATH` may itself be reached411+ Ok(bridge) => bridge,
397- // through a symlink, and containment must compare real paths.412+ Err(no_worker) => return Ok(no_worker.refusal()),
398- let root = tokio::fs::canonicalize(root)413+ };
399- .await414+ let verdict = |cancelled: bool| {
400- .map_err(|_| AppError::NotFound)?;415+ Json(CancelVerdict {
401- let target = tokio::fs::canonicalize(root.join(relative))416+ job_id: job.get_id().key(),
402- .await417+ cancelled,
403- .map_err(|_| AppError::NotFound)?;418+ })
404-419+ .into_response()
405- // Symlink escape: `canonicalize` follows links, so a target that resolves420+ };
406- // outside the school's directory lands here, whatever the link looked like.421+ match podcast::cancel(
407- if !target.starts_with(&root) {422+ &bridge,
408- return Err(refused());423+ &slug,
409- }424+ PodcastCancelPayload {
410- // A directory is not an audio file — and serving `read` on it would be an425+ job_id: job_id.clone(),
411- // I/O error at best.426+ },
412- if !tokio::fs::metadata(&target)427+ )
413- .await428+ .await
414- .map(|meta| meta.is_file())
415- .unwrap_or(false)
416 {429 {
417- return Err(AppError::NotFound);430+ Ok(reply) if reply.cancelled => {
431+ jobs::mark_cancelled(&st.db, job.get_id()).await?;
432+ Ok(verdict(true))
433+ }
434+ // Not cancelled by this call: either it finished first (its terminal
435+ // report is on its way) or it was already cancelled.
436+ Ok(_) => Ok(verdict(false)),
437+ // The service has never heard of a job the row calls live — its store
438+ // was wiped or rolled back. The row records the truth: it cannot finish.
439+ Err(code) if code == "not_found" => {
440+ tracing::warn!("AI podcast service lost live job {job_id}");
441+ jobs::mark_failed(&st.db, job.get_id(), PODCAST_INTERRUPTED_CODE).await?;
442+ Ok(verdict(false))
443+ }
444+ Err(code) => Ok(failure(&code)),
418 }445 }
419- Ok(target)
420 }446 }
421 447
422-/// The content type for a produced artifact, by extension. `mp3` is what the448+/// Read one job for this caller, projected and expiry-checked — the three
423-/// pipeline writes today; the rest of the set is here so a format switch on the449+/// reading doors' shared first act. A foreign id and an unknown id are the
424-/// service side still serves as audio rather than as an opaque download.450+/// same `404`; a job past its retention window is a `410`.
425-fn audio_content_type(path: &std::path::Path) -> &'static str {451+async fn owned(st: &AppState, user: &User, id: &str) -> Result<PodcastJob, AppError> {
426- match path452+ let job = jobs::read_for(&st.db, &PodcastJobId::from_key(id), user.get_id())
427- .extension()453+ .await?
428- .and_then(|ext| ext.to_str())454+ .ok_or(AppError::NotFound)?
429- .map(str::to_ascii_lowercase)455+ .projected();
430- .as_deref()456+ if job.is_expired() {
431- {457+ return Err(AppError::Expired("this podcast job has expired"));
432- Some("mp3") => "audio/mpeg",
433- Some("wav") => "audio/wav",
434- Some("m4a") | Some("mp4") => "audio/mp4",
435- Some("ogg") | Some("oga") | Some("opus") => "audio/ogg",
436- _ => "application/octet-stream",
437 }458 }
459+ Ok(job)
438 }460 }
439 461
440 /// A file as a byte stream: a reader task hands chunks to the body over a462 /// 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 {
442 /// send instead of pinning the whole file in memory, and a closed body ends the464 /// send instead of pinning the whole file in memory, and a closed body ends the
443 /// task by itself.465 /// task by itself.
444 fn pump(file: tokio::fs::File) -> impl Stream<Item = Result<Bytes, std::io::Error>> + Send + 'static {466 fn pump(file: tokio::fs::File) -> impl Stream<Item = Result<Bytes, std::io::Error>> + Send + 'static {
445- let (tx, rx) = mpsc::channel(AUDIO_CHUNKS_IN_FLIGHT);467+ let (tx, rx) = mpsc::channel::<Result<Bytes, std::io::Error>>(AUDIO_CHUNKS_IN_FLIGHT);
446 tokio::spawn(async move {468 tokio::spawn(async move {
447 let mut file = file;469 let mut file = file;
448- let mut buffer = vec![0u8; AUDIO_CHUNK_BYTES];470+ let mut buf = vec![0u8; AUDIO_CHUNK_BYTES];
449 loop {471 loop {
450- match file.read(&mut buffer).await {472+ match tokio::io::AsyncReadExt::read(&mut file, &mut buf).await {
451 Ok(0) => break,473 Ok(0) => break,
452- Ok(read) => {474+ Ok(n) => {
453- if tx475+ if tx.send(Ok(Bytes::copy_from_slice(&buf[..n]))).await.is_err() {
454- .send(Ok(Bytes::copy_from_slice(&buffer[..read])))
455- .await
456- .is_err()
457- {
458 break;476 break;
459 }477 }
460 }478 }
@@ -490,7 +508,7 @@ impl NoWorker {
490 }508 }
491 }509 }
492 510
493-/// The 503 gate every dispatching door shares: no bridge configured, or no511+/// The 503 gate the two dispatching doors share: no bridge configured, or no
494 /// worker declaring this door's capability. `has_capability` is documented512 /// worker declaring this door's capability. `has_capability` is documented
495 /// racy — fine here: it never guards a write, and the dispatch that follows513 /// racy — fine here: it never guards a write, and the dispatch that follows
496 /// re-checks for real; this only spares a caller a round trip into a service514 /// re-checks for real; this only spares a caller a round trip into a service
@@ -523,40 +541,3 @@ fn failure(code: &str) -> Response {
523 };541 };
524 (status, Json(json!({ "error": code }))).into_response()542 (status, Json(json!({ "error": code }))).into_response()
525 }543 }
526-
527-fn receipt(reply: PodcastSubmitReply) -> JobReceipt {
528- JobReceipt {
529- job_id: reply.job_id,
530- state: reply.state,
531- eta_secs: reply.eta_secs,
532- }
533-}
534-
535-fn snapshot(reply: PodcastStatusReply) -> JobStatus {
536- JobStatus {
537- job_id: reply.job_id,
538- state: reply.state,
539- stage: reply.stage,
540- progress: reply.progress,
541- error_code: reply.error_code,
542- }
543-}
544-
545-fn artifacts(reply: PodcastResultReply) -> JobArtifacts {
546- JobArtifacts {
547- job_id: reply.job_id,
548- audio_id: reply.audio_id,
549- duration_secs: reply.duration_secs,
550- script_id: reply.script_id,
551- audio_ids: reply.audio_ids,
552- script_ids: reply.script_ids,
553- format: reply.format,
554- }
555-}
556-
557-fn verdict(reply: PodcastCancelReply) -> CancelVerdict {
558- CancelVerdict {
559- job_id: reply.job_id,
560- cancelled: reply.cancelled,
561- }
562-}
src/web/room.rsmodified+1 -0
@@ -120,6 +120,7 @@ pub(crate) fn public_message(err: &AppError, room: &str) -> String {
120 match err {120 match err {
121 AppError::Validation(err) => err.to_string(),121 AppError::Validation(err) => err.to_string(),
122 AppError::NotFound => "not found".to_string(),122 AppError::NotFound => "not found".to_string(),
123+ AppError::Expired(message) => (*message).to_string(),
123 AppError::Unauthorized => "unauthorized".to_string(),124 AppError::Unauthorized => "unauthorized".to_string(),
124 AppError::Forbidden(message) => (*message).to_string(),125 AppError::Forbidden(message) => (*message).to_string(),
125 AppError::Conflict(message) => (*message).to_string(),126 AppError::Conflict(message) => (*message).to_string(),
tests/integration.rsmodified+1 -1
@@ -434,7 +434,7 @@ async fn protected_routes_require_session() {
434 /// Floor on the number of protected operations swept. It only ever goes434 /// Floor on the number of protected operations swept. It only ever goes
435 /// up: raise it when routes are added. Without it, deleting a route family435 /// up: raise it when routes are added. Without it, deleting a route family
436 /// would delete its own coverage and still pass.436 /// would delete its own coverage and still pass.
437- const MIN_PROTECTED: usize = 323;437+ const MIN_PROTECTED: usize = 337;
438 438
439 let app = mem_app().await;439 let app = mem_app().await;
440 let spec = send(&app, "GET", "/api-docs/openapi.json", None, None)440 let spec = send(&app, "GET", "/api-docs/openapi.json", None, None)
tests/podcast.rsmodified+806 -351
@@ -2,16 +2,18 @@
2 //!2 //!
3 //! Everything here runs over a real QUIC socket on loopback — a real3 //! Everything here runs over a real QUIC socket on loopback — a real
4 //! handshake, real TLS, real streams — with [`Behaviour::Podcast`] standing in4 //! handshake, real TLS, real streams — with [`Behaviour::Podcast`] standing in
5-//! for what the service would do with a request. The four dispatching doors5+//! for what the service does with a request. The **backend owns the job**: the
6-//! are driven through the real router, so what they assert is what a browser6+//! submit door mints the id, writes the `podcast_job` row, and only then
7-//! would receive, and the fake service's `seen` log is what the *service*7+//! dispatches `podcast.submit`; the three reading doors answer from that row
8-//! received.8+//! alone; and the service reports every transition and uploads the finished
9+//! episode on its own client-initiated streams — the same connection it
10+//! registered with, exactly the shape `tests/ai_bridge.rs` drives.
9 //!11 //!
10-//! The audio door is tested against a real directory tree — the same12+//! The assertions therefore split in two: what a browser gets from the real
11-//! `FILES_PATH` layout the deployment uses — because its whole job is refusing13+//! router, and what the *service* received ([`FakeService::seen`]) or what the
12-//! paths that escape a school's directory. Every refusal test first proves the14+//! school's own database and blob directory hold. A reading door that quietly
13-//! target file exists, so a pass cannot come from the file simply being15+//! round-tripped to the service would fail the `seen` assertions; a submit that
14-//! missing.16+//! did not write its row first would fail the database ones.
15 17
16 mod common;18 mod common;
17 19
@@ -19,35 +21,40 @@ use std::sync::{Arc, Mutex};
19 use std::time::Duration;21 use std::time::Duration;
20 22
21 use axum::Router;23 use axum::Router;
22-use axum::http::StatusCode;24+use axum::http::{HeaderMap, StatusCode};
23 use hezarfen_backend::ai::protocol::{25 use hezarfen_backend::ai::protocol::{
24 Greeting, Hello, Request, Response, read_frame, write_frame,26 Greeting, Hello, Request, Response, read_frame, write_frame,
25 };27 };
26 use hezarfen_backend::ai::{AiBridge, BridgeConfig};28 use hezarfen_backend::ai::{AiBridge, BridgeConfig};
27 use hezarfen_backend::constant::{29 use hezarfen_backend::constant::{
28- AI_ALPN, AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_RESULT_CAPABILITY,30+ AI_ALPN, AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_SUBMIT_CAPABILITY, AI_PROTOCOL,
29- AI_PODCAST_STATUS_CAPABILITY, AI_PODCAST_SUBMIT_CAPABILITY, AI_PROTOCOL,31+ PODCAST_JOB_RETENTION_SECS, PODCAST_JOB_STALE_FLOOR_SECS,
30 };32 };
33+use hezarfen_backend::database::Database;
34+use hezarfen_backend::domain::timestamp::Timestamp;
31 use hezarfen_backend::module::{Module, ModuleSet};35 use hezarfen_backend::module::{Module, ModuleSet};
32 use hezarfen_backend::tenant::{DEMO_SLUG, Slug};36 use hezarfen_backend::tenant::{DEMO_SLUG, Slug};
33 use serde_json::{Value, json};37 use serde_json::{Value, json};
38+use uuid::Uuid;
34 39
35 const TOKEN: &str = "shared-ai-token";40 const TOKEN: &str = "shared-ai-token";
36 41
37-/// The four capabilities one podcast service declares.42+/// The two capabilities a live podcast worker offers. Status and result are
38-const CAPABILITIES: [&str; 4] = [43+/// not capabilities any more — the backend answers those from its own row — so
39- AI_PODCAST_SUBMIT_CAPABILITY,44+/// a service declaring only these serves every reading door.
40- AI_PODCAST_STATUS_CAPABILITY,45+const CAPABILITIES: [&str; 2] = [AI_PODCAST_SUBMIT_CAPABILITY, AI_PODCAST_CANCEL_CAPABILITY];
41- AI_PODCAST_RESULT_CAPABILITY,46+
42- AI_PODCAST_CANCEL_CAPABILITY,
43-];
44-
45-/// The job id the fake service mints, and the `audio_id` it answers — a path
46-/// relative to the school's output root, exactly as the real service writes it.
47-const JOB_ID: &str = "job-1";
48-const AUDIO_ID: &str = "ses/duz_okuma/bolum-1/episode.mp3";
49 /// A source id shaped like the backend ids the service is handed.47 /// A source id shaped like the backend ids the service is handed.
50 const SOURCE_ID: &str = "019732e3-7b00-7000-8000-00000000dead";48 const SOURCE_ID: &str = "019732e3-7b00-7000-8000-00000000dead";
49+/// The narration the caller asks for; the reports echo the same value, as the
50+/// service's first report resolves it.
51+const FORMAT: &str = "duz_okuma";
52+/// The estimate the fake service answers a submit with.
53+const ETA_SECS: i64 = 2700;
54+/// What the fake service says its uploaded episode runs for.
55+const DURATION_SECS: f64 = 12.5;
56+const AUDIO_NAME: &str = "bolum-1.mp3";
57+const AUDIO_TYPE: &str = "audio/mpeg";
51 58
52 // ---------------------------------------------------------------- harness --59 // ---------------------------------------------------------------- harness --
53 60
@@ -103,10 +110,13 @@ fn hello(service: &str, capabilities: &[&str]) -> Hello {
103 }110 }
104 111
105 /// A connected fake service. Holding it keeps the connection (and so the112 /// A connected fake service. Holding it keeps the connection (and so the
106-/// registration) alive; dropping it is how a test simulates a crash.113+/// registration) alive; dropping it is how a test simulates a crash. `conn` is
114+/// the registration connection itself — the one a real service opens its own
115+/// streams on when it reports a transition or uploads an episode.
107 struct FakeService {116 struct FakeService {
108 _endpoint: quinn::Endpoint,117 _endpoint: quinn::Endpoint,
109 _control: (quinn::SendStream, quinn::RecvStream),118 _control: (quinn::SendStream, quinn::RecvStream),
119+ conn: quinn::Connection,
110 /// Every request this service received, in arrival order.120 /// Every request this service received, in arrival order.
111 seen: Arc<Mutex<Vec<Request>>>,121 seen: Arc<Mutex<Vec<Request>>>,
112 }122 }
@@ -120,10 +130,12 @@ impl FakeService {
120 /// What the fake service does with each request it receives.130 /// What the fake service does with each request it receives.
121 #[derive(Clone)]131 #[derive(Clone)]
122 enum Behaviour {132 enum Behaviour {
123- /// Answer like the podcast service: a queued receipt, a status snapshot, a133+ /// Answer like the podcast service: a receipt echoing the backend's own
124- /// finished job's artifacts, a cancel verdict — each echoing the job id it134+ /// job id, and a cancel verdict.
125- /// was asked about, so a mis-routed id shows up in the answer.
126 Podcast,135 Podcast,
136+ /// Accept the job under an id of the service's own choosing — the one
137+ /// answer the submit door must not trust.
138+ WrongEcho,
127 /// Answer with a handled failure.139 /// Answer with a handled failure.
128 Fail { code: String, message: String },140 Fail { code: String, message: String },
129 }141 }
@@ -149,6 +161,7 @@ async fn connect_service(bridge: &AiBridge, hello: Hello, behaviour: Behaviour)
149 FakeService {161 FakeService {
150 _endpoint: endpoint,162 _endpoint: endpoint,
151 _control: (send, recv),163 _control: (send, recv),
164+ conn,
152 seen,165 seen,
153 }166 }
154 }167 }
@@ -165,23 +178,26 @@ fn serve(conn: quinn::Connection, behaviour: Behaviour, seen: Arc<Mutex<Vec<Requ
165 };178 };
166 seen.lock().unwrap().push(request.clone());179 seen.lock().unwrap().push(request.clone());
167 let response = match behaviour {180 let response = match behaviour {
168- Behaviour::Podcast => Some(Response::Ok {181+ Behaviour::Podcast => Response::Ok {
169 id: request.id.clone(),182 id: request.id.clone(),
170 school: request.school.clone(),183 school: request.school.clone(),
171 payload: podcast_answer(&request),184 payload: podcast_answer(&request),
172- }),185+ },
173- Behaviour::Fail { code, message } => Some(Response::Err {186+ Behaviour::WrongEcho => Response::Ok {
187+ id: request.id.clone(),
188+ school: request.school.clone(),
189+ payload: wrong_echo_answer(),
190+ },
191+ Behaviour::Fail { code, message } => Response::Err {
174 id: request.id.clone(),192 id: request.id.clone(),
175 school: request.school.clone(),193 school: request.school.clone(),
176 code,194 code,
177 message,195 message,
178- }),196+ },
179 };197 };
180- if let Some(response) = response {198+ let _ = write_frame(&mut send, &response).await;
181- let _ = write_frame(&mut send, &response).await;199+ let _ = send.finish();
182- let _ = send.finish();200+ let _ = send.stopped().await;
183- let _ = send.stopped().await;
184- }
185 });201 });
186 }202 }
187 });203 });
@@ -189,36 +205,27 @@ fn serve(conn: quinn::Connection, behaviour: Behaviour, seen: Arc<Mutex<Vec<Requ
189 205
190 /// What the podcast service would answer for this capability.206 /// What the podcast service would answer for this capability.
191 fn podcast_answer(request: &Request) -> Value {207 fn podcast_answer(request: &Request) -> Value {
192- let job_id = request
193- .payload
194- .get("job_id")
195- .cloned()
196- .unwrap_or_else(|| json!(JOB_ID));
197 match request.capability.as_str() {208 match request.capability.as_str() {
198- AI_PODCAST_SUBMIT_CAPABILITY => {209+ // The receipt must echo the backend's own job id — the id every later
199- json!({ "job_id": JOB_ID, "state": "queued", "eta_secs": 2700 })210+ // call names — so the fake echoes the payload it was handed.
200- }211+ AI_PODCAST_SUBMIT_CAPABILITY => json!({
201- AI_PODCAST_STATUS_CAPABILITY => json!({212+ "job_id": request.payload["job_id"],
202- "job_id": job_id,213+ "state": "queued",
203- "state": "running",214+ "eta_secs": ETA_SECS,
204- "stage": "tts",
205- "progress": 0.5,
206- "error_code": null,
207 }),215 }),
208- AI_PODCAST_RESULT_CAPABILITY => json!({216+ AI_PODCAST_CANCEL_CAPABILITY => json!({
209- "job_id": job_id,217+ "job_id": request.payload["job_id"],
210- "audio_id": AUDIO_ID,218+ "cancelled": true,
211- "duration_secs": 12.5,
212- "script_id": "script-1",
213- "audio_ids": [AUDIO_ID],
214- "script_ids": ["script-1"],
215- "format": "duz_okuma",
216 }),219 }),
217- AI_PODCAST_CANCEL_CAPABILITY => json!({ "job_id": job_id, "cancelled": true }),
218 other => panic!("the fake podcast service was asked for `{other}`"),220 other => panic!("the fake podcast service was asked for `{other}`"),
219 }221 }
220 }222 }
221 223
224+/// The receipt of a service that keyed the job by an id it minted itself.
225+fn wrong_echo_answer() -> Value {
226+ json!({ "job_id": "019732e3-7b00-7000-8000-00000000beef", "state": "queued", "eta_secs": 60 })
227+}
228+
222 /// Registration completes asynchronously after the welcome is on the wire, so229 /// Registration completes asynchronously after the welcome is on the wire, so
223 /// tests that assert on the registry wait for it rather than racing it.230 /// tests that assert on the registry wait for it rather than racing it.
224 async fn await_workers(bridge: &AiBridge, expected: usize) {231 async fn await_workers(bridge: &AiBridge, expected: usize) {
@@ -234,9 +241,11 @@ async fn await_workers(bridge: &AiBridge, expected: usize) {
234 );241 );
235 }242 }
236 243
237-/// A registered podcast service offering all four capabilities, the router244+/// A registered podcast service offering the two capabilities a live worker
238-/// wired to its bridge, and a logged-in student's cookie.245+/// needs, the router wired to its bridge, a logged-in student's cookie, and
239-async fn podcast_app() -> (FakeService, Router, String) {246+/// the school's database handle — the fixture every round-trip test starts
247+/// from.
248+async fn podcast_app() -> (FakeService, Router, String, Database) {
240 let bridge = bridge().await;249 let bridge = bridge().await;
241 let service = connect_service(250 let service = connect_service(
242 &bridge,251 &bridge,
@@ -245,39 +254,347 @@ async fn podcast_app() -> (FakeService, Router, String) {
245 )254 )
246 .await;255 .await;
247 await_workers(&bridge, 1).await;256 await_workers(&bridge, 1).await;
248- let (app, _db) = common::app_with_ai(Some(bridge)).await;257+ let (app, db) = common::app_with_ai(Some(bridge)).await;
249 let cookie = common::login(&app, "ali").await;258 let cookie = common::login(&app, "ali").await;
250- (service, app, cookie)259+ (service, app, cookie, db)
251 }260 }
252 261
262+/// A logged-in caller and the school's database, with **no AI service in the
263+/// picture at all**: the reading doors answer from the row, so the lifetime
264+/// rules and the read refusals need no worker — and a dispatch would be
265+/// impossible.
266+async fn app_without_ai() -> (Router, String, Database) {
267+ let (app, db) = common::app_and_db().await;
268+ let cookie = common::login(&app, "ali").await;
269+ (app, cookie, db)
270+}
271+
272+// ------------------------------------------------------------- http doors --
273+
253 /// Submit one job and return the response.274 /// Submit one job and return the response.
254 async fn submit(app: &Router, cookie: &str, body: Value) -> common::Res {275 async fn submit(app: &Router, cookie: &str, body: Value) -> common::Res {
255 common::send(app, "POST", "/podcast/jobs", Some(cookie), Some(body)).await276 common::send(app, "POST", "/podcast/jobs", Some(cookie), Some(body)).await
256 }277 }
257 278
279+/// Submit one job with the standard body (asserting the `202`) and hand back
280+/// the backend-minted id every other door names.
281+async fn submit_job(app: &Router, cookie: &str) -> String {
282+ let res = submit(
283+ app,
284+ cookie,
285+ json!({ "source_id": SOURCE_ID, "format": FORMAT }),
286+ )
287+ .await;
288+ assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);
289+ res.body["job_id"]
290+ .as_str()
291+ .expect("the receipt names the job")
292+ .to_string()
293+}
294+
295+/// One `GET /podcast/jobs/{id}`.
296+async fn status_of(app: &Router, cookie: &str, id: &str) -> common::Res {
297+ common::send(app, "GET", &format!("/podcast/jobs/{id}"), Some(cookie), None).await
298+}
299+
300+/// One `GET /podcast/jobs/{id}/result`.
301+async fn result_of(app: &Router, cookie: &str, id: &str) -> common::Res {
302+ common::send(
303+ app,
304+ "GET",
305+ &format!("/podcast/jobs/{id}/result"),
306+ Some(cookie),
307+ None,
308+ )
309+ .await
310+}
311+
312+/// One `POST /podcast/jobs/{id}/cancel`.
313+async fn cancel_of(app: &Router, cookie: &str, id: &str) -> common::Res {
314+ common::send(
315+ app,
316+ "POST",
317+ &format!("/podcast/jobs/{id}/cancel"),
318+ Some(cookie),
319+ None,
320+ )
321+ .await
322+}
323+
324+/// One `GET /podcast/jobs/{id}/audio`, raw — the body is audio bytes or a JSON
325+/// refusal, never a parsed envelope.
326+async fn audio_of(app: &Router, cookie: &str, id: &str) -> (StatusCode, HeaderMap, Vec<u8>) {
327+ common::send_raw(
328+ app,
329+ "GET",
330+ &format!("/podcast/jobs/{id}/audio"),
331+ Some(cookie),
332+ None,
333+ Vec::new(),
334+ )
335+ .await
336+}
337+
338+// ------------------------------------------------------------ service i/o --
339+
340+/// One `podcast.report` call, exactly as the real service writes it: a
341+/// client-initiated capability frame on the connection it registered with,
342+/// echoing the job's own identity — the backend refuses a report that
343+/// describes a different job.
344+fn report_frame(job_id: &str, user_id: &str, state: &str, stage: &str, progress: f64) -> Value {
345+ json!({
346+ "id": format!("report-{state}"),
347+ "school": DEMO_SLUG,
348+ "capability": "podcast.report",
349+ "payload": {
350+ "job_id": job_id,
351+ "source_id": SOURCE_ID,
352+ "format": FORMAT,
353+ "user_id": user_id,
354+ "state": state,
355+ "stage": stage,
356+ "progress": progress,
357+ "error_code": null,
358+ },
359+ })
360+}
361+
362+/// One `BlobUploadRequest` for `job_id`, declaring the header of the bytes
363+/// that follow it on the same stream.
364+fn upload_frame(job_id: &str, name: &str, content_type: &str, size: usize) -> Value {
365+ json!({
366+ "id": format!("upload-{job_id}"),
367+ "upload": true,
368+ "school": DEMO_SLUG,
369+ "job_id": job_id,
370+ "name": name,
371+ "content_type": content_type,
372+ "size": size,
373+ "duration_secs": DURATION_SECS,
374+ })
375+}
376+
377+/// Send one client-initiated frame and read the one frame the backend answers
378+/// with — the shape every service→backend call rides.
379+async fn capability_call(conn: &quinn::Connection, request: Value) -> Value {
380+ let (mut send, mut recv) = conn.open_bi().await.expect("client-initiated stream");
381+ write_frame(&mut send, &request).await.expect("write the call");
382+ let _ = send.finish();
383+ read_frame::<_, Value>(&mut recv).await.expect("read the answer")
384+}
385+
386+/// One audio upload on a fresh client-initiated stream: the header frame,
387+/// exactly `body.len()` raw bytes, FIN — then the backend's one answer frame.
388+async fn blob_upload(conn: &quinn::Connection, frame: Value, body: &[u8]) -> Value {
389+ let (mut send, mut recv) = conn.open_bi().await.expect("upload stream");
390+ write_frame(&mut send, &frame)
391+ .await
392+ .expect("write the upload frame");
393+ send.write_all(body).await.expect("write the audio bytes");
394+ let _ = send.finish();
395+ read_frame::<_, Value>(&mut recv)
396+ .await
397+ .expect("read the upload answer")
398+}
399+
400+/// Assert one report was stored: the answer's payload echoes the job and says
401+/// `stored` — an unstored report is a refusal, never a quiet success.
402+fn assert_report_stored(answer: &Value, job_id: &str) {
403+ assert_eq!(answer["status"], "ok", "{answer}");
404+ assert_eq!(answer["payload"]["job_id"], job_id);
405+ assert_eq!(answer["payload"]["stored"], true);
406+}
407+
408+/// The flat refusal code out of one capability answer frame.
409+fn refusal_code(answer: &Value) -> String {
410+ assert_eq!(answer["status"], "err", "{answer}");
411+ answer["code"]
412+ .as_str()
413+ .expect("a refusal carries its code")
414+ .to_string()
415+}
416+
417+// ------------------------------------------------------------------- rows --
418+
419+fn uuid_of(key: &str) -> Uuid {
420+ Uuid::parse_str(key).expect("a uuid key")
421+}
422+
423+/// The wall clock in unix milliseconds — the unit every timestamp column here
424+/// stores.
425+fn now_ms() -> i64 {
426+ Timestamp::now().as_millis()
427+}
428+
429+/// How many podcast jobs this user has on the books.
430+async fn rows_for(db: &Database, user: &str) -> i64 {
431+ sqlx::query_scalar("SELECT count(*) FROM podcast_job WHERE user_id = $1")
432+ .bind(uuid_of(user))
433+ .fetch_one(db)
434+ .await
435+ .expect("count the user's jobs")
436+}
437+
438+/// Write one job row by hand. The shapes the reading doors' own lifetime rules
439+/// are about — untouched past the staleness window, aged out of retention —
440+/// are ones no door can mint, so the fixture writes them directly.
441+async fn seed_job(
442+ db: &Database,
443+ job: Uuid,
444+ user: &str,
445+ state: &str,
446+ eta_secs: Option<i64>,
447+ updated_at: i64,
448+) -> Uuid {
449+ sqlx::query(
450+ "INSERT INTO podcast_job (id, user_id, source_id, state, stage, progress, \
451+ eta_secs, created_at, updated_at) \
452+ VALUES ($1, $2, $3, $4, '', 0, $5, $6, $6)",
453+ )
454+ .bind(job)
455+ .bind(uuid_of(user))
456+ .bind(SOURCE_ID)
457+ .bind(state)
458+ .bind(eta_secs)
459+ .bind(updated_at)
460+ .execute(db)
461+ .await
462+ .expect("seed the job row");
463+ job
464+}
465+
466+/// The same, but `done` and naming an artifact: the row shape the audio door
467+/// reads its key and headers from, whether or not the bytes are still on disk.
468+async fn seed_done_job(
469+ db: &Database,
470+ job: Uuid,
471+ user: &str,
472+ key: &str,
473+ bytes: i64,
474+ updated_at: i64,
475+) -> Uuid {
476+ sqlx::query(
477+ "INSERT INTO podcast_job (id, user_id, source_id, state, stage, progress, \
478+ audio_key, audio_name, audio_type, audio_bytes, duration_secs, \
479+ created_at, updated_at) \
480+ VALUES ($1, $2, $3, 'done', '', 1, $4, $5, $6, $7, $8, $9, $9)",
481+ )
482+ .bind(job)
483+ .bind(uuid_of(user))
484+ .bind(SOURCE_ID)
485+ .bind(key)
486+ .bind(AUDIO_NAME)
487+ .bind(AUDIO_TYPE)
488+ .bind(bytes)
489+ .bind(DURATION_SECS)
490+ .bind(updated_at)
491+ .execute(db)
492+ .await
493+ .expect("seed the done row");
494+ job
495+}
496+
497+/// Write `bytes` at `key` under the demo school's blob directory — the layout
498+/// an ingested episode lands in, and the only place the audio door reads.
499+fn write_blob(key: &str, bytes: &[u8]) {
500+ let path = common::blob_dir().join(key);
501+ std::fs::create_dir_all(path.parent().expect("parent dir")).expect("create the blob tree");
502+ std::fs::write(&path, bytes).expect("write the blob");
503+ assert!(path.is_file(), "the fixture blob really landed");
504+}
505+
506+/// Deterministic pseudo-random episode bytes, past one 64 KiB read chunk so a
507+/// passing door proves it streamed the body rather than fitting one write.
508+fn episode_bytes() -> Vec<u8> {
509+ let mut state = 0x2545_F491_4F6C_DD1Du64;
510+ (0..128 * 1024)
511+ .map(|_| {
512+ state ^= state << 13;
513+ state ^= state >> 7;
514+ state ^= state << 17;
515+ state as u8
516+ })
517+ .collect()
518+}
519+
258 // ------------------------------------------------------------ round trips --520 // ------------------------------------------------------------ round trips --
259 521
522+/// The submit door writes the row before it dispatches, and hands the service
523+/// the id it minted — the one handle every later call names. A service keying
524+/// its own record by what it was sent can therefore never disagree with the
525+/// row, and the receipt carries the service's own ETA.
260 #[tokio::test]526 #[tokio::test]
261-async fn a_submit_round_trips_the_source_and_format_to_the_service() {527+async fn a_submit_writes_the_row_and_hands_the_service_its_own_job_id() {
262- let (service, app, cookie) = podcast_app().await;528+ let (service, app, cookie, db) = podcast_app().await;
529+ let user = common::me_id(&app, &cookie).await;
263 530
264 let res = submit(531 let res = submit(
265 &app,532 &app,
266 &cookie,533 &cookie,
267- json!({ "source_id": SOURCE_ID, "format": "duz_okuma" }),534+ json!({ "source_id": SOURCE_ID, "format": FORMAT }),
268 )535 )
269 .await;536 .await;
270 assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);537 assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);
271- assert_eq!(res.body["job_id"], JOB_ID);
272 assert_eq!(res.body["state"], "queued");538 assert_eq!(res.body["state"], "queued");
273- assert_eq!(res.body["eta_secs"], 2700);539+ assert_eq!(res.body["eta_secs"], ETA_SECS);
540+ let job_id = res.body["job_id"]
541+ .as_str()
542+ .expect("the receipt names the job")
543+ .to_string();
274 544
275 let seen = service.seen();545 let seen = service.seen();
276 assert_eq!(seen.len(), 1, "exactly one dispatch");546 assert_eq!(seen.len(), 1, "exactly one dispatch");
277 assert_eq!(seen[0].capability, AI_PODCAST_SUBMIT_CAPABILITY);547 assert_eq!(seen[0].capability, AI_PODCAST_SUBMIT_CAPABILITY);
278 assert_eq!(seen[0].school, DEMO_SLUG, "the school rides the frame");548 assert_eq!(seen[0].school, DEMO_SLUG, "the school rides the frame");
549+ assert_eq!(
550+ seen[0].payload["job_id"], job_id,
551+ "the service was handed the row's own id"
552+ );
279 assert_eq!(seen[0].payload["source_id"], SOURCE_ID);553 assert_eq!(seen[0].payload["source_id"], SOURCE_ID);
280- assert_eq!(seen[0].payload["format"], "duz_okuma");554+ assert_eq!(seen[0].payload["format"], FORMAT);
555+ assert_eq!(seen[0].payload["user_id"], user);
556+
557+ let (state, eta, source): (String, Option<i64>, String) =
558+ sqlx::query_as("SELECT state, eta_secs, source_id FROM podcast_job WHERE id = $1")
559+ .bind(uuid_of(&job_id))
560+ .fetch_one(&db)
561+ .await
562+ .expect("the row is on the books");
563+ assert_eq!(state, "queued");
564+ assert_eq!(eta, Some(ETA_SECS), "the service's estimate landed on the row");
565+ assert_eq!(source, SOURCE_ID);
566+}
567+
568+/// A service that accepts the job under an id of its own has answered about a
569+/// different job: the echo is checked, not trusted, because the backend's id is
570+/// the only handle every later call uses. The refusal is a `502` — the backend
571+/// cannot vouch for an answer it did not understand — and the row is
572+/// tombstoned rather than left claiming `queued` forever.
573+#[tokio::test]
574+async fn a_submit_that_echoes_another_job_id_is_a_bad_gateway() {
575+ let bridge = bridge().await;
576+ let _service =
577+ connect_service(&bridge, hello("podcast", &CAPABILITIES), Behaviour::WrongEcho).await;
578+ await_workers(&bridge, 1).await;
579+ let (app, db) = common::app_with_ai(Some(bridge)).await;
580+ let cookie = common::login(&app, "ali").await;
581+ let user = common::me_id(&app, &cookie).await;
582+
583+ let res = submit(&app, &cookie, json!({ "source_id": SOURCE_ID })).await;
584+ assert_eq!(res.status, StatusCode::BAD_GATEWAY, "{}", res.body);
585+ assert_eq!(res.body["error"], "bad_reply");
586+
587+ let rows: Vec<(String, Option<String>)> =
588+ sqlx::query_as("SELECT state, error_code FROM podcast_job WHERE user_id = $1")
589+ .bind(uuid_of(&user))
590+ .fetch_all(&db)
591+ .await
592+ .expect("read back the tombstone");
593+ assert_eq!(
594+ rows,
595+ vec![("failed".to_string(), Some("bad_reply".to_string()))],
596+ "exactly one row, and it records why"
597+ );
281 }598 }
282 599
283 /// The format is optional and the service applies its own default: an omitted600 /// 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() {
285 /// distinguish "absent" from "empty".602 /// distinguish "absent" from "empty".
286 #[tokio::test]603 #[tokio::test]
287 async fn an_omitted_format_is_not_sent_at_all() {604 async fn an_omitted_format_is_not_sent_at_all() {
288- let (service, app, cookie) = podcast_app().await;605+ let (service, app, cookie, _db) = podcast_app().await;
289 606
290 let res = submit(&app, &cookie, json!({ "source_id": SOURCE_ID })).await;607 let res = submit(&app, &cookie, json!({ "source_id": SOURCE_ID })).await;
291 assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);608 assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);
@@ -299,375 +616,513 @@ async fn an_omitted_format_is_not_sent_at_all() {
299 );616 );
300 }617 }
301 618
302-/// A blank source id is refused here, before the bridge: the service would619+/// A blank source id is refused here, before the bridge and before the row:
303-/// refuse it too, and a round trip to learn that is a round trip wasted.620+/// the service would refuse it too, and a round trip to learn that is a round
621+/// trip wasted.
304 #[tokio::test]622 #[tokio::test]
305-async fn a_blank_source_id_is_refused_before_dispatch() {623+async fn a_blank_source_id_is_refused_before_anything_is_written() {
306- let (service, app, cookie) = podcast_app().await;624+ let (service, app, cookie, db) = podcast_app().await;
625+ let user = common::me_id(&app, &cookie).await;
307 626
308 let res = submit(&app, &cookie, json!({ "source_id": " " })).await;627 let res = submit(&app, &cookie, json!({ "source_id": " " })).await;
309 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);628 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
310 assert!(service.seen().is_empty(), "nothing reaches the service");629 assert!(service.seen().is_empty(), "nothing reaches the service");
630+ assert_eq!(rows_for(&db, &user).await, 0, "and no row is written");
311 }631 }
312 632
633+/// A report lands on the row, and the reading doors answer from it: the
634+/// service's `seen` log must not grow, because `podcast.status` and
635+/// `podcast.result` are not calls the backend makes any more — a relayed read
636+/// would show up here as a second request.
313 #[tokio::test]637 #[tokio::test]
314-async fn a_status_read_round_trips_the_job_id() {638+async fn a_running_report_lands_on_the_row_and_the_reads_stay_off_the_service() {
315- let (service, app, cookie) = podcast_app().await;639+ let (service, app, cookie, db) = podcast_app().await;
640+ let user = common::me_id(&app, &cookie).await;
641+ let job_id = submit_job(&app, &cookie).await;
642+
643+ assert_report_stored(
644+ &capability_call(
645+ &service.conn,
646+ report_frame(&job_id, &user, "running", "tts", 0.5),
647+ )
648+ .await,
649+ &job_id,
650+ );
316 651
317- let res = common::send(652+ let res = status_of(&app, &cookie, &job_id).await;
318- &app,
319- "GET",
320- &format!("/podcast/jobs/{JOB_ID}"),
321- Some(&cookie),
322- None,
323- )
324- .await;
325 assert_eq!(res.status, StatusCode::OK, "{}", res.body);653 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
326- assert_eq!(res.body["job_id"], JOB_ID);654+ assert_eq!(res.body["job_id"], job_id);
327 assert_eq!(res.body["state"], "running");655 assert_eq!(res.body["state"], "running");
328 assert_eq!(res.body["stage"], "tts");656 assert_eq!(res.body["stage"], "tts");
329 assert_eq!(res.body["progress"], 0.5);657 assert_eq!(res.body["progress"], 0.5);
330 assert!(res.body["error_code"].is_null());658 assert!(res.body["error_code"].is_null());
331 659
332- let seen = service.seen();660+ let state: String = sqlx::query_scalar("SELECT state FROM podcast_job WHERE id = $1")
333- assert_eq!(seen.len(), 1);661+ .bind(uuid_of(&job_id))
334- assert_eq!(seen[0].capability, AI_PODCAST_STATUS_CAPABILITY);662+ .fetch_one(&db)
335- assert_eq!(seen[0].payload["job_id"], JOB_ID);663+ .await
664+ .expect("the report really landed");
665+ assert_eq!(state, "running");
666+ assert_eq!(
667+ service.seen().len(),
668+ 1,
669+ "the reads answered from the row, not the service"
670+ );
336 }671 }
337 672
673+/// The whole pipeline, end to end: submit, a running report, the finished mp3
674+/// uploaded as raw bytes, the done report, then the result door naming the
675+/// artifact and the audio door streaming the very bytes that were uploaded —
676+/// with the content type the row recorded.
338 #[tokio::test]677 #[tokio::test]
339-async fn a_result_read_round_trips_the_artifacts() {678+async fn a_finished_job_serves_the_uploaded_bytes() {
340- let (service, app, cookie) = podcast_app().await;679+ let (service, app, cookie, _db) = podcast_app().await;
680+ let user = common::me_id(&app, &cookie).await;
681+ let job_id = submit_job(&app, &cookie).await;
682+
683+ assert_report_stored(
684+ &capability_call(
685+ &service.conn,
686+ report_frame(&job_id, &user, "running", "tts", 0.25),
687+ )
688+ .await,
689+ &job_id,
690+ );
341 691
342- let res = common::send(692+ let bytes = episode_bytes();
343- &app,693+ let answer = blob_upload(
344- "GET",694+ &service.conn,
345- &format!("/podcast/jobs/{JOB_ID}/result"),695+ upload_frame(&job_id, AUDIO_NAME, AUDIO_TYPE, bytes.len()),
346- Some(&cookie),696+ &bytes,
347- None,
348 )697 )
349 .await;698 .await;
699+ assert_eq!(answer["status"], "ok", "{answer}");
700+ assert_eq!(answer["key"], format!("podcast/{job_id}.mp3"));
701+ assert_eq!(answer["size"], bytes.len() as u64);
702+
703+ assert_report_stored(
704+ &capability_call(
705+ &service.conn,
706+ report_frame(&job_id, &user, "done", "", 1.0),
707+ )
708+ .await,
709+ &job_id,
710+ );
711+
712+ let res = result_of(&app, &cookie, &job_id).await;
350 assert_eq!(res.status, StatusCode::OK, "{}", res.body);713 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
351- assert_eq!(res.body["job_id"], JOB_ID);714+ assert_eq!(res.body["job_id"], job_id);
352- assert_eq!(res.body["audio_id"], AUDIO_ID);715+ assert_eq!(res.body["audio_id"], format!("podcast/{job_id}.mp3"));
353- assert_eq!(res.body["duration_secs"], 12.5);716+ assert_eq!(res.body["duration_secs"], DURATION_SECS);
354- assert_eq!(res.body["script_id"], "script-1");717+ assert_eq!(res.body["format"], FORMAT);
355- assert_eq!(res.body["audio_ids"], json!([AUDIO_ID]));718+
356- assert_eq!(res.body["script_ids"], json!(["script-1"]));719+ let (status, headers, body) = audio_of(&app, &cookie, &job_id).await;
357- assert_eq!(res.body["format"], "duz_okuma");720+ assert_eq!(status, StatusCode::OK, "{:?}", String::from_utf8_lossy(&body));
721+ assert_eq!(headers["content-type"], AUDIO_TYPE, "the row's own type");
722+ assert_eq!(headers["x-content-type-options"], "nosniff");
723+ assert_eq!(headers["cache-control"], "private, no-store");
724+ assert_eq!(body, bytes, "the door streams the uploaded bytes, unchanged");
358 725
359- let seen = service.seen();726+ assert_eq!(
360- assert_eq!(seen.len(), 1);727+ service.seen().len(),
361- assert_eq!(seen[0].capability, AI_PODCAST_RESULT_CAPABILITY);728+ 1,
362- assert_eq!(seen[0].payload["job_id"], JOB_ID);729+ "the upload and the reports are the service's own calls, not dispatches"
730+ );
363 }731 }
364 732
733+/// Cancelling a live job reaches the worker that owns the queue and stamps the
734+/// verdict on the row — the row then records that the job stopped, so a poll
735+/// after the service is gone still reads the truth.
365 #[tokio::test]736 #[tokio::test]
366-async fn a_cancel_round_trips_the_verdict() {737+async fn a_cancel_of_a_live_job_stops_it() {
367- let (service, app, cookie) = podcast_app().await;738+ let (service, app, cookie, db) = podcast_app().await;
739+ let job_id = submit_job(&app, &cookie).await;
368 740
369- let res = common::send(741+ let res = cancel_of(&app, &cookie, &job_id).await;
370- &app,
371- "POST",
372- &format!("/podcast/jobs/{JOB_ID}/cancel"),
373- Some(&cookie),
374- None,
375- )
376- .await;
377 assert_eq!(res.status, StatusCode::OK, "{}", res.body);742 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
378- assert_eq!(res.body["job_id"], JOB_ID);743+ assert_eq!(res.body["job_id"], job_id);
379 assert_eq!(res.body["cancelled"], true);744 assert_eq!(res.body["cancelled"], true);
380 745
381 let seen = service.seen();746 let seen = service.seen();
382- assert_eq!(seen.len(), 1);747+ assert_eq!(seen.len(), 2, "the cancel rode a second dispatch");
383- assert_eq!(seen[0].capability, AI_PODCAST_CANCEL_CAPABILITY);748+ assert_eq!(seen[1].capability, AI_PODCAST_CANCEL_CAPABILITY);
384- assert_eq!(seen[0].payload["job_id"], JOB_ID);749+ assert_eq!(seen[1].payload["job_id"], job_id);
750+
751+ let state: String = sqlx::query_scalar("SELECT state FROM podcast_job WHERE id = $1")
752+ .bind(uuid_of(&job_id))
753+ .fetch_one(&db)
754+ .await
755+ .expect("the row records the verdict");
756+ assert_eq!(state, "cancelled");
757+}
758+
759+/// A job that already stopped is not an error to cancel: the verdict is
760+/// `false` — this call cancelled nothing — and no worker is needed at all,
761+/// because the row is terminal and the door answers before it looks for one.
762+#[tokio::test]
763+async fn a_cancel_of_a_terminal_job_answers_false_without_the_service() {
764+ let (service, app, cookie, db) = podcast_app().await;
765+ let user = common::me_id(&app, &cookie).await;
766+ let job_id = submit_job(&app, &cookie).await;
767+ assert_report_stored(
768+ &capability_call(
769+ &service.conn,
770+ report_frame(&job_id, &user, "failed", "", 0.0),
771+ )
772+ .await,
773+ &job_id,
774+ );
775+
776+ // The pipeline is gone by the time the caller gives up on it.
777+ drop(service);
778+
779+ let res = cancel_of(&app, &cookie, &job_id).await;
780+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
781+ assert_eq!(res.body["job_id"], job_id);
782+ assert_eq!(res.body["cancelled"], false);
783+
784+ let state: String = sqlx::query_scalar("SELECT state FROM podcast_job WHERE id = $1")
785+ .bind(uuid_of(&job_id))
786+ .fetch_one(&db)
787+ .await
788+ .expect("the row is still there");
789+ assert_eq!(state, "failed", "the verdict never rewrites a terminal row");
385 }790 }
386 791
387 // --------------------------------------------------------------- refusals --792 // --------------------------------------------------------------- refusals --
388 793
389-/// With a bridge but no worker, every door answers the shared AI-unavailable794+/// A submit that reaches no service writes nothing: the `503` is the whole
390-/// `503` — never a `500`, and never a dispatch into nothing. The audio door is795+/// answer, so a poll can never find a job nobody will ever work on. Both
391-/// not in this list on purpose: it reads a local file and needs no service.796+/// shapes of "nobody to ask" answer that `503` with their own message — a
797+/// configured-but-unconnected bridge, and a deployment with no bridge at all.
392 #[tokio::test]798 #[tokio::test]
393-async fn every_dispatching_door_is_503_with_no_worker_registered() {799+async fn a_submit_that_reaches_no_service_is_503_and_writes_no_row() {
394- let bridge = bridge().await;800+ let (app, db) = common::app_with_ai(Some(bridge().await)).await;
395- let (app, _db) = common::app_with_ai(Some(bridge)).await;
396 let cookie = common::login(&app, "ali").await;801 let cookie = common::login(&app, "ali").await;
802+ let user = common::me_id(&app, &cookie).await;
803+ let res = submit(&app, &cookie, json!({ "source_id": SOURCE_ID })).await;
804+ assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body);
805+ assert_eq!(res.body["error"], "no AI service is connected right now");
806+ assert_eq!(rows_for(&db, &user).await, 0, "no worker, no row");
397 807
398- let doors = [808+ // The deployment never set `AI_QUIC_ADDR`: there is no bridge at all.
399- ("POST", "/podcast/jobs".to_string(), true),809+ let (app, db) = common::app_with_ai(None).await;
400- ("GET", format!("/podcast/jobs/{JOB_ID}"), false),810+ let cookie = common::login(&app, "ali").await;
401- ("GET", format!("/podcast/jobs/{JOB_ID}/result"), false),811+ let user = common::me_id(&app, &cookie).await;
402- ("POST", format!("/podcast/jobs/{JOB_ID}/cancel"), false),812+ let res = submit(&app, &cookie, json!({ "source_id": SOURCE_ID })).await;
403- ];813+ assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body);
404- for (method, uri, body) in doors {814+ assert_eq!(
405- let res = common::send(815+ res.body["error"],
406- &app,816+ "the AI service is not enabled on this deployment"
407- method,817+ );
408- &uri,818+ assert_eq!(rows_for(&db, &user).await, 0);
409- Some(&cookie),
410- body.then(|| json!({ "source_id": SOURCE_ID })),
411- )
412- .await;
413- assert_eq!(
414- res.status,
415- StatusCode::SERVICE_UNAVAILABLE,
416- "{method} {uri}: {}",
417- res.body
418- );
419- assert_eq!(res.body["error"], "no AI service is connected right now");
420- }
421 }819 }
422 820
423-/// The same doors with no bridge at all (the deployment never set821+/// A service that refuses the job — at capacity, say — leaves the row as the
424-/// `AI_QUIC_ADDR`): still a `503`, with the other message.822+/// record of that: exactly one row, `failed` with the service's own code, and
823+/// the refusal reaches the caller with its own status.
425 #[tokio::test]824 #[tokio::test]
426-async fn every_dispatching_door_is_503_when_the_bridge_is_off() {825+async fn a_refusing_service_tombstones_the_row() {
427- let (app, _db) = common::app_with_ai(None).await;826+ let bridge = bridge().await;
827+ let _service = connect_service(
828+ &bridge,
829+ hello("podcast", &CAPABILITIES),
830+ Behaviour::Fail {
831+ code: "busy".to_string(),
832+ message: "the queue is at capacity".to_string(),
833+ },
834+ )
835+ .await;
836+ await_workers(&bridge, 1).await;
837+ let (app, db) = common::app_with_ai(Some(bridge)).await;
428 let cookie = common::login(&app, "ali").await;838 let cookie = common::login(&app, "ali").await;
839+ let user = common::me_id(&app, &cookie).await;
429 840
430 let res = submit(&app, &cookie, json!({ "source_id": SOURCE_ID })).await;841 let res = submit(&app, &cookie, json!({ "source_id": SOURCE_ID })).await;
431 assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body);842 assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body);
843+ assert_eq!(res.body["error"], "busy");
844+
845+ let rows: Vec<(String, Option<String>)> =
846+ sqlx::query_as("SELECT state, error_code FROM podcast_job WHERE user_id = $1")
847+ .bind(uuid_of(&user))
848+ .fetch_all(&db)
849+ .await
850+ .expect("read back the tombstone");
432 assert_eq!(851 assert_eq!(
433- res.body["error"],852+ rows,
434- "the AI service is not enabled on this deployment"853+ vec![("failed".to_string(), Some("busy".to_string()))],
854+ "exactly one row, and it records the refusal"
435 );855 );
436 }856 }
437 857
438-/// The service's own refusal code decides the HTTP status, so a client can858+/// A foreign job id reads as absent on every door — the same `404` an id that
439-/// branch the same way it does on the bridge: `busy` is the service at859+/// never existed earns, so the answer leaks nothing about somebody else's job.
440-/// capacity (transient, `503`), `not_found` is a job it never had (`404`), and860+/// The cancel is the sharp one: it must not reach the service on a foreign id
441-/// `not_ready` is a job that has not finished (`409`).861+/// either.
442 #[tokio::test]862 #[tokio::test]
443-async fn a_service_refusal_keeps_its_code_and_status() {863+async fn another_users_job_reads_as_absent() {
444- let cases = [864+ let (service, app, ali, _db) = podcast_app().await;
445- ("busy", StatusCode::SERVICE_UNAVAILABLE),865+ let job_id = submit_job(&app, &ali).await;
446- ("not_found", StatusCode::NOT_FOUND),866+ let seen_before = service.seen().len();
447- ("not_ready", StatusCode::CONFLICT),867+
868+ let ayse = common::login(&app, "ayse").await;
869+ let doors = [
870+ ("GET", format!("/podcast/jobs/{job_id}")),
871+ ("GET", format!("/podcast/jobs/{job_id}/result")),
872+ ("GET", format!("/podcast/jobs/{job_id}/audio")),
873+ ("POST", format!("/podcast/jobs/{job_id}/cancel")),
448 ];874 ];
449- for (code, expected) in cases {875+ for (method, uri) in doors {
450- let bridge = bridge().await;876+ let res = common::send(&app, method, &uri, Some(&ayse), None).await;
451- let _service = connect_service(877+ assert_eq!(res.status, StatusCode::NOT_FOUND, "{method} {uri}: {}", res.body);
452- &bridge,878+ assert_eq!(res.body["error"], "not found");
453- hello("podcast", &CAPABILITIES),
454- Behaviour::Fail {
455- code: code.to_string(),
456- message: format!("the service refused with {code}"),
457- },
458- )
459- .await;
460- await_workers(&bridge, 1).await;
461- let (app, _db) = common::app_with_ai(Some(bridge)).await;
462- let cookie = common::login(&app, "ali").await;
463-
464- let res = common::send(
465- &app,
466- "GET",
467- &format!("/podcast/jobs/{JOB_ID}"),
468- Some(&cookie),
469- None,
470- )
471- .await;
472- assert_eq!(res.status, expected, "{code}: {}", res.body);
473- assert_eq!(res.body["error"], code);
474 }879 }
880+ assert_eq!(
881+ service.seen().len(),
882+ seen_before,
883+ "nothing about a foreign job was dispatched"
884+ );
475 }885 }
476 886
477-/// The nest sits behind the school's `chatbot` module — the AI package's only887+/// A terminal job past its retention window is gone for good: `410`, not the
478-/// module — exactly like `/chatbot` and `/rag`: with the module off the whole888+/// `404` of a job that never existed — the row is still there, but nothing
479-/// URL space answers the disabled refusal, never a handler.889+/// about it is served any more.
480 #[tokio::test]890 #[tokio::test]
481-async fn a_school_without_the_chatbot_module_has_no_podcast_nest() {891+async fn an_expired_job_reads_as_gone() {
482- let bridge = bridge().await;892+ let (app, cookie, db) = app_without_ai().await;
483- let (app, _db, tenants) = common::app_with_ai_tenants(Some(bridge)).await;893+ let user = common::me_id(&app, &cookie).await;
484- let cookie = common::login(&app, "ali").await;894+ let job = Uuid::now_v7();
895+ let key = format!("podcast/{job}.mp3");
896+ // Terminal, with its artifact named (the schema's `done` CHECK), and one
897+ // minute past the retention window.
898+ let aged = now_ms() - (PODCAST_JOB_RETENTION_SECS + 60) * 1_000;
899+ seed_done_job(&db, job, &user, &key, 41, aged).await;
900+
901+ let res = status_of(&app, &cookie, &job.to_string()).await;
902+ assert_eq!(res.status, StatusCode::GONE, "{}", res.body);
903+ assert_eq!(res.body["error"], "this podcast job has expired");
904+}
485 905
486- let mut modules = ModuleSet::all();906+/// A job nobody has updated inside its own ETA-scaled window is presented as
487- modules.remove(Module::Chatbot);907+/// `failed`/`interrupted` — and the projection is read-side only: the row the
488- modules.validate().expect("the narrowed set is satisfiable");908+/// database holds still says `running`, so the service's next report (or its
489- tenants909+/// own sweep) is what actually repairs it.
490- .set_modules(&demo(), &modules)910+#[tokio::test]
491- .await911+async fn a_stale_job_reads_as_interrupted_but_the_row_is_untouched() {
492- .expect("narrow the demo school");912+ let (app, cookie, db) = app_without_ai().await;
913+ let user = common::me_id(&app, &cookie).await;
914+ let job = Uuid::now_v7();
915+ // Past the staleness floor (the window a small ETA resolves to), far
916+ // inside the retention window.
917+ let aged = now_ms() - (PODCAST_JOB_STALE_FLOOR_SECS + 100) * 1_000;
918+ seed_job(&db, job, &user, "running", Some(5), aged).await;
919+
920+ let res = status_of(&app, &cookie, &job.to_string()).await;
921+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
922+ assert_eq!(res.body["state"], "failed");
923+ assert_eq!(res.body["error_code"], "interrupted");
493 924
494- let res = common::send(925+ let stored: String = sqlx::query_scalar("SELECT state FROM podcast_job WHERE id = $1")
495- &app,926+ .bind(job)
496- "GET",927+ .fetch_one(&db)
497- &format!("/podcast/jobs/{JOB_ID}"),928+ .await
498- Some(&cookie),929+ .expect("the row is still there");
499- None,930+ assert_eq!(stored, "running", "the projection wrote nothing");
500- )
501- .await;
502- assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
503- assert_eq!(res.body["module"], "chatbot");
504 }931 }
505 932
506-/// Authentication is the whole gate for the dispatching doors: no cookie is a933+/// Neither the result nor the bytes exist before the job is done: both reading
507-/// `401`, not a dispatch under somebody else's name.934+/// doors answer `409` with `not_ready`, so a client branches on the code
935+/// instead of parsing the sentence.
508 #[tokio::test]936 #[tokio::test]
509-async fn the_dispatching_doors_require_a_session() {937+async fn the_result_and_audio_doors_are_not_ready_before_done() {
510- let (service, app, _cookie) = podcast_app().await;938+ let (service, app, cookie, _db) = podcast_app().await;
939+ let user = common::me_id(&app, &cookie).await;
940+ let job_id = submit_job(&app, &cookie).await;
941+ assert_report_stored(
942+ &capability_call(
943+ &service.conn,
944+ report_frame(&job_id, &user, "running", "tts", 0.5),
945+ )
946+ .await,
947+ &job_id,
948+ );
511 949
512- let res = common::send(950+ let res = result_of(&app, &cookie, &job_id).await;
513- &app,951+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
514- "POST",952+ assert_eq!(res.body["code"], "not_ready");
515- "/podcast/jobs",953+
516- None,954+ let (status, _, body) = audio_of(&app, &cookie, &job_id).await;
517- Some(json!({ "source_id": SOURCE_ID })),955+ assert_eq!(
518- )956+ status,
519- .await;957+ StatusCode::CONFLICT,
520- assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{}", res.body);958+ "{:?}",
521- assert!(service.seen().is_empty(), "an anonymous call dispatches nothing");959+ String::from_utf8_lossy(&body)
960+ );
961+ let refusal: Value = serde_json::from_slice(&body).expect("a JSON refusal");
962+ assert_eq!(refusal["code"], "not_ready");
522 }963 }
523 964
524-// -------------------------------------------------------------- audio door --965+/// A `done` report that arrives before its audio was uploaded is refused
966+/// `audio_missing`: the row must never claim a finished episode whose bytes are
967+/// not there (the schema's own CHECK backstops the same rule), and the row
968+/// stays `running` so the service can upload and report again.
969+#[tokio::test]
970+async fn a_done_report_before_the_upload_is_refused() {
971+ let (service, app, cookie, db) = podcast_app().await;
972+ let user = common::me_id(&app, &cookie).await;
973+ let job_id = submit_job(&app, &cookie).await;
974+ assert_report_stored(
975+ &capability_call(
976+ &service.conn,
977+ report_frame(&job_id, &user, "running", "tts", 0.5),
978+ )
979+ .await,
980+ &job_id,
981+ );
525 982
526-/// Write `bytes` at `relative` under the demo school's blob directory and983+ let answer = capability_call(
527-/// return the absolute path it landed at.984+ &service.conn,
528-fn school_file(relative: &str, bytes: &[u8]) -> std::path::PathBuf {985+ report_frame(&job_id, &user, "done", "", 1.0),
529- let path = common::blob_dir().join(relative);986+ )
530- std::fs::create_dir_all(path.parent().expect("parent dir")).expect("create the directory tree");987+ .await;
531- std::fs::write(&path, bytes).expect("write the file");988+ assert_eq!(refusal_code(&answer), "audio_missing");
532- path
533-}
534 989
535-/// One raw `GET /podcast/audio?path=…`.990+ let state: String = sqlx::query_scalar("SELECT state FROM podcast_job WHERE id = $1")
536-async fn fetch_audio(991+ .bind(uuid_of(&job_id))
537- app: &Router,992+ .fetch_one(&db)
538- cookie: Option<&str>,993+ .await
539- path: &str,994+ .expect("the row is still there");
540-) -> (StatusCode, axum::http::HeaderMap, Vec<u8>) {995+ assert_eq!(state, "running", "the refusal wrote nothing");
541- let uri = format!("/podcast/audio?path={path}");
542- common::send_raw(app, "GET", &uri, cookie, None, Vec::new()).await
543 }996 }
544 997
545-/// The happy path: a file under the school's own directory streams back with998+/// A `done` row whose blob is gone from the host answers `409 audio_missing`:
546-/// its bytes and an audio content type.999+/// the record is intact and the bytes are not — a state a client can report,
1000+/// unlike a generic `500`. The result door still names the artifact, so the
1001+/// row itself is provably fine and only the file is missing.
547 #[tokio::test]1002 #[tokio::test]
548-async fn the_audio_door_serves_a_file_under_the_schools_directory() {1003+async fn the_audio_door_reports_a_missing_blob() {
549- let (app, _db) = common::app_and_db().await;1004+ let (app, cookie, db) = app_without_ai().await;
550- let cookie = common::login(&app, "ali").await;1005+ let user = common::me_id(&app, &cookie).await;
551- let bytes = b"ID3\x03\x00\x00\x00fake-mp3-bytes".to_vec();1006+ let job = Uuid::now_v7();
552- school_file("podcast/serve/ok.mp3", &bytes);1007+ let key = format!("podcast/{job}.mp3");
1008+ seed_done_job(&db, job, &user, &key, 41, now_ms()).await;
1009+ assert!(
1010+ !common::blob_dir().join(&key).exists(),
1011+ "the blob really is gone"
1012+ );
553 1013
554- let (status, headers, body) = fetch_audio(&app, Some(&cookie), "podcast/serve/ok.mp3").await;1014+ let res = result_of(&app, &cookie, &job.to_string()).await;
555- assert_eq!(status, StatusCode::OK);1015+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
556- assert_eq!(headers["content-type"], "audio/mpeg");1016+ assert_eq!(res.body["audio_id"], key);
557- assert_eq!(headers["x-content-type-options"], "nosniff");1017+
558- assert_eq!(headers["cache-control"], "private, no-store");1018+ let (status, _, body) = audio_of(&app, &cookie, &job.to_string()).await;
559- assert_eq!(body, bytes, "the bytes are the file's, unchanged");1019+ assert_eq!(
1020+ status,
1021+ StatusCode::CONFLICT,
1022+ "{:?}",
1023+ String::from_utf8_lossy(&body)
1024+ );
1025+ let refusal: Value = serde_json::from_slice(&body).expect("a JSON refusal");
1026+ assert_eq!(refusal["code"], "audio_missing");
560 }1027 }
561 1028
562-/// Without a session the door is a `401` — and the very same path serves `200`1029+/// The reading doors need no AI service at all: a finished job's row and its
563-/// with one, so the refusal is authorization and not a missing file.1030+/// blob are served with no bridge configured — which is the whole reason the
1031+/// row exists (a restarted service, or a wiped service volume, costs nothing
1032+/// but the liveness the row's own projection already covers).
564 #[tokio::test]1033 #[tokio::test]
565-async fn the_audio_door_refuses_an_unauthenticated_caller() {1034+async fn the_reading_doors_need_no_service() {
566- let (app, _db) = common::app_and_db().await;1035+ let (app, cookie, db) = app_without_ai().await;
567- let cookie = common::login(&app, "ali").await;1036+ let user = common::me_id(&app, &cookie).await;
568- let bytes = b"authorized-only".to_vec();1037+ let job = Uuid::now_v7();
569- school_file("podcast/auth/only.mp3", &bytes);1038+ let key = format!("podcast/{job}.mp3");
1039+ let bytes = episode_bytes();
1040+ write_blob(&key, &bytes);
1041+ seed_done_job(&db, job, &user, &key, bytes.len() as i64, now_ms()).await;
1042+
1043+ let res = status_of(&app, &cookie, &job.to_string()).await;
1044+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1045+ assert_eq!(res.body["state"], "done");
570 1046
571- let (anonymous, _, _) = fetch_audio(&app, None, "podcast/auth/only.mp3").await;1047+ let res = result_of(&app, &cookie, &job.to_string()).await;
572- assert_eq!(anonymous, StatusCode::UNAUTHORIZED);1048+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1049+ assert_eq!(res.body["audio_id"], key);
573 1050
574- let (authorized, _, body) = fetch_audio(&app, Some(&cookie), "podcast/auth/only.mp3").await;1051+ let (status, headers, body) = audio_of(&app, &cookie, &job.to_string()).await;
575- assert_eq!(authorized, StatusCode::OK);1052+ assert_eq!(status, StatusCode::OK);
1053+ assert_eq!(headers["content-type"], AUDIO_TYPE);
576 assert_eq!(body, bytes);1054 assert_eq!(body, bytes);
577 }1055 }
578 1056
579-/// A `..` segment is refused even though the file it names exists and the file1057+/// The old `GET /podcast/audio?path=…` door is gone with the caller-chosen path
580-/// *inside* the school's directory is served — the refusal is the shape check,1058+/// it resolved: it could not be owner-scoped, so the whole route is a `404` —
581-/// not a missing target.1059+/// the per-job door is the only audio door, and it streams what the school's
582-#[tokio::test]1060+/// own row names. The fixture proves the file exists, so the answer is the
583-async fn the_audio_door_refuses_a_dotdot_segment_to_an_existing_file() {1061+/// missing route, not a missing target.
584- let (app, _db) = common::app_and_db().await;
585- let cookie = common::login(&app, "ali").await;
586- let inside = b"inside the school".to_vec();
587- let outside = b"outside the school".to_vec();
588- school_file("podcast/traversal/inside.mp3", &inside);
589- // What `../` would reach: the deployment-wide files root, one level above
590- // the school's own directory.
591- let escaped = common::files_dir().join("traversal-outside.mp3");
592- std::fs::write(&escaped, &outside).expect("write the outside file");
593- assert!(escaped.is_file(), "the traversal target really exists");
594-
595- let (served, _, body) = fetch_audio(&app, Some(&cookie), "podcast/traversal/inside.mp3").await;
596- assert_eq!(served, StatusCode::OK);
597- assert_eq!(body, inside);
598-
599- let (refused, _, body) =
600- fetch_audio(&app, Some(&cookie), "podcast/traversal/../../traversal-outside.mp3").await;
601- assert_eq!(refused, StatusCode::BAD_REQUEST, "{:?}", String::from_utf8_lossy(&body));
602- assert_ne!(body, outside, "the escaped file's bytes never came back");
603-}
604-
605-/// An absolute path is refused even though the file it names exists — and a
606-/// naive `root.join(path)` would have *served* it, since joining an absolute
607-/// path replaces the base.
608 #[tokio::test]1062 #[tokio::test]
609-async fn the_audio_door_refuses_an_absolute_path_to_an_existing_file() {1063+async fn the_old_path_audio_door_is_gone() {
610- let (app, _db) = common::app_and_db().await;1064+ let (app, cookie, _db) = app_without_ai().await;
611- let cookie = common::login(&app, "ali").await;1065+ write_blob("podcast/escape/kept.mp3", b"bytes the old door would have served");
612- let outside = common::files_dir().join("absolute-outside.mp3");
613- std::fs::write(&outside, b"not for the audio door").expect("write the outside file");
614 1066
615- let (status, _, body) = fetch_audio(1067+ let res = common::send(
616 &app,1068 &app,
1069+ "GET",
1070+ "/podcast/audio?path=podcast/escape/kept.mp3",
617 Some(&cookie),1071 Some(&cookie),
618- outside.to_str().expect("a UTF-8 temp path"),1072+ None,
619 )1073 )
620 .await;1074 .await;
621- assert_eq!(status, StatusCode::BAD_REQUEST, "{:?}", String::from_utf8_lossy(&body));1075+ assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);
622- assert_ne!(body, b"not for the audio door");
623 }1076 }
624 1077
625-/// A symlink inside the school's directory is refused when it resolves out of1078+/// Authentication is the whole gate on every door: no cookie is a `401`, not a
626-/// it — the escape a plain "does the path start with the root" prefix check1079+/// handler — and not a dispatch under somebody else's name either.
627-/// would miss, since the link itself sits inside the root.
628-#[tokio::test]
629-async fn the_audio_door_refuses_a_symlink_that_escapes_the_school() {
630- let (app, _db) = common::app_and_db().await;
631- let cookie = common::login(&app, "ali").await;
632- let target = common::files_dir().join("symlink-outside.mp3");
633- std::fs::write(&target, b"reached through a link").expect("write the target");
634- let link = common::blob_dir().join("podcast/symlink/escape.mp3");
635- std::fs::create_dir_all(link.parent().expect("parent dir")).expect("create the directory tree");
636- let _ = std::fs::remove_file(&link);
637- std::os::unix::fs::symlink(&target, &link).expect("create the symlink");
638- assert!(target.is_file(), "the link's target really exists");
639-
640- let (status, _, body) = fetch_audio(&app, Some(&cookie), "podcast/symlink/escape.mp3").await;
641- assert_eq!(status, StatusCode::BAD_REQUEST, "{:?}", String::from_utf8_lossy(&body));
642- assert_ne!(body, b"reached through a link");
643-}
644-
645-/// Another school's episode is invisible even when the caller knows its exact
646-/// path: the demo caller's request resolves under the *demo* directory, where
647-/// that path does not exist — though the file itself does, one school over.
648 #[tokio::test]1080 #[tokio::test]
649-async fn the_audio_door_never_reaches_another_schools_file() {1081+async fn every_door_requires_a_session() {
650- let (app, _db) = common::app_and_db().await;1082+ let (service, app, _cookie, _db) = podcast_app().await;
651- let cookie = common::login(&app, "ali").await;1083+ let id = common::GHOST_ID;
652- let other = common::files_dir().join("baska-okul/podcast/ses/episode.mp3");
653- std::fs::create_dir_all(other.parent().expect("parent dir")).expect("create the directory tree");
654- std::fs::write(&other, b"the other school's episode").expect("write the file");
655- assert!(other.is_file());
656 1084
657- let (status, _, _) = fetch_audio(&app, Some(&cookie), "podcast/ses/episode.mp3").await;1085+ let doors = [
658- assert_eq!(status, StatusCode::NOT_FOUND);1086+ ("POST", "/podcast/jobs".to_string(), Some(json!({ "source_id": SOURCE_ID }))),
1087+ ("GET", format!("/podcast/jobs/{id}"), None),
1088+ ("GET", format!("/podcast/jobs/{id}/result"), None),
1089+ ("GET", format!("/podcast/jobs/{id}/audio"), None),
1090+ ("POST", format!("/podcast/jobs/{id}/cancel"), None),
1091+ ];
1092+ for (method, uri, body) in doors {
1093+ let res = common::send(&app, method, &uri, None, body).await;
1094+ assert_eq!(
1095+ res.status,
1096+ StatusCode::UNAUTHORIZED,
1097+ "{method} {uri}: {}",
1098+ res.body
1099+ );
1100+ assert_eq!(res.body["error"], "unauthorized");
1101+ }
1102+ assert!(
1103+ service.seen().is_empty(),
1104+ "an anonymous call dispatches nothing"
1105+ );
659 }1106 }
660 1107
661-/// The door needs no AI bridge at all: a produced file is served with the1108+/// The nest sits behind the school's `chatbot` module — the AI package's only
662-/// service long gone.1109+/// module — exactly like `/chatbot` and `/rag`: with the module off the whole
1110+/// URL space answers the disabled refusal, never a handler.
663 #[tokio::test]1111 #[tokio::test]
664-async fn the_audio_door_needs_no_service() {1112+async fn a_school_without_the_chatbot_module_has_no_podcast_nest() {
665- let (app, _db) = common::app_with_ai(None).await;1113+ let bridge = bridge().await;
1114+ let (app, _db, tenants) = common::app_with_ai_tenants(Some(bridge)).await;
666 let cookie = common::login(&app, "ali").await;1115 let cookie = common::login(&app, "ali").await;
667- let bytes = b"produced before the service left".to_vec();
668- school_file("podcast/offline/episode.mp3", &bytes);
669 1116
670- let (status, _, body) = fetch_audio(&app, Some(&cookie), "podcast/offline/episode.mp3").await;1117+ let mut modules = ModuleSet::all();
671- assert_eq!(status, StatusCode::OK);1118+ modules.remove(Module::Chatbot);
672- assert_eq!(body, bytes);1119+ modules.validate().expect("the narrowed set is satisfiable");
1120+ tenants
1121+ .set_modules(&demo(), &modules)
1122+ .await
1123+ .expect("narrow the demo school");
1124+
1125+ let res = status_of(&app, &cookie, common::GHOST_ID).await;
1126+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
1127+ assert_eq!(res.body["module"], "chatbot");
673 }1128 }