forge
Explore
Log in

Don't you dare go Hollow

πŸ–ΌοΈ document the collaborative whiteboard

Browse files at this commit

f2d913eeea628d038da890bfca21a8796ed757b2Ahmet Kaan GümüşParent: 6208c97
  • docs
    • πŸ–ΌοΈ document the collaborative whiteboard
Show full message
docs: πŸ–ΌοΈ document the collaborative whiteboard

Intro, all eleven /boards routes, a section of its own, the new modules in
the layout, and the board block of /limits β€” the last of the three doc
surfaces the feature owed.
README.mdmodified+172 -5
@@ -10,8 +10,8 @@ attendance, pomodoro, and homework reports β€” that's the whole role. Notes are
10 per-file size cap is school policy in settings (`max_file_bytes`, default10 per-file size cap is school policy in settings (`max_file_bytes`, default
11 5 MiB). Any two users can **message** each other, mail-style β€” subject +11 5 MiB). Any two users can **message** each other, mail-style β€” subject +
12 body into the recipient's inbox, each side filing its own copy through12 body into the recipient's inbox, each side filing its own copy through
13-archive/trash with a read flag the sender sees as a receipt (the one place a13+archive/trash with a read flag the sender sees as a receipt (one of the two
14-`parent` writes). Attendance is event + attendees: create an event with an **audience**14+places a `parent` writes β€” whiteboards below are the other). Attendance is event + attendees: create an event with an **audience**
15 (the whole school, one role, a course's enrollment, or a **registration**15 (the whole school, one role, a course's enrollment, or a **registration**
16 signup list β€” omit for school-wide), then teachers mark the expected attendees16 signup list β€” omit for school-wide), then teachers mark the expected attendees
17 present / absent / late / excused (students never self-mark), and a **roster17 present / absent / late / excused (students never self-mark), and a **roster
@@ -111,6 +111,15 @@ inference outlives a request: the turn plus an empty `pending` answer are
111 written *first*, the call goes out after, so a reload never loses an answer;111 written *first*, the call goes out after, so a reload never loses an answer;
112 the client then polls the message or reads it off an SSE stream (see112 the client then polls the message or reads it off an SSE stream (see
113 "Chatbot").113 "Chatbot").
114+Any signed-in account (a `parent` included) can also open a **collaborative
115+whiteboard**: a titled board whose membership is an **ad-hoc invite list** β€”
116+the creator names participant user ids, and no course, session or appointment
117+is involved. Every participant draws over a WebSocket, the creator alone
118+clears, locks, closes or deletes, and someone who is not on a board gets a
119+`404` for it on every route, existence included. Strokes are **append-only and
120+a clear deletes nothing** β€” it bumps the board's epoch, so the live canvas
121+empties while every mark ever drawn stays stored and replayable through the
122+history reads (see "Collaborative whiteboard").
114 The school's **food program** is published here too: a manager puts up one123 The school's **food program** is published here too: a manager puts up one
115 **menu** per calendar day and meal slot (`date` as `YYYY-MM-DD` text, `slot`124 **menu** per calendar day and meal slot (`date` as `YYYY-MM-DD` text, `slot`
116 drawn from the school's `meal_slots`, unique per pair), lists its **dishes**125 drawn from the school's `meal_slots`, unique per pair), lists its **dishes**
@@ -315,6 +324,12 @@ response in the same commit.
315 "appointment": { "max_note_len": 500, "max_reason_len": 1000, "max_slot_occurrences": 52 },324 "appointment": { "max_note_len": 500, "max_reason_len": 1000, "max_slot_occurrences": 52 },
316 "chatbot": { "max_message_len": 8000, "max_thread_title_len": 200,325 "chatbot": { "max_message_len": 8000, "max_thread_title_len": 200,
317 "min_max_message_len": 100, "…": 0 },326 "min_max_message_len": 100, "…": 0 },
327+ "board": { "max_title_len": 200, "max_participants": 50,
328+ "max_stroke_payload_len": 4096,
329+ "max_epoch_strokes": 5000, "max_board_strokes": 50000,
330+ "max_boards_per_creator": 200,
331+ "stroke_kinds": ["stroke", "clear"],
332+ "ws_tick_secs": 15, "ws_max_board_id_len": 64 },
318 "settings": { "max_list_len": 20, "max_item_len": 50,333 "settings": { "max_list_len": 20, "max_item_len": 50,
319 "min_exam_kind_weight": 1, "max_exam_kind_weight": 100,334 "min_exam_kind_weight": 1, "max_exam_kind_weight": 100,
320 "max_grade_bands": 20, "max_grade_label_len": 20,335 "max_grade_bands": 20, "max_grade_label_len": 20,
@@ -349,7 +364,7 @@ drift from it**, which is enforced rather than asked for:
349 and fails unless each one is either referenced by `src/web/limits.rs` or364 and fails unless each one is either referenced by `src/web/limits.rs` or
350 listed as a deliberate exclusion *with a reason*. A new constant breaks the365 listed as a deliberate exclusion *with a reason*. A new constant breaks the
351 suite until someone decides, consciously, whether clients need it.366 suite until someone decides, consciously, whether clients need it.
352-- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 104 published367+- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 161 published
353 bounds back out of the emitted JSON, and asserts each equals its constant.368 bounds back out of the emitted JSON, and asserts each equals its constant.
354 This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal369 This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal
355 only** β€” a `const` there does not compile β€” so the annotations are370 only** β€” a `const` there does not compile β€” so the annotations are
@@ -387,7 +402,8 @@ Notes:
387 it matches either case; the stored (and returned) value is lowercased, which402 it matches either case; the stored (and returned) value is lowercased, which
388 is the one place a response may differ in case from the request.403 is the one place a response may differ in case from the request.
389 - **Closed value sets ride along.** `roles`, `themes`, `languages`, course404 - **Closed value sets ride along.** `roles`, `themes`, `languages`, course
390- `kinds`, exam `modes`, `question_kinds`, homework `statuses`, and the405+ `kinds`, exam `modes`, `question_kinds`, homework `statuses`, board
406+ `stroke_kinds`, and the
391 uploadable `image_content_types` are the exact accepted spellings β€” build407 uploadable `image_content_types` are the exact accepted spellings β€” build
392 pickers from these rather than from a literal list.408 pickers from these rather than from a literal list.
393 409
@@ -842,6 +858,17 @@ window filtering, before paging; negative values are a `400` naming the field.
842 | POST | `/chatbot/threads/{id}/messages` | student | `{content}` (≀ `max_chatbot_message_len`) β€” send a turn; `202 {message_id, status: "pending"}`, the answer is fetched after (`503` when no AI service offers `chat.reply` β€” nothing is written; `429` + `Retry-After` on the send tier) |858 | POST | `/chatbot/threads/{id}/messages` | student | `{content}` (≀ `max_chatbot_message_len`) β€” send a turn; `202 {message_id, status: "pending"}`, the answer is fetched after (`503` when no AI service offers `chat.reply` β€” nothing is written; `429` + `Retry-After` on the send tier) |
843 | GET | `/chatbot/threads/{id}/messages/{mid}` | student | Poll one turn: `pending` until the answer lands, then `complete` + `content` or `failed` + `error_code` |859 | GET | `/chatbot/threads/{id}/messages/{mid}` | student | Poll one turn: `pending` until the answer lands, then `complete` + `content` or `failed` + `error_code` |
844 | GET | `/chatbot/threads/{id}/messages/{mid}/stream` | student | **SSE** on the same row: `delta` chunks then one `done` β€” or one `error` β€” and close; an already-finished answer replays (see "Chatbot") |860 | GET | `/chatbot/threads/{id}/messages/{mid}/stream` | student | **SSE** on the same row: `delta` chunks then one `done` β€” or one `error` β€” and close; an already-finished answer replays (see "Chatbot") |
861+| POST | `/boards` | student | `{title, participant_ids?}` β€” open a whiteboard; the caller becomes its creator, everyone named may draw; `409` at `max_boards_per_creator` |
862+| GET | `/boards` | student | Boards the caller created or was invited to, newest first Β· paged |
863+| GET | `/boards/{id}` | student | One board β€” a `404`, never a `403`, for anyone not on it |
864+| GET | `/boards/{id}/strokes` | student | The live canvas: the current epoch's strokes, oldest first Β· paged |
865+| GET | `/boards/{id}/history` | student | The whole append-only log, oldest first, `clear` markers included Β· `?epoch=` for one epoch Β· paged |
866+| 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 |
867+| PATCH | `/boards/{id}` | student | `{title?, participants?, locked?}` β€” re-title (any participant); the roster and the lock are the creator's alone (`403`) |
868+| 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 |
869+| POST | `/boards/{id}/close` | student | **Creator only**: retire the board β€” permanently read-only, still fully readable; idempotent, and there is no reopen |
870+| DELETE | `/boards/{id}` | student | **Creator only**: delete the board and its whole stroke log; frees one of the creator's board seats |
871+| GET | `/boards/{id}/ws` | student | **WebSocket** board room: a `join` replays the current epoch, every accepted stroke fans out to the other participants (see "Collaborative whiteboard") |
845 872
846 `status` must be one of the school's attendance statuses (`GET /settings`);873 `status` must be one of the school's attendance statuses (`GET /settings`);
847 the core four `present | absent | late | excused` always exist, plus whatever874 the core four `present | absent | late | excused` always exist, plus whatever
@@ -2472,6 +2499,132 @@ as the message's `error_code`.
2472 add fields (a model name, token counts) and a future backend may send more2499 add fields (a model name, token counts) and a future backend may send more
2473 context without either end having to be redeployed in lockstep.2500 context without either end having to be redeployed in lockstep.
2474 2501
2502+## Collaborative whiteboard
2503+
2504+A board is a shared canvas whose membership is an **ad-hoc invite list**: the
2505+creator names participant user ids at `POST /boards` and that is the whole
2506+model β€” no course, no lesson session, no appointment. Any signed-in account
2507+(a `parent` included) may open one. **Every participant draws; the creator
2508+alone clears, locks, closes or deletes.**
2509+
2510+**Two doors, two statuses.** A caller who is not on a board gets a `404` on
2511+every route, its existence included β€” an outsider must never learn a board is
2512+there. A participant who is not the creator has already been told it exists, so
2513+the four creator-only commands answer them a `403`: hiding it at that point
2514+would be a lie their client cannot act on. Over the socket the same refusal is
2515+`error{code:"forbidden"}` and the socket **stays open** β€” someone clicking a
2516+button they don't own must not lose the canvas they were drawing on.
2517+
2518+**A clear deletes nothing.** Strokes are append-only. `POST /boards/{id}/clear`
2519+bumps the board's `epoch` and appends a `clear` **marker** carrying the epoch
2520+it closed, that epoch's final stroke count, who cleared and when β€” so the live
2521+canvas empties while every mark ever drawn stays stored and replayable. Those
2522+markers *are* the epoch index, which is why there is no epochs table and why
2523+the open (unclosed) epoch is deliberately absent from `GET /boards/{id}/epochs`.
2524+`DELETE /boards/{id}` is the one operation here that really destroys marks.
2525+
2526+**Three caps, and only one of them is terminal** (all three published at `GET
2527+/limits` under `board`):
2528+
2529+- `max_epoch_strokes` bounds the **live** canvas β€” `epoch_stroke_count`, which
2530+ every clear resets. Hitting it is **recoverable**: the creator clears, the
2531+ history is kept, drawing resumes.
2532+- `max_board_strokes` bounds the board's **lifetime** storage β€”
2533+ `total_stroke_count`, which never resets, because a clear keeps its history.
2534+ Hitting it stamps `closed_at` and the board becomes **permanently
2535+ read-only**: still fully readable and replayable, never deleted, and there is
2536+ no reopen β€” open a new board. `POST /boards/{id}/close` is the manual form of
2537+ the same thing, and idempotent.
2538+- `max_boards_per_creator` bounds how many boards one creator holds
2539+ (`board_count` on the user row). Deleting a board frees a seat; closing one
2540+ does not β€” a closed board is still stored.
2541+
2542+**Two ways to read the marks, and the difference matters most to a client
2543+author.** A socket `join` replays the **current epoch only**; history never
2544+rides the socket. History is an explicit paged REST read:
2545+`GET /boards/{id}/history` (the board's whole life, oldest first, `clear`
2546+markers included, `?epoch=` for a single one) and `GET /boards/{id}/epochs`
2547+(the marker index β€” enough to offer "replay session 3" without scanning the
2548+log). `GET /boards/{id}/strokes` is the current epoch over REST, the catch-up
2549+and fallback path for the same canvas the socket replays β€” with one deliberate
2550+difference: the REST read is *not* filtered by kind, while the socket serves
2551+`kind: "stroke"` rows only. In the steady state that is a distinction without a
2552+difference, since a marker is written with the epoch it *closed* and the open
2553+epoch has none; the case where it shows is a clear landing between the board
2554+read and the row read, which surfaces that epoch's closing marker in the page.
2555+For a live canvas the socket is the authority.
2556+
2557+**The board room (WebSocket)** β€” `GET /boards/{id}/ws`, cookie-authed like
2558+everything else and, like the exam room, outside the OpenAPI spec (an upgrade
2559+is not describable there); REST remains the full fallback. The gate before the
2560+upgrade is the same `404` door: not a participant, no room. Then JSON text
2561+frames:
2562+
2563+| direction | frame |
2564+|-----------|-------|
2565+| client β†’ | `{"type":"join", "after":"<last stroke id>", "epoch":3}` β€” both optional; replay the current epoch |
2566+| server β†’ | `{"type":"state", board, epoch, locked, closed_at, creator, participants, now}` on connect and every `ws_tick_secs` |
2567+| server β†’ | `{"type":"strokes", epoch, strokes:[{id, author, payload}]}` β€” one replay chunk, repeated until the epoch is served |
2568+| server β†’ | `{"type":"synced", epoch, cursor}` β€” the replay is complete; `cursor` is what to resume from |
2569+| client β†’ | `{"type":"stroke", "payload":"…"}`, optionally `+ "client_seq":7` β€” any participant |
2570+| server β†’ | `{"type":"saved", id, client_seq?}` β€” your stroke landed |
2571+| server β†’ | `{"type":"stroke", id, author, payload, epoch}` β€” someone *else* drew |
2572+| client β†’ | `{"type":"clear"}` / `{"type":"lock", "locked":true}` β€” **creator only** |
2573+| server β†’ | `{"type":"cleared", …}` / `{"type":"locked", locked, by}` β€” the canvas was emptied / drawing was paused |
2574+| server β†’ | `{"type":"closed", …}` / `{"type":"deleted"}` β€” the board is finished; both end the room |
2575+| server β†’ | `{"type":"participants", creator, participants}` β€” the roster changed; a socket no longer on it is dropped |
2576+| client β†’ | `{"type":"ping"}` β†’ server `{"type":"pong"}` |
2577+| server β†’ | `{"type":"error", code, message, client_seq?}` |
2578+
2579+A `stroke` may carry a `client_seq` exactly as an exam-room `answer` does: any
2580+value the client picks, echoed **verbatim** on that message's `saved` or
2581+`error` and on nothing else, omitted entirely when the request omitted it. The
2582+server never reads it.
2583+
2584+`error` codes are a closed set: `epoch_full` (the live canvas is full β€” clear
2585+it and keep drawing), `board_closed` (permanently read-only), `locked`,
2586+`forbidden` (a creator-only command from a participant), `resync` (below),
2587+`invalid` (bad JSON, an unknown frame, an over-long payload), `not_found`,
2588+`unauthorized`, `too_many_requests`, `conflict`, `internal`.
2589+
2590+**Persist, then publish.** A stroke is fanned out only after its row has
2591+landed, so the channel can never carry a mark the database refused (a locked
2592+board, a full epoch, a closed board). The database is the canvas; the channel
2593+is a notification *about* it β€” which is why a client dedupes by stroke `id`,
2594+why a resync deliberately re-serves marks it already drew, and why a frame is
2595+never the authority: every stroke, clear and lock re-reads the board and
2596+re-checks the roster, so a socket that missed a `participants` or `locked`
2597+frame is refused all the same. One consequence of the same read-then-write
2598+shape: a stroke carries the epoch the server read for it, so a clear landing in
2599+that instant can file one stroke under the epoch it just closed β€” the stroke is
2600+kept and stays replayable in `/history`, it simply is not on the new canvas.
2601+
2602+**Reconnecting.** `join` carries a cursor: `after`, the last stroke id already
2603+drawn, plus the `epoch` it belongs to. Same epoch and only what is newer is
2604+replayed; an older epoch β€” or no cursor at all β€” gets a `cleared` frame first
2605+and then the whole current epoch, because a cursor into a closed epoch no
2606+longer means anything. If the room falls behind a slow socket the server sends
2607+`error{code:"resync"}` and immediately replays the current epoch **out of the
2608+database**: the client does not re-join, it throws its canvas away and takes
2609+what follows. The database is always the source of truth, never the channel.
2610+
2611+```js
2612+const ws = new WebSocket(`${BASE.replace("http", "ws")}/boards/${id}/ws`);
2613+let epoch = null, cursor = null, seq = 0;
2614+ws.onopen = () => ws.send(JSON.stringify({ type: "join", after: cursor, epoch }));
2615+ws.onmessage = (e) => {
2616+ const m = JSON.parse(e.data);
2617+ if (m.type === "cleared") wipeCanvas();
2618+ if (m.type === "strokes") m.strokes.forEach(draw); // dedupe by m.id
2619+ if (m.type === "synced") ({ epoch, cursor } = m);
2620+ if (m.type === "stroke") draw(m);
2621+ if (m.type === "saved") settle(m.client_seq, m.id);
2622+ if (m.type === "error" && m.code === "resync") wipeCanvas();
2623+};
2624+const send = (payload) =>
2625+ ws.send(JSON.stringify({ type: "stroke", payload, client_seq: ++seq }));
2626+```
2627+
2475 ## Concurrency model2628 ## Concurrency model
2476 2629
2477 The backend runs as **one process against one database**, and that buys less2630 The backend runs as **one process against one database**, and that buys less
@@ -2547,7 +2700,8 @@ src/
2547 migration_sql.rs the three boot batches as SurrealQL text (PRE_REPAIR,2700 migration_sql.rs the three boot batches as SurrealQL text (PRE_REPAIR,
2548 MIGRATION, BACKFILL) + MIGRATION_BATCHES, the only list of them2701 MIGRATION, BACKFILL) + MIGRATION_BATCHES, the only list of them
2549 rate_limit.rs fixed-window limiter: per-IP tiers + middleware, per-user chat tier2702 rate_limit.rs fixed-window limiter: per-IP tiers + middleware, per-user chat tier
2550- state.rs AppState { db, files_path, cookie_secure, rate_limit, ai }2703+ state.rs AppState { db, files_path, cookie_secure, rate_limit,
2704+ chatbot_limit, exam_presence, board_hub, db_up, ai }
2551 ai/ QUIC bridge to the out-of-process AI services2705 ai/ QUIC bridge to the out-of-process AI services
2552 (see "AI bridge (QUIC)"; the HTTP half is web/ai.rs)2706 (see "AI bridge (QUIC)"; the HTTP half is web/ai.rs)
2553 protocol.rs Hello/Greeting/Request/Response + length-prefixed JSON framing2707 protocol.rs Hello/Greeting/Request/Response + length-prefixed JSON framing
@@ -2640,6 +2794,13 @@ src/
2640 chatbot_message.rs ChatbotMessageId Β· ChatContent Β· MessageRole Β· MessageStatus Β·2794 chatbot_message.rs ChatbotMessageId Β· ChatContent Β· MessageRole Β· MessageStatus Β·
2641 ChatbotMessage (one turn; the assistant row is written2795 ChatbotMessage (one turn; the assistant row is written
2642 `pending` before the AI call and settled after)2796 `pending` before the AI call and settled after)
2797+ board.rs BoardId Β· BoardTitle Β· Board (a collaborative whiteboard:
2798+ creator + ad-hoc participant list, `epoch`, the two stroke
2799+ counters and `closed_at`)
2800+ board_stroke.rs BoardStrokeId Β· BoardStroke (the
2801+ append-only stroke log; a `clear` row is the marker that
2802+ closed an epoch, carrying its final count β€” nothing is
2803+ ever deleted)
2643 appointment_slot.rs AppointmentSlotId Β· SlotSeries Β· SlotNote Β·2804 appointment_slot.rs AppointmentSlotId Β· SlotSeries Β· SlotNote Β·
2644 AppointmentSlot (a teacher's published availability; a2805 AppointmentSlot (a teacher's published availability; a
2645 recurring publish is expanded into rows sharing a series id)2806 recurring publish is expanded into rows sharing a series id)
@@ -2669,6 +2830,11 @@ src/
2669 extractor.rs CurrentUser Β· RequireTeacher Β· RequireManager Β· RequireAdmin2830 extractor.rs CurrentUser Β· RequireTeacher Β· RequireManager Β· RequireAdmin
2670 dto.rs shared UserResponse Β· CourseResponse Β· ExamResponse Β· SessionResponse schemas2831 dto.rs shared UserResponse Β· CourseResponse Β· ExamResponse Β· SessionResponse schemas
2671 exam_ws.rs the student exam-room WebSocket (state ticks, autosave, finish)2832 exam_ws.rs the student exam-room WebSocket (state ticks, autosave, finish)
2833+ board_ws.rs the collaborative board room WebSocket (join replay, strokes
2834+ fanned out to every participant, clear/lock)
2835+ room.rs the plumbing both rooms share: sending a frame, classifying
2836+ an incoming message, an AppError as a readable code, and a
2837+ client_seq echoed untouched
2672 page.rs PageParams Β· Page<T> (shared pagination)2838 page.rs PageParams Β· Page<T> (shared pagination)
2673 etag.rs conditional-GET middleware: ETag over a 200 JSON body,2839 etag.rs conditional-GET middleware: ETag over a 200 JSON body,
2674 If-None-Match β†’ 304 (GET only; SSE and blobs pass through)2840 If-None-Match β†’ 304 (GET only; SSE and blobs pass through)
@@ -2676,6 +2842,7 @@ src/
2676 courses.rs subjects.rs sessions.rs exams.rs homework.rs questions.rs2842 courses.rs subjects.rs sessions.rs exams.rs homework.rs questions.rs
2677 bank_questions.rs marks.rs work.rs pomodoro.rs attendance.rs2843 bank_questions.rs marks.rs work.rs pomodoro.rs attendance.rs
2678 settings.rs terms.rs meals.rs payments.rs ai.rs chatbot.rs2844 settings.rs terms.rs meals.rs payments.rs ai.rs chatbot.rs
2845+ boards.rs
2679 limits.rs GET /limits: every constant.rs bound served as JSON2846 limits.rs GET /limits: every constant.rs bound served as JSON
2680 ```2847 ```
2681 2848