diff --git a/src/db/mod.rs b/src/db/mod.rs index 229aa07..32af5c7 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -2,4 +2,7 @@ pub mod cap; pub mod field_update; +pub mod note; pub mod page; +pub mod session; +pub mod settings; diff --git a/src/db/note.rs b/src/db/note.rs new file mode 100644 index 0000000..662d640 --- /dev/null +++ b/src/db/note.rs @@ -0,0 +1,181 @@ +//! The `note` table: one user's rows, listed newest first, deleted together +//! with their attachment rows. + +use surrealdb::types::SurrealValue; + +use crate::database::Database; +use crate::db::field_update::FieldUpdate; +use crate::db::page::PagedList; +use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle}; +use crate::domain::note_file::NoteFile; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// What [`delete`]'s transaction removed: the note row (empty if it had +/// already vanished) and every attachment row the cascade took with it — the +/// only set whose blobs are safe to unlink. +#[derive(Debug, SurrealValue)] +struct DeleteOutcome { + note: Vec, + files: Vec, +} + +pub async fn create( + db: &Database, + owner: &UserId, + title: NoteTitle, + content: NoteContent, +) -> Result { + let note = Note { + id: NoteId::generate(), + user: owner.clone(), + title, + content, + }; + let created: Option = db.create(note.id.record()).content(note).await?; + created.ok_or_else(|| AppError::Internal("failed to create note".into())) +} + +/// Read a note only if it belongs to `owner`. +pub async fn read_owned( + db: &Database, + id: &NoteId, + owner: &UserId, +) -> Result, AppError> { + let note: Option = db.select(id.record()).await?; + Ok(note.filter(|note| ¬e.user == owner)) +} + +pub async fn list_for( + db: &Database, + owner: &UserId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new("note WHERE user = $usr", "ORDER BY id DESC") + .bind("usr", owner.record()) + .run(limit, offset, db) + .await +} + +/// 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( + db: &Database, + note: Note, + title: Option, + content: Option, +) -> Result { + FieldUpdate::new(note.id.record()) + .set("title", title) + .set("content", content) + .run::(db) + .await +} + +/// Delete the note and cascade-remove its attachment rows, returning both: +/// the note, and the attachment rows this transaction actually removed. +/// Blob files on disk are the web layer's to remove, but only for *these* +/// rows — a row uploaded after the caller listed the note's files is +/// deleted here too, and a pre-read snapshot would strand its blob. A crash +/// between commit and unlink leaves at worst an unreachable blob, never a +/// row pointing at nothing. +/// +/// Children first, in one transaction, the way +/// [`crate::domain::course::Course::delete`] does it: as two queries, an +/// upload that committed in between kept its row while the note went, and +/// nothing could ever list or delete it again. +pub async fn delete(db: &Database, note: Note) -> Result<(Note, Vec), AppError> { + let mut result = db + .query( + "BEGIN TRANSACTION; + LET $files = (DELETE note_file WHERE note = $note RETURN BEFORE); + LET $gone = (DELETE $note RETURN BEFORE); + RETURN { note: $gone, files: $files }; + COMMIT TRANSACTION;", + ) + .bind(("note", note.id.record())) + .await? + .check()?; + // BEGIN is slot 0, the two LETs slots 1-2; the RETURN is slot 3. + let outcome = result + .take::>(3)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to delete note".into()))?; + let note = outcome.note.into_iter().next().ok_or(AppError::NotFound)?; + Ok((note, outcome.files)) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The blobs the handler unlinks are exactly the rows this transaction + /// removed — including one uploaded after any pre-read snapshot would have + /// been taken, which is the row whose blob used to leak. + #[tokio::test] + async fn delete_returns_the_attachment_rows_it_removed() { + use crate::domain::note_file::{FileContentType, FileName}; + + let db = crate::database::init_mem().await.unwrap(); + let owner = crate::domain::user::UserId::generate(); + let note = create( + &db, + &owner, + NoteTitle::try_new("a").unwrap(), + NoteContent::try_new("body").unwrap(), + ) + .await + .unwrap(); + // What a handler snapshot would have seen... + let early = NoteFile::new( + note.get_id(), + FileName::try_new("early.pdf").unwrap(), + FileContentType::try_new("application/pdf").unwrap(), + 3, + ) + .insert(&db) + .await + .unwrap(); + let (snapshot, _) = NoteFile::list_for(note.get_id(), None, 0, &db) + .await + .unwrap(); + assert_eq!(snapshot.len(), 1); + // ...and the upload that races in after it. + let late = NoteFile::new( + note.get_id(), + FileName::try_new("late.pdf").unwrap(), + FileContentType::try_new("application/pdf").unwrap(), + 3, + ) + .insert(&db) + .await + .unwrap(); + + let (gone, files) = delete(&db, note).await.unwrap(); + assert_eq!(gone.get_title().as_str(), "a"); + let mut keys: Vec<_> = files + .iter() + .map(|file| file.get_id().key().to_string()) + .collect(); + keys.sort(); + let mut want = vec![ + early.get_id().key().to_string(), + late.get_id().key().to_string(), + ]; + want.sort(); + assert_eq!(keys, want); + assert!( + NoteFile::list_for(gone.get_id(), None, 0, &db) + .await + .unwrap() + .0 + .is_empty() + ); + } +} diff --git a/src/db/page.rs b/src/db/page.rs index b6051a1..d584a40 100644 --- a/src/db/page.rs +++ b/src/db/page.rs @@ -138,7 +138,8 @@ fn total_of(count: Value) -> Result { mod tests { use super::*; use crate::database; - use crate::domain::note::{Note, NoteContent, NoteTitle}; + use crate::db::note; + use crate::domain::note::{NoteContent, NoteTitle}; use crate::domain::user::UserId; use ulid::Ulid; @@ -207,24 +208,24 @@ mod tests { let db = database::init_mem().await.unwrap(); let user = UserId::from_key(&Ulid::new().to_string()); for i in 0..5 { - Note::create( + note::create( + &db, &user, NoteTitle::try_new(&format!("n{i}")).unwrap(), NoteContent::try_new("x").unwrap(), - &db, ) .await .unwrap(); } // Every page is `limit` long and `total` ignores the window. - let (page, total) = Note::list_for(&user, Some(2), 0, &db).await.unwrap(); + let (page, total) = note::list_for(&db, &user, Some(2), 0).await.unwrap(); assert_eq!((page.len(), total), (2, 5)); - let (tail, total) = Note::list_for(&user, Some(2), 4, &db).await.unwrap(); + let (tail, total) = note::list_for(&db, &user, Some(2), 4).await.unwrap(); assert_eq!((tail.len(), total), (1, 5)); // Offset past the end is an empty page, not an error. assert_eq!( - Note::list_for(&user, Some(2), 9, &db) + note::list_for(&db, &user, Some(2), 9) .await .unwrap() .0 @@ -232,9 +233,9 @@ mod tests { 0 ); // Unpaged, and unpaged-from-an-offset: the count still covers everything. - let (all, total) = Note::list_for(&user, None, 0, &db).await.unwrap(); + let (all, total) = note::list_for(&db, &user, None, 0).await.unwrap(); assert_eq!((all.len(), total), (5, 5)); - let (rest, total) = Note::list_for(&user, None, 3, &db).await.unwrap(); + let (rest, total) = note::list_for(&db, &user, None, 3).await.unwrap(); assert_eq!((rest.len(), total), (2, 5)); // The pages are consecutive slices of the unpaged list — page diff --git a/src/db/session.rs b/src/db/session.rs new file mode 100644 index 0000000..c985df1 --- /dev/null +++ b/src/db/session.rs @@ -0,0 +1,82 @@ +//! The `session` table: opaque login tokens with an expiry, swept on login. + +use crate::constant::SESSION_DURATION_DAYS; +use crate::database::Database; +use crate::domain::session::{Session, SessionId, SessionToken}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +pub async fn create(db: &Database, user: &UserId) -> Result { + let session = Session { + id: SessionId::generate(), + user: user.clone(), + token: SessionToken::generate()?, + expires_at: Timestamp::in_days(SESSION_DURATION_DAYS), + }; + let created: Option = db.create(session.id.record()).content(session).await?; + created.ok_or_else(|| AppError::Internal("failed to create session".into())) +} + +pub async fn find_by_token(db: &Database, token: &str) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM session WHERE token = $tok LIMIT 1") + .bind(("tok", token.to_string())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) +} + +pub async fn delete_by_token(db: &Database, token: &str) -> Result<(), AppError> { + db.query("DELETE session WHERE token = $tok") + .bind(("tok", token.to_string())) + .await? + .check()?; + Ok(()) +} + +/// Revoke every session a user holds. The other half of a password reset: +/// the new credential means nothing while a cookie minted under the old one +/// still authenticates. +pub async fn delete_by_user(db: &Database, user: &UserId) -> Result<(), AppError> { + db.query("DELETE session WHERE user = $usr") + .bind(("usr", user.record())) + .await? + .check()?; + Ok(()) +} + +/// Delete every session whose expiry is in the past, returning how many were +/// removed. Expired sessions are already rejected at auth, but nothing else +/// deletes their rows — without this sweep the `session` table grows forever. +pub async fn purge_expired(db: &Database) -> Result { + let now = Timestamp::now().as_millis(); + let mut result = db + .query("DELETE session WHERE expires_at < $now RETURN BEFORE") + .bind(("now", now)) + .await? + .check()?; + Ok(result.take::>(0)?.len() as u64) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn purge_expired_removes_only_past_sessions() { + let db = crate::database::init_mem().await.unwrap(); + db.query( + "CREATE session SET user = type::record('user', 'u'), token = 'past', expires_at = 1; + CREATE session SET user = type::record('user', 'u'), token = 'future', expires_at = 99999999999999;", + ) + .await + .unwrap() + .check() + .unwrap(); + + assert_eq!(purge_expired(&db).await.unwrap(), 1); + assert!(find_by_token(&db, "past").await.unwrap().is_none()); + assert!(find_by_token(&db, "future").await.unwrap().is_some()); + } +} diff --git a/src/db/settings.rs b/src/db/settings.rs new file mode 100644 index 0000000..5810b3c --- /dev/null +++ b/src/db/settings.rs @@ -0,0 +1,296 @@ +//! The `settings` singleton: one row (`settings:school`) holding the school's +//! policy knobs. An absent row reads as the built-in defaults everywhere. + +use crate::database::Database; +use crate::domain::settings::Settings; +use crate::error::AppError; + +/// The stored policy, or the defaults when no row exists yet. +pub async fn load(db: &Database) -> Result { + let found: Option = db.select(Settings::record_id()).await?; + Ok(found.unwrap_or_else(Settings::defaults)) +} + +/// Persist the policy (single UPSERT on the fixed singleton id), +/// unconditionally — last write wins. Prefer [`save_if_unchanged`] +/// wherever the new policy was merged from a loaded snapshot. +pub async fn save(db: &Database, settings: Settings) -> Result { + // whole-row-save-ok: test-only seeding; every production write merges from a loaded snapshot and goes through save_if_unchanged + let saved: Option = db.upsert(Settings::record_id()).content(settings).await?; + saved.ok_or_else(|| AppError::Internal("failed to save settings".into())) +} + +/// Persist the policy only while the stored row still matches `expected` +/// — the snapshot the caller merged omitted fields from. `None` means a +/// concurrent edit landed in between and nothing was written: reload, +/// re-merge, retry. Without this compare-and-set, two managers patching +/// *different* fields silently revert each other (both merge from the +/// same snapshot; the later whole-row write restores its stale copy of +/// the other's field). +/// +/// One transaction: the seed insert materializes the defaults-as-loaded +/// state when no row exists yet (`load` reported the defaults, so the +/// defaults are what the caller merged over), then the guarded update +/// applies `settings` only if the row (still) equals `expected`. +/// +/// **`meal_slots` is compared through a projection, and it has to be.** +/// SurrealDB *drops* an object key whose value is `NONE` on write, while +/// the `SurrealValue` derive always emits `serving_minute: NONE` for a +/// slot without one — so `{name: 'lunch'} = {name: 'lunch', serving_minute: +/// NONE}` is **false** and a plain equality guard would never match again +/// for any school with a serving-time-less slot (which is every school +/// until it sets one): every `PATCH /settings` would 409 forever. Rebuilding +/// both sides as full objects normalizes the shapes. The NONE-ness of the +/// column itself is compared separately, so "never set" stays distinguishable +/// from "explicitly empty". Top-level optional columns need none of this: +/// a missing field reads as `NONE`, and `NONE = NONE` holds. +pub async fn save_if_unchanged( + db: &Database, + settings: Settings, + expected: &Settings, +) -> Result, AppError> { + let mut result = db + .query( + "BEGIN TRANSACTION; + INSERT IGNORE INTO settings $expected; + UPDATE $id CONTENT $new + WHERE exam_kinds = $ek + AND attendance_statuses = $st + AND grade_bands = $gb + AND max_file_bytes = $mf + AND chatbot_history_turns = $ct + AND max_chatbot_threads = $cc + AND max_chatbot_message_len = $cl + AND (meal_slots = NONE) = $ms_unset + AND (meal_slots ?? []).map(|$s| { + name: $s.name, + serving_minute: $s.serving_minute + }) = ($ms ?? []) + AND dietary_tags = $dt + AND meal_cancel_cutoff_minutes = $mc; + COMMIT TRANSACTION;", + ) + .bind(("expected", expected.clone())) + .bind(("id", Settings::record_id())) + .bind(("new", settings)) + .bind(("ek", expected.exam_kinds.clone())) + .bind(("st", expected.attendance_statuses.clone())) + .bind(("gb", expected.grade_bands.clone())) + .bind(("mf", expected.max_file_bytes)) + .bind(("ct", expected.chatbot_history_turns)) + .bind(("cc", expected.max_chatbot_threads)) + .bind(("cl", expected.max_chatbot_message_len)) + .bind(("ms_unset", expected.meal_slots.is_none())) + .bind(("ms", expected.meal_slots.clone())) + .bind(("dt", expected.dietary_tags.clone())) + .bind(("mc", expected.meal_cancel_cutoff_minutes)) + .await? + .check()?; + // Statement slots count BEGIN too: the guarded UPDATE is slot 2. An + // empty slot means the row no longer matched `expected`. + Ok(result.take::>(2)?.into_iter().next()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::constant::{ + DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_MAX_CHATBOT_MESSAGE_LEN, + DEFAULT_MAX_CHATBOT_THREADS, DEFAULT_MAX_FILE_BYTES, + }; + use crate::domain::settings::{ExamKindDef, GradeBand, SettingsParams}; + + fn kinds(list: &[&str]) -> Vec { + list.iter() + .map(|s| ExamKindDef::try_new(s, 1).unwrap()) + .collect() + } + + fn names(settings: &Settings) -> Vec<&str> { + settings + .get_exam_kinds() + .iter() + .map(ExamKindDef::get_name) + .collect() + } + + /// The defaults as tweakable params — every site below overrides only the + /// fields it is testing (`..params()`). + fn params() -> SettingsParams { + Settings::defaults().params() + } + + fn bands(list: &[(i64, &str)]) -> Vec { + list.iter() + .map(|(min, label)| GradeBand::try_new(*min, label).unwrap()) + .collect() + } + + #[tokio::test] + async fn a_row_predating_the_optional_knobs_reads_the_defaults() { + let db = crate::database::init_mem().await.unwrap(); + // The defaults carry no explicit knobs, so this writes a row without + // those fields — exactly what a volume from before them looks like. + save(&db, Settings::defaults()).await.unwrap(); + let loaded = load(&db).await.unwrap(); + assert_eq!(loaded.get_max_file_bytes(), DEFAULT_MAX_FILE_BYTES); + assert_eq!( + loaded.get_chatbot_history_turns(), + DEFAULT_CHATBOT_HISTORY_TURNS + ); + assert_eq!( + loaded.get_max_chatbot_threads(), + DEFAULT_MAX_CHATBOT_THREADS + ); + assert_eq!( + loaded.get_max_chatbot_message_len(), + DEFAULT_MAX_CHATBOT_MESSAGE_LEN + ); + // And a snapshot of that old row still passes the compare-and-set. + let saved = save_if_unchanged( + &db, + Settings::try_new(SettingsParams { + max_file_bytes: 4096, + ..loaded.params() + }) + .unwrap(), + &loaded, + ) + .await + .unwrap() + .expect("a merge over an old-shape row applies"); + assert_eq!(saved.get_max_file_bytes(), 4096); + } + + #[tokio::test] + async fn load_save_roundtrip_on_the_singleton() { + let db = crate::database::init_mem().await.unwrap(); + // No row yet → the defaults, not an error. + let loaded = load(&db).await.unwrap(); + assert_eq!( + loaded.get_exam_kinds(), + Settings::defaults().get_exam_kinds() + ); + // Save a custom policy and read it back — bands (nested objects under + // a FLEXIBLE field) must survive the trip. + save( + &db, + Settings::try_new(SettingsParams { + exam_kinds: kinds(&["lab"]), + grade_bands: bands(&[(0, "F"), (50, "P")]), + max_file_bytes: 2048, + chatbot_history_turns: 3, + ..params() + }) + .unwrap(), + ) + .await + .unwrap(); + let loaded = load(&db).await.unwrap(); + assert_eq!(names(&loaded), ["lab"]); + assert_eq!(loaded.get_grade_bands().len(), 2); + assert_eq!(loaded.grade_label(60.0), Some("P")); + assert_eq!(loaded.get_max_file_bytes(), 2048); + assert_eq!(loaded.get_chatbot_history_turns(), 3); + // A second save lands on the same singleton row, not a new one. + save( + &db, + Settings::try_new(SettingsParams { + exam_kinds: kinds(&["quiz"]), + ..params() + }) + .unwrap(), + ) + .await + .unwrap(); + let mut result = db.query("SELECT * FROM settings").await.unwrap(); + let rows: Vec = result.take(0).unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!(names(&rows[0]), ["quiz"]); + } + + #[tokio::test] + async fn a_stale_snapshot_cannot_revert_a_newer_policy() { + let db = crate::database::init_mem().await.unwrap(); + + // Editor A snapshots the policy (the defaults — no row yet)... + let stale = load(&db).await.unwrap(); + // ...then editor B lands a new exam-kind list first. + save( + &db, + Settings::try_new(SettingsParams { + exam_kinds: kinds(&["lab"]), + ..params() + }) + .unwrap(), + ) + .await + .unwrap(); + + // A's merge over the stale snapshot (kinds kept "as loaded", bands + // changed) — exactly what a concurrent PATCH /settings computes — + // must be refused, not applied. + let refused = save_if_unchanged( + &db, + Settings::try_new(SettingsParams { + grade_bands: bands(&[(0, "F"), (50, "P")]), + ..stale.params() + }) + .unwrap(), + &stale, + ) + .await + .unwrap(); + assert!(refused.is_none(), "a stale snapshot's save must not apply"); + + // B's edit must survive A's stale write attempt. + let after = load(&db).await.unwrap(); + assert_eq!( + names(&after), + ["lab"], + "a concurrent editor's exam kinds must not be silently reverted" + ); + assert!(after.get_grade_bands().is_empty()); + + // A's retry — reload, re-merge, save again — lands both edits. + let fresh = load(&db).await.unwrap(); + let saved = save_if_unchanged( + &db, + Settings::try_new(SettingsParams { + grade_bands: bands(&[(0, "F"), (50, "P")]), + ..fresh.params() + }) + .unwrap(), + &fresh, + ) + .await + .unwrap() + .expect("a merge over the current row applies"); + assert_eq!(names(&saved), ["lab"]); + assert_eq!(saved.get_grade_bands().len(), 2); + } + + #[tokio::test] + async fn save_if_unchanged_seeds_the_first_row() { + let db = crate::database::init_mem().await.unwrap(); + // No row yet: `load` reports the defaults, and a save conditioned on + // that snapshot must apply (seeding the singleton on the way). + let current = load(&db).await.unwrap(); + let saved = save_if_unchanged( + &db, + Settings::try_new(SettingsParams { + exam_kinds: kinds(&["lab"]), + ..current.params() + }) + .unwrap(), + ¤t, + ) + .await + .unwrap() + .expect("the first save applies"); + assert_eq!(names(&saved), ["lab"]); + let mut result = db.query("SELECT * FROM settings").await.unwrap(); + let rows: Vec = result.take(0).unwrap(); + assert_eq!(rows.len(), 1, "still one singleton row"); + } +} diff --git a/src/domain/bank_question.rs b/src/domain/bank_question.rs index 4fd24a1..865afb9 100644 --- a/src/domain/bank_question.rs +++ b/src/domain/bank_question.rs @@ -404,7 +404,7 @@ impl BankQuestion { /// Every field the merge re-states is in the guard, which is the same list /// the `SET` writes. `choices` is compared whole: its objects carry two /// required string keys, so none is ever dropped for being `NONE` (the trap - /// [`crate::domain::settings::Settings::save_if_unchanged`] works around). + /// [`crate::db::settings::save_if_unchanged`] works around). /// /// Rides [`write_with_retry`] because an image write now moves this row too /// ([`crate::domain::bank_question_image::BankQuestionImage::upsert`]): an @@ -467,7 +467,7 @@ impl BankQuestion { /// take off disk, but only for *these* rows — an upload that committed /// after the caller listed the template's images is swept here too, and a /// pre-read snapshot would strand its blob for good - /// ([`crate::domain::note::Note::delete`]'s story, this domain over). + /// ([`crate::db::note::delete`]'s story, this domain over). /// /// Children first, in one transaction: as two queries, a failure between /// them left image rows swept under a template that survived, or (the other diff --git a/src/domain/chatbot_thread.rs b/src/domain/chatbot_thread.rs index e62582b..7cbc018 100644 --- a/src/domain/chatbot_thread.rs +++ b/src/domain/chatbot_thread.rs @@ -11,8 +11,8 @@ use crate::constant::{ }; use crate::database::{Database, transaction_with_retry}; use crate::db::cap; -use crate::domain::monotonic_id::next_ulid; use crate::db::page::PagedList; +use crate::domain::monotonic_id::next_ulid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -356,12 +356,14 @@ mod tests { .unwrap() .check() .unwrap(); - Settings::try_new(SettingsParams { - max_chatbot_threads: threads, - ..Settings::defaults().params() - }) - .unwrap() - .save(&db) + crate::db::settings::save( + &db, + Settings::try_new(SettingsParams { + max_chatbot_threads: threads, + ..Settings::defaults().params() + }) + .unwrap(), + ) .await .unwrap(); db diff --git a/src/domain/class_blueprint.rs b/src/domain/class_blueprint.rs index 878b0d8..5fa26fb 100644 --- a/src/domain/class_blueprint.rs +++ b/src/domain/class_blueprint.rs @@ -38,11 +38,11 @@ use crate::constant::{ CLASS_BLUEPRINT_TABLE, CLASS_COURSE_TABLE, ENROLLMENT_COUNT_FIELD, MAX_CLASS_COURSES, }; use crate::database::{Database, transaction_with_retry}; +use crate::db::page::PagedList; use crate::domain::class_course::ClassCourse; use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId}; use crate::domain::class_pump::{Attached, Axis, detach}; use crate::domain::course::CourseId; -use crate::db::page::PagedList; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -76,7 +76,7 @@ use crate::error::{AppError, ValidationError}; /// /// In-process is deployment-wide here: one process by contract, with /// stop-the-world upgrades — the same argument -/// [`crate::domain::settings::SETTINGS_LOCK`] makes. No other lock is taken +/// [`crate::service::settings::SETTINGS_LOCK`] makes. No other lock is taken /// under it, so it has no ordering rule to break. pub(crate) static BLUEPRINT_LOCK: RwLock<()> = RwLock::const_new(()); diff --git a/src/domain/exam.rs b/src/domain/exam.rs index 7f081b8..bdb6c5f 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -493,7 +493,7 @@ impl Exam { /// handler's read: the compare-and-set refuses precisely when that save /// would have reverted somebody. `course`/`creator` are not editable and /// ride along unchanged. Same shape as - /// [`crate::domain::settings::Settings::save_if_unchanged`]. + /// [`crate::db::settings::save_if_unchanged`]. pub async fn update_if_unchanged( mut self, title: ExamTitle, diff --git a/src/domain/note.rs b/src/domain/note.rs index a02ccbb..5324159 100644 --- a/src/domain/note.rs +++ b/src/domain/note.rs @@ -1,13 +1,9 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{MAX_NOTE_CONTENT_LEN, MAX_NOTE_TITLE_LEN, NOTE_TABLE}; -use crate::database::Database; -use crate::db::field_update::FieldUpdate; use crate::domain::monotonic_id::next_ulid; -use crate::domain::note_file::NoteFile; -use crate::db::page::PagedList; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; use crate::validate::{validate_optional, validate_required}; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] @@ -15,7 +11,7 @@ pub struct NoteId(RecordId); impl NoteId { /// Minted from the process-wide monotonic generator, not `Ulid::new()`: - /// notes list `id DESC` (newest first, [`Note::list_for_user`]), + /// notes list `id DESC` (newest first, [`crate::db::note::list_for`]), /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { Self(RecordId::new(NOTE_TABLE, next_ulid().to_string())) @@ -65,21 +61,14 @@ impl NoteContent { } } -/// What [`Note::delete`]'s transaction removed: the note row (empty if it had -/// already vanished) and every attachment row the cascade took with it — the -/// only set whose blobs are safe to unlink. -#[derive(Debug, SurrealValue)] -struct DeleteOutcome { - note: Vec, - files: Vec, -} - +/// Fields are crate-visible: [`crate::db::note`] mints the rows on create and +/// reads the id when updating and cascading a delete. #[derive(Debug, Clone, SurrealValue)] pub struct Note { - id: NoteId, - user: UserId, - title: NoteTitle, - content: NoteContent, + pub(crate) id: NoteId, + pub(crate) user: UserId, + pub(crate) title: NoteTitle, + pub(crate) content: NoteContent, } impl Note { @@ -94,97 +83,6 @@ impl Note { pub fn get_content(&self) -> &NoteContent { &self.content } - - pub async fn create( - owner: &UserId, - title: NoteTitle, - content: NoteContent, - db: &Database, - ) -> Result { - let note = Note { - id: NoteId::generate(), - user: owner.clone(), - title, - content, - }; - let created: Option = db.create(note.id.record()).content(note).await?; - created.ok_or_else(|| AppError::Internal("failed to create note".into())) - } - - /// Read a note only if it belongs to `owner`. - pub async fn read_owned( - id: &NoteId, - owner: &UserId, - db: &Database, - ) -> Result, AppError> { - let note: Option = db.select(id.record()).await?; - Ok(note.filter(|note| ¬e.user == owner)) - } - - pub async fn list_for( - owner: &UserId, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new("note WHERE user = $usr", "ORDER BY id DESC") - .bind("usr", owner.record()) - .run(limit, offset, db) - .await - } - - /// 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, - title: Option, - content: Option, - db: &Database, - ) -> Result { - FieldUpdate::new(self.id.record()) - .set("title", title) - .set("content", content) - .run::(db) - .await - } - - /// Delete the note and cascade-remove its attachment rows, returning both: - /// the note, and the attachment rows this transaction actually removed. - /// Blob files on disk are the web layer's to remove, but only for *these* - /// rows — a row uploaded after the caller listed the note's files is - /// deleted here too, and a pre-read snapshot would strand its blob. A crash - /// between commit and unlink leaves at worst an unreachable blob, never a - /// row pointing at nothing. - /// - /// Children first, in one transaction, the way - /// [`crate::domain::course::Course::delete`] does it: as two queries, an - /// upload that committed in between kept its row while the note went, and - /// nothing could ever list or delete it again. - pub async fn delete(self, db: &Database) -> Result<(Note, Vec), AppError> { - let mut result = db - .query( - "BEGIN TRANSACTION; - LET $files = (DELETE note_file WHERE note = $note RETURN BEFORE); - LET $gone = (DELETE $note RETURN BEFORE); - RETURN { note: $gone, files: $files }; - COMMIT TRANSACTION;", - ) - .bind(("note", self.id.record())) - .await? - .check()?; - // BEGIN is slot 0, the two LETs slots 1-2; the RETURN is slot 3. - let outcome = result - .take::>(3)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to delete note".into()))?; - let note = outcome.note.into_iter().next().ok_or(AppError::NotFound)?; - Ok((note, outcome.files)) - } } #[cfg(test)] @@ -197,70 +95,6 @@ mod tests { assert!(NoteTitle::try_new(" ").is_err()); } - /// The blobs the handler unlinks are exactly the rows this transaction - /// removed — including one uploaded after any pre-read snapshot would have - /// been taken, which is the row whose blob used to leak. - #[tokio::test] - async fn delete_returns_the_attachment_rows_it_removed() { - use crate::domain::note_file::{FileContentType, FileName}; - - let db = crate::database::init_mem().await.unwrap(); - let owner = crate::domain::user::UserId::generate(); - let note = Note::create( - &owner, - NoteTitle::try_new("a").unwrap(), - NoteContent::try_new("body").unwrap(), - &db, - ) - .await - .unwrap(); - // What a handler snapshot would have seen... - let early = NoteFile::new( - note.get_id(), - FileName::try_new("early.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, - ) - .insert(&db) - .await - .unwrap(); - let (snapshot, _) = NoteFile::list_for(note.get_id(), None, 0, &db) - .await - .unwrap(); - assert_eq!(snapshot.len(), 1); - // ...and the upload that races in after it. - let late = NoteFile::new( - note.get_id(), - FileName::try_new("late.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, - ) - .insert(&db) - .await - .unwrap(); - - let (gone, files) = note.delete(&db).await.unwrap(); - assert_eq!(gone.get_title().as_str(), "a"); - let mut keys: Vec<_> = files - .iter() - .map(|file| file.get_id().key().to_string()) - .collect(); - keys.sort(); - let mut want = vec![ - early.get_id().key().to_string(), - late.get_id().key().to_string(), - ]; - want.sort(); - assert_eq!(keys, want); - assert!( - NoteFile::list_for(gone.get_id(), None, 0, &db) - .await - .unwrap() - .0 - .is_empty() - ); - } - #[tokio::test] async fn content_is_optional() { assert_eq!(NoteContent::try_new("").unwrap().as_str(), ""); diff --git a/src/domain/note_file.rs b/src/domain/note_file.rs index 2256f3e..06703ad 100644 --- a/src/domain/note_file.rs +++ b/src/domain/note_file.rs @@ -13,9 +13,9 @@ use crate::constant::{ }; use crate::database::Database; use crate::db::cap; +use crate::db::page::PagedList; use crate::domain::monotonic_id::next_ulid; use crate::domain::note::NoteId; -use crate::db::page::PagedList; use crate::error::{AppError, ValidationError}; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] @@ -279,11 +279,11 @@ mod tests { // note does not exist has no slot to take (a 409, like a full note). let owner = crate::domain::user::UserId::generate(); let note_of = async |title: &str| { - crate::domain::note::Note::create( + crate::db::note::create( + &db, &owner, crate::domain::note::NoteTitle::try_new(title).unwrap(), crate::domain::note::NoteContent::try_new("body").unwrap(), - &db, ) .await .unwrap() @@ -326,11 +326,11 @@ mod tests { #[tokio::test] async fn counter_tracks_stored_rows() { let db = crate::database::init_mem().await.unwrap(); - let note = crate::domain::note::Note::create( + let note = crate::db::note::create( + &db, &crate::domain::user::UserId::generate(), crate::domain::note::NoteTitle::try_new("a").unwrap(), crate::domain::note::NoteContent::try_new("body").unwrap(), - &db, ) .await .unwrap() diff --git a/src/domain/session.rs b/src/domain/session.rs index dc2ba08..245a2e9 100644 --- a/src/domain/session.rs +++ b/src/domain/session.rs @@ -1,8 +1,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::Ulid; -use crate::constant::{SESSION_DURATION_DAYS, SESSION_TABLE}; -use crate::database::Database; +use crate::constant::SESSION_TABLE; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; @@ -44,26 +43,16 @@ impl SessionToken { } } +/// Fields are crate-visible: [`crate::db::session`] mints the rows on login. #[derive(Debug, Clone, SurrealValue)] pub struct Session { - id: SessionId, - user: UserId, - token: SessionToken, - expires_at: Timestamp, + pub(crate) id: SessionId, + pub(crate) user: UserId, + pub(crate) token: SessionToken, + pub(crate) expires_at: Timestamp, } impl Session { - pub async fn create(user: &UserId, db: &Database) -> Result { - let session = Session { - id: SessionId::generate(), - user: user.clone(), - token: SessionToken::generate()?, - expires_at: Timestamp::in_days(SESSION_DURATION_DAYS), - }; - let created: Option = db.create(session.id.record()).content(session).await?; - created.ok_or_else(|| AppError::Internal("failed to create session".into())) - } - pub fn token(&self) -> &SessionToken { &self.token } @@ -75,47 +64,6 @@ impl Session { pub fn is_expired(&self) -> bool { self.expires_at.is_past() } - - pub async fn find_by_token(token: &str, db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM session WHERE token = $tok LIMIT 1") - .bind(("tok", token.to_string())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) - } - - pub async fn delete_by_token(token: &str, db: &Database) -> Result<(), AppError> { - db.query("DELETE session WHERE token = $tok") - .bind(("tok", token.to_string())) - .await? - .check()?; - Ok(()) - } - - /// Revoke every session a user holds. The other half of a password reset: - /// the new credential means nothing while a cookie minted under the old one - /// still authenticates. - pub async fn delete_by_user(user: &UserId, db: &Database) -> Result<(), AppError> { - db.query("DELETE session WHERE user = $usr") - .bind(("usr", user.record())) - .await? - .check()?; - Ok(()) - } - - /// Delete every session whose expiry is in the past, returning how many were - /// removed. Expired sessions are already rejected at auth, but nothing else - /// deletes their rows — without this sweep the `session` table grows forever. - pub async fn purge_expired(db: &Database) -> Result { - let now = Timestamp::now().as_millis(); - let mut result = db - .query("DELETE session WHERE expires_at < $now RETURN BEFORE") - .bind(("now", now)) - .await? - .check()?; - Ok(result.take::>(0)?.len() as u64) - } } #[cfg(test)] @@ -129,26 +77,4 @@ mod tests { assert!(token.as_str().chars().all(|c| c.is_ascii_hexdigit())); assert_ne!(SessionToken::generate().unwrap().as_str(), token.as_str()); } - - #[tokio::test] - async fn purge_expired_removes_only_past_sessions() { - let db = crate::database::init_mem().await.unwrap(); - db.query( - "CREATE session SET user = type::record('user', 'u'), token = 'past', expires_at = 1; - CREATE session SET user = type::record('user', 'u'), token = 'future', expires_at = 99999999999999;", - ) - .await - .unwrap() - .check() - .unwrap(); - - assert_eq!(Session::purge_expired(&db).await.unwrap(), 1); - assert!(Session::find_by_token("past", &db).await.unwrap().is_none()); - assert!( - Session::find_by_token("future", &db) - .await - .unwrap() - .is_some() - ); - } } diff --git a/src/domain/settings.rs b/src/domain/settings.rs index 2aae23a..059da69 100644 --- a/src/domain/settings.rs +++ b/src/domain/settings.rs @@ -12,7 +12,6 @@ //! existing rows, and `UPDATE` re-validates whole records). use surrealdb::types::{RecordId, SurrealValue}; -use tokio::sync::Mutex; use crate::constant::{ DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_DIETARY_TAGS, @@ -24,35 +23,8 @@ use crate::constant::{ MIN_CHATBOT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT, MIN_MARK, MIN_MAX_CHATBOT_MESSAGE_LEN, MIN_MAX_CHATBOT_THREADS, MIN_MAX_FILE_BYTES, SETTINGS_KEY, SETTINGS_TABLE, }; -use crate::database::Database; use crate::domain::text_fold; -use crate::error::{AppError, ValidationError}; - -/// One settings edit at a time, over the whole process. -/// -/// A list edit is a **pair** of writes, and the pair is the guard: every name -/// the edit drops is retired on its reference counter first (which refuses -/// every later claim), and only then is the list itself committed with a -/// compare-and-set against the snapshot the removals were judged from. Neither -/// write can be made to cover the other. Both retirement and un-retirement are -/// *idempotent*, so a rival that decided the same removal against the same -/// snapshot is told "already retired" and records no rollback — and when it is -/// that rival's save that wins the compare-and-set, the attempt which really -/// flipped the bit rolls it back, leaving the name off the stored list with a -/// counter reading "in service": gradable again, and unremovable for good once -/// a mark lands. No per-name bit can close that, because `Unchanged` has -/// erased which attempt owns the flip. -/// -/// So the pair is serialized instead. Every writer of the singleton goes -/// through `PATCH /settings`, and the deployment runs one process by contract -/// (stop-the-world upgrades), so process-wide is deployment-wide here — the -/// same argument [`crate::db::cap`]'s own lock makes for `retire_name`'s -/// two statements, one level up. The compare-and-set stays: it is what keeps a -/// crashed or rolled-back attempt from writing a list nobody merged. -/// -/// **Lock order:** `SETTINGS_LOCK` → `cap`'s `CLAIM_LOCK`, never the reverse — -/// the retirements are taken while this is held. -pub(crate) static SETTINGS_LOCK: Mutex<()> = Mutex::const_new(()); +use crate::error::ValidationError; /// One exam kind the school runs (`"midterm"`, `"oral"`, …) with its weight: /// how many times an exam of that kind counts into its course's average. @@ -218,30 +190,31 @@ impl GradeBand { /// The school's policy knobs, validated as a whole (parse, don't validate — /// like every other entity, an existing `Settings` is always internally -/// consistent). +/// consistent). Fields are crate-visible because [`crate::db::settings`] +/// binds them directly in the compare-and-set guard. #[derive(Debug, Clone, SurrealValue)] pub struct Settings { id: RecordId, - exam_kinds: Vec, - attendance_statuses: Vec, - grade_bands: Vec, + pub(crate) exam_kinds: Vec, + pub(crate) attendance_statuses: Vec, + pub(crate) grade_bands: Vec, /// Per-file byte cap for note uploads. `None` = the row predates the /// field (or the defaults) — reads as `DEFAULT_MAX_FILE_BYTES`. - max_file_bytes: Option, + pub(crate) max_file_bytes: Option, /// Chatbot knobs, `None`-while-unset exactly like `max_file_bytes`. - chatbot_history_turns: Option, - max_chatbot_threads: Option, - max_chatbot_message_len: Option, + pub(crate) chatbot_history_turns: Option, + pub(crate) max_chatbot_threads: Option, + pub(crate) max_chatbot_message_len: Option, /// Food-program knobs. `None`-while-unset exactly like `max_file_bytes` — /// the columns are `option<…>`, never `DEFAULT []`: `save_if_unchanged` /// writes the whole row, so a field this struct did not carry would coerce /// to `NONE` and abort the transaction. - meal_slots: Option>, - dietary_tags: Option>, + pub(crate) meal_slots: Option>, + pub(crate) dietary_tags: Option>, /// Minutes before a meal at which booking *and* cancelling close. One knob /// for both deadlines; `None` = no cutoff at all, which is also what an /// unset column reads as. - meal_cancel_cutoff_minutes: Option, + pub(crate) meal_cancel_cutoff_minutes: Option, } /// Everything [`Settings::try_new`] validates, in one struct — the knobs @@ -263,7 +236,7 @@ pub struct SettingsParams { } impl Settings { - fn record_id() -> RecordId { + pub(crate) fn record_id() -> RecordId { RecordId::new(SETTINGS_TABLE, SETTINGS_KEY) } @@ -529,92 +502,6 @@ impl Settings { .max_by_key(|band| band.get_min()) .map(GradeBand::get_label) } - - /// The stored policy, or the defaults when no row exists yet. - pub async fn load(db: &Database) -> Result { - let found: Option = db.select(Self::record_id()).await?; - Ok(found.unwrap_or_else(Self::defaults)) - } - - /// Persist the policy (single UPSERT on the fixed singleton id), - /// unconditionally — last write wins. Prefer [`Self::save_if_unchanged`] - /// wherever the new policy was merged from a loaded snapshot. - pub async fn save(self, db: &Database) -> Result { - // whole-row-save-ok: test-only seeding; every production write merges from a loaded snapshot and goes through save_if_unchanged - let saved: Option = db.upsert(Self::record_id()).content(self).await?; - saved.ok_or_else(|| AppError::Internal("failed to save settings".into())) - } - - /// Persist the policy only while the stored row still matches `expected` - /// — the snapshot the caller merged omitted fields from. `None` means a - /// concurrent edit landed in between and nothing was written: reload, - /// re-merge, retry. Without this compare-and-set, two managers patching - /// *different* fields silently revert each other (both merge from the - /// same snapshot; the later whole-row write restores its stale copy of - /// the other's field). - /// - /// One transaction: the seed insert materializes the defaults-as-loaded - /// state when no row exists yet (`load` reported the defaults, so the - /// defaults are what the caller merged over), then the guarded update - /// applies `self` only if the row (still) equals `expected`. - /// - /// **`meal_slots` is compared through a projection, and it has to be.** - /// SurrealDB *drops* an object key whose value is `NONE` on write, while - /// the `SurrealValue` derive always emits `serving_minute: NONE` for a - /// slot without one — so `{name: 'lunch'} = {name: 'lunch', serving_minute: - /// NONE}` is **false** and a plain equality guard would never match again - /// for any school with a serving-time-less slot (which is every school - /// until it sets one): every `PATCH /settings` would 409 forever. Rebuilding - /// both sides as full objects normalizes the shapes. The NONE-ness of the - /// column itself is compared separately, so "never set" stays distinguishable - /// from "explicitly empty". Top-level optional columns need none of this: - /// a missing field reads as `NONE`, and `NONE = NONE` holds. - pub async fn save_if_unchanged( - self, - expected: &Settings, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "BEGIN TRANSACTION; - INSERT IGNORE INTO settings $expected; - UPDATE $id CONTENT $new - WHERE exam_kinds = $ek - AND attendance_statuses = $st - AND grade_bands = $gb - AND max_file_bytes = $mf - AND chatbot_history_turns = $ct - AND max_chatbot_threads = $cc - AND max_chatbot_message_len = $cl - AND (meal_slots = NONE) = $ms_unset - AND (meal_slots ?? []).map(|$s| { - name: $s.name, - serving_minute: $s.serving_minute - }) = ($ms ?? []) - AND dietary_tags = $dt - AND meal_cancel_cutoff_minutes = $mc; - COMMIT TRANSACTION;", - ) - .bind(("expected", expected.clone())) - .bind(("id", Self::record_id())) - .bind(("new", self)) - .bind(("ek", expected.exam_kinds.clone())) - .bind(("st", expected.attendance_statuses.clone())) - .bind(("gb", expected.grade_bands.clone())) - .bind(("mf", expected.max_file_bytes)) - .bind(("ct", expected.chatbot_history_turns)) - .bind(("cc", expected.max_chatbot_threads)) - .bind(("cl", expected.max_chatbot_message_len)) - .bind(("ms_unset", expected.meal_slots.is_none())) - .bind(("ms", expected.meal_slots.clone())) - .bind(("dt", expected.dietary_tags.clone())) - .bind(("mc", expected.meal_cancel_cutoff_minutes)) - .await? - .check()?; - // Statement slots count BEGIN too: the guarded UPDATE is slot 2. An - // empty slot means the row no longer matched `expected`. - Ok(result.take::>(2)?.into_iter().next()) - } } /// Shared bounds check for the numeric knobs (upload cap, chatbot limits): @@ -941,156 +828,6 @@ mod tests { assert!(len(MAX_CHATBOT_MESSAGE_LEN as i64 + 1).is_err()); } - #[tokio::test] - async fn a_row_predating_the_optional_knobs_reads_the_defaults() { - let db = crate::database::init_mem().await.unwrap(); - // The defaults carry no explicit knobs, so this writes a row without - // those fields — exactly what a volume from before them looks like. - Settings::defaults().save(&db).await.unwrap(); - let loaded = Settings::load(&db).await.unwrap(); - assert_eq!(loaded.get_max_file_bytes(), DEFAULT_MAX_FILE_BYTES); - assert_eq!( - loaded.get_chatbot_history_turns(), - DEFAULT_CHATBOT_HISTORY_TURNS - ); - assert_eq!( - loaded.get_max_chatbot_threads(), - DEFAULT_MAX_CHATBOT_THREADS - ); - assert_eq!( - loaded.get_max_chatbot_message_len(), - DEFAULT_MAX_CHATBOT_MESSAGE_LEN - ); - // And a snapshot of that old row still passes the compare-and-set. - let saved = Settings::try_new(SettingsParams { - max_file_bytes: 4096, - ..loaded.params() - }) - .unwrap() - .save_if_unchanged(&loaded, &db) - .await - .unwrap() - .expect("a merge over an old-shape row applies"); - assert_eq!(saved.get_max_file_bytes(), 4096); - } - - #[tokio::test] - async fn load_save_roundtrip_on_the_singleton() { - let db = crate::database::init_mem().await.unwrap(); - // No row yet → the defaults, not an error. - let loaded = Settings::load(&db).await.unwrap(); - assert_eq!( - loaded.get_exam_kinds(), - Settings::defaults().get_exam_kinds() - ); - // Save a custom policy and read it back — bands (nested objects under - // a FLEXIBLE field) must survive the trip. - Settings::try_new(SettingsParams { - exam_kinds: kinds(&["lab"]), - grade_bands: bands(&[(0, "F"), (50, "P")]), - max_file_bytes: 2048, - chatbot_history_turns: 3, - ..params() - }) - .unwrap() - .save(&db) - .await - .unwrap(); - let loaded = Settings::load(&db).await.unwrap(); - assert_eq!(names(&loaded), ["lab"]); - assert_eq!(loaded.get_grade_bands().len(), 2); - assert_eq!(loaded.grade_label(60.0), Some("P")); - assert_eq!(loaded.get_max_file_bytes(), 2048); - assert_eq!(loaded.get_chatbot_history_turns(), 3); - // A second save lands on the same singleton row, not a new one. - Settings::try_new(SettingsParams { - exam_kinds: kinds(&["quiz"]), - ..params() - }) - .unwrap() - .save(&db) - .await - .unwrap(); - let mut result = db.query("SELECT * FROM settings").await.unwrap(); - let rows: Vec = result.take(0).unwrap(); - assert_eq!(rows.len(), 1); - assert_eq!(names(&rows[0]), ["quiz"]); - } - - #[tokio::test] - async fn a_stale_snapshot_cannot_revert_a_newer_policy() { - let db = crate::database::init_mem().await.unwrap(); - - // Editor A snapshots the policy (the defaults — no row yet)... - let stale = Settings::load(&db).await.unwrap(); - // ...then editor B lands a new exam-kind list first. - Settings::try_new(SettingsParams { - exam_kinds: kinds(&["lab"]), - ..params() - }) - .unwrap() - .save(&db) - .await - .unwrap(); - - // A's merge over the stale snapshot (kinds kept "as loaded", bands - // changed) — exactly what a concurrent PATCH /settings computes — - // must be refused, not applied. - let refused = Settings::try_new(SettingsParams { - grade_bands: bands(&[(0, "F"), (50, "P")]), - ..stale.params() - }) - .unwrap() - .save_if_unchanged(&stale, &db) - .await - .unwrap(); - assert!(refused.is_none(), "a stale snapshot's save must not apply"); - - // B's edit must survive A's stale write attempt. - let after = Settings::load(&db).await.unwrap(); - assert_eq!( - names(&after), - ["lab"], - "a concurrent editor's exam kinds must not be silently reverted" - ); - assert!(after.get_grade_bands().is_empty()); - - // A's retry — reload, re-merge, save again — lands both edits. - let fresh = Settings::load(&db).await.unwrap(); - let saved = Settings::try_new(SettingsParams { - grade_bands: bands(&[(0, "F"), (50, "P")]), - ..fresh.params() - }) - .unwrap() - .save_if_unchanged(&fresh, &db) - .await - .unwrap() - .expect("a merge over the current row applies"); - assert_eq!(names(&saved), ["lab"]); - assert_eq!(saved.get_grade_bands().len(), 2); - } - - #[tokio::test] - async fn save_if_unchanged_seeds_the_first_row() { - let db = crate::database::init_mem().await.unwrap(); - // No row yet: `load` reports the defaults, and a save conditioned on - // that snapshot must apply (seeding the singleton on the way). - let current = Settings::load(&db).await.unwrap(); - let saved = Settings::try_new(SettingsParams { - exam_kinds: kinds(&["lab"]), - ..current.params() - }) - .unwrap() - .save_if_unchanged(¤t, &db) - .await - .unwrap() - .expect("the first save applies"); - assert_eq!(names(&saved), ["lab"]); - let mut result = db.query("SELECT * FROM settings").await.unwrap(); - let rows: Vec = result.take(0).unwrap(); - assert_eq!(rows.len(), 1, "still one singleton row"); - } - #[tokio::test] async fn grade_label_picks_the_greatest_min_at_or_below() { let s = Settings::try_new(SettingsParams { diff --git a/src/domain/user.rs b/src/domain/user.rs index a185090..5d17e88 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -11,12 +11,12 @@ use crate::constant::{ REGISTRATION_FROZEN_GUARD, REGISTRATION_TABLE, USER_TABLE, }; use crate::database::{Database, transaction_with_retry, write_with_retry}; +use crate::db::field_update::FieldUpdate; +use crate::db::page::PagedList; use crate::domain::appointment::AppointmentStatus; use crate::domain::board::Board; -use crate::db::field_update::FieldUpdate; use crate::domain::monotonic_id::next_ulid; use crate::domain::note_file::FileContentType; -use crate::db::page::PagedList; use crate::domain::preferences::{Language, PaletteColor, Theme}; use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone}; use crate::domain::role::Role; @@ -39,7 +39,7 @@ use crate::validate::{validate_password, validate_username}; /// SurrealQL against the volume. /// /// Serializing the pair is what closes it, the same argument -/// [`crate::domain::settings::SETTINGS_LOCK`] makes one level up: the deployment +/// [`crate::service::settings::SETTINGS_LOCK`] makes one level up: the deployment /// runs one process by contract (stop-the-world upgrades), so process-wide is /// deployment-wide. A per-row counter (the [`crate::db::cap`] shape) does /// not fit — the count being capped is over *every* user row, with no parent @@ -896,7 +896,7 @@ impl User { /// (`POST /schools/{slug}/admin-password`). Only the credential is /// rewritten; revoking the sessions minted under the old one is the /// caller's second half - /// ([`crate::domain::session::Session::delete_by_user`]), because a reset + /// ([`crate::db::session::delete_by_user`]), because a reset /// that leaves a stolen cookie working resets nothing. pub async fn set_password_hash( id: &UserId, diff --git a/src/lib.rs b/src/lib.rs index a57cded..82f96f7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,6 +8,7 @@ pub mod error; pub mod migration_sql; pub mod module; pub mod rate_limit; +pub mod service; pub mod state; pub mod telemetry; pub mod tenant; diff --git a/src/service/mod.rs b/src/service/mod.rs new file mode 100644 index 0000000..b8d74fb --- /dev/null +++ b/src/service/mod.rs @@ -0,0 +1,6 @@ +//! Business rules, workflow locks, multi-call orchestration; calls db::*; no +//! SurrealQL text. + +pub mod note; +pub mod session; +pub mod settings; diff --git a/src/service/note.rs b/src/service/note.rs new file mode 100644 index 0000000..183483b --- /dev/null +++ b/src/service/note.rs @@ -0,0 +1,54 @@ +//! Note workflows: the create/read/list/update/delete paths the notes +//! surface drives, all scoped to the owning user. The queries live in +//! [`crate::db::note`]; blob unlinking stays in the web layer. + +use crate::database::Database; +use crate::db::note; +use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle}; +use crate::domain::note_file::NoteFile; +use crate::domain::user::UserId; +use crate::error::AppError; + +pub async fn create( + db: &Database, + owner: &UserId, + title: NoteTitle, + content: NoteContent, +) -> Result { + note::create(db, owner, title, content).await +} + +/// Read a note only if it belongs to `owner`. +pub async fn read_owned( + db: &Database, + id: &NoteId, + owner: &UserId, +) -> Result, AppError> { + note::read_owned(db, id, owner).await +} + +pub async fn list_for( + db: &Database, + owner: &UserId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + note::list_for(db, owner, limit, offset).await +} + +/// Only what the request carried is written: an omitted field (`None`) is +/// not stored at all, so a concurrent edit of the other field survives. +pub async fn update( + db: &Database, + note: Note, + title: Option, + content: Option, +) -> Result { + note::update(db, note, title, content).await +} + +/// Delete the note and cascade its attachment rows; the returned files are +/// exactly whose blobs the caller may unlink. +pub async fn delete(db: &Database, note: Note) -> Result<(Note, Vec), AppError> { + note::delete(db, note).await +} diff --git a/src/service/session.rs b/src/service/session.rs new file mode 100644 index 0000000..056c25d --- /dev/null +++ b/src/service/session.rs @@ -0,0 +1,31 @@ +//! Session workflows: mint on login, resolve per request, revoke on logout +//! and on password resets, sweep expired rows. The queries live in +//! [`crate::db::session`]. + +use crate::database::Database; +use crate::db::session; +use crate::domain::session::Session; +use crate::domain::user::UserId; +use crate::error::AppError; + +pub async fn create(db: &Database, user: &UserId) -> Result { + session::create(db, user).await +} + +pub async fn find_by_token(db: &Database, token: &str) -> Result, AppError> { + session::find_by_token(db, token).await +} + +pub async fn delete_by_token(db: &Database, token: &str) -> Result<(), AppError> { + session::delete_by_token(db, token).await +} + +/// Revoke every session a user holds — the other half of a password reset. +pub async fn delete_by_user(db: &Database, user: &UserId) -> Result<(), AppError> { + session::delete_by_user(db, user).await +} + +/// Drop expired rows; best-effort on the login path. +pub async fn purge_expired(db: &Database) -> Result { + session::purge_expired(db).await +} diff --git a/src/service/settings.rs b/src/service/settings.rs new file mode 100644 index 0000000..02097bc --- /dev/null +++ b/src/service/settings.rs @@ -0,0 +1,658 @@ +//! The settings edit workflow: one edit at a time under [`SETTINGS_LOCK`], +//! a snapshot-merge-retire-save pair whose halves cannot interleave, and the +//! compare-and-set retry that keeps two managers' patches from silently +//! reverting each other. The singleton's queries live in +//! [`crate::db::settings`]. + +use surrealdb::types::RecordId; +use tokio::sync::Mutex; + +use crate::constant::CAS_UPDATE_RETRIES; +use crate::database::Database; +use crate::db::cap; +use crate::domain::exam_result::kind_ref; +use crate::domain::menu::slot_ref; +use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings}; +use crate::error::AppError; + +/// One settings edit at a time, over the whole process. +/// +/// A list edit is a **pair** of writes, and the pair is the guard: every name +/// the edit drops is retired on its reference counter first (which refuses +/// every later claim), and only then is the list itself committed with a +/// compare-and-set against the snapshot the removals were judged from. Neither +/// write can be made to cover the other. Both retirement and un-retirement are +/// *idempotent*, so a rival that decided the same removal against the same +/// snapshot is told "already retired" and records no rollback — and when it is +/// that rival's save that wins the compare-and-set, the attempt which really +/// flipped the bit rolls it back, leaving the name off the stored list with a +/// counter reading "in service": gradable again, and unremovable for good once +/// a mark lands. No per-name bit can close that, because `Unchanged` has +/// erased which attempt owns the flip. +/// +/// So the pair is serialized instead. Every writer of the singleton goes +/// through `PATCH /settings`, and the deployment runs one process by contract +/// (stop-the-world upgrades), so process-wide is deployment-wide here — the +/// same argument [`crate::db::cap`]'s own lock makes for `retire_name`'s +/// two statements, one level up. The compare-and-set stays: it is what keeps a +/// crashed or rolled-back attempt from writing a list nobody merged. +/// +/// **Lock order:** `SETTINGS_LOCK` → `cap`'s `CLAIM_LOCK`, never the reverse — +/// the retirements are taken while this is held. +pub(crate) static SETTINGS_LOCK: Mutex<()> = Mutex::const_new(()); + +/// The stored policy, or the defaults when no row exists yet. +pub async fn load(db: &Database) -> Result { + crate::db::settings::load(db).await +} + +/// Persist the policy only while the stored row still matches `expected` — +/// the compare-and-set. `None` means a concurrent edit landed in between: +/// reload, re-merge, retry. +pub async fn save_if_unchanged( + db: &Database, + settings: Settings, + expected: &Settings, +) -> Result, AppError> { + crate::db::settings::save_if_unchanged(db, settings, expected).await +} + +/// A `PATCH /settings` body after wire mapping: only the fields the school +/// sent. Lists stay raw on purpose — validating them is the workflow's own +/// step, in its own order, and keeping a stored meal-slot name skips the +/// URL-charset rule (`MealSlotDef::try_kept`), which only [`apply`], holding +/// the lock and the stored list, can decide. +pub struct SettingsPatch { + pub exam_kinds: Option>, + pub attendance_statuses: Option>, + pub grade_bands: Option>, + pub max_file_bytes: Option, + pub chatbot_history_turns: Option, + pub max_chatbot_threads: Option, + pub max_chatbot_message_len: Option, + pub meal_slots: Option>, + pub dietary_tags: Option>, + /// Absent keeps the knob; `Some(None)` clears it (no cutoff at all). + pub meal_cancel_cutoff_minutes: Option>, +} + +/// One submitted exam kind, raw. +pub struct ExamKindInput { + pub name: String, + pub weight: i64, +} + +/// One submitted grade band, raw. +pub struct GradeBandInput { + pub min: i64, + pub label: String, +} + +/// One submitted meal slot, raw. +pub struct MealSlotInput { + pub name: String, + pub serving_minute: Option, +} + +/// The whole edit — snapshot, merge, retire, save — as one operation, so the +/// tests can drive it the way two managers do. +pub async fn apply(db: &Database, patch: &SettingsPatch) -> Result { + // One settings edit at a time: the removals below are decided against the + // snapshot this loop loads and written *before* the save that justifies + // them, and no per-name bookkeeping can make that pair survive a rival's + // pair interleaving with it (see `SETTINGS_LOCK`). + let _guard = SETTINGS_LOCK.lock().await; + // Merge over a snapshot, then save only while the row still matches it — + // otherwise a concurrent PATCH of a *different* field would be silently + // reverted by whichever whole-row write lands second. A refused save + // reloads and re-merges, so both edits land. + for _ in 0..CAS_UPDATE_RETRIES { + let current = load(db).await?; + + let exam_kinds = match &patch.exam_kinds { + Some(kinds) => kinds + .iter() + .map(|kind| ExamKindDef::try_new(&kind.name, kind.weight)) + .collect::, _>>()?, + None => current.get_exam_kinds().to_vec(), + }; + let was_slots = slot_names(¤t.get_meal_slots()); + let meal_slots = match &patch.meal_slots { + Some(slots) => slots + .iter() + .map(|slot| { + // A name the row already carries is validated as a kept one: + // the charset rule is younger than the stored lists, and + // re-validating one under it would leave a school unable to + // edit the rest of its slots at all (`MealSlotDef::try_kept`). + if was_slots.iter().any(|kept| kept == slot.name.trim()) { + MealSlotDef::try_kept(&slot.name, slot.serving_minute) + } else { + MealSlotDef::try_new(&slot.name, slot.serving_minute) + } + }) + .collect::, _>>()?, + None => current.get_meal_slots(), + }; + let attendance_statuses = patch + .attendance_statuses + .clone() + .unwrap_or_else(|| current.get_attendance_statuses().to_vec()); + let grade_bands = match &patch.grade_bands { + Some(bands) => bands + .iter() + .map(|band| GradeBand::try_new(band.min, &band.label)) + .collect::, _>>()?, + None => current.get_grade_bands().to_vec(), + }; + // The name lists as they stand and as they would stand, for the removal + // guards below — a list edit is judged by which names it drops. + let was_kinds = kind_names(current.get_exam_kinds()); + let now_kinds = kind_names(&exam_kinds); + let now_slots = slot_names(&meal_slots); + + // Merge over the snapshot's resolved values: an omitted field keeps + // whatever the row (or the default behind an unset field) reads as. + let mut params = current.params(); + params.exam_kinds = exam_kinds; + params.attendance_statuses = attendance_statuses; + params.grade_bands = grade_bands; + params.max_file_bytes = patch.max_file_bytes.unwrap_or(params.max_file_bytes); + params.chatbot_history_turns = patch + .chatbot_history_turns + .unwrap_or(params.chatbot_history_turns); + params.max_chatbot_threads = patch + .max_chatbot_threads + .unwrap_or(params.max_chatbot_threads); + params.max_chatbot_message_len = patch + .max_chatbot_message_len + .unwrap_or(params.max_chatbot_message_len); + params.meal_slots = meal_slots; + params.dietary_tags = patch + .dietary_tags + .clone() + .unwrap_or_else(|| current.get_dietary_tags()); + // Double option: absent keeps the knob, `null` clears it (no cutoff). + params.meal_cancel_cutoff_minutes = patch + .meal_cancel_cutoff_minutes + .unwrap_or(params.meal_cancel_cutoff_minutes); + + let settings = Settings::try_new(params)?; + + // The removal guards. A name leaves a list by being *retired* on its + // reference counter — one conditional write on one record, which lands + // only while nothing references the name and refuses every claim from + // that instant on. That is the whole guard: the check and the removal + // used to be a cross-table count and a save held together by a + // process-wide lock that was released around the round trip between + // them. + // + // Retired before the save, never after: the other order leaves a window + // in which a mark lands under a kind the settings no longer list. A save + // that then does not land undoes them (`restore`) before the next try. + // + // Only a write that actually *flipped* a bit is recorded for that undo. + // Retirement is idempotent, so two PATCHes dropping the same kind are + // both told "retired" — and the one whose save then loses the row's CAS + // used to un-retire the winner's kind, leaving it off the list with its + // counter in service: gradable again, its count then non-zero, and so + // impossible to remove ever after. + let mut undo: Vec = Vec::new(); + let mut refused = None; + for gone in missing(&was_kinds, &now_kinds) { + let counter = kind_ref(&gone); + match cap::retire_name(&counter, db).await? { + cap::Switched::Flipped => undo.push(Undo::Retired(counter)), + cap::Switched::Unchanged => {} + cap::Switched::InUse => { + refused = Some(AppError::ConflictOwned(format!( + "exams of kind '{gone}' are already graded — the kind cannot be removed" + ))); + break; + } + } + } + // Same shape for meal slots: a slot a menu was already published for + // cannot leave the list — the menu snapshotted the name as text, and a + // slot no longer offered would leave that menu unreachable from the + // school's own list. + if refused.is_none() { + for gone in missing(&was_slots, &now_slots) { + let counter = slot_ref(&gone); + match cap::retire_name(&counter, db).await? { + cap::Switched::Flipped => undo.push(Undo::Retired(counter)), + cap::Switched::Unchanged => {} + cap::Switched::InUse => { + refused = Some(AppError::ConflictOwned(format!( + "menus are already published for the '{gone}' slot — it cannot be removed" + ))); + break; + } + } + } + } + if let Some(refused) = refused { + restore(&undo, db).await?; + return Err(refused); + } + // A name re-entering a list is back in service: its counter still + // carries the retirement from the edit that dropped it, and a mark (or + // a menu) under a kind the school offers again must not be refused. + // Recorded for the same undo as the retirements — a re-add whose save + // does not land leaves a name off the list that grades happily. + for back in missing(&now_kinds, &was_kinds) { + if let cap::Switched::Flipped = cap::unretire_name(&kind_ref(&back), db).await? { + undo.push(Undo::Unretired(kind_ref(&back))); + } + } + for back in missing(&now_slots, &was_slots) { + if let cap::Switched::Flipped = cap::unretire_name(&slot_ref(&back), db).await? { + undo.push(Undo::Unretired(slot_ref(&back))); + } + } + + match save_if_unchanged(db, settings, ¤t).await { + Ok(Some(saved)) => return Ok(saved), + // The row moved under the snapshot these guards were judged against: + // put the names back and re-merge, or the next attempt would decide + // against a list nobody asked for. + Ok(None) => restore(&undo, db).await?, + Err(err) => { + restore(&undo, db).await?; + return Err(err); + } + } + } + Err(AppError::Conflict( + "the settings kept changing underneath this update — try again", + )) +} + +fn kind_names(kinds: &[ExamKindDef]) -> Vec { + kinds + .iter() + .map(|kind| kind.get_name().to_string()) + .collect() +} + +fn slot_names(slots: &[MealSlotDef]) -> Vec { + slots + .iter() + .map(|slot| slot.get_name().to_string()) + .collect() +} + +/// The names `before` carries that `after` does not — a list edit's removals, +/// or its additions with the arguments swapped. +fn missing(before: &[String], after: &[String]) -> Vec { + before + .iter() + .filter(|name| !after.contains(name)) + .cloned() + .collect() +} + +/// One `retired` bit this attempt moved, and which way — what `restore` needs +/// to put it back. Only bits this attempt actually *flipped* are listed: a +/// write that changed nothing has nothing to take back, and taking it back +/// would undo the concurrent edit that really did move it. +enum Undo { + /// Retired for a removal; put it back in service. + Retired(RecordId), + /// Put back in service for a re-add; retire it again. + Unretired(RecordId), +} + +/// Undo every bit this attempt moved: the edit that justified them did not +/// land, so the lists the school offers are still the ones it started with. +async fn restore(undo: &[Undo], db: &Database) -> Result<(), AppError> { + for step in undo { + match step { + Undo::Retired(name) => { + cap::unretire_name(name, db).await?; + } + // A re-retirement can be refused: a mark (or a menu) landed under + // the name during the window it was in service. Refusing to undo is + // then the honest answer — the reference is real, and retiring over + // it would make the row's kind ungradable while nothing lists it. + // The name is left in service, matching the list this attempt is + // about to re-read. + Undo::Unretired(name) => { + cap::retire_name(name, db).await?; + } + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::database::init_mem; + use crate::db::settings::save; + + /// The `retired` bit as the store holds it, `None` when no counter row was + /// ever written — read back, never inferred from a return value. + async fn bit(db: &Database, counter: RecordId) -> Option { + let mut result = db + .query("SELECT VALUE retired FROM $id") + .bind(("id", counter)) + .await + .unwrap() + .check() + .unwrap(); + result.take::>(0).unwrap().first().copied() + } + + /// Two managers drop the same exam kind at once; one of them loses the + /// row's compare-and-set and rolls its attempt back. The winner's + /// retirement must survive that rollback — undone, the kind is off the list + /// with a counter that still grades, and the first mark to land makes it + /// unremovable for good. + /// + /// The loser's half is what runs here: a retirement that changed nothing + /// records no undo, so `restore` has nothing to take back. + #[tokio::test] + async fn the_loser_of_a_settings_race_cannot_un_retire_the_winner_s_kind() { + let db = init_mem().await.unwrap(); + let counter = kind_ref("midterm"); + + // The winner's PATCH retires the kind. + assert!(matches!( + cap::retire_name(&counter, &db).await.unwrap(), + cap::Switched::Flipped + )); + + // The loser's PATCH decides the same removal against the same snapshot, + // then its save is refused. + let mut undo = Vec::new(); + if let cap::Switched::Flipped = cap::retire_name(&counter, &db).await.unwrap() { + undo.push(Undo::Retired(counter.clone())); + } + assert!(undo.is_empty(), "a no-op retirement records no undo"); + restore(&undo, &db).await.unwrap(); + + assert_eq!( + bit(&db, counter).await, + Some(true), + "the winner's retirement must outlive the loser's rollback" + ); + } + + /// The mirror hole: a re-*added* name is put back in service before the + /// save, so a save that does not land owes a re-retirement. Without it the + /// name is off the stored list with a counter that grades happily. + #[tokio::test] + async fn a_rollback_re_retires_a_name_this_attempt_put_back_in_service() { + let db = init_mem().await.unwrap(); + let counter = slot_ref("lunch"); + cap::retire_name(&counter, &db).await.unwrap(); + + // The attempt re-adds the slot, then its save is refused. + let mut undo = Vec::new(); + if let cap::Switched::Flipped = cap::unretire_name(&counter, &db).await.unwrap() { + undo.push(Undo::Unretired(counter.clone())); + } + assert_eq!(undo.len(), 1, "a real un-retirement is undoable"); + restore(&undo, &db).await.unwrap(); + + assert_eq!( + bit(&db, counter).await, + Some(true), + "a re-add that never landed must leave the slot retired" + ); + } + + /// ...unless a menu was published in the window the slot was back in + /// service. The reference is real, so the re-retirement is refused and the + /// slot stays usable — the honest end of the same rule, not a silent + /// overwrite of a live reference. + #[tokio::test] + async fn a_rollback_leaves_a_name_that_gained_a_reference_in_service() { + let db = init_mem().await.unwrap(); + let counter = slot_ref("lunch"); + cap::retire_name(&counter, &db).await.unwrap(); + cap::unretire_name(&counter, &db).await.unwrap(); + db.query("UPDATE $id SET count = 1") + .bind(("id", counter.clone())) + .await + .unwrap() + .check() + .unwrap(); + + restore(&[Undo::Unretired(counter.clone())], &db) + .await + .unwrap(); + + assert_eq!(bit(&db, counter).await, Some(false)); + } + + // --- the whole edit, driven the way two managers drive it ------------- + + /// A `PATCH` body that names nothing: every field keeps the stored value. + fn a_patch() -> SettingsPatch { + SettingsPatch { + exam_kinds: None, + attendance_statuses: None, + grade_bands: None, + max_file_bytes: None, + chatbot_history_turns: None, + max_chatbot_threads: None, + max_chatbot_message_len: None, + meal_slots: None, + dietary_tags: None, + meal_cancel_cutoff_minutes: None, + } + } + + /// An `exam_kinds` list as the router builds it (weight 1, like the + /// harness bodies). + fn kinds(names: &[&str]) -> Vec { + names + .iter() + .map(|name| ExamKindInput { + name: (*name).to_string(), + weight: 1, + }) + .collect() + } + + /// A `meal_slots` list as the router builds it (no serving minute). + fn slots(names: &[&str]) -> Vec { + names + .iter() + .map(|name| MealSlotInput { + name: (*name).to_string(), + serving_minute: None, + }) + .collect() + } + + /// The lists as the store holds them. + async fn stored(db: &Database) -> (Vec, Vec) { + let settings = load(db).await.unwrap(); + ( + kind_names(settings.get_exam_kinds()), + slot_names(&settings.get_meal_slots()), + ) + } + + /// The whole invariant, over the reachable half of the race: two managers + /// drop the same exam kind at once, both edits go through the real path, + /// and when both have returned the counter's `retired` bit must agree with + /// the list the store actually holds. + /// + /// One of the two decides the removal, retires the kind and saves; the + /// other cannot even see the old list, because the whole snapshot-retire- + /// save pair is serialized (`SETTINGS_LOCK`). Interleaved, the second + /// attempt would be told "already retired", record no undo, win the + /// compare-and-set, and leave the first attempt un-retiring the kind it had + /// legitimately removed — off the list and gradable. + #[tokio::test] + async fn two_edits_dropping_the_same_kind_leave_it_retired() { + let db = init_mem().await.unwrap(); + let without = SettingsPatch { + exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])), + ..a_patch() + }; + + let (a, b) = tokio::join!(apply(&db, &without), apply(&db, &without)); + a.unwrap(); + b.unwrap(); + + let (kinds, _) = stored(&db).await; + assert!( + !kinds.contains(&"midterm".to_string()), + "dropped from the list" + ); + assert_eq!( + bit(&db, kind_ref("midterm")).await, + Some(true), + "a kind the stored list no longer offers must not grade" + ); + } + + /// The property those two outcomes rest on, asserted on its own because a + /// `join!` cannot be made to schedule the losing order: the edit is a pair + /// of writes — retire the dropped names, then commit the list — and no + /// rival's pair may run between them. + /// + /// Retirement is idempotent, so an interleaved rival is told "already + /// retired", records no rollback, wins the compare-and-set, and leaves the + /// attempt that really flipped the bit un-retiring a kind the stored list + /// no longer offers: gradable again, and unremovable for good once a mark + /// lands. Holding the lock stands in for a rival mid-pair here — nothing + /// the other edit does may be visible until the pair completes. + #[tokio::test] + async fn a_rival_edit_cannot_run_between_a_retirement_and_its_save() { + let db = init_mem().await.unwrap(); + let without = SettingsPatch { + exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])), + ..a_patch() + }; + + let held = SETTINGS_LOCK.lock().await; + let rival = tokio::spawn({ + let db = db.clone(); + async move { apply(&db, &without).await.map(|_| ()) } + }); + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + + assert_eq!( + bit(&db, kind_ref("midterm")).await, + None, + "a rival's pair must not have started, let alone half-landed" + ); + assert!(stored(&db).await.0.contains(&"midterm".to_string())); + + drop(held); + rival.await.unwrap().unwrap(); + assert_eq!(bit(&db, kind_ref("midterm")).await, Some(true)); + assert!(!stored(&db).await.0.contains(&"midterm".to_string())); + } + + /// The mirror: two managers put the same kind *back* at once. The attempt + /// that loses must not re-retire a name the winner's stored list carries — + /// a listed kind that refuses every grade. + #[tokio::test] + async fn two_edits_re_adding_the_same_kind_leave_it_in_service() { + let db = init_mem().await.unwrap(); + let without = SettingsPatch { + exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])), + ..a_patch() + }; + apply(&db, &without).await.unwrap(); + let with = SettingsPatch { + exam_kinds: Some(kinds(&[ + "homework", "quiz", "midterm", "final", "project", "oral", + ])), + ..a_patch() + }; + + let (a, b) = tokio::join!(apply(&db, &with), apply(&db, &with)); + a.unwrap(); + b.unwrap(); + + let (kinds, _) = stored(&db).await; + assert!(kinds.contains(&"midterm".to_string()), "back on the list"); + assert_eq!( + bit(&db, kind_ref("midterm")).await, + Some(false), + "a kind the stored list offers must grade" + ); + } + + /// The same pair over meal slots, which retire on their own counters. + #[tokio::test] + async fn two_edits_dropping_the_same_slot_leave_it_retired() { + let db = init_mem().await.unwrap(); + let without = SettingsPatch { + meal_slots: Some(slots(&["breakfast", "snack"])), + ..a_patch() + }; + + let (a, b) = tokio::join!(apply(&db, &without), apply(&db, &without)); + a.unwrap(); + b.unwrap(); + + let (_, stored_slots) = stored(&db).await; + assert!(!stored_slots.contains(&"lunch".to_string())); + assert_eq!(bit(&db, slot_ref("lunch")).await, Some(true)); + } + + // --- the stale slot name that wedged the whole list ------------------- + + /// A school that stored `a/b` before the URL-safety rule existed. + async fn a_school_with_a_stale_slot(db: &Database) { + let mut params = Settings::defaults().params(); + params.meal_slots = vec![ + MealSlotDef::try_kept("a/b", None).unwrap(), + MealSlotDef::try_new("lunch", None).unwrap(), + ]; + save(db, Settings::try_new(params).unwrap()).await.unwrap(); + } + + /// The wedge: re-sending a stored name is the only way to *keep* it, and + /// dropping it 409s once a menu references it — so validating it under the + /// younger rule locks the school out of its own `meal_slots` forever. A + /// stored name is submittable; a new one with the same characters is not. + #[tokio::test] + async fn a_stored_slot_name_stays_submittable_but_a_new_one_does_not() { + let db = init_mem().await.unwrap(); + a_school_with_a_stale_slot(&db).await; + + let edit = SettingsPatch { + meal_slots: Some(slots(&["a/b", "lunch", "dinner"])), + ..a_patch() + }; + apply(&db, &edit).await.unwrap(); + let (_, stored_slots) = stored(&db).await; + assert_eq!(stored_slots, ["a/b", "lunch", "dinner"]); + + let fresh = SettingsPatch { + meal_slots: Some(slots(&["a/b", "lunch", "c/d"])), + ..a_patch() + }; + assert!( + apply(&db, &fresh).await.is_err(), + "a name no school ever stored is still refused" + ); + } + + /// And an edit that never mentions `meal_slots` still carries the list + /// over unvalidated — the behaviour the wedge report leaned on. + #[tokio::test] + async fn an_unrelated_edit_carries_a_stale_slot_name_over() { + let db = init_mem().await.unwrap(); + a_school_with_a_stale_slot(&db).await; + + let elsewhere = SettingsPatch { + max_file_bytes: Some(2048), + ..a_patch() + }; + let saved = apply(&db, &elsewhere).await.unwrap(); + + assert_eq!(saved.get_max_file_bytes(), 2048); + assert_eq!(slot_names(&saved.get_meal_slots()), ["a/b", "lunch"]); + } +} diff --git a/src/web/auth.rs b/src/web/auth.rs index 5ca561f..a550d02 100644 --- a/src/web/auth.rs +++ b/src/web/auth.rs @@ -12,10 +12,10 @@ use utoipa_axum::routes; use crate::constant::{RESERVED_USERNAMES, SESSION_DURATION_DAYS}; use crate::domain::builder::BuilderSession; use crate::domain::role::Role as DomainRole; -use crate::domain::session::Session; use crate::domain::user::{Password, PasswordHash, User, Username}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::rate_limit::{RateLimitConfig, RateLimiter}; +use crate::service; use crate::state::AppState; use crate::tenant::Slug; @@ -194,9 +194,9 @@ async fn login( }; // The caller is genuine; opportunistically drop any expired session rows. - let _ = Session::purge_expired(&db).await; + let _ = service::session::purge_expired(&db).await; - let session = Session::create(user.get_id(), &db).await?; + let session = service::session::create(&db, user.get_id()).await?; // `.`: the cookie carries the school, so every later request // finds its database without a second lookup path that could disagree. let cookie = session_cookie( @@ -245,7 +245,7 @@ async fn logout( } else if let Ok(slug) = Slug::try_new(prefix) && let Ok(db) = st.tenants.get(&slug).await { - Session::delete_by_token(token, &db).await?; + service::session::delete_by_token(&db, token).await?; } } let jar = jar.remove(Cookie::build(("session", "")).path("/").build()); diff --git a/src/web/builder.rs b/src/web/builder.rs index 052f2cd..2c0ad73 100644 --- a/src/web/builder.rs +++ b/src/web/builder.rs @@ -28,11 +28,11 @@ use utoipa_axum::routes; use crate::constant::MAX_SCHOOL_NAME_LEN; use crate::domain::builder::{Builder, BuilderSession}; use crate::domain::role::Role; -use crate::domain::session::Session; use crate::domain::user::{Password, PasswordHash, User, Username}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::module::{Module, ModuleSet, Package}; use crate::rate_limit::{RateLimitConfig, RateLimiter}; +use crate::service; use crate::state::AppState; use crate::tenant::{School, SchoolStatus, Slug}; use crate::validate::validate_required; @@ -759,7 +759,7 @@ async fn reset_admin_password( .ok_or(AppError::NotFound)?; // The other half: the new password means nothing while a cookie minted // under the old one still authenticates. - Session::delete_by_user(user.get_id(), &db).await?; + service::session::delete_by_user(&db, user.get_id()).await?; Ok(StatusCode::NO_CONTENT) } @@ -798,7 +798,7 @@ async fn enter_school( } let user = school_admin(&req.username, &db).await?; - let session = Session::create(user.get_id(), &db).await?; + let session = service::session::create(&db, user.get_id()).await?; let cookie = session_cookie( format!("{slug}.{}", session.token().as_str()), st.cookie_secure, diff --git a/src/web/chatbot.rs b/src/web/chatbot.rs index 4264b92..8e7881a 100644 --- a/src/web/chatbot.rs +++ b/src/web/chatbot.rs @@ -49,6 +49,7 @@ use crate::domain::role::Role; use crate::domain::settings::Settings; use crate::domain::user::UserId; use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::service; use crate::state::{AppState, scoped_key}; use super::{CurrentUser, Page, PageParams}; @@ -388,7 +389,7 @@ async fn send_message( .enforce_user(&scoped_key(&slug, user.get_id().key()))?; let thread = own_thread(&id, user.get_id(), &st.db).await?; - let settings = Settings::load(&st.db).await?; + let settings = service::settings::load(&st.db).await?; let reply_cap = content_cap(&settings); let length = req.content.chars().count(); if length > reply_cap { diff --git a/src/web/course_notes.rs b/src/web/course_notes.rs index 63e2e4d..a71922a 100644 --- a/src/web/course_notes.rs +++ b/src/web/course_notes.rs @@ -25,8 +25,8 @@ use crate::domain::course_note_file::{ CourseNoteFile, CourseNoteFileId, FileContentType, FileName, }; use crate::domain::rag_output::{RagOutput, RagOutputId}; -use crate::domain::settings::Settings; use crate::error::{AppError, ErrorResponse}; +use crate::service; use crate::state::AppState; use super::courses::{can_manage_course, can_view_course}; @@ -381,7 +381,7 @@ async fn upload_file( course.require_open(&st.db).await?; // The 10-file cap is enforced inside `CourseNoteFile::insert` (count and // create under one lock) — checking it here too would just race. - let limit = Settings::load(&st.db).await?.get_max_file_bytes(); + let limit = service::settings::load(&st.db).await?.get_max_file_bytes(); let upload = read_upload(&mut multipart, limit).await?; let name = FileName::try_new(&upload.name.unwrap_or_default())?; diff --git a/src/web/courses.rs b/src/web/courses.rs index 46b7057..9e83dfc 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -23,11 +23,11 @@ use crate::domain::homework::{Homework, HomeworkTitle}; use crate::domain::homework_file::HomeworkFile; use crate::domain::question_image::QuestionImage; use crate::domain::role::Role; -use crate::domain::settings::Settings; use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::service; use crate::state::AppState; use super::homework::{description_or_none, resolve_assigned}; @@ -896,7 +896,7 @@ async fn create_exam_in_course( let title = ExamTitle::try_new(&req.title)?; let description = ExamDescription::try_new(&req.description.unwrap_or_default())?; - let school = Settings::load(&st.db).await?; + let school = service::settings::load(&st.db).await?; let kind = ExamKind::try_new(&req.kind, school.get_exam_kinds())?; let starts_at = req.starts_at.map(Timestamp::from_millis); let ends_at = req.ends_at.map(Timestamp::from_millis); diff --git a/src/web/events.rs b/src/web/events.rs index 8a6b475..6f0d101 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -16,10 +16,10 @@ use crate::domain::course::{Course, CourseId}; use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle}; use crate::domain::registration::Registration; use crate::domain::role::Role; -use crate::domain::settings::Settings; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::service; use crate::state::AppState; use super::{ @@ -509,7 +509,7 @@ async fn mark( .await? .ok_or(AppError::NotFound)?; - let school = Settings::load(&st.db).await?; + let school = service::settings::load(&st.db).await?; let status = AttendanceStatus::try_new(&req.status, school.get_attendance_statuses())?; let target = match req.user_id { Some(ref key) => UserId::from_key(key), diff --git a/src/web/exams/mod.rs b/src/web/exams/mod.rs index 64c52df..7361018 100644 --- a/src/web/exams/mod.rs +++ b/src/web/exams/mod.rs @@ -32,10 +32,10 @@ use crate::domain::exam_result::{ExamResult, Mark}; use crate::domain::note_file::FileContentType; use crate::domain::question_image::QuestionImage; use crate::domain::role::Role; -use crate::domain::settings::Settings; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::service; use crate::state::AppState; use super::bank_questions::BankQuestionResponse; @@ -448,7 +448,7 @@ async fn update_exam( // a stored kind survives later list edits, like past times survive // the no-past rule. Some(ref kind) => { - let school = Settings::load(&st.db).await?; + let school = service::settings::load(&st.db).await?; ExamKind::try_new(kind, school.get_exam_kinds())? } None => exam.get_kind().clone(), @@ -691,7 +691,7 @@ async fn grade( // also a mark that averages at weight 1 forever. Both gates, same answer; // this one is a read, the counter's is the one that survives a race. let kind = exam.get_kind().as_str(); - if !Settings::load(&st.db) + if !service::settings::load(&st.db) .await? .get_exam_kinds() .iter() diff --git a/src/web/extractor.rs b/src/web/extractor.rs index ba4c63b..a6f9af5 100644 --- a/src/web/extractor.rs +++ b/src/web/extractor.rs @@ -5,9 +5,9 @@ use axum_extra::extract::CookieJar; use crate::database::Database; use crate::domain::builder::{Builder, BuilderSession}; use crate::domain::role::Role; -use crate::domain::session::Session; use crate::domain::user::User; use crate::error::AppError; +use crate::service; use crate::state::AppState; use crate::web::tenant_state::{resolve_tenant, split_cookie}; @@ -43,7 +43,7 @@ where let cookie = jar.get("session").ok_or(AppError::Unauthorized)?; let (_, token) = split_cookie(cookie.value()).ok_or(AppError::Unauthorized)?; - let session = Session::find_by_token(token, &db) + let session = service::session::find_by_token(&db, token) .await? .ok_or(AppError::Unauthorized)?; if session.is_expired() { diff --git a/src/web/homework.rs b/src/web/homework.rs index a012db2..0852606 100644 --- a/src/web/homework.rs +++ b/src/web/homework.rs @@ -30,10 +30,10 @@ use crate::domain::homework_submission::{ }; use crate::domain::note_file::{FileContentType, FileName}; use crate::domain::role::Role; -use crate::domain::settings::Settings; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::service; use crate::state::AppState; use super::courses::{can_manage_course, can_view_course, visible_courses}; @@ -908,7 +908,7 @@ async fn upload_submission_file( // below, because this snapshot goes stale while the body streams. let preflight = gate_own_submission(&id, &user, &st.db).await?; require_open_term(&preflight, &st.db).await?; - let limit = Settings::load(&st.db).await?.get_max_file_bytes(); + let limit = service::settings::load(&st.db).await?.get_max_file_bytes(); // Consume the body before taking the lock — a slow upload must not stall the // homework subsystem (mirrors the exam/note image uploads). let upload = read_upload(&mut multipart, limit).await?; diff --git a/src/web/image.rs b/src/web/image.rs index 9851b0b..8437fa2 100644 --- a/src/web/image.rs +++ b/src/web/image.rs @@ -15,8 +15,8 @@ use std::future::Future; use axum::extract::Multipart; use crate::domain::note_file::FileContentType; -use crate::domain::settings::Settings; use crate::error::AppError; +use crate::service; use crate::state::AppState; use super::{blob_path, image_content_type, read_upload, remove_blob}; @@ -40,7 +40,7 @@ pub(crate) async fn read_image_upload( st: &AppState, multipart: &mut Multipart, ) -> Result { - let limit = Settings::load(&st.db).await?.get_max_file_bytes(); + let limit = service::settings::load(&st.db).await?.get_max_file_bytes(); let upload = read_upload(multipart, limit).await?; let content_type = image_content_type(&upload.content_type.unwrap_or_default())?; Ok(ImageUpload { diff --git a/src/web/marks.rs b/src/web/marks.rs index cba2b81..f889137 100644 --- a/src/web/marks.rs +++ b/src/web/marks.rs @@ -13,9 +13,9 @@ use crate::domain::course::Course; use crate::domain::exam::Exam; use crate::domain::exam_result::ExamResult; use crate::domain::role::Role; -use crate::domain::settings::Settings; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse}; +use crate::service; use crate::state::AppState; use super::courses::can_manage_course; @@ -102,7 +102,7 @@ async fn build_report( } // One settings read weighs and labels the whole report. - let school = Settings::load(db).await?; + let school = service::settings::load(db).await?; let people = person_map(courses.iter().flat_map(course_people), db).await?; let mut blocks = Vec::with_capacity(courses.len()); diff --git a/src/web/meals.rs b/src/web/meals.rs index 8b27a79..59360f7 100644 --- a/src/web/meals.rs +++ b/src/web/meals.rs @@ -32,9 +32,9 @@ use crate::domain::parent_link::ParentLink; // The same idempotence key `/payments/credits` takes — one grammar, one type. use crate::domain::payment_ledger::PaymentRequestKey; use crate::domain::role::Role; -use crate::domain::settings::Settings; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::service; use crate::state::AppState; use super::{ @@ -270,7 +270,10 @@ async fn create_menu( // against the end of the day, so today's menu is publishable all day — the // meal's own deadline is `meal_cancel_cutoff_minutes`, not this. check_not_past("date", date.day_end())?; - let slot = MenuSlot::try_new(&req.slot, &Settings::load(&st.db).await?.get_meal_slots())?; + let slot = MenuSlot::try_new( + &req.slot, + &service::settings::load(&st.db).await?.get_meal_slots(), + )?; validate_capacity(req.capacity)?; let menu = Menu::create(date, slot, req.capacity, user.get_id(), &st.db).await?; let body = one_menu(&menu, user.get_id(), &st.db).await?; @@ -431,7 +434,10 @@ async fn add_dish( .transpose()? .flatten(); let price = DishPrice::try_new(req.price_minor)?; - let tags = DishTags::try_new(&req.tags, &Settings::load(&st.db).await?.get_dietary_tags())?; + let tags = DishTags::try_new( + &req.tags, + &service::settings::load(&st.db).await?.get_dietary_tags(), + )?; // Dish writes take [`MENU_LOCK`] for the dish cap alone: count-then-write // is write-skew, so the count and the insert have to be one step. The // *price* no longer needs it — a dish write moves the menu's revision, and @@ -499,7 +505,7 @@ async fn update_dish( let tags = match &req.tags { Some(tags) => Some(DishTags::try_new( tags, - &Settings::load(&st.db).await?.get_dietary_tags(), + &service::settings::load(&st.db).await?.get_dietary_tags(), )?), None => None, }; @@ -684,7 +690,7 @@ async fn update_profile( let tags = match &req.tags { Some(tags) => Some(DietaryTags::try_new( tags, - &Settings::load(&st.db).await?.get_dietary_tags(), + &service::settings::load(&st.db).await?.get_dietary_tags(), )?), None => None, }; @@ -764,7 +770,9 @@ async fn booking_responses( /// live on every call, so a serving time corrected today moves the deadline of /// menus already published for it. async fn meal_cutoff(db: &Database) -> Result { - Ok(MealCutoff::from_settings(&Settings::load(db).await?)) + Ok(MealCutoff::from_settings( + &service::settings::load(db).await?, + )) } /// Whose seat is this? A student books only for themselves; a parent only for diff --git a/src/web/notes.rs b/src/web/notes.rs index 74e890c..9c41d24 100644 --- a/src/web/notes.rs +++ b/src/web/notes.rs @@ -12,8 +12,8 @@ use utoipa_axum::routes; use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle}; use crate::domain::note_file::{FileContentType, FileName, NoteFile, NoteFileId}; -use crate::domain::settings::Settings; use crate::error::{AppError, ErrorResponse}; +use crate::service; use crate::state::AppState; use super::{CurrentUser, Page, PageParams, UploadFileForm, blob_path, read_upload, remove_blob}; @@ -89,7 +89,7 @@ async fn create( ) -> Result<(StatusCode, Json), AppError> { let title = NoteTitle::try_new(&req.title)?; let content = NoteContent::try_new(&req.content.unwrap_or_default())?; - let note = Note::create(user.get_id(), title, content, &st.db).await?; + let note = service::note::create(&st.db, user.get_id(), title, content).await?; Ok((StatusCode::CREATED, Json(NoteResponse::new(¬e)))) } @@ -114,7 +114,7 @@ async fn list( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let (notes, total) = Note::list_for(user.get_id(), limit, offset, &st.db).await?; + let (notes, total) = service::note::list_for(&st.db, user.get_id(), limit, offset).await?; let items = notes.iter().map(NoteResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -137,7 +137,7 @@ async fn get_one( CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result, AppError> { - let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) + let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id()) .await? .ok_or(AppError::NotFound)?; Ok(Json(NoteResponse::new(¬e))) @@ -165,7 +165,7 @@ async fn update( Path(id): Path, Json(req): Json, ) -> Result, AppError> { - let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) + let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id()) .await? .ok_or(AppError::NotFound)?; @@ -180,7 +180,7 @@ async fn update( .map(NoteContent::try_new) .transpose()?; - let updated = note.update(title, content, &st.db).await?; + let updated = service::note::update(&st.db, note, title, content).await?; Ok(Json(NoteResponse::new(&updated))) } @@ -202,14 +202,14 @@ async fn delete_one( CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result { - let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) + let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id()) .await? .ok_or(AppError::NotFound)?; // Rows go first (the note delete cascades them), blobs after: a crash in // between strands at worst an unreachable blob, never a row whose blob is // already gone. The files to unlink come from the delete itself, not a // pre-read list — an upload that landed in between is in the cascade too. - let (_, files) = note.delete(&st.db).await?; + let (_, files) = service::note::delete(&st.db, note).await?; for file in &files { remove_blob(&st.files_path, file.get_id().key()).await; } @@ -269,12 +269,12 @@ async fn upload_file( Path(id): Path, mut multipart: Multipart, ) -> Result<(StatusCode, Json), AppError> { - let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) + let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id()) .await? .ok_or(AppError::NotFound)?; // The 10-file cap is enforced inside `NoteFile::insert` (count and create // under one lock) — checking it here too would just race. - let limit = Settings::load(&st.db).await?.get_max_file_bytes(); + let limit = service::settings::load(&st.db).await?.get_max_file_bytes(); let upload = read_upload(&mut multipart, limit).await?; let name = FileName::try_new(&upload.name.unwrap_or_default())?; @@ -319,7 +319,7 @@ async fn list_files( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) + let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id()) .await? .ok_or(AppError::NotFound)?; let (files, total) = NoteFile::list_for(note.get_id(), limit, offset, &st.db).await?; @@ -349,7 +349,7 @@ async fn download_file( CurrentUser(user): CurrentUser, Path((id, file_id)): Path<(String, String)>, ) -> Result { - let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) + let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id()) .await? .ok_or(AppError::NotFound)?; let file = NoteFile::read_for(&NoteFileId::from_key(&file_id), note.get_id(), &st.db) @@ -402,7 +402,7 @@ async fn delete_file( CurrentUser(user): CurrentUser, Path((id, file_id)): Path<(String, String)>, ) -> Result { - let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) + let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id()) .await? .ok_or(AppError::NotFound)?; let file = NoteFile::read_for(&NoteFileId::from_key(&file_id), note.get_id(), &st.db) diff --git a/src/web/sessions.rs b/src/web/sessions.rs index 3e5d50c..270bd0a 100644 --- a/src/web/sessions.rs +++ b/src/web/sessions.rs @@ -17,10 +17,10 @@ use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic use crate::domain::enrollment::Enrollment; use crate::domain::role::Role; use crate::domain::session_attendance::SessionAttendance; -use crate::domain::settings::Settings; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::service; use crate::state::AppState; use super::courses::{can_manage_course, can_view_course}; @@ -320,7 +320,7 @@ async fn mark_roll_call( } course.require_open(&st.db).await?; - let school = Settings::load(&st.db).await?; + let school = service::settings::load(&st.db).await?; let status = AttendanceStatus::try_new(&req.status, school.get_attendance_statuses())?; let target = UserId::from_key(&req.user_id); diff --git a/src/web/settings.rs b/src/web/settings.rs index f71f766..e30e797 100644 --- a/src/web/settings.rs +++ b/src/web/settings.rs @@ -5,15 +5,9 @@ use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; -use surrealdb::types::RecordId; - -use crate::constant::CAS_UPDATE_RETRIES; -use crate::database::Database; -use crate::db::cap; -use crate::domain::exam_result::kind_ref; -use crate::domain::menu::slot_ref; -use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, SETTINGS_LOCK, Settings}; +use crate::domain::settings::Settings; use crate::error::{AppError, ErrorResponse}; +use crate::service; use crate::state::AppState; use super::{CurrentUser, RequireManager, set_or_clear}; @@ -227,7 +221,7 @@ async fn get_settings( State(st): State, CurrentUser(_user): CurrentUser, ) -> Result, AppError> { - let settings = Settings::load(&st.db).await?; + let settings = service::settings::load(&st.db).await?; Ok(Json(SettingsResponse::new(&settings))) } @@ -268,536 +262,47 @@ async fn update_settings( RequireManager(_user): RequireManager, Json(req): Json, ) -> Result, AppError> { - Ok(Json(SettingsResponse::new(&apply(&req, &st.db).await?))) -} - -/// The whole edit — snapshot, merge, retire, save — as one operation, so the -/// tests can drive it the way two managers do. Split out of the handler for -/// nothing else. -async fn apply(req: &UpdateSettings, db: &Database) -> Result { - // One settings edit at a time: the removals below are decided against the - // snapshot this loop loads and written *before* the save that justifies - // them, and no per-name bookkeeping can make that pair survive a rival's - // pair interleaving with it (see `SETTINGS_LOCK`). - let _guard = SETTINGS_LOCK.lock().await; - // Merge over a snapshot, then save only while the row still matches it — - // otherwise a concurrent PATCH of a *different* field would be silently - // reverted by whichever whole-row write lands second. A refused save - // reloads and re-merges, so both edits land. - for _ in 0..CAS_UPDATE_RETRIES { - let current = Settings::load(db).await?; - - let exam_kinds = match &req.exam_kinds { - Some(kinds) => kinds + // Wire → workflow mapping, nothing more. The lists are deliberately not + // validated here: that happens inside the service, in the workflow's own + // order, and a stored meal-slot name skips the URL-charset rule — a + // decision only the locked edit can make (`MealSlotDef::try_kept`). + let patch = service::settings::SettingsPatch { + exam_kinds: req.exam_kinds.as_ref().map(|kinds| { + kinds .iter() - .map(|kind| ExamKindDef::try_new(&kind.name, kind.weight)) - .collect::, _>>()?, - None => current.get_exam_kinds().to_vec(), - }; - let was_slots = slot_names(¤t.get_meal_slots()); - let meal_slots = match &req.meal_slots { - Some(slots) => slots + .map(|kind| service::settings::ExamKindInput { + name: kind.name.clone(), + weight: kind.weight, + }) + .collect() + }), + attendance_statuses: req.attendance_statuses.clone(), + grade_bands: req.grade_bands.as_ref().map(|bands| { + bands .iter() - .map(|slot| { - // A name the row already carries is validated as a kept one: - // the charset rule is younger than the stored lists, and - // re-validating one under it would leave a school unable to - // edit the rest of its slots at all (`MealSlotDef::try_kept`). - if was_slots.iter().any(|kept| kept == slot.name.trim()) { - MealSlotDef::try_kept(&slot.name, slot.serving_minute) - } else { - MealSlotDef::try_new(&slot.name, slot.serving_minute) - } + .map(|band| service::settings::GradeBandInput { + min: band.min, + label: band.label.clone(), }) - .collect::, _>>()?, - None => current.get_meal_slots(), - }; - let attendance_statuses = req - .attendance_statuses - .clone() - .unwrap_or_else(|| current.get_attendance_statuses().to_vec()); - let grade_bands = match &req.grade_bands { - Some(bands) => bands + .collect() + }), + max_file_bytes: req.max_file_bytes, + chatbot_history_turns: req.chatbot_history_turns, + max_chatbot_threads: req.max_chatbot_threads, + max_chatbot_message_len: req.max_chatbot_message_len, + meal_slots: req.meal_slots.as_ref().map(|slots| { + slots .iter() - .map(|band| GradeBand::try_new(band.min, &band.label)) - .collect::, _>>()?, - None => current.get_grade_bands().to_vec(), - }; - // The name lists as they stand and as they would stand, for the removal - // guards below — a list edit is judged by which names it drops. - let was_kinds = kind_names(current.get_exam_kinds()); - let now_kinds = kind_names(&exam_kinds); - let now_slots = slot_names(&meal_slots); - - // Merge over the snapshot's resolved values: an omitted field keeps - // whatever the row (or the default behind an unset field) reads as. - let mut params = current.params(); - params.exam_kinds = exam_kinds; - params.attendance_statuses = attendance_statuses; - params.grade_bands = grade_bands; - params.max_file_bytes = req.max_file_bytes.unwrap_or(params.max_file_bytes); - params.chatbot_history_turns = req - .chatbot_history_turns - .unwrap_or(params.chatbot_history_turns); - params.max_chatbot_threads = req - .max_chatbot_threads - .unwrap_or(params.max_chatbot_threads); - params.max_chatbot_message_len = req - .max_chatbot_message_len - .unwrap_or(params.max_chatbot_message_len); - params.meal_slots = meal_slots; - params.dietary_tags = req - .dietary_tags - .clone() - .unwrap_or_else(|| current.get_dietary_tags()); - // Double option: absent keeps the knob, `null` clears it (no cutoff). - params.meal_cancel_cutoff_minutes = req - .meal_cancel_cutoff_minutes - .unwrap_or(params.meal_cancel_cutoff_minutes); - - let settings = Settings::try_new(params)?; - - // The removal guards. A name leaves a list by being *retired* on its - // reference counter — one conditional write on one record, which lands - // only while nothing references the name and refuses every claim from - // that instant on. That is the whole guard: the check and the removal - // used to be a cross-table count and a save held together by a - // process-wide lock that was released around the round trip between them. - // - // Retired before the save, never after: the other order leaves a window - // in which a mark lands under a kind the settings no longer list. A save - // that then does not land undoes them (`restore`) before the next try. - // - // Only a write that actually *flipped* a bit is recorded for that undo. - // Retirement is idempotent, so two PATCHes dropping the same kind are - // both told "retired" — and the one whose save then loses the row's CAS - // used to un-retire the winner's kind, leaving it off the list with its - // counter in service: gradable again, its count then non-zero, and so - // impossible to remove ever after. - let mut undo: Vec = Vec::new(); - let mut refused = None; - for gone in missing(&was_kinds, &now_kinds) { - let counter = kind_ref(&gone); - match cap::retire_name(&counter, db).await? { - cap::Switched::Flipped => undo.push(Undo::Retired(counter)), - cap::Switched::Unchanged => {} - cap::Switched::InUse => { - refused = Some(AppError::ConflictOwned(format!( - "exams of kind '{gone}' are already graded — the kind cannot be removed" - ))); - break; - } - } - } - // Same shape for meal slots: a slot a menu was already published for - // cannot leave the list — the menu snapshotted the name as text, and a - // slot no longer offered would leave that menu unreachable from the - // school's own list. - if refused.is_none() { - for gone in missing(&was_slots, &now_slots) { - let counter = slot_ref(&gone); - match cap::retire_name(&counter, db).await? { - cap::Switched::Flipped => undo.push(Undo::Retired(counter)), - cap::Switched::Unchanged => {} - cap::Switched::InUse => { - refused = Some(AppError::ConflictOwned(format!( - "menus are already published for the '{gone}' slot — it cannot be removed" - ))); - break; - } - } - } - } - if let Some(refused) = refused { - restore(&undo, db).await?; - return Err(refused); - } - // A name re-entering a list is back in service: its counter still - // carries the retirement from the edit that dropped it, and a mark (or - // a menu) under a kind the school offers again must not be refused. - // Recorded for the same undo as the retirements — a re-add whose save - // does not land leaves a name off the list that grades happily. - for back in missing(&now_kinds, &was_kinds) { - if let cap::Switched::Flipped = cap::unretire_name(&kind_ref(&back), db).await? { - undo.push(Undo::Unretired(kind_ref(&back))); - } - } - for back in missing(&now_slots, &was_slots) { - if let cap::Switched::Flipped = cap::unretire_name(&slot_ref(&back), db).await? { - undo.push(Undo::Unretired(slot_ref(&back))); - } - } - - match settings.save_if_unchanged(¤t, db).await { - Ok(Some(saved)) => return Ok(saved), - // The row moved under the snapshot these guards were judged against: - // put the names back and re-merge, or the next attempt would decide - // against a list nobody asked for. - Ok(None) => restore(&undo, db).await?, - Err(err) => { - restore(&undo, db).await?; - return Err(err); - } - } - } - Err(AppError::Conflict( - "the settings kept changing underneath this update — try again", - )) -} - -fn kind_names(kinds: &[ExamKindDef]) -> Vec { - kinds - .iter() - .map(|kind| kind.get_name().to_string()) - .collect() -} - -fn slot_names(slots: &[MealSlotDef]) -> Vec { - slots - .iter() - .map(|slot| slot.get_name().to_string()) - .collect() -} - -/// The names `before` carries that `after` does not — a list edit's removals, -/// or its additions with the arguments swapped. -fn missing(before: &[String], after: &[String]) -> Vec { - before - .iter() - .filter(|name| !after.contains(name)) - .cloned() - .collect() -} - -/// One `retired` bit this attempt moved, and which way — what `restore` needs -/// to put it back. Only bits this attempt actually *flipped* are listed: a -/// write that changed nothing has nothing to take back, and taking it back -/// would undo the concurrent edit that really did move it. -enum Undo { - /// Retired for a removal; put it back in service. - Retired(RecordId), - /// Put back in service for a re-add; retire it again. - Unretired(RecordId), -} - -/// Undo every bit this attempt moved: the edit that justified them did not -/// land, so the lists the school offers are still the ones it started with. -async fn restore(undo: &[Undo], db: &Database) -> Result<(), AppError> { - for step in undo { - match step { - Undo::Retired(name) => { - cap::unretire_name(name, db).await?; - } - // A re-retirement can be refused: a mark (or a menu) landed under - // the name during the window it was in service. Refusing to undo is - // then the honest answer — the reference is real, and retiring over - // it would make the row's kind ungradable while nothing lists it. - // The name is left in service, matching the list this attempt is - // about to re-read. - Undo::Unretired(name) => { - cap::retire_name(name, db).await?; - } - } - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::database::init_mem; - - /// The `retired` bit as the store holds it, `None` when no counter row was - /// ever written — read back, never inferred from a return value. - async fn bit(db: &Database, counter: RecordId) -> Option { - let mut result = db - .query("SELECT VALUE retired FROM $id") - .bind(("id", counter)) - .await - .unwrap() - .check() - .unwrap(); - result.take::>(0).unwrap().first().copied() - } - - /// Two managers drop the same exam kind at once; one of them loses the - /// row's compare-and-set and rolls its attempt back. The winner's - /// retirement must survive that rollback — undone, the kind is off the list - /// with a counter that still grades, and the first mark to land makes it - /// unremovable for good. - /// - /// The loser's half is what runs here: a retirement that changed nothing - /// records no undo, so `restore` has nothing to take back. - #[tokio::test] - async fn the_loser_of_a_settings_race_cannot_un_retire_the_winner_s_kind() { - let db = init_mem().await.unwrap(); - let counter = kind_ref("midterm"); - - // The winner's PATCH retires the kind. - assert!(matches!( - cap::retire_name(&counter, &db).await.unwrap(), - cap::Switched::Flipped - )); - - // The loser's PATCH decides the same removal against the same snapshot, - // then its save is refused. - let mut undo = Vec::new(); - if let cap::Switched::Flipped = cap::retire_name(&counter, &db).await.unwrap() { - undo.push(Undo::Retired(counter.clone())); - } - assert!(undo.is_empty(), "a no-op retirement records no undo"); - restore(&undo, &db).await.unwrap(); - - assert_eq!( - bit(&db, counter).await, - Some(true), - "the winner's retirement must outlive the loser's rollback" - ); - } - - /// The mirror hole: a re-*added* name is put back in service before the - /// save, so a save that does not land owes a re-retirement. Without it the - /// name is off the stored list with a counter that grades happily. - #[tokio::test] - async fn a_rollback_re_retires_a_name_this_attempt_put_back_in_service() { - let db = init_mem().await.unwrap(); - let counter = slot_ref("lunch"); - cap::retire_name(&counter, &db).await.unwrap(); - - // The attempt re-adds the slot, then its save is refused. - let mut undo = Vec::new(); - if let cap::Switched::Flipped = cap::unretire_name(&counter, &db).await.unwrap() { - undo.push(Undo::Unretired(counter.clone())); - } - assert_eq!(undo.len(), 1, "a real un-retirement is undoable"); - restore(&undo, &db).await.unwrap(); - - assert_eq!( - bit(&db, counter).await, - Some(true), - "a re-add that never landed must leave the slot retired" - ); - } - - /// ...unless a menu was published in the window the slot was back in - /// service. The reference is real, so the re-retirement is refused and the - /// slot stays usable — the honest end of the same rule, not a silent - /// overwrite of a live reference. - #[tokio::test] - async fn a_rollback_leaves_a_name_that_gained_a_reference_in_service() { - let db = init_mem().await.unwrap(); - let counter = slot_ref("lunch"); - cap::retire_name(&counter, &db).await.unwrap(); - cap::unretire_name(&counter, &db).await.unwrap(); - db.query("UPDATE $id SET count = 1") - .bind(("id", counter.clone())) - .await - .unwrap() - .check() - .unwrap(); - - restore(&[Undo::Unretired(counter.clone())], &db) - .await - .unwrap(); - - assert_eq!(bit(&db, counter).await, Some(false)); - } - - // --- the whole edit, driven the way two managers drive it ------------- - - /// A `PATCH` body, built the way the router builds one. - fn patch(body: serde_json::Value) -> UpdateSettings { - serde_json::from_value(body).unwrap() - } - - /// A `meal_slots`/`exam_kinds` list as the DTO carries it. - fn kinds(names: &[&str]) -> serde_json::Value { - names - .iter() - .map(|name| serde_json::json!({ "name": name, "weight": 1 })) - .collect() - } - - fn slots(names: &[&str]) -> serde_json::Value { - names - .iter() - .map(|name| serde_json::json!({ "name": name, "serving_minute": null })) - .collect() - } - - /// The lists as the store holds them. - async fn stored(db: &Database) -> (Vec, Vec) { - let settings = Settings::load(db).await.unwrap(); - ( - kind_names(settings.get_exam_kinds()), - slot_names(&settings.get_meal_slots()), - ) - } - - /// The whole invariant, over the reachable half of the race: two managers - /// drop the same exam kind at once, both edits go through the real path, - /// and when both have returned the counter's `retired` bit must agree with - /// the list the store actually holds. - /// - /// One of the two decides the removal, retires the kind and saves; the - /// other cannot even see the old list, because the whole snapshot-retire- - /// save pair is serialized (`SETTINGS_LOCK`). Interleaved, the second - /// attempt would be told "already retired", record no undo, win the - /// compare-and-set, and leave the first attempt un-retiring the kind it had - /// legitimately removed — off the list and gradable. - #[tokio::test] - async fn two_edits_dropping_the_same_kind_leave_it_retired() { - let db = init_mem().await.unwrap(); - let without = patch(serde_json::json!({ - "exam_kinds": kinds(&["homework", "quiz", "final", "project", "oral"]), - })); - - let (a, b) = tokio::join!(apply(&without, &db), apply(&without, &db)); - a.unwrap(); - b.unwrap(); - - let (kinds, _) = stored(&db).await; - assert!( - !kinds.contains(&"midterm".to_string()), - "dropped from the list" - ); - assert_eq!( - bit(&db, kind_ref("midterm")).await, - Some(true), - "a kind the stored list no longer offers must not grade" - ); - } - - /// The property those two outcomes rest on, asserted on its own because a - /// `join!` cannot be made to schedule the losing order: the edit is a pair - /// of writes — retire the dropped names, then commit the list — and no - /// rival's pair may run between them. - /// - /// Retirement is idempotent, so an interleaved rival is told "already - /// retired", records no rollback, wins the compare-and-set, and leaves the - /// attempt that really flipped the bit un-retiring a kind the stored list - /// no longer offers: gradable again, and unremovable for good once a mark - /// lands. Holding the lock stands in for a rival mid-pair here — nothing - /// the other edit does may be visible until the pair completes. - #[tokio::test] - async fn a_rival_edit_cannot_run_between_a_retirement_and_its_save() { - let db = init_mem().await.unwrap(); - let without = patch(serde_json::json!({ - "exam_kinds": kinds(&["homework", "quiz", "final", "project", "oral"]), - })); - - let held = SETTINGS_LOCK.lock().await; - let rival = tokio::spawn({ - let db = db.clone(); - async move { apply(&without, &db).await.map(|_| ()) } - }); - tokio::time::sleep(std::time::Duration::from_millis(200)).await; - - assert_eq!( - bit(&db, kind_ref("midterm")).await, - None, - "a rival's pair must not have started, let alone half-landed" - ); - assert!(stored(&db).await.0.contains(&"midterm".to_string())); - - drop(held); - rival.await.unwrap().unwrap(); - assert_eq!(bit(&db, kind_ref("midterm")).await, Some(true)); - assert!(!stored(&db).await.0.contains(&"midterm".to_string())); - } - - /// The mirror: two managers put the same kind *back* at once. The attempt - /// that loses must not re-retire a name the winner's stored list carries — - /// a listed kind that refuses every grade. - #[tokio::test] - async fn two_edits_re_adding_the_same_kind_leave_it_in_service() { - let db = init_mem().await.unwrap(); - let without = patch(serde_json::json!({ - "exam_kinds": kinds(&["homework", "quiz", "final", "project", "oral"]), - })); - apply(&without, &db).await.unwrap(); - let with = patch(serde_json::json!({ - "exam_kinds": kinds(&["homework", "quiz", "midterm", "final", "project", "oral"]), - })); - - let (a, b) = tokio::join!(apply(&with, &db), apply(&with, &db)); - a.unwrap(); - b.unwrap(); - - let (kinds, _) = stored(&db).await; - assert!(kinds.contains(&"midterm".to_string()), "back on the list"); - assert_eq!( - bit(&db, kind_ref("midterm")).await, - Some(false), - "a kind the stored list offers must grade" - ); - } - - /// The same pair over meal slots, which retire on their own counters. - #[tokio::test] - async fn two_edits_dropping_the_same_slot_leave_it_retired() { - let db = init_mem().await.unwrap(); - let without = patch(serde_json::json!({ - "meal_slots": slots(&["breakfast", "snack"]), - })); - - let (a, b) = tokio::join!(apply(&without, &db), apply(&without, &db)); - a.unwrap(); - b.unwrap(); - - let (_, stored_slots) = stored(&db).await; - assert!(!stored_slots.contains(&"lunch".to_string())); - assert_eq!(bit(&db, slot_ref("lunch")).await, Some(true)); - } - - // --- the stale slot name that wedged the whole list ------------------- - - /// A school that stored `a/b` before the URL-safety rule existed. - async fn a_school_with_a_stale_slot(db: &Database) { - let mut params = Settings::defaults().params(); - params.meal_slots = vec![ - MealSlotDef::try_kept("a/b", None).unwrap(), - MealSlotDef::try_new("lunch", None).unwrap(), - ]; - Settings::try_new(params).unwrap().save(db).await.unwrap(); - } - - /// The wedge: re-sending a stored name is the only way to *keep* it, and - /// dropping it 409s once a menu references it — so validating it under the - /// younger rule locks the school out of its own `meal_slots` forever. A - /// stored name is submittable; a new one with the same characters is not. - #[tokio::test] - async fn a_stored_slot_name_stays_submittable_but_a_new_one_does_not() { - let db = init_mem().await.unwrap(); - a_school_with_a_stale_slot(&db).await; - - let edit = patch(serde_json::json!({ - "meal_slots": slots(&["a/b", "lunch", "dinner"]), - })); - apply(&edit, &db).await.unwrap(); - let (_, stored_slots) = stored(&db).await; - assert_eq!(stored_slots, ["a/b", "lunch", "dinner"]); - - let fresh = patch(serde_json::json!({ - "meal_slots": slots(&["a/b", "lunch", "c/d"]), - })); - assert!( - apply(&fresh, &db).await.is_err(), - "a name no school ever stored is still refused" - ); - } - - /// And an edit that never mentions `meal_slots` still carries the list - /// over unvalidated — the behaviour the wedge report leaned on. - #[tokio::test] - async fn an_unrelated_edit_carries_a_stale_slot_name_over() { - let db = init_mem().await.unwrap(); - a_school_with_a_stale_slot(&db).await; - - let elsewhere = patch(serde_json::json!({ "max_file_bytes": 2048 })); - let saved = apply(&elsewhere, &db).await.unwrap(); - - assert_eq!(saved.get_max_file_bytes(), 2048); - assert_eq!(slot_names(&saved.get_meal_slots()), ["a/b", "lunch"]); - } + .map(|slot| service::settings::MealSlotInput { + name: slot.name.clone(), + serving_minute: slot.serving_minute, + }) + .collect() + }), + dietary_tags: req.dietary_tags.clone(), + meal_cancel_cutoff_minutes: req.meal_cancel_cutoff_minutes, + }; + Ok(Json(SettingsResponse::new( + &service::settings::apply(&st.db, &patch).await?, + ))) } diff --git a/src/web/tenant_state.rs b/src/web/tenant_state.rs index bcbf6e2..9ba6136 100644 --- a/src/web/tenant_state.rs +++ b/src/web/tenant_state.rs @@ -181,8 +181,8 @@ mod tests { use tower::ServiceExt; use crate::database::init_mem_tenants; + use crate::db::session; use crate::domain::builder::{Builder, BuilderSession}; - use crate::domain::session::Session; use crate::domain::user::{Password, User, Username}; use crate::tenant::DEMO_SLUG; use crate::web::{CurrentUser, RequireBuilder}; @@ -215,7 +215,7 @@ mod tests { ) .await .unwrap(); - let session = Session::create(user.get_id(), &school).await.unwrap(); + let session = session::create(&school, user.get_id()).await.unwrap(); let school_cookie = format!("session={DEMO_SLUG}.{}", session.token().as_str()); Builder::ensure( diff --git a/tests/integration.rs b/tests/integration.rs index 2df55a3..07cee12 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -15,6 +15,7 @@ use hezarfen_backend::constant::{ BANK_VISIBILITY_SCHOOL, MAX_BOARD_STROKES, MAX_BOARDS_PER_CREATOR, MAX_COURSE_NOTE_FILES, MAX_EPOCH_STROKES, MAX_FEE_PLAN_ASSIGN_STUDENTS, }; +use hezarfen_backend::db::session; use hezarfen_backend::domain::board::{Board, BoardId}; use hezarfen_backend::domain::board_stroke::{BoardStroke, BoardStrokeId}; use hezarfen_backend::domain::chatbot_message::ChatbotMessage; @@ -25,7 +26,6 @@ use hezarfen_backend::domain::course_note_file::CourseNoteFileId; use hezarfen_backend::domain::exam::ExamId; use hezarfen_backend::domain::exam_attempt::ExamAttempt; use hezarfen_backend::domain::rag_output::RagOutput; -use hezarfen_backend::domain::session::Session; use hezarfen_backend::domain::timestamp::Timestamp; use hezarfen_backend::domain::user::{Password, User, UserId, Username}; use hezarfen_backend::module::ModuleSet; @@ -5932,7 +5932,7 @@ async fn login_purges_expired_sessions() { .check() .unwrap(); assert!( - Session::find_by_token("expired-token", &db) + session::find_by_token(&db, "expired-token") .await .unwrap() .is_some() @@ -5941,7 +5941,7 @@ async fn login_purges_expired_sessions() { // A later successful login sweeps expired rows... login(&app, "veli").await; assert!( - Session::find_by_token("expired-token", &db) + session::find_by_token(&db, "expired-token") .await .unwrap() .is_none(), @@ -5976,7 +5976,7 @@ async fn expired_session_is_unauthorized_before_any_purge() { // Row exists, but the clock says no. assert!( - Session::find_by_token("stale-token", &db) + session::find_by_token(&db, "stale-token") .await .unwrap() .is_some() diff --git a/tests/regress_attendance.rs b/tests/regress_attendance.rs index 851e898..5aec836 100644 --- a/tests/regress_attendance.rs +++ b/tests/regress_attendance.rs @@ -13,11 +13,11 @@ mod common; use axum::http::StatusCode; use common::{app_and_db, create_course, create_session, enroll, login, login_as, me_id, send}; use hezarfen_backend::database::Database; +use hezarfen_backend::db::settings; use hezarfen_backend::domain::attendance::{Attendance, AttendanceStatus}; use hezarfen_backend::domain::course_session::{CourseSession, CourseSessionId}; use hezarfen_backend::domain::event::EventId; use hezarfen_backend::domain::session_attendance::SessionAttendance; -use hezarfen_backend::domain::settings::Settings; use hezarfen_backend::domain::timestamp::Timestamp; use hezarfen_backend::domain::user::UserId; use hezarfen_backend::error::AppError; @@ -223,7 +223,7 @@ async fn a_mark_against_a_deleted_session_is_refused_and_stores_nothing() { ); // Then the mark arrives, still believing in its snapshot. - let school = Settings::load(&db).await.unwrap(); + let school = settings::load(&db).await.unwrap(); let status = AttendanceStatus::try_new("present", school.get_attendance_statuses()).unwrap(); let marked = SessionAttendance::mark( &snapshot, @@ -392,7 +392,7 @@ async fn an_event_mark_writes_its_event_and_is_refused_once_it_is_gone() { ); // And the mark that arrives after it is refused rather than stored. - let school = Settings::load(&db).await.unwrap(); + let school = settings::load(&db).await.unwrap(); let status = AttendanceStatus::try_new("present", school.get_attendance_statuses()).unwrap(); let marked = Attendance::mark(&EventId::from_key(&event), &ali_ref, status, &hoca_ref, &db).await; diff --git a/tests/regress_roles.rs b/tests/regress_roles.rs index ab02bb9..8d63e56 100644 --- a/tests/regress_roles.rs +++ b/tests/regress_roles.rs @@ -688,7 +688,7 @@ async fn deleting_an_event_takes_its_children_with_it() { /// The note half of the same defect: the attachment rows and the note commit /// together, so an upload can no longer leave a `note_file` pointing at a note -/// that is gone (its *blob* goes too: `Note::delete` returns the rows it +/// that is gone (its *blob* goes too: `db::note::delete` returns the rows it /// removed and the handler unlinks exactly those). #[tokio::test] async fn deleting_a_note_takes_its_attachment_rows_with_it() {