| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | use crate::database::{Database, tx_with_retry}; |
| 8 | use crate::db::page::PagedList; |
| 9 | use crate::domain::attendance::AttendanceStatus; |
| 10 | use crate::domain::class_course::ClassCourseId; |
| 11 | use crate::domain::course_session::{CourseSession, CourseSessionId}; |
| 12 | use crate::domain::session_attendance::SessionAttendance; |
| 13 | use crate::domain::timestamp::Timestamp; |
| 14 | use crate::domain::user::UserId; |
| 15 | use crate::error::AppError; |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | |
| 55 | |
| 56 | |
| 57 | |
| 58 | |
| 59 | |
| 60 | |
| 61 | |
| 62 | |
| 63 | |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | |
| 71 | |
| 72 | |
| 73 | |
| 74 | |
| 75 | |
| 76 | |
| 77 | |
| 78 | |
| 79 | |
| 80 | |
| 81 | pub async fn mark( |
| 82 | db: &Database, |
| 83 | session: &CourseSession, |
| 84 | user: &UserId, |
| 85 | status: AttendanceStatus, |
| 86 | marked_by: &UserId, |
| 87 | ) -> Result<SessionAttendance, AppError> { |
| 88 | let attended = crate::domain::session_attendance::counts_as_attended(&status); |
| 89 | let delta: i64 = if attended { 1 } else { -1 }; |
| 90 | let now = Timestamp::now(); |
| 91 | |
| 92 | let session = session.clone(); |
| 93 | let user = *user; |
| 94 | let status = status.clone(); |
| 95 | let marked_by = *marked_by; |
| 96 | tx_with_retry(db, false, async move |tx| { |
| 97 | |
| 98 | |
| 99 | let sess = sqlx::query!( |
| 100 | r#"SELECT teacher, starts_at, held_counted_at |
| 101 | FROM course_session WHERE id = $1 FOR NO KEY UPDATE"#, |
| 102 | session.id.uuid(), |
| 103 | ) |
| 104 | .fetch_optional(&mut *tx) |
| 105 | .await?; |
| 106 | let Some(sess) = sess else { |
| 107 | return Err(AppError::NotFound); |
| 108 | }; |
| 109 | |
| 110 | |
| 111 | let was = sqlx::query!( |
| 112 | r#"SELECT status FROM session_attendance |
| 113 | WHERE session = $1 AND app_user = $2"#, |
| 114 | session.id.uuid(), |
| 115 | user.uuid(), |
| 116 | ) |
| 117 | .fetch_optional(&mut *tx) |
| 118 | .await? |
| 119 | .map(|row| row.status); |
| 120 | |
| 121 | |
| 122 | |
| 123 | let is_student = sqlx::query!( |
| 124 | r#"SELECT role = 'student' AS "is_student!: bool" FROM app_user WHERE id = $1"#, |
| 125 | user.uuid(), |
| 126 | ) |
| 127 | .fetch_optional(&mut *tx) |
| 128 | .await? |
| 129 | .map(|row| row.is_student) |
| 130 | .unwrap_or(false); |
| 131 | let row = sqlx::query_as!( |
| 132 | SessionAttendance, |
| 133 | r#"INSERT INTO session_attendance (session, app_user, class_course, status, marked_by, marked_at) |
| 134 | VALUES ($1, $2, $3, $4, $5, $6) |
| 135 | ON CONFLICT (session, app_user) DO UPDATE |
| 136 | SET status = EXCLUDED.status, marked_by = EXCLUDED.marked_by, |
| 137 | marked_at = EXCLUDED.marked_at |
| 138 | RETURNING session AS "session: CourseSessionId", app_user AS "user: UserId", |
| 139 | class_course AS "class_course: ClassCourseId", |
| 140 | status AS "status: AttendanceStatus", |
| 141 | marked_by AS "marked_by: UserId""#, |
| 142 | session.id.uuid(), |
| 143 | user.uuid(), |
| 144 | session.class_course.uuid(), |
| 145 | status.as_str(), |
| 146 | marked_by.uuid(), |
| 147 | now.as_millis(), |
| 148 | ) |
| 149 | .fetch_one(&mut *tx) |
| 150 | .await?; |
| 151 | |
| 152 | let was_attended = was |
| 153 | .as_deref() |
| 154 | .is_some_and(|was| was == "present" || was == "late"); |
| 155 | if is_student && was_attended != attended { |
| 156 | sqlx::query!( |
| 157 | r#"UPDATE app_user |
| 158 | SET lessons_attended_total = GREATEST(lessons_attended_total + $2, 0) |
| 159 | WHERE id = $1"#, |
| 160 | user.uuid(), |
| 161 | delta, |
| 162 | ) |
| 163 | .execute(&mut *tx) |
| 164 | .await?; |
| 165 | } |
| 166 | |
| 167 | if sess.held_counted_at.is_none() && sess.starts_at <= now.as_millis() { |
| 168 | sqlx::query!( |
| 169 | r#"UPDATE course_session SET held_counted_at = $2 WHERE id = $1"#, |
| 170 | session.id.uuid(), |
| 171 | now.as_millis(), |
| 172 | ) |
| 173 | .execute(&mut *tx) |
| 174 | .await?; |
| 175 | sqlx::query!( |
| 176 | r#"UPDATE app_user SET lessons_held_total = lessons_held_total + 1 |
| 177 | WHERE id = $1"#, |
| 178 | sess.teacher, |
| 179 | ) |
| 180 | .execute(&mut *tx) |
| 181 | .await?; |
| 182 | } |
| 183 | Ok(row) |
| 184 | }) |
| 185 | .await |
| 186 | } |
| 187 | |
| 188 | pub async fn list_for_session( |
| 189 | db: &Database, |
| 190 | session: &CourseSessionId, |
| 191 | limit: Option<i64>, |
| 192 | offset: i64, |
| 193 | ) -> Result<(Vec<SessionAttendance>, i64), AppError> { |
| 194 | |
| 195 | |
| 196 | |
| 197 | PagedList::new( |
| 198 | "session_attendance WHERE session = $1", |
| 199 | "ORDER BY session DESC, app_user DESC", |
| 200 | ) |
| 201 | .bind(session.uuid()) |
| 202 | .run::<SessionAttendance>(limit, offset, db) |
| 203 | .await |
| 204 | } |
| 205 | |
| 206 | |
| 207 | |
| 208 | |
| 209 | |
| 210 | pub async fn list_for_user( |
| 211 | db: &Database, |
| 212 | user: &UserId, |
| 213 | ) -> Result<Vec<SessionAttendance>, AppError> { |
| 214 | let rows = sqlx::query_as!( |
| 215 | SessionAttendance, |
| 216 | r#"SELECT session AS "session: CourseSessionId", app_user AS "user: UserId", |
| 217 | class_course AS "class_course: ClassCourseId", |
| 218 | status AS "status: AttendanceStatus", |
| 219 | marked_by AS "marked_by: UserId" |
| 220 | FROM session_attendance WHERE app_user = $1 |
| 221 | ORDER BY session DESC, app_user DESC"#, |
| 222 | user.uuid(), |
| 223 | ) |
| 224 | .fetch_all(db) |
| 225 | .await?; |
| 226 | Ok(rows) |
| 227 | } |
| 228 | |
| 229 | |
| 230 | |
| 231 | |
| 232 | |
| 233 | |
| 234 | |
| 235 | |
| 236 | |
| 237 | |
| 238 | |
| 239 | |
| 240 | |
| 241 | pub async fn remove( |
| 242 | db: &Database, |
| 243 | session: &CourseSessionId, |
| 244 | user: &UserId, |
| 245 | ) -> Result<Option<SessionAttendance>, AppError> { |
| 246 | |
| 247 | let session = session.clone(); |
| 248 | let user = *user; |
| 249 | tx_with_retry(db, false, async move |tx| { |
| 250 | |
| 251 | |
| 252 | |
| 253 | let Some(gone) = sqlx::query_as!( |
| 254 | SessionAttendance, |
| 255 | r#"SELECT session AS "session: CourseSessionId", app_user AS "user: UserId", |
| 256 | class_course AS "class_course: ClassCourseId", |
| 257 | status AS "status: AttendanceStatus", |
| 258 | marked_by AS "marked_by: UserId" |
| 259 | FROM session_attendance |
| 260 | WHERE session = $1 AND app_user = $2 |
| 261 | FOR UPDATE"#, |
| 262 | session.uuid(), |
| 263 | user.uuid(), |
| 264 | ) |
| 265 | .fetch_optional(&mut *tx) |
| 266 | .await? |
| 267 | else { |
| 268 | return Ok(None); |
| 269 | }; |
| 270 | if crate::domain::session_attendance::counts_as_attended(&gone.status) { |
| 271 | |
| 272 | let student = sqlx::query!( |
| 273 | r#"SELECT role = 'student' AS "is_student!: bool" FROM app_user WHERE id = $1"#, |
| 274 | user.uuid(), |
| 275 | ) |
| 276 | .fetch_optional(&mut *tx) |
| 277 | .await? |
| 278 | .map(|row| row.is_student) |
| 279 | .unwrap_or(false); |
| 280 | if student { |
| 281 | sqlx::query!( |
| 282 | r#"UPDATE app_user |
| 283 | SET lessons_attended_total = GREATEST(lessons_attended_total - 1, 0) |
| 284 | WHERE id = $1"#, |
| 285 | user.uuid(), |
| 286 | ) |
| 287 | .execute(&mut *tx) |
| 288 | .await?; |
| 289 | } |
| 290 | } |
| 291 | sqlx::query!( |
| 292 | r#"DELETE FROM session_attendance WHERE session = $1 AND app_user = $2"#, |
| 293 | session.uuid(), |
| 294 | user.uuid(), |
| 295 | ) |
| 296 | .execute(&mut *tx) |
| 297 | .await?; |
| 298 | Ok(Some(gone)) |
| 299 | }) |
| 300 | .await |
| 301 | } |
| 302 | |
| 303 | #[cfg(test)] |
| 304 | mod tests { |
| 305 | use super::*; |
| 306 | use crate::constant::DEFAULT_ATTENDANCE_STATUSES; |
| 307 | use crate::database::init_test_db; |
| 308 | use crate::domain::course_session::SessionTopic; |
| 309 | use crate::domain::role::Role; |
| 310 | |
| 311 | |
| 312 | |
| 313 | |
| 314 | async fn a_user(key: &str, role: Role, db: &Database) -> UserId { |
| 315 | |
| 316 | |
| 317 | let user = UserId::generate(); |
| 318 | sqlx::query( |
| 319 | "INSERT INTO app_user (id, username, created_at, role) \ |
| 320 | VALUES ($1, $2, 0, $3)", |
| 321 | ) |
| 322 | .bind(user.uuid()) |
| 323 | .bind(format!("{key}-{}", &user.key()[30..])) |
| 324 | .bind(role.as_str()) |
| 325 | .execute(db) |
| 326 | .await |
| 327 | .unwrap(); |
| 328 | user |
| 329 | } |
| 330 | |
| 331 | async fn a_student(key: &str, db: &Database) -> UserId { |
| 332 | a_user(key, Role::Student, db).await |
| 333 | } |
| 334 | |
| 335 | async fn a_teacher(key: &str, db: &Database) -> UserId { |
| 336 | a_user(key, Role::Teacher, db).await |
| 337 | } |
| 338 | |
| 339 | async fn a_session_at(teacher: &UserId, starts_at: i64, db: &Database) -> CourseSession { |
| 340 | crate::db::course_session::create( |
| 341 | db, |
| 342 | &crate::db::course::a_test_instance(db).await.0, |
| 343 | teacher, |
| 344 | SessionTopic::try_new("limits").unwrap(), |
| 345 | Timestamp::from_millis(starts_at), |
| 346 | None, |
| 347 | ) |
| 348 | .await |
| 349 | .unwrap() |
| 350 | } |
| 351 | |
| 352 | |
| 353 | async fn a_session(teacher: &UserId, db: &Database) -> CourseSession { |
| 354 | a_session_at(teacher, 1, db).await |
| 355 | } |
| 356 | |
| 357 | |
| 358 | |
| 359 | fn status(value: &str) -> AttendanceStatus { |
| 360 | let allowed: Vec<String> = DEFAULT_ATTENDANCE_STATUSES |
| 361 | .iter() |
| 362 | .map(|s| s.to_string()) |
| 363 | .chain(["online".to_string()]) |
| 364 | .collect(); |
| 365 | AttendanceStatus::try_new(value, &allowed).unwrap() |
| 366 | } |
| 367 | |
| 368 | |
| 369 | async fn attended(user: &UserId, db: &Database) -> i64 { |
| 370 | crate::db::badge::load(db, user) |
| 371 | .await |
| 372 | .unwrap() |
| 373 | .get_lessons_attended() |
| 374 | } |
| 375 | |
| 376 | async fn held(user: &UserId, db: &Database) -> i64 { |
| 377 | crate::db::badge::load(db, user) |
| 378 | .await |
| 379 | .unwrap() |
| 380 | .get_lessons_held() |
| 381 | } |
| 382 | |
| 383 | |
| 384 | |
| 385 | |
| 386 | #[tokio::test] |
| 387 | async fn the_counter_follows_every_crossing_and_no_other_move() { |
| 388 | let (db, _leases) = init_test_db().await; |
| 389 | let teacher = a_teacher("t", &db).await; |
| 390 | let student = a_student("s", &db).await; |
| 391 | let session = a_session(&teacher, &db).await; |
| 392 | let mark = async |value: &str, db: &Database| { |
| 393 | super::mark(db, &session, &student, status(value), &teacher) |
| 394 | .await |
| 395 | .unwrap(); |
| 396 | }; |
| 397 | |
| 398 | for (value, expected, why) in [ |
| 399 | ("present", 1, "first mark counts"), |
| 400 | ("present", 1, "re-marking the same status changes nothing"), |
| 401 | ("late", 1, "late is attending too, so no crossing"), |
| 402 | ("absent", 0, "a correction gives the count back"), |
| 403 | ("absent", 0, "and does not keep giving it back"), |
| 404 | ("late", 1, "absent -> late crosses back up"), |
| 405 | ("excused", 0, "excused is neutral: a crossing down"), |
| 406 | ("online", 0, "a school-added status stays neutral"), |
| 407 | ("present", 1, "…and crossing up from one still counts"), |
| 408 | ("online", 0, "…as does crossing down to one"), |
| 409 | ] { |
| 410 | mark(value, &db).await; |
| 411 | assert_eq!(attended(&student, &db).await, expected, "{why}"); |
| 412 | } |
| 413 | assert_eq!(attended(&teacher, &db).await, 0, "credited the marker"); |
| 414 | |
| 415 | assert_eq!(held(&teacher, &db).await, 1, "the lesson was counted twice"); |
| 416 | } |
| 417 | |
| 418 | |
| 419 | |
| 420 | #[tokio::test] |
| 421 | async fn the_first_roll_call_counts_the_lesson_once() { |
| 422 | let (db, _leases) = init_test_db().await; |
| 423 | let teacher = a_teacher("t", &db).await; |
| 424 | let other = a_teacher("o", &db).await; |
| 425 | let session = a_session(&teacher, &db).await; |
| 426 | assert_eq!(held(&teacher, &db).await, 0, "scheduling counts nothing"); |
| 427 | |
| 428 | for key in ["s1", "s2", "s3"] { |
| 429 | let student = a_student(key, &db).await; |
| 430 | mark(&db, &session, &student, status("present"), &teacher) |
| 431 | .await |
| 432 | .unwrap(); |
| 433 | assert_eq!(held(&teacher, &db).await, 1, "{key} counted it again"); |
| 434 | } |
| 435 | assert_eq!(held(&other, &db).await, 0, "credited the wrong teacher"); |
| 436 | |
| 437 | |
| 438 | let second = a_session(&teacher, &db).await; |
| 439 | let student = a_student("s4", &db).await; |
| 440 | mark(&db, &second, &student, status("present"), &teacher) |
| 441 | .await |
| 442 | .unwrap(); |
| 443 | assert_eq!(held(&teacher, &db).await, 2); |
| 444 | } |
| 445 | |
| 446 | |
| 447 | |
| 448 | |
| 449 | #[tokio::test] |
| 450 | async fn a_lesson_that_has_not_started_holds_nothing_yet() { |
| 451 | let (db, _leases) = init_test_db().await; |
| 452 | let teacher = a_teacher("t", &db).await; |
| 453 | let student = a_student("s", &db).await; |
| 454 | let next_week = |
| 455 | a_session_at(&teacher, Timestamp::now().as_millis() + 604_800_000, &db).await; |
| 456 | |
| 457 | mark(&db, &next_week, &student, status("present"), &teacher) |
| 458 | .await |
| 459 | .unwrap(); |
| 460 | assert_eq!(held(&teacher, &db).await, 0, "next week's lesson, today"); |
| 461 | |
| 462 | assert_eq!(attended(&student, &db).await, 1); |
| 463 | |
| 464 | |
| 465 | |
| 466 | sqlx::query("UPDATE course_session SET starts_at = 1 WHERE id = $1") |
| 467 | .bind(next_week.get_id().uuid()) |
| 468 | .execute(&db) |
| 469 | .await |
| 470 | .unwrap(); |
| 471 | for (status_value, why) in [("late", "the bell rang"), ("present", "held twice")] { |
| 472 | mark(&db, &next_week, &student, status(status_value), &teacher) |
| 473 | .await |
| 474 | .unwrap(); |
| 475 | assert_eq!(held(&teacher, &db).await, 1, "{why}"); |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | |
| 480 | |
| 481 | |
| 482 | |
| 483 | #[tokio::test] |
| 484 | async fn a_teacher_marked_present_earns_nothing_for_attending() { |
| 485 | let (db, _leases) = init_test_db().await; |
| 486 | let teacher = a_teacher("t", &db).await; |
| 487 | let session = a_session(&teacher, &db).await; |
| 488 | |
| 489 | mark(&db, &session, &teacher, status("present"), &teacher) |
| 490 | .await |
| 491 | .unwrap(); |
| 492 | assert_eq!(attended(&teacher, &db).await, 0, "staff attended a lesson"); |
| 493 | assert_eq!(held(&teacher, &db).await, 1, "the roll call was taken"); |
| 494 | |
| 495 | |
| 496 | |
| 497 | mark(&db, &session, &teacher, status("absent"), &teacher) |
| 498 | .await |
| 499 | .unwrap(); |
| 500 | assert_eq!(attended(&teacher, &db).await, 0); |
| 501 | remove(&db, session.get_id(), &teacher) |
| 502 | .await |
| 503 | .unwrap() |
| 504 | .expect("the row was there"); |
| 505 | assert_eq!(attended(&teacher, &db).await, 0); |
| 506 | assert_eq!(held(&teacher, &db).await, 1, "the lesson still happened"); |
| 507 | } |
| 508 | |
| 509 | |
| 510 | #[tokio::test] |
| 511 | async fn each_lesson_counts_once_for_the_student_marked() { |
| 512 | let (db, _leases) = init_test_db().await; |
| 513 | let teacher = a_teacher("t", &db).await; |
| 514 | let student = a_student("s", &db).await; |
| 515 | let other = a_student("o", &db).await; |
| 516 | for _ in 0..2 { |
| 517 | let session = a_session(&teacher, &db).await; |
| 518 | mark(&db, &session, &student, status("present"), &teacher) |
| 519 | .await |
| 520 | .unwrap(); |
| 521 | } |
| 522 | assert_eq!(attended(&student, &db).await, 2); |
| 523 | assert_eq!(attended(&other, &db).await, 0, "credited the wrong student"); |
| 524 | } |
| 525 | |
| 526 | |
| 527 | |
| 528 | #[tokio::test] |
| 529 | async fn removing_a_row_gives_back_only_what_it_took() { |
| 530 | let (db, _leases) = init_test_db().await; |
| 531 | let teacher = a_teacher("t", &db).await; |
| 532 | let student = a_student("s", &db).await; |
| 533 | |
| 534 | let counted = a_session(&teacher, &db).await; |
| 535 | mark(&db, &counted, &student, status("present"), &teacher) |
| 536 | .await |
| 537 | .unwrap(); |
| 538 | let neutral = a_session(&teacher, &db).await; |
| 539 | mark(&db, &neutral, &student, status("absent"), &teacher) |
| 540 | .await |
| 541 | .unwrap(); |
| 542 | assert_eq!(attended(&student, &db).await, 1); |
| 543 | |
| 544 | remove(&db, neutral.get_id(), &student) |
| 545 | .await |
| 546 | .unwrap() |
| 547 | .expect("the absent row was there"); |
| 548 | assert_eq!(attended(&student, &db).await, 1, "absent took nothing"); |
| 549 | remove(&db, counted.get_id(), &student) |
| 550 | .await |
| 551 | .unwrap() |
| 552 | .expect("the present row was there"); |
| 553 | assert_eq!(attended(&student, &db).await, 0); |
| 554 | assert!( |
| 555 | remove(&db, counted.get_id(), &student) |
| 556 | .await |
| 557 | .unwrap() |
| 558 | .is_none(), |
| 559 | "nothing left to remove" |
| 560 | ); |
| 561 | assert_eq!(attended(&student, &db).await, 0, "and nothing to give back"); |
| 562 | assert_eq!( |
| 563 | held(&teacher, &db).await, |
| 564 | 2, |
| 565 | "clearing a row un-held a lesson" |
| 566 | ); |
| 567 | } |
| 568 | |
| 569 | |
| 570 | |
| 571 | #[tokio::test] |
| 572 | async fn the_counter_never_goes_below_zero() { |
| 573 | let (db, _leases) = init_test_db().await; |
| 574 | let teacher = a_teacher("t", &db).await; |
| 575 | let student = a_student("s", &db).await; |
| 576 | |
| 577 | |
| 578 | |
| 579 | |
| 580 | let mut sessions = Vec::new(); |
| 581 | for _ in 0..10 { |
| 582 | let session = a_session(&teacher, &db).await; |
| 583 | mark(&db, &session, &student, status("present"), &teacher) |
| 584 | .await |
| 585 | .unwrap(); |
| 586 | sessions.push(session); |
| 587 | } |
| 588 | sqlx::query("UPDATE app_user SET lessons_attended_total = 0 WHERE id = $1") |
| 589 | .bind(student.uuid()) |
| 590 | .execute(&db) |
| 591 | .await |
| 592 | .unwrap(); |
| 593 | |
| 594 | for session in &sessions { |
| 595 | mark(&db, session, &student, status("absent"), &teacher) |
| 596 | .await |
| 597 | .unwrap(); |
| 598 | remove(&db, session.get_id(), &student).await.unwrap(); |
| 599 | assert!(attended(&student, &db).await >= 0); |
| 600 | } |
| 601 | assert_eq!(attended(&student, &db).await, 0, "floored, never negative"); |
| 602 | } |
| 603 | |
| 604 | |
| 605 | |
| 606 | |
| 607 | #[tokio::test] |
| 608 | async fn deleting_the_session_leaves_the_counters_alone() { |
| 609 | let (db, _leases) = init_test_db().await; |
| 610 | let teacher = a_teacher("t", &db).await; |
| 611 | let student = a_student("s", &db).await; |
| 612 | let session = a_session(&teacher, &db).await; |
| 613 | mark(&db, &session, &student, status("present"), &teacher) |
| 614 | .await |
| 615 | .unwrap(); |
| 616 | |
| 617 | crate::db::course_session::delete(&db, session) |
| 618 | .await |
| 619 | .unwrap(); |
| 620 | assert_eq!(attended(&student, &db).await, 1, "the cascade decremented"); |
| 621 | assert_eq!(held(&teacher, &db).await, 1, "the cascade decremented"); |
| 622 | } |
| 623 | |
| 624 | |
| 625 | |
| 626 | #[tokio::test] |
| 627 | async fn a_refused_mark_moves_nothing() { |
| 628 | let (db, _leases) = init_test_db().await; |
| 629 | let teacher = a_teacher("t", &db).await; |
| 630 | let student = a_student("s", &db).await; |
| 631 | let session = a_session(&teacher, &db).await; |
| 632 | let ghost = session.clone(); |
| 633 | crate::db::course_session::delete(&db, session) |
| 634 | .await |
| 635 | .unwrap(); |
| 636 | |
| 637 | assert!(matches!( |
| 638 | mark(&db, &ghost, &student, status("present"), &teacher).await, |
| 639 | Err(AppError::NotFound) |
| 640 | )); |
| 641 | assert_eq!(attended(&student, &db).await, 0); |
| 642 | assert_eq!(held(&teacher, &db).await, 0, "a refused mark held a lesson"); |
| 643 | } |
| 644 | |
| 645 | |
| 646 | |
| 647 | |
| 648 | |
| 649 | |
| 650 | |
| 651 | |
| 652 | |
| 653 | |
| 654 | |
| 655 | |
| 656 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 657 | async fn a_mark_written_inside_a_delete_never_outlives_the_session() { |
| 658 | let (db, _leases) = crate::database::init_test_db().await; |
| 659 | let teacher = a_teacher("t", &db).await; |
| 660 | |
| 661 | async fn session_for( |
| 662 | db: &Database, |
| 663 | teacher: &UserId, |
| 664 | already_counted: bool, |
| 665 | label: &str, |
| 666 | ) -> CourseSession { |
| 667 | if already_counted { |
| 668 | let session = a_session(teacher, db).await; |
| 669 | let first = a_student(label, db).await; |
| 670 | mark(db, &session, &first, status("present"), teacher) |
| 671 | .await |
| 672 | .unwrap(); |
| 673 | session |
| 674 | } else { |
| 675 | a_session_at(teacher, Timestamp::now().as_millis() + 604_800_000, db).await |
| 676 | } |
| 677 | } |
| 678 | |
| 679 | for (flavor, already_counted) in [("fresh", false), ("counted", true)] { |
| 680 | |
| 681 | { |
| 682 | let session = session_for(&db, &teacher, already_counted, &format!("df-{flavor}")) |
| 683 | .await; |
| 684 | let id = session.get_id().clone(); |
| 685 | let ghost = session.clone(); |
| 686 | let dropped = crate::db::course_session::delete(&db, session).await; |
| 687 | assert!( |
| 688 | !matches!(dropped, Err(AppError::Db(_))), |
| 689 | "{flavor} delete-first: a delete must be answered, not 500: {dropped:?}" |
| 690 | ); |
| 691 | assert!( |
| 692 | crate::db::course_session::read(&db, &id) |
| 693 | .await |
| 694 | .unwrap() |
| 695 | .is_none(), |
| 696 | "{flavor} delete-first: the session is still there after delete: {dropped:?}" |
| 697 | ); |
| 698 | let student = a_student(&format!("df-s-{flavor}"), &db).await; |
| 699 | let marked = mark(&db, &ghost, &student, status("present"), &teacher).await; |
| 700 | assert!( |
| 701 | !matches!(marked, Err(AppError::Db(_))), |
| 702 | "{flavor} delete-first: a mark must be answered, not 500: {marked:?}" |
| 703 | ); |
| 704 | assert_eq!( |
| 705 | list_for_session(&db, &id, None, 0).await.unwrap().0.len(), |
| 706 | 0, |
| 707 | "a roll call outlived its session" |
| 708 | ); |
| 709 | } |
| 710 | |
| 711 | |
| 712 | { |
| 713 | let session = session_for(&db, &teacher, already_counted, &format!("wf-{flavor}")) |
| 714 | .await; |
| 715 | let id = session.get_id().clone(); |
| 716 | let student = a_student(&format!("wf-s-{flavor}"), &db).await; |
| 717 | let marked = mark(&db, &session, &student, status("present"), &teacher).await; |
| 718 | assert!( |
| 719 | marked.is_ok(), |
| 720 | "{flavor} write-first: the mark must land before the delete: {marked:?}" |
| 721 | ); |
| 722 | let dropped = crate::db::course_session::delete(&db, session).await; |
| 723 | assert!( |
| 724 | !matches!(dropped, Err(AppError::Db(_))), |
| 725 | "{flavor} write-first: a delete must be answered, not 500: {dropped:?}" |
| 726 | ); |
| 727 | assert!( |
| 728 | crate::db::course_session::read(&db, &id) |
| 729 | .await |
| 730 | .unwrap() |
| 731 | .is_none(), |
| 732 | "{flavor} write-first: the session is still there" |
| 733 | ); |
| 734 | assert_eq!( |
| 735 | list_for_session(&db, &id, None, 0).await.unwrap().0.len(), |
| 736 | 0, |
| 737 | "a roll call outlived its session" |
| 738 | ); |
| 739 | } |
| 740 | } |
| 741 | |
| 742 | |
| 743 | let mut swept = 0; |
| 744 | for (round, already_counted) in [false, true, false, true].into_iter().enumerate() { |
| 745 | let session = session_for(&db, &teacher, already_counted, &format!("c{round}")).await; |
| 746 | let id = session.get_id().clone(); |
| 747 | let ghost = session.clone(); |
| 748 | |
| 749 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); |
| 750 | let drop_it = { |
| 751 | let (db, gate, session) = (db.clone(), gate.clone(), session); |
| 752 | tokio::spawn(async move { |
| 753 | gate.wait().await; |
| 754 | crate::db::course_session::delete(&db, session).await |
| 755 | }) |
| 756 | }; |
| 757 | let marked = { |
| 758 | let (db, teacher, gate) = (db.clone(), teacher, gate); |
| 759 | let student = a_student(&format!("s{round}"), &db).await; |
| 760 | tokio::spawn(async move { |
| 761 | gate.wait().await; |
| 762 | mark(&db, &ghost, &student, status("present"), &teacher).await |
| 763 | }) |
| 764 | }; |
| 765 | let (drop_it, marked) = (drop_it.await.unwrap(), marked.await.unwrap()); |
| 766 | assert!( |
| 767 | !matches!(marked, Err(AppError::Db(_))), |
| 768 | "round {round}: a raced mark must be answered, not 500: {marked:?}" |
| 769 | ); |
| 770 | assert!( |
| 771 | !matches!(drop_it, Err(AppError::Db(_))), |
| 772 | "round {round}: a raced delete must be answered, not 500: {drop_it:?}" |
| 773 | ); |
| 774 | |
| 775 | if crate::db::course_session::read(&db, &id) |
| 776 | .await |
| 777 | .unwrap() |
| 778 | .is_none() |
| 779 | { |
| 780 | swept += 1; |
| 781 | assert_eq!( |
| 782 | list_for_session(&db, &id, None, 0).await.unwrap().0.len(), |
| 783 | 0, |
| 784 | "round {round}: a roll call outlived its session" |
| 785 | ); |
| 786 | } else if drop_it.is_ok() { |
| 787 | panic!( |
| 788 | "round {round}: the delete reported success but the session is still there" |
| 789 | ); |
| 790 | } |
| 791 | } |
| 792 | eprintln!( |
| 793 | "CourseSession::delete raced by a roll call: {swept}/4 concurrent rounds deleted the session" |
| 794 | ); |
| 795 | } |
| 796 | } |