diff --git a/src/domain/course_session.rs b/src/domain/course_session.rs index e293f0a..8382bc4 100644 --- a/src/domain/course_session.rs +++ b/src/domain/course_session.rs @@ -1,14 +1,30 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use tokio::sync::Mutex; use ulid::Ulid; use crate::constant::MAX_SESSION_TOPIC_LEN; use crate::database::{COURSE_SESSION_TABLE, Database}; use crate::domain::course::CourseId; +use crate::domain::field_update::FieldUpdate; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use crate::validate::validate_optional; +/// Serializes a lesson's time-range check against the write it guards, exactly +/// as [`crate::domain::event::EVENT_LOCK`] does for events: `starts_at <= +/// ends_at` is a cross-field check, so a PATCH carrying one end validates it +/// against the *stored* other end — two such PATCHes, each fine on its own +/// snapshot, would otherwise commit an inverted lesson 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 +/// /sessions/{id}`) takes no other lock, and no path holding `EXAM_LOCK`, +/// `BANK_LOCK`, `HOMEWORK_LOCK`, `ENROLL_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 SESSION_LOCK: Mutex<()> = Mutex::const_new(()); + #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct CourseSessionId(RecordId); @@ -134,34 +150,28 @@ impl CourseSession { Ok(result.take::>(0)?) } - /// Field-scoped, like every other save in this codebase: the handler holds - /// no lock across its read and this write, so a whole-row save would carry - /// the whole stale row back over anything that landed in between. + /// Request-scoped: the handler holds no lock across its read and this write + /// unless a schedule end arrives ([`SESSION_LOCK`]), so a field the request + /// omitted (`None`) is not written at all. Re-sending the snapshot's value + /// instead would revert a concurrent PATCH of that field — scoping the + /// `SET` alone does not stop that, the values have to come from the + /// request. `ends_at` is nullable, so it takes the outer/inner + /// `Option>`: `None` = omitted (keep), `Some(None)` = clear. pub async fn update( self, - teacher: UserId, - topic: SessionTopic, - starts_at: Timestamp, - ends_at: Option, + teacher: Option, + topic: Option, + starts_at: Option, + ends_at: Option>, db: &Database, ) -> Result { - let mut result = db - .query( - "UPDATE $id SET teacher = $teacher, topic = $topic, - starts_at = $starts_at, ends_at = $ends_at RETURN AFTER", - ) - .bind(("id", self.id.record())) - .bind(("teacher", teacher.record())) - .bind(("topic", topic)) - .bind(("starts_at", starts_at)) - .bind(("ends_at", ends_at)) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound) + FieldUpdate::new(self.id.record()) + .set("teacher", teacher.map(|teacher| teacher.record())) + .set("topic", topic) + .set("starts_at", starts_at) + .set("ends_at", ends_at) + .run::(db) + .await } /// Delete the session and cascade-remove its roll-call rows. diff --git a/src/domain/field_update.rs b/src/domain/field_update.rs index 530722d..8c0b228 100644 --- a/src/domain/field_update.rs +++ b/src/domain/field_update.rs @@ -4,8 +4,8 @@ //! WHY: a handler reads the row, then writes. Filling a field the request //! omitted from that snapshot re-sends a value the client never gave, so a //! concurrent PATCH of the *other* field that landed in between is silently -//! reverted — the same lost update the whole-row-save gate bans, just spelled -//! field by field. Scoping the `SET` is not enough; the *values* must come +//! reverted — the same lost update a whole-row `.content(self)` save causes, +//! just spelled field by field. Scoping the `SET` is not enough; the *values* must come //! from the request, so an absent field is never written at all. //! //! Callers therefore take `Option` per field (`None` = absent, keep) and diff --git a/src/domain/subject.rs b/src/domain/subject.rs index 822c99b..174fab9 100644 --- a/src/domain/subject.rs +++ b/src/domain/subject.rs @@ -1,9 +1,10 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Ulid; use crate::constant::{MAX_SUBJECT_DESCRIPTION_LEN, MAX_SUBJECT_NAME_LEN}; use crate::database::{Database, SUBJECT_TABLE}; use crate::domain::course::CourseId; +use crate::domain::field_update::FieldUpdate; +use crate::domain::monotonic_id::next_ulid; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_optional, validate_required}; @@ -11,8 +12,12 @@ use crate::validate::{validate_optional, validate_required}; pub struct SubjectId(RecordId); impl SubjectId { + /// Minted from the process-wide monotonic generator, not `Ulid::new()`: the + /// id *is* the curriculum's order ([`Subject::list_for_course`] sorts + /// `id ASC`), and a random low half scrambles a burst of saves that lands + /// inside one millisecond. pub fn generate() -> Self { - Self(RecordId::new(SUBJECT_TABLE, Ulid::new().to_string())) + Self(RecordId::new(SUBJECT_TABLE, next_ulid().to_string())) } pub fn from_key(key: &str) -> Self { @@ -136,27 +141,23 @@ impl Subject { Ok(result.take::>(0)?) } + /// Request-scoped: no lock spans the handler's read and this write, so an + /// omitted field (`None`) is not written at all. Passing the snapshot's + /// value back instead would revert a concurrent edit of that field — + /// scoping the `SET` alone does not prevent that, the values have to come + /// from the request. Neither column is nullable, so plain `Option` per + /// field says everything there is to say. pub async fn update( self, - name: SubjectName, - description: SubjectDescription, + name: Option, + description: Option, db: &Database, ) -> Result { - // Field-scoped: the handler holds no lock across its read and this - // write, so a whole-row save would revert a concurrent edit of the - // other field. - let mut result = db - .query("UPDATE $id SET name = $name, description = $description RETURN AFTER") - .bind(("id", self.id.record())) - .bind(("name", name)) - .bind(("description", description)) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound) + FieldUpdate::new(self.id.record()) + .set("name", name) + .set("description", description) + .run::(db) + .await } /// Delete the subject and clear it off every bank template that carried it @@ -193,6 +194,21 @@ impl Subject { mod tests { use super::*; + /// A teacher entering a curriculum gets it back in the order they typed it: + /// `list_for_course` sorts `id ASC`, so the ids minted inside one + /// millisecond have to sort in mint order. Revert `generate` to + /// `Ulid::new()` and this fails — the low 80 bits are redrawn per id, so a + /// same-tick burst comes out shuffled. + #[tokio::test] + async fn ids_sort_in_creation_order() { + let ids: Vec = (0..500) + .map(|_| SubjectId::generate().key().to_string()) + .collect(); + let mut sorted = ids.clone(); + sorted.sort(); + assert_eq!(ids, sorted); + } + #[tokio::test] async fn name_is_required() { assert!(SubjectName::try_new("Limits").is_ok()); diff --git a/src/domain/user.rs b/src/domain/user.rs index 6383018..1e05c23 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -6,6 +6,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::Ulid; use crate::database::{Database, USER_TABLE}; +use crate::domain::field_update::FieldUpdate; use crate::domain::preferences::{Language, Theme}; use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; use crate::domain::role::Role; @@ -396,63 +397,50 @@ impl User { .ok_or(AppError::NotFound) } - /// Overwrite the personal-info fields wholesale. Each argument is the final - /// value (`None` clears); merging "keep what wasn't sent" against the - /// current row is the HTTP layer's job. The caller authorizes. Writes only - /// the five profile fields — see [`User::set_role`] for why the writers - /// are field-scoped. + /// Write the personal-info fields the request actually carried. Every + /// column is nullable, so each argument is an outer/inner `Option`: `None` + /// = omitted (not written at all), `Some(None)` = cleared, `Some(Some(v))` + /// = set. Merging the request against the current row is the HTTP layer's + /// job; the caller authorizes. + /// + /// Request-scoped, not merely field-scoped: nothing guards the row across + /// the handler's read and this write, so re-sending the snapshot's value + /// for an omitted field would revert a concurrent PATCH of that field — + /// two profile edits (a name and a phone) used to lose each other. See + /// [`User::set_role`] for why no writer here touches the whole row. pub async fn set_profile( self, - name: Option, - surname: Option, - email: Option, - phone: Option, - birth_date: Option, + name: Option>, + surname: Option>, + email: Option>, + phone: Option>, + birth_date: Option>, db: &Database, ) -> Result { - let mut result = db - .query( - "UPDATE $id SET name = $name, surname = $surname, email = $email, \ - phone = $phone, birth_date = $birth_date RETURN AFTER", - ) - .bind(("id", self.id.record())) - .bind(("name", name)) - .bind(("surname", surname)) - .bind(("email", email)) - .bind(("phone", phone)) - .bind(("birth_date", birth_date)) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound) + FieldUpdate::new(self.id.record()) + .set("name", name) + .set("surname", surname) + .set("email", email) + .set("phone", phone) + .set("birth_date", birth_date) + .run::(db) + .await } - /// Overwrite the UI-preference fields wholesale. Same contract as - /// [`User::set_profile`]: each argument is the final value (`None` clears - /// back to "never chose"), merging is the HTTP layer's job, the caller - /// authorizes. Writes only `theme` and `language` — see [`User::set_role`] - /// for why the writers are field-scoped. + /// Write the UI-preference fields the request actually carried. Same + /// contract as [`User::set_profile`]: `None` = omitted (not written), + /// `Some(None)` = cleared back to "never chose", `Some(Some(v))` = set. pub async fn set_preferences( self, - theme: Option, - language: Option, + theme: Option>, + language: Option>, db: &Database, ) -> Result { - let mut result = db - .query("UPDATE $id SET theme = $theme, language = $language RETURN AFTER") - .bind(("id", self.id.record())) - .bind(("theme", theme)) - .bind(("language", language)) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound) + FieldUpdate::new(self.id.record()) + .set("theme", theme) + .set("language", language) + .run::(db) + .await } pub async fn find_by_username(username: &str, db: &Database) -> Result, AppError> { @@ -498,7 +486,7 @@ mod tests { // admin's change. let name = PersonName::try_new("name", "Ayşenur").unwrap(); stale - .set_profile(Some(name.clone()), None, None, None, None, &db) + .set_profile(Some(Some(name.clone())), None, None, None, None, &db) .await .unwrap(); diff --git a/src/web/bank_questions.rs b/src/web/bank_questions.rs index 00ddcc7..cd0c458 100644 --- a/src/web/bank_questions.rs +++ b/src/web/bank_questions.rs @@ -47,8 +47,11 @@ use super::{ }; /// Serializes bank writes that adopt a `subject` against a concurrent subject -/// delete. Bank create/update take the reader lease across their -/// subject-exists check and the write; the subject delete takes the writer +/// delete. Bank create takes the reader lease across its +/// subject-exists check and the write; the *update* takes the writer lease +/// instead, because it is a read-modify-write of the whole template, so its row +/// read must be serialized against another update and not merely against the +/// delete cascade; the subject delete takes the writer /// lease across the cascade that clears `subject` off every template, so a /// template can't land on a subject that vanished mid-flight (it would outlive /// the sweep) — the bank twin of the @@ -419,7 +422,7 @@ pub(crate) async fn store_image( /// Add a template to the bank. Requires teacher+. `subject_id` is origin /// metadata (any subject — the same-course rule lives at instantiate time), /// so it need only exist (an unknown subject is a `400`). `choice` templates -/// carry 2–10 `choices` plus the `correct` index; `text` templates carry +/// carry 2–10 `choices` plus `correct` naming one of them by id; `text` templates carry /// neither. The caller becomes the owner. #[utoipa::path( post, @@ -628,11 +631,21 @@ async fn update_question( Path(bid): Path, Json(req): Json, ) -> Result, AppError> { + // *Writer* lease of [`BANK_LOCK`], taken before the row is read: this is a + // read-modify-write, not a per-field write. Omitted fields are refilled from + // the snapshot below, and the kind/choices/correct trio genuinely has to be + // (a text-only edit re-submits the stored options *with their ids* so every + // choice keeps its picture), so the read, the merge and the write must be + // one unit or a concurrent PATCH of another field is silently reverted. The + // reader lease this used to take was both shared *and* acquired after the + // read, so it serialized nothing; it only ever covered the subject-exists + // check against a subject delete, which the writer lease still covers. + // Exclusive means bank writes queue behind each other — they are rare + // teacher edits, and the per-field alternative cannot express the + // choice-identity merge. Still the only lock this path takes, so the + // documented EXAM → BANK order is unaffected. + let _guard = BANK_LOCK.write().await; let question = owned_question(&st, &user, &bid).await?; - - // Reader lease of [`BANK_LOCK`] across the exists-check and the update, so a - // re-tag to a subject that's being deleted can't straddle the delete-guard. - let _guard = BANK_LOCK.read().await; // Omitted keeps the stored subject — which may already be `None`, cleared // by that subject's delete. let subject = match req.subject_id { @@ -818,8 +831,9 @@ async fn delete_question_image( /// Attach (or replace) one option's picture on a `choice` template. Owner only /// (admins aside). Same form, limits, and rules as the illustration upload; -/// `index` is the option's zero-based position. Replacing the `choices` list -/// drops all its option pictures. +/// `choice_id` is the `id` carried on that choice, as returned in the +/// template's `choices` (not a position — an unknown id is a `400`). Replacing +/// the `choices` list drops all its option pictures. #[utoipa::path( post, path = "/{bid}/choices/{choice_id}/image", diff --git a/src/web/sessions.rs b/src/web/sessions.rs index fe54da9..10d9fae 100644 --- a/src/web/sessions.rs +++ b/src/web/sessions.rs @@ -11,7 +11,7 @@ use utoipa_axum::routes; use crate::database::Database; use crate::domain::attendance::AttendanceStatus; use crate::domain::course::Course; -use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic}; +use crate::domain::course_session::{CourseSession, CourseSessionId, SESSION_LOCK, SessionTopic}; use crate::domain::enrollment::Enrollment; use crate::domain::role::Role; use crate::domain::session_attendance::SessionAttendance; @@ -186,6 +186,25 @@ async fn update_session( Path(id): Path, Json(req): Json, ) -> Result, AppError> { + // Only values this request sets are held to the no-past rule — a kept + // `starts_at` of a lesson already underway is legitimately past. A provided + // `ends_at` sets the field, an explicit `null` clears it, an omitted one is + // left alone. + let starts_at = req.starts_at.map(Timestamp::from_millis); + check_not_past("starts_at", starts_at)?; + let ends_at = req.ends_at.map(|update| update.map(Timestamp::from_millis)); + if let Some(ends_at) = ends_at { + check_not_past("ends_at", ends_at)?; + } + // 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 [`SESSION_LOCK`]. A PATCH + // that moves neither end pays nothing. + let _guard = match (starts_at, ends_at) { + (None, None) => None, + _ => Some(SESSION_LOCK.lock().await), + }; + let (session, course) = session_with_course(&id, &st.db).await?; if !can_manage_course(&course, &user) { return Err(AppError::Forbidden( @@ -193,38 +212,26 @@ async fn update_session( )); } - let topic = match req.topic { - Some(ref topic) => SessionTopic::try_new(topic)?, - None => session.get_topic().clone(), - }; + let topic = req + .topic + .as_deref() + .map(SessionTopic::try_new) + .transpose()?; let teacher = match req.teacher_id { - Some(ref key) => resolve_session_teacher(Some(key), &user, &st.db) - .await? - .get_id() - .clone(), - None => session.get_teacher().clone(), - }; - // Only values this request sets are held to the no-past rule — a kept - // `starts_at` of a lesson already underway is legitimately past. - let starts_at = match req.starts_at { - Some(millis) => { - let starts_at = Timestamp::from_millis(millis); - check_not_past("starts_at", Some(starts_at))?; - starts_at - } - None => session.get_starts_at(), - }; - // A provided value sets the field, an explicit `null` clears it, and an - // omitted one keeps the current value. - let ends_at = match req.ends_at { - Some(update) => { - let ends_at = update.map(Timestamp::from_millis); - check_not_past("ends_at", ends_at)?; - ends_at - } - None => session.get_ends_at(), + Some(ref key) => Some( + resolve_session_teacher(Some(key), &user, &st.db) + .await? + .get_id() + .clone(), + ), + None => None, }; - check_time_range(Some(starts_at), ends_at)?; + // The end this request left out is only *read* for the range check — it is + // never written back, so a concurrent move of it survives. + check_time_range( + Some(starts_at.unwrap_or_else(|| session.get_starts_at())), + ends_at.unwrap_or_else(|| session.get_ends_at()), + )?; let updated = session .update(teacher, topic, starts_at, ends_at, &st.db) diff --git a/src/web/subjects.rs b/src/web/subjects.rs index 118348c..c9bffe3 100644 --- a/src/web/subjects.rs +++ b/src/web/subjects.rs @@ -143,14 +143,15 @@ async fn update_subject( )); } - let name = match req.name { - Some(ref name) => SubjectName::try_new(name)?, - None => subject.get_name().clone(), - }; - let description = match req.description { - Some(ref description) => SubjectDescription::try_new(description)?, - None => subject.get_description().clone(), - }; + // Only what the request actually carried is validated and written — an + // omitted field stays `None` so the save never re-sends this snapshot's + // value over a concurrent PATCH of the other field. + let name = req.name.as_deref().map(SubjectName::try_new).transpose()?; + let description = req + .description + .as_deref() + .map(SubjectDescription::try_new) + .transpose()?; let updated = subject.update(name, description, &st.db).await?; Ok(Json(SubjectResponse::new(&updated))) diff --git a/src/web/users.rs b/src/web/users.rs index 7c30188..e8617c1 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -76,48 +76,45 @@ struct UpdatePreferences { language: Option, } -/// Resolve one patched field: absent keeps the current value, `""` clears it, -/// anything else must parse into the domain newtype. -fn merge_field( - current: Option<&T>, +/// Resolve one patched field into what the save should write: absent (or +/// `null`) is `None` — the column is not written at all, so a concurrent PATCH +/// of it survives; `""` is `Some(None)`, an explicit clear; anything else must +/// parse into the domain newtype, exactly as a create would. +fn merge_field( patch: Option<&str>, parse: impl Fn(&str) -> Result, -) -> Result, ValidationError> { +) -> Result>, ValidationError> { match patch { - None => Ok(current.cloned()), - Some("") => Ok(None), - Some(value) => Ok(Some(parse(value)?)), + None => Ok(None), + Some("") => Ok(Some(None)), + Some(value) => Ok(Some(Some(parse(value)?))), } } -/// Merge `req` over `user`'s current info and persist. Shared by the -/// self-service and admin profile endpoints — they differ only in whose row -/// they load and who may call them. +/// Validate and persist exactly the info fields `req` carried — nothing is +/// merged from `user`'s snapshot, so a concurrent PATCH of another field is not +/// reverted. Shared by the self-service and admin profile endpoints — they +/// differ only in whose row they load and who may call them. async fn apply_profile( user: User, req: &UpdateProfile, db: &Database, ) -> Result { - let name = merge_field(user.get_name(), req.name.as_deref(), |v| { - PersonName::try_new("name", v) - })?; - let surname = merge_field(user.get_surname(), req.surname.as_deref(), |v| { + let name = merge_field(req.name.as_deref(), |v| PersonName::try_new("name", v))?; + let surname = merge_field(req.surname.as_deref(), |v| { PersonName::try_new("surname", v) })?; - let email = merge_field(user.get_email(), req.email.as_deref(), Email::try_new)?; - let phone = merge_field(user.get_phone(), req.phone.as_deref(), Phone::try_new)?; - let birth_date = merge_field( - user.get_birth_date(), - req.birth_date.as_deref(), - BirthDate::try_new, - )?; + let email = merge_field(req.email.as_deref(), Email::try_new)?; + let phone = merge_field(req.phone.as_deref(), Phone::try_new)?; + let birth_date = merge_field(req.birth_date.as_deref(), BirthDate::try_new)?; let updated = user .set_profile(name, surname, email, phone, birth_date, db) .await?; Ok(UserResponse::new(&updated)) } -/// Merge `req` over `user`'s current preferences and persist. Shared by the +/// Validate and persist exactly the preference fields `req` carried — same +/// no-merge reasoning as [`apply_profile`]. Shared by the /// self-service and admin preference endpoints — they differ only in whose row /// they load and who may call them. async fn apply_preferences( @@ -125,14 +122,8 @@ async fn apply_preferences( req: &UpdatePreferences, db: &Database, ) -> Result { - let theme = merge_field(user.get_theme().as_ref(), req.theme.as_deref(), |v| { - Theme::try_from_str(v) - })?; - let language = merge_field( - user.get_language().as_ref(), - req.language.as_deref(), - Language::try_from_str, - )?; + let theme = merge_field(req.theme.as_deref(), Theme::try_from_str)?; + let language = merge_field(req.language.as_deref(), Language::try_from_str)?; let updated = user.set_preferences(theme, language, db).await?; Ok(UserResponse::new(&updated)) } diff --git a/tests/partial_patch_bank_questions.rs b/tests/partial_patch_bank_questions.rs new file mode 100644 index 0000000..9c031ed --- /dev/null +++ b/tests/partial_patch_bank_questions.rs @@ -0,0 +1,166 @@ +//! A bank-template PATCH is a read-modify-write: the kind/choices/correct trio +//! has to be re-submitted as a unit (choices carry their ids, and their +//! pictures hang off those ids), so the row read, the merge and the write are +//! held together under the *writer* lease of `BANK_LOCK`. Without that, two +//! concurrent partial PATCHes revert each other. + +mod common; + +use axum::http::StatusCode; +use common::*; +use serde_json::json; + +async fn template(app: &axum::Router, who: &str, subject: &str) -> String { + let created = send( + app, + "POST", + "/bank-questions", + Some(who), + Some(json!({ "subject_id": subject, "text": "old text", + "kind": "text", "points": 1 })), + ) + .await; + assert_eq!(created.status, StatusCode::CREATED, "{}", created.body); + id_of(&created.body) +} + +#[tokio::test] +async fn concurrent_partial_patches_keep_both_fields() { + let (app, db) = app_and_db().await; + let who = login_as(&app, &db, "ali", "teacher").await; + let course = create_course(&app, &who, "math").await; + let subject = create_subject(&app, &who, &course, "algebra").await; + + for round in 0..20 { + let uri = format!("/bank-questions/{}", template(&app, &who, &subject).await); + + let (a, b) = tokio::join!( + send( + &app, + "PATCH", + &uri, + Some(&who), + Some(json!({ "text": "new text" })), + ), + send( + &app, + "PATCH", + &uri, + Some(&who), + Some(json!({ "points": 7 })), + ), + ); + assert_eq!(a.status, StatusCode::OK, "round {round} text patch"); + assert_eq!(b.status, StatusCode::OK, "round {round} points patch"); + + let after = send(&app, "GET", &uri, Some(&who), None).await.body; + assert_eq!(after["text"], "new text", "round {round}: text reverted"); + assert_eq!(after["points"], 7, "round {round}: points reverted"); + } +} + +/// The visibility switch races a text edit: publishing must not be undone by an +/// edit that never mentioned `visibility`, and vice versa. +#[tokio::test] +async fn publishing_survives_a_concurrent_text_edit() { + let (app, db) = app_and_db().await; + let who = login_as(&app, &db, "veli", "teacher").await; + let course = create_course(&app, &who, "physics").await; + let subject = create_subject(&app, &who, &course, "optics").await; + + for round in 0..20 { + let uri = format!("/bank-questions/{}", template(&app, &who, &subject).await); + + let (a, b) = tokio::join!( + send( + &app, + "PATCH", + &uri, + Some(&who), + Some(json!({ "visibility": "school" })), + ), + send( + &app, + "PATCH", + &uri, + Some(&who), + Some(json!({ "text": "edited" })), + ), + ); + assert_eq!(a.status, StatusCode::OK, "round {round} publish"); + assert_eq!(b.status, StatusCode::OK, "round {round} text patch"); + + let after = send(&app, "GET", &uri, Some(&who), None).await.body; + assert_eq!( + after["visibility"], "school", + "round {round}: publish reverted" + ); + assert_eq!(after["text"], "edited", "round {round}: text reverted"); + } +} + +/// The kind-dependent trio is still merged and re-validated as a unit, and the +/// choice ids (which the pictures hang off) survive a text-only edit. +#[tokio::test] +async fn choice_identity_and_unit_validation_survive() { + let (app, db) = app_and_db().await; + let who = login_as(&app, &db, "ayse", "teacher").await; + let course = create_course(&app, &who, "math").await; + let subject = create_subject(&app, &who, &course, "algebra").await; + + let created = send( + &app, + "POST", + "/bank-questions", + Some(&who), + Some( + json!({ "subject_id": subject, "text": "2 + 2?", "kind": "choice", + "points": 10, + "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], + "correct": "c1" }), + ), + ) + .await; + assert_eq!(created.status, StatusCode::CREATED, "{}", created.body); + let ids: Vec = created.body["choices"] + .as_array() + .expect("choices") + .iter() + .map(|c| c["id"].as_str().expect("choice id").to_string()) + .collect(); + let uri = format!("/bank-questions/{}", id_of(&created.body)); + + let edited = send( + &app, + "PATCH", + &uri, + Some(&who), + Some(json!({ "text": "two plus two?" })), + ) + .await; + assert_eq!(edited.status, StatusCode::OK); + let after_ids: Vec = edited.body["choices"] + .as_array() + .expect("choices") + .iter() + .map(|c| c["id"].as_str().expect("choice id").to_string()) + .collect(); + assert_eq!(after_ids, ids, "a text edit kept every choice id"); + assert_eq!(edited.body["correct"], ids[1], "correct kept"); + + // Switching to a text template while keeping the stored choices is still a + // unit-validation failure — a PATCH cannot land a half-question. + let bad = send( + &app, + "PATCH", + &uri, + Some(&who), + Some(json!({ "kind": "text" })), + ) + .await; + assert_eq!( + bad.status, + StatusCode::BAD_REQUEST, + "text kind with stored choices refused" + ); +} diff --git a/tests/partial_patch_sessions.rs b/tests/partial_patch_sessions.rs new file mode 100644 index 0000000..1d3dc3a --- /dev/null +++ b/tests/partial_patch_sessions.rs @@ -0,0 +1,173 @@ +//! Two concurrent partial PATCHes on the same session must not revert each +//! other, and — since only the fields a request carried are written — the +//! `starts_at`/`ends_at` pair must not be invertible by two one-ended PATCHes +//! either (that is what `SESSION_LOCK` is for). + +mod common; + +use axum::http::StatusCode; +use common::*; +use serde_json::json; + +const FUTURE: i64 = 1_900_000_000_000; + +#[tokio::test] +async fn concurrent_partial_patches_keep_both_fields() { + let (app, db) = app_and_db().await; + let who = login_as(&app, &db, "ali", "teacher").await; + let course = create_course(&app, &who, "math").await; + + for round in 0..20 { + let created = send( + &app, + "POST", + &format!("/courses/{course}/sessions"), + Some(&who), + Some(json!({ "topic": "old topic", "starts_at": FUTURE })), + ) + .await; + assert_eq!(created.status, StatusCode::CREATED, "round {round} create"); + let uri = format!("/sessions/{}", id_of(&created.body)); + + // `topic` races `ends_at`: different fields, neither may lose. + let (a, b) = tokio::join!( + send( + &app, + "PATCH", + &uri, + Some(&who), + Some(json!({ "topic": "new topic" })), + ), + send( + &app, + "PATCH", + &uri, + Some(&who), + Some(json!({ "ends_at": FUTURE + 3_600_000 })), + ), + ); + assert_eq!(a.status, StatusCode::OK, "round {round} topic patch"); + assert_eq!(b.status, StatusCode::OK, "round {round} ends_at patch"); + + let after = send(&app, "GET", &uri, Some(&who), None).await.body; + assert_eq!(after["topic"], "new topic", "round {round}: topic reverted"); + assert_eq!( + after["ends_at"], + FUTURE + 3_600_000, + "round {round}: ends_at reverted" + ); + } +} + +/// Each end moved *just inside* the other is valid on its own snapshot, so two +/// concurrent one-ended PATCHes could each pass their check against the stored +/// row and still commit an inverted lesson between them. Whatever each request +/// returns (200/400 are both 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 course = create_course(&app, &who, "math").await; + let ends = FUTURE + 3_600_000; + + for round in 0..20 { + let created = send( + &app, + "POST", + &format!("/courses/{course}/sessions"), + Some(&who), + Some(json!({ "starts_at": FUTURE, "ends_at": ends })), + ) + .await; + assert_eq!(created.status, StatusCode::CREATED, "round {round} create"); + let uri = format!("/sessions/{}", id_of(&created.body)); + + 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": FUTURE + 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 lesson starts_at={stored_starts} \ + ends_at={stored_ends} (statuses {} {})", + a.status, + b.status + ); + } +} + +/// `ends_at` stays genuinely nullable: omitted keeps it, an explicit `null` +/// clears it — and a one-ended PATCH is still checked against the stored other +/// end (read for the check, never written back). +#[tokio::test] +async fn ends_at_stays_clearable_and_range_checked() { + let (app, db) = app_and_db().await; + let who = login_as(&app, &db, "veli", "teacher").await; + let course = create_course(&app, &who, "physics").await; + let session = create_session(&app, &who, &course, FUTURE).await; + let uri = format!("/sessions/{session}"); + + let set = send( + &app, + "PATCH", + &uri, + Some(&who), + Some(json!({ "ends_at": FUTURE + 1_000 })), + ) + .await; + assert_eq!(set.status, StatusCode::OK); + assert_eq!(set.body["ends_at"], FUTURE + 1_000); + + let kept = send( + &app, + "PATCH", + &uri, + Some(&who), + Some(json!({ "topic": "kept ends" })), + ) + .await; + assert_eq!(kept.status, StatusCode::OK); + assert_eq!(kept.body["starts_at"], FUTURE, "omitted starts_at kept"); + assert_eq!(kept.body["ends_at"], FUTURE + 1_000, "omitted ends_at kept"); + + let bad = send( + &app, + "PATCH", + &uri, + Some(&who), + Some(json!({ "ends_at": FUTURE - 1_000 })), + ) + .await; + assert_eq!( + bad.status, + StatusCode::BAD_REQUEST, + "ends_at before stored starts_at" + ); + + let cleared = send( + &app, + "PATCH", + &uri, + Some(&who), + Some(json!({ "ends_at": null })), + ) + .await; + assert_eq!(cleared.status, StatusCode::OK); + assert_eq!(cleared.body["ends_at"], json!(null), "ends_at not cleared"); +} diff --git a/tests/partial_patch_subjects.rs b/tests/partial_patch_subjects.rs new file mode 100644 index 0000000..25f5c4b --- /dev/null +++ b/tests/partial_patch_subjects.rs @@ -0,0 +1,89 @@ +//! Two concurrent partial PATCHes on the same subject must not revert each +//! other. A handler that fills omitted fields from its own stale read writes +//! back a value the client never sent, so whichever request lands last wipes +//! the other's field. + +mod common; + +use axum::http::StatusCode; +use common::*; +use serde_json::json; + +#[tokio::test] +async fn concurrent_partial_patches_keep_both_fields() { + let (app, db) = app_and_db().await; + let who = login_as(&app, &db, "ali", "teacher").await; + let course = create_course(&app, &who, "math").await; + + for round in 0..20 { + let created = send( + &app, + "POST", + &format!("/courses/{course}/subjects"), + Some(&who), + Some(json!({ "name": "old name", "description": "old description" })), + ) + .await; + assert_eq!(created.status, StatusCode::CREATED, "round {round} create"); + let uri = format!("/subjects/{}", id_of(&created.body)); + + let (a, b) = tokio::join!( + send( + &app, + "PATCH", + &uri, + Some(&who), + Some(json!({ "name": "new name" })), + ), + send( + &app, + "PATCH", + &uri, + Some(&who), + Some(json!({ "description": "new description" })), + ), + ); + assert_eq!(a.status, StatusCode::OK, "round {round} name patch"); + assert_eq!(b.status, StatusCode::OK, "round {round} description patch"); + + let after = send(&app, "GET", &uri, Some(&who), None).await.body; + assert_eq!(after["name"], "new name", "round {round}: name reverted"); + assert_eq!( + after["description"], "new description", + "round {round}: description reverted" + ); + } +} + +/// Omitting a field keeps it, and a PATCH still cannot land a value a POST +/// would reject. +#[tokio::test] +async fn omitted_keeps_and_validation_still_bites() { + let (app, db) = app_and_db().await; + let who = login_as(&app, &db, "veli", "teacher").await; + let course = create_course(&app, &who, "physics").await; + let subject = create_subject(&app, &who, &course, "kept name").await; + let uri = format!("/subjects/{subject}"); + + let kept = send( + &app, + "PATCH", + &uri, + Some(&who), + Some(json!({ "description": "only this" })), + ) + .await; + assert_eq!(kept.status, StatusCode::OK); + assert_eq!(kept.body["name"], "kept name", "omitted name kept"); + assert_eq!(kept.body["description"], "only this"); + + // An empty PATCH writes nothing at all and reads the row back unchanged. + let empty = send(&app, "PATCH", &uri, Some(&who), Some(json!({}))).await; + assert_eq!(empty.status, StatusCode::OK); + assert_eq!(empty.body["name"], "kept name"); + assert_eq!(empty.body["description"], "only this"); + + // A blank name is required at create, so it stays refused at patch. + let bad = send(&app, "PATCH", &uri, Some(&who), Some(json!({ "name": "" }))).await; + assert_eq!(bad.status, StatusCode::BAD_REQUEST, "blank name refused"); +} diff --git a/tests/partial_patch_users.rs b/tests/partial_patch_users.rs new file mode 100644 index 0000000..1fedc86 --- /dev/null +++ b/tests/partial_patch_users.rs @@ -0,0 +1,160 @@ +//! Two concurrent partial PATCHes on the same user row must not revert each +//! other. The profile and preference handlers merged the request over their own +//! stale read and wrote every column, so a name edit racing a surname edit lost +//! one of them — both 200. + +mod common; + +use axum::http::StatusCode; +use common::*; +use serde_json::json; + +#[tokio::test] +async fn concurrent_profile_patches_keep_both_fields() { + let (app, db) = app_and_db().await; + let who = login_as(&app, &db, "ali", "student").await; + + for round in 0..20 { + let name = format!("name{round}"); + let surname = format!("surname{round}"); + let (a, b) = tokio::join!( + send( + &app, + "PATCH", + "/users/me", + Some(&who), + Some(json!({ "name": name })), + ), + send( + &app, + "PATCH", + "/users/me", + Some(&who), + Some(json!({ "surname": surname })), + ), + ); + assert_eq!(a.status, StatusCode::OK, "round {round} name patch"); + assert_eq!(b.status, StatusCode::OK, "round {round} surname patch"); + + // `/auth/me` is the self-read (there is no `GET /users/me`). + let after = send(&app, "GET", "/auth/me", Some(&who), None).await.body; + assert_eq!(after["name"], name, "round {round}: name reverted"); + assert_eq!(after["surname"], surname, "round {round}: surname reverted"); + } +} + +#[tokio::test] +async fn concurrent_preference_patches_keep_both_fields() { + let (app, db) = app_and_db().await; + let who = login_as(&app, &db, "veli", "student").await; + + for round in 0..20 { + // Alternate both values so a revert to the previous round is visible. + let (theme, language) = if round % 2 == 0 { + ("dark", "tr") + } else { + ("light", "en") + }; + let (a, b) = tokio::join!( + send( + &app, + "PATCH", + "/users/me/preferences", + Some(&who), + Some(json!({ "theme": theme })), + ), + send( + &app, + "PATCH", + "/users/me/preferences", + Some(&who), + Some(json!({ "language": language })), + ), + ); + assert_eq!(a.status, StatusCode::OK, "round {round} theme patch"); + assert_eq!(b.status, StatusCode::OK, "round {round} language patch"); + + let after = send(&app, "GET", "/auth/me", Some(&who), None).await.body; + assert_eq!(after["theme"], theme, "round {round}: theme reverted"); + assert_eq!( + after["language"], language, + "round {round}: language reverted" + ); + } +} + +/// The field semantics are unchanged: omitted (and `null`) keeps, `""` clears, +/// and anything else runs through the same validators a create would use. +#[tokio::test] +async fn omitted_keeps_empty_clears_and_validation_still_bites() { + let (app, db) = app_and_db().await; + let who = login_as(&app, &db, "ayse", "student").await; + + let set = send( + &app, + "PATCH", + "/users/me", + Some(&who), + Some(json!({ "name": "Ada", "surname": "Lovelace", "email": "ada@example.com" })), + ) + .await; + assert_eq!(set.status, StatusCode::OK, "{}", set.body); + + // Omitted keeps, and an explicit null keeps too (the documented contract). + let kept = send( + &app, + "PATCH", + "/users/me", + Some(&who), + Some(json!({ "surname": null })), + ) + .await; + assert_eq!(kept.status, StatusCode::OK); + assert_eq!(kept.body["name"], "Ada", "omitted name kept"); + assert_eq!(kept.body["surname"], "Lovelace", "null keeps surname"); + assert_eq!(kept.body["email"], "ada@example.com"); + + // An empty request writes nothing at all. + let empty = send(&app, "PATCH", "/users/me", Some(&who), Some(json!({}))).await; + assert_eq!(empty.status, StatusCode::OK); + assert_eq!(empty.body["name"], "Ada"); + assert_eq!(empty.body["email"], "ada@example.com"); + + // `""` clears — and only the field it was sent for. + let cleared = send( + &app, + "PATCH", + "/users/me", + Some(&who), + Some(json!({ "email": "" })), + ) + .await; + assert_eq!(cleared.status, StatusCode::OK); + assert_eq!(cleared.body["email"], json!(null), "email not cleared"); + assert_eq!(cleared.body["name"], "Ada", "name lost to the clear"); + + // A malformed value is refused, exactly as at create. + let bad = send( + &app, + "PATCH", + "/users/me", + Some(&who), + Some(json!({ "email": "not-an-email" })), + ) + .await; + assert_eq!(bad.status, StatusCode::BAD_REQUEST, "bad email refused"); + + let bad_theme = send( + &app, + "PATCH", + "/users/me/preferences", + Some(&who), + Some(json!({ "theme": "chartreuse" })), + ) + .await; + assert_eq!( + bad_theme.status, + StatusCode::BAD_REQUEST, + "bad theme refused" + ); +}