forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

podcast.rs747 lines, 31.2 KiBHistoryRawDownload
1//! The podcast nest: browser ⇄ backend ⇄ the podcast service (over the QUIC
2//! bridge), plus the doors that hand back the produced audio.
3//!
4//! The **backend owns the job**. `POST /podcast/jobs` mints the id, writes the
5//! row, and only then dispatches `podcast.submit`; the service reports every
6//! transition back (`podcast.report`) and uploads the finished mp3
7//! (`BlobUploadRequest`), which lands under **this school's** blob directory.
8//! `GET /podcast/jobs/{id}` and `.../result` therefore answer from
9//! [`crate::db::podcast_job`] alone — no worker, no service, no second store
10//! that a restart or a wiped volume could take down with it. The service's own
11//! record is a mirror the pipeline works against, not the source of truth.
12//!
13//! Six doors:
14//!
15//! * `POST /podcast/jobs` — write the row, dispatch `podcast.submit`
16//! * `GET /podcast/jobs` — the caller's own history, newest first,
17//! optionally narrowed to one course note (`?source_id=`)
18//! * `GET /podcast/jobs/{id}` — the row's snapshot (projected, see below)
19//! * `GET /podcast/jobs/{id}/result` — a finished job's artifact references
20//! * `GET /podcast/jobs/{id}/audio` — streams the ingested episode
21//! * `POST /podcast/jobs/{id}/cancel` — forward the cancel, stamp the verdict
22//!
23//! The two dispatching doors (`submit`, `cancel`) refuse `503` when no worker
24//! declares their capability; the four reading doors need no service at all.
25//! A relayed failure keeps the service's own code and decides the HTTP status
26//! (`failure`), so a client branches on the same vocabulary the bridge speaks.
27//!
28//! Every door is school-scoped twice: the session resolves the school's
29//! database (`st.db`) and the school's blob directory (`st.files_path`), and
30//! every read is filtered by the submitting user in the statement itself — a
31//! foreign id is a plain `404`, never a hint that it exists. Terminal rows
32//! older than the retention window answer `410`.
33//!
34//! A job nobody is updating — the service died mid-pipeline — is *presented*
35//! as `failed`/`interrupted` by the read path after a bounded, ETA-scaled
36//! window (see [`PodcastJob::projected`]): the projection writes nothing, and
37//! the service's next report overwrites it.
38//!
39//! The **sources** are resolved here, not by the service: `source_id` names a
40//! course note in the caller's own school, and the submit door hands the
41//! service that note's attachments — every one whose blob is on this host, in
42//! upload order — as `sources` (`source_key` rides on as the first source's
43//! key, one-release compat). A note with no attachments, or one whose blobs
44//! are all missing from this host, is refused `409 source_missing` before the
45//! row is written, so a job that could only fail is never queued.
46
47use axum::Json;
48use axum::body::Body;
49use axum::extract::{Path, Query};
50use axum::http::HeaderValue;
51use axum::http::StatusCode;
52use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS};
53use axum::response::{IntoResponse, Response};
54use serde::{Deserialize, Serialize};
55use serde_json::json;
56use utoipa::{IntoParams, ToSchema};
57use utoipa_axum::router::OpenApiRouter;
58use utoipa_axum::routes;
59
60use crate::ai::AiBridge;
61use crate::ai::podcast::{self, PodcastCancelPayload, PodcastSource, PodcastSubmitPayload};
62use crate::constant::{
63 AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_SUBMIT_CAPABILITY, PODCAST_INTERRUPTED_CODE,
64};
65use crate::domain::course_note::CourseNoteId;
66use crate::domain::podcast_job::{PodcastJob, PodcastJobId};
67use crate::domain::user::User;
68use crate::error::{AppError, ErrorResponse, ValidationError};
69use crate::service::course_note_file as note_files;
70use crate::service::podcast_job as jobs;
71use crate::state::AppState;
72use crate::web::tenant_state::{SchoolIdCookie, State};
73
74use super::{CurrentUser, Page, PageParams, ai_unavailable, pump};
75
76pub fn routes() -> OpenApiRouter<AppState> {
77 OpenApiRouter::new()
78 .routes(routes!(submit, list))
79 .routes(routes!(status))
80 .routes(routes!(result))
81 .routes(routes!(audio))
82 .routes(routes!(cancel))
83}
84
85#[derive(Deserialize, ToSchema)]
86struct SubmitPodcast {
87 /// The backend's id for the source to narrate — a course note's id, never
88 /// a path. Sent on as the service's `source_id`.
89 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
90 source_id: String,
91 /// Which narration to produce: `duz_okuma` (the service's default),
92 /// `tek_ogretici` or `ogrenci_hoca`. The two latter need the service's LLM
93 /// key and are refused with `llm_unavailable` (409) without it.
94 #[schema(example = "duz_okuma")]
95 #[serde(default)]
96 format: Option<String>,
97}
98
99/// The receipt for an accepted job: the backend's own row plus the service's
100/// ETA. `state` is always `queued` here — the row was just written.
101#[derive(Serialize, ToSchema)]
102struct JobReceipt {
103 /// The backend-minted job id — every other door names it, and the service
104 /// keys its own record by it.
105 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
106 job_id: String,
107 /// `queued` on a fresh job.
108 state: String,
109 /// The service's own estimate of the job's duration, in seconds.
110 eta_secs: i64,
111}
112
113/// One job's state, from the backend's own row.
114#[derive(Serialize, ToSchema)]
115struct JobStatus {
116 job_id: String,
117 /// `queued`, `running`, `done`, `failed` or `cancelled`.
118 state: String,
119 /// The pipeline stage the job is in.
120 stage: String,
121 /// Fraction complete, `0.0..=1.0`.
122 progress: f64,
123 /// Set only once the job failed.
124 error_code: Option<String>,
125}
126
127/// One attachment's outcome in the finished episode, as the service reported
128/// it.
129#[derive(Serialize, Deserialize, ToSchema)]
130struct JobSourceStatus {
131 /// The attachment's blob key — the id `GET /course-notes/{id}/files`
132 /// lists.
133 key: String,
134 /// The file name the upload declared.
135 name: String,
136 /// `ok`, or `skipped:<code>` when the source failed extraction and was
137 /// left out of the episode.
138 status: String,
139}
140
141/// A finished job's artifacts.
142#[derive(Serialize, ToSchema)]
143struct JobArtifacts {
144 job_id: String,
145 /// The produced audio, as the blob key `GET /podcast/jobs/{id}/audio`
146 /// streams — informational, never a path the caller resolves itself.
147 #[schema(example = "podcast/019732e3-7b00-7000-8000-00000000dead.mp3")]
148 audio_id: String,
149 duration_secs: Option<f64>,
150 /// The resolved narration format.
151 format: Option<String>,
152 /// The episode transcript, chapters joined by blank lines. `null` when the
153 /// service that produced the episode did not report one — every job
154 /// finished before the column existed, and any later job whose done report
155 /// omitted the field.
156 transcript: Option<String>,
157 /// Per-source outcomes for a multi-document episode, exactly as the
158 /// service reported them. `null` for episodes finished before the field
159 /// existed, or by a service that has not learned it.
160 sources: Option<Vec<JobSourceStatus>>,
161}
162
163/// The verdict on a cancel.
164#[derive(Serialize, ToSchema)]
165struct CancelVerdict {
166 job_id: String,
167 /// Whether *this call* cancelled something — `false` for a job that had
168 /// already finished or had already been cancelled.
169 cancelled: bool,
170}
171
172/// Start one podcast job. Answers `202` with the backend's own receipt the
173/// moment the service accepts it.
174///
175/// The row is written **before** the dispatch, so a poll that races the submit
176/// finds the job rather than a `404`; and every dispatch outcome that is not an
177/// acceptance leaves the row `failed` with a reason code rather than claiming
178/// `queued` forever. With no worker connected the row is not written at all —
179/// the `503` is the whole answer — and a note with no usable PDF never gets as
180/// far as a row either (see below).
181///
182/// `source_id` names a course note in this school, and the door resolves it
183/// first: what the service narrates is that note's **attachments** — every
184/// one whose blob is on this host, dispatched as `sources` in upload order
185/// (a missing blob is skipped with a log line, not a refusal). A note with
186/// no attachments — or none whose blob is on this host — is a `409
187/// source_missing` before anything is written, so a job that is guaranteed
188/// to fail is never queued for the service to discover later.
189#[utoipa::path(
190 post,
191 path = "/jobs",
192 tag = "podcast",
193 security(("session_cookie" = [])),
194 request_body = SubmitPodcast,
195 responses(
196 (status = 202, description = "The job is queued; `job_id` names it from here on", body = JobReceipt),
197 (status = 400, description = "Empty `source_id`, or a `format` the service does not serve", body = ErrorResponse),
198 (status = 401, description = "Not authenticated", body = ErrorResponse),
199 (status = 409, description = "The note has no attachments at all, or none of its attachment blobs are present on this host (`source_missing`)", body = ErrorResponse),
200 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing", body = ErrorResponse),
201 (status = 503, description = "No AI service offers `podcast.submit` (or the service is at capacity)", body = ErrorResponse),
202 ),
203)]
204async fn submit(
205 State(st): State<AppState>,
206 SchoolIdCookie(school): SchoolIdCookie,
207 CurrentUser(user): CurrentUser,
208 Json(req): Json<SubmitPodcast>,
209) -> Result<Response, AppError> {
210 let bridge = match worker_for(&st, AI_PODCAST_SUBMIT_CAPABILITY) {
211 Ok(bridge) => bridge,
212 Err(no_worker) => return Ok(no_worker.refusal()),
213 };
214
215 // Whitespace-only is empty: the service applies the same rule, so checking
216 // it here only spares a round trip, never changes the verdict.
217 let source_id = req.source_id.trim();
218 if source_id.is_empty() {
219 return Err(AppError::Validation(ValidationError::Invalid {
220 field: "source_id",
221 reason: "must not be empty",
222 }));
223 }
224
225 // The sources are resolved here, before anything is written: what the
226 // service narrates is the note's own attachments — every one whose blob
227 // is on this host, in upload order (id ASC) — and those keys are what
228 // ride the dispatch. A blob that is gone is skipped with a log line, not
229 // a refusal: the episode just narrates fewer documents. Both shapes of
230 // "no source at all" are refused now — queueing the job would only buy a
231 // failure in the service's own `kaynak` stage, with the caller already
232 // holding a job id.
233 let (mut files, _) =
234 note_files::list_for(&st.db, &CourseNoteId::from_key(source_id), None, 0).await?;
235 let attachments = files.len();
236 // `list_for` is newest first; the payload carries upload order (id ASC),
237 // the order the service narrates in.
238 files.sort_by_key(|file| file.get_id().uuid());
239 let mut sources = Vec::with_capacity(files.len());
240 for file in files {
241 let key = file.get_id().key();
242 match tokio::fs::try_exists(crate::web::blob_path(&st.files_path, &key)).await {
243 Ok(true) => sources.push(PodcastSource {
244 key,
245 name: file.get_name().as_str().to_string(),
246 content_type: file.get_content_type().as_str().to_string(),
247 }),
248 // The row is intact, the bytes are not: leave this one document
249 // out rather than refusing a note whose other attachments are
250 // fine.
251 Ok(false) => tracing::warn!(
252 key = %key,
253 "podcast source's blob is missing from this host; skipping it"
254 ),
255 Err(err) => {
256 return Err(AppError::Internal(format!(
257 "could not stat a note attachment blob: {err}"
258 )));
259 }
260 }
261 }
262 if sources.is_empty() {
263 return Err(source_missing(if attachments == 0 {
264 "this course note has no attachments to narrate"
265 } else {
266 "none of this note's attachments are on this host"
267 }));
268 }
269 let source_key = sources[0].key.clone();
270
271 let job = jobs::create(&st.db, user.get_id(), source_id, req.format.as_deref()).await?;
272 let job_id = job.get_id().key();
273 let payload = PodcastSubmitPayload {
274 job_id: job_id.clone(),
275 source_id: source_id.to_string(),
276 source_key,
277 sources,
278 format: req.format.clone(),
279 user_id: user.get_id().key(),
280 };
281 match podcast::submit(&bridge, &school, payload).await {
282 // The echo is checked, not trusted: this id is the only handle every
283 // later call uses, so an answer about some other job is a protocol
284 // failure, not a receipt.
285 Ok(reply) if reply.job_id == job_id => {
286 let eta_secs = reply.eta_secs;
287 jobs::set_eta(&st.db, job.get_id(), eta_secs).await?;
288 Ok((
289 StatusCode::ACCEPTED,
290 Json(JobReceipt {
291 job_id,
292 state: reply.state,
293 eta_secs,
294 }),
295 )
296 .into_response())
297 }
298 Ok(reply) => {
299 tracing::warn!(
300 "AI podcast service accepted job {} under the id {}",
301 job_id,
302 reply.job_id
303 );
304 jobs::mark_failed(&st.db, job.get_id(), "bad_reply").await?;
305 Ok(failure("bad_reply"))
306 }
307 // The service refused the job: the row is the record of that, and the
308 // refusal reaches the caller with its own status.
309 Err(code) => {
310 jobs::mark_failed(&st.db, job.get_id(), &code).await?;
311 Ok(failure(&code))
312 }
313 }
314}
315
316/// One episode in the caller's history: the backend's own row, plus the title
317/// of the course note it narrates.
318#[derive(Serialize, ToSchema)]
319struct JobSummary {
320 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
321 job_id: String,
322 /// `queued`, `running`, `done`, `failed` or `cancelled` — a job nobody
323 /// has updated inside its ETA-scaled window is presented as `failed`.
324 state: String,
325 /// The narration the service resolved; `null` until its first report
326 /// settles it.
327 #[schema(example = "duz_okuma")]
328 format: Option<String>,
329 /// The course note this episode narrates.
330 #[schema(example = "019732e3-7b00-7000-8000-00000000face")]
331 source_id: String,
332 /// That note's title as of this read; `null` once the note is gone — the
333 /// episode keeps its place in the history either way.
334 #[schema(example = "Hücre ve Canlıların Ortak Özellikleri")]
335 source_title: Option<String>,
336 /// UTC unix-milliseconds, server-stamped.
337 created_at: i64,
338 /// When the job reached its terminal state (the write that finished it);
339 /// `null` while it is live.
340 finished_at: Option<i64>,
341 /// The finished episode's running time, as the service declared it at
342 /// upload; `null` until then.
343 duration_secs: Option<f64>,
344 /// The failure's own code, once one is on the record.
345 error_code: Option<String>,
346}
347
348impl JobSummary {
349 fn new(job: &PodcastJob, source_title: Option<String>) -> Self {
350 Self {
351 job_id: job.get_id().key(),
352 state: job.get_state().as_str().to_string(),
353 format: job.get_format().map(str::to_string),
354 source_id: job.get_source_id().to_string(),
355 source_title,
356 created_at: job.get_created_at().as_millis(),
357 finished_at: job
358 .get_state()
359 .is_terminal()
360 .then(|| job.get_updated_at().as_millis()),
361 duration_secs: job.get_duration_secs(),
362 error_code: job.get_error_code().map(str::to_string),
363 }
364 }
365}
366
367/// The optional `?source_id=` filter on the history: keep only the episodes
368/// that narrate one course note. Omitted, the list is the caller's whole
369/// history — the same response it has always been.
370#[derive(Debug, Deserialize, IntoParams)]
371struct HistoryFilter {
372 /// Keep only the jobs that narrate this course note (a note id).
373 #[param(example = "019732e3-7b00-7000-8000-00000000face")]
374 source_id: Option<String>,
375}
376
377impl HistoryFilter {
378 /// Validate the filter into the note to scope by, or `None` for the whole
379 /// history. The key is parsed the same way the submit door and the title
380 /// lookup parse it ([`CourseNoteId::from_key`]): that path maps anything
381 /// that is not a uuid to the nil id, so a key that lands there is refused
382 /// rather than silently scoping to a note no row can name.
383 fn resolve(&self) -> Result<Option<CourseNoteId>, AppError> {
384 let Some(raw) = self.source_id.as_deref() else {
385 return Ok(None);
386 };
387 let key = raw.trim();
388 if key.is_empty() {
389 return Err(AppError::Validation(ValidationError::Invalid {
390 field: "source_id",
391 reason: "must not be empty",
392 }));
393 }
394 let note = CourseNoteId::from_key(key);
395 if note.uuid().is_nil() {
396 return Err(AppError::Validation(ValidationError::Invalid {
397 field: "source_id",
398 reason: "must be a hyphenated uuid",
399 }));
400 }
401 Ok(Some(note))
402 }
403}
404
405/// The caller's own episodes, newest first — every job the backend ever
406/// minted for this user, whatever state it stopped in, each with the title of
407/// the note it narrated. Paged via `?limit=&offset=`.
408///
409/// This is a reading door like the per-id ones: it answers from the rows
410/// alone, so with the service down, restarted, or never connected at all the
411/// history is still exactly what it was. A job nobody has updated inside its
412/// ETA-scaled window is presented as `failed` (the same read-side projection
413/// the per-id door applies); rows past the retention window stay listed —
414/// opening one is what earns the `410`.
415///
416/// `source_id` narrows the list to the jobs that narrate one course note — the
417/// studio panel that lists a note's own episodes — while leaving the door's
418/// school scoping, ordering and projection untouched. Omitted, the response is
419/// the caller's whole history, unchanged.
420#[utoipa::path(
421 get,
422 path = "/jobs",
423 tag = "podcast",
424 security(("session_cookie" = [])),
425 params(PageParams, HistoryFilter),
426 responses(
427 (status = 200, description = "A page of the caller's episodes, newest first", body = Page<JobSummary>),
428 (status = 400, description = "Invalid limit, offset, or source_id", body = ErrorResponse),
429 (status = 401, description = "Not authenticated", body = ErrorResponse),
430 ),
431)]
432async fn list(
433 State(st): State<AppState>,
434 CurrentUser(user): CurrentUser,
435 Query(page): Query<PageParams>,
436 Query(filter): Query<HistoryFilter>,
437) -> Result<Json<Page<JobSummary>>, AppError> {
438 let (limit, offset) = page.resolve()?;
439 let source_id = filter.resolve()?;
440 let (jobs, total) =
441 jobs::list_for_user(&st.db, user.get_id(), source_id.as_ref(), limit, offset).await?;
442 let items = jobs
443 .into_iter()
444 .map(|(job, source_title)| JobSummary::new(&job.projected(), source_title))
445 .collect();
446 Ok(Json(Page::new(items, total, limit, offset)))
447}
448
449/// One job's current state — the backend's own row, so this door answers with
450/// the service down, restarted, or never connected at all. A job nobody has
451/// updated inside its ETA-scaled window reads as `failed`/`interrupted`; that
452/// projection is read-side only and never written.
453#[utoipa::path(
454 get,
455 path = "/jobs/{id}",
456 tag = "podcast",
457 security(("session_cookie" = [])),
458 params(("id" = String, Path, description = "Job id from `POST /podcast/jobs`")),
459 responses(
460 (status = 200, description = "The job as of now", body = JobStatus),
461 (status = 401, description = "Not authenticated", body = ErrorResponse),
462 (status = 404, description = "No such job for this caller (unknown id, or another user's)", body = ErrorResponse),
463 (status = 410, description = "The job is past its retention window", body = ErrorResponse),
464 ),
465)]
466async fn status(
467 State(st): State<AppState>,
468 CurrentUser(user): CurrentUser,
469 Path(id): Path<String>,
470) -> Result<Response, AppError> {
471 let job = owned(&st, &user, &id).await?;
472 Ok(Json(JobStatus {
473 job_id: job.get_id().key(),
474 state: job.get_state().as_str().to_string(),
475 stage: job.get_stage().to_string(),
476 progress: job.get_progress(),
477 error_code: job.get_error_code().map(str::to_string),
478 })
479 .into_response())
480}
481
482/// A finished job's artifact references. A job that has not finished is a
483/// `409 not_ready`; one the caller does not own, a `404`.
484#[utoipa::path(
485 get,
486 path = "/jobs/{id}/result",
487 tag = "podcast",
488 security(("session_cookie" = [])),
489 params(("id" = String, Path, description = "Job id from `POST /podcast/jobs`")),
490 responses(
491 (status = 200, description = "The finished job's artifacts", body = JobArtifacts),
492 (status = 401, description = "Not authenticated", body = ErrorResponse),
493 (status = 404, description = "No such job for this caller", body = ErrorResponse),
494 (status = 409, description = "The job has not finished (`code: not_ready`)", body = ErrorResponse),
495 (status = 410, description = "The job is past its retention window", body = ErrorResponse),
496 ),
497)]
498async fn result(
499 State(st): State<AppState>,
500 CurrentUser(user): CurrentUser,
501 Path(id): Path<String>,
502) -> Result<Response, AppError> {
503 let job = owned(&st, &user, &id).await?;
504 let audio_id = match job.get_state() {
505 crate::domain::podcast_job::PodcastJobState::Done => job
506 .get_audio_key()
507 .expect("a done row always carries its audio (schema CHECK)")
508 .to_string(),
509 _ => {
510 return Err(AppError::ConflictCoded {
511 code: "not_ready",
512 message: format!("job `{}` is {}", job.get_id().key(), job.get_state().as_str()),
513 });
514 }
515 };
516 Ok(Json(JobArtifacts {
517 job_id: job.get_id().key(),
518 audio_id,
519 duration_secs: job.get_duration_secs(),
520 format: job.get_format().map(str::to_string),
521 transcript: job.get_transcript().map(str::to_string),
522 sources: job.get_sources().map(|sources| {
523 serde_json::from_value(sources.clone())
524 .expect("the report decode guarantees the stored sources shape")
525 }),
526 })
527 .into_response())
528}
529
530/// Stream one produced episode. The bytes are this school's own — ingested
531/// under this school's blob directory — and the content type is the one the
532/// upload declared, replayed from the row.
533///
534/// A job that is not `done` is a `409 not_ready`; a row whose blob is missing
535/// from the host is a `409 audio_missing` (the row is intact, the bytes are
536/// not — a state a client can report, unlike a generic `500`).
537#[utoipa::path(
538 get,
539 path = "/jobs/{id}/audio",
540 tag = "podcast",
541 security(("session_cookie" = [])),
542 params(("id" = String, Path, description = "Job id from `POST /podcast/jobs`")),
543 responses(
544 (status = 200, description = "The audio bytes", content_type = "audio/mpeg"),
545 (status = 401, description = "Not authenticated", body = ErrorResponse),
546 (status = 404, description = "No such job for this caller", body = ErrorResponse),
547 (status = 409, description = "Not finished yet (`not_ready`), or its blob is missing from this host (`audio_missing`)", body = ErrorResponse),
548 (status = 410, description = "The job is past its retention window", body = ErrorResponse),
549 ),
550)]
551async fn audio(
552 State(st): State<AppState>,
553 CurrentUser(user): CurrentUser,
554 Path(id): Path<String>,
555) -> Result<Response, AppError> {
556 let job = owned(&st, &user, &id).await?;
557 let key = match job.get_state() {
558 crate::domain::podcast_job::PodcastJobState::Done => job
559 .get_audio_key()
560 .expect("a done row always carries its audio (schema CHECK)")
561 .to_string(),
562 _ => {
563 return Err(AppError::ConflictCoded {
564 code: "not_ready",
565 message: format!("job `{}` is {}", job.get_id().key(), job.get_state().as_str()),
566 });
567 }
568 };
569 let path = crate::web::blob_path(&st.files_path, &key);
570 let file = tokio::fs::File::open(&path).await.map_err(|err| {
571 tracing::error!("missing blob for podcast job {}: {err}", job.get_id().key());
572 AppError::ConflictCoded {
573 code: "audio_missing",
574 message: "the episode's file is missing on this host".to_string(),
575 }
576 })?;
577 let content_type = job.get_audio_type().unwrap_or("application/octet-stream");
578
579 Ok((
580 [
581 (
582 CONTENT_TYPE,
583 HeaderValue::from_str(content_type)
584 .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream")),
585 ),
586 (X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")),
587 (CACHE_CONTROL, HeaderValue::from_static("private, no-store")),
588 ],
589 Body::from_stream(pump(file)),
590 )
591 .into_response())
592}
593
594/// Cancel one job. `cancelled` says whether *this call* stopped work — a job
595/// that had already finished, or was already cancelled, answers `false` and is
596/// not an error. Only a live job needs the service; a terminal one is answered
597/// from the row without a worker. A service that has never heard of a live job
598/// (its store was wiped) leaves the row `failed`/`interrupted`: the job cannot
599/// finish, and the row says so.
600#[utoipa::path(
601 post,
602 path = "/jobs/{id}/cancel",
603 tag = "podcast",
604 security(("session_cookie" = [])),
605 params(("id" = String, Path, description = "Job id from `POST /podcast/jobs`")),
606 responses(
607 (status = 200, description = "The cancel verdict", body = CancelVerdict),
608 (status = 401, description = "Not authenticated", body = ErrorResponse),
609 (status = 404, description = "No such job for this caller", body = ErrorResponse),
610 (status = 410, description = "The job is past its retention window", body = ErrorResponse),
611 (status = 503, description = "The job is live but no AI service offers `podcast.cancel`", body = ErrorResponse),
612 ),
613)]
614async fn cancel(
615 State(st): State<AppState>,
616 SchoolIdCookie(school): SchoolIdCookie,
617 CurrentUser(user): CurrentUser,
618 Path(id): Path<String>,
619) -> Result<Response, AppError> {
620 let job = owned(&st, &user, &id).await?;
621 let job_id = job.get_id().key();
622 if job.get_state().is_terminal() {
623 return Ok(Json(CancelVerdict {
624 job_id,
625 cancelled: false,
626 })
627 .into_response());
628 }
629 let bridge = match worker_for(&st, AI_PODCAST_CANCEL_CAPABILITY) {
630 Ok(bridge) => bridge,
631 Err(no_worker) => return Ok(no_worker.refusal()),
632 };
633 let verdict = |cancelled: bool| {
634 Json(CancelVerdict {
635 job_id: job.get_id().key(),
636 cancelled,
637 })
638 .into_response()
639 };
640 match podcast::cancel(
641 &bridge,
642 &school,
643 PodcastCancelPayload {
644 job_id: job_id.clone(),
645 },
646 )
647 .await
648 {
649 Ok(reply) if reply.cancelled => {
650 jobs::mark_cancelled(&st.db, job.get_id()).await?;
651 Ok(verdict(true))
652 }
653 // Not cancelled by this call: either it finished first (its terminal
654 // report is on its way) or it was already cancelled.
655 Ok(_) => Ok(verdict(false)),
656 // The service has never heard of a job the row calls live — its store
657 // was wiped or rolled back. The row records the truth: it cannot finish.
658 Err(code) if code == "not_found" => {
659 tracing::warn!("AI podcast service lost live job {job_id}");
660 jobs::mark_failed(&st.db, job.get_id(), PODCAST_INTERRUPTED_CODE).await?;
661 Ok(verdict(false))
662 }
663 Err(code) => Ok(failure(&code)),
664 }
665}
666
667/// Read one job for this caller, projected and expiry-checked — the three
668/// reading doors' shared first act. A foreign id and an unknown id are the
669/// same `404`; a job past its retention window is a `410`.
670async fn owned(st: &AppState, user: &User, id: &str) -> Result<PodcastJob, AppError> {
671 let job = jobs::read_for(&st.db, &PodcastJobId::from_key(id), user.get_id())
672 .await?
673 .ok_or(AppError::NotFound)?
674 .projected();
675 if job.is_expired() {
676 return Err(AppError::Expired("this podcast job has expired"));
677 }
678 Ok(job)
679}
680
681/// Why a dispatching door has no worker to talk to. Deliberately small: the
682/// refusal is not a response — the caller builds the `503` at its own call
683/// site, so a large, rarely-taken `Response` never rides the `Result` type of
684/// a hot path.
685enum NoWorker {
686 /// No AI service is configured on this deployment at all.
687 Disabled,
688 /// A bridge is configured, but no connected worker declares this door's
689 /// capability.
690 Unconnected,
691}
692
693impl NoWorker {
694 /// The `503` the caller returns for this refusal.
695 fn refusal(self) -> Response {
696 ai_unavailable(match self {
697 NoWorker::Disabled => "the AI service is not enabled on this deployment",
698 NoWorker::Unconnected => "no AI service is connected right now",
699 })
700 }
701}
702
703/// The 503 gate the two dispatching doors share: no bridge configured, or no
704/// worker declaring this door's capability. `has_capability` is documented
705/// racy — fine here: it never guards a write, and the dispatch that follows
706/// re-checks for real; this only spares a caller a round trip into a service
707/// that cannot answer.
708fn worker_for(st: &AppState, capability: &str) -> Result<AiBridge, NoWorker> {
709 let Some(bridge) = st.ai.clone() else {
710 return Err(NoWorker::Disabled);
711 };
712 if !bridge.has_capability(capability) {
713 return Err(NoWorker::Unconnected);
714 }
715 Ok(bridge)
716}
717
718/// The submit door's own refusal: the note behind `source_id` cannot be
719/// narrated — it has no attachments, or the bytes every one of them names are
720/// gone from this host. One code (`source_missing`) for both, a message that
721/// says which side is missing, and a `409` either way, so a client branches on
722/// the code instead of parsing the sentence.
723fn source_missing(message: &str) -> AppError {
724 AppError::ConflictCoded {
725 code: "source_missing",
726 message: message.to_string(),
727 }
728}
729
730/// A relayed failure as the response a client branches on: the service's own
731/// code decides the status where it is one this backend knows, and anything
732/// else is a `502` — the backend cannot vouch for an answer it did not
733/// understand, and a gateway error is exactly that claim.
734fn failure(code: &str) -> Response {
735 let status = match code {
736 "bad_request" => StatusCode::BAD_REQUEST,
737 "not_found" => StatusCode::NOT_FOUND,
738 "not_ready" | "llm_unavailable" => StatusCode::CONFLICT,
739 "busy" | "unavailable" => StatusCode::SERVICE_UNAVAILABLE,
740 "timed_out" => StatusCode::GATEWAY_TIMEOUT,
741 "internal" => StatusCode::INTERNAL_SERVER_ERROR,
742 // `transport`, `protocol`, `bad_reply`, `service_error`, and any code
743 // the service invented: a bad gateway.
744 _ => StatusCode::BAD_GATEWAY,
745 };
746 (status, Json(json!({ "error": code }))).into_response()
747}