forge
Explore
Log in

Don't you dare go Hollow

πŸ§‘β€πŸ« invite a whole class or club to a board

Browse files at this commit

0e3eae0c3c5d364faac6d0f71c8b019c828ff568Ahmet Kaan GümüşParent: afff737
  • feat
    • πŸ§‘β€πŸ« invite a whole class or club to a board
Show full message
feat: πŸ§‘β€πŸ« invite a whole class or club to a board

A board roster was one id at a time, so opening a canvas for a class
meant typing thirty of them and the cap refused an ordinary club.

POST /boards/{id}/invite names a group instead β€” a class section, a
course (a club is a course), or an event's roster, resolved through the
audience machinery events already had. The ids expand once, into the
same flat participants array: a snapshot, not a subscription. Live
resolution would have made is_participant, the room's door and
list_for_user cross-table queries, and would have taken per-person
removal away from the creator, which is most of what a board roster is
for. The board stores no source, so re-inviting is both how a roster is
topped up and the one thing that undoes a removal.

Additive only; removal stays PATCH. The participant cap moves 50 -> 200
and is all-or-nothing β€” a partial invite would silently pick which half
of a class gets to draw. Ineligible members (gone, or below student, or
already there) drop silently, because one of them must not fail the
invite for the other twenty-nine.

The gate is not a new permission: a roster is visible to everyone on the
board, so inviting a group discloses it, and each source carries the
gate its own listing route carries. Bulk invite is therefore teacher+;
a student can still build a board by hand but cannot pour a class into
one.

