forge
Explore
Log in

Don't you dare go Hollow

🧪 pin the whiteboard's HTTP surface and its stored guarantees

Browse files at this commit

a05b3196bd30ed8e8d64ba660bf8a9629a0a195fAhmet Kaan GümüşParent: f2d913e
  • test
    • 🧪 pin the whiteboard's HTTP surface and its stored guarantees
Show full message
test: 🧪 pin the whiteboard's HTTP surface and its stored guarantees

The board room's socket already has its own e2e suite; this is the REST
half beside it.

The security boundary first, and exhaustively: an outsider gets a 404 on
every one of the ten routes, asserted against a board id that was never
minted so the two answers are byte-identical — a 403 anywhere there would
confirm the board exists. A participant who is not the creator reads
everything and re-titles, but the four commands and the roster/lock arms
of PATCH are a 403, and none of those refusals writes a thing.

Then the promise the whole storage model exists for: a clear empties
/strokes and leaves /history whole, checked at the table and not only
through the reader a bug could share with the writer. The epoch index
carries one marker per clear, each counting the rows really stored under
the epoch it closed.

Every cap is asserted on the stored counter, never on the response: a
full canvas refuses and stays open, a clear hands the cap back, the
lifetime cap stamps closed_at once and the closed board still serves
every read, and a delete frees a creator's seat.

