forge
Explore
Log in

Don't you dare go Hollow

🎨 stop a bulk board invite from dropping the other invite's group

Browse files at this commit

03467171d2a77c2afca2575cd47f2d2e67e7818fAhmet Kaan GümüşParent: c998c0d
  • fix
    • 🎨 stop a bulk board invite from dropping the other invite's group
Show full message
fix: 🎨 stop a bulk board invite from dropping the other invite's group

`POST /boards/{id}/invite` reads the roster, unions its resolved group
into it, and stores the whole array back. Two invites from the creator
landing together both read roster R: one writes R∪A, the other R∪B, and
the second commit silently drops the first one's people — with both
callers told 200 and a list of participants who are not on the board,
against the route's own "strictly additive, nothing is ever removed by
it" contract. Neither write is wrong on its own, so the database cannot
refuse it; it is a lost update, not an over-cap.

Closed with an in-process lock over the whole read-modify-write, which
genuinely serializes here (one process, stop-the-world deploys) and,
unlike a compare-and-set, does not answer 409 to two calls that do not
conflict in intent. The cap is then checked against the roster actually
read under the lock, so the stored value is the checked value. The
roster branch of `PATCH /boards/{id}` takes the same lock — it reads the
current list before replacing it, so it is the other read-modify-write
of that field, and a lock only half the writers take serializes nothing.

