diff --git a/README.md b/README.md index 9eddb9a..6b2e87a 100644 --- a/README.md +++ b/README.md @@ -3834,6 +3834,14 @@ which is exactly what a code guessed from a *substring* of the refusal did matches the refusal constants by value and a test pairs every one of them with the code its client must act on. +**A closed board is never reported as `locked`.** Locking and closing are +independent — a board may be closed while locked, in either order, and nothing +refuses either call because of the other — and when both hold the answer is +`board_closed` on *every* path (a stroke, a socket `clear`, `POST +/boards/{id}/clear`). Closed outranks locked because there is no reopen: a +pause the client is told to wait out would never lift. Unlocking such a board +changes nothing about it; it stays permanently read-only. + **Persist, then publish.** A stroke is fanned out only after its row has landed, so the channel can never carry a mark the database refused (a locked board, a full epoch, a closed board). The database is the canvas; the channel diff --git a/src/domain/board_stroke.rs b/src/domain/board_stroke.rs index 8822896..4801e2a 100644 --- a/src/domain/board_stroke.rs +++ b/src/domain/board_stroke.rs @@ -199,24 +199,42 @@ impl BoardStroke { } } + /// The one place the module orders `closed` above `locked`, because a board + /// can hold both flags at once (nothing gates `/close` on the lock or the + /// lock on `closed_at`) and **closed outranks locked**: there is no reopen + /// route, so the pause never lifts and only the terminal answer is true. + /// Both classifiers read the precedence from here rather than keeping a + /// copy of it — the copies are what drifted, and a room told "the creator + /// has paused drawing" about a permanently read-only board waits forever. + /// + /// `None` means the board is neither: whatever refused the write, this is + /// not why. + fn state_refusal(board: &Board) -> Option<&'static str> { + if board.get_closed_at().is_some() { + Some(BOARD_CLOSED) + } else if board.is_locked() { + Some(BOARD_LOCKED) + } else { + None + } + } + async fn why_refused(board: &BoardId, db: &Database) -> Result { let board = Board::read(board, db).await?.ok_or(AppError::NotFound)?; - if board.is_locked() { - return Ok(AppError::Conflict(BOARD_LOCKED)); + if let Some(refusal) = Self::state_refusal(&board) { + return Ok(AppError::Conflict(refusal)); } - if board.get_closed_at().is_none() { - // Not closed yet. The lifetime counter has to say so *itself*: - // `FullHard` also fires when the guard failed, so a board that was - // locked (or a clear that moved the epoch) when the claim ran and - // is open again now would otherwise be stamped read-only at one - // stroke of a 50 000 budget — irreversibly, with no reopen. - if Self::total_strokes(board.get_id(), db).await? < MAX_BOARD_STROKES { - return Ok(AppError::Conflict(BOARD_MOVED)); - } - // `Board::close` is the one-way idempotent stamp: a second append - // takes this branch too and leaves the first `closed_at` standing. - board.close(db).await?; + // Neither flag, so the lifetime counter has to say so *itself*: + // `FullHard` also fires when the guard failed, so a board that was + // locked (or a clear that moved the epoch) when the claim ran and is + // open again now would otherwise be stamped read-only at one stroke of + // a 50 000 budget — irreversibly, with no reopen. + if Self::total_strokes(board.get_id(), db).await? < MAX_BOARD_STROKES { + return Ok(AppError::Conflict(BOARD_MOVED)); } + // `Board::close` is the one-way idempotent stamp: a second append takes + // this branch too and leaves the first `closed_at` standing. + board.close(db).await?; Ok(AppError::Conflict(BOARD_CLOSED)) } @@ -330,7 +348,10 @@ impl BoardStroke { db: &Database, ) -> Result { let board = Board::read(board, db).await?.ok_or(AppError::NotFound)?; - if board.get_closed_at().is_some() { + let state = Self::state_refusal(&board); + // Terminal outranks the caller's identity: a closed board is read-only + // for its creator too, so "closed" is the honest answer to anyone. + if state == Some(BOARD_CLOSED) { return Ok(AppError::Conflict(BOARD_CLOSED)); } if !board.is_creator(by) { @@ -339,8 +360,8 @@ impl BoardStroke { // A lock pauses the *creator* too, and it is a state the caller can // undo — a `Conflict`, not the `Forbidden` a wrong caller gets. Unlock, // clear, relock is the recovery for a locked board that is also full. - if board.is_locked() { - return Ok(AppError::Conflict(BOARD_LOCKED)); + if let Some(refusal) = state { + return Ok(AppError::Conflict(refusal)); } Ok(AppError::Conflict(CANVAS_BLANK)) } @@ -737,6 +758,85 @@ mod tests { assert_eq!(reread(&board, &db).await.get_epoch(), 1); } + /// Both classifiers, one board: the words a stroke is refused with and the + /// words the *creator's* clear is refused with. They must match — the two + /// used to be independent chains and drifted apart on the state below. + async fn both_refusals(board: &Board, db: &Database) -> (&'static str, &'static str) { + let stroke = match draw(board, db).await { + Err(AppError::Conflict(msg)) => msg, + other => panic!("the stroke was not refused: {other:?}"), + }; + let clear = match BoardStroke::clear(board.get_id(), &user("c"), db).await { + Err(AppError::Conflict(msg)) => msg, + other => panic!("the clear was not refused: {other:?}"), + }; + (stroke, clear) + } + + /// A board that is locked *and* closed is terminal, and both paths have to + /// say so. Reaching the state is ungated in either direction — `set_locked` + /// carries no `closed_at` test and `close` carries no lock test — and the + /// stroke path used to test the lock first, so a permanently read-only + /// board answered every mark with "the creator has paused drawing" while + /// the same board answered a clear with the terminal words. A room told to + /// wait for a pause that cannot lift waits forever. + /// + /// Locking a closed board stays *allowed*: it is a no-op on a board that is + /// already read-only, and refusing it would break the second half of a + /// close-then-lock a client may legitimately send in either order. + #[tokio::test] + async fn locked_and_closed_answers_closed_whichever_came_first() { + for closed_first in [false, true] { + let db = a_db().await; + let board = a_board(&db).await; + // A mark on the canvas, so "nothing to clear" cannot be the reason. + draw(&board, &db).await.unwrap(); + + let board = if closed_first { + let board = board.close(&db).await.unwrap(); + board.set_locked(true, &user("c"), &db).await.unwrap() + } else { + let board = board.set_locked(true, &user("c"), &db).await.unwrap(); + board.close(&db).await.unwrap() + }; + // Stored state: both flags really are up, and the close stamp stood. + let stored = reread(&board, &db).await; + assert!(stored.is_locked() && stored.get_closed_at().is_some()); + + assert_eq!( + both_refusals(&board, &db).await, + (BOARD_CLOSED, BOARD_CLOSED), + "closed_first = {closed_first}" + ); + // And the refusals wrote nothing: one mark, no marker, epoch 0. + assert_eq!(rows(board.get_id(), &db).await.len(), 1); + assert_eq!(reread(&board, &db).await.get_epoch(), 0); + } + } + + /// The other half of the same contract: a board holding *one* of the flags + /// keeps its own answer on both paths. A lock is recoverable, a close is + /// not, and collapsing either into the other is the mislabel above. + #[tokio::test] + async fn one_flag_alone_keeps_its_own_answer_on_both_paths() { + let db = a_db().await; + let locked = a_board(&db).await; + draw(&locked, &db).await.unwrap(); + let locked = locked.set_locked(true, &user("c"), &db).await.unwrap(); + assert_eq!( + both_refusals(&locked, &db).await, + (BOARD_LOCKED, BOARD_LOCKED) + ); + + let closed = a_board(&db).await; + draw(&closed, &db).await.unwrap(); + let closed = closed.close(&db).await.unwrap(); + assert_eq!( + both_refusals(&closed, &db).await, + (BOARD_CLOSED, BOARD_CLOSED) + ); + } + /// The `next_ulid` hazard: rows minted inside one millisecond must replay /// in mint order, not at random (src/domain/monotonic_id.rs:41-46). #[tokio::test] diff --git a/src/lib.rs b/src/lib.rs index 7bc7966..614bccb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -64,7 +64,7 @@ use crate::state::AppState; (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) — those marks would silently re-weight. Also the food program: the meal slots menus are published for — each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and a slot with no serving minute carries **no cutoff at all** rather than one counted from midnight) — the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` — one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. A slot name may not contain `/ \\ ? # %` (400) — the name is copied verbatim into a menu's record id, which is a URL path segment — but a name the school's stored list already carries is exempt from that rule, since re-validating it would leave a list written before the rule existed unable to be edited at all: re-sending the name is a 400 and dropping it is a 409 once a menu used it. A grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it. Read: any authenticated user; edit: manager+"), (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"), (name = "homework", description = "Course homework: a teacher assigns it per course (`POST /courses/{id}/homework`), tagged with one of the course's subjects (re-taggable; a subject with homework refuses deletion until it is re-tagged or removed) and given a future `due_at`, to the whole enrolled course or an optional `assigned` subset (empty means the whole course — whoever is enrolled when they submit; a subset cannot later be narrowed so as to strand work that already exists). Students submit optional text plus files — any content type, up to 10 per submission, each capped by the school's `max_file_bytes`, always served back as forced attachment downloads (never inline); a submission touched after `due_at` is flagged late (computed from the moving last-touch stamp, never stored — the first-submit stamp is immutable) and stays editable until it is graded. A teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — grading freezes the submission until the grade is removed (un-grading reopens it), never targets the grader themselves, and covers work never handed in (that is how `missing` is set; the student reads the verdict at `GET /homework/{id}/result`). Beyond a teacher-set `missing` the roster and reports also compute a `missing` for anyone unsubmitted past due, and the roster keeps a straggler's stale work visible (flagged `unenrolled`) after an unenrollment or promotion. Homework marks stay out of the weighted `/marks` averages. Students see and fetch only the homework they are assigned (others 404, so a subset assignment never leaks), and the ones it does name get its `assigned` list narrowed to their own id — who else was assigned is roster information, and the roster is teacher+-only; a linked parent reads a student's homework report — statuses, late flags, marks — but never the submitted files"), - (name = "boards", description = "Collaborative whiteboards. Anyone **from `student` upwards** opens a board (`POST /boards`) with a title and an ad-hoc invite list of user ids — no course, session or appointment is involved — and every participant draws on it; the creator alone clears, locks, closes or deletes it. `GET /boards` takes `?open=true|false` to narrow the list by the closing stamp (`total` counts the filtered list) — a closed board is never deleted, so this is how a creator holding many boards trims the retired ones out of sight. It filters `closed_at` and nothing else: a **locked** board, and one that has spent its lifetime stroke budget but was never drawn on again, are both still open, because the stamp is written only by `/close` or by the append the lifetime cap refuses. The `parent` role has no whiteboard access whatsoever: it is refused `POST /boards` and `GET /boards` with a `403`, and cannot be named in an invite list at all (`400`) — so a parent is never on a roster, which makes every id-scoped route and the room's door answer the outsider's `404` rather than a `403` that would confirm the board exists. Every frame the room delivers is authorized against the database first, so a caller who loses the right to be there — taken off the roster, or demoted below `student` — is served no further content: they get one `error{code:\"forbidden\"}` naming which of the two happened, and the room closes. That is separate from a refused *command*: `clear` and `lock` by a non-creator answer `error{code:\"forbidden\"}` and deliberately keep the socket open, since a participant who clicked the wrong button has made a mistake, not left the room. A demotion below `student` also sweeps that account off every roster it was on, and the rosters an older binary left behind were repaired at boot: a board written before that sweep can name a parent, or a user since deleted, and every such id is stripped the first time this binary starts. A board whose *creator* was demoted is left standing — barred to them, unchanged for everyone else. A caller who is not on a board gets a `404` for it on every route, existence included, while a participant who is not the creator gets a `403` on those four commands (they are already rendering the board, so hiding it from them would be a lie their client cannot act on). Strokes are **append-only and a clear deletes nothing**: it bumps the board's `epoch`, so the live canvas empties while every mark ever drawn stays stored — `GET /boards/{id}/strokes` is the current epoch — drawn marks only, never a `clear` marker, exactly as the room's socket replays it, so the REST catch-up and the live canvas can never disagree, `GET /boards/{id}/history?epoch=` is the whole session or one named epoch, and `GET /boards/{id}/epochs` is the index of `clear` markers (a clear needs at least one mark to close: an **already-blank** canvas answers `409` alongside the closed board and the **locked** one — the pause the creator set holds against their own clear too, so a locked board sitting at `max_epoch_strokes` is recovered by unlock, clear, relock — since the marker is a stored row charged to the lifetime cap), each carrying the epoch it closed, that epoch's final stroke count, who cleared and when (the markers *are* the index, so the open epoch is deliberately absent from it). Two growth caps, both published at `GET /limits`: `max_epoch_strokes` bounds the *live* canvas and is recoverable (clear it and drawing resumes, losing nothing), while `max_board_strokes` bounds the board's *lifetime* storage — rows on the board, so a `clear` marker costs one unit like any mark, and a board holds at most `max_board_strokes + 1` rows because the marker closing the final stroke is never the one refused — and stamps `closed_at` on the way past — a closed board is permanently read-only and fully readable, never deleted, and there is no reopen. `POST /boards/{id}/close` is the manual form of that, and idempotent. `DELETE /boards/{id}` is the one operation here that really destroys marks — it takes the whole stroke log with it and frees one of the creator's `max_boards_per_creator` seats. `PATCH /boards/{id}` re-titles (any participant) or changes the roster and the lock (creator only). `POST /boards/{id}/invite` fills that roster from a group that already exists rather than one id at a time — `{kind:\"class\", class}` for a class section (şube), `{kind:\"course\", course}` for a course's enrolled students (clubs and study groups *are* courses, so this is how a whole club is invited), `{kind:\"event\", event}` for an event's expected-attendee roster exactly as `GET /events/{id}/roster` resolves it. It is the creator's alone and strictly **additive** — nothing is ever removed by it, removal stays `PATCH` — and it resolves **once**, at the call: a board holds a flat list of ids and no memory of where they came from, so a student who joins that class tomorrow is not on today's board, and re-inviting the same source is how a roster is topped up (idempotent when nothing changed). Ineligible members are dropped silently rather than failing the call for everyone else — ids that no longer resolve to a user, and anyone below `student`, which is the same cut that keeps `parent` off a whiteboard — but the participant cap is **all-or-nothing**: an invite that would carry the board past `max_participants` is refused with a `409` naming both numbers, and nobody is added. Since a board's roster is visible to every participant, inviting a group *discloses* that group's membership, so each source carries the gate its own listing route already carries: teacher+ for a class, the course's creator/assigned teacher/manager+ for a course, teacher+ for an event. A student may still build a board one id at a time; they cannot pour a class roster into one. Not in this spec (WebSocket): the live board room at `GET /boards/{id}/ws`, where the drawing itself happens — JSON frames, cookie-authed, and a **404** at the door for anyone not on the board. A `join` replays the current epoch only (chunked `strokes`, then `synced` with the cursor to resume from); a `stroke` is persisted before it is fanned out, so every canvas in the room is showing rows that committed; `clear` and `lock` are the creator's alone and refuse anyone else with `error{code:\"forbidden\"}` *without* closing their socket. The REST mutations above fan out into the same room, and a roster change drops the socket of anyone it removed. See `src/web/board_ws.rs` for the frame-by-frame protocol"), + (name = "boards", description = "Collaborative whiteboards. Anyone **from `student` upwards** opens a board (`POST /boards`) with a title and an ad-hoc invite list of user ids — no course, session or appointment is involved — and every participant draws on it; the creator alone clears, locks, closes or deletes it. `GET /boards` takes `?open=true|false` to narrow the list by the closing stamp (`total` counts the filtered list) — a closed board is never deleted, so this is how a creator holding many boards trims the retired ones out of sight. It filters `closed_at` and nothing else: a **locked** board, and one that has spent its lifetime stroke budget but was never drawn on again, are both still open, because the stamp is written only by `/close` or by the append the lifetime cap refuses. The `parent` role has no whiteboard access whatsoever: it is refused `POST /boards` and `GET /boards` with a `403`, and cannot be named in an invite list at all (`400`) — so a parent is never on a roster, which makes every id-scoped route and the room's door answer the outsider's `404` rather than a `403` that would confirm the board exists. Every frame the room delivers is authorized against the database first, so a caller who loses the right to be there — taken off the roster, or demoted below `student` — is served no further content: they get one `error{code:\"forbidden\"}` naming which of the two happened, and the room closes. That is separate from a refused *command*: `clear` and `lock` by a non-creator answer `error{code:\"forbidden\"}` and deliberately keep the socket open, since a participant who clicked the wrong button has made a mistake, not left the room. A demotion below `student` also sweeps that account off every roster it was on, and the rosters an older binary left behind were repaired at boot: a board written before that sweep can name a parent, or a user since deleted, and every such id is stripped the first time this binary starts. A board whose *creator* was demoted is left standing — barred to them, unchanged for everyone else. A caller who is not on a board gets a `404` for it on every route, existence included, while a participant who is not the creator gets a `403` on those four commands (they are already rendering the board, so hiding it from them would be a lie their client cannot act on). Strokes are **append-only and a clear deletes nothing**: it bumps the board's `epoch`, so the live canvas empties while every mark ever drawn stays stored — `GET /boards/{id}/strokes` is the current epoch — drawn marks only, never a `clear` marker, exactly as the room's socket replays it, so the REST catch-up and the live canvas can never disagree, `GET /boards/{id}/history?epoch=` is the whole session or one named epoch, and `GET /boards/{id}/epochs` is the index of `clear` markers (a clear needs at least one mark to close: an **already-blank** canvas answers `409` alongside the closed board and the **locked** one — the pause the creator set holds against their own clear too, so a locked board sitting at `max_epoch_strokes` is recovered by unlock, clear, relock — since the marker is a stored row charged to the lifetime cap), each carrying the epoch it closed, that epoch's final stroke count, who cleared and when (the markers *are* the index, so the open epoch is deliberately absent from it). Two growth caps, both published at `GET /limits`: `max_epoch_strokes` bounds the *live* canvas and is recoverable (clear it and drawing resumes, losing nothing), while `max_board_strokes` bounds the board's *lifetime* storage — rows on the board, so a `clear` marker costs one unit like any mark, and a board holds at most `max_board_strokes + 1` rows because the marker closing the final stroke is never the one refused — and stamps `closed_at` on the way past — a closed board is permanently read-only and fully readable, never deleted, and there is no reopen. `POST /boards/{id}/close` is the manual form of that, and idempotent. Closing and locking are independent, and a board holding both flags answers **closed** everywhere — a stroke, a socket `clear` and `POST /boards/{id}/clear` all report the terminal state, never the pause, because the pause can never lift. `DELETE /boards/{id}` is the one operation here that really destroys marks — it takes the whole stroke log with it and frees one of the creator's `max_boards_per_creator` seats. `PATCH /boards/{id}` re-titles (any participant) or changes the roster and the lock (creator only). `POST /boards/{id}/invite` fills that roster from a group that already exists rather than one id at a time — `{kind:\"class\", class}` for a class section (şube), `{kind:\"course\", course}` for a course's enrolled students (clubs and study groups *are* courses, so this is how a whole club is invited), `{kind:\"event\", event}` for an event's expected-attendee roster exactly as `GET /events/{id}/roster` resolves it. It is the creator's alone and strictly **additive** — nothing is ever removed by it, removal stays `PATCH` — and it resolves **once**, at the call: a board holds a flat list of ids and no memory of where they came from, so a student who joins that class tomorrow is not on today's board, and re-inviting the same source is how a roster is topped up (idempotent when nothing changed). Ineligible members are dropped silently rather than failing the call for everyone else — ids that no longer resolve to a user, and anyone below `student`, which is the same cut that keeps `parent` off a whiteboard — but the participant cap is **all-or-nothing**: an invite that would carry the board past `max_participants` is refused with a `409` naming both numbers, and nobody is added. Since a board's roster is visible to every participant, inviting a group *discloses* that group's membership, so each source carries the gate its own listing route already carries: teacher+ for a class, the course's creator/assigned teacher/manager+ for a course, teacher+ for an event. A student may still build a board one id at a time; they cannot pour a class roster into one. Not in this spec (WebSocket): the live board room at `GET /boards/{id}/ws`, where the drawing itself happens — JSON frames, cookie-authed, and a **404** at the door for anyone not on the board. A `join` replays the current epoch only (chunked `strokes`, then `synced` with the cursor to resume from); a `stroke` is persisted before it is fanned out, so every canvas in the room is showing rows that committed; `clear` and `lock` are the creator's alone and refuse anyone else with `error{code:\"forbidden\"}` *without* closing their socket. The REST mutations above fan out into the same room, and a roster change drops the socket of anyone it removed. See `src/web/board_ws.rs` for the frame-by-frame protocol"), (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses and classes may link to one. A term still linked by any course or class cannot be deleted (409) — unlink them first. Read: any authenticated user; edit: manager+"), ), )] diff --git a/src/web/boards.rs b/src/web/boards.rs index a81a945..ffb41a3 100644 --- a/src/web/boards.rs +++ b/src/web/boards.rs @@ -582,7 +582,9 @@ async fn update_board( /// so a locked full board is recovered by unlock, clear, relock — and on a /// canvas that is **already blank**: the marker is a real stroke row charged to /// the board's lifetime cap, so a clear has to close at least one mark to be -/// worth a row. +/// worth a row. A board that is both locked and closed answers **closed** — +/// here and on every stroke path alike, since there is no reopen and the pause +/// can never lift. #[utoipa::path( post, path = "/{id}/clear",