diff --git a/.sqlx/query-e1bd89bafa14d3594316fc1768683dd9869275117ab83a255dac8de33b35725c.json b/.sqlx/query-e1bd89bafa14d3594316fc1768683dd9869275117ab83a255dac8de33b35725c.json new file mode 100644 index 0000000..8eba76b --- /dev/null +++ b/.sqlx/query-e1bd89bafa14d3594316fc1768683dd9869275117ab83a255dac8de33b35725c.json @@ -0,0 +1,76 @@ +{ + "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/src/ai/podcast.rs b/src/ai/podcast.rs index 00ba3e9..66e2a89 100644 --- a/src/ai/podcast.rs +++ b/src/ai/podcast.rs @@ -15,8 +15,11 @@ //! worker: //! //! * [`submit`] — `podcast.submit`, whose payload carries the backend-minted -//! `job_id` and the submitting `user_id` (the service stores both; its own -//! record is keyed by the id the backend will keep asking about). +//! `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. //! * [`cancel`] — `podcast.cancel`, unchanged: a write on the service's queue, //! and the capability is what decides whether a deployment offers the door. //! @@ -49,7 +52,14 @@ 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. 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. + pub source_key: String, /// `None` means the service applies its own default (`duz_okuma` today). #[serde(default, skip_serializing_if = "Option::is_none")] pub format: Option, diff --git a/src/db/course_note_file.rs b/src/db/course_note_file.rs index 0d73e87..cde6024 100644 --- a/src/db/course_note_file.rs +++ b/src/db/course_note_file.rs @@ -101,6 +101,31 @@ 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/lib.rs b/src/lib.rs index 2597f03..5a44be8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -58,7 +58,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 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."), (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?}`) mints the job id, writes the row, then 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)."), + (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}` (`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)."), (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 8a943b6..8ec6b88 100644 --- a/src/service/course_note_file.rs +++ b/src/service/course_note_file.rs @@ -32,6 +32,15 @@ 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/web/podcast.rs b/src/web/podcast.rs index 6a6d093..a7d8e10 100644 --- a/src/web/podcast.rs +++ b/src/web/podcast.rs @@ -32,10 +32,15 @@ //! A job nobody is updating — the service died mid-pipeline — is *presented* //! as `failed`/`interrupted` by the read path after a bounded, ETA-scaled //! window (see [`PodcastJob::projected`]): the projection writes nothing, and -//! the service's next report overwrites it. And what the backend still cannot -//! judge is stated plainly: `source_id` is the service's own handle on shared -//! media, so no backend query can say what it names — the service resolves it, -//! the backend enforces the tenant. +//! the service's next report overwrites it. +//! +//! The **source** is 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. use axum::Json; use axum::body::{Body, Bytes}; @@ -58,9 +63,11 @@ use crate::ai::podcast::{self, PodcastCancelPayload, PodcastSubmitPayload}; use crate::constant::{ AI_PODCAST_CANCEL_CAPABILITY, AI_PODCAST_SUBMIT_CAPABILITY, PODCAST_INTERRUPTED_CODE, }; +use crate::domain::course_note::CourseNoteId; use crate::domain::podcast_job::{PodcastJob, PodcastJobId}; use crate::domain::user::User; use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::service::course_note_file as note_files; use crate::service::podcast_job as jobs; use crate::state::AppState; use crate::web::tenant_state::{SchoolSlug, State}; @@ -153,7 +160,15 @@ struct CancelVerdict { /// finds the job rather than a `404`; and every dispatch outcome that is not an /// acceptance leaves the row `failed` with a reason code rather than claiming /// `queued` forever. With no worker connected the row is not written at all — -/// the `503` is the whole answer. +/// the `503` is the whole answer — and a note with no usable PDF never gets as +/// 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. #[utoipa::path( post, path = "/jobs", @@ -164,6 +179,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 = 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), ), @@ -189,11 +205,31 @@ 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}" + ))); + } + } + let job = jobs::create(&st.db, user.get_id(), source_id, req.format.as_deref()).await?; let job_id = job.get_id().key(); let payload = PodcastSubmitPayload { job_id: job_id.clone(), source_id: source_id.to_string(), + source_key, format: req.format.clone(), user_id: user.get_id().key(), }; @@ -523,6 +559,18 @@ fn worker_for(st: &AppState, capability: &str) -> Result { Ok(bridge) } +/// 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. +fn source_missing(message: &str) -> AppError { + AppError::ConflictCoded { + code: "source_missing", + message: message.to_string(), + } +} + /// A relayed failure as the response a client branches on: the service's own /// code decides the status where it is one this backend knows, and anything /// else is a `502` — the backend cannot vouch for an answer it did not diff --git a/tests/podcast.rs b/tests/podcast.rs index 2f273d4..c499648 100644 --- a/tests/podcast.rs +++ b/tests/podcast.rs @@ -292,13 +292,15 @@ async fn submit(app: &Router, cookie: &str, body: Value) -> common::Res { common::send(app, "POST", "/podcast/jobs", Some(cookie), Some(body)).await } -/// Submit one job with the standard body (asserting the `202`) and hand back -/// the backend-minted id every other door names. -async fn submit_job(app: &Router, cookie: &str) -> String { +/// 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 +/// 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( app, cookie, - json!({ "source_id": SOURCE_ID, "format": FORMAT }), + json!({ "source_id": source, "format": FORMAT }), ) .await; assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); @@ -308,6 +310,49 @@ async fn submit_job(app: &Router, cookie: &str) -> String { .to_string() } +/// The source a submit narrates, minted through the real doors: a teacher's +/// catalog course, one course note under it, and the note's PDF attachment. +/// Returns (note id, blob key) — the key is what the door hands the service as +/// `source_key`. +async fn note_with_pdf(app: &Router, db: &Database) -> (String, String) { + 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 key = upload_attachment(app, &teacher, ¬e, "recap.pdf", "application/pdf").await; + (note, key) +} + +/// One course note under `course`, created by `teacher`. +async fn create_note(app: &Router, teacher: &str, course: &str) -> String { + let res = common::send( + app, + "POST", + "/course-notes", + Some(teacher), + Some(json!({ "course": course, "title": "Bölüm 1", "content": "özet" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + common::id_of(&res.body) +} + +/// One attachment uploaded onto `note` (asserting the `201`); returns the +/// row's own id — the blob key the bytes are stored under in the school's blob +/// directory. +async fn upload_attachment( + app: &Router, + teacher: &str, + note: &str, + name: &str, + content_type: &str, +) -> String { + let res = + common::upload_course_note_file(app, teacher, note, name, content_type, b"%PDF-1.4 minimal") + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + common::id_of(&res.body) +} + /// One `GET /podcast/jobs/{id}`. async fn status_of(app: &Router, cookie: &str, id: &str) -> common::Res { common::send(app, "GET", &format!("/podcast/jobs/{id}"), Some(cookie), None).await @@ -357,14 +402,21 @@ async fn audio_of(app: &Router, cookie: &str, id: &str) -> (StatusCode, HeaderMa /// client-initiated capability frame on the connection it registered with, /// echoing the job's own identity — the backend refuses a report that /// describes a different job. -fn report_frame(job_id: &str, user_id: &str, state: &str, stage: &str, progress: f64) -> Value { +fn report_frame( + job_id: &str, + source_id: &str, + user_id: &str, + state: &str, + stage: &str, + progress: f64, +) -> Value { json!({ "id": format!("report-{state}"), "school": DEMO_SLUG, "capability": "podcast.report", "payload": { "job_id": job_id, - "source_id": SOURCE_ID, + "source_id": source_id, "format": FORMAT, "user_id": user_id, "state": state, @@ -541,11 +593,12 @@ fn episode_bytes() -> Vec { async fn a_submit_writes_the_row_and_hands_the_service_its_own_job_id() { 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 res = submit( &app, &cookie, - json!({ "source_id": SOURCE_ID, "format": FORMAT }), + json!({ "source_id": ¬e, "format": FORMAT }), ) .await; assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); @@ -564,7 +617,12 @@ async fn a_submit_writes_the_row_and_hands_the_service_its_own_job_id() { seen[0].payload["job_id"], job_id, "the service was handed the row's own id" ); - assert_eq!(seen[0].payload["source_id"], SOURCE_ID); + assert_eq!(seen[0].payload["source_id"], note); + assert_eq!( + seen[0].payload["source_key"], key, + "the note's PDF blob key rides the dispatch: {}", + seen[0].payload + ); assert_eq!(seen[0].payload["format"], FORMAT); assert_eq!(seen[0].payload["user_id"], user); @@ -576,7 +634,7 @@ async fn a_submit_writes_the_row_and_hands_the_service_its_own_job_id() { .expect("the row is on the books"); assert_eq!(state, "queued"); assert_eq!(eta, Some(ETA_SECS), "the service's estimate landed on the row"); - assert_eq!(source, SOURCE_ID); + assert_eq!(source, note, "the row records the note the job narrates"); } /// A service that accepts the job under an id of its own has answered about a @@ -593,8 +651,9 @@ async fn a_submit_that_echoes_another_job_id_is_a_bad_gateway() { let (app, db) = common::app_with_ai(Some(bridge)).await; let cookie = common::login(&app, "ali").await; let user = common::me_id(&app, &cookie).await; + let (note, _key) = note_with_pdf(&app, &db).await; - let res = submit(&app, &cookie, json!({ "source_id": SOURCE_ID })).await; + let res = submit(&app, &cookie, json!({ "source_id": note })).await; assert_eq!(res.status, StatusCode::BAD_GATEWAY, "{}", res.body); assert_eq!(res.body["error"], "bad_reply"); @@ -616,9 +675,10 @@ async fn a_submit_that_echoes_another_job_id_is_a_bad_gateway() { /// distinguish "absent" from "empty". #[tokio::test] async fn an_omitted_format_is_not_sent_at_all() { - let (service, app, cookie, _db) = podcast_app().await; + let (service, app, cookie, db) = podcast_app().await; + let (note, _key) = note_with_pdf(&app, &db).await; - let res = submit(&app, &cookie, json!({ "source_id": SOURCE_ID })).await; + let res = submit(&app, &cookie, json!({ "source_id": note })).await; assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); let seen = service.seen(); @@ -652,12 +712,13 @@ async fn a_blank_source_id_is_refused_before_anything_is_written() { async fn a_running_report_lands_on_the_row_and_the_reads_stay_off_the_service() { let (service, app, cookie, db) = podcast_app().await; let user = common::me_id(&app, &cookie).await; - let job_id = submit_job(&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, &user, "running", "tts", 0.5), + report_frame(&job_id, ¬e, &user, "running", "tts", 0.5), ) .await, &job_id, @@ -690,14 +751,15 @@ async fn a_running_report_lands_on_the_row_and_the_reads_stay_off_the_service() /// with the content type the row recorded. #[tokio::test] async fn a_finished_job_serves_the_uploaded_bytes() { - let (service, app, cookie, _db) = podcast_app().await; + let (service, app, cookie, db) = podcast_app().await; let user = common::me_id(&app, &cookie).await; - let job_id = submit_job(&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, &user, "running", "tts", 0.25), + report_frame(&job_id, ¬e, &user, "running", "tts", 0.25), ) .await, &job_id, @@ -717,7 +779,7 @@ async fn a_finished_job_serves_the_uploaded_bytes() { assert_report_stored( &capability_call( &service.conn, - report_frame(&job_id, &user, "done", "", 1.0), + report_frame(&job_id, ¬e, &user, "done", "", 1.0), ) .await, &job_id, @@ -750,7 +812,8 @@ async fn a_finished_job_serves_the_uploaded_bytes() { #[tokio::test] async fn a_cancel_of_a_live_job_stops_it() { let (service, app, cookie, db) = podcast_app().await; - let job_id = submit_job(&app, &cookie).await; + let (note, _key) = note_with_pdf(&app, &db).await; + let job_id = submit_job(&app, &cookie, ¬e).await; let res = cancel_of(&app, &cookie, &job_id).await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); @@ -777,11 +840,12 @@ async fn a_cancel_of_a_live_job_stops_it() { async fn a_cancel_of_a_terminal_job_answers_false_without_the_service() { let (service, app, cookie, db) = podcast_app().await; let user = common::me_id(&app, &cookie).await; - let job_id = submit_job(&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, &user, "failed", "", 0.0), + report_frame(&job_id, ¬e, &user, "failed", "", 0.0), ) .await, &job_id, @@ -851,8 +915,9 @@ async fn a_refusing_service_tombstones_the_row() { let (app, db) = common::app_with_ai(Some(bridge)).await; let cookie = common::login(&app, "ali").await; let user = common::me_id(&app, &cookie).await; + let (note, _key) = note_with_pdf(&app, &db).await; - let res = submit(&app, &cookie, json!({ "source_id": SOURCE_ID })).await; + let res = submit(&app, &cookie, json!({ "source_id": note })).await; assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body); assert_eq!(res.body["error"], "busy"); @@ -875,8 +940,9 @@ async fn a_refusing_service_tombstones_the_row() { /// either. #[tokio::test] async fn another_users_job_reads_as_absent() { - let (service, app, ali, _db) = podcast_app().await; - let job_id = submit_job(&app, &ali).await; + let (service, app, ali, db) = podcast_app().await; + let (note, _key) = note_with_pdf(&app, &db).await; + let job_id = submit_job(&app, &ali, ¬e).await; let seen_before = service.seen().len(); let ayse = common::login(&app, "ayse").await; @@ -949,13 +1015,14 @@ async fn a_stale_job_reads_as_interrupted_but_the_row_is_untouched() { /// instead of parsing the sentence. #[tokio::test] async fn the_result_and_audio_doors_are_not_ready_before_done() { - let (service, app, cookie, _db) = podcast_app().await; + let (service, app, cookie, db) = podcast_app().await; let user = common::me_id(&app, &cookie).await; - let job_id = submit_job(&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, &user, "running", "tts", 0.5), + report_frame(&job_id, ¬e, &user, "running", "tts", 0.5), ) .await, &job_id, @@ -984,11 +1051,12 @@ async fn the_result_and_audio_doors_are_not_ready_before_done() { async fn a_done_report_before_the_upload_is_refused() { let (service, app, cookie, db) = podcast_app().await; let user = common::me_id(&app, &cookie).await; - let job_id = submit_job(&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, &user, "running", "tts", 0.5), + report_frame(&job_id, ¬e, &user, "running", "tts", 0.5), ) .await, &job_id, @@ -996,7 +1064,7 @@ async fn a_done_report_before_the_upload_is_refused() { let answer = capability_call( &service.conn, - report_frame(&job_id, &user, "done", "", 1.0), + report_frame(&job_id, ¬e, &user, "done", "", 1.0), ) .await; assert_eq!(refusal_code(&answer), "audio_missing"); @@ -1089,6 +1157,90 @@ 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. +#[tokio::test] +async fn a_note_with_no_pdf_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; + let course = common::create_course(&app, &teacher, "Matematik").await; + let note = create_note(&app, &teacher, &course).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"); + + // 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: {:?}", + service.seen() + ); + 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. +#[tokio::test] +async fn a_pdf_whose_blob_is_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; + + let path = common::blob_dir().join(&key); + assert!(path.is_file(), "the upload wrote the blob"); + std::fs::remove_file(&path).expect("take the blob away"); + assert!(!path.exists(), "the blob really is gone"); + + let res = submit(&app, &cookie, json!({ "source_id": note })).await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + assert_eq!(res.body["code"], "source_missing"); + + assert!(service.seen().is_empty(), "nothing was dispatched"); + 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. +#[tokio::test] +async fn the_source_is_the_newest_pdf_attachment() { + 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 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_id"], note); + assert_eq!( + seen[0].payload["source_key"], corrected, + "the newest PDF, not the newest file: {}", + seen[0].payload + ); +} + /// Authentication is the whole gate on every door: no cookie is a `401`, not a /// handler — and not a dispatch under somebody else's name either. #[tokio::test]