🚧 wip: class-pump/meals/homework production fixes + T5 test-port continuation
Browse files at this commit35683ac646cda318a2272bc1b1507d511cef9e13Parent: af331ec83 changed files +2227 -1955
- src/ai/server.rs +1 -3
- src/db/answer_image.rs +4 -4
- src/db/attendance.rs +52 -34
- src/db/badge.rs +9 -9
- src/db/bank_question.rs +35 -39
- src/db/bank_question_image.rs +3 -3
- src/db/board.rs +2 -2
- src/db/builder.rs +1 -1
- src/db/chatbot_message.rs +22 -9
- src/db/chatbot_thread.rs +46 -58
- src/db/class_group.rs +89 -81
- src/db/class_member.rs +90 -28
- src/db/class_pump.rs +86 -118
- src/db/course.rs +101 -63
- src/db/course_note.rs +1 -1
- src/db/course_note_file.rs +2 -2
- src/db/course_session.rs +13 -8
- src/db/enrollment.rs +4 -57
- src/db/event.rs +63 -28
- src/db/exam.rs +123 -147
- src/db/exam_answer.rs +20 -13
- src/db/exam_attempt.rs +10 -10
- src/db/exam_question.rs +37 -30
- src/db/fee_plan.rs +1 -1
- src/db/homework.rs +42 -32
- src/db/homework_file.rs +38 -19
- src/db/homework_result.rs +60 -42
- src/db/homework_submission.rs +95 -62
- src/db/meal_attendance.rs +1 -1
- src/db/meal_booking.rs +34 -20
- src/db/meal_ledger.rs +0 -43
- src/db/menu.rs +95 -80
- src/db/message.rs +1 -1
- src/db/note.rs +1 -1
- src/db/note_file.rs +2 -2
- src/db/payment_ledger.rs +0 -46
- src/db/pomodoro.rs +124 -133
- src/db/pool_question.rs +39 -49
- src/db/profile.rs +3 -3
- src/db/question_image.rs +4 -4
- src/db/rag_output.rs +3 -3
- src/db/session.rs +19 -6
- src/db/session_attendance.rs +28 -27
- src/db/solution.rs +26 -12
- src/db/subject.rs +18 -14
- src/db/term.rs +2 -2
- src/db/work_entry.rs +11 -7
- src/service/appointment.rs +9 -9
- src/service/appointment_slot.rs +8 -8
- src/service/board.rs +1 -1
- src/service/builder.rs +1 -1
- src/service/class_blueprint.rs +146 -105
- src/service/class_course.rs +62 -62
- src/service/class_member.rs +52 -49
- src/service/exam_attempt.rs +31 -41
- src/service/fee_plan_assignment.rs +2 -2
- src/service/meal_booking.rs +24 -16
- src/service/payment_ledger.rs +4 -4
- src/service/settings.rs +121 -73
- src/service/user.rs +4 -4
- src/web/appointments.rs +5 -5
- src/web/bank_questions.rs +4 -4
- src/web/board_ws.rs +1 -1
- src/web/chatbot.rs +5 -5
- src/web/classes.rs +1 -1
- src/web/course_notes.rs +2 -2
- src/web/courses.rs +10 -10
- src/web/dto.rs +5 -5
- src/web/events.rs +2 -2
- src/web/exams/mod.rs +1 -1
- src/web/exams/questions.rs +2 -2
- src/web/homework.rs +2 -2
- src/web/messages.rs +1 -1
- src/web/mod.rs +1 -1
- src/web/payments.rs +2 -2
- src/web/tenant_state.rs +3 -3
- src/web/users.rs +3 -3
- tests/board_invite.rs +21 -15
- tests/regress_course_delete.rs +20 -17
- tests/regress_meals.rs +56 -36
- tests/regress_profile.rs +26 -29
- tests/regress_review.rs +2 -2
- tests/regress_role_sweep.rs +126 -73
src/ai/server.rsmodified+1 -3
| @@ -1077,9 +1077,7 @@ mod tests { | ||
| 1077 | 1077 | async fn armed(router: axum::Router) -> ApiHandle { |
| 1078 | 1078 | ApiHandle { |
| 1079 | 1079 | router, |
| 1080 | - tenants: crate::database::init_mem_tenants() | |
| 1081 | - .await | |
| 1082 | - .expect("in-memory deployment"), | |
| 1080 | + tenants: crate::database::init_test_tenants().await, | |
| 1083 | 1081 | files_path: std::env::temp_dir(), |
| 1084 | 1082 | } |
| 1085 | 1083 | } |
src/db/answer_image.rsmodified+4 -4
| @@ -240,12 +240,12 @@ mod tests { | ||
| 240 | 240 | } |
| 241 | 241 | |
| 242 | 242 | fn student() -> UserId { |
| 243 | - UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA") | |
| 243 | + UserId::from_key("019732e3-7b00-7000-8000-00000000a11a") | |
| 244 | 244 | } |
| 245 | 245 | |
| 246 | 246 | #[tokio::test] |
| 247 | 247 | async fn upsert_replaces_within_a_sitting_but_not_across_them() { |
| 248 | - let db = crate::database::init_mem().await.unwrap(); | |
| 248 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 249 | 249 | let exam = exam_row(&db).await; |
| 250 | 250 | let question = ExamQuestionId::generate(); |
| 251 | 251 | let user = student(); |
| @@ -287,7 +287,7 @@ mod tests { | ||
| 287 | 287 | ); |
| 288 | 288 | |
| 289 | 289 | // Another student's drawing for the same question/sitting is its own row. |
| 290 | - let other = UserId::from_key("01TESTSTUDENTBBBBBBBBBBBBB"); | |
| 290 | + let other = UserId::from_key("019732e3-7b00-7000-8000-00000000b22b"); | |
| 291 | 291 | upsert(&db, AnswerImage::new(&exam, &question, &other, 1, png(), 7)) |
| 292 | 292 | .await |
| 293 | 293 | .unwrap(); |
| @@ -297,7 +297,7 @@ mod tests { | ||
| 297 | 297 | |
| 298 | 298 | #[tokio::test] |
| 299 | 299 | async fn listing_scopes_by_exam_and_user() { |
| 300 | - let db = crate::database::init_mem().await.unwrap(); | |
| 300 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 301 | 301 | let exam_a = exam_row(&db).await; |
| 302 | 302 | let exam_b = exam_row(&db).await; |
| 303 | 303 | let user = student(); |
src/db/attendance.rsmodified+52 -34
| @@ -130,59 +130,77 @@ mod tests { | ||
| 130 | 130 | use crate::domain::settings::Settings; |
| 131 | 131 | |
| 132 | 132 | /// The session twin's race, one table over |
| 133 | - /// ([`crate::db::session_attendance::mark`]): a | |
| 134 | - /// `DEFINE EVENT` on `event` fires inside the delete's own transaction, and | |
| 135 | - /// the event's delete sweeps its attendance rows before removing the row, so | |
| 136 | - /// the `SLEEP` lands exactly between the sweep and the commit — the window | |
| 137 | - /// where a bare upsert wrote a mark nothing would ever sweep again. | |
| 138 | - /// | |
| 139 | - /// Real server, and `#[ignore]`d for it: the subject is the store's | |
| 140 | - /// conflict detection, which `init_mem`'s embedded engine does not have — | |
| 141 | - /// it commits both writes and answers `Ok` to each, so this passes there on | |
| 142 | - /// broken code. Mutation-tested: turning the claim back into a read | |
| 143 | - /// (`SELECT VALUE id FROM $ev`) turns it red. | |
| 133 | + /// ([`crate::db::session_attendance::mark`]): the event's delete sweeps its | |
| 134 | + /// attendance rows and removes the row in one transaction, and a mark that | |
| 135 | + /// wrote into the gap was a bare upsert nothing would ever sweep again. | |
| 136 | + /// The mark now writes the event row too (its seats counter), so the two | |
| 137 | + /// transactions touch one row and Postgres refuses one of them; the barrier | |
| 138 | + /// releases both sides together so every interleaving gets its chance. | |
| 139 | + /// Mutation-tested: turning the claim back into a read turns it red. | |
| 144 | 140 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 145 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | |
| 146 | 141 | async fn a_mark_written_inside_a_delete_never_outlives_the_event() { |
| 147 | - use crate::domain::event::{EventAudience, EventDescription, EventTitle}; | |
| 148 | - let (db, _serialized) = crate::database::init_test_server("event_attendance_race").await; | |
| 149 | - db.query( | |
| 150 | - "DEFINE EVENT hold_the_window ON TABLE event WHEN $event = 'DELETE' \ | |
| 151 | - THEN { SLEEP 1s; };", | |
| 152 | - ) | |
| 153 | - .await | |
| 154 | - .unwrap() | |
| 155 | - .check() | |
| 156 | - .unwrap(); | |
| 142 | + use crate::domain::event::{ | |
| 143 | + EventAudience, EventAudienceKind, EventDescription, EventTitle, | |
| 144 | + }; | |
| 157 | 145 | |
| 146 | + // A real `app_user` row: markers, students and event creators are | |
| 147 | + // foreign keys now. | |
| 148 | + async fn a_person(db: &Database, label: &str) -> UserId { | |
| 149 | + let user = UserId::generate(); | |
| 150 | + sqlx::query( | |
| 151 | + "INSERT INTO app_user (id, username, password_hash, role) \ | |
| 152 | + VALUES ($1, $2, 'x', 'teacher')", | |
| 153 | + ) | |
| 154 | + .bind(user.uuid()) | |
| 155 | + .bind(format!("{label}-{}", &user.key()[..8])) | |
| 156 | + .execute(db) | |
| 157 | + .await | |
| 158 | + .unwrap(); | |
| 159 | + user | |
| 160 | + } | |
| 161 | + | |
| 162 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 158 | 163 | let allowed: Vec<String> = Settings::defaults().get_attendance_statuses().to_vec(); |
| 159 | - let marker = UserId::from_key("t"); | |
| 164 | + let marker = a_person(&db, "marker").await; | |
| 160 | 165 | let (mut swept, mut orphans) = (0, 0); |
| 161 | - for round in 0..4 { | |
| 166 | + for round in 0..8 { | |
| 162 | 167 | let event = crate::db::event::create( |
| 163 | 168 | &db, |
| 164 | 169 | &marker, |
| 165 | 170 | EventTitle::try_new("gezi").unwrap(), |
| 166 | 171 | EventDescription::try_new("").unwrap(), |
| 167 | - EventAudience::School, | |
| 172 | + EventAudience { | |
| 173 | + kind: EventAudienceKind::School, | |
| 174 | + role: None, | |
| 175 | + course: None, | |
| 176 | + class: None, | |
| 177 | + capacity: None, | |
| 178 | + }, | |
| 168 | 179 | None, |
| 169 | 180 | None, |
| 170 | 181 | ) |
| 171 | 182 | .await |
| 172 | 183 | .unwrap(); |
| 173 | 184 | let id = event.get_id().clone(); |
| 185 | + | |
| 186 | + // Delete and mark released together: both write the event row, so | |
| 187 | + // Postgres serializes them and refuses whichever lost. | |
| 188 | + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | |
| 174 | 189 | let drop_it = { |
| 175 | - let db = db.clone(); | |
| 176 | - tokio::spawn(async move { crate::db::event::delete(&db, event).await }) | |
| 190 | + let (db, gate, event) = (db.clone(), gate.clone(), event); | |
| 191 | + tokio::spawn(async move { | |
| 192 | + gate.wait().await; | |
| 193 | + crate::db::event::delete(&db, event).await | |
| 194 | + }) | |
| 177 | 195 | }; |
| 178 | - // The mark starts inside the held window: the sweep has run and the | |
| 179 | - // event row is gone but uncommitted. | |
| 180 | - tokio::time::sleep(std::time::Duration::from_millis(300)).await; | |
| 181 | 196 | let marked = { |
| 182 | - let (db, id, marker) = (db.clone(), id.clone(), marker.clone()); | |
| 183 | - let student = UserId::from_key(&format!("s{round}")); | |
| 197 | + let (db, id, marker, gate) = (db.clone(), id.clone(), marker.clone(), gate); | |
| 198 | + let student = a_person(&db, "student").await; | |
| 184 | 199 | let status = AttendanceStatus::try_new("present", &allowed).unwrap(); |
| 185 | - tokio::spawn(async move { mark(&db, &id, &student, status, &marker).await }) | |
| 200 | + tokio::spawn(async move { | |
| 201 | + gate.wait().await; | |
| 202 | + mark(&db, &id, &student, status, &marker).await | |
| 203 | + }) | |
| 186 | 204 | }; |
| 187 | 205 | let (drop_it, marked) = (drop_it.await.unwrap(), marked.await.unwrap()); |
| 188 | 206 | assert!( |
| @@ -198,7 +216,7 @@ mod tests { | ||
| 198 | 216 | panic!("round {round}: the delete reported success but the event is still there"); |
| 199 | 217 | } |
| 200 | 218 | } |
| 201 | - eprintln!("Event::delete raced by a mark: {swept}/4 rounds deleted the event"); | |
| 219 | + eprintln!("Event::delete raced by a mark: {swept}/8 rounds deleted the event"); | |
| 202 | 220 | assert!( |
| 203 | 221 | swept > 0, |
| 204 | 222 | "no round ever deleted the event, so the window was never reached" |
src/db/badge.rsmodified+9 -9
| @@ -111,7 +111,7 @@ pub async fn sync(db: &Database, user: &UserId) -> Result<(), AppError> { | ||
| 111 | 111 | SET earned_at = badge_award.earned_at \ |
| 112 | 112 | WHERE badge_award.earned_at IS NULL" |
| 113 | 113 | ))) |
| 114 | - .bind(user.uuid()) | |
| 114 | +.bind(user.uuid()) | |
| 115 | 115 | .bind(badge) |
| 116 | 116 | .bind(now) |
| 117 | 117 | .execute(db) |
| @@ -124,7 +124,7 @@ pub async fn sync(db: &Database, user: &UserId) -> Result<(), AppError> { | ||
| 124 | 124 | mod tests { |
| 125 | 125 | use super::*; |
| 126 | 126 | use crate::constant::BADGE_AWARD_TABLE; |
| 127 | - use crate::database::init_mem; | |
| 127 | + use crate::database::init_test_db; | |
| 128 | 128 | use crate::domain::user::{Password, Username}; |
| 129 | 129 | |
| 130 | 130 | async fn a_user(username: &str, db: &Database) -> crate::domain::user::User { |
| @@ -142,9 +142,9 @@ mod tests { | ||
| 142 | 142 | } |
| 143 | 143 | |
| 144 | 144 | async fn count_awards(db: &Database, user: &UserId) -> i64 { |
| 145 | - let (count,): (i64,) = sqlx::query_as(&format!( | |
| 145 | + let (count,): (i64,) = sqlx::query_as(sqlx::AssertSqlSafe(format!( | |
| 146 | 146 | "SELECT count(*) FROM {BADGE_AWARD_TABLE} WHERE app_user = $1" |
| 147 | - )) | |
| 147 | + ))) | |
| 148 | 148 | .bind(user.uuid()) |
| 149 | 149 | .fetch_one(db) |
| 150 | 150 | .await |
| @@ -161,7 +161,7 @@ mod tests { | ||
| 161 | 161 | |
| 162 | 162 | #[tokio::test] |
| 163 | 163 | async fn load_defaults_every_counter_to_zero() { |
| 164 | - let db = init_mem().await.unwrap(); | |
| 164 | + let (db, _leases) = init_test_db().await; | |
| 165 | 165 | let user = a_user("badge-sifir", &db).await; |
| 166 | 166 | |
| 167 | 167 | let stats = load(&db, user.get_id()).await.unwrap(); |
| @@ -177,12 +177,12 @@ mod tests { | ||
| 177 | 177 | |
| 178 | 178 | #[tokio::test] |
| 179 | 179 | async fn sync_is_idempotent_and_keeps_the_first_stamp() { |
| 180 | - let db = init_mem().await.unwrap(); | |
| 180 | + let (db, _leases) = init_test_db().await; | |
| 181 | 181 | let user = a_user("badge-ali", &db).await; |
| 182 | 182 | |
| 183 | 183 | // Seed two submitted homeworks: enough for the first badge tier. |
| 184 | 184 | sqlx::query("UPDATE app_user SET homework_submitted_total = 2 WHERE id = $1") |
| 185 | - .bind(user.uuid()) | |
| 185 | + .bind(user.get_id().uuid()) | |
| 186 | 186 | .execute(&db) |
| 187 | 187 | .await |
| 188 | 188 | .unwrap(); |
| @@ -195,7 +195,7 @@ mod tests { | ||
| 195 | 195 | // A second sync with the counter moved *further* writes nothing: the |
| 196 | 196 | // stamps are from the first crossing, and no row is duplicated. |
| 197 | 197 | sqlx::query("UPDATE app_user SET homework_submitted_total = 5 WHERE id = $1") |
| 198 | - .bind(user.uuid()) | |
| 198 | + .bind(user.get_id().uuid()) | |
| 199 | 199 | .execute(&db) |
| 200 | 200 | .await |
| 201 | 201 | .unwrap(); |
| @@ -218,7 +218,7 @@ mod tests { | ||
| 218 | 218 | |
| 219 | 219 | #[tokio::test] |
| 220 | 220 | async fn sync_writes_nothing_for_a_earned_nothing() { |
| 221 | - let db = init_mem().await.unwrap(); | |
| 221 | + let (db, _leases) = init_test_db().await; | |
| 222 | 222 | let user = a_user("badge-bos", &db).await; |
| 223 | 223 | sync(&db, user.get_id()).await.unwrap(); |
| 224 | 224 | assert_eq!( |
src/db/bank_question.rsmodified+35 -39
| @@ -414,33 +414,33 @@ mod tests { | ||
| 414 | 414 | .unwrap() |
| 415 | 415 | } |
| 416 | 416 | |
| 417 | - /// A row stored before `visibility` existed has no such key — it must decode | |
| 418 | - /// as `private`, the safe value. Asserted on the decoder itself, so no | |
| 419 | - /// schema DEFAULT can paper over it: a `school` default here would publish | |
| 420 | - /// every pre-existing template in the school at once. | |
| 417 | + /// A row without a visibility of its own must decode as `private`, the | |
| 418 | + /// safe value. The old engine could store a row with the field absent; | |
| 419 | + /// Postgres carries the same guarantee in the schema instead — the column | |
| 420 | + /// is `NOT NULL DEFAULT 'private'`, so a `school` default here would | |
| 421 | + /// publish every pre-existing template in the school at once. The insert | |
| 422 | + /// below is written exactly as a pre-visibility row arrives: no column. | |
| 421 | 423 | #[tokio::test] |
| 422 | 424 | async fn a_row_without_the_field_decodes_private() { |
| 423 | - use surrealdb::types::Value; | |
| 424 | - | |
| 425 | - let db = crate::database::init_mem().await.unwrap(); | |
| 426 | - let question = create( | |
| 427 | - &db, | |
| 428 | - UserId::generate(), | |
| 429 | - SubjectId::generate(), | |
| 430 | - QuestionText::try_new("q").unwrap(), | |
| 431 | - QuestionPoints::try_new(1).unwrap(), | |
| 432 | - spec(), | |
| 425 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 426 | + let owner = UserId::generate(); | |
| 427 | + sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, 'q', 'x')") | |
| 428 | + .bind(owner.uuid()) | |
| 429 | + .execute(&db) | |
| 430 | + .await | |
| 431 | + .unwrap(); | |
| 432 | + let id = BankQuestionId::generate(); | |
| 433 | + sqlx::query( | |
| 434 | + "INSERT INTO bank_question (id, owner, text, kind, points, created_at) \ | |
| 435 | + VALUES ($1, $2, 'q', 'multiple_choice', 1, 0)", | |
| 433 | 436 | ) |
| 437 | + .bind(id.uuid()) | |
| 438 | + .bind(owner.uuid()) | |
| 439 | + .execute(&db) | |
| 434 | 440 | .await |
| 435 | 441 | .unwrap(); |
| 436 | - assert_eq!(question.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE); | |
| 437 | 442 | |
| 438 | - let mut stored = question.into_value(); | |
| 439 | - let Value::Object(map) = &mut stored else { | |
| 440 | - panic!("a bank question serializes to an object"); | |
| 441 | - }; | |
| 442 | - assert!(map.remove("visibility").is_some()); | |
| 443 | - let old = BankQuestion::from_value(stored).unwrap(); | |
| 443 | + let old = read(&db, &id).await.unwrap().expect("the row is there"); | |
| 444 | 444 | assert_eq!(old.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE); |
| 445 | 445 | assert!(!old.get_visibility().is_school()); |
| 446 | 446 | } |
| @@ -449,7 +449,7 @@ mod tests { | ||
| 449 | 449 | /// page can contain — never someone else's private templates. |
| 450 | 450 | #[tokio::test] |
| 451 | 451 | async fn list_hides_private_templates_from_others() { |
| 452 | - let db = crate::database::init_mem().await.unwrap(); | |
| 452 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 453 | 453 | let owner = UserId::generate(); |
| 454 | 454 | let other = UserId::generate(); |
| 455 | 455 | let private = create( |
| @@ -516,7 +516,7 @@ mod tests { | ||
| 516 | 516 | /// still answer `Ok`. |
| 517 | 517 | #[tokio::test] |
| 518 | 518 | async fn a_merge_built_on_a_stale_snapshot_is_refused() { |
| 519 | - let db = crate::database::init_mem().await.unwrap(); | |
| 519 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 520 | 520 | let owner = UserId::generate(); |
| 521 | 521 | let stale = create( |
| 522 | 522 | &db, |
| @@ -564,7 +564,7 @@ mod tests { | ||
| 564 | 564 | /// row, and `private` means "my own drafts" for everyone but an admin. |
| 565 | 565 | #[tokio::test] |
| 566 | 566 | async fn visibility_filter_narrows_never_widens() { |
| 567 | - let db = crate::database::init_mem().await.unwrap(); | |
| 567 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 568 | 568 | let owner = UserId::generate(); |
| 569 | 569 | let other = UserId::generate(); |
| 570 | 570 | let mine = |text: &str| { |
| @@ -638,14 +638,10 @@ mod tests { | ||
| 638 | 638 | /// "0"), and questions authored by hand never counted. |
| 639 | 639 | #[tokio::test] |
| 640 | 640 | async fn usage_counts_tallies_a_page_in_one_statement() { |
| 641 | - // One statement, so a page costs one round trip — a `;` here would mean | |
| 642 | - // the per-row N+1 crept back in. | |
| 643 | - assert!( | |
| 644 | - !USAGE_COUNTS_SQL.contains(';'), | |
| 645 | - "usage_counts must be one statement" | |
| 646 | - ); | |
| 647 | - | |
| 648 | - let db = crate::database::init_mem().await.unwrap(); | |
| 641 | + // One statement, so a page costs one round trip: the tally is a single | |
| 642 | + // static `query!` (a `GROUP BY` with no loop around it), which the | |
| 643 | + // compiler now checks the way the old constant asserted. | |
| 644 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 649 | 645 | let owner = UserId::generate(); |
| 650 | 646 | let template = |text: &str| { |
| 651 | 647 | create( |
| @@ -712,10 +708,10 @@ mod tests { | ||
| 712 | 708 | |
| 713 | 709 | let ids = [used_twice.get_id(), used_once.get_id(), unused.get_id()]; |
| 714 | 710 | let counts = usage_counts(&db, &ids).await.unwrap(); |
| 715 | - assert_eq!(counts.get(used_twice.get_id().key()).copied(), Some(2)); | |
| 716 | - assert_eq!(counts.get(used_once.get_id().key()).copied(), Some(1)); | |
| 711 | + assert_eq!(counts.get(&used_twice.get_id().key()).copied(), Some(2)); | |
| 712 | + assert_eq!(counts.get(&used_once.get_id().key()).copied(), Some(1)); | |
| 717 | 713 | assert_eq!( |
| 718 | - counts.get(unused.get_id().key()), | |
| 714 | + counts.get(&unused.get_id().key()), | |
| 719 | 715 | None, |
| 720 | 716 | "unused stays absent" |
| 721 | 717 | ); |
| @@ -724,14 +720,14 @@ mod tests { | ||
| 724 | 720 | // A template outside the page is never counted into it. |
| 725 | 721 | let narrow = usage_counts(&db, &[used_once.get_id()]).await.unwrap(); |
| 726 | 722 | assert_eq!(narrow.len(), 1); |
| 727 | - assert_eq!(narrow.get(used_once.get_id().key()).copied(), Some(1)); | |
| 723 | + assert_eq!(narrow.get(&used_once.get_id().key()).copied(), Some(1)); | |
| 728 | 724 | // An empty page asks nothing at all. |
| 729 | 725 | assert!(usage_counts(&db, &[]).await.unwrap().is_empty()); |
| 730 | 726 | } |
| 731 | 727 | |
| 732 | 728 | #[tokio::test] |
| 733 | 729 | async fn list_is_school_wide() { |
| 734 | - let db = crate::database::init_mem().await.unwrap(); | |
| 730 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 735 | 731 | for _ in 0..2 { |
| 736 | 732 | create( |
| 737 | 733 | &db, |
| @@ -755,7 +751,7 @@ mod tests { | ||
| 755 | 751 | /// The window is SQL, not an in-memory slice, and `total` ignores it. |
| 756 | 752 | #[tokio::test] |
| 757 | 753 | async fn list_pages_newest_first_and_filters_text() { |
| 758 | - let db = crate::database::init_mem().await.unwrap(); | |
| 754 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 759 | 755 | let owner = UserId::generate(); |
| 760 | 756 | for i in 0..5 { |
| 761 | 757 | create( |
| @@ -806,7 +802,7 @@ mod tests { | ||
| 806 | 802 | /// Turkish `İ`/`ı` must not split the search into two disjoint halves. |
| 807 | 803 | #[tokio::test] |
| 808 | 804 | async fn list_text_filter_folds_turkish_casing() { |
| 809 | - let db = crate::database::init_mem().await.unwrap(); | |
| 805 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 810 | 806 | create( |
| 811 | 807 | &db, |
| 812 | 808 | UserId::generate(), |
src/db/bank_question_image.rsmodified+3 -3
| @@ -232,7 +232,7 @@ mod tests { | ||
| 232 | 232 | |
| 233 | 233 | #[tokio::test] |
| 234 | 234 | async fn upsert_replaces_per_slot() { |
| 235 | - let db = crate::database::init_mem().await.unwrap(); | |
| 235 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 236 | 236 | let question = a_template(&db).await; |
| 237 | 237 | |
| 238 | 238 | let (first, retired) = upsert(&db, BankQuestionImage::new(&question, None, png(), 3)) |
| @@ -255,7 +255,7 @@ mod tests { | ||
| 255 | 255 | /// picture, and only a removed option's picture goes. |
| 256 | 256 | #[tokio::test] |
| 257 | 257 | async fn only_the_dropped_options_lose_their_pictures() { |
| 258 | - let db = crate::database::init_mem().await.unwrap(); | |
| 258 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 259 | 259 | let question = a_template(&db).await; |
| 260 | 260 | let ids = choice_ids(); |
| 261 | 261 | upsert(&db, BankQuestionImage::new(&question, None, png(), 1)) |
| @@ -278,7 +278,7 @@ mod tests { | ||
| 278 | 278 | |
| 279 | 279 | #[tokio::test] |
| 280 | 280 | async fn an_empty_keep_set_clears_every_option_picture() { |
| 281 | - let db = crate::database::init_mem().await.unwrap(); | |
| 281 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 282 | 282 | let question = a_template(&db).await; |
| 283 | 283 | let ids = choice_ids(); |
| 284 | 284 | upsert(&db, BankQuestionImage::new(&question, None, png(), 1)) |
src/db/board.rsmodified+2 -2
| @@ -331,7 +331,7 @@ mod tests { | ||
| 331 | 331 | /// the meantime is a 404 — not a silent success. |
| 332 | 332 | #[tokio::test] |
| 333 | 333 | async fn field_scoped_writes_return_the_row_and_a_gone_board_refuses() { |
| 334 | - let db = crate::database::init_mem().await.unwrap(); | |
| 334 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 335 | 335 | let creator = UserId::generate(); |
| 336 | 336 | let board = create( |
| 337 | 337 | &db, |
| @@ -362,7 +362,7 @@ mod tests { | ||
| 362 | 362 | /// board row, and deleting a board hands the seat back. |
| 363 | 363 | #[tokio::test] |
| 364 | 364 | async fn the_cap_refuses_and_delete_releases_the_seat() { |
| 365 | - let db = crate::database::init_mem().await.unwrap(); | |
| 365 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 366 | 366 | let creator = UserId::generate(); |
| 367 | 367 | for index in 0..MAX_BOARDS_PER_CREATOR { |
| 368 | 368 | create( |
src/db/builder.rsmodified+1 -1
| @@ -116,7 +116,7 @@ mod tests { | ||
| 116 | 116 | |
| 117 | 117 | #[tokio::test] |
| 118 | 118 | async fn a_builder_session_round_trips_and_deletes() { |
| 119 | - let tenants = Tenants::new_mem().await.unwrap(); | |
| 119 | + let tenants = crate::database::init_test_tenants().await; | |
| 120 | 120 | let control = tenants.control(); |
| 121 | 121 | builder::ensure( |
| 122 | 122 | control, |
src/db/chatbot_message.rsmodified+22 -9
| @@ -315,16 +315,29 @@ mod tests { | ||
| 315 | 315 | // `id` tie-break decides the thread's order. With a random ULID this |
| 316 | 316 | // inverted a fifth of the pairs; here every pair must read back |
| 317 | 317 | // question-then-answer, from both read paths. |
| 318 | - let db = crate::database::init_mem().await.unwrap(); | |
| 318 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 319 | 319 | // A real thread row: every turn is written through it, so a turn with |
| 320 | - // no thread is refused (see [`insert`]). | |
| 321 | - db.query("CREATE chatbot_thread:c SET user_id = user:u, created_at = 0, updated_at = 0") | |
| 322 | - .await | |
| 323 | - .unwrap() | |
| 324 | - .check() | |
| 325 | - .unwrap(); | |
| 326 | - let thread = ChatbotThreadId::from_key("c"); | |
| 327 | - let user = UserId::from_key("u"); | |
| 320 | + // no thread is refused (see [`insert`]). The owner is a foreign key | |
| 321 | + // now, so both fixture rows are real, under fixed keys. | |
| 322 | + let user = UserId::from_key("019732e3-7b00-7000-8000-00000000cafe"); | |
| 323 | + let thread = ChatbotThreadId::from_key("019732e3-7b00-7000-8000-00000000beef"); | |
| 324 | + sqlx::query( | |
| 325 | + "INSERT INTO app_user (id, username, password_hash) \ | |
| 326 | + VALUES ($1, 'chat-fixture', 'x')", | |
| 327 | + ) | |
| 328 | + .bind(user.uuid()) | |
| 329 | + .execute(&db) | |
| 330 | + .await | |
| 331 | + .unwrap(); | |
| 332 | + sqlx::query( | |
| 333 | + "INSERT INTO chatbot_thread (id, user_id, created_at, updated_at) \ | |
| 334 | + VALUES ($1, $2, 0, 0)", | |
| 335 | + ) | |
| 336 | + .bind(thread.uuid()) | |
| 337 | + .bind(user.uuid()) | |
| 338 | + .execute(&db) | |
| 339 | + .await | |
| 340 | + .unwrap(); | |
| 328 | 341 | const TURNS: usize = 200; |
| 329 | 342 | |
| 330 | 343 | for turn in 0..TURNS { |
src/db/chatbot_thread.rsmodified+46 -58
| @@ -193,34 +193,41 @@ pub async fn delete(db: &Database, thread: ChatbotThread) -> Result<ChatbotThrea | ||
| 193 | 193 | #[cfg(test)] |
| 194 | 194 | mod tests { |
| 195 | 195 | use super::*; |
| 196 | - use surrealdb::types::RecordId; | |
| 196 | + use sqlx::Row as _; | |
| 197 | 197 | |
| 198 | 198 | use crate::db::chatbot_message; |
| 199 | 199 | use crate::domain::chatbot_message::ChatContent; |
| 200 | 200 | use crate::domain::settings::{Settings, SettingsParams}; |
| 201 | 201 | |
| 202 | + /// The fixed fixture person, by a valid id every helper can name. | |
| 203 | + const U: &str = "019732e3-7b00-7000-8000-00000000aaaa"; | |
| 204 | + | |
| 202 | 205 | /// The owner's counter and the threads it counts, both re-read out of the |
| 203 | - /// store — never off a return value, which the in-memory engine forges | |
| 204 | - /// wins on (see [`cap`]). | |
| 206 | + /// store — never off a return value. | |
| 205 | 207 | async fn stored(db: &Database) -> (i64, usize) { |
| 206 | - let mut result = db | |
| 207 | - .query("SELECT VALUE (chatbot_thread_count ?? 0) FROM user:u") | |
| 208 | - .query("SELECT VALUE id FROM chatbot_thread") | |
| 208 | + let counter = | |
| 209 | + sqlx::query("SELECT chatbot_thread_count FROM app_user WHERE id = $1") | |
| 210 | + .bind(UserId::from_key(U).uuid()) | |
| 211 | + .fetch_one(db) | |
| 212 | + .await | |
| 213 | + .unwrap() | |
| 214 | + .try_get::<i64, _>(0) | |
| 215 | + .unwrap(); | |
| 216 | + let rows = sqlx::query("SELECT count(*) FROM chatbot_thread") | |
| 217 | + .fetch_one(db) | |
| 209 | 218 | .await |
| 210 | 219 | .unwrap() |
| 211 | - .check() | |
| 220 | + .try_get::<i64, _>(0) | |
| 212 | 221 | .unwrap(); |
| 213 | - let counter = result.take::<Vec<i64>>(0).unwrap(); | |
| 214 | - let rows = result.take::<Vec<RecordId>>(1).unwrap(); | |
| 215 | - (counter[0], rows.len()) | |
| 222 | + (counter, rows as usize) | |
| 216 | 223 | } |
| 217 | 224 | |
| 218 | 225 | async fn a_user_capped_at(threads: i64) -> Database { |
| 219 | - let db = crate::database::init_mem().await.unwrap(); | |
| 220 | - db.query("CREATE user:u SET username = 'u', password_hash = 'x';") | |
| 226 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 227 | + sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, 'u', 'x')") | |
| 228 | + .bind(UserId::from_key(U).uuid()) | |
| 229 | + .execute(&db) | |
| 221 | 230 | .await |
| 222 | - .unwrap() | |
| 223 | - .check() | |
| 224 | 231 | .unwrap(); |
| 225 | 232 | crate::db::settings::save( |
| 226 | 233 | &db, |
| @@ -241,7 +248,7 @@ mod tests { | ||
| 241 | 248 | #[tokio::test] |
| 242 | 249 | async fn a_capped_create_moves_the_counter_with_the_row() { |
| 243 | 250 | let db = a_user_capped_at(1).await; |
| 244 | - let user = UserId::from_key("u"); | |
| 251 | + let user = UserId::from_key(U); | |
| 245 | 252 | |
| 246 | 253 | create_capped(&db, &user, None).await.expect("first thread"); |
| 247 | 254 | assert_eq!(stored(&db).await, (1, 1)); |
| @@ -262,7 +269,7 @@ mod tests { | ||
| 262 | 269 | #[tokio::test] |
| 263 | 270 | async fn a_turn_writes_its_thread_and_dies_with_it() { |
| 264 | 271 | let db = a_user_capped_at(2).await; |
| 265 | - let user = UserId::from_key("u"); | |
| 272 | + let user = UserId::from_key(U); | |
| 266 | 273 | let thread = create_capped(&db, &user, None).await.expect("thread"); |
| 267 | 274 | let opened = thread.get_updated_at().as_millis(); |
| 268 | 275 | |
| @@ -322,16 +329,15 @@ mod tests { | ||
| 322 | 329 | const LEAD: i64 = 1_000; |
| 323 | 330 | |
| 324 | 331 | let db = a_user_capped_at(1).await; |
| 325 | - let user = UserId::from_key("u"); | |
| 332 | + let user = UserId::from_key(U); | |
| 326 | 333 | let thread = create_capped(&db, &user, None).await.expect("thread"); |
| 327 | 334 | |
| 328 | 335 | let parked = Timestamp::now().as_millis() + LEAD; |
| 329 | - db.query("UPDATE $id SET updated_at = $parked") | |
| 330 | - .bind(("id", thread.get_id().record())) | |
| 331 | - .bind(("parked", parked)) | |
| 336 | + sqlx::query("UPDATE chatbot_thread SET updated_at = $1 WHERE id = $2") | |
| 337 | + .bind(parked) | |
| 338 | + .bind(thread.get_id().uuid()) | |
| 339 | + .execute(&db) | |
| 332 | 340 | .await |
| 333 | - .unwrap() | |
| 334 | - .check() | |
| 335 | 341 | .unwrap(); |
| 336 | 342 | |
| 337 | 343 | for _ in 0..2 { |
| @@ -377,51 +383,33 @@ mod tests { | ||
| 377 | 383 | /// row ([`touch_and_write`]) instead of reading it — the two transactions |
| 378 | 384 | /// then touch one key and the store refuses to commit both. |
| 379 | 385 | /// |
| 380 | - /// The window is opened by the database itself rather than by a lucky | |
| 381 | - /// interleaving: a `DEFINE EVENT` on `chatbot_thread` fires *inside* the | |
| 382 | - /// delete's own transaction, the instant the row goes, so the `SLEEP` lands | |
| 383 | - /// after the message sweep and before the commit every single time. | |
| 384 | - /// | |
| 385 | - /// Real server, and `#[ignore]`d for it: the subject is the store's | |
| 386 | - /// conflict detection, which `init_mem`'s embedded engine does not have — | |
| 387 | - /// it commits both writes and answers `Ok` to each, which would fail this | |
| 388 | - /// test on correct code (see [`crate::database::init_test_server`]). | |
| 386 | + /// The window the schema event used to force open is the thread row's own | |
| 387 | + /// lock now: a turn is written *through* the row ([`touch_and_write`]), | |
| 388 | + /// so a turn racing the delete serializes on that row instead of | |
| 389 | + /// committing past the sweep. A barrier start lets both orders happen, | |
| 390 | + /// and the invariant must hold in each. | |
| 389 | 391 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 390 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | |
| 391 | 392 | async fn a_turn_written_inside_a_delete_never_outlives_the_thread() { |
| 392 | - let (db, _serialized) = crate::database::init_test_server("chat_delete_race").await; | |
| 393 | - db.query("CREATE user:u SET username = 'u', password_hash = 'x';") | |
| 394 | - .await | |
| 395 | - .unwrap() | |
| 396 | - .check() | |
| 397 | - .unwrap(); | |
| 398 | - // Hold the delete open for a full second after the thread row is gone, | |
| 399 | - // while its transaction still has to commit. | |
| 400 | - db.query( | |
| 401 | - "DEFINE EVENT hold_the_window ON TABLE chatbot_thread WHEN $event = 'DELETE' \ | |
| 402 | - THEN { SLEEP 1s; };", | |
| 403 | - ) | |
| 404 | - .await | |
| 405 | - .unwrap() | |
| 406 | - .check() | |
| 407 | - .unwrap(); | |
| 393 | + let db = a_user_capped_at(4).await; | |
| 408 | 394 | |
| 409 | - let user = UserId::from_key("u"); | |
| 395 | + let user = UserId::from_key(U); | |
| 410 | 396 | let (mut orphans, mut swept) = (0, 0); |
| 411 | - for round in 0..4 { | |
| 397 | + for round in 0..8 { | |
| 412 | 398 | let thread = create_capped(&db, &user, None).await.expect("thread"); |
| 413 | 399 | let id = thread.get_id().clone(); |
| 414 | 400 | |
| 401 | + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | |
| 415 | 402 | let drop_it = { |
| 416 | - let db = db.clone(); | |
| 417 | - tokio::spawn(async move { delete(&db, thread).await }) | |
| 403 | + let (db, thread, gate) = (db.clone(), thread, gate.clone()); | |
| 404 | + tokio::spawn(async move { | |
| 405 | + gate.wait().await; | |
| 406 | + delete(&db, thread).await | |
| 407 | + }) | |
| 418 | 408 | }; |
| 419 | - // The turn starts inside the held window — the thread row is gone | |
| 420 | - // but uncommitted, which is exactly what a read believes. | |
| 421 | - tokio::time::sleep(std::time::Duration::from_millis(300)).await; | |
| 422 | 409 | let turn = { |
| 423 | - let (id, db, user) = (id.clone(), db.clone(), user.clone()); | |
| 410 | + let (id, db, user, gate) = (id.clone(), db.clone(), user.clone(), gate); | |
| 424 | 411 | tokio::spawn(async move { |
| 412 | + gate.wait().await; | |
| 425 | 413 | chatbot_message::append_user( |
| 426 | 414 | &db, |
| 427 | 415 | &id, |
| @@ -451,10 +439,10 @@ mod tests { | ||
| 451 | 439 | panic!("round {round}: the delete reported success but the thread is still there"); |
| 452 | 440 | } |
| 453 | 441 | } |
| 454 | - eprintln!("chatbot_thread::delete raced by a turn: {swept}/4 rounds deleted the thread"); | |
| 442 | + eprintln!("chatbot_thread::delete raced by a turn: {swept}/8 rounds deleted the thread"); | |
| 455 | 443 | assert!( |
| 456 | 444 | swept > 0, |
| 457 | - "no round ever deleted the thread, so the window was never reached" | |
| 445 | + "no round ever deleted the thread, so the race never actually ran" | |
| 458 | 446 | ); |
| 459 | 447 | assert_eq!(orphans, 0, "a turn outlived its thread"); |
| 460 | 448 | } |
src/db/class_group.rsmodified+89 -81
| @@ -292,12 +292,31 @@ pub async fn delete(db: &Database, class: ClassGroup) -> Result<bool, AppError> | ||
| 292 | 292 | #[cfg(test)] |
| 293 | 293 | mod tests { |
| 294 | 294 | use super::*; |
| 295 | + use sqlx::Row as _; | |
| 296 | + | |
| 295 | 297 | use crate::domain::term::{Term, TermName}; |
| 296 | 298 | |
| 299 | + /// A real `app_user` row: creator, teacher, and attached-by are foreign | |
| 300 | + /// keys now, so every fixture participant is a row, not a fabricated id. | |
| 301 | + async fn a_named_user(db: &Database, username: &str) -> UserId { | |
| 302 | + let user = UserId::generate(); | |
| 303 | + sqlx::query( | |
| 304 | + "INSERT INTO app_user (id, username, password_hash, role) \ | |
| 305 | + VALUES ($1, $2, 'x', 'teacher')", | |
| 306 | + ) | |
| 307 | + .bind(user.uuid()) | |
| 308 | + .bind(username) | |
| 309 | + .execute(db) | |
| 310 | + .await | |
| 311 | + .unwrap(); | |
| 312 | + user | |
| 313 | + } | |
| 314 | + | |
| 297 | 315 | async fn class_on(term: Option<TermId>, db: &Database) -> ClassGroup { |
| 316 | + let manager = a_named_user(db, "manager").await; | |
| 298 | 317 | create( |
| 299 | 318 | db, |
| 300 | - &UserId::from_key("manager"), | |
| 319 | + &manager, | |
| 301 | 320 | ClassName::try_new("9-A").unwrap(), |
| 302 | 321 | None, |
| 303 | 322 | term, |
| @@ -309,9 +328,10 @@ mod tests { | ||
| 309 | 328 | |
| 310 | 329 | /// A class with a homeroom teacher, no term. |
| 311 | 330 | async fn class_of(teacher: Option<UserId>, db: &Database) -> ClassGroup { |
| 331 | + let manager = a_named_user(db, "manager").await; | |
| 312 | 332 | create( |
| 313 | 333 | db, |
| 314 | - &UserId::from_key("manager"), | |
| 334 | + &manager, | |
| 315 | 335 | ClassName::try_new("9-A").unwrap(), |
| 316 | 336 | None, |
| 317 | 337 | None, |
| @@ -338,41 +358,30 @@ mod tests { | ||
| 338 | 358 | .unwrap() |
| 339 | 359 | } |
| 340 | 360 | |
| 341 | - /// The stored counter, re-read — never off a return value, which the | |
| 342 | - /// in-memory engine forges wins on (see [`crate::db::cap`]). | |
| 343 | - async fn stored_count(sql: &str, db: &Database) -> i64 { | |
| 344 | - let mut result = db.query(sql).await.unwrap().check().unwrap(); | |
| 345 | - result | |
| 346 | - .take::<Vec<i64>>(0) | |
| 361 | + /// The single integer `sql` selects — the stored counter, re-read, never | |
| 362 | + /// off a return value. The SQL is built from literals in this module, so | |
| 363 | + /// the audit wrapper is a formality. | |
| 364 | + async fn one_i64(db: &Database, sql: String) -> i64 { | |
| 365 | + sqlx::query(sqlx::AssertSqlSafe(sql)) | |
| 366 | + .fetch_one(db) | |
| 367 | + .await | |
| 347 | 368 | .unwrap() |
| 348 | - .first() | |
| 349 | - .copied() | |
| 369 | + .try_get::<i64, _>(0) | |
| 350 | 370 | .unwrap() |
| 351 | 371 | } |
| 352 | 372 | |
| 353 | 373 | /// The stored `class_count` on one term, absent counting as zero. |
| 354 | 374 | async fn count_on(term: &TermId, db: &Database) -> i64 { |
| 355 | - let mut result = db | |
| 356 | - .query(format!( | |
| 357 | - "SELECT VALUE ({TERM_CLASS_COUNT_FIELD} ?? 0) FROM $term" | |
| 358 | - )) | |
| 359 | - .bind(("term", term.record())) | |
| 360 | - .await | |
| 361 | - .unwrap() | |
| 362 | - .check() | |
| 363 | - .unwrap(); | |
| 364 | - result | |
| 365 | - .take::<Vec<i64>>(0) | |
| 366 | - .unwrap() | |
| 367 | - .first() | |
| 368 | - .copied() | |
| 369 | - .unwrap_or(0) | |
| 375 | + one_i64( | |
| 376 | + db, | |
| 377 | + format!("SELECT COALESCE(class_count, 0) FROM term WHERE id = '{}'", term.uuid()), | |
| 378 | + ) | |
| 379 | + .await | |
| 370 | 380 | } |
| 371 | 381 | |
| 372 | - /// How many rows `sql` selects ids for. | |
| 373 | - async fn rows(sql: &str, db: &Database) -> usize { | |
| 374 | - let mut result = db.query(sql).await.unwrap().check().unwrap(); | |
| 375 | - result.take::<Vec<RecordId>>(0).unwrap().len() | |
| 382 | + /// How many rows `table` holds. | |
| 383 | + async fn row_count(db: &Database, table: &str) -> i64 { | |
| 384 | + one_i64(db, format!("SELECT count(*) FROM {table}")).await | |
| 376 | 385 | } |
| 377 | 386 | |
| 378 | 387 | /// The homeroom teacher survives a create, is set and cleared by a PATCH, |
| @@ -381,9 +390,9 @@ mod tests { | ||
| 381 | 390 | /// no key at all, which must read back as `None`, not fail the decode. |
| 382 | 391 | #[tokio::test] |
| 383 | 392 | async fn the_homeroom_teacher_is_stored_set_cleared_and_left_alone() { |
| 384 | - let db = crate::database::init_mem().await.unwrap(); | |
| 385 | - let ada = UserId::from_key("ada"); | |
| 386 | - let boole = UserId::from_key("boole"); | |
| 393 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 394 | + let ada = a_named_user(&db, "ada").await; | |
| 395 | + let boole = a_named_user(&db, "boole").await; | |
| 387 | 396 | |
| 388 | 397 | let bare = class_of(None, &db).await; |
| 389 | 398 | assert_eq!(teacher_of(bare.get_id(), &db).await, None); |
| @@ -421,18 +430,18 @@ mod tests { | ||
| 421 | 430 | None, |
| 422 | 431 | None, |
| 423 | 432 | None, |
| 424 | - Some(Some(UserId::from_key("ada"))), | |
| 433 | + Some(Some(a_named_user(&db, "ada").await)), | |
| 425 | 434 | ) |
| 426 | 435 | .await |
| 427 | 436 | .unwrap(); |
| 428 | 437 | assert_eq!(again.get_name().as_str(), "9-B"); |
| 429 | 438 | |
| 430 | - // A row that predates the column: absent key, not NULL. | |
| 431 | - db.query("UPDATE $class UNSET teacher") | |
| 432 | - .bind(("class", bare.get_id().record())) | |
| 439 | + // A row without a homeroom: the column reads back as NULL, not a | |
| 440 | + // decode failure. | |
| 441 | + sqlx::query("UPDATE class_group SET teacher = NULL WHERE id = $1") | |
| 442 | + .bind(bare.get_id().uuid()) | |
| 443 | + .execute(&db) | |
| 433 | 444 | .await |
| 434 | - .unwrap() | |
| 435 | - .check() | |
| 436 | 445 | .unwrap(); |
| 437 | 446 | assert_eq!(teacher_of(bare.get_id(), &db).await, None); |
| 438 | 447 | } |
| @@ -441,9 +450,9 @@ mod tests { | ||
| 441 | 450 | /// *every* class they homeroomed, and nobody else's is touched. |
| 442 | 451 | #[tokio::test] |
| 443 | 452 | async fn unassign_everywhere_clears_only_that_users_classes() { |
| 444 | - let db = crate::database::init_mem().await.unwrap(); | |
| 445 | - let ada = UserId::from_key("ada"); | |
| 446 | - let boole = UserId::from_key("boole"); | |
| 453 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 454 | + let ada = a_named_user(&db, "ada").await; | |
| 455 | + let boole = a_named_user(&db, "boole").await; | |
| 447 | 456 | let first = class_of(Some(ada.clone()), &db).await; |
| 448 | 457 | let second = class_of(Some(ada.clone()), &db).await; |
| 449 | 458 | let other = class_of(Some(boole.clone()), &db).await; |
| @@ -471,18 +480,18 @@ mod tests { | ||
| 471 | 480 | /// instead would pass the first assert and fail the roundtrip through boot. |
| 472 | 481 | #[tokio::test] |
| 473 | 482 | async fn a_term_is_deletable_only_once_no_class_links_it() { |
| 474 | - let db = crate::database::init_mem().await.unwrap(); | |
| 483 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 475 | 484 | let term = a_term(&db).await; |
| 476 | 485 | |
| 477 | 486 | let linked = class_on(Some(term.get_id().clone()), &db).await; |
| 478 | 487 | let patched = class_on(Some(term.get_id().clone()), &db).await; |
| 479 | 488 | assert_eq!( |
| 480 | - stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await, | |
| 489 | + one_i64(&db, "SELECT COALESCE(class_count, 0) FROM term".to_string()).await, | |
| 481 | 490 | 2, |
| 482 | 491 | "classes must count on class_count, not course_count" |
| 483 | 492 | ); |
| 484 | 493 | assert_eq!( |
| 485 | - stored_count("SELECT VALUE course_count ?? 0 FROM term", &db).await, | |
| 494 | + one_i64(&db, "SELECT COALESCE(course_count, 0) FROM term".to_string()).await, | |
| 486 | 495 | 0, |
| 487 | 496 | "the courses' counter is seeded from course rows and must stay untouched" |
| 488 | 497 | ); |
| @@ -511,15 +520,16 @@ mod tests { | ||
| 511 | 520 | /// which a refusal that released it would strand. |
| 512 | 521 | #[tokio::test] |
| 513 | 522 | async fn a_class_with_members_or_courses_refuses_to_delete() { |
| 514 | - for field in [CLASS_MEMBER_COUNT_FIELD, CLASS_COURSE_COUNT_FIELD] { | |
| 515 | - let db = crate::database::init_mem().await.unwrap(); | |
| 523 | + for field in ["class_member_count", "class_course_count"] { | |
| 524 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 516 | 525 | let term = a_term(&db).await; |
| 517 | 526 | let class = class_on(Some(term.get_id().clone()), &db).await; |
| 518 | - db.query(format!("UPDATE $class SET {field} = 1")) | |
| 519 | - .bind(("class", class.get_id().record())) | |
| 527 | + sqlx::query(sqlx::AssertSqlSafe(format!( | |
| 528 | + "UPDATE class_group SET {field} = 1 WHERE id = $1" | |
| 529 | + ))) | |
| 530 | + .bind(class.get_id().uuid()) | |
| 531 | + .execute(&db) | |
| 520 | 532 | .await |
| 521 | - .unwrap() | |
| 522 | - .check() | |
| 523 | 533 | .unwrap(); |
| 524 | 534 | |
| 525 | 535 | assert!( |
| @@ -531,21 +541,22 @@ mod tests { | ||
| 531 | 541 | "a refused delete may write nothing" |
| 532 | 542 | ); |
| 533 | 543 | assert_eq!( |
| 534 | - stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await, | |
| 544 | + one_i64(&db, "SELECT COALESCE(class_count, 0) FROM term".to_string()).await, | |
| 535 | 545 | 1, |
| 536 | 546 | "…the term reference least of all" |
| 537 | 547 | ); |
| 538 | 548 | |
| 539 | 549 | // Back to zero, and the same class deletes and releases the term. |
| 540 | - db.query(format!("UPDATE $class SET {field} = 0")) | |
| 541 | - .bind(("class", class.get_id().record())) | |
| 550 | + sqlx::query(sqlx::AssertSqlSafe(format!( | |
| 551 | + "UPDATE class_group SET {field} = 0 WHERE id = $1" | |
| 552 | + ))) | |
| 553 | + .bind(class.get_id().uuid()) | |
| 554 | + .execute(&db) | |
| 542 | 555 | .await |
| 543 | - .unwrap() | |
| 544 | - .check() | |
| 545 | 556 | .unwrap(); |
| 546 | 557 | assert!(delete(&db, class.clone()).await.unwrap()); |
| 547 | 558 | assert_eq!( |
| 548 | - stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await, | |
| 559 | + one_i64(&db, "SELECT COALESCE(class_count, 0) FROM term".to_string()).await, | |
| 549 | 560 | 0 |
| 550 | 561 | ); |
| 551 | 562 | let again = delete(&db, class).await; |
| @@ -561,14 +572,14 @@ mod tests { | ||
| 561 | 572 | /// delete guard reads, so a stray one would make it undeletable forever). |
| 562 | 573 | #[tokio::test] |
| 563 | 574 | async fn a_refused_create_writes_neither_row_nor_count() { |
| 564 | - let db = crate::database::init_mem().await.unwrap(); | |
| 575 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 565 | 576 | let term = a_term(&db).await; |
| 566 | 577 | let id = term.get_id().clone(); |
| 567 | 578 | assert!(crate::db::term::delete(&db, term).await.unwrap()); |
| 568 | 579 | |
| 569 | 580 | let error = create( |
| 570 | 581 | &db, |
| 571 | - &UserId::from_key("manager"), | |
| 582 | + &a_named_user(&db, "manager").await, | |
| 572 | 583 | ClassName::try_new("9-A").unwrap(), |
| 573 | 584 | None, |
| 574 | 585 | Some(id), |
| @@ -578,12 +589,12 @@ mod tests { | ||
| 578 | 589 | .expect_err("a term that is gone must not be linkable"); |
| 579 | 590 | assert!(error.to_string().contains("term does not exist")); |
| 580 | 591 | assert_eq!( |
| 581 | - rows("SELECT VALUE id FROM class_group", &db).await, | |
| 592 | + row_count(&db, "class_group").await, | |
| 582 | 593 | 0, |
| 583 | 594 | "a refused create may write no row" |
| 584 | 595 | ); |
| 585 | 596 | assert_eq!( |
| 586 | - rows("SELECT VALUE id FROM term", &db).await, | |
| 597 | + row_count(&db, "term").await, | |
| 587 | 598 | 0, |
| 588 | 599 | "…and least of all a count on a term it just brought back" |
| 589 | 600 | ); |
| @@ -596,7 +607,7 @@ mod tests { | ||
| 596 | 607 | /// so the old count would be 0 if the abort did not undo it). |
| 597 | 608 | #[tokio::test] |
| 598 | 609 | async fn a_class_term_move_moves_both_counts_or_neither() { |
| 599 | - let db = crate::database::init_mem().await.unwrap(); | |
| 610 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 600 | 611 | let at = crate::domain::timestamp::Timestamp::from_millis; |
| 601 | 612 | let from = a_term(&db).await; |
| 602 | 613 | let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200)) |
| @@ -660,7 +671,7 @@ mod tests { | ||
| 660 | 671 | /// with the counts reading as if they never ran. |
| 661 | 672 | #[tokio::test] |
| 662 | 673 | async fn a_stale_class_term_write_is_refused_and_moves_no_count() { |
| 663 | - let db = crate::database::init_mem().await.unwrap(); | |
| 674 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 664 | 675 | let at = crate::domain::timestamp::Timestamp::from_millis; |
| 665 | 676 | let from = a_term(&db).await; |
| 666 | 677 | let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200)) |
| @@ -738,8 +749,8 @@ mod tests { | ||
| 738 | 749 | async fn deleting_a_course_sweeps_its_class_attachments() { |
| 739 | 750 | use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; |
| 740 | 751 | |
| 741 | - let db = crate::database::init_mem().await.unwrap(); | |
| 742 | - let manager = UserId::from_key("manager"); | |
| 752 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 753 | + let manager = a_named_user(&db, "manager").await; | |
| 743 | 754 | let course = crate::db::course::create( |
| 744 | 755 | &db, |
| 745 | 756 | &manager, |
| @@ -752,30 +763,27 @@ mod tests { | ||
| 752 | 763 | .await |
| 753 | 764 | .unwrap(); |
| 754 | 765 | let class = class_on(None, &db).await; |
| 755 | - db.query(format!( | |
| 756 | - "CREATE class_course SET class = $class, course = $course, attached_by = $usr; | |
| 757 | - UPDATE $class SET {CLASS_COURSE_COUNT_FIELD} = 1;" | |
| 758 | - )) | |
| 759 | - .bind(("class", class.get_id().record())) | |
| 760 | - .bind(("course", course.get_id().record())) | |
| 761 | - .bind(("usr", manager.record())) | |
| 762 | - .await | |
| 763 | - .unwrap() | |
| 764 | - .check() | |
| 765 | - .unwrap(); | |
| 766 | + sqlx::query("INSERT INTO class_course (class, course, attached_by) VALUES ($1, $2, $3)") | |
| 767 | + .bind(class.get_id().uuid()) | |
| 768 | + .bind(course.get_id().uuid()) | |
| 769 | + .bind(manager.uuid()) | |
| 770 | + .execute(&db) | |
| 771 | + .await | |
| 772 | + .unwrap(); | |
| 773 | + sqlx::query("UPDATE class_group SET class_course_count = 1 WHERE id = $1") | |
| 774 | + .bind(class.get_id().uuid()) | |
| 775 | + .execute(&db) | |
| 776 | + .await | |
| 777 | + .unwrap(); | |
| 766 | 778 | |
| 767 | 779 | assert!(crate::db::course::delete(&db, course).await.unwrap()); |
| 768 | 780 | assert_eq!( |
| 769 | - rows("SELECT VALUE id FROM class_course", &db).await, | |
| 781 | + row_count(&db, "class_course").await, | |
| 770 | 782 | 0, |
| 771 | 783 | "the attachment rows must go with the course" |
| 772 | 784 | ); |
| 773 | 785 | assert_eq!( |
| 774 | - stored_count( | |
| 775 | - &format!("SELECT VALUE {CLASS_COURSE_COUNT_FIELD} ?? 0 FROM class_group"), | |
| 776 | - &db | |
| 777 | - ) | |
| 778 | - .await, | |
| 786 | + one_i64(&db, "SELECT COALESCE(class_course_count, 0) FROM class_group".to_string()).await, | |
| 779 | 787 | 0, |
| 780 | 788 | "…and each class must get its count back" |
| 781 | 789 | ); |
src/db/class_member.rsmodified+90 -28
| @@ -50,14 +50,41 @@ pub async fn list_for_user( | ||
| 50 | 50 | #[cfg(test)] |
| 51 | 51 | pub(crate) mod tests { |
| 52 | 52 | use super::*; |
| 53 | - use crate::domain::class_group::ClassName; | |
| 53 | + use crate::domain::class_group::{ClassGroupId, ClassName}; | |
| 54 | 54 | use crate::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle}; |
| 55 | - use surrealdb::types::RecordId; | |
| 55 | + use crate::domain::user::UserId; | |
| 56 | + | |
| 57 | + /// A real `app_user` row for fixtures, by username — the username is | |
| 58 | + /// unique, so every call for the same name shares one row, whichever call | |
| 59 | + /// minted it. Creators, graders, and `added_by` are foreign keys now, so | |
| 60 | + use sqlx::Row as _; | |
| 61 | + | |
| 62 | + /// fixture actors are rows, not fabricated ids. | |
| 63 | + pub(crate) async fn fixture_user(db: &Database, username: &str) -> UserId { | |
| 64 | + sqlx::query( | |
| 65 | + "INSERT INTO app_user (id, username, password_hash, role) \ | |
| 66 | + VALUES ($1, $2, 'x', 'student') ON CONFLICT DO NOTHING", | |
| 67 | + ) | |
| 68 | + .bind(crate::domain::user::UserId::generate().uuid()) | |
| 69 | + .bind(username) | |
| 70 | + .execute(db) | |
| 71 | + .await | |
| 72 | + .unwrap(); | |
| 73 | + let id: uuid::Uuid = sqlx::query("SELECT id FROM app_user WHERE username = $1") | |
| 74 | + .bind(username) | |
| 75 | + .fetch_one(db) | |
| 76 | + .await | |
| 77 | + .unwrap() | |
| 78 | + .try_get(0) | |
| 79 | + .unwrap(); | |
| 80 | + UserId::from_key(&id.to_string()) | |
| 81 | + } | |
| 56 | 82 | |
| 57 | 83 | pub(crate) async fn a_class(name: &str, db: &Database) -> ClassGroupId { |
| 84 | + let manager = fixture_user(db, "manager").await; | |
| 58 | 85 | crate::db::class_group::create( |
| 59 | 86 | db, |
| 60 | - &UserId::from_key("manager"), | |
| 87 | + &manager, | |
| 61 | 88 | ClassName::try_new(name).unwrap(), |
| 62 | 89 | None, |
| 63 | 90 | None, |
| @@ -70,9 +97,10 @@ pub(crate) mod tests { | ||
| 70 | 97 | } |
| 71 | 98 | |
| 72 | 99 | pub(crate) async fn a_course(title: &str, capacity: Option<i64>, db: &Database) -> CourseId { |
| 100 | + let manager = fixture_user(db, "manager").await; | |
| 73 | 101 | crate::db::course::create( |
| 74 | 102 | db, |
| 75 | - &UserId::from_key("manager"), | |
| 103 | + &manager, | |
| 76 | 104 | CourseTitle::try_new(title).unwrap(), |
| 77 | 105 | CourseDescription::try_new("").unwrap(), |
| 78 | 106 | CourseKind::course(), |
| @@ -85,40 +113,74 @@ pub(crate) mod tests { | ||
| 85 | 113 | .clone() |
| 86 | 114 | } |
| 87 | 115 | |
| 88 | - /// A counter, re-read out of the store — never off a return value, which | |
| 89 | - /// the in-memory engine forges wins on (see [`crate::db::cap`]). | |
| 90 | - pub(crate) async fn counter(field: &str, of: RecordId, db: &Database) -> i64 { | |
| 91 | - let mut result = db | |
| 92 | - .query(format!("SELECT VALUE {field} ?? 0 FROM $of")) | |
| 93 | - .bind(("of", of)) | |
| 116 | + /// A counter column on its row, re-read out of the store — never off a | |
| 117 | + /// return value. The column name picks the table: every `*_count` these | |
| 118 | + /// suites read lives on exactly one. | |
| 119 | + pub(crate) async fn counter(field: &str, of: uuid::Uuid, db: &Database) -> i64 { | |
| 120 | + let table = match field { | |
| 121 | + "enrollment_count" => "course", | |
| 122 | + "class_member_count" | "class_course_count" => "class_group", | |
| 123 | + other => panic!("no table known for the counter {other}"), | |
| 124 | + }; | |
| 125 | + sqlx::query(sqlx::AssertSqlSafe(format!( | |
| 126 | + "SELECT COALESCE({field}, 0) FROM {table} WHERE id = $1" | |
| 127 | + ))) | |
| 128 | + .bind(of) | |
| 129 | + .fetch_one(db) | |
| 94 | 130 | .await |
| 95 | 131 | .unwrap() |
| 96 | - .check() | |
| 97 | - .unwrap(); | |
| 98 | - result | |
| 99 | - .take::<Vec<i64>>(0) | |
| 132 | + .try_get::<i64, _>(0) | |
| 133 | + .unwrap() | |
| 134 | + } | |
| 135 | + | |
| 136 | + /// How many rows `table` holds. | |
| 137 | + pub(crate) async fn rows(table: &str, db: &Database) -> i64 { | |
| 138 | + sqlx::query(sqlx::AssertSqlSafe(format!("SELECT count(*) FROM {table}"))) | |
| 139 | + .fetch_one(db) | |
| 140 | + .await | |
| 100 | 141 | .unwrap() |
| 101 | - .first() | |
| 102 | - .copied() | |
| 142 | + .try_get::<i64, _>(0) | |
| 103 | 143 | .unwrap() |
| 104 | 144 | } |
| 105 | 145 | |
| 106 | - /// How many rows `sql` selects ids for. | |
| 107 | - pub(crate) async fn rows(sql: &str, db: &Database) -> usize { | |
| 108 | - let mut result = db.query(sql).await.unwrap().check().unwrap(); | |
| 109 | - result.take::<Vec<RecordId>>(0).unwrap().len() | |
| 146 | + /// Whether the course row is still there. | |
| 147 | + pub(crate) async fn course_exists(course: &CourseId, db: &Database) -> bool { | |
| 148 | + sqlx::query("SELECT 1 FROM course WHERE id = $1") | |
| 149 | + .bind(course.uuid()) | |
| 150 | + .fetch_optional(db) | |
| 151 | + .await | |
| 152 | + .unwrap() | |
| 153 | + .is_some() | |
| 110 | 154 | } |
| 111 | 155 | |
| 112 | - /// Whether `id` names a live row. | |
| 113 | - pub(crate) async fn exists(id: RecordId, db: &Database) -> bool { | |
| 114 | - let mut result = db | |
| 115 | - .query("SELECT VALUE id FROM $id") | |
| 116 | - .bind(("id", id)) | |
| 156 | + /// Whether the enrollment pair still has its row. | |
| 157 | + pub(crate) async fn enrollment_exists( | |
| 158 | + course: &CourseId, | |
| 159 | + user: &UserId, | |
| 160 | + db: &Database, | |
| 161 | + ) -> bool { | |
| 162 | + sqlx::query("SELECT 1 FROM enrollment WHERE course = $1 AND app_user = $2") | |
| 163 | + .bind(course.uuid()) | |
| 164 | + .bind(user.uuid()) | |
| 165 | + .fetch_optional(db) | |
| 117 | 166 | .await |
| 118 | 167 | .unwrap() |
| 119 | - .check() | |
| 120 | - .unwrap(); | |
| 121 | - !result.take::<Vec<RecordId>>(0).unwrap().is_empty() | |
| 168 | + .is_some() | |
| 169 | + } | |
| 170 | + | |
| 171 | + /// Whether the class-course link is still attached. | |
| 172 | + pub(crate) async fn link_exists( | |
| 173 | + class: &ClassGroupId, | |
| 174 | + course: &CourseId, | |
| 175 | + db: &Database, | |
| 176 | + ) -> bool { | |
| 177 | + sqlx::query("SELECT 1 FROM class_course WHERE class = $1 AND course = $2") | |
| 178 | + .bind(class.uuid()) | |
| 179 | + .bind(course.uuid()) | |
| 180 | + .fetch_optional(db) | |
| 181 | + .await | |
| 182 | + .unwrap() | |
| 183 | + .is_some() | |
| 122 | 184 | } |
| 123 | 185 | |
| 124 | 186 | /// The class that wrote an enrollment, or `None` for a hand-placed row. |
src/db/class_pump.rsmodified+86 -118
| @@ -379,7 +379,7 @@ pub(crate) async fn add_member( | ||
| 379 | 379 | let added_at = Timestamp::now(); |
| 380 | 380 | let class = class.clone(); |
| 381 | 381 | let (user, by) = (*user, *by); |
| 382 | - tx_with_retry(db, false, async move |tx| { | |
| 382 | + let outcome = tx_with_retry(db, false, async move |tx| { | |
| 383 | 383 | if let Some(early) = |
| 384 | 384 | early_verdicts(tx, &class, Axis::Member, Pivot::User(&user), None).await? |
| 385 | 385 | { |
| @@ -439,11 +439,7 @@ pub(crate) async fn add_member( | ||
| 439 | 439 | .fetch_all(&mut *tx) |
| 440 | 440 | .await?; |
| 441 | 441 | let pairs = courses.into_iter().map(|course| (course, user.uuid())); |
| 442 | - match enroll_pairs(tx, &class, pairs, &by).await? { | |
| 443 | - Sweep::Done => {} | |
| 444 | - Sweep::CourseGone(course) => return Ok(Attached::CourseGone(course)), | |
| 445 | - Sweep::Full(course) => return Ok(Attached::Full(course)), | |
| 446 | - } | |
| 442 | + enroll_pairs(tx, &class, pairs, &by).await?; | |
| 447 | 443 | Ok(Attached::Made(ClassMember { |
| 448 | 444 | class: class.clone(), |
| 449 | 445 | user, |
| @@ -451,7 +447,8 @@ pub(crate) async fn add_member( | ||
| 451 | 447 | added_at: Some(added_at), |
| 452 | 448 | })) |
| 453 | 449 | }) |
| 454 | - .await | |
| 450 | + .await; | |
| 451 | + map_sweep_abort(outcome) | |
| 455 | 452 | } |
| 456 | 453 | |
| 457 | 454 | /// Write the course link and enroll the class's whole roster into it, or |
| @@ -478,7 +475,7 @@ pub(crate) async fn attach_course( | ||
| 478 | 475 | let course = course.clone(); |
| 479 | 476 | let by = *by; |
| 480 | 477 | let source = source.cloned(); |
| 481 | - tx_with_retry(db, false, async move |tx| { | |
| 478 | + let outcome = tx_with_retry(db, false, async move |tx| { | |
| 482 | 479 | if let Some(early) = early_verdicts( |
| 483 | 480 | tx, |
| 484 | 481 | &class, |
| @@ -536,11 +533,7 @@ pub(crate) async fn attach_course( | ||
| 536 | 533 | .fetch_all(&mut *tx) |
| 537 | 534 | .await?; |
| 538 | 535 | let pairs = members.into_iter().map(|user| (course.uuid(), user)); |
| 539 | - match enroll_pairs(tx, &class, pairs, &by).await? { | |
| 540 | - Sweep::Done => {} | |
| 541 | - Sweep::CourseGone(course) => return Ok(Attached::CourseGone(course)), | |
| 542 | - Sweep::Full(course) => return Ok(Attached::Full(course)), | |
| 543 | - } | |
| 536 | + enroll_pairs(tx, &class, pairs, &by).await?; | |
| 544 | 537 | Ok(Attached::Made(ClassCourse { |
| 545 | 538 | class: class.clone(), |
| 546 | 539 | course: course.clone(), |
| @@ -549,17 +542,31 @@ pub(crate) async fn attach_course( | ||
| 549 | 542 | attached_at: Some(attached_at), |
| 550 | 543 | })) |
| 551 | 544 | }) |
| 552 | - .await | |
| 545 | + .await; | |
| 546 | + map_sweep_abort(outcome) | |
| 553 | 547 | } |
| 554 | 548 | |
| 555 | -/// What the shared enrollment loop settled for its pairs. | |
| 556 | -enum Sweep { | |
| 557 | - /// Every pair holds the row it owes. | |
| 558 | - Done, | |
| 559 | - /// One of the pairs' courses is gone, named by its key: a stale link. | |
| 560 | - CourseGone(String), | |
| 561 | - /// One of the pairs' courses has no free seat, named by its key. | |
| 562 | - Full(String), | |
| 549 | +/// Abort markers the pair loop raises where the old transaction `THROW` did, | |
| 550 | +/// in the [`crate::db::field_update`] style: a refusal found *after* earlier | |
| 551 | +/// pairs wrote must take the whole run down with it — returning it as `Ok` | |
| 552 | +/// would COMMIT the partial enrollment. The marker carries the course's key | |
| 553 | +/// and is mapped back to [`Attached`] right after [`tx_with_retry`] returns | |
| 554 | +/// ([`map_sweep_abort`]); it never reaches the wire. | |
| 555 | +const COURSE_GONE_MARK: &str = "class_pump_course_gone:"; | |
| 556 | +const COURSE_FULL_MARK: &str = "class_pump_course_full:"; | |
| 557 | + | |
| 558 | +/// The pair loop's abort markers back into their [`Attached`] refusals — | |
| 559 | +/// every other outcome passes through untouched. | |
| 560 | +fn map_sweep_abort<T>(outcome: Result<Attached<T>, AppError>) -> Result<Attached<T>, AppError> { | |
| 561 | + match outcome { | |
| 562 | + Err(AppError::Internal(m)) if m.starts_with(COURSE_GONE_MARK) => Ok(Attached::CourseGone( | |
| 563 | + m[COURSE_GONE_MARK.len()..].to_string(), | |
| 564 | + )), | |
| 565 | + Err(AppError::Internal(m)) if m.starts_with(COURSE_FULL_MARK) => { | |
| 566 | + Ok(Attached::Full(m[COURSE_FULL_MARK.len()..].to_string())) | |
| 567 | + } | |
| 568 | + other => other, | |
| 569 | + } | |
| 563 | 570 | } |
| 564 | 571 | |
| 565 | 572 | /// Enroll every `(course, user)` pair that has no row yet, each against its |
| @@ -583,7 +590,7 @@ async fn enroll_pairs( | ||
| 583 | 590 | class: &ClassGroupId, |
| 584 | 591 | pairs: impl Iterator<Item = (uuid::Uuid, uuid::Uuid)>, |
| 585 | 592 | by: &UserId, |
| 586 | -) -> Result<Sweep, AppError> { | |
| 593 | +) -> Result<(), AppError> { | |
| 587 | 594 | for (course, user) in pairs { |
| 588 | 595 | let held = sqlx::query_scalar!( |
| 589 | 596 | r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#, |
| @@ -601,7 +608,7 @@ async fn enroll_pairs( | ||
| 601 | 608 | .await? |
| 602 | 609 | .is_some(); |
| 603 | 610 | if !alive { |
| 604 | - return Ok(Sweep::CourseGone(course.to_string())); | |
| 611 | + return Err(AppError::Internal(format!("{COURSE_GONE_MARK}{course}"))); | |
| 605 | 612 | } |
| 606 | 613 | let seat = sqlx::query_scalar!( |
| 607 | 614 | r#"UPDATE course SET enrollment_count = enrollment_count + 1 |
| @@ -614,7 +621,7 @@ async fn enroll_pairs( | ||
| 614 | 621 | .await? |
| 615 | 622 | .is_some(); |
| 616 | 623 | if !seat { |
| 617 | - return Ok(Sweep::Full(course.to_string())); | |
| 624 | + return Err(AppError::Internal(format!("{COURSE_FULL_MARK}{course}"))); | |
| 618 | 625 | } |
| 619 | 626 | let wrote = sqlx::query_scalar!( |
| 620 | 627 | r#"INSERT INTO enrollment (course, app_user, enrolled_by, source) |
| @@ -655,7 +662,7 @@ async fn enroll_pairs( | ||
| 655 | 662 | Err(e) => return Err(e.into()), |
| 656 | 663 | } |
| 657 | 664 | } |
| 658 | - Ok(Sweep::Done) | |
| 665 | + Ok(()) | |
| 659 | 666 | } |
| 660 | 667 | |
| 661 | 668 | // The sweep a role change *off` `student` owes — every class membership (each |
| @@ -900,10 +907,8 @@ async fn release( | ||
| 900 | 907 | #[cfg(test)] |
| 901 | 908 | mod tests { |
| 902 | 909 | use super::*; |
| 903 | - use crate::constant::{CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE}; | |
| 904 | - use crate::db::class_member::tests::{a_class, counter, rows}; | |
| 910 | + use crate::db::class_member::tests::{a_class, counter, fixture_user, rows}; | |
| 905 | 911 | use crate::domain::class_group::ClassGroupId; |
| 906 | - use crate::domain::user::UserId; | |
| 907 | 912 | use crate::error::AppError; |
| 908 | 913 | use crate::service::{class_course, class_member}; |
| 909 | 914 | |
| @@ -913,33 +918,32 @@ mod tests { | ||
| 913 | 918 | /// does not exist. |
| 914 | 919 | #[tokio::test] |
| 915 | 920 | async fn an_attach_onto_a_missing_class_writes_nothing() { |
| 916 | - let db = crate::database::init_mem().await.unwrap(); | |
| 917 | - let ghost = ClassGroupId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"); | |
| 921 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 922 | + let ghost = ClassGroupId::from_key("019732e3-7b00-7000-8000-00000000dead"); | |
| 918 | 923 | |
| 919 | 924 | let refused = class_member::add( |
| 920 | 925 | &db, |
| 921 | 926 | &ghost, |
| 922 | - &UserId::from_key("student"), | |
| 923 | - &UserId::from_key("manager"), | |
| 927 | + &fixture_user(&db, "student").await, | |
| 928 | + &fixture_user(&db, "manager").await, | |
| 924 | 929 | ) |
| 925 | 930 | .await; |
| 926 | 931 | assert!( |
| 927 | 932 | matches!(refused, Err(AppError::NotFound)), |
| 928 | 933 | "a class that is gone is a 404, not a counter on nothing: {refused:?}" |
| 929 | 934 | ); |
| 930 | - assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0); | |
| 931 | - assert_eq!(rows("SELECT VALUE id FROM class_group", &db).await, 0); | |
| 935 | + assert_eq!(rows("class_member", &db).await, 0); | |
| 936 | + assert_eq!(rows("class_group", &db).await, 0); | |
| 932 | 937 | } |
| 933 | 938 | |
| 934 | - /// [`detach`] is written to take *many* link rows at once — that is what | |
| 935 | - /// makes a user's whole membership one statement — and every one of them | |
| 936 | - /// releases its own class's counter. Called straight, because the public | |
| 937 | - /// `delete_for_user` throws the count away. | |
| 939 | + /// The role-change sweep takes a user's whole membership apart, link row | |
| 940 | + /// by link row (one transaction per pair since the Postgres port), and | |
| 941 | + /// every one of them releases its own class's counter. | |
| 938 | 942 | #[tokio::test] |
| 939 | 943 | async fn a_detach_releases_every_class_it_unlinked() { |
| 940 | - let db = crate::database::init_mem().await.unwrap(); | |
| 941 | - let manager = UserId::from_key("manager"); | |
| 942 | - let student = UserId::from_key("student"); | |
| 944 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 945 | + let manager = fixture_user(&db, "manager").await; | |
| 946 | + let student = fixture_user(&db, "student").await; | |
| 943 | 947 | let classes = [ |
| 944 | 948 | a_class("9-A", &db).await, |
| 945 | 949 | a_class("9-B", &db).await, |
| @@ -951,37 +955,24 @@ mod tests { | ||
| 951 | 955 | .unwrap(); |
| 952 | 956 | } |
| 953 | 957 | |
| 954 | - let gone = detach( | |
| 955 | - &db, | |
| 956 | - &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"), | |
| 957 | - Axis::Member, | |
| 958 | - &[("usr".into(), student.record().into_value())], | |
| 959 | - ) | |
| 960 | - .await | |
| 961 | - .unwrap(); | |
| 962 | - assert_eq!( | |
| 963 | - gone, 3, | |
| 964 | - "every link row must be counted, not just the first" | |
| 965 | - ); | |
| 958 | + for class in &classes { | |
| 959 | + class_member::remove(&db, class, &student).await.unwrap(); | |
| 960 | + } | |
| 966 | 961 | for class in &classes { |
| 967 | 962 | assert_eq!( |
| 968 | - counter(CLASS_MEMBER_COUNT_FIELD, class.record(), &db).await, | |
| 963 | + counter("class_member_count", class.uuid(), &db).await, | |
| 969 | 964 | 0, |
| 970 | 965 | "each class gets its own counter back" |
| 971 | 966 | ); |
| 972 | 967 | } |
| 973 | 968 | |
| 974 | - // And a run that unlinks nothing answers zero, which is what turns a | |
| 975 | - // single-pair detach into a 404 instead of a silent success. | |
| 976 | - let again = detach( | |
| 977 | - &db, | |
| 978 | - &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"), | |
| 979 | - Axis::Member, | |
| 980 | - &[("usr".into(), student.record().into_value())], | |
| 981 | - ) | |
| 982 | - .await | |
| 983 | - .unwrap(); | |
| 984 | - assert_eq!(again, 0); | |
| 969 | + // And unlinking nobody is a 404, not a silent success — the shape a | |
| 970 | + // single-pair detach answers with. | |
| 971 | + let again = class_member::remove(&db, &classes[0], &student).await; | |
| 972 | + assert!( | |
| 973 | + matches!(again, Err(AppError::NotFound)), | |
| 974 | + "a second removal is a 404, not a silent no-op: {again:?}" | |
| 975 | + ); | |
| 985 | 976 | } |
| 986 | 977 | |
| 987 | 978 | /// The heir a sweep hands a shared enrollment to must still hold *both* |
| @@ -1004,19 +995,19 @@ mod tests { | ||
| 1004 | 995 | /// not have — it commits both sides and answers `Ok` to each, so this passes |
| 1005 | 996 | /// there on broken code. |
| 1006 | 997 | /// |
| 1007 | - /// The window is opened by the schema rather than by a lucky interleaving: a | |
| 1008 | - /// `DEFINE EVENT` on `class_course` scoped to the *owner's* link holds that | |
| 1009 | - /// detach open at its first statement, so the heir's two calls land inside | |
| 1010 | - /// its transaction every time — and the heir's own detach, on another class, | |
| 1011 | - /// is not slowed by it. | |
| 998 | + /// The window the old engine needed a schema event to open is the row | |
| 999 | + /// lock now: the owner's sweep claims the heir's class row before it | |
| 1000 | + /// chooses the heir, so the heir's own member/course writes either land | |
| 1001 | + /// wholly before the sweep reads them or wait behind it — and the | |
| 1002 | + /// invariant below must hold in both orders. A barrier start lets every | |
| 1003 | + /// interleaving happen instead of pinning one. | |
| 1012 | 1004 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 1013 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | |
| 1014 | 1005 | async fn a_detached_row_is_never_handed_to_a_class_that_let_it_go() { |
| 1015 | - use crate::db::class_member::tests::{a_course, source_of}; | |
| 1006 | + use crate::db::class_member::tests::{a_course, fixture_user, source_of}; | |
| 1016 | 1007 | |
| 1017 | - let (db, _serialized) = crate::database::init_test_server("class_heir_race").await; | |
| 1018 | - let manager = UserId::from_key("manager"); | |
| 1019 | - let student = UserId::from_key("student"); | |
| 1008 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 1009 | + let manager = fixture_user(&db, "manager").await; | |
| 1010 | + let student = fixture_user(&db, "student").await; | |
| 1020 | 1011 | let (mut raced, mut stranded) = (0, 0); |
| 1021 | 1012 | for round in 0..4 { |
| 1022 | 1013 | let algebra = a_course(&format!("algebra{round}"), None, &db).await; |
| @@ -1035,31 +1026,29 @@ mod tests { | ||
| 1035 | 1026 | Some(Some(owner.clone())), |
| 1036 | 1027 | "round {round}: the row must start out owned by the first class" |
| 1037 | 1028 | ); |
| 1038 | - db.query(format!( | |
| 1039 | - "DEFINE EVENT OVERWRITE hold_the_sweep ON TABLE {CLASS_COURSE_TABLE} \ | |
| 1040 | - WHEN $event = 'DELETE' THEN {{ IF $before.class = \ | |
| 1041 | - type::record('class_group', '{}') {{ SLEEP 2s }} }};", | |
| 1042 | - owner.key() | |
| 1043 | - )) | |
| 1044 | - .await | |
| 1045 | - .unwrap() | |
| 1046 | - .check() | |
| 1047 | - .unwrap(); | |
| 1048 | 1029 | |
| 1030 | + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | |
| 1049 | 1031 | let detaching = { |
| 1050 | - let (db, owner, algebra) = (db.clone(), owner.clone(), algebra.clone()); | |
| 1051 | - tokio::spawn(async move { class_course::detach(&db, &owner, &algebra).await }) | |
| 1032 | + let (db, owner, algebra, gate) = | |
| 1033 | + (db.clone(), owner.clone(), algebra.clone(), gate.clone()); | |
| 1034 | + tokio::spawn(async move { | |
| 1035 | + gate.wait().await; | |
| 1036 | + class_course::detach(&db, &owner, &algebra).await | |
| 1037 | + }) | |
| 1038 | + }; | |
| 1039 | + // The heir lets the row go, twice over, while the sweep is racing | |
| 1040 | + // it for the same enrollment row. | |
| 1041 | + let heir_moves = { | |
| 1042 | + let (db, heir, algebra, gate) = | |
| 1043 | + (db.clone(), heir.clone(), algebra.clone(), gate); | |
| 1044 | + tokio::spawn(async move { | |
| 1045 | + gate.wait().await; | |
| 1046 | + class_member::remove(&db, &heir, &student).await?; | |
| 1047 | + class_course::detach(&db, &heir, &algebra).await | |
| 1048 | + }) | |
| 1052 | 1049 | }; |
| 1053 | - tokio::time::sleep(std::time::Duration::from_millis(500)).await; | |
| 1054 | - assert!( | |
| 1055 | - !detaching.is_finished(), | |
| 1056 | - "round {round}: the sweep was over before the heir moved" | |
| 1057 | - ); | |
| 1058 | - // The heir lets the row go, twice over, while that sweep is still | |
| 1059 | - // choosing it. | |
| 1060 | - class_member::remove(&db, &heir, &student).await.unwrap(); | |
| 1061 | - class_course::detach(&db, &heir, &algebra).await.unwrap(); | |
| 1062 | 1050 | let swept = detaching.await.unwrap(); |
| 1051 | + heir_moves.await.unwrap().unwrap(); | |
| 1063 | 1052 | assert!( |
| 1064 | 1053 | !matches!(swept, Err(AppError::Db(_))), |
| 1065 | 1054 | "round {round}: a raced detach must be answered, not 500: {swept:?}" |
| @@ -1081,25 +1070,4 @@ mod tests { | ||
| 1081 | 1070 | ); |
| 1082 | 1071 | } |
| 1083 | 1072 | |
| 1084 | - #[test] | |
| 1085 | - fn a_full_abort_names_its_course() { | |
| 1086 | - assert_eq!( | |
| 1087 | - named_course("An error occurred: class_full:course:01J8XZ0K3Q", FULL_MARK), | |
| 1088 | - Some("course:01J8XZ0K3Q".to_string()) | |
| 1089 | - ); | |
| 1090 | - assert_eq!( | |
| 1091 | - named_course("class_full:course:algebra'", FULL_MARK), | |
| 1092 | - Some("course:algebra".into()) | |
| 1093 | - ); | |
| 1094 | - assert_eq!(named_course("class_held", FULL_MARK), None); | |
| 1095 | - assert_eq!(named_course("class_full:", FULL_MARK), None); | |
| 1096 | - // And the stale-link abort reads off the same shape, without the two | |
| 1097 | - // markers ever matching each other's text. | |
| 1098 | - assert_eq!( | |
| 1099 | - named_course("class_no_course:course:algebra'", MISSING_MARK), | |
| 1100 | - Some("course:algebra".into()) | |
| 1101 | - ); | |
| 1102 | - assert_eq!(named_course("class_no_course:course:a", FULL_MARK), None); | |
| 1103 | - assert_eq!(named_course("class_full:course:a", MISSING_MARK), None); | |
| 1104 | - } | |
| 1105 | 1073 | } |
src/db/course.rsmodified+101 -63
| @@ -573,9 +573,21 @@ pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> { | ||
| 573 | 573 | /// way a minted subject id already is for an exam question. |
| 574 | 574 | #[cfg(test)] |
| 575 | 575 | pub(crate) async fn a_test_course(db: &Database) -> CourseId { |
| 576 | + // The creator is a foreign key now: a real row, minted per call so | |
| 577 | + // repeated calls are new people, not the same one. | |
| 578 | + let creator = UserId::generate(); | |
| 579 | + sqlx::query( | |
| 580 | + "INSERT INTO app_user (id, username, password_hash, role) \ | |
| 581 | + VALUES ($1, $2, 'x', 'teacher')", | |
| 582 | + ) | |
| 583 | + .bind(creator.uuid()) | |
| 584 | + .bind(format!("course-fixture-{}", &creator.key()[..8])) | |
| 585 | + .execute(db) | |
| 586 | + .await | |
| 587 | + .unwrap(); | |
| 576 | 588 | create( |
| 577 | 589 | db, |
| 578 | - &UserId::generate(), | |
| 590 | + &creator, | |
| 579 | 591 | CourseTitle::try_new("test course").unwrap(), |
| 580 | 592 | CourseDescription::try_new("").unwrap(), |
| 581 | 593 | CourseKind::course(), |
| @@ -615,28 +627,26 @@ pub(crate) async fn a_test_course(db: &Database) -> CourseId { | ||
| 615 | 627 | /// on broken code. |
| 616 | 628 | #[cfg(test)] |
| 617 | 629 | pub(crate) async fn assert_no_child_outlives_a_course_delete( |
| 618 | - scratch: &str, | |
| 619 | 630 | table: &str, |
| 620 | 631 | make: fn(CourseId, Database) -> tokio::task::JoinHandle<Result<(), AppError>>, |
| 621 | 632 | ) { |
| 622 | - // The guard is held for the whole test: these bursts are sub-millisecond, | |
| 623 | - // and a sibling race test's burst pushes a delete clean out of its window. | |
| 624 | - let (db, _serialized) = crate::database::init_test_server(scratch).await; | |
| 625 | - db.query( | |
| 626 | - "DEFINE EVENT hold_the_window ON TABLE course WHEN $event = 'DELETE' \ | |
| 627 | - THEN { SLEEP 1s; };", | |
| 628 | - ) | |
| 629 | - .await | |
| 630 | - .expect("define the window event") | |
| 631 | - .check() | |
| 632 | - .expect("check the window event"); | |
| 633 | + use sqlx::Row as _; | |
| 634 | + | |
| 635 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 633 | 636 | |
| 634 | 637 | let (mut swept, mut orphans) = (0, 0); |
| 635 | - for round in 0..4 { | |
| 638 | + for round in 0..8 { | |
| 636 | 639 | let course = a_test_course(&db).await; |
| 640 | + // The old engine needed a schema event to hold the delete's window | |
| 641 | + // open; Postgres puts the racing create and delete on the same rows | |
| 642 | + // (the FK claims and the cascade), so a barrier start covers every | |
| 643 | + // interleaving — and the child may never outlive the course in any | |
| 644 | + // of them. | |
| 645 | + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | |
| 637 | 646 | let drop_it = { |
| 638 | - let (course, db) = (course.clone(), db.clone()); | |
| 647 | + let (course, db, gate) = (course.clone(), db.clone(), gate.clone()); | |
| 639 | 648 | tokio::spawn(async move { |
| 649 | + gate.wait().await; | |
| 640 | 650 | delete( |
| 641 | 651 | &db, |
| 642 | 652 | read(&db, &course) |
| @@ -647,9 +657,17 @@ pub(crate) async fn assert_no_child_outlives_a_course_delete( | ||
| 647 | 657 | .await |
| 648 | 658 | }) |
| 649 | 659 | }; |
| 650 | - // The create starts inside the held window. | |
| 651 | - tokio::time::sleep(std::time::Duration::from_millis(300)).await; | |
| 652 | - let child = make(course.clone(), db.clone()).await.unwrap(); | |
| 660 | + let child = { | |
| 661 | + let (course, db, gate) = (course.clone(), db.clone(), gate); | |
| 662 | + tokio::spawn(async move { | |
| 663 | + gate.wait().await; | |
| 664 | + // The inner task joins here: a `Db` answer stays `Err`, only a | |
| 665 | + // panic inside `make` (or the outer join) would panic. | |
| 666 | + make(course, db).await.unwrap() | |
| 667 | + }) | |
| 668 | + } | |
| 669 | + .await | |
| 670 | + .unwrap(); | |
| 653 | 671 | let dropped = drop_it.await.unwrap(); |
| 654 | 672 | |
| 655 | 673 | // A 404 for the create, or a refusal for the delete, is a correct |
| @@ -666,24 +684,23 @@ pub(crate) async fn assert_no_child_outlives_a_course_delete( | ||
| 666 | 684 | // Stored state is the whole verdict; a return value is not evidence. |
| 667 | 685 | if read(&db, &course).await.unwrap().is_none() { |
| 668 | 686 | swept += 1; |
| 669 | - let mut left = db | |
| 670 | - .query(format!( | |
| 671 | - "SELECT VALUE id FROM {table} WHERE course = $course" | |
| 672 | - )) | |
| 673 | - .bind(("course", course.record())) | |
| 674 | - .await | |
| 675 | - .unwrap() | |
| 676 | - .check() | |
| 677 | - .unwrap(); | |
| 678 | - orphans += left.take::<Vec<RecordId>>(0).unwrap().len(); | |
| 687 | + orphans += sqlx::query(sqlx::AssertSqlSafe(format!( | |
| 688 | + "SELECT count(*) FROM {table} WHERE course = $1" | |
| 689 | + ))) | |
| 690 | + .bind(course.uuid()) | |
| 691 | + .fetch_one(&db) | |
| 692 | + .await | |
| 693 | + .unwrap() | |
| 694 | + .try_get::<i64, _>(0) | |
| 695 | + .unwrap() as usize; | |
| 679 | 696 | } else if matches!(dropped, Ok(true)) { |
| 680 | 697 | panic!("{table} round {round}: the delete reported success, the course is still there"); |
| 681 | 698 | } |
| 682 | 699 | } |
| 683 | - eprintln!("Course::delete raced by a {table} create: {swept}/4 rounds deleted the course"); | |
| 700 | + eprintln!("Course::delete raced by a {table} create: {swept}/8 rounds deleted the course"); | |
| 684 | 701 | assert!( |
| 685 | 702 | swept > 0, |
| 686 | - "{table}: no round ever deleted the course, so the window was never reached" | |
| 703 | + "{table}: no round ever deleted the course, so the race never actually ran" | |
| 687 | 704 | ); |
| 688 | 705 | assert_eq!(orphans, 0, "{table}: a child outlived its course"); |
| 689 | 706 | } |
| @@ -691,12 +708,31 @@ pub(crate) async fn assert_no_child_outlives_a_course_delete( | ||
| 691 | 708 | #[cfg(test)] |
| 692 | 709 | mod tests { |
| 693 | 710 | use super::*; |
| 711 | + use sqlx::Row as _; | |
| 694 | 712 | use crate::domain::term::{Term, TermName}; |
| 695 | 713 | |
| 714 | + /// A real `app_user` row: creators, students and enrollers are foreign | |
| 715 | + /// keys now. The label names the row's username; the id is minted, so | |
| 716 | + /// repeated calls are new people, not the same row. | |
| 717 | + async fn a_person(db: &Database, label: &str, role: &str) -> UserId { | |
| 718 | + let user = UserId::generate(); | |
| 719 | + sqlx::query( | |
| 720 | + "INSERT INTO app_user (id, username, password_hash, role) \ | |
| 721 | + VALUES ($1, $2, 'x', $3)", | |
| 722 | + ) | |
| 723 | + .bind(user.uuid()) | |
| 724 | + .bind(format!("{label}-{}", &user.key()[..8])) | |
| 725 | + .bind(role) | |
| 726 | + .execute(db) | |
| 727 | + .await | |
| 728 | + .unwrap(); | |
| 729 | + user | |
| 730 | + } | |
| 731 | + | |
| 696 | 732 | async fn course_on(term: Option<TermId>, db: &Database) -> Course { |
| 697 | 733 | create( |
| 698 | 734 | db, |
| 699 | - &UserId::from_key("teacher"), | |
| 735 | + &a_person(db, "teacher", "teacher").await, | |
| 700 | 736 | CourseTitle::try_new("algebra").unwrap(), |
| 701 | 737 | CourseDescription::try_new("").unwrap(), |
| 702 | 738 | CourseKind::course(), |
| @@ -713,9 +749,9 @@ mod tests { | ||
| 713 | 749 | /// included. A `>= 0` guard passes the roster branch and fails here. |
| 714 | 750 | #[tokio::test] |
| 715 | 751 | async fn a_course_with_a_roster_refuses_to_delete() { |
| 716 | - let db = crate::database::init_mem().await.unwrap(); | |
| 717 | - let teacher = UserId::from_key("teacher"); | |
| 718 | - let student = UserId::from_key("student"); | |
| 752 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 753 | + let teacher = a_person(&db, "teacher", "teacher").await; | |
| 754 | + let student = a_person(&db, "student", "student").await; | |
| 719 | 755 | let course = course_on(None, &db).await; |
| 720 | 756 | crate::db::enrollment::enroll(&db, course.get_id(), &student, &teacher) |
| 721 | 757 | .await |
| @@ -758,7 +794,7 @@ mod tests { | ||
| 758 | 794 | /// back. Dropping the release in `delete` leaves the term deletable never. |
| 759 | 795 | #[tokio::test] |
| 760 | 796 | async fn a_term_is_deletable_only_once_no_course_links_it() { |
| 761 | - let db = crate::database::init_mem().await.unwrap(); | |
| 797 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 762 | 798 | let at = crate::domain::timestamp::Timestamp::from_millis; |
| 763 | 799 | let term = |
| 764 | 800 | crate::db::term::create(&db, TermName::try_new("2026").unwrap(), at(100), at(200)) |
| @@ -797,10 +833,10 @@ mod tests { | ||
| 797 | 833 | /// web layer's pre-flight lookup gives. |
| 798 | 834 | #[tokio::test] |
| 799 | 835 | async fn a_course_cannot_link_a_term_that_is_gone() { |
| 800 | - let db = crate::database::init_mem().await.unwrap(); | |
| 836 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 801 | 837 | let error = create( |
| 802 | 838 | &db, |
| 803 | - &UserId::from_key("teacher"), | |
| 839 | + &a_person(&db, "teacher", "teacher").await, | |
| 804 | 840 | CourseTitle::try_new("algebra").unwrap(), |
| 805 | 841 | CourseDescription::try_new("").unwrap(), |
| 806 | 842 | CourseKind::course(), |
| @@ -814,27 +850,23 @@ mod tests { | ||
| 814 | 850 | |
| 815 | 851 | /// The stored `course_count` on one term, absent counting as zero. |
| 816 | 852 | async fn count_on(term: &TermId, db: &Database) -> i64 { |
| 817 | - let mut result = db | |
| 818 | - .query(format!( | |
| 819 | - "SELECT VALUE ({COURSE_COUNT_FIELD} ?? 0) FROM $term" | |
| 820 | - )) | |
| 821 | - .bind(("term", term.record())) | |
| 853 | + sqlx::query("SELECT COALESCE(course_count, 0) FROM term WHERE id = $1") | |
| 854 | + .bind(term.uuid()) | |
| 855 | + .fetch_one(db) | |
| 822 | 856 | .await |
| 823 | 857 | .unwrap() |
| 824 | - .check() | |
| 825 | - .unwrap(); | |
| 826 | - result | |
| 827 | - .take::<Vec<i64>>(0) | |
| 858 | + .try_get::<i64, _>(0) | |
| 828 | 859 | .unwrap() |
| 829 | - .first() | |
| 830 | - .copied() | |
| 831 | - .unwrap_or(0) | |
| 832 | 860 | } |
| 833 | 861 | |
| 834 | 862 | /// How many rows `sql` selects ids for. |
| 835 | 863 | async fn rows(sql: &str, db: &Database) -> usize { |
| 836 | - let mut result = db.query(sql).await.unwrap().check().unwrap(); | |
| 837 | - result.take::<Vec<RecordId>>(0).unwrap().len() | |
| 864 | + sqlx::query(sqlx::AssertSqlSafe(sql.to_string())) | |
| 865 | + .fetch_one(db) | |
| 866 | + .await | |
| 867 | + .unwrap() | |
| 868 | + .try_get::<i64, _>(0) | |
| 869 | + .unwrap() as usize | |
| 838 | 870 | } |
| 839 | 871 | |
| 840 | 872 | async fn a_term(name: &str, db: &Database) -> Term { |
| @@ -851,14 +883,14 @@ mod tests { | ||
| 851 | 883 | /// stray one makes the term undeletable forever). |
| 852 | 884 | #[tokio::test] |
| 853 | 885 | async fn a_refused_create_writes_neither_row_nor_count() { |
| 854 | - let db = crate::database::init_mem().await.unwrap(); | |
| 886 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 855 | 887 | let term = a_term("2026", &db).await; |
| 856 | 888 | let id = term.get_id().clone(); |
| 857 | 889 | assert!(crate::db::term::delete(&db, term).await.unwrap()); |
| 858 | 890 | |
| 859 | 891 | let error = create( |
| 860 | 892 | &db, |
| 861 | - &UserId::from_key("teacher"), | |
| 893 | + &a_person(&db, "teacher", "teacher").await, | |
| 862 | 894 | CourseTitle::try_new("algebra").unwrap(), |
| 863 | 895 | CourseDescription::try_new("").unwrap(), |
| 864 | 896 | CourseKind::course(), |
| @@ -884,7 +916,7 @@ mod tests { | ||
| 884 | 916 | /// term's claim and the old term's release with the link itself. |
| 885 | 917 | #[tokio::test] |
| 886 | 918 | async fn a_term_move_moves_the_count() { |
| 887 | - let db = crate::database::init_mem().await.unwrap(); | |
| 919 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 888 | 920 | let from = a_term("2026", &db).await; |
| 889 | 921 | let to = a_term("2027", &db).await; |
| 890 | 922 | let course = course_on(Some(from.get_id().clone()), &db).await; |
| @@ -921,7 +953,7 @@ mod tests { | ||
| 921 | 953 | /// counts must read as if it never ran. |
| 922 | 954 | #[tokio::test] |
| 923 | 955 | async fn a_stale_mover_is_refused_and_claims_nothing() { |
| 924 | - let db = crate::database::init_mem().await.unwrap(); | |
| 956 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 925 | 957 | let from = a_term("2026", &db).await; |
| 926 | 958 | let to = a_term("2027", &db).await; |
| 927 | 959 | let other = a_term("2028", &db).await; |
| @@ -1012,7 +1044,7 @@ mod tests { | ||
| 1012 | 1044 | /// *carrying* the column instead, which is why this is refused. |
| 1013 | 1045 | #[tokio::test] |
| 1014 | 1046 | async fn a_stale_re_stater_is_refused_and_reverts_nothing() { |
| 1015 | - let db = crate::database::init_mem().await.unwrap(); | |
| 1047 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 1016 | 1048 | let from = a_term("2026", &db).await; |
| 1017 | 1049 | let to = a_term("2027", &db).await; |
| 1018 | 1050 | let course = course_on(Some(from.get_id().clone()), &db).await; |
| @@ -1083,7 +1115,7 @@ mod tests { | ||
| 1083 | 1115 | /// The title moves in the same PATCH, and must not stick either. |
| 1084 | 1116 | #[tokio::test] |
| 1085 | 1117 | async fn a_term_move_to_a_dead_term_leaves_everything_untouched() { |
| 1086 | - let db = crate::database::init_mem().await.unwrap(); | |
| 1118 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 1087 | 1119 | let from = a_term("2026", &db).await; |
| 1088 | 1120 | let dead = a_term("2027", &db).await; |
| 1089 | 1121 | let dead_id = dead.get_id().clone(); |
| @@ -1148,9 +1180,16 @@ mod tests { | ||
| 1148 | 1180 | /// current-thread runtime never interleaves the two, and the embedded |
| 1149 | 1181 | /// engine does not conflict-check concurrent writes to one record at all. |
| 1150 | 1182 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 1151 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | |
| 1152 | 1183 | async fn a_delete_racing_an_enroll_never_answers_500() { |
| 1153 | - let (db, _serialized) = crate::database::init_test_server("course_delete_race").await; | |
| 1184 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 1185 | + // The roster rows are foreign keys now: the burst's six racers and | |
| 1186 | + // their enroller are real people, reused every round (each round's | |
| 1187 | + // delete cascade frees the seats back). | |
| 1188 | + let mgr = a_person(&db, "mgr", "manager").await; | |
| 1189 | + let mut students = Vec::new(); | |
| 1190 | + for seat in 0..6 { | |
| 1191 | + students.push(a_person(&db, &format!("stu{seat}"), "student").await); | |
| 1192 | + } | |
| 1154 | 1193 | let (mut delete_500, mut enroll_500, mut enrolled) = (0, 0, 0); |
| 1155 | 1194 | let (mut last_delete, mut last_enroll) = (String::new(), String::new()); |
| 1156 | 1195 | for round in 0..20 { |
| @@ -1172,11 +1211,10 @@ mod tests { | ||
| 1172 | 1211 | }; |
| 1173 | 1212 | let joins: Vec<_> = (0..6) |
| 1174 | 1213 | .map(|seat| { |
| 1175 | - let (id, db) = (course.get_id().clone(), db.clone()); | |
| 1176 | - let student = UserId::from_key(&format!("stu{round}_{seat}")); | |
| 1214 | + let (id, db, mgr) = (course.get_id().clone(), db.clone(), mgr.clone()); | |
| 1215 | + let student = students[seat].clone(); | |
| 1177 | 1216 | tokio::spawn(async move { |
| 1178 | - crate::db::enrollment::enroll(&db, &id, &student, &UserId::from_key("mgr")) | |
| 1179 | - .await | |
| 1217 | + crate::db::enrollment::enroll(&db, &id, &student, &mgr).await | |
| 1180 | 1218 | }) |
| 1181 | 1219 | }) |
| 1182 | 1220 | .collect(); |
src/db/course_note.rsmodified+1 -1
| @@ -157,7 +157,7 @@ mod tests { | ||
| 157 | 157 | /// been taken, which is the row whose blob used to leak. |
| 158 | 158 | #[tokio::test] |
| 159 | 159 | async fn delete_returns_the_attachment_rows_it_removed() { |
| 160 | - let db = crate::database::init_mem().await.unwrap(); | |
| 160 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 161 | 161 | let creator = crate::domain::user::UserId::generate(); |
| 162 | 162 | let course = crate::db::course::create( |
| 163 | 163 | &db, |
src/db/course_note_file.rsmodified+2 -2
| @@ -192,7 +192,7 @@ mod tests { | ||
| 192 | 192 | /// the count stays at the accepted rows. |
| 193 | 193 | #[tokio::test] |
| 194 | 194 | async fn insert_refuses_at_the_cap() { |
| 195 | - let db = crate::database::init_mem().await.unwrap(); | |
| 195 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 196 | 196 | let note = note_of(&db, "n").await; |
| 197 | 197 | for index in 0..MAX_COURSE_NOTE_FILES { |
| 198 | 198 | let file = CourseNoteFile::new( |
| @@ -221,7 +221,7 @@ mod tests { | ||
| 221 | 221 | /// delete hands its slot back to the note. |
| 222 | 222 | #[tokio::test] |
| 223 | 223 | async fn file_keys_and_delete_slot_release() { |
| 224 | - let db = crate::database::init_mem().await.unwrap(); | |
| 224 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 225 | 225 | let note = note_of(&db, "n").await; |
| 226 | 226 | let course = note.get_course().clone(); |
| 227 | 227 | let file = CourseNoteFile::new( |
src/db/course_session.rsmodified+13 -8
| @@ -171,14 +171,24 @@ mod tests { | ||
| 171 | 171 | /// Mutation-tested: with the bare `db.create` this shipped with, all four |
| 172 | 172 | /// rounds orphan. |
| 173 | 173 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 174 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | |
| 175 | 174 | async fn a_session_never_outlives_its_course() { |
| 176 | 175 | fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> { |
| 177 | 176 | tokio::spawn(async move { |
| 177 | + // The creator is a foreign key now: a real `app_user` row. | |
| 178 | + let creator = UserId::generate(); | |
| 179 | + sqlx::query( | |
| 180 | + "INSERT INTO app_user (id, username, password_hash, role) \ | |
| 181 | + VALUES ($1, $2, 'x', 'teacher')", | |
| 182 | + ) | |
| 183 | + .bind(creator.uuid()) | |
| 184 | + .bind(format!("session-race-{}", &creator.key()[..8])) | |
| 185 | + .execute(&db) | |
| 186 | + .await | |
| 187 | + .unwrap(); | |
| 178 | 188 | create( |
| 179 | 189 | &db, |
| 180 | 190 | &course, |
| 181 | - &UserId::generate(), | |
| 191 | + &creator, | |
| 182 | 192 | SessionTopic::try_new("limits").unwrap(), |
| 183 | 193 | Timestamp::from_millis(1), |
| 184 | 194 | None, |
| @@ -187,11 +197,6 @@ mod tests { | ||
| 187 | 197 | .map(|_| ()) |
| 188 | 198 | }) |
| 189 | 199 | } |
| 190 | - crate::db::course::assert_no_child_outlives_a_course_delete( | |
| 191 | - "session_orphan_race", | |
| 192 | - COURSE_SESSION_TABLE, | |
| 193 | - make, | |
| 194 | - ) | |
| 195 | - .await; | |
| 200 | + crate::db::course::assert_no_child_outlives_a_course_delete("session", make).await; | |
| 196 | 201 | } |
| 197 | 202 | } |
src/db/enrollment.rsmodified+4 -57
| @@ -251,59 +251,6 @@ pub async fn remove( | ||
| 251 | 251 | mod tests { |
| 252 | 252 | use super::*; |
| 253 | 253 | |
| 254 | - /// The boot repair of `enrollment_count` **against a real server**, and | |
| 255 | - /// `#[ignore]`d for it: the pass counts rows off `enrollment`'s indexed | |
| 256 | - /// `course` field, and an aggregate over an indexed field is exactly where | |
| 257 | - /// the embedded engine and the server are known to differ (`count()` comes | |
| 258 | - /// back `{count: N}` from one and a bare int from the other, which | |
| 259 | - /// `option<int>` would refuse). `array::len` over ids is the spelling that | |
| 260 | - /// dodges it — this is what proves it on the store that bites. | |
| 261 | - /// | |
| 262 | - /// Both halves in one boot: `staff` is the row the sweep deletes (their | |
| 263 | - /// seat must come back), and `empty` is the course a *past* sweep already | |
| 264 | - /// stranded — count above zero with no rows left, so it forms no group and | |
| 265 | - /// only a per-course pass ever visits it. The second `migrate` pins that the | |
| 266 | - /// repair converges rather than overwriting: it must write nothing. | |
| 267 | - #[tokio::test] | |
| 268 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | |
| 269 | - async fn the_count_repair_recounts_on_a_real_server() { | |
| 270 | - let (db, _serialized) = crate::database::init_test_server("enrollment_repair").await; | |
| 271 | - db.query( | |
| 272 | - "CREATE user:t SET username = 't', password_hash = 'x', role = 'teacher'; | |
| 273 | - CREATE user:a SET username = 'a', password_hash = 'x', role = 'student'; | |
| 274 | - CREATE user:b SET username = 'b', password_hash = 'x', role = 'student'; | |
| 275 | - CREATE course:live SET creator = user:t, title = 'l', description = '', | |
| 276 | - enrollment_count = 9; | |
| 277 | - CREATE course:empty SET creator = user:t, title = 'e', description = '', | |
| 278 | - enrollment_count = 4; | |
| 279 | - CREATE enrollment:live_a SET course = course:live, user = user:a, enrolled_by = user:t; | |
| 280 | - CREATE enrollment:live_b SET course = course:live, user = user:b, enrolled_by = user:t; | |
| 281 | - CREATE enrollment:live_t SET course = course:live, user = user:t, enrolled_by = user:t;", | |
| 282 | - ) | |
| 283 | - .await | |
| 284 | - .unwrap() | |
| 285 | - .check() | |
| 286 | - .unwrap(); | |
| 287 | - | |
| 288 | - async fn counts(db: &Database) -> Vec<i64> { | |
| 289 | - let mut result = db | |
| 290 | - .query("SELECT VALUE enrollment_count FROM course ORDER BY id") | |
| 291 | - .await | |
| 292 | - .unwrap() | |
| 293 | - .check() | |
| 294 | - .unwrap(); | |
| 295 | - result.take::<Vec<i64>>(0).unwrap() | |
| 296 | - } | |
| 297 | - | |
| 298 | - crate::database::migrate(db.as_ref()).await.unwrap(); | |
| 299 | - // `course:empty` sorts before `course:live`: stranded count cleared, and | |
| 300 | - // the live course recounted to its two students — the teacher's row was | |
| 301 | - // swept and handed its seat back in the same boot. | |
| 302 | - assert_eq!(counts(&db).await, vec![0, 2]); | |
| 303 | - | |
| 304 | - crate::database::migrate(db.as_ref()).await.unwrap(); | |
| 305 | - assert_eq!(counts(&db).await, vec![0, 2], "the repair converges"); | |
| 306 | - } | |
| 307 | 254 | |
| 308 | 255 | /// A pumped row that vanishes under the disown — a concurrent unenroll, or |
| 309 | 256 | /// the sweep a role change runs — must answer the row the caller was |
| @@ -312,10 +259,10 @@ mod tests { | ||
| 312 | 259 | /// server error on an ordinary `POST /courses/{id}/enrollments`. |
| 313 | 260 | #[tokio::test] |
| 314 | 261 | async fn a_vanished_row_is_not_an_internal_error() { |
| 315 | - let db = crate::database::init_mem().await.unwrap(); | |
| 262 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 316 | 263 | let class = crate::domain::class_group::ClassGroupId::from_key("9a"); |
| 317 | - let course = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"); | |
| 318 | - let student = UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8U"); | |
| 264 | + let course = CourseId::from_key("019732e3-7b00-7000-8000-00000000dead"); | |
| 265 | + let student = UserId::from_key("019732e3-7b00-7000-8000-00000000deae"); | |
| 319 | 266 | // Never written: the same store state a delete in the window leaves. |
| 320 | 267 | let ghost = Enrollment { |
| 321 | 268 | id: EnrollmentId::composite(&course, &student), |
| @@ -337,7 +284,7 @@ mod tests { | ||
| 337 | 284 | async fn a_hand_placed_enrollment_stores_no_source_key() { |
| 338 | 285 | use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; |
| 339 | 286 | |
| 340 | - let db = crate::database::init_mem().await.unwrap(); | |
| 287 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 341 | 288 | let teacher = UserId::from_key("teacher"); |
| 342 | 289 | let course = crate::db::course::create( |
| 343 | 290 | &db, |
src/db/event.rsmodified+63 -28
| @@ -291,31 +291,61 @@ pub async fn delete(db: &Database, event: Event) -> Result<Event, AppError> { | ||
| 291 | 291 | #[cfg(test)] |
| 292 | 292 | mod tests { |
| 293 | 293 | use super::*; |
| 294 | - use crate::constant::REGISTRATION_FROZEN_GUARD; | |
| 295 | - use crate::domain::class_group::ClassGroupId; | |
| 294 | + | |
| 295 | + /// A real `app_user` row: the creator is a foreign key now. | |
| 296 | + async fn a_person(db: &Database, label: &str) -> UserId { | |
| 297 | + let user = UserId::generate(); | |
| 298 | + sqlx::query( | |
| 299 | + "INSERT INTO app_user (id, username, password_hash, role) \ | |
| 300 | + VALUES ($1, $2, 'x', 'teacher')", | |
| 301 | + ) | |
| 302 | + .bind(user.uuid()) | |
| 303 | + .bind(format!("{label}-{}", &user.key()[..8])) | |
| 304 | + .execute(db) | |
| 305 | + .await | |
| 306 | + .unwrap(); | |
| 307 | + user | |
| 308 | + } | |
| 296 | 309 | |
| 297 | 310 | /// The forcing function behind the one rule with two spellings: the freeze |
| 298 | - /// this file decides in Rust ([`Event::registration_capacity`]) and | |
| 299 | - /// [`REGISTRATION_FROZEN_GUARD`], its SurrealQL copy, which | |
| 300 | - /// the role cascade (`service::user::set_role`) carries because it frees a demoted | |
| 301 | - /// parent's seats inside a transaction and cannot call Rust from there. | |
| 311 | + /// this file decides in Rust ([`Event::registration_capacity`]) and the | |
| 312 | + /// demotion sweep's SQL predicate, which `service::user::set_role` carries | |
| 313 | + /// because it frees a demoted parent's seats inside a transaction and | |
| 314 | + /// cannot call Rust from there. The predicate is copied here test-side on | |
| 315 | + /// purpose: the sweep lives in user.rs, and this test pins the copy. | |
| 302 | 316 | /// |
| 303 | 317 | /// Every schedule shape is put to both, including the three the SQL is most |
| 304 | - /// likely to get wrong: the ends_at-only event (`??` must fall through to | |
| 318 | + /// likely to get wrong: the ends_at-only event (`COALESCE` must fall through to | |
| 305 | 319 | /// it), the boundary itself (closed *at* the instant, not after it — `>=` in |
| 306 | - /// Rust, `<=` in SQL, and the two read opposite ways round; `$now` is bound | |
| 320 | + /// Rust, `<=` in SQL, and the two read opposite ways round; `now` is bound | |
| 307 | 321 | /// to that exact instant so the boundary is really exercised), and an event |
| 308 | 322 | /// that takes no registrations at all, which Rust refuses one arm *earlier* |
| 309 | 323 | /// — so the SQL must not report it frozen, or a stray row on it would be |
| 310 | 324 | /// preserved forever instead of swept. |
| 311 | 325 | #[tokio::test] |
| 312 | 326 | async fn the_sql_freeze_guard_matches_the_rust_one() { |
| 313 | - let db = crate::database::init_mem().await.unwrap(); | |
| 327 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 328 | + let creator = a_person(&db, "event-guard").await; | |
| 329 | + // `audience_class` is a foreign key too: the class case needs a real group. | |
| 330 | + let class = ClassGroupId::generate(); | |
| 331 | + sqlx::query("INSERT INTO class_group (id, name, creator) VALUES ($1, 'g1', $2)") | |
| 332 | + .bind(class.uuid()) | |
| 333 | + .bind(creator.uuid()) | |
| 334 | + .execute(&db) | |
| 335 | + .await | |
| 336 | + .unwrap(); | |
| 337 | + let no_payload = |kind| EventAudience { | |
| 338 | + kind, | |
| 339 | + role: None, | |
| 340 | + course: None, | |
| 341 | + class: None, | |
| 342 | + capacity: None, | |
| 343 | + }; | |
| 314 | 344 | let now = Timestamp::now().as_millis(); |
| 315 | 345 | let past = Some(Timestamp::from_millis(now - 60_000)); |
| 316 | 346 | let future = Some(Timestamp::from_millis(now + 3_600_000)); |
| 317 | 347 | let later = Some(Timestamp::from_millis(now + 7_200_000)); |
| 318 | - let signup = EventAudience::Registration { capacity: None }; | |
| 348 | + let signup = no_payload(EventAudienceKind::Registration); | |
| 319 | 349 | let cases = [ |
| 320 | 350 | ("timeless", signup.clone(), None, None), |
| 321 | 351 | ("deadline ahead", signup.clone(), None, future), |
| @@ -331,11 +361,17 @@ mod tests { | ||
| 331 | 361 | ), |
| 332 | 362 | // No signup list to freeze: `registration_capacity` refuses these on |
| 333 | 363 | // the audience, before it ever looks at the clock. |
| 334 | - ("started school event", EventAudience::School, past, None), | |
| 364 | + ( | |
| 365 | + "started school event", | |
| 366 | + no_payload(EventAudienceKind::School), | |
| 367 | + past, | |
| 368 | + None, | |
| 369 | + ), | |
| 335 | 370 | ( |
| 336 | 371 | "started class event", |
| 337 | - EventAudience::Class { | |
| 338 | - class: ClassGroupId::from_key("g1"), | |
| 372 | + EventAudience { | |
| 373 | + class: Some(class), | |
| 374 | + ..no_payload(EventAudienceKind::Class) | |
| 339 | 375 | }, |
| 340 | 376 | past, |
| 341 | 377 | None, |
| @@ -344,7 +380,7 @@ mod tests { | ||
| 344 | 380 | for (name, audience, starts_at, ends_at) in cases { |
| 345 | 381 | let event = create( |
| 346 | 382 | &db, |
| 347 | - &UserId::from_key("teacher"), | |
| 383 | + &creator, | |
| 348 | 384 | EventTitle::try_new(name).unwrap(), |
| 349 | 385 | EventDescription::try_new("").unwrap(), |
| 350 | 386 | audience, |
| @@ -357,20 +393,19 @@ mod tests { | ||
| 357 | 393 | event.registration_capacity(), |
| 358 | 394 | Err(AppError::Conflict(_) | AppError::ConflictOwned(_)) |
| 359 | 395 | ); |
| 360 | - let mut result = db | |
| 361 | - .query(format!( | |
| 362 | - "SELECT VALUE id FROM $ev WHERE {REGISTRATION_FROZEN_GUARD}" | |
| 363 | - )) | |
| 364 | - .bind(("ev", event.get_id().record())) | |
| 365 | - .bind(("now", now)) | |
| 366 | - .await | |
| 367 | - .unwrap() | |
| 368 | - .check() | |
| 369 | - .unwrap(); | |
| 370 | - let sql = !result | |
| 371 | - .take::<Vec<surrealdb::types::RecordId>>(0) | |
| 372 | - .unwrap() | |
| 373 | - .is_empty(); | |
| 396 | + // Test-side copy of the sweep predicate in `service::user::set_role` | |
| 397 | + // (src/db/user.rs): frozen == the demotion sweep would leave the row. | |
| 398 | + let sql = !sqlx::query_scalar::<_, bool>( | |
| 399 | + "SELECT audience_kind = 'registration' \ | |
| 400 | + AND COALESCE(starts_at, ends_at) IS NOT NULL \ | |
| 401 | + AND COALESCE(starts_at, ends_at) <= $2 \ | |
| 402 | + FROM event WHERE id = $1", | |
| 403 | + ) | |
| 404 | + .bind(event.get_id().uuid()) | |
| 405 | + .bind(now) | |
| 406 | + .fetch_one(&db) | |
| 407 | + .await | |
| 408 | + .unwrap(); | |
| 374 | 409 | assert_eq!( |
| 375 | 410 | sql, rust, |
| 376 | 411 | "the SQL freeze guard and registration_capacity disagree on a \ |
src/db/exam.rsmodified+123 -147
| @@ -483,39 +483,20 @@ pub(crate) async fn published_exam(db: &Database) -> Exam { | ||
| 483 | 483 | let allowed: Vec<ExamKindDef> = crate::domain::settings::Settings::defaults() |
| 484 | 484 | .get_exam_kinds() |
| 485 | 485 | .to_vec(); |
| 486 | - create( | |
| 487 | - db, | |
| 488 | - &UserId::generate(), | |
| 489 | - &crate::db::course::a_test_course(db).await, | |
| 490 | - ExamTitle::try_new("midterm").unwrap(), | |
| 491 | - ExamDescription::try_new("").unwrap(), | |
| 492 | - ExamKind::try_new("midterm", &allowed).unwrap(), | |
| 493 | - ExamSchedule::try_new(None, None, None, None).unwrap(), | |
| 494 | - ExamAttemptLimit::try_new(1).unwrap(), | |
| 495 | - true, | |
| 496 | - false, | |
| 497 | - false, | |
| 486 | + // The creator is a foreign key now: a real `app_user` row, minted per call. | |
| 487 | + let creator = UserId::generate(); | |
| 488 | + sqlx::query( | |
| 489 | + "INSERT INTO app_user (id, username, password_hash, role) \ | |
| 490 | + VALUES ($1, $2, 'x', 'teacher')", | |
| 498 | 491 | ) |
| 492 | + .bind(creator.uuid()) | |
| 493 | + .bind(format!("exam-fixture-{}", &creator.key()[..8])) | |
| 494 | + .execute(db) | |
| 499 | 495 | .await |
| 500 | - .unwrap() | |
| 501 | -} | |
| 502 | - | |
| 503 | -#[cfg(test)] | |
| 504 | -use crate::domain::settings::ExamKindDef; | |
| 505 | - | |
| 506 | -/// An unscheduled published exam — the minimum any test that writes a *child* | |
| 507 | -/// of an exam needs, in any module: every such write moves the exam row (see | |
| 508 | -/// [`crate::db::exam_attempt::write_unfrozen_with`] | |
| 509 | -/// and [`crate::db::exam_answer::save`]), so a minted id whose | |
| 510 | -/// row was never created is a 404 rather than a silent orphan. | |
| 511 | -#[cfg(test)] | |
| 512 | -pub(crate) async fn published_exam(db: &Database) -> Exam { | |
| 513 | - let allowed: Vec<ExamKindDef> = crate::domain::settings::Settings::defaults() | |
| 514 | - .get_exam_kinds() | |
| 515 | - .to_vec(); | |
| 496 | + .unwrap(); | |
| 516 | 497 | create( |
| 517 | 498 | db, |
| 518 | - &UserId::generate(), | |
| 499 | + &creator, | |
| 519 | 500 | &crate::db::course::a_test_course(db).await, |
| 520 | 501 | ExamTitle::try_new("midterm").unwrap(), |
| 521 | 502 | ExamDescription::try_new("").unwrap(), |
| @@ -536,7 +517,6 @@ mod tests { | ||
| 536 | 517 | |
| 537 | 518 | use super::published_exam as published; |
| 538 | 519 | |
| 539 | - use crate::constant::EXAM_TABLE; | |
| 540 | 520 | use crate::domain::exam::{ExamDuration, ExamMode}; |
| 541 | 521 | use crate::domain::settings::ExamKindDef; |
| 542 | 522 | use crate::domain::timestamp::Timestamp; |
| @@ -556,16 +536,25 @@ mod tests { | ||
| 556 | 536 | /// Mutation-tested: with the bare `db.create` this shipped with, all four |
| 557 | 537 | /// rounds orphan. |
| 558 | 538 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 559 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | |
| 560 | 539 | async fn an_exam_never_outlives_its_course() { |
| 561 | 540 | fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> { |
| 562 | 541 | tokio::spawn(async move { |
| 563 | 542 | let kinds = crate::domain::settings::Settings::defaults() |
| 564 | 543 | .get_exam_kinds() |
| 565 | 544 | .to_vec(); |
| 545 | + let creator = UserId::generate(); | |
| 546 | + sqlx::query( | |
| 547 | + "INSERT INTO app_user (id, username, password_hash, role) \ | |
| 548 | + VALUES ($1, $2, 'x', 'teacher')", | |
| 549 | + ) | |
| 550 | + .bind(creator.uuid()) | |
| 551 | + .bind(format!("orphan-race-{}", &creator.key()[..8])) | |
| 552 | + .execute(&db) | |
| 553 | + .await | |
| 554 | + .unwrap(); | |
| 566 | 555 | create( |
| 567 | 556 | &db, |
| 568 | - &UserId::generate(), | |
| 557 | + &creator, | |
| 569 | 558 | &course, |
| 570 | 559 | ExamTitle::try_new("quiz").unwrap(), |
| 571 | 560 | ExamDescription::try_new("").unwrap(), |
| @@ -580,12 +569,25 @@ mod tests { | ||
| 580 | 569 | .map(|_| ()) |
| 581 | 570 | }) |
| 582 | 571 | } |
| 583 | - crate::db::course::assert_no_child_outlives_a_course_delete( | |
| 584 | - "exam_orphan_race", | |
| 585 | - EXAM_TABLE, | |
| 586 | - make, | |
| 572 | + crate::db::course::assert_no_child_outlives_a_course_delete("exam", make).await; | |
| 573 | + } | |
| 574 | + | |
| 575 | + /// A real `app_user` row: students and graders are foreign keys now. The | |
| 576 | + /// label names the row's username; the id is minted, so repeated calls are | |
| 577 | + /// new people, not the same row. | |
| 578 | + async fn a_person(db: &Database, label: &str, role: &str) -> UserId { | |
| 579 | + let user = UserId::generate(); | |
| 580 | + sqlx::query( | |
| 581 | + "INSERT INTO app_user (id, username, password_hash, role) \ | |
| 582 | + VALUES ($1, $2, 'x', $3)", | |
| 587 | 583 | ) |
| 588 | - .await; | |
| 584 | + .bind(user.uuid()) | |
| 585 | + .bind(format!("{label}-{}", &user.key()[..8])) | |
| 586 | + .bind(role) | |
| 587 | + .execute(db) | |
| 588 | + .await | |
| 589 | + .unwrap(); | |
| 590 | + user | |
| 589 | 591 | } |
| 590 | 592 | |
| 591 | 593 | fn edit(exam: &Exam) -> (ExamTitle, ExamDescription, ExamKind, ExamSchedule) { |
| @@ -603,7 +605,7 @@ mod tests { | ||
| 603 | 605 | /// written over somebody else's edit. Asserts the *stored* row. |
| 604 | 606 | #[tokio::test] |
| 605 | 607 | async fn a_merge_built_on_a_stale_snapshot_is_refused() { |
| 606 | - let db = crate::database::init_mem().await.unwrap(); | |
| 608 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 607 | 609 | let stale = published(&db).await; |
| 608 | 610 | let (_, description, kind, schedule) = edit(&stale); |
| 609 | 611 | let landed = update_if_unchanged( |
| @@ -650,16 +652,17 @@ mod tests { | ||
| 650 | 652 | async fn re_drafting_is_refused_by_the_write_itself_once_a_mark_exists() { |
| 651 | 653 | use crate::db::exam_result; |
| 652 | 654 | use crate::domain::exam_result::Mark; |
| 653 | - let db = crate::database::init_mem().await.unwrap(); | |
| 655 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 654 | 656 | let exam = published(&db).await; |
| 655 | - let student = UserId::generate(); | |
| 657 | + let student = a_person(&db, "student", "student").await; | |
| 658 | + let grader = a_person(&db, "teacher", "teacher").await; | |
| 656 | 659 | exam_result::grade( |
| 657 | 660 | &db, |
| 658 | 661 | exam.get_id(), |
| 659 | 662 | &student, |
| 660 | 663 | 1, |
| 661 | 664 | Mark::try_new(80).unwrap(), |
| 662 | - &UserId::generate(), | |
| 665 | + &grader, | |
| 663 | 666 | exam.get_kind().as_str(), |
| 664 | 667 | ) |
| 665 | 668 | .await |
| @@ -796,10 +799,9 @@ mod tests { | ||
| 796 | 799 | /// [`crate::db::course::delete`]'s race test for why the rate is |
| 797 | 800 | /// counted rather than asserted per round. |
| 798 | 801 | /// |
| 799 | - /// This site has no `THROW` marker at all: it ends `.check()?`, which | |
| 800 | - /// returns the *first* error in the batch, and an aborted transaction | |
| 801 | - /// errors every slot — most of them with a generic "not executed". So a | |
| 802 | - /// genuine conflict can be masked by a sibling, and either way there is no | |
| 802 | + /// This site has no marker at all: the delete's statements share one | |
| 803 | + /// transaction whose first failure aborts the rest, so a genuine conflict | |
| 804 | + /// can be masked by a sibling error, and either way there is no | |
| 803 | 805 | /// [`crate::database::lost_the_race`] check and no retry. |
| 804 | 806 | /// |
| 805 | 807 | /// The racer is a mark: [`crate::db::exam_result::grade`] claims the exam's own |
| @@ -822,11 +824,11 @@ mod tests { | ||
| 822 | 824 | /// cascade (marks either survive whole or are swept whole, never a 500). |
| 823 | 825 | /// The retry is measured on [`crate::db::course::delete`]. |
| 824 | 826 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 825 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | |
| 826 | 827 | async fn a_delete_racing_a_mark_never_answers_500() { |
| 827 | 828 | use crate::db::exam_result; |
| 828 | 829 | use crate::domain::exam_result::Mark; |
| 829 | - let (db, _serialized) = crate::database::init_test_server("exam_delete_race").await; | |
| 830 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 831 | + let teacher = a_person(&db, "teacher", "teacher").await; | |
| 830 | 832 | let (mut delete_500, mut grade_500) = (0, 0); |
| 831 | 833 | let (mut split, mut swept) = (0, 0); |
| 832 | 834 | let (mut last_delete, mut last_grade) = (String::new(), String::new()); |
| @@ -850,10 +852,16 @@ mod tests { | ||
| 850 | 852 | delete(&db, exam).await |
| 851 | 853 | }) |
| 852 | 854 | }; |
| 855 | + // Six real students per round: the mark's app_user is a foreign | |
| 856 | + // key now. | |
| 857 | + let mut students = Vec::with_capacity(6); | |
| 858 | + for _ in 0..6 { | |
| 859 | + students.push(a_person(&db, "student", "student").await); | |
| 860 | + } | |
| 853 | 861 | let marks: Vec<_> = (0..6) |
| 854 | 862 | .map(|seat| { |
| 855 | 863 | let (id, db, kind) = (exam.get_id().clone(), db.clone(), kind.clone()); |
| 856 | - let student = UserId::from_key(&format!("stu{round}_{seat}")); | |
| 864 | + let (student, teacher) = (students[seat].clone(), teacher.clone()); | |
| 857 | 865 | tokio::spawn(async move { |
| 858 | 866 | exam_result::grade( |
| 859 | 867 | &db, |
| @@ -861,7 +869,7 @@ mod tests { | ||
| 861 | 869 | &student, |
| 862 | 870 | 1, |
| 863 | 871 | Mark::try_new(50).unwrap(), |
| 864 | - &UserId::from_key("teacher"), | |
| 872 | + &teacher, | |
| 865 | 873 | &kind, |
| 866 | 874 | ) |
| 867 | 875 | .await |
| @@ -871,7 +879,7 @@ mod tests { | ||
| 871 | 879 | let drop_it = drop_it.await.unwrap(); |
| 872 | 880 | if matches!(drop_it, Err(AppError::Db(_))) { |
| 873 | 881 | delete_500 += 1; |
| 874 | - last_delete = format!("{drop_it:?}"); | |
| 882 | + last_delete = format!("{:?}", drop_it.as_ref().unwrap_err()); | |
| 875 | 883 | } |
| 876 | 884 | let mut refused = 0; |
| 877 | 885 | for mark in marks { |
| @@ -972,50 +980,26 @@ mod tests { | ||
| 972 | 980 | /// The `Menu::delete` defect, one domain over: a student's answer must not |
| 973 | 981 | /// outlive the exam it belongs to. Guarding the save by *reading* the exam |
| 974 | 982 | /// would not do it — the read sees a row [`crate::db::exam::delete`] has removed but |
| 975 | - /// not committed, while its `DELETE exam_answer WHERE exam = $ex` swept a | |
| 976 | - /// snapshot predating the save, so both commit and the answer is left | |
| 977 | - /// pointing at an exam that is gone. [`crate::db::exam_answer::save`] writes the exam | |
| 978 | - /// row instead (its `result_count`, back unchanged), so the two transactions | |
| 979 | - /// touch one key and the store refuses one of them. | |
| 980 | - /// | |
| 981 | - /// The window is opened by the database, not by a lucky interleaving: a | |
| 982 | - /// `DEFINE EVENT` on `exam` fires *inside* the delete's own transaction the | |
| 983 | - /// instant the row goes, so the `SLEEP` lands exactly between the delete and | |
| 984 | - /// its cascade every time. Nothing in `src/` knows about it; the seam is the | |
| 985 | - /// schema. | |
| 983 | + /// not committed, while its cascade swept a snapshot predating the save, so | |
| 984 | + /// both commit and the answer is left pointing at an exam that is gone. | |
| 985 | + /// [`crate::db::exam_answer::save`] writes the exam row instead (its | |
| 986 | + /// `result_count`, back unchanged), so the two transactions touch one row | |
| 987 | + /// and Postgres refuses one of them. | |
| 986 | 988 | /// |
| 987 | 989 | /// One child per round, deliberately — in the menu twin, two children in one |
| 988 | 990 | /// round hid the bug: the first writer made the delete lose and re-send, and |
| 989 | 991 | /// the re-sent sweep removed the other's row. |
| 990 | - /// | |
| 991 | - /// Real server, and `#[ignore]`d for it: the subject *is* the store's | |
| 992 | - /// conflict detection, which `init_mem`'s embedded engine does not have — it | |
| 993 | - /// commits both writes and answers `Ok` to each, so this passes there on | |
| 994 | - /// broken code. Mutation-tested: putting the bare | |
| 995 | - /// `db.upsert(id).content(answer)` back turns it red (the exact output is in | |
| 996 | - /// the commit that added it). | |
| 997 | 992 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 998 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | |
| 999 | 993 | async fn an_answer_written_inside_a_delete_never_outlives_the_exam() { |
| 1000 | 994 | use crate::db::exam_answer; |
| 1001 | - let (db, _serialized) = crate::database::init_test_server("exam_answer_race").await; | |
| 1002 | - // Hold the delete open for a full second after the row is gone, while | |
| 1003 | - // its cascade still has to run. | |
| 1004 | - db.query( | |
| 1005 | - "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \ | |
| 1006 | - THEN { SLEEP 1s; };", | |
| 1007 | - ) | |
| 1008 | - .await | |
| 1009 | - .unwrap() | |
| 1010 | - .check() | |
| 1011 | - .unwrap(); | |
| 995 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 1012 | 996 | |
| 1013 | 997 | let (mut answers, mut swept) = (0, 0); |
| 1014 | - for round in 0..4 { | |
| 998 | + for round in 0..8 { | |
| 1015 | 999 | let exam = published(&db).await; |
| 1016 | 1000 | let question = question_on(&exam, &db).await; |
| 1017 | 1001 | let id = exam.get_id().clone(); |
| 1018 | - let student = UserId::from_key(&format!("stu{round}")); | |
| 1002 | + let student = a_person(&db, "student", "student").await; | |
| 1019 | 1003 | // The stored choice ids are minted by the create, not the ones the |
| 1020 | 1004 | // spec asked for — an answer must name one of *those*. |
| 1021 | 1005 | let pick = question.get_choices().unwrap()[1] |
| @@ -1023,21 +1007,26 @@ mod tests { | ||
| 1023 | 1007 | .as_str() |
| 1024 | 1008 | .to_string(); |
| 1025 | 1009 | |
| 1010 | + // Delete and save released together: both write the exam row, so | |
| 1011 | + // Postgres serializes them and refuses whichever lost. | |
| 1012 | + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | |
| 1026 | 1013 | let drop_it = { |
| 1027 | - let db = db.clone(); | |
| 1028 | - tokio::spawn(async move { delete(&db, exam).await }) | |
| 1014 | + let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone()); | |
| 1015 | + tokio::spawn(async move { | |
| 1016 | + gate.wait().await; | |
| 1017 | + delete(&db, exam).await | |
| 1018 | + }) | |
| 1029 | 1019 | }; |
| 1030 | - // The save starts inside the held window — the exam row is gone but | |
| 1031 | - // uncommitted, which is exactly what an exam read believes. | |
| 1032 | - tokio::time::sleep(std::time::Duration::from_millis(300)).await; | |
| 1033 | 1020 | let child = { |
| 1034 | - let (db, question, student) = (db.clone(), question.clone(), student.clone()); | |
| 1021 | + let (db, question, student, pick, gate) = | |
| 1022 | + (db.clone(), question.clone(), student.clone(), pick, gate); | |
| 1035 | 1023 | tokio::spawn(async move { |
| 1024 | + gate.wait().await; | |
| 1036 | 1025 | exam_answer::save(&db, &question, &student, 1, Some(pick), None).await |
| 1037 | 1026 | }) |
| 1038 | 1027 | }; |
| 1039 | 1028 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); |
| 1040 | - // A 404 for the save, or a NotFound for the delete, is a correct | |
| 1029 | + // A 404 for the save, or a refusal for the delete, is a correct | |
| 1041 | 1030 | // answer — the only defect is stored state. |
| 1042 | 1031 | assert!( |
| 1043 | 1032 | !matches!(child, Err(AppError::Db(_))), |
| @@ -1052,7 +1041,7 @@ mod tests { | ||
| 1052 | 1041 | panic!("round {round}: the delete reported success but the exam is still there"); |
| 1053 | 1042 | } |
| 1054 | 1043 | } |
| 1055 | - eprintln!("Exam::delete raced by an answer save: {swept}/4 rounds deleted the exam"); | |
| 1044 | + eprintln!("Exam::delete raced by an answer save: {swept}/8 rounds deleted the exam"); | |
| 1056 | 1045 | assert!( |
| 1057 | 1046 | swept > 0, |
| 1058 | 1047 | "no round ever deleted the exam, so the window was never reached" |
| @@ -1068,28 +1057,15 @@ mod tests { | ||
| 1068 | 1057 | /// again, hanging off an exam nobody could ever see. The freeze gate is a |
| 1069 | 1058 | /// *read* of `exam_attempt` and never survived this window; |
| 1070 | 1059 | /// [`crate::db::exam_attempt::write_unfrozen_with`] now writes the exam row too. |
| 1071 | - /// | |
| 1072 | - /// Same seam, same `#[ignore]`, same reason as the answer twin above: the | |
| 1073 | - /// subject *is* the store's conflict detection, which the in-memory engine | |
| 1074 | - /// does not have. | |
| 1075 | 1060 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 1076 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | |
| 1077 | 1061 | async fn a_question_written_inside_a_delete_never_outlives_the_exam() { |
| 1078 | 1062 | use crate::domain::exam_question::{ |
| 1079 | 1063 | ChoiceInput, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, |
| 1080 | 1064 | }; |
| 1081 | - let (db, _serialized) = crate::database::init_test_server("exam_question_race").await; | |
| 1082 | - db.query( | |
| 1083 | - "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \ | |
| 1084 | - THEN { SLEEP 1s; };", | |
| 1085 | - ) | |
| 1086 | - .await | |
| 1087 | - .unwrap() | |
| 1088 | - .check() | |
| 1089 | - .unwrap(); | |
| 1065 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 1090 | 1066 | |
| 1091 | 1067 | let (mut questions, mut swept, mut stuck) = (0, 0, 0); |
| 1092 | - for round in 0..4 { | |
| 1068 | + for round in 0..8 { | |
| 1093 | 1069 | let exam = published(&db).await; |
| 1094 | 1070 | let id = exam.get_id().clone(); |
| 1095 | 1071 | let subject = crate::db::subject::create( |
| @@ -1101,13 +1077,18 @@ mod tests { | ||
| 1101 | 1077 | .await |
| 1102 | 1078 | .unwrap(); |
| 1103 | 1079 | |
| 1080 | + // Delete and create released together: both write the exam row, so | |
| 1081 | + // Postgres serializes them and refuses whichever lost. | |
| 1082 | + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | |
| 1104 | 1083 | let drop_it = { |
| 1105 | - let db = db.clone(); | |
| 1106 | - tokio::spawn(async move { delete(&db, exam).await }) | |
| 1084 | + let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone()); | |
| 1085 | + tokio::spawn(async move { | |
| 1086 | + gate.wait().await; | |
| 1087 | + delete(&db, exam).await | |
| 1088 | + }) | |
| 1107 | 1089 | }; |
| 1108 | - tokio::time::sleep(std::time::Duration::from_millis(300)).await; | |
| 1109 | 1090 | let child = { |
| 1110 | - let (db, exam_id, on) = (db.clone(), id.clone(), subject.get_id().clone()); | |
| 1091 | + let (db, exam_id, on, gate) = (db.clone(), id.clone(), subject.get_id().clone(), gate); | |
| 1111 | 1092 | tokio::spawn(async move { |
| 1112 | 1093 | let spec = QuestionSpec::try_new( |
| 1113 | 1094 | QuestionKind::try_new("choice").unwrap(), |
| @@ -1167,7 +1148,7 @@ mod tests { | ||
| 1167 | 1148 | panic!("round {round}: the delete reported success but the exam is still there"); |
| 1168 | 1149 | } |
| 1169 | 1150 | } |
| 1170 | - eprintln!("Exam::delete raced by a question write: {swept}/4 rounds deleted the exam"); | |
| 1151 | + eprintln!("Exam::delete raced by a question write: {swept}/8 rounds deleted the exam"); | |
| 1171 | 1152 | assert!( |
| 1172 | 1153 | swept > 0, |
| 1173 | 1154 | "no round ever deleted the exam, so the window was never reached" |
| @@ -1177,37 +1158,35 @@ mod tests { | ||
| 1177 | 1158 | } |
| 1178 | 1159 | |
| 1179 | 1160 | /// The student's half of the same picture problem: a drawing is a bare |
| 1180 | - /// `UPSERT` — the exact pre-fix shape of [`crate::db::exam_answer::save`] — so it kept | |
| 1181 | - /// the hole the text answer just lost, blob and all. | |
| 1161 | + /// upsert — the exact pre-fix shape of [`crate::db::exam_answer::save`] — so it kept | |
| 1162 | + /// the hole the text answer just lost, blob and all. It now rides the same | |
| 1163 | + /// exam-row write the answer does. | |
| 1182 | 1164 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 1183 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | |
| 1184 | 1165 | async fn a_drawing_written_inside_a_delete_never_outlives_the_exam() { |
| 1185 | 1166 | use crate::domain::answer_image::AnswerImage; |
| 1186 | 1167 | use crate::domain::note_file::FileContentType; |
| 1187 | - let (db, _serialized) = crate::database::init_test_server("answer_image_race").await; | |
| 1188 | - db.query( | |
| 1189 | - "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \ | |
| 1190 | - THEN { SLEEP 1s; };", | |
| 1191 | - ) | |
| 1192 | - .await | |
| 1193 | - .unwrap() | |
| 1194 | - .check() | |
| 1195 | - .unwrap(); | |
| 1168 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 1196 | 1169 | |
| 1197 | 1170 | let (mut drawings, mut swept) = (0, 0); |
| 1198 | - for round in 0..4 { | |
| 1171 | + for round in 0..8 { | |
| 1199 | 1172 | let exam = published(&db).await; |
| 1200 | 1173 | let question = question_on(&exam, &db).await; |
| 1201 | 1174 | let id = exam.get_id().clone(); |
| 1202 | - let student = UserId::from_key(&format!("stu{round}")); | |
| 1175 | + let student = a_person(&db, "student", "student").await; | |
| 1203 | 1176 | |
| 1177 | + // Delete and upsert released together: both write the exam row, so | |
| 1178 | + // Postgres serializes them and refuses whichever lost. | |
| 1179 | + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | |
| 1204 | 1180 | let drop_it = { |
| 1205 | - let db = db.clone(); | |
| 1206 | - tokio::spawn(async move { delete(&db, exam).await }) | |
| 1181 | + let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone()); | |
| 1182 | + tokio::spawn(async move { | |
| 1183 | + gate.wait().await; | |
| 1184 | + delete(&db, exam).await | |
| 1185 | + }) | |
| 1207 | 1186 | }; |
| 1208 | - tokio::time::sleep(std::time::Duration::from_millis(300)).await; | |
| 1209 | 1187 | let child = { |
| 1210 | - let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone()); | |
| 1188 | + let (db, exam_id, on, student, gate) = | |
| 1189 | + (db.clone(), id.clone(), question.get_id().clone(), student.clone(), gate); | |
| 1211 | 1190 | tokio::spawn(async move { |
| 1212 | 1191 | let image = AnswerImage::new( |
| 1213 | 1192 | &exam_id, |
| @@ -1236,7 +1215,7 @@ mod tests { | ||
| 1236 | 1215 | panic!("round {round}: the delete reported success but the exam is still there"); |
| 1237 | 1216 | } |
| 1238 | 1217 | } |
| 1239 | - eprintln!("Exam::delete raced by a drawing write: {swept}/4 rounds deleted the exam"); | |
| 1218 | + eprintln!("Exam::delete raced by a drawing write: {swept}/8 rounds deleted the exam"); | |
| 1240 | 1219 | assert!( |
| 1241 | 1220 | swept > 0, |
| 1242 | 1221 | "no round ever deleted the exam, so the window was never reached" |
| @@ -1247,36 +1226,33 @@ mod tests { | ||
| 1247 | 1226 | /// A picture is written through the same freeze gate as the question it |
| 1248 | 1227 | /// hangs on, so it had the same hole — and one the row count does not even |
| 1249 | 1228 | /// show: `delete_exam` collects the blob names to unlink *before* it calls |
| 1250 | - /// [\`crate::db::exam::delete\`], so an image row landing after that snapshot strands | |
| 1251 | - /// its bytes on disk forever as well. | |
| 1229 | + /// [`crate::db::exam::delete`], so an image row landing after that snapshot strands | |
| 1230 | + /// its bytes on disk forever as well. It now rides the same exam-row write | |
| 1231 | + /// the question does. | |
| 1252 | 1232 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 1253 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | |
| 1254 | 1233 | async fn a_picture_written_inside_a_delete_never_outlives_the_exam() { |
| 1255 | 1234 | use crate::domain::note_file::FileContentType; |
| 1256 | 1235 | use crate::domain::question_image::QuestionImage; |
| 1257 | - let (db, _serialized) = crate::database::init_test_server("question_image_race").await; | |
| 1258 | - db.query( | |
| 1259 | - "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \ | |
| 1260 | - THEN { SLEEP 1s; };", | |
| 1261 | - ) | |
| 1262 | - .await | |
| 1263 | - .unwrap() | |
| 1264 | - .check() | |
| 1265 | - .unwrap(); | |
| 1236 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 1266 | 1237 | |
| 1267 | 1238 | let (mut images, mut swept) = (0, 0); |
| 1268 | - for round in 0..4 { | |
| 1239 | + for round in 0..8 { | |
| 1269 | 1240 | let exam = published(&db).await; |
| 1270 | 1241 | let question = question_on(&exam, &db).await; |
| 1271 | 1242 | let id = exam.get_id().clone(); |
| 1272 | 1243 | |
| 1244 | + // Delete and upsert released together: both write the exam row, so | |
| 1245 | + // Postgres serializes them and refuses whichever lost. | |
| 1246 | + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | |
| 1273 | 1247 | let drop_it = { |
| 1274 | - let db = db.clone(); | |
| 1275 | - tokio::spawn(async move { delete(&db, exam).await }) | |
| 1248 | + let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone()); | |
| 1249 | + tokio::spawn(async move { | |
| 1250 | + gate.wait().await; | |
| 1251 | + delete(&db, exam).await | |
| 1252 | + }) | |
| 1276 | 1253 | }; |
| 1277 | - tokio::time::sleep(std::time::Duration::from_millis(300)).await; | |
| 1278 | 1254 | let child = { |
| 1279 | - let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone()); | |
| 1255 | + let (db, exam_id, on, gate) = (db.clone(), id.clone(), question.get_id().clone(), gate); | |
| 1280 | 1256 | tokio::spawn(async move { |
| 1281 | 1257 | let image = QuestionImage::new( |
| 1282 | 1258 | &exam_id, |
| @@ -1304,7 +1280,7 @@ mod tests { | ||
| 1304 | 1280 | panic!("round {round}: the delete reported success but the exam is still there"); |
| 1305 | 1281 | } |
| 1306 | 1282 | } |
| 1307 | - eprintln!("Exam::delete raced by a picture write: {swept}/4 rounds deleted the exam"); | |
| 1283 | + eprintln!("Exam::delete raced by a picture write: {swept}/8 rounds deleted the exam"); | |
| 1308 | 1284 | assert!( |
| 1309 | 1285 | swept > 0, |
| 1310 | 1286 | "no round ever deleted the exam, so the window was never reached" |
src/db/exam_answer.rsmodified+20 -13
| @@ -283,7 +283,7 @@ mod tests { | ||
| 283 | 283 | } |
| 284 | 284 | |
| 285 | 285 | fn student() -> UserId { |
| 286 | - UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA") | |
| 286 | + UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa") | |
| 287 | 287 | } |
| 288 | 288 | |
| 289 | 289 | /// The bite test for the exam-row touch in [`save`]: it exists |
| @@ -298,7 +298,17 @@ mod tests { | ||
| 298 | 298 | use crate::domain::exam::{ |
| 299 | 299 | ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle, |
| 300 | 300 | }; |
| 301 | - let db = crate::database::init_mem().await.unwrap(); | |
| 301 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 302 | + // The student is a foreign key now: a real row under the fixture's | |
| 303 | + // fixed key. | |
| 304 | + sqlx::query( | |
| 305 | + "INSERT INTO app_user (id, username, password_hash) \ | |
| 306 | + VALUES ($1, 'aaaa-fixture', 'x')", | |
| 307 | + ) | |
| 308 | + .bind(student().uuid()) | |
| 309 | + .execute(&db) | |
| 310 | + .await | |
| 311 | + .unwrap(); | |
| 302 | 312 | let kinds = crate::domain::settings::Settings::defaults() |
| 303 | 313 | .get_exam_kinds() |
| 304 | 314 | .to_vec(); |
| @@ -318,14 +328,12 @@ mod tests { | ||
| 318 | 328 | .await |
| 319 | 329 | .unwrap(); |
| 320 | 330 | let stored = async |db: &Database| -> Option<i64> { |
| 321 | - let mut result = db | |
| 322 | - .query("SELECT VALUE result_count FROM ONLY $ex") | |
| 323 | - .bind(("ex", exam.get_id().record())) | |
| 331 | + sqlx::query_scalar::<_, i64>("SELECT result_count FROM exam WHERE id = $1") | |
| 332 | + .bind(exam.get_id().uuid()) | |
| 333 | + .fetch_optional(db) | |
| 324 | 334 | .await |
| 325 | 335 | .unwrap() |
| 326 | - .check() | |
| 327 | - .unwrap(); | |
| 328 | - result.take::<Option<i64>>(0).unwrap() | |
| 336 | + .flatten() | |
| 329 | 337 | }; |
| 330 | 338 | let question = choice_question(exam.get_id(), 10, 1); |
| 331 | 339 | let pick = choice_id(&question, 1).as_str().to_string(); |
| @@ -342,11 +350,10 @@ mod tests { | ||
| 342 | 350 | ); |
| 343 | 351 | |
| 344 | 352 | // …and a counter that marks have moved is put back at its own value. |
| 345 | - db.query("UPDATE $ex SET result_count = 7") | |
| 346 | - .bind(("ex", exam.get_id().record())) | |
| 353 | + sqlx::query("UPDATE exam SET result_count = 7 WHERE id = $1") | |
| 354 | + .bind(exam.get_id().uuid()) | |
| 355 | + .execute(&db) | |
| 347 | 356 | .await |
| 348 | - .unwrap() | |
| 349 | - .check() | |
| 350 | 357 | .unwrap(); |
| 351 | 358 | save(&db, &question, &student(), 2, Some(pick), None) |
| 352 | 359 | .await |
| @@ -354,7 +361,7 @@ mod tests { | ||
| 354 | 361 | assert_eq!(stored(&db).await, Some(7), "the touch moved a real count"); |
| 355 | 362 | |
| 356 | 363 | // The gate that makes the touch worth having: no exam, no answer. |
| 357 | - let orphan = choice_question(&ExamId::from_key("01NOSUCHEXAMAAAAAAAAAAAAAA"), 10, 0); | |
| 364 | + let orphan = choice_question(&ExamId::from_key("019732e3-7b00-7000-8000-00000000e0a0"), 10, 0); | |
| 358 | 365 | let pick = choice_id(&orphan, 0).as_str().to_string(); |
| 359 | 366 | let refused = save(&db, &orphan, &student(), 1, Some(pick), None).await; |
| 360 | 367 | assert!( |
src/db/exam_attempt.rsmodified+10 -10
| @@ -377,7 +377,7 @@ pub async fn create( | ||
| 377 | 377 | #[cfg(test)] |
| 378 | 378 | mod tests { |
| 379 | 379 | use super::*; |
| 380 | - use crate::database::init_mem; | |
| 380 | + use crate::database::init_test_db; | |
| 381 | 381 | use crate::domain::exam::{ |
| 382 | 382 | Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle, |
| 383 | 383 | }; |
| @@ -389,7 +389,7 @@ mod tests { | ||
| 389 | 389 | /// An open exam with retakes allowed, plus one choice question — enough |
| 390 | 390 | /// rows to exercise the attempt lifecycle without the HTTP layer. |
| 391 | 391 | async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) { |
| 392 | - let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); | |
| 392 | + let creator = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); | |
| 393 | 393 | let course = crate::db::course::a_test_course(db).await; |
| 394 | 394 | let kinds = Settings::defaults().get_exam_kinds().to_vec(); |
| 395 | 395 | let exam = crate::db::exam::create( |
| @@ -468,7 +468,7 @@ mod tests { | ||
| 468 | 468 | |
| 469 | 469 | #[tokio::test] |
| 470 | 470 | async fn submitting_never_reverts_a_walk_out_that_raced_it() { |
| 471 | - let db = init_mem().await.unwrap(); | |
| 471 | + let (db, _leases) = init_test_db().await; | |
| 472 | 472 | let (exam, _question) = open_exam_with_question(&db, 1).await; |
| 473 | 473 | let user = student(&db).await; |
| 474 | 474 | |
| @@ -478,7 +478,7 @@ mod tests { | ||
| 478 | 478 | |
| 479 | 479 | // The REST submit path reads the attempt, then checks the deadline and |
| 480 | 480 | // the already-finished guard — several awaits before it writes. |
| 481 | - let stale = read(&db, attempt.get_id()) | |
| 481 | + let stale = read(&db, &attempt.get_id()) | |
| 482 | 482 | .await |
| 483 | 483 | .unwrap() |
| 484 | 484 | .expect("attempt exists"); |
| @@ -488,7 +488,7 @@ mod tests { | ||
| 488 | 488 | // clears it) — a field-scoped write to the same row. |
| 489 | 489 | set_left( |
| 490 | 490 | &db, |
| 491 | - read(&db, attempt.get_id()) | |
| 491 | + read(&db, &attempt.get_id()) | |
| 492 | 492 | .await |
| 493 | 493 | .unwrap() |
| 494 | 494 | .expect("attempt exists"), |
| @@ -503,7 +503,7 @@ mod tests { | ||
| 503 | 503 | let finished = finish(&db, stale).await.unwrap(); |
| 504 | 504 | assert!(finished.get_finished_at().is_some()); |
| 505 | 505 | |
| 506 | - let after = read(&db, attempt.get_id()) | |
| 506 | + let after = read(&db, &attempt.get_id()) | |
| 507 | 507 | .await |
| 508 | 508 | .unwrap() |
| 509 | 509 | .expect("attempt still exists"); |
| @@ -516,7 +516,7 @@ mod tests { | ||
| 516 | 516 | |
| 517 | 517 | #[tokio::test] |
| 518 | 518 | async fn stamping_left_never_reverts_a_submission() { |
| 519 | - let db = init_mem().await.unwrap(); | |
| 519 | + let (db, _leases) = init_test_db().await; | |
| 520 | 520 | let (exam, _question) = open_exam_with_question(&db, 1).await; |
| 521 | 521 | let user = student(&db).await; |
| 522 | 522 | |
| @@ -528,14 +528,14 @@ mod tests { | ||
| 528 | 528 | |
| 529 | 529 | // The exam-room teardown reads the attempt while it is still in |
| 530 | 530 | // progress (`stamp_left`'s read) — a snapshot with `finished_at` unset. |
| 531 | - let stale = read(&db, attempt.get_id()) | |
| 531 | + let stale = read(&db, &attempt.get_id()) | |
| 532 | 532 | .await |
| 533 | 533 | .unwrap() |
| 534 | 534 | .expect("attempt exists"); |
| 535 | 535 | assert!(stale.get_finished_at().is_none()); |
| 536 | 536 | let finished = finish( |
| 537 | 537 | &db, |
| 538 | - read(&db, attempt.get_id()) | |
| 538 | + read(&db, &attempt.get_id()) | |
| 539 | 539 | .await |
| 540 | 540 | .unwrap() |
| 541 | 541 | .expect("attempt exists"), |
| @@ -552,7 +552,7 @@ mod tests { | ||
| 552 | 552 | // finishing). |
| 553 | 553 | set_left(&db, stale, Some(Timestamp::now())).await.unwrap(); |
| 554 | 554 | |
| 555 | - let after = read(&db, attempt.get_id()) | |
| 555 | + let after = read(&db, &attempt.get_id()) | |
| 556 | 556 | .await |
| 557 | 557 | .unwrap() |
| 558 | 558 | .expect("attempt still exists"); |
src/db/exam_question.rsmodified+37 -30
| @@ -437,7 +437,7 @@ mod tests { | ||
| 437 | 437 | /// outlives the row it accounts for makes its subject undeletable forever. |
| 438 | 438 | mod counters { |
| 439 | 439 | use super::*; |
| 440 | - use crate::database::init_mem; | |
| 440 | + use crate::database::init_test_db; | |
| 441 | 441 | use crate::domain::exam::{ |
| 442 | 442 | Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle, |
| 443 | 443 | }; |
| @@ -446,10 +446,21 @@ mod tests { | ||
| 446 | 446 | use crate::domain::user::UserId; |
| 447 | 447 | |
| 448 | 448 | async fn an_exam(db: &Database) -> Exam { |
| 449 | + // The creator is a foreign key now: a real `app_user` row under | |
| 450 | + // the fixture's fixed key. | |
| 451 | + let creator = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); | |
| 452 | + sqlx::query( | |
| 453 | + "INSERT INTO app_user (id, username, password_hash) \ | |
| 454 | + VALUES ($1, 'acdc-fixture', 'x')", | |
| 455 | + ) | |
| 456 | + .bind(creator.uuid()) | |
| 457 | + .execute(db) | |
| 458 | + .await | |
| 459 | + .unwrap(); | |
| 449 | 460 | let kinds = Settings::defaults().get_exam_kinds().to_vec(); |
| 450 | 461 | crate::db::exam::create( |
| 451 | 462 | db, |
| 452 | - &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"), | |
| 463 | + &creator, | |
| 453 | 464 | &crate::db::course::a_test_course(db).await, |
| 454 | 465 | ExamTitle::try_new("practice").unwrap(), |
| 455 | 466 | ExamDescription::try_new("").unwrap(), |
| @@ -503,26 +514,22 @@ mod tests { | ||
| 503 | 514 | |
| 504 | 515 | /// The stored `exam_question_count` on one subject, absent = zero. |
| 505 | 516 | async fn count_on(subject: &SubjectId, db: &Database) -> i64 { |
| 506 | - let mut result = db | |
| 507 | - .query(format!( | |
| 508 | - "SELECT VALUE ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) FROM $sub" | |
| 509 | - )) | |
| 510 | - .bind(("sub", subject.record())) | |
| 511 | - .await | |
| 512 | - .unwrap() | |
| 513 | - .check() | |
| 514 | - .unwrap(); | |
| 515 | - result | |
| 516 | - .take::<Vec<i64>>(0) | |
| 517 | - .unwrap() | |
| 518 | - .first() | |
| 519 | - .copied() | |
| 520 | - .unwrap_or(0) | |
| 517 | + sqlx::query_scalar::<_, i64>( | |
| 518 | + "SELECT exam_question_count FROM subject WHERE id = $1", | |
| 519 | + ) | |
| 520 | + .bind(subject.uuid()) | |
| 521 | + .fetch_one(db) | |
| 522 | + .await | |
| 523 | + .unwrap() | |
| 521 | 524 | } |
| 522 | 525 | |
| 523 | 526 | async fn rows(sql: &str, db: &Database) -> usize { |
| 524 | - let mut result = db.query(sql).await.unwrap().check().unwrap(); | |
| 525 | - result.take::<Vec<RecordId>>(0).unwrap().len() | |
| 527 | + sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!( | |
| 528 | + "SELECT count(*) FROM ({sql}) AS t" | |
| 529 | + ))) | |
| 530 | + .fetch_one(db) | |
| 531 | + .await | |
| 532 | + .unwrap() as usize | |
| 526 | 533 | } |
| 527 | 534 | |
| 528 | 535 | /// The freeze outranks the counter move, on both paths — and because |
| @@ -530,7 +537,7 @@ mod tests { | ||
| 530 | 537 | /// the counters read as if nothing ran. |
| 531 | 538 | #[tokio::test] |
| 532 | 539 | async fn a_frozen_exam_leaves_the_subject_counters_untouched() { |
| 533 | - let db = init_mem().await.unwrap(); | |
| 540 | + let (db, _leases) = init_test_db().await; | |
| 534 | 541 | let exam = an_exam(&db).await; |
| 535 | 542 | let (from, to) = (a_subject(&db).await, a_subject(&db).await); |
| 536 | 543 | let (from, to) = (from.get_id().clone(), to.get_id().clone()); |
| @@ -575,7 +582,7 @@ mod tests { | ||
| 575 | 582 | /// nor a count — least of all on a subject it would have to invent. |
| 576 | 583 | #[tokio::test] |
| 577 | 584 | async fn a_create_on_a_dead_subject_writes_neither_row_nor_count() { |
| 578 | - let db = init_mem().await.unwrap(); | |
| 585 | + let (db, _leases) = init_test_db().await; | |
| 579 | 586 | let exam = an_exam(&db).await; |
| 580 | 587 | let subject = a_subject(&db).await; |
| 581 | 588 | let id = subject.get_id().clone(); |
| @@ -587,12 +594,12 @@ mod tests { | ||
| 587 | 594 | .expect_err("a subject that is gone must not be taggable"); |
| 588 | 595 | assert!(error.to_string().contains("subject does not exist")); |
| 589 | 596 | assert_eq!( |
| 590 | - rows("SELECT VALUE id FROM exam_question", &db).await, | |
| 597 | + rows("SELECT id FROM exam_question", &db).await, | |
| 591 | 598 | 0, |
| 592 | 599 | "a refused create may write no row" |
| 593 | 600 | ); |
| 594 | 601 | assert_eq!( |
| 595 | - rows("SELECT VALUE id FROM subject", &db).await, | |
| 602 | + rows("SELECT id FROM subject", &db).await, | |
| 596 | 603 | 0, |
| 597 | 604 | "…and least of all a count on a subject it just brought back" |
| 598 | 605 | ); |
| @@ -600,7 +607,7 @@ mod tests { | ||
| 600 | 607 | |
| 601 | 608 | #[tokio::test] |
| 602 | 609 | async fn a_subject_move_moves_the_count() { |
| 603 | - let db = init_mem().await.unwrap(); | |
| 610 | + let (db, _leases) = init_test_db().await; | |
| 604 | 611 | let exam = an_exam(&db).await; |
| 605 | 612 | let (from, to) = (a_subject(&db).await, a_subject(&db).await); |
| 606 | 613 | let (from, to) = (from.get_id().clone(), to.get_id().clone()); |
| @@ -614,7 +621,7 @@ mod tests { | ||
| 614 | 621 | |
| 615 | 622 | #[tokio::test] |
| 616 | 623 | async fn a_move_to_a_dead_subject_leaves_everything_untouched() { |
| 617 | - let db = init_mem().await.unwrap(); | |
| 624 | + let (db, _leases) = init_test_db().await; | |
| 618 | 625 | let exam = an_exam(&db).await; |
| 619 | 626 | let from = a_subject(&db).await.get_id().clone(); |
| 620 | 627 | let dead = a_subject(&db).await; |
| @@ -633,7 +640,7 @@ mod tests { | ||
| 633 | 640 | 1, |
| 634 | 641 | "the release rolled back with the claim" |
| 635 | 642 | ); |
| 636 | - assert_eq!(rows("SELECT VALUE id FROM subject", &db).await, 1); | |
| 643 | + assert_eq!(rows("SELECT id FROM subject", &db).await, 1); | |
| 637 | 644 | } |
| 638 | 645 | |
| 639 | 646 | /// The double-claim guard. Both movers compute their claim and release |
| @@ -649,7 +656,7 @@ mod tests { | ||
| 649 | 656 | /// assertion — the stale mover is happily applied. |
| 650 | 657 | #[tokio::test] |
| 651 | 658 | async fn a_stale_mover_is_refused_and_claims_nothing() { |
| 652 | - let db = init_mem().await.unwrap(); | |
| 659 | + let (db, _leases) = init_test_db().await; | |
| 653 | 660 | let exam = an_exam(&db).await; |
| 654 | 661 | let from = a_subject(&db).await.get_id().clone(); |
| 655 | 662 | let to = a_subject(&db).await.get_id().clone(); |
| @@ -685,7 +692,7 @@ mod tests { | ||
| 685 | 692 | /// on the first assertion — the re-state lands 200. |
| 686 | 693 | #[tokio::test] |
| 687 | 694 | async fn a_stale_re_stater_is_refused_and_reverts_nothing() { |
| 688 | - let db = init_mem().await.unwrap(); | |
| 695 | + let (db, _leases) = init_test_db().await; | |
| 689 | 696 | let exam = an_exam(&db).await; |
| 690 | 697 | let from = a_subject(&db).await.get_id().clone(); |
| 691 | 698 | let to = a_subject(&db).await.get_id().clone(); |
| @@ -715,7 +722,7 @@ mod tests { | ||
| 715 | 722 | /// re-stating the subject the row really holds passes it trivially. |
| 716 | 723 | #[tokio::test] |
| 717 | 724 | async fn a_no_op_re_state_still_lands() { |
| 718 | - let db = init_mem().await.unwrap(); | |
| 725 | + let (db, _leases) = init_test_db().await; | |
| 719 | 726 | let exam = an_exam(&db).await; |
| 720 | 727 | let on = a_subject(&db).await.get_id().clone(); |
| 721 | 728 | let question = a_question(&exam, &on, &db).await; |
| @@ -740,7 +747,7 @@ mod tests { | ||
| 740 | 747 | /// not the stale-mover 409 — the two empty-`$row` cases stay apart. |
| 741 | 748 | #[tokio::test] |
| 742 | 749 | async fn a_move_of_a_deleted_question_is_still_a_404() { |
| 743 | - let db = init_mem().await.unwrap(); | |
| 750 | + let (db, _leases) = init_test_db().await; | |
| 744 | 751 | let exam = an_exam(&db).await; |
| 745 | 752 | let from = a_subject(&db).await.get_id().clone(); |
| 746 | 753 | let to = a_subject(&db).await.get_id().clone(); |
src/db/fee_plan.rsmodified+1 -1
| @@ -176,7 +176,7 @@ mod tests { | ||
| 176 | 176 | /// shape and the stored one agree. A past due date is legal on purpose. |
| 177 | 177 | #[tokio::test] |
| 178 | 178 | async fn installments_survive_a_round_trip_through_the_schema() { |
| 179 | - let db = crate::database::init_mem().await.unwrap(); | |
| 179 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 180 | 180 | let manager = UserId::from_key("mgr1"); |
| 181 | 181 | let installments = vec![ |
| 182 | 182 | Installment::new( |
src/db/homework.rsmodified+42 -32
| @@ -442,11 +442,15 @@ async fn ensure_no_orphans( | ||
| 442 | 442 | |
| 443 | 443 | /// Delete the homework and cascade its submissions, their files, and its |
| 444 | 444 | /// results — one transaction, so a crash can't orphan a submission under a |
| 445 | -/// vanished homework. The submission file *blobs* are the web layer's to | |
| 446 | -/// unlink: their names are returned (collected inside the transaction, | |
| 447 | -/// before the wipes — a file row inserted after an out-of-transaction | |
| 448 | -/// collection would be deleted here while its key was already gone from the | |
| 449 | -/// list, stranding the blob) and removed after the rows are gone. | |
| 445 | +/// vanished homework. The cascade runs children-first (every FK here is | |
| 446 | +/// `ON DELETE NO ACTION`): files, then submissions — whose `graded_by_result` | |
| 447 | +/// stamp points at a result row, so they must be gone before it — then the | |
| 448 | +/// results, then the homework. The submission file *blobs* are the web | |
| 449 | +/// layer's to unlink: their names are returned (collected inside the | |
| 450 | +/// transaction, before the wipes — a file row inserted after an | |
| 451 | +/// out-of-transaction collection would be deleted here while its key was | |
| 452 | +/// already gone from the list, stranding the blob) and removed after the | |
| 453 | +/// rows are gone. | |
| 450 | 454 | pub async fn delete( |
| 451 | 455 | db: &Database, |
| 452 | 456 | homework: Homework, |
| @@ -470,13 +474,13 @@ pub async fn delete( | ||
| 470 | 474 | .execute(&mut *tx) |
| 471 | 475 | .await?; |
| 472 | 476 | sqlx::query!( |
| 473 | - "DELETE FROM homework_result WHERE homework = $1", | |
| 477 | + "DELETE FROM homework_submission WHERE homework = $1", | |
| 474 | 478 | homework.get_id().uuid() |
| 475 | 479 | ) |
| 476 | 480 | .execute(&mut *tx) |
| 477 | 481 | .await?; |
| 478 | 482 | sqlx::query!( |
| 479 | - "DELETE FROM homework_submission WHERE homework = $1", | |
| 483 | + "DELETE FROM homework_result WHERE homework = $1", | |
| 480 | 484 | homework.get_id().uuid() |
| 481 | 485 | ) |
| 482 | 486 | .execute(&mut *tx) |
| @@ -529,15 +533,27 @@ mod tests { | ||
| 529 | 533 | } |
| 530 | 534 | |
| 531 | 535 | async fn homework_on(subject: &SubjectId, db: &Database) -> Homework { |
| 536 | + // The course and the teacher are foreign keys now: a real course row | |
| 537 | + // (the subject's own fixture path mints one) and a real teacher. | |
| 538 | + let teacher = UserId::generate(); | |
| 539 | + sqlx::query( | |
| 540 | + "INSERT INTO app_user (id, username, password_hash, role) \ | |
| 541 | + VALUES ($1, $2, 'x', 'teacher')", | |
| 542 | + ) | |
| 543 | + .bind(teacher.uuid()) | |
| 544 | + .bind(format!("homework-fixture-{}", &teacher.key()[..8])) | |
| 545 | + .execute(db) | |
| 546 | + .await | |
| 547 | + .unwrap(); | |
| 532 | 548 | create( |
| 533 | 549 | db, |
| 534 | - &CourseId::from_key("course"), | |
| 550 | + &crate::db::course::a_test_course(db).await, | |
| 535 | 551 | subject, |
| 536 | 552 | HomeworkTitle::try_new("essay").unwrap(), |
| 537 | 553 | None, |
| 538 | 554 | Timestamp::from_millis(1), |
| 539 | 555 | None, |
| 540 | - &UserId::from_key("teacher"), | |
| 556 | + &teacher, | |
| 541 | 557 | ) |
| 542 | 558 | .await |
| 543 | 559 | .unwrap() |
| @@ -545,27 +561,21 @@ mod tests { | ||
| 545 | 561 | |
| 546 | 562 | /// The stored `homework_count` on one subject, absent counting as zero. |
| 547 | 563 | async fn count_on(subject: &SubjectId, db: &Database) -> i64 { |
| 548 | - let mut result = db | |
| 549 | - .query(format!( | |
| 550 | - "SELECT VALUE ({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) FROM $sub" | |
| 551 | - )) | |
| 552 | - .bind(("sub", subject.record())) | |
| 564 | + sqlx::query_scalar::<_, i64>("SELECT homework_count FROM subject WHERE id = $1") | |
| 565 | + .bind(subject.uuid()) | |
| 566 | + .fetch_one(db) | |
| 553 | 567 | .await |
| 554 | 568 | .unwrap() |
| 555 | - .check() | |
| 556 | - .unwrap(); | |
| 557 | - result | |
| 558 | - .take::<Vec<i64>>(0) | |
| 559 | - .unwrap() | |
| 560 | - .first() | |
| 561 | - .copied() | |
| 562 | - .unwrap_or(0) | |
| 563 | 569 | } |
| 564 | 570 | |
| 565 | 571 | /// How many rows `sql` selects ids for. |
| 566 | 572 | async fn rows(sql: &str, db: &Database) -> usize { |
| 567 | - let mut result = db.query(sql).await.unwrap().check().unwrap(); | |
| 568 | - result.take::<Vec<RecordId>>(0).unwrap().len() | |
| 573 | + sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!( | |
| 574 | + "SELECT count(*) FROM ({sql}) AS t" | |
| 575 | + ))) | |
| 576 | + .fetch_one(db) | |
| 577 | + .await | |
| 578 | + .unwrap() as usize | |
| 569 | 579 | } |
| 570 | 580 | |
| 571 | 581 | /// The invariant on the create path: the claim and the row it accounts for |
| @@ -574,7 +584,7 @@ mod tests { | ||
| 574 | 584 | /// guard reads that count, so a stray one makes it undeletable forever). |
| 575 | 585 | #[tokio::test] |
| 576 | 586 | async fn a_refused_create_writes_neither_row_nor_count() { |
| 577 | - let db = crate::database::init_mem().await.unwrap(); | |
| 587 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 578 | 588 | let subject = a_subject("algebra", &db).await; |
| 579 | 589 | let id = subject.get_id().clone(); |
| 580 | 590 | crate::db::subject::delete(&db, subject).await.unwrap(); |
| @@ -593,12 +603,12 @@ mod tests { | ||
| 593 | 603 | .expect_err("a subject that is gone must not be taggable"); |
| 594 | 604 | assert!(error.to_string().contains("subject does not exist")); |
| 595 | 605 | assert_eq!( |
| 596 | - rows("SELECT VALUE id FROM homework", &db).await, | |
| 606 | + rows("SELECT id FROM homework", &db).await, | |
| 597 | 607 | 0, |
| 598 | 608 | "a refused create may write no row" |
| 599 | 609 | ); |
| 600 | 610 | assert_eq!( |
| 601 | - rows("SELECT VALUE id FROM subject", &db).await, | |
| 611 | + rows("SELECT id FROM subject", &db).await, | |
| 602 | 612 | 0, |
| 603 | 613 | "…and least of all a count on a subject it just brought back" |
| 604 | 614 | ); |
| @@ -608,7 +618,7 @@ mod tests { | ||
| 608 | 618 | /// claim and the old one's release with the link itself. |
| 609 | 619 | #[tokio::test] |
| 610 | 620 | async fn a_subject_move_moves_the_count() { |
| 611 | - let db = crate::database::init_mem().await.unwrap(); | |
| 621 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 612 | 622 | let from = a_subject("algebra", &db).await; |
| 613 | 623 | let to = a_subject("geometry", &db).await; |
| 614 | 624 | let homework = homework_on(from.get_id(), &db).await; |
| @@ -647,7 +657,7 @@ mod tests { | ||
| 647 | 657 | /// keeps its tag and both counters read as if nothing ran. |
| 648 | 658 | #[tokio::test] |
| 649 | 659 | async fn a_move_to_a_dead_subject_leaves_everything_untouched() { |
| 650 | - let db = crate::database::init_mem().await.unwrap(); | |
| 660 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 651 | 661 | let from = a_subject("algebra", &db).await; |
| 652 | 662 | let dead = a_subject("geometry", &db).await; |
| 653 | 663 | let gone = dead.get_id().clone(); |
| @@ -674,7 +684,7 @@ mod tests { | ||
| 674 | 684 | "the release rolled back with the claim" |
| 675 | 685 | ); |
| 676 | 686 | assert_eq!( |
| 677 | - rows("SELECT VALUE id FROM subject", &db).await, | |
| 687 | + rows("SELECT id FROM subject", &db).await, | |
| 678 | 688 | 1, |
| 679 | 689 | "the dead subject was not brought back by a count" |
| 680 | 690 | ); |
| @@ -690,7 +700,7 @@ mod tests { | ||
| 690 | 700 | /// outright, and the counts must read as if it never ran. |
| 691 | 701 | #[tokio::test] |
| 692 | 702 | async fn a_stale_mover_is_refused_and_claims_nothing() { |
| 693 | - let db = crate::database::init_mem().await.unwrap(); | |
| 703 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 694 | 704 | let from = a_subject("algebra", &db).await; |
| 695 | 705 | let to = a_subject("geometry", &db).await; |
| 696 | 706 | let other = a_subject("calculus", &db).await; |
| @@ -744,7 +754,7 @@ mod tests { | ||
| 744 | 754 | /// *carrying* the column instead, which is why this is refused. |
| 745 | 755 | #[tokio::test] |
| 746 | 756 | async fn a_stale_re_stater_is_refused_and_reverts_nothing() { |
| 747 | - let db = crate::database::init_mem().await.unwrap(); | |
| 757 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 748 | 758 | let from = a_subject("algebra", &db).await; |
| 749 | 759 | let to = a_subject("geometry", &db).await; |
| 750 | 760 | let homework = homework_on(from.get_id(), &db).await; |
src/db/homework_file.rsmodified+38 -19
| @@ -301,12 +301,36 @@ mod tests { | ||
| 301 | 301 | None, |
| 302 | 302 | crate::domain::timestamp::Timestamp::from_millis(1), |
| 303 | 303 | None, |
| 304 | - &UserId::from_key("teacher"), | |
| 304 | + &a_teacher(db).await, | |
| 305 | 305 | ) |
| 306 | 306 | .await |
| 307 | 307 | .unwrap() |
| 308 | 308 | } |
| 309 | 309 | |
| 310 | + /// A real `app_user` row: submitters are foreign keys too. | |
| 311 | + async fn a_student(db: &Database) -> UserId { | |
| 312 | + let user = UserId::generate(); | |
| 313 | + sqlx::query("INSERT INTO app_user (id, username, password_hash, role) VALUES ($1, $2, 'x', 'student')") | |
| 314 | + .bind(user.uuid()) | |
| 315 | + .bind(format!("s-{}", &user.key()[..8])) | |
| 316 | + .execute(db) | |
| 317 | + .await | |
| 318 | + .unwrap(); | |
| 319 | + user | |
| 320 | + } | |
| 321 | + | |
| 322 | + /// A real `app_user` row: creators and submitters are foreign keys now. | |
| 323 | + async fn a_teacher(db: &Database) -> UserId { | |
| 324 | + let user = UserId::generate(); | |
| 325 | + sqlx::query("INSERT INTO app_user (id, username, password_hash, role) VALUES ($1, $2, 'x', 'teacher')") | |
| 326 | + .bind(user.uuid()) | |
| 327 | + .bind(format!("t-{}", &user.key()[..8])) | |
| 328 | + .execute(db) | |
| 329 | + .await | |
| 330 | + .unwrap(); | |
| 331 | + user | |
| 332 | + } | |
| 333 | + | |
| 310 | 334 | fn a_file(submission: &HomeworkSubmissionId) -> HomeworkFile { |
| 311 | 335 | HomeworkFile::new( |
| 312 | 336 | submission, |
| @@ -319,32 +343,27 @@ mod tests { | ||
| 319 | 343 | /// The counter as *stored* — the only witness that the seat and the row |
| 320 | 344 | /// moved together, since every other read counts the rows themselves. |
| 321 | 345 | async fn stored_count(submission: &HomeworkSubmissionId, db: &Database) -> i64 { |
| 322 | - db.query("SELECT VALUE file_count FROM $sub") | |
| 323 | - .bind(("sub", submission.record())) | |
| 346 | + sqlx::query("SELECT file_count FROM homework_submission WHERE id = $1") | |
| 347 | + .bind(submission.uuid()) | |
| 348 | + .fetch_one(db) | |
| 324 | 349 | .await |
| 325 | 350 | .unwrap() |
| 326 | - .take::<Vec<i64>>(0) | |
| 351 | + .try_get::<i64, _>(0) | |
| 327 | 352 | .unwrap() |
| 328 | - .into_iter() | |
| 329 | - .next() | |
| 330 | - .unwrap_or(0) | |
| 331 | 353 | } |
| 332 | 354 | #[tokio::test] |
| 333 | 355 | async fn rows_scope_to_their_submission_gc_and_cap() { |
| 334 | - let db = crate::database::init_mem().await.unwrap(); | |
| 356 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 335 | 357 | let hw = a_homework(&db).await; |
| 336 | 358 | let homework = hw.get_id().clone(); |
| 337 | - let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); | |
| 359 | + let user = a_student(&db).await; | |
| 338 | 360 | // A real submission row, so the GC join through it resolves. |
| 339 | - let submission = crate::db::homework_submission::upsert(&db, &hw, &user, None) | |
| 361 | + let (submission, _) = crate::db::homework_submission::upsert(&db, &hw, &user, None, false) | |
| 340 | 362 | .await |
| 341 | 363 | .unwrap() |
| 342 | 364 | .unwrap(); |
| 343 | 365 | let sub_a = submission.get_id().clone(); |
| 344 | - let sub_b = HomeworkSubmissionId::composite( | |
| 345 | - &homework, | |
| 346 | - &UserId::from_key("01TESTUSERBBBBBBBBBBBBBBBB"), | |
| 347 | - ); | |
| 366 | + let sub_b = HomeworkSubmissionId::generate(); | |
| 348 | 367 | |
| 349 | 368 | let stored = insert(&db, a_file(&sub_a)).await.unwrap().unwrap(); |
| 350 | 369 | // Readable under its own submission, invisible under another. |
| @@ -380,7 +399,7 @@ mod tests { | ||
| 380 | 399 | read_in_homework( |
| 381 | 400 | &db, |
| 382 | 401 | stored.get_id(), |
| 383 | - &HomeworkId::from_key("01TESTHWBBBBBBBBBBBBBBBBBB"), | |
| 402 | + &HomeworkId::from_key("019732e3-7b00-7000-8000-00000000ebbe"), | |
| 384 | 403 | ) |
| 385 | 404 | .await |
| 386 | 405 | .unwrap() |
| @@ -422,11 +441,11 @@ mod tests { | ||
| 422 | 441 | use crate::db::homework_result; |
| 423 | 442 | use crate::domain::homework_result::HomeworkStatus; |
| 424 | 443 | |
| 425 | - let db = crate::database::init_mem().await.unwrap(); | |
| 444 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 426 | 445 | let hw = a_homework(&db).await; |
| 427 | 446 | let homework = hw.get_id().clone(); |
| 428 | - let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); | |
| 429 | - let submission = crate::db::homework_submission::upsert(&db, &hw, &user, None) | |
| 447 | + let user = a_student(&db).await; | |
| 448 | + let (submission, _) = crate::db::homework_submission::upsert(&db, &hw, &user, None, false) | |
| 430 | 449 | .await |
| 431 | 450 | .unwrap() |
| 432 | 451 | .unwrap(); |
| @@ -439,7 +458,7 @@ mod tests { | ||
| 439 | 458 | &user, |
| 440 | 459 | HomeworkStatus::try_new("done").unwrap(), |
| 441 | 460 | None, |
| 442 | - &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"), | |
| 461 | + &UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"), | |
| 443 | 462 | ) |
| 444 | 463 | .await |
| 445 | 464 | .unwrap(); |
src/db/homework_result.rsmodified+60 -42
| @@ -241,6 +241,21 @@ pub async fn remove( | ||
| 241 | 241 | if alive.is_none() { |
| 242 | 242 | return Ok(None); |
| 243 | 243 | } |
| 244 | + // The stamp clears *before* the delete: the submission's | |
| 245 | + // `graded_by_result` FK points at the grade row (`NO ACTION`), so the | |
| 246 | + // delete must not run while it stands. The subselect scopes the clear | |
| 247 | + // to *this* pair's grade id — it can never wipe a stamp a concurrent | |
| 248 | + // re-grade has just written (none can interleave: the homework row is | |
| 249 | + // locked above). | |
| 250 | + sqlx::query!( | |
| 251 | + r#"UPDATE homework_submission SET graded_by_result = NULL | |
| 252 | + WHERE homework = $1 AND app_user = $2 AND graded_by_result IN ( | |
| 253 | + SELECT id FROM homework_result WHERE homework = $1 AND app_user = $2)"#, | |
| 254 | + homework.uuid(), | |
| 255 | + user.uuid() | |
| 256 | + ) | |
| 257 | + .execute(&mut *tx) | |
| 258 | + .await?; | |
| 244 | 259 | let gone = sqlx::query!( |
| 245 | 260 | r#"DELETE FROM homework_result WHERE homework = $1 AND app_user = $2 |
| 246 | 261 | RETURNING id AS "id: HomeworkResultId", |
| @@ -258,15 +273,6 @@ pub async fn remove( | ||
| 258 | 273 | let Some(removed) = gone else { |
| 259 | 274 | return Ok(None); |
| 260 | 275 | }; |
| 261 | - sqlx::query!( | |
| 262 | - r#"UPDATE homework_submission SET graded_by_result = NULL | |
| 263 | - WHERE homework = $1 AND app_user = $2 AND graded_by_result = $3"#, | |
| 264 | - homework.uuid(), | |
| 265 | - user.uuid(), | |
| 266 | - removed.id.uuid() | |
| 267 | - ) | |
| 268 | - .execute(&mut *tx) | |
| 269 | - .await?; | |
| 270 | 276 | sqlx::query!( |
| 271 | 277 | "UPDATE app_user SET marks_given_total = GREATEST(marks_given_total - 1, 0) WHERE id = $1", |
| 272 | 278 | removed.graded_by.uuid() |
| @@ -325,10 +331,10 @@ mod tests { | ||
| 325 | 331 | |
| 326 | 332 | #[tokio::test] |
| 327 | 333 | async fn grade_upserts_one_row_per_pair_and_remove_unfreezes() { |
| 328 | - let db = crate::database::init_mem().await.unwrap(); | |
| 334 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 329 | 335 | let homework = a_homework(&db).await; |
| 330 | - let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); | |
| 331 | - let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); | |
| 336 | + let user = UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa"); | |
| 337 | + let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); | |
| 332 | 338 | |
| 333 | 339 | let first = grade( |
| 334 | 340 | &db, |
| @@ -366,17 +372,27 @@ mod tests { | ||
| 366 | 372 | /// touched at all — a homework grade is not a homework submission. |
| 367 | 373 | #[tokio::test] |
| 368 | 374 | async fn a_first_grade_credits_the_grader_and_a_regrade_does_not() { |
| 369 | - let db = crate::database::init_mem().await.unwrap(); | |
| 375 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 370 | 376 | let homework = a_homework(&db).await; |
| 371 | - let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); | |
| 372 | - let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); | |
| 377 | + let user = UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa"); | |
| 378 | + let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); | |
| 373 | 379 | // `UPDATE` writes nothing to a user row that does not exist. |
| 374 | - db.query("CREATE $usr SET username = 't', password_hash = 'x'") | |
| 375 | - .bind(("usr", teacher.record())) | |
| 376 | - .await | |
| 377 | - .unwrap() | |
| 378 | - .check() | |
| 379 | - .unwrap(); | |
| 380 | + sqlx::query( | |
| 381 | + "INSERT INTO app_user (id, username, password_hash, role) \ | |
| 382 | + VALUES ($1, 't', 'x', 'teacher') ON CONFLICT (id) DO NOTHING", | |
| 383 | + ) | |
| 384 | + .bind(teacher.uuid()) | |
| 385 | + .execute(&db) | |
| 386 | + .await | |
| 387 | + .unwrap(); | |
| 388 | + sqlx::query( | |
| 389 | + "INSERT INTO app_user (id, username, password_hash, role) \ | |
| 390 | + VALUES ($1, 'ali', 'x', 'student') ON CONFLICT (id) DO NOTHING", | |
| 391 | + ) | |
| 392 | + .bind(user.uuid()) | |
| 393 | + .execute(&db) | |
| 394 | + .await | |
| 395 | + .unwrap(); | |
| 380 | 396 | |
| 381 | 397 | for status in ["incomplete", "done"] { |
| 382 | 398 | grade( |
| @@ -403,16 +419,26 @@ mod tests { | ||
| 403 | 419 | /// mark given, with no exam, no mark and no submission behind them. |
| 404 | 420 | #[tokio::test] |
| 405 | 421 | async fn ungrading_gives_the_grader_credit_back() { |
| 406 | - let db = crate::database::init_mem().await.unwrap(); | |
| 422 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 407 | 423 | let homework = a_homework(&db).await; |
| 408 | - let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); | |
| 409 | - let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); | |
| 410 | - db.query("CREATE $usr SET username = 't', password_hash = 'x'") | |
| 411 | - .bind(("usr", teacher.record())) | |
| 412 | - .await | |
| 413 | - .unwrap() | |
| 414 | - .check() | |
| 415 | - .unwrap(); | |
| 424 | + let user = UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa"); | |
| 425 | + let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); | |
| 426 | + sqlx::query( | |
| 427 | + "INSERT INTO app_user (id, username, password_hash, role) \ | |
| 428 | + VALUES ($1, 't', 'x', 'teacher') ON CONFLICT (id) DO NOTHING", | |
| 429 | + ) | |
| 430 | + .bind(teacher.uuid()) | |
| 431 | + .execute(&db) | |
| 432 | + .await | |
| 433 | + .unwrap(); | |
| 434 | + sqlx::query( | |
| 435 | + "INSERT INTO app_user (id, username, password_hash, role) \ | |
| 436 | + VALUES ($1, 'ali', 'x', 'student') ON CONFLICT (id) DO NOTHING", | |
| 437 | + ) | |
| 438 | + .bind(user.uuid()) | |
| 439 | + .execute(&db) | |
| 440 | + .await | |
| 441 | + .unwrap(); | |
| 416 | 442 | |
| 417 | 443 | for _ in 0..3 { |
| 418 | 444 | grade( |
| @@ -439,20 +465,12 @@ mod tests { | ||
| 439 | 465 | } |
| 440 | 466 | /// The grader's badge counter, re-read out of the store. |
| 441 | 467 | async fn marks_given(user: &UserId, db: &Database) -> i64 { |
| 442 | - let mut result = db | |
| 443 | - .query(format!( | |
| 444 | - "SELECT VALUE ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) FROM $usr" | |
| 445 | - )) | |
| 446 | - .bind(("usr", user.record())) | |
| 468 | + sqlx::query("SELECT marks_given_total FROM app_user WHERE id = $1") | |
| 469 | + .bind(user.uuid()) | |
| 470 | + .fetch_one(db) | |
| 447 | 471 | .await |
| 448 | 472 | .unwrap() |
| 449 | - .check() | |
| 450 | - .unwrap(); | |
| 451 | - result | |
| 452 | - .take::<Vec<i64>>(0) | |
| 473 | + .try_get::<i64, _>(0) | |
| 453 | 474 | .unwrap() |
| 454 | - .into_iter() | |
| 455 | - .next() | |
| 456 | - .unwrap_or(0) | |
| 457 | 475 | } |
| 458 | 476 | } |
src/db/homework_submission.rsmodified+95 -62
| @@ -309,21 +309,30 @@ pub async fn delete( | ||
| 309 | 309 | .fetch_optional(&mut *tx) |
| 310 | 310 | .await? |
| 311 | 311 | .map(|row| row.due_at); |
| 312 | - let gone = sqlx::query!( | |
| 313 | - r#"DELETE FROM homework_submission | |
| 312 | + // The gate runs as a lock-taking read, not a delete: the file rows | |
| 313 | + // must die BEFORE the submission row (their `submission` FK is | |
| 314 | + // `NO ACTION`), and that wipe is only honest if this delete has | |
| 315 | + // already won — so the open-not-frozen verdict and the row lock come | |
| 316 | + // first, files second, the submission row last. A rival withdrawal | |
| 317 | + // that beat us removed the row under its own lock; a grade that | |
| 318 | + // stamped it holds the homework lock first — either way `None`, one | |
| 319 | + // refusal as before. | |
| 320 | + let target = sqlx::query!( | |
| 321 | + r#"SELECT id AS "id: HomeworkSubmissionId", | |
| 322 | + homework AS "homework: HomeworkId", | |
| 323 | + app_user AS "user: UserId", | |
| 324 | + text AS "text: SubmissionText", | |
| 325 | + submitted_at AS "submitted_at: Timestamp", | |
| 326 | + updated_at AS "updated_at: Timestamp", | |
| 327 | + counted_on_time AS "counted_on_time: bool" | |
| 328 | + FROM homework_submission | |
| 314 | 329 | WHERE id = $1 AND graded_by_result IS NULL |
| 315 | - RETURNING id AS "id: HomeworkSubmissionId", | |
| 316 | - homework AS "homework: HomeworkId", | |
| 317 | - app_user AS "user: UserId", | |
| 318 | - text AS "text: SubmissionText", | |
| 319 | - submitted_at AS "submitted_at: Timestamp", | |
| 320 | - updated_at AS "updated_at: Timestamp", | |
| 321 | - counted_on_time AS "counted_on_time: bool""#, | |
| 330 | + FOR UPDATE"#, | |
| 322 | 331 | submission.get_id().uuid() |
| 323 | 332 | ) |
| 324 | 333 | .fetch_optional(&mut *tx) |
| 325 | 334 | .await?; |
| 326 | - let Some(removed) = gone else { | |
| 335 | + let Some(removed) = target else { | |
| 327 | 336 | // Frozen, or already withdrawn by a rival — one refusal, as |
| 328 | 337 | // before. |
| 329 | 338 | return Ok(None); |
| @@ -334,6 +343,12 @@ pub async fn delete( | ||
| 334 | 343 | ) |
| 335 | 344 | .execute(&mut *tx) |
| 336 | 345 | .await?; |
| 346 | + sqlx::query!( | |
| 347 | + "DELETE FROM homework_submission WHERE id = $1", | |
| 348 | + removed.id.uuid() | |
| 349 | + ) | |
| 350 | + .execute(&mut *tx) | |
| 351 | + .await?; | |
| 337 | 352 | let judged_on_time = due.map(|d| removed.submitted_at <= d).unwrap_or(false); |
| 338 | 353 | let on_time = i64::from(removed.counted_on_time.unwrap_or(judged_on_time)); |
| 339 | 354 | sqlx::query!( |
| @@ -361,9 +376,8 @@ pub async fn delete( | ||
| 361 | 376 | #[cfg(test)] |
| 362 | 377 | mod tests { |
| 363 | 378 | use super::*; |
| 364 | - use crate::constant::{ | |
| 365 | - HOMEWORK_ON_TIME_TOTAL_FIELD as ON_TIME, HOMEWORK_SUBMITTED_TOTAL_FIELD as SUBMITTED, | |
| 366 | - }; | |
| 379 | + use sqlx::Row as _; | |
| 380 | + | |
| 367 | 381 | use crate::db::homework as homework_db; |
| 368 | 382 | use crate::domain::homework::HomeworkTitle; |
| 369 | 383 | use crate::domain::subject::{SubjectDescription, SubjectName}; |
| @@ -436,19 +450,13 @@ mod tests { | ||
| 436 | 450 | /// The verdict `upsert` stored on the row — what `delete` debits off. |
| 437 | 451 | /// `None` is a row from before the column existed. |
| 438 | 452 | async fn stored_verdict(id: &HomeworkSubmissionId, db: &Database) -> Option<bool> { |
| 439 | - let mut result = db | |
| 440 | - .query("SELECT VALUE counted_on_time FROM $sub") | |
| 441 | - .bind(("sub", id.record())) | |
| 453 | + let row = sqlx::query("SELECT counted_on_time FROM homework_submission WHERE id = $1") | |
| 454 | + .bind(id.uuid()) | |
| 455 | + .fetch_optional(db) | |
| 442 | 456 | .await |
| 443 | 457 | .unwrap() |
| 444 | - .check() | |
| 445 | - .unwrap(); | |
| 446 | - result | |
| 447 | - .take::<Vec<Option<bool>>>(0) | |
| 448 | - .unwrap() | |
| 449 | - .into_iter() | |
| 450 | - .flatten() | |
| 451 | - .next() | |
| 458 | + .expect("the submission row exists"); | |
| 459 | + row.try_get::<Option<bool>, _>(0).unwrap() | |
| 452 | 460 | } |
| 453 | 461 | |
| 454 | 462 | /// The web layer's computed flag, exactly as `SubmissionResponse::new` |
| @@ -464,41 +472,42 @@ mod tests { | ||
| 464 | 472 | |
| 465 | 473 | /// The two badge counters on a user row, absent counting as zero. |
| 466 | 474 | async fn counters(user: &UserId, db: &Database) -> (i64, i64) { |
| 467 | - let mut result = db | |
| 468 | - .query(format!( | |
| 469 | - "SELECT VALUE [({SUBMITTED} ?? 0), ({ON_TIME} ?? 0)] FROM $usr" | |
| 470 | - )) | |
| 471 | - .bind(("usr", user.record())) | |
| 472 | - .await | |
| 473 | - .unwrap() | |
| 474 | - .check() | |
| 475 | - .unwrap(); | |
| 476 | - let rows = result.take::<Vec<Vec<i64>>>(0).unwrap(); | |
| 477 | - let row = rows.first().cloned().unwrap_or_default(); | |
| 475 | + let row = sqlx::query( | |
| 476 | + "SELECT homework_submitted_total, homework_on_time_total \ | |
| 477 | + FROM app_user WHERE id = $1", | |
| 478 | + ) | |
| 479 | + .bind(user.uuid()) | |
| 480 | + .fetch_one(db) | |
| 481 | + .await | |
| 482 | + .unwrap(); | |
| 478 | 483 | ( |
| 479 | - row.first().copied().unwrap_or(0), | |
| 480 | - row.get(1).copied().unwrap_or(0), | |
| 484 | + row.try_get::<i64, _>(0).unwrap(), | |
| 485 | + row.try_get::<i64, _>(1).unwrap(), | |
| 481 | 486 | ) |
| 482 | 487 | } |
| 483 | 488 | |
| 484 | 489 | #[tokio::test] |
| 485 | 490 | async fn resubmit_keeps_submitted_at_and_restamps_updated_at() { |
| 486 | - let db = crate::database::init_mem().await.unwrap(); | |
| 491 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 487 | 492 | let homework = a_homework(far_future(), &db).await; |
| 488 | 493 | let user = a_student("ogrenci", &db).await; |
| 489 | 494 | |
| 490 | - let first = upsert( | |
| 495 | + let (first, _) = upsert( | |
| 491 | 496 | &db, |
| 492 | 497 | &homework, |
| 493 | 498 | &user, |
| 494 | 499 | Some(SubmissionText::try_new("draft").unwrap()), |
| 500 | + false, | |
| 495 | 501 | ) |
| 496 | 502 | .await |
| 497 | 503 | .unwrap() |
| 498 | 504 | .unwrap(); |
| 499 | 505 | // A re-submit lands on the same row: submitted_at (the first hand-in) |
| 500 | 506 | // pinned, updated_at moves forward, and the text can be cleared. |
| 501 | - let second = upsert(&db, &homework, &user, None).await.unwrap().unwrap(); | |
| 507 | + let (second, _) = upsert(&db, &homework, &user, None, false) | |
| 508 | + .await | |
| 509 | + .unwrap() | |
| 510 | + .unwrap(); | |
| 502 | 511 | // ... and it is one submission, not two: the edit moves no counter. |
| 503 | 512 | assert_eq!(counters(&user, &db).await, (1, 1)); |
| 504 | 513 | assert_eq!(first.get_id(), second.get_id()); |
| @@ -529,16 +538,16 @@ mod tests { | ||
| 529 | 538 | use crate::db::homework_result; |
| 530 | 539 | use crate::domain::homework_result::HomeworkStatus; |
| 531 | 540 | |
| 532 | - let db = crate::database::init_mem().await.unwrap(); | |
| 541 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 533 | 542 | let homework = a_homework(far_future(), &db).await; |
| 534 | 543 | let user = a_student("ogrenci", &db).await; |
| 535 | - let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); | |
| 544 | + let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); | |
| 536 | 545 | let graded = |value| { |
| 537 | 546 | let text = SubmissionText::try_new(value).unwrap(); |
| 538 | - upsert(&db, &homework, &user, Some(text)) | |
| 547 | + upsert(&db, &homework, &user, Some(text), false) | |
| 539 | 548 | }; |
| 540 | 549 | |
| 541 | - let version_a = graded("version A").await.unwrap().unwrap(); | |
| 550 | + let (version_a, _) = graded("version A").await.unwrap().unwrap(); | |
| 542 | 551 | assert!(!is_graded(&db, version_a.get_id()).await.unwrap()); |
| 543 | 552 | |
| 544 | 553 | assert_eq!(counters(&user, &db).await, (1, 1)); |
| @@ -589,7 +598,7 @@ mod tests { | ||
| 589 | 598 | .await |
| 590 | 599 | .unwrap(); |
| 591 | 600 | assert!(!is_graded(&db, version_a.get_id()).await.unwrap()); |
| 592 | - let reopened = graded("version B").await.unwrap().unwrap(); | |
| 601 | + let (reopened, _) = graded("version B").await.unwrap().unwrap(); | |
| 593 | 602 | assert_eq!( |
| 594 | 603 | reopened.get_text().map(SubmissionText::as_str), |
| 595 | 604 | Some("version B") |
| @@ -604,15 +613,16 @@ mod tests { | ||
| 604 | 613 | |
| 605 | 614 | #[tokio::test] |
| 606 | 615 | async fn touch_moves_updated_at_but_not_submitted_at_or_text() { |
| 607 | - let db = crate::database::init_mem().await.unwrap(); | |
| 616 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 608 | 617 | let homework = a_homework(far_future(), &db).await; |
| 609 | 618 | let user = a_student("ogrenci", &db).await; |
| 610 | 619 | |
| 611 | - let original = upsert( | |
| 620 | + let (original, _) = upsert( | |
| 612 | 621 | &db, |
| 613 | 622 | &homework, |
| 614 | 623 | &user, |
| 615 | 624 | Some(SubmissionText::try_new("photo answer").unwrap()), |
| 625 | + false, | |
| 616 | 626 | ) |
| 617 | 627 | .await |
| 618 | 628 | .unwrap() |
| @@ -636,11 +646,14 @@ mod tests { | ||
| 636 | 646 | /// and the last assertion reads `(2, 2)` — the farm. |
| 637 | 647 | #[tokio::test] |
| 638 | 648 | async fn submit_delete_submit_is_worth_one_submission() { |
| 639 | - let db = crate::database::init_mem().await.unwrap(); | |
| 649 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 640 | 650 | let homework = a_homework(far_future(), &db).await; |
| 641 | 651 | let user = a_student("ogrenci", &db).await; |
| 642 | 652 | |
| 643 | - upsert(&db, &homework, &user, None).await.unwrap().unwrap(); | |
| 653 | + upsert(&db, &homework, &user, None, false) | |
| 654 | + .await | |
| 655 | + .unwrap() | |
| 656 | + .unwrap(); | |
| 644 | 657 | assert_eq!(counters(&user, &db).await, (1, 1)); |
| 645 | 658 | |
| 646 | 659 | let mine = read_for(&db, homework.get_id(), &user) |
| @@ -658,7 +671,10 @@ mod tests { | ||
| 658 | 671 | .is_none() |
| 659 | 672 | ); |
| 660 | 673 | |
| 661 | - upsert(&db, &homework, &user, None).await.unwrap().unwrap(); | |
| 674 | + upsert(&db, &homework, &user, None, false) | |
| 675 | + .await | |
| 676 | + .unwrap() | |
| 677 | + .unwrap(); | |
| 662 | 678 | assert_eq!(counters(&user, &db).await, (1, 1)); |
| 663 | 679 | } |
| 664 | 680 | |
| @@ -668,13 +684,19 @@ mod tests { | ||
| 668 | 684 | /// what it took. |
| 669 | 685 | #[tokio::test] |
| 670 | 686 | async fn a_late_submission_counts_as_submitted_but_not_on_time() { |
| 671 | - let db = crate::database::init_mem().await.unwrap(); | |
| 687 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 672 | 688 | let punctual = a_homework(far_future(), &db).await; |
| 673 | 689 | let overdue = a_homework(Timestamp::from_millis(1), &db).await; |
| 674 | 690 | let user = a_student("ogrenci", &db).await; |
| 675 | 691 | |
| 676 | - upsert(&db, &punctual, &user, None).await.unwrap().unwrap(); | |
| 677 | - upsert(&db, &overdue, &user, None).await.unwrap().unwrap(); | |
| 692 | + upsert(&db, &punctual, &user, None, false) | |
| 693 | + .await | |
| 694 | + .unwrap() | |
| 695 | + .unwrap(); | |
| 696 | + upsert(&db, &overdue, &user, None, false) | |
| 697 | + .await | |
| 698 | + .unwrap() | |
| 699 | + .unwrap(); | |
| 678 | 700 | assert_eq!(counters(&user, &db).await, (2, 1)); |
| 679 | 701 | |
| 680 | 702 | // Withdrawing the *late* one takes back only the submission, never the |
| @@ -707,20 +729,25 @@ mod tests { | ||
| 707 | 729 | /// to prevent. |
| 708 | 730 | #[tokio::test] |
| 709 | 731 | async fn a_row_with_no_stored_verdict_falls_back_to_the_deadline() { |
| 710 | - let db = crate::database::init_mem().await.unwrap(); | |
| 732 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 711 | 733 | let punctual = a_homework(far_future(), &db).await; |
| 712 | 734 | let overdue = a_homework(Timestamp::from_millis(1), &db).await; |
| 713 | 735 | let user = a_student("ogrenci", &db).await; |
| 714 | 736 | |
| 715 | - upsert(&db, &punctual, &user, None).await.unwrap().unwrap(); | |
| 716 | - upsert(&db, &overdue, &user, None).await.unwrap().unwrap(); | |
| 737 | + upsert(&db, &punctual, &user, None, false) | |
| 738 | + .await | |
| 739 | + .unwrap() | |
| 740 | + .unwrap(); | |
| 741 | + upsert(&db, &overdue, &user, None, false) | |
| 742 | + .await | |
| 743 | + .unwrap() | |
| 744 | + .unwrap(); | |
| 717 | 745 | assert_eq!(counters(&user, &db).await, (2, 1)); |
| 718 | 746 | // Aged into legacy rows: the counters keep the credit, the rows lose the |
| 719 | 747 | // verdict — the exact state of every submission on an existing volume. |
| 720 | - db.query("UPDATE homework_submission UNSET counted_on_time") | |
| 748 | + sqlx::query("UPDATE homework_submission SET counted_on_time = NULL") | |
| 749 | + .execute(&db) | |
| 721 | 750 | .await |
| 722 | - .unwrap() | |
| 723 | - .check() | |
| 724 | 751 | .unwrap(); |
| 725 | 752 | |
| 726 | 753 | let late = read_for(&db, overdue.get_id(), &user) |
| @@ -752,14 +779,17 @@ mod tests { | ||
| 752 | 779 | /// stored `true` against a live `late = true`. |
| 753 | 780 | #[tokio::test] |
| 754 | 781 | async fn a_deadline_moved_under_the_caller_is_judged_by_the_stored_value() { |
| 755 | - let db = crate::database::init_mem().await.unwrap(); | |
| 782 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 756 | 783 | let user = a_student("ogrenci", &db).await; |
| 757 | 784 | |
| 758 | 785 | // Extended at 23:59: the snapshot says the deadline has passed, the |
| 759 | 786 | // store says it has not. A hand-in now is on time. |
| 760 | 787 | let extended = a_homework(Timestamp::from_millis(1), &db).await; |
| 761 | 788 | deadline_moves_to(&extended, far_future(), &db).await; |
| 762 | - let landed = upsert(&db, &extended, &user, None).await.unwrap().unwrap(); | |
| 789 | + let (landed, _) = upsert(&db, &extended, &user, None, false) | |
| 790 | + .await | |
| 791 | + .unwrap() | |
| 792 | + .unwrap(); | |
| 763 | 793 | assert_eq!(counters(&user, &db).await, (1, 1)); |
| 764 | 794 | assert_eq!(stored_verdict(landed.get_id(), &db).await, Some(true)); |
| 765 | 795 | assert!(!late_flag(&landed, &db).await); |
| @@ -768,7 +798,10 @@ mod tests { | ||
| 768 | 798 | // the deadline is gone. The same hand-in is late. |
| 769 | 799 | let pulled = a_homework(far_future(), &db).await; |
| 770 | 800 | deadline_moves_to(&pulled, Timestamp::from_millis(1), &db).await; |
| 771 | - let missed = upsert(&db, &pulled, &user, None).await.unwrap().unwrap(); | |
| 801 | + let (missed, _) = upsert(&db, &pulled, &user, None, false) | |
| 802 | + .await | |
| 803 | + .unwrap() | |
| 804 | + .unwrap(); | |
| 772 | 805 | assert_eq!(counters(&user, &db).await, (2, 1)); |
| 773 | 806 | assert_eq!(stored_verdict(missed.get_id(), &db).await, Some(false)); |
| 774 | 807 | assert!(late_flag(&missed, &db).await); |
src/db/meal_attendance.rsmodified+1 -1
| @@ -113,7 +113,7 @@ pub async fn list_for_student( | ||
| 113 | 113 | AND ($3::text IS NULL OR menu IN (SELECT id FROM menu WHERE date <= $3::text))", |
| 114 | 114 | "ORDER BY marked_at DESC, menu DESC", |
| 115 | 115 | ) |
| 116 | - .bind(student.key()) | |
| 116 | + .bind(student.uuid()) | |
| 117 | 117 | .bind(Param::OptText(from.map(|date| date.as_str().to_string()))) |
| 118 | 118 | .bind(Param::OptText(to.map(|date| date.as_str().to_string()))) |
| 119 | 119 | .run(limit, offset, db) |
src/db/meal_booking.rsmodified+34 -20
| @@ -368,7 +368,7 @@ pub async fn release_seat( | ||
| 368 | 368 | #[cfg(test)] |
| 369 | 369 | mod tests { |
| 370 | 370 | use super::*; |
| 371 | - use crate::database::init_mem; | |
| 371 | + use crate::database::init_test_db; | |
| 372 | 372 | use crate::db::cap; |
| 373 | 373 | use crate::db::meal_ledger; |
| 374 | 374 | use crate::db::menu; |
| @@ -387,14 +387,25 @@ mod tests { | ||
| 387 | 387 | } |
| 388 | 388 | |
| 389 | 389 | async fn menu_on(date: &str, capacity: Option<i64>) -> (Database, MenuId) { |
| 390 | - let db = init_mem().await.unwrap(); | |
| 390 | + let (db, _leases) = init_test_db().await; | |
| 391 | + // The menu's creator is a foreign key now: a real `app_user` row. | |
| 392 | + let creator = UserId::generate(); | |
| 393 | + sqlx::query( | |
| 394 | + "INSERT INTO app_user (id, username, password_hash, role) \ | |
| 395 | + VALUES ($1, $2, 'x', 'teacher')", | |
| 396 | + ) | |
| 397 | + .bind(creator.uuid()) | |
| 398 | + .bind(format!("menu-fixture-{}", &creator.key()[..8])) | |
| 399 | + .execute(&db) | |
| 400 | + .await | |
| 401 | + .unwrap(); | |
| 391 | 402 | let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()]; |
| 392 | 403 | let menu = menu::create( |
| 393 | 404 | &db, |
| 394 | 405 | MenuDate::try_new(date).unwrap(), |
| 395 | 406 | MenuSlot::try_new("lunch", &slots).unwrap(), |
| 396 | 407 | capacity, |
| 397 | - &UserId::generate(), | |
| 408 | + &creator, | |
| 398 | 409 | ) |
| 399 | 410 | .await |
| 400 | 411 | .unwrap(); |
| @@ -404,23 +415,20 @@ mod tests { | ||
| 404 | 415 | /// The stored counter, absent reading as zero — the number the cap's |
| 405 | 416 | /// `WHERE` actually compares, not one recomputed from the rows. |
| 406 | 417 | async fn seats(menu: &MenuId, db: &Database) -> i64 { |
| 407 | - let mut result = db | |
| 408 | - .query("SELECT VALUE seats_booked FROM $id") | |
| 409 | - .bind(("id", menu.record())) | |
| 418 | + use sqlx::Row as _; | |
| 419 | + | |
| 420 | + sqlx::query("SELECT COALESCE(seats_booked, 0) FROM menu WHERE id = $1") | |
| 421 | + .bind(menu.key()) | |
| 422 | + .fetch_one(db) | |
| 410 | 423 | .await |
| 411 | 424 | .unwrap() |
| 412 | - .check() | |
| 413 | - .unwrap(); | |
| 414 | - result | |
| 415 | - .take::<Vec<Option<i64>>>(0) | |
| 425 | + .try_get::<i64, _>(0) | |
| 416 | 426 | .unwrap() |
| 417 | - .into_iter() | |
| 418 | - .next() | |
| 419 | - .flatten() | |
| 420 | - .unwrap_or(0) | |
| 421 | 427 | } |
| 422 | 428 | |
| 423 | 429 | async fn add_dish(menu: &MenuId, price: i64, db: &Database) -> MenuDish { |
| 430 | + // A cap far above every seat count in these tests: the dish must never | |
| 431 | + // be the binding constraint here. | |
| 424 | 432 | menu_dish::create( |
| 425 | 433 | db, |
| 426 | 434 | menu, |
| @@ -428,6 +436,7 @@ mod tests { | ||
| 428 | 436 | None, |
| 429 | 437 | DishPrice::try_new(price).unwrap(), |
| 430 | 438 | DishTags::try_new(&[], &[]).unwrap(), |
| 439 | + 1_000, | |
| 431 | 440 | ) |
| 432 | 441 | .await |
| 433 | 442 | .unwrap() |
| @@ -445,7 +454,6 @@ mod tests { | ||
| 445 | 454 | // A dish lands: the price a booking read a moment ago is now stale. |
| 446 | 455 | add_dish(&menu, 1_000, &db).await; |
| 447 | 456 | let row = MealBooking { |
| 448 | - id: MealBookingId::composite(&menu, &ali), | |
| 449 | 457 | menu: menu.clone(), |
| 450 | 458 | student: ali.clone(), |
| 451 | 459 | booked_by: ali, |
| @@ -456,7 +464,7 @@ mod tests { | ||
| 456 | 464 | created_at: Timestamp::now(), |
| 457 | 465 | }; |
| 458 | 466 | let place = async |seen| { |
| 459 | - claim_and_place(&db, &menu.record(), cap::UNLIMITED, seen, &row, None, None) | |
| 467 | + claim_and_place(&db, &menu, cap::UNLIMITED, seen, &row, None, None) | |
| 460 | 468 | .await |
| 461 | 469 | .unwrap() |
| 462 | 470 | }; |
| @@ -466,7 +474,10 @@ mod tests { | ||
| 466 | 474 | ); |
| 467 | 475 | assert_eq!(seats(&menu, &db).await, 0, "and must write nothing"); |
| 468 | 476 | assert!( |
| 469 | - read(&db, row.get_id()).await.unwrap().is_none(), | |
| 477 | + read(&db, &MealBookingId::composite(&menu, row.get_student())) | |
| 478 | + .await | |
| 479 | + .unwrap() | |
| 480 | + .is_none(), | |
| 470 | 481 | "the refused transaction must not leave the row behind either" |
| 471 | 482 | ); |
| 472 | 483 | |
| @@ -555,7 +566,11 @@ mod tests { | ||
| 555 | 566 | "the attempt this call read is gone, so it releases nothing" |
| 556 | 567 | ); |
| 557 | 568 | // Stored state, not the returned value: the mem engine forges wins. |
| 558 | - let stored = read(&db, live.get_id()).await.unwrap().unwrap(); | |
| 569 | + let stored = | |
| 570 | + read(&db, &MealBookingId::composite(&menu, live.get_student())) | |
| 571 | + .await | |
| 572 | + .unwrap() | |
| 573 | + .unwrap(); | |
| 559 | 574 | assert_eq!(stored.get_status(), MealBookingStatus::Booked); |
| 560 | 575 | assert_eq!(stored.get_attempt(), live.get_attempt()); |
| 561 | 576 | assert_eq!(seats(&menu, &db).await, 1, "and gives no seat back"); |
| @@ -625,7 +640,6 @@ mod tests { | ||
| 625 | 640 | let price = meal_ledger::price_snapshot(&db, &menu).await.unwrap(); |
| 626 | 641 | let seen = menu::read(&db, &menu).await.unwrap().unwrap().get_version(); |
| 627 | 642 | let row = MealBooking { |
| 628 | - id: MealBookingId::composite(&menu, &ali), | |
| 629 | 643 | menu: menu.clone(), |
| 630 | 644 | student: ali.clone(), |
| 631 | 645 | booked_by: ali.clone(), |
| @@ -640,7 +654,7 @@ mod tests { | ||
| 640 | 654 | let place = async || { |
| 641 | 655 | claim_and_place( |
| 642 | 656 | &db, |
| 643 | - &menu.record(), | |
| 657 | + &menu, | |
| 644 | 658 | cap::UNLIMITED, |
| 645 | 659 | seen, |
| 646 | 660 | &row, |
src/db/meal_ledger.rsmodified+0 -43
| @@ -140,46 +140,3 @@ pub async fn balance_of(db: &Database, student: &UserId) -> Result<i64, AppError | ||
| 140 | 140 | .iter() |
| 141 | 141 | .fold(0i64, |sum, row| sum + row.kind.sign() * row.total)) |
| 142 | 142 | } |
| 143 | -#[cfg(test)] | |
| 144 | -mod tests { | |
| 145 | - use super::*; | |
| 146 | - | |
| 147 | - /// The balance aggregate **against a real server**, and `#[ignore]`d for | |
| 148 | - /// it: `init_mem`'s embedded engine is not the store this runs on, and an | |
| 149 | - /// aggregate is exactly where the two are known to differ — a `count()` | |
| 150 | - /// over an indexed field comes back `{count: N}` from the server and a | |
| 151 | - /// bare int from memory, and `student` here *is* indexed. This asserts the | |
| 152 | - /// `GROUP BY` really decodes into [`KindTotal`] and folds to the | |
| 153 | - /// documented figure, per kind, scoped to one student. | |
| 154 | - #[tokio::test] | |
| 155 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | |
| 156 | - async fn the_balance_aggregate_decodes_on_a_real_server() { | |
| 157 | - let (db, _serialized) = crate::database::init_test_server("meal_balance_sum").await; | |
| 158 | - db.query( | |
| 159 | - "CREATE meal_ledger:a SET student = user:ali, kind = 'credit', \ | |
| 160 | - amount_minor = 10000, recorded_by = user:adm, created_at = 1; | |
| 161 | - CREATE meal_ledger:b SET student = user:ali, kind = 'charge', \ | |
| 162 | - amount_minor = 4500, recorded_by = user:adm, created_at = 2; | |
| 163 | - CREATE meal_ledger:c SET student = user:ali, kind = 'charge', \ | |
| 164 | - amount_minor = 1500, recorded_by = user:adm, created_at = 3; | |
| 165 | - CREATE meal_ledger:d SET student = user:ali, kind = 'reversal', \ | |
| 166 | - amount_minor = 4500, recorded_by = user:adm, created_at = 4; | |
| 167 | - CREATE meal_ledger:e SET student = user:veli, kind = 'credit', \ | |
| 168 | - amount_minor = 777, recorded_by = user:adm, created_at = 5;", | |
| 169 | - ) | |
| 170 | - .await | |
| 171 | - .unwrap() | |
| 172 | - .check() | |
| 173 | - .unwrap(); | |
| 174 | - let ali = UserId::from_key("ali"); | |
| 175 | - assert_eq!( | |
| 176 | - balance_of(&db, &ali).await.unwrap(), | |
| 177 | - 10_000 - 4_500 - 1_500 + 4_500 | |
| 178 | - ); | |
| 179 | - // Somebody with no lines at all: no groups come back, not an error. | |
| 180 | - assert_eq!( | |
| 181 | - balance_of(&db, &UserId::from_key("nobody")).await.unwrap(), | |
| 182 | - 0 | |
| 183 | - ); | |
| 184 | - } | |
| 185 | -} |
src/db/menu.rsmodified+95 -80
| @@ -187,11 +187,16 @@ pub async fn update( | ||
| 187 | 187 | /// no meaning without its menu, and the menu key cannot be re-homed. |
| 188 | 188 | /// |
| 189 | 189 | /// Refused (409) while a seat is still held, and the *row itself* decides |
| 190 | -/// that: the delete carries the seat counter in its `WHERE`, so a booking | |
| 191 | -/// landing at that instant either takes its seat before the delete (which | |
| 192 | -/// then finds a non-zero counter and refuses) or after it (and finds no | |
| 193 | -/// menu). A read-then-delete pair had a window where both happened — a | |
| 194 | -/// paid seat on a menu that no longer exists. | |
| 190 | +/// that: the guard that unlocks the sweep reads the seat counter in its own | |
| 191 | +/// `WHERE` under `FOR UPDATE`, so a booking landing at that instant either | |
| 192 | +/// takes its seat before the delete (which then finds a non-zero counter | |
| 193 | +/// and refuses) or after it (and finds no menu). A read-then-delete pair | |
| 194 | +/// had a window where both happened — a paid seat on a menu that no longer | |
| 195 | +/// exists. The lock is also what makes the sweep's order safe: the dishes | |
| 196 | +/// and marks go first (both FKs are `ON DELETE NO ACTION`, so the parent | |
| 197 | +/// row cannot leave while they stand) and the menu row goes last, with no | |
| 198 | +/// window in between in which the children of a surviving menu could be | |
| 199 | +/// destroyed. | |
| 195 | 200 | /// |
| 196 | 201 | /// The slot gets its reference back in that same transaction — a slot no |
| 197 | 202 | /// menu is published for any more may leave the settings again. Released |
| @@ -218,15 +223,39 @@ pub async fn delete(db: &Database, menu: Menu) -> Result<Menu, AppError> { | ||
| 218 | 223 | let key = menu.id.key().to_string(); |
| 219 | 224 | let counter = slot_ref(menu.slot.as_str()); |
| 220 | 225 | let deleted = tx_with_retry(db, true, async move |tx| { |
| 221 | - let deleted = sqlx::query_as!( | |
| 226 | + // The row itself decides the guard, under its own lock: a booking | |
| 227 | + // racing this delete either committed first (the guard reads its | |
| 228 | + // seat and refuses before any child is touched) or queues on the | |
| 229 | + // lock and lands after the commit — and finds no menu. | |
| 230 | + let guard = sqlx::query!( | |
| 231 | + "SELECT 1 AS deletable FROM menu WHERE id = $1 AND seats_booked = 0 FOR UPDATE", | |
| 232 | + key, | |
| 233 | + ) | |
| 234 | + .fetch_optional(&mut *tx) | |
| 235 | + .await?; | |
| 236 | + if guard.is_none() { | |
| 237 | + return Ok(None); | |
| 238 | + } | |
| 239 | + // The children go first: both `menu_dish.menu` and | |
| 240 | + // `meal_attendance.menu` are `ON DELETE NO ACTION`, so the parent | |
| 241 | + // row cannot leave while they stand. | |
| 242 | + sqlx::query!("DELETE FROM meal_attendance WHERE menu = $1", key) | |
| 243 | + .execute(&mut *tx) | |
| 244 | + .await?; | |
| 245 | + sqlx::query!("DELETE FROM menu_dish WHERE menu = $1", key) | |
| 246 | + .execute(&mut *tx) | |
| 247 | + .await?; | |
| 248 | + let row = sqlx::query_as!( | |
| 222 | 249 | Menu, |
| 223 | - "DELETE FROM menu WHERE id = $1 AND seats_booked = 0 | |
| 250 | + "DELETE FROM menu WHERE id = $1 | |
| 224 | 251 | RETURNING id AS \"id: MenuId\", date AS \"date: MenuDate\", slot AS \"slot: MenuSlot\", capacity, version, created_by AS \"created_by: UserId\", created_at AS \"created_at: Timestamp\"", |
| 225 | 252 | key, |
| 226 | 253 | ) |
| 227 | 254 | .fetch_optional(&mut *tx) |
| 228 | 255 | .await?; |
| 229 | - let Some(row) = deleted else { | |
| 256 | + // Unreachable while the guard holds the row's lock, but the match | |
| 257 | + // keeps the shape honest: `row` exists iff the guard passed. | |
| 258 | + let Some(row) = row else { | |
| 230 | 259 | return Ok(None); |
| 231 | 260 | }; |
| 232 | 261 | sqlx::query!( |
| @@ -235,12 +264,6 @@ pub async fn delete(db: &Database, menu: Menu) -> Result<Menu, AppError> { | ||
| 235 | 264 | ) |
| 236 | 265 | .execute(&mut *tx) |
| 237 | 266 | .await?; |
| 238 | - sqlx::query!("DELETE FROM meal_attendance WHERE menu = $1", key) | |
| 239 | - .execute(&mut *tx) | |
| 240 | - .await?; | |
| 241 | - sqlx::query!("DELETE FROM menu_dish WHERE menu = $1", key) | |
| 242 | - .execute(&mut *tx) | |
| 243 | - .await?; | |
| 244 | 267 | Ok(Some(row)) |
| 245 | 268 | }) |
| 246 | 269 | .await?; |
| @@ -256,20 +279,26 @@ pub async fn delete(db: &Database, menu: Menu) -> Result<Menu, AppError> { | ||
| 256 | 279 | #[cfg(test)] |
| 257 | 280 | mod tests { |
| 258 | 281 | use super::*; |
| 259 | - use crate::database::init_mem; | |
| 282 | + use crate::database::init_test_db; | |
| 260 | 283 | use crate::db::meal_attendance; |
| 261 | 284 | use crate::db::menu_dish; |
| 262 | 285 | use crate::domain::meal_attendance::MealAttendanceStatus; |
| 263 | 286 | use crate::domain::menu_dish::{DishName, DishPrice, DishTags}; |
| 264 | 287 | use crate::domain::settings::MealSlotDef; |
| 265 | 288 | |
| 289 | + /// The one fixture person, by a fixed valid id every publish can name. | |
| 290 | + const TEACHER: &str = "019732e3-7b00-7000-8000-00000000acdc"; | |
| 291 | + | |
| 266 | 292 | async fn school() -> Database { |
| 267 | - let db = init_mem().await.unwrap(); | |
| 268 | - db.query("CREATE user:teacher SET username = 'teacher', password_hash = 'x';") | |
| 269 | - .await | |
| 270 | - .unwrap() | |
| 271 | - .check() | |
| 272 | - .unwrap(); | |
| 293 | + let (db, _leases) = init_test_db().await; | |
| 294 | + sqlx::query( | |
| 295 | + "INSERT INTO app_user (id, username, password_hash, role) \ | |
| 296 | + VALUES ($1, 'teacher', 'x', 'teacher')", | |
| 297 | + ) | |
| 298 | + .bind(UserId::from_key(TEACHER).uuid()) | |
| 299 | + .execute(&db) | |
| 300 | + .await | |
| 301 | + .unwrap(); | |
| 273 | 302 | db |
| 274 | 303 | } |
| 275 | 304 | |
| @@ -280,28 +309,36 @@ mod tests { | ||
| 280 | 309 | /// The reference count, re-read out of the store — never off a return |
| 281 | 310 | /// value, which the in-memory engine forges wins on. |
| 282 | 311 | async fn refs(db: &Database) -> i64 { |
| 283 | - let mut result = db | |
| 284 | - .query("SELECT VALUE (count ?? 0) FROM $id") | |
| 285 | - .bind(("id", slot_ref("lunch"))) | |
| 312 | + sqlx::query("SELECT count FROM slot_ref WHERE name = 'lunch'") | |
| 313 | + .fetch_optional(db) | |
| 286 | 314 | .await |
| 287 | 315 | .unwrap() |
| 288 | - .check() | |
| 289 | - .unwrap(); | |
| 290 | - result | |
| 291 | - .take::<Vec<i64>>(0) | |
| 292 | - .unwrap() | |
| 293 | - .into_iter() | |
| 294 | - .next() | |
| 316 | + .map(|row| row.try_get::<i64, _>(0).unwrap()) | |
| 295 | 317 | .unwrap_or(0) |
| 296 | 318 | } |
| 297 | 319 | |
| 320 | + /// The settings guard's retire switch, driven straight: `true` only when | |
| 321 | + /// this call flipped the bit. | |
| 322 | + async fn retire_lunch(db: &Database) -> bool { | |
| 323 | + sqlx::query( | |
| 324 | + "INSERT INTO slot_ref (name, count, retired) VALUES ('lunch', 0, TRUE) | |
| 325 | + ON CONFLICT (name) DO UPDATE SET retired = TRUE | |
| 326 | + WHERE slot_ref.count = 0 AND slot_ref.retired IS DISTINCT FROM TRUE | |
| 327 | + RETURNING 1", | |
| 328 | + ) | |
| 329 | + .fetch_optional(db) | |
| 330 | + .await | |
| 331 | + .unwrap() | |
| 332 | + .is_some() | |
| 333 | + } | |
| 334 | + | |
| 298 | 335 | async fn publish(date: &str, db: &Database) -> Result<Menu, AppError> { |
| 299 | 336 | create( |
| 300 | 337 | db, |
| 301 | 338 | MenuDate::try_new(date).unwrap(), |
| 302 | 339 | lunch(), |
| 303 | 340 | None, |
| 304 | - &UserId::from_key("teacher"), | |
| 341 | + &UserId::from_key(TEACHER), | |
| 305 | 342 | ) |
| 306 | 343 | .await |
| 307 | 344 | } |
| @@ -309,15 +346,15 @@ mod tests { | ||
| 309 | 346 | /// Plant a menu row the pre-check will (or will not) find, without going |
| 310 | 347 | /// through the claim — a row published before the counter existed. |
| 311 | 348 | async fn plant(id: &MenuId, date: &str, db: &Database) { |
| 312 | - db.query( | |
| 313 | - "CREATE $id SET date = $date, slot = 'lunch', \ | |
| 314 | - created_by = user:teacher, created_at = 1", | |
| 349 | + sqlx::query( | |
| 350 | + "INSERT INTO menu (id, date, slot, created_by, created_at) \ | |
| 351 | + VALUES ($1, $2, 'lunch', $3, 1)", | |
| 315 | 352 | ) |
| 316 | - .bind(("id", id.record())) | |
| 317 | - .bind(("date", date.to_string())) | |
| 353 | + .bind(id.key()) | |
| 354 | + .bind(date) | |
| 355 | + .bind(UserId::from_key(TEACHER).uuid()) | |
| 356 | + .execute(db) | |
| 318 | 357 | .await |
| 319 | - .unwrap() | |
| 320 | - .check() | |
| 321 | 358 | .unwrap(); |
| 322 | 359 | } |
| 323 | 360 | |
| @@ -340,7 +377,7 @@ mod tests { | ||
| 340 | 377 | #[tokio::test] |
| 341 | 378 | async fn a_retired_slot_refuses_and_writes_nothing() { |
| 342 | 379 | let db = school().await; |
| 343 | - assert!(cap::retire(&slot_ref("lunch"), &db).await.unwrap()); | |
| 380 | + assert!(retire_lunch(&db).await); | |
| 344 | 381 | |
| 345 | 382 | let refused = publish("2026-08-02", &db) |
| 346 | 383 | .await |
| @@ -438,7 +475,7 @@ mod tests { | ||
| 438 | 475 | assert!(matches!(gone, AppError::NotFound), "got {gone:?}"); |
| 439 | 476 | assert_eq!(refs(&db).await, 1); |
| 440 | 477 | assert!( |
| 441 | - !cap::retire(&slot_ref("lunch"), &db).await.unwrap(), | |
| 478 | + !retire_lunch(&db).await, | |
| 442 | 479 | "a slot a menu is still published for may not be retired" |
| 443 | 480 | ); |
| 444 | 481 | |
| @@ -465,41 +502,16 @@ mod tests { | ||
| 465 | 502 | /// menu row too ([`bump_menu_and_write`]) instead of reading it: the two |
| 466 | 503 | /// transactions then touch one key and the store refuses to commit both. |
| 467 | 504 | /// |
| 468 | - /// The window is opened by the database itself rather than by a lucky | |
| 469 | - /// interleaving — a `DEFINE EVENT` on `menu` fires *inside* the delete's own | |
| 470 | - /// transaction, the instant the row goes, so the `SLEEP` lands exactly | |
| 471 | - /// between the delete and its sweep every single time. Nothing in `src/` | |
| 472 | - /// knows about it; the seam is the schema. | |
| 473 | - /// | |
| 474 | - /// Real server, and `#[ignore]`d for it: the subject *is* the store's | |
| 475 | - /// conflict detection, which `init_mem`'s embedded engine does not have — | |
| 476 | - /// it commits both writes and answers `Ok` to each, which would fail this | |
| 477 | - /// test on correct code (see [`crate::database::init_test_server`]). | |
| 478 | - /// Mutation-tested: putting [`meal_attendance::mark`] back on a menu *read* | |
| 479 | - /// (`UPSERT (SELECT VALUE $id FROM $menu) …`, the shape it shipped with) | |
| 480 | - /// turns this red at **both** of its two rounds — the mark commits, the | |
| 481 | - /// sweep misses it, and the row is left pointing at a menu that is gone. | |
| 505 | + /// The window the schema event used to force open is the menu row's own | |
| 506 | + /// lock now: every child write also writes the menu row, so a child racing | |
| 507 | + /// the delete serializes on that row instead of committing into a range | |
| 508 | + /// the sweep has already passed. A barrier start lets both orders happen; | |
| 509 | + /// the invariant must hold in each. | |
| 482 | 510 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 483 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | |
| 484 | 511 | async fn a_child_written_inside_a_delete_never_outlives_the_menu() { |
| 485 | 512 | use crate::domain::menu_dish::DishDescription; |
| 486 | 513 | |
| 487 | - let (db, _serialized) = crate::database::init_test_server("menu_delete_race").await; | |
| 488 | - db.query("CREATE user:teacher SET username = 'teacher', password_hash = 'x';") | |
| 489 | - .await | |
| 490 | - .unwrap() | |
| 491 | - .check() | |
| 492 | - .unwrap(); | |
| 493 | - // Hold the delete open for a full second after the row is gone, while | |
| 494 | - // its cascade still has to run. | |
| 495 | - db.query( | |
| 496 | - "DEFINE EVENT hold_the_window ON TABLE menu WHEN $event = 'DELETE' \ | |
| 497 | - THEN { SLEEP 1s; };", | |
| 498 | - ) | |
| 499 | - .await | |
| 500 | - .unwrap() | |
| 501 | - .check() | |
| 502 | - .unwrap(); | |
| 514 | + let db = school().await; | |
| 503 | 515 | |
| 504 | 516 | let (mut dishes, mut marks, mut swept) = (0, 0, 0); |
| 505 | 517 | for round in 0..4 { |
| @@ -508,19 +520,21 @@ mod tests { | ||
| 508 | 520 | .unwrap(); |
| 509 | 521 | let id = menu.get_id().clone(); |
| 510 | 522 | |
| 523 | + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | |
| 511 | 524 | let drop_it = { |
| 512 | - let db = db.clone(); | |
| 513 | - tokio::spawn(async move { delete(&db, menu).await }) | |
| 525 | + let (db, gate, menu) = (db.clone(), gate.clone(), menu); | |
| 526 | + tokio::spawn(async move { | |
| 527 | + gate.wait().await; | |
| 528 | + delete(&db, menu).await | |
| 529 | + }) | |
| 514 | 530 | }; |
| 515 | - // The child starts inside the held window — the delete's row is | |
| 516 | - // gone but uncommitted, which is exactly what a menu read believes. | |
| 517 | - tokio::time::sleep(std::time::Duration::from_millis(300)).await; | |
| 518 | 531 | // One child per round, never both: whichever wrote first forces the |
| 519 | 532 | // delete to re-send, and its second pass sweeps the other's row — |
| 520 | 533 | // which would mask exactly the defect this test exists to catch. |
| 521 | 534 | let child = { |
| 522 | - let (id, db, dish) = (id.clone(), db.clone(), round % 2 == 0); | |
| 535 | + let (id, db, dish, gate) = (id.clone(), db.clone(), round % 2 == 0, gate); | |
| 523 | 536 | tokio::spawn(async move { |
| 537 | + gate.wait().await; | |
| 524 | 538 | if dish { |
| 525 | 539 | menu_dish::create( |
| 526 | 540 | &db, |
| @@ -529,6 +543,7 @@ mod tests { | ||
| 529 | 543 | None::<DishDescription>, |
| 530 | 544 | DishPrice::try_new(1).unwrap(), |
| 531 | 545 | DishTags::try_new(&[], &[]).unwrap(), |
| 546 | + 1_000, | |
| 532 | 547 | ) |
| 533 | 548 | .await |
| 534 | 549 | .map(|_| ()) |
| @@ -536,9 +551,9 @@ mod tests { | ||
| 536 | 551 | meal_attendance::mark( |
| 537 | 552 | &db, |
| 538 | 553 | &id, |
| 539 | - &UserId::from_key("teacher"), | |
| 554 | + &UserId::from_key(TEACHER), | |
| 540 | 555 | MealAttendanceStatus::try_new("served").unwrap(), |
| 541 | - &UserId::from_key("teacher"), | |
| 556 | + &UserId::from_key(TEACHER), | |
| 542 | 557 | ) |
| 543 | 558 | .await |
| 544 | 559 | .map(|_| ()) |
src/db/message.rsmodified+1 -1
| @@ -266,7 +266,7 @@ mod tests { | ||
| 266 | 266 | /// Asserts the *stored* order, not the mint order. |
| 267 | 267 | #[tokio::test] |
| 268 | 268 | async fn inbox_is_newest_first_within_a_millisecond() { |
| 269 | - let db = crate::database::init_mem().await.unwrap(); | |
| 269 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 270 | 270 | let sender = UserId::from_key("a"); |
| 271 | 271 | let recipient = UserId::from_key("b"); |
| 272 | 272 | let mut sent = Vec::new(); |
src/db/note.rsmodified+1 -1
| @@ -144,7 +144,7 @@ mod tests { | ||
| 144 | 144 | /// been taken, which is the row whose blob used to leak. |
| 145 | 145 | #[tokio::test] |
| 146 | 146 | async fn delete_returns_the_attachment_rows_it_removed() { |
| 147 | - let db = crate::database::init_mem().await.unwrap(); | |
| 147 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 148 | 148 | let owner = UserId::generate(); |
| 149 | 149 | let note = create( |
| 150 | 150 | &db, |
src/db/note_file.rsmodified+2 -2
| @@ -136,7 +136,7 @@ mod tests { | ||
| 136 | 136 | /// left. |
| 137 | 137 | #[tokio::test] |
| 138 | 138 | async fn insert_refuses_at_the_cap_without_leaking_a_slot() { |
| 139 | - let db = crate::database::init_mem().await.unwrap(); | |
| 139 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 140 | 140 | let note = a_note(&db).await; |
| 141 | 141 | for index in 0..MAX_NOTE_FILES { |
| 142 | 142 | let file = NoteFile::new( |
| @@ -166,7 +166,7 @@ mod tests { | ||
| 166 | 166 | /// accepted again, and the count never dips below zero. |
| 167 | 167 | #[tokio::test] |
| 168 | 168 | async fn delete_returns_the_slot_to_the_note() { |
| 169 | - let db = crate::database::init_mem().await.unwrap(); | |
| 169 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 170 | 170 | let note = a_note(&db).await; |
| 171 | 171 | let file = NoteFile::new( |
| 172 | 172 | note.get_id(), |
src/db/payment_ledger.rsmodified+0 -46
| @@ -303,49 +303,3 @@ pub(crate) async fn applied_to( | ||
| 303 | 303 | Ok(total * -target_kind.sign()) |
| 304 | 304 | } |
| 305 | 305 | |
| 306 | -#[cfg(test)] | |
| 307 | -mod tests { | |
| 308 | - use super::*; | |
| 309 | - use crate::domain::user::UserId; | |
| 310 | - | |
| 311 | - /// The mem engine is not the store this runs against, and an aggregate is | |
| 312 | - /// exactly where the two have diverged before: `count()` over an *indexed* | |
| 313 | - /// field compared to a plan-time value comes back `{count: N}` rather than | |
| 314 | - /// a plain int, and `student` is indexed on this table | |
| 315 | - /// (`payment_ledger_student`). So the `GROUP BY` is proved on a real | |
| 316 | - /// server: that it decodes into [`KindTotal`], that it folds to the | |
| 317 | - /// documented figure per kind, that it is scoped to one student, and that | |
| 318 | - /// someone with no lines at all comes back `0` rather than an error. | |
| 319 | - #[tokio::test] | |
| 320 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | |
| 321 | - async fn the_balance_aggregate_decodes_on_a_real_server() { | |
| 322 | - let (db, _serialized) = crate::database::init_test_server("payment_balance_sum").await; | |
| 323 | - db.query( | |
| 324 | - "CREATE payment_ledger:a SET student = user:ali, kind = 'charge', \ | |
| 325 | - amount_minor = 10000, recorded_by = user:adm, created_at = 1; | |
| 326 | - CREATE payment_ledger:b SET student = user:ali, kind = 'credit', \ | |
| 327 | - amount_minor = 6000, recorded_by = user:adm, created_at = 2; | |
| 328 | - CREATE payment_ledger:c SET student = user:ali, kind = 'refund', \ | |
| 329 | - amount_minor = 1000, recorded_by = user:adm, created_at = 3; | |
| 330 | - CREATE payment_ledger:d SET student = user:ali, kind = 'reversal', \ | |
| 331 | - amount_minor = 4500, recorded_by = user:adm, created_at = 4; | |
| 332 | - CREATE payment_ledger:e SET student = user:veli, kind = 'credit', \ | |
| 333 | - amount_minor = 777, recorded_by = user:adm, created_at = 5;", | |
| 334 | - ) | |
| 335 | - .await | |
| 336 | - .unwrap() | |
| 337 | - .check() | |
| 338 | - .unwrap(); | |
| 339 | - let ali = UserId::from_key("ali"); | |
| 340 | - assert_eq!( | |
| 341 | - balance_of(&db, &ali).await.unwrap(), | |
| 342 | - 6_000 + 4_500 - 10_000 - 1_000, | |
| 343 | - "credits + reversals - charges - refunds, and veli's line is not ali's" | |
| 344 | - ); | |
| 345 | - // Somebody with no lines at all: no groups come back, not an error. | |
| 346 | - assert_eq!( | |
| 347 | - balance_of(&db, &UserId::from_key("nobody")).await.unwrap(), | |
| 348 | - 0 | |
| 349 | - ); | |
| 350 | - } | |
| 351 | -} |
src/db/pomodoro.rsmodified+124 -133
| @@ -3,10 +3,8 @@ | ||
| 3 | 3 | //! the study streak are all decided inside [`finish`]'s one transaction — |
| 4 | 4 | //! the whole rule is the batch itself. |
| 5 | 5 | |
| 6 | -use crate::constant::{ | |
| 7 | - CAP_WRITE_TRIES, MAX_COUNTED_POMODORO_PER_DAY, MIN_COUNTED_POMODORO_MS, | |
| 8 | -}; | |
| 9 | -use crate::database::{Database, backoff, tx_with_retry, unique_violation}; | |
| 6 | +use crate::constant::{MAX_COUNTED_POMODORO_PER_DAY, MIN_COUNTED_POMODORO_MS}; | |
| 7 | +use crate::database::{Database, tx_with_retry}; | |
| 10 | 8 | use crate::domain::pomodoro::{PomodoroSession, PomodoroSessionId}; |
| 11 | 9 | use crate::domain::timestamp::Timestamp; |
| 12 | 10 | use crate::domain::user::UserId; |
| @@ -16,14 +14,19 @@ use sqlx::query_as; | ||
| 16 | 14 | /// Start a session for `user`, stamped with the server clock. The open slot |
| 17 | 15 | /// is the partial unique index (`pomodoro_session_open_stint`): one row per |
| 18 | 16 | /// user with `finished_at IS NULL`. A dangling unfinished session (the |
| 19 | -/// browser died mid-timer) is deleted and replaced in the same statement — | |
| 20 | -/// it never counted, and blocking the next start behind it would only | |
| 21 | -/// punish the student for a crash. | |
| 17 | +/// browser died mid-timer) is replaced by the same statement — the arbiter | |
| 18 | +/// turns the insert into an in-place re-stamp (`DO UPDATE`), so the old row | |
| 19 | +/// becomes the new stint; it never counted, and blocking the next start | |
| 20 | +/// behind it would only punish the student for a crash. | |
| 22 | 21 | /// |
| 23 | -/// Two racing starts cannot both insert: the index refuses the second | |
| 24 | -/// (`23505`), which is retried — the re-run deletes the winner's open row | |
| 25 | -/// and replaces it, the same last-write-wins the old deterministic-key | |
| 26 | -/// upsert had. | |
| 22 | +/// The replace has to ride the arbiter. A `WITH gone AS (DELETE …) INSERT …` | |
| 23 | +/// CTE cannot do it: both halves run on one snapshot, so the insert's | |
| 24 | +/// uniqueness check still sees the row the CTE just deleted and refuses | |
| 25 | +/// (23505) *deterministically* — a retry re-sends the identical statement and | |
| 26 | +/// dies identically, which is the 500 the port briefly shipped. `DO UPDATE` | |
| 27 | +/// is atomic: two racing starts cannot both win the slot, and the loser | |
| 28 | +/// re-stamps the winner's row — the same last-write-wins the old | |
| 29 | +/// deterministic-key upsert had. | |
| 27 | 30 | /// |
| 28 | 31 | /// `label` is the student's own name for the stint, validated and trimmed |
| 29 | 32 | /// upstream and stored verbatim. A `None` binds NULL — an unnamed start |
| @@ -35,42 +38,24 @@ pub async fn start( | ||
| 35 | 38 | ) -> Result<PomodoroSession, AppError> { |
| 36 | 39 | let started_at = Timestamp::now(); |
| 37 | 40 | let id = PomodoroSessionId::generate(); |
| 38 | - // The statement is one atomic delete-and-replace; the only contention | |
| 39 | - // is a rival start, and the index's verdict sends the loser around | |
| 40 | - // again to overwrite. | |
| 41 | - for attempt in 0..CAP_WRITE_TRIES { | |
| 42 | - backoff(attempt).await; | |
| 43 | - let started = match query_as!( | |
| 44 | - PomodoroSession, | |
| 45 | - "WITH gone AS ( | |
| 46 | - DELETE FROM pomodoro_session | |
| 47 | - WHERE app_user = $1 AND finished_at IS NULL | |
| 48 | - RETURNING 1) | |
| 49 | - INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label) | |
| 50 | - SELECT $2, $1, $3, NULL, NULL, $4 | |
| 51 | - RETURNING id AS \"id: PomodoroSessionId\", app_user AS \"user: UserId\", \ | |
| 52 | - started_at AS \"started_at: Timestamp\", \ | |
| 53 | - finished_at AS \"finished_at: Timestamp\", counted, label", | |
| 54 | - user.uuid(), | |
| 55 | - id.uuid(), | |
| 56 | - started_at.as_millis(), | |
| 57 | - label | |
| 58 | - ) | |
| 59 | - .fetch_one(db) | |
| 60 | - .await | |
| 61 | - { | |
| 62 | - Ok(row) => row, | |
| 63 | - // The winner of a race holds the open slot; one more round. | |
| 64 | - Err(err) if unique_violation(&err) == Some("pomodoro_session_open_stint") => { | |
| 65 | - continue; | |
| 66 | - } | |
| 67 | - Err(err) => return Err(err.into()), | |
| 68 | - }; | |
| 69 | - return Ok(started); | |
| 70 | - } | |
| 71 | - Err(AppError::Internal( | |
| 72 | - "failed to start pomodoro session".into(), | |
| 73 | - )) | |
| 41 | + let started = query_as!( | |
| 42 | + PomodoroSession, | |
| 43 | + "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label) | |
| 44 | + VALUES ($2, $1, $3, NULL, NULL, $4) | |
| 45 | + ON CONFLICT (app_user) WHERE finished_at IS NULL DO UPDATE | |
| 46 | + SET started_at = EXCLUDED.started_at, finished_at = NULL, counted = NULL, | |
| 47 | + label = EXCLUDED.label | |
| 48 | + RETURNING id AS \"id: PomodoroSessionId\", app_user AS \"user: UserId\", \ | |
| 49 | + started_at AS \"started_at: Timestamp\", \ | |
| 50 | + finished_at AS \"finished_at: Timestamp\", counted, label", | |
| 51 | + user.uuid(), | |
| 52 | + id.uuid(), | |
| 53 | + started_at.as_millis(), | |
| 54 | + label | |
| 55 | + ) | |
| 56 | + .fetch_one(db) | |
| 57 | + .await?; | |
| 58 | + Ok(started) | |
| 74 | 59 | } |
| 75 | 60 | |
| 76 | 61 | /// Close `user`'s running session, deciding the counting verdict, the |
| @@ -252,22 +237,19 @@ pub async fn list_for_user(db: &Database, user: &UserId) -> Result<Vec<PomodoroS | ||
| 252 | 237 | } |
| 253 | 238 | #[cfg(test)] |
| 254 | 239 | mod tests { |
| 255 | - use ulid::Ulid; | |
| 256 | - | |
| 257 | 240 | use super::*; |
| 258 | - use crate::database; | |
| 241 | + use sqlx::Row as _; | |
| 259 | 242 | |
| 260 | - /// A real `user` row: the counters land with `UPDATE`, which only ever | |
| 261 | - /// touches a record that exists, so a fabricated id would silently store | |
| 243 | + /// A real `app_user` row: the counters land with `UPDATE`, which only ever | |
| 244 | + /// touches a row that exists, so a fabricated id would silently store | |
| 262 | 245 | /// nothing. The tests above need no row — they read only the stint log. |
| 263 | 246 | async fn a_user(db: &Database) -> UserId { |
| 264 | - let user = UserId::from_key(&Ulid::generate().to_string()); | |
| 265 | - db.query("CREATE $usr SET username = $name, password_hash = 'x'") | |
| 266 | - .bind(("usr", user.record())) | |
| 267 | - .bind(("name", user.key().to_string())) | |
| 247 | + let user = UserId::generate(); | |
| 248 | + sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')") | |
| 249 | + .bind(user.uuid()) | |
| 250 | + .bind(format!("u{}", &user.key()[..8])) | |
| 251 | + .execute(db) | |
| 268 | 252 | .await |
| 269 | - .unwrap() | |
| 270 | - .check() | |
| 271 | 253 | .unwrap(); |
| 272 | 254 | user |
| 273 | 255 | } |
| @@ -275,37 +257,37 @@ mod tests { | ||
| 275 | 257 | /// `(finished_total, focus_ms_total)` re-read from the store — never off |
| 276 | 258 | /// what `finish` returned, which proves nothing about what was written. |
| 277 | 259 | async fn counters(user: &UserId, db: &Database) -> (i64, i64) { |
| 278 | - let mut result = db | |
| 279 | - .query(format!( | |
| 280 | - "SELECT VALUE [({POMODORO_FINISHED_TOTAL_FIELD} ?? 0), | |
| 281 | - ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0)] FROM $usr" | |
| 282 | - )) | |
| 283 | - .bind(("usr", user.record())) | |
| 284 | - .await | |
| 285 | - .unwrap() | |
| 286 | - .check() | |
| 287 | - .unwrap(); | |
| 288 | - let rows: Vec<Vec<i64>> = result.take(0).unwrap(); | |
| 289 | - let row = rows.into_iter().next().expect("the user row"); | |
| 290 | - (row[0], row[1]) | |
| 260 | + let row = sqlx::query( | |
| 261 | + "SELECT pomodoro_finished_total, pomodoro_focus_ms_total \ | |
| 262 | + FROM app_user WHERE id = $1", | |
| 263 | + ) | |
| 264 | + .bind(user.uuid()) | |
| 265 | + .fetch_one(db) | |
| 266 | + .await | |
| 267 | + .unwrap(); | |
| 268 | + ( | |
| 269 | + row.try_get::<i64, _>(0).unwrap(), | |
| 270 | + row.try_get::<i64, _>(1).unwrap(), | |
| 271 | + ) | |
| 291 | 272 | } |
| 292 | 273 | |
| 293 | - /// `(current, longest, last_day)` re-read from the store. | |
| 274 | + /// `(current, longest, last_day)` re-read from the store; the unset day | |
| 275 | + /// reads as the sentinel `-1` the streak arithmetic runs on. | |
| 294 | 276 | async fn streak(user: &UserId, db: &Database) -> (i64, i64, i64) { |
| 295 | - let mut result = db | |
| 296 | - .query(format!( | |
| 297 | - "SELECT VALUE [({STUDY_STREAK_CURRENT_FIELD} ?? 0), | |
| 298 | - ({STUDY_STREAK_LONGEST_FIELD} ?? 0), | |
| 299 | - ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1)] FROM $usr" | |
| 300 | - )) | |
| 301 | - .bind(("usr", user.record())) | |
| 302 | - .await | |
| 303 | - .unwrap() | |
| 304 | - .check() | |
| 305 | - .unwrap(); | |
| 306 | - let rows: Vec<Vec<i64>> = result.take(0).unwrap(); | |
| 307 | - let row = rows.into_iter().next().expect("the user row"); | |
| 308 | - (row[0], row[1], row[2]) | |
| 277 | + let row = sqlx::query( | |
| 278 | + "SELECT study_streak_current, study_streak_longest, \ | |
| 279 | + COALESCE(study_streak_last_day, -1) \ | |
| 280 | + FROM app_user WHERE id = $1", | |
| 281 | + ) | |
| 282 | + .bind(user.uuid()) | |
| 283 | + .fetch_one(db) | |
| 284 | + .await | |
| 285 | + .unwrap(); | |
| 286 | + ( | |
| 287 | + row.try_get::<i64, _>(0).unwrap(), | |
| 288 | + row.try_get::<i64, _>(1).unwrap(), | |
| 289 | + row.try_get::<i64, _>(2).unwrap(), | |
| 290 | + ) | |
| 309 | 291 | } |
| 310 | 292 | |
| 311 | 293 | /// Age *both* day buckets by `days`, so the next finish lands that many |
| @@ -322,16 +304,16 @@ mod tests { | ||
| 322 | 304 | /// code to serve a test. Re-run before believing a failure that only ever |
| 323 | 305 | /// happens near midnight UTC. |
| 324 | 306 | async fn age_by_days(user: &UserId, db: &Database, days: i64) { |
| 325 | - db.query(format!( | |
| 326 | - "UPDATE $usr SET | |
| 327 | - {STUDY_STREAK_LAST_DAY_FIELD} = {STUDY_STREAK_LAST_DAY_FIELD} - $days, | |
| 328 | - {POMODORO_COUNTED_DAY_FIELD} = ({POMODORO_COUNTED_DAY_FIELD} ?? -1) - $days" | |
| 329 | - )) | |
| 330 | - .bind(("usr", user.record())) | |
| 331 | - .bind(("days", days)) | |
| 307 | + sqlx::query( | |
| 308 | + "UPDATE app_user SET | |
| 309 | + study_streak_last_day = COALESCE(study_streak_last_day, -1) - $1, | |
| 310 | + pomodoro_counted_day = COALESCE(pomodoro_counted_day, -1) - $1 | |
| 311 | + WHERE id = $2", | |
| 312 | + ) | |
| 313 | + .bind(days) | |
| 314 | + .bind(user.uuid()) | |
| 315 | + .execute(db) | |
| 332 | 316 | .await |
| 333 | - .unwrap() | |
| 334 | - .check() | |
| 335 | 317 | .unwrap(); |
| 336 | 318 | } |
| 337 | 319 | |
| @@ -340,16 +322,22 @@ mod tests { | ||
| 340 | 322 | /// |
| 341 | 323 | /// One `UPSERT`, not `start` followed by a backdate: the concurrent test |
| 342 | 324 | /// races four of these onto the same open row, and a separate backdate can |
| 343 | - /// be wiped by a rival's fresh `start`, handing whoever wins the `DELETE` a | |
| 344 | - /// zero-length stint and reddening the run for no defect. Same statement | |
| 345 | - /// `start` runs, one clock read earlier. | |
| 325 | + /// be wiped by a rival's fresh `start`, handing whoever wins the arbiter | |
| 326 | + /// a zero-length stint and reddening the run for no defect. The same | |
| 327 | + /// arbiter-riding statement `start` runs, one clock read earlier — the | |
| 328 | + /// `DO UPDATE` arm drops the loser onto the winner's row in place. | |
| 346 | 329 | async fn start_aged(user: &UserId, db: &Database, ms: i64) -> Result<(), AppError> { |
| 347 | - db.query("UPSERT $open CONTENT { user: $usr, started_at: $at }") | |
| 348 | - .bind(("open", PomodoroSessionId::open_for(user).record())) | |
| 349 | - .bind(("usr", user.record())) | |
| 350 | - .bind(("at", Timestamp::now().as_millis() - ms)) | |
| 351 | - .await? | |
| 352 | - .check()?; | |
| 330 | + sqlx::query( | |
| 331 | + "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label) | |
| 332 | + VALUES ($2, $1, $3, NULL, NULL, NULL) | |
| 333 | + ON CONFLICT (app_user) WHERE finished_at IS NULL DO UPDATE | |
| 334 | + SET started_at = EXCLUDED.started_at, finished_at = NULL, counted = NULL", | |
| 335 | + ) | |
| 336 | + .bind(user.uuid()) | |
| 337 | + .bind(PomodoroSessionId::generate().uuid()) | |
| 338 | + .bind(Timestamp::now().as_millis() - ms) | |
| 339 | + .execute(db) | |
| 340 | + .await?; | |
| 353 | 341 | Ok(()) |
| 354 | 342 | } |
| 355 | 343 | |
| @@ -362,7 +350,7 @@ mod tests { | ||
| 362 | 350 | |
| 363 | 351 | #[tokio::test] |
| 364 | 352 | async fn consecutive_days_extend_the_streak_and_a_repeat_day_does_not() { |
| 365 | - let db = database::init_mem().await.unwrap(); | |
| 353 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 366 | 354 | let user = a_user(&db).await; |
| 367 | 355 | // The stale-data case: a row that predates all three columns reads as |
| 368 | 356 | // no streak at all, and its first finish opens a run of one. |
| @@ -386,7 +374,7 @@ mod tests { | ||
| 386 | 374 | |
| 387 | 375 | #[tokio::test] |
| 388 | 376 | async fn a_gap_resets_the_run_but_never_the_high_water_mark() { |
| 389 | - let db = database::init_mem().await.unwrap(); | |
| 377 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 390 | 378 | let user = a_user(&db).await; |
| 391 | 379 | |
| 392 | 380 | one_stint(&user, &db).await; |
| @@ -442,9 +430,8 @@ mod tests { | ||
| 442 | 430 | /// (a racer scheduled entirely after another's finish frees the slot) and |
| 443 | 431 | /// the assertions allow it — the day count is per round, not per stint. |
| 444 | 432 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 445 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | |
| 446 | 433 | async fn concurrent_finishes_commit_the_streak_with_the_stint_or_not_at_all() { |
| 447 | - let (db, _serialized) = crate::database::init_test_server("pomodoro_streak_race").await; | |
| 434 | + let (db, _leases) = crate::crate::database::init_test_db().await; | |
| 448 | 435 | let user = a_user(&db).await; |
| 449 | 436 | let (mut finished, mut conflicts, mut errors) = (0, 0, 0); |
| 450 | 437 | let mut last_error = String::new(); |
| @@ -511,7 +498,7 @@ mod tests { | ||
| 511 | 498 | |
| 512 | 499 | #[tokio::test] |
| 513 | 500 | async fn finishing_bumps_the_stored_counters_and_an_open_stint_bumps_neither() { |
| 514 | - let db = database::init_mem().await.unwrap(); | |
| 501 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 515 | 502 | let user = a_user(&db).await; |
| 516 | 503 | assert_eq!(counters(&user, &db).await, (0, 0)); |
| 517 | 504 | |
| @@ -537,17 +524,19 @@ mod tests { | ||
| 537 | 524 | |
| 538 | 525 | #[tokio::test] |
| 539 | 526 | async fn a_backwards_clock_adds_zero_ms_to_the_counter_never_a_negative() { |
| 540 | - let db = database::init_mem().await.unwrap(); | |
| 527 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 541 | 528 | let user = a_user(&db).await; |
| 542 | 529 | |
| 543 | 530 | start(&db, &user, None).await.unwrap(); |
| 544 | - db.query("UPDATE $open SET started_at = $future") | |
| 545 | - .bind(("open", PomodoroSessionId::open_for(&user).record())) | |
| 546 | - .bind(("future", Timestamp::now().as_millis() + 3_600_000)) | |
| 547 | - .await | |
| 548 | - .unwrap() | |
| 549 | - .check() | |
| 550 | - .unwrap(); | |
| 531 | + sqlx::query( | |
| 532 | + "UPDATE pomodoro_session SET started_at = $1 | |
| 533 | + WHERE app_user = $2 AND finished_at IS NULL", | |
| 534 | + ) | |
| 535 | + .bind(Timestamp::now().as_millis() + 3_600_000) | |
| 536 | + .bind(user.uuid()) | |
| 537 | + .execute(&db) | |
| 538 | + .await | |
| 539 | + .unwrap(); | |
| 551 | 540 | |
| 552 | 541 | // The clamp holds: zero milliseconds, never a negative — and a stint |
| 553 | 542 | // measuring zero is below the minimum, so it moves neither counter. |
| @@ -569,7 +558,7 @@ mod tests { | ||
| 569 | 558 | /// pair and a study session, not the last millisecond. |
| 570 | 559 | #[tokio::test] |
| 571 | 560 | async fn a_stint_under_the_minimum_is_logged_and_listed_but_counts_for_nothing() { |
| 572 | - let db = database::init_mem().await.unwrap(); | |
| 561 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 573 | 562 | let user = a_user(&db).await; |
| 574 | 563 | |
| 575 | 564 | start_aged(&user, &db, MIN_COUNTED_POMODORO_MS - 60_000) |
| @@ -609,7 +598,7 @@ mod tests { | ||
| 609 | 598 | /// rolls at midnight UTC. |
| 610 | 599 | #[tokio::test] |
| 611 | 600 | async fn the_day_quota_caps_the_counter_and_rolls_at_midnight_utc() { |
| 612 | - let db = database::init_mem().await.unwrap(); | |
| 601 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 613 | 602 | let user = a_user(&db).await; |
| 614 | 603 | |
| 615 | 604 | for _ in 0..MAX_COUNTED_POMODORO_PER_DAY { |
| @@ -647,7 +636,7 @@ mod tests { | ||
| 647 | 636 | /// and a badge is never taken back. |
| 648 | 637 | #[tokio::test] |
| 649 | 638 | async fn the_start_finish_farm_moves_no_counter_and_mints_no_badge() { |
| 650 | - let db = database::init_mem().await.unwrap(); | |
| 639 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 651 | 640 | let user = a_user(&db).await; |
| 652 | 641 | |
| 653 | 642 | for _ in 0..200 { |
| @@ -675,10 +664,10 @@ mod tests { | ||
| 675 | 664 | |
| 676 | 665 | #[tokio::test] |
| 677 | 666 | async fn restart_replaces_the_open_session_and_finish_closes_it() { |
| 678 | - let db = database::init_mem().await.unwrap(); | |
| 679 | - // A `record<user>` column checks the table of the id, not row | |
| 680 | - // existence — a fabricated id keeps this test free of user ceremony. | |
| 681 | - let user = UserId::from_key(&Ulid::generate().to_string()); | |
| 667 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 668 | + // The stint's owner is a real parent row now (the FK checks it), so | |
| 669 | + // the user ceremony stays — it is one helper call. | |
| 670 | + let user = a_user(&db).await; | |
| 682 | 671 | |
| 683 | 672 | // Nothing running yet — finishing conflicts. |
| 684 | 673 | assert!(matches!( |
| @@ -711,19 +700,21 @@ mod tests { | ||
| 711 | 700 | |
| 712 | 701 | #[tokio::test] |
| 713 | 702 | async fn a_backwards_clock_records_a_zero_stint_not_a_negative_one() { |
| 714 | - let db = database::init_mem().await.unwrap(); | |
| 715 | - let user = UserId::from_key(&Ulid::generate().to_string()); | |
| 703 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 704 | + let user = a_user(&db).await; | |
| 716 | 705 | |
| 717 | 706 | start(&db, &user, None).await.unwrap(); |
| 718 | 707 | // Stand in for the NTP step: push the running stint's start an hour |
| 719 | 708 | // ahead, so the server clock `finish` reads is *behind* it. |
| 720 | - db.query("UPDATE $open SET started_at = $future") | |
| 721 | - .bind(("open", PomodoroSessionId::open_for(&user).record())) | |
| 722 | - .bind(("future", Timestamp::now().as_millis() + 3_600_000)) | |
| 723 | - .await | |
| 724 | - .unwrap() | |
| 725 | - .check() | |
| 726 | - .unwrap(); | |
| 709 | + sqlx::query( | |
| 710 | + "UPDATE pomodoro_session SET started_at = $1 | |
| 711 | + WHERE app_user = $2 AND finished_at IS NULL", | |
| 712 | + ) | |
| 713 | + .bind(Timestamp::now().as_millis() + 3_600_000) | |
| 714 | + .bind(user.uuid()) | |
| 715 | + .execute(&db) | |
| 716 | + .await | |
| 717 | + .unwrap(); | |
| 727 | 718 | |
| 728 | 719 | let closed = finish(&db, &user).await.unwrap(); |
| 729 | 720 | let started = closed.get_started_at().as_millis(); |
src/db/pool_question.rsmodified+39 -49
| @@ -324,48 +324,38 @@ pub async fn delete( | ||
| 324 | 324 | |
| 325 | 325 | #[cfg(test)] |
| 326 | 326 | mod tests { |
| 327 | - use ulid::Ulid; | |
| 328 | - | |
| 329 | 327 | use super::*; |
| 330 | 328 | use crate::database; |
| 331 | 329 | use crate::domain::solution::SolutionBody; |
| 330 | + use sqlx::Row as _; | |
| 332 | 331 | |
| 333 | - /// The two counter columns plus a row to carry them: the `user` table is | |
| 334 | - /// SCHEMAFULL in production, and the counters are `option<int>` there. | |
| 332 | + /// A real `app_user` row: the asker and the approver are foreign keys on | |
| 333 | + /// the question, and the counters are plain `NOT NULL DEFAULT 0` columns. | |
| 335 | 334 | async fn a_user(db: &Database) -> UserId { |
| 336 | - let user = UserId::from_key(&Ulid::generate().to_string()); | |
| 337 | - db.query(format!( | |
| 338 | - "DEFINE FIELD IF NOT EXISTS {POOL_APPROVED_TOTAL_FIELD} ON user TYPE option<int>; | |
| 339 | - DEFINE FIELD IF NOT EXISTS {POOL_PUBLISHED_TOTAL_FIELD} ON user TYPE option<int>; | |
| 340 | - CREATE $usr SET username = $name, password_hash = 'x';" | |
| 341 | - )) | |
| 342 | - .bind(("usr", user.record())) | |
| 343 | - .bind(("name", user.key().to_string())) | |
| 344 | - .await | |
| 345 | - .unwrap() | |
| 346 | - .check() | |
| 347 | - .unwrap(); | |
| 335 | + let user = UserId::generate(); | |
| 336 | + sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')") | |
| 337 | + .bind(user.uuid()) | |
| 338 | + .bind(format!("u{}", &user.key()[..8])) | |
| 339 | + .execute(db) | |
| 340 | + .await | |
| 341 | + .unwrap(); | |
| 348 | 342 | user |
| 349 | 343 | } |
| 350 | 344 | |
| 351 | - /// `(pool_approved_total, pool_published_total)` as stored — absent reads | |
| 352 | - /// zero, the way `BadgeStats::load` reads it. | |
| 345 | + /// `(pool_approved_total, pool_published_total)` as stored — the columns | |
| 346 | + /// read zero on a fresh row, the way `BadgeStats::load` reads them. | |
| 353 | 347 | async fn counters(user: &UserId, db: &Database) -> (i64, i64) { |
| 354 | - let mut result = db | |
| 355 | - .query(format!( | |
| 356 | - "SELECT VALUE [({POOL_APPROVED_TOTAL_FIELD} ?? 0), | |
| 357 | - ({POOL_PUBLISHED_TOTAL_FIELD} ?? 0)] FROM $usr" | |
| 358 | - )) | |
| 359 | - .bind(("usr", user.record())) | |
| 360 | - .await | |
| 361 | - .unwrap() | |
| 362 | - .check() | |
| 363 | - .unwrap(); | |
| 364 | - let rows = result.take::<Vec<Vec<i64>>>(0).unwrap(); | |
| 365 | - let row = rows.into_iter().next().unwrap_or_default(); | |
| 348 | + let row = sqlx::query( | |
| 349 | + "SELECT pool_approved_total, pool_published_total \ | |
| 350 | + FROM app_user WHERE id = $1", | |
| 351 | + ) | |
| 352 | + .bind(user.uuid()) | |
| 353 | + .fetch_one(db) | |
| 354 | + .await | |
| 355 | + .unwrap(); | |
| 366 | 356 | ( |
| 367 | - row.first().copied().unwrap_or(0), | |
| 368 | - row.get(1).copied().unwrap_or(0), | |
| 357 | + row.try_get::<i64, _>(0).unwrap(), | |
| 358 | + row.try_get::<i64, _>(1).unwrap(), | |
| 369 | 359 | ) |
| 370 | 360 | } |
| 371 | 361 | |
| @@ -380,9 +370,9 @@ mod tests { | ||
| 380 | 370 | |
| 381 | 371 | #[tokio::test] |
| 382 | 372 | async fn approval_is_a_one_way_race_safe_transition() { |
| 383 | - let db = database::init_mem().await.unwrap(); | |
| 384 | - let asker = UserId::from_key(&Ulid::generate().to_string()); | |
| 385 | - let teacher = UserId::from_key(&Ulid::generate().to_string()); | |
| 373 | + let (db, _leases) = database::init_test_db().await; | |
| 374 | + let asker = a_user(&db).await; | |
| 375 | + let teacher = a_user(&db).await; | |
| 386 | 376 | |
| 387 | 377 | let q = insert(&db, question(&asker)).await.unwrap(); |
| 388 | 378 | assert_eq!(q.get_status(), STATUS_PENDING); |
| @@ -407,7 +397,7 @@ mod tests { | ||
| 407 | 397 | /// published side, and neither on a second approve of the same question. |
| 408 | 398 | #[tokio::test] |
| 409 | 399 | async fn approval_moves_both_counters_once_and_only_once() { |
| 410 | - let db = database::init_mem().await.unwrap(); | |
| 400 | + let (db, _leases) = database::init_test_db().await; | |
| 411 | 401 | let asker = a_user(&db).await; |
| 412 | 402 | let teacher = a_user(&db).await; |
| 413 | 403 | |
| @@ -440,7 +430,7 @@ mod tests { | ||
| 440 | 430 | /// neither counter moves when one person is both ends of the transition. |
| 441 | 431 | #[tokio::test] |
| 442 | 432 | async fn self_approval_still_approves_but_moves_neither_counter() { |
| 443 | - let db = database::init_mem().await.unwrap(); | |
| 433 | + let (db, _leases) = database::init_test_db().await; | |
| 444 | 434 | let teacher = a_user(&db).await; |
| 445 | 435 | |
| 446 | 436 | let q = insert(&db, question(&teacher)).await.unwrap(); |
| @@ -464,10 +454,10 @@ mod tests { | ||
| 464 | 454 | |
| 465 | 455 | #[tokio::test] |
| 466 | 456 | async fn visibility_hides_others_pending_questions() { |
| 467 | - let db = database::init_mem().await.unwrap(); | |
| 468 | - let asker = UserId::from_key(&Ulid::generate().to_string()); | |
| 469 | - let other = UserId::from_key(&Ulid::generate().to_string()); | |
| 470 | - let teacher = UserId::from_key(&Ulid::generate().to_string()); | |
| 457 | + let (db, _leases) = database::init_test_db().await; | |
| 458 | + let asker = a_user(&db).await; | |
| 459 | + let other = a_user(&db).await; | |
| 460 | + let teacher = a_user(&db).await; | |
| 471 | 461 | |
| 472 | 462 | let pending = insert(&db, question(&asker)).await.unwrap(); |
| 473 | 463 | let published = insert(&db, question(&other)).await.unwrap(); |
| @@ -488,9 +478,9 @@ mod tests { | ||
| 488 | 478 | |
| 489 | 479 | #[tokio::test] |
| 490 | 480 | async fn image_attaches_only_while_pending_and_reports_the_replaced_blob() { |
| 491 | - let db = database::init_mem().await.unwrap(); | |
| 492 | - let asker = UserId::from_key(&Ulid::generate().to_string()); | |
| 493 | - let teacher = UserId::from_key(&Ulid::generate().to_string()); | |
| 481 | + let (db, _leases) = database::init_test_db().await; | |
| 482 | + let asker = a_user(&db).await; | |
| 483 | + let teacher = a_user(&db).await; | |
| 494 | 484 | let png = FileContentType::try_new("image/png").unwrap(); |
| 495 | 485 | |
| 496 | 486 | let q = insert(&db, question(&asker)).await.unwrap(); |
| @@ -535,9 +525,9 @@ mod tests { | ||
| 535 | 525 | |
| 536 | 526 | #[tokio::test] |
| 537 | 527 | async fn delete_cascades_solutions_and_returns_the_row() { |
| 538 | - let db = database::init_mem().await.unwrap(); | |
| 539 | - let asker = UserId::from_key(&Ulid::generate().to_string()); | |
| 540 | - let helper = UserId::from_key(&Ulid::generate().to_string()); | |
| 528 | + let (db, _leases) = database::init_test_db().await; | |
| 529 | + let asker = a_user(&db).await; | |
| 530 | + let helper = a_user(&db).await; | |
| 541 | 531 | |
| 542 | 532 | let q = insert(&db, question(&asker)).await.unwrap(); |
| 543 | 533 | let offered = crate::db::solution::insert( |
| @@ -609,8 +599,8 @@ mod tests { | ||
| 609 | 599 | |
| 610 | 600 | let (mut solutions, mut swept, mut delete_500) = (0, 0, 0); |
| 611 | 601 | for round in 0..4 { |
| 612 | - let asker = UserId::from_key(&Ulid::generate().to_string()); | |
| 613 | - let helper = UserId::from_key(&Ulid::generate().to_string()); | |
| 602 | + let asker = a_user(&db).await; | |
| 603 | + let helper = a_user(&db).await; | |
| 614 | 604 | let q = insert(&db, question(&asker)).await.unwrap(); |
| 615 | 605 | let id = q.get_id().clone(); |
| 616 | 606 |
src/db/profile.rsmodified+3 -3
| @@ -126,7 +126,7 @@ mod tests { | ||
| 126 | 126 | VALUES ($1, $2, 1000, 3000), ($3, $2, 5000, 6000)", |
| 127 | 127 | ) |
| 128 | 128 | .bind(uuid::Uuid::now_v7()) |
| 129 | - .bind(user.uuid()) | |
| 129 | + .bind(user.get_id().uuid()) | |
| 130 | 130 | .bind(uuid::Uuid::now_v7()) |
| 131 | 131 | .execute(&db) |
| 132 | 132 | .await |
| @@ -136,7 +136,7 @@ mod tests { | ||
| 136 | 136 | "INSERT INTO pomodoro_session (id, app_user, started_at) VALUES ($1, $2, 9000)", |
| 137 | 137 | ) |
| 138 | 138 | .bind(uuid::Uuid::now_v7()) |
| 139 | - .bind(user.uuid()) | |
| 139 | + .bind(user.get_id().uuid()) | |
| 140 | 140 | .execute(&db) |
| 141 | 141 | .await |
| 142 | 142 | .unwrap(); |
| @@ -158,7 +158,7 @@ mod tests { | ||
| 158 | 158 | VALUES ($1, $2, 5000, 1000)", |
| 159 | 159 | ) |
| 160 | 160 | .bind(uuid::Uuid::now_v7()) |
| 161 | - .bind(user.uuid()) | |
| 161 | + .bind(user.get_id().uuid()) | |
| 162 | 162 | .execute(&db) |
| 163 | 163 | .await |
| 164 | 164 | .unwrap(); |
src/db/question_image.rsmodified+4 -4
| @@ -248,7 +248,7 @@ mod tests { | ||
| 248 | 248 | |
| 249 | 249 | #[tokio::test] |
| 250 | 250 | async fn upsert_replaces_per_slot() { |
| 251 | - let db = crate::database::init_mem().await.unwrap(); | |
| 251 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 252 | 252 | let exam = exam_row(&db).await; |
| 253 | 253 | let question = ExamQuestionId::generate(); |
| 254 | 254 | let ids = choice_ids(); |
| @@ -293,7 +293,7 @@ mod tests { | ||
| 293 | 293 | /// options keeps exactly their pictures, and drops only the removed one's. |
| 294 | 294 | #[tokio::test] |
| 295 | 295 | async fn only_the_dropped_options_lose_their_pictures() { |
| 296 | - let db = crate::database::init_mem().await.unwrap(); | |
| 296 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 297 | 297 | let exam = exam_row(&db).await; |
| 298 | 298 | let question = ExamQuestionId::generate(); |
| 299 | 299 | let ids = choice_ids(); |
| @@ -335,7 +335,7 @@ mod tests { | ||
| 335 | 335 | |
| 336 | 336 | #[tokio::test] |
| 337 | 337 | async fn an_empty_keep_set_clears_every_option_picture_but_not_the_illustration() { |
| 338 | - let db = crate::database::init_mem().await.unwrap(); | |
| 338 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 339 | 339 | let exam = exam_row(&db).await; |
| 340 | 340 | let question = ExamQuestionId::generate(); |
| 341 | 341 | let ids = choice_ids(); |
| @@ -362,7 +362,7 @@ mod tests { | ||
| 362 | 362 | |
| 363 | 363 | #[tokio::test] |
| 364 | 364 | async fn exam_listing_scopes_by_exam() { |
| 365 | - let db = crate::database::init_mem().await.unwrap(); | |
| 365 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 366 | 366 | let exam_a = exam_row(&db).await; |
| 367 | 367 | let exam_b = exam_row(&db).await; |
| 368 | 368 | upsert( |
src/db/rag_output.rsmodified+3 -3
| @@ -207,7 +207,7 @@ mod tests { | ||
| 207 | 207 | /// the note cascade takes every row of the note with it. |
| 208 | 208 | #[tokio::test] |
| 209 | 209 | async fn create_reads_back_and_cascades_from_the_note() { |
| 210 | - let db = crate::database::init_mem().await.unwrap(); | |
| 210 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 211 | 211 | let note = note_of(&db, "n").await; |
| 212 | 212 | let file = a_file(&db, ¬e).await; |
| 213 | 213 | let row = create( |
| @@ -231,7 +231,7 @@ mod tests { | ||
| 231 | 231 | /// drops a row built from a file that is gone. |
| 232 | 232 | #[tokio::test] |
| 233 | 233 | async fn replace_is_newest_wins_and_source_cascade_drops() { |
| 234 | - let db = crate::database::init_mem().await.unwrap(); | |
| 234 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 235 | 235 | let note = note_of(&db, "n").await; |
| 236 | 236 | let file = a_file(&db, ¬e).await; |
| 237 | 237 | let first = create( |
| @@ -265,7 +265,7 @@ mod tests { | ||
| 265 | 265 | /// Deleting one row returns it; deleting it again is a 404. |
| 266 | 266 | #[tokio::test] |
| 267 | 267 | async fn delete_returns_the_row_then_refuses() { |
| 268 | - let db = crate::database::init_mem().await.unwrap(); | |
| 268 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 269 | 269 | let note = note_of(&db, "n").await; |
| 270 | 270 | let row = create(&db, note.get_id(), note.get_course(), Vec::new(), json!({})) |
| 271 | 271 | .await |
src/db/session.rsmodified+19 -6
| @@ -87,14 +87,27 @@ mod tests { | ||
| 87 | 87 | |
| 88 | 88 | #[tokio::test] |
| 89 | 89 | async fn purge_expired_removes_only_past_sessions() { |
| 90 | - let db = crate::database::init_mem().await.unwrap(); | |
| 91 | - db.query( | |
| 92 | - "CREATE session SET user = type::record('user', 'u'), token = 'past', expires_at = 1; | |
| 93 | - CREATE session SET user = type::record('user', 'u'), token = 'future', expires_at = 99999999999999;", | |
| 90 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 91 | + // The session's owner is a foreign key now: a real `app_user` row | |
| 92 | + // under the fixture's fixed key, then two rows either side of `now`. | |
| 93 | + let user = UserId::from_key("019732e3-7b00-7000-8000-00000000cab0"); | |
| 94 | + sqlx::query( | |
| 95 | + "INSERT INTO app_user (id, username, password_hash) \ | |
| 96 | + VALUES ($1, 'purge-fixture', 'x')", | |
| 94 | 97 | ) |
| 98 | + .bind(user.uuid()) | |
| 99 | + .execute(&db) | |
| 100 | + .await | |
| 101 | + .unwrap(); | |
| 102 | + sqlx::query( | |
| 103 | + "INSERT INTO user_session (id, app_user, token, expires_at) \ | |
| 104 | + VALUES ($1, $3, 'past', 1), ($2, $3, 'future', 99999999999999)", | |
| 105 | + ) | |
| 106 | + .bind(UserId::generate().uuid()) | |
| 107 | + .bind(UserId::generate().uuid()) | |
| 108 | + .bind(user.uuid()) | |
| 109 | + .execute(&db) | |
| 95 | 110 | .await |
| 96 | - .unwrap() | |
| 97 | - .check() | |
| 98 | 111 | .unwrap(); |
| 99 | 112 | |
| 100 | 113 | assert_eq!(purge_expired(&db).await.unwrap(), 1); |
src/db/session_attendance.rsmodified+28 -27
| @@ -299,7 +299,7 @@ pub async fn remove( | ||
| 299 | 299 | mod tests { |
| 300 | 300 | use super::*; |
| 301 | 301 | use crate::constant::DEFAULT_ATTENDANCE_STATUSES; |
| 302 | - use crate::database::init_mem; | |
| 302 | + use crate::database::init_test_db; | |
| 303 | 303 | use crate::domain::course_session::SessionTopic; |
| 304 | 304 | use crate::domain::role::Role; |
| 305 | 305 | |
| @@ -307,15 +307,19 @@ mod tests { | ||
| 307 | 307 | /// writes nothing at all to a record that does not exist), and the live |
| 308 | 308 | /// role is what decides whether the attended counter moves. |
| 309 | 309 | async fn a_user(key: &str, role: Role, db: &Database) -> UserId { |
| 310 | - let user = UserId::from_key(key); | |
| 311 | - db.query("CREATE $usr SET username = $name, password_hash = 'x', role = $role") | |
| 312 | - .bind(("usr", user.record())) | |
| 313 | - .bind(("name", key.to_string())) | |
| 314 | - .bind(("role", role)) | |
| 315 | - .await | |
| 316 | - .unwrap() | |
| 317 | - .check() | |
| 318 | - .unwrap(); | |
| 310 | + // Minted fresh: the id is a real parent row now, and the minted uuid | |
| 311 | + // keeps repeated calls (same label, new person) collision-free. | |
| 312 | + let user = UserId::generate(); | |
| 313 | + sqlx::query( | |
| 314 | + "INSERT INTO app_user (id, username, password_hash, role) \ | |
| 315 | + VALUES ($1, $2, 'x', $3)", | |
| 316 | + ) | |
| 317 | + .bind(user.uuid()) | |
| 318 | + .bind(format!("{key}-{}", &user.key()[..8])) | |
| 319 | + .bind(role.as_str()) | |
| 320 | + .execute(db) | |
| 321 | + .await | |
| 322 | + .unwrap(); | |
| 319 | 323 | user |
| 320 | 324 | } |
| 321 | 325 | |
| @@ -376,7 +380,7 @@ mod tests { | ||
| 376 | 380 | /// a re-mark and a swap within the same class are both no-ops. |
| 377 | 381 | #[tokio::test] |
| 378 | 382 | async fn the_counter_follows_every_crossing_and_no_other_move() { |
| 379 | - let db = init_mem().await.unwrap(); | |
| 383 | + let (db, _leases) = init_test_db().await; | |
| 380 | 384 | let teacher = a_teacher("t", &db).await; |
| 381 | 385 | let student = a_student("s", &db).await; |
| 382 | 386 | let session = a_session(&teacher, &db).await; |
| @@ -410,7 +414,7 @@ mod tests { | ||
| 410 | 414 | /// once: the whole roster, and every later correction, ride the same stamp. |
| 411 | 415 | #[tokio::test] |
| 412 | 416 | async fn the_first_roll_call_counts_the_lesson_once() { |
| 413 | - let db = init_mem().await.unwrap(); | |
| 417 | + let (db, _leases) = init_test_db().await; | |
| 414 | 418 | let teacher = a_teacher("t", &db).await; |
| 415 | 419 | let other = a_teacher("o", &db).await; |
| 416 | 420 | let session = a_session(&teacher, &db).await; |
| @@ -439,7 +443,7 @@ mod tests { | ||
| 439 | 443 | /// two hundred lessons for next week and hold all of them this afternoon. |
| 440 | 444 | #[tokio::test] |
| 441 | 445 | async fn a_lesson_that_has_not_started_holds_nothing_yet() { |
| 442 | - let db = init_mem().await.unwrap(); | |
| 446 | + let (db, _leases) = init_test_db().await; | |
| 443 | 447 | let teacher = a_teacher("t", &db).await; |
| 444 | 448 | let student = a_student("s", &db).await; |
| 445 | 449 | let next_week = |
| @@ -474,7 +478,7 @@ mod tests { | ||
| 474 | 478 | /// lesson held. |
| 475 | 479 | #[tokio::test] |
| 476 | 480 | async fn a_teacher_marked_present_earns_nothing_for_attending() { |
| 477 | - let db = init_mem().await.unwrap(); | |
| 481 | + let (db, _leases) = init_test_db().await; | |
| 478 | 482 | let teacher = a_teacher("t", &db).await; |
| 479 | 483 | let session = a_session(&teacher, &db).await; |
| 480 | 484 | |
| @@ -501,7 +505,7 @@ mod tests { | ||
| 501 | 505 | /// Two lessons are two counts — the counter is per row, not per student. |
| 502 | 506 | #[tokio::test] |
| 503 | 507 | async fn each_lesson_counts_once_for_the_student_marked() { |
| 504 | - let db = init_mem().await.unwrap(); | |
| 508 | + let (db, _leases) = init_test_db().await; | |
| 505 | 509 | let teacher = a_teacher("t", &db).await; |
| 506 | 510 | let student = a_student("s", &db).await; |
| 507 | 511 | let other = a_student("o", &db).await; |
| @@ -519,7 +523,7 @@ mod tests { | ||
| 519 | 523 | /// that was counted. |
| 520 | 524 | #[tokio::test] |
| 521 | 525 | async fn removing_a_row_gives_back_only_what_it_took() { |
| 522 | - let db = init_mem().await.unwrap(); | |
| 526 | + let (db, _leases) = init_test_db().await; | |
| 523 | 527 | let teacher = a_teacher("t", &db).await; |
| 524 | 528 | let student = a_student("s", &db).await; |
| 525 | 529 | |
| @@ -562,7 +566,7 @@ mod tests { | ||
| 562 | 566 | /// a stale row starts from, the counter never goes negative. |
| 563 | 567 | #[tokio::test] |
| 564 | 568 | async fn the_counter_never_goes_below_zero() { |
| 565 | - let db = init_mem().await.unwrap(); | |
| 569 | + let (db, _leases) = init_test_db().await; | |
| 566 | 570 | let teacher = a_teacher("t", &db).await; |
| 567 | 571 | let student = a_student("s", &db).await; |
| 568 | 572 | |
| @@ -577,14 +581,11 @@ mod tests { | ||
| 577 | 581 | .unwrap(); |
| 578 | 582 | sessions.push(session); |
| 579 | 583 | } |
| 580 | - db.query(format!( | |
| 581 | - "UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} = 0" | |
| 582 | - )) | |
| 583 | - .bind(("usr", student.record())) | |
| 584 | - .await | |
| 585 | - .unwrap() | |
| 586 | - .check() | |
| 587 | - .unwrap(); | |
| 584 | + sqlx::query("UPDATE app_user SET lessons_attended_total = 0 WHERE id = $1") | |
| 585 | + .bind(student.uuid()) | |
| 586 | + .execute(&db) | |
| 587 | + .await | |
| 588 | + .unwrap(); | |
| 588 | 589 | |
| 589 | 590 | for session in &sessions { |
| 590 | 591 | mark(&db, session, &student, status("absent"), &teacher) |
| @@ -601,7 +602,7 @@ mod tests { | ||
| 601 | 602 | /// the ruling every other counter here carries. |
| 602 | 603 | #[tokio::test] |
| 603 | 604 | async fn deleting_the_session_leaves_the_counters_alone() { |
| 604 | - let db = init_mem().await.unwrap(); | |
| 605 | + let (db, _leases) = init_test_db().await; | |
| 605 | 606 | let teacher = a_teacher("t", &db).await; |
| 606 | 607 | let student = a_student("s", &db).await; |
| 607 | 608 | let session = a_session(&teacher, &db).await; |
| @@ -620,7 +621,7 @@ mod tests { | ||
| 620 | 621 | /// a count behind either. |
| 621 | 622 | #[tokio::test] |
| 622 | 623 | async fn a_refused_mark_moves_nothing() { |
| 623 | - let db = init_mem().await.unwrap(); | |
| 624 | + let (db, _leases) = init_test_db().await; | |
| 624 | 625 | let teacher = a_teacher("t", &db).await; |
| 625 | 626 | let student = a_student("s", &db).await; |
| 626 | 627 | let session = a_session(&teacher, &db).await; |
src/db/solution.rsmodified+26 -12
| @@ -254,22 +254,36 @@ pub async fn delete(db: &Database, solution: Solution) -> Result<Solution, AppEr | ||
| 254 | 254 | |
| 255 | 255 | #[cfg(test)] |
| 256 | 256 | mod tests { |
| 257 | - use ulid::Ulid; | |
| 258 | - | |
| 259 | 257 | use super::*; |
| 260 | 258 | use crate::database; |
| 261 | 259 | use crate::domain::pool_question::{PoolQuestion, PoolQuestionBody, PoolQuestionTitle}; |
| 262 | 260 | use crate::domain::timestamp::Timestamp; |
| 263 | 261 | use crate::domain::user::UserId; |
| 264 | 262 | |
| 263 | + /// A real `app_user` row: askers and authors are foreign keys now. | |
| 264 | + async fn a_person(db: &Database, label: &str) -> UserId { | |
| 265 | + let user = UserId::generate(); | |
| 266 | + sqlx::query( | |
| 267 | + "INSERT INTO app_user (id, username, password_hash) \ | |
| 268 | + VALUES ($1, $2, 'x')", | |
| 269 | + ) | |
| 270 | + .bind(user.uuid()) | |
| 271 | + .bind(format!("{label}-{}", &user.key()[..8])) | |
| 272 | + .execute(db) | |
| 273 | + .await | |
| 274 | + .unwrap(); | |
| 275 | + user | |
| 276 | + } | |
| 277 | + | |
| 265 | 278 | /// A real question row: offering a solution moves its question's |
| 266 | 279 | /// `asked_at` (that is what keeps a solution from outliving its question), |
| 267 | 280 | /// so a minted id nothing wrote is a 404. |
| 268 | 281 | async fn question_row(db: &Database) -> PoolQuestionId { |
| 282 | + let asker = a_person(db, "asker").await; | |
| 269 | 283 | crate::db::pool_question::insert( |
| 270 | 284 | db, |
| 271 | 285 | PoolQuestion::new( |
| 272 | - &UserId::from_key(&Ulid::generate().to_string()), | |
| 286 | + &asker, | |
| 273 | 287 | PoolQuestionTitle::try_new("soru").unwrap(), |
| 274 | 288 | PoolQuestionBody::try_new("neden").unwrap(), |
| 275 | 289 | ), |
| @@ -282,10 +296,10 @@ mod tests { | ||
| 282 | 296 | |
| 283 | 297 | #[tokio::test] |
| 284 | 298 | async fn rows_scope_to_their_question_and_list_oldest_first() { |
| 285 | - let db = database::init_mem().await.unwrap(); | |
| 299 | + let (db, _leases) = database::init_test_db().await; | |
| 286 | 300 | let question_a = question_row(&db).await; |
| 287 | 301 | let question_b = question_row(&db).await; |
| 288 | - let author = UserId::from_key(&Ulid::generate().to_string()); | |
| 302 | + let author = a_person(&db, "author").await; | |
| 289 | 303 | |
| 290 | 304 | // Distinct offer times so the assertion pins the real contract — |
| 291 | 305 | // older `offered_at` sorts first — not the same-millisecond `id` |
| @@ -341,7 +355,7 @@ mod tests { | ||
| 341 | 355 | |
| 342 | 356 | #[tokio::test] |
| 343 | 357 | async fn image_set_replace_clear_report_the_replaced_blob() { |
| 344 | - let db = database::init_mem().await.unwrap(); | |
| 358 | + let (db, _leases) = database::init_test_db().await; | |
| 345 | 359 | let question = question_row(&db).await; |
| 346 | 360 | let author = UserId::from_key(&Ulid::generate().to_string()); |
| 347 | 361 | let png = FileContentType::try_new("image/png").unwrap(); |
| @@ -402,7 +416,7 @@ mod tests { | ||
| 402 | 416 | |
| 403 | 417 | #[tokio::test] |
| 404 | 418 | async fn set_body_edits_in_place() { |
| 405 | - let db = database::init_mem().await.unwrap(); | |
| 419 | + let (db, _leases) = database::init_test_db().await; | |
| 406 | 420 | let question = question_row(&db).await; |
| 407 | 421 | let author = UserId::from_key(&Ulid::generate().to_string()); |
| 408 | 422 | |
| @@ -443,11 +457,11 @@ mod tests { | ||
| 443 | 457 | |
| 444 | 458 | #[tokio::test] |
| 445 | 459 | async fn counts_for_groups_per_question() { |
| 446 | - let db = database::init_mem().await.unwrap(); | |
| 460 | + let (db, _leases) = database::init_test_db().await; | |
| 447 | 461 | let two = question_row(&db).await; |
| 448 | 462 | let one = question_row(&db).await; |
| 449 | 463 | let none = question_row(&db).await; |
| 450 | - let author = UserId::from_key(&Ulid::generate().to_string()); | |
| 464 | + let author = a_person(&db, "author").await; | |
| 451 | 465 | |
| 452 | 466 | for (question, bodies) in [(&two, vec!["a", "b"]), (&one, vec!["c"])] { |
| 453 | 467 | for body in bodies { |
| @@ -463,10 +477,10 @@ mod tests { | ||
| 463 | 477 | let counts = counts_for(&db, &[two.clone(), one.clone(), none.clone()]) |
| 464 | 478 | .await |
| 465 | 479 | .unwrap(); |
| 466 | - assert_eq!(counts.get(two.key()), Some(&2)); | |
| 467 | - assert_eq!(counts.get(one.key()), Some(&1)); | |
| 480 | + assert_eq!(counts.get(two.key().as_str()), Some(&2)); | |
| 481 | + assert_eq!(counts.get(one.key().as_str()), Some(&1)); | |
| 468 | 482 | // No solutions = no entry; the caller reads the miss as zero. |
| 469 | - assert_eq!(counts.get(none.key()), None); | |
| 483 | + assert_eq!(counts.get(none.key().as_str()), None); | |
| 470 | 484 | assert!(counts_for(&db, &[]).await.unwrap().is_empty()); |
| 471 | 485 | } |
| 472 | 486 | } |
src/db/subject.rsmodified+18 -14
| @@ -133,7 +133,9 @@ pub async fn update( | ||
| 133 | 133 | /// The bank's subject is optional metadata, and blocking on it was a dead |
| 134 | 134 | /// end — only the template's owner may re-tag it, so a manager could never |
| 135 | 135 | /// clear their own 409, and a private template raising it leaked its |
| 136 | -/// existence. Its cascade runs *after* the guarded delete, so a refused | |
| 136 | +/// existence. Its cascade clears the templates before the delete — the FK on | |
| 137 | +/// `bank_question.subject` refuses the parent delete while a template still | |
| 138 | +/// points at it — and the one transaction rolls everything back, so a refused | |
| 137 | 139 | /// delete leaves every template's subject where it was. |
| 138 | 140 | pub async fn delete(db: &Database, subject: Subject) -> Result<Subject, AppError> { |
| 139 | 141 | crate::database::tx_with_retry(db, false, async move |tx| { |
| @@ -157,6 +159,20 @@ pub async fn delete(db: &Database, subject: Subject) -> Result<Subject, AppError | ||
| 157 | 159 | "homework still references this subject — re-tag or delete it first", |
| 158 | 160 | )); |
| 159 | 161 | } |
| 162 | + // The bank's cascade clears the templates *before* the delete: | |
| 163 | + // `bank_question.subject` carries a real foreign key, so a template | |
| 164 | + // still pointing at this row makes the `DELETE` itself fail (23503) | |
| 165 | + // — the old store had no enforced reference to release. The guard | |
| 166 | + // above has already decided, and the transaction makes the pair | |
| 167 | + // atomic, so ordering costs nothing: a refused delete (an error | |
| 168 | + // raised anywhere above) rolls the whole thing back and every | |
| 169 | + // template's subject stays where it was. | |
| 170 | + sqlx::query!( | |
| 171 | + r#"UPDATE bank_question SET subject = NULL WHERE subject = $1"#, | |
| 172 | + subject.id.uuid(), | |
| 173 | + ) | |
| 174 | + .execute(&mut *tx) | |
| 175 | + .await?; | |
| 160 | 176 | let deleted = sqlx::query_as!( |
| 161 | 177 | Subject, |
| 162 | 178 | r#"DELETE FROM subject WHERE id = $1 |
| @@ -168,12 +184,6 @@ pub async fn delete(db: &Database, subject: Subject) -> Result<Subject, AppError | ||
| 168 | 184 | ) |
| 169 | 185 | .fetch_one(&mut *tx) |
| 170 | 186 | .await?; |
| 171 | - sqlx::query!( | |
| 172 | - r#"UPDATE bank_question SET subject = NULL WHERE subject = $1"#, | |
| 173 | - subject.id.uuid(), | |
| 174 | - ) | |
| 175 | - .execute(&mut *tx) | |
| 176 | - .await?; | |
| 177 | 187 | Ok(deleted) |
| 178 | 188 | }) |
| 179 | 189 | .await |
| @@ -196,7 +206,6 @@ mod tests { | ||
| 196 | 206 | /// Mutation-tested: with the bare `db.create` this shipped with, all four |
| 197 | 207 | /// rounds orphan. |
| 198 | 208 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 199 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | |
| 200 | 209 | async fn a_subject_never_outlives_its_course() { |
| 201 | 210 | fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> { |
| 202 | 211 | tokio::spawn(async move { |
| @@ -210,12 +219,7 @@ mod tests { | ||
| 210 | 219 | .map(|_| ()) |
| 211 | 220 | }) |
| 212 | 221 | } |
| 213 | - crate::db::course::assert_no_child_outlives_a_course_delete( | |
| 214 | - "subject_orphan_race", | |
| 215 | - SUBJECT_TABLE, | |
| 216 | - make, | |
| 217 | - ) | |
| 218 | - .await; | |
| 222 | + crate::db::course::assert_no_child_outlives_a_course_delete("subject", make).await; | |
| 219 | 223 | } |
| 220 | 224 | |
| 221 | 225 | /// GUARD, not a retry measurement — read the last paragraph before |
src/db/term.rsmodified+2 -2
| @@ -173,7 +173,7 @@ mod tests { | ||
| 173 | 173 | /// refuse it with the same error, having written nothing. |
| 174 | 174 | #[tokio::test] |
| 175 | 175 | async fn a_moved_end_is_refused_against_the_stored_other_end() { |
| 176 | - let db = crate::database::init_mem().await.unwrap(); | |
| 176 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 177 | 177 | let at = Timestamp::from_millis; |
| 178 | 178 | let term = create(&db, TermName::try_new("2026").unwrap(), at(100), at(200)) |
| 179 | 179 | .await |
| @@ -202,7 +202,7 @@ mod tests { | ||
| 202 | 202 | /// tie-break on identical `starts_at` — stored read-back, then page by page. |
| 203 | 203 | #[tokio::test] |
| 204 | 204 | async fn identical_starts_at_still_pages_each_term_exactly_once() { |
| 205 | - let db = crate::database::init_mem().await.unwrap(); | |
| 205 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 206 | 206 | let at = Timestamp::from_millis; |
| 207 | 207 | let mut minted = Vec::new(); |
| 208 | 208 | for i in 0..12 { |
src/db/work_entry.rsmodified+11 -7
| @@ -195,21 +195,25 @@ pub async fn remove(db: &Database, id: &WorkEntryId) -> Result<Option<WorkEntry> | ||
| 195 | 195 | |
| 196 | 196 | #[cfg(test)] |
| 197 | 197 | mod tests { |
| 198 | - use ulid::Ulid; | |
| 199 | - | |
| 200 | 198 | use super::*; |
| 201 | 199 | use crate::database; |
| 202 | 200 | |
| 203 | 201 | #[tokio::test] |
| 204 | 202 | async fn check_in_is_exclusive_until_check_out() { |
| 205 | - let db = database::init_mem().await.unwrap(); | |
| 206 | - // A `record<user>` column checks the table of the id, not row | |
| 207 | - // existence — a fabricated id keeps this test free of user ceremony. | |
| 208 | - let user = UserId::from_key(&Ulid::generate().to_string()); | |
| 203 | + let (db, _leases) = database::init_test_db().await; | |
| 204 | + // The stint's owner is a foreign key now: a real `app_user` row. | |
| 205 | + let user = UserId::generate(); | |
| 206 | + sqlx::query( | |
| 207 | + "INSERT INTO app_user (id, username, password_hash) \ | |
| 208 | + VALUES ($1, 'work-fixture', 'x')", | |
| 209 | + ) | |
| 210 | + .bind(user.uuid()) | |
| 211 | + .execute(&db) | |
| 212 | + .await | |
| 213 | + .unwrap(); | |
| 209 | 214 | |
| 210 | 215 | let open = check_in(&db, &user).await.unwrap(); |
| 211 | 216 | assert!(open.is_open()); |
| 212 | - assert_eq!(open.get_id().key(), format!("open_{}", user.key())); | |
| 213 | 217 | |
| 214 | 218 | // Second check-in must not create a second stint or reset the clock. |
| 215 | 219 | let dup = check_in(&db, &user).await; |
src/service/appointment.rsmodified+9 -9
| @@ -392,7 +392,7 @@ fn contended() -> AppError { | ||
| 392 | 392 | #[cfg(test)] |
| 393 | 393 | mod tests { |
| 394 | 394 | use super::*; |
| 395 | - use crate::database::{Database, init_mem}; | |
| 395 | + use crate::database::{Database, init_test_db}; | |
| 396 | 396 | use crate::service::appointment_slot; |
| 397 | 397 | |
| 398 | 398 | fn at(millis: i64) -> Timestamp { |
| @@ -406,7 +406,7 @@ mod tests { | ||
| 406 | 406 | |
| 407 | 407 | #[tokio::test] |
| 408 | 408 | async fn window_prefers_a_proposal_over_the_slot() { |
| 409 | - let db = init_mem().await.unwrap(); | |
| 409 | + let (db, _leases) = init_test_db().await; | |
| 410 | 410 | let teacher = UserId::from_key("t1"); |
| 411 | 411 | let (starts_at, ends_at) = (soon(60_000), soon(120_000)); |
| 412 | 412 | let slot = appointment_slot::create(&db, &teacher, starts_at, ends_at, None) |
| @@ -431,7 +431,7 @@ mod tests { | ||
| 431 | 431 | /// to undo the resulting meeting, so the booking would be stuck for good. |
| 432 | 432 | #[tokio::test] |
| 433 | 433 | async fn a_started_slot_cannot_be_booked() { |
| 434 | - let db = init_mem().await.unwrap(); | |
| 434 | + let (db, _leases) = init_test_db().await; | |
| 435 | 435 | let teacher = UserId::from_key("t1"); |
| 436 | 436 | let reason = || AppointmentReason::try_new("görüşme").unwrap(); |
| 437 | 437 | let started = appointment_slot::create(&db, &teacher, soon(-30_000), soon(60_000), None) |
| @@ -456,7 +456,7 @@ mod tests { | ||
| 456 | 456 | /// come and gone cannot be accepted — the meeting would be uncancellable. |
| 457 | 457 | #[tokio::test] |
| 458 | 458 | async fn a_started_proposal_cannot_be_accepted() { |
| 459 | - let db = init_mem().await.unwrap(); | |
| 459 | + let (db, _leases) = init_test_db().await; | |
| 460 | 460 | let teacher = UserId::from_key("t1"); |
| 461 | 461 | let student = UserId::from_key("s1"); |
| 462 | 462 | let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) |
| @@ -544,7 +544,7 @@ mod tests { | ||
| 544 | 544 | /// primitive itself with the exact stale snapshot the race produces. |
| 545 | 545 | #[tokio::test] |
| 546 | 546 | async fn a_decision_built_on_a_stale_snapshot_never_lands() { |
| 547 | - let db = init_mem().await.unwrap(); | |
| 547 | + let (db, _leases) = init_test_db().await; | |
| 548 | 548 | let teacher = UserId::from_key("t1"); |
| 549 | 549 | let student = UserId::from_key("s1"); |
| 550 | 550 | let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) |
| @@ -633,7 +633,7 @@ mod tests { | ||
| 633 | 633 | /// second claim succeed and this fail (mutation-proved). |
| 634 | 634 | #[tokio::test] |
| 635 | 635 | async fn a_concurrent_claim_cannot_take_a_booked_slot() { |
| 636 | - let db = init_mem().await.unwrap(); | |
| 636 | + let (db, _leases) = init_test_db().await; | |
| 637 | 637 | let teacher = UserId::from_key("t1"); |
| 638 | 638 | let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) |
| 639 | 639 | .await |
| @@ -674,7 +674,7 @@ mod tests { | ||
| 674 | 674 | /// bumped the counter would strand the slot forever. |
| 675 | 675 | #[tokio::test] |
| 676 | 676 | async fn a_refused_booking_moves_nothing() { |
| 677 | - let db = init_mem().await.unwrap(); | |
| 677 | + let (db, _leases) = init_test_db().await; | |
| 678 | 678 | let teacher = UserId::from_key("t1"); |
| 679 | 679 | let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) |
| 680 | 680 | .await |
| @@ -711,7 +711,7 @@ mod tests { | ||
| 711 | 711 | /// cancel that moved one without the other would strand the slot forever. |
| 712 | 712 | #[tokio::test] |
| 713 | 713 | async fn cancelling_hands_the_seat_back_with_the_status() { |
| 714 | - let db = init_mem().await.unwrap(); | |
| 714 | + let (db, _leases) = init_test_db().await; | |
| 715 | 715 | let teacher = UserId::from_key("t1"); |
| 716 | 716 | let student = UserId::from_key("s1"); |
| 717 | 717 | let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) |
| @@ -749,7 +749,7 @@ mod tests { | ||
| 749 | 749 | /// Occupancy frees on reject, so the slot can be re-booked. |
| 750 | 750 | #[tokio::test] |
| 751 | 751 | async fn rejecting_frees_the_slot_for_re_booking() { |
| 752 | - let db = init_mem().await.unwrap(); | |
| 752 | + let (db, _leases) = init_test_db().await; | |
| 753 | 753 | let teacher = UserId::from_key("t1"); |
| 754 | 754 | let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) |
| 755 | 755 | .await |
src/service/appointment_slot.rsmodified+8 -8
| @@ -208,7 +208,7 @@ mod tests { | ||
| 208 | 208 | |
| 209 | 209 | #[tokio::test] |
| 210 | 210 | async fn a_publish_shares_one_series_and_orders_its_ids() { |
| 211 | - let db = crate::database::init_mem().await.unwrap(); | |
| 211 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 212 | 212 | let teacher = UserId::from_key("t1"); |
| 213 | 213 | let slots = publish_weekly( |
| 214 | 214 | &db, |
| @@ -236,7 +236,7 @@ mod tests { | ||
| 236 | 236 | |
| 237 | 237 | #[tokio::test] |
| 238 | 238 | async fn overlapping_publish_is_refused_but_touching_is_allowed() { |
| 239 | - let db = crate::database::init_mem().await.unwrap(); | |
| 239 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 240 | 240 | let teacher = UserId::from_key("t1"); |
| 241 | 241 | create(&db, &teacher, at(1_000), at(2_000), None) |
| 242 | 242 | .await |
| @@ -265,7 +265,7 @@ mod tests { | ||
| 265 | 265 | |
| 266 | 266 | #[tokio::test] |
| 267 | 267 | async fn weekly_publish_overlapping_an_existing_slot_writes_nothing() { |
| 268 | - let db = crate::database::init_mem().await.unwrap(); | |
| 268 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 269 | 269 | let teacher = UserId::from_key("t1"); |
| 270 | 270 | // A lone slot on the third week of the coming series. |
| 271 | 271 | create( |
| @@ -301,7 +301,7 @@ mod tests { | ||
| 301 | 301 | /// the batch's boundaries must still be allowed. |
| 302 | 302 | #[tokio::test] |
| 303 | 303 | async fn the_batch_wide_conflict_read_still_sees_the_last_week_and_lets_touching_through() { |
| 304 | - let db = crate::database::init_mem().await.unwrap(); | |
| 304 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 305 | 305 | let teacher = UserId::from_key("t1"); |
| 306 | 306 | let last = 1_000 + 4 * MILLIS_PER_WEEK; |
| 307 | 307 | // Touching both ends of the envelope: ends where the first occurrence |
| @@ -319,7 +319,7 @@ mod tests { | ||
| 319 | 319 | ); |
| 320 | 320 | |
| 321 | 321 | // One millisecond into the last occurrence → the whole publish is 409. |
| 322 | - let db = crate::database::init_mem().await.unwrap(); | |
| 322 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 323 | 323 | create(&db, &teacher, at(last + 999), at(last + 3_000), None) |
| 324 | 324 | .await |
| 325 | 325 | .unwrap(); |
| @@ -339,7 +339,7 @@ mod tests { | ||
| 339 | 339 | /// and the free weeks must survive the refusal. |
| 340 | 340 | #[tokio::test] |
| 341 | 341 | async fn a_taken_slot_is_never_deleted_and_takes_its_series_with_it() { |
| 342 | - let db = crate::database::init_mem().await.unwrap(); | |
| 342 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 343 | 343 | let teacher = UserId::from_key("t1"); |
| 344 | 344 | let slots = publish_weekly( |
| 345 | 345 | &db, |
| @@ -394,7 +394,7 @@ mod tests { | ||
| 394 | 394 | /// teacher+ passes through untouched. |
| 395 | 395 | #[tokio::test] |
| 396 | 396 | async fn a_publish_by_someone_who_lost_the_role_is_refused() { |
| 397 | - let db = crate::database::init_mem().await.unwrap(); | |
| 397 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 398 | 398 | // Written as a row rather than through `User` — the password hasher is |
| 399 | 399 | // private to that module, and the only column this asks about is `role`. |
| 400 | 400 | db.query("CREATE user:eski SET username = 'eski', password_hash = 'x', role = 'student'") |
| @@ -535,7 +535,7 @@ mod tests { | ||
| 535 | 535 | |
| 536 | 536 | #[tokio::test] |
| 537 | 537 | async fn weekly_publish_that_self_overlaps_is_refused() { |
| 538 | - let db = crate::database::init_mem().await.unwrap(); | |
| 538 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 539 | 539 | let teacher = UserId::from_key("t1"); |
| 540 | 540 | // A window longer than the weekly step collides with the next week. |
| 541 | 541 | assert!(matches!( |
src/service/board.rsmodified+1 -1
| @@ -229,7 +229,7 @@ mod tests { | ||
| 229 | 229 | /// participant on the other. |
| 230 | 230 | #[tokio::test] |
| 231 | 231 | async fn an_outsider_gets_404_and_a_participant_gets_403() { |
| 232 | - let db = crate::database::init_mem().await.unwrap(); | |
| 232 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 233 | 233 | // (fixtures rebuilt against Postgres in wave 3) |
| 234 | 234 | let _ = &db; |
| 235 | 235 | } |
src/service/builder.rsmodified+1 -1
| @@ -67,7 +67,7 @@ mod tests { | ||
| 67 | 67 | |
| 68 | 68 | #[tokio::test] |
| 69 | 69 | async fn the_seed_is_idempotent_and_never_rewrites_a_credential() { |
| 70 | - let tenants = Tenants::new_mem().await.unwrap(); | |
| 70 | + let tenants = crate::database::init_test_tenants().await; | |
| 71 | 71 | let control = tenants.control(); |
| 72 | 72 | let name = Username::try_new("builder1").unwrap(); |
| 73 | 73 | ensure(control, name.clone(), Password::try_new("secret1").unwrap()) |
src/service/class_blueprint.rsmodified+146 -105
| @@ -375,9 +375,10 @@ pub async fn status( | ||
| 375 | 375 | #[cfg(test)] |
| 376 | 376 | mod tests { |
| 377 | 377 | use super::*; |
| 378 | - use crate::constant::{CLASS_COURSE_COUNT_FIELD, MAX_CLASS_COURSES}; | |
| 379 | - use crate::db::class_member::tests::{a_class, a_course, counter, exists, rows}; | |
| 380 | - use crate::domain::class_course::ClassCourseId; | |
| 378 | + use crate::constant::MAX_CLASS_COURSES; | |
| 379 | + use crate::db::class_member::tests::{ | |
| 380 | + a_class, a_course, counter, fixture_user, link_exists, rows, | |
| 381 | + }; | |
| 381 | 382 | use crate::domain::class_group::{ClassGroup, ClassName}; |
| 382 | 383 | |
| 383 | 384 | /// A section that a pump's own grade loop can actually find — [`a_class`] |
| @@ -397,9 +398,10 @@ mod tests { | ||
| 397 | 398 | |
| 398 | 399 | /// A blueprint holding `courses`, at grade "9". |
| 399 | 400 | async fn a_blueprint(courses: Vec<CourseId>, db: &Database) -> ClassBlueprint { |
| 401 | + let manager = fixture_user(db, "manager").await; | |
| 400 | 402 | create( |
| 401 | 403 | db, |
| 402 | - &UserId::from_key("manager"), | |
| 404 | + &manager, | |
| 403 | 405 | ClassBlueprint::grade_key("9").unwrap(), |
| 404 | 406 | courses, |
| 405 | 407 | ) |
| @@ -416,22 +418,21 @@ mod tests { | ||
| 416 | 418 | /// really produces it, not from the enum. |
| 417 | 419 | #[tokio::test] |
| 418 | 420 | async fn a_skip_names_what_actually_failed() { |
| 419 | - let manager = UserId::from_key("manager"); | |
| 421 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 422 | + let manager = fixture_user(&db, "manager").await; | |
| 420 | 423 | |
| 421 | 424 | // The course is deleted out from under the pump: the pivot claim |
| 422 | 425 | // matches nothing. |
| 423 | - let db = crate::database::init_mem().await.unwrap(); | |
| 424 | 426 | let course = a_course("algebra", None, &db).await; |
| 425 | 427 | let class = class_group::read(&db, &a_class("9-A", &db).await) |
| 426 | 428 | .await |
| 427 | 429 | .unwrap() |
| 428 | 430 | .unwrap(); |
| 429 | 431 | let blueprint = a_blueprint(vec![course.clone()], &db).await; |
| 430 | - db.query("DELETE $c") | |
| 431 | - .bind(("c", course.record())) | |
| 432 | + sqlx::query("DELETE FROM course WHERE id = $1") | |
| 433 | + .bind(course.uuid()) | |
| 434 | + .execute(&db) | |
| 432 | 435 | .await |
| 433 | - .unwrap() | |
| 434 | - .check() | |
| 435 | 436 | .unwrap(); |
| 436 | 437 | let skipped = apply_to(&db, &blueprint, &class, &manager).await.unwrap(); |
| 437 | 438 | assert_eq!(skipped.len(), 1, "{skipped:?}"); |
| @@ -453,18 +454,17 @@ mod tests { | ||
| 453 | 454 | |
| 454 | 455 | // The class is deleted out from under the pump: the counter claim |
| 455 | 456 | // matches nothing and the read that follows finds no row. |
| 456 | - let db = crate::database::init_mem().await.unwrap(); | |
| 457 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 457 | 458 | let course = a_course("algebra", None, &db).await; |
| 458 | 459 | let class = class_group::read(&db, &a_class("9-A", &db).await) |
| 459 | 460 | .await |
| 460 | 461 | .unwrap() |
| 461 | 462 | .unwrap(); |
| 462 | 463 | let blueprint = a_blueprint(vec![course.clone()], &db).await; |
| 463 | - db.query("DELETE $c") | |
| 464 | - .bind(("c", class.get_id().record())) | |
| 464 | + sqlx::query("DELETE FROM class_group WHERE id = $1") | |
| 465 | + .bind(class.get_id().uuid()) | |
| 466 | + .execute(&db) | |
| 465 | 467 | .await |
| 466 | - .unwrap() | |
| 467 | - .check() | |
| 468 | 468 | .unwrap(); |
| 469 | 469 | let skipped = apply_to(&db, &blueprint, &class, &manager).await.unwrap(); |
| 470 | 470 | assert_eq!(skipped.len(), 1, "{skipped:?}"); |
| @@ -484,22 +484,22 @@ mod tests { | ||
| 484 | 484 | |
| 485 | 485 | // The class stands at its own ceiling: the same claim matches nothing, |
| 486 | 486 | // but the row is there — and that is the one a manager can act on. |
| 487 | - let db = crate::database::init_mem().await.unwrap(); | |
| 487 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 488 | 488 | let course = a_course("algebra", None, &db).await; |
| 489 | 489 | let class = class_group::read(&db, &a_class("9-A", &db).await) |
| 490 | 490 | .await |
| 491 | 491 | .unwrap() |
| 492 | 492 | .unwrap(); |
| 493 | 493 | let blueprint = a_blueprint(vec![course], &db).await; |
| 494 | - db.query(format!( | |
| 495 | - "UPDATE $c SET {} = $cap", | |
| 496 | - crate::constant::CLASS_COURSE_COUNT_FIELD | |
| 497 | - )) | |
| 498 | - .bind(("c", class.get_id().record())) | |
| 499 | - .bind(("cap", MAX_CLASS_COURSES)) | |
| 494 | + sqlx::query( | |
| 495 | + sqlx::AssertSqlSafe(format!( | |
| 496 | + "UPDATE class_group SET class_course_count = {} WHERE id = $1", | |
| 497 | + MAX_CLASS_COURSES | |
| 498 | + )), | |
| 499 | + ) | |
| 500 | + .bind(class.get_id().uuid()) | |
| 501 | + .execute(&db) | |
| 500 | 502 | .await |
| 501 | - .unwrap() | |
| 502 | - .check() | |
| 503 | 503 | .unwrap(); |
| 504 | 504 | let skipped = apply_to(&db, &blueprint, &class, &manager).await.unwrap(); |
| 505 | 505 | assert_eq!(skipped.len(), 1, "{skipped:?}"); |
| @@ -518,8 +518,8 @@ mod tests { | ||
| 518 | 518 | /// this caller in, and deterministic where two live requests are not. |
| 519 | 519 | #[tokio::test] |
| 520 | 520 | async fn a_delete_of_a_list_that_moved_is_a_409_that_writes_nothing() { |
| 521 | - let db = crate::database::init_mem().await.unwrap(); | |
| 522 | - let manager = UserId::from_key("manager"); | |
| 521 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 522 | + let manager = fixture_user(&db, "manager").await; | |
| 523 | 523 | let algebra = a_course("algebra", None, &db).await; |
| 524 | 524 | let physics = a_course("physics", None, &db).await; |
| 525 | 525 | let class = class_group::read(&db, &a_class("9-A", &db).await) |
| @@ -555,7 +555,7 @@ mod tests { | ||
| 555 | 555 | "the row the caller did not read is still there" |
| 556 | 556 | ); |
| 557 | 557 | assert_eq!( |
| 558 | - rows("SELECT VALUE id FROM class_course", &db).await, | |
| 558 | + rows("class_course", &db).await, | |
| 559 | 559 | 2, |
| 560 | 560 | "and neither attachment was swept — including the one this handle \ |
| 561 | 561 | never knew about" |
| @@ -572,47 +572,71 @@ mod tests { | ||
| 572 | 572 | /// and the delete is watched not-finishing on a timeout. |
| 573 | 573 | #[tokio::test] |
| 574 | 574 | async fn a_delete_waits_for_an_attach_in_flight() { |
| 575 | - let db = crate::database::init_mem().await.unwrap(); | |
| 576 | - let manager = UserId::from_key("manager"); | |
| 575 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 576 | + let manager = fixture_user(&db, "manager").await; | |
| 577 | 577 | let algebra = a_course("algebra", None, &db).await; |
| 578 | 578 | let class = class_group::read(&db, &a_class("9-A", &db).await) |
| 579 | 579 | .await |
| 580 | 580 | .unwrap() |
| 581 | 581 | .unwrap(); |
| 582 | - let blueprint = a_blueprint(vec![algebra], &db).await; | |
| 582 | + let blueprint = a_blueprint(vec![algebra.clone()], &db).await; | |
| 583 | 583 | apply_to(&db, &blueprint, &class, &manager).await.unwrap(); |
| 584 | 584 | |
| 585 | - // Stand in for an attach mid-transaction, which is exactly the lease | |
| 586 | - // `apply_to` holds around one course. | |
| 587 | - let attaching = BLUEPRINT_LOCK.read().await; | |
| 588 | - let mut deleting = { | |
| 589 | - let db = db.clone(); | |
| 590 | - let blueprint = blueprint.clone(); | |
| 591 | - tokio::spawn(async move { delete(&db, blueprint).await }) | |
| 585 | + // The lease is gone with the lock; the whole compare-and-set-plus- | |
| 586 | + // sweep is one transaction now, and the pump claims the blueprint | |
| 587 | + // inside its own. A barrier start lets the racing attach and delete | |
| 588 | + // interleave every which way — in all of them no `class_course` row | |
| 589 | + // may survive a blueprint that is gone, and no counter may drift. | |
| 590 | + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | |
| 591 | + let deleting = { | |
| 592 | + let (db, blueprint, gate) = (db.clone(), blueprint.clone(), gate.clone()); | |
| 593 | + tokio::spawn(async move { | |
| 594 | + gate.wait().await; | |
| 595 | + delete(&db, blueprint).await | |
| 596 | + }) | |
| 592 | 597 | }; |
| 593 | - assert!( | |
| 594 | - tokio::time::timeout(std::time::Duration::from_millis(150), &mut deleting) | |
| 595 | - .await | |
| 596 | - .is_err(), | |
| 597 | - "the delete must not run while an attach is in flight" | |
| 598 | - ); | |
| 599 | - assert_eq!( | |
| 600 | - rows("SELECT VALUE id FROM class_blueprint", &db).await, | |
| 601 | - 1, | |
| 602 | - "…and it must not have swept anything either" | |
| 603 | - ); | |
| 598 | + let pumping = { | |
| 599 | + let (db, class, algebra, manager, gate) = | |
| 600 | + (db.clone(), class.clone(), algebra.clone(), manager.clone(), gate); | |
| 601 | + tokio::spawn(async move { | |
| 602 | + gate.wait().await; | |
| 603 | + apply_to(&db, &blueprint, &class, &manager).await | |
| 604 | + }) | |
| 605 | + }; | |
| 606 | + let (deleted, pumped) = (deleting.await.unwrap(), pumping.await.unwrap()); | |
| 607 | + deleted.unwrap(); | |
| 604 | 608 | |
| 605 | - drop(attaching); | |
| 606 | - deleting.await.unwrap().unwrap(); | |
| 609 | + // The delete went through; whatever the pump answered, the stored | |
| 610 | + // state must agree with itself. | |
| 607 | 611 | assert_eq!( |
| 608 | - rows("SELECT VALUE id FROM class_blueprint", &db).await, | |
| 612 | + rows("class_blueprint", &db).await, | |
| 609 | 613 | 0, |
| 610 | - "once the attach is done the delete goes through" | |
| 614 | + "the delete goes through" | |
| 611 | 615 | ); |
| 616 | + let skipped = pumped.unwrap(); | |
| 617 | + if skipped.iter().any(|s| s.reason == "blueprint_deleted") { | |
| 618 | + assert_eq!( | |
| 619 | + rows("class_course", &db).await, | |
| 620 | + 0, | |
| 621 | + "a pump that read a dead blueprint attaches nothing" | |
| 622 | + ); | |
| 623 | + } else { | |
| 624 | + // The pump beat the delete to the claim and attached cleanly: its | |
| 625 | + // rows go with the blueprint the sweep then took. | |
| 626 | + assert!( | |
| 627 | + skipped.is_empty(), | |
| 628 | + "neither a clean attach nor a clean skip: {skipped:?}" | |
| 629 | + ); | |
| 630 | + assert_eq!( | |
| 631 | + rows("class_course", &db).await, | |
| 632 | + 0, | |
| 633 | + "the sweep took the rows the winning pump had just written" | |
| 634 | + ); | |
| 635 | + } | |
| 612 | 636 | assert_eq!( |
| 613 | - rows("SELECT VALUE id FROM class_course", &db).await, | |
| 637 | + counter("class_course_count", class.get_id().uuid(), &db).await, | |
| 614 | 638 | 0, |
| 615 | - "…taking every row carrying its tag with it" | |
| 639 | + "…and whatever happened, the class's counter is back to zero" | |
| 616 | 640 | ); |
| 617 | 641 | } |
| 618 | 642 | |
| @@ -636,58 +660,80 @@ mod tests { | ||
| 636 | 660 | /// assertion rather than passing it by default. |
| 637 | 661 | #[tokio::test] |
| 638 | 662 | async fn a_delete_frees_the_lease_before_its_unbounded_sweep() { |
| 639 | - let db = crate::database::init_mem().await.unwrap(); | |
| 640 | - let manager = UserId::from_key("manager"); | |
| 663 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 664 | + let manager = fixture_user(&db, "manager").await; | |
| 641 | 665 | let courses = vec![ |
| 642 | 666 | a_course("algebra", None, &db).await, |
| 643 | 667 | a_course("physics", None, &db).await, |
| 644 | 668 | ]; |
| 645 | 669 | let blueprint = a_blueprint(courses, &db).await; |
| 646 | - for name in ["9-A", "9-B"] { | |
| 670 | + let mut classes = Vec::new(); | |
| 671 | + for name in ["9-A", "9-B", "9-C"] { | |
| 647 | 672 | let class = class_group::read(&db, &a_class(name, &db).await) |
| 648 | 673 | .await |
| 649 | 674 | .unwrap() |
| 650 | 675 | .unwrap(); |
| 651 | - apply_to(&db, &blueprint, &class, &manager).await.unwrap(); | |
| 676 | + if name != "9-C" { | |
| 677 | + apply_to(&db, &blueprint, &class, &manager).await.unwrap(); | |
| 678 | + } | |
| 679 | + classes.push(class); | |
| 652 | 680 | } |
| 653 | - db.query( | |
| 654 | - "DEFINE EVENT slow_sweep ON TABLE class_course WHEN $event = 'DELETE' \ | |
| 655 | - THEN { SLEEP 300ms; };", | |
| 656 | - ) | |
| 657 | - .await | |
| 658 | - .unwrap() | |
| 659 | - .check() | |
| 660 | - .unwrap(); | |
| 661 | 681 | |
| 682 | + // The lock is gone, so there is no lease to free; what still has to | |
| 683 | + // hold is its point: a pump arriving while the delete's sweep is in | |
| 684 | + // flight is answered by the database, not parked behind the sweep — | |
| 685 | + // and the sweep still takes every row carrying the blueprint's tag. | |
| 686 | + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | |
| 662 | 687 | let deleting = { |
| 663 | - let (db, blueprint) = (db.clone(), blueprint.clone()); | |
| 664 | - tokio::spawn(async move { delete(&db, blueprint).await }) | |
| 688 | + let (db, blueprint, gate) = (db.clone(), blueprint.clone(), gate.clone()); | |
| 689 | + tokio::spawn(async move { | |
| 690 | + gate.wait().await; | |
| 691 | + delete(&db, blueprint).await | |
| 692 | + }) | |
| 665 | 693 | }; |
| 666 | - let beat = std::time::Duration::from_millis(10); | |
| 667 | - // The row is gone the instant the compare-and-set commits, which is | |
| 668 | - // inside the lease this test is about. | |
| 669 | - while rows("SELECT VALUE id FROM class_blueprint", &db).await > 0 { | |
| 670 | - tokio::time::sleep(beat).await; | |
| 671 | - } | |
| 672 | - let mut freed = false; | |
| 673 | - while !deleting.is_finished() { | |
| 674 | - if BLUEPRINT_LOCK.try_read().is_ok() { | |
| 675 | - freed = true; | |
| 676 | - break; | |
| 677 | - } | |
| 678 | - tokio::time::sleep(beat).await; | |
| 679 | - } | |
| 694 | + let pumping = { | |
| 695 | + let (db, class, manager, gate, blueprint) = ( | |
| 696 | + db.clone(), | |
| 697 | + classes[2].clone(), | |
| 698 | + manager.clone(), | |
| 699 | + gate.clone(), | |
| 700 | + blueprint.clone(), | |
| 701 | + ); | |
| 702 | + tokio::spawn(async move { | |
| 703 | + gate.wait().await; | |
| 704 | + apply_to(&db, &blueprint, &class, &manager).await | |
| 705 | + }) | |
| 706 | + }; | |
| 707 | + | |
| 708 | + // The pump is answered in bounded time even though the delete is | |
| 709 | + // sweeping two sections' link rows — and answered with one of the two | |
| 710 | + // honest outcomes, never a 500. | |
| 711 | + let pumped = | |
| 712 | + tokio::time::timeout(std::time::Duration::from_secs(10), pumping) | |
| 713 | + .await | |
| 714 | + .expect("a pump must not wait behind a delete's unbounded sweep") | |
| 715 | + .unwrap(); | |
| 716 | + let skipped = pumped.unwrap(); | |
| 680 | 717 | assert!( |
| 681 | - freed, | |
| 682 | - "a pump may not wait behind a delete's unbounded sweep" | |
| 718 | + skipped.iter().all(|s| { | |
| 719 | + s.reason == "blueprint_deleted" || s.reason == "course_deleted" | |
| 720 | + }) || skipped.is_empty(), | |
| 721 | + "neither a clean attach nor a clean skip: {skipped:?}" | |
| 683 | 722 | ); |
| 684 | 723 | |
| 685 | 724 | deleting.await.unwrap().unwrap(); |
| 686 | 725 | assert_eq!( |
| 687 | - rows("SELECT VALUE id FROM class_course", &db).await, | |
| 726 | + rows("class_course", &db).await, | |
| 688 | 727 | 0, |
| 689 | - "…and the sweep it ran lease-free still took every row it owned" | |
| 728 | + "…and the sweep still took every row it owned" | |
| 690 | 729 | ); |
| 730 | + for class in &classes { | |
| 731 | + assert_eq!( | |
| 732 | + counter("class_course_count", class.get_id().uuid(), &db).await, | |
| 733 | + 0, | |
| 734 | + "…and no counter kept a seat the sweep took back" | |
| 735 | + ); | |
| 736 | + } | |
| 691 | 737 | } |
| 692 | 738 | |
| 693 | 739 | /// The other half: a pump holding a handle to a blueprint that has since |
| @@ -699,8 +745,8 @@ mod tests { | ||
| 699 | 745 | /// reach that row again. |
| 700 | 746 | #[tokio::test] |
| 701 | 747 | async fn a_pump_whose_blueprint_died_attaches_nothing() { |
| 702 | - let db = crate::database::init_mem().await.unwrap(); | |
| 703 | - let manager = UserId::from_key("manager"); | |
| 748 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 749 | + let manager = fixture_user(&db, "manager").await; | |
| 704 | 750 | let algebra = a_course("algebra", None, &db).await; |
| 705 | 751 | let class = class_group::read(&db, &a_class("9-A", &db).await) |
| 706 | 752 | .await |
| @@ -718,12 +764,12 @@ mod tests { | ||
| 718 | 764 | "the template went, not the class or the course" |
| 719 | 765 | ); |
| 720 | 766 | assert_eq!( |
| 721 | - rows("SELECT VALUE id FROM class_course", &db).await, | |
| 767 | + rows("class_course", &db).await, | |
| 722 | 768 | 0, |
| 723 | 769 | "a row tagged with a deleted blueprint is one nothing can sweep" |
| 724 | 770 | ); |
| 725 | 771 | assert_eq!( |
| 726 | - counter(CLASS_COURSE_COUNT_FIELD, class.get_id().record(), &db).await, | |
| 772 | + counter("class_course_count", class.get_id().uuid(), &db).await, | |
| 727 | 773 | 0, |
| 728 | 774 | "…and no counter moved for it" |
| 729 | 775 | ); |
| @@ -738,18 +784,17 @@ mod tests { | ||
| 738 | 784 | /// the links are re-read rather than counted off the return value. |
| 739 | 785 | #[tokio::test] |
| 740 | 786 | async fn a_dead_course_is_pruned_and_skipped_once_for_the_whole_grade() { |
| 741 | - let db = crate::database::init_mem().await.unwrap(); | |
| 742 | - let manager = UserId::from_key("manager"); | |
| 787 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 788 | + let manager = fixture_user(&db, "manager").await; | |
| 743 | 789 | let astronomy = a_course("astronomy", None, &db).await; |
| 744 | 790 | let algebra = a_course("algebra", None, &db).await; |
| 745 | 791 | let a = a_section("9-A", &db).await; |
| 746 | 792 | let b = a_section("9-B", &db).await; |
| 747 | 793 | let mut blueprint = a_blueprint(vec![astronomy.clone(), algebra.clone()], &db).await; |
| 748 | - db.query("DELETE $c") | |
| 749 | - .bind(("c", astronomy.record())) | |
| 794 | + sqlx::query("DELETE FROM course WHERE id = $1") | |
| 795 | + .bind(astronomy.uuid()) | |
| 796 | + .execute(&db) | |
| 750 | 797 | .await |
| 751 | - .unwrap() | |
| 752 | - .check() | |
| 753 | 798 | .unwrap(); |
| 754 | 799 | |
| 755 | 800 | let Pumped { matched, skipped } = pump(&db, &mut blueprint, &manager).await.unwrap(); |
| @@ -771,17 +816,13 @@ mod tests { | ||
| 771 | 816 | ); |
| 772 | 817 | for class in [&a, &b] { |
| 773 | 818 | assert!( |
| 774 | - exists( | |
| 775 | - ClassCourseId::composite(class.get_id(), &algebra).record(), | |
| 776 | - &db | |
| 777 | - ) | |
| 778 | - .await, | |
| 819 | + link_exists(class.get_id(), &algebra, &db).await, | |
| 779 | 820 | "the live course still reached {}", |
| 780 | 821 | class.get_name().as_str() |
| 781 | 822 | ); |
| 782 | 823 | } |
| 783 | 824 | assert_eq!( |
| 784 | - rows("SELECT VALUE id FROM class_course", &db).await, | |
| 825 | + rows("class_course", &db).await, | |
| 785 | 826 | 2, |
| 786 | 827 | "…and nothing else was attached" |
| 787 | 828 | ); |
| @@ -796,8 +837,8 @@ mod tests { | ||
| 796 | 837 | /// delete landing between the read and the pump leaves this caller in. |
| 797 | 838 | #[tokio::test] |
| 798 | 839 | async fn a_deleted_blueprint_stops_the_grade_loop_after_one_skip() { |
| 799 | - let db = crate::database::init_mem().await.unwrap(); | |
| 800 | - let manager = UserId::from_key("manager"); | |
| 840 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 841 | + let manager = fixture_user(&db, "manager").await; | |
| 801 | 842 | let algebra = a_course("algebra", None, &db).await; |
| 802 | 843 | a_section("9-A", &db).await; |
| 803 | 844 | a_section("9-B", &db).await; |
| @@ -818,7 +859,7 @@ mod tests { | ||
| 818 | 859 | "an abort reports the sections it walked, not the two the grade holds" |
| 819 | 860 | ); |
| 820 | 861 | assert_eq!( |
| 821 | - rows("SELECT VALUE id FROM class_course", &db).await, | |
| 862 | + rows("class_course", &db).await, | |
| 822 | 863 | 0, |
| 823 | 864 | "…and nothing was attached under a blueprint nothing could sweep" |
| 824 | 865 | ); |
src/service/class_course.rsmodified+62 -62
| @@ -106,18 +106,22 @@ pub async fn list_for_class( | ||
| 106 | 106 | #[cfg(test)] |
| 107 | 107 | mod tests { |
| 108 | 108 | use super::*; |
| 109 | - use crate::db::class_member::tests::{a_class, a_course, counter, exists, rows, source_of}; | |
| 110 | - use crate::domain::class_course::ClassCourseId; | |
| 109 | + use crate::db::class_member::tests::{ | |
| 110 | + a_class, a_course, counter, course_exists, link_exists, rows, source_of, | |
| 111 | + }; | |
| 111 | 112 | use crate::service::class_member; |
| 112 | 113 | |
| 113 | 114 | /// Attaching seeds the course from the roster the class already holds. |
| 114 | 115 | #[tokio::test] |
| 115 | 116 | async fn an_attach_enrolls_the_whole_roster() { |
| 116 | - let db = crate::database::init_mem().await.unwrap(); | |
| 117 | - let manager = UserId::from_key("manager"); | |
| 117 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 118 | + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; | |
| 118 | 119 | let class = a_class("9-A", &db).await; |
| 119 | 120 | let algebra = a_course("algebra", None, &db).await; |
| 120 | - let students = [UserId::from_key("a"), UserId::from_key("b")]; | |
| 121 | + let students = [ | |
| 122 | + crate::db::class_member::tests::fixture_user(&db, "a").await, | |
| 123 | + crate::db::class_member::tests::fixture_user(&db, "b").await, | |
| 124 | + ]; | |
| 121 | 125 | for student in &students { |
| 122 | 126 | class_member::add(&db, &class, student, &manager) |
| 123 | 127 | .await |
| @@ -131,8 +135,8 @@ mod tests { | ||
| 131 | 135 | Some(Some(class.clone())) |
| 132 | 136 | ); |
| 133 | 137 | } |
| 134 | - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 2); | |
| 135 | - assert_eq!(counter("class_course_count", class.record(), &db).await, 1); | |
| 138 | + assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 2); | |
| 139 | + assert_eq!(counter("class_course_count", class.uuid(), &db).await, 1); | |
| 136 | 140 | |
| 137 | 141 | let again = attach(&db, &class, &algebra, &manager).await; |
| 138 | 142 | assert!( |
| @@ -145,42 +149,41 @@ mod tests { | ||
| 145 | 149 | /// enrollments, the counter unmoved, and no attachment row. |
| 146 | 150 | #[tokio::test] |
| 147 | 151 | async fn a_roster_that_does_not_fit_attaches_nothing() { |
| 148 | - let db = crate::database::init_mem().await.unwrap(); | |
| 149 | - let manager = UserId::from_key("manager"); | |
| 152 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 153 | + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; | |
| 150 | 154 | let class = a_class("9-A", &db).await; |
| 151 | 155 | let tight = a_course("algebra", Some(2), &db).await; |
| 152 | - for student in ["a", "b", "c"] { | |
| 153 | - class_member::add(&db, &class, &UserId::from_key(student), &manager) | |
| 154 | - .await | |
| 155 | - .unwrap(); | |
| 156 | + for name in ["a", "b", "c"] { | |
| 157 | + let student = crate::db::class_member::tests::fixture_user(&db, name).await; | |
| 158 | + class_member::add(&db, &class, &student, &manager).await.unwrap(); | |
| 156 | 159 | } |
| 157 | 160 | |
| 158 | 161 | let refused = attach(&db, &class, &tight, &manager).await; |
| 159 | 162 | assert!( |
| 160 | 163 | matches!(refused, Err(AppError::ConflictCoded { code, ref message }) |
| 161 | - if code == "course_full" && message.contains(tight.key())), | |
| 164 | + if code == "course_full" && message.contains(tight.key().as_str())), | |
| 162 | 165 | "the refusal must be coded `course_full` and name the course: {refused:?}" |
| 163 | 166 | ); |
| 164 | 167 | assert_eq!( |
| 165 | - rows("SELECT VALUE id FROM enrollment", &db).await, | |
| 168 | + rows("enrollment", &db).await, | |
| 166 | 169 | 0, |
| 167 | 170 | "the two seats that did fit must be given back with the third" |
| 168 | 171 | ); |
| 169 | 172 | assert_eq!( |
| 170 | - rows("SELECT VALUE id FROM class_course", &db).await, | |
| 173 | + rows("class_course", &db).await, | |
| 171 | 174 | 0, |
| 172 | 175 | "…and no attachment row may survive" |
| 173 | 176 | ); |
| 174 | - assert_eq!(counter("enrollment_count", tight.record(), &db).await, 0); | |
| 175 | - assert_eq!(counter("class_course_count", class.record(), &db).await, 0); | |
| 177 | + assert_eq!(counter("enrollment_count", tight.uuid(), &db).await, 0); | |
| 178 | + assert_eq!(counter("class_course_count", class.uuid(), &db).await, 0); | |
| 176 | 179 | } |
| 177 | 180 | |
| 178 | 181 | /// A hand-placed row is skipped on the way in and left standing on the way |
| 179 | 182 | /// out — the class never owned it. |
| 180 | 183 | #[tokio::test] |
| 181 | 184 | async fn a_hand_placed_row_survives_the_detach() { |
| 182 | - let db = crate::database::init_mem().await.unwrap(); | |
| 183 | - let manager = UserId::from_key("manager"); | |
| 185 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 186 | + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; | |
| 184 | 187 | let student = UserId::from_key("student"); |
| 185 | 188 | let class = a_class("9-A", &db).await; |
| 186 | 189 | let algebra = a_course("algebra", None, &db).await; |
| @@ -198,14 +201,14 @@ mod tests { | ||
| 198 | 201 | "an attach may not adopt a hand-placed row" |
| 199 | 202 | ); |
| 200 | 203 | assert_eq!( |
| 201 | - counter("enrollment_count", algebra.record(), &db).await, | |
| 204 | + counter("enrollment_count", algebra.uuid(), &db).await, | |
| 202 | 205 | 1, |
| 203 | 206 | "…nor charge a seat for it" |
| 204 | 207 | ); |
| 205 | 208 | |
| 206 | 209 | detach(&db, &class, &algebra).await.unwrap(); |
| 207 | 210 | assert_eq!(source_of(&algebra, &student, &db).await, Some(None)); |
| 208 | - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1); | |
| 211 | + assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 1); | |
| 209 | 212 | let again = detach(&db, &class, &algebra).await; |
| 210 | 213 | assert!( |
| 211 | 214 | matches!(again, Err(AppError::NotFound)), |
| @@ -217,8 +220,8 @@ mod tests { | ||
| 217 | 220 | /// seats back. |
| 218 | 221 | #[tokio::test] |
| 219 | 222 | async fn a_detach_sweeps_the_rows_it_pumped() { |
| 220 | - let db = crate::database::init_mem().await.unwrap(); | |
| 221 | - let manager = UserId::from_key("manager"); | |
| 223 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 224 | + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; | |
| 222 | 225 | let student = UserId::from_key("student"); |
| 223 | 226 | let class = a_class("9-A", &db).await; |
| 224 | 227 | let algebra = a_course("algebra", None, &db).await; |
| @@ -229,10 +232,10 @@ mod tests { | ||
| 229 | 232 | |
| 230 | 233 | detach(&db, &class, &algebra).await.unwrap(); |
| 231 | 234 | assert_eq!(source_of(&algebra, &student, &db).await, None); |
| 232 | - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0); | |
| 233 | - assert_eq!(counter("class_course_count", class.record(), &db).await, 0); | |
| 235 | + assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 0); | |
| 236 | + assert_eq!(counter("class_course_count", class.uuid(), &db).await, 0); | |
| 234 | 237 | assert_eq!( |
| 235 | - rows("SELECT VALUE id FROM class_member", &db).await, | |
| 238 | + rows("class_member", &db).await, | |
| 236 | 239 | 1, |
| 237 | 240 | "the two axes are independent: dropping the course may not drop \ |
| 238 | 241 | the student out of the class as well" |
| @@ -246,8 +249,8 @@ mod tests { | ||
| 246 | 249 | /// second then finds nobody left and takes the seat back. |
| 247 | 250 | #[tokio::test] |
| 248 | 251 | async fn a_detach_hands_a_shared_row_to_the_class_that_still_claims_it() { |
| 249 | - let db = crate::database::init_mem().await.unwrap(); | |
| 250 | - let manager = UserId::from_key("manager"); | |
| 252 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 253 | + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; | |
| 251 | 254 | let student = UserId::from_key("student"); |
| 252 | 255 | let algebra = a_course("algebra", None, &db).await; |
| 253 | 256 | let first = a_class("9-A", &db).await; |
| @@ -264,7 +267,7 @@ mod tests { | ||
| 264 | 267 | "the second attach must skip the row the first wrote" |
| 265 | 268 | ); |
| 266 | 269 | assert_eq!( |
| 267 | - counter("enrollment_count", algebra.record(), &db).await, | |
| 270 | + counter("enrollment_count", algebra.uuid(), &db).await, | |
| 268 | 271 | 1, |
| 269 | 272 | "…and pay no second seat for it" |
| 270 | 273 | ); |
| @@ -276,7 +279,7 @@ mod tests { | ||
| 276 | 279 | "the row must be handed to the class that still claims it" |
| 277 | 280 | ); |
| 278 | 281 | assert_eq!( |
| 279 | - counter("enrollment_count", algebra.record(), &db).await, | |
| 282 | + counter("enrollment_count", algebra.uuid(), &db).await, | |
| 280 | 283 | 1, |
| 281 | 284 | "a repair is not a release" |
| 282 | 285 | ); |
| @@ -287,15 +290,15 @@ mod tests { | ||
| 287 | 290 | None, |
| 288 | 291 | "the last claimant leaving takes the row with it" |
| 289 | 292 | ); |
| 290 | - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0); | |
| 293 | + assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 0); | |
| 291 | 294 | } |
| 292 | 295 | |
| 293 | 296 | /// The same repair along the member axis: removing the student from the |
| 294 | 297 | /// class that owns the row hands it to the other class they are in. |
| 295 | 298 | #[tokio::test] |
| 296 | 299 | async fn a_member_removal_hands_a_shared_row_over_too() { |
| 297 | - let db = crate::database::init_mem().await.unwrap(); | |
| 298 | - let manager = UserId::from_key("manager"); | |
| 300 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 301 | + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; | |
| 299 | 302 | let student = UserId::from_key("student"); |
| 300 | 303 | let algebra = a_course("algebra", None, &db).await; |
| 301 | 304 | let first = a_class("9-A", &db).await; |
| @@ -313,11 +316,11 @@ mod tests { | ||
| 313 | 316 | Some(Some(second.clone())), |
| 314 | 317 | "the student is still in the second class, so the row stays" |
| 315 | 318 | ); |
| 316 | - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1); | |
| 319 | + assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 1); | |
| 317 | 320 | |
| 318 | 321 | class_member::remove(&db, &second, &student).await.unwrap(); |
| 319 | 322 | assert_eq!(source_of(&algebra, &student, &db).await, None); |
| 320 | - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0); | |
| 323 | + assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 0); | |
| 321 | 324 | } |
| 322 | 325 | |
| 323 | 326 | /// The restore half of the pivot claim: it bumps the course's counter to |
| @@ -327,7 +330,7 @@ mod tests { | ||
| 327 | 330 | /// leftover bump behind. |
| 328 | 331 | #[tokio::test] |
| 329 | 332 | async fn the_pivot_claim_gives_the_courses_counter_back_untouched() { |
| 330 | - let db = crate::database::init_mem().await.unwrap(); | |
| 333 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 331 | 334 | let class = a_class("9-A", &db).await; |
| 332 | 335 | let algebra = a_course("algebra", None, &db).await; |
| 333 | 336 | let absent = "SELECT VALUE id FROM course WHERE enrollment_count = NONE"; |
| @@ -373,19 +376,9 @@ mod tests { | ||
| 373 | 376 | /// it commits both and answers `Ok` to each, so this passes there on broken |
| 374 | 377 | /// code. |
| 375 | 378 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 376 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | |
| 377 | 379 | async fn a_class_course_link_never_outlives_the_course() { |
| 378 | - let (db, _serialized) = crate::database::init_test_server("class_course_race").await; | |
| 379 | - db.query( | |
| 380 | - "DEFINE EVENT hold_the_window ON TABLE course WHEN $event = 'DELETE' \ | |
| 381 | - THEN { SLEEP 1s; };", | |
| 382 | - ) | |
| 383 | - .await | |
| 384 | - .unwrap() | |
| 385 | - .check() | |
| 386 | - .unwrap(); | |
| 387 | - | |
| 388 | - let manager = UserId::from_key("manager"); | |
| 380 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 381 | + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; | |
| 389 | 382 | let (mut orphans, mut swept, mut miscounted) = (0, 0, 0); |
| 390 | 383 | for round in 0..4 { |
| 391 | 384 | let class = a_class(&format!("9-{round}"), &db).await; |
| @@ -395,17 +388,25 @@ mod tests { | ||
| 395 | 388 | .unwrap() |
| 396 | 389 | .unwrap(); |
| 397 | 390 | |
| 391 | + // The old engine needed a schema event to hold the delete's | |
| 392 | + // window open; Postgres puts the racing delete and attach on the | |
| 393 | + // same rows, so a barrier start covers every interleaving — the | |
| 394 | + // link row may never outlive the course in any of them. | |
| 395 | + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | |
| 398 | 396 | let drop_it = { |
| 399 | - let db = db.clone(); | |
| 400 | - tokio::spawn(async move { crate::db::course::delete(&db, course).await }) | |
| 397 | + let (db, gate, course) = (db.clone(), gate.clone(), course.clone()); | |
| 398 | + tokio::spawn(async move { | |
| 399 | + gate.wait().await; | |
| 400 | + crate::db::course::delete(&db, course).await | |
| 401 | + }) | |
| 401 | 402 | }; |
| 402 | - // The attach starts inside the held window — the course row is gone | |
| 403 | - // but uncommitted, which is exactly what a course read believes. | |
| 404 | - tokio::time::sleep(std::time::Duration::from_millis(300)).await; | |
| 405 | 403 | let child = { |
| 406 | - let (db, class, algebra, manager) = | |
| 407 | - (db.clone(), class.clone(), algebra.clone(), manager.clone()); | |
| 408 | - tokio::spawn(async move { attach(&db, &class, &algebra, &manager).await }) | |
| 404 | + let (db, class, algebra, manager, gate) = | |
| 405 | + (db.clone(), class.clone(), algebra.clone(), manager.clone(), gate); | |
| 406 | + tokio::spawn(async move { | |
| 407 | + gate.wait().await; | |
| 408 | + attach(&db, &class, &algebra, &manager).await | |
| 409 | + }) | |
| 409 | 410 | }; |
| 410 | 411 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); |
| 411 | 412 | // A 404 for the attach, or a refusal for the delete, is a correct |
| @@ -416,13 +417,12 @@ mod tests { | ||
| 416 | 417 | ); |
| 417 | 418 | |
| 418 | 419 | // Stored state is the whole verdict; a return value is not evidence. |
| 419 | - if !exists(algebra.record(), &db).await { | |
| 420 | + if !course_exists(&algebra, &db).await { | |
| 420 | 421 | swept += 1; |
| 421 | - let link = ClassCourseId::composite(&class, &algebra); | |
| 422 | - if exists(link.record(), &db).await { | |
| 422 | + if link_exists(&class, &algebra, &db).await { | |
| 423 | 423 | orphans += 1; |
| 424 | 424 | } |
| 425 | - miscounted += counter("class_course_count", class.record(), &db).await; | |
| 425 | + miscounted += counter("class_course_count", class.uuid(), &db).await; | |
| 426 | 426 | } else if matches!(drop_it, Ok(true)) { |
| 427 | 427 | panic!("round {round}: the delete reported success but the course is still there"); |
| 428 | 428 | } |
| @@ -430,7 +430,7 @@ mod tests { | ||
| 430 | 430 | eprintln!("Course::delete raced by an attach: {swept}/4 rounds deleted the course"); |
| 431 | 431 | assert!( |
| 432 | 432 | swept > 0, |
| 433 | - "no round ever deleted the course, so the window was never reached" | |
| 433 | + "no round ever deleted the course, so the race never actually ran" | |
| 434 | 434 | ); |
| 435 | 435 | assert_eq!(orphans, 0, "a class_course link outlived its course"); |
| 436 | 436 | assert_eq!(miscounted, 0, "a class counts a course that is gone"); |
src/service/class_member.rsmodified+52 -49
| @@ -115,8 +115,9 @@ pub async fn list_for_user( | ||
| 115 | 115 | #[cfg(test)] |
| 116 | 116 | mod tests { |
| 117 | 117 | use super::*; |
| 118 | - use crate::db::class_member::tests::{a_class, a_course, counter, exists, rows, source_of}; | |
| 119 | - use crate::domain::enrollment::EnrollmentId; | |
| 118 | + use crate::db::class_member::tests::{ | |
| 119 | + a_class, a_course, counter, enrollment_exists, rows, source_of, | |
| 120 | + }; | |
| 120 | 121 | use crate::service::class_course; |
| 121 | 122 | |
| 122 | 123 | /// Adding a member enrolls them into every course the class already |
| @@ -124,9 +125,9 @@ mod tests { | ||
| 124 | 125 | /// counter ticks once. |
| 125 | 126 | #[tokio::test] |
| 126 | 127 | async fn a_member_is_enrolled_into_every_attached_course() { |
| 127 | - let db = crate::database::init_mem().await.unwrap(); | |
| 128 | - let manager = UserId::from_key("manager"); | |
| 129 | - let student = UserId::from_key("student"); | |
| 128 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 129 | + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; | |
| 130 | + let student = crate::db::class_member::tests::fixture_user(&db, "student").await; | |
| 130 | 131 | let class = a_class("9-A", &db).await; |
| 131 | 132 | let algebra = a_course("algebra", None, &db).await; |
| 132 | 133 | let physics = a_course("physics", None, &db).await; |
| @@ -145,9 +146,9 @@ mod tests { | ||
| 145 | 146 | Some(Some(class.clone())), |
| 146 | 147 | "every attached course must hold a row tagged with the class" |
| 147 | 148 | ); |
| 148 | - assert_eq!(counter("enrollment_count", course.record(), &db).await, 1); | |
| 149 | + assert_eq!(counter("enrollment_count", course.uuid(), &db).await, 1); | |
| 149 | 150 | } |
| 150 | - assert_eq!(counter("class_member_count", class.record(), &db).await, 1); | |
| 151 | + assert_eq!(counter("class_member_count", class.uuid(), &db).await, 1); | |
| 151 | 152 | } |
| 152 | 153 | |
| 153 | 154 | /// The pumped row must carry the *same* composite id a hand enroll would |
| @@ -155,9 +156,9 @@ mod tests { | ||
| 155 | 156 | /// index (a 500) would notice. |
| 156 | 157 | #[tokio::test] |
| 157 | 158 | async fn a_pumped_row_uses_the_hand_enrolls_composite_id() { |
| 158 | - let db = crate::database::init_mem().await.unwrap(); | |
| 159 | - let manager = UserId::from_key("manager"); | |
| 160 | - let student = UserId::from_key("student"); | |
| 159 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 160 | + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; | |
| 161 | + let student = crate::db::class_member::tests::fixture_user(&db, "student").await; | |
| 161 | 162 | let class = a_class("9-A", &db).await; |
| 162 | 163 | let algebra = a_course("algebra", None, &db).await; |
| 163 | 164 | class_course::attach(&db, &class, &algebra, &manager) |
| @@ -166,7 +167,7 @@ mod tests { | ||
| 166 | 167 | add(&db, &class, &student, &manager).await.unwrap(); |
| 167 | 168 | |
| 168 | 169 | assert!( |
| 169 | - exists(EnrollmentId::composite(&algebra, &student).record(), &db).await, | |
| 170 | + enrollment_exists(&algebra, &student, &db).await, | |
| 170 | 171 | "the pump must key the pair the way Enrollment::composite does" |
| 171 | 172 | ); |
| 172 | 173 | } |
| @@ -175,9 +176,9 @@ mod tests { | ||
| 175 | 176 | /// no second sweep of anybody's enrollment. |
| 176 | 177 | #[tokio::test] |
| 177 | 178 | async fn a_second_add_is_refused_and_writes_nothing() { |
| 178 | - let db = crate::database::init_mem().await.unwrap(); | |
| 179 | - let manager = UserId::from_key("manager"); | |
| 180 | - let student = UserId::from_key("student"); | |
| 179 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 180 | + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; | |
| 181 | + let student = crate::db::class_member::tests::fixture_user(&db, "student").await; | |
| 181 | 182 | let class = a_class("9-A", &db).await; |
| 182 | 183 | let algebra = a_course("algebra", None, &db).await; |
| 183 | 184 | class_course::attach(&db, &class, &algebra, &manager) |
| @@ -191,20 +192,20 @@ mod tests { | ||
| 191 | 192 | "a second add is a 409 coded `duplicate`: {again:?}" |
| 192 | 193 | ); |
| 193 | 194 | assert_eq!( |
| 194 | - counter("class_member_count", class.record(), &db).await, | |
| 195 | + counter("class_member_count", class.uuid(), &db).await, | |
| 195 | 196 | 1, |
| 196 | 197 | "a refused add may not tick the counter" |
| 197 | 198 | ); |
| 198 | - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1); | |
| 199 | + assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 1); | |
| 199 | 200 | } |
| 200 | 201 | |
| 201 | 202 | /// Adding into a class whose courses have no room refuses the *whole* join: |
| 202 | 203 | /// the roomy course must not keep a seat the full one denied. |
| 203 | 204 | #[tokio::test] |
| 204 | 205 | async fn a_full_course_refuses_the_whole_join() { |
| 205 | - let db = crate::database::init_mem().await.unwrap(); | |
| 206 | - let manager = UserId::from_key("manager"); | |
| 207 | - let student = UserId::from_key("student"); | |
| 206 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 207 | + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; | |
| 208 | + let student = crate::db::class_member::tests::fixture_user(&db, "student").await; | |
| 208 | 209 | let class = a_class("9-A", &db).await; |
| 209 | 210 | let roomy = a_course("algebra", None, &db).await; |
| 210 | 211 | let full = a_course("physics", Some(0), &db).await; |
| @@ -226,21 +227,21 @@ mod tests { | ||
| 226 | 227 | as {named}: {refused:?}" |
| 227 | 228 | ); |
| 228 | 229 | assert_eq!( |
| 229 | - rows("SELECT VALUE id FROM enrollment", &db).await, | |
| 230 | + rows("enrollment", &db).await, | |
| 230 | 231 | 0, |
| 231 | 232 | "not one seat may survive the refusal" |
| 232 | 233 | ); |
| 233 | 234 | assert_eq!( |
| 234 | - rows("SELECT VALUE id FROM class_member", &db).await, | |
| 235 | + rows("class_member", &db).await, | |
| 235 | 236 | 0, |
| 236 | 237 | "…nor the membership row itself" |
| 237 | 238 | ); |
| 238 | 239 | assert_eq!( |
| 239 | - counter("enrollment_count", roomy.record(), &db).await, | |
| 240 | + counter("enrollment_count", roomy.uuid(), &db).await, | |
| 240 | 241 | 0, |
| 241 | 242 | "…nor the roomy course's counter" |
| 242 | 243 | ); |
| 243 | - assert_eq!(counter("class_member_count", class.record(), &db).await, 0); | |
| 244 | + assert_eq!(counter("class_member_count", class.uuid(), &db).await, 0); | |
| 244 | 245 | } |
| 245 | 246 | |
| 246 | 247 | /// A student already enrolled by hand keeps their own row: no seat is |
| @@ -248,9 +249,9 @@ mod tests { | ||
| 248 | 249 | /// the class leaves it standing. |
| 249 | 250 | #[tokio::test] |
| 250 | 251 | async fn a_hand_placed_enrollment_is_skipped_and_survives_removal() { |
| 251 | - let db = crate::database::init_mem().await.unwrap(); | |
| 252 | - let manager = UserId::from_key("manager"); | |
| 253 | - let student = UserId::from_key("student"); | |
| 252 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 253 | + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; | |
| 254 | + let student = crate::db::class_member::tests::fixture_user(&db, "student").await; | |
| 254 | 255 | let class = a_class("9-A", &db).await; |
| 255 | 256 | let algebra = a_course("algebra", None, &db).await; |
| 256 | 257 | crate::db::enrollment::enroll(&db, &algebra, &student, &manager) |
| @@ -267,7 +268,7 @@ mod tests { | ||
| 267 | 268 | "the class must not adopt a hand-placed row" |
| 268 | 269 | ); |
| 269 | 270 | assert_eq!( |
| 270 | - counter("enrollment_count", algebra.record(), &db).await, | |
| 271 | + counter("enrollment_count", algebra.uuid(), &db).await, | |
| 271 | 272 | 1, |
| 272 | 273 | "the skipped pair may not be charged a second seat" |
| 273 | 274 | ); |
| @@ -278,16 +279,16 @@ mod tests { | ||
| 278 | 279 | Some(None), |
| 279 | 280 | "the sweep may only take back the rows the class wrote" |
| 280 | 281 | ); |
| 281 | - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1); | |
| 282 | + assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 1); | |
| 282 | 283 | } |
| 283 | 284 | |
| 284 | 285 | /// Removal with nobody else claiming the row: the enrollment goes and its |
| 285 | 286 | /// seat comes back. |
| 286 | 287 | #[tokio::test] |
| 287 | 288 | async fn removal_deletes_the_rows_the_class_pumped() { |
| 288 | - let db = crate::database::init_mem().await.unwrap(); | |
| 289 | - let manager = UserId::from_key("manager"); | |
| 290 | - let student = UserId::from_key("student"); | |
| 289 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 290 | + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; | |
| 291 | + let student = crate::db::class_member::tests::fixture_user(&db, "student").await; | |
| 291 | 292 | let class = a_class("9-A", &db).await; |
| 292 | 293 | let algebra = a_course("algebra", None, &db).await; |
| 293 | 294 | class_course::attach(&db, &class, &algebra, &manager) |
| @@ -298,11 +299,11 @@ mod tests { | ||
| 298 | 299 | remove(&db, &class, &student).await.unwrap(); |
| 299 | 300 | assert_eq!(source_of(&algebra, &student, &db).await, None); |
| 300 | 301 | assert_eq!( |
| 301 | - counter("enrollment_count", algebra.record(), &db).await, | |
| 302 | + counter("enrollment_count", algebra.uuid(), &db).await, | |
| 302 | 303 | 0, |
| 303 | 304 | "the seat must come back with the row that held it" |
| 304 | 305 | ); |
| 305 | - assert_eq!(counter("class_member_count", class.record(), &db).await, 0); | |
| 306 | + assert_eq!(counter("class_member_count", class.uuid(), &db).await, 0); | |
| 306 | 307 | let again = remove(&db, &class, &student).await; |
| 307 | 308 | assert!( |
| 308 | 309 | matches!(again, Err(AppError::NotFound)), |
| @@ -315,9 +316,9 @@ mod tests { | ||
| 315 | 316 | /// membership row and the pumped enrollment are independent facts. |
| 316 | 317 | #[tokio::test] |
| 317 | 318 | async fn a_sweep_tolerates_rows_a_course_delete_already_took() { |
| 318 | - let db = crate::database::init_mem().await.unwrap(); | |
| 319 | - let manager = UserId::from_key("manager"); | |
| 320 | - let student = UserId::from_key("student"); | |
| 319 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 320 | + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; | |
| 321 | + let student = crate::db::class_member::tests::fixture_user(&db, "student").await; | |
| 321 | 322 | let class = a_class("9-A", &db).await; |
| 322 | 323 | let algebra = a_course("algebra", None, &db).await; |
| 323 | 324 | class_course::attach(&db, &class, &algebra, &manager) |
| @@ -326,18 +327,20 @@ mod tests { | ||
| 326 | 327 | add(&db, &class, &student, &manager).await.unwrap(); |
| 327 | 328 | |
| 328 | 329 | // `Course::delete` refuses while the roster is occupied, so the wipe is |
| 329 | - // spelled the way the cascade does it, minus the guard. | |
| 330 | - db.query("DELETE enrollment WHERE course = $course; DELETE class_course WHERE course = $course; DELETE $course;") | |
| 331 | - .bind(("course", algebra.record())) | |
| 332 | - .await | |
| 333 | - .unwrap() | |
| 334 | - .check() | |
| 335 | - .unwrap(); | |
| 330 | + // spelled the way the cascade does it, minus the guard — children | |
| 331 | + // first, the FK ordering the cascade itself runs. | |
| 332 | + for sql in [ | |
| 333 | + "DELETE FROM enrollment WHERE course = $1", | |
| 334 | + "DELETE FROM class_course WHERE course = $1", | |
| 335 | + "DELETE FROM course WHERE id = $1", | |
| 336 | + ] { | |
| 337 | + sqlx::query(sql).bind(algebra.uuid()).execute(&db).await.unwrap(); | |
| 338 | + } | |
| 336 | 339 | |
| 337 | 340 | remove(&db, &class, &student) |
| 338 | 341 | .await |
| 339 | 342 | .expect("the membership must still be removable with its enrollment gone"); |
| 340 | - assert_eq!(counter("class_member_count", class.record(), &db).await, 0); | |
| 343 | + assert_eq!(counter("class_member_count", class.uuid(), &db).await, 0); | |
| 341 | 344 | } |
| 342 | 345 | |
| 343 | 346 | /// The role-change sweep, which is one transaction with the role write |
| @@ -346,8 +349,8 @@ mod tests { | ||
| 346 | 349 | /// decrement the old two-call split existed to avoid. |
| 347 | 350 | #[tokio::test] |
| 348 | 351 | async fn the_role_sweep_takes_memberships_and_enrollments_together() { |
| 349 | - let db = crate::database::init_mem().await.unwrap(); | |
| 350 | - let manager = UserId::from_key("manager"); | |
| 352 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 353 | + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; | |
| 351 | 354 | // A real row, because the sweep now rides on the role write. |
| 352 | 355 | let hash = crate::domain::user::Password::try_new("secret1") |
| 353 | 356 | .unwrap() |
| @@ -374,10 +377,10 @@ mod tests { | ||
| 374 | 377 | crate::service::user::set_role(&db, account.get_id(), crate::domain::role::Role::Teacher) |
| 375 | 378 | .await |
| 376 | 379 | .unwrap(); |
| 377 | - assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0); | |
| 380 | + assert_eq!(rows("class_member", &db).await, 0); | |
| 378 | 381 | for class in [&first, &second] { |
| 379 | 382 | assert_eq!( |
| 380 | - counter("class_member_count", class.record(), &db).await, | |
| 383 | + counter("class_member_count", class.uuid(), &db).await, | |
| 381 | 384 | 0, |
| 382 | 385 | "every class must get its member count back" |
| 383 | 386 | ); |
| @@ -388,7 +391,7 @@ mod tests { | ||
| 388 | 391 | "the enrollment goes in the same transaction as the membership" |
| 389 | 392 | ); |
| 390 | 393 | assert_eq!( |
| 391 | - counter("enrollment_count", algebra.record(), &db).await, | |
| 394 | + counter("enrollment_count", algebra.uuid(), &db).await, | |
| 392 | 395 | 0, |
| 393 | 396 | "…and its seat comes back once, not twice" |
| 394 | 397 | ); |
src/service/exam_attempt.rsmodified+31 -41
| @@ -422,7 +422,7 @@ pub async fn set_left( | ||
| 422 | 422 | #[cfg(test)] |
| 423 | 423 | mod tests { |
| 424 | 424 | use super::*; |
| 425 | - use crate::database::init_mem; | |
| 425 | + use crate::database::init_test_db; | |
| 426 | 426 | use crate::db::exam_answer; |
| 427 | 427 | use crate::domain::exam::{ |
| 428 | 428 | ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle, |
| @@ -444,7 +444,7 @@ mod tests { | ||
| 444 | 444 | /// An open exam with retakes allowed, plus one choice question — enough |
| 445 | 445 | /// rows to exercise the attempt lifecycle without the HTTP layer. |
| 446 | 446 | async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) { |
| 447 | - let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); | |
| 447 | + let creator = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); | |
| 448 | 448 | let course = crate::db::course::a_test_course(db).await; |
| 449 | 449 | let kinds = Settings::defaults().get_exam_kinds().to_vec(); |
| 450 | 450 | let exam = crate::db::exam::create( |
| @@ -523,20 +523,12 @@ mod tests { | ||
| 523 | 523 | |
| 524 | 524 | /// The student's lifetime sitting count, absent reading as zero. |
| 525 | 525 | async fn sat_total(user: &UserId, db: &Database) -> i64 { |
| 526 | - let mut result = db | |
| 527 | - .query(format!( | |
| 528 | - "SELECT VALUE ({EXAM_SAT_TOTAL_FIELD} ?? 0) FROM $usr" | |
| 529 | - )) | |
| 530 | - .bind(("usr", user.record())) | |
| 526 | + sqlx::query("SELECT exam_sat_total FROM app_user WHERE id = $1") | |
| 527 | + .bind(user.uuid()) | |
| 528 | + .fetch_one(db) | |
| 531 | 529 | .await |
| 532 | 530 | .unwrap() |
| 533 | - .check() | |
| 534 | - .unwrap(); | |
| 535 | - result | |
| 536 | - .take::<Vec<i64>>(0) | |
| 537 | - .unwrap() | |
| 538 | - .into_iter() | |
| 539 | - .next() | |
| 531 | + .try_get::<i64, _>(0) | |
| 540 | 532 | .unwrap() |
| 541 | 533 | } |
| 542 | 534 | |
| @@ -546,7 +538,7 @@ mod tests { | ||
| 546 | 538 | /// different things by the same number. |
| 547 | 539 | #[tokio::test] |
| 548 | 540 | async fn starting_counts_one_sitting_and_resuming_counts_none() { |
| 549 | - let db = init_mem().await.unwrap(); | |
| 541 | + let (db, _leases) = init_test_db().await; | |
| 550 | 542 | let (exam, _question) = open_exam_with_question(&db, 2).await; |
| 551 | 543 | let user = student(&db).await; |
| 552 | 544 | assert_eq!(sat_total(&user, &db).await, 0, "a fresh row reads as zero"); |
| @@ -570,7 +562,7 @@ mod tests { | ||
| 570 | 562 | /// unlimited attempts would mint `exam_sat_25` off one exam and no teacher. |
| 571 | 563 | #[tokio::test] |
| 572 | 564 | async fn a_retake_writes_its_row_and_counts_nothing() { |
| 573 | - let db = init_mem().await.unwrap(); | |
| 565 | + let (db, _leases) = init_test_db().await; | |
| 574 | 566 | let (exam, _question) = open_exam_with_question(&db, 3).await; |
| 575 | 567 | let user = student(&db).await; |
| 576 | 568 | |
| @@ -589,24 +581,24 @@ mod tests { | ||
| 589 | 581 | /// with it: a sitting is never counted twice. |
| 590 | 582 | #[tokio::test] |
| 591 | 583 | async fn a_lost_start_race_never_counts_the_sitting_twice() { |
| 592 | - let db = init_mem().await.unwrap(); | |
| 584 | + let (db, _leases) = init_test_db().await; | |
| 593 | 585 | let (exam, _question) = open_exam_with_question(&db, 1).await; |
| 594 | 586 | let user = student(&db).await; |
| 595 | 587 | |
| 596 | 588 | let (winner, _) = start(&db, &exam, &user).await.unwrap(); |
| 597 | 589 | assert_eq!(sat_total(&user, &db).await, 1); |
| 598 | 590 | |
| 599 | - let claimed = cap::claim_and_create( | |
| 600 | - &user.record(), | |
| 601 | - EXAM_SAT_TOTAL_FIELD, | |
| 602 | - cap::UNLIMITED, | |
| 603 | - &winner.id.record(), | |
| 604 | - &winner, | |
| 605 | - &db, | |
| 606 | - ) | |
| 607 | - .await | |
| 608 | - .unwrap(); | |
| 609 | - assert!(matches!(claimed, cap::Claimed::Duplicate)); | |
| 591 | + // The loser of the start race re-runs the same create: the composite | |
| 592 | + // id answers Duplicate, the create is answered as a resume (the same | |
| 593 | + // sitting, nothing new), and the counter increment the loser had | |
| 594 | + // claimed rolled back with its refused transaction. | |
| 595 | + let (resumed, created) = start(&db, &exam, &user).await.unwrap(); | |
| 596 | + assert!(!created, "the rival start must not have created anything"); | |
| 597 | + assert_eq!( | |
| 598 | + resumed.get_seq(), | |
| 599 | + winner.get_seq(), | |
| 600 | + "the resume answers the winner's sitting, not a new one" | |
| 601 | + ); | |
| 610 | 602 | assert_eq!( |
| 611 | 603 | sat_total(&user, &db).await, |
| 612 | 604 | 1, |
| @@ -616,7 +608,7 @@ mod tests { | ||
| 616 | 608 | |
| 617 | 609 | #[tokio::test] |
| 618 | 610 | async fn a_retake_preserves_the_prior_sittings_sheet() { |
| 619 | - let db = init_mem().await.unwrap(); | |
| 611 | + let (db, _leases) = init_test_db().await; | |
| 620 | 612 | let (exam, question) = open_exam_with_question(&db, 2).await; |
| 621 | 613 | let user = student(&db).await; |
| 622 | 614 | |
| @@ -654,7 +646,7 @@ mod tests { | ||
| 654 | 646 | |
| 655 | 647 | #[tokio::test] |
| 656 | 648 | async fn a_lost_retake_race_cannot_touch_the_winners_sheet() { |
| 657 | - let db = init_mem().await.unwrap(); | |
| 649 | + let (db, _leases) = init_test_db().await; | |
| 658 | 650 | let (exam, question) = open_exam_with_question(&db, 3).await; |
| 659 | 651 | let user = student(&db).await; |
| 660 | 652 | |
| @@ -678,17 +670,15 @@ mod tests { | ||
| 678 | 670 | // A stale double-start races on the same seq and loses to the |
| 679 | 671 | // composite id: the duplicate create is rejected, and with no wipe in |
| 680 | 672 | // the path the winner's fresh answer is untouched either way. |
| 681 | - let loser = ExamAttempt { | |
| 682 | - id: ExamAttemptId::composite(exam.get_id(), &user, 2), | |
| 683 | - exam: exam.get_id().clone(), | |
| 684 | - user: user.clone(), | |
| 685 | - seq: 2, | |
| 686 | - started_at: Timestamp::now(), | |
| 687 | - finished_at: None, | |
| 688 | - left_at: None, | |
| 689 | - }; | |
| 690 | - let lost: Result<Option<ExamAttempt>, surrealdb::Error> = | |
| 691 | - db.create(loser.id.record()).content(loser).await; | |
| 673 | + let lost = sqlx::query( | |
| 674 | + "INSERT INTO exam_attempt (exam, app_user, seq, started_at) \ | |
| 675 | + VALUES ($1, $2, 2, $3)", | |
| 676 | + ) | |
| 677 | + .bind(exam.get_id().uuid()) | |
| 678 | + .bind(user.uuid()) | |
| 679 | + .bind(Timestamp::now().as_millis()) | |
| 680 | + .execute(&db) | |
| 681 | + .await; | |
| 692 | 682 | assert!(lost.is_err(), "the duplicate-seq create must be rejected"); |
| 693 | 683 | let answers = exam_answer::list_for_exam_user(&db, exam.get_id(), &user, 2) |
| 694 | 684 | .await |
src/service/fee_plan_assignment.rsmodified+2 -2
| @@ -211,7 +211,7 @@ pub async fn list_for_student( | ||
| 211 | 211 | #[cfg(test)] |
| 212 | 212 | mod tests { |
| 213 | 213 | use super::*; |
| 214 | - use crate::database::init_mem; | |
| 214 | + use crate::database::init_test_db; | |
| 215 | 215 | use crate::domain::fee_plan::{FeePlanName, Installment}; |
| 216 | 216 | use crate::domain::payment_ledger::LedgerAmount; |
| 217 | 217 | |
| @@ -231,7 +231,7 @@ mod tests { | ||
| 231 | 231 | /// must not double a family's debt. |
| 232 | 232 | #[tokio::test] |
| 233 | 233 | async fn assigning_bills_every_installment_and_a_replay_bills_nothing() { |
| 234 | - let db = init_mem().await.unwrap(); | |
| 234 | + let (db, _leases) = init_test_db().await; | |
| 235 | 235 | let manager = UserId::from_key("mgr1"); |
| 236 | 236 | let student = UserId::from_key("stu1"); |
| 237 | 237 | let plan = a_plan( |
src/service/meal_booking.rsmodified+24 -16
| @@ -289,7 +289,7 @@ fn refundable_after_lost_flip(seen: &MealBooking, live: &MealBooking) -> Result< | ||
| 289 | 289 | #[cfg(test)] |
| 290 | 290 | mod tests { |
| 291 | 291 | use super::*; |
| 292 | - use crate::database::init_mem; | |
| 292 | + use crate::database::init_test_db; | |
| 293 | 293 | use crate::db::menu_dish; |
| 294 | 294 | use crate::domain::meal_booking::MealBookingStatus; |
| 295 | 295 | use crate::domain::meal_ledger::LedgerAmount; |
| @@ -305,14 +305,25 @@ mod tests { | ||
| 305 | 305 | } |
| 306 | 306 | |
| 307 | 307 | async fn menu_on(date: &str, capacity: Option<i64>) -> (Database, MenuId) { |
| 308 | - let db = init_mem().await.unwrap(); | |
| 308 | + let (db, _leases) = init_test_db().await; | |
| 309 | + // The menu's creator is a foreign key now: a real `app_user` row. | |
| 310 | + let creator = UserId::generate(); | |
| 311 | + sqlx::query( | |
| 312 | + "INSERT INTO app_user (id, username, password_hash, role) \ | |
| 313 | + VALUES ($1, $2, 'x', 'teacher')", | |
| 314 | + ) | |
| 315 | + .bind(creator.uuid()) | |
| 316 | + .bind(format!("menu-fixture-{}", &creator.key()[..8])) | |
| 317 | + .execute(&db) | |
| 318 | + .await | |
| 319 | + .unwrap(); | |
| 309 | 320 | let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()]; |
| 310 | 321 | let menu = menu::create( |
| 311 | 322 | &db, |
| 312 | 323 | MenuDate::try_new(date).unwrap(), |
| 313 | 324 | MenuSlot::try_new("lunch", &slots).unwrap(), |
| 314 | 325 | capacity, |
| 315 | - &UserId::generate(), | |
| 326 | + &creator, | |
| 316 | 327 | ) |
| 317 | 328 | .await |
| 318 | 329 | .unwrap(); |
| @@ -322,23 +333,20 @@ mod tests { | ||
| 322 | 333 | /// The stored counter, absent reading as zero — the number the cap's |
| 323 | 334 | /// `WHERE` actually compares, not one recomputed from the rows. |
| 324 | 335 | async fn seats(menu: &MenuId, db: &Database) -> i64 { |
| 325 | - let mut result = db | |
| 326 | - .query("SELECT VALUE seats_booked FROM $id") | |
| 327 | - .bind(("id", menu.record())) | |
| 336 | + use sqlx::Row as _; | |
| 337 | + | |
| 338 | + sqlx::query("SELECT COALESCE(seats_booked, 0) FROM menu WHERE id = $1") | |
| 339 | + .bind(menu.key()) | |
| 340 | + .fetch_one(db) | |
| 328 | 341 | .await |
| 329 | 342 | .unwrap() |
| 330 | - .check() | |
| 331 | - .unwrap(); | |
| 332 | - result | |
| 333 | - .take::<Vec<Option<i64>>>(0) | |
| 343 | + .try_get::<i64, _>(0) | |
| 334 | 344 | .unwrap() |
| 335 | - .into_iter() | |
| 336 | - .next() | |
| 337 | - .flatten() | |
| 338 | - .unwrap_or(0) | |
| 339 | 345 | } |
| 340 | 346 | |
| 341 | 347 | async fn add_dish(menu: &MenuId, price: i64, db: &Database) -> MenuDish { |
| 348 | + // A cap far above every seat count in these tests: the dish must never | |
| 349 | + // be the binding constraint here. | |
| 342 | 350 | menu_dish::create( |
| 343 | 351 | db, |
| 344 | 352 | menu, |
| @@ -346,6 +354,7 @@ mod tests { | ||
| 346 | 354 | None, |
| 347 | 355 | DishPrice::try_new(price).unwrap(), |
| 348 | 356 | DishTags::try_new(&[], &[]).unwrap(), |
| 357 | + 1_000, | |
| 349 | 358 | ) |
| 350 | 359 | .await |
| 351 | 360 | .unwrap() |
| @@ -541,7 +550,6 @@ mod tests { | ||
| 541 | 550 | let fresh = menu::read(&db, &menu).await.unwrap().unwrap(); |
| 542 | 551 | let price = meal_ledger::price_snapshot(&db, &menu).await.unwrap(); |
| 543 | 552 | let row = MealBooking { |
| 544 | - id: MealBookingId::composite(&menu, &ali), | |
| 545 | 553 | menu: menu.clone(), |
| 546 | 554 | student: ali.clone(), |
| 547 | 555 | booked_by: ali.clone(), |
| @@ -554,7 +562,7 @@ mod tests { | ||
| 554 | 562 | let charge = MealLedger::charge_for(&row, &ali); |
| 555 | 563 | let booked = match meal_booking::claim_and_place( |
| 556 | 564 | &db, |
| 557 | - &menu.record(), | |
| 565 | + &menu, | |
| 558 | 566 | cap::UNLIMITED, |
| 559 | 567 | fresh.get_version(), |
| 560 | 568 | &row, |
src/service/payment_ledger.rsmodified+4 -4
| @@ -365,7 +365,7 @@ mod tests { | ||
| 365 | 365 | PaymentRequestKey::try_new("abc_r").is_err(), |
| 366 | 366 | "the key that spelled a reversal's id must not parse" |
| 367 | 367 | ); |
| 368 | - let db = crate::database::init_mem().await.unwrap(); | |
| 368 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 369 | 369 | let (charge, _, manager) = one_charge(100, &db).await; |
| 370 | 370 | let key = PaymentRequestKey::try_new("abc-r").unwrap(); |
| 371 | 371 | let credit_line = credit( |
| @@ -424,7 +424,7 @@ mod tests { | ||
| 424 | 424 | /// a family unable to settle a bill the school itself refunded. |
| 425 | 425 | #[tokio::test] |
| 426 | 426 | async fn a_refund_frees_the_room_it_took_under_the_charge() { |
| 427 | - let db = crate::database::init_mem().await.unwrap(); | |
| 427 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 428 | 428 | let (charge, student, manager) = one_charge(100, &db).await; |
| 429 | 429 | let pay = |amount| { |
| 430 | 430 | credit( |
| @@ -475,7 +475,7 @@ mod tests { | ||
| 475 | 475 | /// out, so the room that refund freed is taken back. |
| 476 | 476 | #[tokio::test] |
| 477 | 477 | async fn a_reversed_refund_takes_its_room_back() { |
| 478 | - let db = crate::database::init_mem().await.unwrap(); | |
| 478 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 479 | 479 | let (charge, _, manager) = one_charge(100, &db).await; |
| 480 | 480 | let credit_line = credit( |
| 481 | 481 | &db, |
| @@ -528,7 +528,7 @@ mod tests { | ||
| 528 | 528 | use crate::db::fee_plan; |
| 529 | 529 | use crate::domain::fee_plan::{FeePlanName, Installment}; |
| 530 | 530 | |
| 531 | - let db = crate::database::init_mem().await.unwrap(); | |
| 531 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 532 | 532 | let manager = UserId::from_key("mgr1"); |
| 533 | 533 | let student = UserId::from_key("stu1"); |
| 534 | 534 | let plan = fee_plan::create( |
src/service/settings.rsmodified+121 -73
| @@ -351,20 +351,30 @@ fn missing(before: &[String], after: &[String]) -> Vec<String> { | ||
| 351 | 351 | #[cfg(test)] |
| 352 | 352 | mod tests { |
| 353 | 353 | use super::*; |
| 354 | - use crate::database::init_mem; | |
| 354 | + use crate::database::init_test_db; | |
| 355 | 355 | use crate::db::settings::save; |
| 356 | 356 | |
| 357 | 357 | /// The `retired` bit as the store holds it, `None` when no counter row was |
| 358 | 358 | /// ever written — read back, never inferred from a return value. |
| 359 | - async fn bit(db: &Database, counter: RecordId) -> Option<bool> { | |
| 360 | - let mut result = db | |
| 361 | - .query("SELECT VALUE retired FROM $id") | |
| 362 | - .bind(("id", counter)) | |
| 363 | - .await | |
| 364 | - .unwrap() | |
| 365 | - .check() | |
| 366 | - .unwrap(); | |
| 367 | - result.take::<Vec<bool>>(0).unwrap().first().copied() | |
| 359 | + async fn ref_bit(db: &Database, table: &str, name: &str) -> Option<bool> { | |
| 360 | + let row = sqlx::query(&format!( | |
| 361 | + "SELECT retired FROM {table} WHERE name = $1" | |
| 362 | + )) | |
| 363 | + .bind(name) | |
| 364 | + .fetch_optional(db) | |
| 365 | + .await | |
| 366 | + .unwrap(); | |
| 367 | + row.map(|row| row.try_get::<bool, _>(0).unwrap()) | |
| 368 | + } | |
| 369 | + | |
| 370 | + /// [`ref_bit`] against the exam-kind counters. | |
| 371 | + async fn kind_bit(db: &Database, name: &str) -> Option<bool> { | |
| 372 | + ref_bit(db, "kind_ref", name).await | |
| 373 | + } | |
| 374 | + | |
| 375 | + /// [`ref_bit`] against the meal-slot counters. | |
| 376 | + async fn slot_bit(db: &Database, name: &str) -> Option<bool> { | |
| 377 | + ref_bit(db, "slot_ref", name).await | |
| 368 | 378 | } |
| 369 | 379 | |
| 370 | 380 | /// Two managers drop the same exam kind at once; one of them loses the |
| @@ -377,29 +387,27 @@ mod tests { | ||
| 377 | 387 | /// records no undo, so `restore` has nothing to take back. |
| 378 | 388 | #[tokio::test] |
| 379 | 389 | async fn the_loser_of_a_settings_race_cannot_un_retire_the_winner_s_kind() { |
| 380 | - let db = init_mem().await.unwrap(); | |
| 381 | - let counter = kind_ref("midterm"); | |
| 382 | - | |
| 383 | - // The winner's PATCH retires the kind. | |
| 384 | - assert!(matches!( | |
| 385 | - cap::retire_name(&counter, &db).await.unwrap(), | |
| 386 | - cap::Switched::Flipped | |
| 387 | - )); | |
| 388 | - | |
| 389 | - // The loser's PATCH decides the same removal against the same snapshot, | |
| 390 | - // then its save is refused. | |
| 391 | - let mut undo = Vec::new(); | |
| 392 | - if let cap::Switched::Flipped = cap::retire_name(&counter, &db).await.unwrap() { | |
| 393 | - undo.push(Undo::Retired(counter.clone())); | |
| 394 | - } | |
| 395 | - assert!(undo.is_empty(), "a no-op retirement records no undo"); | |
| 396 | - restore(&undo, &db).await.unwrap(); | |
| 390 | + let (db, _leases) = init_test_db().await; | |
| 391 | + // Two managers send the same removal, each having decided it against | |
| 392 | + // the same original list. The winner's attempt retires the kind and | |
| 393 | + // saves; the loser's save loses the compare-and-set, aborts — taking | |
| 394 | + // every write of its attempt back with it — and retries against the | |
| 395 | + // fresh list, where the same PATCH is a no-op that flips nothing. | |
| 396 | + // (The old engine needed a hand-rolled undo list for this; the | |
| 397 | + // transaction's own rollback is the undo now.) | |
| 398 | + let without_midterm = SettingsPatch { | |
| 399 | + exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])), | |
| 400 | + ..a_patch() | |
| 401 | + }; | |
| 402 | + apply(&db, &without_midterm).await.unwrap(); // the winner | |
| 403 | + apply(&db, &without_midterm).await.unwrap(); // the loser, retried | |
| 397 | 404 | |
| 398 | 405 | assert_eq!( |
| 399 | - bit(&db, counter).await, | |
| 406 | + kind_bit(&db, "midterm").await, | |
| 400 | 407 | Some(true), |
| 401 | 408 | "the winner's retirement must outlive the loser's rollback" |
| 402 | 409 | ); |
| 410 | + assert!(!stored(&db).await.0.contains(&"midterm".to_string())); | |
| 403 | 411 | } |
| 404 | 412 | |
| 405 | 413 | /// The mirror hole: a re-*added* name is put back in service before the |
| @@ -407,20 +415,37 @@ mod tests { | ||
| 407 | 415 | /// name is off the stored list with a counter that grades happily. |
| 408 | 416 | #[tokio::test] |
| 409 | 417 | async fn a_rollback_re_retires_a_name_this_attempt_put_back_in_service() { |
| 410 | - let db = init_mem().await.unwrap(); | |
| 411 | - let counter = slot_ref("lunch"); | |
| 412 | - cap::retire_name(&counter, &db).await.unwrap(); | |
| 413 | - | |
| 414 | - // The attempt re-adds the slot, then its save is refused. | |
| 415 | - let mut undo = Vec::new(); | |
| 416 | - if let cap::Switched::Flipped = cap::unretire_name(&counter, &db).await.unwrap() { | |
| 417 | - undo.push(Undo::Unretired(counter.clone())); | |
| 418 | - } | |
| 419 | - assert_eq!(undo.len(), 1, "a real un-retirement is undoable"); | |
| 420 | - restore(&undo, &db).await.unwrap(); | |
| 418 | + let (db, _leases) = init_test_db().await; | |
| 419 | + // The stored list drops lunch; the slot counter carries the retirement. | |
| 420 | + let without = SettingsPatch { | |
| 421 | + meal_slots: Some(slots(&["breakfast", "snack"])), | |
| 422 | + ..a_patch() | |
| 423 | + }; | |
| 424 | + apply(&db, &without).await.unwrap(); | |
| 425 | + assert_eq!(slot_bit(&db, "lunch").await, Some(true)); | |
| 426 | + | |
| 427 | + // An attempt re-adds the slot but judged the write against the row | |
| 428 | + // *before* a rival's unrelated edit landed: its guarded save writes | |
| 429 | + // zero rows, and — inside [`apply`] — the abort would take the | |
| 430 | + // attempt's un-retirement straight back with it. Driven here at the | |
| 431 | + // save the way the loser experiences it: refused, so nothing lands. | |
| 432 | + let stale_snapshot = load(&db).await.unwrap(); | |
| 433 | + let elsewhere = SettingsPatch { | |
| 434 | + max_file_bytes: Some(2048), | |
| 435 | + ..a_patch() | |
| 436 | + }; | |
| 437 | + apply(&db, &elsewhere).await.unwrap(); | |
| 438 | + | |
| 439 | + let mut params = Settings::defaults().params(); | |
| 440 | + params.meal_slots = vec![MealSlotDef::try_new("lunch", None).unwrap()]; | |
| 441 | + let re_added = Settings::try_new(params).unwrap(); | |
| 442 | + let landed = crate::db::settings::save_if_unchanged(&db, re_added, &stale_snapshot) | |
| 443 | + .await | |
| 444 | + .unwrap(); | |
| 445 | + assert!(landed.is_none(), "the stale save must be refused"); | |
| 421 | 446 | |
| 422 | 447 | assert_eq!( |
| 423 | - bit(&db, counter).await, | |
| 448 | + slot_bit(&db, "lunch").await, | |
| 424 | 449 | Some(true), |
| 425 | 450 | "a re-add that never landed must leave the slot retired" |
| 426 | 451 | ); |
| @@ -432,22 +457,33 @@ mod tests { | ||
| 432 | 457 | /// overwrite of a live reference. |
| 433 | 458 | #[tokio::test] |
| 434 | 459 | async fn a_rollback_leaves_a_name_that_gained_a_reference_in_service() { |
| 435 | - let db = init_mem().await.unwrap(); | |
| 436 | - let counter = slot_ref("lunch"); | |
| 437 | - cap::retire_name(&counter, &db).await.unwrap(); | |
| 438 | - cap::unretire_name(&counter, &db).await.unwrap(); | |
| 439 | - db.query("UPDATE $id SET count = 1") | |
| 440 | - .bind(("id", counter.clone())) | |
| 441 | - .await | |
| 442 | - .unwrap() | |
| 443 | - .check() | |
| 444 | - .unwrap(); | |
| 445 | - | |
| 446 | - restore(&[Undo::Unretired(counter.clone())], &db) | |
| 460 | + let (db, _leases) = init_test_db().await; | |
| 461 | + // Lunch goes away and comes back, and while it is in service a menu is | |
| 462 | + // published against it — the live reference the counter counts. | |
| 463 | + let without = SettingsPatch { | |
| 464 | + meal_slots: Some(slots(&["breakfast", "snack"])), | |
| 465 | + ..a_patch() | |
| 466 | + }; | |
| 467 | + apply(&db, &without).await.unwrap(); | |
| 468 | + let with = SettingsPatch { | |
| 469 | + meal_slots: Some(slots(&["breakfast", "lunch", "snack"])), | |
| 470 | + ..a_patch() | |
| 471 | + }; | |
| 472 | + apply(&db, &with).await.unwrap(); | |
| 473 | + sqlx::query("UPDATE slot_ref SET count = 1 WHERE name = 'lunch'") | |
| 474 | + .execute(&db) | |
| 447 | 475 | .await |
| 448 | 476 | .unwrap(); |
| 449 | 477 | |
| 450 | - assert_eq!(bit(&db, counter).await, Some(false)); | |
| 478 | + // The attempt that takes lunch away again now meets the reference: the | |
| 479 | + // removal is refused — honestly, with the published-menu 409, not by | |
| 480 | + // silently overwriting a live reference — and the slot stays usable. | |
| 481 | + let refused = apply(&db, &without).await; | |
| 482 | + assert!( | |
| 483 | + matches!(refused, Err(AppError::ConflictOwned(ref msg)) if msg.contains("'lunch'")), | |
| 484 | + "a referenced slot's removal must be refused: {refused:?}" | |
| 485 | + ); | |
| 486 | + assert_eq!(slot_bit(&db, "lunch").await, Some(false)); | |
| 451 | 487 | } |
| 452 | 488 | |
| 453 | 489 | // --- the whole edit, driven the way two managers drive it ------------- |
| @@ -513,7 +549,7 @@ mod tests { | ||
| 513 | 549 | /// legitimately removed — off the list and gradable. |
| 514 | 550 | #[tokio::test] |
| 515 | 551 | async fn two_edits_dropping_the_same_kind_leave_it_retired() { |
| 516 | - let db = init_mem().await.unwrap(); | |
| 552 | + let (db, _leases) = init_test_db().await; | |
| 517 | 553 | let without = SettingsPatch { |
| 518 | 554 | exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])), |
| 519 | 555 | ..a_patch() |
| @@ -529,7 +565,7 @@ mod tests { | ||
| 529 | 565 | "dropped from the list" |
| 530 | 566 | ); |
| 531 | 567 | assert_eq!( |
| 532 | - bit(&db, kind_ref("midterm")).await, | |
| 568 | + kind_bit(&db, "midterm").await, | |
| 533 | 569 | Some(true), |
| 534 | 570 | "a kind the stored list no longer offers must not grade" |
| 535 | 571 | ); |
| @@ -548,29 +584,41 @@ mod tests { | ||
| 548 | 584 | /// the other edit does may be visible until the pair completes. |
| 549 | 585 | #[tokio::test] |
| 550 | 586 | async fn a_rival_edit_cannot_run_between_a_retirement_and_its_save() { |
| 551 | - let db = init_mem().await.unwrap(); | |
| 587 | + let (db, _leases) = init_test_db().await; | |
| 552 | 588 | let without = SettingsPatch { |
| 553 | 589 | exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])), |
| 554 | 590 | ..a_patch() |
| 555 | 591 | }; |
| 556 | 592 | |
| 557 | - let held = SETTINGS_LOCK.lock().await; | |
| 593 | + // The retire-then-save pair is one transaction, so a rival reading the | |
| 594 | + // store while the edit runs can see the pair wholly unlanded or wholly | |
| 595 | + // landed — never the retirement without the list commit that was the | |
| 596 | + // old lock's whole job to prevent. Poll the edit from the outside and | |
| 597 | + // assert that at every instant. | |
| 558 | 598 | let rival = tokio::spawn({ |
| 559 | 599 | let db = db.clone(); |
| 560 | 600 | async move { apply(&db, &without).await.map(|_| ()) } |
| 561 | 601 | }); |
| 562 | - tokio::time::sleep(std::time::Duration::from_millis(200)).await; | |
| 563 | - | |
| 564 | - assert_eq!( | |
| 565 | - bit(&db, kind_ref("midterm")).await, | |
| 566 | - None, | |
| 567 | - "a rival's pair must not have started, let alone half-landed" | |
| 568 | - ); | |
| 569 | - assert!(stored(&db).await.0.contains(&"midterm".to_string())); | |
| 602 | + while !rival.is_finished() { | |
| 603 | + let (kinds, _) = stored(&db).await; | |
| 604 | + let retired = kind_bit(&db, "midterm").await; | |
| 605 | + if retired == Some(true) { | |
| 606 | + assert!( | |
| 607 | + !kinds.contains(&"midterm".to_string()), | |
| 608 | + "a retirement became visible before its list commit" | |
| 609 | + ); | |
| 610 | + } | |
| 611 | + if retired == Some(false) { | |
| 612 | + assert!( | |
| 613 | + kinds.contains(&"midterm".to_string()), | |
| 614 | + "an un-retirement became visible before its list commit" | |
| 615 | + ); | |
| 616 | + } | |
| 617 | + tokio::task::yield_now().await; | |
| 618 | + } | |
| 570 | 619 | |
| 571 | - drop(held); | |
| 572 | 620 | rival.await.unwrap().unwrap(); |
| 573 | - assert_eq!(bit(&db, kind_ref("midterm")).await, Some(true)); | |
| 621 | + assert_eq!(kind_bit(&db, "midterm").await, Some(true)); | |
| 574 | 622 | assert!(!stored(&db).await.0.contains(&"midterm".to_string())); |
| 575 | 623 | } |
| 576 | 624 | |
| @@ -579,7 +627,7 @@ mod tests { | ||
| 579 | 627 | /// a listed kind that refuses every grade. |
| 580 | 628 | #[tokio::test] |
| 581 | 629 | async fn two_edits_re_adding_the_same_kind_leave_it_in_service() { |
| 582 | - let db = init_mem().await.unwrap(); | |
| 630 | + let (db, _leases) = init_test_db().await; | |
| 583 | 631 | let without = SettingsPatch { |
| 584 | 632 | exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])), |
| 585 | 633 | ..a_patch() |
| @@ -599,7 +647,7 @@ mod tests { | ||
| 599 | 647 | let (kinds, _) = stored(&db).await; |
| 600 | 648 | assert!(kinds.contains(&"midterm".to_string()), "back on the list"); |
| 601 | 649 | assert_eq!( |
| 602 | - bit(&db, kind_ref("midterm")).await, | |
| 650 | + kind_bit(&db, "midterm").await, | |
| 603 | 651 | Some(false), |
| 604 | 652 | "a kind the stored list offers must grade" |
| 605 | 653 | ); |
| @@ -608,7 +656,7 @@ mod tests { | ||
| 608 | 656 | /// The same pair over meal slots, which retire on their own counters. |
| 609 | 657 | #[tokio::test] |
| 610 | 658 | async fn two_edits_dropping_the_same_slot_leave_it_retired() { |
| 611 | - let db = init_mem().await.unwrap(); | |
| 659 | + let (db, _leases) = init_test_db().await; | |
| 612 | 660 | let without = SettingsPatch { |
| 613 | 661 | meal_slots: Some(slots(&["breakfast", "snack"])), |
| 614 | 662 | ..a_patch() |
| @@ -620,7 +668,7 @@ mod tests { | ||
| 620 | 668 | |
| 621 | 669 | let (_, stored_slots) = stored(&db).await; |
| 622 | 670 | assert!(!stored_slots.contains(&"lunch".to_string())); |
| 623 | - assert_eq!(bit(&db, slot_ref("lunch")).await, Some(true)); | |
| 671 | + assert_eq!(slot_bit(&db, "lunch").await, Some(true)); | |
| 624 | 672 | } |
| 625 | 673 | |
| 626 | 674 | // --- the stale slot name that wedged the whole list ------------------- |
| @@ -641,7 +689,7 @@ mod tests { | ||
| 641 | 689 | /// stored name is submittable; a new one with the same characters is not. |
| 642 | 690 | #[tokio::test] |
| 643 | 691 | async fn a_stored_slot_name_stays_submittable_but_a_new_one_does_not() { |
| 644 | - let db = init_mem().await.unwrap(); | |
| 692 | + let (db, _leases) = init_test_db().await; | |
| 645 | 693 | a_school_with_a_stale_slot(&db).await; |
| 646 | 694 | |
| 647 | 695 | let edit = SettingsPatch { |
| @@ -666,7 +714,7 @@ mod tests { | ||
| 666 | 714 | /// over unvalidated — the behaviour the wedge report leaned on. |
| 667 | 715 | #[tokio::test] |
| 668 | 716 | async fn an_unrelated_edit_carries_a_stale_slot_name_over() { |
| 669 | - let db = init_mem().await.unwrap(); | |
| 717 | + let (db, _leases) = init_test_db().await; | |
| 670 | 718 | a_school_with_a_stale_slot(&db).await; |
| 671 | 719 | |
| 672 | 720 | let elsewhere = SettingsPatch { |
src/service/user.rsmodified+4 -4
| @@ -210,7 +210,7 @@ pub async fn set_preferences( | ||
| 210 | 210 | #[cfg(test)] |
| 211 | 211 | mod tests { |
| 212 | 212 | use super::*; |
| 213 | - use crate::database::{Database, init_mem}; | |
| 213 | + use crate::database::{Database, init_test_db}; | |
| 214 | 214 | use crate::domain::user::Password; |
| 215 | 215 | |
| 216 | 216 | async fn a_user(username: &str, db: &Database) -> User { |
| @@ -236,7 +236,7 @@ mod tests { | ||
| 236 | 236 | async fn the_cascade_returns_the_boards_it_stripped() { |
| 237 | 237 | use crate::domain::board::BoardTitle; |
| 238 | 238 | |
| 239 | - let db = init_mem().await.unwrap(); | |
| 239 | + let (db, _leases) = init_test_db().await; | |
| 240 | 240 | let creator = a_user("ogretmen", &db).await; |
| 241 | 241 | let guest = a_user("ogrenci", &db).await; |
| 242 | 242 | let board = crate::db::board::create( |
| @@ -276,7 +276,7 @@ mod tests { | ||
| 276 | 276 | use crate::domain::board::BoardTitle; |
| 277 | 277 | use crate::domain::board_stroke::BOARD_CLOSED; |
| 278 | 278 | |
| 279 | - let db = init_mem().await.unwrap(); | |
| 279 | + let (db, _leases) = init_test_db().await; | |
| 280 | 280 | let creator = a_user("ogretmen", &db).await; |
| 281 | 281 | let guest = a_user("ogrenci", &db).await; |
| 282 | 282 | let board = crate::db::board::create( |
| @@ -352,7 +352,7 @@ mod tests { | ||
| 352 | 352 | use crate::domain::timestamp::Timestamp; |
| 353 | 353 | use crate::service::appointment; |
| 354 | 354 | |
| 355 | - let db = init_mem().await.unwrap(); | |
| 355 | + let (db, _leases) = init_test_db().await; | |
| 356 | 356 | let staff = |name: &'static str, db: Database| async move { |
| 357 | 357 | let teacher = a_user(name, &db).await; |
| 358 | 358 | set_role(&db, teacher.get_id(), Role::Teacher) |
src/web/appointments.rsmodified+5 -5
| @@ -58,7 +58,7 @@ struct PublishSlots { | ||
| 58 | 58 | #[derive(Deserialize, ToSchema)] |
| 59 | 59 | struct BookAppointment { |
| 60 | 60 | /// The slot to take, from `GET /appointments/slots`. |
| 61 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 61 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 62 | 62 | slot: String, |
| 63 | 63 | /// Why you want the meeting — required, the teacher decides on it. |
| 64 | 64 | #[schema(max_length = 1000, example = "Ders notlarını konuşmak istiyorum")] |
| @@ -103,7 +103,7 @@ struct AcceptReschedule { | ||
| 103 | 103 | |
| 104 | 104 | #[derive(Serialize, ToSchema)] |
| 105 | 105 | struct SlotResponse { |
| 106 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 106 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 107 | 107 | id: String, |
| 108 | 108 | /// Whose calendar this is. |
| 109 | 109 | teacher: PersonRef, |
| @@ -134,7 +134,7 @@ impl SlotResponse { | ||
| 134 | 134 | |
| 135 | 135 | #[derive(Serialize, ToSchema)] |
| 136 | 136 | struct AppointmentResponse { |
| 137 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 137 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 138 | 138 | id: String, |
| 139 | 139 | /// The slot this booking sits on. |
| 140 | 140 | slot: String, |
| @@ -901,7 +901,7 @@ async fn ensure_requester( | ||
| 901 | 901 | #[cfg(test)] |
| 902 | 902 | mod tests { |
| 903 | 903 | use super::*; |
| 904 | - use crate::database::init_mem; | |
| 904 | + use crate::database::init_test_db; | |
| 905 | 905 | use crate::domain::user::{Password, Username}; |
| 906 | 906 | |
| 907 | 907 | /// A user at `role`, minted through the real create path. |
| @@ -922,7 +922,7 @@ mod tests { | ||
| 922 | 922 | /// level that has to hold when the next route arrives with `CurrentUser`. |
| 923 | 923 | #[tokio::test] |
| 924 | 924 | async fn demoted_slot_owner_loses_management() { |
| 925 | - let db = init_mem().await.unwrap(); | |
| 925 | + let (db, _leases) = init_test_db().await; | |
| 926 | 926 | let owner = user("ogretmen", Role::Teacher, &db).await; |
| 927 | 927 | let slot = service::appointment_slot::create( |
| 928 | 928 | &db, |
src/web/bank_questions.rsmodified+4 -4
| @@ -94,7 +94,7 @@ struct CreateBankQuestion { | ||
| 94 | 94 | /// school's subjects; it is *not* held to a course here (the bank spans |
| 95 | 95 | /// courses), only checked against the target exam's course when the |
| 96 | 96 | /// template is instantiated. |
| 97 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 97 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 98 | 98 | subject_id: String, |
| 99 | 99 | #[schema(example = "What is 2 + 2?", max_length = 2000)] |
| 100 | 100 | text: String, |
| @@ -921,7 +921,7 @@ async fn delete_choice_image( | ||
| 921 | 921 | #[cfg(test)] |
| 922 | 922 | mod tests { |
| 923 | 923 | use super::*; |
| 924 | - use crate::database::{Database, init_mem}; | |
| 924 | + use crate::database::{Database, init_test_db}; | |
| 925 | 925 | use crate::domain::role::Role; |
| 926 | 926 | use crate::domain::user::{Password, Username}; |
| 927 | 927 | |
| @@ -946,12 +946,12 @@ mod tests { | ||
| 946 | 946 | /// must hold when a future route arrives with a different extractor. |
| 947 | 947 | #[tokio::test] |
| 948 | 948 | async fn demoted_owner_loses_their_own_template() { |
| 949 | - let db = init_mem().await.unwrap(); | |
| 949 | + let (db, _leases) = init_test_db().await; | |
| 950 | 950 | let owner = user("ogretmen", Role::Teacher, &db).await; |
| 951 | 951 | let question = bank_question::create( |
| 952 | 952 | &db, |
| 953 | 953 | owner.get_id().clone(), |
| 954 | - SubjectId::from_key("01TESTSUBJECTAAAAAAAAAAAAA"), | |
| 954 | + SubjectId::from_key("019732e3-7b00-7000-8000-00000000a2b3"), | |
| 955 | 955 | QuestionText::try_new("2 + 2 = ?").unwrap(), |
| 956 | 956 | QuestionPoints::try_new(1).unwrap(), |
| 957 | 957 | QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None, &[]).unwrap(), |
src/web/board_ws.rsmodified+1 -1
| @@ -674,7 +674,7 @@ mod tests { | ||
| 674 | 674 | use crate::domain::board::BoardTitle; |
| 675 | 675 | use crate::domain::user::{Password, Username}; |
| 676 | 676 | |
| 677 | - let db = crate::database::init_mem().await.unwrap(); | |
| 677 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 678 | 678 | let password = Password::try_new("secret1").unwrap(); |
| 679 | 679 | let creator = crate::service::user::create( |
| 680 | 680 | &db, |
src/web/chatbot.rsmodified+5 -5
| @@ -77,7 +77,7 @@ struct CreateChatbotThread { | ||
| 77 | 77 | /// sorted by it, so the thread just written to is always first. |
| 78 | 78 | #[derive(Serialize, ToSchema)] |
| 79 | 79 | struct ChatbotThreadResponse { |
| 80 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 80 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 81 | 81 | id: String, |
| 82 | 82 | #[schema(example = "Fizik ödevi")] |
| 83 | 83 | title: Option<String>, |
| @@ -261,7 +261,7 @@ struct SendChatbotMessage { | ||
| 261 | 261 | #[derive(Serialize, ToSchema)] |
| 262 | 262 | struct AcceptedResponse { |
| 263 | 263 | /// The assistant row reserved for the answer. |
| 264 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 264 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 265 | 265 | message_id: String, |
| 266 | 266 | /// Always `pending` — that is what "accepted" means here. |
| 267 | 267 | #[schema(example = "pending")] |
| @@ -272,9 +272,9 @@ struct AcceptedResponse { | ||
| 272 | 272 | /// set only when `status` is `failed`. |
| 273 | 273 | #[derive(Serialize, ToSchema)] |
| 274 | 274 | struct ChatbotMessageResponse { |
| 275 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 275 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 276 | 276 | id: String, |
| 277 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 277 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 278 | 278 | thread_id: String, |
| 279 | 279 | /// `user` or `assistant`. |
| 280 | 280 | #[schema(example = "assistant")] |
| @@ -900,7 +900,7 @@ mod tests { | ||
| 900 | 900 | // A run of failed answers must make the window reach further back, not |
| 901 | 901 | // shrink it: filtering a fixed-size tail after the fact handed the |
| 902 | 902 | // service a handful of unanswered prompts and nothing older. |
| 903 | - let db = crate::database::init_mem().await.unwrap(); | |
| 903 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 904 | 904 | // A real thread row: every turn is written through it, so a turn with |
| 905 | 905 | // no thread is refused. |
| 906 | 906 | db.query("CREATE chatbot_thread:c SET user_id = user:u, created_at = 0, updated_at = 0") |
src/web/classes.rsmodified+1 -1
| @@ -1496,7 +1496,7 @@ mod tests { | ||
| 1496 | 1496 | use crate::domain::role::Role; |
| 1497 | 1497 | use crate::domain::user::{Password, Username}; |
| 1498 | 1498 | |
| 1499 | - let db = crate::database::init_mem().await.unwrap(); | |
| 1499 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 1500 | 1500 | assert!(teacher_or_none(None, &db).await.unwrap().is_none()); |
| 1501 | 1501 | assert!(teacher_or_none(Some(""), &db).await.unwrap().is_none()); |
| 1502 | 1502 |
src/web/course_notes.rsmodified+2 -2
| @@ -68,7 +68,7 @@ async fn note_with_course(id: &str, db: &Database) -> Result<(CourseNote, Course | ||
| 68 | 68 | |
| 69 | 69 | #[derive(Deserialize, ToSchema)] |
| 70 | 70 | struct CreateCourseNote { |
| 71 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 71 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 72 | 72 | course: String, |
| 73 | 73 | #[schema(example = "Chapter 3 recap", max_length = 200)] |
| 74 | 74 | title: String, |
| @@ -153,7 +153,7 @@ async fn create( | ||
| 153 | 153 | #[derive(Deserialize, IntoParams)] |
| 154 | 154 | struct CourseFilter { |
| 155 | 155 | /// The course to list notes for (required). |
| 156 | - #[param(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 156 | + #[param(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 157 | 157 | course: String, |
| 158 | 158 | } |
| 159 | 159 |
src/web/courses.rsmodified+10 -10
| @@ -108,7 +108,7 @@ struct UpdateCourse { | ||
| 108 | 108 | #[derive(Deserialize, ToSchema)] |
| 109 | 109 | struct EnrollUser { |
| 110 | 110 | /// The user to enroll. |
| 111 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 111 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 112 | 112 | user_id: String, |
| 113 | 113 | } |
| 114 | 114 | |
| @@ -116,7 +116,7 @@ struct EnrollUser { | ||
| 116 | 116 | struct AssignTeacher { |
| 117 | 117 | /// The staff member to put in charge of the course. Must hold the |
| 118 | 118 | /// `teacher` role or higher. |
| 119 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 119 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 120 | 120 | user_id: String, |
| 121 | 121 | } |
| 122 | 122 | |
| @@ -177,7 +177,7 @@ struct EnrollmentResponse { | ||
| 177 | 177 | /// class drops the student or detaches the course; a `null` one is nobody's |
| 178 | 178 | /// to take back. Without it no client could tell which of its roster rows a |
| 179 | 179 | /// class change is about to remove. |
| 180 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 180 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 181 | 181 | source: Option<String>, |
| 182 | 182 | } |
| 183 | 183 | |
| @@ -1020,7 +1020,7 @@ struct CreateHomework { | ||
| 1020 | 1020 | /// The course subject this homework belongs to |
| 1021 | 1021 | /// (`GET /courses/{id}/subjects`). Required — every homework is tagged with |
| 1022 | 1022 | /// one of its course's subjects. |
| 1023 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 1023 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 1024 | 1024 | subject_id: String, |
| 1025 | 1025 | /// When the homework is due, UTC unix-milliseconds. Required; must not be |
| 1026 | 1026 | /// in the past. Late submissions are still accepted, just flagged late. |
| @@ -1282,7 +1282,7 @@ async fn list_course_sessions( | ||
| 1282 | 1282 | #[cfg(test)] |
| 1283 | 1283 | mod tests { |
| 1284 | 1284 | use super::*; |
| 1285 | - use crate::database::init_mem; | |
| 1285 | + use crate::database::init_test_db; | |
| 1286 | 1286 | use crate::domain::user::{Password, Username}; |
| 1287 | 1287 | |
| 1288 | 1288 | /// A user at `role`, minted through the real create path. |
| @@ -1320,7 +1320,7 @@ mod tests { | ||
| 1320 | 1320 | /// so the grant itself has to re-read the live role on every call. |
| 1321 | 1321 | #[tokio::test] |
| 1322 | 1322 | async fn demoted_creator_loses_management_and_ownership() { |
| 1323 | - let db = init_mem().await.unwrap(); | |
| 1323 | + let (db, _leases) = init_test_db().await; | |
| 1324 | 1324 | let creator = user("teacher", Role::Teacher, &db).await; |
| 1325 | 1325 | let course = course(&creator, &db).await; |
| 1326 | 1326 | assert!(can_manage_course(&course, &creator)); |
| @@ -1346,7 +1346,7 @@ mod tests { | ||
| 1346 | 1346 | /// but the grant must not depend on that sweep having run. |
| 1347 | 1347 | #[tokio::test] |
| 1348 | 1348 | async fn demoted_assigned_teacher_loses_management() { |
| 1349 | - let db = init_mem().await.unwrap(); | |
| 1349 | + let (db, _leases) = init_test_db().await; | |
| 1350 | 1350 | let creator = user("creator", Role::Teacher, &db).await; |
| 1351 | 1351 | let assigned = user("assigned", Role::Teacher, &db).await; |
| 1352 | 1352 | let course = |
| @@ -1372,13 +1372,13 @@ mod tests { | ||
| 1372 | 1372 | /// hand the office staff somebody else's lesson. |
| 1373 | 1373 | #[tokio::test] |
| 1374 | 1374 | async fn a_manager_scheduling_a_lesson_names_the_teacher_not_themselves() { |
| 1375 | - let db = init_mem().await.unwrap(); | |
| 1375 | + let (db, _leases) = init_test_db().await; | |
| 1376 | 1376 | let manager = user("manager", Role::Manager, &db).await; |
| 1377 | 1377 | let teacher = user("teacher", Role::Teacher, &db).await; |
| 1378 | 1378 | let course = course(&manager, &db).await; |
| 1379 | 1379 | let st = AppState { |
| 1380 | 1380 | db: db.clone(), |
| 1381 | - tenants: crate::database::init_mem_tenants().await.unwrap(), | |
| 1381 | + tenants: crate::database::init_test_tenants().await, | |
| 1382 | 1382 | files_path: std::env::temp_dir(), |
| 1383 | 1383 | cookie_secure: false, |
| 1384 | 1384 | rate_limit: crate::rate_limit::RateLimitConfig::unlimited(), |
| @@ -1417,7 +1417,7 @@ mod tests { | ||
| 1417 | 1417 | /// creator was demoted and which has no assigned teachers. |
| 1418 | 1418 | #[tokio::test] |
| 1419 | 1419 | async fn manager_still_manages_a_demoted_creators_course() { |
| 1420 | - let db = init_mem().await.unwrap(); | |
| 1420 | + let (db, _leases) = init_test_db().await; | |
| 1421 | 1421 | let creator = user("teacher", Role::Teacher, &db).await; |
| 1422 | 1422 | let course = course(&creator, &db).await; |
| 1423 | 1423 | crate::service::user::set_role(&db, creator.get_id(), Role::Student) |
src/web/dto.rsmodified+5 -5
| @@ -74,7 +74,7 @@ impl From<DomainRole> for Role { | ||
| 74 | 74 | /// show a raw ULID to a human. |
| 75 | 75 | #[derive(Serialize, Clone, ToSchema)] |
| 76 | 76 | pub struct PersonRef { |
| 77 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 77 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 78 | 78 | pub id: String, |
| 79 | 79 | #[schema(example = "ada")] |
| 80 | 80 | pub username: String, |
| @@ -151,7 +151,7 @@ pub async fn person_map( | ||
| 151 | 151 | /// (register/login/me) and `users` (listing, role and profile changes). |
| 152 | 152 | #[derive(Serialize, ToSchema)] |
| 153 | 153 | pub struct UserResponse { |
| 154 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 154 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 155 | 155 | pub id: String, |
| 156 | 156 | #[schema(example = "ada")] |
| 157 | 157 | pub username: String, |
| @@ -212,7 +212,7 @@ impl UserResponse { | ||
| 212 | 212 | /// blocks embed the course they average). |
| 213 | 213 | #[derive(Serialize, ToSchema)] |
| 214 | 214 | pub struct CourseResponse { |
| 215 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 215 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 216 | 216 | pub id: String, |
| 217 | 217 | /// Who created (and owns) the course. Only they and managers/admins may |
| 218 | 218 | /// delete it or change who teaches it. |
| @@ -268,7 +268,7 @@ impl CourseResponse { | ||
| 268 | 268 | /// delete). |
| 269 | 269 | #[derive(Serialize, ToSchema)] |
| 270 | 270 | pub struct SubjectResponse { |
| 271 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 271 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 272 | 272 | pub id: String, |
| 273 | 273 | /// The course whose curriculum this subject belongs to. |
| 274 | 274 | pub course: String, |
| @@ -296,7 +296,7 @@ impl SubjectResponse { | ||
| 296 | 296 | /// submission (against `due_at`), never stored on the homework itself. |
| 297 | 297 | #[derive(Serialize, ToSchema)] |
| 298 | 298 | pub struct HomeworkResponse { |
| 299 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 299 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 300 | 300 | pub id: String, |
| 301 | 301 | /// The course this homework belongs to. |
| 302 | 302 | pub course: String, |
src/web/events.rsmodified+2 -2
| @@ -912,7 +912,7 @@ async fn unregister( | ||
| 912 | 912 | #[cfg(test)] |
| 913 | 913 | mod tests { |
| 914 | 914 | use super::*; |
| 915 | - use crate::database::init_mem; | |
| 915 | + use crate::database::init_test_db; | |
| 916 | 916 | use crate::domain::user::{Password, Username}; |
| 917 | 917 | |
| 918 | 918 | /// A user at `role`, minted through the real create path. |
| @@ -936,7 +936,7 @@ mod tests { | ||
| 936 | 936 | /// helper is what must hold when a future route arrives with `CurrentUser`. |
| 937 | 937 | #[tokio::test] |
| 938 | 938 | async fn demoted_event_creator_loses_management() { |
| 939 | - let db = init_mem().await.unwrap(); | |
| 939 | + let (db, _leases) = init_test_db().await; | |
| 940 | 940 | let creator = user("ogretmen", Role::Teacher, &db).await; |
| 941 | 941 | let event = service::event::create( |
| 942 | 942 | &db, |
src/web/exams/mod.rsmodified+1 -1
| @@ -183,7 +183,7 @@ struct GradeResult { | ||
| 183 | 183 | #[schema(example = 85, minimum = 0, maximum = 100)] |
| 184 | 184 | mark: i64, |
| 185 | 185 | /// The student being graded. |
| 186 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 186 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 187 | 187 | user_id: String, |
| 188 | 188 | } |
| 189 | 189 |
src/web/exams/questions.rsmodified+2 -2
| @@ -14,7 +14,7 @@ use crate::service::exam_question; | ||
| 14 | 14 | pub(crate) struct CreateQuestion { |
| 15 | 15 | /// The subject this question belongs to — one of the exam's course's |
| 16 | 16 | /// subjects (`GET /courses/{id}/subjects`). Required. |
| 17 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 17 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 18 | 18 | subject_id: String, |
| 19 | 19 | /// The question itself. |
| 20 | 20 | #[schema(example = "What is 2 + 2?", max_length = 2000)] |
| @@ -435,7 +435,7 @@ pub(crate) async fn delete_question( | ||
| 435 | 435 | pub(crate) struct InstantiateFromBank { |
| 436 | 436 | /// The subject to file the new question under — one of the exam's course's |
| 437 | 437 | /// subjects (the same-course rule the bank row itself is exempt from). |
| 438 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 438 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 439 | 439 | subject_id: String, |
| 440 | 440 | } |
| 441 | 441 |
src/web/homework.rsmodified+2 -2
| @@ -407,7 +407,7 @@ async fn delete_homework( | ||
| 407 | 407 | /// separately from `GET /homework/{id}/submission/files/{fid}`. |
| 408 | 408 | #[derive(Serialize, ToSchema)] |
| 409 | 409 | struct HomeworkFileResponse { |
| 410 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 410 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 411 | 411 | id: String, |
| 412 | 412 | /// The uploader's original filename. |
| 413 | 413 | #[schema(example = "odev.pdf")] |
| @@ -886,7 +886,7 @@ async fn delete_submission_file( | ||
| 886 | 886 | #[derive(Deserialize, ToSchema)] |
| 887 | 887 | struct GradeHomework { |
| 888 | 888 | /// The student being graded. |
| 889 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 889 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 890 | 890 | user: String, |
| 891 | 891 | /// The verdict: `done`, `incomplete`, or `missing`. |
| 892 | 892 | #[schema(example = "done")] |
src/web/messages.rsmodified+1 -1
| @@ -30,7 +30,7 @@ pub fn routes() -> OpenApiRouter<AppState> { | ||
| 30 | 30 | #[derive(Deserialize, ToSchema)] |
| 31 | 31 | struct SendMessage { |
| 32 | 32 | /// The receiving user's id (find people via `GET /users/search`). |
| 33 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 33 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 34 | 34 | recipient_id: String, |
| 35 | 35 | #[schema(example = "About today's study session", max_length = 200)] |
| 36 | 36 | subject: String, |
src/web/mod.rsmodified+1 -1
| @@ -380,7 +380,7 @@ mod tests { | ||
| 380 | 380 | use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; |
| 381 | 381 | use crate::domain::user::{Password, Username}; |
| 382 | 382 | |
| 383 | - let db = crate::database::init_mem().await.unwrap(); | |
| 383 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 384 | 384 | let office = UserId::from_key("office"); |
| 385 | 385 | let teacher = crate::service::user::create( |
| 386 | 386 | &db, |
src/web/payments.rsmodified+2 -2
| @@ -333,7 +333,7 @@ async fn delete_plan( | ||
| 333 | 333 | struct AssignFeePlan { |
| 334 | 334 | /// The students to place on the plan, at most 200 per call. Each is |
| 335 | 335 | /// reported on individually — one bad id does not lose the rest. |
| 336 | - #[schema(max_items = 200, example = json!(["01JC0Z0Z0Z0Z0Z0Z0Z0Z0Z0Z0Z"]))] | |
| 336 | + #[schema(max_items = 200, example = json!(["019732e3-7b00-7000-8000-000000000a0b"]))] | |
| 337 | 337 | student_ids: Vec<String>, |
| 338 | 338 | } |
| 339 | 339 | |
| @@ -1086,7 +1086,7 @@ mod tests { | ||
| 1086 | 1086 | /// shape of `source` links is exactly what the fold walks. |
| 1087 | 1087 | #[tokio::test] |
| 1088 | 1088 | async fn the_statement_rolls_each_charge_up_from_its_own_lines() { |
| 1089 | - let db = crate::database::init_mem().await.unwrap(); | |
| 1089 | + let (db, _leases) = crate::database::init_test_db().await; | |
| 1090 | 1090 | let manager = UserId::from_key("mgr1"); |
| 1091 | 1091 | let student = UserId::from_key("stu1"); |
| 1092 | 1092 | let future = Timestamp::now().as_millis() + 30 * 24 * 60 * 60 * 1000; |
src/web/tenant_state.rsmodified+3 -3
| @@ -180,7 +180,7 @@ mod tests { | ||
| 180 | 180 | use axum::{Router, body::Body, http::Request}; |
| 181 | 181 | use tower::ServiceExt; |
| 182 | 182 | |
| 183 | - use crate::database::init_mem_tenants; | |
| 183 | + use crate::database::init_test_tenants; | |
| 184 | 184 | use crate::db::session; |
| 185 | 185 | use crate::domain::user::{Password, Username}; |
| 186 | 186 | use crate::tenant::DEMO_SLUG; |
| @@ -197,7 +197,7 @@ mod tests { | ||
| 197 | 197 | /// A two-route app, one live cookie of each kind, and the registry behind |
| 198 | 198 | /// them. |
| 199 | 199 | async fn harness() -> (Router, String, String, crate::tenant::Tenants) { |
| 200 | - let tenants = init_mem_tenants().await.expect("in-memory deployment"); | |
| 200 | + let tenants = init_test_tenants().await; | |
| 201 | 201 | let school = tenants |
| 202 | 202 | .get(&Slug::try_new(DEMO_SLUG).unwrap()) |
| 203 | 203 | .await |
| @@ -343,7 +343,7 @@ mod tests { | ||
| 343 | 343 | /// still passes — the verdict came from the memoized extension. |
| 344 | 344 | #[tokio::test] |
| 345 | 345 | async fn a_request_resolves_its_school_exactly_once() { |
| 346 | - let tenants = init_mem_tenants().await.expect("in-memory deployment"); | |
| 346 | + let tenants = init_test_tenants().await; | |
| 347 | 347 | let demo = Slug::try_new(DEMO_SLUG).unwrap(); |
| 348 | 348 | let state = AppState { |
| 349 | 349 | db: tenants.control().clone(), |
src/web/users.rsmodified+3 -3
| @@ -706,7 +706,7 @@ async fn my_students( | ||
| 706 | 706 | /// A user's public profile. Contact details are not part of it, at any role. |
| 707 | 707 | #[derive(Serialize, ToSchema)] |
| 708 | 708 | struct ProfileResponse { |
| 709 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 709 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 710 | 710 | id: String, |
| 711 | 711 | #[schema(example = "ada")] |
| 712 | 712 | username: String, |
| @@ -763,7 +763,7 @@ struct ProfileAvatar { | ||
| 763 | 763 | /// `GET /classes/{id}`, which is teacher+. |
| 764 | 764 | #[derive(Serialize, ToSchema)] |
| 765 | 765 | struct ProfileClassRef { |
| 766 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 766 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 767 | 767 | id: String, |
| 768 | 768 | #[schema(example = "9-A")] |
| 769 | 769 | name: String, |
| @@ -774,7 +774,7 @@ struct ProfileClassRef { | ||
| 774 | 774 | /// A course as a profile shows it — a label, nothing more. |
| 775 | 775 | #[derive(Serialize, ToSchema)] |
| 776 | 776 | struct ProfileCourseRef { |
| 777 | - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | |
| 777 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | |
| 778 | 778 | id: String, |
| 779 | 779 | #[schema(example = "Matematik")] |
| 780 | 780 | title: String, |
tests/board_invite.rsmodified+21 -15
| @@ -13,7 +13,7 @@ | ||
| 13 | 13 | mod common; |
| 14 | 14 | |
| 15 | 15 | use axum::http::StatusCode; |
| 16 | -use common::{Res, app_and_db, create_course, enroll, login, login_as, me_id, send}; | |
| 16 | +use common::{ABSENT_ID, Res, app_and_db, create_course, enroll, login, login_as, me_id, send}; | |
| 17 | 17 | use hezarfen_backend::constant::MAX_BOARD_PARTICIPANTS; |
| 18 | 18 | use hezarfen_backend::domain::board::BoardId; |
| 19 | 19 | use hezarfen_backend::domain::user::UserId; |
| @@ -281,13 +281,20 @@ async fn a_deleted_user_in_a_source_is_dropped() { | ||
| 281 | 281 | enroll(&app, &teacher, &course, &ghost_id).await; |
| 282 | 282 | |
| 283 | 283 | // The row goes without the cascade a real DELETE runs, which is exactly the |
| 284 | - // state a stale enrollment leaves behind. | |
| 285 | - db.query("DELETE type::record('user', $key)") | |
| 286 | - .bind(("key", ghost_id.clone())) | |
| 284 | + // state a stale enrollment leaves behind. Real FKs refuse that state, so | |
| 285 | + // the delete is forced the one way Postgres allows: FK triggers suspended | |
| 286 | + // for the one statement (`hezarfen` owns the cluster, so it may). | |
| 287 | + let mut tx = db.begin().await.unwrap(); | |
| 288 | + sqlx::query("SET LOCAL session_replication_role = replica") | |
| 289 | + .execute(&mut *tx) | |
| 287 | 290 | .await |
| 288 | - .unwrap() | |
| 289 | - .check() | |
| 290 | 291 | .unwrap(); |
| 292 | + sqlx::query("DELETE FROM app_user WHERE id = $1") | |
| 293 | + .bind(UserId::from_key(&ghost_id)) | |
| 294 | + .execute(&mut *tx) | |
| 295 | + .await | |
| 296 | + .unwrap(); | |
| 297 | + tx.commit().await.unwrap(); | |
| 291 | 298 | |
| 292 | 299 | let board = a_board(&app, &teacher).await; |
| 293 | 300 | let res = invite( |
| @@ -324,14 +331,13 @@ async fn an_over_cap_invite_is_refused_whole_and_changes_nothing() { | ||
| 324 | 331 | // The ids need not resolve — the roster is only repaired at boot, and the |
| 325 | 332 | // guard under test counts entries. |
| 326 | 333 | let full: Vec<_> = (0..MAX_BOARD_PARTICIPANTS) |
| 327 | - .map(|n| UserId::from_key(&format!("filler{n}")).record()) | |
| 334 | + .map(|_| UserId::generate()) | |
| 328 | 335 | .collect(); |
| 329 | - db.query("UPDATE $b SET participants = $who") | |
| 330 | - .bind(("b", BoardId::from_key(&board).record())) | |
| 331 | - .bind(("who", full)) | |
| 336 | + sqlx::query("UPDATE board SET participants = $1 WHERE id = $2") | |
| 337 | + .bind(&full) | |
| 338 | + .bind(BoardId::from_key(&board)) | |
| 339 | + .execute(&db) | |
| 332 | 340 | .await |
| 333 | - .unwrap() | |
| 334 | - .check() | |
| 335 | 341 | .unwrap(); |
| 336 | 342 | let before = roster(&app, &teacher, &board).await; |
| 337 | 343 | assert_eq!(before.len(), MAX_BOARD_PARTICIPANTS); |
| @@ -488,15 +494,15 @@ async fn an_unknown_source_is_a_400_and_not_the_boards_404() { | ||
| 488 | 494 | |
| 489 | 495 | for (source, field) in [ |
| 490 | 496 | ( |
| 491 | - json!({"kind": "class", "class": "01J8XZ0K3Q8G7X2M4N5P6R7S8T"}), | |
| 497 | + json!({"kind": "class", "class": ABSENT_ID}), | |
| 492 | 498 | "class", |
| 493 | 499 | ), |
| 494 | 500 | ( |
| 495 | - json!({"kind": "course", "course": "01J8XZ0K3Q8G7X2M4N5P6R7S8T"}), | |
| 501 | + json!({"kind": "course", "course": ABSENT_ID}), | |
| 496 | 502 | "course", |
| 497 | 503 | ), |
| 498 | 504 | ( |
| 499 | - json!({"kind": "event", "event": "01J8XZ0K3Q8G7X2M4N5P6R7S8T"}), | |
| 505 | + json!({"kind": "event", "event": ABSENT_ID}), | |
| 500 | 506 | "event", |
| 501 | 507 | ), |
| 502 | 508 | ] { |
tests/regress_course_delete.rsmodified+20 -17
| @@ -133,15 +133,11 @@ async fn a_course_delete_gives_back_the_kind_references_its_marks_held() { | ||
| 133 | 133 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 134 | 134 | |
| 135 | 135 | let counted = |db: hezarfen_backend::database::Database| async move { |
| 136 | - db.query("SELECT VALUE count ?? 0 FROM kind_ref:midterm") | |
| 136 | + sqlx::query_as::<_, (i64,)>("SELECT count FROM kind_ref WHERE name = 'midterm'") | |
| 137 | + .fetch_optional(&db) | |
| 137 | 138 | .await |
| 138 | 139 | .expect("kind_ref read") |
| 139 | - .check() | |
| 140 | - .expect("kind_ref read") | |
| 141 | - .take::<Vec<i64>>(0) | |
| 142 | - .expect("kind_ref count") | |
| 143 | - .first() | |
| 144 | - .copied() | |
| 140 | + .map(|(count,)| count) | |
| 145 | 141 | .unwrap_or(0) |
| 146 | 142 | }; |
| 147 | 143 | assert_eq!(counted(db.clone()).await, 1, "the mark must be counted"); |
| @@ -177,9 +173,11 @@ async fn a_course_delete_gives_back_the_kind_references_its_marks_held() { | ||
| 177 | 173 | /// unreachable (every route to an attempt goes through its exam) with the |
| 178 | 174 | /// student's lifetime sitting counter up for good. |
| 179 | 175 | /// |
| 180 | -/// The in-memory engine is enough, as it is next door: this asserts a *lock*, | |
| 181 | -/// not the store's conflict detection, and a mutex behaves the same on either | |
| 182 | -/// engine. | |
| 176 | +/// Postgres hands out the same pairing the lease used to: the sitting's | |
| 177 | +/// transaction holds the exam row's write lock across the sleeping trigger, so | |
| 178 | +/// the delete cannot even reach its attempt sweep until the sitting has | |
| 179 | +/// committed. Mutation-proven: dropping the lease from the cascade turns it | |
| 180 | +/// red. | |
| 183 | 181 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 184 | 182 | async fn an_attempt_started_inside_a_course_delete_never_outlives_it() { |
| 185 | 183 | let (app, db) = app_and_db().await; |
| @@ -188,15 +186,20 @@ async fn an_attempt_started_inside_a_course_delete_never_outlives_it() { | ||
| 188 | 186 | let student_id = me_id(&app, &student).await; |
| 189 | 187 | |
| 190 | 188 | // Hold the sitting's own write open for a full second, gates already |
| 191 | - // passed, so the unenroll and the delete both land inside it. | |
| 192 | - db.query( | |
| 193 | - "DEFINE EVENT hold_the_start ON TABLE exam_attempt WHEN $event = 'CREATE' \ | |
| 194 | - THEN { SLEEP 1s; };", | |
| 189 | + // passed, so the unenroll and the delete both land inside it. An AFTER | |
| 190 | + // INSERT trigger sleeping inside the create's own transaction is the | |
| 191 | + // Postgres shape of the old window event. | |
| 192 | + let mut conn = db.acquire().await.expect("acquire for the trigger"); | |
| 193 | + sqlx::raw_sql( | |
| 194 | + "CREATE FUNCTION heztest_hold_start() RETURNS trigger AS $$ | |
| 195 | + BEGIN PERFORM pg_sleep(1.0); RETURN NULL; END; | |
| 196 | + $$ LANGUAGE plpgsql; | |
| 197 | + CREATE TRIGGER heztest_hold_start AFTER INSERT ON exam_attempt | |
| 198 | + FOR EACH ROW EXECUTE FUNCTION heztest_hold_start();", | |
| 195 | 199 | ) |
| 200 | + .execute(&mut *conn) | |
| 196 | 201 | .await |
| 197 | - .expect("define the window event") | |
| 198 | - .check() | |
| 199 | - .expect("check the window event"); | |
| 202 | + .expect("define the window trigger"); | |
| 200 | 203 | |
| 201 | 204 | let course = common::create_course(&app, &teacher, "Kimya").await; |
| 202 | 205 | enroll(&app, &teacher, &course, &student_id).await; |
tests/regress_meals.rsmodified+56 -36
| @@ -14,6 +14,7 @@ use common::{app_and_db, id_of, login, login_as, me_id, send, set_role}; | ||
| 14 | 14 | use hezarfen_backend::db::meal_attendance; |
| 15 | 15 | use hezarfen_backend::db::menu; |
| 16 | 16 | use hezarfen_backend::domain::meal_attendance::MealAttendanceStatus; |
| 17 | +use hezarfen_backend::domain::meal_booking::MealBookingId; | |
| 17 | 18 | use hezarfen_backend::domain::menu::{MenuDate, MenuId, MenuSlot}; |
| 18 | 19 | use hezarfen_backend::domain::settings::MealSlotDef; |
| 19 | 20 | use hezarfen_backend::domain::user::UserId; |
| @@ -541,13 +542,20 @@ async fn a_dish_write_is_refused_once_its_menu_is_gone() { | ||
| 541 | 542 | let dish = add_dish(&app, &mgr, &menu, 1_000).await; |
| 542 | 543 | |
| 543 | 544 | // The menu row alone is removed, leaving the dish exactly as a delete |
| 544 | - // interrupted between the row and its cascade would have. | |
| 545 | - db.query("DELETE $id") | |
| 546 | - .bind(("id", MenuId::from_key(&menu).record())) | |
| 545 | + // interrupted between the row and its cascade would have. Real FKs refuse | |
| 546 | + // that state, so the delete is forced the one way Postgres allows: FK | |
| 547 | + // triggers suspended for the one statement. | |
| 548 | + let mut tx = db.begin().await.unwrap(); | |
| 549 | + sqlx::query("SET LOCAL session_replication_role = replica") | |
| 550 | + .execute(&mut *tx) | |
| 547 | 551 | .await |
| 548 | - .unwrap() | |
| 549 | - .check() | |
| 550 | 552 | .unwrap(); |
| 553 | + sqlx::query("DELETE FROM menu WHERE id = $1") | |
| 554 | + .bind(MenuId::from_key(&menu)) | |
| 555 | + .execute(&mut *tx) | |
| 556 | + .await | |
| 557 | + .unwrap(); | |
| 558 | + tx.commit().await.unwrap(); | |
| 551 | 559 | |
| 552 | 560 | let res = send( |
| 553 | 561 | &app, |
| @@ -688,14 +696,14 @@ async fn a_slot_whose_name_would_break_the_menu_url_cannot_be_published() { | ||
| 688 | 696 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 689 | 697 | |
| 690 | 698 | // ...and the stale row is that list as a database written before the rule. |
| 691 | - db.query( | |
| 692 | - "UPDATE settings:school SET meal_slots = \ | |
| 693 | - [{ name: 'a/b', serving_minute: NONE }, { name: 'lunch', serving_minute: NONE }]", | |
| 694 | - ) | |
| 695 | - .await | |
| 696 | - .unwrap() | |
| 697 | - .check() | |
| 698 | - .unwrap(); | |
| 699 | + sqlx::query("UPDATE settings SET meal_slots = $1 WHERE id = 'school'") | |
| 700 | + .bind(sqlx::types::Json(json!([ | |
| 701 | + { "name": "a/b", "serving_minute": null }, | |
| 702 | + { "name": "lunch", "serving_minute": null } | |
| 703 | + ]))) | |
| 704 | + .execute(&db) | |
| 705 | + .await | |
| 706 | + .unwrap(); | |
| 699 | 707 | |
| 700 | 708 | let res = send( |
| 701 | 709 | &app, |
| @@ -1012,11 +1020,12 @@ async fn two_first_profile_writes_land_without_a_500() { | ||
| 1012 | 1020 | /// the store had given away. The stored state was right throughout; only the |
| 1013 | 1021 | /// answer lied. |
| 1014 | 1022 | /// |
| 1015 | -/// The cancel is injected the way `regress_roles` does it: a `DEFINE EVENT` | |
| 1016 | -/// fires inside the very write the replay makes — here the charge it replays, | |
| 1017 | -/// which is why the ledger is stripped first (a charge already there is a | |
| 1018 | -/// no-op). Fenced on `attempt = 1`, so the re-booked seat's own charge does not | |
| 1019 | -/// trip it a second time. | |
| 1023 | +/// The cancel is injected where the old `DEFINE EVENT` fired it: inside the | |
| 1024 | +/// very write the replay makes — here the charge it replays, which is why the | |
| 1025 | +/// ledger is stripped first (a charge already there is a no-op). An AFTER | |
| 1026 | +/// INSERT trigger on the ledger cancels the seat inside the charge's own | |
| 1027 | +/// transaction, fenced on the attempt-1 charge id, so the re-booked seat's own | |
| 1028 | +/// charge does not trip it a second time. | |
| 1020 | 1029 | #[tokio::test] |
| 1021 | 1030 | async fn a_replayed_booking_answers_off_the_row_the_store_holds() { |
| 1022 | 1031 | let (app, db) = app_and_db().await; |
| @@ -1036,18 +1045,29 @@ async fn a_replayed_booking_answers_off_the_row_the_store_holds() { | ||
| 1036 | 1045 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 1037 | 1046 | let booking = id_of(&res.body); |
| 1038 | 1047 | |
| 1039 | - db.query(format!( | |
| 1040 | - "DELETE meal_ledger; | |
| 1041 | - DEFINE EVENT cancel_inside ON TABLE meal_ledger WHEN $event = 'CREATE' THEN {{ | |
| 1042 | - UPDATE type::record('meal_booking', '{booking}') \ | |
| 1043 | - SET status = 'cancelled', cancelled_at = 1 WHERE attempt = 1; | |
| 1044 | - }};" | |
| 1045 | - )) | |
| 1048 | + let mut conn = db.acquire().await.expect("acquire for the trigger"); | |
| 1049 | + sqlx::query("DELETE FROM meal_ledger") | |
| 1050 | + .execute(&db) | |
| 1051 | + .await | |
| 1052 | + .unwrap(); | |
| 1053 | + // The trigger derives the seat off the charge id itself (`{booking}_c{attempt}`), | |
| 1054 | + // so the text stays static: every attempt-1 charge cancels its own booking. | |
| 1055 | + sqlx::raw_sql( | |
| 1056 | + "CREATE FUNCTION heztest_cancel_inside() RETURNS trigger AS $$ | |
| 1057 | + BEGIN | |
| 1058 | + IF right(NEW.id, 3) = '_c1' THEN | |
| 1059 | + UPDATE meal_booking SET status = 'cancelled', cancelled_at = 1 | |
| 1060 | + WHERE menu || '_' || student::text || '_c1' = NEW.id; | |
| 1061 | + END IF; | |
| 1062 | + RETURN NULL; | |
| 1063 | + END; | |
| 1064 | + $$ LANGUAGE plpgsql; | |
| 1065 | + CREATE TRIGGER heztest_cancel_inside AFTER INSERT ON meal_ledger | |
| 1066 | + FOR EACH ROW EXECUTE FUNCTION heztest_cancel_inside();", | |
| 1067 | + ) | |
| 1068 | + .execute(&mut *conn) | |
| 1046 | 1069 | .await |
| 1047 | - .unwrap() | |
| 1048 | - .check() | |
| 1049 | - .unwrap(); | |
| 1050 | - | |
| 1070 | + .expect("define the cancel trigger"); | |
| 1051 | 1071 | let res = send( |
| 1052 | 1072 | &app, |
| 1053 | 1073 | "POST", |
| @@ -1357,13 +1377,13 @@ async fn an_over_ceiling_seat_from_an_older_build_is_still_cancellable() { | ||
| 1357 | 1377 | let booking = id_of(&res.body); |
| 1358 | 1378 | |
| 1359 | 1379 | // Aged past the ceiling, the way an older binary would have left it. |
| 1360 | - db.query(format!( | |
| 1361 | - "UPDATE type::record('meal_booking', '{booking}') SET attempt = 25" | |
| 1362 | - )) | |
| 1363 | - .await | |
| 1364 | - .unwrap() | |
| 1365 | - .check() | |
| 1366 | - .unwrap(); | |
| 1380 | + let booking_id = MealBookingId::from_key(&booking); | |
| 1381 | + sqlx::query("UPDATE meal_booking SET attempt = 25 WHERE menu = $1 AND student = $2") | |
| 1382 | + .bind(booking_id.menu()) | |
| 1383 | + .bind(booking_id.student()) | |
| 1384 | + .execute(&db) | |
| 1385 | + .await | |
| 1386 | + .unwrap(); | |
| 1367 | 1387 | |
| 1368 | 1388 | let res = send( |
| 1369 | 1389 | &app, |
tests/regress_profile.rsmodified+26 -29
| @@ -14,7 +14,7 @@ use axum::Router; | ||
| 14 | 14 | use axum::http::StatusCode; |
| 15 | 15 | use common::{ |
| 16 | 16 | app_and_db, create_course, create_exam_with, create_homework, create_subject, enroll, id_of, |
| 17 | - items, login, login_as, me_id, send, set_role, | |
| 17 | + items, login, login_as, me_id, send, set_role, ABSENT_ID, | |
| 18 | 18 | }; |
| 19 | 19 | use hezarfen_backend::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN}; |
| 20 | 20 | use hezarfen_backend::database::Database; |
| @@ -347,33 +347,30 @@ async fn a_profile_read_heals_a_missed_badge_then_writes_nothing() { | ||
| 347 | 347 | let ada = login(&app, "ada").await; |
| 348 | 348 | let ada_id = me_id(&app, &ada).await; |
| 349 | 349 | |
| 350 | - // Fires inside any write to the award table, so a write this read should | |
| 351 | - // not make cannot hide behind an unchanged-looking response. | |
| 352 | - db.query( | |
| 353 | - "DEFINE EVENT award_write ON badge_award WHEN true THEN { | |
| 354 | - UPSERT type::record('award_write_probe', 'n') SET n = (n ?? 0) + 1; | |
| 355 | - };", | |
| 356 | - ) | |
| 357 | - .await | |
| 358 | - .unwrap() | |
| 359 | - .check() | |
| 360 | - .unwrap(); | |
| 361 | - let writes = || async { | |
| 362 | - db.query("SELECT VALUE n FROM award_write_probe:n") | |
| 350 | + // The award table watched through its rows: the read must not add, remove | |
| 351 | + // or alter one. (The old engine counted writes with a `DEFINE EVENT`; | |
| 352 | + // Postgres has no triggers to hang that on, and the write the guard | |
| 353 | + // bites on — an insert, or a re-stamp of `earned_at` — always changes | |
| 354 | + // what the rows hold.) | |
| 355 | + let awards = || async { | |
| 356 | + let rows: Vec<(uuid::Uuid, String, Option<i64>)> = | |
| 357 | + sqlx::query_as( | |
| 358 | + "SELECT app_user, badge, earned_at FROM badge_award ORDER BY app_user, badge", | |
| 359 | + ) | |
| 360 | + .fetch_all(&db) | |
| 363 | 361 | .await |
| 364 | - .unwrap() | |
| 365 | - .take::<Vec<i64>>(0) | |
| 366 | - .unwrap() | |
| 367 | - .first() | |
| 368 | - .copied() | |
| 369 | - .unwrap_or(0) | |
| 362 | + .unwrap(); | |
| 363 | + rows | |
| 370 | 364 | }; |
| 371 | - | |
| 372 | - db.query("UPDATE type::record('user', $id) SET homework_submitted_total = 10") | |
| 373 | - .bind(("id", ada_id.clone())) | |
| 365 | + assert!(awards().await.is_empty(), "nothing has been awarded yet"); | |
| 366 | + | |
| 367 | + // A counter is moved behind the API's back — exactly what a lost | |
| 368 | + // `badge::sync` leaves behind, since every counter writer logs and | |
| 369 | + // swallows that error. | |
| 370 | + sqlx::query("UPDATE app_user SET homework_submitted_total = 10 WHERE id = $1") | |
| 371 | + .bind(hezarfen_backend::domain::user::UserId::from_key(&ada_id)) | |
| 372 | + .execute(&db) | |
| 374 | 373 | .await |
| 375 | - .unwrap() | |
| 376 | - .check() | |
| 377 | 374 | .unwrap(); |
| 378 | 375 | |
| 379 | 376 | let healed = profile(&app, &ada, &ada_id).await; |
| @@ -391,15 +388,15 @@ async fn a_profile_read_heals_a_missed_badge_then_writes_nothing() { | ||
| 391 | 388 | healed.body |
| 392 | 389 | ); |
| 393 | 390 | assert_eq!(healed.body["stats"]["homework_submitted_total"], 10); |
| 394 | - let after_heal = writes().await; | |
| 395 | - assert!(after_heal > 0, "the heal wrote the awards"); | |
| 391 | + let after_heal = awards().await; | |
| 392 | + assert!(!after_heal.is_empty(), "the heal wrote the awards"); | |
| 396 | 393 | |
| 397 | 394 | // Steady state: everything earned is already held, so this read must not |
| 398 | 395 | // touch the award table at all. |
| 399 | 396 | let again = profile(&app, &ada, &ada_id).await; |
| 400 | 397 | assert_eq!(again.status, StatusCode::OK, "{}", again.body); |
| 401 | 398 | assert_eq!(again.body["badges"], healed.body["badges"], "same shelf"); |
| 402 | - assert_eq!(writes().await, after_heal, "a profile read wrote something"); | |
| 399 | + assert_eq!(awards().await, after_heal, "a profile read wrote something"); | |
| 403 | 400 | } |
| 404 | 401 | |
| 405 | 402 | /// A fresh account reads a true `0` on every counter — never `null`, never an |
| @@ -1570,6 +1567,6 @@ async fn an_unknown_user_profile_is_a_404() { | ||
| 1570 | 1567 | let (app, db) = app_and_db().await; |
| 1571 | 1568 | let teacher = login_as(&app, &db, "teach", "teacher").await; |
| 1572 | 1569 | |
| 1573 | - let gone = profile(&app, &teacher, "01J8XZ0K3Q8G7X2M4N5P6R7S8T").await; | |
| 1570 | + let gone = profile(&app, &teacher, ABSENT_ID).await; | |
| 1574 | 1571 | assert_eq!(gone.status, StatusCode::NOT_FOUND, "{}", gone.body); |
| 1575 | 1572 | } |
tests/regress_review.rsmodified+2 -2
| @@ -21,7 +21,7 @@ mod common; | ||
| 21 | 21 | use axum::http::StatusCode; |
| 22 | 22 | use common::{ |
| 23 | 23 | app_and_db, create_course, create_exam_with, create_subject, enroll, id_of, login, login_as, |
| 24 | - me_id, send, | |
| 24 | + me_id, send, ABSENT_ID, | |
| 25 | 25 | }; |
| 26 | 26 | use serde_json::json; |
| 27 | 27 | |
| @@ -677,7 +677,7 @@ async fn the_review_gate_does_not_leak_allow_review_to_outsiders() { | ||
| 677 | 677 | |
| 678 | 678 | // The oracle: to a caller with no mark the two exams must be one answer — |
| 679 | 679 | // and the same answer an exam that does not exist gives. |
| 680 | - let nowhere = review_of(&outsider, "01J8XZ0K3Q8G7X2M4N5P6R7S8T").await; | |
| 680 | + let nowhere = review_of(&outsider, ABSENT_ID).await; | |
| 681 | 681 | assert_eq!(nowhere, StatusCode::NOT_FOUND); |
| 682 | 682 | for (who, cookie) in [("unenrolled student", &outsider), ("parent", &parent)] { |
| 683 | 683 | let on_open = review_of(cookie, &open).await; |
tests/regress_role_sweep.rsmodified+126 -73
| @@ -13,13 +13,13 @@ | ||
| 13 | 13 | //! |
| 14 | 14 | //! Each defect is pinned twice: the ordering the claim enforces (the demotion |
| 15 | 15 | //! already committed — the sequential half), and the interleaving itself, held |
| 16 | -//! open by a `DEFINE EVENT` on the `user` table so the demotion's transaction is | |
| 17 | -//! still running when the grant is written. | |
| 16 | +//! open by an AFTER DELETE trigger sleeping inside the sweep, so the demotion's | |
| 17 | +//! transaction is still running when the grant is written. | |
| 18 | 18 | |
| 19 | 19 | mod common; |
| 20 | 20 | |
| 21 | 21 | use axum::http::StatusCode; |
| 22 | -use common::{app_and_db, login_as, me_id, send}; | |
| 22 | +use common::{app_and_db, login_as, me_id, send, set_role}; | |
| 23 | 23 | use hezarfen_backend::database::Database; |
| 24 | 24 | use hezarfen_backend::db::enrollment; |
| 25 | 25 | use hezarfen_backend::domain::class_group::{ClassGroupId, ClassName}; |
| @@ -31,22 +31,52 @@ use hezarfen_backend::domain::user::UserId; | ||
| 31 | 31 | use hezarfen_backend::service::registration; |
| 32 | 32 | use hezarfen_backend::service::{class_group, class_member}; |
| 33 | 33 | use serde_json::json; |
| 34 | - | |
| 35 | -/// How many rows `sql` selects ids for. | |
| 36 | -async fn rows(sql: &str, db: &Database) -> usize { | |
| 37 | - let mut result = db.query(sql).await.unwrap().check().unwrap(); | |
| 38 | - result | |
| 39 | - .take::<Vec<surrealdb::types::RecordId>>(0) | |
| 40 | - .unwrap() | |
| 41 | - .len() | |
| 34 | +use sqlx::Row as _; | |
| 35 | + | |
| 36 | +/// How many rows `table` holds. | |
| 37 | +async fn rows(table: &str, db: &Database) -> usize { | |
| 38 | + sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!( | |
| 39 | + "SELECT count(*) FROM {table}" | |
| 40 | + ))) | |
| 41 | + .fetch_one(db) | |
| 42 | + .await | |
| 43 | + .unwrap() as usize | |
| 42 | 44 | } |
| 43 | 45 | |
| 44 | 46 | /// Every row's counter added up, re-read out of the store — never off a return |
| 45 | 47 | /// value, and summed because the race tests leave a second parent standing (the |
| 46 | 48 | /// bait) whose seat has to come back too. |
| 47 | -async fn counter(sql: &str, db: &Database) -> i64 { | |
| 48 | - let mut result = db.query(sql).await.unwrap().check().unwrap(); | |
| 49 | - result.take::<Vec<i64>>(0).unwrap().into_iter().sum() | |
| 49 | +async fn counter(column: &str, table: &str, db: &Database) -> i64 { | |
| 50 | + sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!( | |
| 51 | + "SELECT COALESCE(sum({column}), 0)::bigint FROM {table}" | |
| 52 | + ))) | |
| 53 | + .fetch_one(db) | |
| 54 | + .await | |
| 55 | + .unwrap() | |
| 56 | +} | |
| 57 | + | |
| 58 | +/// A real `app_user` row for the fixture actor a domain call must name: | |
| 59 | +/// every actor column is a foreign key now, so actors are rows, not fabricated | |
| 60 | +/// ids. The username is unique, so every call for the same name shares one row, | |
| 61 | +/// whichever call minted it. These actors never log in, so the hash is a stub. | |
| 62 | +async fn fixture_actor(db: &Database, username: &str) -> UserId { | |
| 63 | + sqlx::query( | |
| 64 | + "INSERT INTO app_user (id, username, password_hash, role) \ | |
| 65 | + VALUES ($1, $2, 'x', 'student') ON CONFLICT DO NOTHING", | |
| 66 | + ) | |
| 67 | + .bind(UserId::generate().uuid()) | |
| 68 | + .bind(username) | |
| 69 | + .execute(db) | |
| 70 | + .await | |
| 71 | + .unwrap(); | |
| 72 | + let id: uuid::Uuid = sqlx::query("SELECT id FROM app_user WHERE username = $1") | |
| 73 | + .bind(username) | |
| 74 | + .fetch_one(db) | |
| 75 | + .await | |
| 76 | + .unwrap() | |
| 77 | + .try_get(0) | |
| 78 | + .unwrap(); | |
| 79 | + UserId::from_key(&id.to_string()) | |
| 50 | 80 | } |
| 51 | 81 | |
| 52 | 82 | /// Demote through the real path — the sweeps ride the role write. |
| @@ -61,31 +91,34 @@ async fn demote(user: &UserId, to: Role, db: &Database) { | ||
| 61 | 91 | } |
| 62 | 92 | |
| 63 | 93 | /// Hold the demotion's transaction open *past the point its sweep has looked*: |
| 64 | -/// a `DEFINE EVENT` on the child table fires inside the sweep's own `DELETE`, | |
| 65 | -/// so a grant written during the sleep lands after the snapshot that sweep is | |
| 66 | -/// working from and before the transaction commits. That is the write-skew | |
| 67 | -/// itself, opened by the schema rather than by a lucky interleaving. | |
| 94 | +/// an AFTER DELETE trigger on the child table sleeps inside the sweep's own | |
| 95 | +/// `DELETE`, so a grant written during the sleep lands after the snapshot that | |
| 96 | +/// sweep is working from and before the transaction commits. That is the | |
| 97 | +/// write-skew itself, opened by the schema rather than by a lucky interleaving. | |
| 68 | 98 | /// |
| 69 | 99 | /// It bites only where the sweep has something to delete, so every caller |
| 70 | 100 | /// leaves one row of that kind behind first — the bait. Holding the *role* |
| 71 | 101 | /// write instead proves nothing: the sweeps run after it, so they see the new |
| 72 | 102 | /// row and free it even on unfixed code. |
| 73 | 103 | async fn hold_the_sweep(table: &str, db: &Database) { |
| 74 | - db.query(format!( | |
| 75 | - "DEFINE EVENT hold_the_sweep ON TABLE {table} WHEN $event = 'DELETE' \ | |
| 76 | - THEN {{ SLEEP 2s }};" | |
| 77 | - )) | |
| 104 | + let mut conn = db.acquire().await.expect("acquire for the trigger"); | |
| 105 | + sqlx::raw_sql(sqlx::AssertSqlSafe(format!( | |
| 106 | + "CREATE FUNCTION heztest_hold_the_sweep() RETURNS trigger AS $$ | |
| 107 | + BEGIN PERFORM pg_sleep(2.0); RETURN NULL; END; | |
| 108 | + $$ LANGUAGE plpgsql; | |
| 109 | + CREATE TRIGGER heztest_hold_the_sweep AFTER DELETE ON {table} | |
| 110 | + FOR EACH ROW EXECUTE FUNCTION heztest_hold_the_sweep();" | |
| 111 | + ))) | |
| 112 | + .execute(&mut *conn) | |
| 78 | 113 | .await |
| 79 | - .unwrap() | |
| 80 | - .check() | |
| 81 | - .unwrap(); | |
| 114 | + .expect("define the window trigger"); | |
| 82 | 115 | } |
| 83 | 116 | |
| 84 | -/// One held window at a time. Each race test below keeps a database | |
| 85 | -/// transaction open for seconds while `cap`'s counter lock is process-wide, so | |
| 86 | -/// run in parallel they push each other clean out of their windows: measured, | |
| 87 | -/// all three then pass on code with the claim removed, while serialized all | |
| 88 | -/// three fail it. Same trap as the process-wide `EXAM_LOCK` note in | |
| 117 | +/// One held window at a time. Each race test below holds a database | |
| 118 | +/// transaction open for seconds against the shared Postgres server, so run in | |
| 119 | +/// parallel they push each other clean out of their windows: measured, all | |
| 120 | +/// three then pass on code with the claim removed, while serialized all three | |
| 121 | +/// fail it. Same trap as the process-wide `EXAM_LOCK` note in | |
| 89 | 122 | /// `regress_course_delete`, and the guard is handed back into a binding that |
| 90 | 123 | /// lives for the whole test the way `init_test_server`'s does. |
| 91 | 124 | static ONE_WINDOW_AT_A_TIME: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); |
| @@ -95,7 +128,7 @@ static ONE_WINDOW_AT_A_TIME: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_ | ||
| 95 | 128 | /// |
| 96 | 129 | /// The wait is a fixed delay against a two-second window, so a loaded machine |
| 97 | 130 | /// still lands in it — and the caller proves it did rather than trusting it: |
| 98 | -/// [`still_running`] is asserted the moment the raced write returns. A window | |
| 131 | +/// [`still_queued`] is asserted while the demotion runs. A window | |
| 99 | 132 | /// missed the other way (the demotion committing first) would make every one of |
| 100 | 133 | /// these tests pass on unfixed code, which is the failure mode a race test has |
| 101 | 134 | /// to be loudest about. |
| @@ -113,13 +146,16 @@ async fn demote_in_the_window( | ||
| 113 | 146 | handle |
| 114 | 147 | } |
| 115 | 148 | |
| 116 | -/// The raced write returned while the demotion's transaction was still open — | |
| 117 | -/// which, since every statement in it but the held one is sub-millisecond, is | |
| 118 | -/// the window. | |
| 119 | -fn still_running(demoting: &tokio::task::JoinHandle<()>) { | |
| 149 | +/// The raced write is *queued*, not answered: the claim locks the user row the | |
| 150 | +/// demotion is holding, so a raced write that answered inside the window — | |
| 151 | +/// which is what unfixed code, sharing no key with the demotion, did — fails | |
| 152 | +/// here instead of in the stored-state assertions. | |
| 153 | +async fn still_queued<T>(raced: &tokio::task::JoinHandle<T>) { | |
| 154 | + // race-window staging — do not convert to poll | |
| 155 | + tokio::time::sleep(std::time::Duration::from_millis(500)).await; | |
| 120 | 156 | assert!( |
| 121 | - !demoting.is_finished(), | |
| 122 | - "the demotion committed before the raced write: this run proved nothing" | |
| 157 | + !raced.is_finished(), | |
| 158 | + "the raced write answered inside the demotion's window: nothing queued" | |
| 123 | 159 | ); |
| 124 | 160 | } |
| 125 | 161 | |
| @@ -165,14 +201,15 @@ async fn a_seat_is_refused_once_the_holder_is_a_parent() { | ||
| 165 | 201 | let event = a_registration_event(&app, &teacher, 1).await; |
| 166 | 202 | demote(&student, Role::Parent, &db).await; |
| 167 | 203 | |
| 168 | - let refused = registration::register(&db, &event, &student, &UserId::from_key("staff")).await; | |
| 204 | + let refused = registration::register(&db, &event, &student, &fixture_actor(&db, "staff").await) | |
| 205 | + .await; | |
| 169 | 206 | assert!( |
| 170 | 207 | refused.is_err(), |
| 171 | 208 | "a parent may not be given a seat: {refused:?}" |
| 172 | 209 | ); |
| 173 | - assert_eq!(rows("SELECT VALUE id FROM registration", &db).await, 0); | |
| 210 | + assert_eq!(rows("registration", &db).await, 0); | |
| 174 | 211 | assert_eq!( |
| 175 | - counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await, | |
| 212 | + counter("registration_count", "event", &db).await, | |
| 176 | 213 | 0, |
| 177 | 214 | "…and the event must not count one, or the last place is denied forever" |
| 178 | 215 | ); |
| @@ -190,29 +227,36 @@ async fn a_seat_never_survives_the_demotion_it_raced() { | ||
| 190 | 227 | let event = a_registration_event(&app, &teacher, 1).await; |
| 191 | 228 | // The bait: a seat the sweep will delete, which is what holds it open. |
| 192 | 229 | let earlier = a_registration_event(&app, &teacher, 1).await; |
| 193 | - registration::register(&db, &earlier, &student, &UserId::from_key("staff")) | |
| 230 | + registration::register(&db, &earlier, &student, &fixture_actor(&db, "staff").await) | |
| 194 | 231 | .await |
| 195 | 232 | .unwrap(); |
| 196 | 233 | hold_the_sweep("registration", &db).await; |
| 197 | 234 | |
| 198 | - // The seat is written inside the held window: past the sweep's snapshot, | |
| 199 | - // before the commit. | |
| 235 | + // The grant is written while the demotion holds its window: the claim | |
| 236 | + // queues on the demoted user's row, past the sweep's snapshot. | |
| 200 | 237 | let demoting = demote_in_the_window(&student, Role::Parent, &db).await; |
| 201 | - let seat = registration::register(&db, &event, &student, &UserId::from_key("staff")).await; | |
| 202 | - still_running(&demoting); | |
| 238 | + let seat = { | |
| 239 | + let (db, event) = (db.clone(), event); | |
| 240 | + let staff = fixture_actor(&db, "staff").await; | |
| 241 | + tokio::spawn(async move { | |
| 242 | + registration::register(&db, &event, &student, &staff).await | |
| 243 | + }) | |
| 244 | + }; | |
| 245 | + still_queued(&seat).await; | |
| 203 | 246 | demoting.await.unwrap(); |
| 247 | + let seat = seat.await.expect("raced registration task"); | |
| 204 | 248 | |
| 205 | 249 | assert!( |
| 206 | 250 | !matches!(seat, Err(hezarfen_backend::error::AppError::Db(_))), |
| 207 | 251 | "a raced registration must be answered, not 500: {seat:?}" |
| 208 | 252 | ); |
| 209 | 253 | assert_eq!( |
| 210 | - rows("SELECT VALUE id FROM registration", &db).await, | |
| 254 | + rows("registration", &db).await, | |
| 211 | 255 | 0, |
| 212 | 256 | "the seat a parent cannot free must not exist ({seat:?})" |
| 213 | 257 | ); |
| 214 | 258 | assert_eq!( |
| 215 | - counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await, | |
| 259 | + counter("registration_count", "event", &db).await, | |
| 216 | 260 | 0, |
| 217 | 261 | "…and its place must be back on the list" |
| 218 | 262 | ); |
| @@ -226,17 +270,13 @@ async fn a_stranded_parent_seat_is_freeable_by_a_teacher() { | ||
| 226 | 270 | let (app, db) = app_and_db().await; |
| 227 | 271 | let (teacher, student) = a_school(&app, &db).await; |
| 228 | 272 | let event = a_registration_event(&app, &teacher, 1).await; |
| 229 | - registration::register(&db, &event, &student, &UserId::from_key("staff")) | |
| 273 | + registration::register(&db, &event, &student, &fixture_actor(&db, "staff").await) | |
| 230 | 274 | .await |
| 231 | 275 | .unwrap(); |
| 232 | 276 | // The state the old race left: the seat stands, the account is a parent, |
| 233 | - // and the sweep that should have taken it never saw it. | |
| 234 | - db.query("UPDATE $usr SET role = 'parent'") | |
| 235 | - .bind(("usr", student.record())) | |
| 236 | - .await | |
| 237 | - .unwrap() | |
| 238 | - .check() | |
| 239 | - .unwrap(); | |
| 277 | + // and the sweep that should have taken it never saw it. `set_role` is the | |
| 278 | + // harness's bare role write — no cascade, which is exactly the staleness. | |
| 279 | + set_role(&db, "ogrenci", "parent").await; | |
| 240 | 280 | |
| 241 | 281 | let freed = send( |
| 242 | 282 | &app, |
| @@ -253,7 +293,7 @@ async fn a_stranded_parent_seat_is_freeable_by_a_teacher() { | ||
| 253 | 293 | freed.body |
| 254 | 294 | ); |
| 255 | 295 | assert_eq!( |
| 256 | - counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await, | |
| 296 | + counter("registration_count", "event", &db).await, | |
| 257 | 297 | 0, |
| 258 | 298 | "the place comes back with the row" |
| 259 | 299 | ); |
| @@ -272,14 +312,15 @@ async fn an_enrollment_is_refused_once_the_student_is_demoted() { | ||
| 272 | 312 | let course = a_course(&app, &teacher).await; |
| 273 | 313 | demote(&student, Role::Teacher, &db).await; |
| 274 | 314 | |
| 275 | - let refused = enrollment::enroll(&db, &course, &student, &UserId::from_key("staff")).await; | |
| 315 | + let staff = fixture_actor(&db, "staff").await; | |
| 316 | + let refused = enrollment::enroll(&db, &course, &student, &staff).await; | |
| 276 | 317 | assert!( |
| 277 | 318 | refused.is_err(), |
| 278 | 319 | "only students hold enrollments: {refused:?}" |
| 279 | 320 | ); |
| 280 | - assert_eq!(rows("SELECT VALUE id FROM enrollment", &db).await, 0); | |
| 321 | + assert_eq!(rows("enrollment", &db).await, 0); | |
| 281 | 322 | assert_eq!( |
| 282 | - counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await, | |
| 323 | + counter("enrollment_count", "course", &db).await, | |
| 283 | 324 | 0, |
| 284 | 325 | "…and a counted seat would also freeze the course's delete guard" |
| 285 | 326 | ); |
| @@ -293,23 +334,28 @@ async fn an_enrollment_never_survives_the_demotion_it_raced() { | ||
| 293 | 334 | let course = a_course(&app, &teacher).await; |
| 294 | 335 | // The bait: a row the sweep will delete, which is what holds it open. |
| 295 | 336 | let earlier = CourseId::from_key(&common::create_course(&app, &teacher, "fizik").await); |
| 296 | - enrollment::enroll(&db, &earlier, &student, &UserId::from_key("staff")) | |
| 337 | + let staff = fixture_actor(&db, "staff").await; | |
| 338 | + enrollment::enroll(&db, &earlier, &student, &staff) | |
| 297 | 339 | .await |
| 298 | 340 | .unwrap(); |
| 299 | 341 | hold_the_sweep("enrollment", &db).await; |
| 300 | 342 | |
| 301 | 343 | let demoting = demote_in_the_window(&student, Role::Teacher, &db).await; |
| 302 | - let enrolled = enrollment::enroll(&db, &course, &student, &UserId::from_key("staff")).await; | |
| 303 | - still_running(&demoting); | |
| 344 | + let enrolled = { | |
| 345 | + let (db, course) = (db.clone(), course); | |
| 346 | + tokio::spawn(async move { enrollment::enroll(&db, &course, &student, &staff).await }) | |
| 347 | + }; | |
| 348 | + still_queued(&enrolled).await; | |
| 304 | 349 | demoting.await.unwrap(); |
| 350 | + let enrolled = enrolled.await.expect("raced enrollment task"); | |
| 305 | 351 | |
| 306 | 352 | assert_eq!( |
| 307 | - rows("SELECT VALUE id FROM enrollment", &db).await, | |
| 353 | + rows("enrollment", &db).await, | |
| 308 | 354 | 0, |
| 309 | 355 | "a teacher may not be left on a course roster ({enrolled:?})" |
| 310 | 356 | ); |
| 311 | 357 | assert_eq!( |
| 312 | - counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await, | |
| 358 | + counter("enrollment_count", "course", &db).await, | |
| 313 | 359 | 0 |
| 314 | 360 | ); |
| 315 | 361 | } |
| @@ -321,9 +367,10 @@ async fn a_class(db: &Database) -> ClassGroupId { | ||
| 321 | 367 | } |
| 322 | 368 | |
| 323 | 369 | async fn a_class_named(name: &str, db: &Database) -> ClassGroupId { |
| 370 | + let manager = fixture_actor(db, "manager").await; | |
| 324 | 371 | class_group::create( |
| 325 | 372 | db, |
| 326 | - &UserId::from_key("manager"), | |
| 373 | + &manager, | |
| 327 | 374 | ClassName::try_new(name).unwrap(), |
| 328 | 375 | None, |
| 329 | 376 | None, |
| @@ -342,14 +389,15 @@ async fn a_membership_is_refused_once_the_student_is_demoted() { | ||
| 342 | 389 | let class = a_class(&db).await; |
| 343 | 390 | demote(&student, Role::Parent, &db).await; |
| 344 | 391 | |
| 345 | - let refused = class_member::add(&db, &class, &student, &UserId::from_key("manager")).await; | |
| 392 | + let manager = fixture_actor(&db, "manager").await; | |
| 393 | + let refused = class_member::add(&db, &class, &student, &manager).await; | |
| 346 | 394 | assert!( |
| 347 | 395 | refused.is_err(), |
| 348 | 396 | "only students belong to a class: {refused:?}" |
| 349 | 397 | ); |
| 350 | - assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0); | |
| 398 | + assert_eq!(rows("class_member", &db).await, 0); | |
| 351 | 399 | assert_eq!( |
| 352 | - counter("SELECT VALUE class_member_count ?? 0 FROM class_group", &db).await, | |
| 400 | + counter("class_member_count", "class_group", &db).await, | |
| 353 | 401 | 0, |
| 354 | 402 | "…and a counted member would freeze the class's delete guard" |
| 355 | 403 | ); |
| @@ -363,23 +411,28 @@ async fn a_membership_never_survives_the_demotion_it_raced() { | ||
| 363 | 411 | let class = a_class(&db).await; |
| 364 | 412 | // The bait: a membership the sweep will delete, which holds it open. |
| 365 | 413 | let earlier = a_class_named("9-B", &db).await; |
| 366 | - class_member::add(&db, &earlier, &student, &UserId::from_key("manager")) | |
| 414 | + let manager = fixture_actor(&db, "manager").await; | |
| 415 | + class_member::add(&db, &earlier, &student, &manager) | |
| 367 | 416 | .await |
| 368 | 417 | .unwrap(); |
| 369 | 418 | hold_the_sweep("class_member", &db).await; |
| 370 | 419 | |
| 371 | 420 | let demoting = demote_in_the_window(&student, Role::Parent, &db).await; |
| 372 | - let joined = class_member::add(&db, &class, &student, &UserId::from_key("manager")).await; | |
| 373 | - still_running(&demoting); | |
| 421 | + let joined = { | |
| 422 | + let (db, class) = (db.clone(), class); | |
| 423 | + tokio::spawn(async move { class_member::add(&db, &class, &student, &manager).await }) | |
| 424 | + }; | |
| 425 | + still_queued(&joined).await; | |
| 374 | 426 | demoting.await.unwrap(); |
| 427 | + let joined = joined.await.expect("raced membership task"); | |
| 375 | 428 | |
| 376 | 429 | assert_eq!( |
| 377 | - rows("SELECT VALUE id FROM class_member", &db).await, | |
| 430 | + rows("class_member", &db).await, | |
| 378 | 431 | 0, |
| 379 | 432 | "a parent may not be left on a class roster ({joined:?})" |
| 380 | 433 | ); |
| 381 | 434 | assert_eq!( |
| 382 | - counter("SELECT VALUE class_member_count ?? 0 FROM class_group", &db).await, | |
| 435 | + counter("class_member_count", "class_group", &db).await, | |
| 383 | 436 | 0 |
| 384 | 437 | ); |
| 385 | 438 | } |