resolve_participants now batches its lookup. It read one row per id,
which at the new cap made a read-modify-write PATCH of a class-filled
board β€” the ordinary client shape now β€” two hundred sequential reads.
README.mdmodified+64 -4
@@ -343,7 +343,7 @@ response in the same commit.
343 "appointment": { "max_note_len": 500, "max_reason_len": 1000, "max_slot_occurrences": 52 },343 "appointment": { "max_note_len": 500, "max_reason_len": 1000, "max_slot_occurrences": 52 },
344 "chatbot": { "max_message_len": 8000, "max_thread_title_len": 200,344 "chatbot": { "max_message_len": 8000, "max_thread_title_len": 200,
345 "min_max_message_len": 100, "…": 0 },345 "min_max_message_len": 100, "…": 0 },
346- "board": { "max_title_len": 200, "max_participants": 50,346+ "board": { "max_title_len": 200, "max_participants": 200,
347 "max_stroke_payload_len": 4096,347 "max_stroke_payload_len": 4096,
348 "max_epoch_strokes": 5000, "max_board_strokes": 50000,348 "max_epoch_strokes": 5000, "max_board_strokes": 50000,
349 "max_boards_per_creator": 200,349 "max_boards_per_creator": 200,
@@ -972,6 +972,7 @@ window filtering, before paging; negative values are a `400` naming the field.
972 | GET | `/boards/{id}/history` | student | The whole append-only log, oldest first, `clear` markers included Β· `?epoch=` for one epoch Β· paged |972 | GET | `/boards/{id}/history` | student | The whole append-only log, oldest first, `clear` markers included Β· `?epoch=` for one epoch Β· paged |
973 | GET | `/boards/{id}/epochs` | student | The epoch index: every `clear` marker (the epoch it closed, that epoch's final stroke count, who cleared, when) Β· paged |973 | GET | `/boards/{id}/epochs` | student | The epoch index: every `clear` marker (the epoch it closed, that epoch's final stroke count, who cleared, when) Β· paged |
974 | PATCH | `/boards/{id}` | student | `{title?, participants?, locked?}` β€” re-title (any participant); the roster and the lock are the creator's alone (`403`) |974 | PATCH | `/boards/{id}` | student | `{title?, participants?, locked?}` β€” re-title (any participant); the roster and the lock are the creator's alone (`403`) |
975+| POST | `/boards/{id}/invite` | teacher | **Creator only**, additive: fill the roster from a group β€” `{kind:"class", class}`, `{kind:"course", course}` (a club is a course), `{kind:"event", event}`. Resolved once, never live; `409` all-or-nothing at `max_participants` |
975 | POST | `/boards/{id}/clear` | student | **Creator only**: bump the epoch, blanking the live canvas and resetting its cap β€” nothing is deleted; `409` on a closed board, on a **locked** board, and on a canvas that is **already blank** (the marker is a stored row, so a clear has to close at least one mark to be worth one) |976 | POST | `/boards/{id}/clear` | student | **Creator only**: bump the epoch, blanking the live canvas and resetting its cap β€” nothing is deleted; `409` on a closed board, on a **locked** board, and on a canvas that is **already blank** (the marker is a stored row, so a clear has to close at least one mark to be worth one) |
976 | POST | `/boards/{id}/close` | student | **Creator only**: retire the board β€” permanently read-only, still fully readable; idempotent, and there is no reopen |977 | POST | `/boards/{id}/close` | student | **Creator only**: retire the board β€” permanently read-only, still fully readable; idempotent, and there is no reopen |
977 | DELETE | `/boards/{id}` | student | **Creator only**: delete the board and its whole stroke log; frees one of the creator's board seats |978 | DELETE | `/boards/{id}` | student | **Creator only**: delete the board and its whole stroke log; frees one of the creator's board seats |
@@ -2979,9 +2980,12 @@ context without either end having to be redeployed in lockstep.
2979 2980
2980 A board is a shared canvas whose membership is an **ad-hoc invite list**: the2981 A board is a shared canvas whose membership is an **ad-hoc invite list**: the
2981 creator names participant user ids at `POST /boards` and that is the whole2982 creator names participant user ids at `POST /boards` and that is the whole
2982-model β€” no course, no lesson session, no appointment. Any account from2983+model β€” no course, no lesson session, no appointment binds a board. Any account
2983-`student` upwards may open one. **Every participant draws; the creator2984+from `student` upwards may open one. **Every participant draws; the creator
2984-alone clears, locks, closes or deletes.**2985+alone clears, locks, closes or deletes.** A teacher who does not want to type
2986+thirty ids fills the same list in one call with `POST /boards/{id}/invite`
2987+(below) β€” that is a bulk *write* into the ad-hoc list, not a binding: the board
2988+still owns its roster afterwards.
2985 2989
2986 The roster is spelled `participants` everywhere β€” in the `POST` body, in the2990 The roster is spelled `participants` everywhere β€” in the `POST` body, in the
2987 `PATCH` body and in every board response β€” so the field never changes name2991 `PATCH` body and in every board response β€” so the field never changes name
@@ -3005,6 +3009,62 @@ read-modify-write never wedges on a value the server itself handed over.
3005 Naming a *new* id that is unknown or a parent is still a `400`, and the whole3009 Naming a *new* id that is unknown or a parent is still a `400`, and the whole
3006 call is refused β€” the roster is never half-applied.3010 call is refused β€” the roster is never half-applied.
3007 3011
3012+**Bulk invite.** `POST /boards/{id}/invite` fills the roster from a group that
3013+already exists instead of one id at a time. The body is tagged by `kind`, the
3014+same wire shape an event audience uses:
3015+
3016+```json
3017+{ "kind": "class", "class": "01J…" } // everyone in a class section (şube)
3018+{ "kind": "course", "course": "01J…" } // everyone enrolled in a course
3019+{ "kind": "event", "event": "01J…" } // the event's expected-attendee roster
3020+```
3021+
3022+A **club is a course** (`kind` `club`), so "invite the whole club" is the
3023+`course` form; so is a study group (`study`). The `event` form resolves exactly
3024+what `GET /events/{id}/roster` resolves, which is the signup list for a
3025+registration event and the class or course roster for the others β€” a
3026+school-wide or role-wide event will normally overflow the cap, and that is a
3027+`409` rather than a truncation.
3028+
3029+It is the creator's call and **additive**: everyone the source names is *added*,
3030+nobody is ever removed by it. Removal stays `PATCH /boards/{id}` β€” send the
3031+roster you want.
3032+
3033+**The ids are resolved once, at the call β€” this is a snapshot, not a
3034+subscription.** A board keeps a flat list of ids and no memory of where they
3035+came from, so a student who joins that class tomorrow is *not* on today's board,
3036+and nothing the class does afterwards puts back a student the creator took off.
3037+Re-inviting the same source is how a board is topped up after the class changed;
3038+it adds only who is missing, so it is idempotent when nothing did β€” and it is
3039+also the one thing that undoes a removal, because the source still names that
3040+student. Removing someone from a board you intend to re-invite the class to is
3041+therefore not a ban; there is no per-board exclusion list. Live resolution was the alternative and
3042+was rejected here: it would turn the permission check behind every stroke, the
3043+room's door and "which boards may I open" into cross-table queries, and it would
3044+take the per-person removal away from the creator β€” which is most of what a
3045+whiteboard roster is for.
3046+
3047+Three filters run before the ids land, and all three are **silent**, because one
3048+ineligible member must not fail the invite for the other twenty-nine: ids that
3049+no longer resolve to a user are dropped, anyone below `student` is dropped (the
3050+same cut that keeps `parent` off a whiteboard), and anyone already on the board
3051+β€” the creator included β€” is not added twice.
3052+
3053+The cap, though, is **all-or-nothing**: if the union would carry the board past
3054+`max_participants` the whole invite is refused with a `409` naming both numbers
3055+and the roster is left exactly as it was. A partial invite would silently pick
3056+which half of a class gets to draw.
3057+
3058+**Inviting a group discloses that group.** A board's roster is visible to every
3059+participant, so each source carries the gate its own listing route carries β€”
3060+teacher+ for a class (`GET /classes/{id}/members`), the course's creator, an
3061+assigned teacher or a manager+ for a course (`GET /courses/{id}/enrollments`),
3062+teacher+ for an event (`GET /events/{id}/roster`). A student may still build a
3063+board one id at a time; they cannot pour a class roster into one. A source that
3064+does not exist is a `400` naming the field, never a `404` β€” on these routes a
3065+`404` means "no such board, or not yours", and reusing it here would tell a
3066+creator their own board had vanished.
3067+
3008 **No parents, anywhere.** The `parent` role is the school's read-only observer,3068 **No parents, anywhere.** The `parent` role is the school's read-only observer,
3009 and it has no whiteboard access at all β€” not a view-only tier, none. It is3069 and it has no whiteboard access at all β€” not a view-only tier, none. It is
3010 refused `POST /boards` and `GET /boards` with a `403`, and it cannot be *named*3070 refused `POST /boards` and `GET /boards` with a `403`, and it cannot be *named*
src/constant.rsmodified+8 -2
@@ -299,10 +299,16 @@ pub const MAX_FEE_PLAN_ASSIGN_STUDENTS: usize = 200;
299 pub const MAX_PAYMENT_REQUEST_KEY_LEN: usize = 64;299 pub const MAX_PAYMENT_REQUEST_KEY_LEN: usize = 64;
300 300
301 /// Bounds on a whiteboard: its title, and how many people the creator may name301 /// Bounds on a whiteboard: its title, and how many people the creator may name
302-/// onto it. Fifty is a class and its teachers, not the school; every302+/// onto it. Two hundred is a big club or a whole grade, not the school; every
303 /// participant may draw, so this is also what bounds one board's writer count.303 /// participant may draw, so this is also what bounds one board's writer count.
304+///
305+/// It was fifty while a roster could only be typed one id at a time. Bulk
306+/// invite (`POST /boards/{id}/invite`) resolves a class section, a course or an
307+/// event's roster in one call, and fifty refused an ordinary club β€” so the
308+/// ceiling moved to the size of the largest group a school actually puts on one
309+/// canvas. Raising it can only widen what an existing row is allowed to hold.
304 pub const MAX_BOARD_TITLE_LEN: usize = 200;310 pub const MAX_BOARD_TITLE_LEN: usize = 200;
305-pub const MAX_BOARD_PARTICIPANTS: usize = 50;311+pub const MAX_BOARD_PARTICIPANTS: usize = 200;
306 312
307 /// Ceiling on one stroke's serialized payload. A stroke is a short path β€” a313 /// Ceiling on one stroke's serialized payload. A stroke is a short path β€” a
308 /// handful of points, a colour, a width β€” and it is stored verbatim and fanned314 /// handful of points, a colour, a width β€” and it is stored verbatim and fanned
src/lib.rsmodified+1 -1
@@ -64,7 +64,7 @@ use crate::state::AppState;
64 (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 the cutoff then counts from midnight UTC) β€” 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+"),64 (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 the cutoff then counts from midnight UTC) β€” 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+"),
65 (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"),65 (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"),
66 (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); a linked parent reads a student's homework report β€” statuses, late flags, marks β€” but never the submitted files"),66 (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); a linked parent reads a student's homework report β€” statuses, late flags, marks β€” but never the submitted files"),
67- (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). 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"),67+ (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"),
68 (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+"),68 (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+"),
69 ),69 ),
70 )]70 )]
src/web/boards.rsmodified+241 -23
@@ -31,11 +31,17 @@ use crate::constant::MAX_BOARD_PARTICIPANTS;
31 use crate::database::Database;31 use crate::database::Database;
32 use crate::domain::board::{Board, BoardId, BoardTitle};32 use crate::domain::board::{Board, BoardId, BoardTitle};
33 use crate::domain::board_stroke::BoardStroke;33 use crate::domain::board_stroke::BoardStroke;
34+use crate::domain::class_group::{ClassGroup, ClassGroupId};
35+use crate::domain::class_member::ClassMember;
36+use crate::domain::course::{Course, CourseId};
37+use crate::domain::enrollment::Enrollment;
38+use crate::domain::event::{Event, EventId};
34 use crate::domain::role::Role;39 use crate::domain::role::Role;
35 use crate::domain::user::{User, UserId};40 use crate::domain::user::{User, UserId};
36 use crate::error::{AppError, ErrorResponse, ValidationError};41 use crate::error::{AppError, ErrorResponse, ValidationError};
37 use crate::state::AppState;42 use crate::state::AppState;
38 43
44+use super::courses::can_manage_course;
39 use super::{CurrentUser, Page, PageParams, RequireStudent, paginate, set_or_clear};45 use super::{CurrentUser, Page, PageParams, RequireStudent, paginate, set_or_clear};
40 46
41 pub fn routes() -> OpenApiRouter<AppState> {47 pub fn routes() -> OpenApiRouter<AppState> {
@@ -51,6 +57,7 @@ pub fn routes() -> OpenApiRouter<AppState> {
51 .routes(routes!(list_epochs))57 .routes(routes!(list_epochs))
52 .routes(routes!(clear_board))58 .routes(routes!(clear_board))
53 .routes(routes!(close_board))59 .routes(routes!(close_board))
60+ .routes(routes!(invite_board))
54 }61 }
55 62
56 /// The board, or a 404 β€” including the deliberate 404 for a caller who is not63 /// The board, or a 404 β€” including the deliberate 404 for a caller who is not
@@ -83,9 +90,16 @@ fn ensure_creator(board: &Board, user: &User) -> Result<(), AppError> {
83 }90 }
84 91
85 /// The invite list off the wire: deduped, capped, and every id resolved against92 /// The invite list off the wire: deduped, capped, and every id resolved against
86-/// a real user. The cap is applied *before* the lookups (the domain caps too,93+/// a real user. The cap is applied *before* the lookup (the domain caps too, but
87-/// but only after this loop would have run one read per id), and an unknown id94+/// only after the read would already have run), and an unknown id is a 400
88-/// is a 400 rather than a silently dropped invitation.95+/// rather than a silently dropped invitation.
96+///
97+/// The eligible set is fetched in **one** read, not one per id. That was a
98+/// per-id loop while a roster could only be typed by hand and so was a handful
99+/// of ids; bulk invite made a full board an ordinary thing to own, and a
100+/// read-modify-write PATCH of one β€” read the board, drop a name, send the rest
101+/// back β€” is the common client shape, so the loop had become
102+/// `max_participants` sequential round trips on a routine edit.
89 ///103 ///
90 /// A `parent` is refused here, and that is the cut that keeps the role off the104 /// A `parent` is refused here, and that is the cut that keeps the role off the
91 /// whiteboard: never on a roster means [`board_for`] and the room's door already105 /// whiteboard: never on a roster means [`board_for`] and the room's door already
@@ -118,11 +132,19 @@ async fn resolve_participants(
118 got: ids.len(),132 got: ids.len(),
119 }));133 }));
120 }134 }
121- let mut users = Vec::with_capacity(ids.len());135+ let wanted: Vec<UserId> = ids.iter().map(|id| UserId::from_key(id)).collect();
122- for id in ids {136+ // Absent from this list means "no such user, or below `student`" β€” the two
123- let user = UserId::from_key(&id);137+ // are one case here, and telling them apart is what the caller must not be
124- let found = User::read(&user, db).await?;138+ // able to do anyway.
125- if !found.is_some_and(|found| found.get_role().at_least(Role::Student)) {139+ let eligible: Vec<UserId> = User::list_by_ids(&wanted, db)
140+ .await?
141+ .iter()
142+ .filter(|found| found.get_role().at_least(Role::Student))
143+ .map(|found| found.get_id().clone())
144+ .collect();
145+ let mut users = Vec::with_capacity(wanted.len());
146+ for user in wanted {
147+ if !eligible.contains(&user) {
126 if current.contains(&user) {148 if current.contains(&user) {
127 continue;149 continue;
128 }150 }
@@ -142,6 +164,22 @@ fn fan_out(st: &AppState, board: &BoardId, frame: serde_json::Value) {
142 st.board_hub.publish(board.key(), frame.to_string());164 st.board_hub.publish(board.key(), frame.to_string());
143 }165 }
144 166
167+/// The roster frame every path that changes the invite list must publish. A
168+/// participant dropped from the array keeps drawing over the socket they
169+/// already hold until the room hears this, so it is a permission fix rather
170+/// than a notification.
171+fn participants_frame(board: &Board) -> serde_json::Value {
172+ json!({
173+ "type": "participants",
174+ "creator": board.get_creator().key(),
175+ "participants": board
176+ .get_participants()
177+ .iter()
178+ .map(|user| user.key())
179+ .collect::<Vec<_>>(),
180+ })
181+}
182+
145 #[derive(Serialize, ToSchema)]183 #[derive(Serialize, ToSchema)]
146 struct BoardResponse {184 struct BoardResponse {
147 id: String,185 id: String,
@@ -229,7 +267,7 @@ struct CreateBoard {
229 title: String,267 title: String,
230 /// Who may draw, besides the creator. Omit or send an empty list to open a268 /// Who may draw, besides the creator. Omit or send an empty list to open a
231 /// board alone and invite later.269 /// board alone and invite later.
232- #[schema(max_items = 50)]270+ #[schema(max_items = 200)]
233 participants: Option<Vec<String>>,271 participants: Option<Vec<String>>,
234 }272 }
235 273
@@ -462,7 +500,7 @@ struct UpdateBoard {
462 /// Replace the invite list β€” **creator only**. Omit to keep; send `null`500 /// Replace the invite list β€” **creator only**. Omit to keep; send `null`
463 /// (or an empty list) to leave the creator alone on the board.501 /// (or an empty list) to leave the creator alone on the board.
464 #[serde(default, deserialize_with = "set_or_clear")]502 #[serde(default, deserialize_with = "set_or_clear")]
465- #[schema(value_type = Option<Vec<String>>, max_items = 50)]503+ #[schema(value_type = Option<Vec<String>>, max_items = 200)]
466 participants: Option<Option<Vec<String>>>,504 participants: Option<Option<Vec<String>>>,
467 /// Pause (`true`) or resume (`false`) drawing β€” **creator only**. Omit to505 /// Pause (`true`) or resume (`false`) drawing β€” **creator only**. Omit to
468 /// keep.506 /// keep.
@@ -514,19 +552,7 @@ async fn update_board(
514 let participants =552 let participants =
515 resolve_participants(participants, board.get_participants(), &st.db).await?;553 resolve_participants(participants, board.get_participants(), &st.db).await?;
516 board = board.set_participants(participants, &st.db).await?;554 board = board.set_participants(participants, &st.db).await?;
517- fan_out(555+ fan_out(&st, board.get_id(), participants_frame(&board));
518- &st,
519- board.get_id(),
520- json!({
521- "type": "participants",
522- "creator": board.get_creator().key(),
523- "participants": board
524- .get_participants()
525- .iter()
526- .map(|user| user.key())
527- .collect::<Vec<_>>(),
528- }),
529- );
530 }556 }
531 if let Some(locked) = req.locked {557 if let Some(locked) = req.locked {
532 board = board.set_locked(locked, user.get_id(), &st.db).await?;558 board = board.set_locked(locked, user.get_id(), &st.db).await?;
@@ -622,6 +648,198 @@ async fn close_board(
622 Ok(Json(BoardResponse::new(&board)))648 Ok(Json(BoardResponse::new(&board)))
623 }649 }
624 650
651+/// A bulk invite's source: a roster that already exists somewhere else, named
652+/// on the wire and resolved to user ids **once**, at the moment of the call.
653+/// Tagged by `kind`, the same wire shape an event audience uses.
654+///
655+/// The result is a **snapshot**, not a subscription. A board holds a flat list
656+/// of ids and nothing else β€” it does not remember it was filled from a class β€”
657+/// so a student who joins that class tomorrow is not on yesterday's board, and
658+/// nothing the class does afterwards puts back a student the creator took off.
659+/// That is the point of the shape: the roster is a list the creator owns and can
660+/// edit, and re-inviting the same source is how it is topped up (adding only who
661+/// is missing). Re-inviting *is* also what undoes a removal β€” the source still
662+/// names that student β€” so a removal is not a per-board ban; there is no
663+/// exclusion list.
664+///
665+/// Live resolution was the alternative and is rejected for this feature: it
666+/// would make [`Board::is_participant`], the board room's door and
667+/// `list_for_user` cross-table queries β€” "which boards may I open" would stop
668+/// being one indexed read β€” and it would take the per-person removal away from
669+/// the creator, which is what a whiteboard is for.
670+#[derive(Deserialize, ToSchema)]
671+#[serde(tag = "kind", rename_all = "lowercase")]
672+enum InviteSource {
673+ /// Everyone currently in this class section (şube). The homeroom teacher is
674+ /// not implied β€” the field is a label and grants nothing.
675+ Class { class: String },
676+ /// Everyone currently enrolled in this course. Clubs and study groups are
677+ /// courses (`kind` `club` / `study`), so this is how a whole club is
678+ /// invited. Staff running the course are not enrolled and so are not
679+ /// included.
680+ Course { course: String },
681+ /// The event's expected-attendee roster, exactly as `GET
682+ /// /events/{id}/roster` resolves it β€” the signup list for a registration
683+ /// event, the class or the course roster for the others. A school-wide or
684+ /// role-wide event will normally overflow the board's participant cap; that
685+ /// is a `409`, not a truncation.
686+ Event { event: String },
687+}
688+
689+impl InviteSource {
690+ /// Resolve to raw user ids, refusing a caller who may not read this roster
691+ /// in the first place.
692+ ///
693+ /// The gate is deliberately not a new permission: a board's roster is
694+ /// visible to everyone on the board, so a bulk invite *discloses* the source
695+ /// roster. Each arm therefore mirrors the gate on that roster's own listing
696+ /// route β€” teacher+ for a class (`GET /classes/{id}/members`),
697+ /// [`can_manage_course`] for a course (`GET /courses/{id}/enrollments`),
698+ /// teacher+ for an event (`GET /events/{id}/roster`). A student can still
699+ /// build a board one id at a time; they cannot dump a class roster into one.
700+ ///
701+ /// A source that does not exist is a `400` naming the field, never a `404`:
702+ /// on these routes a 404 means "no such board, or not yours", and reusing it
703+ /// here would tell a creator their own board had vanished.
704+ async fn resolve(self, user: &User, db: &Database) -> Result<Vec<UserId>, AppError> {
705+ match self {
706+ InviteSource::Class { class } => {
707+ if !user.get_role().at_least(Role::Teacher) {
708+ return Err(AppError::Forbidden(
709+ "requires teacher role or higher to invite a whole class section",
710+ ));
711+ }
712+ let class = ClassGroupId::from_key(&class);
713+ if ClassGroup::read(&class, db).await?.is_none() {
714+ return Err(AppError::Validation(ValidationError::Invalid {
715+ field: "class",
716+ reason: "no such class section",
717+ }));
718+ }
719+ Ok(ClassMember::list_for_class(&class, None, 0, db)
720+ .await?
721+ .0
722+ .iter()
723+ .map(|member| member.get_user().clone())
724+ .collect())
725+ }
726+ InviteSource::Course { course } => {
727+ let course = Course::read(&CourseId::from_key(&course), db)
728+ .await?
729+ .ok_or(AppError::Validation(ValidationError::Invalid {
730+ field: "course",
731+ reason: "no such course",
732+ }))?;
733+ if !can_manage_course(&course, user) {
734+ return Err(AppError::Forbidden(
735+ "only the course creator, an assigned teacher, or a manager/admin can invite its roster",
736+ ));
737+ }
738+ Ok(Enrollment::list_for_course(course.get_id(), None, 0, db)
739+ .await?
740+ .0
741+ .iter()
742+ .map(|enrollment| enrollment.get_user().clone())
743+ .collect())
744+ }
745+ InviteSource::Event { event } => {
746+ if !user.get_role().at_least(Role::Teacher) {
747+ return Err(AppError::Forbidden(
748+ "requires teacher role or higher to invite an event's roster",
749+ ));
750+ }
751+ let event = Event::read(&EventId::from_key(&event), db).await?.ok_or(
752+ AppError::Validation(ValidationError::Invalid {
753+ field: "event",
754+ reason: "no such event",
755+ }),
756+ )?;
757+ event.get_audience().members(event.get_id(), db).await
758+ }
759+ }
760+ }
761+}
762+
763+/// Invite a whole roster at once β€” creator only, and additive: everyone the
764+/// source names is **added** to the invite list, nobody is ever removed by it.
765+/// Re-inviting the same source is therefore how a board is topped up after the
766+/// class gained a student, and it is idempotent when nothing changed.
767+///
768+/// The ids are resolved once, here. The board keeps a flat list and no memory
769+/// of where it came from, so the roster does not track the source afterwards β€”
770+/// see [`InviteSource`] for why. Removal stays `PATCH /boards/{id}`: send the
771+/// roster you want.
772+///
773+/// Three filters run on the resolved list before it lands, and all three are
774+/// silent β€” a source is a whole group, and one ineligible member must not fail
775+/// the invite for the other twenty-nine:
776+/// - ids that no longer resolve to a user row are dropped,
777+/// - anyone below the student role is dropped, which is what keeps `parent` off
778+/// the whiteboard by the same cut [`resolve_participants`] makes,
779+/// - anyone already on the board (the creator included) is not added twice.
780+///
781+/// The cap is **all-or-nothing**: if the union would exceed
782+/// `max_participants` (`GET /limits`) the whole invite is refused with a `409`
783+/// naming the two numbers, and the roster is left exactly as it was. A partial
784+/// invite would silently pick which half of a class gets to draw.
785+#[utoipa::path(
786+ post,
787+ path = "/{id}/invite",
788+ tag = "boards",
789+ security(("session_cookie" = [])),
790+ params(("id" = String, Path, description = "Board id")),
791+ request_body = InviteSource,
792+ responses(
793+ (status = 200, description = "The board with the widened roster", body = BoardResponse),
794+ (status = 400, description = "The named class, course or event does not exist", body = ErrorResponse),
795+ (status = 401, description = "Not authenticated", body = ErrorResponse),
796+ (status = 403, description = "Not the board's creator, or not allowed to read that roster", body = ErrorResponse),
797+ (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),
798+ (status = 409, description = "The invite would put the board over its participant cap; nobody was added", body = ErrorResponse),
799+ (status = 422, description = "The body does not fit this request: an unknown or missing `kind`, or the field that `kind` requires is absent"),
800+ ),
801+)]
802+async fn invite_board(
803+ State(st): State<AppState>,
804+ CurrentUser(user): CurrentUser,
805+ Path(id): Path<String>,
806+ Json(req): Json<InviteSource>,
807+) -> Result<Json<BoardResponse>, AppError> {
808+ let board = board_for(&id, &user, &st.db).await?;
809+ ensure_creator(&board, &user)?;
810+ let invited = req.resolve(&user, &st.db).await?;
811+
812+ // One read for the whole group. The filters below are silent on purpose β€”
813+ // a source is a whole group, and one member who has left or was never
814+ // eligible must not fail the invite for the other twenty-nine.
815+ let mut roster = board.get_participants().to_vec();
816+ for candidate in User::list_by_ids(&invited, &st.db).await? {
817+ if !candidate.get_role().at_least(Role::Student) {
818+ continue;
819+ }
820+ // The creator is a participant by construction and never sits in the
821+ // array; adding them there would spend a seat on someone who already
822+ // has access.
823+ if candidate.get_id() == board.get_creator() || roster.contains(candidate.get_id()) {
824+ continue;
825+ }
826+ roster.push(candidate.get_id().clone());
827+ }
828+
829+ if roster.len() > MAX_BOARD_PARTICIPANTS {
830+ return Err(AppError::ConflictOwned(format!(
831+ "this invite would put the board at {} participants, over the limit of {MAX_BOARD_PARTICIPANTS}; nobody was added",
832+ roster.len()
833+ )));
834+ }
835+ // Unchanged rosters still write and still fan out: the alternative is a
836+ // branch that has to prove the two lists are equal, and a re-invite that
837+ // added nobody is the idempotent case, not the hot path.
838+ let board = board.set_participants(roster, &st.db).await?;
839+ fan_out(&st, board.get_id(), participants_frame(&board));
840+ Ok(Json(BoardResponse::new(&board)))
841+}
842+
625 /// Delete the board and its whole stroke history β€” creator only, and the one843 /// Delete the board and its whole stroke history β€” creator only, and the one
626 /// operation in this system that really destroys marks (a clear never does).844 /// operation in this system that really destroys marks (a clear never does).
627 /// It also frees the creator's board seat. Use `/close` to retire a board while845 /// It also frees the creator's board seat. Use `/close` to retire a board while
tests/board_invite.rsadded+548 -0
@@ -0,0 +1,548 @@
1+//! `POST /boards/{id}/invite` β€” filling a whiteboard's roster from a group that
2+//! already exists (a class section, a course/club, an event's roster) instead of
3+//! one id at a time.
4+//!
5+//! The invariants pinned here are the ones the feature would be wrong without:
6+//! the expansion is a **snapshot** and not a subscription, it only ever **adds**,
7+//! the participant cap is **all-or-nothing**, ineligible members are dropped
8+//! **silently** while the whole call still succeeds, and β€” because a board's
9+//! roster is visible to everyone on the board β€” each source carries the gate its
10+//! own listing route carries, so bulk invite cannot become a roster-disclosure
11+//! oracle for a student.
12+
13+mod common;
14+
15+use axum::http::StatusCode;
16+use common::{Res, app_and_db, create_course, enroll, login, login_as, me_id, send};
17+use hezarfen_backend::constant::MAX_BOARD_PARTICIPANTS;
18+use hezarfen_backend::domain::board::BoardId;
19+use hezarfen_backend::domain::user::UserId;
20+use serde_json::{Value, json};
21+
22+/// Open a board as `cookie`; returns its id.
23+async fn a_board(app: &axum::Router, cookie: &str) -> String {
24+ let res = send(
25+ app,
26+ "POST",
27+ "/boards",
28+ Some(cookie),
29+ Some(json!({ "title": "Tahta" })),
30+ )
31+ .await;
32+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
33+ res.body["id"].as_str().unwrap().to_string()
34+}
35+
36+async fn invite(app: &axum::Router, cookie: &str, board: &str, source: Value) -> Res {
37+ send(
38+ app,
39+ "POST",
40+ &format!("/boards/{board}/invite"),
41+ Some(cookie),
42+ Some(source),
43+ )
44+ .await
45+}
46+
47+/// The roster as the *server* holds it, read back off `GET /boards/{id}` rather
48+/// than trusted from the invite's own reply.
49+async fn roster(app: &axum::Router, cookie: &str, board: &str) -> Vec<String> {
50+ let res = send(app, "GET", &format!("/boards/{board}"), Some(cookie), None).await;
51+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
52+ let mut ids: Vec<String> = res.body["participants"]
53+ .as_array()
54+ .expect("participants array")
55+ .iter()
56+ .map(|id| id.as_str().unwrap().to_string())
57+ .collect();
58+ ids.sort();
59+ ids
60+}
61+
62+/// A class section with `members` in it, created by `manager`.
63+async fn a_class(app: &axum::Router, manager: &str, name: &str, members: &[&str]) -> String {
64+ let res = send(
65+ app,
66+ "POST",
67+ "/classes",
68+ Some(manager),
69+ Some(json!({ "name": name })),
70+ )
71+ .await;
72+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
73+ let class = res.body["id"].as_str().unwrap().to_string();
74+ for user in members {
75+ let res = send(
76+ app,
77+ "POST",
78+ &format!("/classes/{class}/members"),
79+ Some(manager),
80+ Some(json!({ "user_id": user })),
81+ )
82+ .await;
83+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
84+ }
85+ class
86+}
87+
88+/// The headline case: a teacher fills a board with a whole class in one call,
89+/// and the expansion is a snapshot β€” a student who joins the class *after* the
90+/// invite is not on the board until someone invites the class again, and that
91+/// re-invite adds only the person who was missing.
92+#[tokio::test]
93+async fn a_class_invite_fills_the_roster_and_re_inviting_tops_it_up() {
94+ let (app, db) = app_and_db().await;
95+ let manager = login_as(&app, &db, "manager_a", "manager").await;
96+ let teacher = login_as(&app, &db, "teacher_a", "teacher").await;
97+ let ali = login(&app, "ali").await;
98+ let ayse = login(&app, "ayse").await;
99+ let deniz = login(&app, "deniz").await;
100+ let (ali_id, ayse_id, deniz_id) = (
101+ me_id(&app, &ali).await,
102+ me_id(&app, &ayse).await,
103+ me_id(&app, &deniz).await,
104+ );
105+
106+ let class = a_class(&app, &manager, "9-A", &[&ali_id, &ayse_id]).await;
107+ let board = a_board(&app, &teacher).await;
108+
109+ let res = invite(
110+ &app,
111+ &teacher,
112+ &board,
113+ json!({"kind": "class", "class": class}),
114+ )
115+ .await;
116+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
117+
118+ let mut expected = vec![ali_id.clone(), ayse_id.clone()];
119+ expected.sort();
120+ assert_eq!(
121+ roster(&app, &teacher, &board).await,
122+ expected,
123+ "the whole class should be on the board"
124+ );
125+
126+ // The class gains a student. The board is a snapshot, so nothing happens to
127+ // it β€” this is the assertion that separates this design from a live roster.
128+ let res = send(
129+ &app,
130+ "POST",
131+ &format!("/classes/{class}/members"),
132+ Some(&manager),
133+ Some(json!({ "user_id": deniz_id })),
134+ )
135+ .await;
136+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
137+ assert_eq!(
138+ roster(&app, &teacher, &board).await,
139+ expected,
140+ "a snapshot must not follow the class; the new member appeared on the board by itself"
141+ );
142+
143+ // Re-inviting the same source tops it up, adding only who is missing.
144+ let res = invite(
145+ &app,
146+ &teacher,
147+ &board,
148+ json!({"kind": "class", "class": class}),
149+ )
150+ .await;
151+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
152+ let mut topped = vec![ali_id, ayse_id, deniz_id];
153+ topped.sort();
154+ assert_eq!(
155+ roster(&app, &teacher, &board).await,
156+ topped,
157+ "a re-invite should add the missing member and duplicate nobody"
158+ );
159+}
160+
161+/// "Invite the whole club" is the course form β€” a club is a course whose `kind`
162+/// is `club`, so the club case needs no source of its own. The same call also
163+/// pins the two things an invite must never do: remove anybody, or spend a seat
164+/// on the creator (who is a participant by construction and never sits in the
165+/// array).
166+#[tokio::test]
167+async fn a_club_invite_adds_its_members_without_removing_a_hand_invited_one() {
168+ let (app, db) = app_and_db().await;
169+ let teacher = login_as(&app, &db, "teacher_b", "teacher").await;
170+ let teacher_id = me_id(&app, &teacher).await;
171+ let ali = login(&app, "ali").await;
172+ let ayse = login(&app, "ayse").await;
173+ let hakan = login(&app, "hakan").await;
174+ let (ali_id, ayse_id, hakan_id) = (
175+ me_id(&app, &ali).await,
176+ me_id(&app, &ayse).await,
177+ me_id(&app, &hakan).await,
178+ );
179+
180+ let res = send(
181+ &app,
182+ "POST",
183+ "/courses",
184+ Some(&teacher),
185+ Some(json!({ "title": "SatranΓ§ KulΓΌbΓΌ", "kind": "club" })),
186+ )
187+ .await;
188+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
189+ let club = res.body["id"].as_str().unwrap().to_string();
190+ enroll(&app, &teacher, &club, &ali_id).await;
191+ enroll(&app, &teacher, &club, &ayse_id).await;
192+
193+ // Hakan is not in the club β€” he was invited by hand, and the club invite
194+ // must leave him alone.
195+ let res = send(
196+ &app,
197+ "POST",
198+ "/boards",
199+ Some(&teacher),
200+ Some(json!({ "title": "Açılış", "participants": [hakan_id] })),
201+ )
202+ .await;
203+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
204+ let board = res.body["id"].as_str().unwrap().to_string();
205+
206+ let res = invite(
207+ &app,
208+ &teacher,
209+ &board,
210+ json!({"kind": "course", "course": club}),
211+ )
212+ .await;
213+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
214+
215+ let mut expected = vec![ali_id, ayse_id, hakan_id];
216+ expected.sort();
217+ let seen = roster(&app, &teacher, &board).await;
218+ assert_eq!(
219+ seen, expected,
220+ "an invite adds; it must never drop the hand-invited participant"
221+ );
222+ assert!(
223+ !seen.contains(&teacher_id),
224+ "the creator is a participant by construction and must not take a seat in the array: {seen:?}"
225+ );
226+}
227+
228+/// An event source resolves whatever `GET /events/{id}/roster` resolves, and the
229+/// role filter runs over the result: a `parent`-role event names only parents,
230+/// and the whiteboard admits none of them. The call still succeeds β€” a source is
231+/// a whole group, and dropping its ineligible members must not fail it.
232+#[tokio::test]
233+async fn parents_in_a_source_are_dropped_silently_and_the_invite_still_succeeds() {
234+ let (app, db) = app_and_db().await;
235+ let teacher = login_as(&app, &db, "teacher_c", "teacher").await;
236+ let _veli = login_as(&app, &db, "veli", "parent").await;
237+
238+ let res = send(
239+ &app,
240+ "POST",
241+ "/events",
242+ Some(&teacher),
243+ Some(json!({ "title": "Veli toplantΔ±sΔ±", "audience": {"kind": "role", "role": "parent"} })),
244+ )
245+ .await;
246+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
247+ let event = res.body["id"].as_str().unwrap().to_string();
248+
249+ let board = a_board(&app, &teacher).await;
250+ let res = invite(
251+ &app,
252+ &teacher,
253+ &board,
254+ json!({"kind": "event", "event": event}),
255+ )
256+ .await;
257+ assert_eq!(
258+ res.status,
259+ StatusCode::OK,
260+ "an all-parent source must be a successful no-op, not an error: {}",
261+ res.body
262+ );
263+ assert!(
264+ roster(&app, &teacher, &board).await.is_empty(),
265+ "a parent reached a whiteboard roster through bulk invite"
266+ );
267+}
268+
269+/// A member the source still names but whose user row is gone is dropped the
270+/// same silent way β€” the batch lookup simply does not return them.
271+#[tokio::test]
272+async fn a_deleted_user_in_a_source_is_dropped() {
273+ let (app, db) = app_and_db().await;
274+ let teacher = login_as(&app, &db, "teacher_d", "teacher").await;
275+ let ali = login(&app, "ali").await;
276+ let ghost = login(&app, "ghost").await;
277+ let (ali_id, ghost_id) = (me_id(&app, &ali).await, me_id(&app, &ghost).await);
278+
279+ let course = create_course(&app, &teacher, "Fizik").await;
280+ enroll(&app, &teacher, &course, &ali_id).await;
281+ enroll(&app, &teacher, &course, &ghost_id).await;
282+
283+ // The row goes without the cascade a real DELETE runs, which is exactly the
284+ // state a stale enrollment leaves behind.
285+ db.query("DELETE type::record('user', $key)")
286+ .bind(("key", ghost_id.clone()))
287+ .await
288+ .unwrap()
289+ .check()
290+ .unwrap();
291+
292+ let board = a_board(&app, &teacher).await;
293+ let res = invite(
294+ &app,
295+ &teacher,
296+ &board,
297+ json!({"kind": "course", "course": course}),
298+ )
299+ .await;
300+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
301+ assert_eq!(
302+ roster(&app, &teacher, &board).await,
303+ vec![ali_id],
304+ "a deleted user must not be written onto a roster"
305+ );
306+}
307+
308+/// The cap is all-or-nothing. A partial invite would silently pick which half of
309+/// a class gets to draw, so an invite that would carry the board past
310+/// `max_participants` is refused whole and leaves the roster untouched.
311+#[tokio::test]
312+async fn an_over_cap_invite_is_refused_whole_and_changes_nothing() {
313+ let (app, db) = app_and_db().await;
314+ let manager = login_as(&app, &db, "manager_e", "manager").await;
315+ let teacher = login_as(&app, &db, "teacher_e", "teacher").await;
316+ let ali = login(&app, "ali").await;
317+ let ali_id = me_id(&app, &ali).await;
318+
319+ let class = a_class(&app, &manager, "9-B", &[&ali_id]).await;
320+ let board = a_board(&app, &teacher).await;
321+
322+ // Fill the roster to the brim directly: reaching the cap through the API
323+ // would mean registering two hundred accounts to prove an arithmetic guard.
324+ // The ids need not resolve β€” the roster is only repaired at boot, and the
325+ // guard under test counts entries.
326+ let full: Vec<_> = (0..MAX_BOARD_PARTICIPANTS)
327+ .map(|n| UserId::from_key(&format!("filler{n}")).record())
328+ .collect();
329+ db.query("UPDATE $b SET participants = $who")
330+ .bind(("b", BoardId::from_key(&board).record()))
331+ .bind(("who", full))
332+ .await
333+ .unwrap()
334+ .check()
335+ .unwrap();
336+ let before = roster(&app, &teacher, &board).await;
337+ assert_eq!(before.len(), MAX_BOARD_PARTICIPANTS);
338+
339+ let res = invite(
340+ &app,
341+ &teacher,
342+ &board,
343+ json!({"kind": "class", "class": class}),
344+ )
345+ .await;
346+ assert_eq!(
347+ res.status,
348+ StatusCode::CONFLICT,
349+ "one member over the cap must be a 409: {}",
350+ res.body
351+ );
352+ assert_eq!(
353+ roster(&app, &teacher, &board).await,
354+ before,
355+ "a refused invite must leave the roster byte-identical"
356+ );
357+}
358+
359+/// The disclosure gate. A board's roster is visible to every participant, so
360+/// inviting a group hands that group's membership to everyone on the board β€”
361+/// which makes bulk invite a *read* of the source roster, and it must carry the
362+/// same gate that roster's own listing route carries. A student can still build
363+/// a board one id at a time; they cannot pour a class into one.
364+#[tokio::test]
365+async fn a_student_cannot_use_bulk_invite_as_a_class_roster_oracle() {
366+ let (app, db) = app_and_db().await;
367+ let manager = login_as(&app, &db, "manager_f", "manager").await;
368+ let ali = login(&app, "ali").await;
369+ let ayse = login(&app, "ayse").await;
370+ let (ali_id, ayse_id) = (me_id(&app, &ali).await, me_id(&app, &ayse).await);
371+
372+ let class = a_class(&app, &manager, "9-C", &[&ali_id, &ayse_id]).await;
373+ // Ali is *in* the class, and still may not dump it onto his own board.
374+ let board = a_board(&app, &ali).await;
375+
376+ let res = invite(&app, &ali, &board, json!({"kind": "class", "class": class})).await;
377+ assert_eq!(
378+ res.status,
379+ StatusCode::FORBIDDEN,
380+ "a student expanded a class roster: {}",
381+ res.body
382+ );
383+ assert!(roster(&app, &ali, &board).await.is_empty(), "{}", res.body);
384+}
385+
386+/// The course arm's gate is narrower than teacher+: a teacher who neither
387+/// created the course nor was assigned to it cannot read its roster, so they
388+/// cannot invite it either. The course's own teacher can.
389+#[tokio::test]
390+async fn a_teacher_who_does_not_run_the_course_cannot_invite_its_roster() {
391+ let (app, db) = app_and_db().await;
392+ let owner = login_as(&app, &db, "teacher_g", "teacher").await;
393+ let outsider = login_as(&app, &db, "teacher_h", "teacher").await;
394+ let ali = login(&app, "ali").await;
395+ let ali_id = me_id(&app, &ali).await;
396+
397+ let course = create_course(&app, &owner, "Kimya").await;
398+ enroll(&app, &owner, &course, &ali_id).await;
399+
400+ let their_board = a_board(&app, &outsider).await;
401+ let res = invite(
402+ &app,
403+ &outsider,
404+ &their_board,
405+ json!({"kind": "course", "course": course}),
406+ )
407+ .await;
408+ assert_eq!(
409+ res.status,
410+ StatusCode::FORBIDDEN,
411+ "an unrelated teacher read a course roster through an invite: {}",
412+ res.body
413+ );
414+
415+ let own_board = a_board(&app, &owner).await;
416+ let res = invite(
417+ &app,
418+ &owner,
419+ &own_board,
420+ json!({"kind": "course", "course": course}),
421+ )
422+ .await;
423+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
424+ assert_eq!(roster(&app, &owner, &own_board).await, vec![ali_id]);
425+}
426+
427+/// The board's own two-tier answer, unchanged by the new route: an outsider is
428+/// told the board does not exist, a participant who is not the creator is told
429+/// it is not theirs to command.
430+#[tokio::test]
431+async fn a_participant_gets_403_and_an_outsider_gets_404() {
432+ let (app, db) = app_and_db().await;
433+ let manager = login_as(&app, &db, "manager_i", "manager").await;
434+ let creator = login_as(&app, &db, "teacher_i", "teacher").await;
435+ let other = login_as(&app, &db, "teacher_j", "teacher").await;
436+ let stranger = login_as(&app, &db, "teacher_k", "teacher").await;
437+ let other_id = me_id(&app, &other).await;
438+
439+ let class = a_class(&app, &manager, "9-D", &[]).await;
440+ let res = send(
441+ &app,
442+ "POST",
443+ "/boards",
444+ Some(&creator),
445+ Some(json!({ "title": "Tahta", "participants": [other_id] })),
446+ )
447+ .await;
448+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
449+ let board = res.body["id"].as_str().unwrap().to_string();
450+
451+ let res = invite(
452+ &app,
453+ &other,
454+ &board,
455+ json!({"kind": "class", "class": class.clone()}),
456+ )
457+ .await;
458+ assert_eq!(
459+ res.status,
460+ StatusCode::FORBIDDEN,
461+ "a participant who is not the creator: {}",
462+ res.body
463+ );
464+
465+ let res = invite(
466+ &app,
467+ &stranger,
468+ &board,
469+ json!({"kind": "class", "class": class}),
470+ )
471+ .await;
472+ assert_eq!(
473+ res.status,
474+ StatusCode::NOT_FOUND,
475+ "an outsider must not learn the board exists: {}",
476+ res.body
477+ );
478+}
479+
480+/// A source that does not exist is a `400` naming the field it came in on β€”
481+/// never a `404`, which on these routes means "no such board, or not yours" and
482+/// would tell a creator their own board had vanished.
483+#[tokio::test]
484+async fn an_unknown_source_is_a_400_and_not_the_boards_404() {
485+ let (app, db) = app_and_db().await;
486+ let teacher = login_as(&app, &db, "teacher_l", "teacher").await;
487+ let board = a_board(&app, &teacher).await;
488+
489+ for (source, field) in [
490+ (
491+ json!({"kind": "class", "class": "01J8XZ0K3Q8G7X2M4N5P6R7S8T"}),
492+ "class",
493+ ),
494+ (
495+ json!({"kind": "course", "course": "01J8XZ0K3Q8G7X2M4N5P6R7S8T"}),
496+ "course",
497+ ),
498+ (
499+ json!({"kind": "event", "event": "01J8XZ0K3Q8G7X2M4N5P6R7S8T"}),
500+ "event",
501+ ),
502+ ] {
503+ let res = invite(&app, &teacher, &board, source).await;
504+ assert_eq!(
505+ res.status,
506+ StatusCode::BAD_REQUEST,
507+ "a missing {field} must not borrow the board's 404: {}",
508+ res.body
509+ );
510+ assert!(
511+ res.body.to_string().contains(field),
512+ "the 400 should name the field that was wrong: {}",
513+ res.body
514+ );
515+ }
516+}
517+
518+/// The reply is the board itself, so a client never has to re-fetch to learn who
519+/// it just added. (That the live room is *told* as well is an end-to-end matter
520+/// and is pinned over a real socket in `e2e.rs`.)
521+#[tokio::test]
522+async fn the_reply_carries_the_widened_roster() {
523+ let (app, db) = app_and_db().await;
524+ let manager = login_as(&app, &db, "manager_m", "manager").await;
525+ let teacher = login_as(&app, &db, "teacher_m", "teacher").await;
526+ let ali = login(&app, "ali").await;
527+ let ali_id = me_id(&app, &ali).await;
528+
529+ let class = a_class(&app, &manager, "9-E", &[&ali_id]).await;
530+ let board = a_board(&app, &teacher).await;
531+ let res = invite(
532+ &app,
533+ &teacher,
534+ &board,
535+ json!({"kind": "class", "class": class}),
536+ )
537+ .await;
538+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
539+
540+ // The reply is the board, so the roster the room is told about and the
541+ // roster the caller is shown are the same list.
542+ assert_eq!(
543+ res.body["participants"],
544+ json!([ali_id]),
545+ "the invite's own reply must carry the widened roster: {}",
546+ res.body
547+ );
548+}
tests/e2e.rsmodified+76 -0
@@ -2709,6 +2709,82 @@ async fn a_removed_participant_can_no_longer_draw() {
2709 }2709 }
2710 }2710 }
2711 2711
2712+/// A bulk invite (`POST /boards/{id}/invite`) must reach the live room like any
2713+/// other roster change. The room authorizes every delivery against the roster it
2714+/// is told about, so a path that widens the array and stays silent leaves the
2715+/// new participant unrenderable to the people already drawing β€” and this one is
2716+/// easy to forget precisely because it only ever *adds*, so it can never trip
2717+/// the removal test above.
2718+#[tokio::test]
2719+async fn a_bulk_invite_announces_the_widened_roster_to_the_room() {
2720+ let room = board_room_fixture().await;
2721+ let (base, board) = (room.base.as_str(), room.board_id.as_str());
2722+ // The invite gates are teacher+, and the fixture's creator is a student.
2723+ promote(&room.db, "ali", "teacher").await;
2724+
2725+ let mut veli = board_open(base, board, Some(&room.veli_cookie))
2726+ .await
2727+ .expect("invited");
2728+ board_join(&mut veli, None, None).await;
2729+
2730+ // A school-wide event resolves to every account, which here is the three the
2731+ // fixture registered β€” so the invite adds exactly the outsider, ayşe.
2732+ let res = room
2733+ .creator
2734+ .post(format!("{base}/events"))
2735+ .json(&json!({ "title": "TΓΌm okul" }))
2736+ .send()
2737+ .await
2738+ .unwrap();
2739+ assert_eq!(res.status(), StatusCode::CREATED);
2740+ let event: Value = res.json().await.unwrap();
2741+ let event_id = event["id"].as_str().unwrap().to_string();
2742+
2743+ let res = room
2744+ .creator
2745+ .post(format!("{base}/boards/{board}/invite"))
2746+ .json(&json!({ "kind": "event", "event": event_id }))
2747+ .send()
2748+ .await
2749+ .unwrap();
2750+ assert_eq!(res.status(), StatusCode::OK);
2751+ let widened: Value = res.json().await.unwrap();
2752+
2753+ let frame = board_frame_of_type(&mut veli, "participants").await;
2754+ let announced = frame["participants"].as_array().unwrap();
2755+ assert!(
2756+ announced.iter().any(|id| id == &json!(room.veli_id)),
2757+ "the standing participant must still be on the announced roster: {frame}"
2758+ );
2759+ assert_eq!(
2760+ announced.len(),
2761+ 2,
2762+ "the outsider should have been added and announced: {frame}"
2763+ );
2764+ // The wire and the reply are the same list, and the creator is in neither
2765+ // array β€” they are a participant by construction.
2766+ let mut from_frame: Vec<&Value> = announced.iter().collect();
2767+ let served = widened["participants"].as_array().unwrap();
2768+ let mut from_body: Vec<&Value> = served.iter().collect();
2769+ from_frame.sort_by_key(|id| id.as_str().unwrap());
2770+ from_body.sort_by_key(|id| id.as_str().unwrap());
2771+ assert_eq!(from_frame, from_body, "{frame} vs {widened}");
2772+ assert_eq!(frame["creator"], widened["creator"], "{frame}");
2773+
2774+ // The stored row is the authority β€” the mem engine forges write wins, so a
2775+ // frame alone proves only that the server said something.
2776+ let stored: Value = room
2777+ .creator
2778+ .get(format!("{base}/boards/{board}"))
2779+ .send()
2780+ .await
2781+ .unwrap()
2782+ .json()
2783+ .await
2784+ .unwrap();
2785+ assert_eq!(stored["participants"], widened["participants"]);
2786+}
2787+
2712 /// Test 8 β€” `client_seq` is the client's correlation id and is echoed2788 /// Test 8 β€” `client_seq` is the client's correlation id and is echoed
2713 /// verbatim, including a value no `i32` holds; a message without one gets a2789 /// verbatim, including a value no `i32` holds; a message without one gets a
2714 /// reply without the key at all. Kills the "helpfully normalize it" bug that2790 /// reply without the key at all. Kills the "helpfully normalize it" bug that