From 979d53ff4e87fc1e436834bc111b8a654b1a84c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 23 Sep 2026 14:24:02 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(podcast):=20dispatch=20every?= =?UTF-8?q?=20attachment=20as=20sources,=20not=20just=20the=20newest=20PDF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The submit door now lists all of the note's attachments (id ASC), stats each blob, and dispatches the present ones as `sources` — `source_key` rides on as the first source's key, one-release compat. A blob that is gone is skipped with a log line; `409 source_missing` now means zero attachments or zero present blobs, and a note id with any single attachment is a valid job. `podcast.report` gains additive `sources` (`{key, name, status}`, `ok` or `skipped:`), stored verbatim into the job row's new JSONB `sources` column and replayed by `GET /podcast/jobs/{id}/result`. `newest_pdf` is deleted with its service wrapper — clean cutover. Local-Gate: fe26c0cd12b31b6a48cacff9a3a6119bd241d89e (1518 passed, 459s) --- ...0cf16978179c96a0beac016b39a4cd74aa39.json} | 38 +++-- ...4b5ae9030899c067026f218ce02d6a7528cb.json} | 38 +++-- ...ec191a369da3e0e29966b6d0f0830b5ddb6e.json} | 38 +++-- ...4780cba13e76123e7d9f4f9d64c17ca5105b.json} | 38 +++-- ...bfd31de8ca2fe54ddf8cd19e0653de7711cf.json} | 38 +++-- ...83be29811979fcfa869677c8dbbe5d19e2a8.json} | 39 +++-- ...ac43234ee56ca59e70693e2d920c5a227a86.json} | 41 +++-- ...fb4add9e70c39cc9095ddafd3693e27f7bfd.json} | 38 +++-- ...83dd9869275117ab83a255dac8de33b35725c.json | 76 --------- .../school/20260923000002_podcast_sources.sql | 11 ++ src/ai/podcast.rs | 59 +++++-- src/db/course_note_file.rs | 25 --- src/db/podcast_job.rs | 45 +++-- src/domain/podcast_job.rs | 12 ++ src/lib.rs | 2 +- src/service/course_note_file.rs | 9 - src/service/podcast_job.rs | 24 +++ src/web/podcast.rs | 117 +++++++++---- tests/podcast.rs | 157 ++++++++++++++---- 19 files changed, 536 insertions(+), 309 deletions(-) rename .sqlx/{query-b3044b692a7cca8eb27c9060462465df513a477b6f67329ea555ed41c87919d0.json => query-1ac7a9d2e2b86e6b1a44f58c2c630cf16978179c96a0beac016b39a4cd74aa39.json} (87%) rename .sqlx/{query-37c8e360c3557ede7f79c9f210984598576292ee347427e1a54441bceb88ed12.json => query-1b8d4d66fc69afb04cc66fc0e0e34b5ae9030899c067026f218ce02d6a7528cb.json} (87%) rename .sqlx/{query-4b05eec4ece0295d6be7ce2b92238e49fabe71d62b021c1d1425e51d9f1adbe3.json => query-26c326f8fce441ccc6dcb8cf8c4aec191a369da3e0e29966b6d0f0830b5ddb6e.json} (87%) rename .sqlx/{query-45ade92df6adc604f90c5e2111fc4bd23b8c6e901d81ca64a96bef3116ab906f.json => query-3e66c333be0794213c6c6f077e184780cba13e76123e7d9f4f9d64c17ca5105b.json} (86%) rename .sqlx/{query-814486dbb11e8eeaf410bced5a0aae724aa3f0198ce4204cd94016b827ab55b7.json => query-63f0dc707ee7f6fe9976a0e903b8bfd31de8ca2fe54ddf8cd19e0653de7711cf.json} (87%) rename .sqlx/{query-f40008ce74997412bd8099f21cc58579d2c6efc73d04072849fe650a737e7a4c.json => query-6b6ca993e9600caf8a4066432a7583be29811979fcfa869677c8dbbe5d19e2a8.json} (84%) rename .sqlx/{query-cabbdce4f24ffcd7792dc8b9b9f72d02d920bf9fabc10c61584b0bd64c7712ff.json => query-beb6594d280ac53dbb187850d195ac43234ee56ca59e70693e2d920c5a227a86.json} (85%) rename .sqlx/{query-d1b16c756ea05fe53f875c57b4d46dfdc152943eb31d5df4c531af6da3e6ec7b.json => query-cb286f2c1e63c638be8a58c0b9b0fb4add9e70c39cc9095ddafd3693e27f7bfd.json} (86%) delete mode 100644 .sqlx/query-e1bd89bafa14d3594316fc1768683dd9869275117ab83a255dac8de33b35725c.json create mode 100644 migrations/school/20260923000002_podcast_sources.sql diff --git a/.sqlx/query-b3044b692a7cca8eb27c9060462465df513a477b6f67329ea555ed41c87919d0.json b/.sqlx/query-1ac7a9d2e2b86e6b1a44f58c2c630cf16978179c96a0beac016b39a4cd74aa39.json similarity index 87% rename from .sqlx/query-b3044b692a7cca8eb27c9060462465df513a477b6f67329ea555ed41c87919d0.json rename to .sqlx/query-1ac7a9d2e2b86e6b1a44f58c2c630cf16978179c96a0beac016b39a4cd74aa39.json index 280536d..3a256f4 100644 --- a/.sqlx/query-b3044b692a7cca8eb27c9060462465df513a477b6f67329ea555ed41c87919d0.json +++ b/.sqlx/query-1ac7a9d2e2b86e6b1a44f58c2c630cf16978179c96a0beac016b39a4cd74aa39.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE podcast_job SET audio_key = $2, audio_name = $3, audio_type = $4, audio_bytes = $5, duration_secs = $6, updated_at = $7 WHERE id = $1 RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, transcript, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", + "query": "UPDATE podcast_job SET audio_key = $2, audio_name = $3, audio_type = $4, audio_bytes = $5, duration_secs = $6, updated_at = $7 WHERE id = $1 RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, transcript, sources AS \"sources: Json\", state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", "describe": { "columns": [ { @@ -60,6 +60,17 @@ }, { "ordinal": 5, + "name": "sources: Json", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "podcast_job", + "name": "sources" + } + } + }, + { + "ordinal": 6, "name": "state: PodcastJobState", "type_info": "Text", "origin": { @@ -70,7 +81,7 @@ } }, { - "ordinal": 6, + "ordinal": 7, "name": "stage", "type_info": "Text", "origin": { @@ -81,7 +92,7 @@ } }, { - "ordinal": 7, + "ordinal": 8, "name": "progress", "type_info": "Float8", "origin": { @@ -92,7 +103,7 @@ } }, { - "ordinal": 8, + "ordinal": 9, "name": "error_code", "type_info": "Text", "origin": { @@ -103,7 +114,7 @@ } }, { - "ordinal": 9, + "ordinal": 10, "name": "audio_key", "type_info": "Text", "origin": { @@ -114,7 +125,7 @@ } }, { - "ordinal": 10, + "ordinal": 11, "name": "audio_name", "type_info": "Text", "origin": { @@ -125,7 +136,7 @@ } }, { - "ordinal": 11, + "ordinal": 12, "name": "audio_type", "type_info": "Text", "origin": { @@ -136,7 +147,7 @@ } }, { - "ordinal": 12, + "ordinal": 13, "name": "audio_bytes", "type_info": "Int8", "origin": { @@ -147,7 +158,7 @@ } }, { - "ordinal": 13, + "ordinal": 14, "name": "duration_secs", "type_info": "Float8", "origin": { @@ -158,7 +169,7 @@ } }, { - "ordinal": 14, + "ordinal": 15, "name": "eta_secs", "type_info": "Int8", "origin": { @@ -169,7 +180,7 @@ } }, { - "ordinal": 15, + "ordinal": 16, "name": "created_at: Timestamp", "type_info": "Int8", "origin": { @@ -180,7 +191,7 @@ } }, { - "ordinal": 16, + "ordinal": 17, "name": "updated_at: Timestamp", "type_info": "Int8", "origin": { @@ -208,6 +219,7 @@ false, true, true, + true, false, false, false, @@ -222,5 +234,5 @@ false ] }, - "hash": "b3044b692a7cca8eb27c9060462465df513a477b6f67329ea555ed41c87919d0" + "hash": "1ac7a9d2e2b86e6b1a44f58c2c630cf16978179c96a0beac016b39a4cd74aa39" } diff --git a/.sqlx/query-37c8e360c3557ede7f79c9f210984598576292ee347427e1a54441bceb88ed12.json b/.sqlx/query-1b8d4d66fc69afb04cc66fc0e0e34b5ae9030899c067026f218ce02d6a7528cb.json similarity index 87% rename from .sqlx/query-37c8e360c3557ede7f79c9f210984598576292ee347427e1a54441bceb88ed12.json rename to .sqlx/query-1b8d4d66fc69afb04cc66fc0e0e34b5ae9030899c067026f218ce02d6a7528cb.json index aca455a..3519fe4 100644 --- a/.sqlx/query-37c8e360c3557ede7f79c9f210984598576292ee347427e1a54441bceb88ed12.json +++ b/.sqlx/query-1b8d4d66fc69afb04cc66fc0e0e34b5ae9030899c067026f218ce02d6a7528cb.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE podcast_job SET eta_secs = $2 WHERE id = $1 RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, transcript, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", + "query": "UPDATE podcast_job SET eta_secs = $2 WHERE id = $1 RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, transcript, sources AS \"sources: Json\", state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", "describe": { "columns": [ { @@ -60,6 +60,17 @@ }, { "ordinal": 5, + "name": "sources: Json", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "podcast_job", + "name": "sources" + } + } + }, + { + "ordinal": 6, "name": "state: PodcastJobState", "type_info": "Text", "origin": { @@ -70,7 +81,7 @@ } }, { - "ordinal": 6, + "ordinal": 7, "name": "stage", "type_info": "Text", "origin": { @@ -81,7 +92,7 @@ } }, { - "ordinal": 7, + "ordinal": 8, "name": "progress", "type_info": "Float8", "origin": { @@ -92,7 +103,7 @@ } }, { - "ordinal": 8, + "ordinal": 9, "name": "error_code", "type_info": "Text", "origin": { @@ -103,7 +114,7 @@ } }, { - "ordinal": 9, + "ordinal": 10, "name": "audio_key", "type_info": "Text", "origin": { @@ -114,7 +125,7 @@ } }, { - "ordinal": 10, + "ordinal": 11, "name": "audio_name", "type_info": "Text", "origin": { @@ -125,7 +136,7 @@ } }, { - "ordinal": 11, + "ordinal": 12, "name": "audio_type", "type_info": "Text", "origin": { @@ -136,7 +147,7 @@ } }, { - "ordinal": 12, + "ordinal": 13, "name": "audio_bytes", "type_info": "Int8", "origin": { @@ -147,7 +158,7 @@ } }, { - "ordinal": 13, + "ordinal": 14, "name": "duration_secs", "type_info": "Float8", "origin": { @@ -158,7 +169,7 @@ } }, { - "ordinal": 14, + "ordinal": 15, "name": "eta_secs", "type_info": "Int8", "origin": { @@ -169,7 +180,7 @@ } }, { - "ordinal": 15, + "ordinal": 16, "name": "created_at: Timestamp", "type_info": "Int8", "origin": { @@ -180,7 +191,7 @@ } }, { - "ordinal": 16, + "ordinal": 17, "name": "updated_at: Timestamp", "type_info": "Int8", "origin": { @@ -203,6 +214,7 @@ false, true, true, + true, false, false, false, @@ -217,5 +229,5 @@ false ] }, - "hash": "37c8e360c3557ede7f79c9f210984598576292ee347427e1a54441bceb88ed12" + "hash": "1b8d4d66fc69afb04cc66fc0e0e34b5ae9030899c067026f218ce02d6a7528cb" } diff --git a/.sqlx/query-4b05eec4ece0295d6be7ce2b92238e49fabe71d62b021c1d1425e51d9f1adbe3.json b/.sqlx/query-26c326f8fce441ccc6dcb8cf8c4aec191a369da3e0e29966b6d0f0830b5ddb6e.json similarity index 87% rename from .sqlx/query-4b05eec4ece0295d6be7ce2b92238e49fabe71d62b021c1d1425e51d9f1adbe3.json rename to .sqlx/query-26c326f8fce441ccc6dcb8cf8c4aec191a369da3e0e29966b6d0f0830b5ddb6e.json index 0d966c8..78a8d8f 100644 --- a/.sqlx/query-4b05eec4ece0295d6be7ce2b92238e49fabe71d62b021c1d1425e51d9f1adbe3.json +++ b/.sqlx/query-26c326f8fce441ccc6dcb8cf8c4aec191a369da3e0e29966b6d0f0830b5ddb6e.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE podcast_job SET state = 'cancelled', stage = '', updated_at = $2 WHERE id = $1 AND state IN ('queued', 'running') RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, transcript, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", + "query": "UPDATE podcast_job SET state = 'cancelled', stage = '', updated_at = $2 WHERE id = $1 AND state IN ('queued', 'running') RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, transcript, sources AS \"sources: Json\", state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", "describe": { "columns": [ { @@ -60,6 +60,17 @@ }, { "ordinal": 5, + "name": "sources: Json", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "podcast_job", + "name": "sources" + } + } + }, + { + "ordinal": 6, "name": "state: PodcastJobState", "type_info": "Text", "origin": { @@ -70,7 +81,7 @@ } }, { - "ordinal": 6, + "ordinal": 7, "name": "stage", "type_info": "Text", "origin": { @@ -81,7 +92,7 @@ } }, { - "ordinal": 7, + "ordinal": 8, "name": "progress", "type_info": "Float8", "origin": { @@ -92,7 +103,7 @@ } }, { - "ordinal": 8, + "ordinal": 9, "name": "error_code", "type_info": "Text", "origin": { @@ -103,7 +114,7 @@ } }, { - "ordinal": 9, + "ordinal": 10, "name": "audio_key", "type_info": "Text", "origin": { @@ -114,7 +125,7 @@ } }, { - "ordinal": 10, + "ordinal": 11, "name": "audio_name", "type_info": "Text", "origin": { @@ -125,7 +136,7 @@ } }, { - "ordinal": 11, + "ordinal": 12, "name": "audio_type", "type_info": "Text", "origin": { @@ -136,7 +147,7 @@ } }, { - "ordinal": 12, + "ordinal": 13, "name": "audio_bytes", "type_info": "Int8", "origin": { @@ -147,7 +158,7 @@ } }, { - "ordinal": 13, + "ordinal": 14, "name": "duration_secs", "type_info": "Float8", "origin": { @@ -158,7 +169,7 @@ } }, { - "ordinal": 14, + "ordinal": 15, "name": "eta_secs", "type_info": "Int8", "origin": { @@ -169,7 +180,7 @@ } }, { - "ordinal": 15, + "ordinal": 16, "name": "created_at: Timestamp", "type_info": "Int8", "origin": { @@ -180,7 +191,7 @@ } }, { - "ordinal": 16, + "ordinal": 17, "name": "updated_at: Timestamp", "type_info": "Int8", "origin": { @@ -203,6 +214,7 @@ false, true, true, + true, false, false, false, @@ -217,5 +229,5 @@ false ] }, - "hash": "4b05eec4ece0295d6be7ce2b92238e49fabe71d62b021c1d1425e51d9f1adbe3" + "hash": "26c326f8fce441ccc6dcb8cf8c4aec191a369da3e0e29966b6d0f0830b5ddb6e" } diff --git a/.sqlx/query-45ade92df6adc604f90c5e2111fc4bd23b8c6e901d81ca64a96bef3116ab906f.json b/.sqlx/query-3e66c333be0794213c6c6f077e184780cba13e76123e7d9f4f9d64c17ca5105b.json similarity index 86% rename from .sqlx/query-45ade92df6adc604f90c5e2111fc4bd23b8c6e901d81ca64a96bef3116ab906f.json rename to .sqlx/query-3e66c333be0794213c6c6f077e184780cba13e76123e7d9f4f9d64c17ca5105b.json index 664a2b3..268afcd 100644 --- a/.sqlx/query-45ade92df6adc604f90c5e2111fc4bd23b8c6e901d81ca64a96bef3116ab906f.json +++ b/.sqlx/query-3e66c333be0794213c6c6f077e184780cba13e76123e7d9f4f9d64c17ca5105b.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, transcript, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\" FROM podcast_job WHERE id = $1 AND user_id = $2", + "query": "SELECT id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, transcript, sources AS \"sources: Json\", state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\" FROM podcast_job WHERE id = $1 AND user_id = $2", "describe": { "columns": [ { @@ -60,6 +60,17 @@ }, { "ordinal": 5, + "name": "sources: Json", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "podcast_job", + "name": "sources" + } + } + }, + { + "ordinal": 6, "name": "state: PodcastJobState", "type_info": "Text", "origin": { @@ -70,7 +81,7 @@ } }, { - "ordinal": 6, + "ordinal": 7, "name": "stage", "type_info": "Text", "origin": { @@ -81,7 +92,7 @@ } }, { - "ordinal": 7, + "ordinal": 8, "name": "progress", "type_info": "Float8", "origin": { @@ -92,7 +103,7 @@ } }, { - "ordinal": 8, + "ordinal": 9, "name": "error_code", "type_info": "Text", "origin": { @@ -103,7 +114,7 @@ } }, { - "ordinal": 9, + "ordinal": 10, "name": "audio_key", "type_info": "Text", "origin": { @@ -114,7 +125,7 @@ } }, { - "ordinal": 10, + "ordinal": 11, "name": "audio_name", "type_info": "Text", "origin": { @@ -125,7 +136,7 @@ } }, { - "ordinal": 11, + "ordinal": 12, "name": "audio_type", "type_info": "Text", "origin": { @@ -136,7 +147,7 @@ } }, { - "ordinal": 12, + "ordinal": 13, "name": "audio_bytes", "type_info": "Int8", "origin": { @@ -147,7 +158,7 @@ } }, { - "ordinal": 13, + "ordinal": 14, "name": "duration_secs", "type_info": "Float8", "origin": { @@ -158,7 +169,7 @@ } }, { - "ordinal": 14, + "ordinal": 15, "name": "eta_secs", "type_info": "Int8", "origin": { @@ -169,7 +180,7 @@ } }, { - "ordinal": 15, + "ordinal": 16, "name": "created_at: Timestamp", "type_info": "Int8", "origin": { @@ -180,7 +191,7 @@ } }, { - "ordinal": 16, + "ordinal": 17, "name": "updated_at: Timestamp", "type_info": "Int8", "origin": { @@ -203,6 +214,7 @@ false, true, true, + true, false, false, false, @@ -217,5 +229,5 @@ false ] }, - "hash": "45ade92df6adc604f90c5e2111fc4bd23b8c6e901d81ca64a96bef3116ab906f" + "hash": "3e66c333be0794213c6c6f077e184780cba13e76123e7d9f4f9d64c17ca5105b" } diff --git a/.sqlx/query-814486dbb11e8eeaf410bced5a0aae724aa3f0198ce4204cd94016b827ab55b7.json b/.sqlx/query-63f0dc707ee7f6fe9976a0e903b8bfd31de8ca2fe54ddf8cd19e0653de7711cf.json similarity index 87% rename from .sqlx/query-814486dbb11e8eeaf410bced5a0aae724aa3f0198ce4204cd94016b827ab55b7.json rename to .sqlx/query-63f0dc707ee7f6fe9976a0e903b8bfd31de8ca2fe54ddf8cd19e0653de7711cf.json index 37f4fb4..681eb35 100644 --- a/.sqlx/query-814486dbb11e8eeaf410bced5a0aae724aa3f0198ce4204cd94016b827ab55b7.json +++ b/.sqlx/query-63f0dc707ee7f6fe9976a0e903b8bfd31de8ca2fe54ddf8cd19e0653de7711cf.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE podcast_job SET state = 'failed', error_code = $2, stage = '', updated_at = $3 WHERE id = $1 AND state IN ('queued', 'running') RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, transcript, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", + "query": "UPDATE podcast_job SET state = 'failed', error_code = $2, stage = '', updated_at = $3 WHERE id = $1 AND state IN ('queued', 'running') RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, transcript, sources AS \"sources: Json\", state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", "describe": { "columns": [ { @@ -60,6 +60,17 @@ }, { "ordinal": 5, + "name": "sources: Json", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "podcast_job", + "name": "sources" + } + } + }, + { + "ordinal": 6, "name": "state: PodcastJobState", "type_info": "Text", "origin": { @@ -70,7 +81,7 @@ } }, { - "ordinal": 6, + "ordinal": 7, "name": "stage", "type_info": "Text", "origin": { @@ -81,7 +92,7 @@ } }, { - "ordinal": 7, + "ordinal": 8, "name": "progress", "type_info": "Float8", "origin": { @@ -92,7 +103,7 @@ } }, { - "ordinal": 8, + "ordinal": 9, "name": "error_code", "type_info": "Text", "origin": { @@ -103,7 +114,7 @@ } }, { - "ordinal": 9, + "ordinal": 10, "name": "audio_key", "type_info": "Text", "origin": { @@ -114,7 +125,7 @@ } }, { - "ordinal": 10, + "ordinal": 11, "name": "audio_name", "type_info": "Text", "origin": { @@ -125,7 +136,7 @@ } }, { - "ordinal": 11, + "ordinal": 12, "name": "audio_type", "type_info": "Text", "origin": { @@ -136,7 +147,7 @@ } }, { - "ordinal": 12, + "ordinal": 13, "name": "audio_bytes", "type_info": "Int8", "origin": { @@ -147,7 +158,7 @@ } }, { - "ordinal": 13, + "ordinal": 14, "name": "duration_secs", "type_info": "Float8", "origin": { @@ -158,7 +169,7 @@ } }, { - "ordinal": 14, + "ordinal": 15, "name": "eta_secs", "type_info": "Int8", "origin": { @@ -169,7 +180,7 @@ } }, { - "ordinal": 15, + "ordinal": 16, "name": "created_at: Timestamp", "type_info": "Int8", "origin": { @@ -180,7 +191,7 @@ } }, { - "ordinal": 16, + "ordinal": 17, "name": "updated_at: Timestamp", "type_info": "Int8", "origin": { @@ -204,6 +215,7 @@ false, true, true, + true, false, false, false, @@ -218,5 +230,5 @@ false ] }, - "hash": "814486dbb11e8eeaf410bced5a0aae724aa3f0198ce4204cd94016b827ab55b7" + "hash": "63f0dc707ee7f6fe9976a0e903b8bfd31de8ca2fe54ddf8cd19e0653de7711cf" } diff --git a/.sqlx/query-f40008ce74997412bd8099f21cc58579d2c6efc73d04072849fe650a737e7a4c.json b/.sqlx/query-6b6ca993e9600caf8a4066432a7583be29811979fcfa869677c8dbbe5d19e2a8.json similarity index 84% rename from .sqlx/query-f40008ce74997412bd8099f21cc58579d2c6efc73d04072849fe650a737e7a4c.json rename to .sqlx/query-6b6ca993e9600caf8a4066432a7583be29811979fcfa869677c8dbbe5d19e2a8.json index 821fdf8..31e5fb0 100644 --- a/.sqlx/query-f40008ce74997412bd8099f21cc58579d2c6efc73d04072849fe650a737e7a4c.json +++ b/.sqlx/query-6b6ca993e9600caf8a4066432a7583be29811979fcfa869677c8dbbe5d19e2a8.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE podcast_job SET state = $3, stage = $4, progress = $5, error_code = $6, format = COALESCE(format, $7::text), transcript = COALESCE(transcript, $8::text), updated_at = $9 WHERE id = $1 AND state = $2 RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, transcript, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", + "query": "UPDATE podcast_job SET state = $3, stage = $4, progress = $5, error_code = $6, format = COALESCE(format, $7::text), transcript = COALESCE(transcript, $8::text), sources = COALESCE(sources, $9::jsonb), updated_at = $10 WHERE id = $1 AND state = $2 RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, transcript, sources AS \"sources: Json\", state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", "describe": { "columns": [ { @@ -60,6 +60,17 @@ }, { "ordinal": 5, + "name": "sources: Json", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "podcast_job", + "name": "sources" + } + } + }, + { + "ordinal": 6, "name": "state: PodcastJobState", "type_info": "Text", "origin": { @@ -70,7 +81,7 @@ } }, { - "ordinal": 6, + "ordinal": 7, "name": "stage", "type_info": "Text", "origin": { @@ -81,7 +92,7 @@ } }, { - "ordinal": 7, + "ordinal": 8, "name": "progress", "type_info": "Float8", "origin": { @@ -92,7 +103,7 @@ } }, { - "ordinal": 8, + "ordinal": 9, "name": "error_code", "type_info": "Text", "origin": { @@ -103,7 +114,7 @@ } }, { - "ordinal": 9, + "ordinal": 10, "name": "audio_key", "type_info": "Text", "origin": { @@ -114,7 +125,7 @@ } }, { - "ordinal": 10, + "ordinal": 11, "name": "audio_name", "type_info": "Text", "origin": { @@ -125,7 +136,7 @@ } }, { - "ordinal": 11, + "ordinal": 12, "name": "audio_type", "type_info": "Text", "origin": { @@ -136,7 +147,7 @@ } }, { - "ordinal": 12, + "ordinal": 13, "name": "audio_bytes", "type_info": "Int8", "origin": { @@ -147,7 +158,7 @@ } }, { - "ordinal": 13, + "ordinal": 14, "name": "duration_secs", "type_info": "Float8", "origin": { @@ -158,7 +169,7 @@ } }, { - "ordinal": 14, + "ordinal": 15, "name": "eta_secs", "type_info": "Int8", "origin": { @@ -169,7 +180,7 @@ } }, { - "ordinal": 15, + "ordinal": 16, "name": "created_at: Timestamp", "type_info": "Int8", "origin": { @@ -180,7 +191,7 @@ } }, { - "ordinal": 16, + "ordinal": 17, "name": "updated_at: Timestamp", "type_info": "Int8", "origin": { @@ -201,6 +212,7 @@ "Text", "Text", "Text", + "Jsonb", "Int8" ] }, @@ -210,6 +222,7 @@ false, true, true, + true, false, false, false, @@ -224,5 +237,5 @@ false ] }, - "hash": "f40008ce74997412bd8099f21cc58579d2c6efc73d04072849fe650a737e7a4c" + "hash": "6b6ca993e9600caf8a4066432a7583be29811979fcfa869677c8dbbe5d19e2a8" } diff --git a/.sqlx/query-cabbdce4f24ffcd7792dc8b9b9f72d02d920bf9fabc10c61584b0bd64c7712ff.json b/.sqlx/query-beb6594d280ac53dbb187850d195ac43234ee56ca59e70693e2d920c5a227a86.json similarity index 85% rename from .sqlx/query-cabbdce4f24ffcd7792dc8b9b9f72d02d920bf9fabc10c61584b0bd64c7712ff.json rename to .sqlx/query-beb6594d280ac53dbb187850d195ac43234ee56ca59e70693e2d920c5a227a86.json index d279439..b410821 100644 --- a/.sqlx/query-cabbdce4f24ffcd7792dc8b9b9f72d02d920bf9fabc10c61584b0bd64c7712ff.json +++ b/.sqlx/query-beb6594d280ac53dbb187850d195ac43234ee56ca59e70693e2d920c5a227a86.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO podcast_job (id, user_id, source_id, format, state, stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $15) RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, transcript, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", + "query": "INSERT INTO podcast_job (id, user_id, source_id, format, state, stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at, updated_at, sources) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $15, $16) RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, transcript, sources AS \"sources: Json\", state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", "describe": { "columns": [ { @@ -60,6 +60,17 @@ }, { "ordinal": 5, + "name": "sources: Json", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "podcast_job", + "name": "sources" + } + } + }, + { + "ordinal": 6, "name": "state: PodcastJobState", "type_info": "Text", "origin": { @@ -70,7 +81,7 @@ } }, { - "ordinal": 6, + "ordinal": 7, "name": "stage", "type_info": "Text", "origin": { @@ -81,7 +92,7 @@ } }, { - "ordinal": 7, + "ordinal": 8, "name": "progress", "type_info": "Float8", "origin": { @@ -92,7 +103,7 @@ } }, { - "ordinal": 8, + "ordinal": 9, "name": "error_code", "type_info": "Text", "origin": { @@ -103,7 +114,7 @@ } }, { - "ordinal": 9, + "ordinal": 10, "name": "audio_key", "type_info": "Text", "origin": { @@ -114,7 +125,7 @@ } }, { - "ordinal": 10, + "ordinal": 11, "name": "audio_name", "type_info": "Text", "origin": { @@ -125,7 +136,7 @@ } }, { - "ordinal": 11, + "ordinal": 12, "name": "audio_type", "type_info": "Text", "origin": { @@ -136,7 +147,7 @@ } }, { - "ordinal": 12, + "ordinal": 13, "name": "audio_bytes", "type_info": "Int8", "origin": { @@ -147,7 +158,7 @@ } }, { - "ordinal": 13, + "ordinal": 14, "name": "duration_secs", "type_info": "Float8", "origin": { @@ -158,7 +169,7 @@ } }, { - "ordinal": 14, + "ordinal": 15, "name": "eta_secs", "type_info": "Int8", "origin": { @@ -169,7 +180,7 @@ } }, { - "ordinal": 15, + "ordinal": 16, "name": "created_at: Timestamp", "type_info": "Int8", "origin": { @@ -180,7 +191,7 @@ } }, { - "ordinal": 16, + "ordinal": 17, "name": "updated_at: Timestamp", "type_info": "Int8", "origin": { @@ -207,7 +218,8 @@ "Int8", "Float8", "Int8", - "Int8" + "Int8", + "Jsonb" ] }, "nullable": [ @@ -216,6 +228,7 @@ false, true, true, + true, false, false, false, @@ -230,5 +243,5 @@ false ] }, - "hash": "cabbdce4f24ffcd7792dc8b9b9f72d02d920bf9fabc10c61584b0bd64c7712ff" + "hash": "beb6594d280ac53dbb187850d195ac43234ee56ca59e70693e2d920c5a227a86" } diff --git a/.sqlx/query-d1b16c756ea05fe53f875c57b4d46dfdc152943eb31d5df4c531af6da3e6ec7b.json b/.sqlx/query-cb286f2c1e63c638be8a58c0b9b0fb4add9e70c39cc9095ddafd3693e27f7bfd.json similarity index 86% rename from .sqlx/query-d1b16c756ea05fe53f875c57b4d46dfdc152943eb31d5df4c531af6da3e6ec7b.json rename to .sqlx/query-cb286f2c1e63c638be8a58c0b9b0fb4add9e70c39cc9095ddafd3693e27f7bfd.json index 3314af8..cf2703b 100644 --- a/.sqlx/query-d1b16c756ea05fe53f875c57b4d46dfdc152943eb31d5df4c531af6da3e6ec7b.json +++ b/.sqlx/query-cb286f2c1e63c638be8a58c0b9b0fb4add9e70c39cc9095ddafd3693e27f7bfd.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, transcript, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\" FROM podcast_job WHERE id = $1", + "query": "SELECT id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, transcript, sources AS \"sources: Json\", state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\" FROM podcast_job WHERE id = $1", "describe": { "columns": [ { @@ -60,6 +60,17 @@ }, { "ordinal": 5, + "name": "sources: Json", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "podcast_job", + "name": "sources" + } + } + }, + { + "ordinal": 6, "name": "state: PodcastJobState", "type_info": "Text", "origin": { @@ -70,7 +81,7 @@ } }, { - "ordinal": 6, + "ordinal": 7, "name": "stage", "type_info": "Text", "origin": { @@ -81,7 +92,7 @@ } }, { - "ordinal": 7, + "ordinal": 8, "name": "progress", "type_info": "Float8", "origin": { @@ -92,7 +103,7 @@ } }, { - "ordinal": 8, + "ordinal": 9, "name": "error_code", "type_info": "Text", "origin": { @@ -103,7 +114,7 @@ } }, { - "ordinal": 9, + "ordinal": 10, "name": "audio_key", "type_info": "Text", "origin": { @@ -114,7 +125,7 @@ } }, { - "ordinal": 10, + "ordinal": 11, "name": "audio_name", "type_info": "Text", "origin": { @@ -125,7 +136,7 @@ } }, { - "ordinal": 11, + "ordinal": 12, "name": "audio_type", "type_info": "Text", "origin": { @@ -136,7 +147,7 @@ } }, { - "ordinal": 12, + "ordinal": 13, "name": "audio_bytes", "type_info": "Int8", "origin": { @@ -147,7 +158,7 @@ } }, { - "ordinal": 13, + "ordinal": 14, "name": "duration_secs", "type_info": "Float8", "origin": { @@ -158,7 +169,7 @@ } }, { - "ordinal": 14, + "ordinal": 15, "name": "eta_secs", "type_info": "Int8", "origin": { @@ -169,7 +180,7 @@ } }, { - "ordinal": 15, + "ordinal": 16, "name": "created_at: Timestamp", "type_info": "Int8", "origin": { @@ -180,7 +191,7 @@ } }, { - "ordinal": 16, + "ordinal": 17, "name": "updated_at: Timestamp", "type_info": "Int8", "origin": { @@ -202,6 +213,7 @@ false, true, true, + true, false, false, false, @@ -216,5 +228,5 @@ false ] }, - "hash": "d1b16c756ea05fe53f875c57b4d46dfdc152943eb31d5df4c531af6da3e6ec7b" + "hash": "cb286f2c1e63c638be8a58c0b9b0fb4add9e70c39cc9095ddafd3693e27f7bfd" } diff --git a/.sqlx/query-e1bd89bafa14d3594316fc1768683dd9869275117ab83a255dac8de33b35725c.json b/.sqlx/query-e1bd89bafa14d3594316fc1768683dd9869275117ab83a255dac8de33b35725c.json deleted file mode 100644 index 8eba76b..0000000 --- a/.sqlx/query-e1bd89bafa14d3594316fc1768683dd9869275117ab83a255dac8de33b35725c.json +++ /dev/null @@ -1,76 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: CourseNoteFileId\",\n course_note AS \"course_note: CourseNoteId\", name AS \"name: FileName\",\n content_type AS \"content_type: FileContentType\", size FROM course_note_file\n WHERE course_note = $1 AND content_type = 'application/pdf'\n ORDER BY id DESC\n LIMIT 1", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "id: CourseNoteFileId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "course_note_file", - "name": "id" - } - } - }, - { - "ordinal": 1, - "name": "course_note: CourseNoteId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "course_note_file", - "name": "course_note" - } - } - }, - { - "ordinal": 2, - "name": "name: FileName", - "type_info": "Text", - "origin": { - "Table": { - "table": "course_note_file", - "name": "name" - } - } - }, - { - "ordinal": 3, - "name": "content_type: FileContentType", - "type_info": "Text", - "origin": { - "Table": { - "table": "course_note_file", - "name": "content_type" - } - } - }, - { - "ordinal": 4, - "name": "size", - "type_info": "Int8", - "origin": { - "Table": { - "table": "course_note_file", - "name": "size" - } - } - } - ], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [ - false, - false, - false, - false, - false - ] - }, - "hash": "e1bd89bafa14d3594316fc1768683dd9869275117ab83a255dac8de33b35725c" -} diff --git a/migrations/school/20260923000002_podcast_sources.sql b/migrations/school/20260923000002_podcast_sources.sql new file mode 100644 index 0000000..52e7d9f --- /dev/null +++ b/migrations/school/20260923000002_podcast_sources.sql @@ -0,0 +1,11 @@ +-- The per-source outcomes the service reports on `podcast.report` for a +-- multi-document episode: one JSONB array of `{key, name, status}`, stored +-- verbatim and replayed by `GET /podcast/jobs/{id}/result`. +-- +-- WHERE THIS FILE BELONGS: `migrations/school/` in the backend repo. APPEND-ONLY +-- relative to the existing school migrations: one new nullable column, no +-- backfill. A job finished before this column existed stays NULL, and a report +-- that omits the field (a service that has not learned it yet) leaves it NULL. +-- The report statement fills it once (`COALESCE`), the same way `transcript` +-- is filled, and never rewrites a value that already landed. +ALTER TABLE podcast_job ADD COLUMN sources JSONB NULL; diff --git a/src/ai/podcast.rs b/src/ai/podcast.rs index 0af213b..6cb964f 100644 --- a/src/ai/podcast.rs +++ b/src/ai/podcast.rs @@ -1,8 +1,8 @@ //! Payload contract for the `podcast.*` capabilities and the audio ingest — //! both directions of the podcast seam. //! -//! The podcast service turns one stored source — a course note's PDF — into an -//! audio episode. Since 2026-09-17 the **backend owns that job's record**: the +//! The podcast service turns a course note's stored attachments — PDF, +//! document, text — into one audio episode, narrating them in order. Since 2026-09-17 the **backend owns that job's record**: the //! submit door mints the job id, writes the row, and then dispatches //! `podcast.submit` with that id; the service reports every transition back //! through the client-initiated `podcast.report` capability, and uploads the @@ -17,9 +17,10 @@ //! * [`submit`] — `podcast.submit`, whose payload carries the backend-minted //! `job_id`, the submitting `user_id` (the service stores both; its own //! record is keyed by the id the backend will keep asking about), and the -//! `source_key` of the note's PDF: the backend resolves which file that is -//! before the job exists, so the service is never asked to open a name it -//! cannot turn into bytes. +//! note's `sources` — every attachment whose blob is on this host, in +//! upload order: the backend resolves which files those are before the job +//! exists, so the service is never asked to open a name it cannot turn +//! into bytes. //! * [`cancel`] — `podcast.cancel`, unchanged: a write on the service's queue, //! and the capability is what decides whether a deployment offers the door. //! @@ -45,6 +46,17 @@ pub use crate::constant::{ AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_REPORT_CAPABILITY, AI_PODCAST_SUBMIT_CAPABILITY, }; +/// One attachment the job narrates, as the submit door resolved it: the blob +/// key the service reads at `//`, the file +/// name the upload declared, and the declared content type — which the +/// service treats as a hint only, extracting by magic bytes instead. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct PodcastSource { + pub key: String, + pub name: String, + pub content_type: String, +} + /// What the backend asks a podcast service to start. The `job_id` is the /// backend's own minted id — the service keys its record by it and echoes it /// in every report, so the two stores can never disagree about which job a @@ -52,13 +64,17 @@ pub use crate::constant::{ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PodcastSubmitPayload { pub job_id: String, - /// The course note the job narrates, for the record. `source_key` is the - /// handle the service actually opens. + /// The course note the job narrates, for the record. pub source_id: String, - /// The blob key of the note's PDF attachment — the file the service reads - /// at `//`. The backend resolves - /// it (the note's newest `application/pdf` attachment) before the job - /// exists; `source_id` alone names nothing the service could open. + /// The note's attachments, in upload order (id ASC): every attachment + /// whose blob is on this host. The backend resolves them before the job + /// exists; `source_id` alone names nothing the service could open. The + /// service narrates all of them, one document each. + pub sources: Vec, + /// One-release compat alias for `sources[0].key`: the pre-multi-source + /// field, kept so a service that has not learned `sources` yet still + /// narrates the first document. A service reads `sources` when present + /// and falls back to this. pub source_key: String, /// `None` means the service applies its own default (`duz_okuma` today). #[serde(default, skip_serializing_if = "Option::is_none")] @@ -120,6 +136,22 @@ pub struct PodcastReportPayload { /// keeps that older payload valid. #[serde(default)] pub transcript: Option, + /// The per-source outcomes of the episode: `ok`, or `skipped:` for + /// a source that failed extraction and was left out. Absent on a service + /// that has not learned the field yet — `#[serde(default)]` keeps that + /// older payload valid, exactly as it does for `transcript`. + #[serde(default)] + pub sources: Option>, +} + +/// One source's outcome as the service reported it. The backend stores the +/// array verbatim on the job row; the result door replays it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct PodcastSourceStatus { + pub key: String, + pub name: String, + /// `ok`, or `skipped:`. + pub status: String, } /// The answer to one report. `stored` is always `true` on an `Ok` — an @@ -154,8 +186,8 @@ pub async fn cancel( /// /// The decode is deliberately strict: a payload that does not fit /// [`PodcastReportPayload`] is `invalid_payload`, never coerced into a -/// half-filled report. `transcript` is the one defaulted field, so a service -/// that omits it still reports. +/// half-filled report. `transcript` and `sources` are the defaulted fields, +/// so a service that omits them still reports. pub async fn report(db: &Database, payload: Value) -> Result { let report: PodcastReportPayload = serde_json::from_value(payload).map_err(|err| { ( @@ -173,6 +205,7 @@ pub async fn report(db: &Database, payload: Value) -> Result Ok(serde_json::to_value(PodcastReportReply { diff --git a/src/db/course_note_file.rs b/src/db/course_note_file.rs index cde6024..0d73e87 100644 --- a/src/db/course_note_file.rs +++ b/src/db/course_note_file.rs @@ -101,31 +101,6 @@ pub async fn read_for( Ok(file) } -/// The note's newest `application/pdf` attachment — the file the podcast -/// submit door narrates. `None` covers both a note that never had a PDF and a -/// note id that names no row at all: either way there is nothing to narrate. -/// -/// The content type is matched exactly as it was declared on upload, because -/// that is the only type the service's extractor reads. -pub async fn newest_pdf( - db: &Database, - note: &CourseNoteId, -) -> Result, AppError> { - let file = sqlx::query_as!( - CourseNoteFile, - r#"SELECT id AS "id: CourseNoteFileId", - course_note AS "course_note: CourseNoteId", name AS "name: FileName", - content_type AS "content_type: FileContentType", size FROM course_note_file - WHERE course_note = $1 AND content_type = 'application/pdf' - ORDER BY id DESC - LIMIT 1"#, - note.uuid() - ) - .fetch_optional(db) - .await?; - Ok(file) -} - /// All of `note`'s attachment rows, newest first. pub async fn list_for( db: &Database, diff --git a/src/db/podcast_job.rs b/src/db/podcast_job.rs index 902ceb4..ab6106f 100644 --- a/src/db/podcast_job.rs +++ b/src/db/podcast_job.rs @@ -23,6 +23,8 @@ use crate::domain::podcast_job::{PodcastJob, PodcastJobId, PodcastJobState}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; +use serde_json::Value; +use sqlx::types::Json; use sqlx::{query, query_as}; /// Write one freshly minted job. The id and timestamps are the caller's — the @@ -33,10 +35,10 @@ pub async fn insert(db: &Database, job: &PodcastJob) -> Result\", state AS \"state: PodcastJobState\", stage, progress, error_code, \ audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \ created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", job.get_id().uuid(), @@ -54,6 +56,7 @@ pub async fn insert(db: &Database, job: &PodcastJob) -> Result Result Ok(query_as!( PodcastJob, "SELECT id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", \ - source_id, format, transcript, state AS \"state: PodcastJobState\", stage, progress, error_code, \ + source_id, format, transcript, sources AS \"sources: Json\", state AS \"state: PodcastJobState\", stage, progress, error_code, \ audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \ created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\" \ FROM podcast_job WHERE id = $1", @@ -87,7 +90,7 @@ pub async fn read_for( Ok(query_as!( PodcastJob, "SELECT id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", \ - source_id, format, transcript, state AS \"state: PodcastJobState\", stage, progress, error_code, \ + source_id, format, transcript, sources AS \"sources: Json\", state AS \"state: PodcastJobState\", stage, progress, error_code, \ audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \ created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\" \ FROM podcast_job WHERE id = $1 AND user_id = $2", @@ -177,11 +180,11 @@ async fn with_source_titles( /// concurrent write (a cancel, another report) moved it first — the caller /// re-reads and answers the truth. /// -/// `format` and `transcript` fill their columns once and never rewrite them: -/// the service's default resolution arrives on the first report, and a later -/// report disagreeing with the format is refused by the service layer, not -/// silently stored. A later transcript is ignored the same way — the first -/// non-null value stands. +/// `format`, `transcript` and `sources` fill their columns once and never +/// rewrite them: the service's default resolution arrives on the first +/// report, and a later report disagreeing with the format is refused by the +/// service layer, not silently stored. A later transcript is ignored the same +/// way — the first non-null value stands. #[allow(clippy::too_many_arguments)] pub async fn report( db: &Database, @@ -193,16 +196,17 @@ pub async fn report( error_code: Option<&str>, format: Option<&str>, transcript: Option<&str>, + sources: Option<&Value>, ) -> Result, AppError> { let now = Timestamp::now().as_millis(); Ok(query_as!( PodcastJob, "UPDATE podcast_job SET state = $3, stage = $4, progress = $5, error_code = $6, \ format = COALESCE(format, $7::text), transcript = COALESCE(transcript, $8::text), \ - updated_at = $9 \ - WHERE id = $1 AND state = $2 \ + sources = COALESCE(sources, $9::jsonb), updated_at = $10 \ + WHERE id = $1 AND state = $2 \ RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", \ - source_id, format, transcript, state AS \"state: PodcastJobState\", stage, progress, error_code, \ + source_id, format, transcript, sources AS \"sources: Json\", state AS \"state: PodcastJobState\", stage, progress, error_code, \ audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \ created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", id.uuid(), @@ -213,6 +217,7 @@ pub async fn report( error_code, format, transcript, + sources, now, ) .fetch_optional(db) @@ -233,7 +238,7 @@ pub async fn set_cancelled( "UPDATE podcast_job SET state = 'cancelled', stage = '', updated_at = $2 \ WHERE id = $1 AND state IN ('queued', 'running') \ RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", \ - source_id, format, transcript, state AS \"state: PodcastJobState\", stage, progress, error_code, \ + source_id, format, transcript, sources AS \"sources: Json\", state AS \"state: PodcastJobState\", stage, progress, error_code, \ audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \ created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", id.uuid(), @@ -258,7 +263,7 @@ pub async fn set_failed( "UPDATE podcast_job SET state = 'failed', error_code = $2, stage = '', updated_at = $3 \ WHERE id = $1 AND state IN ('queued', 'running') \ RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", \ - source_id, format, transcript, state AS \"state: PodcastJobState\", stage, progress, error_code, \ + source_id, format, transcript, sources AS \"sources: Json\", state AS \"state: PodcastJobState\", stage, progress, error_code, \ audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \ created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", id.uuid(), @@ -289,7 +294,7 @@ pub async fn set_audio( audio_bytes = $5, duration_secs = $6, updated_at = $7 \ WHERE id = $1 \ RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", \ - source_id, format, transcript, state AS \"state: PodcastJobState\", stage, progress, error_code, \ + source_id, format, transcript, sources AS \"sources: Json\", state AS \"state: PodcastJobState\", stage, progress, error_code, \ audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \ created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", id.uuid(), @@ -316,7 +321,7 @@ pub async fn set_eta( PodcastJob, "UPDATE podcast_job SET eta_secs = $2 WHERE id = $1 \ RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", \ - source_id, format, transcript, state AS \"state: PodcastJobState\", stage, progress, error_code, \ + source_id, format, transcript, sources AS \"sources: Json\", state AS \"state: PodcastJobState\", stage, progress, error_code, \ audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, \ created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", id.uuid(), @@ -361,6 +366,7 @@ mod tests { source_id: "src".to_string(), format: None, transcript: None, + sources: None, state: PodcastJobState::Queued, stage: String::new(), progress: 0.0, @@ -398,6 +404,7 @@ mod tests { None, Some("duz_okuma"), Some("bolum bir\n\nbolum iki"), + None, ) .await .expect("report") @@ -417,6 +424,7 @@ mod tests { None, None, Some("should not land"), + None, ) .await .expect("report"); @@ -434,6 +442,7 @@ mod tests { None, None, Some("also not"), + None, ) .await .expect("report"); @@ -495,6 +504,7 @@ mod tests { None, None, None, + None, ) .await; assert!(refused.is_err(), "the CHECK backstops the service layer"); @@ -520,6 +530,7 @@ mod tests { None, None, Some("metin"), + None, ) .await .expect("report") diff --git a/src/domain/podcast_job.rs b/src/domain/podcast_job.rs index b44959f..136081d 100644 --- a/src/domain/podcast_job.rs +++ b/src/domain/podcast_job.rs @@ -27,6 +27,8 @@ use crate::constant::{ use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; +use serde_json::Value; +use sqlx::types::Json; #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] #[sqlx(transparent)] @@ -139,6 +141,10 @@ pub struct PodcastJob { /// The episode transcript, chapters joined with blank lines. `None` until /// a report carries one, and forever for a job whose service never did. pub(crate) transcript: Option, + /// The per-source outcomes the service reported on `podcast.report` — a + /// JSON array of `{key, name, status}`, stored verbatim. `None` until a + /// report carries one, and forever for a job whose service never did. + pub(crate) sources: Option>, pub(crate) state: PodcastJobState, pub(crate) stage: String, pub(crate) progress: f64, @@ -174,6 +180,11 @@ impl PodcastJob { self.transcript.as_deref() } + /// The verbatim per-source report, if the service ever sent one. + pub fn get_sources(&self) -> Option<&Value> { + self.sources.as_ref().map(|sources| &sources.0) + } + pub fn get_state(&self) -> PodcastJobState { self.state } @@ -334,6 +345,7 @@ mod tests { source_id: "src".to_string(), format: None, transcript: None, + sources: None, state, stage: String::new(), progress: 0.0, diff --git a/src/lib.rs b/src/lib.rs index 3ffbcf0..488ecbd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -59,7 +59,7 @@ use crate::web::module_gate::gate; (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"), (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 `(sınıf, ders)` pairs derived by the server — a manager or an admin gets every class-course pair in the school, everyone else their own memberships (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. Two **study** doors are one-shot and synchronous rather than threaded: `POST /rag/summarize` returns a summary of one page/span range and `POST /rag/questions` returns a set of practice questions (plus their range-bounded answers) over one — the artifact is the answer, so nothing is stored and there is no thread or poll. Their body names only a *target within* the asker's own derived pairs (the body's `sinif` plus `ders`): a pair the caller does not hold is `403`, and omitting `sinif` for a ders taught at more than one grade is `400` — the backend never picks a corpus for the caller. Both answer `503` when no AI service offers `rag.summarize`/`rag.questions`, and an `abstained: true` reply with a `reason` is a complete `200`, exactly as on a chat turn. Each waits on its dispatch under a 25 s deadline, deliberately inside the middleware's own 30 s envelope — a dropped handler would answer with prose written for a request that may have written something."), (name = "insights", description = "ZEKA's computed student insights. The `hezarfen_zeka` AI service dials in over the same QUIC bridge as the chatbot, but it does **not** touch a school database: the backend owns every statement against the `zeka_*` tables, and the service calls the backend by name (`insight.*` capabilities on a client-initiated stream — see `src/ai/insight.rs`) to have its computed rows written and read back. So this nest reads what the service computed and asks it to compute on demand, and its write doors are the same operations the bridge serves: `POST /insights/summaries`, `/recommendations`, `/segments`, `/profiles` and `/runs` store one batch each (manager+, one call one transaction, rows about students school-wide), `GET /insights/pending` is the students the freshest run left pending, and `POST /insights/sweep` / `POST /insights/purge` are retention and graduation housekeeping — all scoped to the caller's own school by the nest's extractors, and none of them takes a school, a database or a query in its body. `GET /insights/schools` is the exception and is not this nest's usual principal: the active-school directory names every customer, so it is mounted on the **builder** principal outside the school gate (a school session answers `401`), exactly like the vendor surface's `GET /schools`. `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."), - (name = "podcast", description = "Podcast generation, relayed through the same QUIC bridge as the chatbot and the RAG nest — and the **backend owns the job**, not just the HTTP surface. `POST /podcast/jobs` (`{source_id, format?}`) resolves the note's newest `application/pdf` attachment — the blob key the dispatch hands the service as `source_key`, so the service opens `//` — refusing `409 source_missing` when the note has no PDF or its bytes are missing from this host, then mints the job id, writes the row, dispatches `podcast.submit` to the service and answers `202` with `{job_id, state, eta_secs}`; `GET /podcast/jobs/{id}` polls the backend's own row `{state, stage, progress, error_code}` with no service round trip, `GET /podcast/jobs/{id}/result` collects a finished job's `{audio_id, duration_secs, format, transcript}` (`409` while it is still running), `GET /podcast/jobs/{id}/audio` streams the episode the service uploaded into this school's own blob directory, and `POST /podcast/jobs/{id}/cancel` asks the service to stop it (`cancelled` is \"this call stopped work\", so a finished job answers `false`; a terminal job answers without the service); `GET /podcast/jobs` is the caller's own history, newest first (`?limit=&offset=`), each row carrying the title of the note it narrated. The service reports every transition back through the `podcast.report` capability and uploads the finished mp3 — so status, result and audio keep answering while the service is down or restarted, and a job nobody is updating reads as failed/interrupted after an ETA-scaled window. Submit and cancel refuse `503` when no worker is connected; none of the four read doors needs one (404 for an unknown or foreign job, 410 past the retention window, 409 before the job is done or when its blob is missing from this host)."), + (name = "podcast", description = "Podcast generation, relayed through the same QUIC bridge as the chatbot and the RAG nest — and the **backend owns the job**, not just the HTTP surface. `POST /podcast/jobs` (`{source_id, format?}`) resolves the note's attachments — every one whose blob is on this host, dispatched as `sources` in upload order, the blob keys the service opens as `//` (`source_key` rides on as the first source's key, one-release compat) — refusing `409 source_missing` when the note has no attachments or none of their blobs are present on this host, then mints the job id, writes the row, dispatches `podcast.submit` to the service and answers `202` with `{job_id, state, eta_secs}`; `GET /podcast/jobs/{id}` polls the backend's own row `{state, stage, progress, error_code}` with no service round trip, `GET /podcast/jobs/{id}/result` collects a finished job's `{audio_id, duration_secs, format, transcript, sources?}` (`409` while it is still running), `GET /podcast/jobs/{id}/audio` streams the episode the service uploaded into this school's own blob directory, and `POST /podcast/jobs/{id}/cancel` asks the service to stop it (`cancelled` is \"this call stopped work\", so a finished job answers `false`; a terminal job answers without the service); `GET /podcast/jobs` is the caller's own history, newest first (`?limit=&offset=`), each row carrying the title of the note it narrated. The service reports every transition back through the `podcast.report` capability and uploads the finished mp3 — so status, result and audio keep answering while the service is down or restarted, and a job nobody is updating reads as failed/interrupted after an ETA-scaled window. Submit and cancel refuse `503` when no worker is connected; none of the four read doors needs one (404 for an unknown or foreign job, 410 past the retention window, 409 before the job is done or when its blob is missing from this host)."), (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`"), (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"), (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"), diff --git a/src/service/course_note_file.rs b/src/service/course_note_file.rs index 8ec6b88..8a943b6 100644 --- a/src/service/course_note_file.rs +++ b/src/service/course_note_file.rs @@ -32,15 +32,6 @@ pub async fn read_for( course_note_file::read_for(db, id, note).await } -/// The note's newest `application/pdf` attachment — what the podcast submit -/// door narrates, resolved before any job row is written. -pub async fn newest_pdf( - db: &Database, - note: &CourseNoteId, -) -> Result, AppError> { - course_note_file::newest_pdf(db, note).await -} - pub async fn list_for( db: &Database, note: &CourseNoteId, diff --git a/src/service/podcast_job.rs b/src/service/podcast_job.rs index f170449..1ccbf34 100644 --- a/src/service/podcast_job.rs +++ b/src/service/podcast_job.rs @@ -9,6 +9,8 @@ //! enum), the retention window, and the "done means audio" rule — in that //! order — before a single statement runs. +use crate::ai::podcast::PodcastSourceStatus; +use crate::constant::MAX_COURSE_NOTE_FILES; use crate::database::Database; use crate::db::podcast_job; use crate::domain::course_note::CourseNoteId; @@ -101,6 +103,9 @@ pub struct ReportInput<'a> { pub progress: f64, pub error_code: Option<&'a str>, pub transcript: Option<&'a str>, + /// The per-source outcomes, as the report carried them. `None` from a + /// service that has not learned the field yet. + pub sources: Option<&'a [PodcastSourceStatus]>, } /// Mint and store one freshly submitted job. The id is the backend's (the @@ -120,6 +125,7 @@ pub async fn create( source_id: source_id.to_string(), format: format.map(str::to_string), transcript: None, + sources: None, state: PodcastJobState::Queued, stage: String::new(), progress: 0.0, @@ -215,6 +221,15 @@ pub async fn report( "transcript is longer than {MAX_TRANSCRIPT_LEN} characters" ))); } + // A note cannot hold more than [`MAX_COURSE_NOTE_FILES`] attachments, so + // a longer source list is not a report this backend could have asked for. + if let Some(sources) = input.sources + && sources.len() > MAX_COURSE_NOTE_FILES + { + return Err(PodcastRefusal::InvalidPayload(format!( + "sources carries more than the {MAX_COURSE_NOTE_FILES} attachments a note can hold" + ))); + } let Some(row) = podcast_job::read(db, &id).await? else { return Err(PodcastRefusal::UnknownJob); @@ -253,6 +268,11 @@ pub async fn report( // that empty string and then ignore the done report's text, so a blank // or all-whitespace transcript is absent, not a value. let transcript = input.transcript.filter(|text| !text.trim().is_empty()); + // Stored verbatim, like the transcript: a service-owned shape this side + // neither interprets nor rewrites. + let sources = input + .sources + .map(|sources| serde_json::to_value(sources).expect("a source list is always encodable")); match podcast_job::report( db, @@ -264,6 +284,7 @@ pub async fn report( input.error_code, input.format, transcript, + sources.as_ref(), ) .await? { @@ -387,6 +408,7 @@ mod tests { progress: 0.0, error_code: None, transcript: Some(&huge), + sources: None, }; let err = report(&db, &input).await.expect_err("over the cap"); assert_eq!(err.code(), "invalid_payload"); @@ -423,6 +445,7 @@ mod tests { progress: 0.2, error_code: None, transcript: Some(""), + sources: None, }; let running = report(&db, &progress).await.expect("progress report"); assert_eq!(running.get_state(), PodcastJobState::Running); @@ -450,6 +473,7 @@ mod tests { progress: 1.0, error_code: None, transcript: Some("bolum bir\n\nbolum iki"), + sources: None, }; let finished = report(&db, &done).await.expect("done report"); assert_eq!(finished.get_transcript(), Some("bolum bir\n\nbolum iki")); diff --git a/src/web/podcast.rs b/src/web/podcast.rs index 328019b..e4d3c76 100644 --- a/src/web/podcast.rs +++ b/src/web/podcast.rs @@ -36,13 +36,13 @@ //! window (see [`PodcastJob::projected`]): the projection writes nothing, and //! the service's next report overwrites it. //! -//! The **source** is resolved here, not by the service: `source_id` names a +//! The **sources** are resolved here, not by the service: `source_id` names a //! course note in the caller's own school, and the submit door hands the -//! service the blob key of that note's newest `application/pdf` attachment -//! (`source_key`) — the file it reads under its shared media root. A note with -//! no such attachment, or one whose blob is missing from this host, is refused -//! `409 source_missing` before the row is written, so a job that could only -//! fail is never queued. +//! service that note's attachments — every one whose blob is on this host, in +//! upload order — as `sources` (`source_key` rides on as the first source's +//! key, one-release compat). A note with no attachments, or one whose blobs +//! are all missing from this host, is refused `409 source_missing` before the +//! row is written, so a job that could only fail is never queued. use axum::Json; use axum::body::Body; @@ -58,7 +58,7 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::ai::AiBridge; -use crate::ai::podcast::{self, PodcastCancelPayload, PodcastSubmitPayload}; +use crate::ai::podcast::{self, PodcastCancelPayload, PodcastSource, PodcastSubmitPayload}; use crate::constant::{ AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_SUBMIT_CAPABILITY, PODCAST_INTERRUPTED_CODE, }; @@ -124,6 +124,20 @@ struct JobStatus { error_code: Option, } +/// One attachment's outcome in the finished episode, as the service reported +/// it. +#[derive(Serialize, Deserialize, ToSchema)] +struct JobSourceStatus { + /// The attachment's blob key — the id `GET /course-notes/{id}/files` + /// lists. + key: String, + /// The file name the upload declared. + name: String, + /// `ok`, or `skipped:` when the source failed extraction and was + /// left out of the episode. + status: String, +} + /// A finished job's artifacts. #[derive(Serialize, ToSchema)] struct JobArtifacts { @@ -140,6 +154,10 @@ struct JobArtifacts { /// finished before the column existed, and any later job whose done report /// omitted the field. transcript: Option, + /// Per-source outcomes for a multi-document episode, exactly as the + /// service reported them. `null` for episodes finished before the field + /// existed, or by a service that has not learned it. + sources: Option>, } /// The verdict on a cancel. @@ -162,11 +180,12 @@ struct CancelVerdict { /// far as a row either (see below). /// /// `source_id` names a course note in this school, and the door resolves it -/// first: what the service narrates is that note's **newest -/// `application/pdf` attachment**, whose blob key rides the dispatch as -/// `source_key`. A note with no PDF — or one whose blob is missing from this -/// host — is a `409 source_missing` before anything is written, so a job that -/// is guaranteed to fail is never queued for the service to discover later. +/// first: what the service narrates is that note's **attachments** — every +/// one whose blob is on this host, dispatched as `sources` in upload order +/// (a missing blob is skipped with a log line, not a refusal). A note with +/// no attachments — or none whose blob is on this host — is a `409 +/// source_missing` before anything is written, so a job that is guaranteed +/// to fail is never queued for the service to discover later. #[utoipa::path( post, path = "/jobs", @@ -177,7 +196,7 @@ struct CancelVerdict { (status = 202, description = "The job is queued; `job_id` names it from here on", body = JobReceipt), (status = 400, description = "Empty `source_id`, or a `format` the service does not serve", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 409, description = "The note has no `application/pdf` attachment, or that attachment's blob is missing from this host (`source_missing`)", body = ErrorResponse), + (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), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing", body = ErrorResponse), (status = 503, description = "No AI service offers `podcast.submit` (or the service is at capacity)", body = ErrorResponse), ), @@ -203,24 +222,51 @@ async fn submit( })); } - // The source is resolved here, before anything is written: what the - // service narrates is the note's own newest PDF, and the key of those - // bytes is what rides the dispatch. Both shapes of "no source" are refused - // now — queueing the job would only buy a failure in the service's own - // `kaynak` stage, with the caller already holding a job id. - let file = note_files::newest_pdf(&st.db, &CourseNoteId::from_key(source_id)) - .await? - .ok_or_else(|| source_missing("this course note has no PDF attachment to narrate"))?; - let source_key = file.get_id().key(); - match tokio::fs::try_exists(crate::web::blob_path(&st.files_path, &source_key)).await { - Ok(true) => {} - Ok(false) => return Err(source_missing("this note's PDF is missing on this host")), - Err(err) => { - return Err(AppError::Internal(format!( - "could not stat the note's PDF blob: {err}" - ))); + // The sources are resolved here, before anything is written: what the + // service narrates is the note's own attachments — every one whose blob + // is on this host, in upload order (id ASC) — and those keys are what + // ride the dispatch. A blob that is gone is skipped with a log line, not + // a refusal: the episode just narrates fewer documents. Both shapes of + // "no source at all" are refused now — queueing the job would only buy a + // failure in the service's own `kaynak` stage, with the caller already + // holding a job id. + let (mut files, _) = + note_files::list_for(&st.db, &CourseNoteId::from_key(source_id), None, 0).await?; + let attachments = files.len(); + // `list_for` is newest first; the payload carries upload order (id ASC), + // the order the service narrates in. + files.sort_by_key(|file| file.get_id().uuid()); + let mut sources = Vec::with_capacity(files.len()); + for file in files { + let key = file.get_id().key(); + match tokio::fs::try_exists(crate::web::blob_path(&st.files_path, &key)).await { + Ok(true) => sources.push(PodcastSource { + key, + name: file.get_name().as_str().to_string(), + content_type: file.get_content_type().as_str().to_string(), + }), + // The row is intact, the bytes are not: leave this one document + // out rather than refusing a note whose other attachments are + // fine. + Ok(false) => tracing::warn!( + key = %key, + "podcast source's blob is missing from this host; skipping it" + ), + Err(err) => { + return Err(AppError::Internal(format!( + "could not stat a note attachment blob: {err}" + ))); + } } } + if sources.is_empty() { + return Err(source_missing(if attachments == 0 { + "this course note has no attachments to narrate" + } else { + "none of this note's attachments are on this host" + })); + } + let source_key = sources[0].key.clone(); let job = jobs::create(&st.db, user.get_id(), source_id, req.format.as_deref()).await?; let job_id = job.get_id().key(); @@ -228,6 +274,7 @@ async fn submit( job_id: job_id.clone(), source_id: source_id.to_string(), source_key, + sources, format: req.format.clone(), user_id: user.get_id().key(), }; @@ -472,6 +519,10 @@ async fn result( duration_secs: job.get_duration_secs(), format: job.get_format().map(str::to_string), transcript: job.get_transcript().map(str::to_string), + sources: job.get_sources().map(|sources| { + serde_json::from_value(sources.clone()) + .expect("the report decode guarantees the stored sources shape") + }), }) .into_response()) } @@ -665,10 +716,10 @@ fn worker_for(st: &AppState, capability: &str) -> Result { } /// The submit door's own refusal: the note behind `source_id` cannot be -/// narrated — it has no PDF attachment, or the bytes the row names are gone -/// from this host. One code (`source_missing`) for both, a message that says -/// which side is missing, and a `409` either way, so a client branches on the -/// code instead of parsing the sentence. +/// narrated — it has no attachments, or the bytes every one of them names are +/// gone from this host. One code (`source_missing`) for both, a message that +/// says which side is missing, and a `409` either way, so a client branches on +/// the code instead of parsing the sentence. fn source_missing(message: &str) -> AppError { AppError::ConflictCoded { code: "source_missing", diff --git a/tests/podcast.rs b/tests/podcast.rs index 33c0932..5cc497e 100644 --- a/tests/podcast.rs +++ b/tests/podcast.rs @@ -294,7 +294,7 @@ async fn submit(app: &Router, cookie: &str, body: Value) -> common::Res { /// Submit one job for `source` with the standard format (asserting the `202`) /// and hand back the backend-minted id every other door names. `source` is the -/// note id: the door resolves the note's own newest PDF before it writes +/// note id: the door resolves the note's attachments before it writes /// anything, so every submitting test needs a real note behind its source. async fn submit_job(app: &Router, cookie: &str, source: &str) -> String { let res = submit( @@ -843,6 +843,57 @@ async fn a_finished_job_serves_the_uploaded_bytes() { ); } +/// The per-source outcomes ride the done report and come back on the result +/// door, verbatim — the frontend can show which documents made it into the +/// episode without a second contract. A job whose service never reported them +/// keeps the field absent. +#[tokio::test] +async fn the_result_door_exposes_the_reported_sources() { + let (service, app, cookie, db) = podcast_app().await; + let user = common::me_id(&app, &cookie).await; + let (note, _key) = note_with_pdf(&app, &db).await; + let job_id = submit_job(&app, &cookie, ¬e).await; + + assert_report_stored( + &capability_call( + &service.conn, + report_frame(&job_id, ¬e, &user, "running", "tts", 0.25), + ) + .await, + &job_id, + ); + + let bytes = episode_bytes(); + let answer = blob_upload( + &service.conn, + upload_frame(&job_id, AUDIO_NAME, AUDIO_TYPE, bytes.len()), + &bytes, + ) + .await; + assert_eq!(answer["status"], "ok", "{answer}"); + + let mut done = report_frame(&job_id, ¬e, &user, "done", "", 1.0); + done["payload"]["transcript"] = json!("bolum bir\n\nbolum iki"); + done["payload"]["sources"] = json!([ + { "key": "019732e3-7b00-7000-8000-00000000beef", "name": "tanim.pdf", "status": "ok" }, + { "key": "019732e3-7b00-7000-8000-00000000feed", "name": "ozet.txt", "status": "skipped:no_text_layer" }, + ]); + assert_report_stored(&capability_call(&service.conn, done).await, &job_id); + + let res = result_of(&app, &cookie, &job_id).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["sources"][0]["key"], "019732e3-7b00-7000-8000-00000000beef"); + assert_eq!(res.body["sources"][0]["name"], "tanim.pdf"); + assert_eq!(res.body["sources"][0]["status"], "ok"); + assert_eq!(res.body["sources"][1]["key"], "019732e3-7b00-7000-8000-00000000feed"); + assert_eq!(res.body["sources"][1]["name"], "ozet.txt"); + assert_eq!(res.body["sources"][1]["status"], "skipped:no_text_layer"); + + // The audio-missing refusal earlier in the file proves a job cannot go + // `done` without its upload; a report that never learns `sources` leaves + // the field absent rather than an empty list. +} + /// Cancelling a live job reaches the worker that owns the queue and stamps the /// verdict on the row — the row then records that the job stopped, so a poll /// after the service is gone still reads the truth. @@ -1593,13 +1644,14 @@ async fn the_old_path_audio_door_is_gone() { assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); } -/// The submit door resolves the source itself: a note with no PDF attachment -/// is refused `409 source_missing` **before** anything is written. Pre-fix the -/// door accepted the job and it died later in the service's `kaynak` stage — -/// a queued job guaranteed to fail, which is what this refusal exists to -/// prevent. A newer non-PDF attachment changes nothing: it is not a source. +/// The submit door resolves the sources itself: a note with no attachments at +/// all is refused `409 source_missing` **before** anything is written. +/// Pre-fix the door accepted the job and it died later in the service's +/// `kaynak` stage — a queued job guaranteed to fail, which is what this +/// refusal exists to prevent. A single attachment — PDF or not — is a valid +/// source now, so the refusal is exactly about emptiness. #[tokio::test] -async fn a_note_with_no_pdf_is_refused_at_the_door() { +async fn a_note_with_no_attachments_is_refused_at_the_door() { let (service, app, cookie, db) = podcast_app().await; let user = common::me_id(&app, &cookie).await; let teacher = common::login_as(&app, &db, "hoca", "teacher").await; @@ -1610,12 +1662,6 @@ async fn a_note_with_no_pdf_is_refused_at_the_door() { assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); assert_eq!(res.body["code"], "source_missing"); - // A non-PDF attachment is newer than nothing, and is still not a source. - let _txt = upload_attachment(&app, &teacher, ¬e, "ozet.txt", "text/plain").await; - let res = submit(&app, &cookie, json!({ "source_id": ¬e })).await; - assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); - assert_eq!(res.body["code"], "source_missing"); - assert!( service.seen().is_empty(), "the refusal never reaches a worker: {:?}", @@ -1624,12 +1670,12 @@ async fn a_note_with_no_pdf_is_refused_at_the_door() { assert_eq!(rows_for(&db, &user).await, 0, "and no row is written"); } -/// A note whose PDF is on record but whose blob is gone from this host is -/// refused the same way: the row is intact and the bytes are not, and the -/// service could only fail on it — so the door answers now instead of queueing -/// a job nobody can finish. +/// A note whose attachment blobs are **all** gone from this host is refused +/// the same way as a note with no attachments: the rows are intact and the +/// bytes are not, and the service could only fail on them — so the door +/// answers now instead of queueing a job nobody can finish. #[tokio::test] -async fn a_pdf_whose_blob_is_gone_is_refused_at_the_door() { +async fn a_note_whose_blobs_are_all_gone_is_refused_at_the_door() { let (service, app, cookie, db) = podcast_app().await; let user = common::me_id(&app, &cookie).await; let (note, key) = note_with_pdf(&app, &db).await; @@ -1647,22 +1693,58 @@ async fn a_pdf_whose_blob_is_gone_is_refused_at_the_door() { assert_eq!(rows_for(&db, &user).await, 0, "and no row is written"); } -/// Which attachment narrates: the note's **newest PDF**, not its newest file — -/// a text recap uploaded after the PDF is not a source, and a corrected PDF -/// uploaded after that is. +/// One blob missing among several is **not** a refusal: the door dispatches +/// the attachments that are present (the skip is a log line) — the episode +/// just narrates fewer documents. Only an empty result set refuses. +#[tokio::test] +async fn a_missing_blob_among_several_is_skipped_not_a_refusal() { + let (service, app, cookie, db) = podcast_app().await; + let teacher = common::login_as(&app, &db, "hoca", "teacher").await; + let course = common::create_course(&app, &teacher, "Matematik").await; + let note = create_note(&app, &teacher, &course).await; + let kept = upload_attachment(&app, &teacher, ¬e, "kaldi.pdf", "application/pdf").await; + let gone = upload_attachment(&app, &teacher, ¬e, "gitti.txt", "text/plain").await; + let path = common::blob_dir().join(&gone); + std::fs::remove_file(&path).expect("take the blob away"); + + let res = submit(&app, &cookie, json!({ "source_id": ¬e })).await; + assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); + + let seen = service.seen(); + assert_eq!(seen.len(), 1, "exactly one dispatch"); + assert_eq!(seen[0].payload["source_key"], kept, "the first present blob"); + let sources = seen[0].payload["sources"].as_array().expect("a source list"); + assert_eq!(sources.len(), 1, "the missing blob is filtered at the door"); + assert_eq!(sources[0]["key"], kept); + assert_eq!(sources[0]["name"], "kaldi.pdf"); + assert_eq!( + sources[0]["content_type"], "application/pdf", + "the declared type rides along as a hint" + ); +} + +/// Which sources narrate: **every** attachment of the note, in upload order +/// (id ASC) — PDF, text and docx alike; the service extracts by magic bytes, +/// not by the declared type, so the type rides along as a hint only. +/// `source_key`, the one-release compat field, is the first source's key. #[tokio::test] -async fn the_source_is_the_newest_pdf_attachment() { +async fn the_sources_are_all_attachments_in_upload_order() { let (service, app, cookie, db) = podcast_app().await; let teacher = common::login_as(&app, &db, "hoca", "teacher").await; let course = common::create_course(&app, &teacher, "Matematik").await; let note = create_note(&app, &teacher, &course).await; - let draft = upload_attachment(&app, &teacher, ¬e, "taslak.pdf", "application/pdf").await; - let _newer_text = - upload_attachment(&app, &teacher, ¬e, "ozet.txt", "text/plain").await; - let corrected = - upload_attachment(&app, &teacher, ¬e, "duzeltilmis.pdf", "application/pdf").await; - assert_ne!(draft, corrected, "two distinct attachment rows"); + let first = upload_attachment(&app, &teacher, ¬e, "taslak.pdf", "application/pdf").await; + let second = upload_attachment(&app, &teacher, ¬e, "ozet.txt", "text/plain").await; + let third = upload_attachment( + &app, + &teacher, + ¬e, + "konusma.docx", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + ) + .await; + assert_ne!(first, second, "two distinct attachment rows"); let res = submit(&app, &cookie, json!({ "source_id": ¬e })).await; assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); @@ -1671,10 +1753,25 @@ async fn the_source_is_the_newest_pdf_attachment() { assert_eq!(seen.len(), 1, "exactly one dispatch"); assert_eq!(seen[0].payload["source_id"], note); assert_eq!( - seen[0].payload["source_key"], corrected, - "the newest PDF, not the newest file: {}", + seen[0].payload["source_key"], first, + "the compat alias is the first source's key: {}", seen[0].payload ); + let sources = seen[0].payload["sources"].as_array().expect("a source list"); + assert_eq!(sources.len(), 3, "{}", seen[0].payload); + for (source, (key, name, content_type)) in sources.iter().zip([ + (first.as_str(), "taslak.pdf", "application/pdf"), + (second.as_str(), "ozet.txt", "text/plain"), + ( + third.as_str(), + "konusma.docx", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + ), + ]) { + assert_eq!(source["key"], key); + assert_eq!(source["name"], name); + assert_eq!(source["content_type"], content_type); + } } /// Authentication is the whole gate on every door: no cookie is a `401`, not a