diff --git a/src/domain/event.rs b/src/domain/event.rs index 9abd444..bb25a5f 100644 --- a/src/domain/event.rs +++ b/src/domain/event.rs @@ -1,6 +1,7 @@ // `Value` looks unused but is load-bearing: the `SurrealValue` derive on the // tagged `EventAudience` enum expands to code that names `Value` unqualified. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value}; +use tokio::sync::Mutex; use ulid::Ulid; use crate::constant::{MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN}; @@ -15,6 +16,20 @@ use crate::domain::user::{User, UserId}; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_optional, validate_required}; +/// Serializes the schedule-range check against the write it guards, exactly as +/// `TERM_LOCK` does for terms: `starts_at <= ends_at` is a cross-field check, +/// so a partial PATCH validates the end it carries against the *stored* other +/// end — two such PATCHes, each fine on its own snapshot, would otherwise +/// commit an inverted range between them. A PATCH that moves neither end +/// checks nothing cross-field and stays lock-free. +/// +/// Lock order: this is a leaf — the only path that takes it (`PATCH +/// /events/{id}`) takes no other lock, and no path that holds `REGISTER_LOCK`, +/// `ENROLL_LOCK`, `TERM_LOCK`, `EXAM_LOCK` or any other takes this one, so it +/// cannot sit in a cycle. Should a future path need both, take the other lock +/// first and this one innermost. +pub(crate) static EVENT_LOCK: Mutex<()> = Mutex::const_new(()); + #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct EventId(RecordId); diff --git a/src/domain/work_entry.rs b/src/domain/work_entry.rs index d1935c1..39b1c2c 100644 --- a/src/domain/work_entry.rs +++ b/src/domain/work_entry.rs @@ -1,4 +1,5 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use tokio::sync::Mutex; use ulid::Ulid; use crate::database::{Database, WORK_ENTRY_TABLE}; @@ -7,6 +8,20 @@ use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; +/// Serializes a stint correction's ordering check against the write it guards, +/// exactly as `TERM_LOCK` does for terms: `check_in <= check_out` is a +/// cross-field check, so a correction of one instant validates against the +/// *stored* other one — two such corrections, each fine on its own snapshot, +/// would otherwise commit an inverted stint between them. Check-in/check-out +/// themselves stay lock-free (they are atomic single-row writes), and a PATCH +/// carrying neither instant checks nothing cross-field. +/// +/// Lock order: this is a leaf — the only path that takes it (`PATCH +/// /work/entries/{id}`) takes no other lock, and no path holding another lock +/// takes this one, so it cannot sit in a cycle. Should a future path need +/// both, take the other lock first and this one innermost. +pub(crate) static WORK_ENTRY_LOCK: Mutex<()> = Mutex::const_new(()); + #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct WorkEntryId(RecordId); diff --git a/src/web/events.rs b/src/web/events.rs index 2a34303..140fb2e 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -11,7 +11,9 @@ use utoipa_axum::routes; use crate::database::Database; use crate::domain::attendance::{Attendance, AttendanceStatus}; use crate::domain::course::{Course, CourseId}; -use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle}; +use crate::domain::event::{ + EVENT_LOCK, Event, EventAudience, EventDescription, EventId, EventTitle, +}; use crate::domain::registration::Registration; use crate::domain::role::Role; use crate::domain::settings::Settings; @@ -335,6 +337,22 @@ async fn update_event( Path(id): Path, Json(req): Json, ) -> Result, AppError> { + // The schedule columns are nullable, so they keep the outer/inner + // distinction: a provided value sets the field, an explicit `null` clears + // it, and an omitted one is left alone. + let starts_at = req + .starts_at + .map(|update| update.map(Timestamp::from_millis)); + let ends_at = req.ends_at.map(|update| update.map(Timestamp::from_millis)); + // Only the range check needs the stored row, and only it can race: it + // validates an arriving end against the other end as stored, so the read, + // the check and the write are held together under [`EVENT_LOCK`]. A PATCH + // that moves neither end pays nothing. + let _guard = match (starts_at, ends_at) { + (None, None) => None, + _ => Some(EVENT_LOCK.lock().await), + }; + let event = Event::read(&EventId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; @@ -359,14 +377,8 @@ async fn update_event( Some(audience) => Some(audience.into_domain(&st.db).await?), None => None, }; - // The schedule columns are nullable, so they keep the outer/inner - // distinction: a provided value sets the field, an explicit `null` clears - // it, and an omitted one is left alone. Only set values are held to the - // no-past rule — a kept time of an event already underway may be past. - let starts_at = req - .starts_at - .map(|update| update.map(Timestamp::from_millis)); - let ends_at = req.ends_at.map(|update| update.map(Timestamp::from_millis)); + // Only set schedule values are held to the no-past rule — a kept time of + // an event already underway may be past. if let Some(starts_at) = starts_at { check_not_past("starts_at", starts_at)?; } diff --git a/src/web/work.rs b/src/web/work.rs index 2e38ac5..c48e021 100644 --- a/src/web/work.rs +++ b/src/web/work.rs @@ -8,7 +8,7 @@ use utoipa_axum::routes; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; -use crate::domain::work_entry::{WorkEntry, WorkEntryId}; +use crate::domain::work_entry::{WORK_ENTRY_LOCK, WorkEntry, WorkEntryId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; @@ -198,6 +198,17 @@ async fn update_entry( Path(id): Path, Json(req): Json, ) -> Result, AppError> { + let check_in = req.check_in.map(Timestamp::from_millis); + let check_out = req.check_out.map(Timestamp::from_millis); + // Only the ordering check needs the stored row, and only it can race: it + // validates an arriving instant against the other one as stored, so the + // read, the check and the write are held together under + // [`WORK_ENTRY_LOCK`]. A PATCH carrying neither instant pays nothing. + let _guard = match (check_in, check_out) { + (None, None) => None, + _ => Some(WORK_ENTRY_LOCK.lock().await), + }; + let entry = WorkEntry::read(&WorkEntryId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; @@ -207,8 +218,6 @@ async fn update_entry( )); }; - let check_in = req.check_in.map(Timestamp::from_millis); - let check_out = req.check_out.map(Timestamp::from_millis); // The side the correction left out is only *read* for the ordering check — // it is never written back, so a concurrent correction of it survives. if check_out.unwrap_or(current_out) < check_in.unwrap_or_else(|| entry.get_check_in()) { diff --git a/tests/partial_patch_events.rs b/tests/partial_patch_events.rs index f72b8a1..0341097 100644 --- a/tests/partial_patch_events.rs +++ b/tests/partial_patch_events.rs @@ -125,3 +125,58 @@ async fn range_check_still_sees_the_stored_other_side() { "ends_at before stored starts_at" ); } + +/// Each end moved *just inside* the other is valid on its own snapshot, so two +/// concurrent one-ended PATCHes can each pass their check against the stored +/// row and still commit an inverted range between them. Whatever each request +/// returns (200/400/409 are all fine), the stored pair must stay ordered. +#[tokio::test] +async fn concurrent_range_patches_never_invert_the_stored_row() { + let (app, db) = app_and_db().await; + let who = login_as(&app, &db, "range", "teacher").await; + let starts = 1_900_000_000_000_i64; + let ends = starts + 3_600_000; + + for round in 0..20 { + let created = send( + &app, + "POST", + "/events", + Some(&who), + Some(json!({ "title": "timed", "starts_at": starts, "ends_at": ends })), + ) + .await; + assert_eq!(created.status, StatusCode::CREATED, "round {round} create"); + let uri = format!("/events/{}", id_of(&created.body)); + + // Each alone is valid: starts_at lands before the stored ends_at, and + // ends_at lands after the stored starts_at. + let (a, b) = tokio::join!( + send( + &app, + "PATCH", + &uri, + Some(&who), + Some(json!({ "starts_at": ends - 1000 })), + ), + send( + &app, + "PATCH", + &uri, + Some(&who), + Some(json!({ "ends_at": starts + 1000 })), + ), + ); + + let after = send(&app, "GET", &uri, Some(&who), None).await.body; + let stored_starts = after["starts_at"].as_i64().expect("starts_at"); + let stored_ends = after["ends_at"].as_i64().expect("ends_at"); + assert!( + stored_starts <= stored_ends, + "round {round}: stored inverted range starts_at={stored_starts} \ + ends_at={stored_ends} (statuses {} {})", + a.status, + b.status + ); + } +} diff --git a/tests/partial_patch_work.rs b/tests/partial_patch_work.rs index f9acefe..98a48f7 100644 --- a/tests/partial_patch_work.rs +++ b/tests/partial_patch_work.rs @@ -129,3 +129,63 @@ async fn range_check_still_sees_the_stored_other_side() { "check_out before the stored check_in" ); } + +/// Each instant moved *just inside* the other is valid on its own snapshot, so +/// two concurrent one-sided corrections can each pass their check against the +/// stored row and still commit an inverted stint between them. Whatever each +/// request returns (200/400/409 are all fine), the stored pair must stay +/// ordered. +#[tokio::test] +async fn concurrent_range_patches_never_invert_the_stored_stint() { + let (app, db) = app_and_db().await; + let who = login_as(&app, &db, "mudur5", "manager").await; + + let base = 1_000_000_000_000_i64; + let end = base + 3_600_000; + + for round in 0..20 { + let id = closed_entry(&app, &who).await; + let uri = format!("/work/entries/{id}"); + // The server stamps both instants milliseconds apart; widen the stint + // first so the racing corrections have room to invert it. + let widened = send( + &app, + "PATCH", + &uri, + Some(&who), + Some(json!({ "check_in": base, "check_out": end })), + ) + .await; + assert_eq!(widened.status, StatusCode::OK, "round {round} widen"); + + // Each alone is valid: check_in lands before the stored check_out, and + // check_out after the stored check_in. + let (a, b) = tokio::join!( + send( + &app, + "PATCH", + &uri, + Some(&who), + Some(json!({ "check_in": end - 1000 })), + ), + send( + &app, + "PATCH", + &uri, + Some(&who), + Some(json!({ "check_out": base + 1000 })), + ), + ); + + let after = entry(&app, &who, &id).await; + let final_in = after["check_in"].as_i64().expect("check_in"); + let final_out = after["check_out"].as_i64().expect("check_out"); + assert!( + final_in <= final_out, + "round {round}: stored inverted stint check_in={final_in} \ + check_out={final_out} (statuses {} {})", + a.status, + b.status + ); + } +}