forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

boards.rs788 lines, 35.2 KiBHistoryRawDownload
1//! The whiteboard's HTTP surface: open a board, read its roster, its live
2//! canvas and its whole history, and run the creator's four commands (clear,
3//! lock, close, delete). Live drawing itself rides the board-room WebSocket
4//! next door; everything here is the REST half it sits beside.
5//!
6//! The permission model is a role bar plus two predicates
7//! (student-and-above, then [`Board::is_participant`], [`Board::is_creator`]),
8//! applied in one order on
9//! every route: a non-participant gets a **404** even for a board that plainly
10//! exists (a 403 would confirm it — see the rationale at `src/lib.rs`), while a
11//! participant who is not the creator gets a **403** on the four commands. They
12//! are already rendering the board and its strokes, so hiding it from them
13//! there would be a lie their client cannot act on (same two-tier line as
14//! [`super::homework`]).
15//!
16//! Every mutation a live room must notice ends in a `board_hub` publish, and
17//! one of them is a permission fix rather than a nicety: a participant dropped
18//! mid-session keeps drawing over an already-open socket until the room hears
19//! about it, so a roster change *must* fan out.
20
21use crate::web::tenant_state::{SchoolIdCookie, State};
22use axum::Json;
23use axum::extract::{Path, Query};
24use axum::http::StatusCode;
25use serde::{Deserialize, Serialize};
26use serde_json::json;
27use utoipa::ToSchema;
28use utoipa_axum::router::OpenApiRouter;
29use utoipa_axum::routes;
30
31use crate::database::Database;
32use crate::domain::board::{Board, BoardId, BoardTitle};
33use crate::domain::board_stroke::BoardStroke;
34use crate::domain::class_group::ClassGroupId;
35use crate::domain::course::CourseId;
36use crate::domain::event::EventId;
37use crate::domain::role::Role;
38use crate::domain::user::{User, UserId};
39use crate::error::{AppError, ErrorResponse, ValidationError};
40use crate::service::course::can_manage_course;
41use crate::service::{board, board_stroke};
42use crate::state::AppState;
43use crate::tenant::SchoolId;
44
45use super::{CurrentUser, Page, PageParams, RequireStudent, paginate, set_or_clear};
46
47pub fn routes() -> OpenApiRouter<AppState> {
48 OpenApiRouter::new()
49 // Plain route: OpenApiRouter can't describe a WebSocket upgrade, so
50 // the board room lives outside the generated spec (see the `boards`
51 // tag description and README for the protocol).
52 .route("/{id}/ws", axum::routing::get(super::board_ws::board_ws))
53 .routes(routes!(create_board, list_boards))
54 .routes(routes!(get_board, update_board, delete_board))
55 .routes(routes!(list_strokes))
56 .routes(routes!(list_history))
57 .routes(routes!(list_epochs))
58 .routes(routes!(clear_board))
59 .routes(routes!(close_board))
60 .routes(routes!(invite_board))
61}
62
63/// Push one frame to whoever is in the room right now. An empty room is the
64/// normal case, not a failure.
65fn fan_out(st: &AppState, school: &SchoolId, board: &BoardId, frame: serde_json::Value) {
66 st.board_hub.publish(school, &board.key(), frame.to_string());
67}
68
69/// The roster frame every path that changes the invite list must publish. A
70/// participant dropped from the array keeps drawing over the socket they
71/// already hold until the room hears this, so it is a permission fix rather
72/// than a notification.
73fn participants_frame(board: &Board) -> serde_json::Value {
74 json!({
75 "type": "participants",
76 "creator": board.get_creator().key(),
77 "participants": board
78 .get_participants()
79 .iter()
80 .map(|user| user.key())
81 .collect::<Vec<_>>(),
82 })
83}
84
85#[derive(Serialize, ToSchema)]
86struct BoardResponse {
87 id: String,
88 title: String,
89 /// The creator: draws, and is the only one who may clear, lock, close or
90 /// delete. Always a participant without appearing in `participants`.
91 creator: String,
92 /// The invited user ids. Everyone here draws.
93 participants: Vec<String>,
94 /// Drawing is paused while `true`; the creator toggles it.
95 locked: bool,
96 locked_by: Option<String>,
97 /// UTC unix-milliseconds, `null` while unlocked.
98 locked_at: Option<i64>,
99 /// The live canvas' generation. A clear bumps it; strokes from earlier
100 /// epochs stay stored and replayable through `/history`.
101 epoch: i64,
102 /// Stamped when the board was closed — by its creator or by the lifetime
103 /// stroke cap. A closed board is permanently read-only, never deleted.
104 closed_at: Option<i64>,
105 created_at: i64,
106}
107
108impl BoardResponse {
109 fn new(board: &Board) -> Self {
110 Self {
111 id: board.get_id().key().to_string(),
112 title: board.get_title().as_str().to_string(),
113 creator: board.get_creator().key().to_string(),
114 participants: board
115 .get_participants()
116 .iter()
117 .map(|user| user.key().to_string())
118 .collect(),
119 locked: board.is_locked(),
120 locked_by: board.get_locked_by().map(|user| user.key().to_string()),
121 locked_at: board.get_locked_at().map(|at| at.as_millis()),
122 epoch: board.get_epoch(),
123 closed_at: board.get_closed_at().map(|at| at.as_millis()),
124 created_at: board.get_created_at().as_millis(),
125 }
126 }
127}
128
129/// One row of the append-only stroke log. Both kinds ride this shape: a
130/// `stroke` carries `payload`, a `clear` marker carries `count` — the final
131/// stroke count of the epoch it closed — and never the other way round.
132#[derive(Serialize, ToSchema)]
133struct StrokeResponse {
134 id: String,
135 author: String,
136 /// `stroke` or `clear`.
137 kind: String,
138 /// The client's serialized mark. `null` on a `clear` marker.
139 payload: Option<String>,
140 /// The closed epoch's final stroke count. Present only on a `clear`.
141 count: Option<i64>,
142 epoch: i64,
143 created_at: i64,
144}
145
146impl StrokeResponse {
147 fn new(stroke: &BoardStroke) -> Self {
148 Self {
149 id: stroke.get_id().key().to_string(),
150 author: stroke.get_author().key().to_string(),
151 kind: stroke.get_kind().to_string(),
152 payload: stroke.get_payload().map(str::to_string),
153 count: stroke.get_count(),
154 epoch: stroke.get_epoch(),
155 created_at: stroke.get_created_at().as_millis(),
156 }
157 }
158}
159
160/// `deny_unknown_fields` on both board request bodies is deliberate: this DTO
161/// used to spell the roster `participant_ids` while the response and the PATCH
162/// spelled it `participants`, so a client posting a board it had just read got
163/// a `201` with a silently empty roster. A misspelled field is now refused
164/// instead of dropped.
165#[derive(Deserialize, ToSchema)]
166#[serde(deny_unknown_fields)]
167struct CreateBoard {
168 #[schema(max_length = 200)]
169 title: String,
170 /// Who may draw, besides the creator. Omit or send an empty list to open a
171 /// board alone and invite later.
172 #[schema(max_items = 200)]
173 participants: Option<Vec<String>>,
174}
175
176/// Open a whiteboard. The caller becomes its creator — the only one who may
177/// clear, lock, close or delete it — and everyone named in `participants`
178/// may draw on it. Student and above: the `parent` role has no whiteboard
179/// access at all, neither as a creator nor as a participant. `409` once the
180/// caller holds `max_boards_per_creator` boards (`GET /limits`); delete one to
181/// free a seat.
182#[utoipa::path(
183 post,
184 path = "/",
185 tag = "boards",
186 security(("session_cookie" = [])),
187 request_body = CreateBoard,
188 responses(
189 (status = 201, description = "The new board", body = BoardResponse),
190 (status = 400, description = "Invalid title, or a participant list that is too long, names an unknown user, or names a parent", body = ErrorResponse),
191 (status = 401, description = "Not authenticated", body = ErrorResponse),
192 (status = 403, description = "The caller is a parent", body = ErrorResponse),
193 (status = 409, description = "The caller already holds the maximum number of boards", body = ErrorResponse),
194 (status = 422, description = "The body does not fit this request: a field has the wrong type, a required field is missing, or it carries a key this request does not accept — a board response cannot be posted back verbatim"),
195 ),
196)]
197async fn create_board(
198 State(st): State<AppState>,
199 RequireStudent(user): RequireStudent,
200 Json(req): Json<CreateBoard>,
201) -> Result<(StatusCode, Json<BoardResponse>), AppError> {
202 let title = BoardTitle::try_new(&req.title)?;
203 // No roster yet, so nothing is grandfathered: every id must qualify.
204 let participants = board::resolve_participants(req.participants, &[], &st.db).await?;
205 let board = board::create(&st.db, user.get_id(), title, participants).await?;
206 Ok((StatusCode::CREATED, Json(BoardResponse::new(&board))))
207}
208
209#[derive(Deserialize, utoipa::IntoParams)]
210struct ListFilter {
211 /// Narrow by `closed_at`: `true` = still open, `false` = closed only. Omit
212 /// for both. A closed board is never deleted, so this is how a heavy
213 /// creator trims a list of retired boards.
214 open: Option<bool>,
215 /// Free-text search over the title: a case- and diacritic-insensitive
216 /// substring (`geometri` finds `Geometri`). Literal text — `%` and `_`
217 /// carry no special meaning. Blank means no search.
218 #[param(example = "geometri")]
219 q: Option<String>,
220}
221
222/// Every board the caller may open — the ones they created and the ones they
223/// were invited to — newest first. `?open=` narrows by the closed flag, and
224/// `total` counts the filtered list. Paged via `?limit=&offset=` (omit `limit`
225/// for all of them).
226///
227/// `?open=true` means "not closed", nothing more: a **locked** board, and one
228/// that has spent its lifetime stroke budget but was never drawn on again, are
229/// both still open — the closing stamp is only ever written by `/close` or by
230/// the append that the lifetime cap refuses.
231///
232/// `?q=` narrows further by title: a case- and diacritic-insensitive
233/// substring, composed with `open`; `total` counts the matches. Blank means
234/// no search.
235#[utoipa::path(
236 get,
237 path = "/",
238 tag = "boards",
239 security(("session_cookie" = [])),
240 params(ListFilter, PageParams),
241 responses(
242 (status = 200, description = "A page of the caller's boards", body = Page<BoardResponse>),
243 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
244 (status = 401, description = "Not authenticated", body = ErrorResponse),
245 (status = 403, description = "The caller is a parent", body = ErrorResponse),
246 ),
247)]
248async fn list_boards(
249 State(st): State<AppState>,
250 RequireStudent(user): RequireStudent,
251 Query(filter): Query<ListFilter>,
252 Query(page): Query<PageParams>,
253) -> Result<Json<Page<BoardResponse>>, AppError> {
254 let (limit, offset) = page.resolve()?;
255 let (boards, total) = board::list_for_user(
256 &st.db,
257 user.get_id(),
258 filter.open,
259 filter.q.as_deref(),
260 limit,
261 offset,
262 )
263 .await?;
264 let items = boards.iter().map(BoardResponse::new).collect();
265 Ok(Json(Page::new(items, total, limit, offset)))
266}
267
268/// Fetch one board. A caller who is neither its creator nor one of its
269/// participants gets a `404`, not a `403` — an outsider must not learn that a
270/// board exists.
271#[utoipa::path(
272 get,
273 path = "/{id}",
274 tag = "boards",
275 security(("session_cookie" = [])),
276 params(("id" = String, Path, description = "Board id")),
277 responses(
278 (status = 200, description = "The board", body = BoardResponse),
279 (status = 401, description = "Not authenticated", body = ErrorResponse),
280 (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),
281 ),
282)]
283async fn get_board(
284 State(st): State<AppState>,
285 CurrentUser(user): CurrentUser,
286 Path(id): Path<String>,
287) -> Result<Json<BoardResponse>, AppError> {
288 let board = board::board_for(&id, &user, &st.db).await?;
289 Ok(Json(BoardResponse::new(&board)))
290}
291
292/// The live canvas: the current epoch's strokes, oldest first, paged via
293/// `?limit=&offset=`. This is what a client draws to catch up — earlier epochs
294/// are still stored, and read through `/history`. Drawn marks only: a `clear`
295/// marker never appears here, exactly as it never appears on the board room's
296/// socket. Read `/history` or `/epochs` for the markers.
297#[utoipa::path(
298 get,
299 path = "/{id}/strokes",
300 tag = "boards",
301 security(("session_cookie" = [])),
302 params(("id" = String, Path, description = "Board id"), PageParams),
303 responses(
304 (status = 200, description = "A page of the current epoch's strokes", body = Page<StrokeResponse>),
305 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
306 (status = 401, description = "Not authenticated", body = ErrorResponse),
307 (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),
308 ),
309)]
310async fn list_strokes(
311 State(st): State<AppState>,
312 CurrentUser(user): CurrentUser,
313 Path(id): Path<String>,
314 Query(page): Query<PageParams>,
315) -> Result<Json<Page<StrokeResponse>>, AppError> {
316 let (limit, offset) = page.resolve()?;
317 let board = board::board_for(&id, &user, &st.db).await?;
318 // The current epoch holds no `clear` marker — a marker is written with the
319 // epoch it *closed* — so scoping history to it is the live canvas. Markers
320 // are dropped anyway: a clear committing between the board read above and
321 // this read files one under the epoch just named, and the room's socket
322 // never shows it, so without the filter the two views disagree in exactly
323 // that race.
324 let (strokes, total) = board_stroke::history(
325 &st.db,
326 board.get_id(),
327 Some(board.get_epoch()),
328 true,
329 limit,
330 offset,
331 )
332 .await?;
333 let items = strokes.iter().map(StrokeResponse::new).collect();
334 Ok(Json(Page::new(items, total, limit, offset)))
335}
336
337#[derive(Deserialize, utoipa::IntoParams)]
338struct HistoryParams {
339 /// One epoch's rows only. Omit for the board's whole life, oldest first.
340 epoch: Option<i64>,
341}
342
343/// The whole stroke log, oldest first — every epoch the board ever had, or the
344/// single `?epoch=` named. A clear deletes nothing, so this replays the entire
345/// session; the `clear` markers in the stream are where one epoch ended.
346/// Paged via `?limit=&offset=`.
347#[utoipa::path(
348 get,
349 path = "/{id}/history",
350 tag = "boards",
351 security(("session_cookie" = [])),
352 params(("id" = String, Path, description = "Board id"), HistoryParams, PageParams),
353 responses(
354 (status = 200, description = "A page of the stroke log", body = Page<StrokeResponse>),
355 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
356 (status = 401, description = "Not authenticated", body = ErrorResponse),
357 (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),
358 ),
359)]
360async fn list_history(
361 State(st): State<AppState>,
362 CurrentUser(user): CurrentUser,
363 Path(id): Path<String>,
364 Query(scope): Query<HistoryParams>,
365 Query(page): Query<PageParams>,
366) -> Result<Json<Page<StrokeResponse>>, AppError> {
367 let (limit, offset) = page.resolve()?;
368 let board = board::board_for(&id, &user, &st.db).await?;
369 let (strokes, total) =
370 board_stroke::history(&st.db, board.get_id(), scope.epoch, false, limit, offset).await?;
371 let items = strokes.iter().map(StrokeResponse::new).collect();
372 Ok(Json(Page::new(items, total, limit, offset)))
373}
374
375/// The epoch index: every `clear` marker this board has, oldest first. Each one
376/// carries the epoch it closed (`epoch`), that epoch's final stroke count
377/// (`count`), who cleared and when — which is all a client needs to offer
378/// "replay session 3" without scanning the log. The markers *are* the index, so
379/// the current (unclosed) epoch is deliberately absent. Paged via
380/// `?limit=&offset=`.
381#[utoipa::path(
382 get,
383 path = "/{id}/epochs",
384 tag = "boards",
385 security(("session_cookie" = [])),
386 params(("id" = String, Path, description = "Board id"), PageParams),
387 responses(
388 (status = 200, description = "A page of the board's clear markers", body = Page<StrokeResponse>),
389 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
390 (status = 401, description = "Not authenticated", body = ErrorResponse),
391 (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),
392 ),
393)]
394async fn list_epochs(
395 State(st): State<AppState>,
396 CurrentUser(user): CurrentUser,
397 Path(id): Path<String>,
398 Query(page): Query<PageParams>,
399) -> Result<Json<Page<StrokeResponse>>, AppError> {
400 let (limit, offset) = page.resolve()?;
401 let board = board::board_for(&id, &user, &st.db).await?;
402 let markers = board_stroke::epochs(&st.db, board.get_id()).await?;
403 // Paged in the web layer: the marker list is one bounded read, and a board
404 // has at most one marker per clear.
405 let items = paginate(&markers, limit, offset)
406 .iter()
407 .map(StrokeResponse::new)
408 .collect();
409 Ok(Json(Page::new(items, markers.len() as i64, limit, offset)))
410}
411
412#[derive(Deserialize, ToSchema)]
413#[serde(deny_unknown_fields)]
414struct UpdateBoard {
415 /// Re-title. Any participant may. Omit to keep.
416 #[schema(max_length = 200)]
417 title: Option<String>,
418 /// Replace the invite list — **creator only**. Omit to keep; send `null`
419 /// (or an empty list) to leave the creator alone on the board.
420 #[serde(default, deserialize_with = "set_or_clear")]
421 #[schema(value_type = Option<Vec<String>>, max_items = 200)]
422 participants: Option<Option<Vec<String>>>,
423 /// Pause (`true`) or resume (`false`) drawing — **creator only**. Omit to
424 /// keep.
425 locked: Option<bool>,
426}
427
428/// Edit a board. Re-titling is open to every participant; changing the invite
429/// list or the lock is the creator's alone (`403` for anyone else on the
430/// board). Omitted fields keep their value.
431///
432/// A roster change and a lock change are both fanned out to the live room at
433/// once — a participant removed here would otherwise keep drawing over the
434/// socket they already hold.
435///
436/// The roster this route just served can always be sent back: an id already on
437/// the board that stopped qualifying is dropped rather than refused (see
438/// [`resolve_participants`]). Adding an unqualified id is still a 400.
439#[utoipa::path(
440 patch,
441 path = "/{id}",
442 tag = "boards",
443 security(("session_cookie" = [])),
444 params(("id" = String, Path, description = "Board id")),
445 request_body = UpdateBoard,
446 responses(
447 (status = 200, description = "The updated board", body = BoardResponse),
448 (status = 400, description = "Invalid title, or a participant list that is too long, or one that newly names an unknown user or a parent. An id already on the board that no longer qualifies is dropped instead, so the roster just read can be sent back verbatim", body = ErrorResponse),
449 (status = 401, description = "Not authenticated", body = ErrorResponse),
450 (status = 403, description = "Only the creator may change the participants or the lock", body = ErrorResponse),
451 (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),
452 (status = 422, description = "The body does not fit this request: a field has the wrong type, a required field is missing, or it carries a key this request does not accept — a board response cannot be posted back verbatim"),
453 ),
454)]
455async fn update_board(
456 State(st): State<AppState>,
457 SchoolIdCookie(school): SchoolIdCookie,
458 CurrentUser(user): CurrentUser,
459 Path(id): Path<String>,
460 Json(req): Json<UpdateBoard>,
461) -> Result<Json<BoardResponse>, AppError> {
462 // A roster PATCH resolves against the roster as this request read it
463 // (to keep the ids that stopped qualifying) and replaces it with one
464 // field-scoped write: the request carries the whole intended roster, so
465 // it is a creator-driven replace, not a merge — an invite committing
466 // between the read and this write is superseded by the PATCH, which is
467 // the route's contract.
468 let mut board = board::board_for(&id, &user, &st.db).await?;
469 if req.participants.is_some() || req.locked.is_some() {
470 board::ensure_creator(&board, &user)?;
471 }
472
473 if let Some(title) = req.title.as_deref() {
474 board = board::set_title(&st.db, &board, BoardTitle::try_new(title)?).await?;
475 }
476 if let Some(participants) = req.participants {
477 let participants =
478 board::resolve_participants(participants, board.get_participants(), &st.db).await?;
479 board = board::set_participants(&st.db, &board, participants).await?;
480 fan_out(&st, &school, board.get_id(), participants_frame(&board));
481 }
482 if let Some(locked) = req.locked {
483 board = board::set_locked(&st.db, &board, locked, user.get_id()).await?;
484 fan_out(
485 &st,
486 &school,
487 board.get_id(),
488 json!({"type": "locked", "locked": locked, "by": user.get_id().key()}),
489 );
490 }
491 Ok(Json(BoardResponse::new(&board)))
492}
493
494/// Empty the canvas — creator only. **Nothing is deleted**: the board's epoch
495/// is bumped and a `clear` marker is appended carrying the closed epoch's final
496/// stroke count, so the live canvas is blank while every mark ever drawn stays
497/// readable through `/history`. Also resets the live-canvas cap, which is how a
498/// board that answered "clear it to keep drawing" is recovered. `409` on a
499/// closed board, on a **locked** one — the pause holds against its own creator,
500/// so a locked full board is recovered by unlock, clear, relock — and on a
501/// canvas that is **already blank**: the marker is a real stroke row charged to
502/// the board's lifetime cap, so a clear has to close at least one mark to be
503/// worth a row. A board that is both locked and closed answers **closed** —
504/// here and on every stroke path alike, since there is no reopen and the pause
505/// can never lift.
506#[utoipa::path(
507 post,
508 path = "/{id}/clear",
509 tag = "boards",
510 security(("session_cookie" = [])),
511 params(("id" = String, Path, description = "Board id")),
512 responses(
513 (status = 201, description = "The clear marker that closed the epoch", body = StrokeResponse),
514 (status = 401, description = "Not authenticated", body = ErrorResponse),
515 (status = 403, description = "Only the creator may clear the board", body = ErrorResponse),
516 (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),
517 (status = 409, description = "The canvas is already blank, or the board is locked or closed", body = ErrorResponse),
518 ),
519)]
520async fn clear_board(
521 State(st): State<AppState>,
522 SchoolIdCookie(school): SchoolIdCookie,
523 CurrentUser(user): CurrentUser,
524 Path(id): Path<String>,
525) -> Result<(StatusCode, Json<StrokeResponse>), AppError> {
526 let board = board::board_for(&id, &user, &st.db).await?;
527 board::ensure_creator(&board, &user)?;
528 let marker = board_stroke::clear(&st.db, board.get_id(), user.get_id()).await?;
529 // The marker carries the epoch it *closed*; the room's new canvas is the
530 // next one.
531 fan_out(
532 &st,
533 &school,
534 board.get_id(),
535 json!({
536 "type": "cleared",
537 "epoch": marker.get_epoch() + 1,
538 "by": user.get_id().key(),
539 }),
540 );
541 Ok((StatusCode::CREATED, Json(StrokeResponse::new(&marker))))
542}
543
544/// Retire the board — creator only. It becomes permanently read-only: no more
545/// strokes and no more clears, while every stroke and every epoch stays
546/// readable. Idempotent: closing an already-closed board returns it with its
547/// original `closed_at` rather than re-stamping. There is no reopen — a closed
548/// board is finished, and a new one is cheap.
549#[utoipa::path(
550 post,
551 path = "/{id}/close",
552 tag = "boards",
553 security(("session_cookie" = [])),
554 params(("id" = String, Path, description = "Board id")),
555 responses(
556 (status = 200, description = "The closed board", body = BoardResponse),
557 (status = 401, description = "Not authenticated", body = ErrorResponse),
558 (status = 403, description = "Only the creator may close the board", body = ErrorResponse),
559 (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),
560 ),
561)]
562async fn close_board(
563 State(st): State<AppState>,
564 SchoolIdCookie(school): SchoolIdCookie,
565 CurrentUser(user): CurrentUser,
566 Path(id): Path<String>,
567) -> Result<Json<BoardResponse>, AppError> {
568 let board = board::board_for(&id, &user, &st.db).await?;
569 board::ensure_creator(&board, &user)?;
570 let board = board::close(&st.db, &board).await?;
571 fan_out(
572 &st,
573 &school,
574 board.get_id(),
575 json!({
576 "type": "closed",
577 "closed_at": board.get_closed_at().map(|at| at.as_millis()),
578 }),
579 );
580 Ok(Json(BoardResponse::new(&board)))
581}
582
583/// A bulk invite's source: a roster that already exists somewhere else, named
584/// on the wire and resolved to user ids **once**, at the moment of the call.
585/// Tagged by `kind`, the same wire shape an event audience uses.
586///
587/// The result is a **snapshot**, not a subscription. A board holds a flat list
588/// of ids and nothing else — it does not remember it was filled from a class —
589/// so a student who joins that class tomorrow is not on yesterday's board, and
590/// nothing the class does afterwards puts back a student the creator took off.
591/// That is the point of the shape: the roster is a list the creator owns and can
592/// edit, and re-inviting the same source is how it is topped up (adding only who
593/// is missing). Re-inviting *is* also what undoes a removal — the source still
594/// names that student — so a removal is not a per-board ban; there is no
595/// exclusion list.
596///
597/// Live resolution was the alternative and is rejected for this feature: it
598/// would make [`Board::is_participant`], the board room's door and
599/// `list_for_user` cross-table queries — "which boards may I open" would stop
600/// being one indexed read — and it would take the per-person removal away from
601/// the creator, which is what a whiteboard is for.
602#[derive(Deserialize, ToSchema)]
603#[serde(tag = "kind", rename_all = "lowercase")]
604enum InviteSource {
605 /// Everyone currently in this class section. The homeroom teacher is
606 /// not implied — the field is a label and grants nothing.
607 Class { class: String },
608 /// Everyone the course reaches: the union of every instance's roster and
609 /// the course's individual members. Clubs and study groups are courses
610 /// (`kind` `club` / `study`), so this is how a whole club is invited. Staff
611 /// running the course are not enrolled and so are not included.
612 Course { course: String },
613 /// The event's expected-attendee roster, exactly as `GET
614 /// /events/{id}/roster` resolves it — the signup list for a registration
615 /// event, the class or the course roster for the others. A school-wide or
616 /// role-wide event will normally overflow the board's participant cap; that
617 /// is a `409`, not a truncation.
618 Event { event: String },
619}
620
621impl InviteSource {
622 /// Resolve to raw user ids, refusing a caller who may not read this roster
623 /// in the first place.
624 ///
625 /// The gate is deliberately not a new permission: a board's roster is
626 /// visible to everyone on the board, so a bulk invite *discloses* the source
627 /// roster. Each arm therefore mirrors the gate on that roster's own listing
628 /// route — teacher+ for a class (`GET /classes/{id}/members`), teacher+ for
629 /// an event (`GET /events/{id}/roster`); the course arm keeps
630 /// [`can_manage_course`], the gate over a catalog row, because a course's
631 /// audience (every instance's roster plus its individual members) has no
632 /// single listing route of its own. A student can still build a board one id
633 /// at a time; they cannot dump a class roster into one.
634 ///
635 /// A source that does not exist is a `400` naming the field, never a `404`:
636 /// on these routes a 404 means "no such board, or not yours", and reusing it
637 /// here would tell a creator their own board had vanished.
638 async fn resolve(self, user: &User, db: &Database) -> Result<Vec<UserId>, AppError> {
639 match self {
640 InviteSource::Class { class } => {
641 if !user.get_role().at_least(Role::Teacher) {
642 return Err(AppError::Forbidden(
643 "requires teacher role or higher to invite a whole class section",
644 ));
645 }
646 let class = ClassGroupId::from_key(&class);
647 if crate::service::class_group::read(db, &class)
648 .await?
649 .is_none()
650 {
651 return Err(AppError::Validation(ValidationError::Invalid {
652 field: "class",
653 reason: "no such class section",
654 }));
655 }
656 Ok(
657 crate::service::class_member::list_for_class(db, &class, None, 0)
658 .await?
659 .0
660 .iter()
661 .map(|member| *member.get_user())
662 .collect(),
663 )
664 }
665 InviteSource::Course { course } => {
666 let course = crate::service::course::read(db, &CourseId::from_key(&course))
667 .await?
668 .ok_or(AppError::Validation(ValidationError::Invalid {
669 field: "course",
670 reason: "no such course",
671 }))?;
672 if !can_manage_course(&course, user) {
673 return Err(AppError::Forbidden(
674 "only the course creator or a manager/admin can invite its roster",
675 ));
676 }
677 Ok(crate::db::enrollment::list_users_for_course(db, course.get_id()).await?)
678 }
679 InviteSource::Event { event } => {
680 if !user.get_role().at_least(Role::Teacher) {
681 return Err(AppError::Forbidden(
682 "requires teacher role or higher to invite an event's roster",
683 ));
684 }
685 let event = crate::service::event::read(db, &EventId::from_key(&event))
686 .await?
687 .ok_or(AppError::Validation(ValidationError::Invalid {
688 field: "event",
689 reason: "no such event",
690 }))?;
691 crate::service::event::members(db, &event).await
692 }
693 }
694 }
695}
696
697/// Invite a whole roster at once — creator only, and additive: everyone the
698/// source names is **added** to the invite list, nobody is ever removed by it.
699/// Re-inviting the same source is therefore how a board is topped up after the
700/// class gained a student, and it is idempotent when nothing changed.
701///
702/// The ids are resolved once, here. The board keeps a flat list and no memory
703/// of where it came from, so the roster does not track the source afterwards —
704/// see [`InviteSource`] for why. Removal stays `PATCH /boards/{id}`: send the
705/// roster you want.
706///
707/// Three filters run on the resolved list before it lands, and all three are
708/// silent — a source is a whole group, and one ineligible member must not fail
709/// the invite for the other twenty-nine:
710/// - ids that no longer resolve to a user row are dropped,
711/// - anyone below the student role is dropped, which is what keeps `parent` off
712/// the whiteboard by the same cut [`resolve_participants`] makes,
713/// - anyone already on the board (the creator included) is not added twice.
714///
715/// The cap is **all-or-nothing**: if the union would exceed
716/// `max_participants` (`GET /limits`) the whole invite is refused with a `409`
717/// naming the two numbers, and the roster is left exactly as it was. A partial
718/// invite would silently pick which half of a class gets to draw.
719#[utoipa::path(
720 post,
721 path = "/{id}/invite",
722 tag = "boards",
723 security(("session_cookie" = [])),
724 params(("id" = String, Path, description = "Board id")),
725 request_body = InviteSource,
726 responses(
727 (status = 200, description = "The board with the widened roster", body = BoardResponse),
728 (status = 400, description = "The named class, course or event does not exist", body = ErrorResponse),
729 (status = 401, description = "Not authenticated", body = ErrorResponse),
730 (status = 403, description = "Not the board's creator, or not allowed to read that roster", body = ErrorResponse),
731 (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),
732 (status = 409, description = "The invite would put the board over its participant cap; nobody was added", body = ErrorResponse),
733 (status = 422, description = "The body does not fit this request: an unknown or missing `kind`, or the field that `kind` requires is absent"),
734 ),
735)]
736async fn invite_board(
737 State(st): State<AppState>,
738 SchoolIdCookie(school): SchoolIdCookie,
739 CurrentUser(user): CurrentUser,
740 Path(id): Path<String>,
741 Json(req): Json<InviteSource>,
742) -> Result<Json<BoardResponse>, AppError> {
743 // The merge is one atomic guarded statement (see
744 // `crate::db::board::invite_group`): two invites landing together both
745 // union into the
746 // roster the row holds at write time, so neither can drop the other's
747 // people — the property the old process-wide roster lock provided, now
748 // enforced by the row itself.
749 let board = board::board_for(&id, &user, &st.db).await?;
750 board::ensure_creator(&board, &user)?;
751 let invited = req.resolve(&user, &st.db).await?;
752 let board = board::invite(&st.db, &board, invited).await?;
753 fan_out(&st, &school, board.get_id(), participants_frame(&board));
754 Ok(Json(BoardResponse::new(&board)))
755}
756
757/// Delete the board and its whole stroke history — creator only, and the one
758/// operation in this system that really destroys marks (a clear never does).
759/// It also frees the creator's board seat. Use `/close` to retire a board while
760/// keeping it readable.
761#[utoipa::path(
762 delete,
763 path = "/{id}",
764 tag = "boards",
765 security(("session_cookie" = [])),
766 params(("id" = String, Path, description = "Board id")),
767 responses(
768 (status = 204, description = "Deleted, with every stroke it held"),
769 (status = 401, description = "Not authenticated", body = ErrorResponse),
770 (status = 403, description = "Only the creator may delete the board", body = ErrorResponse),
771 (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),
772 ),
773)]
774async fn delete_board(
775 State(st): State<AppState>,
776 SchoolIdCookie(school): SchoolIdCookie,
777 CurrentUser(user): CurrentUser,
778 Path(id): Path<String>,
779) -> Result<StatusCode, AppError> {
780 let board = board::board_for(&id, &user, &st.db).await?;
781 board::ensure_creator(&board, &user)?;
782 let id = board.get_id().clone();
783 board::delete(&st.db, board).await?;
784 // Told after the row is gone: a room that acts on this and then re-reads
785 // must find nothing, not a board about to disappear.
786 fan_out(&st, &school, &id, json!({"type": "deleted"}));
787 Ok(StatusCode::NO_CONTENT)
788}