forge
Explore
Log in

Don't you dare go Hollow

The history can be scoped to one course note

Browse files at this commit

81a8384c885cd5459618826b369be7c3336b2e4cAhmet Kaan GümüşParent: 6ed7e12
  • feat
    • the history can be scoped to one course note
Show full message
🎧 feat(podcast): the history can be scoped to one course note

`GET /podcast/jobs` gains an optional `?source_id=` filter, so the studio
panel can list one note's own episodes instead of the caller's whole
history. The filter is part of the paging statement's `from_where`, so the
page and the count run the same predicate and `total` stays the filtered
count; the compare is `lower(source_id) = $2` against the canonical key, so
an equivalently-spelled note id still matches every row it names.

Omitted, the door answers exactly what it always did. A `source_id` that is
not a uuid is a `400` naming the field rather than a nil id answering a
silently empty page. School scoping, ordering and the staleness projection
are untouched: a foreign note id is an empty page, not a window across
schools.

The param is published on the route (`IntoParams` + `params(...)`); the
README endpoint table is unchanged.
src/db/podcast_job.rsmodified+19 -7
@@ -106,19 +106,31 @@ pub async fn read_for(
106106 /// count that pages the list must count jobs, and a join there could only
107107 /// multiply or drop one. A note that is gone answers `None` — the job stays
108108 /// in the caller's history either way.
109+///
110+/// `source_id` narrows the list to one course note when given, and leaves it
111+/// whole when absent. The filter is part of `from_where`, so the page and the
112+/// count run the *same* predicate — a `total` that disagreed with the window
113+/// would page forever. The stored column holds the string the submit door was
114+/// handed verbatim ([`crate::service::podcast_job::create`]), so the compare
115+/// is `lower(source_id) = $2` against the canonical key: an upper-case
116+/// spelling of the same note still matches, and a note whose jobs exist is
117+/// never silently reported empty.
109118 pub async fn list_for_user(
110119 db: &Database,
111120 user: &UserId,
121+ source_id: Option<&CourseNoteId>,
112122 limit: Option<i64>,
113123 offset: i64,
114124 ) -> Result<(Vec<(PodcastJob, Option<String>)>, i64), AppError> {
115- let (rows, total) = PagedList::new(
116- "podcast_job WHERE user_id = $1",
117- "ORDER BY created_at DESC, id DESC",
118- )
119- .bind(user.uuid())
120- .run::<PodcastJob>(limit, offset, db)
121- .await?;
125+ let from_where = match source_id {
126+ Some(_) => "podcast_job WHERE user_id = $1 AND lower(source_id) = $2",
127+ None => "podcast_job WHERE user_id = $1",
128+ };
129+ let mut list = PagedList::new(from_where, "ORDER BY created_at DESC, id DESC").bind(user.uuid());
130+ if let Some(source_id) = source_id {
131+ list = list.bind(source_id.key());
132+ }
133+ let (rows, total) = list.run::<PodcastJob>(limit, offset, db).await?;
122134 Ok((with_source_titles(db, rows).await?, total))
123135 }
124136
src/service/podcast_job.rsmodified+6 -1
@@ -11,6 +11,7 @@
1111
1212 use crate::database::Database;
1313 use crate::db::podcast_job;
14+use crate::domain::course_note::CourseNoteId;
1415 use crate::domain::podcast_job::{PodcastJob, PodcastJobId, PodcastJobState};
1516 use crate::domain::timestamp::Timestamp;
1617 use crate::domain::user::UserId;
@@ -151,13 +152,17 @@ pub async fn read_for(
151152 /// A user's own jobs, newest first, each paired with the title of the course
152153 /// note it narrates — `None` once that note is gone. The pairing is this
153154 /// list's whole extra read; everything else is the row.
155+///
156+/// `source_id` narrows the list to one course note; `None` leaves the whole
157+/// history, byte-for-byte the response it always was.
154158 pub async fn list_for_user(
155159 db: &Database,
156160 user: &UserId,
161+ source_id: Option<&CourseNoteId>,
157162 limit: Option<i64>,
158163 offset: i64,
159164 ) -> Result<(Vec<(PodcastJob, Option<String>)>, i64), AppError> {
160- podcast_job::list_for_user(db, user, limit, offset).await
165+ podcast_job::list_for_user(db, user, source_id, limit, offset).await
161166 }
162167
163168 /// Apply one report from the service. The order of the checks is the point:
src/web/podcast.rsmodified+52 -5
@@ -13,7 +13,8 @@
1313 //! Six doors:
1414 //!
1515 //! * `POST /podcast/jobs` — write the row, dispatch `podcast.submit`
16-//! * `GET /podcast/jobs` — the caller's own history, newest first
16+//! * `GET /podcast/jobs` — the caller's own history, newest first,
17+//! optionally narrowed to one course note (`?source_id=`)
1718 //! * `GET /podcast/jobs/{id}` — the row's snapshot (projected, see below)
1819 //! * `GET /podcast/jobs/{id}/result` — a finished job's artifact references
1920 //! * `GET /podcast/jobs/{id}/audio` — streams the ingested episode
@@ -55,7 +56,7 @@ use serde_json::json;
5556 use tokio::sync::mpsc;
5657 use tokio_stream::Stream;
5758 use tokio_stream::wrappers::ReceiverStream;
58-use utoipa::ToSchema;
59+use utoipa::{IntoParams, ToSchema};
5960 use utoipa_axum::router::OpenApiRouter;
6061 use utoipa_axum::routes;
6162
@@ -320,6 +321,44 @@ impl JobSummary {
320321 }
321322 }
322323
324+/// The optional `?source_id=` filter on the history: keep only the episodes
325+/// that narrate one course note. Omitted, the list is the caller's whole
326+/// history — the same response it has always been.
327+#[derive(Debug, Deserialize, IntoParams)]
328+struct HistoryFilter {
329+ /// Keep only the jobs that narrate this course note (a note id).
330+ #[param(example = "019732e3-7b00-7000-8000-00000000face")]
331+ source_id: Option<String>,
332+}
333+
334+impl HistoryFilter {
335+ /// Validate the filter into the note to scope by, or `None` for the whole
336+ /// history. The key is parsed the same way the submit door and the title
337+ /// lookup parse it ([`CourseNoteId::from_key`]): that path maps anything
338+ /// that is not a uuid to the nil id, so a key that lands there is refused
339+ /// rather than silently scoping to a note no row can name.
340+ fn resolve(&self) -> Result<Option<CourseNoteId>, AppError> {
341+ let Some(raw) = self.source_id.as_deref() else {
342+ return Ok(None);
343+ };
344+ let key = raw.trim();
345+ if key.is_empty() {
346+ return Err(AppError::Validation(ValidationError::Invalid {
347+ field: "source_id",
348+ reason: "must not be empty",
349+ }));
350+ }
351+ let note = CourseNoteId::from_key(key);
352+ if note.uuid().is_nil() {
353+ return Err(AppError::Validation(ValidationError::Invalid {
354+ field: "source_id",
355+ reason: "must be a hyphenated uuid",
356+ }));
357+ }
358+ Ok(Some(note))
359+ }
360+}
361+
323362 /// The caller's own episodes, newest first — every job the backend ever
324363 /// minted for this user, whatever state it stopped in, each with the title of
325364 /// the note it narrated. Paged via `?limit=&offset=`.
@@ -330,15 +369,20 @@ impl JobSummary {
330369 /// ETA-scaled window is presented as `failed` (the same read-side projection
331370 /// the per-id door applies); rows past the retention window stay listed —
332371 /// opening one is what earns the `410`.
372+///
373+/// `source_id` narrows the list to the jobs that narrate one course note — the
374+/// studio panel that lists a note's own episodes — while leaving the door's
375+/// school scoping, ordering and projection untouched. Omitted, the response is
376+/// the caller's whole history, unchanged.
333377 #[utoipa::path(
334378 get,
335379 path = "/jobs",
336380 tag = "podcast",
337381 security(("session_cookie" = [])),
338- params(PageParams),
382+ params(PageParams, HistoryFilter),
339383 responses(
340384 (status = 200, description = "A page of the caller's episodes, newest first", body = Page<JobSummary>),
341- (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
385+ (status = 400, description = "Invalid limit, offset, or source_id", body = ErrorResponse),
342386 (status = 401, description = "Not authenticated", body = ErrorResponse),
343387 ),
344388 )]
@@ -346,9 +390,12 @@ async fn list(
346390 State(st): State<AppState>,
347391 CurrentUser(user): CurrentUser,
348392 Query(page): Query<PageParams>,
393+ Query(filter): Query<HistoryFilter>,
349394 ) -> Result<Json<Page<JobSummary>>, AppError> {
350395 let (limit, offset) = page.resolve()?;
351- let (jobs, total) = jobs::list_for_user(&st.db, user.get_id(), limit, offset).await?;
396+ let source_id = filter.resolve()?;
397+ let (jobs, total) =
398+ jobs::list_for_user(&st.db, user.get_id(), source_id.as_ref(), limit, offset).await?;
352399 let items = jobs
353400 .into_iter()
354401 .map(|(job, source_title)| JobSummary::new(&job.projected(), source_title))
tests/podcast.rsmodified+116 -0
@@ -1091,6 +1091,103 @@ async fn an_empty_history_is_an_empty_page() {
10911091 assert!(res.body["limit"].is_null());
10921092 }
10931093
1094+/// `?source_id=` narrows the history to one note's own episodes — the studio
1095+/// panel's list — and `total` counts that same filtered predicate, so a client
1096+/// can page a scoped list. A note with no episodes is an empty page, not an
1097+/// error; omitting the filter still returns every job, so the absent case is
1098+/// exactly the response it always was.
1099+#[tokio::test]
1100+async fn the_history_scopes_to_one_note_when_asked() {
1101+ let (app, cookie, db) = app_without_ai().await;
1102+ let teacher = common::login_as(&app, &db, "hoca", "teacher").await;
1103+ let course = common::create_course(&app, &teacher, "Matematik").await;
1104+ let first = create_note(&app, &teacher, &course).await;
1105+ let second = create_note(&app, &teacher, &course).await;
1106+ let empty = create_note(&app, &teacher, &course).await;
1107+ let user = common::me_id(&app, &cookie).await;
1108+ let base = now_ms() - 3 * 60 * 60 * 1_000;
1109+ let older = seed_listed_job(&db, Uuid::now_v7(), &user, &first, "done", base).await;
1110+ let newer = seed_listed_job(
1111+ &db,
1112+ Uuid::now_v7(),
1113+ &user,
1114+ &first,
1115+ "failed",
1116+ base + 3_600_000,
1117+ )
1118+ .await;
1119+ let other = seed_listed_job(
1120+ &db,
1121+ Uuid::now_v7(),
1122+ &user,
1123+ &second,
1124+ "done",
1125+ base + 7_200_000,
1126+ )
1127+ .await;
1128+
1129+ let scoped = list_of(&app, &cookie, &format!("?source_id={first}")).await;
1130+ assert_eq!(scoped.status, StatusCode::OK, "{}", scoped.body);
1131+ assert_eq!(scoped.body["total"], 2, "the count is the filtered count");
1132+ assert_eq!(
1133+ ids_of(&scoped.body),
1134+ vec![newer.to_string(), older.to_string()],
1135+ "newest first, and only the asked note's rows"
1136+ );
1137+ assert!(
1138+ scoped.body["items"]
1139+ .as_array()
1140+ .expect("items")
1141+ .iter()
1142+ .all(|item| item["source_id"] == first),
1143+ "every row narrates the asked note: {}",
1144+ scoped.body
1145+ );
1146+
1147+ let second_only = list_of(&app, &cookie, &format!("?source_id={second}")).await;
1148+ assert_eq!(second_only.status, StatusCode::OK, "{}", second_only.body);
1149+ assert_eq!(second_only.body["total"], 1);
1150+ assert_eq!(ids_of(&second_only.body), vec![other.to_string()]);
1151+
1152+ let none = list_of(&app, &cookie, &format!("?source_id={empty}")).await;
1153+ assert_eq!(none.status, StatusCode::OK, "{}", none.body);
1154+ assert_eq!(none.body["total"], 0, "a note with no episodes is an empty page");
1155+ assert!(ids_of(&none.body).is_empty());
1156+
1157+ let all = list_of(&app, &cookie, "").await;
1158+ assert_eq!(all.status, StatusCode::OK, "{}", all.body);
1159+ assert_eq!(all.body["total"], 3, "omitting the filter returns every job");
1160+ assert_eq!(ids_of(&all.body).len(), 3);
1161+}
1162+
1163+/// A `source_id` that is not a uuid is a `400` naming the field — refused
1164+/// rather than parsed to the nil id and answering an empty page that hides the
1165+/// caller's typo.
1166+#[tokio::test]
1167+async fn a_malformed_source_filter_is_refused() {
1168+ let (app, cookie, db) = app_without_ai().await;
1169+ let user = common::me_id(&app, &cookie).await;
1170+ let _ = seed_listed_job(&db, Uuid::now_v7(), &user, SOURCE_ID, "done", now_ms()).await;
1171+
1172+ for bad in ["not-a-uuid", "%20", ""] {
1173+ let res = list_of(&app, &cookie, &format!("?source_id={bad}")).await;
1174+ assert_eq!(
1175+ res.status,
1176+ StatusCode::BAD_REQUEST,
1177+ "source_id={bad:?}: {}",
1178+ res.body
1179+ );
1180+ assert!(
1181+ res.body["error"]
1182+ .as_str()
1183+ .expect("an error")
1184+ .contains("source_id"),
1185+ "the refusal names the field: {}",
1186+ res.body
1187+ );
1188+ }
1189+}
1190+
10941191 /// A live job lists as itself, with everything only a finished episode can
10951192 /// know left `null` — and a job nobody has updated inside its ETA-scaled
10961193 /// window reads `failed`/`interrupted`, the same read-side projection the
@@ -1182,6 +1279,25 @@ async fn the_history_never_shows_another_schools_jobs() {
11821279 assert_eq!(beta_list.body["total"], 1);
11831280 assert_eq!(ids_of(&beta_list.body), vec![beta_job.to_string()]);
11841281 assert_ne!(beta_list.body["items"][0]["job_id"], demo_job.to_string());
1282+
1283+ // The filter is school-scoped like the list itself: the demo school's own
1284+ // note scopes to its one job, and the other school's note id names no job
1285+ // here, whichever side asks — a foreign note id is an empty page, not a
1286+ // window into the other school.
1287+ let demo_scoped = list_of(app, &demo_cookie, &format!("?source_id={demo_note}")).await;
1288+ assert_eq!(demo_scoped.status, StatusCode::OK, "{}", demo_scoped.body);
1289+ assert_eq!(demo_scoped.body["total"], 1);
1290+ assert_eq!(ids_of(&demo_scoped.body), vec![demo_job.to_string()]);
1291+
1292+ let cross = list_of(app, &demo_cookie, &format!("?source_id={SOURCE_ID}")).await;
1293+ assert_eq!(cross.status, StatusCode::OK, "{}", cross.body);
1294+ assert_eq!(cross.body["total"], 0, "beta's note names no demo job");
1295+ assert!(ids_of(&cross.body).is_empty());
1296+
1297+ let cross_back = list_of(app, &beta_cookie, &format!("?source_id={demo_note}")).await;
1298+ assert_eq!(cross_back.status, StatusCode::OK, "{}", cross_back.body);
1299+ assert_eq!(cross_back.body["total"], 0, "demo's note names no beta job");
1300+ assert!(ids_of(&cross_back.body).is_empty());
11851301 }
11861302
11871303 // --------------------------------------------------------------- refusals --