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(
329329 ));
330330 }
331331 let db = &tenant.db;
332- let answer = match capability {
332+ match capability {
333333 AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY => {
334334 let request: SummaryWriteRequest = decode(payload)?;
335335 encode(&db::insight::write_summaries(db, request.rows).await.map_err(refusal)?)
@@ -374,14 +374,11 @@ pub async fn serve(
374374 // `scope_of` matched above, so the table and this match agree; the
375375 // arm exists so a table entry without an operation is a compile-time
376376 // miss instead of a runtime surprise.
377- other => {
378- return Err((
379- "unknown_capability",
380- format!("the backend serves no `{other}` operation"),
381- ));
382- }
383- };
384- answer
377+ other => Err((
378+ "unknown_capability",
379+ format!("the backend serves no `{other}` operation"),
380+ )),
381+ }
385382 }
386383
387384 /// Decode one payload into the operation's own type. A payload that does not
src/ai/mod.rsmodified+6 -3
@@ -13,10 +13,12 @@
1313 //!
1414 //! * [`api`] — which REST paths a service may read back through the bridge
1515 //! * [`protocol`] — frames on the wire
16+//! * [`capability`] — the capabilities the **backend** serves, and their scopes
1617 //! * [`chat`] — the JSON payloads carried for the `chat.reply` capability
1718 //! * [`rag`] — the `rag.index` payloads, and the course-note dispatch behind them
1819 //! * [`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 them
20+//! * [`podcast`] — the `podcast.*` job payloads, the relay behind submit/cancel,
21+//! and the job-state report the service calls back
2022 //! * [`server`] — the listener, handshake, and [`server::AiBridge::dispatch`]
2123 //! * [`registry`] — who is connected here, and who gets the next request
2224 //! * [`tls`] — the listener's certificate
@@ -24,10 +26,11 @@
2426 //! The transport is generic; the features land on top of it. So far that is
2527 //! the chatbot (`web::chatbot`), which routes on the `chat.reply` capability,
2628 //! course-note indexing (`web::course_notes`), which routes on `rag.index`,
27-//! and the podcast relay (`web::podcast`), which routes on the four
28-//! `podcast.*` capabilities and streams the audio they produce.
29+//! and the podcast relay (`web::podcast`), which dispatches `podcast.submit`/
30+//! `podcast.cancel`, serves `podcast.report`, and streams the ingested audio.
2931
3032 pub mod api;
33+pub mod capability;
3134 pub mod chat;
3235 pub mod error;
3336 pub mod insight;
src/ai/podcast.rsmodified+215 -118
@@ -1,143 +1,117 @@
1-//! Payload contract for the `podcast.*` capabilities, and the dispatch behind
2-//! them.
1+//! Payload contract for the `podcast.*` capabilities and the audio ingest —
2+//! both directions of the podcast seam.
33 //!
44 //! 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 result
6-//! read it back minutes later, cancel stops it. So these are four verbs on one
7-//! record that the **service** owns, not four steps of one backend request,
8-//! and the backend relays each call to the worker declaring the matching
9-//! capability.
5+//! audio episode. Since 2026-09-17 the **backend owns that job's record**: the
6+//! submit door mints the job id, writes the row, and then dispatches
7+//! `podcast.submit` with that id; the service reports every transition back
8+//! through the client-initiated `podcast.report` capability, and uploads the
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.
1013 //!
11-//! Nothing here is spawned, unlike [`chat`](crate::ai::chat) and
12-//! [`rag_chat`](crate::ai::rag_chat): every one of the four calls answers
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.
14+//! What remains **server-initiated** are the two calls that must reach a live
15+//! worker:
1816 //!
19-//! Tenancy is the transport's job: [`crate::ai::server`] stamps the caller's
20-//! school onto every `hab/2` request; it does **not** verify the echo on
21-//! replies (the bridge correlates answers by frame id alone), so the wall is
22-//! the stamp plus the service's own honesty — and it holds even though the
23-//! job records themselves live outside the backend's databases.
17+//! * [`submit`] — `podcast.submit`, whose payload carries the backend-minted
18+//! `job_id` and the submitting `user_id` (the service stores both; its own
19+//! record is keyed by the id the backend will keep asking about).
20+//! * [`cancel`] — `podcast.cancel`, unchanged: a write on the service's queue,
21+//! and the capability is what decides whether a deployment offers the door.
2422 //!
25-//! The produced audio does not cross the bridge. `podcast.result` answers an
26-//! `audio_id` that is a path *relative* to the service's
27-//! `PODCAST_OUTPUT_ROOT`, which the deployment points at the school's own
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`].
23+//! Tenancy is the transport's job: [`crate::ai::server`] stamps the caller's
24+//! school onto every `hab/2` request and resolves the frame's school on every
25+//! client-initiated one; this module never re-derives a school.
3226
3327 use serde::de::DeserializeOwned;
3428 use serde::{Deserialize, Serialize};
29+use serde_json::Value;
3530
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};
3736 use crate::tenant::Slug;
3837
3938 /// The capability strings, re-exported so a reader of the payload contract
4039 /// finds them next to the payloads — the same shape as
4140 /// [`crate::ai::rag`](crate::ai::rag).
4241 pub use crate::constant::{
43- AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_RESULT_CAPABILITY, AI_PODCAST_STATUS_CAPABILITY,
44- AI_PODCAST_SUBMIT_CAPABILITY,
42+ AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_REPORT_CAPABILITY, AI_PODCAST_SUBMIT_CAPABILITY,
4543 };
4644
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.
4849 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
4950 pub struct PodcastSubmitPayload {
50- /// The backend's record id for the source to narrate — a course note id,
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.
51+ pub job_id: String,
5352 pub source_id: String,
54- /// Which narration to produce. `duz_okuma` (plain reading) is the
55- /// service's default and the only one that needs no LLM key;
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")]
53+ /// `None` means the service applies its own default (`duz_okuma` today).
54+ #[serde(default, skip_serializing_if = "Option::is_none")]
6055 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,
6159 }
6260
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.
6463 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
6564 pub struct PodcastSubmitReply {
66- /// The id the service minted for the job. Every later call names it.
6765 pub job_id: String,
68- /// The job's state right after submission (`queued`).
66+ /// `queued` on a fresh job.
6967 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.
7169 pub eta_secs: i64,
7270 }
7371
74-/// What the backend asks about one job's progress.
72+/// What the backend asks to cancel.
7573 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76-pub struct PodcastStatusPayload {
74+pub struct PodcastCancelPayload {
7775 pub job_id: String,
7876 }
7977
80-/// One job's state, as of now.
81-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
82-pub struct PodcastStatusReply {
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.
78+/// The verdict on a cancel: `cancelled` is "this call cancelled something",
79+/// not "the job is cancelled" — cancelling an already-finished job answers
80+/// `false`, and so does cancelling one that was already cancelled.
9881 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
99-pub struct PodcastResultPayload {
82+pub struct PodcastCancelReply {
10083 pub job_id: String,
84+ pub cancelled: bool,
10185 }
10286
103-/// A finished job's artifacts. Only a `done` job answers this: the service
104-/// refuses any other state with `not_ready`, so nothing here is nullable — a
105-/// reply missing `audio_id` is an unreadable answer, not a half-finished job.
87+/// One state report from the service — the payload of a client-initiated
88+/// [`AI_PODCAST_REPORT_CAPABILITY`] call. The service sends one per
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.
10692 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
107-pub struct PodcastResultReply {
93+pub struct PodcastReportPayload {
10894 pub job_id: String,
109- /// The produced audio, as a path **relative** to `PODCAST_OUTPUT_ROOT` on
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]`.
95+ pub source_id: String,
11996 #[serde(default)]
120- pub audio_ids: Vec<String>,
121- /// One entry per script the audio was aligned to.
97+ pub format: Option<String>,
98+ pub user_id: String,
99+ /// `queued` | `running` | `done` | `failed` | `cancelled`.
100+ pub state: String,
122101 #[serde(default)]
123- pub script_ids: Vec<String>,
124- /// The narration format the job was produced with.
125- pub format: String,
126-}
127-
128-/// What the backend asks to cancel.
129-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
130-pub struct PodcastCancelPayload {
131- pub job_id: String,
102+ pub stage: String,
103+ #[serde(default)]
104+ pub progress: f64,
105+ #[serde(default)]
106+ pub error_code: Option<String>,
132107 }
133108
134-/// The verdict on a cancel: `cancelled` is "this call cancelled something",
135-/// not "the job is cancelled" — cancelling an already-finished job answers
136-/// `false`, and so does cancelling one that was already cancelled.
109+/// The answer to one report. `stored` is always `true` on an `Ok` — an
110+/// unstored report is a refusal, never a quiet success.
137111 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
138-pub struct PodcastCancelReply {
112+pub struct PodcastReportReply {
139113 pub job_id: String,
140- pub cancelled: bool,
114+ pub stored: bool,
141115 }
142116
143117 /// Start one job. `Err` is a short, stable code — see [`failure_code`].
@@ -149,24 +123,6 @@ pub async fn submit(
149123 dispatch(bridge, slug, AI_PODCAST_SUBMIT_CAPABILITY, payload).await
150124 }
151125
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-
170126 /// Cancel one job.
171127 pub async fn cancel(
172128 bridge: &AiBridge,
@@ -176,14 +132,155 @@ pub async fn cancel(
176132 dispatch(bridge, slug, AI_PODCAST_CANCEL_CAPABILITY, payload).await
177133 }
178134
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+
179282 /// One `podcast.*` round trip: encode, dispatch, decode. Every capability
180283 /// 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.
187284 async fn dispatch<P, R>(
188285 bridge: &AiBridge,
189286 slug: &Slug,
src/ai/server.rsmodified+2 -7
@@ -646,12 +646,7 @@ async fn serve_upload(
646646 // sender so its write stops rather than filling a stream nobody
647647 // reads.
648648 let _ = recv.stop(1u32.into());
649- upload_refusal(
650- request.id.clone(),
651- request.school.clone(),
652- &code,
653- message,
654- )
649+ upload_refusal(request.id.clone(), request.school.clone(), code, message)
655650 }
656651 };
657652 if let Err(e) = write_frame(send, &response).await {
@@ -1092,7 +1087,7 @@ async fn serve_capability(inner: &Inner, request: CapabilityRequest) -> Capabili
10921087 let call = capability::serve(
10931088 &request.capability,
10941089 tenant.as_ref(),
1095- &control,
1090+ control,
10961091 &request.payload,
10971092 );
10981093 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;
5353 pub mod parent_link;
5454 pub mod payment_ledger;
5555 pub mod person;
56+pub mod podcast_job;
5657 pub mod pomodoro;
5758 pub mod pool_question;
5859 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 {
6363 Validation(#[from] ValidationError),
6464 #[error("not found")]
6565 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),
6673 #[error("unauthorized")]
6774 Unauthorized,
6875 #[error("forbidden: {0}")]
@@ -152,6 +159,7 @@ impl AppError {
152159 match self {
153160 AppError::Validation(_) => "validation",
154161 AppError::NotFound => "not_found",
162+ AppError::Expired(_) => "expired",
155163 AppError::Unauthorized => "unauthorized",
156164 AppError::Forbidden(_) => "forbidden",
157165 AppError::ModuleDisabled(_) => "module_disabled",
@@ -266,6 +274,7 @@ impl AppError {
266274 }
267275 AppError::Validation(v) => (StatusCode::BAD_REQUEST, v.to_string()),
268276 AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()),
277+ AppError::Expired(m) => (StatusCode::GONE, m.to_string()),
269278 AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),
270279 AppError::Forbidden(m) => (StatusCode::FORBIDDEN, m.to_string()),
271280 AppError::Conflict(m) => (StatusCode::CONFLICT, m.to_string()),
src/service/mod.rsmodified+1 -0
@@ -47,6 +47,7 @@ pub mod note_file;
4747 pub mod parent_link;
4848 pub mod payment_ledger;
4949 pub mod person;
50+pub mod podcast_job;
5051 pub mod pomodoro;
5152 pub mod pool_question;
5253 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 {
585585 AppError::Conflict(_) | AppError::ConflictOwned(_) => "conflict",
586586 AppError::Validation(_) | AppError::PayloadTooLarge(_) => "invalid",
587587 AppError::NotFound => "not_found",
588+ AppError::Expired(_) => "expired",
588589 // See `room::public_message`: the gate refuses the upgrade first.
589590 AppError::ModuleDisabled(_) => "module_disabled",
590591 AppError::Unauthorized => "unauthorized",
src/web/podcast.rsmodified+263 -282
@@ -1,75 +1,67 @@
11 //! 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.
33 //!
4-//! The relay contract is the chatbot's and the RAG nest's, shape for shape:
5-//! the backend owns authentication and the thin HTTP surface, the **service**
6-//! owns the job. Four doors map one-to-one onto the four `podcast.*`
7-//! capabilities — `POST /jobs` (submit), `GET /jobs/{id}` (status),
8-//! `GET /jobs/{id}/result` (result) and `POST /jobs/{id}/cancel` (cancel) —
9-//! each refusing `503` when no worker declares its capability, and each
10-//! relaying what the service answered: the receipt, the status snapshot, the
11-//! artifacts, the cancel verdict. A service-side refusal keeps its own code
12-//! (`not_found`, `not_ready`, `busy`, …) and decides the HTTP status, so a
13-//! client branches on the same vocabulary the bridge speaks.
4+//! The **backend owns the job**. `POST /podcast/jobs` mints the id, writes the
5+//! row, and only then dispatches `podcast.submit`; the service reports every
6+//! transition back (`podcast.report`) and uploads the finished mp3
7+//! (`BlobUploadRequest`), which lands under **this school's** blob directory.
8+//! `GET /podcast/jobs/{id}` and `.../result` therefore answer from
9+//! [`crate::db::podcast_job`] alone — no worker, no service, no second store
10+//! that a restart or a wiped volume could take down with it. The service's own
11+//! record is a mirror the pipeline works against, not the source of truth.
1412 //!
15-//! The fifth door is the audio itself. `podcast.result` answers an `audio_id`
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.
13+//! Five doors:
2514 //!
26-//! Every door is school-scoped twice: the session resolves the school, and the
27-//! audio door resolves the path under *that* school's directory, so a caller
28-//! cannot reach another school's episode even knowing its exact path.
15+//! * `POST /podcast/jobs` — write the row, dispatch `podcast.submit`
16+//! * `GET /podcast/jobs/{id}` — the row's snapshot (projected, see below)
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
2920 //!
30-//! None of the four dispatching doors writes a row: the job record and the
31-//! produced files live in the service. That is also why they are synchronous —
32-//! every capability answers immediately (the pipeline runs in the service's own
33-//! pool), so there is nothing here to await off the request path.
21+//! The two dispatching doors (`submit`, `cancel`) refuse `503` when no worker
22+//! declares their capability; the three reading doors need no service at all.
23+//! A relayed failure keeps the service's own code and decides the HTTP status
24+//! (`failure`), so a client branches on the same vocabulary the bridge speaks.
3425 //!
35-//! What the backend can and cannot judge, stated plainly: the gate is a
36-//! session — any authenticated member of the school may use the doors, the same
37-//! floor `/chatbot` and `/rag` hold — and the school wall is the bridge's
38-//! (`hab/2` stamps the caller's school onto every request; the bridge does
39-//! not verify the echo on replies — answers are correlated by frame id
40-//! alone). It cannot scope
41-//! *which* sources a caller may narrate: `source_id` is the service's own
42-//! record, and no backend query can say what it names. That is a property of
43-//! the wire the two sides share, not an oversight — the service resolves the
44-//! id against the shared media volume and the backend enforces the tenant.
26+//! Every door is school-scoped twice: the session resolves the school's
27+//! database (`st.db`) and the school's blob directory (`st.files_path`), and
28+//! every read is filtered by the submitting user in the statement itself — a
29+//! foreign id is a plain `404`, never a hint that it exists. Terminal rows
30+//! older than the retention window answer `410`.
31+//!
32+//! A job nobody is updating — the service died mid-pipeline — is *presented*
33+//! as `failed`/`interrupted` by the read path after a bounded, ETA-scaled
34+//! window (see [`PodcastJob::projected`]): the projection writes nothing, and
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.
4539
4640 use axum::Json;
4741 use axum::body::{Body, Bytes};
48-use axum::extract::{Path, Query};
42+use axum::extract::Path;
4943 use axum::http::HeaderValue;
5044 use axum::http::StatusCode;
5145 use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS};
5246 use axum::response::{IntoResponse, Response};
5347 use serde::{Deserialize, Serialize};
5448 use serde_json::json;
55-use tokio::io::AsyncReadExt;
5649 use tokio::sync::mpsc;
5750 use tokio_stream::Stream;
5851 use tokio_stream::wrappers::ReceiverStream;
59-use utoipa::{IntoParams, ToSchema};
52+use utoipa::ToSchema;
6053 use utoipa_axum::router::OpenApiRouter;
6154 use utoipa_axum::routes;
6255
6356 use crate::ai::AiBridge;
64-use crate::ai::podcast::{
65- self, PodcastCancelPayload, PodcastCancelReply, PodcastResultPayload, PodcastResultReply,
66- PodcastStatusPayload, PodcastStatusReply, PodcastSubmitPayload, PodcastSubmitReply,
67-};
57+use crate::ai::podcast::{self, PodcastCancelPayload, PodcastSubmitPayload};
6858 use crate::constant::{
69- AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_RESULT_CAPABILITY, AI_PODCAST_STATUS_CAPABILITY,
70- AI_PODCAST_SUBMIT_CAPABILITY,
59+ AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_SUBMIT_CAPABILITY, PODCAST_INTERRUPTED_CODE,
7160 };
61+use crate::domain::podcast_job::{PodcastJob, PodcastJobId};
62+use crate::domain::user::User;
7263 use crate::error::{AppError, ErrorResponse, ValidationError};
64+use crate::service::podcast_job as jobs;
7365 use crate::state::AppState;
7466 use crate::web::tenant_state::{SchoolSlug, State};
7567
@@ -86,8 +78,8 @@ pub fn routes() -> OpenApiRouter<AppState> {
8678 .routes(routes!(submit))
8779 .routes(routes!(status))
8880 .routes(routes!(result))
89- .routes(routes!(cancel))
9081 .routes(routes!(audio))
82+ .routes(routes!(cancel))
9183 }
9284
9385 #[derive(Deserialize, ToSchema)]
@@ -104,10 +96,13 @@ struct SubmitPodcast {
10496 format: Option<String>,
10597 }
10698
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.
108101 #[derive(Serialize, ToSchema)]
109102 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")]
111106 job_id: String,
112107 /// `queued` on a fresh job.
113108 state: String,
@@ -115,7 +110,7 @@ struct JobReceipt {
115110 eta_secs: i64,
116111 }
117112
118-/// One job's state, passed through verbatim.
113+/// One job's state, from the backend's own row.
119114 #[derive(Serialize, ToSchema)]
120115 struct JobStatus {
121116 job_id: String,
@@ -129,21 +124,17 @@ struct JobStatus {
129124 error_code: Option<String>,
130125 }
131126
132-/// A finished job's artifacts, passed through verbatim.
127+/// A finished job's artifacts.
133128 #[derive(Serialize, ToSchema)]
134129 struct JobArtifacts {
135130 job_id: String,
136- /// The produced audio, as a path relative to the school's podcast output
137- /// root — feed it straight to `GET /podcast/audio?path=…`.
138- #[schema(example = "ses/duz_okuma/019732e3-7b00-7000-8000-00000000dead/episode.mp3")]
131+ /// The produced audio, as the blob key `GET /podcast/jobs/{id}/audio`
132+ /// streams — informational, never a path the caller resolves itself.
133+ #[schema(example = "podcast/019732e3-7b00-7000-8000-00000000dead.mp3")]
139134 audio_id: String,
140- duration_secs: f64,
141- script_id: String,
142- /// One entry per produced chapter; usually `[audio_id]`.
143- audio_ids: Vec<String>,
144- /// One entry per script the audio was aligned to.
145- script_ids: Vec<String>,
146- format: String,
135+ duration_secs: Option<f64>,
136+ /// The resolved narration format.
137+ format: Option<String>,
147138 }
148139
149140 /// The verdict on a cancel.
@@ -155,9 +146,14 @@ struct CancelVerdict {
155146 cancelled: bool,
156147 }
157148
158-/// Start one podcast job. Answers `202` with the service's receipt the moment
159-/// the service accepts it; the pipeline then runs in the service's own worker
160-/// pool, so poll `GET /jobs/{id}` for progress.
149+/// Start one podcast job. Answers `202` with the backend's own receipt the
150+/// moment the service accepts it.
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.
161157 #[utoipa::path(
162158 post,
163159 path = "/jobs",
@@ -175,7 +171,7 @@ struct CancelVerdict {
175171 async fn submit(
176172 State(st): State<AppState>,
177173 SchoolSlug(slug): SchoolSlug,
178- CurrentUser(_user): CurrentUser,
174+ CurrentUser(user): CurrentUser,
179175 Json(req): Json<SubmitPodcast>,
180176 ) -> Result<Response, AppError> {
181177 let bridge = match worker_for(&st, AI_PODCAST_SUBMIT_CAPABILITY) {
@@ -193,18 +189,53 @@ async fn submit(
193189 }));
194190 }
195191
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();
196194 let payload = PodcastSubmitPayload {
195+ job_id: job_id.clone(),
197196 source_id: source_id.to_string(),
198- format: req.format,
197+ format: req.format.clone(),
198+ user_id: user.get_id().key(),
199199 };
200200 match podcast::submit(&bridge, &slug, payload).await {
201- Ok(reply) => Ok((StatusCode::ACCEPTED, Json(receipt(reply))).into_response()),
202- Err(code) => Ok(failure(&code)),
201+ // The echo is checked, not trusted: this id is the only handle every
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+ }
203232 }
204233 }
205234
206-/// One job's current state. Poll this; the answer is the service's own
207-/// snapshot.
235+/// One job's current state — the backend's own row, so this door answers with
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.
208239 #[utoipa::path(
209240 get,
210241 path = "/jobs/{id}",
@@ -214,29 +245,28 @@ async fn submit(
214245 responses(
215246 (status = 200, description = "The job as of now", body = JobStatus),
216247 (status = 401, description = "Not authenticated", body = ErrorResponse),
217- (status = 404, description = "No such job (the service answered `not_found`)", body = ErrorResponse),
218- (status = 503, description = "No AI service offers `podcast.status`", body = ErrorResponse),
248+ (status = 404, description = "No such job for this caller (unknown id, or another user's)", body = ErrorResponse),
249+ (status = 410, description = "The job is past its retention window", body = ErrorResponse),
219250 ),
220251 )]
221252 async fn status(
222253 State(st): State<AppState>,
223- SchoolSlug(slug): SchoolSlug,
224- CurrentUser(_user): CurrentUser,
254+ CurrentUser(user): CurrentUser,
225255 Path(id): Path<String>,
226256 ) -> Result<Response, AppError> {
227- let bridge = match worker_for(&st, AI_PODCAST_STATUS_CAPABILITY) {
228- Ok(bridge) => bridge,
229- Err(no_worker) => return Ok(no_worker.refusal()),
230- };
231- match podcast::status(&bridge, &slug, PodcastStatusPayload { job_id: id }).await {
232- Ok(reply) => Ok(Json(snapshot(reply)).into_response()),
233- Err(code) => Ok(failure(&code)),
234- }
257+ let job = owned(&st, &user, &id).await?;
258+ Ok(Json(JobStatus {
259+ job_id: job.get_id().key(),
260+ state: job.get_state().as_str().to_string(),
261+ stage: job.get_stage().to_string(),
262+ progress: job.get_progress(),
263+ error_code: job.get_error_code().map(str::to_string),
264+ })
265+ .into_response())
235266 }
236267
237-/// A finished job's artifacts — above all the `audio_id` the audio door
238-/// streams. A job that has not finished yet is refused by the service with
239-/// `not_ready` (409); one it has never heard of with `not_found` (404).
268+/// A finished job's artifact references. A job that has not finished is a
269+/// `409 not_ready`; one the caller does not own, a `404`.
240270 #[utoipa::path(
241271 get,
242272 path = "/jobs/{id}/result",
@@ -246,109 +276,94 @@ async fn status(
246276 responses(
247277 (status = 200, description = "The finished job's artifacts", body = JobArtifacts),
248278 (status = 401, description = "Not authenticated", body = ErrorResponse),
249- (status = 404, description = "No such job (the service answered `not_found`)", body = ErrorResponse),
250- (status = 409, description = "The job has not finished (the service answered `not_ready`)", body = ErrorResponse),
251- (status = 503, description = "No AI service offers `podcast.result`", body = ErrorResponse),
279+ (status = 404, description = "No such job for this caller", body = ErrorResponse),
280+ (status = 409, description = "The job has not finished (`code: not_ready`)", body = ErrorResponse),
281+ (status = 410, description = "The job is past its retention window", body = ErrorResponse),
252282 ),
253283 )]
254284 async fn result(
255285 State(st): State<AppState>,
256- SchoolSlug(slug): SchoolSlug,
257- CurrentUser(_user): CurrentUser,
286+ CurrentUser(user): CurrentUser,
258287 Path(id): Path<String>,
259288 ) -> Result<Response, AppError> {
260- let bridge = match worker_for(&st, AI_PODCAST_RESULT_CAPABILITY) {
261- Ok(bridge) => bridge,
262- Err(no_worker) => return Ok(no_worker.refusal()),
263- };
264- match podcast::result(&bridge, &slug, PodcastResultPayload { job_id: id }).await {
265- Ok(reply) => Ok(Json(artifacts(reply)).into_response()),
266- Err(code) => Ok(failure(&code)),
267- }
268-}
269-
270-/// Cancel one job. `cancelled` says whether *this call* stopped work — a job
271-/// that had already finished, or was already cancelled, answers `false` and is
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()),
289+ let job = owned(&st, &user, &id).await?;
290+ let audio_id = match job.get_state() {
291+ crate::domain::podcast_job::PodcastJobState::Done => job
292+ .get_audio_key()
293+ .expect("a done row always carries its audio (schema CHECK)")
294+ .to_string(),
295+ _ => {
296+ return Err(AppError::ConflictCoded {
297+ code: "not_ready",
298+ message: format!("job `{}` is {}", job.get_id().key(), job.get_state().as_str()),
299+ });
300+ }
295301 };
296- match podcast::cancel(&bridge, &slug, PodcastCancelPayload { job_id: id }).await {
297- Ok(reply) => Ok(Json(verdict(reply)).into_response()),
298- Err(code) => Ok(failure(&code)),
299- }
300-}
301-
302-/// The query behind the audio door.
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,
302+ Ok(Json(JobArtifacts {
303+ job_id: job.get_id().key(),
304+ audio_id,
305+ duration_secs: job.get_duration_secs(),
306+ format: job.get_format().map(str::to_string),
307+ })
308+ .into_response())
309309 }
310310
311-/// Stream one produced audio file. `path` is the `audio_id`
312-/// `podcast.result` answered, resolved under **this caller's school** output
313-/// directory — the same directory the service's `PODCAST_OUTPUT_ROOT` points
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.
311+/// Stream one produced episode. The bytes are this school's own — ingested
312+/// under this school's blob directory — and the content type is the one the
313+/// upload declared, replayed from the row.
316314 ///
317-/// The path is hostile input: a leading `/`, any `.`/`..` segment, a
318-/// backslash, a drive colon, or a symlink whose target resolves outside the
319-/// school's directory is a `400` (a path this backend will not resolve), not a
320-/// `404` — a caller probing the boundary gets the truth, and a caller with a
321-/// legitimate `audio_id` never sees either.
315+/// A job that is not `done` is a `409 not_ready`; a row whose blob is missing
316+/// from the host is a `409 audio_missing` (the row is intact, the bytes are
317+/// not — a state a client can report, unlike a generic `500`).
322318 #[utoipa::path(
323319 get,
324- path = "/audio",
320+ path = "/jobs/{id}/audio",
325321 tag = "podcast",
326322 security(("session_cookie" = [])),
323+ params(("id" = String, Path, description = "Job id from `POST /podcast/jobs`")),
327324 responses(
328325 (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),
330326 (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),
332330 ),
333331 )]
334332 async fn audio(
335333 State(st): State<AppState>,
336- CurrentUser(_user): CurrentUser,
337- Query(query): Query<AudioQuery>,
334+ CurrentUser(user): CurrentUser,
335+ Path(id): Path<String>,
338336 ) -> Result<Response, AppError> {
339- // The school-scoped `State` has already narrowed `files_path` to the
340- // caller's own directory under `FILES_PATH` — the very directory the
341- // service's `PODCAST_OUTPUT_ROOT` points at — so the containment root here
342- // needs no school arithmetic of its own, and cannot drift from the one
343- // every other blob route uses.
344- let file_path = resolve_audio(&st.files_path, &query.path).await?;
345- let file = tokio::fs::File::open(&file_path)
346- .await
347- .map_err(|_| AppError::NotFound)?;
337+ let job = owned(&st, &user, &id).await?;
338+ let key = match job.get_state() {
339+ crate::domain::podcast_job::PodcastJobState::Done => job
340+ .get_audio_key()
341+ .expect("a done row always carries its audio (schema CHECK)")
342+ .to_string(),
343+ _ => {
344+ return Err(AppError::ConflictCoded {
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");
348359
349360 Ok((
350361 [
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+ ),
352367 (X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")),
353368 (CACHE_CONTROL, HeaderValue::from_static("private, no-store")),
354369 ],
@@ -357,84 +372,91 @@ async fn audio(
357372 .into_response())
358373 }
359374
360-/// Resolve one `audio_id` into a real file under `root`, or refuse it.
361-///
362-/// The order is the point: shape first (so an absolute path or a `..` segment
363-/// never reaches the filesystem), then canonicalization — which follows every
364-/// symlink, so a link that only *looks* like it lives under the root resolves
365-/// out of it and is refused by the containment check rather than served.
366-async fn resolve_audio(
367- root: &std::path::Path,
368- relative: &str,
369-) -> Result<std::path::PathBuf, AppError> {
370- let refused = || {
371- AppError::Validation(ValidationError::Invalid {
372- field: "path",
373- reason: "must be a relative path inside this school's podcast output",
375+/// Cancel one job. `cancelled` says whether *this call* stopped work — a job
376+/// that had already finished, or was already cancelled, answers `false` and is
377+/// not an error. Only a live job needs the service; a terminal one is answered
378+/// from the row without a worker. A service that has never heard of a live job
379+/// (its store was wiped) leaves the row `failed`/`interrupted`: the job cannot
380+/// finish, and the row says so.
381+#[utoipa::path(
382+ post,
383+ path = "/jobs/{id}/cancel",
384+ tag = "podcast",
385+ security(("session_cookie" = [])),
386+ params(("id" = String, Path, description = "Job id from `POST /podcast/jobs`")),
387+ responses(
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,
374407 })
375- };
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());
408+ .into_response());
394409 }
395-
396- // The root is canonicalized too: `FILES_PATH` may itself be reached
397- // through a symlink, and containment must compare real paths.
398- let root = tokio::fs::canonicalize(root)
399- .await
400- .map_err(|_| AppError::NotFound)?;
401- let target = tokio::fs::canonicalize(root.join(relative))
402- .await
403- .map_err(|_| AppError::NotFound)?;
404-
405- // Symlink escape: `canonicalize` follows links, so a target that resolves
406- // outside the school's directory lands here, whatever the link looked like.
407- if !target.starts_with(&root) {
408- return Err(refused());
409- }
410- // A directory is not an audio file — and serving `read` on it would be an
411- // I/O error at best.
412- if !tokio::fs::metadata(&target)
413- .await
414- .map(|meta| meta.is_file())
415- .unwrap_or(false)
410+ let bridge = match worker_for(&st, AI_PODCAST_CANCEL_CAPABILITY) {
411+ Ok(bridge) => bridge,
412+ Err(no_worker) => return Ok(no_worker.refusal()),
413+ };
414+ let verdict = |cancelled: bool| {
415+ Json(CancelVerdict {
416+ job_id: job.get_id().key(),
417+ cancelled,
418+ })
419+ .into_response()
420+ };
421+ match podcast::cancel(
422+ &bridge,
423+ &slug,
424+ PodcastCancelPayload {
425+ job_id: job_id.clone(),
426+ },
427+ )
428+ .await
416429 {
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)),
418445 }
419- Ok(target)
420446 }
421447
422-/// The content type for a produced artifact, by extension. `mp3` is what the
423-/// pipeline writes today; the rest of the set is here so a format switch on the
424-/// service side still serves as audio rather than as an opaque download.
425-fn audio_content_type(path: &std::path::Path) -> &'static str {
426- match path
427- .extension()
428- .and_then(|ext| ext.to_str())
429- .map(str::to_ascii_lowercase)
430- .as_deref()
431- {
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",
448+/// Read one job for this caller, projected and expiry-checked — the three
449+/// reading doors' shared first act. A foreign id and an unknown id are the
450+/// same `404`; a job past its retention window is a `410`.
451+async fn owned(st: &AppState, user: &User, id: &str) -> Result<PodcastJob, AppError> {
452+ let job = jobs::read_for(&st.db, &PodcastJobId::from_key(id), user.get_id())
453+ .await?
454+ .ok_or(AppError::NotFound)?
455+ .projected();
456+ if job.is_expired() {
457+ return Err(AppError::Expired("this podcast job has expired"));
437458 }
459+ Ok(job)
438460 }
439461
440462 /// 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 {
442464 /// send instead of pinning the whole file in memory, and a closed body ends the
443465 /// task by itself.
444466 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);
446468 tokio::spawn(async move {
447469 let mut file = file;
448- let mut buffer = vec![0u8; AUDIO_CHUNK_BYTES];
470+ let mut buf = vec![0u8; AUDIO_CHUNK_BYTES];
449471 loop {
450- match file.read(&mut buffer).await {
472+ match tokio::io::AsyncReadExt::read(&mut file, &mut buf).await {
451473 Ok(0) => break,
452- Ok(read) => {
453- if tx
454- .send(Ok(Bytes::copy_from_slice(&buffer[..read])))
455- .await
456- .is_err()
457- {
474+ Ok(n) => {
475+ if tx.send(Ok(Bytes::copy_from_slice(&buf[..n]))).await.is_err() {
458476 break;
459477 }
460478 }
@@ -490,7 +508,7 @@ impl NoWorker {
490508 }
491509 }
492510
493-/// The 503 gate every dispatching door shares: no bridge configured, or no
511+/// The 503 gate the two dispatching doors share: no bridge configured, or no
494512 /// worker declaring this door's capability. `has_capability` is documented
495513 /// racy — fine here: it never guards a write, and the dispatch that follows
496514 /// re-checks for real; this only spares a caller a round trip into a service
@@ -523,40 +541,3 @@ fn failure(code: &str) -> Response {
523541 };
524542 (status, Json(json!({ "error": code }))).into_response()
525543 }
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 {
120120 match err {
121121 AppError::Validation(err) => err.to_string(),
122122 AppError::NotFound => "not found".to_string(),
123+ AppError::Expired(message) => (*message).to_string(),
123124 AppError::Unauthorized => "unauthorized".to_string(),
124125 AppError::Forbidden(message) => (*message).to_string(),
125126 AppError::Conflict(message) => (*message).to_string(),
tests/integration.rsmodified+1 -1
@@ -434,7 +434,7 @@ async fn protected_routes_require_session() {
434434 /// Floor on the number of protected operations swept. It only ever goes
435435 /// up: raise it when routes are added. Without it, deleting a route family
436436 /// would delete its own coverage and still pass.
437- const MIN_PROTECTED: usize = 323;
437+ const MIN_PROTECTED: usize = 337;
438438
439439 let app = mem_app().await;
440440 let spec = send(&app, "GET", "/api-docs/openapi.json", None, None)
tests/podcast.rsmodified+806 -351
@@ -2,16 +2,18 @@
22 //!
33 //! Everything here runs over a real QUIC socket on loopback — a real
44 //! handshake, real TLS, real streams — with [`Behaviour::Podcast`] standing in
5-//! for what the service would do with a request. The four dispatching doors
6-//! are driven through the real router, so what they assert is what a browser
7-//! would receive, and the fake service's `seen` log is what the *service*
8-//! received.
5+//! for what the service does with a request. The **backend owns the job**: the
6+//! submit door mints the id, writes the `podcast_job` row, and only then
7+//! dispatches `podcast.submit`; the three reading doors answer from that row
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.
911 //!
10-//! The audio door is tested against a real directory tree — the same
11-//! `FILES_PATH` layout the deployment uses — because its whole job is refusing
12-//! paths that escape a school's directory. Every refusal test first proves the
13-//! target file exists, so a pass cannot come from the file simply being
14-//! missing.
12+//! The assertions therefore split in two: what a browser gets from the real
13+//! router, and what the *service* received ([`FakeService::seen`]) or what the
14+//! school's own database and blob directory hold. A reading door that quietly
15+//! round-tripped to the service would fail the `seen` assertions; a submit that
16+//! did not write its row first would fail the database ones.
1517
1618 mod common;
1719
@@ -19,35 +21,40 @@ use std::sync::{Arc, Mutex};
1921 use std::time::Duration;
2022
2123 use axum::Router;
22-use axum::http::StatusCode;
24+use axum::http::{HeaderMap, StatusCode};
2325 use hezarfen_backend::ai::protocol::{
2426 Greeting, Hello, Request, Response, read_frame, write_frame,
2527 };
2628 use hezarfen_backend::ai::{AiBridge, BridgeConfig};
2729 use hezarfen_backend::constant::{
28- AI_ALPN, AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_RESULT_CAPABILITY,
29- AI_PODCAST_STATUS_CAPABILITY, AI_PODCAST_SUBMIT_CAPABILITY, AI_PROTOCOL,
30+ AI_ALPN, AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_SUBMIT_CAPABILITY, AI_PROTOCOL,
31+ PODCAST_JOB_RETENTION_SECS, PODCAST_JOB_STALE_FLOOR_SECS,
3032 };
33+use hezarfen_backend::database::Database;
34+use hezarfen_backend::domain::timestamp::Timestamp;
3135 use hezarfen_backend::module::{Module, ModuleSet};
3236 use hezarfen_backend::tenant::{DEMO_SLUG, Slug};
3337 use serde_json::{Value, json};
38+use uuid::Uuid;
3439
3540 const TOKEN: &str = "shared-ai-token";
3641
37-/// The four capabilities one podcast service declares.
38-const CAPABILITIES: [&str; 4] = [
39- AI_PODCAST_SUBMIT_CAPABILITY,
40- AI_PODCAST_STATUS_CAPABILITY,
41- AI_PODCAST_RESULT_CAPABILITY,
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";
42+/// The two capabilities a live podcast worker offers. Status and result are
43+/// not capabilities any more — the backend answers those from its own row — so
44+/// a service declaring only these serves every reading door.
45+const CAPABILITIES: [&str; 2] = [AI_PODCAST_SUBMIT_CAPABILITY, AI_PODCAST_CANCEL_CAPABILITY];
46+
4947 /// A source id shaped like the backend ids the service is handed.
5048 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";
5158
5259 // ---------------------------------------------------------------- harness --
5360
@@ -103,10 +110,13 @@ fn hello(service: &str, capabilities: &[&str]) -> Hello {
103110 }
104111
105112 /// 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.
107116 struct FakeService {
108117 _endpoint: quinn::Endpoint,
109118 _control: (quinn::SendStream, quinn::RecvStream),
119+ conn: quinn::Connection,
110120 /// Every request this service received, in arrival order.
111121 seen: Arc<Mutex<Vec<Request>>>,
112122 }
@@ -120,10 +130,12 @@ impl FakeService {
120130 /// What the fake service does with each request it receives.
121131 #[derive(Clone)]
122132 enum Behaviour {
123- /// Answer like the podcast service: a queued receipt, a status snapshot, a
124- /// finished job's artifacts, a cancel verdict — each echoing the job id it
125- /// was asked about, so a mis-routed id shows up in the answer.
133+ /// Answer like the podcast service: a receipt echoing the backend's own
134+ /// job id, and a cancel verdict.
126135 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,
127139 /// Answer with a handled failure.
128140 Fail { code: String, message: String },
129141 }
@@ -149,6 +161,7 @@ async fn connect_service(bridge: &AiBridge, hello: Hello, behaviour: Behaviour)
149161 FakeService {
150162 _endpoint: endpoint,
151163 _control: (send, recv),
164+ conn,
152165 seen,
153166 }
154167 }
@@ -165,23 +178,26 @@ fn serve(conn: quinn::Connection, behaviour: Behaviour, seen: Arc<Mutex<Vec<Requ
165178 };
166179 seen.lock().unwrap().push(request.clone());
167180 let response = match behaviour {
168- Behaviour::Podcast => Some(Response::Ok {
181+ Behaviour::Podcast => Response::Ok {
169182 id: request.id.clone(),
170183 school: request.school.clone(),
171184 payload: podcast_answer(&request),
172- }),
173- Behaviour::Fail { code, message } => Some(Response::Err {
185+ },
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 {
174192 id: request.id.clone(),
175193 school: request.school.clone(),
176194 code,
177195 message,
178- }),
196+ },
179197 };
180- if let Some(response) = response {
181- let _ = write_frame(&mut send, &response).await;
182- let _ = send.finish();
183- let _ = send.stopped().await;
184- }
198+ let _ = write_frame(&mut send, &response).await;
199+ let _ = send.finish();
200+ let _ = send.stopped().await;
185201 });
186202 }
187203 });
@@ -189,36 +205,27 @@ fn serve(conn: quinn::Connection, behaviour: Behaviour, seen: Arc<Mutex<Vec<Requ
189205
190206 /// What the podcast service would answer for this capability.
191207 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));
197208 match request.capability.as_str() {
198- AI_PODCAST_SUBMIT_CAPABILITY => {
199- json!({ "job_id": JOB_ID, "state": "queued", "eta_secs": 2700 })
200- }
201- AI_PODCAST_STATUS_CAPABILITY => json!({
202- "job_id": job_id,
203- "state": "running",
204- "stage": "tts",
205- "progress": 0.5,
206- "error_code": null,
209+ // The receipt must echo the backend's own job id — the id every later
210+ // call names — so the fake echoes the payload it was handed.
211+ AI_PODCAST_SUBMIT_CAPABILITY => json!({
212+ "job_id": request.payload["job_id"],
213+ "state": "queued",
214+ "eta_secs": ETA_SECS,
207215 }),
208- AI_PODCAST_RESULT_CAPABILITY => json!({
209- "job_id": job_id,
210- "audio_id": AUDIO_ID,
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+ AI_PODCAST_CANCEL_CAPABILITY => json!({
217+ "job_id": request.payload["job_id"],
218+ "cancelled": true,
216219 }),
217- AI_PODCAST_CANCEL_CAPABILITY => json!({ "job_id": job_id, "cancelled": true }),
218220 other => panic!("the fake podcast service was asked for `{other}`"),
219221 }
220222 }
221223
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+
222229 /// Registration completes asynchronously after the welcome is on the wire, so
223230 /// tests that assert on the registry wait for it rather than racing it.
224231 async fn await_workers(bridge: &AiBridge, expected: usize) {
@@ -234,9 +241,11 @@ async fn await_workers(bridge: &AiBridge, expected: usize) {
234241 );
235242 }
236243
237-/// A registered podcast service offering all four capabilities, the router
238-/// wired to its bridge, and a logged-in student's cookie.
239-async fn podcast_app() -> (FakeService, Router, String) {
244+/// A registered podcast service offering the two capabilities a live worker
245+/// needs, the router wired to its bridge, a logged-in student's cookie, and
246+/// the school's database handle — the fixture every round-trip test starts
247+/// from.
248+async fn podcast_app() -> (FakeService, Router, String, Database) {
240249 let bridge = bridge().await;
241250 let service = connect_service(
242251 &bridge,
@@ -245,39 +254,347 @@ async fn podcast_app() -> (FakeService, Router, String) {
245254 )
246255 .await;
247256 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;
249258 let cookie = common::login(&app, "ali").await;
250- (service, app, cookie)
259+ (service, app, cookie, db)
251260 }
252261
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+
253274 /// Submit one job and return the response.
254275 async fn submit(app: &Router, cookie: &str, body: Value) -> common::Res {
255276 common::send(app, "POST", "/podcast/jobs", Some(cookie), Some(body)).await
256277 }
257278
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+
258520 // ------------------------------------------------------------ round trips --
259521
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.
260526 #[tokio::test]
261-async fn a_submit_round_trips_the_source_and_format_to_the_service() {
262- let (service, app, cookie) = podcast_app().await;
527+async fn a_submit_writes_the_row_and_hands_the_service_its_own_job_id() {
528+ let (service, app, cookie, db) = podcast_app().await;
529+ let user = common::me_id(&app, &cookie).await;
263530
264531 let res = submit(
265532 &app,
266533 &cookie,
267- json!({ "source_id": SOURCE_ID, "format": "duz_okuma" }),
534+ json!({ "source_id": SOURCE_ID, "format": FORMAT }),
268535 )
269536 .await;
270537 assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);
271- assert_eq!(res.body["job_id"], JOB_ID);
272538 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();
274544
275545 let seen = service.seen();
276546 assert_eq!(seen.len(), 1, "exactly one dispatch");
277547 assert_eq!(seen[0].capability, AI_PODCAST_SUBMIT_CAPABILITY);
278548 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+ );
279553 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+ );
281598 }
282599
283600 /// 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() {
285602 /// distinguish "absent" from "empty".
286603 #[tokio::test]
287604 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;
289606
290607 let res = submit(&app, &cookie, json!({ "source_id": SOURCE_ID })).await;
291608 assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);
@@ -299,375 +616,513 @@ async fn an_omitted_format_is_not_sent_at_all() {
299616 );
300617 }
301618
302-/// A blank source id is refused here, before the bridge: the service would
303-/// refuse it too, and a round trip to learn that is a round trip wasted.
619+/// A blank source id is refused here, before the bridge and before the row:
620+/// the service would refuse it too, and a round trip to learn that is a round
621+/// trip wasted.
304622 #[tokio::test]
305-async fn a_blank_source_id_is_refused_before_dispatch() {
306- let (service, app, cookie) = podcast_app().await;
623+async fn a_blank_source_id_is_refused_before_anything_is_written() {
624+ let (service, app, cookie, db) = podcast_app().await;
625+ let user = common::me_id(&app, &cookie).await;
307626
308627 let res = submit(&app, &cookie, json!({ "source_id": " " })).await;
309628 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
310629 assert!(service.seen().is_empty(), "nothing reaches the service");
630+ assert_eq!(rows_for(&db, &user).await, 0, "and no row is written");
311631 }
312632
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.
313637 #[tokio::test]
314-async fn a_status_read_round_trips_the_job_id() {
315- let (service, app, cookie) = podcast_app().await;
638+async fn a_running_report_lands_on_the_row_and_the_reads_stay_off_the_service() {
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+ );
316651
317- let res = common::send(
318- &app,
319- "GET",
320- &format!("/podcast/jobs/{JOB_ID}"),
321- Some(&cookie),
322- None,
323- )
324- .await;
652+ let res = status_of(&app, &cookie, &job_id).await;
325653 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);
327655 assert_eq!(res.body["state"], "running");
328656 assert_eq!(res.body["stage"], "tts");
329657 assert_eq!(res.body["progress"], 0.5);
330658 assert!(res.body["error_code"].is_null());
331659
332- let seen = service.seen();
333- assert_eq!(seen.len(), 1);
334- assert_eq!(seen[0].capability, AI_PODCAST_STATUS_CAPABILITY);
335- assert_eq!(seen[0].payload["job_id"], JOB_ID);
660+ let state: String = sqlx::query_scalar("SELECT state FROM podcast_job WHERE id = $1")
661+ .bind(uuid_of(&job_id))
662+ .fetch_one(&db)
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+ );
336671 }
337672
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.
338677 #[tokio::test]
339-async fn a_result_read_round_trips_the_artifacts() {
340- let (service, app, cookie) = podcast_app().await;
678+async fn a_finished_job_serves_the_uploaded_bytes() {
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+ );
341691
342- let res = common::send(
343- &app,
344- "GET",
345- &format!("/podcast/jobs/{JOB_ID}/result"),
346- Some(&cookie),
347- None,
692+ let bytes = episode_bytes();
693+ let answer = blob_upload(
694+ &service.conn,
695+ upload_frame(&job_id, AUDIO_NAME, AUDIO_TYPE, bytes.len()),
696+ &bytes,
348697 )
349698 .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;
350713 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
351- assert_eq!(res.body["job_id"], JOB_ID);
352- assert_eq!(res.body["audio_id"], AUDIO_ID);
353- assert_eq!(res.body["duration_secs"], 12.5);
354- assert_eq!(res.body["script_id"], "script-1");
355- assert_eq!(res.body["audio_ids"], json!([AUDIO_ID]));
356- assert_eq!(res.body["script_ids"], json!(["script-1"]));
357- assert_eq!(res.body["format"], "duz_okuma");
714+ assert_eq!(res.body["job_id"], job_id);
715+ assert_eq!(res.body["audio_id"], format!("podcast/{job_id}.mp3"));
716+ assert_eq!(res.body["duration_secs"], DURATION_SECS);
717+ assert_eq!(res.body["format"], FORMAT);
718+
719+ let (status, headers, body) = audio_of(&app, &cookie, &job_id).await;
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");
358725
359- let seen = service.seen();
360- assert_eq!(seen.len(), 1);
361- assert_eq!(seen[0].capability, AI_PODCAST_RESULT_CAPABILITY);
362- assert_eq!(seen[0].payload["job_id"], JOB_ID);
726+ assert_eq!(
727+ service.seen().len(),
728+ 1,
729+ "the upload and the reports are the service's own calls, not dispatches"
730+ );
363731 }
364732
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.
365736 #[tokio::test]
366-async fn a_cancel_round_trips_the_verdict() {
367- let (service, app, cookie) = podcast_app().await;
737+async fn a_cancel_of_a_live_job_stops_it() {
738+ let (service, app, cookie, db) = podcast_app().await;
739+ let job_id = submit_job(&app, &cookie).await;
368740
369- let res = common::send(
370- &app,
371- "POST",
372- &format!("/podcast/jobs/{JOB_ID}/cancel"),
373- Some(&cookie),
374- None,
375- )
376- .await;
741+ let res = cancel_of(&app, &cookie, &job_id).await;
377742 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);
379744 assert_eq!(res.body["cancelled"], true);
380745
381746 let seen = service.seen();
382- assert_eq!(seen.len(), 1);
383- assert_eq!(seen[0].capability, AI_PODCAST_CANCEL_CAPABILITY);
384- assert_eq!(seen[0].payload["job_id"], JOB_ID);
747+ assert_eq!(seen.len(), 2, "the cancel rode a second dispatch");
748+ assert_eq!(seen[1].capability, AI_PODCAST_CANCEL_CAPABILITY);
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");
385790 }
386791
387792 // --------------------------------------------------------------- refusals --
388793
389-/// With a bridge but no worker, every door answers the shared AI-unavailable
390-/// `503` — never a `500`, and never a dispatch into nothing. The audio door is
391-/// not in this list on purpose: it reads a local file and needs no service.
794+/// A submit that reaches no service writes nothing: the `503` is the whole
795+/// answer, so a poll can never find a job nobody will ever work on. Both
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.
392798 #[tokio::test]
393-async fn every_dispatching_door_is_503_with_no_worker_registered() {
394- let bridge = bridge().await;
395- let (app, _db) = common::app_with_ai(Some(bridge)).await;
799+async fn a_submit_that_reaches_no_service_is_503_and_writes_no_row() {
800+ let (app, db) = common::app_with_ai(Some(bridge().await)).await;
396801 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");
397807
398- let doors = [
399- ("POST", "/podcast/jobs".to_string(), true),
400- ("GET", format!("/podcast/jobs/{JOB_ID}"), false),
401- ("GET", format!("/podcast/jobs/{JOB_ID}/result"), false),
402- ("POST", format!("/podcast/jobs/{JOB_ID}/cancel"), false),
403- ];
404- for (method, uri, body) in doors {
405- let res = common::send(
406- &app,
407- method,
408- &uri,
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- }
808+ // The deployment never set `AI_QUIC_ADDR`: there is no bridge at all.
809+ let (app, db) = common::app_with_ai(None).await;
810+ let cookie = common::login(&app, "ali").await;
811+ let user = common::me_id(&app, &cookie).await;
812+ let res = submit(&app, &cookie, json!({ "source_id": SOURCE_ID })).await;
813+ assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body);
814+ assert_eq!(
815+ res.body["error"],
816+ "the AI service is not enabled on this deployment"
817+ );
818+ assert_eq!(rows_for(&db, &user).await, 0);
421819 }
422820
423-/// The same doors with no bridge at all (the deployment never set
424-/// `AI_QUIC_ADDR`): still a `503`, with the other message.
821+/// A service that refuses the job — at capacity, say — leaves the row as the
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.
425824 #[tokio::test]
426-async fn every_dispatching_door_is_503_when_the_bridge_is_off() {
427- let (app, _db) = common::app_with_ai(None).await;
825+async fn a_refusing_service_tombstones_the_row() {
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;
428838 let cookie = common::login(&app, "ali").await;
839+ let user = common::me_id(&app, &cookie).await;
429840
430841 let res = submit(&app, &cookie, json!({ "source_id": SOURCE_ID })).await;
431842 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");
432851 assert_eq!(
433- res.body["error"],
434- "the AI service is not enabled on this deployment"
852+ rows,
853+ vec![("failed".to_string(), Some("busy".to_string()))],
854+ "exactly one row, and it records the refusal"
435855 );
436856 }
437857
438-/// The service's own refusal code decides the HTTP status, so a client can
439-/// branch the same way it does on the bridge: `busy` is the service at
440-/// capacity (transient, `503`), `not_found` is a job it never had (`404`), and
441-/// `not_ready` is a job that has not finished (`409`).
858+/// A foreign job id reads as absent on every door — the same `404` an id that
859+/// never existed earns, so the answer leaks nothing about somebody else's job.
860+/// The cancel is the sharp one: it must not reach the service on a foreign id
861+/// either.
442862 #[tokio::test]
443-async fn a_service_refusal_keeps_its_code_and_status() {
444- let cases = [
445- ("busy", StatusCode::SERVICE_UNAVAILABLE),
446- ("not_found", StatusCode::NOT_FOUND),
447- ("not_ready", StatusCode::CONFLICT),
863+async fn another_users_job_reads_as_absent() {
864+ let (service, app, ali, _db) = podcast_app().await;
865+ let job_id = submit_job(&app, &ali).await;
866+ let seen_before = service.seen().len();
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")),
448874 ];
449- for (code, expected) in cases {
450- let bridge = bridge().await;
451- let _service = connect_service(
452- &bridge,
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);
875+ for (method, uri) in doors {
876+ let res = common::send(&app, method, &uri, Some(&ayse), None).await;
877+ assert_eq!(res.status, StatusCode::NOT_FOUND, "{method} {uri}: {}", res.body);
878+ assert_eq!(res.body["error"], "not found");
474879 }
880+ assert_eq!(
881+ service.seen().len(),
882+ seen_before,
883+ "nothing about a foreign job was dispatched"
884+ );
475885 }
476886
477-/// The nest sits behind the school's `chatbot` module — the AI package's only
478-/// module — exactly like `/chatbot` and `/rag`: with the module off the whole
479-/// URL space answers the disabled refusal, never a handler.
887+/// A terminal job past its retention window is gone for good: `410`, not the
888+/// `404` of a job that never existed — the row is still there, but nothing
889+/// about it is served any more.
480890 #[tokio::test]
481-async fn a_school_without_the_chatbot_module_has_no_podcast_nest() {
482- let bridge = bridge().await;
483- let (app, _db, tenants) = common::app_with_ai_tenants(Some(bridge)).await;
484- let cookie = common::login(&app, "ali").await;
891+async fn an_expired_job_reads_as_gone() {
892+ let (app, cookie, db) = app_without_ai().await;
893+ let user = common::me_id(&app, &cookie).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+}
485905
486- let mut modules = ModuleSet::all();
487- modules.remove(Module::Chatbot);
488- modules.validate().expect("the narrowed set is satisfiable");
489- tenants
490- .set_modules(&demo(), &modules)
491- .await
492- .expect("narrow the demo school");
906+/// A job nobody has updated inside its own ETA-scaled window is presented as
907+/// `failed`/`interrupted` — and the projection is read-side only: the row the
908+/// database holds still says `running`, so the service's next report (or its
909+/// own sweep) is what actually repairs it.
910+#[tokio::test]
911+async fn a_stale_job_reads_as_interrupted_but_the_row_is_untouched() {
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");
493924
494- let res = common::send(
495- &app,
496- "GET",
497- &format!("/podcast/jobs/{JOB_ID}"),
498- Some(&cookie),
499- None,
500- )
501- .await;
502- assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
503- assert_eq!(res.body["module"], "chatbot");
925+ let stored: String = sqlx::query_scalar("SELECT state FROM podcast_job WHERE id = $1")
926+ .bind(job)
927+ .fetch_one(&db)
928+ .await
929+ .expect("the row is still there");
930+ assert_eq!(stored, "running", "the projection wrote nothing");
504931 }
505932
506-/// Authentication is the whole gate for the dispatching doors: no cookie is a
507-/// `401`, not a dispatch under somebody else's name.
933+/// Neither the result nor the bytes exist before the job is done: both reading
934+/// doors answer `409` with `not_ready`, so a client branches on the code
935+/// instead of parsing the sentence.
508936 #[tokio::test]
509-async fn the_dispatching_doors_require_a_session() {
510- let (service, app, _cookie) = podcast_app().await;
937+async fn the_result_and_audio_doors_are_not_ready_before_done() {
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+ );
511949
512- let res = common::send(
513- &app,
514- "POST",
515- "/podcast/jobs",
516- None,
517- Some(json!({ "source_id": SOURCE_ID })),
518- )
519- .await;
520- assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{}", res.body);
521- assert!(service.seen().is_empty(), "an anonymous call dispatches nothing");
950+ let res = result_of(&app, &cookie, &job_id).await;
951+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
952+ assert_eq!(res.body["code"], "not_ready");
953+
954+ let (status, _, body) = audio_of(&app, &cookie, &job_id).await;
955+ assert_eq!(
956+ status,
957+ StatusCode::CONFLICT,
958+ "{:?}",
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");
522963 }
523964
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+ );
525982
526-/// Write `bytes` at `relative` under the demo school's blob directory and
527-/// return the absolute path it landed at.
528-fn school_file(relative: &str, bytes: &[u8]) -> std::path::PathBuf {
529- let path = common::blob_dir().join(relative);
530- std::fs::create_dir_all(path.parent().expect("parent dir")).expect("create the directory tree");
531- std::fs::write(&path, bytes).expect("write the file");
532- path
533-}
983+ let answer = capability_call(
984+ &service.conn,
985+ report_frame(&job_id, &user, "done", "", 1.0),
986+ )
987+ .await;
988+ assert_eq!(refusal_code(&answer), "audio_missing");
534989
535-/// One raw `GET /podcast/audio?path=…`.
536-async fn fetch_audio(
537- app: &Router,
538- cookie: Option<&str>,
539- path: &str,
540-) -> (StatusCode, axum::http::HeaderMap, Vec<u8>) {
541- let uri = format!("/podcast/audio?path={path}");
542- common::send_raw(app, "GET", &uri, cookie, None, Vec::new()).await
990+ let state: String = sqlx::query_scalar("SELECT state FROM podcast_job WHERE id = $1")
991+ .bind(uuid_of(&job_id))
992+ .fetch_one(&db)
993+ .await
994+ .expect("the row is still there");
995+ assert_eq!(state, "running", "the refusal wrote nothing");
543996 }
544997
545-/// The happy path: a file under the school's own directory streams back with
546-/// its bytes and an audio content type.
998+/// A `done` row whose blob is gone from the host answers `409 audio_missing`:
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.
5471002 #[tokio::test]
548-async fn the_audio_door_serves_a_file_under_the_schools_directory() {
549- let (app, _db) = common::app_and_db().await;
550- let cookie = common::login(&app, "ali").await;
551- let bytes = b"ID3\x03\x00\x00\x00fake-mp3-bytes".to_vec();
552- school_file("podcast/serve/ok.mp3", &bytes);
1003+async fn the_audio_door_reports_a_missing_blob() {
1004+ let (app, cookie, db) = app_without_ai().await;
1005+ let user = common::me_id(&app, &cookie).await;
1006+ let job = Uuid::now_v7();
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+ );
5531013
554- let (status, headers, body) = fetch_audio(&app, Some(&cookie), "podcast/serve/ok.mp3").await;
555- assert_eq!(status, StatusCode::OK);
556- assert_eq!(headers["content-type"], "audio/mpeg");
557- assert_eq!(headers["x-content-type-options"], "nosniff");
558- assert_eq!(headers["cache-control"], "private, no-store");
559- assert_eq!(body, bytes, "the bytes are the file's, unchanged");
1014+ let res = result_of(&app, &cookie, &job.to_string()).await;
1015+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1016+ assert_eq!(res.body["audio_id"], key);
1017+
1018+ let (status, _, body) = audio_of(&app, &cookie, &job.to_string()).await;
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");
5601027 }
5611028
562-/// Without a session the door is a `401` — and the very same path serves `200`
563-/// with one, so the refusal is authorization and not a missing file.
1029+/// The reading doors need no AI service at all: a finished job's row and its
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).
5641033 #[tokio::test]
565-async fn the_audio_door_refuses_an_unauthenticated_caller() {
566- let (app, _db) = common::app_and_db().await;
567- let cookie = common::login(&app, "ali").await;
568- let bytes = b"authorized-only".to_vec();
569- school_file("podcast/auth/only.mp3", &bytes);
1034+async fn the_reading_doors_need_no_service() {
1035+ let (app, cookie, db) = app_without_ai().await;
1036+ let user = common::me_id(&app, &cookie).await;
1037+ let job = Uuid::now_v7();
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");
5701046
571- let (anonymous, _, _) = fetch_audio(&app, None, "podcast/auth/only.mp3").await;
572- assert_eq!(anonymous, StatusCode::UNAUTHORIZED);
1047+ let res = result_of(&app, &cookie, &job.to_string()).await;
1048+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1049+ assert_eq!(res.body["audio_id"], key);
5731050
574- let (authorized, _, body) = fetch_audio(&app, Some(&cookie), "podcast/auth/only.mp3").await;
575- assert_eq!(authorized, StatusCode::OK);
1051+ let (status, headers, body) = audio_of(&app, &cookie, &job.to_string()).await;
1052+ assert_eq!(status, StatusCode::OK);
1053+ assert_eq!(headers["content-type"], AUDIO_TYPE);
5761054 assert_eq!(body, bytes);
5771055 }
5781056
579-/// A `..` segment is refused even though the file it names exists and the file
580-/// *inside* the school's directory is served — the refusal is the shape check,
581-/// not a missing target.
582-#[tokio::test]
583-async fn the_audio_door_refuses_a_dotdot_segment_to_an_existing_file() {
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.
1057+/// The old `GET /podcast/audio?path=…` door is gone with the caller-chosen path
1058+/// it resolved: it could not be owner-scoped, so the whole route is a `404` —
1059+/// the per-job door is the only audio door, and it streams what the school's
1060+/// own row names. The fixture proves the file exists, so the answer is the
1061+/// missing route, not a missing target.
6081062 #[tokio::test]
609-async fn the_audio_door_refuses_an_absolute_path_to_an_existing_file() {
610- let (app, _db) = common::app_and_db().await;
611- let cookie = common::login(&app, "ali").await;
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");
1063+async fn the_old_path_audio_door_is_gone() {
1064+ let (app, cookie, _db) = app_without_ai().await;
1065+ write_blob("podcast/escape/kept.mp3", b"bytes the old door would have served");
6141066
615- let (status, _, body) = fetch_audio(
1067+ let res = common::send(
6161068 &app,
1069+ "GET",
1070+ "/podcast/audio?path=podcast/escape/kept.mp3",
6171071 Some(&cookie),
618- outside.to_str().expect("a UTF-8 temp path"),
1072+ None,
6191073 )
6201074 .await;
621- assert_eq!(status, StatusCode::BAD_REQUEST, "{:?}", String::from_utf8_lossy(&body));
622- assert_ne!(body, b"not for the audio door");
1075+ assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);
6231076 }
6241077
625-/// A symlink inside the school's directory is refused when it resolves out of
626-/// it — the escape a plain "does the path start with the root" prefix check
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.
1078+/// Authentication is the whole gate on every door: no cookie is a `401`, not a
1079+/// handler — and not a dispatch under somebody else's name either.
6481080 #[tokio::test]
649-async fn the_audio_door_never_reaches_another_schools_file() {
650- let (app, _db) = common::app_and_db().await;
651- let cookie = common::login(&app, "ali").await;
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());
1081+async fn every_door_requires_a_session() {
1082+ let (service, app, _cookie, _db) = podcast_app().await;
1083+ let id = common::GHOST_ID;
6561084
657- let (status, _, _) = fetch_audio(&app, Some(&cookie), "podcast/ses/episode.mp3").await;
658- assert_eq!(status, StatusCode::NOT_FOUND);
1085+ let doors = [
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+ );
6591106 }
6601107
661-/// The door needs no AI bridge at all: a produced file is served with the
662-/// service long gone.
1108+/// The nest sits behind the school's `chatbot` module — the AI package's only
1109+/// module — exactly like `/chatbot` and `/rag`: with the module off the whole
1110+/// URL space answers the disabled refusal, never a handler.
6631111 #[tokio::test]
664-async fn the_audio_door_needs_no_service() {
665- let (app, _db) = common::app_with_ai(None).await;
1112+async fn a_school_without_the_chatbot_module_has_no_podcast_nest() {
1113+ let bridge = bridge().await;
1114+ let (app, _db, tenants) = common::app_with_ai_tenants(Some(bridge)).await;
6661115 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);
6691116
670- let (status, _, body) = fetch_audio(&app, Some(&cookie), "podcast/offline/episode.mp3").await;
671- assert_eq!(status, StatusCode::OK);
672- assert_eq!(body, bytes);
1117+ let mut modules = ModuleSet::all();
1118+ modules.remove(Module::Chatbot);
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");
6731128 }