The mint-order test splits in two on purpose: the DB round trip proves
/strokes and /history replay in mint order, while the same-millisecond
half of the next_ulid hazard is pinned by a tight mint loop with no
database in the way — whether 60 appends share a millisecond depends on
how loaded the machine is, and a test must not.
tests/integration.rsmodified+768 -1
@@ -9,7 +9,12 @@ use common::{
9 app_and_db, create_course, create_exam, create_exam_with, create_homework, create_session,9 app_and_db, create_course, create_exam, create_exam_with, create_homework, create_session,
10 create_subject, enroll, id_of, login, login_as, me_id, mem_app, send, set_role, unenroll,10 create_subject, enroll, id_of, login, login_as, me_id, mem_app, send, set_role, unenroll,
11 };11 };
12-use hezarfen_backend::constant::{BANK_VISIBILITY_SCHOOL, MAX_FEE_PLAN_ASSIGN_STUDENTS};12+use hezarfen_backend::constant::{
13+ BANK_VISIBILITY_SCHOOL, MAX_BOARD_STROKES, MAX_BOARDS_PER_CREATOR, MAX_EPOCH_STROKES,
14+ MAX_FEE_PLAN_ASSIGN_STUDENTS,
15+};
16+use hezarfen_backend::domain::board::{Board, BoardId};
17+use hezarfen_backend::domain::board_stroke::{BoardStroke, BoardStrokeId};
13 use hezarfen_backend::domain::chatbot_message::ChatbotMessage;18 use hezarfen_backend::domain::chatbot_message::ChatbotMessage;
14 use hezarfen_backend::domain::chatbot_thread::ChatbotThreadId;19 use hezarfen_backend::domain::chatbot_thread::ChatbotThreadId;
15 use hezarfen_backend::domain::exam::ExamId;20 use hezarfen_backend::domain::exam::ExamId;
@@ -24055,3 +24060,765 @@ async fn bulk_assignment_is_capped_at_two_hundred_students() {
24055 assert_eq!(pay_row_count(&db, "fee_plan_assignment").await, 0);24060 assert_eq!(pay_row_count(&db, "fee_plan_assignment").await, 0);
24056 assert_eq!(pay_row_count(&db, "payment_ledger").await, 0);24061 assert_eq!(pay_row_count(&db, "payment_ledger").await, 0);
24057 }24062 }
24063+
24064+// --- whiteboards ---------------------------------------------------------
24065+
24066+/// Open a board (asserts 201); returns its id.
24067+async fn create_board(
24068+ app: &axum::Router,
24069+ cookie: &str,
24070+ title: &str,
24071+ participants: &[&str],
24072+) -> String {
24073+ let res = send(
24074+ app,
24075+ "POST",
24076+ "/boards",
24077+ Some(cookie),
24078+ Some(json!({ "title": title, "participant_ids": participants })),
24079+ )
24080+ .await;
24081+ assert_eq!(
24082+ res.status,
24083+ StatusCode::CREATED,
24084+ "create board: {}",
24085+ res.body
24086+ );
24087+ id_of(&res.body)
24088+}
24089+
24090+/// Draw one mark straight through the domain. Drawing is a WebSocket surface
24091+/// (`tests/e2e.rs` owns the room), but every REST read below needs marks on the
24092+/// board first, and the two caps below need one refused at a boundary no HTTP
24093+/// route can reach.
24094+async fn draw(
24095+ db: &Database,
24096+ board: &str,
24097+ author: &str,
24098+ epoch: i64,
24099+ payload: &str,
24100+) -> Result<BoardStroke, hezarfen_backend::error::AppError> {
24101+ BoardStroke::append(
24102+ &BoardId::from_key(board),
24103+ &UserId::from_key(author),
24104+ payload,
24105+ epoch,
24106+ db,
24107+ )
24108+ .await
24109+}
24110+
24111+/// The board row as the store holds it — never the response body, which cannot
24112+/// prove a counter moved (src/domain/cap.rs:44-49).
24113+async fn stored_board(db: &Database, board: &str) -> Option<Board> {
24114+ Board::read(&BoardId::from_key(board), db).await.unwrap()
24115+}
24116+
24117+/// Every stroke row of a board, oldest first, straight out of the table.
24118+/// `SELECT *`, because SurrealDB 3 refuses `ORDER BY id` on a projection that
24119+/// omits `id`.
24120+async fn stroke_rows(db: &Database, board: &str) -> Vec<BoardStroke> {
24121+ let mut result = db
24122+ .query("SELECT * FROM board_stroke WHERE board = $b ORDER BY id")
24123+ .bind(("b", BoardId::from_key(board).record()))
24124+ .await
24125+ .unwrap()
24126+ .check()
24127+ .unwrap();
24128+ result.take(0).unwrap()
24129+}
24130+
24131+/// The stored `[epoch_stroke_count, total_stroke_count]` pair.
24132+async fn stored_counters(db: &Database, board: &str) -> Vec<i64> {
24133+ let mut result = db
24134+ .query(
24135+ "SELECT VALUE [epoch_stroke_count ?? 0, total_stroke_count ?? 0] \
24136+ FROM $id",
24137+ )
24138+ .bind(("id", BoardId::from_key(board).record()))
24139+ .await
24140+ .unwrap()
24141+ .check()
24142+ .unwrap();
24143+ result.take::<Vec<Vec<i64>>>(0).unwrap().remove(0)
24144+}
24145+
24146+async fn set_counters(db: &Database, board: &str, epoch: i64, total: i64) {
24147+ db.query("UPDATE $id SET epoch_stroke_count = $e, total_stroke_count = $t")
24148+ .bind(("id", BoardId::from_key(board).record()))
24149+ .bind(("e", epoch))
24150+ .bind(("t", total))
24151+ .await
24152+ .unwrap()
24153+ .check()
24154+ .unwrap();
24155+}
24156+
24157+/// The creator's stored `board_count` — the authority on how many boards they
24158+/// hold, so the per-creator cap is asserted here and not off a 409.
24159+async fn stored_board_count(db: &Database, user: &str) -> i64 {
24160+ let mut result = db
24161+ .query("SELECT VALUE board_count ?? 0 FROM $id")
24162+ .bind(("id", UserId::from_key(user).record()))
24163+ .await
24164+ .unwrap()
24165+ .check()
24166+ .unwrap();
24167+ result.take::<Vec<i64>>(0).unwrap()[0]
24168+}
24169+
24170+/// Every id-scoped board route, with a body where the route needs one. The
24171+/// `PATCH` arms are split because they carry different rights: `title` is every
24172+/// participant's, `participants` and `locked` are the creator's alone.
24173+fn board_routes(id: &str) -> Vec<(&'static str, String, Option<serde_json::Value>)> {
24174+ vec![
24175+ ("GET", format!("/boards/{id}"), None),
24176+ ("GET", format!("/boards/{id}/strokes"), None),
24177+ ("GET", format!("/boards/{id}/history"), None),
24178+ ("GET", format!("/boards/{id}/epochs"), None),
24179+ (
24180+ "PATCH",
24181+ format!("/boards/{id}"),
24182+ Some(json!({"title": "x"})),
24183+ ),
24184+ (
24185+ "PATCH",
24186+ format!("/boards/{id}"),
24187+ Some(json!({"participants": []})),
24188+ ),
24189+ (
24190+ "PATCH",
24191+ format!("/boards/{id}"),
24192+ Some(json!({"locked": true})),
24193+ ),
24194+ ("POST", format!("/boards/{id}/clear"), None),
24195+ ("POST", format!("/boards/{id}/close"), None),
24196+ ("DELETE", format!("/boards/{id}"), None),
24197+ ]
24198+}
24199+
24200+/// A board that exists must be indistinguishable from one that does not, on
24201+/// every single route — a 403 anywhere here would tell an outsider the school
24202+/// holds a board with that id, and the id list is guessable from nothing else.
24203+#[tokio::test]
24204+async fn every_board_route_is_a_404_for_an_outsider() {
24205+ let (app, db) = app_and_db().await;
24206+ let ali = login(&app, "ali").await;
24207+ let veli = login(&app, "veli").await;
24208+ let zeynep = login(&app, "zeynep").await;
24209+ let veli_id = me_id(&app, &veli).await;
24210+ let board = create_board(&app, &ali, "Geometri", &[&veli_id]).await;
24211+ draw(&db, &board, &me_id(&app, &ali).await, 0, "{\"p\":[1,2]}")
24212+ .await
24213+ .unwrap();
24214+
24215+ // The real board and an id that was never minted answer identically.
24216+ let ghost = board_routes("nosuchboard");
24217+ for (n, (method, uri, body)) in board_routes(&board).into_iter().enumerate() {
24218+ let res = send(&app, method, &uri, Some(&zeynep), body).await;
24219+ assert_eq!(
24220+ res.status,
24221+ StatusCode::NOT_FOUND,
24222+ "{method} {uri} must 404 for an outsider, got {}",
24223+ res.body
24224+ );
24225+ let (gm, gu, gb) = ghost[n].clone();
24226+ let gone = send(&app, gm, &gu, Some(&zeynep), gb).await;
24227+ assert_eq!(
24228+ res.status, gone.status,
24229+ "{method} {uri} must answer exactly like a board that does not exist"
24230+ );
24231+ assert_eq!(res.body, gone.body, "{method} {uri} bodies must match too");
24232+ }
24233+
24234+ // The list route leaks nothing either, and none of the refusals above
24235+ // touched the row: still open, still one stroke, still the same roster.
24236+ let res = send(&app, "GET", "/boards", Some(&zeynep), None).await;
24237+ assert_eq!(res.status, StatusCode::OK);
24238+ assert_eq!(common::total(&res.body), 0, "an outsider lists no boards");
24239+ let stored = stored_board(&db, &board).await.expect("board survived");
24240+ assert_eq!(stored.get_title().as_str(), "Geometri");
24241+ assert_eq!(stored.get_epoch(), 0);
24242+ assert!(!stored.is_locked());
24243+ assert!(stored.get_closed_at().is_none());
24244+ assert_eq!(stored.get_participants().len(), 1);
24245+ assert_eq!(stroke_rows(&db, &board).await.len(), 1);
24246+
24247+ // Opening a board is nobody's privilege — the outsider gets their own.
24248+ let mine = create_board(&app, &zeynep, "Kendi tahtam", &[]).await;
24249+ assert_ne!(mine, board);
24250+}
24251+
24252+/// The other half of the two-tier line: a participant sees the board and may
24253+/// re-title it, but the four commands and the roster/lock arms of `PATCH` are
24254+/// the creator's alone — a 403, because hiding a board they are already
24255+/// rendering would be a lie their client cannot act on.
24256+#[tokio::test]
24257+async fn a_participant_reads_and_retitles_but_cannot_command() {
24258+ let (app, db) = app_and_db().await;
24259+ let ali = login(&app, "ali").await;
24260+ let veli = login(&app, "veli").await;
24261+ let ali_id = me_id(&app, &ali).await;
24262+ let veli_id = me_id(&app, &veli).await;
24263+ let board = create_board(&app, &ali, "Geometri", &[&veli_id]).await;
24264+ draw(&db, &board, &veli_id, 0, "{\"p\":[1,2]}")
24265+ .await
24266+ .unwrap();
24267+
24268+ // Every read, and the title arm: the participant's.
24269+ for uri in [
24270+ format!("/boards/{board}"),
24271+ format!("/boards/{board}/strokes"),
24272+ format!("/boards/{board}/history"),
24273+ format!("/boards/{board}/epochs"),
24274+ "/boards".to_string(),
24275+ ] {
24276+ let res = send(&app, "GET", &uri, Some(&veli), None).await;
24277+ assert_eq!(res.status, StatusCode::OK, "GET {uri}: {}", res.body);
24278+ }
24279+ let res = send(&app, "GET", "/boards", Some(&veli), None).await;
24280+ assert_eq!(common::total(&res.body), 1, "an invitee lists the board");
24281+
24282+ let res = send(
24283+ &app,
24284+ "PATCH",
24285+ &format!("/boards/{board}"),
24286+ Some(&veli),
24287+ Some(json!({ "title": "Cebir" })),
24288+ )
24289+ .await;
24290+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
24291+ assert_eq!(
24292+ stored_board(&db, &board)
24293+ .await
24294+ .unwrap()
24295+ .get_title()
24296+ .as_str(),
24297+ "Cebir",
24298+ "the re-title really landed"
24299+ );
24300+
24301+ // The creator's four commands, and the two creator-only PATCH arms.
24302+ for (method, uri, body) in [
24303+ (
24304+ "PATCH",
24305+ format!("/boards/{board}"),
24306+ Some(json!({"participants": []})),
24307+ ),
24308+ (
24309+ "PATCH",
24310+ format!("/boards/{board}"),
24311+ Some(json!({"locked": true})),
24312+ ),
24313+ ("POST", format!("/boards/{board}/clear"), None),
24314+ ("POST", format!("/boards/{board}/close"), None),
24315+ ("DELETE", format!("/boards/{board}"), None),
24316+ ] {
24317+ let res = send(&app, method, &uri, Some(&veli), body).await;
24318+ assert_eq!(
24319+ res.status,
24320+ StatusCode::FORBIDDEN,
24321+ "{method} {uri} must 403 for a non-creator participant, got {}",
24322+ res.body
24323+ );
24324+ }
24325+
24326+ // Not one of those refusals wrote anything.
24327+ let stored = stored_board(&db, &board).await.expect("board survived");
24328+ assert_eq!(stored.get_participants().len(), 1, "roster untouched");
24329+ assert!(!stored.is_locked(), "lock untouched");
24330+ assert_eq!(stored.get_epoch(), 0, "no clear landed");
24331+ assert!(stored.get_closed_at().is_none(), "not closed");
24332+ assert_eq!(stroke_rows(&db, &board).await.len(), 1, "stroke kept");
24333+ assert_eq!(stored.get_creator().key(), ali_id);
24334+
24335+ // And the creator's own PATCH arms do work — the 403s above are about the
24336+ // caller, not a route that refuses everyone.
24337+ let res = send(
24338+ &app,
24339+ "PATCH",
24340+ &format!("/boards/{board}"),
24341+ Some(&ali),
24342+ Some(json!({ "locked": true })),
24343+ )
24344+ .await;
24345+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
24346+ assert!(stored_board(&db, &board).await.unwrap().is_locked());
24347+}
24348+
24349+/// The user's core requirement, over HTTP: a clear empties the live canvas and
24350+/// destroys nothing. If `/history` ever shrinks here, the feature is wrong.
24351+#[tokio::test]
24352+async fn a_clear_empties_the_canvas_and_keeps_the_history() {
24353+ let (app, db) = app_and_db().await;
24354+ let ali = login(&app, "ali").await;
24355+ let ali_id = me_id(&app, &ali).await;
24356+ let board = create_board(&app, &ali, "Geometri", &[]).await;
24357+ for n in 0..3 {
24358+ draw(&db, &board, &ali_id, 0, &format!("{{\"p\":[{n}]}}"))
24359+ .await
24360+ .unwrap();
24361+ }
24362+ let before: Vec<String> = stroke_rows(&db, &board)
24363+ .await
24364+ .iter()
24365+ .map(|row| row.get_id().key().to_string())
24366+ .collect();
24367+ assert_eq!(before.len(), 3);
24368+
24369+ let res = send(
24370+ &app,
24371+ "GET",
24372+ &format!("/boards/{board}/strokes"),
24373+ Some(&ali),
24374+ None,
24375+ )
24376+ .await;
24377+ assert_eq!(common::total(&res.body), 3, "the live canvas has 3 marks");
24378+
24379+ let res = send(
24380+ &app,
24381+ "POST",
24382+ &format!("/boards/{board}/clear"),
24383+ Some(&ali),
24384+ None,
24385+ )
24386+ .await;
24387+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
24388+ assert_eq!(res.body["kind"], "clear");
24389+ assert_eq!(
24390+ res.body["epoch"], 0,
24391+ "the marker carries the epoch it closed"
24392+ );
24393+ assert_eq!(res.body["count"], 3);
24394+ assert!(res.body["payload"].is_null());
24395+
24396+ // The canvas is blank...
24397+ let res = send(
24398+ &app,
24399+ "GET",
24400+ &format!("/boards/{board}/strokes"),
24401+ Some(&ali),
24402+ None,
24403+ )
24404+ .await;
24405+ assert_eq!(common::total(&res.body), 0, "the canvas is empty");
24406+ assert!(common::items(&res.body).is_empty());
24407+
24408+ // ...and the history is not. 3 strokes + the marker.
24409+ let res = send(
24410+ &app,
24411+ "GET",
24412+ &format!("/boards/{board}/history"),
24413+ Some(&ali),
24414+ None,
24415+ )
24416+ .await;
24417+ assert_eq!(common::total(&res.body), 4);
24418+ let kept: Vec<&str> = common::items(&res.body)
24419+ .iter()
24420+ .map(|row| row["id"].as_str().unwrap())
24421+ .collect();
24422+ for id in &before {
24423+ assert!(kept.contains(&id.as_str()), "a clear lost stroke {id}");
24424+ }
24425+
24426+ // Asserted at the table too, not just through the reader that a bug could
24427+ // share with the writer.
24428+ let rows = stroke_rows(&db, &board).await;
24429+ assert_eq!(rows.len(), 4, "nothing was deleted");
24430+ let stored: Vec<String> = rows.iter().map(|r| r.get_id().key().to_string()).collect();
24431+ for id in &before {
24432+ assert!(stored.contains(id), "stroke {id} is gone from the table");
24433+ }
24434+
24435+ // Drawing resumes on the new epoch, and the old one is still readable
24436+ // whole through `?epoch=`.
24437+ let board_row = stored_board(&db, &board).await.unwrap();
24438+ assert_eq!(board_row.get_epoch(), 1);
24439+ draw(&db, &board, &ali_id, 1, "{\"p\":[9]}").await.unwrap();
24440+ let res = send(
24441+ &app,
24442+ "GET",
24443+ &format!("/boards/{board}/strokes"),
24444+ Some(&ali),
24445+ None,
24446+ )
24447+ .await;
24448+ assert_eq!(common::total(&res.body), 1, "the new canvas has one mark");
24449+ let res = send(
24450+ &app,
24451+ "GET",
24452+ &format!("/boards/{board}/history?epoch=0"),
24453+ Some(&ali),
24454+ None,
24455+ )
24456+ .await;
24457+ assert_eq!(common::total(&res.body), 4, "epoch 0 replays in full");
24458+ let res = send(
24459+ &app,
24460+ "GET",
24461+ &format!("/boards/{board}/history"),
24462+ Some(&ali),
24463+ None,
24464+ )
24465+ .await;
24466+ assert_eq!(common::total(&res.body), 5, "the whole session is one log");
24467+}
24468+
24469+/// The epoch index: one entry per clear, each carrying the final stroke count
24470+/// of the epoch it closed — which must equal the rows actually on the table for
24471+/// that epoch, or "replay session 2" replays the wrong thing.
24472+#[tokio::test]
24473+async fn the_epoch_index_counts_each_epoch_it_closed() {
24474+ let (app, db) = app_and_db().await;
24475+ let ali = login(&app, "ali").await;
24476+ let ali_id = me_id(&app, &ali).await;
24477+ let board = create_board(&app, &ali, "Geometri", &[]).await;
24478+
24479+ // Epoch 0 gets 2 marks, epoch 1 gets 3, then epoch 2 is left open.
24480+ for (epoch, marks) in [(0, 2), (1, 3)] {
24481+ for n in 0..marks {
24482+ draw(&db, &board, &ali_id, epoch, &format!("{{\"p\":[{n}]}}"))
24483+ .await
24484+ .unwrap();
24485+ }
24486+ let res = send(
24487+ &app,
24488+ "POST",
24489+ &format!("/boards/{board}/clear"),
24490+ Some(&ali),
24491+ None,
24492+ )
24493+ .await;
24494+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
24495+ }
24496+ draw(&db, &board, &ali_id, 2, "{\"p\":[7]}").await.unwrap();
24497+
24498+ let res = send(
24499+ &app,
24500+ "GET",
24501+ &format!("/boards/{board}/epochs"),
24502+ Some(&ali),
24503+ None,
24504+ )
24505+ .await;
24506+ assert_eq!(res.status, StatusCode::OK);
24507+ assert_eq!(common::total(&res.body), 2, "one marker per clear, no more");
24508+ let markers = common::items(&res.body);
24509+ assert_eq!(markers[0]["epoch"], 0);
24510+ assert_eq!(markers[0]["count"], 2);
24511+ assert_eq!(markers[1]["epoch"], 1);
24512+ assert_eq!(markers[1]["count"], 3);
24513+ for marker in markers {
24514+ assert_eq!(marker["kind"], "clear");
24515+ assert_eq!(marker["author"], ali_id.as_str());
24516+ }
24517+
24518+ // Each `count` against the rows really stored under that epoch.
24519+ let rows = stroke_rows(&db, &board).await;
24520+ for marker in markers {
24521+ let epoch = marker["epoch"].as_i64().unwrap();
24522+ let drawn = rows
24523+ .iter()
24524+ .filter(|row| row.get_epoch() == epoch && !row.is_clear())
24525+ .count() as i64;
24526+ assert_eq!(
24527+ marker["count"].as_i64().unwrap(),
24528+ drawn,
24529+ "marker for epoch {epoch} miscounts its strokes"
24530+ );
24531+ }
24532+ // The open epoch is deliberately absent — the markers *are* the index.
24533+ assert_eq!(stored_board(&db, &board).await.unwrap().get_epoch(), 2);
24534+}
24535+
24536+/// A full live canvas is a *recoverable* refusal: the board stays open and a
24537+/// clear hands the whole cap back.
24538+#[tokio::test]
24539+async fn a_full_canvas_is_refused_until_the_creator_clears_it() {
24540+ let (app, db) = app_and_db().await;
24541+ let ali = login(&app, "ali").await;
24542+ let ali_id = me_id(&app, &ali).await;
24543+ let board = create_board(&app, &ali, "Geometri", &[]).await;
24544+ set_counters(&db, &board, MAX_EPOCH_STROKES, MAX_EPOCH_STROKES).await;
24545+
24546+ let refused = draw(&db, &board, &ali_id, 0, "{\"p\":[1]}").await;
24547+ assert!(refused.is_err(), "a full canvas must refuse the append");
24548+ assert!(stroke_rows(&db, &board).await.is_empty(), "nothing written");
24549+ let stored = stored_board(&db, &board).await.unwrap();
24550+ assert!(
24551+ stored.get_closed_at().is_none(),
24552+ "a full canvas must NOT close the board — it is recoverable"
24553+ );
24554+ assert_eq!(
24555+ stored_counters(&db, &board).await,
24556+ vec![MAX_EPOCH_STROKES, MAX_EPOCH_STROKES],
24557+ "the refusal claimed nothing"
24558+ );
24559+
24560+ // The creator clears, and drawing resumes against a fresh cap.
24561+ let res = send(
24562+ &app,
24563+ "POST",
24564+ &format!("/boards/{board}/clear"),
24565+ Some(&ali),
24566+ None,
24567+ )
24568+ .await;
24569+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
24570+ assert_eq!(res.body["count"], MAX_EPOCH_STROKES);
24571+ assert!(
24572+ draw(&db, &board, &ali_id, 1, "{\"p\":[1]}").await.is_ok(),
24573+ "a clear must un-refuse the board"
24574+ );
24575+ assert_eq!(
24576+ stored_counters(&db, &board).await,
24577+ vec![1, MAX_EPOCH_STROKES + 1],
24578+ "the epoch counter reset; the lifetime counter did not"
24579+ );
24580+ let res = send(
24581+ &app,
24582+ "GET",
24583+ &format!("/boards/{board}/strokes"),
24584+ Some(&ali),
24585+ None,
24586+ )
24587+ .await;
24588+ assert_eq!(common::total(&res.body), 1, "the new mark is on the canvas");
24589+}
24590+
24591+/// The lifetime cap is the permanent one: it stamps `closed_at`, and a closed
24592+/// board still serves every read it ever served.
24593+#[tokio::test]
24594+async fn the_lifetime_cap_closes_the_board_and_it_stays_readable() {
24595+ let (app, db) = app_and_db().await;
24596+ let ali = login(&app, "ali").await;
24597+ let ali_id = me_id(&app, &ali).await;
24598+ let board = create_board(&app, &ali, "Geometri", &[]).await;
24599+ draw(&db, &board, &ali_id, 0, "{\"p\":[1]}").await.unwrap();
24600+ let res = send(
24601+ &app,
24602+ "POST",
24603+ &format!("/boards/{board}/clear"),
24604+ Some(&ali),
24605+ None,
24606+ )
24607+ .await;
24608+ assert_eq!(res.status, StatusCode::CREATED);
24609+ set_counters(&db, &board, 0, MAX_BOARD_STROKES).await;
24610+
24611+ assert!(
24612+ draw(&db, &board, &ali_id, 1, "{\"p\":[2]}").await.is_err(),
24613+ "the lifetime cap must refuse the append"
24614+ );
24615+ let stamp = stored_board(&db, &board)
24616+ .await
24617+ .unwrap()
24618+ .get_closed_at()
24619+ .expect("the lifetime cap stamps closed_at");
24620+ assert_eq!(stroke_rows(&db, &board).await.len(), 2, "nothing written");
24621+
24622+ // Permanently read-only: no more strokes, and no more clears either.
24623+ tokio::time::sleep(std::time::Duration::from_millis(2)).await;
24624+ assert!(draw(&db, &board, &ali_id, 1, "{\"p\":[3]}").await.is_err());
24625+ assert_eq!(
24626+ stored_board(&db, &board).await.unwrap().get_closed_at(),
24627+ Some(stamp),
24628+ "a second refusal must not re-stamp closed_at"
24629+ );
24630+ let res = send(
24631+ &app,
24632+ "POST",
24633+ &format!("/boards/{board}/clear"),
24634+ Some(&ali),
24635+ None,
24636+ )
24637+ .await;
24638+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
24639+
24640+ // Still fully readable — that is the whole point of closing rather than
24641+ // deleting.
24642+ let res = send(&app, "GET", &format!("/boards/{board}"), Some(&ali), None).await;
24643+ assert_eq!(res.status, StatusCode::OK);
24644+ assert_eq!(res.body["closed_at"], stamp.as_millis());
24645+ let res = send(
24646+ &app,
24647+ "GET",
24648+ &format!("/boards/{board}/history"),
24649+ Some(&ali),
24650+ None,
24651+ )
24652+ .await;
24653+ assert_eq!(common::total(&res.body), 2, "the whole log is still served");
24654+ let res = send(
24655+ &app,
24656+ "GET",
24657+ &format!("/boards/{board}/epochs"),
24658+ Some(&ali),
24659+ None,
24660+ )
24661+ .await;
24662+ assert_eq!(common::total(&res.body), 1);
24663+ let res = send(
24664+ &app,
24665+ "GET",
24666+ &format!("/boards/{board}/strokes"),
24667+ Some(&ali),
24668+ None,
24669+ )
24670+ .await;
24671+ assert_eq!(res.status, StatusCode::OK);
24672+ let res = send(&app, "GET", "/boards", Some(&ali), None).await;
24673+ assert_eq!(
24674+ common::total(&res.body),
24675+ 1,
24676+ "a closed board is still listed"
24677+ );
24678+}
24679+
24680+/// The per-creator cap, asserted on the stored counter — and a delete really
24681+/// hands the seat back, or a busy teacher's limit ratchets shut forever.
24682+#[tokio::test]
24683+async fn the_per_creator_cap_refuses_and_a_delete_frees_a_seat() {
24684+ let (app, db) = app_and_db().await;
24685+ let ali = login(&app, "ali").await;
24686+ let ali_id = me_id(&app, &ali).await;
24687+ let board = create_board(&app, &ali, "Geometri", &[]).await;
24688+ assert_eq!(stored_board_count(&db, &ali_id).await, 1);
24689+
24690+ // Age the counter to full rather than open 200 boards.
24691+ db.query("UPDATE $id SET board_count = $full")
24692+ .bind(("id", UserId::from_key(&ali_id).record()))
24693+ .bind(("full", MAX_BOARDS_PER_CREATOR))
24694+ .await
24695+ .unwrap()
24696+ .check()
24697+ .unwrap();
24698+
24699+ let res = send(
24700+ &app,
24701+ "POST",
24702+ "/boards",
24703+ Some(&ali),
24704+ Some(json!({ "title": "Bir tane daha" })),
24705+ )
24706+ .await;
24707+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
24708+ assert_eq!(
24709+ stored_board_count(&db, &ali_id).await,
24710+ MAX_BOARDS_PER_CREATOR,
24711+ "the refusal must not have claimed a seat"
24712+ );
24713+ let mut result = db
24714+ .query("SELECT VALUE id FROM board")
24715+ .await
24716+ .unwrap()
24717+ .check()
24718+ .unwrap();
24719+ assert_eq!(
24720+ result
24721+ .take::<Vec<surrealdb::types::RecordId>>(0)
24722+ .unwrap()
24723+ .len(),
24724+ 1,
24725+ "no row was written by the refused create"
24726+ );
24727+
24728+ // Deleting frees exactly one seat, and the next create takes it.
24729+ let res = send(
24730+ &app,
24731+ "DELETE",
24732+ &format!("/boards/{board}"),
24733+ Some(&ali),
24734+ None,
24735+ )
24736+ .await;
24737+ assert_eq!(res.status, StatusCode::NO_CONTENT);
24738+ assert_eq!(
24739+ stored_board_count(&db, &ali_id).await,
24740+ MAX_BOARDS_PER_CREATOR - 1,
24741+ "the delete handed the seat back"
24742+ );
24743+ let next = create_board(&app, &ali, "Bir tane daha", &[]).await;
24744+ assert_eq!(
24745+ stored_board_count(&db, &ali_id).await,
24746+ MAX_BOARDS_PER_CREATOR
24747+ );
24748+ assert!(stored_board(&db, &next).await.is_some());
24749+ // And the deleted board is gone for its own creator too.
24750+ let res = send(&app, "GET", &format!("/boards/{board}"), Some(&ali), None).await;
24751+ assert_eq!(res.status, StatusCode::NOT_FOUND);
24752+}
24753+
24754+/// The `next_ulid` hazard, over HTTP: a burst of marks all lands inside one or
24755+/// two milliseconds, and `Ulid::new()` would sort those rows at random
24756+/// (src/domain/monotonic_id.rs:41-46). The canvas is a drawing, so an order
24757+/// that shuffles is a drawing that redraws wrong.
24758+#[tokio::test]
24759+async fn a_burst_of_strokes_comes_back_in_mint_order() {
24760+ let (app, db) = app_and_db().await;
24761+ let ali = login(&app, "ali").await;
24762+ let ali_id = me_id(&app, &ali).await;
24763+ let board = create_board(&app, &ali, "Geometri", &[]).await;
24764+
24765+ let mut minted = Vec::new();
24766+ for n in 0..60 {
24767+ minted.push(
24768+ draw(&db, &board, &ali_id, 0, &format!("{{\"p\":[{n}]}}"))
24769+ .await
24770+ .unwrap()
24771+ .get_id()
24772+ .key()
24773+ .to_string(),
24774+ );
24775+ }
24776+ // Whether *those* 60 shared a millisecond depends on how loaded the
24777+ // machine is, so the same-millisecond half of the hazard is pinned with no
24778+ // database in the way: a tight mint loop that certainly does share one, and
24779+ // `ORDER BY id` on a string key is a plain string sort — so mint order must
24780+ // already BE sorted order. `Ulid::new()` fails this within a few ids.
24781+ let ids: Vec<String> = (0..500)
24782+ .map(|_| BoardStrokeId::generate().key().to_string())
24783+ .collect();
24784+ let mut sorted = ids.clone();
24785+ sorted.sort();
24786+ assert_eq!(
24787+ sorted, ids,
24788+ "ids minted in one millisecond must sort in mint order"
24789+ );
24790+
24791+ let res = send(
24792+ &app,
24793+ "GET",
24794+ &format!("/boards/{board}/strokes"),
24795+ Some(&ali),
24796+ None,
24797+ )
24798+ .await;
24799+ let served: Vec<&str> = common::items(&res.body)
24800+ .iter()
24801+ .map(|row| row["id"].as_str().unwrap())
24802+ .collect();
24803+ assert_eq!(served, minted, "/strokes must replay in mint order");
24804+ let res = send(
24805+ &app,
24806+ "GET",
24807+ &format!("/boards/{board}/history"),
24808+ Some(&ali),
24809+ None,
24810+ )
24811+ .await;
24812+ let served: Vec<&str> = common::items(&res.body)
24813+ .iter()
24814+ .map(|row| row["id"].as_str().unwrap())
24815+ .collect();
24816+ assert_eq!(served, minted, "/history must replay in mint order too");
24817+ // And the payloads ride along in that same order.
24818+ let payloads: Vec<String> = common::items(&res.body)
24819+ .iter()
24820+ .map(|row| row["payload"].as_str().unwrap().to_string())
24821+ .collect();
24822+ assert_eq!(payloads[0], "{\"p\":[0]}");
24823+ assert_eq!(payloads[59], "{\"p\":[59]}");
24824+}
tests/pagination.rsmodified+141 -0
@@ -388,3 +388,144 @@ async fn user_search_is_paged_not_capped() {
388 assert_eq!(res.status, StatusCode::OK);388 assert_eq!(res.status, StatusCode::OK);
389 assert_eq!(total(&res.body), 1, "role scope excludes the students");389 assert_eq!(total(&res.body), 1, "role scope excludes the students");
390 }390 }
391+
392+/// The whiteboard's four lists all speak the envelope: the board list, the live
393+/// canvas, the whole history and the epoch index. `/epochs` is the odd one —
394+/// it pages in the web layer over a bounded read (`web/boards.rs:391`), so it
395+/// gets the same windowing proof as the three DB-paged lists.
396+#[tokio::test]
397+async fn board_lists_are_paged() {
398+ let (app, db) = app_and_db().await;
399+ let ali = login(&app, "ali").await;
400+ let ali_id = me_id(&app, &ali).await;
401+
402+ // Three boards, and one of them carries the strokes.
403+ let mut boards = Vec::new();
404+ for n in 0..3 {
405+ let res = send(
406+ &app,
407+ "POST",
408+ "/boards",
409+ Some(&ali),
410+ Some(json!({ "title": format!("Tahta {n}") })),
411+ )
412+ .await;
413+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
414+ boards.push(res.body["id"].as_str().unwrap().to_string());
415+ }
416+ let board = boards[0].clone();
417+
418+ // Two closed epochs of 2 marks each, then 5 live ones: 2 markers in the
419+ // index, 11 rows in the history (4 marks + 2 markers + 5 live), 5 on the
420+ // canvas.
421+ for epoch in 0..2 {
422+ for n in 0..2 {
423+ hezarfen_backend::domain::board_stroke::BoardStroke::append(
424+ &hezarfen_backend::domain::board::BoardId::from_key(&board),
425+ &hezarfen_backend::domain::user::UserId::from_key(&ali_id),
426+ &format!("{{\"p\":[{epoch},{n}]}}"),
427+ epoch,
428+ &db,
429+ )
430+ .await
431+ .expect("append");
432+ }
433+ let res = send(
434+ &app,
435+ "POST",
436+ &format!("/boards/{board}/clear"),
437+ Some(&ali),
438+ None,
439+ )
440+ .await;
441+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
442+ }
443+ for n in 0..5 {
444+ hezarfen_backend::domain::board_stroke::BoardStroke::append(
445+ &hezarfen_backend::domain::board::BoardId::from_key(&board),
446+ &hezarfen_backend::domain::user::UserId::from_key(&ali_id),
447+ &format!("{{\"p\":[2,{n}]}}"),
448+ 2,
449+ &db,
450+ )
451+ .await
452+ .expect("append");
453+ }
454+
455+ for (uri, count) in [
456+ ("/boards".to_string(), 3),
457+ (format!("/boards/{board}/strokes"), 5),
458+ (format!("/boards/{board}/history"), 11),
459+ (format!("/boards/{board}/epochs"), 2),
460+ ] {
461+ // Unpaged: everything, `limit` echoes null.
462+ let res = send(&app, "GET", &uri, Some(&ali), None).await;
463+ assert_eq!(res.status, StatusCode::OK, "GET {uri}: {}", res.body);
464+ assert_eq!(total(&res.body), count, "GET {uri} total");
465+ assert_eq!(items(&res.body).len() as i64, count, "GET {uri} items");
466+ assert!(res.body["limit"].is_null(), "GET {uri} echoes a null limit");
467+ assert_eq!(res.body["offset"], 0);
468+
469+ // A window of 1: the total stays the unpaged count, the windows are
470+ // disjoint, and the page past the end is empty rather than an error.
471+ let res = send(
472+ &app,
473+ "GET",
474+ &format!("{uri}?limit=1&offset=0"),
475+ Some(&ali),
476+ None,
477+ )
478+ .await;
479+ assert_eq!(total(&res.body), count, "GET {uri} windowed total");
480+ assert_eq!(items(&res.body).len(), 1, "GET {uri} window size");
481+ assert_eq!(res.body["limit"], 1);
482+ let first = items(&res.body)[0]["id"].clone();
483+ let res = send(
484+ &app,
485+ "GET",
486+ &format!("{uri}?limit=1&offset=1"),
487+ Some(&ali),
488+ None,
489+ )
490+ .await;
491+ assert_eq!(res.body["offset"], 1);
492+ assert_ne!(items(&res.body)[0]["id"], first, "GET {uri} pages overlap");
493+ let res = send(
494+ &app,
495+ "GET",
496+ &format!("{uri}?limit=1&offset=99"),
497+ Some(&ali),
498+ None,
499+ )
500+ .await;
501+ assert_eq!(res.status, StatusCode::OK);
502+ assert!(items(&res.body).is_empty(), "GET {uri} past the end");
503+ assert_eq!(total(&res.body), count, "GET {uri} total stays honest");
504+
505+ // The shared bounds bite on every one of them.
506+ for bad in ["limit=0", "limit=501", "offset=-1"] {
507+ let res = send(&app, "GET", &format!("{uri}?{bad}"), Some(&ali), None).await;
508+ assert_eq!(
509+ res.status,
510+ StatusCode::BAD_REQUEST,
511+ "GET {uri}?{bad} should be 400"
512+ );
513+ }
514+ }
515+
516+ // `?epoch=` narrows the history and still pages: epoch 0 is 2 marks plus
517+ // the marker that closed it.
518+ let uri = format!("/boards/{board}/history?epoch=0");
519+ let res = send(&app, "GET", &uri, Some(&ali), None).await;
520+ assert_eq!(total(&res.body), 3, "{}", res.body);
521+ let res = send(
522+ &app,
523+ "GET",
524+ &format!("{uri}&limit=2&offset=2"),
525+ Some(&ali),
526+ None,
527+ )
528+ .await;
529+ assert_eq!(total(&res.body), 3, "the scoped total is the scoped count");
530+ assert_eq!(items(&res.body).len(), 1, "offset 2 of 3 leaves 1");
531+}
tests/persistence.rsmodified+144 -0
@@ -1759,3 +1759,147 @@ async fn a_user_row_without_palette_color_still_reads_and_patches() {
1759 assert_eq!(set.status, StatusCode::OK, "{}", set.body);1759 assert_eq!(set.status, StatusCode::OK, "{}", set.body);
1760 assert_eq!(set.body["palette_color"], "#fefae0");1760 assert_eq!(set.body["palette_color"], "#fefae0");
1761 }1761 }
1762+
1763+/// A whiteboard, its whole stroke log and the creator's `board_count` all
1764+/// survive a second boot. `board_count` is the authority on how many boards a
1765+/// creator holds, so a migration that reset it would ratchet a busy teacher's
1766+/// limit — and the strokes are the one thing in this feature that a clear is
1767+/// promised never to lose.
1768+#[tokio::test]
1769+async fn boards_and_their_strokes_survive_remigration() {
1770+ let (app, db) = common::app_and_db().await;
1771+ let creds = json!({ "username": "ali", "password": "secret1" });
1772+ let cookie = common::login(&app, "ali").await;
1773+ let veli = common::login(&app, "veli").await;
1774+ let ali_id = me_id(&app, &cookie).await;
1775+ let veli_id = me_id(&app, &veli).await;
1776+
1777+ let res = send(
1778+ &app,
1779+ "POST",
1780+ "/boards",
1781+ Some(&cookie),
1782+ Some(json!({ "title": "Geometri", "participant_ids": [veli_id] })),
1783+ )
1784+ .await;
1785+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
1786+ let board = res.body["id"].as_str().unwrap().to_string();
1787+
1788+ // Two epochs: two marks cleared away, then one live mark.
1789+ let draw = async |epoch: i64, payload: &str| {
1790+ hezarfen_backend::domain::board_stroke::BoardStroke::append(
1791+ &hezarfen_backend::domain::board::BoardId::from_key(&board),
1792+ &hezarfen_backend::domain::user::UserId::from_key(&ali_id),
1793+ payload,
1794+ epoch,
1795+ &db,
1796+ )
1797+ .await
1798+ .expect("append")
1799+ };
1800+ draw(0, "{\"p\":[1]}").await;
1801+ draw(0, "{\"p\":[2]}").await;
1802+ let res = send(
1803+ &app,
1804+ "POST",
1805+ &format!("/boards/{board}/clear"),
1806+ Some(&cookie),
1807+ None,
1808+ )
1809+ .await;
1810+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
1811+ draw(1, "{\"p\":[3]}").await;
1812+
1813+ // Second boot: the migration re-applied over live board data.
1814+ let app = reboot(&db).await;
1815+ let cookie = send(&app, "POST", "/auth/login", None, Some(creds))
1816+ .await
1817+ .cookie
1818+ .unwrap();
1819+
1820+ let res = send(
1821+ &app,
1822+ "GET",
1823+ &format!("/boards/{board}"),
1824+ Some(&cookie),
1825+ None,
1826+ )
1827+ .await;
1828+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1829+ assert_eq!(res.body["title"], "Geometri");
1830+ assert_eq!(res.body["creator"], ali_id.as_str());
1831+ assert_eq!(res.body["participants"], json!([veli_id]));
1832+ assert_eq!(res.body["epoch"], 1, "the epoch survived");
1833+ assert!(res.body["closed_at"].is_null());
1834+
1835+ // The log came back whole: 2 marks, the marker that counted them, 1 live.
1836+ let res = send(
1837+ &app,
1838+ "GET",
1839+ &format!("/boards/{board}/history"),
1840+ Some(&cookie),
1841+ None,
1842+ )
1843+ .await;
1844+ assert_eq!(common::total(&res.body), 4, "{}", res.body);
1845+ let rows = common::items(&res.body);
1846+ assert_eq!(rows[0]["payload"], "{\"p\":[1]}");
1847+ assert_eq!(rows[2]["kind"], "clear");
1848+ assert_eq!(rows[2]["count"], 2, "the marker kept its count");
1849+ assert_eq!(rows[3]["payload"], "{\"p\":[3]}");
1850+ let res = send(
1851+ &app,
1852+ "GET",
1853+ &format!("/boards/{board}/strokes"),
1854+ Some(&cookie),
1855+ None,
1856+ )
1857+ .await;
1858+ assert_eq!(
1859+ common::total(&res.body),
1860+ 1,
1861+ "the live canvas is the new epoch"
1862+ );
1863+
1864+ // The counters the schema carries but the struct does not, straight from
1865+ // the row: a re-migration must not have reset either of them.
1866+ let mut result = db
1867+ .query(
1868+ "SELECT VALUE [epoch_stroke_count ?? 0, total_stroke_count ?? 0, \
1869+ (SELECT VALUE board_count ?? 0 FROM $usr)[0]] FROM $id",
1870+ )
1871+ .bind((
1872+ "id",
1873+ hezarfen_backend::domain::board::BoardId::from_key(&board).record(),
1874+ ))
1875+ .bind((
1876+ "usr",
1877+ hezarfen_backend::domain::user::UserId::from_key(&ali_id).record(),
1878+ ))
1879+ .await
1880+ .unwrap()
1881+ .check()
1882+ .unwrap();
1883+ assert_eq!(
1884+ result.take::<Vec<Vec<i64>>>(0).unwrap()[0],
1885+ vec![1, 3, 1],
1886+ "epoch counter, lifetime counter and the creator's board_count"
1887+ );
1888+
1889+ // And the board is still writable after the boot — the counters that came
1890+ // back are the ones the cap reads.
1891+ draw(1, "{\"p\":[4]}").await;
1892+ let res = send(
1893+ &app,
1894+ "GET",
1895+ &format!("/boards/{board}/strokes"),
1896+ Some(&cookie),
1897+ None,
1898+ )
1899+ .await;
1900+ assert_eq!(
1901+ common::total(&res.body),
1902+ 2,
1903+ "drawing resumed after the boot"
1904+ );
1905+}