forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

settings.rs788 lines, 33.0 KiBHistoryRawDownload
1//! The settings edit workflow: snapshot-merge-guard-save, with every name-list
2//! guard and the compare-and-set riding ONE transaction, so two managers'
3//! patches can neither silently revert each other nor strand a half-applied
4//! removal. The singleton's queries live in [`crate::db::settings`].
5
6use crate::constant::CAS_UPDATE_RETRIES;
7use crate::database::{Database, tx_with_retry};
8use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings};
9use crate::error::AppError;
10
11/// The abort marker the edit transaction's closure raises when the guarded
12/// save wrote zero rows — the stored row moved under the snapshot this
13/// attempt was judged against. It never reaches the wire: [`apply`] maps it
14/// to another loop turn right here, and the transaction's rollback already
15/// took every retirement back with it. (Same abort-through-`Internal`
16/// pattern as `crate::db::field_update`'s markers: a refusal is a decision,
17/// so it must not be retried — this one is *un*-decided, which is exactly
18/// why the loop re-runs.)
19const STALE_SAVE: &str = "settings_save_lost_cas";
20
21/// The stored policy, or the defaults when no row exists yet.
22pub async fn load(db: &Database) -> Result<Settings, AppError> {
23 crate::db::settings::load(db).await
24}
25
26/// Persist the policy only while the stored row still matches `expected` —
27/// the compare-and-set. `None` means a concurrent edit landed in between:
28/// reload, re-merge, retry.
29pub async fn save_if_unchanged(
30 db: &Database,
31 settings: Settings,
32 expected: &Settings,
33) -> Result<Option<Settings>, AppError> {
34 crate::db::settings::save_if_unchanged(db, settings, expected).await
35}
36
37/// A `PATCH /settings` body after wire mapping: only the fields the school
38/// sent. Lists stay raw on purpose — validating them is the workflow's own
39/// step, in its own order, and keeping a stored meal-slot name skips the
40/// URL-charset rule (`MealSlotDef::try_kept`), which only [`apply`],
41/// holding the stored list, can decide.
42pub struct SettingsPatch {
43 pub exam_kinds: Option<Vec<ExamKindInput>>,
44 pub attendance_statuses: Option<Vec<String>>,
45 pub grade_bands: Option<Vec<GradeBandInput>>,
46 pub max_file_bytes: Option<i64>,
47 pub chatbot_history_turns: Option<i64>,
48 pub max_chatbot_threads: Option<i64>,
49 pub max_chatbot_message_len: Option<i64>,
50 pub meal_slots: Option<Vec<MealSlotInput>>,
51 pub dietary_tags: Option<Vec<String>>,
52 /// Absent keeps the knob; `Some(None)` clears it (no cutoff at all).
53 pub meal_cancel_cutoff_minutes: Option<Option<i64>>,
54 /// The school's subject-specialisation list, raw like `dietary_tags` (the
55 /// workflow's own validation step, holding the stored list, decides whether
56 /// an empty list means "keep" or "clear" — see `Settings::try_new`).
57 pub branches: Option<Vec<String>>,
58 /// The absence excuse kinds, raw like `branches`.
59 pub excuse_kinds: Option<Vec<String>>,
60 /// Absent keeps the limit; `Some(None)` clears it (no ceiling).
61 pub max_excused_absent_days: Option<Option<i64>>,
62 pub max_unexcused_absent_days: Option<Option<i64>>,
63 /// Absent keeps the zone; `Some(None)` restores the deployment default.
64 pub timezone: Option<Option<String>>,
65}
66
67/// One submitted exam kind, raw.
68pub struct ExamKindInput {
69 pub name: String,
70 pub weight: i64,
71}
72
73/// One submitted grade band, raw.
74pub struct GradeBandInput {
75 pub min: i64,
76 pub label: String,
77}
78
79/// One submitted meal slot, raw.
80pub struct MealSlotInput {
81 pub name: String,
82 pub serving_minute: Option<i64>,
83}
84
85/// The whole edit — snapshot, merge, guard, save — as one operation, so the
86/// tests can drive it the way two managers do.
87///
88/// The guards and the save share one transaction, and that is the whole
89/// guard: a list edit is a *pair* of writes — every name the edit drops is
90/// retired on its reference counter first (which refuses every later
91/// claim), and only then is the list itself committed with a
92/// compare-and-set against the snapshot the removals were judged from. The
93/// old engine could not serialize that pair on its own, so a process-wide
94/// lock held it together, and the winner-loses-rollback interaction between
95/// two same-snapshot attempts needed a hand-rolled undo list
96/// (`Unchanged`-erased which attempt owned a flip, so a no-op could undo a
97/// rival). Postgres needs neither: retirement and save commit together or
98/// not at all, a stale save rolls its retirements back by aborting, and the
99/// row-locked retire switch serializes two attempts dropping the same name.
100///
101/// Retired before the save, never after: the other order leaves a window in
102/// which a mark lands under a kind the settings no longer list. A save that
103/// then does not land undoes them — by transaction abort, before the next
104/// try, with no undo list to get wrong.
105pub async fn apply(db: &Database, patch: &SettingsPatch) -> Result<Settings, AppError> {
106 // Merge over a snapshot, then save only while the row still matches it —
107 // otherwise a concurrent PATCH of a *different* field would be silently
108 // reverted by whichever whole-row write lands second. A refused save
109 // reloads and re-merges, so both edits land.
110 for _ in 0..CAS_UPDATE_RETRIES {
111 let current = load(db).await?;
112
113 let exam_kinds = match &patch.exam_kinds {
114 Some(kinds) => kinds
115 .iter()
116 .map(|kind| ExamKindDef::try_new(&kind.name, kind.weight))
117 .collect::<Result<Vec<_>, _>>()?,
118 None => current.get_exam_kinds().to_vec(),
119 };
120 let was_slots = slot_names(&current.get_meal_slots());
121 let meal_slots = match &patch.meal_slots {
122 Some(slots) => slots
123 .iter()
124 .map(|slot| {
125 // A name the row already carries is validated as a kept one:
126 // the charset rule is younger than the stored lists, and
127 // re-validating one under it would leave a school unable to
128 // edit the rest of its slots at all (`MealSlotDef::try_kept`).
129 if was_slots.iter().any(|kept| kept == slot.name.trim()) {
130 MealSlotDef::try_kept(&slot.name, slot.serving_minute)
131 } else {
132 MealSlotDef::try_new(&slot.name, slot.serving_minute)
133 }
134 })
135 .collect::<Result<Vec<_>, _>>()?,
136 None => current.get_meal_slots(),
137 };
138 let attendance_statuses = patch
139 .attendance_statuses
140 .clone()
141 .unwrap_or_else(|| current.get_attendance_statuses().to_vec());
142 let grade_bands = match &patch.grade_bands {
143 Some(bands) => bands
144 .iter()
145 .map(|band| GradeBand::try_new(band.min, &band.label))
146 .collect::<Result<Vec<_>, _>>()?,
147 None => current.get_grade_bands().to_vec(),
148 };
149 // The name lists as they stand and as they would stand, for the removal
150 // guards below — a list edit is judged by which names it drops.
151 let was_kinds = kind_names(current.get_exam_kinds());
152 let now_kinds = kind_names(&exam_kinds);
153 let now_slots = slot_names(&meal_slots);
154
155 // Merge over the snapshot's resolved values: an omitted field keeps
156 // whatever the row (or the default behind an unset field) reads as.
157 let mut params = current.params();
158 params.exam_kinds = exam_kinds;
159 params.attendance_statuses = attendance_statuses;
160 params.grade_bands = grade_bands;
161 params.max_file_bytes = patch.max_file_bytes.unwrap_or(params.max_file_bytes);
162 params.chatbot_history_turns = patch
163 .chatbot_history_turns
164 .unwrap_or(params.chatbot_history_turns);
165 params.max_chatbot_threads = patch
166 .max_chatbot_threads
167 .unwrap_or(params.max_chatbot_threads);
168 params.max_chatbot_message_len = patch
169 .max_chatbot_message_len
170 .unwrap_or(params.max_chatbot_message_len);
171 params.meal_slots = meal_slots;
172 params.dietary_tags = patch
173 .dietary_tags
174 .clone()
175 .unwrap_or_else(|| current.get_dietary_tags());
176 // Double option: absent keeps the knob, `null` clears it (no cutoff).
177 params.meal_cancel_cutoff_minutes = patch
178 .meal_cancel_cutoff_minutes
179 .unwrap_or(params.meal_cancel_cutoff_minutes);
180 // The year's shape: the subject-specialisation and excuse-kind lists
181 // ride the same idiom as `dietary_tags` below — an *absent* field
182 // keeps the stored list, an explicitly submitted one replaces it whole
183 // (empty is a legal list: a school that never configured subject
184 // specialisations keeps none), and both are validated by
185 // `Settings::try_new` under the stored-list rules at the end of this
186 // merge.
187 params.branches = patch
188 .branches
189 .clone()
190 .unwrap_or_else(|| current.get_branches());
191 params.excuse_kinds = patch
192 .excuse_kinds
193 .clone()
194 .unwrap_or_else(|| current.get_excuse_kinds());
195 // Double option, exactly like `meal_cancel_cutoff_minutes`: absent
196 // keeps the ceiling, `null` clears it (no limit).
197 params.max_excused_absent_days = patch
198 .max_excused_absent_days
199 .unwrap_or(params.max_excused_absent_days);
200 params.max_unexcused_absent_days = patch
201 .max_unexcused_absent_days
202 .unwrap_or(params.max_unexcused_absent_days);
203 // …and the school's day-bucketing zone: absent keeps the stored one,
204 // `null` puts the deployment default back.
205 params.timezone = patch.timezone.clone().unwrap_or(params.timezone.clone());
206
207 let settings = Settings::try_new(params)?;
208
209 // Guards + save, one transaction. The removal refusals are the same
210 // 409s as ever; a stale save is the `STALE_SAVE` marker, answered by
211 // another loop turn below; everything else surfaces.
212 let attempted = tx_with_retry(db, false, async move |tx| {
213 // A name leaves a list by being *retired* on its reference
214 // counter — one row-locked switch, which lands only while
215 // nothing references the name and refuses every claim from that
216 // instant on. A refused removal aborts the transaction, taking
217 // any earlier retirement in this same attempt back with it.
218 for gone in missing(&was_kinds, &now_kinds) {
219 retire_kind(&mut *tx, &gone).await?;
220 }
221 // Same shape for meal slots: a slot a menu was already published
222 // for cannot leave the list — the menu snapshotted the name as
223 // text, and a slot no longer offered would leave that menu
224 // unreachable from the school's own list.
225 for gone in missing(&was_slots, &now_slots) {
226 retire_slot(&mut *tx, &gone).await?;
227 }
228 // A name re-entering a list is back in service: its counter still
229 // carries the retirement from the edit that dropped it, and a mark
230 // (or a menu) under a kind the school offers again must not be
231 // refused. Inside the transaction, "in service" stands only if
232 // the save below lands — a stale save aborts and re-retires it.
233 for back in missing(&now_kinds, &was_kinds) {
234 unretire_kind(&mut *tx, &back).await?;
235 }
236 for back in missing(&now_slots, &was_slots) {
237 unretire_slot(&mut *tx, &back).await?;
238 }
239
240 match crate::db::settings::save_if_unchanged(&mut *tx, settings.clone(), &current)
241 .await?
242 {
243 Some(saved) => Ok(saved),
244 // The row moved under the snapshot these guards were judged
245 // against: the abort puts the names back, and the caller's
246 // loop re-merges — or the next attempt would decide against a
247 // list nobody asked for.
248 None => Err(AppError::Internal(STALE_SAVE.to_string())),
249 }
250 })
251 .await;
252
253 match attempted {
254 Ok(saved) => return Ok(saved),
255 Err(AppError::Internal(marker)) if marker == STALE_SAVE => continue,
256 Err(err) => return Err(err),
257 }
258 }
259 Err(AppError::Conflict(
260 "the settings kept changing underneath this update — try again",
261 ))
262}
263
264/// Retire an exam kind on its reference counter, inside the caller's
265/// transaction — the row-locked switch of the `cap` module's retire recipe:
266/// the row is read `FOR UPDATE` first, so the read of `retired` and the flip
267/// are one unit against a concurrent claim or retire. The flip landing and
268/// the flip already standing are both success — the transaction that follows
269/// decides whether the retired state stands, so `Unchanged` needs no
270/// bookkeeping (the database owns the rollback).
271///
272/// The name still referenced (`count > 0`) is the caller's removal refusal,
273/// byte for byte the old 409.
274async fn retire_kind(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppError> {
275 let landed = sqlx::query!(
276 r#"INSERT INTO kind_ref (name, count, retired) VALUES ($1, 0, TRUE)
277 ON CONFLICT (name) DO UPDATE SET retired = TRUE
278 WHERE kind_ref.count = 0 AND kind_ref.retired IS DISTINCT FROM TRUE
279 RETURNING 1 AS "landed!: i64""#,
280 name
281 )
282 .fetch_optional(&mut *tx)
283 .await?
284 .is_some();
285 if landed {
286 // Flipped by this call: nothing to do — the transaction decides
287 // whether the retirement stands.
288 return Ok(());
289 }
290 // The upsert's `WHERE` refused the flip. Under READ COMMITTED the row it
291 // conflicted with may have committed *after* this transaction's first
292 // snapshot, so the settled state is read here rather than carried over:
293 // still in use (`count > 0`) is the removal refusal, byte for byte the
294 // old 409; already retired (with nothing referencing it) is a rival
295 // having decided the same removal — success, same as a fresh flip.
296 let row = sqlx::query!(
297 r#"SELECT count AS "count!: i64", retired AS "retired!: bool"
298 FROM kind_ref WHERE name = $1 FOR UPDATE"#,
299 name
300 )
301 .fetch_one(&mut *tx)
302 .await?;
303 if row.count > 0 {
304 return Err(AppError::ConflictOwned(format!(
305 "exams of kind '{name}' are already graded — the kind cannot be removed"
306 )));
307 }
308 let _ = row.retired;
309 Ok(())
310}
311
312/// [`retire_kind`] against the meal-slot counters.
313async fn retire_slot(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppError> {
314 // Same shape as [`retire_kind`]: the settled row is read *after* the
315 // refused flip, never carried over from this transaction's first
316 // snapshot — a rival's retirement may have committed in between, and
317 // that is success, not a refusal.
318 let landed = sqlx::query!(
319 r#"INSERT INTO slot_ref (name, count, retired) VALUES ($1, 0, TRUE)
320 ON CONFLICT (name) DO UPDATE SET retired = TRUE
321 WHERE slot_ref.count = 0 AND slot_ref.retired IS DISTINCT FROM TRUE
322 RETURNING 1 AS "landed!: i64""#,
323 name
324 )
325 .fetch_optional(&mut *tx)
326 .await?
327 .is_some();
328 if landed {
329 return Ok(());
330 }
331 let row = sqlx::query!(
332 r#"SELECT count AS "count!: i64" FROM slot_ref WHERE name = $1 FOR UPDATE"#,
333 name
334 )
335 .fetch_one(&mut *tx)
336 .await?;
337 if row.count > 0 {
338 return Err(AppError::ConflictOwned(format!(
339 "menus are already published for the '{name}' slot — it cannot be removed"
340 )));
341 }
342 Ok(())
343}
344
345/// Put an exam kind back in service, inside the caller's transaction. One
346/// guarded write: the flip lands only while the name is actually retired, so
347/// it is idempotent. Whether the name *stays* in service is the save's
348/// decision — a stale save aborts this transaction and the retirement stands
349/// again, with no undo list to get wrong.
350async fn unretire_kind(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppError> {
351 sqlx::query!(
352 r#"INSERT INTO kind_ref (name, count, retired) VALUES ($1, 0, FALSE)
353 ON CONFLICT (name) DO UPDATE SET retired = FALSE
354 WHERE kind_ref.retired IS DISTINCT FROM FALSE
355 RETURNING 1 AS "landed!: i64""#,
356 name
357 )
358 .fetch_optional(&mut *tx)
359 .await?;
360 Ok(())
361}
362
363/// [`unretire_kind`] against the meal-slot counters.
364async fn unretire_slot(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppError> {
365 sqlx::query!(
366 r#"INSERT INTO slot_ref (name, count, retired) VALUES ($1, 0, FALSE)
367 ON CONFLICT (name) DO UPDATE SET retired = FALSE
368 WHERE slot_ref.retired IS DISTINCT FROM FALSE
369 RETURNING 1 AS "landed!: i64""#,
370 name
371 )
372 .fetch_optional(&mut *tx)
373 .await?;
374 Ok(())
375}
376
377fn kind_names(kinds: &[ExamKindDef]) -> Vec<String> {
378 kinds
379 .iter()
380 .map(|kind| kind.get_name().to_string())
381 .collect()
382}
383
384fn slot_names(slots: &[MealSlotDef]) -> Vec<String> {
385 slots
386 .iter()
387 .map(|slot| slot.get_name().to_string())
388 .collect()
389}
390
391/// The names `before` carries that `after` does not — a list edit's removals,
392/// or its additions with the arguments swapped.
393fn missing(before: &[String], after: &[String]) -> Vec<String> {
394 before
395 .iter()
396 .filter(|name| !after.contains(name))
397 .cloned()
398 .collect()
399}
400
401#[cfg(test)]
402mod tests {
403 use super::*;
404 use crate::database::init_test_db;
405 use crate::db::settings::save;
406
407 /// The `retired` bit as the store holds it, `None` when no counter row was
408 /// ever written — read back, never inferred from a return value.
409 async fn ref_bit(db: &Database, table: &str, name: &str) -> Option<bool> {
410 use sqlx::Row as _;
411
412 let row = sqlx::query(sqlx::AssertSqlSafe(format!(
413 "SELECT retired FROM {table} WHERE name = $1"
414 )))
415 .bind(name)
416 .fetch_optional(db)
417 .await
418 .unwrap();
419 row.map(|row| row.try_get::<bool, _>(0).unwrap())
420 }
421
422 /// [`ref_bit`] against the exam-kind counters.
423 async fn kind_bit(db: &Database, name: &str) -> Option<bool> {
424 ref_bit(db, "kind_ref", name).await
425 }
426
427 /// [`ref_bit`] against the meal-slot counters.
428 async fn slot_bit(db: &Database, name: &str) -> Option<bool> {
429 ref_bit(db, "slot_ref", name).await
430 }
431
432 /// Two managers drop the same exam kind at once; one of them loses the
433 /// row's compare-and-set and rolls its attempt back. The winner's
434 /// retirement must survive that rollback — undone, the kind is off the list
435 /// with a counter that still grades, and the first mark to land makes it
436 /// unremovable for good.
437 ///
438 /// The loser's half is what runs here: a retirement that changed nothing
439 /// records no undo, so `restore` has nothing to take back.
440 #[tokio::test]
441 async fn the_loser_of_a_settings_race_cannot_un_retire_the_winner_s_kind() {
442 let (db, _leases) = init_test_db().await;
443 // Two managers send the same removal, each having decided it against
444 // the same original list. The winner's attempt retires the kind and
445 // saves; the loser's save loses the compare-and-set, aborts — taking
446 // every write of its attempt back with it — and retries against the
447 // fresh list, where the same PATCH is a no-op that flips nothing.
448 // (The old engine needed a hand-rolled undo list for this; the
449 // transaction's own rollback is the undo now.)
450 let without_sozlu = SettingsPatch {
451 exam_kinds: Some(kinds(&["yazili", "uygulama"])),
452 ..a_patch()
453 };
454 apply(&db, &without_sozlu).await.unwrap(); // the winner
455 apply(&db, &without_sozlu).await.unwrap(); // the loser, retried
456
457 assert_eq!(
458 kind_bit(&db, "sozlu").await,
459 Some(true),
460 "the winner's retirement must outlive the loser's rollback"
461 );
462 assert!(!stored(&db).await.0.contains(&"sozlu".to_string()));
463 }
464
465 /// The mirror hole: a re-*added* name is put back in service before the
466 /// save, so a save that does not land owes a re-retirement. Without it the
467 /// name is off the stored list with a counter that grades happily.
468 #[tokio::test]
469 async fn a_rollback_re_retires_a_name_this_attempt_put_back_in_service() {
470 let (db, _leases) = init_test_db().await;
471 // The stored list drops lunch; the slot counter carries the retirement.
472 let without = SettingsPatch {
473 meal_slots: Some(slots(&["breakfast", "snack"])),
474 ..a_patch()
475 };
476 apply(&db, &without).await.unwrap();
477 assert_eq!(slot_bit(&db, "lunch").await, Some(true));
478
479 // An attempt re-adds the slot but judged the write against the row
480 // *before* a rival's unrelated edit landed: its guarded save writes
481 // zero rows, and — inside [`apply`] — the abort would take the
482 // attempt's un-retirement straight back with it. Driven here at the
483 // save the way the loser experiences it: refused, so nothing lands.
484 let stale_snapshot = load(&db).await.unwrap();
485 let elsewhere = SettingsPatch {
486 max_file_bytes: Some(2048),
487 ..a_patch()
488 };
489 apply(&db, &elsewhere).await.unwrap();
490
491 let mut params = Settings::defaults().params();
492 params.meal_slots = vec![MealSlotDef::try_new("lunch", None).unwrap()];
493 let re_added = Settings::try_new(params).unwrap();
494 let landed = crate::db::settings::save_if_unchanged(&db, re_added, &stale_snapshot)
495 .await
496 .unwrap();
497 assert!(landed.is_none(), "the stale save must be refused");
498
499 assert_eq!(
500 slot_bit(&db, "lunch").await,
501 Some(true),
502 "a re-add that never landed must leave the slot retired"
503 );
504 }
505
506 /// ...unless a menu was published in the window the slot was back in
507 /// service. The reference is real, so the re-retirement is refused and the
508 /// slot stays usable — the honest end of the same rule, not a silent
509 /// overwrite of a live reference.
510 #[tokio::test]
511 async fn a_rollback_leaves_a_name_that_gained_a_reference_in_service() {
512 let (db, _leases) = init_test_db().await;
513 // Lunch goes away and comes back, and while it is in service a menu is
514 // published against it — the live reference the counter counts.
515 let without = SettingsPatch {
516 meal_slots: Some(slots(&["breakfast", "snack"])),
517 ..a_patch()
518 };
519 apply(&db, &without).await.unwrap();
520 let with = SettingsPatch {
521 meal_slots: Some(slots(&["breakfast", "lunch", "snack"])),
522 ..a_patch()
523 };
524 apply(&db, &with).await.unwrap();
525 sqlx::query("UPDATE slot_ref SET count = 1 WHERE name = 'lunch'")
526 .execute(&db)
527 .await
528 .unwrap();
529
530 // The attempt that takes lunch away again now meets the reference: the
531 // removal is refused — honestly, with the published-menu 409, not by
532 // silently overwriting a live reference — and the slot stays usable.
533 let refused = apply(&db, &without).await;
534 assert!(
535 matches!(refused, Err(AppError::ConflictOwned(ref msg)) if msg.contains("'lunch'")),
536 "a referenced slot's removal must be refused: {refused:?}"
537 );
538 assert_eq!(slot_bit(&db, "lunch").await, Some(false));
539 }
540
541 // --- the whole edit, driven the way two managers drive it -------------
542
543 /// A `PATCH` body that names nothing: every field keeps the stored value.
544 fn a_patch() -> SettingsPatch {
545 SettingsPatch {
546 exam_kinds: None,
547 attendance_statuses: None,
548 grade_bands: None,
549 max_file_bytes: None,
550 chatbot_history_turns: None,
551 max_chatbot_threads: None,
552 max_chatbot_message_len: None,
553 meal_slots: None,
554 dietary_tags: None,
555 meal_cancel_cutoff_minutes: None,
556 branches: None,
557 excuse_kinds: None,
558 max_excused_absent_days: None,
559 max_unexcused_absent_days: None,
560 timezone: None,
561 }
562 }
563
564 /// An `exam_kinds` list as the router builds it (weight 1, like the
565 /// harness bodies).
566 fn kinds(names: &[&str]) -> Vec<ExamKindInput> {
567 names
568 .iter()
569 .map(|name| ExamKindInput {
570 name: (*name).to_string(),
571 weight: 1,
572 })
573 .collect()
574 }
575
576 /// A `meal_slots` list as the router builds it (no serving minute).
577 fn slots(names: &[&str]) -> Vec<MealSlotInput> {
578 names
579 .iter()
580 .map(|name| MealSlotInput {
581 name: (*name).to_string(),
582 serving_minute: None,
583 })
584 .collect()
585 }
586
587 /// The lists as the store holds them.
588 async fn stored(db: &Database) -> (Vec<String>, Vec<String>) {
589 let settings = load(db).await.unwrap();
590 (
591 kind_names(settings.get_exam_kinds()),
592 slot_names(&settings.get_meal_slots()),
593 )
594 }
595
596 /// The whole invariant, over the reachable half of the race: two managers
597 /// drop the same exam kind at once, both edits go through the real path,
598 /// and when both have returned the counter's `retired` bit must agree with
599 /// the list the store actually holds.
600 ///
601 /// One of the two decides the removal, retires the kind and saves; the
602 /// other cannot even see the old list, because retirement and save share
603 /// one transaction. Interleaved, the second attempt would be told "already
604 /// retired", record no undo, win the compare-and-set, and leave the first
605 /// attempt un-retiring the kind it had legitimately removed — off the list
606 /// and gradable.
607 #[tokio::test]
608 async fn two_edits_dropping_the_same_kind_leave_it_retired() {
609 let (db, _leases) = init_test_db().await;
610 let without = SettingsPatch {
611 exam_kinds: Some(kinds(&["yazili", "uygulama"])),
612 ..a_patch()
613 };
614
615 let (a, b) = tokio::join!(apply(&db, &without), apply(&db, &without));
616 a.unwrap();
617 b.unwrap();
618
619 let (kinds, _) = stored(&db).await;
620 assert!(
621 !kinds.contains(&"sozlu".to_string()),
622 "dropped from the list"
623 );
624 assert_eq!(
625 kind_bit(&db, "sozlu").await,
626 Some(true),
627 "a kind the stored list no longer offers must not grade"
628 );
629 }
630
631 /// The property those two outcomes rest on, asserted on its own because a
632 /// `join!` cannot be made to schedule the losing order: the edit is a pair
633 /// of writes — retire the dropped names, then commit the list — and no
634 /// rival's pair may run between them.
635 ///
636 /// Retirement is idempotent, so an interleaved rival is told "already
637 /// retired", records no rollback, wins the compare-and-set, and leaves the
638 /// attempt that really flipped the bit un-retiring a kind the stored list
639 /// no longer offers: gradable again, and unremovable for good once a mark
640 /// lands. Holding the lock stands in for a rival mid-pair here — nothing
641 /// the other edit does may be visible until the pair completes.
642 #[tokio::test]
643 async fn a_rival_edit_cannot_run_between_a_retirement_and_its_save() {
644 let (db, _leases) = init_test_db().await;
645 let without = SettingsPatch {
646 exam_kinds: Some(kinds(&["yazili", "uygulama"])),
647 ..a_patch()
648 };
649
650 // The retire-then-save pair is one transaction, so a rival reading the
651 // store while the edit runs can see the pair wholly unlanded or wholly
652 // landed — never the retirement without the list commit that was the
653 // old lock's whole job to prevent. Poll the edit from the outside and
654 // assert that at every instant.
655 let rival = tokio::spawn({
656 let db = db.clone();
657 async move { apply(&db, &without).await.map(|_| ()) }
658 });
659 while !rival.is_finished() {
660 // The bit is read BEFORE the list: a `true` bit proves the edit's
661 // commit already landed, so the list read that follows cannot
662 // predate it. The other order races the commit between the two
663 // probes and "sees" a split that never existed.
664 let retired = kind_bit(&db, "sozlu").await;
665 let (kinds, _) = stored(&db).await;
666 if retired == Some(true) {
667 assert!(
668 !kinds.contains(&"sozlu".to_string()),
669 "a retirement became visible before its list commit"
670 );
671 }
672 if retired == Some(false) {
673 assert!(
674 kinds.contains(&"sozlu".to_string()),
675 "an un-retirement became visible before its list commit"
676 );
677 }
678 tokio::task::yield_now().await;
679 }
680
681 rival.await.unwrap().unwrap();
682 assert_eq!(kind_bit(&db, "sozlu").await, Some(true));
683 assert!(!stored(&db).await.0.contains(&"sozlu".to_string()));
684 }
685
686 /// The mirror: two managers put the same kind *back* at once. The attempt
687 /// that loses must not re-retire a name the winner's stored list carries —
688 /// a listed kind that refuses every grade.
689 #[tokio::test]
690 async fn two_edits_re_adding_the_same_kind_leave_it_in_service() {
691 let (db, _leases) = init_test_db().await;
692 let without = SettingsPatch {
693 exam_kinds: Some(kinds(&["yazili", "uygulama"])),
694 ..a_patch()
695 };
696 apply(&db, &without).await.unwrap();
697 let with = SettingsPatch {
698 exam_kinds: Some(kinds(&["yazili", "sozlu", "uygulama"])),
699 ..a_patch()
700 };
701
702 let (a, b) = tokio::join!(apply(&db, &with), apply(&db, &with));
703 a.unwrap();
704 b.unwrap();
705
706 let (kinds, _) = stored(&db).await;
707 assert!(kinds.contains(&"sozlu".to_string()), "back on the list");
708 assert_eq!(
709 kind_bit(&db, "sozlu").await,
710 Some(false),
711 "a kind the stored list offers must grade"
712 );
713 }
714
715 /// The same pair over meal slots, which retire on their own counters.
716 #[tokio::test]
717 async fn two_edits_dropping_the_same_slot_leave_it_retired() {
718 let (db, _leases) = init_test_db().await;
719 let without = SettingsPatch {
720 meal_slots: Some(slots(&["breakfast", "snack"])),
721 ..a_patch()
722 };
723
724 let (a, b) = tokio::join!(apply(&db, &without), apply(&db, &without));
725 a.unwrap();
726 b.unwrap();
727
728 let (_, stored_slots) = stored(&db).await;
729 assert!(!stored_slots.contains(&"lunch".to_string()));
730 assert_eq!(slot_bit(&db, "lunch").await, Some(true));
731 }
732
733 // --- the stale slot name that wedged the whole list -------------------
734
735 /// A school that stored `a/b` before the URL-safety rule existed.
736 async fn a_school_with_a_stale_slot(db: &Database) {
737 let mut params = Settings::defaults().params();
738 params.meal_slots = vec![
739 MealSlotDef::try_kept("a/b", None).unwrap(),
740 MealSlotDef::try_new("lunch", None).unwrap(),
741 ];
742 save(db, Settings::try_new(params).unwrap()).await.unwrap();
743 }
744
745 /// The wedge: re-sending a stored name is the only way to *keep* it, and
746 /// dropping it 409s once a menu references it — so validating it under the
747 /// younger rule locks the school out of its own `meal_slots` forever. A
748 /// stored name is submittable; a new one with the same characters is not.
749 #[tokio::test]
750 async fn a_stored_slot_name_stays_submittable_but_a_new_one_does_not() {
751 let (db, _leases) = init_test_db().await;
752 a_school_with_a_stale_slot(&db).await;
753
754 let edit = SettingsPatch {
755 meal_slots: Some(slots(&["a/b", "lunch", "dinner"])),
756 ..a_patch()
757 };
758 apply(&db, &edit).await.unwrap();
759 let (_, stored_slots) = stored(&db).await;
760 assert_eq!(stored_slots, ["a/b", "lunch", "dinner"]);
761
762 let fresh = SettingsPatch {
763 meal_slots: Some(slots(&["a/b", "lunch", "c/d"])),
764 ..a_patch()
765 };
766 assert!(
767 apply(&db, &fresh).await.is_err(),
768 "a name no school ever stored is still refused"
769 );
770 }
771
772 /// And an edit that never mentions `meal_slots` still carries the list
773 /// over unvalidated — the behaviour the wedge report leaned on.
774 #[tokio::test]
775 async fn an_unrelated_edit_carries_a_stale_slot_name_over() {
776 let (db, _leases) = init_test_db().await;
777 a_school_with_a_stale_slot(&db).await;
778
779 let elsewhere = SettingsPatch {
780 max_file_bytes: Some(2048),
781 ..a_patch()
782 };
783 let saved = apply(&db, &elsewhere).await.unwrap();
784
785 assert_eq!(saved.get_max_file_bytes(), 2048);
786 assert_eq!(slot_names(&saved.get_meal_slots()), ["a/b", "lunch"]);
787 }
788}