| 1 | use axum::Json; |
| 2 | use axum::extract::State; |
| 3 | use serde::{Deserialize, Serialize}; |
| 4 | use utoipa::ToSchema; |
| 5 | use utoipa_axum::router::OpenApiRouter; |
| 6 | use utoipa_axum::routes; |
| 7 | |
| 8 | use surrealdb::types::RecordId; |
| 9 | |
| 10 | use crate::constant::CAS_UPDATE_RETRIES; |
| 11 | use crate::database::Database; |
| 12 | use crate::domain::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}; |
| 17 | use crate::state::AppState; |
| 18 | |
| 19 | use super::{CurrentUser, RequireManager, set_or_clear}; |
| 20 | |
| 21 | pub fn routes() -> OpenApiRouter<AppState> { |
| 22 | OpenApiRouter::new().routes(routes!(get_settings, update_settings)) |
| 23 | } |
| 24 | |
| 25 | |
| 26 | |
| 27 | #[derive(Serialize, Deserialize, ToSchema)] |
| 28 | struct ExamKindDto { |
| 29 | |
| 30 | #[schema(example = "midterm", max_length = 50)] |
| 31 | name: String, |
| 32 | |
| 33 | |
| 34 | #[schema(example = 2, minimum = 1, maximum = 100)] |
| 35 | weight: i64, |
| 36 | } |
| 37 | |
| 38 | |
| 39 | |
| 40 | #[derive(Serialize, Deserialize, ToSchema)] |
| 41 | struct MealSlotDto { |
| 42 | |
| 43 | #[schema(example = "lunch", max_length = 50)] |
| 44 | name: String, |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | #[schema(example = 720, minimum = 0, maximum = 1_439)] |
| 54 | serving_minute: Option<i64>, |
| 55 | } |
| 56 | |
| 57 | |
| 58 | |
| 59 | #[derive(Serialize, Deserialize, ToSchema)] |
| 60 | struct GradeBandDto { |
| 61 | |
| 62 | #[schema(example = 85, minimum = 0, maximum = 100)] |
| 63 | min: i64, |
| 64 | |
| 65 | #[schema(example = "AA", max_length = 20)] |
| 66 | label: String, |
| 67 | } |
| 68 | |
| 69 | |
| 70 | |
| 71 | |
| 72 | #[derive(Serialize, ToSchema)] |
| 73 | struct SettingsResponse { |
| 74 | |
| 75 | |
| 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 | |
| 83 | |
| 84 | #[schema(example = json!(["present", "absent", "late", "excused"]))] |
| 85 | attendance_statuses: Vec<String>, |
| 86 | |
| 87 | grade_bands: Vec<GradeBandDto>, |
| 88 | |
| 89 | #[schema(example = 5_242_880)] |
| 90 | max_file_bytes: i64, |
| 91 | |
| 92 | #[schema(example = 10)] |
| 93 | chatbot_history_turns: i64, |
| 94 | |
| 95 | #[schema(example = 50)] |
| 96 | max_chatbot_threads: i64, |
| 97 | |
| 98 | #[schema(example = 4000)] |
| 99 | max_chatbot_message_len: i64, |
| 100 | |
| 101 | |
| 102 | |
| 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 | |
| 110 | #[schema(example = json!(["vegetarian", "vegan", "gluten_free"]))] |
| 111 | dietary_tags: Vec<String>, |
| 112 | |
| 113 | |
| 114 | #[schema(example = 120)] |
| 115 | meal_cancel_cutoff_minutes: Option<i64>, |
| 116 | } |
| 117 | |
| 118 | impl 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)] |
| 157 | struct UpdateSettings { |
| 158 | |
| 159 | |
| 160 | #[schema(max_items = 20)] |
| 161 | exam_kinds: Option<Vec<ExamKindDto>>, |
| 162 | |
| 163 | |
| 164 | |
| 165 | #[schema(max_items = 20)] |
| 166 | attendance_statuses: Option<Vec<String>>, |
| 167 | |
| 168 | |
| 169 | #[schema(max_items = 20)] |
| 170 | grade_bands: Option<Vec<GradeBandDto>>, |
| 171 | |
| 172 | |
| 173 | #[schema(example = 5_242_880, minimum = 1_024, maximum = 26_214_400)] |
| 174 | max_file_bytes: Option<i64>, |
| 175 | |
| 176 | |
| 177 | #[schema(example = 10, minimum = 1, maximum = 50)] |
| 178 | chatbot_history_turns: Option<i64>, |
| 179 | |
| 180 | |
| 181 | #[schema(example = 50, minimum = 1, maximum = 500)] |
| 182 | max_chatbot_threads: Option<i64>, |
| 183 | |
| 184 | |
| 185 | #[schema(example = 4000, minimum = 100, maximum = 8_000)] |
| 186 | max_chatbot_message_len: Option<i64>, |
| 187 | |
| 188 | |
| 189 | |
| 190 | |
| 191 | |
| 192 | |
| 193 | |
| 194 | |
| 195 | |
| 196 | #[schema(max_items = 20)] |
| 197 | meal_slots: Option<Vec<MealSlotDto>>, |
| 198 | |
| 199 | |
| 200 | #[schema(max_items = 20)] |
| 201 | dietary_tags: Option<Vec<String>>, |
| 202 | |
| 203 | |
| 204 | |
| 205 | |
| 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 | |
| 212 | |
| 213 | |
| 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 | )] |
| 224 | async 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 | |
| 233 | |
| 234 | |
| 235 | |
| 236 | |
| 237 | |
| 238 | |
| 239 | |
| 240 | |
| 241 | |
| 242 | |
| 243 | |
| 244 | |
| 245 | |
| 246 | |
| 247 | |
| 248 | |
| 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 | )] |
| 264 | async 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 | |
| 273 | |
| 274 | |
| 275 | async fn apply(req: &UpdateSettings, db: &Database) -> Result<Settings, AppError> { |
| 276 | |
| 277 | |
| 278 | |
| 279 | |
| 280 | let _guard = SETTINGS_LOCK.lock().await; |
| 281 | |
| 282 | |
| 283 | |
| 284 | |
| 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(¤t.get_meal_slots()); |
| 296 | let meal_slots = match &req.meal_slots { |
| 297 | Some(slots) => slots |
| 298 | .iter() |
| 299 | .map(|slot| { |
| 300 | |
| 301 | |
| 302 | |
| 303 | |
| 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 | |
| 325 | |
| 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 | |
| 331 | |
| 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 | |
| 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 | |
| 359 | |
| 360 | |
| 361 | |
| 362 | |
| 363 | |
| 364 | |
| 365 | |
| 366 | |
| 367 | |
| 368 | |
| 369 | |
| 370 | |
| 371 | |
| 372 | |
| 373 | |
| 374 | |
| 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 | |
| 391 | |
| 392 | |
| 393 | |
| 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 | |
| 414 | |
| 415 | |
| 416 | |
| 417 | |
| 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(¤t, db).await { |
| 430 | Ok(Some(saved)) => return Ok(saved), |
| 431 | |
| 432 | |
| 433 | |
| 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 | |
| 446 | fn kind_names(kinds: &[ExamKindDef]) -> Vec<String> { |
| 447 | kinds |
| 448 | .iter() |
| 449 | .map(|kind| kind.get_name().to_string()) |
| 450 | .collect() |
| 451 | } |
| 452 | |
| 453 | fn slot_names(slots: &[MealSlotDef]) -> Vec<String> { |
| 454 | slots |
| 455 | .iter() |
| 456 | .map(|slot| slot.get_name().to_string()) |
| 457 | .collect() |
| 458 | } |
| 459 | |
| 460 | |
| 461 | |
| 462 | fn missing(before: &[String], after: &[String]) -> Vec<String> { |
| 463 | before |
| 464 | .iter() |
| 465 | .filter(|name| !after.contains(name)) |
| 466 | .cloned() |
| 467 | .collect() |
| 468 | } |
| 469 | |
| 470 | |
| 471 | |
| 472 | |
| 473 | |
| 474 | enum Undo { |
| 475 | |
| 476 | Retired(RecordId), |
| 477 | |
| 478 | Unretired(RecordId), |
| 479 | } |
| 480 | |
| 481 | |
| 482 | |
| 483 | async 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 | |
| 490 | |
| 491 | |
| 492 | |
| 493 | |
| 494 | |
| 495 | Undo::Unretired(name) => { |
| 496 | cap::retire_name(name, db).await?; |
| 497 | } |
| 498 | } |
| 499 | } |
| 500 | Ok(()) |
| 501 | } |
| 502 | |
| 503 | #[cfg(test)] |
| 504 | mod tests { |
| 505 | use super::*; |
| 506 | use crate::database::init_mem; |
| 507 | |
| 508 | |
| 509 | |
| 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 | |
| 522 | |
| 523 | |
| 524 | |
| 525 | |
| 526 | |
| 527 | |
| 528 | |
| 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 | |
| 535 | assert!(matches!( |
| 536 | cap::retire_name(&counter, &db).await.unwrap(), |
| 537 | cap::Switched::Flipped |
| 538 | )); |
| 539 | |
| 540 | |
| 541 | |
| 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 | |
| 557 | |
| 558 | |
| 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 | |
| 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 | |
| 581 | |
| 582 | |
| 583 | |
| 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 | |
| 605 | |
| 606 | |
| 607 | fn patch(body: serde_json::Value) -> UpdateSettings { |
| 608 | serde_json::from_value(body).unwrap() |
| 609 | } |
| 610 | |
| 611 | |
| 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 | |
| 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 | |
| 636 | |
| 637 | |
| 638 | |
| 639 | |
| 640 | |
| 641 | |
| 642 | |
| 643 | |
| 644 | |
| 645 | |
| 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 | |
| 670 | |
| 671 | |
| 672 | |
| 673 | |
| 674 | |
| 675 | |
| 676 | |
| 677 | |
| 678 | |
| 679 | |
| 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 | |
| 708 | |
| 709 | |
| 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 | |
| 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 | |
| 752 | |
| 753 | |
| 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 | |
| 764 | |
| 765 | |
| 766 | |
| 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 | |
| 789 | |
| 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 | } |