forge
Explore
Log in

Don't you dare go Hollow

Split note/session/settings into domain/db/service layers

Browse files at this commit

efea304a9ccf84ed46e426a7c196baddd1e36e12Ahmet Kaan GümüşParent: 3763468
  • chore
    • split note/session/settings into domain/db/service layers
Show full message
🧹 chore: split note/session/settings into domain/db/service layers

Pilot wave of the three-layer split. All query execution for the three
domains now lives in src/db/{note,session,settings}.rs as free fns taking
db first; web handlers call service::<x>::* only; domain keeps pure types.

- service/settings.rs gains the PATCH workflow (apply) and SETTINGS_LOCK —
  it spans a multi-call pair (retire names, CAS save, restore), so it is a
  service lock, not a db lock. The service takes its own input records
  (SettingsPatch/*Input) so wire DTOs stay in web and list validation keeps
  its original order, including the try_kept grandfathering that needs the
  stored list.
- Note/Session/Settings fields the db layer mints or CAS-binds become
  pub(crate); Settings::record_id becomes pub(crate).
- Unit tests rode with their fns: note delete cascade → db/note, session
  purge → db/session, settings load/save/CAS → db/settings, the whole
  settings edit workflow suite → service/settings.
- Doc links re-pointed (user, class_blueprint, bank_question, exam,
  note_file, tests/regress_roles); NoteId::generate's stale
  'Note::list_for_user' link now names db::note::list_for.
- Known residual for a later wave: web/notes.rs:411 file.delete() is
  note_file-domain persistence (note_file splits in C3).

38 changed files +1479 -1153

src/db/mod.rsmodified+3 -0
@@ -2,4 +2,7 @@
2 2
3 pub mod cap;3 pub mod cap;
4 pub mod field_update;4 pub mod field_update;
5+pub mod note;
5 pub mod page;6 pub mod page;
7+pub mod session;
8+pub mod settings;
src/db/note.rsadded+181 -0
@@ -0,0 +1,181 @@
1+//! The `note` table: one user's rows, listed newest first, deleted together
2+//! with their attachment rows.
3+
4+use surrealdb::types::SurrealValue;
5+
6+use crate::database::Database;
7+use crate::db::field_update::FieldUpdate;
8+use crate::db::page::PagedList;
9+use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle};
10+use crate::domain::note_file::NoteFile;
11+use crate::domain::user::UserId;
12+use crate::error::AppError;
13+
14+/// What [`delete`]'s transaction removed: the note row (empty if it had
15+/// already vanished) and every attachment row the cascade took with it — the
16+/// only set whose blobs are safe to unlink.
17+#[derive(Debug, SurrealValue)]
18+struct DeleteOutcome {
19+ note: Vec<Note>,
20+ files: Vec<NoteFile>,
21+}
22+
23+pub async fn create(
24+ db: &Database,
25+ owner: &UserId,
26+ title: NoteTitle,
27+ content: NoteContent,
28+) -> Result<Note, AppError> {
29+ let note = Note {
30+ id: NoteId::generate(),
31+ user: owner.clone(),
32+ title,
33+ content,
34+ };
35+ let created: Option<Note> = db.create(note.id.record()).content(note).await?;
36+ created.ok_or_else(|| AppError::Internal("failed to create note".into()))
37+}
38+
39+/// Read a note only if it belongs to `owner`.
40+pub async fn read_owned(
41+ db: &Database,
42+ id: &NoteId,
43+ owner: &UserId,
44+) -> Result<Option<Note>, AppError> {
45+ let note: Option<Note> = db.select(id.record()).await?;
46+ Ok(note.filter(|note| &note.user == owner))
47+}
48+
49+pub async fn list_for(
50+ db: &Database,
51+ owner: &UserId,
52+ limit: Option<i64>,
53+ offset: i64,
54+) -> Result<(Vec<Note>, i64), AppError> {
55+ PagedList::new("note WHERE user = $usr", "ORDER BY id DESC")
56+ .bind("usr", owner.record())
57+ .run(limit, offset, db)
58+ .await
59+}
60+
61+/// Request-scoped: no lock spans the handler's read and this write, so an
62+/// omitted field (`None`) is not written at all. Passing the snapshot's
63+/// value back instead would revert a concurrent edit of that field —
64+/// scoping the `SET` alone does not prevent that, the values have to come
65+/// from the request. Neither column is nullable, so plain `Option` per
66+/// field says everything there is to say.
67+pub async fn update(
68+ db: &Database,
69+ note: Note,
70+ title: Option<NoteTitle>,
71+ content: Option<NoteContent>,
72+) -> Result<Note, AppError> {
73+ FieldUpdate::new(note.id.record())
74+ .set("title", title)
75+ .set("content", content)
76+ .run::<Note>(db)
77+ .await
78+}
79+
80+/// Delete the note and cascade-remove its attachment rows, returning both:
81+/// the note, and the attachment rows this transaction actually removed.
82+/// Blob files on disk are the web layer's to remove, but only for *these*
83+/// rows — a row uploaded after the caller listed the note's files is
84+/// deleted here too, and a pre-read snapshot would strand its blob. A crash
85+/// between commit and unlink leaves at worst an unreachable blob, never a
86+/// row pointing at nothing.
87+///
88+/// Children first, in one transaction, the way
89+/// [`crate::domain::course::Course::delete`] does it: as two queries, an
90+/// upload that committed in between kept its row while the note went, and
91+/// nothing could ever list or delete it again.
92+pub async fn delete(db: &Database, note: Note) -> Result<(Note, Vec<NoteFile>), AppError> {
93+ let mut result = db
94+ .query(
95+ "BEGIN TRANSACTION;
96+ LET $files = (DELETE note_file WHERE note = $note RETURN BEFORE);
97+ LET $gone = (DELETE $note RETURN BEFORE);
98+ RETURN { note: $gone, files: $files };
99+ COMMIT TRANSACTION;",
100+ )
101+ .bind(("note", note.id.record()))
102+ .await?
103+ .check()?;
104+ // BEGIN is slot 0, the two LETs slots 1-2; the RETURN is slot 3.
105+ let outcome = result
106+ .take::<Vec<DeleteOutcome>>(3)?
107+ .into_iter()
108+ .next()
109+ .ok_or_else(|| AppError::Internal("failed to delete note".into()))?;
110+ let note = outcome.note.into_iter().next().ok_or(AppError::NotFound)?;
111+ Ok((note, outcome.files))
112+}
113+
114+#[cfg(test)]
115+mod tests {
116+ use super::*;
117+
118+ /// The blobs the handler unlinks are exactly the rows this transaction
119+ /// removed — including one uploaded after any pre-read snapshot would have
120+ /// been taken, which is the row whose blob used to leak.
121+ #[tokio::test]
122+ async fn delete_returns_the_attachment_rows_it_removed() {
123+ use crate::domain::note_file::{FileContentType, FileName};
124+
125+ let db = crate::database::init_mem().await.unwrap();
126+ let owner = crate::domain::user::UserId::generate();
127+ let note = create(
128+ &db,
129+ &owner,
130+ NoteTitle::try_new("a").unwrap(),
131+ NoteContent::try_new("body").unwrap(),
132+ )
133+ .await
134+ .unwrap();
135+ // What a handler snapshot would have seen...
136+ let early = NoteFile::new(
137+ note.get_id(),
138+ FileName::try_new("early.pdf").unwrap(),
139+ FileContentType::try_new("application/pdf").unwrap(),
140+ 3,
141+ )
142+ .insert(&db)
143+ .await
144+ .unwrap();
145+ let (snapshot, _) = NoteFile::list_for(note.get_id(), None, 0, &db)
146+ .await
147+ .unwrap();
148+ assert_eq!(snapshot.len(), 1);
149+ // ...and the upload that races in after it.
150+ let late = NoteFile::new(
151+ note.get_id(),
152+ FileName::try_new("late.pdf").unwrap(),
153+ FileContentType::try_new("application/pdf").unwrap(),
154+ 3,
155+ )
156+ .insert(&db)
157+ .await
158+ .unwrap();
159+
160+ let (gone, files) = delete(&db, note).await.unwrap();
161+ assert_eq!(gone.get_title().as_str(), "a");
162+ let mut keys: Vec<_> = files
163+ .iter()
164+ .map(|file| file.get_id().key().to_string())
165+ .collect();
166+ keys.sort();
167+ let mut want = vec![
168+ early.get_id().key().to_string(),
169+ late.get_id().key().to_string(),
170+ ];
171+ want.sort();
172+ assert_eq!(keys, want);
173+ assert!(
174+ NoteFile::list_for(gone.get_id(), None, 0, &db)
175+ .await
176+ .unwrap()
177+ .0
178+ .is_empty()
179+ );
180+ }
181+}
src/db/page.rsmodified+9 -8
@@ -138,7 +138,8 @@ fn total_of(count: Value) -> Result<i64, AppError> {
138 mod tests {138 mod tests {
139 use super::*;139 use super::*;
140 use crate::database;140 use crate::database;
141- use crate::domain::note::{Note, NoteContent, NoteTitle};141+ use crate::db::note;
142+ use crate::domain::note::{NoteContent, NoteTitle};
142 use crate::domain::user::UserId;143 use crate::domain::user::UserId;
143 use ulid::Ulid;144 use ulid::Ulid;
144 145
@@ -207,24 +208,24 @@ mod tests {
207 let db = database::init_mem().await.unwrap();208 let db = database::init_mem().await.unwrap();
208 let user = UserId::from_key(&Ulid::new().to_string());209 let user = UserId::from_key(&Ulid::new().to_string());
209 for i in 0..5 {210 for i in 0..5 {
210- Note::create(211+ note::create(
212+ &db,
211 &user,213 &user,
212 NoteTitle::try_new(&format!("n{i}")).unwrap(),214 NoteTitle::try_new(&format!("n{i}")).unwrap(),
213 NoteContent::try_new("x").unwrap(),215 NoteContent::try_new("x").unwrap(),
214- &db,
215 )216 )
216 .await217 .await
217 .unwrap();218 .unwrap();
218 }219 }
219 220
220 // Every page is `limit` long and `total` ignores the window.221 // Every page is `limit` long and `total` ignores the window.
221- let (page, total) = Note::list_for(&user, Some(2), 0, &db).await.unwrap();222+ let (page, total) = note::list_for(&db, &user, Some(2), 0).await.unwrap();
222 assert_eq!((page.len(), total), (2, 5));223 assert_eq!((page.len(), total), (2, 5));
223- let (tail, total) = Note::list_for(&user, Some(2), 4, &db).await.unwrap();224+ let (tail, total) = note::list_for(&db, &user, Some(2), 4).await.unwrap();
224 assert_eq!((tail.len(), total), (1, 5));225 assert_eq!((tail.len(), total), (1, 5));
225 // Offset past the end is an empty page, not an error.226 // Offset past the end is an empty page, not an error.
226 assert_eq!(227 assert_eq!(
227- Note::list_for(&user, Some(2), 9, &db)228+ note::list_for(&db, &user, Some(2), 9)
228 .await229 .await
229 .unwrap()230 .unwrap()
230 .0231 .0
@@ -232,9 +233,9 @@ mod tests {
232 0233 0
233 );234 );
234 // Unpaged, and unpaged-from-an-offset: the count still covers everything.235 // Unpaged, and unpaged-from-an-offset: the count still covers everything.
235- let (all, total) = Note::list_for(&user, None, 0, &db).await.unwrap();236+ let (all, total) = note::list_for(&db, &user, None, 0).await.unwrap();
236 assert_eq!((all.len(), total), (5, 5));237 assert_eq!((all.len(), total), (5, 5));
237- let (rest, total) = Note::list_for(&user, None, 3, &db).await.unwrap();238+ let (rest, total) = note::list_for(&db, &user, None, 3).await.unwrap();
238 assert_eq!((rest.len(), total), (2, 5));239 assert_eq!((rest.len(), total), (2, 5));
239 240
240 // The pages are consecutive slices of the unpaged list — page241 // The pages are consecutive slices of the unpaged list — page
src/db/session.rsadded+82 -0
@@ -0,0 +1,82 @@
1+//! The `session` table: opaque login tokens with an expiry, swept on login.
2+
3+use crate::constant::SESSION_DURATION_DAYS;
4+use crate::database::Database;
5+use crate::domain::session::{Session, SessionId, SessionToken};
6+use crate::domain::timestamp::Timestamp;
7+use crate::domain::user::UserId;
8+use crate::error::AppError;
9+
10+pub async fn create(db: &Database, user: &UserId) -> Result<Session, AppError> {
11+ let session = Session {
12+ id: SessionId::generate(),
13+ user: user.clone(),
14+ token: SessionToken::generate()?,
15+ expires_at: Timestamp::in_days(SESSION_DURATION_DAYS),
16+ };
17+ let created: Option<Session> = db.create(session.id.record()).content(session).await?;
18+ created.ok_or_else(|| AppError::Internal("failed to create session".into()))
19+}
20+
21+pub async fn find_by_token(db: &Database, token: &str) -> Result<Option<Session>, AppError> {
22+ let mut result = db
23+ .query("SELECT * FROM session WHERE token = $tok LIMIT 1")
24+ .bind(("tok", token.to_string()))
25+ .await?
26+ .check()?;
27+ Ok(result.take::<Vec<Session>>(0)?.into_iter().next())
28+}
29+
30+pub async fn delete_by_token(db: &Database, token: &str) -> Result<(), AppError> {
31+ db.query("DELETE session WHERE token = $tok")
32+ .bind(("tok", token.to_string()))
33+ .await?
34+ .check()?;
35+ Ok(())
36+}
37+
38+/// Revoke every session a user holds. The other half of a password reset:
39+/// the new credential means nothing while a cookie minted under the old one
40+/// still authenticates.
41+pub async fn delete_by_user(db: &Database, user: &UserId) -> Result<(), AppError> {
42+ db.query("DELETE session WHERE user = $usr")
43+ .bind(("usr", user.record()))
44+ .await?
45+ .check()?;
46+ Ok(())
47+}
48+
49+/// Delete every session whose expiry is in the past, returning how many were
50+/// removed. Expired sessions are already rejected at auth, but nothing else
51+/// deletes their rows — without this sweep the `session` table grows forever.
52+pub async fn purge_expired(db: &Database) -> Result<u64, AppError> {
53+ let now = Timestamp::now().as_millis();
54+ let mut result = db
55+ .query("DELETE session WHERE expires_at < $now RETURN BEFORE")
56+ .bind(("now", now))
57+ .await?
58+ .check()?;
59+ Ok(result.take::<Vec<Session>>(0)?.len() as u64)
60+}
61+
62+#[cfg(test)]
63+mod tests {
64+ use super::*;
65+
66+ #[tokio::test]
67+ async fn purge_expired_removes_only_past_sessions() {
68+ let db = crate::database::init_mem().await.unwrap();
69+ db.query(
70+ "CREATE session SET user = type::record('user', 'u'), token = 'past', expires_at = 1;
71+ CREATE session SET user = type::record('user', 'u'), token = 'future', expires_at = 99999999999999;",
72+ )
73+ .await
74+ .unwrap()
75+ .check()
76+ .unwrap();
77+
78+ assert_eq!(purge_expired(&db).await.unwrap(), 1);
79+ assert!(find_by_token(&db, "past").await.unwrap().is_none());
80+ assert!(find_by_token(&db, "future").await.unwrap().is_some());
81+ }
82+}
src/db/settings.rsadded+296 -0
@@ -0,0 +1,296 @@
1+//! The `settings` singleton: one row (`settings:school`) holding the school's
2+//! policy knobs. An absent row reads as the built-in defaults everywhere.
3+
4+use crate::database::Database;
5+use crate::domain::settings::Settings;
6+use crate::error::AppError;
7+
8+/// The stored policy, or the defaults when no row exists yet.
9+pub async fn load(db: &Database) -> Result<Settings, AppError> {
10+ let found: Option<Settings> = db.select(Settings::record_id()).await?;
11+ Ok(found.unwrap_or_else(Settings::defaults))
12+}
13+
14+/// Persist the policy (single UPSERT on the fixed singleton id),
15+/// unconditionally — last write wins. Prefer [`save_if_unchanged`]
16+/// wherever the new policy was merged from a loaded snapshot.
17+pub async fn save(db: &Database, settings: Settings) -> Result<Settings, AppError> {
18+ // whole-row-save-ok: test-only seeding; every production write merges from a loaded snapshot and goes through save_if_unchanged
19+ let saved: Option<Settings> = db.upsert(Settings::record_id()).content(settings).await?;
20+ saved.ok_or_else(|| AppError::Internal("failed to save settings".into()))
21+}
22+
23+/// Persist the policy only while the stored row still matches `expected`
24+/// — the snapshot the caller merged omitted fields from. `None` means a
25+/// concurrent edit landed in between and nothing was written: reload,
26+/// re-merge, retry. Without this compare-and-set, two managers patching
27+/// *different* fields silently revert each other (both merge from the
28+/// same snapshot; the later whole-row write restores its stale copy of
29+/// the other's field).
30+///
31+/// One transaction: the seed insert materializes the defaults-as-loaded
32+/// state when no row exists yet (`load` reported the defaults, so the
33+/// defaults are what the caller merged over), then the guarded update
34+/// applies `settings` only if the row (still) equals `expected`.
35+///
36+/// **`meal_slots` is compared through a projection, and it has to be.**
37+/// SurrealDB *drops* an object key whose value is `NONE` on write, while
38+/// the `SurrealValue` derive always emits `serving_minute: NONE` for a
39+/// slot without one — so `{name: 'lunch'} = {name: 'lunch', serving_minute:
40+/// NONE}` is **false** and a plain equality guard would never match again
41+/// for any school with a serving-time-less slot (which is every school
42+/// until it sets one): every `PATCH /settings` would 409 forever. Rebuilding
43+/// both sides as full objects normalizes the shapes. The NONE-ness of the
44+/// column itself is compared separately, so "never set" stays distinguishable
45+/// from "explicitly empty". Top-level optional columns need none of this:
46+/// a missing field reads as `NONE`, and `NONE = NONE` holds.
47+pub async fn save_if_unchanged(
48+ db: &Database,
49+ settings: Settings,
50+ expected: &Settings,
51+) -> Result<Option<Settings>, AppError> {
52+ let mut result = db
53+ .query(
54+ "BEGIN TRANSACTION;
55+ INSERT IGNORE INTO settings $expected;
56+ UPDATE $id CONTENT $new
57+ WHERE exam_kinds = $ek
58+ AND attendance_statuses = $st
59+ AND grade_bands = $gb
60+ AND max_file_bytes = $mf
61+ AND chatbot_history_turns = $ct
62+ AND max_chatbot_threads = $cc
63+ AND max_chatbot_message_len = $cl
64+ AND (meal_slots = NONE) = $ms_unset
65+ AND (meal_slots ?? []).map(|$s| {
66+ name: $s.name,
67+ serving_minute: $s.serving_minute
68+ }) = ($ms ?? [])
69+ AND dietary_tags = $dt
70+ AND meal_cancel_cutoff_minutes = $mc;
71+ COMMIT TRANSACTION;",
72+ )
73+ .bind(("expected", expected.clone()))
74+ .bind(("id", Settings::record_id()))
75+ .bind(("new", settings))
76+ .bind(("ek", expected.exam_kinds.clone()))
77+ .bind(("st", expected.attendance_statuses.clone()))
78+ .bind(("gb", expected.grade_bands.clone()))
79+ .bind(("mf", expected.max_file_bytes))
80+ .bind(("ct", expected.chatbot_history_turns))
81+ .bind(("cc", expected.max_chatbot_threads))
82+ .bind(("cl", expected.max_chatbot_message_len))
83+ .bind(("ms_unset", expected.meal_slots.is_none()))
84+ .bind(("ms", expected.meal_slots.clone()))
85+ .bind(("dt", expected.dietary_tags.clone()))
86+ .bind(("mc", expected.meal_cancel_cutoff_minutes))
87+ .await?
88+ .check()?;
89+ // Statement slots count BEGIN too: the guarded UPDATE is slot 2. An
90+ // empty slot means the row no longer matched `expected`.
91+ Ok(result.take::<Vec<Settings>>(2)?.into_iter().next())
92+}
93+
94+#[cfg(test)]
95+mod tests {
96+ use super::*;
97+ use crate::constant::{
98+ DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_MAX_CHATBOT_MESSAGE_LEN,
99+ DEFAULT_MAX_CHATBOT_THREADS, DEFAULT_MAX_FILE_BYTES,
100+ };
101+ use crate::domain::settings::{ExamKindDef, GradeBand, SettingsParams};
102+
103+ fn kinds(list: &[&str]) -> Vec<ExamKindDef> {
104+ list.iter()
105+ .map(|s| ExamKindDef::try_new(s, 1).unwrap())
106+ .collect()
107+ }
108+
109+ fn names(settings: &Settings) -> Vec<&str> {
110+ settings
111+ .get_exam_kinds()
112+ .iter()
113+ .map(ExamKindDef::get_name)
114+ .collect()
115+ }
116+
117+ /// The defaults as tweakable params — every site below overrides only the
118+ /// fields it is testing (`..params()`).
119+ fn params() -> SettingsParams {
120+ Settings::defaults().params()
121+ }
122+
123+ fn bands(list: &[(i64, &str)]) -> Vec<GradeBand> {
124+ list.iter()
125+ .map(|(min, label)| GradeBand::try_new(*min, label).unwrap())
126+ .collect()
127+ }
128+
129+ #[tokio::test]
130+ async fn a_row_predating_the_optional_knobs_reads_the_defaults() {
131+ let db = crate::database::init_mem().await.unwrap();
132+ // The defaults carry no explicit knobs, so this writes a row without
133+ // those fields — exactly what a volume from before them looks like.
134+ save(&db, Settings::defaults()).await.unwrap();
135+ let loaded = load(&db).await.unwrap();
136+ assert_eq!(loaded.get_max_file_bytes(), DEFAULT_MAX_FILE_BYTES);
137+ assert_eq!(
138+ loaded.get_chatbot_history_turns(),
139+ DEFAULT_CHATBOT_HISTORY_TURNS
140+ );
141+ assert_eq!(
142+ loaded.get_max_chatbot_threads(),
143+ DEFAULT_MAX_CHATBOT_THREADS
144+ );
145+ assert_eq!(
146+ loaded.get_max_chatbot_message_len(),
147+ DEFAULT_MAX_CHATBOT_MESSAGE_LEN
148+ );
149+ // And a snapshot of that old row still passes the compare-and-set.
150+ let saved = save_if_unchanged(
151+ &db,
152+ Settings::try_new(SettingsParams {
153+ max_file_bytes: 4096,
154+ ..loaded.params()
155+ })
156+ .unwrap(),
157+ &loaded,
158+ )
159+ .await
160+ .unwrap()
161+ .expect("a merge over an old-shape row applies");
162+ assert_eq!(saved.get_max_file_bytes(), 4096);
163+ }
164+
165+ #[tokio::test]
166+ async fn load_save_roundtrip_on_the_singleton() {
167+ let db = crate::database::init_mem().await.unwrap();
168+ // No row yet → the defaults, not an error.
169+ let loaded = load(&db).await.unwrap();
170+ assert_eq!(
171+ loaded.get_exam_kinds(),
172+ Settings::defaults().get_exam_kinds()
173+ );
174+ // Save a custom policy and read it back — bands (nested objects under
175+ // a FLEXIBLE field) must survive the trip.
176+ save(
177+ &db,
178+ Settings::try_new(SettingsParams {
179+ exam_kinds: kinds(&["lab"]),
180+ grade_bands: bands(&[(0, "F"), (50, "P")]),
181+ max_file_bytes: 2048,
182+ chatbot_history_turns: 3,
183+ ..params()
184+ })
185+ .unwrap(),
186+ )
187+ .await
188+ .unwrap();
189+ let loaded = load(&db).await.unwrap();
190+ assert_eq!(names(&loaded), ["lab"]);
191+ assert_eq!(loaded.get_grade_bands().len(), 2);
192+ assert_eq!(loaded.grade_label(60.0), Some("P"));
193+ assert_eq!(loaded.get_max_file_bytes(), 2048);
194+ assert_eq!(loaded.get_chatbot_history_turns(), 3);
195+ // A second save lands on the same singleton row, not a new one.
196+ save(
197+ &db,
198+ Settings::try_new(SettingsParams {
199+ exam_kinds: kinds(&["quiz"]),
200+ ..params()
201+ })
202+ .unwrap(),
203+ )
204+ .await
205+ .unwrap();
206+ let mut result = db.query("SELECT * FROM settings").await.unwrap();
207+ let rows: Vec<Settings> = result.take(0).unwrap();
208+ assert_eq!(rows.len(), 1);
209+ assert_eq!(names(&rows[0]), ["quiz"]);
210+ }
211+
212+ #[tokio::test]
213+ async fn a_stale_snapshot_cannot_revert_a_newer_policy() {
214+ let db = crate::database::init_mem().await.unwrap();
215+
216+ // Editor A snapshots the policy (the defaults — no row yet)...
217+ let stale = load(&db).await.unwrap();
218+ // ...then editor B lands a new exam-kind list first.
219+ save(
220+ &db,
221+ Settings::try_new(SettingsParams {
222+ exam_kinds: kinds(&["lab"]),
223+ ..params()
224+ })
225+ .unwrap(),
226+ )
227+ .await
228+ .unwrap();
229+
230+ // A's merge over the stale snapshot (kinds kept "as loaded", bands
231+ // changed) — exactly what a concurrent PATCH /settings computes —
232+ // must be refused, not applied.
233+ let refused = save_if_unchanged(
234+ &db,
235+ Settings::try_new(SettingsParams {
236+ grade_bands: bands(&[(0, "F"), (50, "P")]),
237+ ..stale.params()
238+ })
239+ .unwrap(),
240+ &stale,
241+ )
242+ .await
243+ .unwrap();
244+ assert!(refused.is_none(), "a stale snapshot's save must not apply");
245+
246+ // B's edit must survive A's stale write attempt.
247+ let after = load(&db).await.unwrap();
248+ assert_eq!(
249+ names(&after),
250+ ["lab"],
251+ "a concurrent editor's exam kinds must not be silently reverted"
252+ );
253+ assert!(after.get_grade_bands().is_empty());
254+
255+ // A's retry — reload, re-merge, save again — lands both edits.
256+ let fresh = load(&db).await.unwrap();
257+ let saved = save_if_unchanged(
258+ &db,
259+ Settings::try_new(SettingsParams {
260+ grade_bands: bands(&[(0, "F"), (50, "P")]),
261+ ..fresh.params()
262+ })
263+ .unwrap(),
264+ &fresh,
265+ )
266+ .await
267+ .unwrap()
268+ .expect("a merge over the current row applies");
269+ assert_eq!(names(&saved), ["lab"]);
270+ assert_eq!(saved.get_grade_bands().len(), 2);
271+ }
272+
273+ #[tokio::test]
274+ async fn save_if_unchanged_seeds_the_first_row() {
275+ let db = crate::database::init_mem().await.unwrap();
276+ // No row yet: `load` reports the defaults, and a save conditioned on
277+ // that snapshot must apply (seeding the singleton on the way).
278+ let current = load(&db).await.unwrap();
279+ let saved = save_if_unchanged(
280+ &db,
281+ Settings::try_new(SettingsParams {
282+ exam_kinds: kinds(&["lab"]),
283+ ..current.params()
284+ })
285+ .unwrap(),
286+ &current,
287+ )
288+ .await
289+ .unwrap()
290+ .expect("the first save applies");
291+ assert_eq!(names(&saved), ["lab"]);
292+ let mut result = db.query("SELECT * FROM settings").await.unwrap();
293+ let rows: Vec<Settings> = result.take(0).unwrap();
294+ assert_eq!(rows.len(), 1, "still one singleton row");
295+ }
296+}
src/domain/bank_question.rsmodified+2 -2
@@ -404,7 +404,7 @@ impl BankQuestion {
404 /// Every field the merge re-states is in the guard, which is the same list404 /// Every field the merge re-states is in the guard, which is the same list
405 /// the `SET` writes. `choices` is compared whole: its objects carry two405 /// the `SET` writes. `choices` is compared whole: its objects carry two
406 /// required string keys, so none is ever dropped for being `NONE` (the trap406 /// required string keys, so none is ever dropped for being `NONE` (the trap
407- /// [`crate::domain::settings::Settings::save_if_unchanged`] works around).407+ /// [`crate::db::settings::save_if_unchanged`] works around).
408 ///408 ///
409 /// Rides [`write_with_retry`] because an image write now moves this row too409 /// Rides [`write_with_retry`] because an image write now moves this row too
410 /// ([`crate::domain::bank_question_image::BankQuestionImage::upsert`]): an410 /// ([`crate::domain::bank_question_image::BankQuestionImage::upsert`]): an
@@ -467,7 +467,7 @@ impl BankQuestion {
467 /// take off disk, but only for *these* rows — an upload that committed467 /// take off disk, but only for *these* rows — an upload that committed
468 /// after the caller listed the template's images is swept here too, and a468 /// after the caller listed the template's images is swept here too, and a
469 /// pre-read snapshot would strand its blob for good469 /// pre-read snapshot would strand its blob for good
470- /// ([`crate::domain::note::Note::delete`]'s story, this domain over).470+ /// ([`crate::db::note::delete`]'s story, this domain over).
471 ///471 ///
472 /// Children first, in one transaction: as two queries, a failure between472 /// Children first, in one transaction: as two queries, a failure between
473 /// them left image rows swept under a template that survived, or (the other473 /// them left image rows swept under a template that survived, or (the other
src/domain/chatbot_thread.rsmodified+9 -7
@@ -11,8 +11,8 @@ use crate::constant::{
11 };11 };
12 use crate::database::{Database, transaction_with_retry};12 use crate::database::{Database, transaction_with_retry};
13 use crate::db::cap;13 use crate::db::cap;
14-use crate::domain::monotonic_id::next_ulid;
15 use crate::db::page::PagedList;14 use crate::db::page::PagedList;
15+use crate::domain::monotonic_id::next_ulid;
16 use crate::domain::timestamp::Timestamp;16 use crate::domain::timestamp::Timestamp;
17 use crate::domain::user::UserId;17 use crate::domain::user::UserId;
18 use crate::error::{AppError, ValidationError};18 use crate::error::{AppError, ValidationError};
@@ -356,12 +356,14 @@ mod tests {
356 .unwrap()356 .unwrap()
357 .check()357 .check()
358 .unwrap();358 .unwrap();
359- Settings::try_new(SettingsParams {359+ crate::db::settings::save(
360- max_chatbot_threads: threads,360+ &db,
361- ..Settings::defaults().params()361+ Settings::try_new(SettingsParams {
362- })362+ max_chatbot_threads: threads,
363- .unwrap()363+ ..Settings::defaults().params()
364- .save(&db)364+ })
365+ .unwrap(),
366+ )
365 .await367 .await
366 .unwrap();368 .unwrap();
367 db369 db
src/domain/class_blueprint.rsmodified+2 -2
@@ -38,11 +38,11 @@ use crate::constant::{
38 CLASS_BLUEPRINT_TABLE, CLASS_COURSE_TABLE, ENROLLMENT_COUNT_FIELD, MAX_CLASS_COURSES,38 CLASS_BLUEPRINT_TABLE, CLASS_COURSE_TABLE, ENROLLMENT_COUNT_FIELD, MAX_CLASS_COURSES,
39 };39 };
40 use crate::database::{Database, transaction_with_retry};40 use crate::database::{Database, transaction_with_retry};
41+use crate::db::page::PagedList;
41 use crate::domain::class_course::ClassCourse;42 use crate::domain::class_course::ClassCourse;
42 use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId};43 use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId};
43 use crate::domain::class_pump::{Attached, Axis, detach};44 use crate::domain::class_pump::{Attached, Axis, detach};
44 use crate::domain::course::CourseId;45 use crate::domain::course::CourseId;
45-use crate::db::page::PagedList;
46 use crate::domain::user::UserId;46 use crate::domain::user::UserId;
47 use crate::error::{AppError, ValidationError};47 use crate::error::{AppError, ValidationError};
48 48
@@ -76,7 +76,7 @@ use crate::error::{AppError, ValidationError};
76 ///76 ///
77 /// In-process is deployment-wide here: one process by contract, with77 /// In-process is deployment-wide here: one process by contract, with
78 /// stop-the-world upgrades — the same argument78 /// stop-the-world upgrades — the same argument
79-/// [`crate::domain::settings::SETTINGS_LOCK`] makes. No other lock is taken79+/// [`crate::service::settings::SETTINGS_LOCK`] makes. No other lock is taken
80 /// under it, so it has no ordering rule to break.80 /// under it, so it has no ordering rule to break.
81 pub(crate) static BLUEPRINT_LOCK: RwLock<()> = RwLock::const_new(());81 pub(crate) static BLUEPRINT_LOCK: RwLock<()> = RwLock::const_new(());
82 82
src/domain/exam.rsmodified+1 -1
@@ -493,7 +493,7 @@ impl Exam {
493 /// handler's read: the compare-and-set refuses precisely when that save493 /// handler's read: the compare-and-set refuses precisely when that save
494 /// would have reverted somebody. `course`/`creator` are not editable and494 /// would have reverted somebody. `course`/`creator` are not editable and
495 /// ride along unchanged. Same shape as495 /// ride along unchanged. Same shape as
496- /// [`crate::domain::settings::Settings::save_if_unchanged`].496+ /// [`crate::db::settings::save_if_unchanged`].
497 pub async fn update_if_unchanged(497 pub async fn update_if_unchanged(
498 mut self,498 mut self,
499 title: ExamTitle,499 title: ExamTitle,
src/domain/note.rsmodified+8 -174
@@ -1,13 +1,9 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 2
3 use crate::constant::{MAX_NOTE_CONTENT_LEN, MAX_NOTE_TITLE_LEN, NOTE_TABLE};3 use crate::constant::{MAX_NOTE_CONTENT_LEN, MAX_NOTE_TITLE_LEN, NOTE_TABLE};
4-use crate::database::Database;
5-use crate::db::field_update::FieldUpdate;
6 use crate::domain::monotonic_id::next_ulid;4 use crate::domain::monotonic_id::next_ulid;
7-use crate::domain::note_file::NoteFile;
8-use crate::db::page::PagedList;
9 use crate::domain::user::UserId;5 use crate::domain::user::UserId;
10-use crate::error::{AppError, ValidationError};6+use crate::error::ValidationError;
11 use crate::validate::{validate_optional, validate_required};7 use crate::validate::{validate_optional, validate_required};
12 8
13 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]9 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
@@ -15,7 +11,7 @@ pub struct NoteId(RecordId);
15 11
16 impl NoteId {12 impl NoteId {
17 /// Minted from the process-wide monotonic generator, not `Ulid::new()`:13 /// Minted from the process-wide monotonic generator, not `Ulid::new()`:
18- /// notes list `id DESC` (newest first, [`Note::list_for_user`]),14+ /// notes list `id DESC` (newest first, [`crate::db::note::list_for`]),
19 /// and a random low half scrambles rows minted in the same millisecond.15 /// and a random low half scrambles rows minted in the same millisecond.
20 pub fn generate() -> Self {16 pub fn generate() -> Self {
21 Self(RecordId::new(NOTE_TABLE, next_ulid().to_string()))17 Self(RecordId::new(NOTE_TABLE, next_ulid().to_string()))
@@ -65,21 +61,14 @@ impl NoteContent {
65 }61 }
66 }62 }
67 63
68-/// What [`Note::delete`]'s transaction removed: the note row (empty if it had64+/// Fields are crate-visible: [`crate::db::note`] mints the rows on create and
69-/// already vanished) and every attachment row the cascade took with it — the65+/// reads the id when updating and cascading a delete.
70-/// only set whose blobs are safe to unlink.
71-#[derive(Debug, SurrealValue)]
72-struct DeleteOutcome {
73- note: Vec<Note>,
74- files: Vec<NoteFile>,
75-}
76-
77 #[derive(Debug, Clone, SurrealValue)]66 #[derive(Debug, Clone, SurrealValue)]
78 pub struct Note {67 pub struct Note {
79- id: NoteId,68+ pub(crate) id: NoteId,
80- user: UserId,69+ pub(crate) user: UserId,
81- title: NoteTitle,70+ pub(crate) title: NoteTitle,
82- content: NoteContent,71+ pub(crate) content: NoteContent,
83 }72 }
84 73
85 impl Note {74 impl Note {
@@ -94,97 +83,6 @@ impl Note {
94 pub fn get_content(&self) -> &NoteContent {83 pub fn get_content(&self) -> &NoteContent {
95 &self.content84 &self.content
96 }85 }
97-
98- pub async fn create(
99- owner: &UserId,
100- title: NoteTitle,
101- content: NoteContent,
102- db: &Database,
103- ) -> Result<Note, AppError> {
104- let note = Note {
105- id: NoteId::generate(),
106- user: owner.clone(),
107- title,
108- content,
109- };
110- let created: Option<Note> = db.create(note.id.record()).content(note).await?;
111- created.ok_or_else(|| AppError::Internal("failed to create note".into()))
112- }
113-
114- /// Read a note only if it belongs to `owner`.
115- pub async fn read_owned(
116- id: &NoteId,
117- owner: &UserId,
118- db: &Database,
119- ) -> Result<Option<Note>, AppError> {
120- let note: Option<Note> = db.select(id.record()).await?;
121- Ok(note.filter(|note| &note.user == owner))
122- }
123-
124- pub async fn list_for(
125- owner: &UserId,
126- limit: Option<i64>,
127- offset: i64,
128- db: &Database,
129- ) -> Result<(Vec<Note>, i64), AppError> {
130- PagedList::new("note WHERE user = $usr", "ORDER BY id DESC")
131- .bind("usr", owner.record())
132- .run(limit, offset, db)
133- .await
134- }
135-
136- /// Request-scoped: no lock spans the handler's read and this write, so an
137- /// omitted field (`None`) is not written at all. Passing the snapshot's
138- /// value back instead would revert a concurrent edit of that field —
139- /// scoping the `SET` alone does not prevent that, the values have to come
140- /// from the request. Neither column is nullable, so plain `Option` per
141- /// field says everything there is to say.
142- pub async fn update(
143- self,
144- title: Option<NoteTitle>,
145- content: Option<NoteContent>,
146- db: &Database,
147- ) -> Result<Note, AppError> {
148- FieldUpdate::new(self.id.record())
149- .set("title", title)
150- .set("content", content)
151- .run::<Note>(db)
152- .await
153- }
154-
155- /// Delete the note and cascade-remove its attachment rows, returning both:
156- /// the note, and the attachment rows this transaction actually removed.
157- /// Blob files on disk are the web layer's to remove, but only for *these*
158- /// rows — a row uploaded after the caller listed the note's files is
159- /// deleted here too, and a pre-read snapshot would strand its blob. A crash
160- /// between commit and unlink leaves at worst an unreachable blob, never a
161- /// row pointing at nothing.
162- ///
163- /// Children first, in one transaction, the way
164- /// [`crate::domain::course::Course::delete`] does it: as two queries, an
165- /// upload that committed in between kept its row while the note went, and
166- /// nothing could ever list or delete it again.
167- pub async fn delete(self, db: &Database) -> Result<(Note, Vec<NoteFile>), AppError> {
168- let mut result = db
169- .query(
170- "BEGIN TRANSACTION;
171- LET $files = (DELETE note_file WHERE note = $note RETURN BEFORE);
172- LET $gone = (DELETE $note RETURN BEFORE);
173- RETURN { note: $gone, files: $files };
174- COMMIT TRANSACTION;",
175- )
176- .bind(("note", self.id.record()))
177- .await?
178- .check()?;
179- // BEGIN is slot 0, the two LETs slots 1-2; the RETURN is slot 3.
180- let outcome = result
181- .take::<Vec<DeleteOutcome>>(3)?
182- .into_iter()
183- .next()
184- .ok_or_else(|| AppError::Internal("failed to delete note".into()))?;
185- let note = outcome.note.into_iter().next().ok_or(AppError::NotFound)?;
186- Ok((note, outcome.files))
187- }
188 }86 }
189 87
190 #[cfg(test)]88 #[cfg(test)]
@@ -197,70 +95,6 @@ mod tests {
197 assert!(NoteTitle::try_new(" ").is_err());95 assert!(NoteTitle::try_new(" ").is_err());
198 }96 }
199 97
200- /// The blobs the handler unlinks are exactly the rows this transaction
201- /// removed — including one uploaded after any pre-read snapshot would have
202- /// been taken, which is the row whose blob used to leak.
203- #[tokio::test]
204- async fn delete_returns_the_attachment_rows_it_removed() {
205- use crate::domain::note_file::{FileContentType, FileName};
206-
207- let db = crate::database::init_mem().await.unwrap();
208- let owner = crate::domain::user::UserId::generate();
209- let note = Note::create(
210- &owner,
211- NoteTitle::try_new("a").unwrap(),
212- NoteContent::try_new("body").unwrap(),
213- &db,
214- )
215- .await
216- .unwrap();
217- // What a handler snapshot would have seen...
218- let early = NoteFile::new(
219- note.get_id(),
220- FileName::try_new("early.pdf").unwrap(),
221- FileContentType::try_new("application/pdf").unwrap(),
222- 3,
223- )
224- .insert(&db)
225- .await
226- .unwrap();
227- let (snapshot, _) = NoteFile::list_for(note.get_id(), None, 0, &db)
228- .await
229- .unwrap();
230- assert_eq!(snapshot.len(), 1);
231- // ...and the upload that races in after it.
232- let late = NoteFile::new(
233- note.get_id(),
234- FileName::try_new("late.pdf").unwrap(),
235- FileContentType::try_new("application/pdf").unwrap(),
236- 3,
237- )
238- .insert(&db)
239- .await
240- .unwrap();
241-
242- let (gone, files) = note.delete(&db).await.unwrap();
243- assert_eq!(gone.get_title().as_str(), "a");
244- let mut keys: Vec<_> = files
245- .iter()
246- .map(|file| file.get_id().key().to_string())
247- .collect();
248- keys.sort();
249- let mut want = vec![
250- early.get_id().key().to_string(),
251- late.get_id().key().to_string(),
252- ];
253- want.sort();
254- assert_eq!(keys, want);
255- assert!(
256- NoteFile::list_for(gone.get_id(), None, 0, &db)
257- .await
258- .unwrap()
259- .0
260- .is_empty()
261- );
262- }
263-
264 #[tokio::test]98 #[tokio::test]
265 async fn content_is_optional() {99 async fn content_is_optional() {
266 assert_eq!(NoteContent::try_new("").unwrap().as_str(), "");100 assert_eq!(NoteContent::try_new("").unwrap().as_str(), "");
src/domain/note_file.rsmodified+5 -5
@@ -13,9 +13,9 @@ use crate::constant::{
13 };13 };
14 use crate::database::Database;14 use crate::database::Database;
15 use crate::db::cap;15 use crate::db::cap;
16+use crate::db::page::PagedList;
16 use crate::domain::monotonic_id::next_ulid;17 use crate::domain::monotonic_id::next_ulid;
17 use crate::domain::note::NoteId;18 use crate::domain::note::NoteId;
18-use crate::db::page::PagedList;
19 use crate::error::{AppError, ValidationError};19 use crate::error::{AppError, ValidationError};
20 20
21 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]21 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
@@ -279,11 +279,11 @@ mod tests {
279 // note does not exist has no slot to take (a 409, like a full note).279 // note does not exist has no slot to take (a 409, like a full note).
280 let owner = crate::domain::user::UserId::generate();280 let owner = crate::domain::user::UserId::generate();
281 let note_of = async |title: &str| {281 let note_of = async |title: &str| {
282- crate::domain::note::Note::create(282+ crate::db::note::create(
283+ &db,
283 &owner,284 &owner,
284 crate::domain::note::NoteTitle::try_new(title).unwrap(),285 crate::domain::note::NoteTitle::try_new(title).unwrap(),
285 crate::domain::note::NoteContent::try_new("body").unwrap(),286 crate::domain::note::NoteContent::try_new("body").unwrap(),
286- &db,
287 )287 )
288 .await288 .await
289 .unwrap()289 .unwrap()
@@ -326,11 +326,11 @@ mod tests {
326 #[tokio::test]326 #[tokio::test]
327 async fn counter_tracks_stored_rows() {327 async fn counter_tracks_stored_rows() {
328 let db = crate::database::init_mem().await.unwrap();328 let db = crate::database::init_mem().await.unwrap();
329- let note = crate::domain::note::Note::create(329+ let note = crate::db::note::create(
330+ &db,
330 &crate::domain::user::UserId::generate(),331 &crate::domain::user::UserId::generate(),
331 crate::domain::note::NoteTitle::try_new("a").unwrap(),332 crate::domain::note::NoteTitle::try_new("a").unwrap(),
332 crate::domain::note::NoteContent::try_new("body").unwrap(),333 crate::domain::note::NoteContent::try_new("body").unwrap(),
333- &db,
334 )334 )
335 .await335 .await
336 .unwrap()336 .unwrap()
src/domain/session.rsmodified+6 -80
@@ -1,8 +1,7 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 use ulid::Ulid;2 use ulid::Ulid;
3 3
4-use crate::constant::{SESSION_DURATION_DAYS, SESSION_TABLE};4+use crate::constant::SESSION_TABLE;
5-use crate::database::Database;
6 use crate::domain::timestamp::Timestamp;5 use crate::domain::timestamp::Timestamp;
7 use crate::domain::user::UserId;6 use crate::domain::user::UserId;
8 use crate::error::AppError;7 use crate::error::AppError;
@@ -44,26 +43,16 @@ impl SessionToken {
44 }43 }
45 }44 }
46 45
46+/// Fields are crate-visible: [`crate::db::session`] mints the rows on login.
47 #[derive(Debug, Clone, SurrealValue)]47 #[derive(Debug, Clone, SurrealValue)]
48 pub struct Session {48 pub struct Session {
49- id: SessionId,49+ pub(crate) id: SessionId,
50- user: UserId,50+ pub(crate) user: UserId,
51- token: SessionToken,51+ pub(crate) token: SessionToken,
52- expires_at: Timestamp,52+ pub(crate) expires_at: Timestamp,
53 }53 }
54 54
55 impl Session {55 impl Session {
56- pub async fn create(user: &UserId, db: &Database) -> Result<Session, AppError> {
57- let session = Session {
58- id: SessionId::generate(),
59- user: user.clone(),
60- token: SessionToken::generate()?,
61- expires_at: Timestamp::in_days(SESSION_DURATION_DAYS),
62- };
63- let created: Option<Session> = db.create(session.id.record()).content(session).await?;
64- created.ok_or_else(|| AppError::Internal("failed to create session".into()))
65- }
66-
67 pub fn token(&self) -> &SessionToken {56 pub fn token(&self) -> &SessionToken {
68 &self.token57 &self.token
69 }58 }
@@ -75,47 +64,6 @@ impl Session {
75 pub fn is_expired(&self) -> bool {64 pub fn is_expired(&self) -> bool {
76 self.expires_at.is_past()65 self.expires_at.is_past()
77 }66 }
78-
79- pub async fn find_by_token(token: &str, db: &Database) -> Result<Option<Session>, AppError> {
80- let mut result = db
81- .query("SELECT * FROM session WHERE token = $tok LIMIT 1")
82- .bind(("tok", token.to_string()))
83- .await?
84- .check()?;
85- Ok(result.take::<Vec<Session>>(0)?.into_iter().next())
86- }
87-
88- pub async fn delete_by_token(token: &str, db: &Database) -> Result<(), AppError> {
89- db.query("DELETE session WHERE token = $tok")
90- .bind(("tok", token.to_string()))
91- .await?
92- .check()?;
93- Ok(())
94- }
95-
96- /// Revoke every session a user holds. The other half of a password reset:
97- /// the new credential means nothing while a cookie minted under the old one
98- /// still authenticates.
99- pub async fn delete_by_user(user: &UserId, db: &Database) -> Result<(), AppError> {
100- db.query("DELETE session WHERE user = $usr")
101- .bind(("usr", user.record()))
102- .await?
103- .check()?;
104- Ok(())
105- }
106-
107- /// Delete every session whose expiry is in the past, returning how many were
108- /// removed. Expired sessions are already rejected at auth, but nothing else
109- /// deletes their rows — without this sweep the `session` table grows forever.
110- pub async fn purge_expired(db: &Database) -> Result<u64, AppError> {
111- let now = Timestamp::now().as_millis();
112- let mut result = db
113- .query("DELETE session WHERE expires_at < $now RETURN BEFORE")
114- .bind(("now", now))
115- .await?
116- .check()?;
117- Ok(result.take::<Vec<Session>>(0)?.len() as u64)
118- }
119 }67 }
120 68
121 #[cfg(test)]69 #[cfg(test)]
@@ -129,26 +77,4 @@ mod tests {
129 assert!(token.as_str().chars().all(|c| c.is_ascii_hexdigit()));77 assert!(token.as_str().chars().all(|c| c.is_ascii_hexdigit()));
130 assert_ne!(SessionToken::generate().unwrap().as_str(), token.as_str());78 assert_ne!(SessionToken::generate().unwrap().as_str(), token.as_str());
131 }79 }
132-
133- #[tokio::test]
134- async fn purge_expired_removes_only_past_sessions() {
135- let db = crate::database::init_mem().await.unwrap();
136- db.query(
137- "CREATE session SET user = type::record('user', 'u'), token = 'past', expires_at = 1;
138- CREATE session SET user = type::record('user', 'u'), token = 'future', expires_at = 99999999999999;",
139- )
140- .await
141- .unwrap()
142- .check()
143- .unwrap();
144-
145- assert_eq!(Session::purge_expired(&db).await.unwrap(), 1);
146- assert!(Session::find_by_token("past", &db).await.unwrap().is_none());
147- assert!(
148- Session::find_by_token("future", &db)
149- .await
150- .unwrap()
151- .is_some()
152- );
153- }
154 }80 }
src/domain/settings.rsmodified+14 -277
@@ -12,7 +12,6 @@
12 //! existing rows, and `UPDATE` re-validates whole records).12 //! existing rows, and `UPDATE` re-validates whole records).
13 13
14 use surrealdb::types::{RecordId, SurrealValue};14 use surrealdb::types::{RecordId, SurrealValue};
15-use tokio::sync::Mutex;
16 15
17 use crate::constant::{16 use crate::constant::{
18 DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_DIETARY_TAGS,17 DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_DIETARY_TAGS,
@@ -24,35 +23,8 @@ use crate::constant::{
24 MIN_CHATBOT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT, MIN_MARK, MIN_MAX_CHATBOT_MESSAGE_LEN,23 MIN_CHATBOT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT, MIN_MARK, MIN_MAX_CHATBOT_MESSAGE_LEN,
25 MIN_MAX_CHATBOT_THREADS, MIN_MAX_FILE_BYTES, SETTINGS_KEY, SETTINGS_TABLE,24 MIN_MAX_CHATBOT_THREADS, MIN_MAX_FILE_BYTES, SETTINGS_KEY, SETTINGS_TABLE,
26 };25 };
27-use crate::database::Database;
28 use crate::domain::text_fold;26 use crate::domain::text_fold;
29-use crate::error::{AppError, ValidationError};27+use crate::error::ValidationError;
30-
31-/// One settings edit at a time, over the whole process.
32-///
33-/// A list edit is a **pair** of writes, and the pair is the guard: every name
34-/// the edit drops is retired on its reference counter first (which refuses
35-/// every later claim), and only then is the list itself committed with a
36-/// compare-and-set against the snapshot the removals were judged from. Neither
37-/// write can be made to cover the other. Both retirement and un-retirement are
38-/// *idempotent*, so a rival that decided the same removal against the same
39-/// snapshot is told "already retired" and records no rollback — and when it is
40-/// that rival's save that wins the compare-and-set, the attempt which really
41-/// flipped the bit rolls it back, leaving the name off the stored list with a
42-/// counter reading "in service": gradable again, and unremovable for good once
43-/// a mark lands. No per-name bit can close that, because `Unchanged` has
44-/// erased which attempt owns the flip.
45-///
46-/// So the pair is serialized instead. Every writer of the singleton goes
47-/// through `PATCH /settings`, and the deployment runs one process by contract
48-/// (stop-the-world upgrades), so process-wide is deployment-wide here — the
49-/// same argument [`crate::db::cap`]'s own lock makes for `retire_name`'s
50-/// two statements, one level up. The compare-and-set stays: it is what keeps a
51-/// crashed or rolled-back attempt from writing a list nobody merged.
52-///
53-/// **Lock order:** `SETTINGS_LOCK` → `cap`'s `CLAIM_LOCK`, never the reverse —
54-/// the retirements are taken while this is held.
55-pub(crate) static SETTINGS_LOCK: Mutex<()> = Mutex::const_new(());
56 28
57 /// One exam kind the school runs (`"midterm"`, `"oral"`, …) with its weight:29 /// One exam kind the school runs (`"midterm"`, `"oral"`, …) with its weight:
58 /// how many times an exam of that kind counts into its course's average.30 /// how many times an exam of that kind counts into its course's average.
@@ -218,30 +190,31 @@ impl GradeBand {
218 190
219 /// The school's policy knobs, validated as a whole (parse, don't validate —191 /// The school's policy knobs, validated as a whole (parse, don't validate —
220 /// like every other entity, an existing `Settings` is always internally192 /// like every other entity, an existing `Settings` is always internally
221-/// consistent).193+/// consistent). Fields are crate-visible because [`crate::db::settings`]
194+/// binds them directly in the compare-and-set guard.
222 #[derive(Debug, Clone, SurrealValue)]195 #[derive(Debug, Clone, SurrealValue)]
223 pub struct Settings {196 pub struct Settings {
224 id: RecordId,197 id: RecordId,
225- exam_kinds: Vec<ExamKindDef>,198+ pub(crate) exam_kinds: Vec<ExamKindDef>,
226- attendance_statuses: Vec<String>,199+ pub(crate) attendance_statuses: Vec<String>,
227- grade_bands: Vec<GradeBand>,200+ pub(crate) grade_bands: Vec<GradeBand>,
228 /// Per-file byte cap for note uploads. `None` = the row predates the201 /// Per-file byte cap for note uploads. `None` = the row predates the
229 /// field (or the defaults) — reads as `DEFAULT_MAX_FILE_BYTES`.202 /// field (or the defaults) — reads as `DEFAULT_MAX_FILE_BYTES`.
230- max_file_bytes: Option<i64>,203+ pub(crate) max_file_bytes: Option<i64>,
231 /// Chatbot knobs, `None`-while-unset exactly like `max_file_bytes`.204 /// Chatbot knobs, `None`-while-unset exactly like `max_file_bytes`.
232- chatbot_history_turns: Option<i64>,205+ pub(crate) chatbot_history_turns: Option<i64>,
233- max_chatbot_threads: Option<i64>,206+ pub(crate) max_chatbot_threads: Option<i64>,
234- max_chatbot_message_len: Option<i64>,207+ pub(crate) max_chatbot_message_len: Option<i64>,
235 /// Food-program knobs. `None`-while-unset exactly like `max_file_bytes` —208 /// Food-program knobs. `None`-while-unset exactly like `max_file_bytes` —
236 /// the columns are `option<…>`, never `DEFAULT []`: `save_if_unchanged`209 /// the columns are `option<…>`, never `DEFAULT []`: `save_if_unchanged`
237 /// writes the whole row, so a field this struct did not carry would coerce210 /// writes the whole row, so a field this struct did not carry would coerce
238 /// to `NONE` and abort the transaction.211 /// to `NONE` and abort the transaction.
239- meal_slots: Option<Vec<MealSlotDef>>,212+ pub(crate) meal_slots: Option<Vec<MealSlotDef>>,
240- dietary_tags: Option<Vec<String>>,213+ pub(crate) dietary_tags: Option<Vec<String>>,
241 /// Minutes before a meal at which booking *and* cancelling close. One knob214 /// Minutes before a meal at which booking *and* cancelling close. One knob
242 /// for both deadlines; `None` = no cutoff at all, which is also what an215 /// for both deadlines; `None` = no cutoff at all, which is also what an
243 /// unset column reads as.216 /// unset column reads as.
244- meal_cancel_cutoff_minutes: Option<i64>,217+ pub(crate) meal_cancel_cutoff_minutes: Option<i64>,
245 }218 }
246 219
247 /// Everything [`Settings::try_new`] validates, in one struct — the knobs220 /// Everything [`Settings::try_new`] validates, in one struct — the knobs
@@ -263,7 +236,7 @@ pub struct SettingsParams {
263 }236 }
264 237
265 impl Settings {238 impl Settings {
266- fn record_id() -> RecordId {239+ pub(crate) fn record_id() -> RecordId {
267 RecordId::new(SETTINGS_TABLE, SETTINGS_KEY)240 RecordId::new(SETTINGS_TABLE, SETTINGS_KEY)
268 }241 }
269 242
@@ -529,92 +502,6 @@ impl Settings {
529 .max_by_key(|band| band.get_min())502 .max_by_key(|band| band.get_min())
530 .map(GradeBand::get_label)503 .map(GradeBand::get_label)
531 }504 }
532-
533- /// The stored policy, or the defaults when no row exists yet.
534- pub async fn load(db: &Database) -> Result<Settings, AppError> {
535- let found: Option<Settings> = db.select(Self::record_id()).await?;
536- Ok(found.unwrap_or_else(Self::defaults))
537- }
538-
539- /// Persist the policy (single UPSERT on the fixed singleton id),
540- /// unconditionally — last write wins. Prefer [`Self::save_if_unchanged`]
541- /// wherever the new policy was merged from a loaded snapshot.
542- pub async fn save(self, db: &Database) -> Result<Settings, AppError> {
543- // whole-row-save-ok: test-only seeding; every production write merges from a loaded snapshot and goes through save_if_unchanged
544- let saved: Option<Settings> = db.upsert(Self::record_id()).content(self).await?;
545- saved.ok_or_else(|| AppError::Internal("failed to save settings".into()))
546- }
547-
548- /// Persist the policy only while the stored row still matches `expected`
549- /// — the snapshot the caller merged omitted fields from. `None` means a
550- /// concurrent edit landed in between and nothing was written: reload,
551- /// re-merge, retry. Without this compare-and-set, two managers patching
552- /// *different* fields silently revert each other (both merge from the
553- /// same snapshot; the later whole-row write restores its stale copy of
554- /// the other's field).
555- ///
556- /// One transaction: the seed insert materializes the defaults-as-loaded
557- /// state when no row exists yet (`load` reported the defaults, so the
558- /// defaults are what the caller merged over), then the guarded update
559- /// applies `self` only if the row (still) equals `expected`.
560- ///
561- /// **`meal_slots` is compared through a projection, and it has to be.**
562- /// SurrealDB *drops* an object key whose value is `NONE` on write, while
563- /// the `SurrealValue` derive always emits `serving_minute: NONE` for a
564- /// slot without one — so `{name: 'lunch'} = {name: 'lunch', serving_minute:
565- /// NONE}` is **false** and a plain equality guard would never match again
566- /// for any school with a serving-time-less slot (which is every school
567- /// until it sets one): every `PATCH /settings` would 409 forever. Rebuilding
568- /// both sides as full objects normalizes the shapes. The NONE-ness of the
569- /// column itself is compared separately, so "never set" stays distinguishable
570- /// from "explicitly empty". Top-level optional columns need none of this:
571- /// a missing field reads as `NONE`, and `NONE = NONE` holds.
572- pub async fn save_if_unchanged(
573- self,
574- expected: &Settings,
575- db: &Database,
576- ) -> Result<Option<Settings>, AppError> {
577- let mut result = db
578- .query(
579- "BEGIN TRANSACTION;
580- INSERT IGNORE INTO settings $expected;
581- UPDATE $id CONTENT $new
582- WHERE exam_kinds = $ek
583- AND attendance_statuses = $st
584- AND grade_bands = $gb
585- AND max_file_bytes = $mf
586- AND chatbot_history_turns = $ct
587- AND max_chatbot_threads = $cc
588- AND max_chatbot_message_len = $cl
589- AND (meal_slots = NONE) = $ms_unset
590- AND (meal_slots ?? []).map(|$s| {
591- name: $s.name,
592- serving_minute: $s.serving_minute
593- }) = ($ms ?? [])
594- AND dietary_tags = $dt
595- AND meal_cancel_cutoff_minutes = $mc;
596- COMMIT TRANSACTION;",
597- )
598- .bind(("expected", expected.clone()))
599- .bind(("id", Self::record_id()))
600- .bind(("new", self))
601- .bind(("ek", expected.exam_kinds.clone()))
602- .bind(("st", expected.attendance_statuses.clone()))
603- .bind(("gb", expected.grade_bands.clone()))
604- .bind(("mf", expected.max_file_bytes))
605- .bind(("ct", expected.chatbot_history_turns))
606- .bind(("cc", expected.max_chatbot_threads))
607- .bind(("cl", expected.max_chatbot_message_len))
608- .bind(("ms_unset", expected.meal_slots.is_none()))
609- .bind(("ms", expected.meal_slots.clone()))
610- .bind(("dt", expected.dietary_tags.clone()))
611- .bind(("mc", expected.meal_cancel_cutoff_minutes))
612- .await?
613- .check()?;
614- // Statement slots count BEGIN too: the guarded UPDATE is slot 2. An
615- // empty slot means the row no longer matched `expected`.
616- Ok(result.take::<Vec<Settings>>(2)?.into_iter().next())
617- }
618 }505 }
619 506
620 /// Shared bounds check for the numeric knobs (upload cap, chatbot limits):507 /// Shared bounds check for the numeric knobs (upload cap, chatbot limits):
@@ -941,156 +828,6 @@ mod tests {
941 assert!(len(MAX_CHATBOT_MESSAGE_LEN as i64 + 1).is_err());828 assert!(len(MAX_CHATBOT_MESSAGE_LEN as i64 + 1).is_err());
942 }829 }
943 830
944- #[tokio::test]
945- async fn a_row_predating_the_optional_knobs_reads_the_defaults() {
946- let db = crate::database::init_mem().await.unwrap();
947- // The defaults carry no explicit knobs, so this writes a row without
948- // those fields — exactly what a volume from before them looks like.
949- Settings::defaults().save(&db).await.unwrap();
950- let loaded = Settings::load(&db).await.unwrap();
951- assert_eq!(loaded.get_max_file_bytes(), DEFAULT_MAX_FILE_BYTES);
952- assert_eq!(
953- loaded.get_chatbot_history_turns(),
954- DEFAULT_CHATBOT_HISTORY_TURNS
955- );
956- assert_eq!(
957- loaded.get_max_chatbot_threads(),
958- DEFAULT_MAX_CHATBOT_THREADS
959- );
960- assert_eq!(
961- loaded.get_max_chatbot_message_len(),
962- DEFAULT_MAX_CHATBOT_MESSAGE_LEN
963- );
964- // And a snapshot of that old row still passes the compare-and-set.
965- let saved = Settings::try_new(SettingsParams {
966- max_file_bytes: 4096,
967- ..loaded.params()
968- })
969- .unwrap()
970- .save_if_unchanged(&loaded, &db)
971- .await
972- .unwrap()
973- .expect("a merge over an old-shape row applies");
974- assert_eq!(saved.get_max_file_bytes(), 4096);
975- }
976-
977- #[tokio::test]
978- async fn load_save_roundtrip_on_the_singleton() {
979- let db = crate::database::init_mem().await.unwrap();
980- // No row yet → the defaults, not an error.
981- let loaded = Settings::load(&db).await.unwrap();
982- assert_eq!(
983- loaded.get_exam_kinds(),
984- Settings::defaults().get_exam_kinds()
985- );
986- // Save a custom policy and read it back — bands (nested objects under
987- // a FLEXIBLE field) must survive the trip.
988- Settings::try_new(SettingsParams {
989- exam_kinds: kinds(&["lab"]),
990- grade_bands: bands(&[(0, "F"), (50, "P")]),
991- max_file_bytes: 2048,
992- chatbot_history_turns: 3,
993- ..params()
994- })
995- .unwrap()
996- .save(&db)
997- .await
998- .unwrap();
999- let loaded = Settings::load(&db).await.unwrap();
1000- assert_eq!(names(&loaded), ["lab"]);
1001- assert_eq!(loaded.get_grade_bands().len(), 2);
1002- assert_eq!(loaded.grade_label(60.0), Some("P"));
1003- assert_eq!(loaded.get_max_file_bytes(), 2048);
1004- assert_eq!(loaded.get_chatbot_history_turns(), 3);
1005- // A second save lands on the same singleton row, not a new one.
1006- Settings::try_new(SettingsParams {
1007- exam_kinds: kinds(&["quiz"]),
1008- ..params()
1009- })
1010- .unwrap()
1011- .save(&db)
1012- .await
1013- .unwrap();
1014- let mut result = db.query("SELECT * FROM settings").await.unwrap();
1015- let rows: Vec<Settings> = result.take(0).unwrap();
1016- assert_eq!(rows.len(), 1);
1017- assert_eq!(names(&rows[0]), ["quiz"]);
1018- }
1019-
1020- #[tokio::test]
1021- async fn a_stale_snapshot_cannot_revert_a_newer_policy() {
1022- let db = crate::database::init_mem().await.unwrap();
1023-
1024- // Editor A snapshots the policy (the defaults — no row yet)...
1025- let stale = Settings::load(&db).await.unwrap();
1026- // ...then editor B lands a new exam-kind list first.
1027- Settings::try_new(SettingsParams {
1028- exam_kinds: kinds(&["lab"]),
1029- ..params()
1030- })
1031- .unwrap()
1032- .save(&db)
1033- .await
1034- .unwrap();
1035-
1036- // A's merge over the stale snapshot (kinds kept "as loaded", bands
1037- // changed) — exactly what a concurrent PATCH /settings computes —
1038- // must be refused, not applied.
1039- let refused = Settings::try_new(SettingsParams {
1040- grade_bands: bands(&[(0, "F"), (50, "P")]),
1041- ..stale.params()
1042- })
1043- .unwrap()
1044- .save_if_unchanged(&stale, &db)
1045- .await
1046- .unwrap();
1047- assert!(refused.is_none(), "a stale snapshot's save must not apply");
1048-
1049- // B's edit must survive A's stale write attempt.
1050- let after = Settings::load(&db).await.unwrap();
1051- assert_eq!(
1052- names(&after),
1053- ["lab"],
1054- "a concurrent editor's exam kinds must not be silently reverted"
1055- );
1056- assert!(after.get_grade_bands().is_empty());
1057-
1058- // A's retry — reload, re-merge, save again — lands both edits.
1059- let fresh = Settings::load(&db).await.unwrap();
1060- let saved = Settings::try_new(SettingsParams {
1061- grade_bands: bands(&[(0, "F"), (50, "P")]),
1062- ..fresh.params()
1063- })
1064- .unwrap()
1065- .save_if_unchanged(&fresh, &db)
1066- .await
1067- .unwrap()
1068- .expect("a merge over the current row applies");
1069- assert_eq!(names(&saved), ["lab"]);
1070- assert_eq!(saved.get_grade_bands().len(), 2);
1071- }
1072-
1073- #[tokio::test]
1074- async fn save_if_unchanged_seeds_the_first_row() {
1075- let db = crate::database::init_mem().await.unwrap();
1076- // No row yet: `load` reports the defaults, and a save conditioned on
1077- // that snapshot must apply (seeding the singleton on the way).
1078- let current = Settings::load(&db).await.unwrap();
1079- let saved = Settings::try_new(SettingsParams {
1080- exam_kinds: kinds(&["lab"]),
1081- ..current.params()
1082- })
1083- .unwrap()
1084- .save_if_unchanged(&current, &db)
1085- .await
1086- .unwrap()
1087- .expect("the first save applies");
1088- assert_eq!(names(&saved), ["lab"]);
1089- let mut result = db.query("SELECT * FROM settings").await.unwrap();
1090- let rows: Vec<Settings> = result.take(0).unwrap();
1091- assert_eq!(rows.len(), 1, "still one singleton row");
1092- }
1093-
1094 #[tokio::test]831 #[tokio::test]
1095 async fn grade_label_picks_the_greatest_min_at_or_below() {832 async fn grade_label_picks_the_greatest_min_at_or_below() {
1096 let s = Settings::try_new(SettingsParams {833 let s = Settings::try_new(SettingsParams {
src/domain/user.rsmodified+4 -4
@@ -11,12 +11,12 @@ use crate::constant::{
11 REGISTRATION_FROZEN_GUARD, REGISTRATION_TABLE, USER_TABLE,11 REGISTRATION_FROZEN_GUARD, REGISTRATION_TABLE, USER_TABLE,
12 };12 };
13 use crate::database::{Database, transaction_with_retry, write_with_retry};13 use crate::database::{Database, transaction_with_retry, write_with_retry};
14+use crate::db::field_update::FieldUpdate;
15+use crate::db::page::PagedList;
14 use crate::domain::appointment::AppointmentStatus;16 use crate::domain::appointment::AppointmentStatus;
15 use crate::domain::board::Board;17 use crate::domain::board::Board;
16-use crate::db::field_update::FieldUpdate;
17 use crate::domain::monotonic_id::next_ulid;18 use crate::domain::monotonic_id::next_ulid;
18 use crate::domain::note_file::FileContentType;19 use crate::domain::note_file::FileContentType;
19-use crate::db::page::PagedList;
20 use crate::domain::preferences::{Language, PaletteColor, Theme};20 use crate::domain::preferences::{Language, PaletteColor, Theme};
21 use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone};21 use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone};
22 use crate::domain::role::Role;22 use crate::domain::role::Role;
@@ -39,7 +39,7 @@ use crate::validate::{validate_password, validate_username};
39 /// SurrealQL against the volume.39 /// SurrealQL against the volume.
40 ///40 ///
41 /// Serializing the pair is what closes it, the same argument41 /// Serializing the pair is what closes it, the same argument
42-/// [`crate::domain::settings::SETTINGS_LOCK`] makes one level up: the deployment42+/// [`crate::service::settings::SETTINGS_LOCK`] makes one level up: the deployment
43 /// runs one process by contract (stop-the-world upgrades), so process-wide is43 /// runs one process by contract (stop-the-world upgrades), so process-wide is
44 /// deployment-wide. A per-row counter (the [`crate::db::cap`] shape) does44 /// deployment-wide. A per-row counter (the [`crate::db::cap`] shape) does
45 /// not fit — the count being capped is over *every* user row, with no parent45 /// not fit — the count being capped is over *every* user row, with no parent
@@ -896,7 +896,7 @@ impl User {
896 /// (`POST /schools/{slug}/admin-password`). Only the credential is896 /// (`POST /schools/{slug}/admin-password`). Only the credential is
897 /// rewritten; revoking the sessions minted under the old one is the897 /// rewritten; revoking the sessions minted under the old one is the
898 /// caller's second half898 /// caller's second half
899- /// ([`crate::domain::session::Session::delete_by_user`]), because a reset899+ /// ([`crate::db::session::delete_by_user`]), because a reset
900 /// that leaves a stolen cookie working resets nothing.900 /// that leaves a stolen cookie working resets nothing.
901 pub async fn set_password_hash(901 pub async fn set_password_hash(
902 id: &UserId,902 id: &UserId,
src/lib.rsmodified+1 -0
@@ -8,6 +8,7 @@ pub mod error;
8 pub mod migration_sql;8 pub mod migration_sql;
9 pub mod module;9 pub mod module;
10 pub mod rate_limit;10 pub mod rate_limit;
11+pub mod service;
11 pub mod state;12 pub mod state;
12 pub mod telemetry;13 pub mod telemetry;
13 pub mod tenant;14 pub mod tenant;
src/service/mod.rsadded+6 -0
@@ -0,0 +1,6 @@
1+//! Business rules, workflow locks, multi-call orchestration; calls db::*; no
2+//! SurrealQL text.
3+
4+pub mod note;
5+pub mod session;
6+pub mod settings;
src/service/note.rsadded+54 -0
@@ -0,0 +1,54 @@
1+//! Note workflows: the create/read/list/update/delete paths the notes
2+//! surface drives, all scoped to the owning user. The queries live in
3+//! [`crate::db::note`]; blob unlinking stays in the web layer.
4+
5+use crate::database::Database;
6+use crate::db::note;
7+use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle};
8+use crate::domain::note_file::NoteFile;
9+use crate::domain::user::UserId;
10+use crate::error::AppError;
11+
12+pub async fn create(
13+ db: &Database,
14+ owner: &UserId,
15+ title: NoteTitle,
16+ content: NoteContent,
17+) -> Result<Note, AppError> {
18+ note::create(db, owner, title, content).await
19+}
20+
21+/// Read a note only if it belongs to `owner`.
22+pub async fn read_owned(
23+ db: &Database,
24+ id: &NoteId,
25+ owner: &UserId,
26+) -> Result<Option<Note>, AppError> {
27+ note::read_owned(db, id, owner).await
28+}
29+
30+pub async fn list_for(
31+ db: &Database,
32+ owner: &UserId,
33+ limit: Option<i64>,
34+ offset: i64,
35+) -> Result<(Vec<Note>, i64), AppError> {
36+ note::list_for(db, owner, limit, offset).await
37+}
38+
39+/// Only what the request carried is written: an omitted field (`None`) is
40+/// not stored at all, so a concurrent edit of the other field survives.
41+pub async fn update(
42+ db: &Database,
43+ note: Note,
44+ title: Option<NoteTitle>,
45+ content: Option<NoteContent>,
46+) -> Result<Note, AppError> {
47+ note::update(db, note, title, content).await
48+}
49+
50+/// Delete the note and cascade its attachment rows; the returned files are
51+/// exactly whose blobs the caller may unlink.
52+pub async fn delete(db: &Database, note: Note) -> Result<(Note, Vec<NoteFile>), AppError> {
53+ note::delete(db, note).await
54+}
src/service/session.rsadded+31 -0
@@ -0,0 +1,31 @@
1+//! Session workflows: mint on login, resolve per request, revoke on logout
2+//! and on password resets, sweep expired rows. The queries live in
3+//! [`crate::db::session`].
4+
5+use crate::database::Database;
6+use crate::db::session;
7+use crate::domain::session::Session;
8+use crate::domain::user::UserId;
9+use crate::error::AppError;
10+
11+pub async fn create(db: &Database, user: &UserId) -> Result<Session, AppError> {
12+ session::create(db, user).await
13+}
14+
15+pub async fn find_by_token(db: &Database, token: &str) -> Result<Option<Session>, AppError> {
16+ session::find_by_token(db, token).await
17+}
18+
19+pub async fn delete_by_token(db: &Database, token: &str) -> Result<(), AppError> {
20+ session::delete_by_token(db, token).await
21+}
22+
23+/// Revoke every session a user holds — the other half of a password reset.
24+pub async fn delete_by_user(db: &Database, user: &UserId) -> Result<(), AppError> {
25+ session::delete_by_user(db, user).await
26+}
27+
28+/// Drop expired rows; best-effort on the login path.
29+pub async fn purge_expired(db: &Database) -> Result<u64, AppError> {
30+ session::purge_expired(db).await
31+}
src/service/settings.rsadded+658 -0
@@ -0,0 +1,658 @@
1+//! The settings edit workflow: one edit at a time under [`SETTINGS_LOCK`],
2+//! a snapshot-merge-retire-save pair whose halves cannot interleave, and the
3+//! compare-and-set retry that keeps two managers' patches from silently
4+//! reverting each other. The singleton's queries live in
5+//! [`crate::db::settings`].
6+
7+use surrealdb::types::RecordId;
8+use tokio::sync::Mutex;
9+
10+use crate::constant::CAS_UPDATE_RETRIES;
11+use crate::database::Database;
12+use crate::db::cap;
13+use crate::domain::exam_result::kind_ref;
14+use crate::domain::menu::slot_ref;
15+use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings};
16+use crate::error::AppError;
17+
18+/// One settings edit at a time, over the whole process.
19+///
20+/// A list edit is a **pair** of writes, and the pair is the guard: every name
21+/// the edit drops is retired on its reference counter first (which refuses
22+/// every later claim), and only then is the list itself committed with a
23+/// compare-and-set against the snapshot the removals were judged from. Neither
24+/// write can be made to cover the other. Both retirement and un-retirement are
25+/// *idempotent*, so a rival that decided the same removal against the same
26+/// snapshot is told "already retired" and records no rollback — and when it is
27+/// that rival's save that wins the compare-and-set, the attempt which really
28+/// flipped the bit rolls it back, leaving the name off the stored list with a
29+/// counter reading "in service": gradable again, and unremovable for good once
30+/// a mark lands. No per-name bit can close that, because `Unchanged` has
31+/// erased which attempt owns the flip.
32+///
33+/// So the pair is serialized instead. Every writer of the singleton goes
34+/// through `PATCH /settings`, and the deployment runs one process by contract
35+/// (stop-the-world upgrades), so process-wide is deployment-wide here — the
36+/// same argument [`crate::db::cap`]'s own lock makes for `retire_name`'s
37+/// two statements, one level up. The compare-and-set stays: it is what keeps a
38+/// crashed or rolled-back attempt from writing a list nobody merged.
39+///
40+/// **Lock order:** `SETTINGS_LOCK` → `cap`'s `CLAIM_LOCK`, never the reverse —
41+/// the retirements are taken while this is held.
42+pub(crate) static SETTINGS_LOCK: Mutex<()> = Mutex::const_new(());
43+
44+/// The stored policy, or the defaults when no row exists yet.
45+pub async fn load(db: &Database) -> Result<Settings, AppError> {
46+ crate::db::settings::load(db).await
47+}
48+
49+/// Persist the policy only while the stored row still matches `expected` —
50+/// the compare-and-set. `None` means a concurrent edit landed in between:
51+/// reload, re-merge, retry.
52+pub async fn save_if_unchanged(
53+ db: &Database,
54+ settings: Settings,
55+ expected: &Settings,
56+) -> Result<Option<Settings>, AppError> {
57+ crate::db::settings::save_if_unchanged(db, settings, expected).await
58+}
59+
60+/// A `PATCH /settings` body after wire mapping: only the fields the school
61+/// sent. Lists stay raw on purpose — validating them is the workflow's own
62+/// step, in its own order, and keeping a stored meal-slot name skips the
63+/// URL-charset rule (`MealSlotDef::try_kept`), which only [`apply`], holding
64+/// the lock and the stored list, can decide.
65+pub struct SettingsPatch {
66+ pub exam_kinds: Option<Vec<ExamKindInput>>,
67+ pub attendance_statuses: Option<Vec<String>>,
68+ pub grade_bands: Option<Vec<GradeBandInput>>,
69+ pub max_file_bytes: Option<i64>,
70+ pub chatbot_history_turns: Option<i64>,
71+ pub max_chatbot_threads: Option<i64>,
72+ pub max_chatbot_message_len: Option<i64>,
73+ pub meal_slots: Option<Vec<MealSlotInput>>,
74+ pub dietary_tags: Option<Vec<String>>,
75+ /// Absent keeps the knob; `Some(None)` clears it (no cutoff at all).
76+ pub meal_cancel_cutoff_minutes: Option<Option<i64>>,
77+}
78+
79+/// One submitted exam kind, raw.
80+pub struct ExamKindInput {
81+ pub name: String,
82+ pub weight: i64,
83+}
84+
85+/// One submitted grade band, raw.
86+pub struct GradeBandInput {
87+ pub min: i64,
88+ pub label: String,
89+}
90+
91+/// One submitted meal slot, raw.
92+pub struct MealSlotInput {
93+ pub name: String,
94+ pub serving_minute: Option<i64>,
95+}
96+
97+/// The whole edit — snapshot, merge, retire, save — as one operation, so the
98+/// tests can drive it the way two managers do.
99+pub async fn apply(db: &Database, patch: &SettingsPatch) -> Result<Settings, AppError> {
100+ // One settings edit at a time: the removals below are decided against the
101+ // snapshot this loop loads and written *before* the save that justifies
102+ // them, and no per-name bookkeeping can make that pair survive a rival's
103+ // pair interleaving with it (see `SETTINGS_LOCK`).
104+ let _guard = SETTINGS_LOCK.lock().await;
105+ // Merge over a snapshot, then save only while the row still matches it —
106+ // otherwise a concurrent PATCH of a *different* field would be silently
107+ // reverted by whichever whole-row write lands second. A refused save
108+ // reloads and re-merges, so both edits land.
109+ for _ in 0..CAS_UPDATE_RETRIES {
110+ let current = load(db).await?;
111+
112+ let exam_kinds = match &patch.exam_kinds {
113+ Some(kinds) => kinds
114+ .iter()
115+ .map(|kind| ExamKindDef::try_new(&kind.name, kind.weight))
116+ .collect::<Result<Vec<_>, _>>()?,
117+ None => current.get_exam_kinds().to_vec(),
118+ };
119+ let was_slots = slot_names(&current.get_meal_slots());
120+ let meal_slots = match &patch.meal_slots {
121+ Some(slots) => slots
122+ .iter()
123+ .map(|slot| {
124+ // A name the row already carries is validated as a kept one:
125+ // the charset rule is younger than the stored lists, and
126+ // re-validating one under it would leave a school unable to
127+ // edit the rest of its slots at all (`MealSlotDef::try_kept`).
128+ if was_slots.iter().any(|kept| kept == slot.name.trim()) {
129+ MealSlotDef::try_kept(&slot.name, slot.serving_minute)
130+ } else {
131+ MealSlotDef::try_new(&slot.name, slot.serving_minute)
132+ }
133+ })
134+ .collect::<Result<Vec<_>, _>>()?,
135+ None => current.get_meal_slots(),
136+ };
137+ let attendance_statuses = patch
138+ .attendance_statuses
139+ .clone()
140+ .unwrap_or_else(|| current.get_attendance_statuses().to_vec());
141+ let grade_bands = match &patch.grade_bands {
142+ Some(bands) => bands
143+ .iter()
144+ .map(|band| GradeBand::try_new(band.min, &band.label))
145+ .collect::<Result<Vec<_>, _>>()?,
146+ None => current.get_grade_bands().to_vec(),
147+ };
148+ // The name lists as they stand and as they would stand, for the removal
149+ // guards below — a list edit is judged by which names it drops.
150+ let was_kinds = kind_names(current.get_exam_kinds());
151+ let now_kinds = kind_names(&exam_kinds);
152+ let now_slots = slot_names(&meal_slots);
153+
154+ // Merge over the snapshot's resolved values: an omitted field keeps
155+ // whatever the row (or the default behind an unset field) reads as.
156+ let mut params = current.params();
157+ params.exam_kinds = exam_kinds;
158+ params.attendance_statuses = attendance_statuses;
159+ params.grade_bands = grade_bands;
160+ params.max_file_bytes = patch.max_file_bytes.unwrap_or(params.max_file_bytes);
161+ params.chatbot_history_turns = patch
162+ .chatbot_history_turns
163+ .unwrap_or(params.chatbot_history_turns);
164+ params.max_chatbot_threads = patch
165+ .max_chatbot_threads
166+ .unwrap_or(params.max_chatbot_threads);
167+ params.max_chatbot_message_len = patch
168+ .max_chatbot_message_len
169+ .unwrap_or(params.max_chatbot_message_len);
170+ params.meal_slots = meal_slots;
171+ params.dietary_tags = patch
172+ .dietary_tags
173+ .clone()
174+ .unwrap_or_else(|| current.get_dietary_tags());
175+ // Double option: absent keeps the knob, `null` clears it (no cutoff).
176+ params.meal_cancel_cutoff_minutes = patch
177+ .meal_cancel_cutoff_minutes
178+ .unwrap_or(params.meal_cancel_cutoff_minutes);
179+
180+ let settings = Settings::try_new(params)?;
181+
182+ // The removal guards. A name leaves a list by being *retired* on its
183+ // reference counter — one conditional write on one record, which lands
184+ // only while nothing references the name and refuses every claim from
185+ // that instant on. That is the whole guard: the check and the removal
186+ // used to be a cross-table count and a save held together by a
187+ // process-wide lock that was released around the round trip between
188+ // them.
189+ //
190+ // Retired before the save, never after: the other order leaves a window
191+ // in which a mark lands under a kind the settings no longer list. A save
192+ // that then does not land undoes them (`restore`) before the next try.
193+ //
194+ // Only a write that actually *flipped* a bit is recorded for that undo.
195+ // Retirement is idempotent, so two PATCHes dropping the same kind are
196+ // both told "retired" — and the one whose save then loses the row's CAS
197+ // used to un-retire the winner's kind, leaving it off the list with its
198+ // counter in service: gradable again, its count then non-zero, and so
199+ // impossible to remove ever after.
200+ let mut undo: Vec<Undo> = Vec::new();
201+ let mut refused = None;
202+ for gone in missing(&was_kinds, &now_kinds) {
203+ let counter = kind_ref(&gone);
204+ match cap::retire_name(&counter, db).await? {
205+ cap::Switched::Flipped => undo.push(Undo::Retired(counter)),
206+ cap::Switched::Unchanged => {}
207+ cap::Switched::InUse => {
208+ refused = Some(AppError::ConflictOwned(format!(
209+ "exams of kind '{gone}' are already graded — the kind cannot be removed"
210+ )));
211+ break;
212+ }
213+ }
214+ }
215+ // Same shape for meal slots: a slot a menu was already published for
216+ // cannot leave the list — the menu snapshotted the name as text, and a
217+ // slot no longer offered would leave that menu unreachable from the
218+ // school's own list.
219+ if refused.is_none() {
220+ for gone in missing(&was_slots, &now_slots) {
221+ let counter = slot_ref(&gone);
222+ match cap::retire_name(&counter, db).await? {
223+ cap::Switched::Flipped => undo.push(Undo::Retired(counter)),
224+ cap::Switched::Unchanged => {}
225+ cap::Switched::InUse => {
226+ refused = Some(AppError::ConflictOwned(format!(
227+ "menus are already published for the '{gone}' slot — it cannot be removed"
228+ )));
229+ break;
230+ }
231+ }
232+ }
233+ }
234+ if let Some(refused) = refused {
235+ restore(&undo, db).await?;
236+ return Err(refused);
237+ }
238+ // A name re-entering a list is back in service: its counter still
239+ // carries the retirement from the edit that dropped it, and a mark (or
240+ // a menu) under a kind the school offers again must not be refused.
241+ // Recorded for the same undo as the retirements — a re-add whose save
242+ // does not land leaves a name off the list that grades happily.
243+ for back in missing(&now_kinds, &was_kinds) {
244+ if let cap::Switched::Flipped = cap::unretire_name(&kind_ref(&back), db).await? {
245+ undo.push(Undo::Unretired(kind_ref(&back)));
246+ }
247+ }
248+ for back in missing(&now_slots, &was_slots) {
249+ if let cap::Switched::Flipped = cap::unretire_name(&slot_ref(&back), db).await? {
250+ undo.push(Undo::Unretired(slot_ref(&back)));
251+ }
252+ }
253+
254+ match save_if_unchanged(db, settings, &current).await {
255+ Ok(Some(saved)) => return Ok(saved),
256+ // The row moved under the snapshot these guards were judged against:
257+ // put the names back and re-merge, or the next attempt would decide
258+ // against a list nobody asked for.
259+ Ok(None) => restore(&undo, db).await?,
260+ Err(err) => {
261+ restore(&undo, db).await?;
262+ return Err(err);
263+ }
264+ }
265+ }
266+ Err(AppError::Conflict(
267+ "the settings kept changing underneath this update — try again",
268+ ))
269+}
270+
271+fn kind_names(kinds: &[ExamKindDef]) -> Vec<String> {
272+ kinds
273+ .iter()
274+ .map(|kind| kind.get_name().to_string())
275+ .collect()
276+}
277+
278+fn slot_names(slots: &[MealSlotDef]) -> Vec<String> {
279+ slots
280+ .iter()
281+ .map(|slot| slot.get_name().to_string())
282+ .collect()
283+}
284+
285+/// The names `before` carries that `after` does not — a list edit's removals,
286+/// or its additions with the arguments swapped.
287+fn missing(before: &[String], after: &[String]) -> Vec<String> {
288+ before
289+ .iter()
290+ .filter(|name| !after.contains(name))
291+ .cloned()
292+ .collect()
293+}
294+
295+/// One `retired` bit this attempt moved, and which way — what `restore` needs
296+/// to put it back. Only bits this attempt actually *flipped* are listed: a
297+/// write that changed nothing has nothing to take back, and taking it back
298+/// would undo the concurrent edit that really did move it.
299+enum Undo {
300+ /// Retired for a removal; put it back in service.
301+ Retired(RecordId),
302+ /// Put back in service for a re-add; retire it again.
303+ Unretired(RecordId),
304+}
305+
306+/// Undo every bit this attempt moved: the edit that justified them did not
307+/// land, so the lists the school offers are still the ones it started with.
308+async fn restore(undo: &[Undo], db: &Database) -> Result<(), AppError> {
309+ for step in undo {
310+ match step {
311+ Undo::Retired(name) => {
312+ cap::unretire_name(name, db).await?;
313+ }
314+ // A re-retirement can be refused: a mark (or a menu) landed under
315+ // the name during the window it was in service. Refusing to undo is
316+ // then the honest answer — the reference is real, and retiring over
317+ // it would make the row's kind ungradable while nothing lists it.
318+ // The name is left in service, matching the list this attempt is
319+ // about to re-read.
320+ Undo::Unretired(name) => {
321+ cap::retire_name(name, db).await?;
322+ }
323+ }
324+ }
325+ Ok(())
326+}
327+
328+#[cfg(test)]
329+mod tests {
330+ use super::*;
331+ use crate::database::init_mem;
332+ use crate::db::settings::save;
333+
334+ /// The `retired` bit as the store holds it, `None` when no counter row was
335+ /// ever written — read back, never inferred from a return value.
336+ async fn bit(db: &Database, counter: RecordId) -> Option<bool> {
337+ let mut result = db
338+ .query("SELECT VALUE retired FROM $id")
339+ .bind(("id", counter))
340+ .await
341+ .unwrap()
342+ .check()
343+ .unwrap();
344+ result.take::<Vec<bool>>(0).unwrap().first().copied()
345+ }
346+
347+ /// Two managers drop the same exam kind at once; one of them loses the
348+ /// row's compare-and-set and rolls its attempt back. The winner's
349+ /// retirement must survive that rollback — undone, the kind is off the list
350+ /// with a counter that still grades, and the first mark to land makes it
351+ /// unremovable for good.
352+ ///
353+ /// The loser's half is what runs here: a retirement that changed nothing
354+ /// records no undo, so `restore` has nothing to take back.
355+ #[tokio::test]
356+ async fn the_loser_of_a_settings_race_cannot_un_retire_the_winner_s_kind() {
357+ let db = init_mem().await.unwrap();
358+ let counter = kind_ref("midterm");
359+
360+ // The winner's PATCH retires the kind.
361+ assert!(matches!(
362+ cap::retire_name(&counter, &db).await.unwrap(),
363+ cap::Switched::Flipped
364+ ));
365+
366+ // The loser's PATCH decides the same removal against the same snapshot,
367+ // then its save is refused.
368+ let mut undo = Vec::new();
369+ if let cap::Switched::Flipped = cap::retire_name(&counter, &db).await.unwrap() {
370+ undo.push(Undo::Retired(counter.clone()));
371+ }
372+ assert!(undo.is_empty(), "a no-op retirement records no undo");
373+ restore(&undo, &db).await.unwrap();
374+
375+ assert_eq!(
376+ bit(&db, counter).await,
377+ Some(true),
378+ "the winner's retirement must outlive the loser's rollback"
379+ );
380+ }
381+
382+ /// The mirror hole: a re-*added* name is put back in service before the
383+ /// save, so a save that does not land owes a re-retirement. Without it the
384+ /// name is off the stored list with a counter that grades happily.
385+ #[tokio::test]
386+ async fn a_rollback_re_retires_a_name_this_attempt_put_back_in_service() {
387+ let db = init_mem().await.unwrap();
388+ let counter = slot_ref("lunch");
389+ cap::retire_name(&counter, &db).await.unwrap();
390+
391+ // The attempt re-adds the slot, then its save is refused.
392+ let mut undo = Vec::new();
393+ if let cap::Switched::Flipped = cap::unretire_name(&counter, &db).await.unwrap() {
394+ undo.push(Undo::Unretired(counter.clone()));
395+ }
396+ assert_eq!(undo.len(), 1, "a real un-retirement is undoable");
397+ restore(&undo, &db).await.unwrap();
398+
399+ assert_eq!(
400+ bit(&db, counter).await,
401+ Some(true),
402+ "a re-add that never landed must leave the slot retired"
403+ );
404+ }
405+
406+ /// ...unless a menu was published in the window the slot was back in
407+ /// service. The reference is real, so the re-retirement is refused and the
408+ /// slot stays usable — the honest end of the same rule, not a silent
409+ /// overwrite of a live reference.
410+ #[tokio::test]
411+ async fn a_rollback_leaves_a_name_that_gained_a_reference_in_service() {
412+ let db = init_mem().await.unwrap();
413+ let counter = slot_ref("lunch");
414+ cap::retire_name(&counter, &db).await.unwrap();
415+ cap::unretire_name(&counter, &db).await.unwrap();
416+ db.query("UPDATE $id SET count = 1")
417+ .bind(("id", counter.clone()))
418+ .await
419+ .unwrap()
420+ .check()
421+ .unwrap();
422+
423+ restore(&[Undo::Unretired(counter.clone())], &db)
424+ .await
425+ .unwrap();
426+
427+ assert_eq!(bit(&db, counter).await, Some(false));
428+ }
429+
430+ // --- the whole edit, driven the way two managers drive it -------------
431+
432+ /// A `PATCH` body that names nothing: every field keeps the stored value.
433+ fn a_patch() -> SettingsPatch {
434+ SettingsPatch {
435+ exam_kinds: None,
436+ attendance_statuses: None,
437+ grade_bands: None,
438+ max_file_bytes: None,
439+ chatbot_history_turns: None,
440+ max_chatbot_threads: None,
441+ max_chatbot_message_len: None,
442+ meal_slots: None,
443+ dietary_tags: None,
444+ meal_cancel_cutoff_minutes: None,
445+ }
446+ }
447+
448+ /// An `exam_kinds` list as the router builds it (weight 1, like the
449+ /// harness bodies).
450+ fn kinds(names: &[&str]) -> Vec<ExamKindInput> {
451+ names
452+ .iter()
453+ .map(|name| ExamKindInput {
454+ name: (*name).to_string(),
455+ weight: 1,
456+ })
457+ .collect()
458+ }
459+
460+ /// A `meal_slots` list as the router builds it (no serving minute).
461+ fn slots(names: &[&str]) -> Vec<MealSlotInput> {
462+ names
463+ .iter()
464+ .map(|name| MealSlotInput {
465+ name: (*name).to_string(),
466+ serving_minute: None,
467+ })
468+ .collect()
469+ }
470+
471+ /// The lists as the store holds them.
472+ async fn stored(db: &Database) -> (Vec<String>, Vec<String>) {
473+ let settings = load(db).await.unwrap();
474+ (
475+ kind_names(settings.get_exam_kinds()),
476+ slot_names(&settings.get_meal_slots()),
477+ )
478+ }
479+
480+ /// The whole invariant, over the reachable half of the race: two managers
481+ /// drop the same exam kind at once, both edits go through the real path,
482+ /// and when both have returned the counter's `retired` bit must agree with
483+ /// the list the store actually holds.
484+ ///
485+ /// One of the two decides the removal, retires the kind and saves; the
486+ /// other cannot even see the old list, because the whole snapshot-retire-
487+ /// save pair is serialized (`SETTINGS_LOCK`). Interleaved, the second
488+ /// attempt would be told "already retired", record no undo, win the
489+ /// compare-and-set, and leave the first attempt un-retiring the kind it had
490+ /// legitimately removed — off the list and gradable.
491+ #[tokio::test]
492+ async fn two_edits_dropping_the_same_kind_leave_it_retired() {
493+ let db = init_mem().await.unwrap();
494+ let without = SettingsPatch {
495+ exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])),
496+ ..a_patch()
497+ };
498+
499+ let (a, b) = tokio::join!(apply(&db, &without), apply(&db, &without));
500+ a.unwrap();
501+ b.unwrap();
502+
503+ let (kinds, _) = stored(&db).await;
504+ assert!(
505+ !kinds.contains(&"midterm".to_string()),
506+ "dropped from the list"
507+ );
508+ assert_eq!(
509+ bit(&db, kind_ref("midterm")).await,
510+ Some(true),
511+ "a kind the stored list no longer offers must not grade"
512+ );
513+ }
514+
515+ /// The property those two outcomes rest on, asserted on its own because a
516+ /// `join!` cannot be made to schedule the losing order: the edit is a pair
517+ /// of writes — retire the dropped names, then commit the list — and no
518+ /// rival's pair may run between them.
519+ ///
520+ /// Retirement is idempotent, so an interleaved rival is told "already
521+ /// retired", records no rollback, wins the compare-and-set, and leaves the
522+ /// attempt that really flipped the bit un-retiring a kind the stored list
523+ /// no longer offers: gradable again, and unremovable for good once a mark
524+ /// lands. Holding the lock stands in for a rival mid-pair here — nothing
525+ /// the other edit does may be visible until the pair completes.
526+ #[tokio::test]
527+ async fn a_rival_edit_cannot_run_between_a_retirement_and_its_save() {
528+ let db = init_mem().await.unwrap();
529+ let without = SettingsPatch {
530+ exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])),
531+ ..a_patch()
532+ };
533+
534+ let held = SETTINGS_LOCK.lock().await;
535+ let rival = tokio::spawn({
536+ let db = db.clone();
537+ async move { apply(&db, &without).await.map(|_| ()) }
538+ });
539+ tokio::time::sleep(std::time::Duration::from_millis(200)).await;
540+
541+ assert_eq!(
542+ bit(&db, kind_ref("midterm")).await,
543+ None,
544+ "a rival's pair must not have started, let alone half-landed"
545+ );
546+ assert!(stored(&db).await.0.contains(&"midterm".to_string()));
547+
548+ drop(held);
549+ rival.await.unwrap().unwrap();
550+ assert_eq!(bit(&db, kind_ref("midterm")).await, Some(true));
551+ assert!(!stored(&db).await.0.contains(&"midterm".to_string()));
552+ }
553+
554+ /// The mirror: two managers put the same kind *back* at once. The attempt
555+ /// that loses must not re-retire a name the winner's stored list carries —
556+ /// a listed kind that refuses every grade.
557+ #[tokio::test]
558+ async fn two_edits_re_adding_the_same_kind_leave_it_in_service() {
559+ let db = init_mem().await.unwrap();
560+ let without = SettingsPatch {
561+ exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])),
562+ ..a_patch()
563+ };
564+ apply(&db, &without).await.unwrap();
565+ let with = SettingsPatch {
566+ exam_kinds: Some(kinds(&[
567+ "homework", "quiz", "midterm", "final", "project", "oral",
568+ ])),
569+ ..a_patch()
570+ };
571+
572+ let (a, b) = tokio::join!(apply(&db, &with), apply(&db, &with));
573+ a.unwrap();
574+ b.unwrap();
575+
576+ let (kinds, _) = stored(&db).await;
577+ assert!(kinds.contains(&"midterm".to_string()), "back on the list");
578+ assert_eq!(
579+ bit(&db, kind_ref("midterm")).await,
580+ Some(false),
581+ "a kind the stored list offers must grade"
582+ );
583+ }
584+
585+ /// The same pair over meal slots, which retire on their own counters.
586+ #[tokio::test]
587+ async fn two_edits_dropping_the_same_slot_leave_it_retired() {
588+ let db = init_mem().await.unwrap();
589+ let without = SettingsPatch {
590+ meal_slots: Some(slots(&["breakfast", "snack"])),
591+ ..a_patch()
592+ };
593+
594+ let (a, b) = tokio::join!(apply(&db, &without), apply(&db, &without));
595+ a.unwrap();
596+ b.unwrap();
597+
598+ let (_, stored_slots) = stored(&db).await;
599+ assert!(!stored_slots.contains(&"lunch".to_string()));
600+ assert_eq!(bit(&db, slot_ref("lunch")).await, Some(true));
601+ }
602+
603+ // --- the stale slot name that wedged the whole list -------------------
604+
605+ /// A school that stored `a/b` before the URL-safety rule existed.
606+ async fn a_school_with_a_stale_slot(db: &Database) {
607+ let mut params = Settings::defaults().params();
608+ params.meal_slots = vec![
609+ MealSlotDef::try_kept("a/b", None).unwrap(),
610+ MealSlotDef::try_new("lunch", None).unwrap(),
611+ ];
612+ save(db, Settings::try_new(params).unwrap()).await.unwrap();
613+ }
614+
615+ /// The wedge: re-sending a stored name is the only way to *keep* it, and
616+ /// dropping it 409s once a menu references it — so validating it under the
617+ /// younger rule locks the school out of its own `meal_slots` forever. A
618+ /// stored name is submittable; a new one with the same characters is not.
619+ #[tokio::test]
620+ async fn a_stored_slot_name_stays_submittable_but_a_new_one_does_not() {
621+ let db = init_mem().await.unwrap();
622+ a_school_with_a_stale_slot(&db).await;
623+
624+ let edit = SettingsPatch {
625+ meal_slots: Some(slots(&["a/b", "lunch", "dinner"])),
626+ ..a_patch()
627+ };
628+ apply(&db, &edit).await.unwrap();
629+ let (_, stored_slots) = stored(&db).await;
630+ assert_eq!(stored_slots, ["a/b", "lunch", "dinner"]);
631+
632+ let fresh = SettingsPatch {
633+ meal_slots: Some(slots(&["a/b", "lunch", "c/d"])),
634+ ..a_patch()
635+ };
636+ assert!(
637+ apply(&db, &fresh).await.is_err(),
638+ "a name no school ever stored is still refused"
639+ );
640+ }
641+
642+ /// And an edit that never mentions `meal_slots` still carries the list
643+ /// over unvalidated — the behaviour the wedge report leaned on.
644+ #[tokio::test]
645+ async fn an_unrelated_edit_carries_a_stale_slot_name_over() {
646+ let db = init_mem().await.unwrap();
647+ a_school_with_a_stale_slot(&db).await;
648+
649+ let elsewhere = SettingsPatch {
650+ max_file_bytes: Some(2048),
651+ ..a_patch()
652+ };
653+ let saved = apply(&db, &elsewhere).await.unwrap();
654+
655+ assert_eq!(saved.get_max_file_bytes(), 2048);
656+ assert_eq!(slot_names(&saved.get_meal_slots()), ["a/b", "lunch"]);
657+ }
658+}
src/web/auth.rsmodified+4 -4
@@ -12,10 +12,10 @@ use utoipa_axum::routes;
12 use crate::constant::{RESERVED_USERNAMES, SESSION_DURATION_DAYS};12 use crate::constant::{RESERVED_USERNAMES, SESSION_DURATION_DAYS};
13 use crate::domain::builder::BuilderSession;13 use crate::domain::builder::BuilderSession;
14 use crate::domain::role::Role as DomainRole;14 use crate::domain::role::Role as DomainRole;
15-use crate::domain::session::Session;
16 use crate::domain::user::{Password, PasswordHash, User, Username};15 use crate::domain::user::{Password, PasswordHash, User, Username};
17 use crate::error::{AppError, ErrorResponse, ValidationError};16 use crate::error::{AppError, ErrorResponse, ValidationError};
18 use crate::rate_limit::{RateLimitConfig, RateLimiter};17 use crate::rate_limit::{RateLimitConfig, RateLimiter};
18+use crate::service;
19 use crate::state::AppState;19 use crate::state::AppState;
20 use crate::tenant::Slug;20 use crate::tenant::Slug;
21 21
@@ -194,9 +194,9 @@ async fn login(
194 };194 };
195 195
196 // The caller is genuine; opportunistically drop any expired session rows.196 // The caller is genuine; opportunistically drop any expired session rows.
197- let _ = Session::purge_expired(&db).await;197+ let _ = service::session::purge_expired(&db).await;
198 198
199- let session = Session::create(user.get_id(), &db).await?;199+ let session = service::session::create(&db, user.get_id()).await?;
200 // `<slug>.<token>`: the cookie carries the school, so every later request200 // `<slug>.<token>`: the cookie carries the school, so every later request
201 // finds its database without a second lookup path that could disagree.201 // finds its database without a second lookup path that could disagree.
202 let cookie = session_cookie(202 let cookie = session_cookie(
@@ -245,7 +245,7 @@ async fn logout(
245 } else if let Ok(slug) = Slug::try_new(prefix)245 } else if let Ok(slug) = Slug::try_new(prefix)
246 && let Ok(db) = st.tenants.get(&slug).await246 && let Ok(db) = st.tenants.get(&slug).await
247 {247 {
248- Session::delete_by_token(token, &db).await?;248+ service::session::delete_by_token(&db, token).await?;
249 }249 }
250 }250 }
251 let jar = jar.remove(Cookie::build(("session", "")).path("/").build());251 let jar = jar.remove(Cookie::build(("session", "")).path("/").build());
src/web/builder.rsmodified+3 -3
@@ -28,11 +28,11 @@ use utoipa_axum::routes;
28 use crate::constant::MAX_SCHOOL_NAME_LEN;28 use crate::constant::MAX_SCHOOL_NAME_LEN;
29 use crate::domain::builder::{Builder, BuilderSession};29 use crate::domain::builder::{Builder, BuilderSession};
30 use crate::domain::role::Role;30 use crate::domain::role::Role;
31-use crate::domain::session::Session;
32 use crate::domain::user::{Password, PasswordHash, User, Username};31 use crate::domain::user::{Password, PasswordHash, User, Username};
33 use crate::error::{AppError, ErrorResponse, ValidationError};32 use crate::error::{AppError, ErrorResponse, ValidationError};
34 use crate::module::{Module, ModuleSet, Package};33 use crate::module::{Module, ModuleSet, Package};
35 use crate::rate_limit::{RateLimitConfig, RateLimiter};34 use crate::rate_limit::{RateLimitConfig, RateLimiter};
35+use crate::service;
36 use crate::state::AppState;36 use crate::state::AppState;
37 use crate::tenant::{School, SchoolStatus, Slug};37 use crate::tenant::{School, SchoolStatus, Slug};
38 use crate::validate::validate_required;38 use crate::validate::validate_required;
@@ -759,7 +759,7 @@ async fn reset_admin_password(
759 .ok_or(AppError::NotFound)?;759 .ok_or(AppError::NotFound)?;
760 // The other half: the new password means nothing while a cookie minted760 // The other half: the new password means nothing while a cookie minted
761 // under the old one still authenticates.761 // under the old one still authenticates.
762- Session::delete_by_user(user.get_id(), &db).await?;762+ service::session::delete_by_user(&db, user.get_id()).await?;
763 Ok(StatusCode::NO_CONTENT)763 Ok(StatusCode::NO_CONTENT)
764 }764 }
765 765
@@ -798,7 +798,7 @@ async fn enter_school(
798 }798 }
799 let user = school_admin(&req.username, &db).await?;799 let user = school_admin(&req.username, &db).await?;
800 800
801- let session = Session::create(user.get_id(), &db).await?;801+ let session = service::session::create(&db, user.get_id()).await?;
802 let cookie = session_cookie(802 let cookie = session_cookie(
803 format!("{slug}.{}", session.token().as_str()),803 format!("{slug}.{}", session.token().as_str()),
804 st.cookie_secure,804 st.cookie_secure,
src/web/chatbot.rsmodified+2 -1
@@ -49,6 +49,7 @@ use crate::domain::role::Role;
49 use crate::domain::settings::Settings;49 use crate::domain::settings::Settings;
50 use crate::domain::user::UserId;50 use crate::domain::user::UserId;
51 use crate::error::{AppError, ErrorResponse, ValidationError};51 use crate::error::{AppError, ErrorResponse, ValidationError};
52+use crate::service;
52 use crate::state::{AppState, scoped_key};53 use crate::state::{AppState, scoped_key};
53 54
54 use super::{CurrentUser, Page, PageParams};55 use super::{CurrentUser, Page, PageParams};
@@ -388,7 +389,7 @@ async fn send_message(
388 .enforce_user(&scoped_key(&slug, user.get_id().key()))?;389 .enforce_user(&scoped_key(&slug, user.get_id().key()))?;
389 390
390 let thread = own_thread(&id, user.get_id(), &st.db).await?;391 let thread = own_thread(&id, user.get_id(), &st.db).await?;
391- let settings = Settings::load(&st.db).await?;392+ let settings = service::settings::load(&st.db).await?;
392 let reply_cap = content_cap(&settings);393 let reply_cap = content_cap(&settings);
393 let length = req.content.chars().count();394 let length = req.content.chars().count();
394 if length > reply_cap {395 if length > reply_cap {
src/web/course_notes.rsmodified+2 -2
@@ -25,8 +25,8 @@ use crate::domain::course_note_file::{
25 CourseNoteFile, CourseNoteFileId, FileContentType, FileName,25 CourseNoteFile, CourseNoteFileId, FileContentType, FileName,
26 };26 };
27 use crate::domain::rag_output::{RagOutput, RagOutputId};27 use crate::domain::rag_output::{RagOutput, RagOutputId};
28-use crate::domain::settings::Settings;
29 use crate::error::{AppError, ErrorResponse};28 use crate::error::{AppError, ErrorResponse};
29+use crate::service;
30 use crate::state::AppState;30 use crate::state::AppState;
31 31
32 use super::courses::{can_manage_course, can_view_course};32 use super::courses::{can_manage_course, can_view_course};
@@ -381,7 +381,7 @@ async fn upload_file(
381 course.require_open(&st.db).await?;381 course.require_open(&st.db).await?;
382 // The 10-file cap is enforced inside `CourseNoteFile::insert` (count and382 // The 10-file cap is enforced inside `CourseNoteFile::insert` (count and
383 // create under one lock) — checking it here too would just race.383 // create under one lock) — checking it here too would just race.
384- let limit = Settings::load(&st.db).await?.get_max_file_bytes();384+ let limit = service::settings::load(&st.db).await?.get_max_file_bytes();
385 385
386 let upload = read_upload(&mut multipart, limit).await?;386 let upload = read_upload(&mut multipart, limit).await?;
387 let name = FileName::try_new(&upload.name.unwrap_or_default())?;387 let name = FileName::try_new(&upload.name.unwrap_or_default())?;
src/web/courses.rsmodified+2 -2
@@ -23,11 +23,11 @@ use crate::domain::homework::{Homework, HomeworkTitle};
23 use crate::domain::homework_file::HomeworkFile;23 use crate::domain::homework_file::HomeworkFile;
24 use crate::domain::question_image::QuestionImage;24 use crate::domain::question_image::QuestionImage;
25 use crate::domain::role::Role;25 use crate::domain::role::Role;
26-use crate::domain::settings::Settings;
27 use crate::domain::subject::{Subject, SubjectDescription, SubjectName};26 use crate::domain::subject::{Subject, SubjectDescription, SubjectName};
28 use crate::domain::timestamp::Timestamp;27 use crate::domain::timestamp::Timestamp;
29 use crate::domain::user::{User, UserId};28 use crate::domain::user::{User, UserId};
30 use crate::error::{AppError, ErrorResponse, ValidationError};29 use crate::error::{AppError, ErrorResponse, ValidationError};
30+use crate::service;
31 use crate::state::AppState;31 use crate::state::AppState;
32 32
33 use super::homework::{description_or_none, resolve_assigned};33 use super::homework::{description_or_none, resolve_assigned};
@@ -896,7 +896,7 @@ async fn create_exam_in_course(
896 896
897 let title = ExamTitle::try_new(&req.title)?;897 let title = ExamTitle::try_new(&req.title)?;
898 let description = ExamDescription::try_new(&req.description.unwrap_or_default())?;898 let description = ExamDescription::try_new(&req.description.unwrap_or_default())?;
899- let school = Settings::load(&st.db).await?;899+ let school = service::settings::load(&st.db).await?;
900 let kind = ExamKind::try_new(&req.kind, school.get_exam_kinds())?;900 let kind = ExamKind::try_new(&req.kind, school.get_exam_kinds())?;
901 let starts_at = req.starts_at.map(Timestamp::from_millis);901 let starts_at = req.starts_at.map(Timestamp::from_millis);
902 let ends_at = req.ends_at.map(Timestamp::from_millis);902 let ends_at = req.ends_at.map(Timestamp::from_millis);
src/web/events.rsmodified+2 -2
@@ -16,10 +16,10 @@ use crate::domain::course::{Course, CourseId};
16 use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle};16 use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle};
17 use crate::domain::registration::Registration;17 use crate::domain::registration::Registration;
18 use crate::domain::role::Role;18 use crate::domain::role::Role;
19-use crate::domain::settings::Settings;
20 use crate::domain::timestamp::Timestamp;19 use crate::domain::timestamp::Timestamp;
21 use crate::domain::user::{User, UserId};20 use crate::domain::user::{User, UserId};
22 use crate::error::{AppError, ErrorResponse, ValidationError};21 use crate::error::{AppError, ErrorResponse, ValidationError};
22+use crate::service;
23 use crate::state::AppState;23 use crate::state::AppState;
24 24
25 use super::{25 use super::{
@@ -509,7 +509,7 @@ async fn mark(
509 .await?509 .await?
510 .ok_or(AppError::NotFound)?;510 .ok_or(AppError::NotFound)?;
511 511
512- let school = Settings::load(&st.db).await?;512+ let school = service::settings::load(&st.db).await?;
513 let status = AttendanceStatus::try_new(&req.status, school.get_attendance_statuses())?;513 let status = AttendanceStatus::try_new(&req.status, school.get_attendance_statuses())?;
514 let target = match req.user_id {514 let target = match req.user_id {
515 Some(ref key) => UserId::from_key(key),515 Some(ref key) => UserId::from_key(key),
src/web/exams/mod.rsmodified+3 -3
@@ -32,10 +32,10 @@ use crate::domain::exam_result::{ExamResult, Mark};
32 use crate::domain::note_file::FileContentType;32 use crate::domain::note_file::FileContentType;
33 use crate::domain::question_image::QuestionImage;33 use crate::domain::question_image::QuestionImage;
34 use crate::domain::role::Role;34 use crate::domain::role::Role;
35-use crate::domain::settings::Settings;
36 use crate::domain::timestamp::Timestamp;35 use crate::domain::timestamp::Timestamp;
37 use crate::domain::user::{User, UserId};36 use crate::domain::user::{User, UserId};
38 use crate::error::{AppError, ErrorResponse, ValidationError};37 use crate::error::{AppError, ErrorResponse, ValidationError};
38+use crate::service;
39 use crate::state::AppState;39 use crate::state::AppState;
40 40
41 use super::bank_questions::BankQuestionResponse;41 use super::bank_questions::BankQuestionResponse;
@@ -448,7 +448,7 @@ async fn update_exam(
448 // a stored kind survives later list edits, like past times survive448 // a stored kind survives later list edits, like past times survive
449 // the no-past rule.449 // the no-past rule.
450 Some(ref kind) => {450 Some(ref kind) => {
451- let school = Settings::load(&st.db).await?;451+ let school = service::settings::load(&st.db).await?;
452 ExamKind::try_new(kind, school.get_exam_kinds())?452 ExamKind::try_new(kind, school.get_exam_kinds())?
453 }453 }
454 None => exam.get_kind().clone(),454 None => exam.get_kind().clone(),
@@ -691,7 +691,7 @@ async fn grade(
691 // also a mark that averages at weight 1 forever. Both gates, same answer;691 // also a mark that averages at weight 1 forever. Both gates, same answer;
692 // this one is a read, the counter's is the one that survives a race.692 // this one is a read, the counter's is the one that survives a race.
693 let kind = exam.get_kind().as_str();693 let kind = exam.get_kind().as_str();
694- if !Settings::load(&st.db)694+ if !service::settings::load(&st.db)
695 .await?695 .await?
696 .get_exam_kinds()696 .get_exam_kinds()
697 .iter()697 .iter()
src/web/extractor.rsmodified+2 -2
@@ -5,9 +5,9 @@ use axum_extra::extract::CookieJar;
5 use crate::database::Database;5 use crate::database::Database;
6 use crate::domain::builder::{Builder, BuilderSession};6 use crate::domain::builder::{Builder, BuilderSession};
7 use crate::domain::role::Role;7 use crate::domain::role::Role;
8-use crate::domain::session::Session;
9 use crate::domain::user::User;8 use crate::domain::user::User;
10 use crate::error::AppError;9 use crate::error::AppError;
10+use crate::service;
11 use crate::state::AppState;11 use crate::state::AppState;
12 use crate::web::tenant_state::{resolve_tenant, split_cookie};12 use crate::web::tenant_state::{resolve_tenant, split_cookie};
13 13
@@ -43,7 +43,7 @@ where
43 let cookie = jar.get("session").ok_or(AppError::Unauthorized)?;43 let cookie = jar.get("session").ok_or(AppError::Unauthorized)?;
44 let (_, token) = split_cookie(cookie.value()).ok_or(AppError::Unauthorized)?;44 let (_, token) = split_cookie(cookie.value()).ok_or(AppError::Unauthorized)?;
45 45
46- let session = Session::find_by_token(token, &db)46+ let session = service::session::find_by_token(&db, token)
47 .await?47 .await?
48 .ok_or(AppError::Unauthorized)?;48 .ok_or(AppError::Unauthorized)?;
49 if session.is_expired() {49 if session.is_expired() {
src/web/homework.rsmodified+2 -2
@@ -30,10 +30,10 @@ use crate::domain::homework_submission::{
30 };30 };
31 use crate::domain::note_file::{FileContentType, FileName};31 use crate::domain::note_file::{FileContentType, FileName};
32 use crate::domain::role::Role;32 use crate::domain::role::Role;
33-use crate::domain::settings::Settings;
34 use crate::domain::timestamp::Timestamp;33 use crate::domain::timestamp::Timestamp;
35 use crate::domain::user::{User, UserId};34 use crate::domain::user::{User, UserId};
36 use crate::error::{AppError, ErrorResponse, ValidationError};35 use crate::error::{AppError, ErrorResponse, ValidationError};
36+use crate::service;
37 use crate::state::AppState;37 use crate::state::AppState;
38 38
39 use super::courses::{can_manage_course, can_view_course, visible_courses};39 use super::courses::{can_manage_course, can_view_course, visible_courses};
@@ -908,7 +908,7 @@ async fn upload_submission_file(
908 // below, because this snapshot goes stale while the body streams.908 // below, because this snapshot goes stale while the body streams.
909 let preflight = gate_own_submission(&id, &user, &st.db).await?;909 let preflight = gate_own_submission(&id, &user, &st.db).await?;
910 require_open_term(&preflight, &st.db).await?;910 require_open_term(&preflight, &st.db).await?;
911- let limit = Settings::load(&st.db).await?.get_max_file_bytes();911+ let limit = service::settings::load(&st.db).await?.get_max_file_bytes();
912 // Consume the body before taking the lock — a slow upload must not stall the912 // Consume the body before taking the lock — a slow upload must not stall the
913 // homework subsystem (mirrors the exam/note image uploads).913 // homework subsystem (mirrors the exam/note image uploads).
914 let upload = read_upload(&mut multipart, limit).await?;914 let upload = read_upload(&mut multipart, limit).await?;
src/web/image.rsmodified+2 -2
@@ -15,8 +15,8 @@ use std::future::Future;
15 use axum::extract::Multipart;15 use axum::extract::Multipart;
16 16
17 use crate::domain::note_file::FileContentType;17 use crate::domain::note_file::FileContentType;
18-use crate::domain::settings::Settings;
19 use crate::error::AppError;18 use crate::error::AppError;
19+use crate::service;
20 use crate::state::AppState;20 use crate::state::AppState;
21 21
22 use super::{blob_path, image_content_type, read_upload, remove_blob};22 use super::{blob_path, image_content_type, read_upload, remove_blob};
@@ -40,7 +40,7 @@ pub(crate) async fn read_image_upload(
40 st: &AppState,40 st: &AppState,
41 multipart: &mut Multipart,41 multipart: &mut Multipart,
42 ) -> Result<ImageUpload, AppError> {42 ) -> Result<ImageUpload, AppError> {
43- let limit = Settings::load(&st.db).await?.get_max_file_bytes();43+ let limit = service::settings::load(&st.db).await?.get_max_file_bytes();
44 let upload = read_upload(multipart, limit).await?;44 let upload = read_upload(multipart, limit).await?;
45 let content_type = image_content_type(&upload.content_type.unwrap_or_default())?;45 let content_type = image_content_type(&upload.content_type.unwrap_or_default())?;
46 Ok(ImageUpload {46 Ok(ImageUpload {
src/web/marks.rsmodified+2 -2
@@ -13,9 +13,9 @@ use crate::domain::course::Course;
13 use crate::domain::exam::Exam;13 use crate::domain::exam::Exam;
14 use crate::domain::exam_result::ExamResult;14 use crate::domain::exam_result::ExamResult;
15 use crate::domain::role::Role;15 use crate::domain::role::Role;
16-use crate::domain::settings::Settings;
17 use crate::domain::user::{User, UserId};16 use crate::domain::user::{User, UserId};
18 use crate::error::{AppError, ErrorResponse};17 use crate::error::{AppError, ErrorResponse};
18+use crate::service;
19 use crate::state::AppState;19 use crate::state::AppState;
20 20
21 use super::courses::can_manage_course;21 use super::courses::can_manage_course;
@@ -102,7 +102,7 @@ async fn build_report(
102 }102 }
103 103
104 // One settings read weighs and labels the whole report.104 // One settings read weighs and labels the whole report.
105- let school = Settings::load(db).await?;105+ let school = service::settings::load(db).await?;
106 let people = person_map(courses.iter().flat_map(course_people), db).await?;106 let people = person_map(courses.iter().flat_map(course_people), db).await?;
107 107
108 let mut blocks = Vec::with_capacity(courses.len());108 let mut blocks = Vec::with_capacity(courses.len());
src/web/meals.rsmodified+14 -6
@@ -32,9 +32,9 @@ use crate::domain::parent_link::ParentLink;
32 // The same idempotence key `/payments/credits` takes — one grammar, one type.32 // The same idempotence key `/payments/credits` takes — one grammar, one type.
33 use crate::domain::payment_ledger::PaymentRequestKey;33 use crate::domain::payment_ledger::PaymentRequestKey;
34 use crate::domain::role::Role;34 use crate::domain::role::Role;
35-use crate::domain::settings::Settings;
36 use crate::domain::user::{User, UserId};35 use crate::domain::user::{User, UserId};
37 use crate::error::{AppError, ErrorResponse, ValidationError};36 use crate::error::{AppError, ErrorResponse, ValidationError};
37+use crate::service;
38 use crate::state::AppState;38 use crate::state::AppState;
39 39
40 use super::{40 use super::{
@@ -270,7 +270,10 @@ async fn create_menu(
270 // against the end of the day, so today's menu is publishable all day — the270 // against the end of the day, so today's menu is publishable all day — the
271 // meal's own deadline is `meal_cancel_cutoff_minutes`, not this.271 // meal's own deadline is `meal_cancel_cutoff_minutes`, not this.
272 check_not_past("date", date.day_end())?;272 check_not_past("date", date.day_end())?;
273- let slot = MenuSlot::try_new(&req.slot, &Settings::load(&st.db).await?.get_meal_slots())?;273+ let slot = MenuSlot::try_new(
274+ &req.slot,
275+ &service::settings::load(&st.db).await?.get_meal_slots(),
276+ )?;
274 validate_capacity(req.capacity)?;277 validate_capacity(req.capacity)?;
275 let menu = Menu::create(date, slot, req.capacity, user.get_id(), &st.db).await?;278 let menu = Menu::create(date, slot, req.capacity, user.get_id(), &st.db).await?;
276 let body = one_menu(&menu, user.get_id(), &st.db).await?;279 let body = one_menu(&menu, user.get_id(), &st.db).await?;
@@ -431,7 +434,10 @@ async fn add_dish(
431 .transpose()?434 .transpose()?
432 .flatten();435 .flatten();
433 let price = DishPrice::try_new(req.price_minor)?;436 let price = DishPrice::try_new(req.price_minor)?;
434- let tags = DishTags::try_new(&req.tags, &Settings::load(&st.db).await?.get_dietary_tags())?;437+ let tags = DishTags::try_new(
438+ &req.tags,
439+ &service::settings::load(&st.db).await?.get_dietary_tags(),
440+ )?;
435 // Dish writes take [`MENU_LOCK`] for the dish cap alone: count-then-write441 // Dish writes take [`MENU_LOCK`] for the dish cap alone: count-then-write
436 // is write-skew, so the count and the insert have to be one step. The442 // is write-skew, so the count and the insert have to be one step. The
437 // *price* no longer needs it — a dish write moves the menu's revision, and443 // *price* no longer needs it — a dish write moves the menu's revision, and
@@ -499,7 +505,7 @@ async fn update_dish(
499 let tags = match &req.tags {505 let tags = match &req.tags {
500 Some(tags) => Some(DishTags::try_new(506 Some(tags) => Some(DishTags::try_new(
501 tags,507 tags,
502- &Settings::load(&st.db).await?.get_dietary_tags(),508+ &service::settings::load(&st.db).await?.get_dietary_tags(),
503 )?),509 )?),
504 None => None,510 None => None,
505 };511 };
@@ -684,7 +690,7 @@ async fn update_profile(
684 let tags = match &req.tags {690 let tags = match &req.tags {
685 Some(tags) => Some(DietaryTags::try_new(691 Some(tags) => Some(DietaryTags::try_new(
686 tags,692 tags,
687- &Settings::load(&st.db).await?.get_dietary_tags(),693+ &service::settings::load(&st.db).await?.get_dietary_tags(),
688 )?),694 )?),
689 None => None,695 None => None,
690 };696 };
@@ -764,7 +770,9 @@ async fn booking_responses(
764 /// live on every call, so a serving time corrected today moves the deadline of770 /// live on every call, so a serving time corrected today moves the deadline of
765 /// menus already published for it.771 /// menus already published for it.
766 async fn meal_cutoff(db: &Database) -> Result<MealCutoff, AppError> {772 async fn meal_cutoff(db: &Database) -> Result<MealCutoff, AppError> {
767- Ok(MealCutoff::from_settings(&Settings::load(db).await?))773+ Ok(MealCutoff::from_settings(
774+ &service::settings::load(db).await?,
775+ ))
768 }776 }
769 777
770 /// Whose seat is this? A student books only for themselves; a parent only for778 /// Whose seat is this? A student books only for themselves; a parent only for
src/web/notes.rsmodified+13 -13
@@ -12,8 +12,8 @@ use utoipa_axum::routes;
12 use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};12 use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};
13 use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle};13 use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle};
14 use crate::domain::note_file::{FileContentType, FileName, NoteFile, NoteFileId};14 use crate::domain::note_file::{FileContentType, FileName, NoteFile, NoteFileId};
15-use crate::domain::settings::Settings;
16 use crate::error::{AppError, ErrorResponse};15 use crate::error::{AppError, ErrorResponse};
16+use crate::service;
17 use crate::state::AppState;17 use crate::state::AppState;
18 18
19 use super::{CurrentUser, Page, PageParams, UploadFileForm, blob_path, read_upload, remove_blob};19 use super::{CurrentUser, Page, PageParams, UploadFileForm, blob_path, read_upload, remove_blob};
@@ -89,7 +89,7 @@ async fn create(
89 ) -> Result<(StatusCode, Json<NoteResponse>), AppError> {89 ) -> Result<(StatusCode, Json<NoteResponse>), AppError> {
90 let title = NoteTitle::try_new(&req.title)?;90 let title = NoteTitle::try_new(&req.title)?;
91 let content = NoteContent::try_new(&req.content.unwrap_or_default())?;91 let content = NoteContent::try_new(&req.content.unwrap_or_default())?;
92- let note = Note::create(user.get_id(), title, content, &st.db).await?;92+ let note = service::note::create(&st.db, user.get_id(), title, content).await?;
93 Ok((StatusCode::CREATED, Json(NoteResponse::new(&note))))93 Ok((StatusCode::CREATED, Json(NoteResponse::new(&note))))
94 }94 }
95 95
@@ -114,7 +114,7 @@ async fn list(
114 Query(page): Query<PageParams>,114 Query(page): Query<PageParams>,
115 ) -> Result<Json<Page<NoteResponse>>, AppError> {115 ) -> Result<Json<Page<NoteResponse>>, AppError> {
116 let (limit, offset) = page.resolve()?;116 let (limit, offset) = page.resolve()?;
117- let (notes, total) = Note::list_for(user.get_id(), limit, offset, &st.db).await?;117+ let (notes, total) = service::note::list_for(&st.db, user.get_id(), limit, offset).await?;
118 let items = notes.iter().map(NoteResponse::new).collect();118 let items = notes.iter().map(NoteResponse::new).collect();
119 Ok(Json(Page::new(items, total, limit, offset)))119 Ok(Json(Page::new(items, total, limit, offset)))
120 }120 }
@@ -137,7 +137,7 @@ async fn get_one(
137 CurrentUser(user): CurrentUser,137 CurrentUser(user): CurrentUser,
138 Path(id): Path<String>,138 Path(id): Path<String>,
139 ) -> Result<Json<NoteResponse>, AppError> {139 ) -> Result<Json<NoteResponse>, AppError> {
140- let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db)140+ let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id())
141 .await?141 .await?
142 .ok_or(AppError::NotFound)?;142 .ok_or(AppError::NotFound)?;
143 Ok(Json(NoteResponse::new(&note)))143 Ok(Json(NoteResponse::new(&note)))
@@ -165,7 +165,7 @@ async fn update(
165 Path(id): Path<String>,165 Path(id): Path<String>,
166 Json(req): Json<UpdateNote>,166 Json(req): Json<UpdateNote>,
167 ) -> Result<Json<NoteResponse>, AppError> {167 ) -> Result<Json<NoteResponse>, AppError> {
168- let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db)168+ let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id())
169 .await?169 .await?
170 .ok_or(AppError::NotFound)?;170 .ok_or(AppError::NotFound)?;
171 171
@@ -180,7 +180,7 @@ async fn update(
180 .map(NoteContent::try_new)180 .map(NoteContent::try_new)
181 .transpose()?;181 .transpose()?;
182 182
183- let updated = note.update(title, content, &st.db).await?;183+ let updated = service::note::update(&st.db, note, title, content).await?;
184 Ok(Json(NoteResponse::new(&updated)))184 Ok(Json(NoteResponse::new(&updated)))
185 }185 }
186 186
@@ -202,14 +202,14 @@ async fn delete_one(
202 CurrentUser(user): CurrentUser,202 CurrentUser(user): CurrentUser,
203 Path(id): Path<String>,203 Path(id): Path<String>,
204 ) -> Result<StatusCode, AppError> {204 ) -> Result<StatusCode, AppError> {
205- let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db)205+ let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id())
206 .await?206 .await?
207 .ok_or(AppError::NotFound)?;207 .ok_or(AppError::NotFound)?;
208 // Rows go first (the note delete cascades them), blobs after: a crash in208 // Rows go first (the note delete cascades them), blobs after: a crash in
209 // between strands at worst an unreachable blob, never a row whose blob is209 // between strands at worst an unreachable blob, never a row whose blob is
210 // already gone. The files to unlink come from the delete itself, not a210 // already gone. The files to unlink come from the delete itself, not a
211 // pre-read list — an upload that landed in between is in the cascade too.211 // pre-read list — an upload that landed in between is in the cascade too.
212- let (_, files) = note.delete(&st.db).await?;212+ let (_, files) = service::note::delete(&st.db, note).await?;
213 for file in &files {213 for file in &files {
214 remove_blob(&st.files_path, file.get_id().key()).await;214 remove_blob(&st.files_path, file.get_id().key()).await;
215 }215 }
@@ -269,12 +269,12 @@ async fn upload_file(
269 Path(id): Path<String>,269 Path(id): Path<String>,
270 mut multipart: Multipart,270 mut multipart: Multipart,
271 ) -> Result<(StatusCode, Json<NoteFileResponse>), AppError> {271 ) -> Result<(StatusCode, Json<NoteFileResponse>), AppError> {
272- let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db)272+ let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id())
273 .await?273 .await?
274 .ok_or(AppError::NotFound)?;274 .ok_or(AppError::NotFound)?;
275 // The 10-file cap is enforced inside `NoteFile::insert` (count and create275 // The 10-file cap is enforced inside `NoteFile::insert` (count and create
276 // under one lock) — checking it here too would just race.276 // under one lock) — checking it here too would just race.
277- let limit = Settings::load(&st.db).await?.get_max_file_bytes();277+ let limit = service::settings::load(&st.db).await?.get_max_file_bytes();
278 278
279 let upload = read_upload(&mut multipart, limit).await?;279 let upload = read_upload(&mut multipart, limit).await?;
280 let name = FileName::try_new(&upload.name.unwrap_or_default())?;280 let name = FileName::try_new(&upload.name.unwrap_or_default())?;
@@ -319,7 +319,7 @@ async fn list_files(
319 Query(page): Query<PageParams>,319 Query(page): Query<PageParams>,
320 ) -> Result<Json<Page<NoteFileResponse>>, AppError> {320 ) -> Result<Json<Page<NoteFileResponse>>, AppError> {
321 let (limit, offset) = page.resolve()?;321 let (limit, offset) = page.resolve()?;
322- let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db)322+ let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id())
323 .await?323 .await?
324 .ok_or(AppError::NotFound)?;324 .ok_or(AppError::NotFound)?;
325 let (files, total) = NoteFile::list_for(note.get_id(), limit, offset, &st.db).await?;325 let (files, total) = NoteFile::list_for(note.get_id(), limit, offset, &st.db).await?;
@@ -349,7 +349,7 @@ async fn download_file(
349 CurrentUser(user): CurrentUser,349 CurrentUser(user): CurrentUser,
350 Path((id, file_id)): Path<(String, String)>,350 Path((id, file_id)): Path<(String, String)>,
351 ) -> Result<Response, AppError> {351 ) -> Result<Response, AppError> {
352- let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db)352+ let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id())
353 .await?353 .await?
354 .ok_or(AppError::NotFound)?;354 .ok_or(AppError::NotFound)?;
355 let file = NoteFile::read_for(&NoteFileId::from_key(&file_id), note.get_id(), &st.db)355 let file = NoteFile::read_for(&NoteFileId::from_key(&file_id), note.get_id(), &st.db)
@@ -402,7 +402,7 @@ async fn delete_file(
402 CurrentUser(user): CurrentUser,402 CurrentUser(user): CurrentUser,
403 Path((id, file_id)): Path<(String, String)>,403 Path((id, file_id)): Path<(String, String)>,
404 ) -> Result<StatusCode, AppError> {404 ) -> Result<StatusCode, AppError> {
405- let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db)405+ let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id())
406 .await?406 .await?
407 .ok_or(AppError::NotFound)?;407 .ok_or(AppError::NotFound)?;
408 let file = NoteFile::read_for(&NoteFileId::from_key(&file_id), note.get_id(), &st.db)408 let file = NoteFile::read_for(&NoteFileId::from_key(&file_id), note.get_id(), &st.db)
src/web/sessions.rsmodified+2 -2
@@ -17,10 +17,10 @@ use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic
17 use crate::domain::enrollment::Enrollment;17 use crate::domain::enrollment::Enrollment;
18 use crate::domain::role::Role;18 use crate::domain::role::Role;
19 use crate::domain::session_attendance::SessionAttendance;19 use crate::domain::session_attendance::SessionAttendance;
20-use crate::domain::settings::Settings;
21 use crate::domain::timestamp::Timestamp;20 use crate::domain::timestamp::Timestamp;
22 use crate::domain::user::{User, UserId};21 use crate::domain::user::{User, UserId};
23 use crate::error::{AppError, ErrorResponse, ValidationError};22 use crate::error::{AppError, ErrorResponse, ValidationError};
23+use crate::service;
24 use crate::state::AppState;24 use crate::state::AppState;
25 25
26 use super::courses::{can_manage_course, can_view_course};26 use super::courses::{can_manage_course, can_view_course};
@@ -320,7 +320,7 @@ async fn mark_roll_call(
320 }320 }
321 course.require_open(&st.db).await?;321 course.require_open(&st.db).await?;
322 322
323- let school = Settings::load(&st.db).await?;323+ let school = service::settings::load(&st.db).await?;
324 let status = AttendanceStatus::try_new(&req.status, school.get_attendance_statuses())?;324 let status = AttendanceStatus::try_new(&req.status, school.get_attendance_statuses())?;
325 let target = UserId::from_key(&req.user_id);325 let target = UserId::from_key(&req.user_id);
326 326
src/web/settings.rsmodified+42 -537
@@ -5,15 +5,9 @@ use utoipa::ToSchema;
5 use utoipa_axum::router::OpenApiRouter;5 use utoipa_axum::router::OpenApiRouter;
6 use utoipa_axum::routes;6 use utoipa_axum::routes;
7 7
8-use surrealdb::types::RecordId;8+use crate::domain::settings::Settings;
9-
10-use crate::constant::CAS_UPDATE_RETRIES;
11-use crate::database::Database;
12-use crate::db::cap;
13-use crate::domain::exam_result::kind_ref;
14-use crate::domain::menu::slot_ref;
15-use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, SETTINGS_LOCK, Settings};
16 use crate::error::{AppError, ErrorResponse};9 use crate::error::{AppError, ErrorResponse};
10+use crate::service;
17 use crate::state::AppState;11 use crate::state::AppState;
18 12
19 use super::{CurrentUser, RequireManager, set_or_clear};13 use super::{CurrentUser, RequireManager, set_or_clear};
@@ -227,7 +221,7 @@ async fn get_settings(
227 State(st): State<AppState>,221 State(st): State<AppState>,
228 CurrentUser(_user): CurrentUser,222 CurrentUser(_user): CurrentUser,
229 ) -> Result<Json<SettingsResponse>, AppError> {223 ) -> Result<Json<SettingsResponse>, AppError> {
230- let settings = Settings::load(&st.db).await?;224+ let settings = service::settings::load(&st.db).await?;
231 Ok(Json(SettingsResponse::new(&settings)))225 Ok(Json(SettingsResponse::new(&settings)))
232 }226 }
233 227
@@ -268,536 +262,47 @@ async fn update_settings(
268 RequireManager(_user): RequireManager,262 RequireManager(_user): RequireManager,
269 Json(req): Json<UpdateSettings>,263 Json(req): Json<UpdateSettings>,
270 ) -> Result<Json<SettingsResponse>, AppError> {264 ) -> Result<Json<SettingsResponse>, AppError> {
271- Ok(Json(SettingsResponse::new(&apply(&req, &st.db).await?)))265+ // Wire → workflow mapping, nothing more. The lists are deliberately not
272-}266+ // validated here: that happens inside the service, in the workflow's own
273-267+ // order, and a stored meal-slot name skips the URL-charset rule — a
274-/// The whole edit — snapshot, merge, retire, save — as one operation, so the268+ // decision only the locked edit can make (`MealSlotDef::try_kept`).
275-/// tests can drive it the way two managers do. Split out of the handler for269+ let patch = service::settings::SettingsPatch {
276-/// nothing else.270+ exam_kinds: req.exam_kinds.as_ref().map(|kinds| {
277-async fn apply(req: &UpdateSettings, db: &Database) -> Result<Settings, AppError> {271+ kinds
278- // One settings edit at a time: the removals below are decided against the
279- // snapshot this loop loads and written *before* the save that justifies
280- // them, and no per-name bookkeeping can make that pair survive a rival's
281- // pair interleaving with it (see `SETTINGS_LOCK`).
282- let _guard = SETTINGS_LOCK.lock().await;
283- // Merge over a snapshot, then save only while the row still matches it —
284- // otherwise a concurrent PATCH of a *different* field would be silently
285- // reverted by whichever whole-row write lands second. A refused save
286- // reloads and re-merges, so both edits land.
287- for _ in 0..CAS_UPDATE_RETRIES {
288- let current = Settings::load(db).await?;
289-
290- let exam_kinds = match &req.exam_kinds {
291- Some(kinds) => kinds
292 .iter()272 .iter()
293- .map(|kind| ExamKindDef::try_new(&kind.name, kind.weight))273+ .map(|kind| service::settings::ExamKindInput {
294- .collect::<Result<Vec<_>, _>>()?,274+ name: kind.name.clone(),
295- None => current.get_exam_kinds().to_vec(),275+ weight: kind.weight,
296- };276+ })
297- let was_slots = slot_names(&current.get_meal_slots());277+ .collect()
298- let meal_slots = match &req.meal_slots {278+ }),
299- Some(slots) => slots279+ attendance_statuses: req.attendance_statuses.clone(),
280+ grade_bands: req.grade_bands.as_ref().map(|bands| {
281+ bands
300 .iter()282 .iter()
301- .map(|slot| {283+ .map(|band| service::settings::GradeBandInput {
302- // A name the row already carries is validated as a kept one:284+ min: band.min,
303- // the charset rule is younger than the stored lists, and285+ label: band.label.clone(),
304- // re-validating one under it would leave a school unable to
305- // edit the rest of its slots at all (`MealSlotDef::try_kept`).
306- if was_slots.iter().any(|kept| kept == slot.name.trim()) {
307- MealSlotDef::try_kept(&slot.name, slot.serving_minute)
308- } else {
309- MealSlotDef::try_new(&slot.name, slot.serving_minute)
310- }
311 })286 })
312- .collect::<Result<Vec<_>, _>>()?,287+ .collect()
313- None => current.get_meal_slots(),288+ }),
314- };289+ max_file_bytes: req.max_file_bytes,
315- let attendance_statuses = req290+ chatbot_history_turns: req.chatbot_history_turns,
316- .attendance_statuses291+ max_chatbot_threads: req.max_chatbot_threads,
317- .clone()292+ max_chatbot_message_len: req.max_chatbot_message_len,
318- .unwrap_or_else(|| current.get_attendance_statuses().to_vec());293+ meal_slots: req.meal_slots.as_ref().map(|slots| {
319- let grade_bands = match &req.grade_bands {294+ slots
320- Some(bands) => bands
321 .iter()295 .iter()
322- .map(|band| GradeBand::try_new(band.min, &band.label))296+ .map(|slot| service::settings::MealSlotInput {
323- .collect::<Result<Vec<_>, _>>()?,297+ name: slot.name.clone(),
324- None => current.get_grade_bands().to_vec(),298+ serving_minute: slot.serving_minute,
325- };299+ })
326- // The name lists as they stand and as they would stand, for the removal300+ .collect()
327- // guards below — a list edit is judged by which names it drops.301+ }),
328- let was_kinds = kind_names(current.get_exam_kinds());302+ dietary_tags: req.dietary_tags.clone(),
329- let now_kinds = kind_names(&exam_kinds);303+ meal_cancel_cutoff_minutes: req.meal_cancel_cutoff_minutes,
330- let now_slots = slot_names(&meal_slots);304+ };
331-305+ Ok(Json(SettingsResponse::new(
332- // Merge over the snapshot's resolved values: an omitted field keeps306+ &service::settings::apply(&st.db, &patch).await?,
333- // whatever the row (or the default behind an unset field) reads as.307+ )))
334- let mut params = current.params();
335- params.exam_kinds = exam_kinds;
336- params.attendance_statuses = attendance_statuses;
337- params.grade_bands = grade_bands;
338- params.max_file_bytes = req.max_file_bytes.unwrap_or(params.max_file_bytes);
339- params.chatbot_history_turns = req
340- .chatbot_history_turns
341- .unwrap_or(params.chatbot_history_turns);
342- params.max_chatbot_threads = req
343- .max_chatbot_threads
344- .unwrap_or(params.max_chatbot_threads);
345- params.max_chatbot_message_len = req
346- .max_chatbot_message_len
347- .unwrap_or(params.max_chatbot_message_len);
348- params.meal_slots = meal_slots;
349- params.dietary_tags = req
350- .dietary_tags
351- .clone()
352- .unwrap_or_else(|| current.get_dietary_tags());
353- // Double option: absent keeps the knob, `null` clears it (no cutoff).
354- params.meal_cancel_cutoff_minutes = req
355- .meal_cancel_cutoff_minutes
356- .unwrap_or(params.meal_cancel_cutoff_minutes);
357-
358- let settings = Settings::try_new(params)?;
359-
360- // The removal guards. A name leaves a list by being *retired* on its
361- // reference counter — one conditional write on one record, which lands
362- // only while nothing references the name and refuses every claim from
363- // that instant on. That is the whole guard: the check and the removal
364- // used to be a cross-table count and a save held together by a
365- // process-wide lock that was released around the round trip between them.
366- //
367- // Retired before the save, never after: the other order leaves a window
368- // in which a mark lands under a kind the settings no longer list. A save
369- // that then does not land undoes them (`restore`) before the next try.
370- //
371- // Only a write that actually *flipped* a bit is recorded for that undo.
372- // Retirement is idempotent, so two PATCHes dropping the same kind are
373- // both told "retired" — and the one whose save then loses the row's CAS
374- // used to un-retire the winner's kind, leaving it off the list with its
375- // counter in service: gradable again, its count then non-zero, and so
376- // impossible to remove ever after.
377- let mut undo: Vec<Undo> = Vec::new();
378- let mut refused = None;
379- for gone in missing(&was_kinds, &now_kinds) {
380- let counter = kind_ref(&gone);
381- match cap::retire_name(&counter, db).await? {
382- cap::Switched::Flipped => undo.push(Undo::Retired(counter)),
383- cap::Switched::Unchanged => {}
384- cap::Switched::InUse => {
385- refused = Some(AppError::ConflictOwned(format!(
386- "exams of kind '{gone}' are already graded — the kind cannot be removed"
387- )));
388- break;
389- }
390- }
391- }
392- // Same shape for meal slots: a slot a menu was already published for
393- // cannot leave the list — the menu snapshotted the name as text, and a
394- // slot no longer offered would leave that menu unreachable from the
395- // school's own list.
396- if refused.is_none() {
397- for gone in missing(&was_slots, &now_slots) {
398- let counter = slot_ref(&gone);
399- match cap::retire_name(&counter, db).await? {
400- cap::Switched::Flipped => undo.push(Undo::Retired(counter)),
401- cap::Switched::Unchanged => {}
402- cap::Switched::InUse => {
403- refused = Some(AppError::ConflictOwned(format!(
404- "menus are already published for the '{gone}' slot — it cannot be removed"
405- )));
406- break;
407- }
408- }
409- }
410- }
411- if let Some(refused) = refused {
412- restore(&undo, db).await?;
413- return Err(refused);
414- }
415- // A name re-entering a list is back in service: its counter still
416- // carries the retirement from the edit that dropped it, and a mark (or
417- // a menu) under a kind the school offers again must not be refused.
418- // Recorded for the same undo as the retirements — a re-add whose save
419- // does not land leaves a name off the list that grades happily.
420- for back in missing(&now_kinds, &was_kinds) {
421- if let cap::Switched::Flipped = cap::unretire_name(&kind_ref(&back), db).await? {
422- undo.push(Undo::Unretired(kind_ref(&back)));
423- }
424- }
425- for back in missing(&now_slots, &was_slots) {
426- if let cap::Switched::Flipped = cap::unretire_name(&slot_ref(&back), db).await? {
427- undo.push(Undo::Unretired(slot_ref(&back)));
428- }
429- }
430-
431- match settings.save_if_unchanged(&current, db).await {
432- Ok(Some(saved)) => return Ok(saved),
433- // The row moved under the snapshot these guards were judged against:
434- // put the names back and re-merge, or the next attempt would decide
435- // against a list nobody asked for.
436- Ok(None) => restore(&undo, db).await?,
437- Err(err) => {
438- restore(&undo, db).await?;
439- return Err(err);
440- }
441- }
442- }
443- Err(AppError::Conflict(
444- "the settings kept changing underneath this update — try again",
445- ))
446-}
447-
448-fn kind_names(kinds: &[ExamKindDef]) -> Vec<String> {
449- kinds
450- .iter()
451- .map(|kind| kind.get_name().to_string())
452- .collect()
453-}
454-
455-fn slot_names(slots: &[MealSlotDef]) -> Vec<String> {
456- slots
457- .iter()
458- .map(|slot| slot.get_name().to_string())
459- .collect()
460-}
461-
462-/// The names `before` carries that `after` does not — a list edit's removals,
463-/// or its additions with the arguments swapped.
464-fn missing(before: &[String], after: &[String]) -> Vec<String> {
465- before
466- .iter()
467- .filter(|name| !after.contains(name))
468- .cloned()
469- .collect()
470-}
471-
472-/// One `retired` bit this attempt moved, and which way — what `restore` needs
473-/// to put it back. Only bits this attempt actually *flipped* are listed: a
474-/// write that changed nothing has nothing to take back, and taking it back
475-/// would undo the concurrent edit that really did move it.
476-enum Undo {
477- /// Retired for a removal; put it back in service.
478- Retired(RecordId),
479- /// Put back in service for a re-add; retire it again.
480- Unretired(RecordId),
481-}
482-
483-/// Undo every bit this attempt moved: the edit that justified them did not
484-/// land, so the lists the school offers are still the ones it started with.
485-async fn restore(undo: &[Undo], db: &Database) -> Result<(), AppError> {
486- for step in undo {
487- match step {
488- Undo::Retired(name) => {
489- cap::unretire_name(name, db).await?;
490- }
491- // A re-retirement can be refused: a mark (or a menu) landed under
492- // the name during the window it was in service. Refusing to undo is
493- // then the honest answer — the reference is real, and retiring over
494- // it would make the row's kind ungradable while nothing lists it.
495- // The name is left in service, matching the list this attempt is
496- // about to re-read.
497- Undo::Unretired(name) => {
498- cap::retire_name(name, db).await?;
499- }
500- }
501- }
502- Ok(())
503-}
504-
505-#[cfg(test)]
506-mod tests {
507- use super::*;
508- use crate::database::init_mem;
509-
510- /// The `retired` bit as the store holds it, `None` when no counter row was
511- /// ever written — read back, never inferred from a return value.
512- async fn bit(db: &Database, counter: RecordId) -> Option<bool> {
513- let mut result = db
514- .query("SELECT VALUE retired FROM $id")
515- .bind(("id", counter))
516- .await
517- .unwrap()
518- .check()
519- .unwrap();
520- result.take::<Vec<bool>>(0).unwrap().first().copied()
521- }
522-
523- /// Two managers drop the same exam kind at once; one of them loses the
524- /// row's compare-and-set and rolls its attempt back. The winner's
525- /// retirement must survive that rollback — undone, the kind is off the list
526- /// with a counter that still grades, and the first mark to land makes it
527- /// unremovable for good.
528- ///
529- /// The loser's half is what runs here: a retirement that changed nothing
530- /// records no undo, so `restore` has nothing to take back.
531- #[tokio::test]
532- async fn the_loser_of_a_settings_race_cannot_un_retire_the_winner_s_kind() {
533- let db = init_mem().await.unwrap();
534- let counter = kind_ref("midterm");
535-
536- // The winner's PATCH retires the kind.
537- assert!(matches!(
538- cap::retire_name(&counter, &db).await.unwrap(),
539- cap::Switched::Flipped
540- ));
541-
542- // The loser's PATCH decides the same removal against the same snapshot,
543- // then its save is refused.
544- let mut undo = Vec::new();
545- if let cap::Switched::Flipped = cap::retire_name(&counter, &db).await.unwrap() {
546- undo.push(Undo::Retired(counter.clone()));
547- }
548- assert!(undo.is_empty(), "a no-op retirement records no undo");
549- restore(&undo, &db).await.unwrap();
550-
551- assert_eq!(
552- bit(&db, counter).await,
553- Some(true),
554- "the winner's retirement must outlive the loser's rollback"
555- );
556- }
557-
558- /// The mirror hole: a re-*added* name is put back in service before the
559- /// save, so a save that does not land owes a re-retirement. Without it the
560- /// name is off the stored list with a counter that grades happily.
561- #[tokio::test]
562- async fn a_rollback_re_retires_a_name_this_attempt_put_back_in_service() {
563- let db = init_mem().await.unwrap();
564- let counter = slot_ref("lunch");
565- cap::retire_name(&counter, &db).await.unwrap();
566-
567- // The attempt re-adds the slot, then its save is refused.
568- let mut undo = Vec::new();
569- if let cap::Switched::Flipped = cap::unretire_name(&counter, &db).await.unwrap() {
570- undo.push(Undo::Unretired(counter.clone()));
571- }
572- assert_eq!(undo.len(), 1, "a real un-retirement is undoable");
573- restore(&undo, &db).await.unwrap();
574-
575- assert_eq!(
576- bit(&db, counter).await,
577- Some(true),
578- "a re-add that never landed must leave the slot retired"
579- );
580- }
581-
582- /// ...unless a menu was published in the window the slot was back in
583- /// service. The reference is real, so the re-retirement is refused and the
584- /// slot stays usable — the honest end of the same rule, not a silent
585- /// overwrite of a live reference.
586- #[tokio::test]
587- async fn a_rollback_leaves_a_name_that_gained_a_reference_in_service() {
588- let db = init_mem().await.unwrap();
589- let counter = slot_ref("lunch");
590- cap::retire_name(&counter, &db).await.unwrap();
591- cap::unretire_name(&counter, &db).await.unwrap();
592- db.query("UPDATE $id SET count = 1")
593- .bind(("id", counter.clone()))
594- .await
595- .unwrap()
596- .check()
597- .unwrap();
598-
599- restore(&[Undo::Unretired(counter.clone())], &db)
600- .await
601- .unwrap();
602-
603- assert_eq!(bit(&db, counter).await, Some(false));
604- }
605-
606- // --- the whole edit, driven the way two managers drive it -------------
607-
608- /// A `PATCH` body, built the way the router builds one.
609- fn patch(body: serde_json::Value) -> UpdateSettings {
610- serde_json::from_value(body).unwrap()
611- }
612-
613- /// A `meal_slots`/`exam_kinds` list as the DTO carries it.
614- fn kinds(names: &[&str]) -> serde_json::Value {
615- names
616- .iter()
617- .map(|name| serde_json::json!({ "name": name, "weight": 1 }))
618- .collect()
619- }
620-
621- fn slots(names: &[&str]) -> serde_json::Value {
622- names
623- .iter()
624- .map(|name| serde_json::json!({ "name": name, "serving_minute": null }))
625- .collect()
626- }
627-
628- /// The lists as the store holds them.
629- async fn stored(db: &Database) -> (Vec<String>, Vec<String>) {
630- let settings = Settings::load(db).await.unwrap();
631- (
632- kind_names(settings.get_exam_kinds()),
633- slot_names(&settings.get_meal_slots()),
634- )
635- }
636-
637- /// The whole invariant, over the reachable half of the race: two managers
638- /// drop the same exam kind at once, both edits go through the real path,
639- /// and when both have returned the counter's `retired` bit must agree with
640- /// the list the store actually holds.
641- ///
642- /// One of the two decides the removal, retires the kind and saves; the
643- /// other cannot even see the old list, because the whole snapshot-retire-
644- /// save pair is serialized (`SETTINGS_LOCK`). Interleaved, the second
645- /// attempt would be told "already retired", record no undo, win the
646- /// compare-and-set, and leave the first attempt un-retiring the kind it had
647- /// legitimately removed — off the list and gradable.
648- #[tokio::test]
649- async fn two_edits_dropping_the_same_kind_leave_it_retired() {
650- let db = init_mem().await.unwrap();
651- let without = patch(serde_json::json!({
652- "exam_kinds": kinds(&["homework", "quiz", "final", "project", "oral"]),
653- }));
654-
655- let (a, b) = tokio::join!(apply(&without, &db), apply(&without, &db));
656- a.unwrap();
657- b.unwrap();
658-
659- let (kinds, _) = stored(&db).await;
660- assert!(
661- !kinds.contains(&"midterm".to_string()),
662- "dropped from the list"
663- );
664- assert_eq!(
665- bit(&db, kind_ref("midterm")).await,
666- Some(true),
667- "a kind the stored list no longer offers must not grade"
668- );
669- }
670-
671- /// The property those two outcomes rest on, asserted on its own because a
672- /// `join!` cannot be made to schedule the losing order: the edit is a pair
673- /// of writes — retire the dropped names, then commit the list — and no
674- /// rival's pair may run between them.
675- ///
676- /// Retirement is idempotent, so an interleaved rival is told "already
677- /// retired", records no rollback, wins the compare-and-set, and leaves the
678- /// attempt that really flipped the bit un-retiring a kind the stored list
679- /// no longer offers: gradable again, and unremovable for good once a mark
680- /// lands. Holding the lock stands in for a rival mid-pair here — nothing
681- /// the other edit does may be visible until the pair completes.
682- #[tokio::test]
683- async fn a_rival_edit_cannot_run_between_a_retirement_and_its_save() {
684- let db = init_mem().await.unwrap();
685- let without = patch(serde_json::json!({
686- "exam_kinds": kinds(&["homework", "quiz", "final", "project", "oral"]),
687- }));
688-
689- let held = SETTINGS_LOCK.lock().await;
690- let rival = tokio::spawn({
691- let db = db.clone();
692- async move { apply(&without, &db).await.map(|_| ()) }
693- });
694- tokio::time::sleep(std::time::Duration::from_millis(200)).await;
695-
696- assert_eq!(
697- bit(&db, kind_ref("midterm")).await,
698- None,
699- "a rival's pair must not have started, let alone half-landed"
700- );
701- assert!(stored(&db).await.0.contains(&"midterm".to_string()));
702-
703- drop(held);
704- rival.await.unwrap().unwrap();
705- assert_eq!(bit(&db, kind_ref("midterm")).await, Some(true));
706- assert!(!stored(&db).await.0.contains(&"midterm".to_string()));
707- }
708-
709- /// The mirror: two managers put the same kind *back* at once. The attempt
710- /// that loses must not re-retire a name the winner's stored list carries —
711- /// a listed kind that refuses every grade.
712- #[tokio::test]
713- async fn two_edits_re_adding_the_same_kind_leave_it_in_service() {
714- let db = init_mem().await.unwrap();
715- let without = patch(serde_json::json!({
716- "exam_kinds": kinds(&["homework", "quiz", "final", "project", "oral"]),
717- }));
718- apply(&without, &db).await.unwrap();
719- let with = patch(serde_json::json!({
720- "exam_kinds": kinds(&["homework", "quiz", "midterm", "final", "project", "oral"]),
721- }));
722-
723- let (a, b) = tokio::join!(apply(&with, &db), apply(&with, &db));
724- a.unwrap();
725- b.unwrap();
726-
727- let (kinds, _) = stored(&db).await;
728- assert!(kinds.contains(&"midterm".to_string()), "back on the list");
729- assert_eq!(
730- bit(&db, kind_ref("midterm")).await,
731- Some(false),
732- "a kind the stored list offers must grade"
733- );
734- }
735-
736- /// The same pair over meal slots, which retire on their own counters.
737- #[tokio::test]
738- async fn two_edits_dropping_the_same_slot_leave_it_retired() {
739- let db = init_mem().await.unwrap();
740- let without = patch(serde_json::json!({
741- "meal_slots": slots(&["breakfast", "snack"]),
742- }));
743-
744- let (a, b) = tokio::join!(apply(&without, &db), apply(&without, &db));
745- a.unwrap();
746- b.unwrap();
747-
748- let (_, stored_slots) = stored(&db).await;
749- assert!(!stored_slots.contains(&"lunch".to_string()));
750- assert_eq!(bit(&db, slot_ref("lunch")).await, Some(true));
751- }
752-
753- // --- the stale slot name that wedged the whole list -------------------
754-
755- /// A school that stored `a/b` before the URL-safety rule existed.
756- async fn a_school_with_a_stale_slot(db: &Database) {
757- let mut params = Settings::defaults().params();
758- params.meal_slots = vec![
759- MealSlotDef::try_kept("a/b", None).unwrap(),
760- MealSlotDef::try_new("lunch", None).unwrap(),
761- ];
762- Settings::try_new(params).unwrap().save(db).await.unwrap();
763- }
764-
765- /// The wedge: re-sending a stored name is the only way to *keep* it, and
766- /// dropping it 409s once a menu references it — so validating it under the
767- /// younger rule locks the school out of its own `meal_slots` forever. A
768- /// stored name is submittable; a new one with the same characters is not.
769- #[tokio::test]
770- async fn a_stored_slot_name_stays_submittable_but_a_new_one_does_not() {
771- let db = init_mem().await.unwrap();
772- a_school_with_a_stale_slot(&db).await;
773-
774- let edit = patch(serde_json::json!({
775- "meal_slots": slots(&["a/b", "lunch", "dinner"]),
776- }));
777- apply(&edit, &db).await.unwrap();
778- let (_, stored_slots) = stored(&db).await;
779- assert_eq!(stored_slots, ["a/b", "lunch", "dinner"]);
780-
781- let fresh = patch(serde_json::json!({
782- "meal_slots": slots(&["a/b", "lunch", "c/d"]),
783- }));
784- assert!(
785- apply(&fresh, &db).await.is_err(),
786- "a name no school ever stored is still refused"
787- );
788- }
789-
790- /// And an edit that never mentions `meal_slots` still carries the list
791- /// over unvalidated — the behaviour the wedge report leaned on.
792- #[tokio::test]
793- async fn an_unrelated_edit_carries_a_stale_slot_name_over() {
794- let db = init_mem().await.unwrap();
795- a_school_with_a_stale_slot(&db).await;
796-
797- let elsewhere = patch(serde_json::json!({ "max_file_bytes": 2048 }));
798- let saved = apply(&elsewhere, &db).await.unwrap();
799-
800- assert_eq!(saved.get_max_file_bytes(), 2048);
801- assert_eq!(slot_names(&saved.get_meal_slots()), ["a/b", "lunch"]);
802- }
803 }308 }
src/web/tenant_state.rsmodified+2 -2
@@ -181,8 +181,8 @@ mod tests {
181 use tower::ServiceExt;181 use tower::ServiceExt;
182 182
183 use crate::database::init_mem_tenants;183 use crate::database::init_mem_tenants;
184+ use crate::db::session;
184 use crate::domain::builder::{Builder, BuilderSession};185 use crate::domain::builder::{Builder, BuilderSession};
185- use crate::domain::session::Session;
186 use crate::domain::user::{Password, User, Username};186 use crate::domain::user::{Password, User, Username};
187 use crate::tenant::DEMO_SLUG;187 use crate::tenant::DEMO_SLUG;
188 use crate::web::{CurrentUser, RequireBuilder};188 use crate::web::{CurrentUser, RequireBuilder};
@@ -215,7 +215,7 @@ mod tests {
215 )215 )
216 .await216 .await
217 .unwrap();217 .unwrap();
218- let session = Session::create(user.get_id(), &school).await.unwrap();218+ let session = session::create(&school, user.get_id()).await.unwrap();
219 let school_cookie = format!("session={DEMO_SLUG}.{}", session.token().as_str());219 let school_cookie = format!("session={DEMO_SLUG}.{}", session.token().as_str());
220 220
221 Builder::ensure(221 Builder::ensure(
tests/integration.rsmodified+4 -4
@@ -15,6 +15,7 @@ use hezarfen_backend::constant::{
15 BANK_VISIBILITY_SCHOOL, MAX_BOARD_STROKES, MAX_BOARDS_PER_CREATOR, MAX_COURSE_NOTE_FILES,15 BANK_VISIBILITY_SCHOOL, MAX_BOARD_STROKES, MAX_BOARDS_PER_CREATOR, MAX_COURSE_NOTE_FILES,
16 MAX_EPOCH_STROKES, MAX_FEE_PLAN_ASSIGN_STUDENTS,16 MAX_EPOCH_STROKES, MAX_FEE_PLAN_ASSIGN_STUDENTS,
17 };17 };
18+use hezarfen_backend::db::session;
18 use hezarfen_backend::domain::board::{Board, BoardId};19 use hezarfen_backend::domain::board::{Board, BoardId};
19 use hezarfen_backend::domain::board_stroke::{BoardStroke, BoardStrokeId};20 use hezarfen_backend::domain::board_stroke::{BoardStroke, BoardStrokeId};
20 use hezarfen_backend::domain::chatbot_message::ChatbotMessage;21 use hezarfen_backend::domain::chatbot_message::ChatbotMessage;
@@ -25,7 +26,6 @@ use hezarfen_backend::domain::course_note_file::CourseNoteFileId;
25 use hezarfen_backend::domain::exam::ExamId;26 use hezarfen_backend::domain::exam::ExamId;
26 use hezarfen_backend::domain::exam_attempt::ExamAttempt;27 use hezarfen_backend::domain::exam_attempt::ExamAttempt;
27 use hezarfen_backend::domain::rag_output::RagOutput;28 use hezarfen_backend::domain::rag_output::RagOutput;
28-use hezarfen_backend::domain::session::Session;
29 use hezarfen_backend::domain::timestamp::Timestamp;29 use hezarfen_backend::domain::timestamp::Timestamp;
30 use hezarfen_backend::domain::user::{Password, User, UserId, Username};30 use hezarfen_backend::domain::user::{Password, User, UserId, Username};
31 use hezarfen_backend::module::ModuleSet;31 use hezarfen_backend::module::ModuleSet;
@@ -5932,7 +5932,7 @@ async fn login_purges_expired_sessions() {
5932 .check()5932 .check()
5933 .unwrap();5933 .unwrap();
5934 assert!(5934 assert!(
5935- Session::find_by_token("expired-token", &db)5935+ session::find_by_token(&db, "expired-token")
5936 .await5936 .await
5937 .unwrap()5937 .unwrap()
5938 .is_some()5938 .is_some()
@@ -5941,7 +5941,7 @@ async fn login_purges_expired_sessions() {
5941 // A later successful login sweeps expired rows...5941 // A later successful login sweeps expired rows...
5942 login(&app, "veli").await;5942 login(&app, "veli").await;
5943 assert!(5943 assert!(
5944- Session::find_by_token("expired-token", &db)5944+ session::find_by_token(&db, "expired-token")
5945 .await5945 .await
5946 .unwrap()5946 .unwrap()
5947 .is_none(),5947 .is_none(),
@@ -5976,7 +5976,7 @@ async fn expired_session_is_unauthorized_before_any_purge() {
5976 5976
5977 // Row exists, but the clock says no.5977 // Row exists, but the clock says no.
5978 assert!(5978 assert!(
5979- Session::find_by_token("stale-token", &db)5979+ session::find_by_token(&db, "stale-token")
5980 .await5980 .await
5981 .unwrap()5981 .unwrap()
5982 .is_some()5982 .is_some()
tests/regress_attendance.rsmodified+3 -3
@@ -13,11 +13,11 @@ mod common;
13 use axum::http::StatusCode;13 use axum::http::StatusCode;
14 use common::{app_and_db, create_course, create_session, enroll, login, login_as, me_id, send};14 use common::{app_and_db, create_course, create_session, enroll, login, login_as, me_id, send};
15 use hezarfen_backend::database::Database;15 use hezarfen_backend::database::Database;
16+use hezarfen_backend::db::settings;
16 use hezarfen_backend::domain::attendance::{Attendance, AttendanceStatus};17 use hezarfen_backend::domain::attendance::{Attendance, AttendanceStatus};
17 use hezarfen_backend::domain::course_session::{CourseSession, CourseSessionId};18 use hezarfen_backend::domain::course_session::{CourseSession, CourseSessionId};
18 use hezarfen_backend::domain::event::EventId;19 use hezarfen_backend::domain::event::EventId;
19 use hezarfen_backend::domain::session_attendance::SessionAttendance;20 use hezarfen_backend::domain::session_attendance::SessionAttendance;
20-use hezarfen_backend::domain::settings::Settings;
21 use hezarfen_backend::domain::timestamp::Timestamp;21 use hezarfen_backend::domain::timestamp::Timestamp;
22 use hezarfen_backend::domain::user::UserId;22 use hezarfen_backend::domain::user::UserId;
23 use hezarfen_backend::error::AppError;23 use hezarfen_backend::error::AppError;
@@ -223,7 +223,7 @@ async fn a_mark_against_a_deleted_session_is_refused_and_stores_nothing() {
223 );223 );
224 224
225 // Then the mark arrives, still believing in its snapshot.225 // Then the mark arrives, still believing in its snapshot.
226- let school = Settings::load(&db).await.unwrap();226+ let school = settings::load(&db).await.unwrap();
227 let status = AttendanceStatus::try_new("present", school.get_attendance_statuses()).unwrap();227 let status = AttendanceStatus::try_new("present", school.get_attendance_statuses()).unwrap();
228 let marked = SessionAttendance::mark(228 let marked = SessionAttendance::mark(
229 &snapshot,229 &snapshot,
@@ -392,7 +392,7 @@ async fn an_event_mark_writes_its_event_and_is_refused_once_it_is_gone() {
392 );392 );
393 393
394 // And the mark that arrives after it is refused rather than stored.394 // And the mark that arrives after it is refused rather than stored.
395- let school = Settings::load(&db).await.unwrap();395+ let school = settings::load(&db).await.unwrap();
396 let status = AttendanceStatus::try_new("present", school.get_attendance_statuses()).unwrap();396 let status = AttendanceStatus::try_new("present", school.get_attendance_statuses()).unwrap();
397 let marked =397 let marked =
398 Attendance::mark(&EventId::from_key(&event), &ali_ref, status, &hoca_ref, &db).await;398 Attendance::mark(&EventId::from_key(&event), &ali_ref, status, &hoca_ref, &db).await;
tests/regress_roles.rsmodified+1 -1
@@ -688,7 +688,7 @@ async fn deleting_an_event_takes_its_children_with_it() {
688 688
689 /// The note half of the same defect: the attachment rows and the note commit689 /// The note half of the same defect: the attachment rows and the note commit
690 /// together, so an upload can no longer leave a `note_file` pointing at a note690 /// together, so an upload can no longer leave a `note_file` pointing at a note
691-/// that is gone (its *blob* goes too: `Note::delete` returns the rows it691+/// that is gone (its *blob* goes too: `db::note::delete` returns the rows it
692 /// removed and the handler unlinks exactly those).692 /// removed and the handler unlinks exactly those).
693 #[tokio::test]693 #[tokio::test]
694 async fn deleting_a_note_takes_its_attachment_rows_with_it() {694 async fn deleting_a_note_takes_its_attachment_rows_with_it() {