diff --git a/README.md b/README.md index 6da6e62..acebc02 100644 --- a/README.md +++ b/README.md @@ -116,8 +116,11 @@ anyone, `null` until chosen so the client can fall back to the device preference (or, for the accent, its own default). Every account also has a **public profile** (`/users/{id}/profile`): a self-chosen `display_name` and `bio`, one **avatar**, the classes and courses -it belongs to, and counters computed at read (finished pomodoro stints, course -and class totals). Contact details are deliberately not part of it — email, +it belongs to, counters computed at read (finished pomodoro stints, course and +class totals) beside stored lifetime tallies of homework handed in, exams sat +and focus time, and the **badges** those tallies have earned — auto-earned +only, no route awards or revokes one, and permanent once earned even if the +counter later falls. Contact details are deliberately not part of it — email, phone and birth date keep the gate they already have — and any authenticated account reads any profile, except a `parent`, who reads their own and their linked students' only (see "User profiles & avatars"). @@ -334,6 +337,9 @@ response in the same commit. "themes": ["light", "dark"], "languages": ["tr", "en"], "palette_color_pattern": "^#[0-9a-fA-F]{6}$", "palette_color_len": 7, "session_duration_days": 7 }, + "badges": { "catalog": [ { "id": "homework_submitted_10", + "stat": "homework_submitted", "threshold": 10 }, + { "…": 0 } ] }, "note": { "max_title_len": 200, "max_content_len": 10000, "max_files": 10 }, "file": { "max_name_len": 255, "max_content_type_len": 100, "min_max_file_bytes": 1024, "max_max_file_bytes": 26214400, @@ -393,7 +399,7 @@ drift from it**, which is enforced rather than asked for: and fails unless each one is either referenced by `src/web/limits.rs` or listed as a deliberate exclusion *with a reason*. A new constant breaks the suite until someone decides, consciously, whether clients need it. -- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 161 published +- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 168 published bounds back out of the emitted JSON, and asserts each equals its constant. This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal only** — a `const` there does not compile — so the annotations are @@ -435,6 +441,19 @@ Notes: `stroke_kinds`, and the uploadable `image_content_types` are the exact accepted spellings — build pickers from these rather than from a literal list. +- **The badge catalog rides here too.** `badges.catalog[]` is every badge the + system can auto-award — `{id, stat, threshold}`, 13 of them, in catalog + order. It is a group (an object with one `catalog` key) rather than a bare + array because every key of this document is a group, and that uniformity is + what lets a client walk the response generically. `stat` is the API's name + for the lifetime counter behind the badge (`homework_submitted`, + `homework_on_time`, `exam_sat`, `pomodoro_finished`, `pomodoro_focus_ms`), + deliberately not the database column it is stored in, so storage can be + renamed without moving a published contract; badges sharing a `stat` form a + ladder. The catalog is compiled in, so a threshold moves only with a deploy — + the rules stay reviewable in a diff instead of editable in a settings row. + Labels and icons are **not** here: like `roles` and course `kinds`, the id is + the whole contract and the client owns what it looks like. **`422` versus `400`.** The two refusals mean different things and a client must not treat them alike. Every JSON-bodied route can answer **`422`**: the @@ -1116,8 +1135,12 @@ the school. `GET /users/me/profile` is the caller's own copy of it, "avatar": { "content_type": "image/png", "size": 20480 }, "classes": [ { "id": "01J8…", "name": "9-A", "grade": "9" } ], "courses": [ { "id": "01J8…", "title": "Matematik", "kind": "course" } ], + "badges": [ { "id": "homework_submitted_10", "earned_at": 1754300000000 } ], "stats": { "pomodoro_sessions": 42, "pomodoro_focus_ms": 63000000, - "courses": 7, "classes": 1 } + "courses": 7, "classes": 1, + "homework_submitted_total": 12, "homework_on_time_total": 11, + "exam_sat_total": 5, "pomodoro_finished_total": 44, + "pomodoro_focus_ms_total": 65400000 } } ``` @@ -1169,13 +1192,20 @@ owner's true total on purpose — it is the motivational counter, a per-reader number would be meaningless, and a magnitude names no course. One consequence, by design: a teacher you share nothing with has an empty `courses` block. -**Stats are computed at read, never stored.** No counter column can drift out -of sync with the rows behind it, and an account with no data reads a true `0` -rather than `null`. Only *finished* pomodoro stints count — a timer left -running is not study time. Exam averages, homework-done rates and attendance -rates are deliberately absent: those tables are indexed for their own reads, so -a per-user aggregate over them is a full table scan, and a profile is far too -cheap a page to pay for one. +**`stats` holds nine numbers of two different kinds, and the difference is +worth knowing.** `pomodoro_sessions`, `pomodoro_focus_ms`, `courses` and +`classes` are **computed at read**: they are recounted from the live rows on +every call, so no column can drift out of sync with what is behind it. The five +`*_total` keys are **stored lifetime tallies**, maintained at write time (see +below), so a tally can outlive the rows behind it — a student's +`exam_sat_total` still counts an exam a teacher has since deleted, which is the +point of a lifetime counter. Either kind reads a true `0` on a fresh account, +never `null`. Only *finished* pomodoro stints count on either side — a timer +left running is not study time. Exam averages, homework-done rates and +attendance rates are deliberately absent: those tables are indexed for their +own reads, so a per-user aggregate over them is a full table scan, and a +profile is far too cheap a page to pay for one — which is also why the five +lifetime counters are tallied at write rather than recounted here. **The avatar** is one picture per account, uploaded as `multipart/form-data` with the image under a `file` field. Raster types only (`image/png`, @@ -1191,9 +1221,57 @@ offensive picture is a school problem. The bytes come back from `GET /users/me/avatar` is the same read for the caller's own picture, so a client that never learned its own id still has a route. -There is no `badges` key yet. Auto-earned badges are a planned second pass and -will be added to `stats`' neighborhood additively, so a client written against -today's document keeps working. +### Badges + +**`badges` is auto-earned and nothing else.** There is no route that awards one +and none that revokes one — a badge appears when a stored counter crosses a +hardcoded threshold, normally on the same write that moved the counter (and, as +a backstop, on a profile read that finds an earned badge missing — the sync +after a write is best-effort, so a failed one heals rather than being lost). +The rule is the only author. Handing a teacher an award button would make +the counters decorative, and a badge that can be given can be argued about. + +**A badge is permanent.** Once earned it stays, whatever the counter does +afterwards: withdraw a submission and `homework_submitted_total` falls, but the +badge it earned does not come off. The award records that the student *did* the +thing, not that they still have it. `earned_at` is pinned at the first crossing +and never moved, so the list is a history and stays in order — it comes back +oldest first. + +**Ids only.** Each entry is `{id, earned_at}`. The label, the icon and the +description are the frontend's, keyed by the id — the same deal `roles` and +course `kinds` already have. The catalog behind the ids is at `GET /limits` as +`badges.catalog[]` (`{id, stat, threshold}`, 13 badges); it is compiled into +the binary, so changing a threshold is a deploy, not a settings edit. An id is +never reused for another meaning, and retiring a badge just drops it from the +catalog — awards carrying it stop being served, no migration. + +**How the counters move**, since a badge is exactly a threshold on one of them: + +- **Homework.** A genuine first hand-in is `+1 homework_submitted_total`, and + `+1 homework_on_time_total` if that hand-in beat `due_at`. **Withdrawing your + own submission decrements both** — the one place a counter comes down, and it + exists because withdrawal is student-callable: without it, submit/delete/ + submit farms one homework into fifty. Editing an existing submission moves + nothing, so the on-time verdict is fixed at the first hand-in and attaching a + file after the deadline cannot turn an on-time submission late. +- **Exams.** `+1 exam_sat_total` per attempt created, retakes included — + sitting an exam twice is two sittings. Resuming an attempt already running is + not a new one. Deleting an exam removes the attempt rows but does **not** + decrement anyone: a teacher tidying up does not un-sit the exam. +- **Pomodoro.** Finishing a stint is `+1 pomodoro_finished_total` and its + duration into `pomodoro_focus_ms_total`. An open stint counts for neither — + unfinished focus has no honest duration to add. + +**Existing accounts are seeded once.** The first boot of this version tallies +every account from its real history, so nobody starts at zero for work they +already did; the pass is marked done and skipped on every boot after. One +consequence is not fixable and is not an oversight: the seed can only count +rows that still exist, so a student whose exam was deleted before the upgrade +is seeded short on `exam_sat_total`. The live rule (never decrement) and the +seed (count what is there) simply cannot agree about history that is gone — +and the fix is not to make deletion decrement, which would break the tally for +everyone in order to patch it for a few. ## Appointments @@ -3516,6 +3594,8 @@ src/ bank_question_image.rs BankQuestionImageId · BankQuestionImage (bank question/choice picture metadata; bytes on disk under FILES_PATH) profile.rs PersonName · Email · Phone · BirthDate (personal-info newtypes) + badge.rs BadgeStat · BadgeStats · earned · BadgeAward (auto-earned, + permanent badges off the lifetime counters on the user row) preferences.rs Theme · Language · PaletteColor (own UI preferences) message.rs MessageId · MessageSubject · MessageBody · MessageLabel · Message (per-copy folders: inbox/sent/archive/trash) diff --git a/src/constant.rs b/src/constant.rs index ab942bf..4d0fe20 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -1,5 +1,6 @@ //! Validation limits, in one place. +use crate::domain::badge::BadgeStat; use crate::domain::message::Folder; use crate::domain::preferences::{Language, Theme}; use crate::domain::role::Role; @@ -798,6 +799,11 @@ pub const FEE_PLAN_ASSIGNMENT_TABLE: &str = "fee_plan_assignment"; pub const PAYMENT_LEDGER_TABLE: &str = "payment_ledger"; pub const BOARD_TABLE: &str = "board"; pub const BOARD_STROKE_TABLE: &str = "board_stroke"; +/// One row per badge a user has earned, keyed by the pair. A table of its own +/// rather than an array column on the user row: an `array<…>` there breaks +/// every `PATCH` of that row, and awards are append-only facts with their own +/// timestamp (see [`crate::domain::badge`]). +pub const BADGE_AWARD_TABLE: &str = "badge_award"; /// One row per *name* the school's settings offer, keyed by the name itself: /// how many rows still reference it, and whether it has been retired out of the /// list (see the reference counters in [`crate::domain::cap`]). @@ -850,6 +856,62 @@ pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count"; /// what closes the "open another board" way around the two board counters /// below; released when a board is deleted. pub const USER_BOARD_COUNT_FIELD: &str = "board_count"; +/// The lifetime totals behind the badges, all on the user row. Not caps: each +/// one counts something the student *did*. Only the two homework counters ever +/// come down, and in exactly one case — a student withdrawing their own +/// submission — because that route is self-service and a strictly monotonic +/// counter would let one homework be farmed into fifty by submit/delete/submit. +/// The exam and pomodoro totals never decrease at all: there is no student-facing +/// delete behind them, so sitting an exam or finishing a stint is a lifetime +/// fact. Nothing else decrements: a teacher's delete and the course cascade +/// (which do take the attempt rows with them) leave them alone, +/// since history a teacher erased is still history the student lived. A badge +/// already earned is never taken back either, whatever a counter does +/// afterwards — [`crate::domain::badge`] only ever adds award rows. Floored at +/// zero, and absent means zero: an account older than the columns reads exactly +/// like a fresh one. +pub const HOMEWORK_SUBMITTED_TOTAL_FIELD: &str = "homework_submitted_total"; +pub const HOMEWORK_ON_TIME_TOTAL_FIELD: &str = "homework_on_time_total"; +pub const EXAM_SAT_TOTAL_FIELD: &str = "exam_sat_total"; +pub const POMODORO_FINISHED_TOTAL_FIELD: &str = "pomodoro_finished_total"; +pub const POMODORO_FOCUS_MS_TOTAL_FIELD: &str = "pomodoro_focus_ms_total"; + +/// The badge catalog: every badge the system can award, as +/// `(id, the counter it reads, the value that earns it)`. Hardcoded on +/// purpose — moving a threshold is a deploy, which is what keeps +/// [`crate::domain::badge::earned`] a pure function of the stats and makes the +/// rules reviewable in a diff instead of editable in a settings row. +/// +/// The ids are the API: the frontend maps them to a label and an icon, and an +/// award row stores one forever. So an id is never reused for a different +/// meaning; retiring one is done by deleting the line, and the awards that +/// carry it simply stop being served (no data migration — +/// [`crate::domain::badge::BadgeAward::list_for`] filters to the live +/// catalog). +pub const BADGES: [(&str, BadgeStat, i64); 13] = [ + ("homework_submitted_1", BadgeStat::HomeworkSubmitted, 1), + ("homework_submitted_10", BadgeStat::HomeworkSubmitted, 10), + ("homework_submitted_50", BadgeStat::HomeworkSubmitted, 50), + ("homework_on_time_10", BadgeStat::HomeworkOnTime, 10), + ("homework_on_time_25", BadgeStat::HomeworkOnTime, 25), + ("exam_sat_1", BadgeStat::ExamSat, 1), + ("exam_sat_10", BadgeStat::ExamSat, 10), + ("exam_sat_25", BadgeStat::ExamSat, 25), + ("pomodoro_finished_10", BadgeStat::PomodoroFinished, 10), + ("pomodoro_finished_50", BadgeStat::PomodoroFinished, 50), + ("pomodoro_finished_200", BadgeStat::PomodoroFinished, 200), + // Ten and fifty hours of focus, in the milliseconds the counter stores. + ( + "pomodoro_focus_ms_36000000", + BadgeStat::PomodoroFocusMs, + 36_000_000, + ), + ( + "pomodoro_focus_ms_180000000", + BadgeStat::PomodoroFocusMs, + 180_000_000, + ), +]; /// The two stroke counters on a board row. `epoch_stroke_count` is reset to /// zero by a clear and capped at `MAX_EPOCH_STROKES` — a full epoch is /// recoverable. `total_stroke_count` is never reset and capped at diff --git a/src/database.rs b/src/database.rs index fa3e540..64cb75c 100644 --- a/src/database.rs +++ b/src/database.rs @@ -581,6 +581,183 @@ mod tests { assert_eq!(writes(&db).await, vec![2]); } + /// Stale-data path for the 2026-08-04 badge counters. Every account on an + /// existing volume predates the columns, and a badge is decided off the + /// stored total — so a zero start would not lose a number, it would + /// permanently mis-award the student who really did the work. Boot seeds the + /// counters from the rows that exist, exactly once. + #[tokio::test] + async fn the_badge_counters_are_seeded_from_history_exactly_once() { + let db = super::init_mem().await.unwrap(); + db.query( + "CREATE user:a SET username = 'a', password_hash = 'x', role = 'student'; + CREATE user:b SET username = 'b', password_hash = 'x', role = 'student'; + CREATE user:c SET username = 'c', password_hash = 'x', role = 'student'; + CREATE homework:h SET course = course:c, subject = subject:s, title = 'H', + due_at = 100, created_by = user:a, created_at = 1; + -- Three on time (the equal case counts as on time) and one whose + -- homework was deleted out from under it: that last one is + -- submitted but not on time, because the traversal yields nothing. + CREATE homework_submission:s1 SET homework = homework:h, user = user:a, + submitted_at = 50, updated_at = 50; + CREATE homework_submission:s2 SET homework = homework:h, user = user:a, + submitted_at = 60, updated_at = 100; + -- Handed in before the deadline, then edited well after it — a + -- `touch()` from a single file add does this. On time, because the + -- live path credits the hand-in and debits by `submitted_at`; if + -- the seed judged this one by `updated_at` a later withdrawal + -- would decrement a credit that was never given. + CREATE homework_submission:s3 SET homework = homework:h, user = user:a, + submitted_at = 70, updated_at = 200; + CREATE homework_submission:s4 SET homework = homework:gone, user = user:a, + submitted_at = 80, updated_at = 1; + CREATE exam_attempt:e1 SET exam = exam:x, user = user:a, seq = 1, started_at = 1; + CREATE exam_attempt:e2 SET exam = exam:y, user = user:a, seq = 1, started_at = 2; + -- Two finished stints and one still open, which counts for neither. + CREATE pomodoro_session:p1 SET user = user:a, started_at = 1000, finished_at = 2000; + CREATE pomodoro_session:p2 SET user = user:a, started_at = 5000, finished_at = 7500; + CREATE pomodoro_session:p3 SET user = user:a, started_at = 9000; + -- One real stint beside one written with a backwards clock. The + -- floor is per row, like the live close, so the negative one + -- contributes zero and the real 1000ms survives; flooring the + -- per-user sum instead would seed 0 and lose the real stint. + CREATE pomodoro_session:p4 SET user = user:c, started_at = 0, finished_at = 1000; + CREATE pomodoro_session:p5 SET user = user:c, started_at = 9000, finished_at = 3000; + DELETE migration_mark:profile_counters;", + ) + .await + .unwrap() + .check() + .unwrap(); + // `init_mem` boots a *migrated* database, so the seed is already marked + // done on an empty store — which is right, and is exactly why the mark is + // dropped here: a volume written before the columns existed carries + // history and no mark at all, and that is the state under test. + // A write probe on the table being seeded: the event fires *inside* the + // UPDATE, so it counts real writes rather than trusting a re-read. + db.query( + "DEFINE TABLE user_write_probe SCHEMALESS; + DEFINE EVENT user_write ON user WHEN $event = 'UPDATE' THEN { + UPSERT type::record('user_write_probe', 'n') SET n = (n ?? 0) + 1; + };", + ) + .await + .unwrap() + .check() + .unwrap(); + + super::migrate(&db).await.unwrap(); + + async fn counters(db: &super::Database) -> Vec<(i64, i64, i64, i64, i64)> { + let mut rows = db + .query( + "SELECT VALUE [homework_submitted_total, homework_on_time_total, + exam_sat_total, pomodoro_finished_total, + pomodoro_focus_ms_total] + FROM user ORDER BY id", + ) + .await + .unwrap(); + rows.take::>>(0) + .unwrap() + .into_iter() + .map(|row| (row[0], row[1], row[2], row[3], row[4])) + .collect() + } + let after_first = counters(&db).await; + // `a`, `b`, `c` by id. `b` has no history at all and reads as a fresh + // account; `c` keeps the 1000ms real stint the -6000ms one sits beside. + assert_eq!( + after_first, + vec![(4, 3, 2, 2, 3500), (0, 0, 0, 0, 0), (0, 0, 0, 2, 1000)], + "{after_first:?}" + ); + + // The seed also stamps each submission with the verdict it was counted + // under, because `due_at` is mutable: a withdrawal after the teacher + // moves the deadline must debit what was credited, not what the + // deadline says by then. Asserted through `WHERE` rather than read back + // as a column, so an unstamped row would show up as belonging to + // neither set instead of deserializing as some default. + async fn stamped(db: &super::Database, cond: &str) -> Vec { + let mut rows = db + .query(format!( + "SELECT VALUE record::id(id) FROM homework_submission + WHERE {cond} ORDER BY id" + )) + .await + .unwrap(); + rows.take(0).unwrap() + } + // s1/s2/s3 beat the deadline (50, 60, 70 vs 100). s4 hangs off a + // deleted homework, so `submitted_at <= homework.due_at` compares + // against NONE and lands on `false` — which is exactly what the count + // above credited it as, so the stamp agrees with the counter rather + // than leaving the row to a fallback that could later disagree. + assert_eq!( + stamped(&db, "counted_on_time = true").await, + ["s1", "s2", "s3"] + ); + assert_eq!(stamped(&db, "counted_on_time = false").await, ["s4"]); + + async fn writes(db: &super::Database) -> Vec { + let mut rows = db + .query("SELECT VALUE n FROM user_write_probe:n") + .await + .unwrap(); + rows.take(0).unwrap() + } + let first_writes = writes(&db).await; + // Pinned non-zero, not just compared: "the second pass wrote nothing" + // would hold vacuously if the probe itself stopped firing, and then the + // test would pass on a seed that never ran. + assert!( + matches!(first_writes.as_slice(), [n] if *n > 0), + "{first_writes:?}" + ); + + // The second boot: every boot runs the backfill, and a recount here + // would not converge the way the counters above it do — these columns + // are maintained by the request path from now on, so a second pass would + // overwrite everything earned since. It must not write at all… + super::migrate(&db).await.unwrap(); + assert_eq!(counters(&db).await, after_first); + assert_eq!( + writes(&db).await, + first_writes, + "the second pass wrote nothing" + ); + + // …and it must not *look*, either, which is the whole point of the mark: + // writing nothing is not the same as scanning nothing. A submission that + // lands after the mark is the probe — its counter stays where the request + // path left it, which no recomputing backfill could produce. + let mut mark = db + .query("SELECT VALUE done_at FROM migration_mark:profile_counters") + .await + .unwrap(); + assert_eq!( + mark.take::>(0).unwrap().len(), + 1, + "the seed marks itself finished" + ); + db.query( + "CREATE homework_submission:late SET homework = homework:h, user = user:b, + submitted_at = 90, updated_at = 90;", + ) + .await + .unwrap() + .check() + .unwrap(); + super::migrate(&db).await.unwrap(); + assert_eq!( + counters(&db).await, + after_first, + "a marked database skips the seed entirely" + ); + assert_eq!(writes(&db).await, first_writes); + } + #[tokio::test] async fn the_retired_claim_columns_are_dropped_off_a_live_row() { // Stale-data path for the 2026-07-30 removal of the chat claim queue. diff --git a/src/domain/badge.rs b/src/domain/badge.rs new file mode 100644 index 0000000..761d14e --- /dev/null +++ b/src/domain/badge.rs @@ -0,0 +1,498 @@ +//! Auto-earned badges: the lifetime counters a badge is decided from, the +//! catalog rule that decides it, and the award rows it writes. +//! +//! Three properties hold here and nowhere else: +//! +//! - **Auto-earned only.** No route awards a badge; [`sync`] is called after +//! the writes that move a counter, and that is the only way a row appears. +//! - **Permanent.** Nothing in this file deletes or revokes an award. A +//! counter that later drops below the threshold — a submission withdrawn, +//! say — leaves the badge standing, because it records that the student did +//! the thing, not that they still have it. +//! - **Pure rules.** The catalog is [`crate::constant::BADGES`], a hardcoded +//! table, so [`earned`] is a total function of [`BadgeStats`] with no I/O +//! and no configuration behind it. + +use surrealdb::types::SurrealValue; + +use crate::constant::{ + BADGE_AWARD_TABLE, BADGES, EXAM_SAT_TOTAL_FIELD, HOMEWORK_ON_TIME_TOTAL_FIELD, + HOMEWORK_SUBMITTED_TOTAL_FIELD, POMODORO_FINISHED_TOTAL_FIELD, POMODORO_FOCUS_MS_TOTAL_FIELD, +}; +use crate::database::Database; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// The counter a badge family reads. One variant per column, and the enum is +/// what ties a catalog line to a real number: a family added here cannot be +/// referenced from `BADGES` until [`BadgeStats`] carries its counter, because +/// both matches below are exhaustive. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BadgeStat { + HomeworkSubmitted, + HomeworkOnTime, + ExamSat, + PomodoroFinished, + PomodoroFocusMs, +} + +impl BadgeStat { + /// Where it is *stored*: the column on the user row this counter lives in. + /// Internal — every caller is a query in this crate, and renaming a column + /// means changing this and the migration together. + pub fn field(&self) -> &'static str { + match self { + BadgeStat::HomeworkSubmitted => HOMEWORK_SUBMITTED_TOTAL_FIELD, + BadgeStat::HomeworkOnTime => HOMEWORK_ON_TIME_TOTAL_FIELD, + BadgeStat::ExamSat => EXAM_SAT_TOTAL_FIELD, + BadgeStat::PomodoroFinished => POMODORO_FINISHED_TOTAL_FIELD, + BadgeStat::PomodoroFocusMs => POMODORO_FOCUS_MS_TOTAL_FIELD, + } + } + + /// What the *API* calls it: the name `GET /limits` publishes, the same + /// spelling the badge ids are built from. Deliberately not [`field`] — + /// these are two names for two audiences, and keeping them apart is what + /// lets a column be renamed without breaking a published contract. Do not + /// collapse them. + /// + /// [`field`]: BadgeStat::field + pub fn as_str(&self) -> &'static str { + match self { + BadgeStat::HomeworkSubmitted => "homework_submitted", + BadgeStat::HomeworkOnTime => "homework_on_time", + BadgeStat::ExamSat => "exam_sat", + BadgeStat::PomodoroFinished => "pomodoro_finished", + BadgeStat::PomodoroFocusMs => "pomodoro_focus_ms", + } + } +} + +/// The lifetime counters one user has accumulated, as the badge rules see +/// them. Every field is a count and never an `Option`: no rows is a true zero, +/// and an account that predates the columns reads like a fresh one. +#[derive(Debug, Clone, Default, SurrealValue)] +pub struct BadgeStats { + homework_submitted: i64, + homework_on_time: i64, + exam_sat: i64, + pomodoro_finished: i64, + pomodoro_focus_ms: i64, +} + +impl BadgeStats { + pub fn get_homework_submitted(&self) -> i64 { + self.homework_submitted + } + + pub fn get_homework_on_time(&self) -> i64 { + self.homework_on_time + } + + pub fn get_exam_sat(&self) -> i64 { + self.exam_sat + } + + pub fn get_pomodoro_finished(&self) -> i64 { + self.pomodoro_finished + } + + pub fn get_pomodoro_focus_ms(&self) -> i64 { + self.pomodoro_focus_ms + } + + /// All five counters off the user row, in one statement — a record lookup, + /// not a scan. + /// + /// Each projection is `(column ?? 0)`, parenthesized because `??` binds + /// loosely, and it is the whole stale-data story: the columns are + /// `option`, a row written before they existed carries none of them, + /// and absent must read as zero rather than as a null or an error. A user + /// row that is gone entirely reads as five zeros too — a badge sync is not + /// the place to discover a deleted account. + pub async fn load(user: &UserId, db: &Database) -> Result { + let mut result = db + .query(format!( + "SELECT ({homework_submitted} ?? 0) AS homework_submitted, + ({homework_on_time} ?? 0) AS homework_on_time, + ({exam_sat} ?? 0) AS exam_sat, + ({pomodoro_finished} ?? 0) AS pomodoro_finished, + ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms + FROM $usr", + homework_submitted = BadgeStat::HomeworkSubmitted.field(), + homework_on_time = BadgeStat::HomeworkOnTime.field(), + exam_sat = BadgeStat::ExamSat.field(), + pomodoro_finished = BadgeStat::PomodoroFinished.field(), + pomodoro_focus_ms = BadgeStat::PomodoroFocusMs.field(), + )) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result + .take::>(0)? + .into_iter() + .next() + .unwrap_or_default()) + } +} + +/// The ids of every badge `stats` has earned — the whole rule, and pure: no +/// database, no clock, no configuration. A badge is earned at `>=` its +/// threshold and stays earned, so this is only ever asked "what should be +/// held", never "what should be taken away". +pub fn earned(stats: &BadgeStats) -> Vec<&'static str> { + BADGES + .iter() + .filter(|(_, stat, threshold)| { + // Exhaustive on purpose: a new `BadgeStat` variant fails to compile + // here until the counter behind it exists on `BadgeStats`. + let value = match stat { + BadgeStat::HomeworkSubmitted => stats.homework_submitted, + BadgeStat::HomeworkOnTime => stats.homework_on_time, + BadgeStat::ExamSat => stats.exam_sat, + BadgeStat::PomodoroFinished => stats.pomodoro_finished, + BadgeStat::PomodoroFocusMs => stats.pomodoro_focus_ms, + }; + value >= *threshold + }) + .map(|(id, ..)| *id) + .collect() +} + +/// The record one (user, badge) pair always maps to, so a second [`sync`] +/// resolves onto the row the first one wrote instead of minting a duplicate. +/// A user key is a ULID (alphanumeric), so `_` cannot make two pairs collide. +fn award_key(user: &UserId, badge: &str) -> String { + format!("{}_{badge}", user.key()) +} + +/// One badge one user has earned, and when. +#[derive(Debug, Clone, SurrealValue)] +pub struct BadgeAward { + badge: String, + earned_at: Timestamp, +} + +impl BadgeAward { + pub fn get_badge(&self) -> &str { + &self.badge + } + + pub fn get_earned_at(&self) -> Timestamp { + self.earned_at + } + + /// Everything `user` has earned, oldest first. + /// + /// Filtered to the ids the catalog still holds: a badge retired from + /// `BADGES` stops being served without a data migration, and its rows stay + /// where they are in case the line comes back. + /// + /// The badge id breaks the tie, because one sync stamps every badge it + /// awards with the same millisecond and an arbitrary order there would + /// shuffle a student's shelf between reads. It is the record id's order + /// too — the key is `{user}_{badge}` and this reads one user — but spelled + /// as the projected column on purpose: SurrealDB 3.2.3 refuses to sort by + /// an idiom the selection does not carry ("Missing order idiom `id` in + /// statement selection"), and `id` is not a field of an award. + pub async fn list_for(user: &UserId, db: &Database) -> Result, AppError> { + let ids: Vec<&str> = BADGES.iter().map(|(id, ..)| *id).collect(); + let mut result = db + .query(format!( + "SELECT badge, earned_at FROM {BADGE_AWARD_TABLE} + WHERE user = $usr AND badge IN $ids + ORDER BY earned_at ASC, badge ASC LIMIT {}", + BADGES.len() + )) + .bind(("usr", user.record())) + .bind(("ids", ids)) + .await? + .check()?; + Ok(result.take::>(0)?) + } +} + +/// Write an award row for every badge `user` has now earned and does not +/// already hold. +/// +/// The `WHERE earned_at = NONE` on an `UPSERT` of the pair's own key is the +/// whole of the idempotency: the first call creates the row, and every later +/// call — with a later `$now` — matches a row that already has a stamp and +/// writes nothing at all. So the earned-at a student sees is when they first +/// crossed the line, not when the counter last moved. +/// +/// **Callers must log and ignore the error.** A badge is a decoration on top +/// of somebody's homework submission, exam sitting or pomodoro stint, and none +/// of those may fail because the decoration could not be written. The `Result` +/// is returned rather than swallowed here so the caller's log line names the +/// real cause; the next counter bump re-runs this and heals whatever was +/// missed, which is also why a lost write race needs no retry loop. +pub async fn sync(user: &UserId, db: &Database) -> Result<(), AppError> { + let stats = BadgeStats::load(user, db).await?; + let earned = earned(&stats); + if earned.is_empty() { + return Ok(()); + } + let mut sql = String::new(); + for index in 0..earned.len() { + sql.push_str(&format!( + "UPSERT type::record($table, $key{index}) SET user = $usr, badge = $badge{index}, + earned_at = $now WHERE earned_at = NONE RETURN AFTER;\n" + )); + } + let mut query = db + .query(sql) + .bind(("table", BADGE_AWARD_TABLE)) + .bind(("usr", user.record())) + .bind(("now", Timestamp::now())); + for (index, badge) in earned.iter().enumerate() { + query = query + .bind((format!("key{index}"), award_key(user, badge))) + .bind((format!("badge{index}"), badge.to_string())); + } + query.await?.check()?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The schema these rows need, which `src/migration_sql.rs` owns. Spelled + /// with the same `IF NOT EXISTS` guards the migration uses, so it is a + /// no-op once the real definitions land next to it. + async fn schema(db: &Database) { + db.query(format!( + "DEFINE FIELD IF NOT EXISTS {HOMEWORK_SUBMITTED_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {HOMEWORK_ON_TIME_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {EXAM_SAT_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {POMODORO_FINISHED_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {POMODORO_FOCUS_MS_TOTAL_FIELD} ON user TYPE option; + DEFINE TABLE IF NOT EXISTS {BADGE_AWARD_TABLE} SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS user ON {BADGE_AWARD_TABLE} TYPE record; + DEFINE FIELD IF NOT EXISTS badge ON {BADGE_AWARD_TABLE} TYPE string; + DEFINE FIELD IF NOT EXISTS earned_at ON {BADGE_AWARD_TABLE} TYPE option; + DEFINE INDEX IF NOT EXISTS badge_award_user ON {BADGE_AWARD_TABLE} FIELDS user;" + )) + .await + .unwrap() + .check() + .unwrap(); + } + + /// A user row carrying `counters`, by column name. + async fn a_user(counters: &[(&str, i64)], db: &Database) -> UserId { + let user = UserId::from_key(&ulid::Ulid::new().to_string()); + let sets: Vec = counters + .iter() + .map(|(field, value)| format!("{field} = {value}")) + .collect(); + let extra = if sets.is_empty() { + String::new() + } else { + format!(", {}", sets.join(", ")) + }; + db.query(format!( + "CREATE $usr SET username = $name, password_hash = 'x'{extra}" + )) + .bind(("usr", user.record())) + .bind(("name", user.key().to_string())) + .await + .unwrap() + .check() + .unwrap(); + user + } + + /// The stamps on the stored rows, oldest first. + async fn stamps(user: &UserId, db: &Database) -> Vec<(String, i64)> { + BadgeAward::list_for(user, db) + .await + .unwrap() + .into_iter() + .map(|award| (award.badge, award.earned_at.as_millis())) + .collect() + } + + /// The wire name and the column name are two names, not one. If a later + /// edit points `as_str` back at `field`, this fails — which is the point: + /// the split is what lets a column be renamed without breaking `/limits`. + #[test] + fn the_wire_name_is_never_the_column_name() { + for (stat, wire) in [ + (BadgeStat::HomeworkSubmitted, "homework_submitted"), + (BadgeStat::HomeworkOnTime, "homework_on_time"), + (BadgeStat::ExamSat, "exam_sat"), + (BadgeStat::PomodoroFinished, "pomodoro_finished"), + (BadgeStat::PomodoroFocusMs, "pomodoro_focus_ms"), + ] { + assert_eq!(stat.as_str(), wire, "the published name is frozen"); + assert_ne!(stat.as_str(), stat.field(), "{stat:?} collapsed the two"); + } + } + + #[tokio::test] + async fn a_row_without_the_columns_loads_as_five_zeros() { + let db = crate::database::init_mem().await.unwrap(); + schema(&db).await; + // The stale-data case: an account written before the counters existed + // carries none of them. And the harsher one — no row at all. + for user in [a_user(&[], &db).await, UserId::from_key("ghost")] { + let stats = BadgeStats::load(&user, &db).await.unwrap(); + assert_eq!(stats.get_homework_submitted(), 0); + assert_eq!(stats.get_homework_on_time(), 0); + assert_eq!(stats.get_exam_sat(), 0); + assert_eq!(stats.get_pomodoro_finished(), 0); + assert_eq!(stats.get_pomodoro_focus_ms(), 0); + assert!(earned(&stats).is_empty(), "zero earns nothing"); + } + } + + #[tokio::test] + async fn the_rule_takes_every_threshold_at_or_below_the_count() { + let stats = BadgeStats { + homework_submitted: 10, + homework_on_time: 9, + exam_sat: 0, + pomodoro_finished: 200, + pomodoro_focus_ms: 36_000_000, + }; + assert_eq!( + earned(&stats), + vec![ + // 10 clears the 1 and the 10, not the 50. + "homework_submitted_1", + "homework_submitted_10", + // 9 clears nothing; 0 exams likewise, so `exam_sat_1` is out. + "pomodoro_finished_10", + "pomodoro_finished_50", + "pomodoro_finished_200", + // Exactly at the threshold earns it. + "pomodoro_focus_ms_36000000", + ] + ); + } + + #[tokio::test] + async fn a_second_sync_does_not_move_the_stamp() { + let db = crate::database::init_mem().await.unwrap(); + schema(&db).await; + let user = a_user(&[(HOMEWORK_SUBMITTED_TOTAL_FIELD, 1)], &db).await; + + sync(&user, &db).await.unwrap(); + let first = stamps(&user, &db).await; + assert_eq!(first.len(), 1, "{first:?}"); + assert_eq!(first[0].0, "homework_submitted_1"); + + // A later sync, provably at a later millisecond: the row must keep the + // instant the badge was *first* earned, and must not be doubled. + tokio::time::sleep(std::time::Duration::from_millis(5)).await; + sync(&user, &db).await.unwrap(); + assert_eq!(stamps(&user, &db).await, first, "the stamp is frozen"); + } + + #[tokio::test] + async fn an_award_survives_a_counter_that_falls_back_below_it() { + let db = crate::database::init_mem().await.unwrap(); + schema(&db).await; + let user = a_user(&[(HOMEWORK_SUBMITTED_TOTAL_FIELD, 10)], &db).await; + sync(&user, &db).await.unwrap(); + assert_eq!( + stamps(&user, &db).await.len(), + 2, + "1 and 10 are both earned" + ); + + // The submission is withdrawn and the counter comes back down. A badge + // records that it was done, so nothing here may take it away. + db.query(format!( + "UPDATE $usr SET {HOMEWORK_SUBMITTED_TOTAL_FIELD} = 0" + )) + .bind(("usr", user.record())) + .await + .unwrap() + .check() + .unwrap(); + assert!( + earned(&BadgeStats::load(&user, &db).await.unwrap()).is_empty(), + "the rule no longer holds…" + ); + sync(&user, &db).await.unwrap(); + let kept: Vec = stamps(&user, &db) + .await + .into_iter() + .map(|(badge, _)| badge) + .collect(); + assert_eq!( + kept, + vec!["homework_submitted_1", "homework_submitted_10"], + "…and the awards stand anyway" + ); + } + + #[tokio::test] + async fn a_badge_the_catalog_dropped_is_not_served() { + let db = crate::database::init_mem().await.unwrap(); + schema(&db).await; + let user = a_user(&[(EXAM_SAT_TOTAL_FIELD, 1)], &db).await; + sync(&user, &db).await.unwrap(); + // The row a retired catalog line left behind: still stored, never + // served, and no migration deleted it. + db.query("CREATE $id SET user = $usr, badge = 'exam_sat_3', earned_at = 1") + .bind(( + "id", + surrealdb::types::RecordId::new(BADGE_AWARD_TABLE, award_key(&user, "exam_sat_3")), + )) + .bind(("usr", user.record())) + .await + .unwrap() + .check() + .unwrap(); + + let served: Vec = stamps(&user, &db) + .await + .into_iter() + .map(|(badge, _)| badge) + .collect(); + assert_eq!(served, vec!["exam_sat_1"]); + let mut rows = db + .query(format!("SELECT VALUE badge FROM {BADGE_AWARD_TABLE}")) + .await + .unwrap(); + assert_eq!(rows.take::>(0).unwrap().len(), 2, "both stored"); + } + + /// One sync stamps every badge it writes with the same millisecond, so the + /// tie-break is what makes the order stable rather than incidental. + #[tokio::test] + async fn same_millisecond_awards_come_back_in_badge_order() { + let db = crate::database::init_mem().await.unwrap(); + schema(&db).await; + let user = a_user( + &[ + (HOMEWORK_SUBMITTED_TOTAL_FIELD, 50), + (EXAM_SAT_TOTAL_FIELD, 1), + ], + &db, + ) + .await; + sync(&user, &db).await.unwrap(); + + let served = stamps(&user, &db).await; + let ids: Vec<&str> = served.iter().map(|(badge, _)| badge.as_str()).collect(); + assert_eq!( + ids, + vec![ + "exam_sat_1", + "homework_submitted_1", + "homework_submitted_10", + "homework_submitted_50" + ] + ); + assert!( + served.windows(2).all(|pair| pair[0].1 == pair[1].1), + "one sync stamps one instant: {served:?}" + ); + } +} diff --git a/src/domain/exam_attempt.rs b/src/domain/exam_attempt.rs index 0358cbd..3e05ebd 100644 --- a/src/domain/exam_attempt.rs +++ b/src/domain/exam_attempt.rs @@ -1,12 +1,12 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::EXAM_ATTEMPT_TABLE; +use crate::constant::{EXAM_ATTEMPT_TABLE, EXAM_SAT_TOTAL_FIELD}; use crate::database::{Database, transaction_with_retry}; use crate::domain::exam::Exam; use crate::domain::exam::ExamId; -use crate::domain::key; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; +use crate::domain::{badge, cap, key}; use crate::error::AppError; /// The `THROW` marker the freeze gate aborts with, and the one 409 both it and @@ -163,6 +163,11 @@ impl ExamAttempt { /// The composite id makes each create atomic; a concurrent double-start /// races on the same seq, loses to the unique id, and reads the winner's /// row. + /// + /// A created row rides [`cap::claim_and_create`] so the student's + /// `exam_sat_total` moves in the same transaction — one per sitting, + /// retakes included, which is exactly what the one-time backfill counted. + /// A lost race writes neither the row nor the increment. pub async fn start( exam: &Exam, user: &UserId, @@ -192,23 +197,45 @@ impl ExamAttempt { finished_at: None, left_at: None, }; - let created: Result, surrealdb::Error> = - db.create(attempt.id.record()).content(attempt).await; - match created { - Ok(Some(created)) => Ok((created, true)), - Ok(None) => Err(AppError::Internal("failed to start exam attempt".into())), + let id = attempt.id.record(); + match cap::claim_and_create( + &user.record(), + EXAM_SAT_TOTAL_FIELD, + cap::UNLIMITED, + &id, + &attempt, + db, + ) + .await? + { + cap::Claimed::Made(created) => { + if let Err(err) = badge::sync(user, db).await { + tracing::warn!("failed to sync badges for {}: {err}", user.key()); + } + Ok((created, true)) + } // Only a still-running row proves the loss was a double-start // collision (the winner's fresh sitting); a terminal or missing // latest means the create genuinely failed — surface that instead - // of passing a finished sitting off as a resume. - Err(err) => match Self::read_latest_for_user(exam.get_id(), user, db).await? { - Some(existing) - if existing.status(exam, Timestamp::now()) == AttemptStatus::InProgress => - { - Ok((existing, false)) + // of passing a finished sitting off as a resume. The duplicate + // aborted the transaction, so the loser's increment went with it. + cap::Claimed::Duplicate => { + match Self::read_latest_for_user(exam.get_id(), user, db).await? { + Some(existing) + if existing.status(exam, Timestamp::now()) == AttemptStatus::InProgress => + { + Ok((existing, false)) + } + _ => Err(AppError::Internal("failed to start exam attempt".into())), } - _ => Err(err.into()), - }, + } + // Nothing caps sittings, so the conditional write can only miss by + // finding no user row — not a state a live session can reach, and + // passing it off as a resume would hand out a sitting the counter + // never learned about. + cap::Claimed::Full => Err(AppError::Internal( + "cannot start an exam attempt: the student's account row is missing".into(), + )), } } @@ -519,15 +546,122 @@ mod tests { (exam, question) } - fn student() -> UserId { - UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA") + /// A real user row: the sitting counter lives on it, and the claim that + /// rides the attempt's create has nothing to write to without one. + async fn student(db: &Database) -> UserId { + let hash = crate::domain::user::Password::try_new("secret1") + .unwrap() + .hash_async() + .await + .unwrap(); + crate::domain::user::User::create( + crate::domain::user::Username::try_new("ogrenci").unwrap(), + hash, + db, + ) + .await + .unwrap() + .get_id() + .clone() + } + + /// The student's lifetime sitting count, absent reading as zero. + async fn sat_total(user: &UserId, db: &Database) -> i64 { + let mut result = db + .query(format!( + "SELECT VALUE ({EXAM_SAT_TOTAL_FIELD} ?? 0) FROM $usr" + )) + .bind(("usr", user.record())) + .await + .unwrap() + .check() + .unwrap(); + result + .take::>(0) + .unwrap() + .into_iter() + .next() + .unwrap() + } + + /// The badge counter counts *sittings*, one per created row — so a start + /// moves it by exactly one and a resume, which creates nothing, leaves it + /// alone. Anything else and a seeded account and a fresh one would mean + /// different things by the same number. + #[tokio::test] + async fn starting_counts_one_sitting_and_resuming_counts_none() { + let db = init_mem().await.unwrap(); + let (exam, _question) = open_exam_with_question(&db, 2).await; + let user = student(&db).await; + assert_eq!(sat_total(&user, &db).await, 0, "a fresh row reads as zero"); + + let (_, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); + assert!(created); + assert_eq!(sat_total(&user, &db).await, 1); + + // Still in progress: this start returns the running sitting untouched. + let (_, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); + assert!(!created); + assert_eq!( + sat_total(&user, &db).await, + 1, + "a resume writes no row, so it counts nothing" + ); + } + + /// The backfill counted every `seq`, retakes included — a second sitting + /// is a second row and moves the counter again. + #[tokio::test] + async fn a_retake_counts_as_another_sitting() { + let db = init_mem().await.unwrap(); + let (exam, _question) = open_exam_with_question(&db, 3).await; + let user = student(&db).await; + + let (first, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); + first.finish(&db).await.unwrap(); + let (second, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); + assert!(created); + assert_eq!(second.get_seq(), 2); + assert_eq!(sat_total(&user, &db).await, 2); + } + + /// The lost half of a double-start race. `start` can only reach that branch + /// by interleaving with a rival, so the claim is put to the counter + /// directly — the same call `start` makes, aimed at a row that already + /// exists. The duplicate aborts the transaction and takes its increment + /// with it: a sitting is never counted twice. + #[tokio::test] + async fn a_lost_start_race_never_counts_the_sitting_twice() { + let db = init_mem().await.unwrap(); + let (exam, _question) = open_exam_with_question(&db, 1).await; + let user = student(&db).await; + + let (winner, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); + assert_eq!(sat_total(&user, &db).await, 1); + + let claimed = cap::claim_and_create( + &user.record(), + EXAM_SAT_TOTAL_FIELD, + cap::UNLIMITED, + &winner.id.record(), + &winner, + &db, + ) + .await + .unwrap(); + assert!(matches!(claimed, cap::Claimed::Duplicate)); + assert_eq!( + sat_total(&user, &db).await, + 1, + "the loser's increment rolled back with its duplicate create" + ); } #[tokio::test] async fn a_retake_preserves_the_prior_sittings_sheet() { let db = init_mem().await.unwrap(); let (exam, question) = open_exam_with_question(&db, 2).await; - let user = student(); + let user = student(&db).await; let (first, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); assert!(created); @@ -565,7 +699,7 @@ mod tests { async fn a_lost_retake_race_cannot_touch_the_winners_sheet() { let db = init_mem().await.unwrap(); let (exam, question) = open_exam_with_question(&db, 3).await; - let user = student(); + let user = student(&db).await; // Sitting #1 ends; the winner starts sitting #2 and saves an answer. let (first, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); @@ -618,7 +752,7 @@ mod tests { async fn submitting_never_reverts_a_walk_out_that_raced_it() { let db = init_mem().await.unwrap(); let (exam, _question) = open_exam_with_question(&db, 1).await; - let user = student(); + let user = student(&db).await; let (attempt, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); @@ -661,7 +795,7 @@ mod tests { async fn stamping_left_never_reverts_a_submission() { let db = init_mem().await.unwrap(); let (exam, _question) = open_exam_with_question(&db, 1).await; - let user = student(); + let user = student(&db).await; // The student is sitting the exam. let (attempt, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); diff --git a/src/domain/exam_question.rs b/src/domain/exam_question.rs index 256871c..e9b9db2 100644 --- a/src/domain/exam_question.rs +++ b/src/domain/exam_question.rs @@ -1183,7 +1183,22 @@ mod tests { let question = a_question(&exam, &from, &db).await; assert_eq!(count_on(&from, &db).await, 1); - ExamAttempt::start(&exam, &UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA"), &db) + // A real user row: starting a sitting moves that student's badge + // counter in the same transaction, and an `UPDATE` has nothing to + // write to without one. + let hash = crate::domain::user::Password::try_new("secret1") + .unwrap() + .hash_async() + .await + .unwrap(); + let student = crate::domain::user::User::create( + crate::domain::user::Username::try_new("ogrenci").unwrap(), + hash, + &db, + ) + .await + .unwrap(); + ExamAttempt::start(&exam, student.get_id(), &db) .await .unwrap(); diff --git a/src/domain/homework_file.rs b/src/domain/homework_file.rs index 17a4803..15ea743 100644 --- a/src/domain/homework_file.rs +++ b/src/domain/homework_file.rs @@ -308,6 +308,36 @@ mod tests { use crate::domain::homework_submission::HomeworkSubmission; use crate::domain::user::UserId; + /// A real homework row (with the subject it references): `upsert` reads the + /// deadline off the entity now, so a bare id no longer does. + async fn a_homework(db: &Database) -> crate::domain::homework::Homework { + use crate::domain::course::CourseId; + use crate::domain::homework::{Homework, HomeworkTitle}; + use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; + + let course = CourseId::from_key("course"); + let subject = Subject::create( + &course, + SubjectName::try_new("topic").unwrap(), + SubjectDescription::try_new("").unwrap(), + db, + ) + .await + .unwrap(); + Homework::create( + &course, + subject.get_id(), + HomeworkTitle::try_new("essay").unwrap(), + None, + crate::domain::timestamp::Timestamp::from_millis(1), + None, + &UserId::from_key("teacher"), + db, + ) + .await + .unwrap() + } + fn a_file(submission: &HomeworkSubmissionId) -> HomeworkFile { HomeworkFile::new( submission, @@ -334,10 +364,11 @@ mod tests { #[tokio::test] async fn rows_scope_to_their_submission_gc_and_cap() { let db = crate::database::init_mem().await.unwrap(); - let homework = HomeworkId::from_key("01TESTHWAAAAAAAAAAAAAAAAAA"); + let hw = a_homework(&db).await; + let homework = hw.get_id().clone(); let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); // A real submission row, so the GC join through it resolves. - let submission = HomeworkSubmission::upsert(&homework, &user, None, &db) + let submission = HomeworkSubmission::upsert(&hw, &user, None, &db) .await .unwrap() .unwrap(); @@ -432,9 +463,10 @@ mod tests { use crate::domain::homework_result::{HomeworkResult, HomeworkStatus}; let db = crate::database::init_mem().await.unwrap(); - let homework = HomeworkId::from_key("01TESTHWAAAAAAAAAAAAAAAAAA"); + let hw = a_homework(&db).await; + let homework = hw.get_id().clone(); let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); - let submission = HomeworkSubmission::upsert(&homework, &user, None, &db) + let submission = HomeworkSubmission::upsert(&hw, &user, None, &db) .await .unwrap() .unwrap(); diff --git a/src/domain/homework_submission.rs b/src/domain/homework_submission.rs index bfd13d3..e787f86 100644 --- a/src/domain/homework_submission.rs +++ b/src/domain/homework_submission.rs @@ -15,11 +15,11 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{ - HOMEWORK_SUBMISSION_TABLE, MAX_HOMEWORK_TEXT_LEN, SUBMISSION_GRADED_FIELD, - SUBMISSION_OPEN_GUARD, + HOMEWORK_ON_TIME_TOTAL_FIELD, HOMEWORK_SUBMISSION_TABLE, HOMEWORK_SUBMITTED_TOTAL_FIELD, + MAX_HOMEWORK_TEXT_LEN, SUBMISSION_GRADED_FIELD, SUBMISSION_OPEN_GUARD, }; -use crate::database::Database; -use crate::domain::homework::HomeworkId; +use crate::database::{Database, transaction_with_retry}; +use crate::domain::homework::{Homework, HomeworkId}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -119,29 +119,80 @@ impl HomeworkSubmission { /// yet" a condition of this very write instead of a read a concurrent grade /// can land behind. An absent row satisfies it (the stamp is `NONE` there /// too), so a first submit still creates. + /// + /// The badge counters on the student's user row move in this very + /// transaction, and the order is load-bearing: the increment sits *after* + /// the UPSERT and is conditional on it having matched a row, because a + /// frozen row makes that `WHERE` match nothing **silently** (unlike + /// [`crate::domain::exam_result::ExamResult::grade`], which `THROW`s) — put + /// first, it would count a submission the freeze refused. `$before = NONE` + /// keeps it to a genuine first create, so an edit moves neither counter, + /// which is what makes the live count mean the same thing the one-time + /// backfill seeded (one per row; on time judged against `due_at`, equal + /// counting as on time). Takes the whole [`Homework`] only for that + /// deadline — both callers already hold the row. + /// + /// `counted_on_time` is stamped on the row from the *same* `$on_time` + /// expression the increment adds, in the same statement block: the deadline + /// is mutable, so a withdrawal that re-judged it against the live `due_at` + /// gave back something other than what was taken. Writing the verdict beside + /// the counter is what keeps the two from ever disagreeing — read back by + /// [`HomeworkSubmission::delete`], never re-derived. pub async fn upsert( - homework: &HomeworkId, + homework: &Homework, user: &UserId, text: Option, db: &Database, ) -> Result, AppError> { - let id = HomeworkSubmissionId::composite(homework, user); + let id = HomeworkSubmissionId::composite(homework.get_id(), user); let now = Timestamp::now(); let text = text.map(|text| text.as_str().to_string()); - let mut saved = db - .query(format!( - "UPSERT $id SET homework = $hw, user = $usr, text = $text, \ - updated_at = $now, submitted_at = submitted_at ?? $now \ - WHERE {SUBMISSION_OPEN_GUARD} RETURN AFTER" - )) - .bind(("id", id.record())) - .bind(("hw", homework.record())) - .bind(("usr", user.record())) - .bind(("text", text)) - .bind(("now", now)) - .await? - .check()?; - Ok(saved.take::>(0)?.into_iter().next()) + // Sound to re-send: the UPSERT is on a deterministic id on a table with + // no unique index, so it can never legitimately answer "already exists", + // and the counter UPDATE never can either. + let (mut saved, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + LET $before = (SELECT VALUE id FROM ONLY $id); + LET $on_time = $now <= $due; + LET $after = (UPSERT $id SET homework = $hw, user = $usr, text = $text, + updated_at = $now, submitted_at = submitted_at ?? $now + WHERE {SUBMISSION_OPEN_GUARD} RETURN AFTER); + IF $before = NONE AND array::len($after) > 0 {{ + UPDATE $id SET counted_on_time = $on_time; + UPDATE $usr SET + {HOMEWORK_SUBMITTED_TOTAL_FIELD} = ({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0) + 1, + {HOMEWORK_ON_TIME_TOTAL_FIELD} = ({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0) + + IF $on_time {{ 1 }} ELSE {{ 0 }} + }}; + RETURN $after; + COMMIT TRANSACTION;" + ), + &[ + ("id".into(), id.record().into_value()), + ("hw".into(), homework.get_id().record().into_value()), + ("usr".into(), user.record().into_value()), + ("text".into(), text.into_value()), + ("now".into(), now.into_value()), + ("due".into(), homework.get_due_at().into_value()), + ], + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The trailing `RETURN` is always the last statement before `COMMIT`, so + // its slot follows the statement count rather than a hand-kept number. + // It returns the whole array, never `$after[0]`: a refused write makes + // that `NONE`, which fails to deserialize ("expected object, got none") + // instead of reading as the "frozen" the caller answers 409 to. + let slot = saved.num_statements().saturating_sub(2); + Ok(saved + .take::>(slot)? + .into_iter() + .next()) } /// Re-stamp a submission's `updated_at` to now, leaving its text and files @@ -216,21 +267,64 @@ impl HomeworkSubmission { /// answers 409): the submission's own delete carries /// [`SUBMISSION_OPEN_GUARD`], and the file wipe is conditional on it having /// bitten, so a refused delete leaves the children standing too. + /// + /// The one place either badge counter comes back down, and deliberately the + /// only one: this route is student-callable on their own row, so without it + /// a student farms "handed in 50 homeworks" by submit/delete/submit on a + /// single homework. A teacher's homework delete and the course cascade + /// leave the counters alone — history a teacher erased is still history the + /// student lived. + /// + /// The on-time half is given back by the verdict [`HomeworkSubmission::upsert`] + /// *stored* on the row, never by re-judging the deadline: `due_at` is + /// mutable, so re-deriving read whatever the teacher had moved it to since + /// and gave back something other than what was taken — extend it after a + /// late hand-in and this debited a credit that was never given; pull it back + /// after a punctual one and it debited nothing, leaving `on_time` above + /// `submitted`. A row from before the column exists carries no verdict, and + /// cannot be given one for a credit that already happened, so it falls back + /// to the old cut (`submitted_at`, the readonly stamp the increment judged, + /// against the live deadline); a dangling `homework` link leaves `$due` + /// `NONE` there, which compares false and so counts as late, matching the + /// backfill. Floored at zero: a row that predates the columns has none. + /// + /// Badges already earned are never taken away — [`crate::domain::badge`] is + /// add-only, which is where that permanence lives. pub async fn delete(self, db: &Database) -> Result, AppError> { - let mut result = db - .query(format!( + // Sound to re-send: DELETE and UPDATE can never answer "already exists". + let (mut result, mut errors) = transaction_with_retry( + db, + &format!( "BEGIN TRANSACTION; + LET $due = (SELECT VALUE homework.due_at FROM ONLY $sub); LET $gone = (DELETE $sub WHERE {SUBMISSION_OPEN_GUARD} RETURN BEFORE); - IF array::len($gone) > 0 {{ DELETE homework_file WHERE submission = $sub }}; + IF array::len($gone) > 0 {{ + DELETE homework_file WHERE submission = $sub; + LET $on_time = IF ($gone[0].counted_on_time + ?? ($gone[0].submitted_at <= $due)) {{ 1 }} ELSE {{ 0 }}; + UPDATE $usr SET + {HOMEWORK_SUBMITTED_TOTAL_FIELD} = + math::max([({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0) - 1, 0]), + {HOMEWORK_ON_TIME_TOTAL_FIELD} = + math::max([({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0) - $on_time, 0]) + }}; RETURN $gone; COMMIT TRANSACTION;" - )) - .bind(("sub", self.id.record())) - .await? - .check()?; - // BEGIN is slot 0, the LET slot 1 and the IF slot 2; the RETURN is slot 3. + ), + &[ + ("sub".into(), self.id.record().into_value()), + ("usr".into(), self.user.record().into_value()), + ], + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The trailing `RETURN` is always the last statement before `COMMIT`. + let slot = result.num_statements().saturating_sub(2); Ok(result - .take::>(3)? + .take::>(slot)? .into_iter() .next()) } @@ -240,6 +334,81 @@ impl HomeworkSubmission { mod tests { use super::*; + use crate::domain::course::CourseId; + use crate::domain::homework::HomeworkTitle; + use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; + + /// A real homework row (and the subject it must reference) due at `due_at` — + /// `upsert` now reads the deadline off the entity, so the tests need one. + async fn a_homework(due_at: Timestamp, db: &Database) -> Homework { + let course = CourseId::from_key("course"); + let subject = Subject::create( + &course, + SubjectName::try_new("topic").unwrap(), + SubjectDescription::try_new("").unwrap(), + db, + ) + .await + .unwrap(); + Homework::create( + &course, + subject.get_id(), + HomeworkTitle::try_new("essay").unwrap(), + None, + due_at, + None, + &UserId::from_key("teacher"), + db, + ) + .await + .unwrap() + } + + /// A deadline no test run can reach, so a submission is unambiguously on + /// time; `Timestamp::from_millis(1)` is its late twin. + fn far_future() -> Timestamp { + Timestamp::from_millis(Timestamp::now().as_millis() + 3_600_000) + } + + /// A real user row: the counters live on it, and an `UPDATE` has nothing to + /// write to without one. + async fn a_student(username: &str, db: &Database) -> UserId { + let hash = crate::domain::user::Password::try_new("secret1") + .unwrap() + .hash_async() + .await + .unwrap(); + crate::domain::user::User::create( + crate::domain::user::Username::try_new(username).unwrap(), + hash, + db, + ) + .await + .unwrap() + .get_id() + .clone() + } + + /// The two badge counters on a user row, absent counting as zero. + async fn counters(user: &UserId, db: &Database) -> (i64, i64) { + let mut result = db + .query(format!( + "SELECT VALUE [({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0), + ({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0)] FROM $usr" + )) + .bind(("usr", user.record())) + .await + .unwrap() + .check() + .unwrap(); + let rows = result.take::>>(0).unwrap(); + let row = rows.first().cloned().unwrap_or_default(); + ( + row.first().copied().unwrap_or(0), + row.get(1).copied().unwrap_or(0), + ) + } + #[tokio::test] async fn text_is_optional_but_bounded() { assert!(SubmissionText::try_new("").is_ok()); @@ -250,8 +419,8 @@ mod tests { #[tokio::test] async fn resubmit_keeps_submitted_at_and_restamps_updated_at() { let db = crate::database::init_mem().await.unwrap(); - let homework = HomeworkId::generate(); - let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); + let homework = a_homework(far_future(), &db).await; + let user = a_student("ogrenci", &db).await; let first = HomeworkSubmission::upsert( &homework, @@ -268,13 +437,15 @@ mod tests { .await .unwrap() .unwrap(); + // ... and it is one submission, not two: the edit moves no counter. + assert_eq!(counters(&user, &db).await, (1, 1)); assert_eq!(first.get_id(), second.get_id()); assert_eq!(first.get_submitted_at(), second.get_submitted_at()); assert!(second.get_updated_at() >= first.get_updated_at()); assert!(second.get_text().is_none()); // One row per (homework, user), whatever the re-submit count. assert_eq!( - HomeworkSubmission::list_for_homework(&homework, &db) + HomeworkSubmission::list_for_homework(homework.get_id(), &db) .await .unwrap() .len(), @@ -294,8 +465,8 @@ mod tests { #[tokio::test] async fn a_grade_freezes_the_submission_row_itself() { let db = crate::database::init_mem().await.unwrap(); - let homework = HomeworkId::from_key("01TESTHWAAAAAAAAAAAAAAAAAA"); - let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); + let homework = a_homework(far_future(), &db).await; + let user = a_student("ogrenci", &db).await; let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); let graded = |value| { let text = SubmissionText::try_new(value).unwrap(); @@ -309,8 +480,10 @@ mod tests { .unwrap() ); + assert_eq!(counters(&user, &db).await, (1, 1)); + crate::domain::homework_result::HomeworkResult::grade( - &homework, + homework.get_id(), &user, crate::domain::homework_result::HomeworkStatus::try_new("done").unwrap(), None, @@ -329,27 +502,33 @@ mod tests { // still the version that was graded. assert!(graded("version B").await.unwrap().is_none()); assert_eq!( - HomeworkSubmission::read_for(&homework, &user, &db) + HomeworkSubmission::read_for(homework.get_id(), &user, &db) .await .unwrap() .and_then(|row| row.get_text().map(|text| text.as_str().to_string())), Some("version A".to_string()) ); + // The refusal is silent — the UPSERT simply matches nothing — so the + // counters are the only thing that can catch an increment placed in + // front of it: a submission the freeze refused must count for nothing. + assert_eq!(counters(&user, &db).await, (1, 1)); // ... and so is withdrawing it wholesale. - let frozen = HomeworkSubmission::read_for(&homework, &user, &db) + let frozen = HomeworkSubmission::read_for(homework.get_id(), &user, &db) .await .unwrap() .unwrap(); assert!(frozen.delete(&db).await.unwrap().is_none()); assert!( - HomeworkSubmission::read_for(&homework, &user, &db) + HomeworkSubmission::read_for(homework.get_id(), &user, &db) .await .unwrap() .is_some() ); + // A refused delete decrements nothing either. + assert_eq!(counters(&user, &db).await, (1, 1)); // Un-grading unfreezes it, stamp and all. - crate::domain::homework_result::HomeworkResult::remove(&homework, &user, &db) + crate::domain::homework_result::HomeworkResult::remove(homework.get_id(), &user, &db) .await .unwrap(); assert!( @@ -362,6 +541,8 @@ mod tests { reopened.get_text().map(SubmissionText::as_str), Some("version B") ); + // Still an edit to the row that was already counted, un-freeze or not. + assert_eq!(counters(&user, &db).await, (1, 1)); // The two-stamp lateness rule is untouched by any of it: the first // hand-in is still the first hand-in. assert_eq!(reopened.get_submitted_at(), version_a.get_submitted_at()); @@ -371,8 +552,8 @@ mod tests { #[tokio::test] async fn touch_moves_updated_at_but_not_submitted_at_or_text() { let db = crate::database::init_mem().await.unwrap(); - let homework = HomeworkId::generate(); - let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); + let homework = a_homework(far_future(), &db).await; + let user = a_student("ogrenci", &db).await; let original = HomeworkSubmission::upsert( &homework, @@ -395,4 +576,132 @@ mod tests { Some("photo answer") ); } + + /// The farm, closed: `delete_submission` is the student's own route, so a + /// counter that only ever went up would let one homework be handed in fifty + /// times. Submit → withdraw → submit is worth exactly one submission. + /// + /// Bite check: drop the `UPDATE $usr` from [`HomeworkSubmission::delete`] + /// and the last assertion reads `(2, 2)` — the farm. + #[tokio::test] + async fn submit_delete_submit_is_worth_one_submission() { + let db = crate::database::init_mem().await.unwrap(); + let homework = a_homework(far_future(), &db).await; + let user = a_student("ogrenci", &db).await; + + HomeworkSubmission::upsert(&homework, &user, None, &db) + .await + .unwrap() + .unwrap(); + assert_eq!(counters(&user, &db).await, (1, 1)); + + let mine = HomeworkSubmission::read_for(homework.get_id(), &user, &db) + .await + .unwrap() + .unwrap(); + mine.delete(&db).await.unwrap().unwrap(); + assert_eq!(counters(&user, &db).await, (0, 0)); + // Floored: a second withdrawal (or a row from before the columns + // existed) can never push either counter negative. + assert!( + HomeworkSubmission::read_for(homework.get_id(), &user, &db) + .await + .unwrap() + .is_none() + ); + + HomeworkSubmission::upsert(&homework, &user, None, &db) + .await + .unwrap() + .unwrap(); + assert_eq!(counters(&user, &db).await, (1, 1)); + } + + /// Lateness is judged against the homework's own deadline at hand-in, the + /// same cut the one-time backfill used, and only the on-time counter sees + /// it: a late hand-in is still a hand-in. Its withdrawal gives back only + /// what it took. + #[tokio::test] + async fn a_late_submission_counts_as_submitted_but_not_on_time() { + let db = crate::database::init_mem().await.unwrap(); + let punctual = a_homework(far_future(), &db).await; + let overdue = a_homework(Timestamp::from_millis(1), &db).await; + let user = a_student("ogrenci", &db).await; + + HomeworkSubmission::upsert(&punctual, &user, None, &db) + .await + .unwrap() + .unwrap(); + HomeworkSubmission::upsert(&overdue, &user, None, &db) + .await + .unwrap() + .unwrap(); + assert_eq!(counters(&user, &db).await, (2, 1)); + + // Withdrawing the *late* one takes back only the submission, never the + // on-time credit the punctual one earned — the zero floor would hide a + // wrong subtraction here if the on-time count were sitting at zero. + let late = HomeworkSubmission::read_for(overdue.get_id(), &user, &db) + .await + .unwrap() + .unwrap(); + late.delete(&db).await.unwrap().unwrap(); + assert_eq!(counters(&user, &db).await, (1, 1)); + + // ... and withdrawing the punctual one gives back exactly that credit. + let kept = HomeworkSubmission::read_for(punctual.get_id(), &user, &db) + .await + .unwrap() + .unwrap(); + kept.delete(&db).await.unwrap().unwrap(); + assert_eq!(counters(&user, &db).await, (0, 0)); + } + + /// A row from before `counted_on_time` existed carries no verdict — it was + /// credited by a comparison that left no trace, and cannot be given one + /// retroactively. Withdrawing it falls back to that same comparison, so the + /// pre-2026-08-04 rows on a live volume keep behaving exactly as they did. + /// + /// Bite check: an absent verdict read as `false` rather than falling through + /// (`??` binding the wrong side of the `<=`) leaves the last assertion at + /// `(0, 1)` — on time above submitted, the shape the stored verdict exists + /// to prevent. + #[tokio::test] + async fn a_row_with_no_stored_verdict_falls_back_to_the_deadline() { + let db = crate::database::init_mem().await.unwrap(); + let punctual = a_homework(far_future(), &db).await; + let overdue = a_homework(Timestamp::from_millis(1), &db).await; + let user = a_student("ogrenci", &db).await; + + HomeworkSubmission::upsert(&punctual, &user, None, &db) + .await + .unwrap() + .unwrap(); + HomeworkSubmission::upsert(&overdue, &user, None, &db) + .await + .unwrap() + .unwrap(); + assert_eq!(counters(&user, &db).await, (2, 1)); + // Aged into legacy rows: the counters keep the credit, the rows lose the + // verdict — the exact state of every submission on an existing volume. + db.query("UPDATE homework_submission UNSET counted_on_time") + .await + .unwrap() + .check() + .unwrap(); + + let late = HomeworkSubmission::read_for(overdue.get_id(), &user, &db) + .await + .unwrap() + .unwrap(); + late.delete(&db).await.unwrap().unwrap(); + assert_eq!(counters(&user, &db).await, (1, 1)); + + let kept = HomeworkSubmission::read_for(punctual.get_id(), &user, &db) + .await + .unwrap() + .unwrap(); + kept.delete(&db).await.unwrap().unwrap(); + assert_eq!(counters(&user, &db).await, (0, 0)); + } } diff --git a/src/domain/mod.rs b/src/domain/mod.rs index bf0bd56..756377d 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -6,6 +6,7 @@ pub mod answer_image; pub mod appointment; pub mod appointment_slot; pub mod attendance; +pub mod badge; pub mod bank_question; pub mod bank_question_image; pub mod board; diff --git a/src/domain/pomodoro.rs b/src/domain/pomodoro.rs index 8fe024c..223dae7 100644 --- a/src/domain/pomodoro.rs +++ b/src/domain/pomodoro.rs @@ -1,7 +1,10 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::POMODORO_SESSION_TABLE; +use crate::constant::{ + POMODORO_FINISHED_TOTAL_FIELD, POMODORO_FOCUS_MS_TOTAL_FIELD, POMODORO_SESSION_TABLE, +}; use crate::database::{Database, transaction_with_retry}; +use crate::domain::badge; use crate::domain::monotonic_id::next_ulid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -116,23 +119,41 @@ impl PomodoroSession { /// student did not cause; recording a zero-length stint keeps the session /// count honest and its duration merely understated. Nothing downstream may /// then read a negative duration (`ProfileStats::load` sums these). + /// + /// The lifetime badge counters on the user row move in this same + /// transaction, so they can never count a stint the log does not hold (nor + /// miss one it does), and a retried round re-applies nothing — the abort + /// rolled the increment back with the rest. They are written field-scoped: + /// the row also carries admin-owned data (`role`), which a whole-row save + /// would silently revert. The clamped duration is the *same* expression the + /// `CREATE` stores, so the counter can never take a negative summand and + /// nothing downstream needs a floor. Only *finished* stints reach here — an + /// open row is a `pomodoro_session` row and nothing else — and there is no + /// student-facing delete for a stint, so neither counter ever decrements. pub async fn finish(user: &UserId, db: &Database) -> Result { let (mut result, mut errors) = transaction_with_retry( db, - "BEGIN TRANSACTION; + &format!( + "BEGIN TRANSACTION; LET $before = (DELETE $open RETURN BEFORE); - IF array::len($before) = 0 { THROW 'no_pomodoro_running' }; - CREATE $closed CONTENT { + IF array::len($before) = 0 {{ THROW 'no_pomodoro_running' }}; + UPDATE $usr SET + {POMODORO_FINISHED_TOTAL_FIELD} = ({POMODORO_FINISHED_TOTAL_FIELD} ?? 0) + 1, + {POMODORO_FOCUS_MS_TOTAL_FIELD} = ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0) + + (math::max([$before[0].started_at, $done]) - $before[0].started_at); + CREATE $closed CONTENT {{ user: $before[0].user, started_at: $before[0].started_at, finished_at: math::max([$before[0].started_at, $done]), - }; - COMMIT TRANSACTION;", + }}; + COMMIT TRANSACTION;" + ), &[ ( "open".into(), PomodoroSessionId::open_for(user).record().into_value(), ), + ("usr".into(), user.record().into_value()), ( "closed".into(), PomodoroSessionId::generate().record().into_value(), @@ -154,10 +175,26 @@ impl PomodoroSession { if let Some(error) = errors.drain().map(|(_, error)| error).next() { return Err(error.into()); } - // Statement slots count BEGIN, the LET, and the IF: the CREATE is slot 3. - let saved: Option = - result.take::>(3)?.into_iter().next(); - saved.ok_or_else(|| AppError::Internal("failed to close pomodoro session".into())) + // The `CREATE` is deliberately kept the last statement before `COMMIT` + // (the counter `UPDATE` sits ahead of it — same transaction, so the + // order is free), which is what lets its slot follow the statement + // count instead of a hand-kept number: `num_statements` counts `BEGIN` + // and `COMMIT` too, hence -2. See `ExamResult::record` for the bug a + // hand-kept slot caused. + let slot = result.num_statements().saturating_sub(2); + let saved: Option = result + .take::>(slot)? + .into_iter() + .next(); + let saved = + saved.ok_or_else(|| AppError::Internal("failed to close pomodoro session".into()))?; + // A badge is a decoration on top of the stint: losing one to a + // transient database error must never fail the finish, and the next + // counter move re-runs this and heals it. + if let Err(err) = badge::sync(user, db).await { + tracing::warn!("failed to sync badges for {}: {err}", user.key()); + } + Ok(saved) } /// Every session of `user`, newest first — the running one (if any) @@ -186,6 +223,79 @@ mod tests { use super::*; use crate::database; + /// A real `user` row: the counters land with `UPDATE`, which only ever + /// touches a record that exists, so a fabricated id would silently store + /// nothing. The tests above need no row — they read only the stint log. + async fn a_user(db: &Database) -> UserId { + let user = UserId::from_key(&Ulid::new().to_string()); + db.query("CREATE $usr SET username = $name, password_hash = 'x'") + .bind(("usr", user.record())) + .bind(("name", user.key().to_string())) + .await + .unwrap() + .check() + .unwrap(); + user + } + + /// `(finished_total, focus_ms_total)` re-read from the store — never off + /// what `finish` returned, which proves nothing about what was written. + async fn counters(user: &UserId, db: &Database) -> (i64, i64) { + let mut result = db + .query(format!( + "SELECT VALUE [({POMODORO_FINISHED_TOTAL_FIELD} ?? 0), + ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0)] FROM $usr" + )) + .bind(("usr", user.record())) + .await + .unwrap() + .check() + .unwrap(); + let rows: Vec> = result.take(0).unwrap(); + let row = rows.into_iter().next().expect("the user row"); + (row[0], row[1]) + } + + #[tokio::test] + async fn finishing_bumps_the_stored_counters_and_an_open_stint_bumps_neither() { + let db = database::init_mem().await.unwrap(); + let user = a_user(&db).await; + assert_eq!(counters(&user, &db).await, (0, 0)); + + // An open stint is not a finished one: neither counter moves until it + // closes. + PomodoroSession::start(&user, &db).await.unwrap(); + assert_eq!(counters(&user, &db).await, (0, 0)); + + let mut focus_ms = 0; + for _ in 0..2 { + let closed = PomodoroSession::finish(&user, &db).await.unwrap(); + focus_ms += + closed.get_finished_at().unwrap().as_millis() - closed.get_started_at().as_millis(); + PomodoroSession::start(&user, &db).await.unwrap(); + } + // Three starts, two finishes — the third is still running. + assert_eq!(counters(&user, &db).await, (2, focus_ms)); + } + + #[tokio::test] + async fn a_backwards_clock_adds_zero_ms_to_the_counter_never_a_negative() { + let db = database::init_mem().await.unwrap(); + let user = a_user(&db).await; + + PomodoroSession::start(&user, &db).await.unwrap(); + db.query("UPDATE $open SET started_at = $future") + .bind(("open", PomodoroSessionId::open_for(&user).record())) + .bind(("future", Timestamp::now().as_millis() + 3_600_000)) + .await + .unwrap() + .check() + .unwrap(); + + PomodoroSession::finish(&user, &db).await.unwrap(); + assert_eq!(counters(&user, &db).await, (1, 0)); + } + #[tokio::test] async fn restart_replaces_the_open_session_and_finish_closes_it() { let db = database::init_mem().await.unwrap(); diff --git a/src/domain/profile.rs b/src/domain/profile.rs index d106c17..9ee003c 100644 --- a/src/domain/profile.rs +++ b/src/domain/profile.rs @@ -5,6 +5,7 @@ use surrealdb::types::SurrealValue; use crate::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN, MAX_NAME_LEN}; use crate::database::Database; +use crate::domain::badge::{BadgeStat, BadgeStats}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -143,6 +144,7 @@ pub struct ProfileStats { pomodoro_focus_ms: i64, courses: i64, classes: i64, + totals: BadgeStats, } impl ProfileStats { @@ -162,16 +164,29 @@ impl ProfileStats { self.classes } - /// One query, and only one: `courses` and `classes` arrive from the caller, - /// which already holds them as the `total` of the paged class and course - /// readers it ran for the profile's own blocks — re-counting them here - /// would be two extra reads for numbers already in hand. + /// The stored lifetime counters — the same numbers [`crate::domain::badge`] + /// decides an award from, so a profile read can check the shelf without a + /// second load of them. + pub fn get_totals(&self) -> &BadgeStats { + &self.totals + } + + /// One round trip, and only one: `courses` and `classes` arrive from the + /// caller, which already holds them as the `total` of the paged class and + /// course readers it ran for the profile's own blocks — re-counting them + /// here would be two extra reads for numbers already in hand. /// /// The pomodoro aggregate rides the per-user index, so it is a lookup and /// not a scan. `finished_at != NONE` is the filter because NONE is falsy: a /// bare truthiness test would also drop a stint that finished at epoch. An /// open stint contributes to neither the count nor the sum — unfinished /// focus has no honest duration to add. + /// + /// The lifetime counters ride along as a second statement in the *same* + /// query rather than a [`BadgeStats::load`] call, which would be a second + /// round trip for one record lookup. It repeats that projection — `?? 0` + /// per column, because the columns are `option` and a row predating + /// them carries none — so the two must move together if the shape changes. pub async fn load( user: &UserId, courses: i64, @@ -179,17 +194,35 @@ impl ProfileStats { db: &Database, ) -> Result { let mut result = db - .query( + .query(format!( "SELECT count() AS sessions, math::sum(finished_at - started_at) AS focus_ms - FROM pomodoro_session WHERE user = $usr AND finished_at != NONE GROUP ALL", - ) + FROM pomodoro_session WHERE user = $usr AND finished_at != NONE GROUP ALL; + SELECT ({homework_submitted} ?? 0) AS homework_submitted, + ({homework_on_time} ?? 0) AS homework_on_time, + ({exam_sat} ?? 0) AS exam_sat, + ({pomodoro_finished} ?? 0) AS pomodoro_finished, + ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms + FROM $usr;", + homework_submitted = BadgeStat::HomeworkSubmitted.field(), + homework_on_time = BadgeStat::HomeworkOnTime.field(), + exam_sat = BadgeStat::ExamSat.field(), + pomodoro_finished = BadgeStat::PomodoroFinished.field(), + pomodoro_focus_ms = BadgeStat::PomodoroFocusMs.field(), + )) .bind(("usr", user.record())) .await? .check()?; // `GROUP ALL` yields no row at all when nothing matched — that is the // zero case, not a missing one. let row = result.take::>(0)?.into_iter().next(); + // A vanished user row reads as five zeros, same as a fresh account. + let totals = result + .take::>(1)? + .into_iter() + .next() + .unwrap_or_default(); Ok(ProfileStats { + totals, pomodoro_sessions: row.as_ref().map_or(0, |totals| totals.sessions), // Floored at zero: a stint stamped by a wall clock that stepped // backwards mid-session sums as negative time, and "you focused for @@ -308,6 +341,38 @@ mod tests { // The passed-in counts survive untouched. assert_eq!(stats.get_courses(), 3); assert_eq!(stats.get_classes(), 1); + // No user row at all — the lifetime counters still read as zeros. + assert_eq!(stats.get_totals().get_homework_submitted(), 0); + assert_eq!(stats.get_totals().get_pomodoro_focus_ms(), 0); + } + + /// The second statement of the same query: the stored counters, straight off + /// the user row, with the columns an older row is missing read as zero. + #[tokio::test] + async fn lifetime_totals_ride_the_same_query() { + let db = crate::database::init_mem().await.unwrap(); + let user = UserId::from_key(&ulid::Ulid::new().to_string()); + db.query(format!( + "CREATE $usr SET username = $name, password_hash = 'x', + {} = 4, {} = 3", + crate::constant::HOMEWORK_SUBMITTED_TOTAL_FIELD, + crate::constant::EXAM_SAT_TOTAL_FIELD, + )) + .bind(("usr", user.record())) + .bind(("name", user.key().to_string())) + .await + .unwrap() + .check() + .unwrap(); + + let totals = ProfileStats::load(&user, 0, 0, &db).await.unwrap(); + let totals = totals.get_totals(); + assert_eq!(totals.get_homework_submitted(), 4); + assert_eq!(totals.get_exam_sat(), 3); + // Never written on this row: absent must read as 0, not as an error. + assert_eq!(totals.get_homework_on_time(), 0); + assert_eq!(totals.get_pomodoro_finished(), 0); + assert_eq!(totals.get_pomodoro_focus_ms(), 0); } #[tokio::test] diff --git a/src/lib.rs b/src/lib.rs index df487a7..14ce0dc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -44,7 +44,7 @@ use crate::state::AppState; (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/1`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With no certificate configured the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"), (name = "auth", description = "Registration, login, session lifecycle. `POST /auth/register` answers `201` whether or not the username was free, and the two bodies are byte-identical: it returns only `{username, role}` — the echoed name and the `student` role every fresh account gets — and deliberately **no `id`**, since on the taken path there is no row to name (log in to learn your id). A deliberate anti-enumeration measure, since the route is unauthenticated and a `409` would let anyone harvest the school's user list. The accepted cost is that a caller who collides gets no distinct error and simply cannot log in with that password; do not \"fix\" this back to a `409`"), (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 a claimed job rather than an in-process task: whichever backend process holds a `chat.reply` worker picks it up (within ~200ms), dispatches it and stamps the result, so a restart no longer strands an accepted turn and a claim its owner never finishes is retried after 90 seconds. 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 = "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 (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). 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`; 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` — 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), and stats computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts; `0`, never `null`). 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, and `stats.courses` stays the owner's true total either way. `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 = "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 (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). 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`; 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` — 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 nine-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 five are stored lifetime tallies maintained at write time (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total`, `pomodoro_finished_total`, `pomodoro_focus_ms_total`), so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all nine read `0`, never `null`. **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}`, 13 badges, `stat` being the API's name for the counter rather than the column it is stored in), 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, and `stats.courses` stays the owner's true total either way. `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`)"), (name = "messages", description = "One-to-one mail-style messages between any two users (parents included — messaging is the one place a parent writes), 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"), (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing — one colliding occurrence refuses the whole series. Students and parents book one with a required reason — a parent books for themselves, this is the parent-teacher conference — and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked, an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel — declining included, since a decline *is* a cancel — only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) — visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A teacher demoted after publishing leaves inert slots: they drop out of the bookable list and booking one is refused"), diff --git a/src/migration_sql.rs b/src/migration_sql.rs index 30221ef..a01b098 100644 --- a/src/migration_sql.rs +++ b/src/migration_sql.rs @@ -65,6 +65,16 @@ pub const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS avatar_size ON user TYPE option; DEFINE FIELD IF NOT EXISTS chatbot_thread_count ON user TYPE option; DEFINE FIELD IF NOT EXISTS board_count ON user TYPE option; + -- Lifetime badge counters (2026-08-04). Not caps and never released: each + -- counts something the student *did*, so a badge earned off one stands even + -- if the counter later drops. `option` and absent reads as zero, so a + -- row written before them needs no repair to be *readable* — but it does + -- need one to be *right*, which is what the BACKFILL seeding is for. + DEFINE FIELD IF NOT EXISTS homework_submitted_total ON user TYPE option; + DEFINE FIELD IF NOT EXISTS homework_on_time_total ON user TYPE option; + DEFINE FIELD IF NOT EXISTS exam_sat_total ON user TYPE option; + DEFINE FIELD IF NOT EXISTS pomodoro_finished_total ON user TYPE option; + DEFINE FIELD IF NOT EXISTS pomodoro_focus_ms_total ON user TYPE option; DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE; DEFINE TABLE IF NOT EXISTS session SCHEMAFULL; @@ -613,6 +623,18 @@ pub const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS submitted_at ON homework_submission TYPE int READONLY; DEFINE FIELD IF NOT EXISTS updated_at ON homework_submission TYPE int; DEFINE FIELD IF NOT EXISTS file_count ON homework_submission TYPE option; + -- The on-time verdict the badge counter was actually credited with, stamped + -- at the first hand-in and never re-judged. `due_at` is mutable (a teacher + -- moves a deadline with `PATCH /homework/{id}`), so re-deriving the verdict + -- at withdrawal read a *different* deadline than the credit did and gave + -- back the wrong thing in both directions — extend the deadline after a late + -- hand-in and the withdrawal debited an on-time credit that was never given; + -- pull it back after a punctual one and it debited nothing, leaving on_time + -- above submitted. `option<>` because every row predating 2026-08-04 has no + -- stored verdict and cannot be given one for a credit that already happened: + -- those fall back to the old comparison (see + -- [`crate::domain::homework_submission::HomeworkSubmission::delete`]). + DEFINE FIELD IF NOT EXISTS counted_on_time ON homework_submission TYPE option; -- The grade that froze this submission, absent while it is still open. The -- freeze used to be a cross-table read (does a homework_result exist?) -- followed by a write here, which no lock can hold across replicas; the @@ -812,6 +834,20 @@ pub const MIGRATION: &str = " DEFINE INDEX IF NOT EXISTS payment_ledger_student ON payment_ledger FIELDS student; DEFINE INDEX IF NOT EXISTS payment_ledger_source ON payment_ledger FIELDS source; + -- One row per badge a user has earned, keyed `{user}_{badge}` so the award + -- is written by an UPSERT that can never double (domain::badge). `earned_at` + -- is `option` because that is what makes the stamp write-once: the + -- UPSERT carries `WHERE earned_at = NONE`, so a re-sync of a badge already + -- held leaves the original date standing. Awards are permanent — nothing + -- deletes a row here — so the table needs no repair and no BACKFILL. + DEFINE TABLE IF NOT EXISTS badge_award SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS user ON badge_award TYPE record; + DEFINE FIELD IF NOT EXISTS badge ON badge_award TYPE string; + DEFINE FIELD IF NOT EXISTS earned_at ON badge_award TYPE option; + -- A plain field index, never `FIELDS user[*]`: the per-element form is used + -- by the planner and then returns zero rows (see the `course.teachers` note). + DEFINE INDEX IF NOT EXISTS badge_award_user ON badge_award FIELDS user; + -- Reference counters, one row per *name* the settings offer, keyed by the -- name itself (2026-07-27). They are how 'a kind nothing is graded under -- may be removed' survives a second replica: the guard used to be a @@ -1169,6 +1205,83 @@ pub const BACKFILL: &str = " }; UPSERT migration_mark:board_roster SET done_at = time::unix(time::now()) * 1000; }; + + -- The badge counters, seeded from the history that already exists + -- (2026-08-04). Badges are earned off stored lifetime totals, and every + -- account on an existing volume predates the columns — so starting them all + -- at zero would not merely lose a number, it would mis-award every student + -- permanently: someone who really handed in 40 homeworks would owe 10 *more* + -- than a new account does to reach the same badge. The counts below are the + -- rows that exist, so the seed says exactly what the student did. + -- + -- Marked one-time, like the board-roster sweep above and unlike every other + -- backfill in this file — but for the opposite reason. Those recompute a + -- number the live system does not own; these columns are maintained by the + -- request path from here on (a submission increments as it lands), so a + -- second recount would not converge, it would *overwrite* everything earned + -- since boot. The mark is the only thing that makes that safe. + -- + -- The reset is inside the mark and comes first, so the whole block is + -- recompute-from-scratch: a boot killed mid-seed writes no mark and the next + -- one redoes it from a clean slate, and an operator who clears the mark to + -- force a re-seed gets the counts as they stand rather than a stale high + -- water mark. It is the one place a *zero pass* is right: it writes over + -- whatever a half-finished pass left, and it runs exactly once per volume. + -- + -- Every counter here has to *mean* what the request path means, or a + -- pre-existing student diverges from a new one forever. So the on-time cut + -- is `submitted_at <= due_at`, the stamp both live sites use: the create + -- credits on the first hand-in and the delete debits by `submitted_at`, so + -- judging the seed by `updated_at` would let a withdrawal decrement a + -- submission the seed never credited and drive the counter *below* the + -- truth — and `touch()` moves `updated_at` on every file add or delete, so + -- merely attaching a file after the deadline would have done it. A dangling + -- `homework` link still falls out of the pass rather than counting as on + -- time (the traversal yields no value, so the comparison fails). + -- + -- The focus sum floors *per row*, like the live close does + -- (`math::max([started_at, done])`), not per user: a legacy stint written + -- with a backwards clock is negative, and flooring the total instead would + -- let one such row swallow the real stints beside it. `math::max` *around* + -- the aggregate is the spelling that is rejected ('nested aggregate + -- functions are not supported'); inside it, per row, is fine. + -- + -- Two counters the seed cannot make whole, for the same reason: + -- `exam_sat_total` (deleting an exam or a course deletes its `exam_attempt` + -- rows) and `homework_submitted_total` (deleting a homework cascades its + -- `homework_submission` rows away). Neither delete decrements — deliberate, + -- a lifetime 'did it' tally must not shrink because a teacher tidied up — so + -- the live count stands where the request path left it while a re-seed of + -- the same volume would read *lower*: the rows do not exist to be counted. + -- Do not 'repair' this by making the live path decrement; that breaks the + -- tally for everyone to patch history for a few. + -- + -- `counted_on_time` is stamped here too, for every row the pass looks at and + -- by the very same cut, so a submission that predates this seed debits at + -- withdrawal exactly what the seed credited it. Absolute like every SET + -- below, so it converges on a forced re-seed. + IF array::len((SELECT VALUE id FROM migration_mark:profile_counters)) = 0 { + UPDATE user SET homework_submitted_total = 0, homework_on_time_total = 0, + exam_sat_total = 0, pomodoro_finished_total = 0, pomodoro_focus_ms_total = 0; + FOR $row IN ((SELECT user, count() AS n FROM homework_submission GROUP BY user) ?? []) { + UPDATE $row.user SET homework_submitted_total = $row.n; + }; + FOR $row IN ((SELECT user, count() AS n FROM homework_submission + WHERE submitted_at <= homework.due_at GROUP BY user) ?? []) { + UPDATE $row.user SET homework_on_time_total = $row.n; + }; + UPDATE homework_submission SET counted_on_time = submitted_at <= homework.due_at; + FOR $row IN ((SELECT user, count() AS n FROM exam_attempt GROUP BY user) ?? []) { + UPDATE $row.user SET exam_sat_total = $row.n; + }; + FOR $row IN ((SELECT user, count() AS sessions, + math::sum(math::max([finished_at - started_at, 0])) AS focus_ms + FROM pomodoro_session WHERE finished_at != NONE GROUP BY user) ?? []) { + UPDATE $row.user SET pomodoro_finished_total = $row.sessions, + pomodoro_focus_ms_total = $row.focus_ms; + }; + UPSERT migration_mark:profile_counters SET done_at = time::unix(time::now()) * 1000; + }; "; /// The migration batches, in the order a boot applies them — and the *only* diff --git a/src/web/homework.rs b/src/web/homework.rs index 99e2a9e..1b1b4e5 100644 --- a/src/web/homework.rs +++ b/src/web/homework.rs @@ -17,6 +17,7 @@ use utoipa_axum::routes; use crate::constant::{MAX_HOMEWORK_ASSIGNED, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; use crate::database::Database; +use crate::domain::badge; use crate::domain::course::{Course, CourseId}; use crate::domain::enrollment::Enrollment; use crate::domain::exam_result::Mark; @@ -654,12 +655,17 @@ async fn submit( .await? .is_some(); let Some(submission) = - HomeworkSubmission::upsert(homework.get_id(), user.get_id(), text, &st.db).await? + HomeworkSubmission::upsert(&homework, user.get_id(), text, &st.db).await? else { return Err(AppError::Conflict( "this homework has been graded — ask the teacher to remove the grade before editing your submission", )); }; + // Only a first hand-in moved a counter, so only a first hand-in can have + // earned anything — an edit re-runs nothing. + if !existed { + award_badges(user.get_id(), &st.db).await; + } let files = HomeworkFile::list_for_submission(submission.get_id(), &st.db).await?; let status = if existed { StatusCode::OK @@ -760,12 +766,26 @@ async fn delete_submission( "this homework has been graded — ask the teacher to remove the grade before deleting your submission", )); } + // The counters just came down; a badge already earned stays earned (`sync` + // only ever adds), so this is here to keep the award rows in step with the + // *next* submission rather than to take anything back. + award_badges(user.get_id(), &st.db).await; for file in &files { remove_blob(&st.files_path, file.get_file()).await; } Ok(StatusCode::NO_CONTENT) } +/// Bring the student's badge awards up to date after a submission moved their +/// counters. Never fails the request it follows: a badge is a decoration on top +/// of the work, and losing one to a transient database error is not worth +/// refusing a hand-in over — the next counter move re-runs this and heals it. +async fn award_badges(user: &UserId, db: &Database) { + if let Err(err) = badge::sync(user, db).await { + tracing::warn!("failed to sync badges for {}: {err}", user.key()); + } +} + /// Serve a submission file as a download — `Content-Disposition: attachment`, /// never inline. Homework files take *any* content type (documents, photos — /// and so a `text/html` or `image/svg+xml` too), so, unlike the raster-only, @@ -857,9 +877,15 @@ async fn upload_submission_file( let submission = match HomeworkSubmission::read_for(homework.get_id(), user.get_id(), &st.db).await? { Some(existing) => existing, - None => HomeworkSubmission::upsert(homework.get_id(), user.get_id(), None, &st.db) - .await? - .ok_or(GRADED)?, + // A photo-only hand-in is a hand-in: it creates the row, so it moves + // the counters, so it earns badges exactly as a text submit does. + None => { + let created = HomeworkSubmission::upsert(&homework, user.get_id(), None, &st.db) + .await? + .ok_or(GRADED)?; + award_badges(user.get_id(), &st.db).await; + created + } }; // Blob first, row second — a stored row always points at a real blob. The diff --git a/src/web/limits.rs b/src/web/limits.rs index aa87ccc..d7ed80f 100644 --- a/src/web/limits.rs +++ b/src/web/limits.rs @@ -74,6 +74,36 @@ struct UserLimits { session_duration_days: i64, } +/// The auto-earned badge catalog. A group like every other key here, so a +/// client can walk this response uniformly; the catalog itself is the one +/// field inside. +#[derive(Serialize, ToSchema)] +struct BadgeLimits { + /// Every badge the system can auto-award, in catalog order. Hardcoded, so + /// like everything else here it moves only with a deploy. + catalog: Vec, +} + +/// One badge in the auto-earned catalog. The id is the whole contract: a +/// profile hands back ids and nothing else, and the label and icon behind one +/// live in the client, exactly as they do for a role or a course kind. +#[derive(Serialize, ToSchema)] +struct BadgeLimit { + /// Stable id, never reused for another meaning. A retired badge simply + /// stops appearing here. + #[schema(example = "homework_submitted_10")] + id: &'static str, + /// The lifetime counter it reads — badges sharing one form a ladder. An + /// API-side name, not the column it is stored in, so storage can be + /// renamed without moving this contract. + #[schema(example = "homework_submitted")] + stat: &'static str, + /// Counter value that earns it. Awards are permanent: a counter that later + /// falls back below this does not take the badge away. + #[schema(example = 10)] + threshold: i64, +} + /// Note bodies and their attachments. #[derive(Serialize, ToSchema)] struct NoteLimits { @@ -368,6 +398,7 @@ struct RequestLimits { #[derive(Serialize, ToSchema)] struct LimitsResponse { user: UserLimits, + badges: BadgeLimits, note: NoteLimits, file: FileLimits, message: MessageLimits, @@ -411,6 +442,16 @@ impl LimitsResponse { palette_color_len: PALETTE_COLOR_LEN, session_duration_days: SESSION_DURATION_DAYS, }, + badges: BadgeLimits { + catalog: BADGES + .iter() + .map(|(id, stat, threshold)| BadgeLimit { + id, + stat: stat.as_str(), + threshold: *threshold, + }) + .collect(), + }, note: NoteLimits { max_title_len: MAX_NOTE_TITLE_LEN, max_content_len: MAX_NOTE_CONTENT_LEN, diff --git a/src/web/users.rs b/src/web/users.rs index 27e4a70..7d265bd 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -12,6 +12,7 @@ use crate::constant::{ MAX_MAX_FILE_BYTES, MAX_PROFILE_CLASSES, MAX_PROFILE_COURSES, UPLOAD_BODY_OVERHEAD_BYTES, }; use crate::database::Database; +use crate::domain::badge::{self, BadgeAward}; use crate::domain::class_group::{ClassGroup, ClassGroupId}; use crate::domain::class_member::ClassMember; use crate::domain::course::Course; @@ -689,9 +690,26 @@ struct ProfileResponse { /// block, the owner and manager+ see it whole. The full list is at /// `GET /courses/me`. courses: Vec, + /// Every badge this account has earned, oldest first. Ids and stamps only — + /// the label and the icon are the client's, keyed by id off the `badges` + /// catalog at `GET /limits`. + badges: Vec, stats: ProfileStatsResponse, } +/// One earned badge. Permanent: once it appears here it never leaves, even if +/// the counter behind it falls back below the threshold that earned it. +#[derive(Serialize, ToSchema)] +struct ProfileBadge { + /// A catalog id from `GET /limits` — `badges.catalog[].id`. + #[schema(example = "pomodoro_finished_10")] + id: String, + /// When it was *first* earned, UTC unix-milliseconds. Later syncs never + /// move it. + #[schema(example = 1_759_000_000_000_i64)] + earned_at: i64, +} + /// What a stored avatar is, without its bytes. #[derive(Serialize, ToSchema)] struct ProfileAvatar { @@ -729,6 +747,14 @@ struct ProfileCourseRef { /// The motivational counters. Derived, never settable, and never `null`: an /// account with no rows behind a counter reads a true `0`. +/// +/// Two kinds live here. The first four are **computed at read time** from the +/// rows that exist right now, so deleting the rows moves them down. The five +/// `*_total` ones are **stored lifetime counters**, incremented as the work +/// happens and never recomputed — they can therefore outlive the rows behind +/// them (an exam deleted by its teacher still counts as sat), which is exactly +/// why a badge earned off them stays earned. Each is named for a `stat` of the +/// badge catalog at `GET /limits`, plus `_total`. #[derive(Serialize, ToSchema)] struct ProfileStatsResponse { /// Finished pomodoro stints; an open one counts for nothing. @@ -739,6 +765,18 @@ struct ProfileStatsResponse { courses: i64, /// Every class behind the `classes` block, not just the embedded window. classes: i64, + /// Lifetime homework hand-ins. Withdrawing a submission gives one back; + /// editing one moves nothing. + homework_submitted_total: i64, + /// Lifetime hand-ins made before their deadline, judged at hand-in. + homework_on_time_total: i64, + /// Lifetime exam sittings, counted once per attempt — retakes included, and + /// deleting the exam does not take them back. + exam_sat_total: i64, + /// Lifetime finished pomodoro stints. + pomodoro_finished_total: i64, + /// Lifetime focused milliseconds. + pomodoro_focus_ms_total: i64, } /// Build one profile as `viewer` may see it. The course block is chosen off the @@ -796,6 +834,7 @@ async fn profile_of( // Both totals are the full counts, not the windowed ones — the blocks are a // preview, the stats are the truth. let stats = ProfileStats::load(id, course_total, class_total, &st.db).await?; + let badges = badges_of(st, id, &stats).await?; Ok(ProfileResponse { id: id.key().to_string(), username: user.get_username().as_str().to_string(), @@ -828,15 +867,61 @@ async fn profile_of( kind: course.get_kind().as_str().to_string(), }) .collect(), + badges: badges + .iter() + .map(|award| ProfileBadge { + id: award.get_badge().to_string(), + earned_at: award.get_earned_at().as_millis(), + }) + .collect(), stats: ProfileStatsResponse { pomodoro_sessions: stats.get_pomodoro_sessions(), pomodoro_focus_ms: stats.get_pomodoro_focus_ms(), courses: stats.get_courses(), classes: stats.get_classes(), + homework_submitted_total: stats.get_totals().get_homework_submitted(), + homework_on_time_total: stats.get_totals().get_homework_on_time(), + exam_sat_total: stats.get_totals().get_exam_sat(), + pomodoro_finished_total: stats.get_totals().get_pomodoro_finished(), + pomodoro_focus_ms_total: stats.get_totals().get_pomodoro_focus_ms(), }, }) } +/// The owner's earned badges, and the backstop that keeps them honest. +/// +/// Every write that moves a counter syncs the badges behind it, so in the +/// steady state the earned set holds nothing the award rows do not already +/// carry and this is one read and **no write at all**. Only a threshold crossed +/// by a path whose sync was lost — a transient database error, which those +/// callers log and swallow on purpose — leaves a gap, and that heals here on +/// the next profile read of that account. +/// +/// Nothing here revokes: [`badge::sync`] only ever adds, so a counter that has +/// since fallen back below its threshold leaves the badge standing. The sync's +/// own error is logged and dropped, and the awards already read are served — +/// a decoration may not fail the profile it decorates. +async fn badges_of( + st: &AppState, + user: &UserId, + stats: &ProfileStats, +) -> Result, AppError> { + let awards = BadgeAward::list_for(user, &st.db).await?; + let complete = badge::earned(stats.get_totals()) + .iter() + .all(|id| awards.iter().any(|award| award.get_badge() == *id)); + if complete { + return Ok(awards); + } + if let Err(err) = badge::sync(user, &st.db).await { + tracing::warn!("failed to sync badges for {}: {err}", user.key()); + return Ok(awards); + } + // Re-read so the badge just healed appears on *this* response, stamp and + // all, rather than only on the next one. + BadgeAward::list_for(user, &st.db).await +} + /// The profile gate: any authenticated account reads any profile — except a /// parent, who is an observer of their own children and of nobody else. The /// link alone is not the grant either; [`ensure_can_observe`] re-reads the @@ -878,7 +963,9 @@ async fn my_profile( } /// One user's public profile: display name, bio, avatar meta, their class and -/// course blocks, and the motivational counters. Readable by every +/// course blocks, the badges they have earned, and the motivational counters. +/// Badges carry an id and the instant they were first earned; their labels and +/// icons come from the `badges` catalog at `GET /limits`. Readable by every /// authenticated account — except a parent, who reads only their own and their /// linked students'. Never carries email, phone, or birth date; those stay on /// `GET /users/{id}` (admin) and `GET /auth/me`. The embedded blocks are capped diff --git a/tests/regress_profile.rs b/tests/regress_profile.rs index 42abff0..5cdbfc1 100644 --- a/tests/regress_profile.rs +++ b/tests/regress_profile.rs @@ -12,8 +12,13 @@ mod common; use axum::Router; use axum::http::StatusCode; -use common::{app_and_db, create_course, enroll, login, login_as, me_id, send, set_role}; +use common::{ + app_and_db, create_course, create_exam_with, create_homework, create_subject, enroll, id_of, + login, login_as, me_id, send, set_role, +}; use hezarfen_backend::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN}; +use hezarfen_backend::database::Database; +use hezarfen_backend::domain::timestamp::Timestamp; use serde_json::{Value, json}; const BOUNDARY: &str = "multipart/form-data; boundary=hezarfen-test-boundary"; @@ -102,13 +107,16 @@ async fn a_peer_profile_carries_no_contact_fields() { let seen = profile(&app, &peer, &ada_id).await; assert_eq!(seen.status, StatusCode::OK, "{}", seen.body); assert_eq!(seen.body["username"], "ada"); - for private in ["email", "phone", "birth_date", "badges"] { + for private in ["email", "phone", "birth_date"] { assert!( seen.body.get(private).is_none(), "{private} must not ride on a profile: {}", seen.body ); } + // Badges are public, unlike the contact fields — and an account that has + // earned none says so with an empty list, never with a missing key. + assert_eq!(seen.body["badges"], json!([]), "{}", seen.body); } /// A parent is an observer of their own children and of nobody else: the @@ -238,6 +246,75 @@ async fn display_name_falls_back_to_the_legal_name_then_null() { ); } +/// The read-time badge backstop, and the write it must not make. +/// +/// A counter is moved behind the API's back — exactly what a lost `badge::sync` +/// leaves behind, since every counter writer logs and swallows that error. The +/// first profile read must heal it and serve the badges with their stamps; the +/// second must serve the identical shelf and write *nothing*, which is what the +/// `badge_award` write probe counts. Zero extra writes on a read is the whole +/// point: a profile is a read endpoint. +#[tokio::test] +async fn a_profile_read_heals_a_missed_badge_then_writes_nothing() { + let (app, db) = app_and_db().await; + let ada = login(&app, "ada").await; + let ada_id = me_id(&app, &ada).await; + + // Fires inside any write to the award table, so a write this read should + // not make cannot hide behind an unchanged-looking response. + db.query( + "DEFINE EVENT award_write ON badge_award WHEN true THEN { + UPSERT type::record('award_write_probe', 'n') SET n = (n ?? 0) + 1; + };", + ) + .await + .unwrap() + .check() + .unwrap(); + let writes = || async { + db.query("SELECT VALUE n FROM award_write_probe:n") + .await + .unwrap() + .take::>(0) + .unwrap() + .first() + .copied() + .unwrap_or(0) + }; + + db.query("UPDATE type::record('user', $id) SET homework_submitted_total = 10") + .bind(("id", ada_id.clone())) + .await + .unwrap() + .check() + .unwrap(); + + let healed = profile(&app, &ada, &ada_id).await; + assert_eq!(healed.status, StatusCode::OK, "{}", healed.body); + let ids: Vec<&str> = healed.body["badges"] + .as_array() + .expect("badges array") + .iter() + .map(|badge| badge["id"].as_str().expect("badge id")) + .collect(); + assert_eq!(ids, vec!["homework_submitted_1", "homework_submitted_10"]); + assert!( + healed.body["badges"][0]["earned_at"].as_i64().unwrap_or(0) > 0, + "a badge carries when it was earned: {}", + healed.body + ); + assert_eq!(healed.body["stats"]["homework_submitted_total"], 10); + let after_heal = writes().await; + assert!(after_heal > 0, "the heal wrote the awards"); + + // Steady state: everything earned is already held, so this read must not + // touch the award table at all. + let again = profile(&app, &ada, &ada_id).await; + assert_eq!(again.status, StatusCode::OK, "{}", again.body); + assert_eq!(again.body["badges"], healed.body["badges"], "same shelf"); + assert_eq!(writes().await, after_heal, "a profile read wrote something"); +} + /// The counters are derived, so a fresh account reads a true `0` on all four — /// never `null`, never an absent key a client would have to guard. #[tokio::test] @@ -253,6 +330,13 @@ async fn fresh_stats_read_zero_on_every_field() { "pomodoro_focus_ms", "courses", "classes", + // The stored lifetime counters: a row that predates the columns carries + // none of them, and absent must still read as a numeric 0. + "homework_submitted_total", + "homework_on_time_total", + "exam_sat_total", + "pomodoro_finished_total", + "pomodoro_focus_ms_total", ] { assert_eq!( stats.get(field).and_then(Value::as_i64), @@ -261,7 +345,7 @@ async fn fresh_stats_read_zero_on_every_field() { stats.get(field) ); } - assert_eq!(stats.len(), 4, "no fifth counter shipped: {stats:?}"); + assert_eq!(stats.len(), 9, "no tenth counter shipped: {stats:?}"); assert!(mine.body["avatar"].is_null()); assert_eq!(mine.body["classes"], json!([])); assert_eq!(mine.body["courses"], json!([])); @@ -685,6 +769,472 @@ async fn stats_courses_stays_the_owners_true_total() { assert_eq!(peer.body["stats"]["courses"], 2); } +// --- Badges --------------------------------------------------------------- +// +// Badges are *permanent*: an award row is stamped once and nothing ever moves +// or removes it, while the counters underneath it move both ways. Every test +// below is written against that split — the award, not the counter, is what +// carries the promise — and the counter tests read off the profile rather than +// the database, because the profile is the only surface a client has. + +/// A course with a subject and one enrolled student: the smallest cast that +/// can move a homework counter. +struct Classroom { + app: Router, + db: Database, + teacher: String, + student: String, + student_id: String, + course: String, + subject: String, +} + +async fn classroom() -> Classroom { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teach", "teacher").await; + let student = login(&app, "stu").await; + let student_id = me_id(&app, &student).await; + let course = create_course(&app, &teacher, "Algebra").await; + enroll(&app, &teacher, &course, &student_id).await; + let subject = create_subject(&app, &teacher, &course, "Fractions").await; + Classroom { + app, + db, + teacher, + student, + student_id, + course, + subject, + } +} + +/// A homework due `in_ms` from now. Negative backdates it *inside* the +/// scheduling grace — the only way to hand something in late in one test. +async fn homework(c: &Classroom, title: &str, in_ms: i64) -> String { + let due = Timestamp::now().as_millis() + in_ms; + create_homework(&c.app, &c.teacher, &c.course, &c.subject, title, due).await +} + +/// Move `homework`'s deadline to `in_ms` from now, as the teacher who set it. +/// Negative backdates it *inside* the scheduling grace, which is legal — the +/// deadline is mutable in both directions, which is what the two tests below +/// are about. +async fn move_deadline(c: &Classroom, homework: &str, in_ms: i64) { + let due = Timestamp::now().as_millis() + in_ms; + let res = send( + &c.app, + "PATCH", + &format!("/homework/{homework}"), + Some(&c.teacher), + Some(json!({ "due_at": due })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); +} + +/// Hand in `homework` as `cookie`, asserting the first-hand-in `201`. +async fn hand_in(app: &Router, cookie: &str, homework: &str) { + let res = send( + app, + "POST", + &format!("/homework/{homework}/submission"), + Some(cookie), + Some(json!({ "text": "done" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); +} + +/// Withdraw the caller's own submission, asserting the `204`. +async fn withdraw(app: &Router, cookie: &str, homework: &str) { + let res = send( + app, + "DELETE", + &format!("/homework/{homework}/submission"), + Some(cookie), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); +} + +/// The caller's own profile body (asserts the `200`). +async fn my_profile(app: &Router, cookie: &str) -> Value { + let res = send(app, "GET", "/users/me/profile", Some(cookie), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + res.body +} + +/// When `id` was earned, off a profile body — `None` if the shelf lacks it. +fn stamp_of(profile: &Value, id: &str) -> Option { + profile["badges"] + .as_array() + .expect("badges array") + .iter() + .find(|badge| badge["id"] == id) + .map(|badge| badge["earned_at"].as_i64().expect("earned_at millis")) +} + +/// The badge ids on a profile, in the order served. +fn badge_ids(profile: &Value) -> Vec<&str> { + profile["badges"] + .as_array() + .expect("badges array") + .iter() + .map(|badge| badge["id"].as_str().expect("badge id")) + .collect() +} + +/// Crossing a threshold earns the badge there and then, stamped with the +/// moment it happened — not at some later sweep. The window is taken around +/// the request, so a stamp copied from anywhere else fails. +#[tokio::test] +async fn a_badge_lands_the_moment_its_threshold_is_crossed() { + let c = classroom().await; + let first = homework(&c, "Fractions I", 600_000).await; + + let before = my_profile(&c.app, &c.student).await; + assert_eq!(badge_ids(&before), Vec::<&str>::new(), "nothing earned yet"); + + let opened = Timestamp::now().as_millis(); + hand_in(&c.app, &c.student, &first).await; + let closed = Timestamp::now().as_millis(); + + let mine = my_profile(&c.app, &c.student).await; + assert_eq!(badge_ids(&mine), ["homework_submitted_1"], "{mine}"); + let earned = stamp_of(&mine, "homework_submitted_1").expect("the badge"); + assert!( + (opened..=closed).contains(&earned), + "earned_at {earned} is outside the request window {opened}..={closed}: {mine}" + ); + // One hand-in is one submission, and the ten-badge is nine away. + assert_eq!(mine["stats"]["homework_submitted_total"], 1); + assert_eq!(mine["stats"]["homework_on_time_total"], 1); +} + +/// The permanence guarantee, at the stamp: crossing again re-runs the sync, +/// and the sync's `WHERE earned_at = NONE` must leave the original stamp +/// standing. The clock is given room to move between the two hand-ins, so a +/// sync that *did* overwrite would write a demonstrably later value. +#[tokio::test] +async fn a_second_crossing_never_moves_the_stamp() { + let c = classroom().await; + let first = homework(&c, "Fractions I", 600_000).await; + let second = homework(&c, "Fractions II", 600_000).await; + + hand_in(&c.app, &c.student, &first).await; + let earned = stamp_of( + &my_profile(&c.app, &c.student).await, + "homework_submitted_1", + ) + .expect("the badge"); + + // Any overwrite from here on is strictly later than this instant. + tokio::time::sleep(std::time::Duration::from_millis(5)).await; + let moved_on = Timestamp::now().as_millis(); + assert!(earned < moved_on, "the clock never moved — test is vacuous"); + + hand_in(&c.app, &c.student, &second).await; + let after = my_profile(&c.app, &c.student).await; + assert_eq!(after["stats"]["homework_submitted_total"], 2, "{after}"); + assert_eq!( + stamp_of(&after, "homework_submitted_1"), + Some(earned), + "a re-sync moved a permanent stamp: {after}" + ); +} + +/// The whole point of an award row: permanence lives at the award, not at the +/// counter. Withdrawing the submission takes the counter back to zero — and +/// the badge it earned stays on the shelf, stamp untouched. +#[tokio::test] +async fn a_badge_outlives_the_counter_that_earned_it() { + let c = classroom().await; + let only = homework(&c, "Fractions I", 600_000).await; + + hand_in(&c.app, &c.student, &only).await; + let earned_it = my_profile(&c.app, &c.student).await; + let earned = stamp_of(&earned_it, "homework_submitted_1").expect("the badge"); + assert_eq!(earned_it["stats"]["homework_submitted_total"], 1); + + withdraw(&c.app, &c.student, &only).await; + + let after = my_profile(&c.app, &c.student).await; + assert_eq!( + after["stats"]["homework_submitted_total"], 0, + "the counter must come back down: {after}" + ); + assert_eq!(after["stats"]["homework_on_time_total"], 0, "{after}"); + assert_eq!( + stamp_of(&after, "homework_submitted_1"), + Some(earned), + "a badge is never taken back: {after}" + ); +} + +/// The farm hole, closed at the counter: withdrawing gives the credit back, so +/// submit → withdraw → submit is worth exactly one submission however many +/// times it is run. Without the decrement, one homework mints unlimited ones. +#[tokio::test] +async fn submit_withdraw_submit_is_worth_one_submission() { + let c = classroom().await; + let only = homework(&c, "Fractions I", 600_000).await; + + for _ in 0..3 { + hand_in(&c.app, &c.student, &only).await; + withdraw(&c.app, &c.student, &only).await; + } + hand_in(&c.app, &c.student, &only).await; + + let mine = my_profile(&c.app, &c.student).await; + assert_eq!( + mine["stats"]["homework_submitted_total"], 1, + "one homework handed in once, whatever the churn: {mine}" + ); + assert_eq!(mine["stats"]["homework_on_time_total"], 1, "{mine}"); +} + +/// The two homework counters part company at the deadline: everything handed +/// in counts as submitted, only what beat `due_at` counts as on time. The +/// on-time hand-in in the same test is what proves the counter still moves at +/// all, so a permanently-stuck `on_time` cannot pass as "the late one". +#[tokio::test] +async fn a_late_submission_moves_submitted_but_not_on_time() { + let c = classroom().await; + // Backdated inside the scheduling grace: already due, still creatable. + let overdue = homework(&c, "Yesterday's", -30_000).await; + let punctual = homework(&c, "Next week's", 600_000).await; + + hand_in(&c.app, &c.student, &overdue).await; + let late = my_profile(&c.app, &c.student).await; + assert_eq!(late["stats"]["homework_submitted_total"], 1, "{late}"); + assert_eq!( + late["stats"]["homework_on_time_total"], 0, + "a submission past due_at earns no on-time credit: {late}" + ); + + hand_in(&c.app, &c.student, &punctual).await; + let both = my_profile(&c.app, &c.student).await; + assert_eq!(both["stats"]["homework_submitted_total"], 2, "{both}"); + assert_eq!(both["stats"]["homework_on_time_total"], 1, "{both}"); +} + +/// A withdrawal gives back what the hand-in was credited with, not what the +/// deadline says *now*: a teacher who extends `due_at` after a late hand-in has +/// not made it on time retroactively. Re-judging at withdrawal debited an +/// on-time credit that was never given, and the zero floor hid it — so a +/// genuinely on-time submission is held throughout, and it is that one's credit +/// the late withdrawal used to eat. +#[tokio::test] +async fn extending_a_deadline_never_debits_an_on_time_credit_it_never_gave() { + let c = classroom().await; + let punctual = homework(&c, "Next week's", 600_000).await; + // Backdated inside the scheduling grace: already due, still creatable. + let overdue = homework(&c, "Yesterday's", -30_000).await; + + hand_in(&c.app, &c.student, &punctual).await; + hand_in(&c.app, &c.student, &overdue).await; + let both = my_profile(&c.app, &c.student).await; + assert_eq!(both["stats"]["homework_submitted_total"], 2, "{both}"); + assert_eq!(both["stats"]["homework_on_time_total"], 1, "{both}"); + + // The teacher relents and moves the deadline out. The hand-in that was late + // when it landed was still late when it landed. + move_deadline(&c, &overdue, 600_000).await; + let moved = my_profile(&c.app, &c.student).await; + assert_eq!(moved["stats"]["homework_on_time_total"], 1, "{moved}"); + + withdraw(&c.app, &c.student, &overdue).await; + let after = my_profile(&c.app, &c.student).await; + assert_eq!(after["stats"]["homework_submitted_total"], 1, "{after}"); + assert_eq!( + after["stats"]["homework_on_time_total"], 1, + "withdrawing the late one took the punctual one's credit: {after}" + ); + + // ... and the punctual one still has exactly its own credit to give back. + withdraw(&c.app, &c.student, &punctual).await; + let empty = my_profile(&c.app, &c.student).await; + assert_eq!(empty["stats"]["homework_submitted_total"], 0, "{empty}"); + assert_eq!(empty["stats"]["homework_on_time_total"], 0, "{empty}"); +} + +/// The other direction, where the floor cannot hide it: pulling `due_at` back +/// after a punctual hand-in used to make the withdrawal debit *nothing* on +/// time, leaving `on_time` standing above `submitted` — a student credited with +/// more punctual hand-ins than hand-ins. The invariant is checked at every step, +/// not just at the end. +#[tokio::test] +async fn pulling_a_deadline_back_leaves_on_time_no_higher_than_submitted() { + let c = classroom().await; + let only = homework(&c, "Next week's", 600_000).await; + + let counted = |profile: &Value| -> (i64, i64) { + let submitted = profile["stats"]["homework_submitted_total"] + .as_i64() + .unwrap_or_else(|| panic!("submitted total: {profile}")); + let on_time = profile["stats"]["homework_on_time_total"] + .as_i64() + .unwrap_or_else(|| panic!("on-time total: {profile}")); + assert!( + on_time <= submitted, + "on_time {on_time} exceeds submitted {submitted}: {profile}" + ); + (submitted, on_time) + }; + + hand_in(&c.app, &c.student, &only).await; + assert_eq!(counted(&my_profile(&c.app, &c.student).await), (1, 1)); + + // Backdating inside the grace is a legal PATCH, and it moves the very cut + // the credit was judged by. + move_deadline(&c, &only, -30_000).await; + assert_eq!( + counted(&my_profile(&c.app, &c.student).await), + (1, 1), + "moving a deadline re-judges nothing already credited" + ); + + withdraw(&c.app, &c.student, &only).await; + assert_eq!( + counted(&my_profile(&c.app, &c.student).await), + (0, 0), + "the withdrawal gave back the on-time credit it took" + ); +} + +/// `exam_sat_total` counts sittings, not requests: re-posting a running +/// attempt resumes it (`200`, same clock) and must leave the counter alone. +#[tokio::test] +async fn a_resumed_exam_attempt_counts_once() { + let c = classroom().await; + let now = Timestamp::now().as_millis(); + let res = create_exam_with( + &c.app, + &c.teacher, + &c.course, + json!({ "title": "Midterm", "kind": "quiz", "mode": "sync", + "starts_at": now - 1_000, "ends_at": now + 600_000 }), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let exam = id_of(&res.body); + + let started = send( + &c.app, + "POST", + &format!("/exams/{exam}/attempt"), + Some(&c.student), + None, + ) + .await; + assert_eq!(started.status, StatusCode::CREATED, "{}", started.body); + + let resumed = send( + &c.app, + "POST", + &format!("/exams/{exam}/attempt"), + Some(&c.student), + None, + ) + .await; + assert_eq!( + resumed.status, + StatusCode::OK, + "the second post must resume, not start: {}", + resumed.body + ); + + let mine = my_profile(&c.app, &c.student).await; + assert_eq!( + mine["stats"]["exam_sat_total"], 1, + "a resume is not a second sitting: {mine}" + ); + assert_eq!(badge_ids(&mine), ["exam_sat_1"], "{mine}"); +} + +/// The catalog a client renders badges from, end to end. `stat` is a **wire** +/// name: a domain test pins that it differs from the user-row column, and this +/// pins that what ships is the wire one — and that appending `_total` to it +/// lands on a real key of a real profile's stats, which is the only thing that +/// lets a client join the two surfaces at all. +#[tokio::test] +async fn the_badge_catalog_is_reachable_and_wire_named() { + let (app, _db) = app_and_db().await; + let fresh = login(&app, "fresh").await; + let stats = my_profile(&app, &fresh).await["stats"] + .as_object() + .expect("stats object") + .clone(); + + // Unauthenticated: the form that renders a badge needs no session. + let res = send(&app, "GET", "/limits", None, None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let catalog = res.body["badges"]["catalog"] + .as_array() + .unwrap_or_else(|| panic!("badges.catalog array: {}", res.body)); + assert!(!catalog.is_empty(), "an empty catalog awards nothing"); + + for badge in catalog { + let id = badge["id"] + .as_str() + .unwrap_or_else(|| panic!("id: {badge}")); + let stat = badge["stat"] + .as_str() + .unwrap_or_else(|| panic!("stat: {badge}")); + let threshold = badge["threshold"] + .as_i64() + .unwrap_or_else(|| panic!("threshold: {badge}")); + assert!(threshold > 0, "{id} is earned by doing nothing"); + assert!( + !stat.ends_with("_total"), + "{id} serves the database column {stat}, not a wire name: renaming \ + the column would break the API" + ); + assert!( + stats.contains_key(&format!("{stat}_total")), + "{id}'s stat {stat} joins no profile stats key: {stats:?}" + ); + } + assert!( + catalog + .iter() + .any(|badge| badge["id"] == "homework_submitted_1" && badge["threshold"] == 1), + "the first-homework badge left the catalog: {res_body}", + res_body = res.body + ); +} + +/// Badges are public — they are a decoration, not a record — so they ride the +/// profile's existing gate and open no door of their own: a peer reads them, +/// and a parent with no link to the student is still refused the whole +/// profile, badges included. +#[tokio::test] +async fn badges_ride_the_profile_gate_and_open_no_new_door() { + let c = classroom().await; + let only = homework(&c, "Fractions I", 600_000).await; + hand_in(&c.app, &c.student, &only).await; + + let peer = login(&c.app, "peer").await; + let seen = profile(&c.app, &peer, &c.student_id).await; + assert_eq!(seen.status, StatusCode::OK, "{}", seen.body); + assert_eq!( + badge_ids(&seen.body), + ["homework_submitted_1"], + "a peer sees the shelf: {}", + seen.body + ); + + let stranger = login_as(&c.app, &c.db, "mom", "parent").await; + let blocked = profile(&c.app, &stranger, &c.student_id).await; + assert_eq!( + blocked.status, + StatusCode::FORBIDDEN, + "an unlinked parent reads no profile, badges included: {}", + blocked.body + ); +} + /// A profile that was never there is a 404, at any role — the id is not an /// existence oracle wearing a 403. #[tokio::test] diff --git a/tests/spec_bounds.rs b/tests/spec_bounds.rs index d73986d..c04279c 100644 --- a/tests/spec_bounds.rs +++ b/tests/spec_bounds.rs @@ -1045,6 +1045,40 @@ fn expectations_cover_every_annotation() { ); } +/// README.md quotes how many bounds this suite checks — a hand-kept copy of +/// [`expectations`]`.len()`, and one that had already gone stale twice before +/// anything watched it. This is that watcher. +#[test] +fn the_readme_states_the_real_bound_count() { + // Anchored on the sentence itself, not a line number or a loose digit + // scan: the README is 73KB and full of other numbers. + const ANCHOR: &str = "`tests/spec_bounds.rs` builds the OpenAPI document, reads all "; + let readme = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/README.md")) + .expect("read README.md"); + let at = readme.find(ANCHOR).unwrap_or_else(|| { + panic!( + "README.md no longer contains the sentence this test reads:\n \"{ANCHOR}…\"\n\n\ + It states how many published bounds this suite checks ({} today). Restore that \ + wording, or move the count and re-anchor this test on its new phrasing.", + expectations().len() + ) + }); + let stated: String = readme[at + ANCHOR.len()..] + .chars() + .take_while(char::is_ascii_digit) + .collect(); + + assert_eq!( + stated.parse::().ok(), + Some(expectations().len()), + "README.md says this suite checks {stated:?} published bounds, but the expectations \ + table has {} rows.\n\nEdit README.md so that sentence reads \"reads all {} published \ + bounds\" — the table is the truth, the README is the copy.", + expectations().len(), + expectations().len() + ); +} + /// The three image-meta bodies — exam question images, bank template images, /// and pool question/solution photos — are hand-kept copies of one shape, /// `{content_type, size}`. The write half behind them is shared