forge
Explore
Log in

Don't you dare go Hollow

merge: πŸ”€ lane/insight + lane/podcast β€” the zeka insight nest and the podcast relay

Browse files at this commit

e66cef0f7d57d1506006e23a614b96a3e88a1d2bAhmet Kaan GümüşParent: b0b5e0c5a5a483
Both lanes append to constant.rs/lib.rs/ai+web mod.rs in disjoint regions; the two
conflicts were adjacent-line appends, resolved by keeping both sides. tests/integration.rs
MODULE_PREFIXES carries both new nest rows (renamed 23 -> 25) from lane/insight.
README.mdmodified+5 -0
@@ -1400,6 +1400,11 @@ window filtering, before paging; negative values are a `400` naming the field.
1400 | POST | `/payments/reversals` | manager | Undo a line entered by mistake, for its exact amount β€” the line itself stays, with an opposing one appended beside it. Only a `charge` or a `refund` may be reversed (`400` otherwise): a mistaken payment is corrected with a refund, so money leaving the school is always spelled the one way. **Idempotent** β€” a line has at most one reversal, however often the call is retried. |1400 | POST | `/payments/reversals` | manager | Undo a line entered by mistake, for its exact amount β€” the line itself stays, with an opposing one appended beside it. Only a `charge` or a `refund` may be reversed (`400` otherwise): a mistaken payment is corrected with a refund, so money leaving the school is always spelled the one way. **Idempotent** β€” a line has at most one reversal, however often the call is retried. |
1401 | GET | `/payments/statement/me` | student | The caller's own statement. The per-charge rows are paged via `?limit=&offset=` (omit `limit` for all of them); `balance_minor` is the same on every page, because the fold behind it reads every line. |1401 | GET | `/payments/statement/me` | student | The caller's own statement. The per-charge rows are paged via `?limit=&offset=` (omit `limit` for all of them); `balance_minor` is the same on every page, because the fold behind it reads every line. |
1402 | GET | `/payments/statement/{user}` | manager | One student's statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is overdue. Own record always; otherwise manager+ or a parent link (a teacher gets a `403`). The rows are paged via `?limit=&offset=`; `balance_minor` is the same on every page. |1402 | GET | `/payments/statement/{user}` | manager | One student's statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is overdue. Own record always; otherwise manager+ or a parent link (a teacher gets a `403`). The rows are paged via `?limit=&offset=`; `balance_minor` is the same on every page. |
1403+| GET | `/podcast/audio` | student | Stream one produced audio file. `path` is the `audio_id` `podcast.result` answered, resolved under **this caller's school** output directory β€” the same directory the service's `PODCAST_OUTPUT_ROOT` points at β€” and streamed in 64 KiB chunks, so a long episode costs the backend a bounded buffer rather than its whole length in memory. |
1404+| POST | `/podcast/jobs` | student | Start one podcast job. Answers `202` with the service's receipt the moment the service accepts it; the pipeline then runs in the service's own worker pool, so poll `GET /jobs/{id}` for progress. |
1405+| GET | `/podcast/jobs/{id}` | student | One job's current state. Poll this; the answer is the service's own snapshot. |
1406+| POST | `/podcast/jobs/{id}/cancel` | student | Cancel one job. `cancelled` says whether *this call* stopped work β€” a job that had already finished, or was already cancelled, answers `false` and is not an error. |
1407+| GET | `/podcast/jobs/{id}/result` | student | A finished job's artifacts β€” above all the `audio_id` the audio door streams. A job that has not finished yet is refused by the service with `not_ready` (409); one it has never heard of with `not_found` (404). |
1403 | POST | `/pomodoro/finish` | student | Finish the running pomodoro session, closing it with a server-stamped instant (`409` when nothing is running); answers `counted` β€” whether it moved the badge counters (ran at least `pomodoro.min_counted_ms`, within that UTC day's `pomodoro.max_counted_per_day`). |1408 | POST | `/pomodoro/finish` | student | Finish the running pomodoro session, closing it with a server-stamped instant (`409` when nothing is running); answers `counted` β€” whether it moved the badge counters (ran at least `pomodoro.min_counted_ms`, within that UTC day's `pomodoro.max_counted_per_day`). |
1404 | GET | `/pomodoro/me` | student | The caller's own pomodoro log, newest first β€” the running session (if any) included (`finished_at: null`) β€” plus `total_focus_ms`, the unpaged sum of finished-session durations. Paged via `?limit=&offset=` (omit `limit` for the whole log). |1409 | GET | `/pomodoro/me` | student | The caller's own pomodoro log, newest first β€” the running session (if any) included (`finished_at: null`) β€” plus `total_focus_ms`, the unpaged sum of finished-session durations. Paged via `?limit=&offset=` (omit `limit` for the whole log). |
1405 | POST | `/pomodoro/start` | student | Start a pomodoro focus session. Students only. The instant is stamped by the server clock β€” clients never supply it. Always succeeds for a student: a dangling unfinished session (the browser died mid-timer) is discarded and replaced, so there is no way to lock yourself out of starting. The frontend runs the visible countdown and the break rhythm; the backend records only the focus stint. The body is optional and names the stint: a `label` rides the response and every log it lists in β€” a blank or absent body starts an unnamed stint, an over-long label is `400`. |1410 | POST | `/pomodoro/start` | student | Start a pomodoro focus session. Students only. The instant is stamped by the server clock β€” clients never supply it. Always succeeds for a student: a dangling unfinished session (the browser died mid-timer) is discarded and replaced, so there is no way to lock yourself out of starting. The frontend runs the visible countdown and the break rhythm; the backend records only the focus stint. The body is optional and names the stint: a `label` rides the response and every log it lists in β€” a blank or absent body starts an unnamed stint, an over-long label is `400`. |
src/ai/mod.rsmodified+5 -1
@@ -16,18 +16,22 @@
16 //! * [`chat`] β€” the JSON payloads carried for the `chat.reply` capability16 //! * [`chat`] β€” the JSON payloads carried for the `chat.reply` capability
17 //! * [`rag`] β€” the `rag.index` payloads, and the course-note dispatch behind them17 //! * [`rag`] β€” the `rag.index` payloads, and the course-note dispatch behind them
18 //! * [`rag_chat`] β€” the `rag.chat` payloads: a scoped question and the citations behind its answer18 //! * [`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
19 //! * [`server`] β€” the listener, handshake, and [`server::AiBridge::dispatch`]20 //! * [`server`] β€” the listener, handshake, and [`server::AiBridge::dispatch`]
20 //! * [`registry`] β€” who is connected here, and who gets the next request21 //! * [`registry`] β€” who is connected here, and who gets the next request
21 //! * [`tls`] β€” the listener's certificate22 //! * [`tls`] β€” the listener's certificate
22 //!23 //!
23 //! The transport is generic; the features land on top of it. So far that is24 //! The transport is generic; the features land on top of it. So far that is
24 //! the chatbot (`web::chatbot`), which routes on the `chat.reply` capability,25 //! the chatbot (`web::chatbot`), which routes on the `chat.reply` capability,
25-//! and course-note indexing (`web::course_notes`), which routes on `rag.index`.26+//! 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.
26 29
27 pub mod api;30 pub mod api;
28 pub mod chat;31 pub mod chat;
29 pub mod error;32 pub mod error;
30 pub mod insight;33 pub mod insight;
34+pub mod podcast;
31 pub mod protocol;35 pub mod protocol;
32 pub mod rag;36 pub mod rag;
33 pub mod rag_chat;37 pub mod rag_chat;
src/ai/podcast.rsadded+233 -0
@@ -0,0 +1,233 @@
1+//! Payload contract for the `podcast.*` capabilities, and the dispatch behind
2+//! them.
3+//!
4+//! 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.
10+//!
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.
18+//!
19+//! Tenancy is the transport's job: [`crate::ai::server`] stamps the caller's
20+//! school onto every `hab/2` request and refuses an answer that does not echo
21+//! it, so a worker registered by one school never answers another's call β€”
22+//! the wall holds even though the job records themselves live outside the
23+//! backend's databases.
24+//!
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`].
32+
33+use serde::de::DeserializeOwned;
34+use serde::{Deserialize, Serialize};
35+
36+use crate::ai::{AiBridge, AiError};
37+use crate::tenant::Slug;
38+
39+/// The capability strings, re-exported so a reader of the payload contract
40+/// finds them next to the payloads β€” the same shape as
41+/// [`crate::ai::rag`](crate::ai::rag).
42+pub use crate::constant::{
43+ AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_RESULT_CAPABILITY, AI_PODCAST_STATUS_CAPABILITY,
44+ AI_PODCAST_SUBMIT_CAPABILITY,
45+};
46+
47+/// What the backend asks a podcast service to start.
48+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
49+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.
53+ 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")]
60+ pub format: Option<String>,
61+}
62+
63+/// The receipt for an accepted job, echoed straight to the caller.
64+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
65+pub struct PodcastSubmitReply {
66+ /// The id the service minted for the job. Every later call names it.
67+ pub job_id: String,
68+ /// The job's state right after submission (`queued`).
69+ pub state: String,
70+ /// The service's own estimate of how long the job will take, in seconds.
71+ pub eta_secs: i64,
72+}
73+
74+/// What the backend asks about one job's progress.
75+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76+pub struct PodcastStatusPayload {
77+ pub job_id: String,
78+}
79+
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.
98+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
99+pub struct PodcastResultPayload {
100+ pub job_id: String,
101+}
102+
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.
106+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
107+pub struct PodcastResultReply {
108+ 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]`.
119+ #[serde(default)]
120+ pub audio_ids: Vec<String>,
121+ /// One entry per script the audio was aligned to.
122+ #[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,
132+}
133+
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.
137+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
138+pub struct PodcastCancelReply {
139+ pub job_id: String,
140+ pub cancelled: bool,
141+}
142+
143+/// Start one job. `Err` is a short, stable code β€” see [`failure_code`].
144+pub async fn submit(
145+ bridge: &AiBridge,
146+ slug: &Slug,
147+ payload: PodcastSubmitPayload,
148+) -> Result<PodcastSubmitReply, String> {
149+ dispatch(bridge, slug, AI_PODCAST_SUBMIT_CAPABILITY, payload).await
150+}
151+
152+/// Read one job's progress.
153+pub async fn status(
154+ bridge: &AiBridge,
155+ slug: &Slug,
156+ payload: PodcastStatusPayload,
157+) -> Result<PodcastStatusReply, String> {
158+ dispatch(bridge, slug, AI_PODCAST_STATUS_CAPABILITY, payload).await
159+}
160+
161+/// Read one finished job's artifacts.
162+pub async fn result(
163+ bridge: &AiBridge,
164+ slug: &Slug,
165+ payload: PodcastResultPayload,
166+) -> Result<PodcastResultReply, String> {
167+ dispatch(bridge, slug, AI_PODCAST_RESULT_CAPABILITY, payload).await
168+}
169+
170+/// Cancel one job.
171+pub async fn cancel(
172+ bridge: &AiBridge,
173+ slug: &Slug,
174+ payload: PodcastCancelPayload,
175+) -> Result<PodcastCancelReply, String> {
176+ dispatch(bridge, slug, AI_PODCAST_CANCEL_CAPABILITY, payload).await
177+}
178+
179+/// One `podcast.*` round trip: encode, dispatch, decode. Every capability
180+/// travels this path, so the encode/decode failure vocabulary is written once.
181+///
182+/// The reply is decoded into the *typed* contract rather than handed back as
183+/// [`serde_json::Value`]: the service is a trust boundary, and a field the
184+/// backend then acts on (above all `audio_id`, which becomes a path under a
185+/// school's files directory) must exist and be a string before anything uses
186+/// it.
187+async fn dispatch<P, R>(
188+ bridge: &AiBridge,
189+ slug: &Slug,
190+ capability: &str,
191+ payload: P,
192+) -> Result<R, String>
193+where
194+ P: Serialize,
195+ R: DeserializeOwned,
196+{
197+ let payload = serde_json::to_value(payload).map_err(|err| {
198+ tracing::error!("could not encode a {capability} request: {err}");
199+ "internal".to_string()
200+ })?;
201+
202+ let raw = bridge
203+ .dispatch(slug, capability, payload)
204+ .await
205+ .map_err(failure_code)?;
206+
207+ serde_json::from_value(raw).map_err(|err| {
208+ tracing::warn!("AI service answered with an unreadable {capability} payload: {err}");
209+ "bad_reply".to_string()
210+ })
211+}
212+
213+/// A dispatch failure as a short, stable code the web layer maps to a status.
214+/// Mirrors `web::chatbot`'s and `ai::rag_chat`'s helpers.
215+fn failure_code(err: AiError) -> String {
216+ match err {
217+ AiError::NoWorker(_) | AiError::Setup(_) => "unavailable".to_string(),
218+ AiError::Busy(_) => "busy".to_string(),
219+ AiError::Timeout(_) => "timed_out".to_string(),
220+ AiError::Transport(_) => "transport".to_string(),
221+ AiError::Protocol(_) | AiError::IdMismatch { .. } => "protocol".to_string(),
222+ // The service's own verdict. Kept verbatim (the domain trims it) so a
223+ // service can define codes the backend has never heard of.
224+ AiError::Remote { code, message } => {
225+ tracing::warn!("AI podcast service refused the request: {code}: {message}");
226+ if code.trim().is_empty() {
227+ "service_error".to_string()
228+ } else {
229+ code
230+ }
231+ }
232+ }
233+}
src/constant.rsmodified+29 -0
@@ -640,6 +640,35 @@ pub const AI_INSIGHT_REFRESH_TIMEOUT_SECS: u64 = 300;
640 /// anyone answer it, so the same staleness window applies.640 /// anyone answer it, so the same staleness window applies.
641 pub const RAG_PENDING_STALE_SECS: i64 = CHATBOT_PENDING_STALE_SECS;641 pub const RAG_PENDING_STALE_SECS: i64 = CHATBOT_PENDING_STALE_SECS;
642 642
643+// ---- podcast ---------------------------------------------------------------
644+//
645+// The podcast service turns one stored source into an audio episode, which is
646+// a *job*: submitted, polled, collected, and maybe cancelled β€” the service
647+// owns the record, and the backend relays each HTTP call to the worker that
648+// declares the matching capability. All four capabilities answer immediately
649+// (the pipeline runs in the service's own pool), so unlike `rag.index` and
650+// `rag.chat` none of them needs a per-capability deadline: the bridge's
651+// ordinary request timeout already covers a job-store read.
652+
653+/// The capability an AI service declares to accept a podcast job. The backend
654+/// dispatches on it from `POST /podcast/jobs`, and the service mints the job
655+/// id every other `podcast.*` call then names.
656+pub const AI_PODCAST_SUBMIT_CAPABILITY: &str = "podcast.submit";
657+
658+/// The capability an AI service declares to report one podcast job's state,
659+/// read back by `GET /podcast/jobs/{id}`.
660+pub const AI_PODCAST_STATUS_CAPABILITY: &str = "podcast.status";
661+
662+/// The capability an AI service declares to hand back a finished job's
663+/// artifacts β€” above all the `audio_id` the `/podcast/audio` door streams.
664+pub const AI_PODCAST_RESULT_CAPABILITY: &str = "podcast.result";
665+
666+/// The capability an AI service declares to cancel one podcast job. Its own
667+/// capability rather than a flag on submit: the cancel is a write on the
668+/// service's queue, and the capability is what decides whether a deployment
669+/// can offer the door at all.
670+pub const AI_PODCAST_CANCEL_CAPABILITY: &str = "podcast.cancel";
671+
643 /// The most `(sΔ±nΔ±f, ders)` scope pairs one `rag.chat` request may carry. The672 /// The most `(sΔ±nΔ±f, ders)` scope pairs one `rag.chat` request may carry. The
644 /// corpus is routed by the **pair** β€” a grade and a subject list sent673 /// corpus is routed by the **pair** β€” a grade and a subject list sent
645 /// separately would cross-product into combinations the asker never named β€” so674 /// separately would cross-product into combinations the asker never named β€” so
src/lib.rsmodified+3 -0
@@ -58,6 +58,7 @@ use crate::web::module_gate::gate;
58 (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner β€” nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed β€” or its name cleared β€” with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn β€” it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion β€” both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) β€” both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` β€” the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"),58 (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner β€” nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed β€” or its name cleared β€” with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn β€” it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion β€” both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) β€” both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` β€” the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"),
59 (name = "rag", description = "The course-note RAG: its own nest, threads and tables, relayed through the same QUIC bridge as the chatbot β€” RAG is not folded into the chatbot's storage. Every authenticated role may ask (parents included) and every thread is private to its owner. Every question is scoped server-side to the asker's own `(sΔ±nΔ±f, ders)` pairs, derived on each request from their live memberships β€” their şubeler' instances, a linked parent's children, and the school-wide club/etΓΌt memberships they hold (which scope the subject across grades, `sinif: null`) β€” never from the body, so a caller cannot widen their own retrieval; a scope past `MAX_RAG_SCOPE_PAIRS` pairs is refused (400) rather than narrowed. A RAG thread draws on the school's existing AI thread seats (`max_chatbot_threads`, the same seat count the chatbot nest uses, one pool per user), its prompts and answers are bounded by `max_chatbot_message_len`, and its per-minute tier is its own: `RATE_LIMIT_RAG_PER_MINUTE` (default 6, `0` disables the tier; 429 with `Retry-After`). Sending is asynchronous exactly as the chatbot's is: `POST /rag/threads/{id}/messages` writes the turn plus a `pending` assistant row and answers `202`, then poll `GET /rag/threads/{id}/messages/{mid}` or open its `/stream` (SSE `delta`s then `done`/`error`). `503` when no AI service offers `rag.chat`, with nothing written. An answer may abstain β€” `abstained: true` with a `reason` (`guard_*`, `insufficient_data`, `model_abstained`) is a complete, successful turn, not an error β€” and carries its `citations`, up to `MAX_RAG_CITATIONS` per answer and at most `MAX_RAG_CITATION_PAGES` pages each (a service reply past either cap fails the turn whole). Each citation's corpus `doc_id` is resolved to the course-note file that owns it (`file`, `null` when no file the asker may view claims that document) beside the pages and retrieval span ids behind it."),59 (name = "rag", description = "The course-note RAG: its own nest, threads and tables, relayed through the same QUIC bridge as the chatbot β€” RAG is not folded into the chatbot's storage. Every authenticated role may ask (parents included) and every thread is private to its owner. Every question is scoped server-side to the asker's own `(sΔ±nΔ±f, ders)` pairs, derived on each request from their live memberships β€” their şubeler' instances, a linked parent's children, and the school-wide club/etΓΌt memberships they hold (which scope the subject across grades, `sinif: null`) β€” never from the body, so a caller cannot widen their own retrieval; a scope past `MAX_RAG_SCOPE_PAIRS` pairs is refused (400) rather than narrowed. A RAG thread draws on the school's existing AI thread seats (`max_chatbot_threads`, the same seat count the chatbot nest uses, one pool per user), its prompts and answers are bounded by `max_chatbot_message_len`, and its per-minute tier is its own: `RATE_LIMIT_RAG_PER_MINUTE` (default 6, `0` disables the tier; 429 with `Retry-After`). Sending is asynchronous exactly as the chatbot's is: `POST /rag/threads/{id}/messages` writes the turn plus a `pending` assistant row and answers `202`, then poll `GET /rag/threads/{id}/messages/{mid}` or open its `/stream` (SSE `delta`s then `done`/`error`). `503` when no AI service offers `rag.chat`, with nothing written. An answer may abstain β€” `abstained: true` with a `reason` (`guard_*`, `insufficient_data`, `model_abstained`) is a complete, successful turn, not an error β€” and carries its `citations`, up to `MAX_RAG_CITATIONS` per answer and at most `MAX_RAG_CITATION_PAGES` pages each (a service reply past either cap fails the turn whole). Each citation's corpus `doc_id` is resolved to the course-note file that owns it (`file`, `null` when no file the asker may view claims that document) beside the pages and retrieval span ids behind it."),
60 (name = "insights", description = "ZEKA's computed student insights β€” the `hezarfen_zeka` AI service dials in over the same QUIC bridge as the chatbot and writes its own `zeka_*` rows into each school's database, so this nest reads what it wrote and asks it to compute on demand; the backend never composes an insight row itself. `GET /insights/me` is the caller's own view: a student's summary, their own recommendation cards and their segment profile β€” and **never** the attention list about themselves, which is a teacher's tool and is not returned to a student or to a linked parent. `GET /insights/students/{id}` is the observer's view of one student β€” teacher+ narrowed to the students they actually reach through a shared classΓ—course instance, or a parent holding a live link β€” adding the attention list and the caller's own cards about that student; anyone else reads `404`, never `403`. `POST /insights/students/{id}` and `POST /insights/refresh` (manager+) queue a recompute through the bridge and answer `202` β€” the compute lands in the service's own rows, so a client polls the read routes; `GET /insights/runs` (manager+) is the run ledger, newest first. Both dispatch doors answer `503` when no service offers the capability, and nothing is queued. Expired and dismissed cards are filtered out of every card read, segment rows below 30 answers (`confidence: none`) are filtered out of every profile read, and a card's `about` is never returned to a student caller."),60 (name = "insights", description = "ZEKA's computed student insights β€” the `hezarfen_zeka` AI service dials in over the same QUIC bridge as the chatbot and writes its own `zeka_*` rows into each school's database, so this nest reads what it wrote and asks it to compute on demand; the backend never composes an insight row itself. `GET /insights/me` is the caller's own view: a student's summary, their own recommendation cards and their segment profile β€” and **never** the attention list about themselves, which is a teacher's tool and is not returned to a student or to a linked parent. `GET /insights/students/{id}` is the observer's view of one student β€” teacher+ narrowed to the students they actually reach through a shared classΓ—course instance, or a parent holding a live link β€” adding the attention list and the caller's own cards about that student; anyone else reads `404`, never `403`. `POST /insights/students/{id}` and `POST /insights/refresh` (manager+) queue a recompute through the bridge and answer `202` β€” the compute lands in the service's own rows, so a client polls the read routes; `GET /insights/runs` (manager+) is the run ledger, newest first. Both dispatch doors answer `503` when no service offers the capability, and nothing is queued. Expired and dismissed cards are filtered out of every card read, segment rows below 30 answers (`confidence: none`) are filtered out of every profile read, and a card's `about` is never returned to a student caller."),
61+ (name = "podcast", description = "Podcast generation, relayed through the same QUIC bridge as the chatbot and the RAG nest β€” the backend owns authentication and the HTTP surface, the podcast service owns the job. `POST /podcast/jobs` (`{source_id, format?}`) starts one and answers `202` with the service's `{job_id, state, eta_secs}` receipt; `GET /podcast/jobs/{id}` polls its `{state, stage, progress, error_code}`, `GET /podcast/jobs/{id}/result` collects a finished job's `{audio_id, duration_secs, script_id, audio_ids, script_ids, format}` (`409` while it is still running), and `POST /podcast/jobs/{id}/cancel` asks the service to stop it (`cancelled` is \"this call stopped work\", so a finished job answers `false`). Each door refuses `503` when no connected service declares its capability, and each relays the service's own refusal code (`not_found`, `not_ready`, `busy`, `llm_unavailable`, …) with a matching status. The produced audio never crosses the bridge: `audio_id` is a path relative to the school's own output directory under `FILES_PATH` (the service's `PODCAST_OUTPUT_ROOT` points there), and `GET /podcast/audio?path=…` streams those bytes β€” refusing absolute paths, `.`/`..` segments, backslashes and symlinks that resolve outside the school's directory with `400`, so one school can never read another's episode even knowing its path. **None of these doors writes a row**: the job record and its files live in the service. Gated by the school's `chatbot` module (the AI package's only module), like `/chatbot` and `/rag`; any authenticated member of the school may call them, and the school wall is the bridge's (`hab/2` refuses an answer that does not echo the caller's school). What the backend cannot judge is *which* sources a caller may narrate β€” `source_id` is the service's own record id, and no backend query can say what it names."),
61 (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` β€” returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names β€” `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) β€” role management can no longer lock everyone out, not even when two admins…, accent color `palette_color` as `#rrggbb` β€” returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names β€” `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) β€” role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink β€” a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` β€” the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only β€” never a class's creator or homeroom teacher β€” capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it β€” a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` β€” **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it β€”, `pomodoro_finished_total`, `pomodoro_focus_ms_total` β€” the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair β€” a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade β†’ un-grade β†’ regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pendingβ†’approved transition β€” a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's β€” but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` β€” the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** β€” no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile β€” except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created β€” and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile β€” every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two β€” `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `display_name` (≀ 50) and `bio` (≀ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only β€” no SVG, whose script can run when the bytes render inline school-wide β€” at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` β€” or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id β€” (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"),62 (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` β€” returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names β€” `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) β€” role management can no longer lock everyone out, not even when two admins…, accent color `palette_color` as `#rrggbb` β€” returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names β€” `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) β€” role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink β€” a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` β€” the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only β€” never a class's creator or homeroom teacher β€” capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it β€” a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` β€” **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it β€”, `pomodoro_finished_total`, `pomodoro_focus_ms_total` β€” the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair β€” a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade β†’ un-grade β†’ regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pendingβ†’approved transition β€” a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's β€” but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` β€” the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** β€” no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile β€” except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created β€” and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile β€” every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two β€” `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `display_name` (≀ 50) and `bio` (≀ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only β€” no SVG, whose script can run when the bytes render inline school-wide β€” at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` β€” or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id β€” (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"),
62 (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete β€” at most 10 per note, each at most the school's settings-configured `max_file_bytes`). Every authenticated role keeps notes, `parent` included: a note is private own-scoped data with no other reader, and the routes carry **no role bar at all** β€” ownership is the whole authorization, so nobody but the owner ever reaches a note or its files (a stranger's id is a `404`, never a `403`). That is deliberate and it is the fix for a real defect: while these routes required `student`, a demotion to `parent` locked the owner out of their own notes for good, and since nothing else in the crate reads a note and no route cascades one, the rows and their on-disk blobs became unreachable and undeletable by everybody. Own-scoped personal data is not confiscated by a role change"),63 (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete β€” at most 10 per note, each at most the school's settings-configured `max_file_bytes`). Every authenticated role keeps notes, `parent` included: a note is private own-scoped data with no other reader, and the routes carry **no role bar at all** β€” ownership is the whole authorization, so nobody but the owner ever reaches a note or its files (a stranger's id is a `404`, never a `403`). That is deliberate and it is the fix for a real defect: while these routes required `student`, a demotion to `parent` locked the owner out of their own notes for good, and since nothing else in the crate reads a note and no route cascades one, the rows and their on-disk blobs became unreachable and undeletable by everybody. Own-scoped personal data is not confiscated by a role change"),
63 (name = "messages", description = "One-to-one mail-style messages, upward only below staff: a student or parent writes to a teacher, manager or admin (parents included β€” messaging is the one place a parent writes) and never to another student or parent (`403`), while staff write to anyone, each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread β€” with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"),64 (name = "messages", description = "One-to-one mail-style messages, upward only below staff: a student or parent writes to a teacher, manager or admin (parents included β€” messaging is the one place a parent writes) and never to another student or parent (`403`), while staff write to anyone, each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread β€” with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"),
@@ -165,6 +166,8 @@ pub fn build_router(state: AppState) -> Router {
165 .nest(166 .nest(
166 "/insights",167 "/insights",
167 gate(web::insights::routes(), &state, Module::Chatbot),168 gate(web::insights::routes(), &state, Module::Chatbot),
169+ "/podcast",
170+ gate(web::podcast::routes(), &state, Module::Chatbot),
168 )171 )
169 .nest("/users", web::users::routes())172 .nest("/users", web::users::routes())
170 .nest("/notes", gate(web::notes::routes(), &state, Module::Notes))173 .nest("/notes", gate(web::notes::routes(), &state, Module::Notes))
src/web/mod.rsmodified+1 -0
@@ -31,6 +31,7 @@ pub mod module_gate;
31 pub mod modules;31 pub mod modules;
32 pub mod notes;32 pub mod notes;
33 pub mod payments;33 pub mod payments;
34+pub mod podcast;
34 pub mod pomodoro;35 pub mod pomodoro;
35 pub mod questions;36 pub mod questions;
36 pub mod rag;37 pub mod rag;
src/web/podcast.rsadded+540 -0
@@ -0,0 +1,540 @@
1+//! The podcast nest: browser ⇄ backend ⇄ the podcast service (over the QUIC
2+//! bridge), plus the door that hands back the produced audio.
3+//!
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.
14+//!
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.
25+//!
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.
29+//!
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.
34+//!
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` refuses an answer that does not echo the school). It cannot scope
39+//! *which* sources a caller may narrate: `source_id` is the service's own
40+//! record, and no backend query can say what it names. That is a property of
41+//! the wire the two sides share, not an oversight β€” the service resolves the
42+//! id against the shared media volume and the backend enforces the tenant.
43+
44+use axum::Json;
45+use axum::body::{Body, Bytes};
46+use axum::extract::{Path, Query};
47+use axum::http::HeaderValue;
48+use axum::http::StatusCode;
49+use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS};
50+use axum::response::{IntoResponse, Response};
51+use serde::{Deserialize, Serialize};
52+use serde_json::json;
53+use tokio::io::AsyncReadExt;
54+use tokio::sync::mpsc;
55+use tokio_stream::Stream;
56+use tokio_stream::wrappers::ReceiverStream;
57+use utoipa::{IntoParams, ToSchema};
58+use utoipa_axum::router::OpenApiRouter;
59+use utoipa_axum::routes;
60+
61+use crate::ai::AiBridge;
62+use crate::ai::podcast::{
63+ self, PodcastCancelPayload, PodcastCancelReply, PodcastResultPayload, PodcastResultReply,
64+ PodcastStatusPayload, PodcastStatusReply, PodcastSubmitPayload, PodcastSubmitReply,
65+};
66+use crate::constant::{
67+ AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_RESULT_CAPABILITY, AI_PODCAST_STATUS_CAPABILITY,
68+ AI_PODCAST_SUBMIT_CAPABILITY,
69+};
70+use crate::error::{AppError, ErrorResponse, ValidationError};
71+use crate::state::AppState;
72+use crate::web::tenant_state::{SchoolSlug, State};
73+
74+use super::{CurrentUser, ai_unavailable};
75+
76+/// How much of the audio is read per chunk, and how many chunks the body may
77+/// have in flight. 4 Γ— 64 KiB is the whole memory ceiling one audio stream
78+/// costs, however large the file behind it.
79+const AUDIO_CHUNK_BYTES: usize = 64 * 1024;
80+const AUDIO_CHUNKS_IN_FLIGHT: usize = 4;
81+
82+pub fn routes() -> OpenApiRouter<AppState> {
83+ OpenApiRouter::new()
84+ .routes(routes!(submit))
85+ .routes(routes!(status))
86+ .routes(routes!(result))
87+ .routes(routes!(cancel))
88+ .routes(routes!(audio))
89+}
90+
91+#[derive(Deserialize, ToSchema)]
92+struct SubmitPodcast {
93+ /// The backend's id for the source to narrate β€” a course note's id, never
94+ /// a path. Sent on as the service's `source_id`.
95+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
96+ source_id: String,
97+ /// Which narration to produce: `duz_okuma` (the service's default),
98+ /// `tek_ogretici` or `ogrenci_hoca`. The two latter need the service's LLM
99+ /// key and are refused with `llm_unavailable` (409) without it.
100+ #[schema(example = "duz_okuma")]
101+ #[serde(default)]
102+ format: Option<String>,
103+}
104+
105+/// The service's receipt for an accepted job, passed through verbatim.
106+#[derive(Serialize, ToSchema)]
107+struct JobReceipt {
108+ /// The job id the service minted β€” every other door names it.
109+ job_id: String,
110+ /// `queued` on a fresh job.
111+ state: String,
112+ /// The service's own estimate of the job's duration, in seconds.
113+ eta_secs: i64,
114+}
115+
116+/// One job's state, passed through verbatim.
117+#[derive(Serialize, ToSchema)]
118+struct JobStatus {
119+ job_id: String,
120+ /// `queued`, `running`, `done`, `failed` or `cancelled`.
121+ state: String,
122+ /// The pipeline stage the job is in.
123+ stage: String,
124+ /// Fraction complete, `0.0..=1.0`.
125+ progress: f64,
126+ /// Set only once the job failed.
127+ error_code: Option<String>,
128+}
129+
130+/// A finished job's artifacts, passed through verbatim.
131+#[derive(Serialize, ToSchema)]
132+struct JobArtifacts {
133+ job_id: String,
134+ /// The produced audio, as a path relative to the school's podcast output
135+ /// root β€” feed it straight to `GET /podcast/audio?path=…`.
136+ #[schema(example = "ses/duz_okuma/019732e3-7b00-7000-8000-00000000dead/episode.mp3")]
137+ audio_id: String,
138+ duration_secs: f64,
139+ script_id: String,
140+ /// One entry per produced chapter; usually `[audio_id]`.
141+ audio_ids: Vec<String>,
142+ /// One entry per script the audio was aligned to.
143+ script_ids: Vec<String>,
144+ format: String,
145+}
146+
147+/// The verdict on a cancel.
148+#[derive(Serialize, ToSchema)]
149+struct CancelVerdict {
150+ job_id: String,
151+ /// Whether *this call* cancelled something β€” `false` for a job that had
152+ /// already finished or had already been cancelled.
153+ cancelled: bool,
154+}
155+
156+/// Start one podcast job. Answers `202` with the service's receipt the moment
157+/// the service accepts it; the pipeline then runs in the service's own worker
158+/// pool, so poll `GET /jobs/{id}` for progress.
159+#[utoipa::path(
160+ post,
161+ path = "/jobs",
162+ tag = "podcast",
163+ security(("session_cookie" = [])),
164+ request_body = SubmitPodcast,
165+ responses(
166+ (status = 202, description = "The job is queued; `job_id` names it from here on", body = JobReceipt),
167+ (status = 400, description = "Empty `source_id`, or a `format` the service does not serve", body = ErrorResponse),
168+ (status = 401, description = "Not authenticated", body = ErrorResponse),
169+ (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing", body = ErrorResponse),
170+ (status = 503, description = "No AI service offers `podcast.submit` (or the service is at capacity)", body = ErrorResponse),
171+ ),
172+)]
173+async fn submit(
174+ State(st): State<AppState>,
175+ SchoolSlug(slug): SchoolSlug,
176+ CurrentUser(_user): CurrentUser,
177+ Json(req): Json<SubmitPodcast>,
178+) -> Result<Response, AppError> {
179+ let bridge = match worker_for(&st, AI_PODCAST_SUBMIT_CAPABILITY) {
180+ Ok(bridge) => bridge,
181+ Err(refusal) => return Ok(refusal),
182+ };
183+
184+ // Whitespace-only is empty: the service applies the same rule, so checking
185+ // it here only spares a round trip, never changes the verdict.
186+ let source_id = req.source_id.trim();
187+ if source_id.is_empty() {
188+ return Err(AppError::Validation(ValidationError::Invalid {
189+ field: "source_id",
190+ reason: "must not be empty",
191+ }));
192+ }
193+
194+ let payload = PodcastSubmitPayload {
195+ source_id: source_id.to_string(),
196+ format: req.format,
197+ };
198+ match podcast::submit(&bridge, &slug, payload).await {
199+ Ok(reply) => Ok((StatusCode::ACCEPTED, Json(receipt(reply))).into_response()),
200+ Err(code) => Ok(failure(&code)),
201+ }
202+}
203+
204+/// One job's current state. Poll this; the answer is the service's own
205+/// snapshot.
206+#[utoipa::path(
207+ get,
208+ path = "/jobs/{id}",
209+ tag = "podcast",
210+ security(("session_cookie" = [])),
211+ params(("id" = String, Path, description = "Job id from `POST /podcast/jobs`")),
212+ responses(
213+ (status = 200, description = "The job as of now", body = JobStatus),
214+ (status = 401, description = "Not authenticated", body = ErrorResponse),
215+ (status = 404, description = "No such job (the service answered `not_found`)", body = ErrorResponse),
216+ (status = 503, description = "No AI service offers `podcast.status`", body = ErrorResponse),
217+ ),
218+)]
219+async fn status(
220+ State(st): State<AppState>,
221+ SchoolSlug(slug): SchoolSlug,
222+ CurrentUser(_user): CurrentUser,
223+ Path(id): Path<String>,
224+) -> Result<Response, AppError> {
225+ let bridge = match worker_for(&st, AI_PODCAST_STATUS_CAPABILITY) {
226+ Ok(bridge) => bridge,
227+ Err(refusal) => return Ok(refusal),
228+ };
229+ match podcast::status(&bridge, &slug, PodcastStatusPayload { job_id: id }).await {
230+ Ok(reply) => Ok(Json(snapshot(reply)).into_response()),
231+ Err(code) => Ok(failure(&code)),
232+ }
233+}
234+
235+/// A finished job's artifacts β€” above all the `audio_id` the audio door
236+/// streams. A job that has not finished yet is refused by the service with
237+/// `not_ready` (409); one it has never heard of with `not_found` (404).
238+#[utoipa::path(
239+ get,
240+ path = "/jobs/{id}/result",
241+ tag = "podcast",
242+ security(("session_cookie" = [])),
243+ params(("id" = String, Path, description = "Job id from `POST /podcast/jobs`")),
244+ responses(
245+ (status = 200, description = "The finished job's artifacts", body = JobArtifacts),
246+ (status = 401, description = "Not authenticated", body = ErrorResponse),
247+ (status = 404, description = "No such job (the service answered `not_found`)", body = ErrorResponse),
248+ (status = 409, description = "The job has not finished (the service answered `not_ready`)", body = ErrorResponse),
249+ (status = 503, description = "No AI service offers `podcast.result`", body = ErrorResponse),
250+ ),
251+)]
252+async fn result(
253+ State(st): State<AppState>,
254+ SchoolSlug(slug): SchoolSlug,
255+ CurrentUser(_user): CurrentUser,
256+ Path(id): Path<String>,
257+) -> Result<Response, AppError> {
258+ let bridge = match worker_for(&st, AI_PODCAST_RESULT_CAPABILITY) {
259+ Ok(bridge) => bridge,
260+ Err(refusal) => return Ok(refusal),
261+ };
262+ match podcast::result(&bridge, &slug, PodcastResultPayload { job_id: id }).await {
263+ Ok(reply) => Ok(Json(artifacts(reply)).into_response()),
264+ Err(code) => Ok(failure(&code)),
265+ }
266+}
267+
268+/// Cancel one job. `cancelled` says whether *this call* stopped work β€” a job
269+/// that had already finished, or was already cancelled, answers `false` and is
270+/// not an error.
271+#[utoipa::path(
272+ post,
273+ path = "/jobs/{id}/cancel",
274+ tag = "podcast",
275+ security(("session_cookie" = [])),
276+ params(("id" = String, Path, description = "Job id from `POST /podcast/jobs`")),
277+ responses(
278+ (status = 200, description = "The cancel verdict", body = CancelVerdict),
279+ (status = 401, description = "Not authenticated", body = ErrorResponse),
280+ (status = 404, description = "No such job (the service answered `not_found`)", body = ErrorResponse),
281+ (status = 503, description = "No AI service offers `podcast.cancel`", body = ErrorResponse),
282+ ),
283+)]
284+async fn cancel(
285+ State(st): State<AppState>,
286+ SchoolSlug(slug): SchoolSlug,
287+ CurrentUser(_user): CurrentUser,
288+ Path(id): Path<String>,
289+) -> Result<Response, AppError> {
290+ let bridge = match worker_for(&st, AI_PODCAST_CANCEL_CAPABILITY) {
291+ Ok(bridge) => bridge,
292+ Err(refusal) => return Ok(refusal),
293+ };
294+ match podcast::cancel(&bridge, &slug, PodcastCancelPayload { job_id: id }).await {
295+ Ok(reply) => Ok(Json(verdict(reply)).into_response()),
296+ Err(code) => Ok(failure(&code)),
297+ }
298+}
299+
300+/// The query behind the audio door.
301+#[derive(Deserialize, IntoParams)]
302+struct AudioQuery {
303+ /// The `audio_id` from `GET /podcast/jobs/{id}/result`, **verbatim**: a
304+ /// path relative to this school's podcast output root.
305+ #[param(example = "ses/duz_okuma/019732e3-7b00-7000-8000-00000000dead/episode.mp3")]
306+ path: String,
307+}
308+
309+/// Stream one produced audio file. `path` is the `audio_id`
310+/// `podcast.result` answered, resolved under **this caller's school** output
311+/// directory β€” the same directory the service's `PODCAST_OUTPUT_ROOT` points
312+/// at β€” and streamed in 64 KiB chunks, so a long episode costs the backend a
313+/// bounded buffer rather than its whole length in memory.
314+///
315+/// The path is hostile input: a leading `/`, any `.`/`..` segment, a
316+/// backslash, a drive colon, or a symlink whose target resolves outside the
317+/// school's directory is a `400` (a path this backend will not resolve), not a
318+/// `404` β€” a caller probing the boundary gets the truth, and a caller with a
319+/// legitimate `audio_id` never sees either.
320+#[utoipa::path(
321+ get,
322+ path = "/audio",
323+ tag = "podcast",
324+ security(("session_cookie" = [])),
325+ responses(
326+ (status = 200, description = "The audio bytes", content_type = "audio/mpeg"),
327+ (status = 400, description = "`path` is not a relative path inside this school's podcast output", body = ErrorResponse),
328+ (status = 401, description = "Not authenticated", body = ErrorResponse),
329+ (status = 404, description = "No such file in this school's podcast output", body = ErrorResponse),
330+ ),
331+)]
332+async fn audio(
333+ State(st): State<AppState>,
334+ CurrentUser(_user): CurrentUser,
335+ Query(query): Query<AudioQuery>,
336+) -> Result<Response, AppError> {
337+ // The school-scoped `State` has already narrowed `files_path` to the
338+ // caller's own directory under `FILES_PATH` β€” the very directory the
339+ // service's `PODCAST_OUTPUT_ROOT` points at β€” so the containment root here
340+ // needs no school arithmetic of its own, and cannot drift from the one
341+ // every other blob route uses.
342+ let file_path = resolve_audio(&st.files_path, &query.path).await?;
343+ let file = tokio::fs::File::open(&file_path)
344+ .await
345+ .map_err(|_| AppError::NotFound)?;
346+
347+ Ok((
348+ [
349+ (CONTENT_TYPE, HeaderValue::from_static(audio_content_type(&file_path))),
350+ (X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")),
351+ (CACHE_CONTROL, HeaderValue::from_static("private, no-store")),
352+ ],
353+ Body::from_stream(pump(file)),
354+ )
355+ .into_response())
356+}
357+
358+/// Resolve one `audio_id` into a real file under `root`, or refuse it.
359+///
360+/// The order is the point: shape first (so an absolute path or a `..` segment
361+/// never reaches the filesystem), then canonicalization β€” which follows every
362+/// symlink, so a link that only *looks* like it lives under the root resolves
363+/// out of it and is refused by the containment check rather than served.
364+async fn resolve_audio(
365+ root: &std::path::Path,
366+ relative: &str,
367+) -> Result<std::path::PathBuf, AppError> {
368+ let refused = || {
369+ AppError::Validation(ValidationError::Invalid {
370+ field: "path",
371+ reason: "must be a relative path inside this school's podcast output",
372+ })
373+ };
374+
375+ if relative.is_empty() || relative.starts_with('/') {
376+ return Err(refused());
377+ }
378+ // Neither byte appears in a path this backend produced: `\` is a separator
379+ // on another platform, `:` is a drive designator there β€” and a NUL could
380+ // only truncate the path inside the OS. Refused here, not left to the
381+ // platform's rules.
382+ if relative.contains('\\') || relative.contains(':') || relative.contains('\0') {
383+ return Err(refused());
384+ }
385+ // Any `.`/`..` segment, or an empty one (`a//b`): the shape a traversal
386+ // needs, refused before anything is joined.
387+ if relative
388+ .split('/')
389+ .any(|segment| segment.is_empty() || segment == "." || segment == "..")
390+ {
391+ return Err(refused());
392+ }
393+
394+ // The root is canonicalized too: `FILES_PATH` may itself be reached
395+ // through a symlink, and containment must compare real paths.
396+ let root = tokio::fs::canonicalize(root)
397+ .await
398+ .map_err(|_| AppError::NotFound)?;
399+ let target = tokio::fs::canonicalize(root.join(relative))
400+ .await
401+ .map_err(|_| AppError::NotFound)?;
402+
403+ // Symlink escape: `canonicalize` follows links, so a target that resolves
404+ // outside the school's directory lands here, whatever the link looked like.
405+ if !target.starts_with(&root) {
406+ return Err(refused());
407+ }
408+ // A directory is not an audio file β€” and serving `read` on it would be an
409+ // I/O error at best.
410+ if !tokio::fs::metadata(&target)
411+ .await
412+ .map(|meta| meta.is_file())
413+ .unwrap_or(false)
414+ {
415+ return Err(AppError::NotFound);
416+ }
417+ Ok(target)
418+}
419+
420+/// The content type for a produced artifact, by extension. `mp3` is what the
421+/// pipeline writes today; the rest of the set is here so a format switch on the
422+/// service side still serves as audio rather than as an opaque download.
423+fn audio_content_type(path: &std::path::Path) -> &'static str {
424+ match path
425+ .extension()
426+ .and_then(|ext| ext.to_str())
427+ .map(str::to_ascii_lowercase)
428+ .as_deref()
429+ {
430+ Some("mp3") => "audio/mpeg",
431+ Some("wav") => "audio/wav",
432+ Some("m4a") | Some("mp4") => "audio/mp4",
433+ Some("ogg") | Some("oga") | Some("opus") => "audio/ogg",
434+ _ => "application/octet-stream",
435+ }
436+}
437+
438+/// A file as a byte stream: a reader task hands chunks to the body over a
439+/// bounded channel, so a client that stops reading parks the pump at the next
440+/// send instead of pinning the whole file in memory, and a closed body ends the
441+/// task by itself.
442+fn pump(file: tokio::fs::File) -> impl Stream<Item = Result<Bytes, std::io::Error>> + Send + 'static {
443+ let (tx, rx) = mpsc::channel(AUDIO_CHUNKS_IN_FLIGHT);
444+ tokio::spawn(async move {
445+ let mut file = file;
446+ let mut buffer = vec![0u8; AUDIO_CHUNK_BYTES];
447+ loop {
448+ match file.read(&mut buffer).await {
449+ Ok(0) => break,
450+ Ok(read) => {
451+ if tx
452+ .send(Ok(Bytes::copy_from_slice(&buffer[..read])))
453+ .await
454+ .is_err()
455+ {
456+ break;
457+ }
458+ }
459+ Err(err) => {
460+ let _ = tx.send(Err(err)).await;
461+ break;
462+ }
463+ }
464+ }
465+ });
466+ ReceiverStream::new(rx)
467+}
468+
469+/// The 503 gate every dispatching door shares: no bridge configured, or no
470+/// worker declaring this door's capability. `has_capability` is documented
471+/// racy β€” fine here: it never guards a write, and the dispatch that follows
472+/// re-checks for real; this only spares a caller a round trip into a service
473+/// that cannot answer.
474+fn worker_for(st: &AppState, capability: &str) -> Result<AiBridge, Response> {
475+ let Some(bridge) = st.ai.clone() else {
476+ return Err(ai_unavailable(
477+ "the AI service is not enabled on this deployment",
478+ ));
479+ };
480+ if !bridge.has_capability(capability) {
481+ return Err(ai_unavailable("no AI service is connected right now"));
482+ }
483+ Ok(bridge)
484+}
485+
486+/// A relayed failure as the response a client branches on: the service's own
487+/// code decides the status where it is one this backend knows, and anything
488+/// else is a `502` β€” the backend cannot vouch for an answer it did not
489+/// understand, and a gateway error is exactly that claim.
490+fn failure(code: &str) -> Response {
491+ let status = match code {
492+ "bad_request" => StatusCode::BAD_REQUEST,
493+ "not_found" => StatusCode::NOT_FOUND,
494+ "not_ready" | "llm_unavailable" => StatusCode::CONFLICT,
495+ "busy" | "unavailable" => StatusCode::SERVICE_UNAVAILABLE,
496+ "timed_out" => StatusCode::GATEWAY_TIMEOUT,
497+ "internal" => StatusCode::INTERNAL_SERVER_ERROR,
498+ // `transport`, `protocol`, `bad_reply`, `service_error`, and any code
499+ // the service invented: a bad gateway.
500+ _ => StatusCode::BAD_GATEWAY,
501+ };
502+ (status, Json(json!({ "error": code }))).into_response()
503+}
504+
505+fn receipt(reply: PodcastSubmitReply) -> JobReceipt {
506+ JobReceipt {
507+ job_id: reply.job_id,
508+ state: reply.state,
509+ eta_secs: reply.eta_secs,
510+ }
511+}
512+
513+fn snapshot(reply: PodcastStatusReply) -> JobStatus {
514+ JobStatus {
515+ job_id: reply.job_id,
516+ state: reply.state,
517+ stage: reply.stage,
518+ progress: reply.progress,
519+ error_code: reply.error_code,
520+ }
521+}
522+
523+fn artifacts(reply: PodcastResultReply) -> JobArtifacts {
524+ JobArtifacts {
525+ job_id: reply.job_id,
526+ audio_id: reply.audio_id,
527+ duration_secs: reply.duration_secs,
528+ script_id: reply.script_id,
529+ audio_ids: reply.audio_ids,
530+ script_ids: reply.script_ids,
531+ format: reply.format,
532+ }
533+}
534+
535+fn verdict(reply: PodcastCancelReply) -> CancelVerdict {
536+ CancelVerdict {
537+ job_id: reply.job_id,
538+ cancelled: reply.cancelled,
539+ }
540+}
tests/podcast.rsadded+673 -0
@@ -0,0 +1,673 @@
1+//! End-to-end tests for the podcast nest, against a fake podcast service.
2+//!
3+//! Everything here runs over a real QUIC socket on loopback β€” a real
4+//! 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.
9+//!
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.
15+
16+mod common;
17+
18+use std::sync::{Arc, Mutex};
19+use std::time::Duration;
20+
21+use axum::Router;
22+use axum::http::StatusCode;
23+use hezarfen_backend::ai::protocol::{
24+ Greeting, Hello, Request, Response, read_frame, write_frame,
25+};
26+use hezarfen_backend::ai::{AiBridge, BridgeConfig};
27+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+};
31+use hezarfen_backend::module::{Module, ModuleSet};
32+use hezarfen_backend::tenant::{DEMO_SLUG, Slug};
33+use serde_json::{Value, json};
34+
35+const TOKEN: &str = "shared-ai-token";
36+
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";
49+/// A source id shaped like the backend ids the service is handed.
50+const SOURCE_ID: &str = "019732e3-7b00-7000-8000-00000000dead";
51+
52+// ---------------------------------------------------------------- harness --
53+
54+/// Start a bridge on an ephemeral port.
55+async fn bridge() -> AiBridge {
56+ AiBridge::bind(BridgeConfig {
57+ addr: "127.0.0.1:0".parse().unwrap(),
58+ token: TOKEN.to_string(),
59+ cert_path: None,
60+ key_path: None,
61+ request_timeout: Duration::from_secs(5),
62+ })
63+ .await
64+ .expect("bridge binds on an ephemeral port")
65+}
66+
67+/// A QUIC client endpoint that trusts exactly the bridge's own certificate β€”
68+/// the same pinning a real service does, rather than a verification bypass.
69+fn client_endpoint(bridge: &AiBridge) -> quinn::Endpoint {
70+ hezarfen_backend::ai::tls::install_crypto_provider();
71+ let mut roots = rustls::RootCertStore::empty();
72+ roots.add(bridge.certificate()).expect("pin the leaf");
73+ let mut tls = rustls::ClientConfig::builder()
74+ .with_root_certificates(roots)
75+ .with_no_client_auth();
76+ tls.alpn_protocols = vec![AI_ALPN.to_vec()];
77+
78+ let quic_tls =
79+ quinn::crypto::rustls::QuicClientConfig::try_from(tls).expect("client TLS is QUIC-usable");
80+ let mut config = quinn::ClientConfig::new(Arc::new(quic_tls));
81+ let mut transport = quinn::TransportConfig::default();
82+ transport.max_concurrent_bidi_streams(64u32.into());
83+ config.transport_config(Arc::new(transport));
84+
85+ let mut endpoint =
86+ quinn::Endpoint::client("127.0.0.1:0".parse().unwrap()).expect("client bind");
87+ endpoint.set_default_client_config(config);
88+ endpoint
89+}
90+
91+fn demo() -> Slug {
92+ Slug::try_new(DEMO_SLUG).expect("the demo slug")
93+}
94+
95+fn hello(service: &str, capabilities: &[&str]) -> Hello {
96+ Hello {
97+ protocol: AI_PROTOCOL.to_string(),
98+ service: service.to_string(),
99+ capabilities: capabilities.iter().map(|c| c.to_string()).collect(),
100+ token: TOKEN.to_string(),
101+ max_concurrent: None,
102+ }
103+}
104+
105+/// A connected fake service. Holding it keeps the connection (and so the
106+/// registration) alive; dropping it is how a test simulates a crash.
107+struct FakeService {
108+ _endpoint: quinn::Endpoint,
109+ _control: (quinn::SendStream, quinn::RecvStream),
110+ /// Every request this service received, in arrival order.
111+ seen: Arc<Mutex<Vec<Request>>>,
112+}
113+
114+impl FakeService {
115+ fn seen(&self) -> Vec<Request> {
116+ self.seen.lock().unwrap().clone()
117+ }
118+}
119+
120+/// What the fake service does with each request it receives.
121+#[derive(Clone)]
122+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.
126+ Podcast,
127+ /// Answer with a handled failure.
128+ Fail { code: String, message: String },
129+}
130+
131+/// Dial, register, and start serving requests with `behaviour`.
132+async fn connect_service(bridge: &AiBridge, hello: Hello, behaviour: Behaviour) -> FakeService {
133+ let endpoint = client_endpoint(bridge);
134+ let conn = endpoint
135+ .connect(bridge.local_addr().unwrap(), "localhost")
136+ .expect("dial")
137+ .await
138+ .expect("QUIC handshake");
139+ let (mut send, mut recv) = conn.open_bi().await.expect("control stream");
140+ write_frame(&mut send, &hello).await.expect("send Hello");
141+ let greeting: Greeting = read_frame(&mut recv).await.expect("read Greeting");
142+ match greeting {
143+ Greeting::Welcome { protocol, .. } => assert_eq!(protocol, AI_PROTOCOL),
144+ other => panic!("expected a welcome, got {other:?}"),
145+ }
146+
147+ let seen = Arc::new(Mutex::new(Vec::new()));
148+ serve(conn.clone(), behaviour, Arc::clone(&seen));
149+ FakeService {
150+ _endpoint: endpoint,
151+ _control: (send, recv),
152+ seen,
153+ }
154+}
155+
156+/// The service's request loop: one task per incoming server-initiated stream.
157+fn serve(conn: quinn::Connection, behaviour: Behaviour, seen: Arc<Mutex<Vec<Request>>>) {
158+ tokio::spawn(async move {
159+ while let Ok((mut send, mut recv)) = conn.accept_bi().await {
160+ let behaviour = behaviour.clone();
161+ let seen = Arc::clone(&seen);
162+ tokio::spawn(async move {
163+ let Ok(request) = read_frame::<_, Request>(&mut recv).await else {
164+ return;
165+ };
166+ seen.lock().unwrap().push(request.clone());
167+ let response = match behaviour {
168+ Behaviour::Podcast => Some(Response::Ok {
169+ id: request.id.clone(),
170+ school: request.school.clone(),
171+ payload: podcast_answer(&request),
172+ }),
173+ Behaviour::Fail { code, message } => Some(Response::Err {
174+ id: request.id.clone(),
175+ school: request.school.clone(),
176+ code,
177+ message,
178+ }),
179+ };
180+ if let Some(response) = response {
181+ let _ = write_frame(&mut send, &response).await;
182+ let _ = send.finish();
183+ let _ = send.stopped().await;
184+ }
185+ });
186+ }
187+ });
188+}
189+
190+/// What the podcast service would answer for this capability.
191+fn podcast_answer(request: &Request) -> Value {
192+ let job_id = request
193+ .payload
194+ .get("job_id")
195+ .cloned()
196+ .unwrap_or_else(|| json!(JOB_ID));
197+ match request.capability.as_str() {
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,
207+ }),
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+ }),
217+ AI_PODCAST_CANCEL_CAPABILITY => json!({ "job_id": job_id, "cancelled": true }),
218+ other => panic!("the fake podcast service was asked for `{other}`"),
219+ }
220+}
221+
222+/// Registration completes asynchronously after the welcome is on the wire, so
223+/// tests that assert on the registry wait for it rather than racing it.
224+async fn await_workers(bridge: &AiBridge, expected: usize) {
225+ for _ in 0..300 {
226+ if bridge.workers().len() == expected {
227+ return;
228+ }
229+ tokio::time::sleep(Duration::from_millis(10)).await;
230+ }
231+ panic!(
232+ "expected {expected} workers, registry holds {:?}",
233+ bridge.workers()
234+ );
235+}
236+
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) {
240+ let bridge = bridge().await;
241+ let service = connect_service(
242+ &bridge,
243+ hello("podcast", &CAPABILITIES),
244+ Behaviour::Podcast,
245+ )
246+ .await;
247+ await_workers(&bridge, 1).await;
248+ let (app, _db) = common::app_with_ai(Some(bridge)).await;
249+ let cookie = common::login(&app, "ali").await;
250+ (service, app, cookie)
251+}
252+
253+/// Submit one job and return the response.
254+async fn submit(app: &Router, cookie: &str, body: Value) -> common::Res {
255+ common::send(app, "POST", "/podcast/jobs", Some(cookie), Some(body)).await
256+}
257+
258+// ------------------------------------------------------------ round trips --
259+
260+#[tokio::test]
261+async fn a_submit_round_trips_the_source_and_format_to_the_service() {
262+ let (service, app, cookie) = podcast_app().await;
263+
264+ let res = submit(
265+ &app,
266+ &cookie,
267+ json!({ "source_id": SOURCE_ID, "format": "duz_okuma" }),
268+ )
269+ .await;
270+ assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);
271+ assert_eq!(res.body["job_id"], JOB_ID);
272+ assert_eq!(res.body["state"], "queued");
273+ assert_eq!(res.body["eta_secs"], 2700);
274+
275+ let seen = service.seen();
276+ assert_eq!(seen.len(), 1, "exactly one dispatch");
277+ assert_eq!(seen[0].capability, AI_PODCAST_SUBMIT_CAPABILITY);
278+ assert_eq!(seen[0].school, DEMO_SLUG, "the school rides the frame");
279+ assert_eq!(seen[0].payload["source_id"], SOURCE_ID);
280+ assert_eq!(seen[0].payload["format"], "duz_okuma");
281+}
282+
283+/// The format is optional and the service applies its own default: an omitted
284+/// format must not appear on the wire at all, or the service would have to
285+/// distinguish "absent" from "empty".
286+#[tokio::test]
287+async fn an_omitted_format_is_not_sent_at_all() {
288+ let (service, app, cookie) = podcast_app().await;
289+
290+ let res = submit(&app, &cookie, json!({ "source_id": SOURCE_ID })).await;
291+ assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);
292+
293+ let seen = service.seen();
294+ assert_eq!(seen.len(), 1);
295+ assert!(
296+ seen[0].payload.get("format").is_none(),
297+ "no format was asked for, so none is sent: {}",
298+ seen[0].payload
299+ );
300+}
301+
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.
304+#[tokio::test]
305+async fn a_blank_source_id_is_refused_before_dispatch() {
306+ let (service, app, cookie) = podcast_app().await;
307+
308+ let res = submit(&app, &cookie, json!({ "source_id": " " })).await;
309+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
310+ assert!(service.seen().is_empty(), "nothing reaches the service");
311+}
312+
313+#[tokio::test]
314+async fn a_status_read_round_trips_the_job_id() {
315+ let (service, app, cookie) = podcast_app().await;
316+
317+ let res = common::send(
318+ &app,
319+ "GET",
320+ &format!("/podcast/jobs/{JOB_ID}"),
321+ Some(&cookie),
322+ None,
323+ )
324+ .await;
325+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
326+ assert_eq!(res.body["job_id"], JOB_ID);
327+ assert_eq!(res.body["state"], "running");
328+ assert_eq!(res.body["stage"], "tts");
329+ assert_eq!(res.body["progress"], 0.5);
330+ assert!(res.body["error_code"].is_null());
331+
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);
336+}
337+
338+#[tokio::test]
339+async fn a_result_read_round_trips_the_artifacts() {
340+ let (service, app, cookie) = podcast_app().await;
341+
342+ let res = common::send(
343+ &app,
344+ "GET",
345+ &format!("/podcast/jobs/{JOB_ID}/result"),
346+ Some(&cookie),
347+ None,
348+ )
349+ .await;
350+ 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");
358+
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);
363+}
364+
365+#[tokio::test]
366+async fn a_cancel_round_trips_the_verdict() {
367+ let (service, app, cookie) = podcast_app().await;
368+
369+ let res = common::send(
370+ &app,
371+ "POST",
372+ &format!("/podcast/jobs/{JOB_ID}/cancel"),
373+ Some(&cookie),
374+ None,
375+ )
376+ .await;
377+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
378+ assert_eq!(res.body["job_id"], JOB_ID);
379+ assert_eq!(res.body["cancelled"], true);
380+
381+ 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);
385+}
386+
387+// --------------------------------------------------------------- refusals --
388+
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.
392+#[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;
396+ let cookie = common::login(&app, "ali").await;
397+
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+ }
421+}
422+
423+/// The same doors with no bridge at all (the deployment never set
424+/// `AI_QUIC_ADDR`): still a `503`, with the other message.
425+#[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;
428+ let cookie = common::login(&app, "ali").await;
429+
430+ let res = submit(&app, &cookie, json!({ "source_id": SOURCE_ID })).await;
431+ assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body);
432+ assert_eq!(
433+ res.body["error"],
434+ "the AI service is not enabled on this deployment"
435+ );
436+}
437+
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`).
442+#[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),
448+ ];
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);
474+ }
475+}
476+
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.
480+#[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;
485+
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");
493+
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");
504+}
505+
506+/// Authentication is the whole gate for the dispatching doors: no cookie is a
507+/// `401`, not a dispatch under somebody else's name.
508+#[tokio::test]
509+async fn the_dispatching_doors_require_a_session() {
510+ let (service, app, _cookie) = podcast_app().await;
511+
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");
522+}
523+
524+// -------------------------------------------------------------- audio door --
525+
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+}
534+
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
543+}
544+
545+/// The happy path: a file under the school's own directory streams back with
546+/// its bytes and an audio content type.
547+#[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);
553+
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");
560+}
561+
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.
564+#[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);
570+
571+ let (anonymous, _, _) = fetch_audio(&app, None, "podcast/auth/only.mp3").await;
572+ assert_eq!(anonymous, StatusCode::UNAUTHORIZED);
573+
574+ let (authorized, _, body) = fetch_audio(&app, Some(&cookie), "podcast/auth/only.mp3").await;
575+ assert_eq!(authorized, StatusCode::OK);
576+ assert_eq!(body, bytes);
577+}
578+
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.
608+#[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");
614+
615+ let (status, _, body) = fetch_audio(
616+ &app,
617+ Some(&cookie),
618+ outside.to_str().expect("a UTF-8 temp path"),
619+ )
620+ .await;
621+ assert_eq!(status, StatusCode::BAD_REQUEST, "{:?}", String::from_utf8_lossy(&body));
622+ assert_ne!(body, b"not for the audio door");
623+}
624+
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.
648+#[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());
656+
657+ let (status, _, _) = fetch_audio(&app, Some(&cookie), "podcast/ses/episode.mp3").await;
658+ assert_eq!(status, StatusCode::NOT_FOUND);
659+}
660+
661+/// The door needs no AI bridge at all: a produced file is served with the
662+/// service long gone.
663+#[tokio::test]
664+async fn the_audio_door_needs_no_service() {
665+ let (app, _db) = common::app_with_ai(None).await;
666+ let cookie = common::login(&app, "ali").await;
667+ let bytes = b"produced before the service left".to_vec();
668+ school_file("podcast/offline/episode.mp3", &bytes);
669+
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);
673+}