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

session_attendance.rs796 lines, 33.3 KiBHistoryRawDownload
1//! The `session_attendance` table: the lesson roll call and the two badge
2//! counters its mark and remove move. Every write is a single transaction
3//! whose gates ride inside it; the target-eligibility rules (staff rows are
4//! management's, only students attend, enrollment) are
5//! [`crate::service::session_attendance`]'s to judge before calling here.
6
7use crate::database::{Database, tx_with_retry};
8use crate::db::page::PagedList;
9use crate::domain::attendance::AttendanceStatus;
10use crate::domain::class_course::ClassCourseId;
11use crate::domain::course_session::{CourseSession, CourseSessionId};
12use crate::domain::session_attendance::SessionAttendance;
13use crate::domain::timestamp::Timestamp;
14use crate::domain::user::UserId;
15use crate::error::AppError;
16
17/// Record (or overwrite) `user`'s status for the session. The table's
18/// primary key *is* the (session, user) pair, so the mark is a single
19/// atomic upsert — concurrent marks converge on the one row.
20///
21/// The "session still exists" gate is a row lock: the transaction takes the
22/// session row `FOR NO KEY UPDATE` before anything else, so a session (or
23/// instance) delete cascading beneath this mark simply waits, and a delete
24/// that got there first leaves this gate matching nothing — `404`, the
25/// mirror of [`crate::db::course_session::delete`]. The caller's
26/// pre-flight read sits several round trips in front of this write, which
27/// is exactly the gap the old code had to fake with a bump-and-restore
28/// write on the session row; the lock is the same serialization without
29/// the trick. It also freezes `starts_at` and `held_counted_at` for the
30/// transaction, so two simultaneous first marks take turns and the
31/// lesson-held credit below is stamped exactly once.
32///
33/// Two badge counters move in this same transaction, both of them read
34/// from the store rather than taken on the caller's word:
35///
36/// - `lessons_attended_total`, on the person marked, as a *delta* rather
37/// than an increment, because this is an upsert: a re-mark that changes
38/// nothing must change nothing, and a teacher's correction must move it
39/// back down. The pair's stored status is read before the upsert
40/// overwrites it (`None` when the pair has no row yet), so it writes
41/// only on a real crossing of the attended line, and only for a
42/// **student** — attending lessons is a student's badge, the same
43/// student-only rule enrolling and sitting an exam already carry, so a
44/// teacher marked present in their own lesson moves it in neither
45/// direction. The live `role` decides that, not the role someone held
46/// when the row was written.
47/// - `lessons_held_total`, on the *session's* teacher, exactly once per
48/// session: the first roll call taken stamps `held_counted_at` on the
49/// lesson and every later mark sees the stamp and credits nothing. It
50/// counts lessons that actually happened — scheduling one and
51/// cancelling it earns nothing, which is why the credit does not live
52/// in `crate::db::course_session::create`. Two simultaneous first
53/// marks serialize on the session row's lock, so the stamp cannot be
54/// set twice.
55///
56/// "Actually happened" is a clock reading, not a request count: the
57/// credit waits for the lesson's own `starts_at` to arrive. Roll call is
58/// deliberately *not* time-gated — a teacher may open the sheet early
59/// and is never refused — so without this a teacher could schedule two
60/// hundred lessons for next week, mark one student in each, and hold two
61/// hundred lessons this afternoon. Because the stamp is written only on
62/// the branch that credits, a sheet opened early and touched again after
63/// the bell still credits exactly once, then; a sheet never touched
64/// again credits never, which is the deliberate cost of not storing a
65/// promise the passage of time would have to redeem on its own.
66///
67/// `lessons_attended_total` is *not* gated the same way, and the
68/// asymmetry is on purpose: it is a delta off the row's stored status,
69/// which carries no record of whether the credit was ever taken, so a
70/// gate would refund at the correction what the early mark never
71/// credited — a student's real lessons eaten by someone else's farm. It
72/// is also nobody's self-service: only a teacher can mark a student, so
73/// the counter cannot be moved by the person it decorates.
74//
75// corner-cut: that asymmetry leaves a teacher able to inflate a *student's*
76// attendance with future-dated lessons. Closing it needs the credit stamped
77// on the roll-call row itself and refunded off that stamp — the same column
78// the live-role note on `remove` below wants, and the shape
79// `counted_on_time` already uses for homework. One column closes both;
80// neither is worth it until a real complaint names one.
81pub 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 // Owned captures (`Send` rule of `tx_with_retry` closures).
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 // The gate and the serialization point: a live session row, locked
98 // against the delete cascade and every rival mark.
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 // The pair's stored status — the pre-image the attended delta is
110 // computed off.
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 // The live role of the person marked (a gone user row marks as
121 // non-student — no badge to move; the service gate has already
122 // refused a vanished target before this write ran).
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 // The attended badge: student-only, and only on a real crossing.
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 // The held badge: once per lesson, and only once the lesson began.
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
188pub 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 // The old composite key `{session}_{user}` sorted by user within a
195 // session — its session prefix was constant — so the natural-PK
196 // columns sort the same way.
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/// Every roll-call row ever recorded for `user` — the session half of the
207/// attendance report. Deliberately not filtered by current enrollment:
208/// attendance is a historical record, so unenrolling hides marks (report
209/// semantics) but never absences.
210pub 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/// Clearing a row the student was counted for gives the count back, in the
230/// delete's own transaction — the other direction of the delta in
231/// [`mark`], so a row that never existed and a row that
232/// was withdrawn leave the same number behind. Only *this* route decrements:
233/// [`crate::db::course_session::delete`]'s cascade sweeps the rows with a `DELETE` of
234/// its own and never comes through here, which is the ruling
235/// `exam_sat_total` already carries — deleting the lesson does not un-attend
236/// it. `lessons_held_total` is never given back either: the lesson was
237/// taken, and clearing one student's row does not un-take it.
238///
239/// Student-only on the same terms as the mark, and read from the store for
240/// the same reason.
241pub async fn remove(
242 db: &Database,
243 session: &CourseSessionId,
244 user: &UserId,
245) -> Result<Option<SessionAttendance>, AppError> {
246 // Owned captures (`Send` rule of `tx_with_retry` closures).
247 let session = session.clone();
248 let user = *user;
249 tx_with_retry(db, false, async move |tx| {
250 // The pre-image and the row's right to exist in one locked
251 // statement: the row cannot vanish (or change status) under this
252 // transaction, and `None` here is simply "nothing to remove".
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 // Student-only, live role: the same rule the mark pays.
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)]
304mod 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 /// A user row carrying its role — the counters are `UPDATE`s on one (which
312 /// writes nothing at all to a record that does not exist), and the live
313 /// role is what decides whether the attended counter moves.
314 async fn a_user(key: &str, role: Role, db: &Database) -> UserId {
315 // Minted fresh: the id is a real parent row now, and the minted uuid
316 // keeps repeated calls (same label, new person) collision-free.
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 /// A lesson long since begun — every test but the gate's own wants one.
353 async fn a_session(teacher: &UserId, db: &Database) -> CourseSession {
354 a_session_at(teacher, 1, db).await
355 }
356
357 /// A status this school allows — the four core ones plus a school-added
358 /// `online`, which is exactly the open half of the set.
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 /// The two counters as the badge rules read them, off the stored row.
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 /// The whole transition table in one pass: an upsert may only move the
384 /// counter when the mark crosses the attended line, in either direction, so
385 /// a re-mark and a swap within the same class are both no-ops.
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 // Ten marks, one lesson: correcting a roll call is not holding another.
415 assert_eq!(held(&teacher, &db).await, 1, "the lesson was counted twice");
416 }
417
418 /// The lesson is credited to its teacher when the roll call is *taken*, and
419 /// once: the whole roster, and every later correction, ride the same stamp.
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 // A second lesson is a second count — the stamp is per session.
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 /// A lesson is held when its own time comes, not when the sheet is opened.
447 /// Roll call is never refused early, so ungated a teacher could schedule
448 /// two hundred lessons for next week and hold all of them this afternoon.
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 // The mark itself stands — opening the sheet early is not an error.
462 assert_eq!(attended(&student, &db).await, 1);
463
464 // The bell rings. The same sheet, touched again, credits now — and
465 // only once: nothing backfills, so the stamp is the whole guard.
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 /// Attending lessons is a student's badge. A teacher marked present in
480 /// their own lesson (which management does, not the teacher) moves nothing
481 /// for them as an attendee — while the roll call itself still counts as a
482 /// lesson held.
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 // And the correction direction is just as closed: nothing was taken, so
496 // nothing may be given back.
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 /// Two lessons are two counts — the counter is per row, not per student.
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 /// Removing the row is the other direction of the delta, and only for a row
527 /// that was counted.
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 /// The floor: however the corrections and removals interleave, and whatever
570 /// a stale row starts from, the counter never goes negative.
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 // Ten counted lessons whose counter was never credited — the stale-data
578 // case, an account that predates the column. Every one of them is now
579 // corrected away, which is ten decrements against a zero.
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 /// Deleting the lesson sweeps its roll-call rows with a `DELETE` of its own
605 /// — it never reaches [`remove`] — so the count stands,
606 /// the ruling every other counter here carries.
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 /// A mark on a session that is already gone is refused, so it cannot leave
625 /// a count behind either.
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 /// The claim the existence gate cannot make by *reading*. The mark writes
646 /// the session row too (its attendance stamp), so the delete and the mark
647 /// touch one row and Postgres refuses one of them.
648 ///
649 /// The two flavors raced are the ones the credit branch never wrote for — a
650 /// lesson that has not begun, and a student with no row yet on a lesson
651 /// already counted. Both orders are forced for each flavor by awaiting one
652 /// side to completion before the other starts. A few rounds still start
653 /// together; those may all lose the delete, and that is not a failure.
654 /// Mutation-tested: dropping the unconditional session-row write from
655 /// `mark` turns the write-first rounds red.
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 // Delete-first.
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 // Write-first.
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 // Overlapped rounds. Delete may lose every one of them.
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}