diff --git a/src/domain/board.rs b/src/domain/board.rs index ff108ed..c3101ff 100644 --- a/src/domain/board.rs +++ b/src/domain/board.rs @@ -13,6 +13,7 @@ //! `CONTENT` save would silently wipe both (src/constant.rs:717-722). use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use tokio::sync::Mutex; use crate::constant::{ BOARD_TABLE, MAX_BOARD_PARTICIPANTS, MAX_BOARD_TITLE_LEN, MAX_BOARDS_PER_CREATOR, @@ -27,6 +28,32 @@ use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use crate::validate::validate_required; +/// Serializes every **read-modify-write** of a board's `participants` array: +/// `POST /boards/{id}/invite` (union the resolved group into the roster it just +/// read) and the roster branch of `PATCH /boards/{id}` (which reads the current +/// list to decide which no-longer-eligible ids survive). +/// +/// [`Board::set_participants`] stores the whole array, so two invites that both +/// read roster `R` write `R ∪ X` and `R ∪ Y` and the second one silently drops +/// the first one's group — a caller told `200` with a list of people who are not +/// on the board, against the route's own "strictly additive" contract. The +/// database cannot refuse that: both are single well-formed writes to one field, +/// and neither is wrong on its own. +/// +/// A lock rather than a compare-and-set because the deployment is one process +/// with stop-the-world deploys, so it genuinely serializes — and because the +/// alternative answer is a `409` on a race between two calls that do not +/// conflict in intent, which a client could only resolve by re-sending the same +/// invite. Contended invites simply queue; the section they hold is one board +/// read, one user-list read and one field write. +/// +/// **A leaf**: nothing under it takes another lock. Note it does not reach the +/// demotion sweep in [`crate::domain::user::User::set_role`], which strips ids +/// from every roster inside the role write's own transaction — an invite that +/// read a roster before that sweep can put a swept id back, which the boot +/// repair and the room's own live gate both still catch. +pub(crate) static BOARD_ROSTER_LOCK: Mutex<()> = Mutex::const_new(()); + #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct BoardId(RecordId); diff --git a/src/web/boards.rs b/src/web/boards.rs index 581bc0b..a81a945 100644 --- a/src/web/boards.rs +++ b/src/web/boards.rs @@ -29,7 +29,7 @@ use utoipa_axum::routes; use crate::constant::MAX_BOARD_PARTICIPANTS; use crate::database::Database; -use crate::domain::board::{Board, BoardId, BoardTitle}; +use crate::domain::board::{BOARD_ROSTER_LOCK, Board, BoardId, BoardTitle}; use crate::domain::board_stroke::BoardStroke; use crate::domain::class_group::{ClassGroup, ClassGroupId}; use crate::domain::class_member::ClassMember; @@ -540,6 +540,14 @@ async fn update_board( Path(id): Path, Json(req): Json, ) -> Result, AppError> { + // A roster PATCH reads the current list (to keep the ids that stopped + // qualifying) before replacing it, so it is the other read-modify-write of + // this field and takes the same lock — one an invite could otherwise land + // inside. Title- and lock-only edits never touch the array and are not held. + let _guard = match req.participants.is_some() { + true => Some(BOARD_ROSTER_LOCK.lock().await), + false => None, + }; let mut board = board_for(&id, &user, &st.db).await?; if req.participants.is_some() || req.locked.is_some() { ensure_creator(&board, &user)?; @@ -805,6 +813,11 @@ async fn invite_board( Path(id): Path, Json(req): Json, ) -> Result, AppError> { + // Held across the read *and* the write: this is a read-modify-write of one + // array, so two invites landing together would each union their group into + // the same roster and the second write would drop the first one's people — + // silently, with both callers told 200. See [`BOARD_ROSTER_LOCK`]. + let _guard = BOARD_ROSTER_LOCK.lock().await; let board = board_for(&id, &user, &st.db).await?; ensure_creator(&board, &user)?; let invited = req.resolve(&user, &st.db).await?; diff --git a/tests/board_invite.rs b/tests/board_invite.rs index 6fc44e3..56c907d 100644 --- a/tests/board_invite.rs +++ b/tests/board_invite.rs @@ -546,3 +546,54 @@ async fn the_reply_carries_the_widened_roster() { res.body ); } + +/// Two invites landing at once must both stick. The handler unions its group +/// into the roster it read a moment earlier and stores the whole array back, so +/// without a lock across that read-modify-write both calls read roster `R`, one +/// writes `R ∪ A`, the other `R ∪ B`, and the loser's whole group is silently +/// absent from a board its caller was told `200` with — the exact opposite of +/// this route's "strictly additive, nothing is ever removed by it" contract. +/// +/// Stored state is the verdict, read back off `GET /boards/{id}` rather than +/// from either reply. (The lock is in-process, which is a real serializer here: +/// one process, stop-the-world deploys.) +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn two_invites_landing_together_keep_both_groups() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "manager_r", "manager").await; + let teacher = login_as(&app, &db, "teacher_r", "teacher").await; + let mut ids = Vec::new(); + for name in ["ali", "ayse", "deniz", "hakan"] { + let cookie = login(&app, name).await; + ids.push(me_id(&app, &cookie).await); + } + + let first = a_class(&app, &manager, "9-R", &[&ids[0], &ids[1]]).await; + let second = a_class(&app, &manager, "9-S", &[&ids[2], &ids[3]]).await; + let board = a_board(&app, &teacher).await; + + let both = [first, second].map(|class| { + let (app, teacher, board) = (app.clone(), teacher.clone(), board.clone()); + tokio::spawn(async move { + invite( + &app, + &teacher, + &board, + json!({"kind": "class", "class": class}), + ) + .await + }) + }); + for call in both { + let res = call.await.expect("invite task"); + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + } + + let mut expected = ids.clone(); + expected.sort(); + assert_eq!( + roster(&app, &teacher, &board).await, + expected, + "one group was dropped: an invite is additive, and both callers were told 200" + ); +}