The regression test races two class invites and reads the roster back
off the server: without the lock it drops one group, 2 of 4 members.
src/domain/board.rsmodified+27 -0
@@ -13,6 +13,7 @@
13 //! `CONTENT` save would silently wipe both (src/constant.rs:717-722).13 //! `CONTENT` save would silently wipe both (src/constant.rs:717-722).
14 14
15 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};15 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
16+use tokio::sync::Mutex;
16 17
17 use crate::constant::{18 use crate::constant::{
18 BOARD_TABLE, MAX_BOARD_PARTICIPANTS, MAX_BOARD_TITLE_LEN, MAX_BOARDS_PER_CREATOR,19 BOARD_TABLE, MAX_BOARD_PARTICIPANTS, MAX_BOARD_TITLE_LEN, MAX_BOARDS_PER_CREATOR,
@@ -27,6 +28,32 @@ use crate::domain::user::UserId;
27 use crate::error::{AppError, ValidationError};28 use crate::error::{AppError, ValidationError};
28 use crate::validate::validate_required;29 use crate::validate::validate_required;
29 30
31+/// Serializes every **read-modify-write** of a board's `participants` array:
32+/// `POST /boards/{id}/invite` (union the resolved group into the roster it just
33+/// read) and the roster branch of `PATCH /boards/{id}` (which reads the current
34+/// list to decide which no-longer-eligible ids survive).
35+///
36+/// [`Board::set_participants`] stores the whole array, so two invites that both
37+/// read roster `R` write `R ∪ X` and `R ∪ Y` and the second one silently drops
38+/// the first one's group — a caller told `200` with a list of people who are not
39+/// on the board, against the route's own "strictly additive" contract. The
40+/// database cannot refuse that: both are single well-formed writes to one field,
41+/// and neither is wrong on its own.
42+///
43+/// A lock rather than a compare-and-set because the deployment is one process
44+/// with stop-the-world deploys, so it genuinely serializes — and because the
45+/// alternative answer is a `409` on a race between two calls that do not
46+/// conflict in intent, which a client could only resolve by re-sending the same
47+/// invite. Contended invites simply queue; the section they hold is one board
48+/// read, one user-list read and one field write.
49+///
50+/// **A leaf**: nothing under it takes another lock. Note it does not reach the
51+/// demotion sweep in [`crate::domain::user::User::set_role`], which strips ids
52+/// from every roster inside the role write's own transaction — an invite that
53+/// read a roster before that sweep can put a swept id back, which the boot
54+/// repair and the room's own live gate both still catch.
55+pub(crate) static BOARD_ROSTER_LOCK: Mutex<()> = Mutex::const_new(());
56+
30 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]57 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
31 pub struct BoardId(RecordId);58 pub struct BoardId(RecordId);
32 59
src/web/boards.rsmodified+14 -1
@@ -29,7 +29,7 @@ use utoipa_axum::routes;
29 29
30 use crate::constant::MAX_BOARD_PARTICIPANTS;30 use crate::constant::MAX_BOARD_PARTICIPANTS;
31 use crate::database::Database;31 use crate::database::Database;
32-use crate::domain::board::{Board, BoardId, BoardTitle};32+use crate::domain::board::{BOARD_ROSTER_LOCK, Board, BoardId, BoardTitle};
33 use crate::domain::board_stroke::BoardStroke;33 use crate::domain::board_stroke::BoardStroke;
34 use crate::domain::class_group::{ClassGroup, ClassGroupId};34 use crate::domain::class_group::{ClassGroup, ClassGroupId};
35 use crate::domain::class_member::ClassMember;35 use crate::domain::class_member::ClassMember;
@@ -540,6 +540,14 @@ async fn update_board(
540 Path(id): Path<String>,540 Path(id): Path<String>,
541 Json(req): Json<UpdateBoard>,541 Json(req): Json<UpdateBoard>,
542 ) -> Result<Json<BoardResponse>, AppError> {542 ) -> Result<Json<BoardResponse>, AppError> {
543+ // A roster PATCH reads the current list (to keep the ids that stopped
544+ // qualifying) before replacing it, so it is the other read-modify-write of
545+ // this field and takes the same lock — one an invite could otherwise land
546+ // inside. Title- and lock-only edits never touch the array and are not held.
547+ let _guard = match req.participants.is_some() {
548+ true => Some(BOARD_ROSTER_LOCK.lock().await),
549+ false => None,
550+ };
543 let mut board = board_for(&id, &user, &st.db).await?;551 let mut board = board_for(&id, &user, &st.db).await?;
544 if req.participants.is_some() || req.locked.is_some() {552 if req.participants.is_some() || req.locked.is_some() {
545 ensure_creator(&board, &user)?;553 ensure_creator(&board, &user)?;
@@ -805,6 +813,11 @@ async fn invite_board(
805 Path(id): Path<String>,813 Path(id): Path<String>,
806 Json(req): Json<InviteSource>,814 Json(req): Json<InviteSource>,
807 ) -> Result<Json<BoardResponse>, AppError> {815 ) -> Result<Json<BoardResponse>, AppError> {
816+ // Held across the read *and* the write: this is a read-modify-write of one
817+ // array, so two invites landing together would each union their group into
818+ // the same roster and the second write would drop the first one's people —
819+ // silently, with both callers told 200. See [`BOARD_ROSTER_LOCK`].
820+ let _guard = BOARD_ROSTER_LOCK.lock().await;
808 let board = board_for(&id, &user, &st.db).await?;821 let board = board_for(&id, &user, &st.db).await?;
809 ensure_creator(&board, &user)?;822 ensure_creator(&board, &user)?;
810 let invited = req.resolve(&user, &st.db).await?;823 let invited = req.resolve(&user, &st.db).await?;
tests/board_invite.rsmodified+51 -0
@@ -546,3 +546,54 @@ async fn the_reply_carries_the_widened_roster() {
546 res.body546 res.body
547 );547 );
548 }548 }
549+
550+/// Two invites landing at once must both stick. The handler unions its group
551+/// into the roster it read a moment earlier and stores the whole array back, so
552+/// without a lock across that read-modify-write both calls read roster `R`, one
553+/// writes `R ∪ A`, the other `R ∪ B`, and the loser's whole group is silently
554+/// absent from a board its caller was told `200` with — the exact opposite of
555+/// this route's "strictly additive, nothing is ever removed by it" contract.
556+///
557+/// Stored state is the verdict, read back off `GET /boards/{id}` rather than
558+/// from either reply. (The lock is in-process, which is a real serializer here:
559+/// one process, stop-the-world deploys.)
560+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
561+async fn two_invites_landing_together_keep_both_groups() {
562+ let (app, db) = app_and_db().await;
563+ let manager = login_as(&app, &db, "manager_r", "manager").await;
564+ let teacher = login_as(&app, &db, "teacher_r", "teacher").await;
565+ let mut ids = Vec::new();
566+ for name in ["ali", "ayse", "deniz", "hakan"] {
567+ let cookie = login(&app, name).await;
568+ ids.push(me_id(&app, &cookie).await);
569+ }
570+
571+ let first = a_class(&app, &manager, "9-R", &[&ids[0], &ids[1]]).await;
572+ let second = a_class(&app, &manager, "9-S", &[&ids[2], &ids[3]]).await;
573+ let board = a_board(&app, &teacher).await;
574+
575+ let both = [first, second].map(|class| {
576+ let (app, teacher, board) = (app.clone(), teacher.clone(), board.clone());
577+ tokio::spawn(async move {
578+ invite(
579+ &app,
580+ &teacher,
581+ &board,
582+ json!({"kind": "class", "class": class}),
583+ )
584+ .await
585+ })
586+ });
587+ for call in both {
588+ let res = call.await.expect("invite task");
589+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
590+ }
591+
592+ let mut expected = ids.clone();
593+ expected.sort();
594+ assert_eq!(
595+ roster(&app, &teacher, &board).await,
596+ expected,
597+ "one group was dropped: an invite is additive, and both callers were told 200"
598+ );
599+}