diff --git a/src/db/podcast_job.rs b/src/db/podcast_job.rs index 7714cfd..39e80fc 100644 --- a/src/db/podcast_job.rs +++ b/src/db/podcast_job.rs @@ -106,19 +106,31 @@ pub async fn read_for( /// count that pages the list must count jobs, and a join there could only /// multiply or drop one. A note that is gone answers `None` — the job stays /// in the caller's history either way. +/// +/// `source_id` narrows the list to one course note when given, and leaves it +/// whole when absent. The filter is part of `from_where`, so the page and the +/// count run the *same* predicate — a `total` that disagreed with the window +/// would page forever. The stored column holds the string the submit door was +/// handed verbatim ([`crate::service::podcast_job::create`]), so the compare +/// is `lower(source_id) = $2` against the canonical key: an upper-case +/// spelling of the same note still matches, and a note whose jobs exist is +/// never silently reported empty. pub async fn list_for_user( db: &Database, user: &UserId, + source_id: Option<&CourseNoteId>, limit: Option, offset: i64, ) -> Result<(Vec<(PodcastJob, Option)>, i64), AppError> { - let (rows, total) = PagedList::new( - "podcast_job WHERE user_id = $1", - "ORDER BY created_at DESC, id DESC", - ) - .bind(user.uuid()) - .run::(limit, offset, db) - .await?; + let from_where = match source_id { + Some(_) => "podcast_job WHERE user_id = $1 AND lower(source_id) = $2", + None => "podcast_job WHERE user_id = $1", + }; + let mut list = PagedList::new(from_where, "ORDER BY created_at DESC, id DESC").bind(user.uuid()); + if let Some(source_id) = source_id { + list = list.bind(source_id.key()); + } + let (rows, total) = list.run::(limit, offset, db).await?; Ok((with_source_titles(db, rows).await?, total)) } diff --git a/src/service/podcast_job.rs b/src/service/podcast_job.rs index 456572f..5fbf298 100644 --- a/src/service/podcast_job.rs +++ b/src/service/podcast_job.rs @@ -11,6 +11,7 @@ use crate::database::Database; use crate::db::podcast_job; +use crate::domain::course_note::CourseNoteId; use crate::domain::podcast_job::{PodcastJob, PodcastJobId, PodcastJobState}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -151,13 +152,17 @@ pub async fn read_for( /// A user's own jobs, newest first, each paired with the title of the course /// note it narrates — `None` once that note is gone. The pairing is this /// list's whole extra read; everything else is the row. +/// +/// `source_id` narrows the list to one course note; `None` leaves the whole +/// history, byte-for-byte the response it always was. pub async fn list_for_user( db: &Database, user: &UserId, + source_id: Option<&CourseNoteId>, limit: Option, offset: i64, ) -> Result<(Vec<(PodcastJob, Option)>, i64), AppError> { - podcast_job::list_for_user(db, user, limit, offset).await + podcast_job::list_for_user(db, user, source_id, limit, offset).await } /// Apply one report from the service. The order of the checks is the point: diff --git a/src/web/podcast.rs b/src/web/podcast.rs index 480cb34..060cb40 100644 --- a/src/web/podcast.rs +++ b/src/web/podcast.rs @@ -13,7 +13,8 @@ //! Six doors: //! //! * `POST /podcast/jobs` — write the row, dispatch `podcast.submit` -//! * `GET /podcast/jobs` — the caller's own history, newest first +//! * `GET /podcast/jobs` — the caller's own history, newest first, +//! optionally narrowed to one course note (`?source_id=`) //! * `GET /podcast/jobs/{id}` — the row's snapshot (projected, see below) //! * `GET /podcast/jobs/{id}/result` — a finished job's artifact references //! * `GET /podcast/jobs/{id}/audio` — streams the ingested episode @@ -55,7 +56,7 @@ use serde_json::json; use tokio::sync::mpsc; use tokio_stream::Stream; use tokio_stream::wrappers::ReceiverStream; -use utoipa::ToSchema; +use utoipa::{IntoParams, ToSchema}; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; @@ -320,6 +321,44 @@ impl JobSummary { } } +/// The optional `?source_id=` filter on the history: keep only the episodes +/// that narrate one course note. Omitted, the list is the caller's whole +/// history — the same response it has always been. +#[derive(Debug, Deserialize, IntoParams)] +struct HistoryFilter { + /// Keep only the jobs that narrate this course note (a note id). + #[param(example = "019732e3-7b00-7000-8000-00000000face")] + source_id: Option, +} + +impl HistoryFilter { + /// Validate the filter into the note to scope by, or `None` for the whole + /// history. The key is parsed the same way the submit door and the title + /// lookup parse it ([`CourseNoteId::from_key`]): that path maps anything + /// that is not a uuid to the nil id, so a key that lands there is refused + /// rather than silently scoping to a note no row can name. + fn resolve(&self) -> Result, AppError> { + let Some(raw) = self.source_id.as_deref() else { + return Ok(None); + }; + let key = raw.trim(); + if key.is_empty() { + return Err(AppError::Validation(ValidationError::Invalid { + field: "source_id", + reason: "must not be empty", + })); + } + let note = CourseNoteId::from_key(key); + if note.uuid().is_nil() { + return Err(AppError::Validation(ValidationError::Invalid { + field: "source_id", + reason: "must be a hyphenated uuid", + })); + } + Ok(Some(note)) + } +} + /// The caller's own episodes, newest first — every job the backend ever /// minted for this user, whatever state it stopped in, each with the title of /// the note it narrated. Paged via `?limit=&offset=`. @@ -330,15 +369,20 @@ impl JobSummary { /// ETA-scaled window is presented as `failed` (the same read-side projection /// the per-id door applies); rows past the retention window stay listed — /// opening one is what earns the `410`. +/// +/// `source_id` narrows the list to the jobs that narrate one course note — the +/// studio panel that lists a note's own episodes — while leaving the door's +/// school scoping, ordering and projection untouched. Omitted, the response is +/// the caller's whole history, unchanged. #[utoipa::path( get, path = "/jobs", tag = "podcast", security(("session_cookie" = [])), - params(PageParams), + params(PageParams, HistoryFilter), responses( (status = 200, description = "A page of the caller's episodes, newest first", body = Page), - (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 400, description = "Invalid limit, offset, or source_id", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] @@ -346,9 +390,12 @@ async fn list( State(st): State, CurrentUser(user): CurrentUser, Query(page): Query, + Query(filter): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let (jobs, total) = jobs::list_for_user(&st.db, user.get_id(), limit, offset).await?; + let source_id = filter.resolve()?; + let (jobs, total) = + jobs::list_for_user(&st.db, user.get_id(), source_id.as_ref(), limit, offset).await?; let items = jobs .into_iter() .map(|(job, source_title)| JobSummary::new(&job.projected(), source_title)) diff --git a/tests/podcast.rs b/tests/podcast.rs index d00241d..287dfe0 100644 --- a/tests/podcast.rs +++ b/tests/podcast.rs @@ -1091,6 +1091,103 @@ async fn an_empty_history_is_an_empty_page() { assert!(res.body["limit"].is_null()); } +/// `?source_id=` narrows the history to one note's own episodes — the studio +/// panel's list — and `total` counts that same filtered predicate, so a client +/// can page a scoped list. A note with no episodes is an empty page, not an +/// error; omitting the filter still returns every job, so the absent case is +/// exactly the response it always was. +#[tokio::test] +async fn the_history_scopes_to_one_note_when_asked() { + let (app, cookie, db) = app_without_ai().await; + let teacher = common::login_as(&app, &db, "hoca", "teacher").await; + let course = common::create_course(&app, &teacher, "Matematik").await; + let first = create_note(&app, &teacher, &course).await; + let second = create_note(&app, &teacher, &course).await; + let empty = create_note(&app, &teacher, &course).await; + let user = common::me_id(&app, &cookie).await; + let base = now_ms() - 3 * 60 * 60 * 1_000; + let older = seed_listed_job(&db, Uuid::now_v7(), &user, &first, "done", base).await; + let newer = seed_listed_job( + &db, + Uuid::now_v7(), + &user, + &first, + "failed", + base + 3_600_000, + ) + .await; + let other = seed_listed_job( + &db, + Uuid::now_v7(), + &user, + &second, + "done", + base + 7_200_000, + ) + .await; + + let scoped = list_of(&app, &cookie, &format!("?source_id={first}")).await; + assert_eq!(scoped.status, StatusCode::OK, "{}", scoped.body); + assert_eq!(scoped.body["total"], 2, "the count is the filtered count"); + assert_eq!( + ids_of(&scoped.body), + vec![newer.to_string(), older.to_string()], + "newest first, and only the asked note's rows" + ); + assert!( + scoped.body["items"] + .as_array() + .expect("items") + .iter() + .all(|item| item["source_id"] == first), + "every row narrates the asked note: {}", + scoped.body + ); + + let second_only = list_of(&app, &cookie, &format!("?source_id={second}")).await; + assert_eq!(second_only.status, StatusCode::OK, "{}", second_only.body); + assert_eq!(second_only.body["total"], 1); + assert_eq!(ids_of(&second_only.body), vec![other.to_string()]); + + let none = list_of(&app, &cookie, &format!("?source_id={empty}")).await; + assert_eq!(none.status, StatusCode::OK, "{}", none.body); + assert_eq!(none.body["total"], 0, "a note with no episodes is an empty page"); + assert!(ids_of(&none.body).is_empty()); + + let all = list_of(&app, &cookie, "").await; + assert_eq!(all.status, StatusCode::OK, "{}", all.body); + assert_eq!(all.body["total"], 3, "omitting the filter returns every job"); + assert_eq!(ids_of(&all.body).len(), 3); +} + +/// A `source_id` that is not a uuid is a `400` naming the field — refused +/// rather than parsed to the nil id and answering an empty page that hides the +/// caller's typo. +#[tokio::test] +async fn a_malformed_source_filter_is_refused() { + let (app, cookie, db) = app_without_ai().await; + let user = common::me_id(&app, &cookie).await; + let _ = seed_listed_job(&db, Uuid::now_v7(), &user, SOURCE_ID, "done", now_ms()).await; + + for bad in ["not-a-uuid", "%20", ""] { + let res = list_of(&app, &cookie, &format!("?source_id={bad}")).await; + assert_eq!( + res.status, + StatusCode::BAD_REQUEST, + "source_id={bad:?}: {}", + res.body + ); + assert!( + res.body["error"] + .as_str() + .expect("an error") + .contains("source_id"), + "the refusal names the field: {}", + res.body + ); + } +} + /// A live job lists as itself, with everything only a finished episode can /// know left `null` — and a job nobody has updated inside its ETA-scaled /// window reads `failed`/`interrupted`, the same read-side projection the @@ -1182,6 +1279,25 @@ async fn the_history_never_shows_another_schools_jobs() { assert_eq!(beta_list.body["total"], 1); assert_eq!(ids_of(&beta_list.body), vec![beta_job.to_string()]); assert_ne!(beta_list.body["items"][0]["job_id"], demo_job.to_string()); + + // The filter is school-scoped like the list itself: the demo school's own + // note scopes to its one job, and the other school's note id names no job + // here, whichever side asks — a foreign note id is an empty page, not a + // window into the other school. + let demo_scoped = list_of(app, &demo_cookie, &format!("?source_id={demo_note}")).await; + assert_eq!(demo_scoped.status, StatusCode::OK, "{}", demo_scoped.body); + assert_eq!(demo_scoped.body["total"], 1); + assert_eq!(ids_of(&demo_scoped.body), vec![demo_job.to_string()]); + + let cross = list_of(app, &demo_cookie, &format!("?source_id={SOURCE_ID}")).await; + assert_eq!(cross.status, StatusCode::OK, "{}", cross.body); + assert_eq!(cross.body["total"], 0, "beta's note names no demo job"); + assert!(ids_of(&cross.body).is_empty()); + + let cross_back = list_of(app, &beta_cookie, &format!("?source_id={demo_note}")).await; + assert_eq!(cross_back.status, StatusCode::OK, "{}", cross_back.body); + assert_eq!(cross_back.body["total"], 0, "demo's note names no beta job"); + assert!(ids_of(&cross_back.body).is_empty()); } // --------------------------------------------------------------- refusals --