forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB0346717Ahmet Kaan Gümüş3 months ago230 commits

settings.rs801 lines, 34.4 KiBHistoryRawDownload
1use axum::Json;
2use axum::extract::State;
3use serde::{Deserialize, Serialize};
4use utoipa::ToSchema;
5use utoipa_axum::router::OpenApiRouter;
6use utoipa_axum::routes;
7
8use surrealdb::types::RecordId;
9
10use crate::constant::CAS_UPDATE_RETRIES;
11use crate::database::Database;
12use crate::domain::cap;
13use crate::domain::exam_result::kind_ref;
14use crate::domain::menu::slot_ref;
15use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, SETTINGS_LOCK, Settings};
16use crate::error::{AppError, ErrorResponse};
17use crate::state::AppState;
18
19use super::{CurrentUser, RequireManager, set_or_clear};
20
21pub fn routes() -> OpenApiRouter<AppState> {
22 OpenApiRouter::new().routes(routes!(get_settings, update_settings))
23}
24
25/// One exam kind the school runs, with its weight in course averages. An exam
26/// of this kind counts `weight` times into `Σ(mark×weight) / Σ(weight)`.
27#[derive(Serialize, Deserialize, ToSchema)]
28struct ExamKindDto {
29 /// The `kind` value exams carry, 1–50 characters.
30 #[schema(example = "midterm", max_length = 50)]
31 name: String,
32 /// The kind's weight in the course average, `1`–`100`. Editing it
33 /// re-weights every exam of this kind at once.
34 #[schema(example = 2, minimum = 1, maximum = 100)]
35 weight: i64,
36}
37
38/// One meal slot the school serves. A published menu snapshots this name, so
39/// renaming or retiring a slot never rewrites a past menu.
40#[derive(Serialize, Deserialize, ToSchema)]
41struct MealSlotDto {
42 /// The `slot` value menus carry, 1–50 characters.
43 #[schema(example = "lunch", max_length = 50)]
44 name: String,
45 /// When the slot is served, as minutes past midnight **UTC** on the menu's
46 /// date (`0`–`1439`; `720` = 12:00 UTC). `meal_cancel_cutoff_minutes`
47 /// counts back from this instant.
48 ///
49 /// **The clock is UTC, not local time** — this API stores no school
50 /// timezone, so a UTC+3 school enters `540` (09:00 UTC) for a meal served
51 /// at noon locally. `null` = unset, and then the cutoff counts back from
52 /// midnight UTC of the menu's date, the pre-serving-time behaviour.
53 #[schema(example = 720, minimum = 0, maximum = 1_439)]
54 serving_minute: Option<i64>,
55}
56
57/// One grade-display band: marks at or above `min` (and below the next band's
58/// `min`) render as `label`.
59#[derive(Serialize, Deserialize, ToSchema)]
60struct GradeBandDto {
61 /// Lowest mark of the band, `0`–`100`. One band must start at `0`.
62 #[schema(example = 85, minimum = 0, maximum = 100)]
63 min: i64,
64 /// What that range shows as, 1–20 characters (`"AA"`, `"5"`, `"pass"`).
65 #[schema(example = "AA", max_length = 20)]
66 label: String,
67}
68
69/// The school's policy: which exam kinds exist (and their weights in course
70/// averages), which attendance statuses the roll call accepts, and how
71/// numeric marks display as grades.
72#[derive(Serialize, ToSchema)]
73struct SettingsResponse {
74 /// Accepted `kind` values for new exams, each with its weight in the
75 /// course average.
76 #[schema(example = json!([
77 {"name": "midterm", "weight": 2},
78 {"name": "final", "weight": 3},
79 {"name": "oral", "weight": 1},
80 ]))]
81 exam_kinds: Vec<ExamKindDto>,
82 /// Accepted `status` values for attendance marking. Always contains the
83 /// core four (`present`, `absent`, `late`, `excused`).
84 #[schema(example = json!(["present", "absent", "late", "excused"]))]
85 attendance_statuses: Vec<String>,
86 /// Grade-display bands, highest first. Empty = marks display numeric-only.
87 grade_bands: Vec<GradeBandDto>,
88 /// Per-file size limit for note uploads, in bytes.
89 #[schema(example = 5_242_880)]
90 max_file_bytes: i64,
91 /// How many prior turns of a thread the chatbot is given as context.
92 #[schema(example = 10)]
93 chatbot_history_turns: i64,
94 /// How many chatbot threads one user may keep.
95 #[schema(example = 50)]
96 max_chatbot_threads: i64,
97 /// Character limit on one chat message.
98 #[schema(example = 4000)]
99 max_chatbot_message_len: i64,
100 /// Meal slots menus may be published for, each with the UTC minute it is
101 /// served at (`null` = unset → the cutoff counts back from midnight UTC).
102 /// Empty = the school runs no meal program.
103 #[schema(example = json!([
104 {"name": "breakfast", "serving_minute": 300},
105 {"name": "lunch", "serving_minute": 720},
106 {"name": "snack", "serving_minute": null},
107 ]))]
108 meal_slots: Vec<MealSlotDto>,
109 /// Dietary tags a dish and a student's profile may carry.
110 #[schema(example = json!(["vegetarian", "vegan", "gluten_free"]))]
111 dietary_tags: Vec<String>,
112 /// How many minutes before a slot's `serving_minute` booking and
113 /// cancelling close. `null` = no cutoff.
114 #[schema(example = 120)]
115 meal_cancel_cutoff_minutes: Option<i64>,
116}
117
118impl SettingsResponse {
119 fn new(settings: &Settings) -> Self {
120 Self {
121 exam_kinds: settings
122 .get_exam_kinds()
123 .iter()
124 .map(|kind| ExamKindDto {
125 name: kind.get_name().to_string(),
126 weight: kind.get_weight(),
127 })
128 .collect(),
129 attendance_statuses: settings.get_attendance_statuses().to_vec(),
130 grade_bands: settings
131 .get_grade_bands()
132 .iter()
133 .map(|band| GradeBandDto {
134 min: band.get_min(),
135 label: band.get_label().to_string(),
136 })
137 .collect(),
138 max_file_bytes: settings.get_max_file_bytes(),
139 chatbot_history_turns: settings.get_chatbot_history_turns(),
140 max_chatbot_threads: settings.get_max_chatbot_threads(),
141 max_chatbot_message_len: settings.get_max_chatbot_message_len(),
142 meal_slots: settings
143 .get_meal_slots()
144 .iter()
145 .map(|slot| MealSlotDto {
146 name: slot.get_name().to_string(),
147 serving_minute: slot.get_serving_minute(),
148 })
149 .collect(),
150 dietary_tags: settings.get_dietary_tags(),
151 meal_cancel_cutoff_minutes: settings.get_meal_cancel_cutoff_minutes(),
152 }
153 }
154}
155
156#[derive(Deserialize, ToSchema)]
157struct UpdateSettings {
158 /// Replaces the whole list when present: 1–20 entries with unique names,
159 /// each name 1–50 characters, each weight `1`–`100`.
160 #[schema(max_items = 20)]
161 exam_kinds: Option<Vec<ExamKindDto>>,
162 /// Replaces the whole list when present; must keep `present`, `absent`,
163 /// `late`, `excused` (the attendance rate is defined over them). Each entry
164 /// is 1–50 characters.
165 #[schema(max_items = 20)]
166 attendance_statuses: Option<Vec<String>>,
167 /// Replaces the whole set when present. `[]` clears the bands (numeric-only
168 /// marks); otherwise mins are unique and one band must start at `0`.
169 #[schema(max_items = 20)]
170 grade_bands: Option<Vec<GradeBandDto>>,
171 /// Per-file size limit for note uploads, in bytes:
172 /// `1024` (1 KiB) – `26214400` (25 MiB). The ceiling is a server hard cap.
173 #[schema(example = 5_242_880, minimum = 1_024, maximum = 26_214_400)]
174 max_file_bytes: Option<i64>,
175 /// How many prior turns of a thread the chatbot is given as context,
176 /// `1`–`50`. Every turn is re-sent on every reply, so this costs tokens.
177 #[schema(example = 10, minimum = 1, maximum = 50)]
178 chatbot_history_turns: Option<i64>,
179 /// How many chatbot threads one user may keep, `1`–`500`. At the cap
180 /// the user deletes an old thread before starting a new one.
181 #[schema(example = 50, minimum = 1, maximum = 500)]
182 max_chatbot_threads: Option<i64>,
183 /// Character limit on one chat message, `100`–`8000`. The ceiling is a
184 /// server hard cap.
185 #[schema(example = 4000, minimum = 100, maximum = 8_000)]
186 max_chatbot_message_len: Option<i64>,
187 /// Replaces the whole list when present: at most 20 entries with unique
188 /// names, each 1–50 characters, each with an optional `serving_minute`
189 /// (minutes past midnight **UTC**, `0`–`1439`) the booking cutoff counts
190 /// back from. `[]` switches the meal program off. A slot a menu was already
191 /// published for cannot be removed (409); its serving time may be edited
192 /// freely and applies live, to menus already published for it too. Names
193 /// must not contain `/ \ ? # %` (a menu's id carries the name into a URL) —
194 /// except a name the school already stores, which stays submittable so a
195 /// list written before that rule can still be edited.
196 #[schema(max_items = 20)]
197 meal_slots: Option<Vec<MealSlotDto>>,
198 /// Replaces the whole list when present: at most 20 unique entries, each
199 /// 1–50 characters. `[]` means the school tracks no dietary tags.
200 #[schema(max_items = 20)]
201 dietary_tags: Option<Vec<String>>,
202 /// Minutes before a slot's `serving_minute` at which booking *and*
203 /// cancelling close, `0`–`10080` (one week). A slot with no serving time
204 /// is measured from midnight UTC of the menu's date instead. Omit to keep the current value; send `null` for
205 /// no cutoff at all.
206 #[serde(default, deserialize_with = "set_or_clear")]
207 #[schema(value_type = Option<i64>, example = 120, minimum = 0, maximum = 10_080)]
208 meal_cancel_cutoff_minutes: Option<Option<i64>>,
209}
210
211/// The school's current policy. Any authenticated user — clients need it to
212/// render pickers and grades. Falls back to the built-in defaults until a
213/// manager edits it.
214#[utoipa::path(
215 get,
216 path = "/",
217 tag = "settings",
218 security(("session_cookie" = [])),
219 responses(
220 (status = 200, description = "The school's policy", body = SettingsResponse),
221 (status = 401, description = "Not authenticated", body = ErrorResponse),
222 ),
223)]
224async fn get_settings(
225 State(st): State<AppState>,
226 CurrentUser(_user): CurrentUser,
227) -> Result<Json<SettingsResponse>, AppError> {
228 let settings = Settings::load(&st.db).await?;
229 Ok(Json(SettingsResponse::new(&settings)))
230}
231
232/// Update the school's policy. Requires manager+. Omitted fields keep their
233/// value; a present field replaces its list wholesale. Existing rows are
234/// untouched — a removed exam kind or status lives on in old records; only
235/// new writes are held to the new lists. Kind weights, though, apply live:
236/// mark reports read them at request time, so editing a weight re-weights
237/// every exam of that kind. For that reason a kind whose exams already carry
238/// marks cannot be dropped from the list (409) — those marks would silently
239/// re-weight to 1; an unmarked kind leaves freely, and an exam whose kind is
240/// gone counts with weight 1 but cannot be graded (409) until the kind
241/// returns — the other end of the same rule. `max_file_bytes` likewise
242/// applies at upload time only — already-stored files keep their size, and the
243/// chatbot knobs apply to the next chat request only. `meal_slots` follows the
244/// exam-kind rule: a slot a menu was already published for cannot be dropped
245/// (409), because the menu snapshotted its name. Slot names must not contain
246/// `/ \ ? # %` (400) — a menu's id carries the name into a URL — but a name
247/// already on the school's stored list is exempt, so a list written before that
248/// rule can still be edited around it.
249#[utoipa::path(
250 patch,
251 path = "/",
252 tag = "settings",
253 security(("session_cookie" = [])),
254 request_body = UpdateSettings,
255 responses(
256 (status = 200, description = "Updated policy", body = SettingsResponse),
257 (status = 400, description = "Invalid lists, bands, file limit, or chat limits", body = ErrorResponse),
258 (status = 401, description = "Not authenticated", body = ErrorResponse),
259 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
260 (status = 409, description = "A removed exam kind still has graded exams, a removed meal slot still has published menus, or concurrent edits kept changing the settings mid-save", body = ErrorResponse),
261 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
262 ),
263)]
264async fn update_settings(
265 State(st): State<AppState>,
266 RequireManager(_user): RequireManager,
267 Json(req): Json<UpdateSettings>,
268) -> Result<Json<SettingsResponse>, AppError> {
269 Ok(Json(SettingsResponse::new(&apply(&req, &st.db).await?)))
270}
271
272/// The whole edit — snapshot, merge, retire, save — as one operation, so the
273/// tests can drive it the way two managers do. Split out of the handler for
274/// nothing else.
275async fn apply(req: &UpdateSettings, db: &Database) -> Result<Settings, AppError> {
276 // One settings edit at a time: the removals below are decided against the
277 // snapshot this loop loads and written *before* the save that justifies
278 // them, and no per-name bookkeeping can make that pair survive a rival's
279 // pair interleaving with it (see `SETTINGS_LOCK`).
280 let _guard = SETTINGS_LOCK.lock().await;
281 // Merge over a snapshot, then save only while the row still matches it —
282 // otherwise a concurrent PATCH of a *different* field would be silently
283 // reverted by whichever whole-row write lands second. A refused save
284 // reloads and re-merges, so both edits land.
285 for _ in 0..CAS_UPDATE_RETRIES {
286 let current = Settings::load(db).await?;
287
288 let exam_kinds = match &req.exam_kinds {
289 Some(kinds) => kinds
290 .iter()
291 .map(|kind| ExamKindDef::try_new(&kind.name, kind.weight))
292 .collect::<Result<Vec<_>, _>>()?,
293 None => current.get_exam_kinds().to_vec(),
294 };
295 let was_slots = slot_names(&current.get_meal_slots());
296 let meal_slots = match &req.meal_slots {
297 Some(slots) => slots
298 .iter()
299 .map(|slot| {
300 // A name the row already carries is validated as a kept one:
301 // the charset rule is younger than the stored lists, and
302 // re-validating one under it would leave a school unable to
303 // edit the rest of its slots at all (`MealSlotDef::try_kept`).
304 if was_slots.iter().any(|kept| kept == slot.name.trim()) {
305 MealSlotDef::try_kept(&slot.name, slot.serving_minute)
306 } else {
307 MealSlotDef::try_new(&slot.name, slot.serving_minute)
308 }
309 })
310 .collect::<Result<Vec<_>, _>>()?,
311 None => current.get_meal_slots(),
312 };
313 let attendance_statuses = req
314 .attendance_statuses
315 .clone()
316 .unwrap_or_else(|| current.get_attendance_statuses().to_vec());
317 let grade_bands = match &req.grade_bands {
318 Some(bands) => bands
319 .iter()
320 .map(|band| GradeBand::try_new(band.min, &band.label))
321 .collect::<Result<Vec<_>, _>>()?,
322 None => current.get_grade_bands().to_vec(),
323 };
324 // The name lists as they stand and as they would stand, for the removal
325 // guards below — a list edit is judged by which names it drops.
326 let was_kinds = kind_names(current.get_exam_kinds());
327 let now_kinds = kind_names(&exam_kinds);
328 let now_slots = slot_names(&meal_slots);
329
330 // Merge over the snapshot's resolved values: an omitted field keeps
331 // whatever the row (or the default behind an unset field) reads as.
332 let mut params = current.params();
333 params.exam_kinds = exam_kinds;
334 params.attendance_statuses = attendance_statuses;
335 params.grade_bands = grade_bands;
336 params.max_file_bytes = req.max_file_bytes.unwrap_or(params.max_file_bytes);
337 params.chatbot_history_turns = req
338 .chatbot_history_turns
339 .unwrap_or(params.chatbot_history_turns);
340 params.max_chatbot_threads = req
341 .max_chatbot_threads
342 .unwrap_or(params.max_chatbot_threads);
343 params.max_chatbot_message_len = req
344 .max_chatbot_message_len
345 .unwrap_or(params.max_chatbot_message_len);
346 params.meal_slots = meal_slots;
347 params.dietary_tags = req
348 .dietary_tags
349 .clone()
350 .unwrap_or_else(|| current.get_dietary_tags());
351 // Double option: absent keeps the knob, `null` clears it (no cutoff).
352 params.meal_cancel_cutoff_minutes = req
353 .meal_cancel_cutoff_minutes
354 .unwrap_or(params.meal_cancel_cutoff_minutes);
355
356 let settings = Settings::try_new(params)?;
357
358 // The removal guards. A name leaves a list by being *retired* on its
359 // reference counter — one conditional write on one record, which lands
360 // only while nothing references the name and refuses every claim from
361 // that instant on. That is the whole guard: the check and the removal
362 // used to be a cross-table count and a save held together by a
363 // process-wide lock that was released around the round trip between them.
364 //
365 // Retired before the save, never after: the other order leaves a window
366 // in which a mark lands under a kind the settings no longer list. A save
367 // that then does not land undoes them (`restore`) before the next try.
368 //
369 // Only a write that actually *flipped* a bit is recorded for that undo.
370 // Retirement is idempotent, so two PATCHes dropping the same kind are
371 // both told "retired" — and the one whose save then loses the row's CAS
372 // used to un-retire the winner's kind, leaving it off the list with its
373 // counter in service: gradable again, its count then non-zero, and so
374 // impossible to remove ever after.
375 let mut undo: Vec<Undo> = Vec::new();
376 let mut refused = None;
377 for gone in missing(&was_kinds, &now_kinds) {
378 let counter = kind_ref(&gone);
379 match cap::retire_name(&counter, db).await? {
380 cap::Switched::Flipped => undo.push(Undo::Retired(counter)),
381 cap::Switched::Unchanged => {}
382 cap::Switched::InUse => {
383 refused = Some(AppError::ConflictOwned(format!(
384 "exams of kind '{gone}' are already graded — the kind cannot be removed"
385 )));
386 break;
387 }
388 }
389 }
390 // Same shape for meal slots: a slot a menu was already published for
391 // cannot leave the list — the menu snapshotted the name as text, and a
392 // slot no longer offered would leave that menu unreachable from the
393 // school's own list.
394 if refused.is_none() {
395 for gone in missing(&was_slots, &now_slots) {
396 let counter = slot_ref(&gone);
397 match cap::retire_name(&counter, db).await? {
398 cap::Switched::Flipped => undo.push(Undo::Retired(counter)),
399 cap::Switched::Unchanged => {}
400 cap::Switched::InUse => {
401 refused = Some(AppError::ConflictOwned(format!(
402 "menus are already published for the '{gone}' slot — it cannot be removed"
403 )));
404 break;
405 }
406 }
407 }
408 }
409 if let Some(refused) = refused {
410 restore(&undo, db).await?;
411 return Err(refused);
412 }
413 // A name re-entering a list is back in service: its counter still
414 // carries the retirement from the edit that dropped it, and a mark (or
415 // a menu) under a kind the school offers again must not be refused.
416 // Recorded for the same undo as the retirements — a re-add whose save
417 // does not land leaves a name off the list that grades happily.
418 for back in missing(&now_kinds, &was_kinds) {
419 if let cap::Switched::Flipped = cap::unretire_name(&kind_ref(&back), db).await? {
420 undo.push(Undo::Unretired(kind_ref(&back)));
421 }
422 }
423 for back in missing(&now_slots, &was_slots) {
424 if let cap::Switched::Flipped = cap::unretire_name(&slot_ref(&back), db).await? {
425 undo.push(Undo::Unretired(slot_ref(&back)));
426 }
427 }
428
429 match settings.save_if_unchanged(&current, db).await {
430 Ok(Some(saved)) => return Ok(saved),
431 // The row moved under the snapshot these guards were judged against:
432 // put the names back and re-merge, or the next attempt would decide
433 // against a list nobody asked for.
434 Ok(None) => restore(&undo, db).await?,
435 Err(err) => {
436 restore(&undo, db).await?;
437 return Err(err);
438 }
439 }
440 }
441 Err(AppError::Conflict(
442 "the settings kept changing underneath this update — try again",
443 ))
444}
445
446fn kind_names(kinds: &[ExamKindDef]) -> Vec<String> {
447 kinds
448 .iter()
449 .map(|kind| kind.get_name().to_string())
450 .collect()
451}
452
453fn slot_names(slots: &[MealSlotDef]) -> Vec<String> {
454 slots
455 .iter()
456 .map(|slot| slot.get_name().to_string())
457 .collect()
458}
459
460/// The names `before` carries that `after` does not — a list edit's removals,
461/// or its additions with the arguments swapped.
462fn missing(before: &[String], after: &[String]) -> Vec<String> {
463 before
464 .iter()
465 .filter(|name| !after.contains(name))
466 .cloned()
467 .collect()
468}
469
470/// One `retired` bit this attempt moved, and which way — what `restore` needs
471/// to put it back. Only bits this attempt actually *flipped* are listed: a
472/// write that changed nothing has nothing to take back, and taking it back
473/// would undo the concurrent edit that really did move it.
474enum Undo {
475 /// Retired for a removal; put it back in service.
476 Retired(RecordId),
477 /// Put back in service for a re-add; retire it again.
478 Unretired(RecordId),
479}
480
481/// Undo every bit this attempt moved: the edit that justified them did not
482/// land, so the lists the school offers are still the ones it started with.
483async fn restore(undo: &[Undo], db: &Database) -> Result<(), AppError> {
484 for step in undo {
485 match step {
486 Undo::Retired(name) => {
487 cap::unretire_name(name, db).await?;
488 }
489 // A re-retirement can be refused: a mark (or a menu) landed under
490 // the name during the window it was in service. Refusing to undo is
491 // then the honest answer — the reference is real, and retiring over
492 // it would make the row's kind ungradable while nothing lists it.
493 // The name is left in service, matching the list this attempt is
494 // about to re-read.
495 Undo::Unretired(name) => {
496 cap::retire_name(name, db).await?;
497 }
498 }
499 }
500 Ok(())
501}
502
503#[cfg(test)]
504mod tests {
505 use super::*;
506 use crate::database::init_mem;
507
508 /// The `retired` bit as the store holds it, `None` when no counter row was
509 /// ever written — read back, never inferred from a return value.
510 async fn bit(db: &Database, counter: RecordId) -> Option<bool> {
511 let mut result = db
512 .query("SELECT VALUE retired FROM $id")
513 .bind(("id", counter))
514 .await
515 .unwrap()
516 .check()
517 .unwrap();
518 result.take::<Vec<bool>>(0).unwrap().first().copied()
519 }
520
521 /// Two managers drop the same exam kind at once; one of them loses the
522 /// row's compare-and-set and rolls its attempt back. The winner's
523 /// retirement must survive that rollback — undone, the kind is off the list
524 /// with a counter that still grades, and the first mark to land makes it
525 /// unremovable for good.
526 ///
527 /// The loser's half is what runs here: a retirement that changed nothing
528 /// records no undo, so `restore` has nothing to take back.
529 #[tokio::test]
530 async fn the_loser_of_a_settings_race_cannot_un_retire_the_winner_s_kind() {
531 let db = init_mem().await.unwrap();
532 let counter = kind_ref("midterm");
533
534 // The winner's PATCH retires the kind.
535 assert!(matches!(
536 cap::retire_name(&counter, &db).await.unwrap(),
537 cap::Switched::Flipped
538 ));
539
540 // The loser's PATCH decides the same removal against the same snapshot,
541 // then its save is refused.
542 let mut undo = Vec::new();
543 if let cap::Switched::Flipped = cap::retire_name(&counter, &db).await.unwrap() {
544 undo.push(Undo::Retired(counter.clone()));
545 }
546 assert!(undo.is_empty(), "a no-op retirement records no undo");
547 restore(&undo, &db).await.unwrap();
548
549 assert_eq!(
550 bit(&db, counter).await,
551 Some(true),
552 "the winner's retirement must outlive the loser's rollback"
553 );
554 }
555
556 /// The mirror hole: a re-*added* name is put back in service before the
557 /// save, so a save that does not land owes a re-retirement. Without it the
558 /// name is off the stored list with a counter that grades happily.
559 #[tokio::test]
560 async fn a_rollback_re_retires_a_name_this_attempt_put_back_in_service() {
561 let db = init_mem().await.unwrap();
562 let counter = slot_ref("lunch");
563 cap::retire_name(&counter, &db).await.unwrap();
564
565 // The attempt re-adds the slot, then its save is refused.
566 let mut undo = Vec::new();
567 if let cap::Switched::Flipped = cap::unretire_name(&counter, &db).await.unwrap() {
568 undo.push(Undo::Unretired(counter.clone()));
569 }
570 assert_eq!(undo.len(), 1, "a real un-retirement is undoable");
571 restore(&undo, &db).await.unwrap();
572
573 assert_eq!(
574 bit(&db, counter).await,
575 Some(true),
576 "a re-add that never landed must leave the slot retired"
577 );
578 }
579
580 /// ...unless a menu was published in the window the slot was back in
581 /// service. The reference is real, so the re-retirement is refused and the
582 /// slot stays usable — the honest end of the same rule, not a silent
583 /// overwrite of a live reference.
584 #[tokio::test]
585 async fn a_rollback_leaves_a_name_that_gained_a_reference_in_service() {
586 let db = init_mem().await.unwrap();
587 let counter = slot_ref("lunch");
588 cap::retire_name(&counter, &db).await.unwrap();
589 cap::unretire_name(&counter, &db).await.unwrap();
590 db.query("UPDATE $id SET count = 1")
591 .bind(("id", counter.clone()))
592 .await
593 .unwrap()
594 .check()
595 .unwrap();
596
597 restore(&[Undo::Unretired(counter.clone())], &db)
598 .await
599 .unwrap();
600
601 assert_eq!(bit(&db, counter).await, Some(false));
602 }
603
604 // --- the whole edit, driven the way two managers drive it -------------
605
606 /// A `PATCH` body, built the way the router builds one.
607 fn patch(body: serde_json::Value) -> UpdateSettings {
608 serde_json::from_value(body).unwrap()
609 }
610
611 /// A `meal_slots`/`exam_kinds` list as the DTO carries it.
612 fn kinds(names: &[&str]) -> serde_json::Value {
613 names
614 .iter()
615 .map(|name| serde_json::json!({ "name": name, "weight": 1 }))
616 .collect()
617 }
618
619 fn slots(names: &[&str]) -> serde_json::Value {
620 names
621 .iter()
622 .map(|name| serde_json::json!({ "name": name, "serving_minute": null }))
623 .collect()
624 }
625
626 /// The lists as the store holds them.
627 async fn stored(db: &Database) -> (Vec<String>, Vec<String>) {
628 let settings = Settings::load(db).await.unwrap();
629 (
630 kind_names(settings.get_exam_kinds()),
631 slot_names(&settings.get_meal_slots()),
632 )
633 }
634
635 /// The whole invariant, over the reachable half of the race: two managers
636 /// drop the same exam kind at once, both edits go through the real path,
637 /// and when both have returned the counter's `retired` bit must agree with
638 /// the list the store actually holds.
639 ///
640 /// One of the two decides the removal, retires the kind and saves; the
641 /// other cannot even see the old list, because the whole snapshot-retire-
642 /// save pair is serialized (`SETTINGS_LOCK`). Interleaved, the second
643 /// attempt would be told "already retired", record no undo, win the
644 /// compare-and-set, and leave the first attempt un-retiring the kind it had
645 /// legitimately removed — off the list and gradable.
646 #[tokio::test]
647 async fn two_edits_dropping_the_same_kind_leave_it_retired() {
648 let db = init_mem().await.unwrap();
649 let without = patch(serde_json::json!({
650 "exam_kinds": kinds(&["homework", "quiz", "final", "project", "oral"]),
651 }));
652
653 let (a, b) = tokio::join!(apply(&without, &db), apply(&without, &db));
654 a.unwrap();
655 b.unwrap();
656
657 let (kinds, _) = stored(&db).await;
658 assert!(
659 !kinds.contains(&"midterm".to_string()),
660 "dropped from the list"
661 );
662 assert_eq!(
663 bit(&db, kind_ref("midterm")).await,
664 Some(true),
665 "a kind the stored list no longer offers must not grade"
666 );
667 }
668
669 /// The property those two outcomes rest on, asserted on its own because a
670 /// `join!` cannot be made to schedule the losing order: the edit is a pair
671 /// of writes — retire the dropped names, then commit the list — and no
672 /// rival's pair may run between them.
673 ///
674 /// Retirement is idempotent, so an interleaved rival is told "already
675 /// retired", records no rollback, wins the compare-and-set, and leaves the
676 /// attempt that really flipped the bit un-retiring a kind the stored list
677 /// no longer offers: gradable again, and unremovable for good once a mark
678 /// lands. Holding the lock stands in for a rival mid-pair here — nothing
679 /// the other edit does may be visible until the pair completes.
680 #[tokio::test]
681 async fn a_rival_edit_cannot_run_between_a_retirement_and_its_save() {
682 let db = init_mem().await.unwrap();
683 let without = patch(serde_json::json!({
684 "exam_kinds": kinds(&["homework", "quiz", "final", "project", "oral"]),
685 }));
686
687 let held = SETTINGS_LOCK.lock().await;
688 let rival = tokio::spawn({
689 let db = db.clone();
690 async move { apply(&without, &db).await.map(|_| ()) }
691 });
692 tokio::time::sleep(std::time::Duration::from_millis(200)).await;
693
694 assert_eq!(
695 bit(&db, kind_ref("midterm")).await,
696 None,
697 "a rival's pair must not have started, let alone half-landed"
698 );
699 assert!(stored(&db).await.0.contains(&"midterm".to_string()));
700
701 drop(held);
702 rival.await.unwrap().unwrap();
703 assert_eq!(bit(&db, kind_ref("midterm")).await, Some(true));
704 assert!(!stored(&db).await.0.contains(&"midterm".to_string()));
705 }
706
707 /// The mirror: two managers put the same kind *back* at once. The attempt
708 /// that loses must not re-retire a name the winner's stored list carries —
709 /// a listed kind that refuses every grade.
710 #[tokio::test]
711 async fn two_edits_re_adding_the_same_kind_leave_it_in_service() {
712 let db = init_mem().await.unwrap();
713 let without = patch(serde_json::json!({
714 "exam_kinds": kinds(&["homework", "quiz", "final", "project", "oral"]),
715 }));
716 apply(&without, &db).await.unwrap();
717 let with = patch(serde_json::json!({
718 "exam_kinds": kinds(&["homework", "quiz", "midterm", "final", "project", "oral"]),
719 }));
720
721 let (a, b) = tokio::join!(apply(&with, &db), apply(&with, &db));
722 a.unwrap();
723 b.unwrap();
724
725 let (kinds, _) = stored(&db).await;
726 assert!(kinds.contains(&"midterm".to_string()), "back on the list");
727 assert_eq!(
728 bit(&db, kind_ref("midterm")).await,
729 Some(false),
730 "a kind the stored list offers must grade"
731 );
732 }
733
734 /// The same pair over meal slots, which retire on their own counters.
735 #[tokio::test]
736 async fn two_edits_dropping_the_same_slot_leave_it_retired() {
737 let db = init_mem().await.unwrap();
738 let without = patch(serde_json::json!({
739 "meal_slots": slots(&["breakfast", "snack"]),
740 }));
741
742 let (a, b) = tokio::join!(apply(&without, &db), apply(&without, &db));
743 a.unwrap();
744 b.unwrap();
745
746 let (_, stored_slots) = stored(&db).await;
747 assert!(!stored_slots.contains(&"lunch".to_string()));
748 assert_eq!(bit(&db, slot_ref("lunch")).await, Some(true));
749 }
750
751 // --- the stale slot name that wedged the whole list -------------------
752
753 /// A school that stored `a/b` before the URL-safety rule existed.
754 async fn a_school_with_a_stale_slot(db: &Database) {
755 let mut params = Settings::defaults().params();
756 params.meal_slots = vec![
757 MealSlotDef::try_kept("a/b", None).unwrap(),
758 MealSlotDef::try_new("lunch", None).unwrap(),
759 ];
760 Settings::try_new(params).unwrap().save(db).await.unwrap();
761 }
762
763 /// The wedge: re-sending a stored name is the only way to *keep* it, and
764 /// dropping it 409s once a menu references it — so validating it under the
765 /// younger rule locks the school out of its own `meal_slots` forever. A
766 /// stored name is submittable; a new one with the same characters is not.
767 #[tokio::test]
768 async fn a_stored_slot_name_stays_submittable_but_a_new_one_does_not() {
769 let db = init_mem().await.unwrap();
770 a_school_with_a_stale_slot(&db).await;
771
772 let edit = patch(serde_json::json!({
773 "meal_slots": slots(&["a/b", "lunch", "dinner"]),
774 }));
775 apply(&edit, &db).await.unwrap();
776 let (_, stored_slots) = stored(&db).await;
777 assert_eq!(stored_slots, ["a/b", "lunch", "dinner"]);
778
779 let fresh = patch(serde_json::json!({
780 "meal_slots": slots(&["a/b", "lunch", "c/d"]),
781 }));
782 assert!(
783 apply(&fresh, &db).await.is_err(),
784 "a name no school ever stored is still refused"
785 );
786 }
787
788 /// And an edit that never mentions `meal_slots` still carries the list
789 /// over unvalidated — the behaviour the wedge report leaned on.
790 #[tokio::test]
791 async fn an_unrelated_edit_carries_a_stale_slot_name_over() {
792 let db = init_mem().await.unwrap();
793 a_school_with_a_stale_slot(&db).await;
794
795 let elsewhere = patch(serde_json::json!({ "max_file_bytes": 2048 }));
796 let saved = apply(&elsewhere, &db).await.unwrap();
797
798 assert_eq!(saved.get_max_file_bytes(), 2048);
799 assert_eq!(slot_names(&saved.get_meal_slots()), ["a/b", "lunch"]);
800 }
801}