The history lists the caller's own episodes
Browse files at this commit6ed7e124c74c60c98e4c914fd5724cecd9aa9c8bParent: 5f9e97c- feat
- the history lists the caller's own episodes
8 changed files +512 -16
- .sqlx/query-09f372bb386bd8608b10f78098067bec84db3a9b14e722e34e54404d1edc39d0.json +40 -0
- README.md +1 -0
- src/db/podcast_job.rs +53 -6
- src/lib.rs +1 -1
- src/service/podcast_job.rs +4 -2
- src/web/podcast.rs +93 -5
- tests/integration.rs +1 -1
- tests/podcast.rs +319 -1
.sqlx/query-09f372bb386bd8608b10f78098067bec84db3a9b14e722e34e54404d1edc39d0.jsonadded+40 -0
| @@ -0,0 +1,40 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "SELECT id, title FROM course_note WHERE id = ANY($1)", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "course_note", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "title", | ||
| 20 | + "type_info": "Text", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "course_note", | ||
| 24 | + "name": "title" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + } | ||
| 28 | + ], | ||
| 29 | + "parameters": { | ||
| 30 | + "Left": [ | ||
| 31 | + "UuidArray" | ||
| 32 | + ] | ||
| 33 | + }, | ||
| 34 | + "nullable": [ | ||
| 35 | + false, | ||
| 36 | + false | ||
| 37 | + ] | ||
| 38 | + }, | ||
| 39 | + "hash": "09f372bb386bd8608b10f78098067bec84db3a9b14e722e34e54404d1edc39d0" | ||
| 40 | +} | ||
README.mdmodified+1 -0
| @@ -1409,6 +1409,7 @@ window filtering, before paging; negative values are a `400` naming the field. | |||
| 1409 | | POST | `/payments/reversals` | manager | Undo a line entered by mistake, for its exact amount — the line itself stays, with an opposing one appended beside it. Only a `charge` or a `refund` may be reversed (`400` otherwise): a mistaken payment is corrected with a refund, so money leaving the school is always spelled the one way. **Idempotent** — a line has at most one reversal, however often the call is retried. | | 1409 | | POST | `/payments/reversals` | manager | Undo a line entered by mistake, for its exact amount — the line itself stays, with an opposing one appended beside it. Only a `charge` or a `refund` may be reversed (`400` otherwise): a mistaken payment is corrected with a refund, so money leaving the school is always spelled the one way. **Idempotent** — a line has at most one reversal, however often the call is retried. | |
| 1410 | | GET | `/payments/statement/me` | student | The caller's own statement. The per-charge rows are paged via `?limit=&offset=` (omit `limit` for all of them); `balance_minor` is the same on every page, because the fold behind it reads every line. | | 1410 | | GET | `/payments/statement/me` | student | The caller's own statement. The per-charge rows are paged via `?limit=&offset=` (omit `limit` for all of them); `balance_minor` is the same on every page, because the fold behind it reads every line. | |
| 1411 | | GET | `/payments/statement/{user}` | manager | One student's statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is overdue. Own record always; otherwise manager+ or a parent link (a teacher gets a `403`). The rows are paged via `?limit=&offset=`; `balance_minor` is the same on every page. | | 1411 | | GET | `/payments/statement/{user}` | manager | One student's statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is overdue. Own record always; otherwise manager+ or a parent link (a teacher gets a `403`). The rows are paged via `?limit=&offset=`; `balance_minor` is the same on every page. | |
| 1412 | +| GET | `/podcast/jobs` | student | The caller's own episodes, newest first — every job the backend ever minted for this user, whatever state it stopped in, each with the title of the note it narrated. Paged via `?limit=&offset=`. | | ||
| 1412 | | POST | `/podcast/jobs` | student | Start one podcast job. Answers `202` with the backend's own receipt the moment the service accepts it. | | 1413 | | POST | `/podcast/jobs` | student | Start one podcast job. Answers `202` with the backend's own receipt the moment the service accepts it. | |
| 1413 | | GET | `/podcast/jobs/{id}` | student | One job's current state — the backend's own row, so this door answers with the service down, restarted, or never connected at all. A job nobody has updated inside its ETA-scaled window reads as `failed`/`interrupted`; that projection is read-side only and never written. | | 1414 | | GET | `/podcast/jobs/{id}` | student | One job's current state — the backend's own row, so this door answers with the service down, restarted, or never connected at all. A job nobody has updated inside its ETA-scaled window reads as `failed`/`interrupted`; that projection is read-side only and never written. | |
| 1414 | | GET | `/podcast/jobs/{id}/audio` | student | Stream one produced episode. The bytes are this school's own — ingested under this school's blob directory — and the content type is the one the upload declared, replayed from the row. | | 1415 | | GET | `/podcast/jobs/{id}/audio` | student | Stream one produced episode. The bytes are this school's own — ingested under this school's blob directory — and the content type is the one the upload declared, replayed from the row. | |
src/db/podcast_job.rsmodified+53 -6
| @@ -14,13 +14,16 @@ | |||
| 14 | //! (`podcast_job_done_has_audio`) backstops the service layer's refusal, so a | 14 | //! (`podcast_job_done_has_audio`) backstops the service layer's refusal, so a |
| 15 | //! result door can trust every `done` row to name a blob. | 15 | //! result door can trust every `done` row to name a blob. |
| 16 | 16 | ||
| 17 | +use std::collections::HashMap; | ||
| 18 | + | ||
| 17 | use crate::database::Database; | 19 | use crate::database::Database; |
| 18 | use crate::db::page::PagedList; | 20 | use crate::db::page::PagedList; |
| 21 | +use crate::domain::course_note::CourseNoteId; | ||
| 19 | use crate::domain::podcast_job::{PodcastJob, PodcastJobId, PodcastJobState}; | 22 | use crate::domain::podcast_job::{PodcastJob, PodcastJobId, PodcastJobState}; |
| 20 | use crate::domain::timestamp::Timestamp; | 23 | use crate::domain::timestamp::Timestamp; |
| 21 | use crate::domain::user::UserId; | 24 | use crate::domain::user::UserId; |
| 22 | use crate::error::AppError; | 25 | use crate::error::AppError; |
| 23 | -use sqlx::query_as; | 26 | +use sqlx::{query, query_as}; |
| 24 | 27 | ||
| 25 | /// Write one freshly minted job. The id and timestamps are the caller's — the | 28 | /// Write one freshly minted job. The id and timestamps are the caller's — the |
| 26 | /// service is handed the id this statement stores, so the row and the | 29 | /// service is handed the id this statement stores, so the row and the |
| @@ -96,20 +99,64 @@ pub async fn read_for( | |||
| 96 | } | 99 | } |
| 97 | 100 | ||
| 98 | /// A user's jobs, newest first — the sort `podcast_job_user_created` exists | 101 | /// A user's jobs, newest first — the sort `podcast_job_user_created` exists |
| 99 | -/// for. | 102 | +/// for — each paired with the title of the course note it narrates. |
| 103 | +/// | ||
| 104 | +/// The title is a second read over the page alone (the [`PagedList`] window | ||
| 105 | +/// already chose the rows), not a join inside the paging statement: the | ||
| 106 | +/// count that pages the list must count jobs, and a join there could only | ||
| 107 | +/// multiply or drop one. A note that is gone answers `None` — the job stays | ||
| 108 | +/// in the caller's history either way. | ||
| 100 | pub async fn list_for_user( | 109 | pub async fn list_for_user( |
| 101 | db: &Database, | 110 | db: &Database, |
| 102 | user: &UserId, | 111 | user: &UserId, |
| 103 | limit: Option<i64>, | 112 | limit: Option<i64>, |
| 104 | offset: i64, | 113 | offset: i64, |
| 105 | -) -> Result<(Vec<PodcastJob>, i64), AppError> { | 114 | +) -> Result<(Vec<(PodcastJob, Option<String>)>, i64), AppError> { |
| 106 | - PagedList::new( | 115 | + let (rows, total) = PagedList::new( |
| 107 | "podcast_job WHERE user_id = $1", | 116 | "podcast_job WHERE user_id = $1", |
| 108 | "ORDER BY created_at DESC, id DESC", | 117 | "ORDER BY created_at DESC, id DESC", |
| 109 | ) | 118 | ) |
| 110 | .bind(user.uuid()) | 119 | .bind(user.uuid()) |
| 111 | - .run(limit, offset, db) | 120 | + .run::<PodcastJob>(limit, offset, db) |
| 112 | - .await | 121 | + .await?; |
| 122 | + Ok((with_source_titles(db, rows).await?, total)) | ||
| 123 | +} | ||
| 124 | + | ||
| 125 | +/// Pair the jobs of one page with the titles of the notes they narrate: one | ||
| 126 | +/// statement however many distinct notes the page names (the ids ride a | ||
| 127 | +/// single `ANY`), none at all for an empty page. | ||
| 128 | +/// | ||
| 129 | +/// `source_id` is stored as the string the submit door was handed, so the | ||
| 130 | +/// lookup parses it the same way that door did | ||
| 131 | +/// ([`CourseNoteId::from_key`]); a job whose source no row matches keeps its | ||
| 132 | +/// `None`. | ||
| 133 | +async fn with_source_titles( | ||
| 134 | + db: &Database, | ||
| 135 | + jobs: Vec<PodcastJob>, | ||
| 136 | +) -> Result<Vec<(PodcastJob, Option<String>)>, AppError> { | ||
| 137 | + if jobs.is_empty() { | ||
| 138 | + return Ok(Vec::new()); | ||
| 139 | + } | ||
| 140 | + let ids: Vec<uuid::Uuid> = jobs | ||
| 141 | + .iter() | ||
| 142 | + .map(|job| CourseNoteId::from_key(job.get_source_id()).uuid()) | ||
| 143 | + .collect(); | ||
| 144 | + let titles: HashMap<uuid::Uuid, String> = | ||
| 145 | + query!("SELECT id, title FROM course_note WHERE id = ANY($1)", &ids,) | ||
| 146 | + .fetch_all(db) | ||
| 147 | + .await? | ||
| 148 | + .into_iter() | ||
| 149 | + .map(|row| (row.id, row.title)) | ||
| 150 | + .collect(); | ||
| 151 | + Ok(jobs | ||
| 152 | + .into_iter() | ||
| 153 | + .map(|job| { | ||
| 154 | + let title = titles | ||
| 155 | + .get(&CourseNoteId::from_key(job.get_source_id()).uuid()) | ||
| 156 | + .cloned(); | ||
| 157 | + (job, title) | ||
| 158 | + }) | ||
| 159 | + .collect()) | ||
| 113 | } | 160 | } |
| 114 | 161 | ||
| 115 | /// Apply one validated report: `from` is the state the service layer read and | 162 | /// Apply one validated report: `from` is the state the service layer read and |
src/lib.rsmodified+1 -1
| @@ -58,7 +58,7 @@ use crate::web::module_gate::gate; | |||
| 58 | (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"), | 58 | (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"), |
| 59 | (name = "rag", description = "The course-note RAG: its own nest, threads and tables, relayed through the same QUIC bridge as the chatbot — RAG is not folded into the chatbot's storage. Every authenticated role may ask (parents included) and every thread is private to its owner. Every question is scoped server-side to the asker's own `(sınıf, ders)` pairs, derived on each request from their live memberships — their şubeler' instances, a linked parent's children, and the school-wide club/etüt memberships they hold (which scope the subject across grades, `sinif: null`) — never from the body, so a caller cannot widen their own retrieval; a scope past `MAX_RAG_SCOPE_PAIRS` pairs is refused (400) rather than narrowed. A RAG thread draws on the school's existing AI thread seats (`max_chatbot_threads`, the same seat count the chatbot nest uses, one pool per user), its prompts and answers are bounded by `max_chatbot_message_len`, and its per-minute tier is its own: `RATE_LIMIT_RAG_PER_MINUTE` (default 6, `0` disables the tier; 429 with `Retry-After`). Sending is asynchronous exactly as the chatbot's is: `POST /rag/threads/{id}/messages` writes the turn plus a `pending` assistant row and answers `202`, then poll `GET /rag/threads/{id}/messages/{mid}` or open its `/stream` (SSE `delta`s then `done`/`error`). `503` when no AI service offers `rag.chat`, with nothing written. An answer may abstain — `abstained: true` with a `reason` (`guard_*`, `insufficient_data`, `model_abstained`) is a complete, successful turn, not an error — and carries its `citations`, up to `MAX_RAG_CITATIONS` per answer and at most `MAX_RAG_CITATION_PAGES` pages each (a service reply past either cap fails the turn whole). Each citation's corpus `doc_id` is resolved to the course-note file that owns it (`file`, `null` when no file the asker may view claims that document) beside the pages and retrieval span ids behind it."), | 59 | (name = "rag", description = "The course-note RAG: its own nest, threads and tables, relayed through the same QUIC bridge as the chatbot — RAG is not folded into the chatbot's storage. Every authenticated role may ask (parents included) and every thread is private to its owner. Every question is scoped server-side to the asker's own `(sınıf, ders)` pairs, derived on each request from their live memberships — their şubeler' instances, a linked parent's children, and the school-wide club/etüt memberships they hold (which scope the subject across grades, `sinif: null`) — never from the body, so a caller cannot widen their own retrieval; a scope past `MAX_RAG_SCOPE_PAIRS` pairs is refused (400) rather than narrowed. A RAG thread draws on the school's existing AI thread seats (`max_chatbot_threads`, the same seat count the chatbot nest uses, one pool per user), its prompts and answers are bounded by `max_chatbot_message_len`, and its per-minute tier is its own: `RATE_LIMIT_RAG_PER_MINUTE` (default 6, `0` disables the tier; 429 with `Retry-After`). Sending is asynchronous exactly as the chatbot's is: `POST /rag/threads/{id}/messages` writes the turn plus a `pending` assistant row and answers `202`, then poll `GET /rag/threads/{id}/messages/{mid}` or open its `/stream` (SSE `delta`s then `done`/`error`). `503` when no AI service offers `rag.chat`, with nothing written. An answer may abstain — `abstained: true` with a `reason` (`guard_*`, `insufficient_data`, `model_abstained`) is a complete, successful turn, not an error — and carries its `citations`, up to `MAX_RAG_CITATIONS` per answer and at most `MAX_RAG_CITATION_PAGES` pages each (a service reply past either cap fails the turn whole). Each citation's corpus `doc_id` is resolved to the course-note file that owns it (`file`, `null` when no file the asker may view claims that document) beside the pages and retrieval span ids behind it."), |
| 60 | (name = "insights", description = "ZEKA's computed student insights. The `hezarfen_zeka` AI service dials in over the same QUIC bridge as the chatbot, 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."), | 60 | (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."), |
| 61 | - (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 `<media root>/<school>/<source_key>` — 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}` (`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). 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 three 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)."), | 61 | + (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 `<media root>/<school>/<source_key>` — 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}` (`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)."), |
| 62 | (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names — `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins…, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names — `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"), | 62 | (name = "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`"), |
| 63 | (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`). Every authenticated role keeps notes, `parent` included: a note is private own-scoped data with no other reader, and the routes carry **no role bar at all** — ownership is the whole authorization, so nobody but the owner ever reaches a note or its files (a stranger's id is a `404`, never a `403`). That is deliberate and it is the fix for a real defect: while these routes required `student`, a demotion to `parent` locked the owner out of their own notes for good, and since nothing else in the crate reads a note and no route cascades one, the rows and their on-disk blobs became unreachable and undeletable by everybody. Own-scoped personal data is not confiscated by a role change"), | 63 | (name = "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"), |
| 64 | (name = "messages", description = "One-to-one mail-style messages, upward only below staff: a student or parent writes to a teacher, manager or admin (parents included — messaging is the one place a parent writes) and never to another student or parent (`403`), while staff write to anyone, each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"), | 64 | (name = "messages", description = "One-to-one mail-style messages, upward only below staff: a student or parent writes to a teacher, manager or admin (parents included — messaging is the one place a parent writes) and never to another student or parent (`403`), while staff write to anyone, each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"), |
src/service/podcast_job.rsmodified+4 -2
| @@ -148,13 +148,15 @@ pub async fn read_for( | |||
| 148 | podcast_job::read_for(db, id, user).await | 148 | podcast_job::read_for(db, id, user).await |
| 149 | } | 149 | } |
| 150 | 150 | ||
| 151 | -/// A user's own jobs, newest first. | 151 | +/// A user's own jobs, newest first, each paired with the title of the course |
| 152 | +/// note it narrates — `None` once that note is gone. The pairing is this | ||
| 153 | +/// list's whole extra read; everything else is the row. | ||
| 152 | pub async fn list_for_user( | 154 | pub async fn list_for_user( |
| 153 | db: &Database, | 155 | db: &Database, |
| 154 | user: &UserId, | 156 | user: &UserId, |
| 155 | limit: Option<i64>, | 157 | limit: Option<i64>, |
| 156 | offset: i64, | 158 | offset: i64, |
| 157 | -) -> Result<(Vec<PodcastJob>, i64), AppError> { | 159 | +) -> Result<(Vec<(PodcastJob, Option<String>)>, i64), AppError> { |
| 158 | podcast_job::list_for_user(db, user, limit, offset).await | 160 | podcast_job::list_for_user(db, user, limit, offset).await |
| 159 | } | 161 | } |
| 160 | 162 | ||
src/web/podcast.rsmodified+93 -5
| @@ -10,16 +10,17 @@ | |||
| 10 | //! that a restart or a wiped volume could take down with it. The service's own | 10 | //! that a restart or a wiped volume could take down with it. The service's own |
| 11 | //! record is a mirror the pipeline works against, not the source of truth. | 11 | //! record is a mirror the pipeline works against, not the source of truth. |
| 12 | //! | 12 | //! |
| 13 | -//! Five doors: | 13 | +//! Six doors: |
| 14 | //! | 14 | //! |
| 15 | //! * `POST /podcast/jobs` — write the row, dispatch `podcast.submit` | 15 | //! * `POST /podcast/jobs` — write the row, dispatch `podcast.submit` |
| 16 | +//! * `GET /podcast/jobs` — the caller's own history, newest first | ||
| 16 | //! * `GET /podcast/jobs/{id}` — the row's snapshot (projected, see below) | 17 | //! * `GET /podcast/jobs/{id}` — the row's snapshot (projected, see below) |
| 17 | //! * `GET /podcast/jobs/{id}/result` — a finished job's artifact references | 18 | //! * `GET /podcast/jobs/{id}/result` — a finished job's artifact references |
| 18 | //! * `GET /podcast/jobs/{id}/audio` — streams the ingested episode | 19 | //! * `GET /podcast/jobs/{id}/audio` — streams the ingested episode |
| 19 | //! * `POST /podcast/jobs/{id}/cancel` — forward the cancel, stamp the verdict | 20 | //! * `POST /podcast/jobs/{id}/cancel` — forward the cancel, stamp the verdict |
| 20 | //! | 21 | //! |
| 21 | //! The two dispatching doors (`submit`, `cancel`) refuse `503` when no worker | 22 | //! The two dispatching doors (`submit`, `cancel`) refuse `503` when no worker |
| 22 | -//! declares their capability; the three reading doors need no service at all. | 23 | +//! declares their capability; the four reading doors need no service at all. |
| 23 | //! A relayed failure keeps the service's own code and decides the HTTP status | 24 | //! A relayed failure keeps the service's own code and decides the HTTP status |
| 24 | //! (`failure`), so a client branches on the same vocabulary the bridge speaks. | 25 | //! (`failure`), so a client branches on the same vocabulary the bridge speaks. |
| 25 | //! | 26 | //! |
| @@ -44,7 +45,7 @@ | |||
| 44 | 45 | ||
| 45 | use axum::Json; | 46 | use axum::Json; |
| 46 | use axum::body::{Body, Bytes}; | 47 | use axum::body::{Body, Bytes}; |
| 47 | -use axum::extract::Path; | 48 | +use axum::extract::{Path, Query}; |
| 48 | use axum::http::HeaderValue; | 49 | use axum::http::HeaderValue; |
| 49 | use axum::http::StatusCode; | 50 | use axum::http::StatusCode; |
| 50 | use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS}; | 51 | use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS}; |
| @@ -72,7 +73,7 @@ use crate::service::podcast_job as jobs; | |||
| 72 | use crate::state::AppState; | 73 | use crate::state::AppState; |
| 73 | use crate::web::tenant_state::{SchoolSlug, State}; | 74 | use crate::web::tenant_state::{SchoolSlug, State}; |
| 74 | 75 | ||
| 75 | -use super::{CurrentUser, ai_unavailable}; | 76 | +use super::{CurrentUser, Page, PageParams, ai_unavailable}; |
| 76 | 77 | ||
| 77 | /// How much of the audio is read per chunk, and how many chunks the body may | 78 | /// How much of the audio is read per chunk, and how many chunks the body may |
| 78 | /// have in flight. 4 × 64 KiB is the whole memory ceiling one audio stream | 79 | /// have in flight. 4 × 64 KiB is the whole memory ceiling one audio stream |
| @@ -82,7 +83,7 @@ const AUDIO_CHUNKS_IN_FLIGHT: usize = 4; | |||
| 82 | 83 | ||
| 83 | pub fn routes() -> OpenApiRouter<AppState> { | 84 | pub fn routes() -> OpenApiRouter<AppState> { |
| 84 | OpenApiRouter::new() | 85 | OpenApiRouter::new() |
| 85 | - .routes(routes!(submit)) | 86 | + .routes(routes!(submit, list)) |
| 86 | .routes(routes!(status)) | 87 | .routes(routes!(status)) |
| 87 | .routes(routes!(result)) | 88 | .routes(routes!(result)) |
| 88 | .routes(routes!(audio)) | 89 | .routes(routes!(audio)) |
| @@ -268,6 +269,93 @@ async fn submit( | |||
| 268 | } | 269 | } |
| 269 | } | 270 | } |
| 270 | 271 | ||
| 272 | +/// One episode in the caller's history: the backend's own row, plus the title | ||
| 273 | +/// of the course note it narrates. | ||
| 274 | +#[derive(Serialize, ToSchema)] | ||
| 275 | +struct JobSummary { | ||
| 276 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | ||
| 277 | + job_id: String, | ||
| 278 | + /// `queued`, `running`, `done`, `failed` or `cancelled` — a job nobody | ||
| 279 | + /// has updated inside its ETA-scaled window is presented as `failed`. | ||
| 280 | + state: String, | ||
| 281 | + /// The narration the service resolved; `null` until its first report | ||
| 282 | + /// settles it. | ||
| 283 | + #[schema(example = "duz_okuma")] | ||
| 284 | + format: Option<String>, | ||
| 285 | + /// The course note this episode narrates. | ||
| 286 | + #[schema(example = "019732e3-7b00-7000-8000-00000000face")] | ||
| 287 | + source_id: String, | ||
| 288 | + /// That note's title as of this read; `null` once the note is gone — the | ||
| 289 | + /// episode keeps its place in the history either way. | ||
| 290 | + #[schema(example = "Hücre ve Canlıların Ortak Özellikleri")] | ||
| 291 | + source_title: Option<String>, | ||
| 292 | + /// UTC unix-milliseconds, server-stamped. | ||
| 293 | + created_at: i64, | ||
| 294 | + /// When the job reached its terminal state (the write that finished it); | ||
| 295 | + /// `null` while it is live. | ||
| 296 | + finished_at: Option<i64>, | ||
| 297 | + /// The finished episode's running time, as the service declared it at | ||
| 298 | + /// upload; `null` until then. | ||
| 299 | + duration_secs: Option<f64>, | ||
| 300 | + /// The failure's own code, once one is on the record. | ||
| 301 | + error_code: Option<String>, | ||
| 302 | +} | ||
| 303 | + | ||
| 304 | +impl JobSummary { | ||
| 305 | + fn new(job: &PodcastJob, source_title: Option<String>) -> Self { | ||
| 306 | + Self { | ||
| 307 | + job_id: job.get_id().key(), | ||
| 308 | + state: job.get_state().as_str().to_string(), | ||
| 309 | + format: job.get_format().map(str::to_string), | ||
| 310 | + source_id: job.get_source_id().to_string(), | ||
| 311 | + source_title, | ||
| 312 | + created_at: job.get_created_at().as_millis(), | ||
| 313 | + finished_at: job | ||
| 314 | + .get_state() | ||
| 315 | + .is_terminal() | ||
| 316 | + .then(|| job.get_updated_at().as_millis()), | ||
| 317 | + duration_secs: job.get_duration_secs(), | ||
| 318 | + error_code: job.get_error_code().map(str::to_string), | ||
| 319 | + } | ||
| 320 | + } | ||
| 321 | +} | ||
| 322 | + | ||
| 323 | +/// The caller's own episodes, newest first — every job the backend ever | ||
| 324 | +/// minted for this user, whatever state it stopped in, each with the title of | ||
| 325 | +/// the note it narrated. Paged via `?limit=&offset=`. | ||
| 326 | +/// | ||
| 327 | +/// This is a reading door like the per-id ones: it answers from the rows | ||
| 328 | +/// alone, so with the service down, restarted, or never connected at all the | ||
| 329 | +/// history is still exactly what it was. A job nobody has updated inside its | ||
| 330 | +/// ETA-scaled window is presented as `failed` (the same read-side projection | ||
| 331 | +/// the per-id door applies); rows past the retention window stay listed — | ||
| 332 | +/// opening one is what earns the `410`. | ||
| 333 | +#[utoipa::path( | ||
| 334 | + get, | ||
| 335 | + path = "/jobs", | ||
| 336 | + tag = "podcast", | ||
| 337 | + security(("session_cookie" = [])), | ||
| 338 | + params(PageParams), | ||
| 339 | + responses( | ||
| 340 | + (status = 200, description = "A page of the caller's episodes, newest first", body = Page<JobSummary>), | ||
| 341 | + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), | ||
| 342 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 343 | + ), | ||
| 344 | +)] | ||
| 345 | +async fn list( | ||
| 346 | + State(st): State<AppState>, | ||
| 347 | + CurrentUser(user): CurrentUser, | ||
| 348 | + Query(page): Query<PageParams>, | ||
| 349 | +) -> Result<Json<Page<JobSummary>>, AppError> { | ||
| 350 | + let (limit, offset) = page.resolve()?; | ||
| 351 | + let (jobs, total) = jobs::list_for_user(&st.db, user.get_id(), limit, offset).await?; | ||
| 352 | + let items = jobs | ||
| 353 | + .into_iter() | ||
| 354 | + .map(|(job, source_title)| JobSummary::new(&job.projected(), source_title)) | ||
| 355 | + .collect(); | ||
| 356 | + Ok(Json(Page::new(items, total, limit, offset))) | ||
| 357 | +} | ||
| 358 | + | ||
| 271 | /// One job's current state — the backend's own row, so this door answers with | 359 | /// One job's current state — the backend's own row, so this door answers with |
| 272 | /// the service down, restarted, or never connected at all. A job nobody has | 360 | /// the service down, restarted, or never connected at all. A job nobody has |
| 273 | /// updated inside its ETA-scaled window reads as `failed`/`interrupted`; that | 361 | /// updated inside its ETA-scaled window reads as `failed`/`interrupted`; that |
tests/integration.rsmodified+1 -1
| @@ -434,7 +434,7 @@ async fn protected_routes_require_session() { | |||
| 434 | /// Floor on the number of protected operations swept. It only ever goes | 434 | /// Floor on the number of protected operations swept. It only ever goes |
| 435 | /// up: raise it when routes are added. Without it, deleting a route family | 435 | /// up: raise it when routes are added. Without it, deleting a route family |
| 436 | /// would delete its own coverage and still pass. | 436 | /// would delete its own coverage and still pass. |
| 437 | - const MIN_PROTECTED: usize = 337; | 437 | + const MIN_PROTECTED: usize = 338; |
| 438 | 438 | ||
| 439 | let app = mem_app().await; | 439 | let app = mem_app().await; |
| 440 | let spec = send(&app, "GET", "/api-docs/openapi.json", None, None) | 440 | let spec = send(&app, "GET", "/api-docs/openapi.json", None, None) |
tests/podcast.rsmodified+319 -1
| @@ -28,7 +28,7 @@ use hezarfen_backend::ai::protocol::{ | |||
| 28 | use hezarfen_backend::ai::{AiBridge, BridgeConfig}; | 28 | use hezarfen_backend::ai::{AiBridge, BridgeConfig}; |
| 29 | use hezarfen_backend::constant::{ | 29 | use hezarfen_backend::constant::{ |
| 30 | AI_ALPN, AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_SUBMIT_CAPABILITY, AI_PROTOCOL, | 30 | AI_ALPN, AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_SUBMIT_CAPABILITY, AI_PROTOCOL, |
| 31 | - PODCAST_JOB_RETENTION_SECS, PODCAST_JOB_STALE_FLOOR_SECS, | 31 | + PODCAST_INTERRUPTED_CODE, PODCAST_JOB_RETENTION_SECS, PODCAST_JOB_STALE_FLOOR_SECS, |
| 32 | }; | 32 | }; |
| 33 | use hezarfen_backend::database::Database; | 33 | use hezarfen_backend::database::Database; |
| 34 | use hezarfen_backend::domain::timestamp::Timestamp; | 34 | use hezarfen_backend::domain::timestamp::Timestamp; |
| @@ -560,6 +560,44 @@ async fn seed_done_job( | |||
| 560 | job | 560 | job |
| 561 | } | 561 | } |
| 562 | 562 | ||
| 563 | +/// One job row in the shape the history reads: a chosen `state`, the note it | ||
| 564 | +/// narrates, and a `created_at` the test owns — the list orders by that | ||
| 565 | +/// column, so a wall-clock stamp would race the assertion. `done` rows name | ||
| 566 | +/// an artifact (the schema's own rule); anything else carries none. | ||
| 567 | +async fn seed_listed_job( | ||
| 568 | + db: &Database, | ||
| 569 | + job: Uuid, | ||
| 570 | + user: &str, | ||
| 571 | + source: &str, | ||
| 572 | + state: &str, | ||
| 573 | + created_at: i64, | ||
| 574 | +) -> Uuid { | ||
| 575 | + let done = state == "done"; | ||
| 576 | + let audio_key = done.then(|| format!("podcast/{job}.mp3")); | ||
| 577 | + sqlx::query( | ||
| 578 | + "INSERT INTO podcast_job (id, user_id, source_id, format, state, stage, progress, \ | ||
| 579 | + error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, \ | ||
| 580 | + created_at, updated_at) \ | ||
| 581 | + VALUES ($1, $2, $3, $4, $5, '', 1, $6, $7, $8, $9, $10, $11, $12, $12)", | ||
| 582 | + ) | ||
| 583 | + .bind(job) | ||
| 584 | + .bind(uuid_of(user)) | ||
| 585 | + .bind(source) | ||
| 586 | + .bind(FORMAT) | ||
| 587 | + .bind(state) | ||
| 588 | + .bind((state == "failed").then_some(PODCAST_INTERRUPTED_CODE)) | ||
| 589 | + .bind(&audio_key) | ||
| 590 | + .bind(done.then_some(AUDIO_NAME)) | ||
| 591 | + .bind(done.then_some(AUDIO_TYPE)) | ||
| 592 | + .bind(done.then_some(4096_i64)) | ||
| 593 | + .bind(done.then_some(DURATION_SECS)) | ||
| 594 | + .bind(created_at) | ||
| 595 | + .execute(db) | ||
| 596 | + .await | ||
| 597 | + .expect("seed the listed job"); | ||
| 598 | + job | ||
| 599 | +} | ||
| 600 | + | ||
| 563 | /// Write `bytes` at `key` under the demo school's blob directory — the layout | 601 | /// Write `bytes` at `key` under the demo school's blob directory — the layout |
| 564 | /// an ingested episode lands in, and the only place the audio door reads. | 602 | /// an ingested episode lands in, and the only place the audio door reads. |
| 565 | fn write_blob(key: &str, bytes: &[u8]) { | 603 | fn write_blob(key: &str, bytes: &[u8]) { |
| @@ -867,6 +905,285 @@ async fn a_cancel_of_a_terminal_job_answers_false_without_the_service() { | |||
| 867 | assert_eq!(state, "failed", "the verdict never rewrites a terminal row"); | 905 | assert_eq!(state, "failed", "the verdict never rewrites a terminal row"); |
| 868 | } | 906 | } |
| 869 | 907 | ||
| 908 | +// ------------------------------------------------------------- the history -- | ||
| 909 | + | ||
| 910 | +/// One `GET /podcast/jobs…` — the caller's own history. | ||
| 911 | +async fn list_of(app: &Router, cookie: &str, query: &str) -> common::Res { | ||
| 912 | + common::send( | ||
| 913 | + app, | ||
| 914 | + "GET", | ||
| 915 | + &format!("/podcast/jobs{query}"), | ||
| 916 | + Some(cookie), | ||
| 917 | + None, | ||
| 918 | + ) | ||
| 919 | + .await | ||
| 920 | +} | ||
| 921 | + | ||
| 922 | +/// The `job_id`s of one list response, in the order it returned them. | ||
| 923 | +fn ids_of(body: &Value) -> Vec<String> { | ||
| 924 | + body["items"] | ||
| 925 | + .as_array() | ||
| 926 | + .expect("a list response carries items") | ||
| 927 | + .iter() | ||
| 928 | + .map(|item| { | ||
| 929 | + item["job_id"] | ||
| 930 | + .as_str() | ||
| 931 | + .expect("every item names its job") | ||
| 932 | + .to_string() | ||
| 933 | + }) | ||
| 934 | + .collect() | ||
| 935 | +} | ||
| 936 | + | ||
| 937 | +/// The history shows what the school produced: a finished episode comes back | ||
| 938 | +/// with the title of the note it narrates, its running time, and where it | ||
| 939 | +/// ended — all from the backend's own row, with no service in the picture. | ||
| 940 | +#[tokio::test] | ||
| 941 | +async fn the_history_lists_a_finished_job_with_its_source_title() { | ||
| 942 | + let (app, cookie, db) = app_without_ai().await; | ||
| 943 | + let user = common::me_id(&app, &cookie).await; | ||
| 944 | + let (note, _key) = note_with_pdf(&app, &db).await; | ||
| 945 | + let stamp = now_ms(); | ||
| 946 | + let job = seed_listed_job(&db, Uuid::now_v7(), &user, ¬e, "done", stamp).await; | ||
| 947 | + | ||
| 948 | + let res = list_of(&app, &cookie, "").await; | ||
| 949 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 950 | + assert_eq!(res.body["total"], 1); | ||
| 951 | + assert_eq!(res.body["offset"], 0); | ||
| 952 | + let item = &res.body["items"][0]; | ||
| 953 | + assert_eq!(item["job_id"], job.to_string()); | ||
| 954 | + assert_eq!(item["state"], "done"); | ||
| 955 | + assert_eq!(item["format"], FORMAT); | ||
| 956 | + assert_eq!(item["source_id"], note); | ||
| 957 | + assert_eq!(item["source_title"], "Bölüm 1"); | ||
| 958 | + assert_eq!(item["created_at"], stamp); | ||
| 959 | + assert_eq!(item["finished_at"], stamp); | ||
| 960 | + assert_eq!(item["duration_secs"], DURATION_SECS); | ||
| 961 | + assert!(item["error_code"].is_null()); | ||
| 962 | +} | ||
| 963 | + | ||
| 964 | +/// Newest first, with the id breaking the tie: the frozen order, on rows | ||
| 965 | +/// seeded out of order — including two that share their instant. | ||
| 966 | +#[tokio::test] | ||
| 967 | +async fn the_history_is_newest_first() { | ||
| 968 | + let (app, cookie, db) = app_without_ai().await; | ||
| 969 | + let user = common::me_id(&app, &cookie).await; | ||
| 970 | + let base = now_ms() - 3 * 60 * 60 * 1_000; | ||
| 971 | + let oldest = seed_listed_job(&db, Uuid::now_v7(), &user, SOURCE_ID, "done", base).await; | ||
| 972 | + let middle = seed_listed_job( | ||
| 973 | + &db, | ||
| 974 | + Uuid::now_v7(), | ||
| 975 | + &user, | ||
| 976 | + SOURCE_ID, | ||
| 977 | + "failed", | ||
| 978 | + base + 3_600_000, | ||
| 979 | + ) | ||
| 980 | + .await; | ||
| 981 | + let tie_old = seed_listed_job( | ||
| 982 | + &db, | ||
| 983 | + Uuid::now_v7(), | ||
| 984 | + &user, | ||
| 985 | + SOURCE_ID, | ||
| 986 | + "done", | ||
| 987 | + base + 7_200_000, | ||
| 988 | + ) | ||
| 989 | + .await; | ||
| 990 | + let tie_new = seed_listed_job( | ||
| 991 | + &db, | ||
| 992 | + Uuid::now_v7(), | ||
| 993 | + &user, | ||
| 994 | + SOURCE_ID, | ||
| 995 | + "done", | ||
| 996 | + base + 7_200_000, | ||
| 997 | + ) | ||
| 998 | + .await; | ||
| 999 | + | ||
| 1000 | + let res = list_of(&app, &cookie, "").await; | ||
| 1001 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 1002 | + assert_eq!(res.body["total"], 4); | ||
| 1003 | + assert_eq!( | ||
| 1004 | + ids_of(&res.body), | ||
| 1005 | + vec![ | ||
| 1006 | + tie_new.to_string(), | ||
| 1007 | + tie_old.to_string(), | ||
| 1008 | + middle.to_string(), | ||
| 1009 | + oldest.to_string() | ||
| 1010 | + ] | ||
| 1011 | + ); | ||
| 1012 | +} | ||
| 1013 | + | ||
| 1014 | +/// `?limit=&offset=` slice the ordered history and `total` stays the unpaged | ||
| 1015 | +/// count, so a client can page without a second request — and an offset past | ||
| 1016 | +/// the tail is an empty page, not an error. | ||
| 1017 | +#[tokio::test] | ||
| 1018 | +async fn the_history_pages_with_limit_and_offset() { | ||
| 1019 | + let (app, cookie, db) = app_without_ai().await; | ||
| 1020 | + let user = common::me_id(&app, &cookie).await; | ||
| 1021 | + let base = now_ms() - 3 * 60 * 60 * 1_000; | ||
| 1022 | + let oldest = seed_listed_job(&db, Uuid::now_v7(), &user, SOURCE_ID, "done", base).await; | ||
| 1023 | + let middle = seed_listed_job( | ||
| 1024 | + &db, | ||
| 1025 | + Uuid::now_v7(), | ||
| 1026 | + &user, | ||
| 1027 | + SOURCE_ID, | ||
| 1028 | + "done", | ||
| 1029 | + base + 3_600_000, | ||
| 1030 | + ) | ||
| 1031 | + .await; | ||
| 1032 | + let newest = seed_listed_job( | ||
| 1033 | + &db, | ||
| 1034 | + Uuid::now_v7(), | ||
| 1035 | + &user, | ||
| 1036 | + SOURCE_ID, | ||
| 1037 | + "done", | ||
| 1038 | + base + 7_200_000, | ||
| 1039 | + ) | ||
| 1040 | + .await; | ||
| 1041 | + | ||
| 1042 | + let first = list_of(&app, &cookie, "?limit=2").await; | ||
| 1043 | + assert_eq!(first.status, StatusCode::OK, "{}", first.body); | ||
| 1044 | + assert_eq!(first.body["total"], 3); | ||
| 1045 | + assert_eq!(first.body["limit"], 2); | ||
| 1046 | + assert_eq!( | ||
| 1047 | + ids_of(&first.body), | ||
| 1048 | + vec![newest.to_string(), middle.to_string()] | ||
| 1049 | + ); | ||
| 1050 | + | ||
| 1051 | + let second = list_of(&app, &cookie, "?limit=1&offset=1").await; | ||
| 1052 | + assert_eq!(second.body["total"], 3); | ||
| 1053 | + assert_eq!(second.body["offset"], 1); | ||
| 1054 | + assert_eq!(ids_of(&second.body), vec![middle.to_string()]); | ||
| 1055 | + | ||
| 1056 | + let past = list_of(&app, &cookie, "?limit=2&offset=9").await; | ||
| 1057 | + assert_eq!(past.body["total"], 3); | ||
| 1058 | + assert!(ids_of(&past.body).is_empty()); | ||
| 1059 | + | ||
| 1060 | + let bad = list_of(&app, &cookie, "?limit=0").await; | ||
| 1061 | + assert_eq!(bad.status, StatusCode::BAD_REQUEST, "{}", bad.body); | ||
| 1062 | + assert!( | ||
| 1063 | + bad.body["error"] | ||
| 1064 | + .as_str() | ||
| 1065 | + .expect("an error") | ||
| 1066 | + .contains("limit"), | ||
| 1067 | + "the refusal names the field: {}", | ||
| 1068 | + bad.body | ||
| 1069 | + ); | ||
| 1070 | + | ||
| 1071 | + let unpaged = list_of(&app, &cookie, "?offset=1").await; | ||
| 1072 | + assert_eq!(unpaged.body["total"], 3); | ||
| 1073 | + assert!(unpaged.body["limit"].is_null()); | ||
| 1074 | + assert_eq!( | ||
| 1075 | + ids_of(&unpaged.body).len(), | ||
| 1076 | + 2, | ||
| 1077 | + "{oldest} is the one skipped" | ||
| 1078 | + ); | ||
| 1079 | +} | ||
| 1080 | + | ||
| 1081 | +/// A school with no episodes yet answers an empty page — `items: []`, | ||
| 1082 | +/// `total: 0` — never a `404`. | ||
| 1083 | +#[tokio::test] | ||
| 1084 | +async fn an_empty_history_is_an_empty_page() { | ||
| 1085 | + let (app, cookie, _db) = app_without_ai().await; | ||
| 1086 | + | ||
| 1087 | + let res = list_of(&app, &cookie, "").await; | ||
| 1088 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 1089 | + assert_eq!(res.body["total"], 0); | ||
| 1090 | + assert!(ids_of(&res.body).is_empty()); | ||
| 1091 | + assert!(res.body["limit"].is_null()); | ||
| 1092 | +} | ||
| 1093 | + | ||
| 1094 | +/// A live job lists as itself, with everything only a finished episode can | ||
| 1095 | +/// know left `null` — and a job nobody has updated inside its ETA-scaled | ||
| 1096 | +/// window reads `failed`/`interrupted`, the same read-side projection the | ||
| 1097 | +/// per-id door applies. The projection writes nothing: the row still says | ||
| 1098 | +/// `running` afterwards. | ||
| 1099 | +#[tokio::test] | ||
| 1100 | +async fn a_live_job_lists_with_nulls_and_a_stale_one_reads_failed() { | ||
| 1101 | + let (app, cookie, db) = app_without_ai().await; | ||
| 1102 | + let user = common::me_id(&app, &cookie).await; | ||
| 1103 | + let fresh = seed_listed_job(&db, Uuid::now_v7(), &user, SOURCE_ID, "running", now_ms()).await; | ||
| 1104 | + let aged = now_ms() - (PODCAST_JOB_STALE_FLOOR_SECS + 100) * 1_000; | ||
| 1105 | + let stale = seed_listed_job(&db, Uuid::now_v7(), &user, SOURCE_ID, "running", aged).await; | ||
| 1106 | + | ||
| 1107 | + let res = list_of(&app, &cookie, "").await; | ||
| 1108 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 1109 | + let items = res.body["items"].as_array().expect("items"); | ||
| 1110 | + assert_eq!(items.len(), 2); | ||
| 1111 | + let live = items | ||
| 1112 | + .iter() | ||
| 1113 | + .find(|item| item["job_id"] == fresh.to_string()) | ||
| 1114 | + .expect("the fresh job is listed"); | ||
| 1115 | + assert_eq!(live["state"], "running"); | ||
| 1116 | + assert!(live["finished_at"].is_null()); | ||
| 1117 | + assert!(live["duration_secs"].is_null()); | ||
| 1118 | + assert!(live["error_code"].is_null()); | ||
| 1119 | + assert!(live["source_title"].is_null(), "no note answers to that id"); | ||
| 1120 | + let dead = items | ||
| 1121 | + .iter() | ||
| 1122 | + .find(|item| item["job_id"] == stale.to_string()) | ||
| 1123 | + .expect("the stale job is listed"); | ||
| 1124 | + assert_eq!(dead["state"], "failed"); | ||
| 1125 | + assert_eq!(dead["error_code"], "interrupted"); | ||
| 1126 | + | ||
| 1127 | + let stored: String = sqlx::query_scalar("SELECT state FROM podcast_job WHERE id = $1") | ||
| 1128 | + .bind(stale) | ||
| 1129 | + .fetch_one(&db) | ||
| 1130 | + .await | ||
| 1131 | + .expect("the row is still there"); | ||
| 1132 | + assert_eq!(stored, "running", "the projection wrote nothing"); | ||
| 1133 | +} | ||
| 1134 | + | ||
| 1135 | +/// The history is school-scoped like every other door: each school lists its | ||
| 1136 | +/// own episodes only, even when both hold a job for a user of the same name — | ||
| 1137 | +/// and a note's title never crosses either. | ||
| 1138 | +#[tokio::test] | ||
| 1139 | +async fn the_history_never_shows_another_schools_jobs() { | ||
| 1140 | + let deployment = common::deployment_with(&[("beta", "Beta Koleji")]).await; | ||
| 1141 | + let app = &deployment.app; | ||
| 1142 | + let demo_db = common::demo_db(&deployment.tenants).await; | ||
| 1143 | + let beta_db = deployment | ||
| 1144 | + .tenants | ||
| 1145 | + .get(&Slug::try_new("beta").expect("the beta slug")) | ||
| 1146 | + .await | ||
| 1147 | + .expect("the beta school's handle"); | ||
| 1148 | + let demo_cookie = common::login_as_school(app, &demo_db, DEMO_SLUG, "ali", "teacher").await; | ||
| 1149 | + let beta_cookie = common::login_as_school(app, &beta_db, "beta", "ali", "teacher").await; | ||
| 1150 | + let demo_user = common::me_id(app, &demo_cookie).await; | ||
| 1151 | + let beta_user = common::me_id(app, &beta_cookie).await; | ||
| 1152 | + | ||
| 1153 | + let course = common::create_course(app, &demo_cookie, "Matematik").await; | ||
| 1154 | + let demo_note = create_note(app, &demo_cookie, &course).await; | ||
| 1155 | + let demo_job = seed_listed_job( | ||
| 1156 | + &demo_db, | ||
| 1157 | + Uuid::now_v7(), | ||
| 1158 | + &demo_user, | ||
| 1159 | + &demo_note, | ||
| 1160 | + "done", | ||
| 1161 | + now_ms(), | ||
| 1162 | + ) | ||
| 1163 | + .await; | ||
| 1164 | + let beta_job = seed_listed_job( | ||
| 1165 | + &beta_db, | ||
| 1166 | + Uuid::now_v7(), | ||
| 1167 | + &beta_user, | ||
| 1168 | + SOURCE_ID, | ||
| 1169 | + "done", | ||
| 1170 | + now_ms(), | ||
| 1171 | + ) | ||
| 1172 | + .await; | ||
| 1173 | + | ||
| 1174 | + let demo_list = list_of(app, &demo_cookie, "").await; | ||
| 1175 | + assert_eq!(demo_list.status, StatusCode::OK, "{}", demo_list.body); | ||
| 1176 | + assert_eq!(demo_list.body["total"], 1); | ||
| 1177 | + assert_eq!(ids_of(&demo_list.body), vec![demo_job.to_string()]); | ||
| 1178 | + assert_eq!(demo_list.body["items"][0]["source_title"], "Bölüm 1"); | ||
| 1179 | + | ||
| 1180 | + let beta_list = list_of(app, &beta_cookie, "").await; | ||
| 1181 | + assert_eq!(beta_list.status, StatusCode::OK, "{}", beta_list.body); | ||
| 1182 | + assert_eq!(beta_list.body["total"], 1); | ||
| 1183 | + assert_eq!(ids_of(&beta_list.body), vec![beta_job.to_string()]); | ||
| 1184 | + assert_ne!(beta_list.body["items"][0]["job_id"], demo_job.to_string()); | ||
| 1185 | +} | ||
| 1186 | + | ||
| 870 | // --------------------------------------------------------------- refusals -- | 1187 | // --------------------------------------------------------------- refusals -- |
| 871 | 1188 | ||
| 872 | /// A submit that reaches no service writes nothing: the `503` is the whole | 1189 | /// A submit that reaches no service writes nothing: the `503` is the whole |
| @@ -1250,6 +1567,7 @@ async fn every_door_requires_a_session() { | |||
| 1250 | 1567 | ||
| 1251 | let doors = [ | 1568 | let doors = [ |
| 1252 | ("POST", "/podcast/jobs".to_string(), Some(json!({ "source_id": SOURCE_ID }))), | 1569 | ("POST", "/podcast/jobs".to_string(), Some(json!({ "source_id": SOURCE_ID }))), |
| 1570 | + ("GET", "/podcast/jobs".to_string(), None), | ||
| 1253 | ("GET", format!("/podcast/jobs/{id}"), None), | 1571 | ("GET", format!("/podcast/jobs/{id}"), None), |
| 1254 | ("GET", format!("/podcast/jobs/{id}/result"), None), | 1572 | ("GET", format!("/podcast/jobs/{id}/result"), None), |
| 1255 | ("GET", format!("/podcast/jobs/{id}/audio"), None), | 1573 | ("GET", format!("/podcast/jobs/{id}/audio"), None), |