diff --git a/src/ai/server.rs b/src/ai/server.rs index 26cbcfe..fbc4f27 100644 --- a/src/ai/server.rs +++ b/src/ai/server.rs @@ -1077,9 +1077,7 @@ mod tests { async fn armed(router: axum::Router) -> ApiHandle { ApiHandle { router, - tenants: crate::database::init_mem_tenants() - .await - .expect("in-memory deployment"), + tenants: crate::database::init_test_tenants().await, files_path: std::env::temp_dir(), } } diff --git a/src/db/answer_image.rs b/src/db/answer_image.rs index 5cfa869..7eca622 100644 --- a/src/db/answer_image.rs +++ b/src/db/answer_image.rs @@ -240,12 +240,12 @@ mod tests { } fn student() -> UserId { - UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA") + UserId::from_key("019732e3-7b00-7000-8000-00000000a11a") } #[tokio::test] async fn upsert_replaces_within_a_sitting_but_not_across_them() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let exam = exam_row(&db).await; let question = ExamQuestionId::generate(); let user = student(); @@ -287,7 +287,7 @@ mod tests { ); // Another student's drawing for the same question/sitting is its own row. - let other = UserId::from_key("01TESTSTUDENTBBBBBBBBBBBBB"); + let other = UserId::from_key("019732e3-7b00-7000-8000-00000000b22b"); upsert(&db, AnswerImage::new(&exam, &question, &other, 1, png(), 7)) .await .unwrap(); @@ -297,7 +297,7 @@ mod tests { #[tokio::test] async fn listing_scopes_by_exam_and_user() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let exam_a = exam_row(&db).await; let exam_b = exam_row(&db).await; let user = student(); diff --git a/src/db/attendance.rs b/src/db/attendance.rs index d42793a..4f406f0 100644 --- a/src/db/attendance.rs +++ b/src/db/attendance.rs @@ -130,59 +130,77 @@ mod tests { use crate::domain::settings::Settings; /// The session twin's race, one table over - /// ([`crate::db::session_attendance::mark`]): a - /// `DEFINE EVENT` on `event` fires inside the delete's own transaction, and - /// the event's delete sweeps its attendance rows before removing the row, so - /// the `SLEEP` lands exactly between the sweep and the commit — the window - /// where a bare upsert wrote a mark nothing would ever sweep again. - /// - /// Real server, and `#[ignore]`d for it: the subject is the store's - /// conflict detection, which `init_mem`'s embedded engine does not have — - /// it commits both writes and answers `Ok` to each, so this passes there on - /// broken code. Mutation-tested: turning the claim back into a read - /// (`SELECT VALUE id FROM $ev`) turns it red. + /// ([`crate::db::session_attendance::mark`]): the event's delete sweeps its + /// attendance rows and removes the row in one transaction, and a mark that + /// wrote into the gap was a bare upsert nothing would ever sweep again. + /// The mark now writes the event row too (its seats counter), so the two + /// transactions touch one row and Postgres refuses one of them; the barrier + /// releases both sides together so every interleaving gets its chance. + /// Mutation-tested: turning the claim back into a read turns it red. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn a_mark_written_inside_a_delete_never_outlives_the_event() { - use crate::domain::event::{EventAudience, EventDescription, EventTitle}; - let (db, _serialized) = crate::database::init_test_server("event_attendance_race").await; - db.query( - "DEFINE EVENT hold_the_window ON TABLE event WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .unwrap() - .check() - .unwrap(); + use crate::domain::event::{ + EventAudience, EventAudienceKind, EventDescription, EventTitle, + }; + // A real `app_user` row: markers, students and event creators are + // foreign keys now. + async fn a_person(db: &Database, label: &str) -> UserId { + let user = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, $2, 'x', 'teacher')", + ) + .bind(user.uuid()) + .bind(format!("{label}-{}", &user.key()[..8])) + .execute(db) + .await + .unwrap(); + user + } + + let (db, _leases) = crate::database::init_test_db().await; let allowed: Vec = Settings::defaults().get_attendance_statuses().to_vec(); - let marker = UserId::from_key("t"); + let marker = a_person(&db, "marker").await; let (mut swept, mut orphans) = (0, 0); - for round in 0..4 { + for round in 0..8 { let event = crate::db::event::create( &db, &marker, EventTitle::try_new("gezi").unwrap(), EventDescription::try_new("").unwrap(), - EventAudience::School, + EventAudience { + kind: EventAudienceKind::School, + role: None, + course: None, + class: None, + capacity: None, + }, None, None, ) .await .unwrap(); let id = event.get_id().clone(); + + // Delete and mark released together: both write the event row, so + // Postgres serializes them and refuses whichever lost. + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let drop_it = { - let db = db.clone(); - tokio::spawn(async move { crate::db::event::delete(&db, event).await }) + let (db, gate, event) = (db.clone(), gate.clone(), event); + tokio::spawn(async move { + gate.wait().await; + crate::db::event::delete(&db, event).await + }) }; - // The mark starts inside the held window: the sweep has run and the - // event row is gone but uncommitted. - tokio::time::sleep(std::time::Duration::from_millis(300)).await; let marked = { - let (db, id, marker) = (db.clone(), id.clone(), marker.clone()); - let student = UserId::from_key(&format!("s{round}")); + let (db, id, marker, gate) = (db.clone(), id.clone(), marker.clone(), gate); + let student = a_person(&db, "student").await; let status = AttendanceStatus::try_new("present", &allowed).unwrap(); - tokio::spawn(async move { mark(&db, &id, &student, status, &marker).await }) + tokio::spawn(async move { + gate.wait().await; + mark(&db, &id, &student, status, &marker).await + }) }; let (drop_it, marked) = (drop_it.await.unwrap(), marked.await.unwrap()); assert!( @@ -198,7 +216,7 @@ mod tests { panic!("round {round}: the delete reported success but the event is still there"); } } - eprintln!("Event::delete raced by a mark: {swept}/4 rounds deleted the event"); + eprintln!("Event::delete raced by a mark: {swept}/8 rounds deleted the event"); assert!( swept > 0, "no round ever deleted the event, so the window was never reached" diff --git a/src/db/badge.rs b/src/db/badge.rs index 2eb590c..4bcf40c 100644 --- a/src/db/badge.rs +++ b/src/db/badge.rs @@ -111,7 +111,7 @@ pub async fn sync(db: &Database, user: &UserId) -> Result<(), AppError> { SET earned_at = badge_award.earned_at \ WHERE badge_award.earned_at IS NULL" ))) - .bind(user.uuid()) +.bind(user.uuid()) .bind(badge) .bind(now) .execute(db) @@ -124,7 +124,7 @@ pub async fn sync(db: &Database, user: &UserId) -> Result<(), AppError> { mod tests { use super::*; use crate::constant::BADGE_AWARD_TABLE; - use crate::database::init_mem; + use crate::database::init_test_db; use crate::domain::user::{Password, Username}; async fn a_user(username: &str, db: &Database) -> crate::domain::user::User { @@ -142,9 +142,9 @@ mod tests { } async fn count_awards(db: &Database, user: &UserId) -> i64 { - let (count,): (i64,) = sqlx::query_as(&format!( + let (count,): (i64,) = sqlx::query_as(sqlx::AssertSqlSafe(format!( "SELECT count(*) FROM {BADGE_AWARD_TABLE} WHERE app_user = $1" - )) + ))) .bind(user.uuid()) .fetch_one(db) .await @@ -161,7 +161,7 @@ mod tests { #[tokio::test] async fn load_defaults_every_counter_to_zero() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let user = a_user("badge-sifir", &db).await; let stats = load(&db, user.get_id()).await.unwrap(); @@ -177,12 +177,12 @@ mod tests { #[tokio::test] async fn sync_is_idempotent_and_keeps_the_first_stamp() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let user = a_user("badge-ali", &db).await; // Seed two submitted homeworks: enough for the first badge tier. sqlx::query("UPDATE app_user SET homework_submitted_total = 2 WHERE id = $1") - .bind(user.uuid()) + .bind(user.get_id().uuid()) .execute(&db) .await .unwrap(); @@ -195,7 +195,7 @@ mod tests { // A second sync with the counter moved *further* writes nothing: the // stamps are from the first crossing, and no row is duplicated. sqlx::query("UPDATE app_user SET homework_submitted_total = 5 WHERE id = $1") - .bind(user.uuid()) + .bind(user.get_id().uuid()) .execute(&db) .await .unwrap(); @@ -218,7 +218,7 @@ mod tests { #[tokio::test] async fn sync_writes_nothing_for_a_earned_nothing() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let user = a_user("badge-bos", &db).await; sync(&db, user.get_id()).await.unwrap(); assert_eq!( diff --git a/src/db/bank_question.rs b/src/db/bank_question.rs index 78a6d6d..a5f7885 100644 --- a/src/db/bank_question.rs +++ b/src/db/bank_question.rs @@ -414,33 +414,33 @@ mod tests { .unwrap() } - /// A row stored before `visibility` existed has no such key — it must decode - /// as `private`, the safe value. Asserted on the decoder itself, so no - /// schema DEFAULT can paper over it: a `school` default here would publish - /// every pre-existing template in the school at once. + /// A row without a visibility of its own must decode as `private`, the + /// safe value. The old engine could store a row with the field absent; + /// Postgres carries the same guarantee in the schema instead — the column + /// is `NOT NULL DEFAULT 'private'`, so a `school` default here would + /// publish every pre-existing template in the school at once. The insert + /// below is written exactly as a pre-visibility row arrives: no column. #[tokio::test] async fn a_row_without_the_field_decodes_private() { - use surrealdb::types::Value; - - let db = crate::database::init_mem().await.unwrap(); - let question = create( - &db, - UserId::generate(), - SubjectId::generate(), - QuestionText::try_new("q").unwrap(), - QuestionPoints::try_new(1).unwrap(), - spec(), + let (db, _leases) = crate::database::init_test_db().await; + let owner = UserId::generate(); + sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, 'q', 'x')") + .bind(owner.uuid()) + .execute(&db) + .await + .unwrap(); + let id = BankQuestionId::generate(); + sqlx::query( + "INSERT INTO bank_question (id, owner, text, kind, points, created_at) \ + VALUES ($1, $2, 'q', 'multiple_choice', 1, 0)", ) + .bind(id.uuid()) + .bind(owner.uuid()) + .execute(&db) .await .unwrap(); - assert_eq!(question.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE); - let mut stored = question.into_value(); - let Value::Object(map) = &mut stored else { - panic!("a bank question serializes to an object"); - }; - assert!(map.remove("visibility").is_some()); - let old = BankQuestion::from_value(stored).unwrap(); + let old = read(&db, &id).await.unwrap().expect("the row is there"); assert_eq!(old.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE); assert!(!old.get_visibility().is_school()); } @@ -449,7 +449,7 @@ mod tests { /// page can contain — never someone else's private templates. #[tokio::test] async fn list_hides_private_templates_from_others() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let owner = UserId::generate(); let other = UserId::generate(); let private = create( @@ -516,7 +516,7 @@ mod tests { /// still answer `Ok`. #[tokio::test] async fn a_merge_built_on_a_stale_snapshot_is_refused() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let owner = UserId::generate(); let stale = create( &db, @@ -564,7 +564,7 @@ mod tests { /// row, and `private` means "my own drafts" for everyone but an admin. #[tokio::test] async fn visibility_filter_narrows_never_widens() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let owner = UserId::generate(); let other = UserId::generate(); let mine = |text: &str| { @@ -638,14 +638,10 @@ mod tests { /// "0"), and questions authored by hand never counted. #[tokio::test] async fn usage_counts_tallies_a_page_in_one_statement() { - // One statement, so a page costs one round trip — a `;` here would mean - // the per-row N+1 crept back in. - assert!( - !USAGE_COUNTS_SQL.contains(';'), - "usage_counts must be one statement" - ); - - let db = crate::database::init_mem().await.unwrap(); + // One statement, so a page costs one round trip: the tally is a single + // static `query!` (a `GROUP BY` with no loop around it), which the + // compiler now checks the way the old constant asserted. + let (db, _leases) = crate::database::init_test_db().await; let owner = UserId::generate(); let template = |text: &str| { create( @@ -712,10 +708,10 @@ mod tests { let ids = [used_twice.get_id(), used_once.get_id(), unused.get_id()]; let counts = usage_counts(&db, &ids).await.unwrap(); - assert_eq!(counts.get(used_twice.get_id().key()).copied(), Some(2)); - assert_eq!(counts.get(used_once.get_id().key()).copied(), Some(1)); + assert_eq!(counts.get(&used_twice.get_id().key()).copied(), Some(2)); + assert_eq!(counts.get(&used_once.get_id().key()).copied(), Some(1)); assert_eq!( - counts.get(unused.get_id().key()), + counts.get(&unused.get_id().key()), None, "unused stays absent" ); @@ -724,14 +720,14 @@ mod tests { // A template outside the page is never counted into it. let narrow = usage_counts(&db, &[used_once.get_id()]).await.unwrap(); assert_eq!(narrow.len(), 1); - assert_eq!(narrow.get(used_once.get_id().key()).copied(), Some(1)); + assert_eq!(narrow.get(&used_once.get_id().key()).copied(), Some(1)); // An empty page asks nothing at all. assert!(usage_counts(&db, &[]).await.unwrap().is_empty()); } #[tokio::test] async fn list_is_school_wide() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; for _ in 0..2 { create( &db, @@ -755,7 +751,7 @@ mod tests { /// The window is SQL, not an in-memory slice, and `total` ignores it. #[tokio::test] async fn list_pages_newest_first_and_filters_text() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let owner = UserId::generate(); for i in 0..5 { create( @@ -806,7 +802,7 @@ mod tests { /// Turkish `İ`/`ı` must not split the search into two disjoint halves. #[tokio::test] async fn list_text_filter_folds_turkish_casing() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; create( &db, UserId::generate(), diff --git a/src/db/bank_question_image.rs b/src/db/bank_question_image.rs index 87b5426..377e108 100644 --- a/src/db/bank_question_image.rs +++ b/src/db/bank_question_image.rs @@ -232,7 +232,7 @@ mod tests { #[tokio::test] async fn upsert_replaces_per_slot() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let question = a_template(&db).await; let (first, retired) = upsert(&db, BankQuestionImage::new(&question, None, png(), 3)) @@ -255,7 +255,7 @@ mod tests { /// picture, and only a removed option's picture goes. #[tokio::test] async fn only_the_dropped_options_lose_their_pictures() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let question = a_template(&db).await; let ids = choice_ids(); upsert(&db, BankQuestionImage::new(&question, None, png(), 1)) @@ -278,7 +278,7 @@ mod tests { #[tokio::test] async fn an_empty_keep_set_clears_every_option_picture() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let question = a_template(&db).await; let ids = choice_ids(); upsert(&db, BankQuestionImage::new(&question, None, png(), 1)) diff --git a/src/db/board.rs b/src/db/board.rs index b0b0735..ddd9852 100644 --- a/src/db/board.rs +++ b/src/db/board.rs @@ -331,7 +331,7 @@ mod tests { /// the meantime is a 404 — not a silent success. #[tokio::test] async fn field_scoped_writes_return_the_row_and_a_gone_board_refuses() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let creator = UserId::generate(); let board = create( &db, @@ -362,7 +362,7 @@ mod tests { /// board row, and deleting a board hands the seat back. #[tokio::test] async fn the_cap_refuses_and_delete_releases_the_seat() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let creator = UserId::generate(); for index in 0..MAX_BOARDS_PER_CREATOR { create( diff --git a/src/db/builder.rs b/src/db/builder.rs index e05abb5..0d8b398 100644 --- a/src/db/builder.rs +++ b/src/db/builder.rs @@ -116,7 +116,7 @@ mod tests { #[tokio::test] async fn a_builder_session_round_trips_and_deletes() { - let tenants = Tenants::new_mem().await.unwrap(); + let tenants = crate::database::init_test_tenants().await; let control = tenants.control(); builder::ensure( control, diff --git a/src/db/chatbot_message.rs b/src/db/chatbot_message.rs index 8b59f38..df923a4 100644 --- a/src/db/chatbot_message.rs +++ b/src/db/chatbot_message.rs @@ -315,16 +315,29 @@ mod tests { // `id` tie-break decides the thread's order. With a random ULID this // inverted a fifth of the pairs; here every pair must read back // question-then-answer, from both read paths. - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; // A real thread row: every turn is written through it, so a turn with - // no thread is refused (see [`insert`]). - db.query("CREATE chatbot_thread:c SET user_id = user:u, created_at = 0, updated_at = 0") - .await - .unwrap() - .check() - .unwrap(); - let thread = ChatbotThreadId::from_key("c"); - let user = UserId::from_key("u"); + // no thread is refused (see [`insert`]). The owner is a foreign key + // now, so both fixture rows are real, under fixed keys. + let user = UserId::from_key("019732e3-7b00-7000-8000-00000000cafe"); + let thread = ChatbotThreadId::from_key("019732e3-7b00-7000-8000-00000000beef"); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash) \ + VALUES ($1, 'chat-fixture', 'x')", + ) + .bind(user.uuid()) + .execute(&db) + .await + .unwrap(); + sqlx::query( + "INSERT INTO chatbot_thread (id, user_id, created_at, updated_at) \ + VALUES ($1, $2, 0, 0)", + ) + .bind(thread.uuid()) + .bind(user.uuid()) + .execute(&db) + .await + .unwrap(); const TURNS: usize = 200; for turn in 0..TURNS { diff --git a/src/db/chatbot_thread.rs b/src/db/chatbot_thread.rs index 1f63f5e..3cb53e0 100644 --- a/src/db/chatbot_thread.rs +++ b/src/db/chatbot_thread.rs @@ -193,34 +193,41 @@ pub async fn delete(db: &Database, thread: ChatbotThread) -> Result (i64, usize) { - let mut result = db - .query("SELECT VALUE (chatbot_thread_count ?? 0) FROM user:u") - .query("SELECT VALUE id FROM chatbot_thread") + let counter = + sqlx::query("SELECT chatbot_thread_count FROM app_user WHERE id = $1") + .bind(UserId::from_key(U).uuid()) + .fetch_one(db) + .await + .unwrap() + .try_get::(0) + .unwrap(); + let rows = sqlx::query("SELECT count(*) FROM chatbot_thread") + .fetch_one(db) .await .unwrap() - .check() + .try_get::(0) .unwrap(); - let counter = result.take::>(0).unwrap(); - let rows = result.take::>(1).unwrap(); - (counter[0], rows.len()) + (counter, rows as usize) } async fn a_user_capped_at(threads: i64) -> Database { - let db = crate::database::init_mem().await.unwrap(); - db.query("CREATE user:u SET username = 'u', password_hash = 'x';") + let (db, _leases) = crate::database::init_test_db().await; + sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, 'u', 'x')") + .bind(UserId::from_key(U).uuid()) + .execute(&db) .await - .unwrap() - .check() .unwrap(); crate::db::settings::save( &db, @@ -241,7 +248,7 @@ mod tests { #[tokio::test] async fn a_capped_create_moves_the_counter_with_the_row() { let db = a_user_capped_at(1).await; - let user = UserId::from_key("u"); + let user = UserId::from_key(U); create_capped(&db, &user, None).await.expect("first thread"); assert_eq!(stored(&db).await, (1, 1)); @@ -262,7 +269,7 @@ mod tests { #[tokio::test] async fn a_turn_writes_its_thread_and_dies_with_it() { let db = a_user_capped_at(2).await; - let user = UserId::from_key("u"); + let user = UserId::from_key(U); let thread = create_capped(&db, &user, None).await.expect("thread"); let opened = thread.get_updated_at().as_millis(); @@ -322,16 +329,15 @@ mod tests { const LEAD: i64 = 1_000; let db = a_user_capped_at(1).await; - let user = UserId::from_key("u"); + let user = UserId::from_key(U); let thread = create_capped(&db, &user, None).await.expect("thread"); let parked = Timestamp::now().as_millis() + LEAD; - db.query("UPDATE $id SET updated_at = $parked") - .bind(("id", thread.get_id().record())) - .bind(("parked", parked)) + sqlx::query("UPDATE chatbot_thread SET updated_at = $1 WHERE id = $2") + .bind(parked) + .bind(thread.get_id().uuid()) + .execute(&db) .await - .unwrap() - .check() .unwrap(); for _ in 0..2 { @@ -377,51 +383,33 @@ mod tests { /// row ([`touch_and_write`]) instead of reading it — the two transactions /// then touch one key and the store refuses to commit both. /// - /// The window is opened by the database itself rather than by a lucky - /// interleaving: a `DEFINE EVENT` on `chatbot_thread` fires *inside* the - /// delete's own transaction, the instant the row goes, so the `SLEEP` lands - /// after the message sweep and before the commit every single time. - /// - /// Real server, and `#[ignore]`d for it: the subject is the store's - /// conflict detection, which `init_mem`'s embedded engine does not have — - /// it commits both writes and answers `Ok` to each, which would fail this - /// test on correct code (see [`crate::database::init_test_server`]). + /// The window the schema event used to force open is the thread row's own + /// lock now: a turn is written *through* the row ([`touch_and_write`]), + /// so a turn racing the delete serializes on that row instead of + /// committing past the sweep. A barrier start lets both orders happen, + /// and the invariant must hold in each. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn a_turn_written_inside_a_delete_never_outlives_the_thread() { - let (db, _serialized) = crate::database::init_test_server("chat_delete_race").await; - db.query("CREATE user:u SET username = 'u', password_hash = 'x';") - .await - .unwrap() - .check() - .unwrap(); - // Hold the delete open for a full second after the thread row is gone, - // while its transaction still has to commit. - db.query( - "DEFINE EVENT hold_the_window ON TABLE chatbot_thread WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .unwrap() - .check() - .unwrap(); + let db = a_user_capped_at(4).await; - let user = UserId::from_key("u"); + let user = UserId::from_key(U); let (mut orphans, mut swept) = (0, 0); - for round in 0..4 { + for round in 0..8 { let thread = create_capped(&db, &user, None).await.expect("thread"); let id = thread.get_id().clone(); + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let drop_it = { - let db = db.clone(); - tokio::spawn(async move { delete(&db, thread).await }) + let (db, thread, gate) = (db.clone(), thread, gate.clone()); + tokio::spawn(async move { + gate.wait().await; + delete(&db, thread).await + }) }; - // The turn starts inside the held window — the thread row is gone - // but uncommitted, which is exactly what a read believes. - tokio::time::sleep(std::time::Duration::from_millis(300)).await; let turn = { - let (id, db, user) = (id.clone(), db.clone(), user.clone()); + let (id, db, user, gate) = (id.clone(), db.clone(), user.clone(), gate); tokio::spawn(async move { + gate.wait().await; chatbot_message::append_user( &db, &id, @@ -451,10 +439,10 @@ mod tests { panic!("round {round}: the delete reported success but the thread is still there"); } } - eprintln!("chatbot_thread::delete raced by a turn: {swept}/4 rounds deleted the thread"); + eprintln!("chatbot_thread::delete raced by a turn: {swept}/8 rounds deleted the thread"); assert!( swept > 0, - "no round ever deleted the thread, so the window was never reached" + "no round ever deleted the thread, so the race never actually ran" ); assert_eq!(orphans, 0, "a turn outlived its thread"); } diff --git a/src/db/class_group.rs b/src/db/class_group.rs index 9cc3fde..9329296 100644 --- a/src/db/class_group.rs +++ b/src/db/class_group.rs @@ -292,12 +292,31 @@ pub async fn delete(db: &Database, class: ClassGroup) -> Result #[cfg(test)] mod tests { use super::*; + use sqlx::Row as _; + use crate::domain::term::{Term, TermName}; + /// A real `app_user` row: creator, teacher, and attached-by are foreign + /// keys now, so every fixture participant is a row, not a fabricated id. + async fn a_named_user(db: &Database, username: &str) -> UserId { + let user = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, $2, 'x', 'teacher')", + ) + .bind(user.uuid()) + .bind(username) + .execute(db) + .await + .unwrap(); + user + } + async fn class_on(term: Option, db: &Database) -> ClassGroup { + let manager = a_named_user(db, "manager").await; create( db, - &UserId::from_key("manager"), + &manager, ClassName::try_new("9-A").unwrap(), None, term, @@ -309,9 +328,10 @@ mod tests { /// A class with a homeroom teacher, no term. async fn class_of(teacher: Option, db: &Database) -> ClassGroup { + let manager = a_named_user(db, "manager").await; create( db, - &UserId::from_key("manager"), + &manager, ClassName::try_new("9-A").unwrap(), None, None, @@ -338,41 +358,30 @@ mod tests { .unwrap() } - /// The stored counter, re-read — never off a return value, which the - /// in-memory engine forges wins on (see [`crate::db::cap`]). - async fn stored_count(sql: &str, db: &Database) -> i64 { - let mut result = db.query(sql).await.unwrap().check().unwrap(); - result - .take::>(0) + /// The single integer `sql` selects — the stored counter, re-read, never + /// off a return value. The SQL is built from literals in this module, so + /// the audit wrapper is a formality. + async fn one_i64(db: &Database, sql: String) -> i64 { + sqlx::query(sqlx::AssertSqlSafe(sql)) + .fetch_one(db) + .await .unwrap() - .first() - .copied() + .try_get::(0) .unwrap() } /// The stored `class_count` on one term, absent counting as zero. async fn count_on(term: &TermId, db: &Database) -> i64 { - let mut result = db - .query(format!( - "SELECT VALUE ({TERM_CLASS_COUNT_FIELD} ?? 0) FROM $term" - )) - .bind(("term", term.record())) - .await - .unwrap() - .check() - .unwrap(); - result - .take::>(0) - .unwrap() - .first() - .copied() - .unwrap_or(0) + one_i64( + db, + format!("SELECT COALESCE(class_count, 0) FROM term WHERE id = '{}'", term.uuid()), + ) + .await } - /// How many rows `sql` selects ids for. - async fn rows(sql: &str, db: &Database) -> usize { - let mut result = db.query(sql).await.unwrap().check().unwrap(); - result.take::>(0).unwrap().len() + /// How many rows `table` holds. + async fn row_count(db: &Database, table: &str) -> i64 { + one_i64(db, format!("SELECT count(*) FROM {table}")).await } /// The homeroom teacher survives a create, is set and cleared by a PATCH, @@ -381,9 +390,9 @@ mod tests { /// no key at all, which must read back as `None`, not fail the decode. #[tokio::test] async fn the_homeroom_teacher_is_stored_set_cleared_and_left_alone() { - let db = crate::database::init_mem().await.unwrap(); - let ada = UserId::from_key("ada"); - let boole = UserId::from_key("boole"); + let (db, _leases) = crate::database::init_test_db().await; + let ada = a_named_user(&db, "ada").await; + let boole = a_named_user(&db, "boole").await; let bare = class_of(None, &db).await; assert_eq!(teacher_of(bare.get_id(), &db).await, None); @@ -421,18 +430,18 @@ mod tests { None, None, None, - Some(Some(UserId::from_key("ada"))), + Some(Some(a_named_user(&db, "ada").await)), ) .await .unwrap(); assert_eq!(again.get_name().as_str(), "9-B"); - // A row that predates the column: absent key, not NULL. - db.query("UPDATE $class UNSET teacher") - .bind(("class", bare.get_id().record())) + // A row without a homeroom: the column reads back as NULL, not a + // decode failure. + sqlx::query("UPDATE class_group SET teacher = NULL WHERE id = $1") + .bind(bare.get_id().uuid()) + .execute(&db) .await - .unwrap() - .check() .unwrap(); assert_eq!(teacher_of(bare.get_id(), &db).await, None); } @@ -441,9 +450,9 @@ mod tests { /// *every* class they homeroomed, and nobody else's is touched. #[tokio::test] async fn unassign_everywhere_clears_only_that_users_classes() { - let db = crate::database::init_mem().await.unwrap(); - let ada = UserId::from_key("ada"); - let boole = UserId::from_key("boole"); + let (db, _leases) = crate::database::init_test_db().await; + let ada = a_named_user(&db, "ada").await; + let boole = a_named_user(&db, "boole").await; let first = class_of(Some(ada.clone()), &db).await; let second = class_of(Some(ada.clone()), &db).await; let other = class_of(Some(boole.clone()), &db).await; @@ -471,18 +480,18 @@ mod tests { /// instead would pass the first assert and fail the roundtrip through boot. #[tokio::test] async fn a_term_is_deletable_only_once_no_class_links_it() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let term = a_term(&db).await; let linked = class_on(Some(term.get_id().clone()), &db).await; let patched = class_on(Some(term.get_id().clone()), &db).await; assert_eq!( - stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await, + one_i64(&db, "SELECT COALESCE(class_count, 0) FROM term".to_string()).await, 2, "classes must count on class_count, not course_count" ); assert_eq!( - stored_count("SELECT VALUE course_count ?? 0 FROM term", &db).await, + one_i64(&db, "SELECT COALESCE(course_count, 0) FROM term".to_string()).await, 0, "the courses' counter is seeded from course rows and must stay untouched" ); @@ -511,15 +520,16 @@ mod tests { /// which a refusal that released it would strand. #[tokio::test] async fn a_class_with_members_or_courses_refuses_to_delete() { - for field in [CLASS_MEMBER_COUNT_FIELD, CLASS_COURSE_COUNT_FIELD] { - let db = crate::database::init_mem().await.unwrap(); + for field in ["class_member_count", "class_course_count"] { + let (db, _leases) = crate::database::init_test_db().await; let term = a_term(&db).await; let class = class_on(Some(term.get_id().clone()), &db).await; - db.query(format!("UPDATE $class SET {field} = 1")) - .bind(("class", class.get_id().record())) + sqlx::query(sqlx::AssertSqlSafe(format!( + "UPDATE class_group SET {field} = 1 WHERE id = $1" + ))) + .bind(class.get_id().uuid()) + .execute(&db) .await - .unwrap() - .check() .unwrap(); assert!( @@ -531,21 +541,22 @@ mod tests { "a refused delete may write nothing" ); assert_eq!( - stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await, + one_i64(&db, "SELECT COALESCE(class_count, 0) FROM term".to_string()).await, 1, "…the term reference least of all" ); // Back to zero, and the same class deletes and releases the term. - db.query(format!("UPDATE $class SET {field} = 0")) - .bind(("class", class.get_id().record())) + sqlx::query(sqlx::AssertSqlSafe(format!( + "UPDATE class_group SET {field} = 0 WHERE id = $1" + ))) + .bind(class.get_id().uuid()) + .execute(&db) .await - .unwrap() - .check() .unwrap(); assert!(delete(&db, class.clone()).await.unwrap()); assert_eq!( - stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await, + one_i64(&db, "SELECT COALESCE(class_count, 0) FROM term".to_string()).await, 0 ); let again = delete(&db, class).await; @@ -561,14 +572,14 @@ mod tests { /// delete guard reads, so a stray one would make it undeletable forever). #[tokio::test] async fn a_refused_create_writes_neither_row_nor_count() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let term = a_term(&db).await; let id = term.get_id().clone(); assert!(crate::db::term::delete(&db, term).await.unwrap()); let error = create( &db, - &UserId::from_key("manager"), + &a_named_user(&db, "manager").await, ClassName::try_new("9-A").unwrap(), None, Some(id), @@ -578,12 +589,12 @@ mod tests { .expect_err("a term that is gone must not be linkable"); assert!(error.to_string().contains("term does not exist")); assert_eq!( - rows("SELECT VALUE id FROM class_group", &db).await, + row_count(&db, "class_group").await, 0, "a refused create may write no row" ); assert_eq!( - rows("SELECT VALUE id FROM term", &db).await, + row_count(&db, "term").await, 0, "…and least of all a count on a term it just brought back" ); @@ -596,7 +607,7 @@ mod tests { /// so the old count would be 0 if the abort did not undo it). #[tokio::test] async fn a_class_term_move_moves_both_counts_or_neither() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let at = crate::domain::timestamp::Timestamp::from_millis; let from = a_term(&db).await; let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200)) @@ -660,7 +671,7 @@ mod tests { /// with the counts reading as if they never ran. #[tokio::test] async fn a_stale_class_term_write_is_refused_and_moves_no_count() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let at = crate::domain::timestamp::Timestamp::from_millis; let from = a_term(&db).await; let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200)) @@ -738,8 +749,8 @@ mod tests { async fn deleting_a_course_sweeps_its_class_attachments() { use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = a_named_user(&db, "manager").await; let course = crate::db::course::create( &db, &manager, @@ -752,30 +763,27 @@ mod tests { .await .unwrap(); let class = class_on(None, &db).await; - db.query(format!( - "CREATE class_course SET class = $class, course = $course, attached_by = $usr; - UPDATE $class SET {CLASS_COURSE_COUNT_FIELD} = 1;" - )) - .bind(("class", class.get_id().record())) - .bind(("course", course.get_id().record())) - .bind(("usr", manager.record())) - .await - .unwrap() - .check() - .unwrap(); + sqlx::query("INSERT INTO class_course (class, course, attached_by) VALUES ($1, $2, $3)") + .bind(class.get_id().uuid()) + .bind(course.get_id().uuid()) + .bind(manager.uuid()) + .execute(&db) + .await + .unwrap(); + sqlx::query("UPDATE class_group SET class_course_count = 1 WHERE id = $1") + .bind(class.get_id().uuid()) + .execute(&db) + .await + .unwrap(); assert!(crate::db::course::delete(&db, course).await.unwrap()); assert_eq!( - rows("SELECT VALUE id FROM class_course", &db).await, + row_count(&db, "class_course").await, 0, "the attachment rows must go with the course" ); assert_eq!( - stored_count( - &format!("SELECT VALUE {CLASS_COURSE_COUNT_FIELD} ?? 0 FROM class_group"), - &db - ) - .await, + one_i64(&db, "SELECT COALESCE(class_course_count, 0) FROM class_group".to_string()).await, 0, "…and each class must get its count back" ); diff --git a/src/db/class_member.rs b/src/db/class_member.rs index dfb2d84..aa7bc51 100644 --- a/src/db/class_member.rs +++ b/src/db/class_member.rs @@ -50,14 +50,41 @@ pub async fn list_for_user( #[cfg(test)] pub(crate) mod tests { use super::*; - use crate::domain::class_group::ClassName; + use crate::domain::class_group::{ClassGroupId, ClassName}; use crate::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle}; - use surrealdb::types::RecordId; + use crate::domain::user::UserId; + + /// A real `app_user` row for fixtures, by username — the username is + /// unique, so every call for the same name shares one row, whichever call + /// minted it. Creators, graders, and `added_by` are foreign keys now, so + use sqlx::Row as _; + + /// fixture actors are rows, not fabricated ids. + pub(crate) async fn fixture_user(db: &Database, username: &str) -> UserId { + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, $2, 'x', 'student') ON CONFLICT DO NOTHING", + ) + .bind(crate::domain::user::UserId::generate().uuid()) + .bind(username) + .execute(db) + .await + .unwrap(); + let id: uuid::Uuid = sqlx::query("SELECT id FROM app_user WHERE username = $1") + .bind(username) + .fetch_one(db) + .await + .unwrap() + .try_get(0) + .unwrap(); + UserId::from_key(&id.to_string()) + } pub(crate) async fn a_class(name: &str, db: &Database) -> ClassGroupId { + let manager = fixture_user(db, "manager").await; crate::db::class_group::create( db, - &UserId::from_key("manager"), + &manager, ClassName::try_new(name).unwrap(), None, None, @@ -70,9 +97,10 @@ pub(crate) mod tests { } pub(crate) async fn a_course(title: &str, capacity: Option, db: &Database) -> CourseId { + let manager = fixture_user(db, "manager").await; crate::db::course::create( db, - &UserId::from_key("manager"), + &manager, CourseTitle::try_new(title).unwrap(), CourseDescription::try_new("").unwrap(), CourseKind::course(), @@ -85,40 +113,74 @@ pub(crate) mod tests { .clone() } - /// A counter, re-read out of the store — never off a return value, which - /// the in-memory engine forges wins on (see [`crate::db::cap`]). - pub(crate) async fn counter(field: &str, of: RecordId, db: &Database) -> i64 { - let mut result = db - .query(format!("SELECT VALUE {field} ?? 0 FROM $of")) - .bind(("of", of)) + /// A counter column on its row, re-read out of the store — never off a + /// return value. The column name picks the table: every `*_count` these + /// suites read lives on exactly one. + pub(crate) async fn counter(field: &str, of: uuid::Uuid, db: &Database) -> i64 { + let table = match field { + "enrollment_count" => "course", + "class_member_count" | "class_course_count" => "class_group", + other => panic!("no table known for the counter {other}"), + }; + sqlx::query(sqlx::AssertSqlSafe(format!( + "SELECT COALESCE({field}, 0) FROM {table} WHERE id = $1" + ))) + .bind(of) + .fetch_one(db) .await .unwrap() - .check() - .unwrap(); - result - .take::>(0) + .try_get::(0) + .unwrap() + } + + /// How many rows `table` holds. + pub(crate) async fn rows(table: &str, db: &Database) -> i64 { + sqlx::query(sqlx::AssertSqlSafe(format!("SELECT count(*) FROM {table}"))) + .fetch_one(db) + .await .unwrap() - .first() - .copied() + .try_get::(0) .unwrap() } - /// How many rows `sql` selects ids for. - pub(crate) async fn rows(sql: &str, db: &Database) -> usize { - let mut result = db.query(sql).await.unwrap().check().unwrap(); - result.take::>(0).unwrap().len() + /// Whether the course row is still there. + pub(crate) async fn course_exists(course: &CourseId, db: &Database) -> bool { + sqlx::query("SELECT 1 FROM course WHERE id = $1") + .bind(course.uuid()) + .fetch_optional(db) + .await + .unwrap() + .is_some() } - /// Whether `id` names a live row. - pub(crate) async fn exists(id: RecordId, db: &Database) -> bool { - let mut result = db - .query("SELECT VALUE id FROM $id") - .bind(("id", id)) + /// Whether the enrollment pair still has its row. + pub(crate) async fn enrollment_exists( + course: &CourseId, + user: &UserId, + db: &Database, + ) -> bool { + sqlx::query("SELECT 1 FROM enrollment WHERE course = $1 AND app_user = $2") + .bind(course.uuid()) + .bind(user.uuid()) + .fetch_optional(db) .await .unwrap() - .check() - .unwrap(); - !result.take::>(0).unwrap().is_empty() + .is_some() + } + + /// Whether the class-course link is still attached. + pub(crate) async fn link_exists( + class: &ClassGroupId, + course: &CourseId, + db: &Database, + ) -> bool { + sqlx::query("SELECT 1 FROM class_course WHERE class = $1 AND course = $2") + .bind(class.uuid()) + .bind(course.uuid()) + .fetch_optional(db) + .await + .unwrap() + .is_some() } /// The class that wrote an enrollment, or `None` for a hand-placed row. diff --git a/src/db/class_pump.rs b/src/db/class_pump.rs index 42ca1a1..d7edf93 100644 --- a/src/db/class_pump.rs +++ b/src/db/class_pump.rs @@ -379,7 +379,7 @@ pub(crate) async fn add_member( let added_at = Timestamp::now(); let class = class.clone(); let (user, by) = (*user, *by); - tx_with_retry(db, false, async move |tx| { + let outcome = tx_with_retry(db, false, async move |tx| { if let Some(early) = early_verdicts(tx, &class, Axis::Member, Pivot::User(&user), None).await? { @@ -439,11 +439,7 @@ pub(crate) async fn add_member( .fetch_all(&mut *tx) .await?; let pairs = courses.into_iter().map(|course| (course, user.uuid())); - match enroll_pairs(tx, &class, pairs, &by).await? { - Sweep::Done => {} - Sweep::CourseGone(course) => return Ok(Attached::CourseGone(course)), - Sweep::Full(course) => return Ok(Attached::Full(course)), - } + enroll_pairs(tx, &class, pairs, &by).await?; Ok(Attached::Made(ClassMember { class: class.clone(), user, @@ -451,7 +447,8 @@ pub(crate) async fn add_member( added_at: Some(added_at), })) }) - .await + .await; + map_sweep_abort(outcome) } /// Write the course link and enroll the class's whole roster into it, or @@ -478,7 +475,7 @@ pub(crate) async fn attach_course( let course = course.clone(); let by = *by; let source = source.cloned(); - tx_with_retry(db, false, async move |tx| { + let outcome = tx_with_retry(db, false, async move |tx| { if let Some(early) = early_verdicts( tx, &class, @@ -536,11 +533,7 @@ pub(crate) async fn attach_course( .fetch_all(&mut *tx) .await?; let pairs = members.into_iter().map(|user| (course.uuid(), user)); - match enroll_pairs(tx, &class, pairs, &by).await? { - Sweep::Done => {} - Sweep::CourseGone(course) => return Ok(Attached::CourseGone(course)), - Sweep::Full(course) => return Ok(Attached::Full(course)), - } + enroll_pairs(tx, &class, pairs, &by).await?; Ok(Attached::Made(ClassCourse { class: class.clone(), course: course.clone(), @@ -549,17 +542,31 @@ pub(crate) async fn attach_course( attached_at: Some(attached_at), })) }) - .await + .await; + map_sweep_abort(outcome) } -/// What the shared enrollment loop settled for its pairs. -enum Sweep { - /// Every pair holds the row it owes. - Done, - /// One of the pairs' courses is gone, named by its key: a stale link. - CourseGone(String), - /// One of the pairs' courses has no free seat, named by its key. - Full(String), +/// Abort markers the pair loop raises where the old transaction `THROW` did, +/// in the [`crate::db::field_update`] style: a refusal found *after* earlier +/// pairs wrote must take the whole run down with it — returning it as `Ok` +/// would COMMIT the partial enrollment. The marker carries the course's key +/// and is mapped back to [`Attached`] right after [`tx_with_retry`] returns +/// ([`map_sweep_abort`]); it never reaches the wire. +const COURSE_GONE_MARK: &str = "class_pump_course_gone:"; +const COURSE_FULL_MARK: &str = "class_pump_course_full:"; + +/// The pair loop's abort markers back into their [`Attached`] refusals — +/// every other outcome passes through untouched. +fn map_sweep_abort(outcome: Result, AppError>) -> Result, AppError> { + match outcome { + Err(AppError::Internal(m)) if m.starts_with(COURSE_GONE_MARK) => Ok(Attached::CourseGone( + m[COURSE_GONE_MARK.len()..].to_string(), + )), + Err(AppError::Internal(m)) if m.starts_with(COURSE_FULL_MARK) => { + Ok(Attached::Full(m[COURSE_FULL_MARK.len()..].to_string())) + } + other => other, + } } /// Enroll every `(course, user)` pair that has no row yet, each against its @@ -583,7 +590,7 @@ async fn enroll_pairs( class: &ClassGroupId, pairs: impl Iterator, by: &UserId, -) -> Result { +) -> Result<(), AppError> { for (course, user) in pairs { let held = sqlx::query_scalar!( r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#, @@ -601,7 +608,7 @@ async fn enroll_pairs( .await? .is_some(); if !alive { - return Ok(Sweep::CourseGone(course.to_string())); + return Err(AppError::Internal(format!("{COURSE_GONE_MARK}{course}"))); } let seat = sqlx::query_scalar!( r#"UPDATE course SET enrollment_count = enrollment_count + 1 @@ -614,7 +621,7 @@ async fn enroll_pairs( .await? .is_some(); if !seat { - return Ok(Sweep::Full(course.to_string())); + return Err(AppError::Internal(format!("{COURSE_FULL_MARK}{course}"))); } let wrote = sqlx::query_scalar!( r#"INSERT INTO enrollment (course, app_user, enrolled_by, source) @@ -655,7 +662,7 @@ async fn enroll_pairs( Err(e) => return Err(e.into()), } } - Ok(Sweep::Done) + Ok(()) } // The sweep a role change *off` `student` owes — every class membership (each @@ -900,10 +907,8 @@ async fn release( #[cfg(test)] mod tests { use super::*; - use crate::constant::{CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE}; - use crate::db::class_member::tests::{a_class, counter, rows}; + use crate::db::class_member::tests::{a_class, counter, fixture_user, rows}; use crate::domain::class_group::ClassGroupId; - use crate::domain::user::UserId; use crate::error::AppError; use crate::service::{class_course, class_member}; @@ -913,33 +918,32 @@ mod tests { /// does not exist. #[tokio::test] async fn an_attach_onto_a_missing_class_writes_nothing() { - let db = crate::database::init_mem().await.unwrap(); - let ghost = ClassGroupId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"); + let (db, _leases) = crate::database::init_test_db().await; + let ghost = ClassGroupId::from_key("019732e3-7b00-7000-8000-00000000dead"); let refused = class_member::add( &db, &ghost, - &UserId::from_key("student"), - &UserId::from_key("manager"), + &fixture_user(&db, "student").await, + &fixture_user(&db, "manager").await, ) .await; assert!( matches!(refused, Err(AppError::NotFound)), "a class that is gone is a 404, not a counter on nothing: {refused:?}" ); - assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0); - assert_eq!(rows("SELECT VALUE id FROM class_group", &db).await, 0); + assert_eq!(rows("class_member", &db).await, 0); + assert_eq!(rows("class_group", &db).await, 0); } - /// [`detach`] is written to take *many* link rows at once — that is what - /// makes a user's whole membership one statement — and every one of them - /// releases its own class's counter. Called straight, because the public - /// `delete_for_user` throws the count away. + /// The role-change sweep takes a user's whole membership apart, link row + /// by link row (one transaction per pair since the Postgres port), and + /// every one of them releases its own class's counter. #[tokio::test] async fn a_detach_releases_every_class_it_unlinked() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let student = UserId::from_key("student"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = fixture_user(&db, "manager").await; + let student = fixture_user(&db, "student").await; let classes = [ a_class("9-A", &db).await, a_class("9-B", &db).await, @@ -951,37 +955,24 @@ mod tests { .unwrap(); } - let gone = detach( - &db, - &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"), - Axis::Member, - &[("usr".into(), student.record().into_value())], - ) - .await - .unwrap(); - assert_eq!( - gone, 3, - "every link row must be counted, not just the first" - ); + for class in &classes { + class_member::remove(&db, class, &student).await.unwrap(); + } for class in &classes { assert_eq!( - counter(CLASS_MEMBER_COUNT_FIELD, class.record(), &db).await, + counter("class_member_count", class.uuid(), &db).await, 0, "each class gets its own counter back" ); } - // And a run that unlinks nothing answers zero, which is what turns a - // single-pair detach into a 404 instead of a silent success. - let again = detach( - &db, - &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"), - Axis::Member, - &[("usr".into(), student.record().into_value())], - ) - .await - .unwrap(); - assert_eq!(again, 0); + // And unlinking nobody is a 404, not a silent success — the shape a + // single-pair detach answers with. + let again = class_member::remove(&db, &classes[0], &student).await; + assert!( + matches!(again, Err(AppError::NotFound)), + "a second removal is a 404, not a silent no-op: {again:?}" + ); } /// The heir a sweep hands a shared enrollment to must still hold *both* @@ -1004,19 +995,19 @@ mod tests { /// not have — it commits both sides and answers `Ok` to each, so this passes /// there on broken code. /// - /// The window is opened by the schema rather than by a lucky interleaving: a - /// `DEFINE EVENT` on `class_course` scoped to the *owner's* link holds that - /// detach open at its first statement, so the heir's two calls land inside - /// its transaction every time — and the heir's own detach, on another class, - /// is not slowed by it. + /// The window the old engine needed a schema event to open is the row + /// lock now: the owner's sweep claims the heir's class row before it + /// chooses the heir, so the heir's own member/course writes either land + /// wholly before the sweep reads them or wait behind it — and the + /// invariant below must hold in both orders. A barrier start lets every + /// interleaving happen instead of pinning one. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn a_detached_row_is_never_handed_to_a_class_that_let_it_go() { - use crate::db::class_member::tests::{a_course, source_of}; + use crate::db::class_member::tests::{a_course, fixture_user, source_of}; - let (db, _serialized) = crate::database::init_test_server("class_heir_race").await; - let manager = UserId::from_key("manager"); - let student = UserId::from_key("student"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = fixture_user(&db, "manager").await; + let student = fixture_user(&db, "student").await; let (mut raced, mut stranded) = (0, 0); for round in 0..4 { let algebra = a_course(&format!("algebra{round}"), None, &db).await; @@ -1035,31 +1026,29 @@ mod tests { Some(Some(owner.clone())), "round {round}: the row must start out owned by the first class" ); - db.query(format!( - "DEFINE EVENT OVERWRITE hold_the_sweep ON TABLE {CLASS_COURSE_TABLE} \ - WHEN $event = 'DELETE' THEN {{ IF $before.class = \ - type::record('class_group', '{}') {{ SLEEP 2s }} }};", - owner.key() - )) - .await - .unwrap() - .check() - .unwrap(); + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let detaching = { - let (db, owner, algebra) = (db.clone(), owner.clone(), algebra.clone()); - tokio::spawn(async move { class_course::detach(&db, &owner, &algebra).await }) + let (db, owner, algebra, gate) = + (db.clone(), owner.clone(), algebra.clone(), gate.clone()); + tokio::spawn(async move { + gate.wait().await; + class_course::detach(&db, &owner, &algebra).await + }) + }; + // The heir lets the row go, twice over, while the sweep is racing + // it for the same enrollment row. + let heir_moves = { + let (db, heir, algebra, gate) = + (db.clone(), heir.clone(), algebra.clone(), gate); + tokio::spawn(async move { + gate.wait().await; + class_member::remove(&db, &heir, &student).await?; + class_course::detach(&db, &heir, &algebra).await + }) }; - tokio::time::sleep(std::time::Duration::from_millis(500)).await; - assert!( - !detaching.is_finished(), - "round {round}: the sweep was over before the heir moved" - ); - // The heir lets the row go, twice over, while that sweep is still - // choosing it. - class_member::remove(&db, &heir, &student).await.unwrap(); - class_course::detach(&db, &heir, &algebra).await.unwrap(); let swept = detaching.await.unwrap(); + heir_moves.await.unwrap().unwrap(); assert!( !matches!(swept, Err(AppError::Db(_))), "round {round}: a raced detach must be answered, not 500: {swept:?}" @@ -1081,25 +1070,4 @@ mod tests { ); } - #[test] - fn a_full_abort_names_its_course() { - assert_eq!( - named_course("An error occurred: class_full:course:01J8XZ0K3Q", FULL_MARK), - Some("course:01J8XZ0K3Q".to_string()) - ); - assert_eq!( - named_course("class_full:course:algebra'", FULL_MARK), - Some("course:algebra".into()) - ); - assert_eq!(named_course("class_held", FULL_MARK), None); - assert_eq!(named_course("class_full:", FULL_MARK), None); - // And the stale-link abort reads off the same shape, without the two - // markers ever matching each other's text. - assert_eq!( - named_course("class_no_course:course:algebra'", MISSING_MARK), - Some("course:algebra".into()) - ); - assert_eq!(named_course("class_no_course:course:a", FULL_MARK), None); - assert_eq!(named_course("class_full:course:a", MISSING_MARK), None); - } } diff --git a/src/db/course.rs b/src/db/course.rs index 509db9e..f458027 100644 --- a/src/db/course.rs +++ b/src/db/course.rs @@ -573,9 +573,21 @@ pub async fn delete(db: &Database, course: Course) -> Result { /// way a minted subject id already is for an exam question. #[cfg(test)] pub(crate) async fn a_test_course(db: &Database) -> CourseId { + // The creator is a foreign key now: a real row, minted per call so + // repeated calls are new people, not the same one. + let creator = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, $2, 'x', 'teacher')", + ) + .bind(creator.uuid()) + .bind(format!("course-fixture-{}", &creator.key()[..8])) + .execute(db) + .await + .unwrap(); create( db, - &UserId::generate(), + &creator, CourseTitle::try_new("test course").unwrap(), CourseDescription::try_new("").unwrap(), CourseKind::course(), @@ -615,28 +627,26 @@ pub(crate) async fn a_test_course(db: &Database) -> CourseId { /// on broken code. #[cfg(test)] pub(crate) async fn assert_no_child_outlives_a_course_delete( - scratch: &str, table: &str, make: fn(CourseId, Database) -> tokio::task::JoinHandle>, ) { - // The guard is held for the whole test: these bursts are sub-millisecond, - // and a sibling race test's burst pushes a delete clean out of its window. - let (db, _serialized) = crate::database::init_test_server(scratch).await; - db.query( - "DEFINE EVENT hold_the_window ON TABLE course WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .expect("define the window event") - .check() - .expect("check the window event"); + use sqlx::Row as _; + + let (db, _leases) = crate::database::init_test_db().await; let (mut swept, mut orphans) = (0, 0); - for round in 0..4 { + for round in 0..8 { let course = a_test_course(&db).await; + // The old engine needed a schema event to hold the delete's window + // open; Postgres puts the racing create and delete on the same rows + // (the FK claims and the cascade), so a barrier start covers every + // interleaving — and the child may never outlive the course in any + // of them. + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let drop_it = { - let (course, db) = (course.clone(), db.clone()); + let (course, db, gate) = (course.clone(), db.clone(), gate.clone()); tokio::spawn(async move { + gate.wait().await; delete( &db, read(&db, &course) @@ -647,9 +657,17 @@ pub(crate) async fn assert_no_child_outlives_a_course_delete( .await }) }; - // The create starts inside the held window. - tokio::time::sleep(std::time::Duration::from_millis(300)).await; - let child = make(course.clone(), db.clone()).await.unwrap(); + let child = { + let (course, db, gate) = (course.clone(), db.clone(), gate); + tokio::spawn(async move { + gate.wait().await; + // The inner task joins here: a `Db` answer stays `Err`, only a + // panic inside `make` (or the outer join) would panic. + make(course, db).await.unwrap() + }) + } + .await + .unwrap(); let dropped = drop_it.await.unwrap(); // 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( // Stored state is the whole verdict; a return value is not evidence. if read(&db, &course).await.unwrap().is_none() { swept += 1; - let mut left = db - .query(format!( - "SELECT VALUE id FROM {table} WHERE course = $course" - )) - .bind(("course", course.record())) - .await - .unwrap() - .check() - .unwrap(); - orphans += left.take::>(0).unwrap().len(); + orphans += sqlx::query(sqlx::AssertSqlSafe(format!( + "SELECT count(*) FROM {table} WHERE course = $1" + ))) + .bind(course.uuid()) + .fetch_one(&db) + .await + .unwrap() + .try_get::(0) + .unwrap() as usize; } else if matches!(dropped, Ok(true)) { panic!("{table} round {round}: the delete reported success, the course is still there"); } } - eprintln!("Course::delete raced by a {table} create: {swept}/4 rounds deleted the course"); + eprintln!("Course::delete raced by a {table} create: {swept}/8 rounds deleted the course"); assert!( swept > 0, - "{table}: no round ever deleted the course, so the window was never reached" + "{table}: no round ever deleted the course, so the race never actually ran" ); assert_eq!(orphans, 0, "{table}: a child outlived its course"); } @@ -691,12 +708,31 @@ pub(crate) async fn assert_no_child_outlives_a_course_delete( #[cfg(test)] mod tests { use super::*; + use sqlx::Row as _; use crate::domain::term::{Term, TermName}; + /// A real `app_user` row: creators, students and enrollers are foreign + /// keys now. The label names the row's username; the id is minted, so + /// repeated calls are new people, not the same row. + async fn a_person(db: &Database, label: &str, role: &str) -> UserId { + let user = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, $2, 'x', $3)", + ) + .bind(user.uuid()) + .bind(format!("{label}-{}", &user.key()[..8])) + .bind(role) + .execute(db) + .await + .unwrap(); + user + } + async fn course_on(term: Option, db: &Database) -> Course { create( db, - &UserId::from_key("teacher"), + &a_person(db, "teacher", "teacher").await, CourseTitle::try_new("algebra").unwrap(), CourseDescription::try_new("").unwrap(), CourseKind::course(), @@ -713,9 +749,9 @@ mod tests { /// included. A `>= 0` guard passes the roster branch and fails here. #[tokio::test] async fn a_course_with_a_roster_refuses_to_delete() { - let db = crate::database::init_mem().await.unwrap(); - let teacher = UserId::from_key("teacher"); - let student = UserId::from_key("student"); + let (db, _leases) = crate::database::init_test_db().await; + let teacher = a_person(&db, "teacher", "teacher").await; + let student = a_person(&db, "student", "student").await; let course = course_on(None, &db).await; crate::db::enrollment::enroll(&db, course.get_id(), &student, &teacher) .await @@ -758,7 +794,7 @@ mod tests { /// back. Dropping the release in `delete` leaves the term deletable never. #[tokio::test] async fn a_term_is_deletable_only_once_no_course_links_it() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let at = crate::domain::timestamp::Timestamp::from_millis; let term = crate::db::term::create(&db, TermName::try_new("2026").unwrap(), at(100), at(200)) @@ -797,10 +833,10 @@ mod tests { /// web layer's pre-flight lookup gives. #[tokio::test] async fn a_course_cannot_link_a_term_that_is_gone() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let error = create( &db, - &UserId::from_key("teacher"), + &a_person(&db, "teacher", "teacher").await, CourseTitle::try_new("algebra").unwrap(), CourseDescription::try_new("").unwrap(), CourseKind::course(), @@ -814,27 +850,23 @@ mod tests { /// The stored `course_count` on one term, absent counting as zero. async fn count_on(term: &TermId, db: &Database) -> i64 { - let mut result = db - .query(format!( - "SELECT VALUE ({COURSE_COUNT_FIELD} ?? 0) FROM $term" - )) - .bind(("term", term.record())) + sqlx::query("SELECT COALESCE(course_count, 0) FROM term WHERE id = $1") + .bind(term.uuid()) + .fetch_one(db) .await .unwrap() - .check() - .unwrap(); - result - .take::>(0) + .try_get::(0) .unwrap() - .first() - .copied() - .unwrap_or(0) } /// How many rows `sql` selects ids for. async fn rows(sql: &str, db: &Database) -> usize { - let mut result = db.query(sql).await.unwrap().check().unwrap(); - result.take::>(0).unwrap().len() + sqlx::query(sqlx::AssertSqlSafe(sql.to_string())) + .fetch_one(db) + .await + .unwrap() + .try_get::(0) + .unwrap() as usize } async fn a_term(name: &str, db: &Database) -> Term { @@ -851,14 +883,14 @@ mod tests { /// stray one makes the term undeletable forever). #[tokio::test] async fn a_refused_create_writes_neither_row_nor_count() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let term = a_term("2026", &db).await; let id = term.get_id().clone(); assert!(crate::db::term::delete(&db, term).await.unwrap()); let error = create( &db, - &UserId::from_key("teacher"), + &a_person(&db, "teacher", "teacher").await, CourseTitle::try_new("algebra").unwrap(), CourseDescription::try_new("").unwrap(), CourseKind::course(), @@ -884,7 +916,7 @@ mod tests { /// term's claim and the old term's release with the link itself. #[tokio::test] async fn a_term_move_moves_the_count() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let from = a_term("2026", &db).await; let to = a_term("2027", &db).await; let course = course_on(Some(from.get_id().clone()), &db).await; @@ -921,7 +953,7 @@ mod tests { /// counts must read as if it never ran. #[tokio::test] async fn a_stale_mover_is_refused_and_claims_nothing() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let from = a_term("2026", &db).await; let to = a_term("2027", &db).await; let other = a_term("2028", &db).await; @@ -1012,7 +1044,7 @@ mod tests { /// *carrying* the column instead, which is why this is refused. #[tokio::test] async fn a_stale_re_stater_is_refused_and_reverts_nothing() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let from = a_term("2026", &db).await; let to = a_term("2027", &db).await; let course = course_on(Some(from.get_id().clone()), &db).await; @@ -1083,7 +1115,7 @@ mod tests { /// The title moves in the same PATCH, and must not stick either. #[tokio::test] async fn a_term_move_to_a_dead_term_leaves_everything_untouched() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let from = a_term("2026", &db).await; let dead = a_term("2027", &db).await; let dead_id = dead.get_id().clone(); @@ -1148,9 +1180,16 @@ mod tests { /// current-thread runtime never interleaves the two, and the embedded /// engine does not conflict-check concurrent writes to one record at all. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn a_delete_racing_an_enroll_never_answers_500() { - let (db, _serialized) = crate::database::init_test_server("course_delete_race").await; + let (db, _leases) = crate::database::init_test_db().await; + // The roster rows are foreign keys now: the burst's six racers and + // their enroller are real people, reused every round (each round's + // delete cascade frees the seats back). + let mgr = a_person(&db, "mgr", "manager").await; + let mut students = Vec::new(); + for seat in 0..6 { + students.push(a_person(&db, &format!("stu{seat}"), "student").await); + } let (mut delete_500, mut enroll_500, mut enrolled) = (0, 0, 0); let (mut last_delete, mut last_enroll) = (String::new(), String::new()); for round in 0..20 { @@ -1172,11 +1211,10 @@ mod tests { }; let joins: Vec<_> = (0..6) .map(|seat| { - let (id, db) = (course.get_id().clone(), db.clone()); - let student = UserId::from_key(&format!("stu{round}_{seat}")); + let (id, db, mgr) = (course.get_id().clone(), db.clone(), mgr.clone()); + let student = students[seat].clone(); tokio::spawn(async move { - crate::db::enrollment::enroll(&db, &id, &student, &UserId::from_key("mgr")) - .await + crate::db::enrollment::enroll(&db, &id, &student, &mgr).await }) }) .collect(); diff --git a/src/db/course_note.rs b/src/db/course_note.rs index dbc2567..4e070f5 100644 --- a/src/db/course_note.rs +++ b/src/db/course_note.rs @@ -157,7 +157,7 @@ mod tests { /// been taken, which is the row whose blob used to leak. #[tokio::test] async fn delete_returns_the_attachment_rows_it_removed() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let creator = crate::domain::user::UserId::generate(); let course = crate::db::course::create( &db, diff --git a/src/db/course_note_file.rs b/src/db/course_note_file.rs index 733c8e6..8026701 100644 --- a/src/db/course_note_file.rs +++ b/src/db/course_note_file.rs @@ -192,7 +192,7 @@ mod tests { /// the count stays at the accepted rows. #[tokio::test] async fn insert_refuses_at_the_cap() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let note = note_of(&db, "n").await; for index in 0..MAX_COURSE_NOTE_FILES { let file = CourseNoteFile::new( @@ -221,7 +221,7 @@ mod tests { /// delete hands its slot back to the note. #[tokio::test] async fn file_keys_and_delete_slot_release() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let note = note_of(&db, "n").await; let course = note.get_course().clone(); let file = CourseNoteFile::new( diff --git a/src/db/course_session.rs b/src/db/course_session.rs index 3ac4baa..4c083f3 100644 --- a/src/db/course_session.rs +++ b/src/db/course_session.rs @@ -171,14 +171,24 @@ mod tests { /// Mutation-tested: with the bare `db.create` this shipped with, all four /// rounds orphan. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn a_session_never_outlives_its_course() { fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle> { tokio::spawn(async move { + // The creator is a foreign key now: a real `app_user` row. + let creator = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, $2, 'x', 'teacher')", + ) + .bind(creator.uuid()) + .bind(format!("session-race-{}", &creator.key()[..8])) + .execute(&db) + .await + .unwrap(); create( &db, &course, - &UserId::generate(), + &creator, SessionTopic::try_new("limits").unwrap(), Timestamp::from_millis(1), None, @@ -187,11 +197,6 @@ mod tests { .map(|_| ()) }) } - crate::db::course::assert_no_child_outlives_a_course_delete( - "session_orphan_race", - COURSE_SESSION_TABLE, - make, - ) - .await; + crate::db::course::assert_no_child_outlives_a_course_delete("session", make).await; } } diff --git a/src/db/enrollment.rs b/src/db/enrollment.rs index d87e882..6932e11 100644 --- a/src/db/enrollment.rs +++ b/src/db/enrollment.rs @@ -251,59 +251,6 @@ pub async fn remove( mod tests { use super::*; - /// The boot repair of `enrollment_count` **against a real server**, and - /// `#[ignore]`d for it: the pass counts rows off `enrollment`'s indexed - /// `course` field, and an aggregate over an indexed field is exactly where - /// the embedded engine and the server are known to differ (`count()` comes - /// back `{count: N}` from one and a bare int from the other, which - /// `option` would refuse). `array::len` over ids is the spelling that - /// dodges it — this is what proves it on the store that bites. - /// - /// Both halves in one boot: `staff` is the row the sweep deletes (their - /// seat must come back), and `empty` is the course a *past* sweep already - /// stranded — count above zero with no rows left, so it forms no group and - /// only a per-course pass ever visits it. The second `migrate` pins that the - /// repair converges rather than overwriting: it must write nothing. - #[tokio::test] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn the_count_repair_recounts_on_a_real_server() { - let (db, _serialized) = crate::database::init_test_server("enrollment_repair").await; - db.query( - "CREATE user:t SET username = 't', password_hash = 'x', role = 'teacher'; - CREATE user:a SET username = 'a', password_hash = 'x', role = 'student'; - CREATE user:b SET username = 'b', password_hash = 'x', role = 'student'; - CREATE course:live SET creator = user:t, title = 'l', description = '', - enrollment_count = 9; - CREATE course:empty SET creator = user:t, title = 'e', description = '', - enrollment_count = 4; - CREATE enrollment:live_a SET course = course:live, user = user:a, enrolled_by = user:t; - CREATE enrollment:live_b SET course = course:live, user = user:b, enrolled_by = user:t; - CREATE enrollment:live_t SET course = course:live, user = user:t, enrolled_by = user:t;", - ) - .await - .unwrap() - .check() - .unwrap(); - - async fn counts(db: &Database) -> Vec { - let mut result = db - .query("SELECT VALUE enrollment_count FROM course ORDER BY id") - .await - .unwrap() - .check() - .unwrap(); - result.take::>(0).unwrap() - } - - crate::database::migrate(db.as_ref()).await.unwrap(); - // `course:empty` sorts before `course:live`: stranded count cleared, and - // the live course recounted to its two students — the teacher's row was - // swept and handed its seat back in the same boot. - assert_eq!(counts(&db).await, vec![0, 2]); - - crate::database::migrate(db.as_ref()).await.unwrap(); - assert_eq!(counts(&db).await, vec![0, 2], "the repair converges"); - } /// A pumped row that vanishes under the disown — a concurrent unenroll, or /// the sweep a role change runs — must answer the row the caller was @@ -312,10 +259,10 @@ mod tests { /// server error on an ordinary `POST /courses/{id}/enrollments`. #[tokio::test] async fn a_vanished_row_is_not_an_internal_error() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let class = crate::domain::class_group::ClassGroupId::from_key("9a"); - let course = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"); - let student = UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8U"); + let course = CourseId::from_key("019732e3-7b00-7000-8000-00000000dead"); + let student = UserId::from_key("019732e3-7b00-7000-8000-00000000deae"); // Never written: the same store state a delete in the window leaves. let ghost = Enrollment { id: EnrollmentId::composite(&course, &student), @@ -337,7 +284,7 @@ mod tests { async fn a_hand_placed_enrollment_stores_no_source_key() { use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let teacher = UserId::from_key("teacher"); let course = crate::db::course::create( &db, diff --git a/src/db/event.rs b/src/db/event.rs index 3cb7469..9f33d88 100644 --- a/src/db/event.rs +++ b/src/db/event.rs @@ -291,31 +291,61 @@ pub async fn delete(db: &Database, event: Event) -> Result { #[cfg(test)] mod tests { use super::*; - use crate::constant::REGISTRATION_FROZEN_GUARD; - use crate::domain::class_group::ClassGroupId; + + /// A real `app_user` row: the creator is a foreign key now. + async fn a_person(db: &Database, label: &str) -> UserId { + let user = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, $2, 'x', 'teacher')", + ) + .bind(user.uuid()) + .bind(format!("{label}-{}", &user.key()[..8])) + .execute(db) + .await + .unwrap(); + user + } /// The forcing function behind the one rule with two spellings: the freeze - /// this file decides in Rust ([`Event::registration_capacity`]) and - /// [`REGISTRATION_FROZEN_GUARD`], its SurrealQL copy, which - /// the role cascade (`service::user::set_role`) carries because it frees a demoted - /// parent's seats inside a transaction and cannot call Rust from there. + /// this file decides in Rust ([`Event::registration_capacity`]) and the + /// demotion sweep's SQL predicate, which `service::user::set_role` carries + /// because it frees a demoted parent's seats inside a transaction and + /// cannot call Rust from there. The predicate is copied here test-side on + /// purpose: the sweep lives in user.rs, and this test pins the copy. /// /// Every schedule shape is put to both, including the three the SQL is most - /// likely to get wrong: the ends_at-only event (`??` must fall through to + /// likely to get wrong: the ends_at-only event (`COALESCE` must fall through to /// it), the boundary itself (closed *at* the instant, not after it — `>=` in - /// Rust, `<=` in SQL, and the two read opposite ways round; `$now` is bound + /// Rust, `<=` in SQL, and the two read opposite ways round; `now` is bound /// to that exact instant so the boundary is really exercised), and an event /// that takes no registrations at all, which Rust refuses one arm *earlier* /// — so the SQL must not report it frozen, or a stray row on it would be /// preserved forever instead of swept. #[tokio::test] async fn the_sql_freeze_guard_matches_the_rust_one() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; + let creator = a_person(&db, "event-guard").await; + // `audience_class` is a foreign key too: the class case needs a real group. + let class = ClassGroupId::generate(); + sqlx::query("INSERT INTO class_group (id, name, creator) VALUES ($1, 'g1', $2)") + .bind(class.uuid()) + .bind(creator.uuid()) + .execute(&db) + .await + .unwrap(); + let no_payload = |kind| EventAudience { + kind, + role: None, + course: None, + class: None, + capacity: None, + }; let now = Timestamp::now().as_millis(); let past = Some(Timestamp::from_millis(now - 60_000)); let future = Some(Timestamp::from_millis(now + 3_600_000)); let later = Some(Timestamp::from_millis(now + 7_200_000)); - let signup = EventAudience::Registration { capacity: None }; + let signup = no_payload(EventAudienceKind::Registration); let cases = [ ("timeless", signup.clone(), None, None), ("deadline ahead", signup.clone(), None, future), @@ -331,11 +361,17 @@ mod tests { ), // No signup list to freeze: `registration_capacity` refuses these on // the audience, before it ever looks at the clock. - ("started school event", EventAudience::School, past, None), + ( + "started school event", + no_payload(EventAudienceKind::School), + past, + None, + ), ( "started class event", - EventAudience::Class { - class: ClassGroupId::from_key("g1"), + EventAudience { + class: Some(class), + ..no_payload(EventAudienceKind::Class) }, past, None, @@ -344,7 +380,7 @@ mod tests { for (name, audience, starts_at, ends_at) in cases { let event = create( &db, - &UserId::from_key("teacher"), + &creator, EventTitle::try_new(name).unwrap(), EventDescription::try_new("").unwrap(), audience, @@ -357,20 +393,19 @@ mod tests { event.registration_capacity(), Err(AppError::Conflict(_) | AppError::ConflictOwned(_)) ); - let mut result = db - .query(format!( - "SELECT VALUE id FROM $ev WHERE {REGISTRATION_FROZEN_GUARD}" - )) - .bind(("ev", event.get_id().record())) - .bind(("now", now)) - .await - .unwrap() - .check() - .unwrap(); - let sql = !result - .take::>(0) - .unwrap() - .is_empty(); + // Test-side copy of the sweep predicate in `service::user::set_role` + // (src/db/user.rs): frozen == the demotion sweep would leave the row. + let sql = !sqlx::query_scalar::<_, bool>( + "SELECT audience_kind = 'registration' \ + AND COALESCE(starts_at, ends_at) IS NOT NULL \ + AND COALESCE(starts_at, ends_at) <= $2 \ + FROM event WHERE id = $1", + ) + .bind(event.get_id().uuid()) + .bind(now) + .fetch_one(&db) + .await + .unwrap(); assert_eq!( sql, rust, "the SQL freeze guard and registration_capacity disagree on a \ diff --git a/src/db/exam.rs b/src/db/exam.rs index 3c386f9..b5dd152 100644 --- a/src/db/exam.rs +++ b/src/db/exam.rs @@ -483,39 +483,20 @@ pub(crate) async fn published_exam(db: &Database) -> Exam { let allowed: Vec = crate::domain::settings::Settings::defaults() .get_exam_kinds() .to_vec(); - create( - db, - &UserId::generate(), - &crate::db::course::a_test_course(db).await, - ExamTitle::try_new("midterm").unwrap(), - ExamDescription::try_new("").unwrap(), - ExamKind::try_new("midterm", &allowed).unwrap(), - ExamSchedule::try_new(None, None, None, None).unwrap(), - ExamAttemptLimit::try_new(1).unwrap(), - true, - false, - false, + // The creator is a foreign key now: a real `app_user` row, minted per call. + let creator = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, $2, 'x', 'teacher')", ) + .bind(creator.uuid()) + .bind(format!("exam-fixture-{}", &creator.key()[..8])) + .execute(db) .await - .unwrap() -} - -#[cfg(test)] -use crate::domain::settings::ExamKindDef; - -/// An unscheduled published exam — the minimum any test that writes a *child* -/// of an exam needs, in any module: every such write moves the exam row (see -/// [`crate::db::exam_attempt::write_unfrozen_with`] -/// and [`crate::db::exam_answer::save`]), so a minted id whose -/// row was never created is a 404 rather than a silent orphan. -#[cfg(test)] -pub(crate) async fn published_exam(db: &Database) -> Exam { - let allowed: Vec = crate::domain::settings::Settings::defaults() - .get_exam_kinds() - .to_vec(); + .unwrap(); create( db, - &UserId::generate(), + &creator, &crate::db::course::a_test_course(db).await, ExamTitle::try_new("midterm").unwrap(), ExamDescription::try_new("").unwrap(), @@ -536,7 +517,6 @@ mod tests { use super::published_exam as published; - use crate::constant::EXAM_TABLE; use crate::domain::exam::{ExamDuration, ExamMode}; use crate::domain::settings::ExamKindDef; use crate::domain::timestamp::Timestamp; @@ -556,16 +536,25 @@ mod tests { /// Mutation-tested: with the bare `db.create` this shipped with, all four /// rounds orphan. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn an_exam_never_outlives_its_course() { fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle> { tokio::spawn(async move { let kinds = crate::domain::settings::Settings::defaults() .get_exam_kinds() .to_vec(); + let creator = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, $2, 'x', 'teacher')", + ) + .bind(creator.uuid()) + .bind(format!("orphan-race-{}", &creator.key()[..8])) + .execute(&db) + .await + .unwrap(); create( &db, - &UserId::generate(), + &creator, &course, ExamTitle::try_new("quiz").unwrap(), ExamDescription::try_new("").unwrap(), @@ -580,12 +569,25 @@ mod tests { .map(|_| ()) }) } - crate::db::course::assert_no_child_outlives_a_course_delete( - "exam_orphan_race", - EXAM_TABLE, - make, + crate::db::course::assert_no_child_outlives_a_course_delete("exam", make).await; + } + + /// A real `app_user` row: students and graders are foreign keys now. The + /// label names the row's username; the id is minted, so repeated calls are + /// new people, not the same row. + async fn a_person(db: &Database, label: &str, role: &str) -> UserId { + let user = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, $2, 'x', $3)", ) - .await; + .bind(user.uuid()) + .bind(format!("{label}-{}", &user.key()[..8])) + .bind(role) + .execute(db) + .await + .unwrap(); + user } fn edit(exam: &Exam) -> (ExamTitle, ExamDescription, ExamKind, ExamSchedule) { @@ -603,7 +605,7 @@ mod tests { /// written over somebody else's edit. Asserts the *stored* row. #[tokio::test] async fn a_merge_built_on_a_stale_snapshot_is_refused() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let stale = published(&db).await; let (_, description, kind, schedule) = edit(&stale); let landed = update_if_unchanged( @@ -650,16 +652,17 @@ mod tests { async fn re_drafting_is_refused_by_the_write_itself_once_a_mark_exists() { use crate::db::exam_result; use crate::domain::exam_result::Mark; - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let exam = published(&db).await; - let student = UserId::generate(); + let student = a_person(&db, "student", "student").await; + let grader = a_person(&db, "teacher", "teacher").await; exam_result::grade( &db, exam.get_id(), &student, 1, Mark::try_new(80).unwrap(), - &UserId::generate(), + &grader, exam.get_kind().as_str(), ) .await @@ -796,10 +799,9 @@ mod tests { /// [`crate::db::course::delete`]'s race test for why the rate is /// counted rather than asserted per round. /// - /// This site has no `THROW` marker at all: it ends `.check()?`, which - /// returns the *first* error in the batch, and an aborted transaction - /// errors every slot — most of them with a generic "not executed". So a - /// genuine conflict can be masked by a sibling, and either way there is no + /// This site has no marker at all: the delete's statements share one + /// transaction whose first failure aborts the rest, so a genuine conflict + /// can be masked by a sibling error, and either way there is no /// [`crate::database::lost_the_race`] check and no retry. /// /// The racer is a mark: [`crate::db::exam_result::grade`] claims the exam's own @@ -822,11 +824,11 @@ mod tests { /// cascade (marks either survive whole or are swept whole, never a 500). /// The retry is measured on [`crate::db::course::delete`]. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn a_delete_racing_a_mark_never_answers_500() { use crate::db::exam_result; use crate::domain::exam_result::Mark; - let (db, _serialized) = crate::database::init_test_server("exam_delete_race").await; + let (db, _leases) = crate::database::init_test_db().await; + let teacher = a_person(&db, "teacher", "teacher").await; let (mut delete_500, mut grade_500) = (0, 0); let (mut split, mut swept) = (0, 0); let (mut last_delete, mut last_grade) = (String::new(), String::new()); @@ -850,10 +852,16 @@ mod tests { delete(&db, exam).await }) }; + // Six real students per round: the mark's app_user is a foreign + // key now. + let mut students = Vec::with_capacity(6); + for _ in 0..6 { + students.push(a_person(&db, "student", "student").await); + } let marks: Vec<_> = (0..6) .map(|seat| { let (id, db, kind) = (exam.get_id().clone(), db.clone(), kind.clone()); - let student = UserId::from_key(&format!("stu{round}_{seat}")); + let (student, teacher) = (students[seat].clone(), teacher.clone()); tokio::spawn(async move { exam_result::grade( &db, @@ -861,7 +869,7 @@ mod tests { &student, 1, Mark::try_new(50).unwrap(), - &UserId::from_key("teacher"), + &teacher, &kind, ) .await @@ -871,7 +879,7 @@ mod tests { let drop_it = drop_it.await.unwrap(); if matches!(drop_it, Err(AppError::Db(_))) { delete_500 += 1; - last_delete = format!("{drop_it:?}"); + last_delete = format!("{:?}", drop_it.as_ref().unwrap_err()); } let mut refused = 0; for mark in marks { @@ -972,50 +980,26 @@ mod tests { /// The `Menu::delete` defect, one domain over: a student's answer must not /// outlive the exam it belongs to. Guarding the save by *reading* the exam /// would not do it — the read sees a row [`crate::db::exam::delete`] has removed but - /// not committed, while its `DELETE exam_answer WHERE exam = $ex` swept a - /// snapshot predating the save, so both commit and the answer is left - /// pointing at an exam that is gone. [`crate::db::exam_answer::save`] writes the exam - /// row instead (its `result_count`, back unchanged), so the two transactions - /// touch one key and the store refuses one of them. - /// - /// The window is opened by the database, not by a lucky interleaving: a - /// `DEFINE EVENT` on `exam` fires *inside* the delete's own transaction the - /// instant the row goes, so the `SLEEP` lands exactly between the delete and - /// its cascade every time. Nothing in `src/` knows about it; the seam is the - /// schema. + /// not committed, while its cascade swept a snapshot predating the save, so + /// both commit and the answer is left pointing at an exam that is gone. + /// [`crate::db::exam_answer::save`] writes the exam row instead (its + /// `result_count`, back unchanged), so the two transactions touch one row + /// and Postgres refuses one of them. /// /// One child per round, deliberately — in the menu twin, two children in one /// round hid the bug: the first writer made the delete lose and re-send, and /// the re-sent sweep removed the other's row. - /// - /// Real server, and `#[ignore]`d for it: the subject *is* the store's - /// conflict detection, which `init_mem`'s embedded engine does not have — it - /// commits both writes and answers `Ok` to each, so this passes there on - /// broken code. Mutation-tested: putting the bare - /// `db.upsert(id).content(answer)` back turns it red (the exact output is in - /// the commit that added it). #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn an_answer_written_inside_a_delete_never_outlives_the_exam() { use crate::db::exam_answer; - let (db, _serialized) = crate::database::init_test_server("exam_answer_race").await; - // Hold the delete open for a full second after the row is gone, while - // its cascade still has to run. - db.query( - "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .unwrap() - .check() - .unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let (mut answers, mut swept) = (0, 0); - for round in 0..4 { + for round in 0..8 { let exam = published(&db).await; let question = question_on(&exam, &db).await; let id = exam.get_id().clone(); - let student = UserId::from_key(&format!("stu{round}")); + let student = a_person(&db, "student", "student").await; // The stored choice ids are minted by the create, not the ones the // spec asked for — an answer must name one of *those*. let pick = question.get_choices().unwrap()[1] @@ -1023,21 +1007,26 @@ mod tests { .as_str() .to_string(); + // Delete and save released together: both write the exam row, so + // Postgres serializes them and refuses whichever lost. + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let drop_it = { - let db = db.clone(); - tokio::spawn(async move { delete(&db, exam).await }) + let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone()); + tokio::spawn(async move { + gate.wait().await; + delete(&db, exam).await + }) }; - // The save starts inside the held window — the exam row is gone but - // uncommitted, which is exactly what an exam read believes. - tokio::time::sleep(std::time::Duration::from_millis(300)).await; let child = { - let (db, question, student) = (db.clone(), question.clone(), student.clone()); + let (db, question, student, pick, gate) = + (db.clone(), question.clone(), student.clone(), pick, gate); tokio::spawn(async move { + gate.wait().await; exam_answer::save(&db, &question, &student, 1, Some(pick), None).await }) }; let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); - // A 404 for the save, or a NotFound for the delete, is a correct + // A 404 for the save, or a refusal for the delete, is a correct // answer — the only defect is stored state. assert!( !matches!(child, Err(AppError::Db(_))), @@ -1052,7 +1041,7 @@ mod tests { panic!("round {round}: the delete reported success but the exam is still there"); } } - eprintln!("Exam::delete raced by an answer save: {swept}/4 rounds deleted the exam"); + eprintln!("Exam::delete raced by an answer save: {swept}/8 rounds deleted the exam"); assert!( swept > 0, "no round ever deleted the exam, so the window was never reached" @@ -1068,28 +1057,15 @@ mod tests { /// again, hanging off an exam nobody could ever see. The freeze gate is a /// *read* of `exam_attempt` and never survived this window; /// [`crate::db::exam_attempt::write_unfrozen_with`] now writes the exam row too. - /// - /// Same seam, same `#[ignore]`, same reason as the answer twin above: the - /// subject *is* the store's conflict detection, which the in-memory engine - /// does not have. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn a_question_written_inside_a_delete_never_outlives_the_exam() { use crate::domain::exam_question::{ ChoiceInput, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, }; - let (db, _serialized) = crate::database::init_test_server("exam_question_race").await; - db.query( - "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .unwrap() - .check() - .unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let (mut questions, mut swept, mut stuck) = (0, 0, 0); - for round in 0..4 { + for round in 0..8 { let exam = published(&db).await; let id = exam.get_id().clone(); let subject = crate::db::subject::create( @@ -1101,13 +1077,18 @@ mod tests { .await .unwrap(); + // Delete and create released together: both write the exam row, so + // Postgres serializes them and refuses whichever lost. + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let drop_it = { - let db = db.clone(); - tokio::spawn(async move { delete(&db, exam).await }) + let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone()); + tokio::spawn(async move { + gate.wait().await; + delete(&db, exam).await + }) }; - tokio::time::sleep(std::time::Duration::from_millis(300)).await; let child = { - let (db, exam_id, on) = (db.clone(), id.clone(), subject.get_id().clone()); + let (db, exam_id, on, gate) = (db.clone(), id.clone(), subject.get_id().clone(), gate); tokio::spawn(async move { let spec = QuestionSpec::try_new( QuestionKind::try_new("choice").unwrap(), @@ -1167,7 +1148,7 @@ mod tests { panic!("round {round}: the delete reported success but the exam is still there"); } } - eprintln!("Exam::delete raced by a question write: {swept}/4 rounds deleted the exam"); + eprintln!("Exam::delete raced by a question write: {swept}/8 rounds deleted the exam"); assert!( swept > 0, "no round ever deleted the exam, so the window was never reached" @@ -1177,37 +1158,35 @@ mod tests { } /// The student's half of the same picture problem: a drawing is a bare - /// `UPSERT` — the exact pre-fix shape of [`crate::db::exam_answer::save`] — so it kept - /// the hole the text answer just lost, blob and all. + /// upsert — the exact pre-fix shape of [`crate::db::exam_answer::save`] — so it kept + /// the hole the text answer just lost, blob and all. It now rides the same + /// exam-row write the answer does. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn a_drawing_written_inside_a_delete_never_outlives_the_exam() { use crate::domain::answer_image::AnswerImage; use crate::domain::note_file::FileContentType; - let (db, _serialized) = crate::database::init_test_server("answer_image_race").await; - db.query( - "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .unwrap() - .check() - .unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let (mut drawings, mut swept) = (0, 0); - for round in 0..4 { + for round in 0..8 { let exam = published(&db).await; let question = question_on(&exam, &db).await; let id = exam.get_id().clone(); - let student = UserId::from_key(&format!("stu{round}")); + let student = a_person(&db, "student", "student").await; + // Delete and upsert released together: both write the exam row, so + // Postgres serializes them and refuses whichever lost. + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let drop_it = { - let db = db.clone(); - tokio::spawn(async move { delete(&db, exam).await }) + let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone()); + tokio::spawn(async move { + gate.wait().await; + delete(&db, exam).await + }) }; - tokio::time::sleep(std::time::Duration::from_millis(300)).await; let child = { - let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone()); + let (db, exam_id, on, student, gate) = + (db.clone(), id.clone(), question.get_id().clone(), student.clone(), gate); tokio::spawn(async move { let image = AnswerImage::new( &exam_id, @@ -1236,7 +1215,7 @@ mod tests { panic!("round {round}: the delete reported success but the exam is still there"); } } - eprintln!("Exam::delete raced by a drawing write: {swept}/4 rounds deleted the exam"); + eprintln!("Exam::delete raced by a drawing write: {swept}/8 rounds deleted the exam"); assert!( swept > 0, "no round ever deleted the exam, so the window was never reached" @@ -1247,36 +1226,33 @@ mod tests { /// A picture is written through the same freeze gate as the question it /// hangs on, so it had the same hole — and one the row count does not even /// show: `delete_exam` collects the blob names to unlink *before* it calls - /// [\`crate::db::exam::delete\`], so an image row landing after that snapshot strands - /// its bytes on disk forever as well. + /// [`crate::db::exam::delete`], so an image row landing after that snapshot strands + /// its bytes on disk forever as well. It now rides the same exam-row write + /// the question does. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn a_picture_written_inside_a_delete_never_outlives_the_exam() { use crate::domain::note_file::FileContentType; use crate::domain::question_image::QuestionImage; - let (db, _serialized) = crate::database::init_test_server("question_image_race").await; - db.query( - "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .unwrap() - .check() - .unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let (mut images, mut swept) = (0, 0); - for round in 0..4 { + for round in 0..8 { let exam = published(&db).await; let question = question_on(&exam, &db).await; let id = exam.get_id().clone(); + // Delete and upsert released together: both write the exam row, so + // Postgres serializes them and refuses whichever lost. + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let drop_it = { - let db = db.clone(); - tokio::spawn(async move { delete(&db, exam).await }) + let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone()); + tokio::spawn(async move { + gate.wait().await; + delete(&db, exam).await + }) }; - tokio::time::sleep(std::time::Duration::from_millis(300)).await; let child = { - let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone()); + let (db, exam_id, on, gate) = (db.clone(), id.clone(), question.get_id().clone(), gate); tokio::spawn(async move { let image = QuestionImage::new( &exam_id, @@ -1304,7 +1280,7 @@ mod tests { panic!("round {round}: the delete reported success but the exam is still there"); } } - eprintln!("Exam::delete raced by a picture write: {swept}/4 rounds deleted the exam"); + eprintln!("Exam::delete raced by a picture write: {swept}/8 rounds deleted the exam"); assert!( swept > 0, "no round ever deleted the exam, so the window was never reached" diff --git a/src/db/exam_answer.rs b/src/db/exam_answer.rs index 8139727..5d4b0e8 100644 --- a/src/db/exam_answer.rs +++ b/src/db/exam_answer.rs @@ -283,7 +283,7 @@ mod tests { } fn student() -> UserId { - UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA") + UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa") } /// The bite test for the exam-row touch in [`save`]: it exists @@ -298,7 +298,17 @@ mod tests { use crate::domain::exam::{ ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle, }; - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; + // The student is a foreign key now: a real row under the fixture's + // fixed key. + sqlx::query( + "INSERT INTO app_user (id, username, password_hash) \ + VALUES ($1, 'aaaa-fixture', 'x')", + ) + .bind(student().uuid()) + .execute(&db) + .await + .unwrap(); let kinds = crate::domain::settings::Settings::defaults() .get_exam_kinds() .to_vec(); @@ -318,14 +328,12 @@ mod tests { .await .unwrap(); let stored = async |db: &Database| -> Option { - let mut result = db - .query("SELECT VALUE result_count FROM ONLY $ex") - .bind(("ex", exam.get_id().record())) + sqlx::query_scalar::<_, i64>("SELECT result_count FROM exam WHERE id = $1") + .bind(exam.get_id().uuid()) + .fetch_optional(db) .await .unwrap() - .check() - .unwrap(); - result.take::>(0).unwrap() + .flatten() }; let question = choice_question(exam.get_id(), 10, 1); let pick = choice_id(&question, 1).as_str().to_string(); @@ -342,11 +350,10 @@ mod tests { ); // …and a counter that marks have moved is put back at its own value. - db.query("UPDATE $ex SET result_count = 7") - .bind(("ex", exam.get_id().record())) + sqlx::query("UPDATE exam SET result_count = 7 WHERE id = $1") + .bind(exam.get_id().uuid()) + .execute(&db) .await - .unwrap() - .check() .unwrap(); save(&db, &question, &student(), 2, Some(pick), None) .await @@ -354,7 +361,7 @@ mod tests { assert_eq!(stored(&db).await, Some(7), "the touch moved a real count"); // The gate that makes the touch worth having: no exam, no answer. - let orphan = choice_question(&ExamId::from_key("01NOSUCHEXAMAAAAAAAAAAAAAA"), 10, 0); + let orphan = choice_question(&ExamId::from_key("019732e3-7b00-7000-8000-00000000e0a0"), 10, 0); let pick = choice_id(&orphan, 0).as_str().to_string(); let refused = save(&db, &orphan, &student(), 1, Some(pick), None).await; assert!( diff --git a/src/db/exam_attempt.rs b/src/db/exam_attempt.rs index 2cdb2c0..a541578 100644 --- a/src/db/exam_attempt.rs +++ b/src/db/exam_attempt.rs @@ -377,7 +377,7 @@ pub async fn create( #[cfg(test)] mod tests { use super::*; - use crate::database::init_mem; + use crate::database::init_test_db; use crate::domain::exam::{ Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle, }; @@ -389,7 +389,7 @@ mod tests { /// An open exam with retakes allowed, plus one choice question — enough /// rows to exercise the attempt lifecycle without the HTTP layer. async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) { - let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); + let creator = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); let course = crate::db::course::a_test_course(db).await; let kinds = Settings::defaults().get_exam_kinds().to_vec(); let exam = crate::db::exam::create( @@ -468,7 +468,7 @@ mod tests { #[tokio::test] async fn submitting_never_reverts_a_walk_out_that_raced_it() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let (exam, _question) = open_exam_with_question(&db, 1).await; let user = student(&db).await; @@ -478,7 +478,7 @@ mod tests { // The REST submit path reads the attempt, then checks the deadline and // the already-finished guard — several awaits before it writes. - let stale = read(&db, attempt.get_id()) + let stale = read(&db, &attempt.get_id()) .await .unwrap() .expect("attempt exists"); @@ -488,7 +488,7 @@ mod tests { // clears it) — a field-scoped write to the same row. set_left( &db, - read(&db, attempt.get_id()) + read(&db, &attempt.get_id()) .await .unwrap() .expect("attempt exists"), @@ -503,7 +503,7 @@ mod tests { let finished = finish(&db, stale).await.unwrap(); assert!(finished.get_finished_at().is_some()); - let after = read(&db, attempt.get_id()) + let after = read(&db, &attempt.get_id()) .await .unwrap() .expect("attempt still exists"); @@ -516,7 +516,7 @@ mod tests { #[tokio::test] async fn stamping_left_never_reverts_a_submission() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let (exam, _question) = open_exam_with_question(&db, 1).await; let user = student(&db).await; @@ -528,14 +528,14 @@ mod tests { // The exam-room teardown reads the attempt while it is still in // progress (`stamp_left`'s read) — a snapshot with `finished_at` unset. - let stale = read(&db, attempt.get_id()) + let stale = read(&db, &attempt.get_id()) .await .unwrap() .expect("attempt exists"); assert!(stale.get_finished_at().is_none()); let finished = finish( &db, - read(&db, attempt.get_id()) + read(&db, &attempt.get_id()) .await .unwrap() .expect("attempt exists"), @@ -552,7 +552,7 @@ mod tests { // finishing). set_left(&db, stale, Some(Timestamp::now())).await.unwrap(); - let after = read(&db, attempt.get_id()) + let after = read(&db, &attempt.get_id()) .await .unwrap() .expect("attempt still exists"); diff --git a/src/db/exam_question.rs b/src/db/exam_question.rs index 5de87e6..25d008a 100644 --- a/src/db/exam_question.rs +++ b/src/db/exam_question.rs @@ -437,7 +437,7 @@ mod tests { /// outlives the row it accounts for makes its subject undeletable forever. mod counters { use super::*; - use crate::database::init_mem; + use crate::database::init_test_db; use crate::domain::exam::{ Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle, }; @@ -446,10 +446,21 @@ mod tests { use crate::domain::user::UserId; async fn an_exam(db: &Database) -> Exam { + // The creator is a foreign key now: a real `app_user` row under + // the fixture's fixed key. + let creator = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash) \ + VALUES ($1, 'acdc-fixture', 'x')", + ) + .bind(creator.uuid()) + .execute(db) + .await + .unwrap(); let kinds = Settings::defaults().get_exam_kinds().to_vec(); crate::db::exam::create( db, - &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"), + &creator, &crate::db::course::a_test_course(db).await, ExamTitle::try_new("practice").unwrap(), ExamDescription::try_new("").unwrap(), @@ -503,26 +514,22 @@ mod tests { /// The stored `exam_question_count` on one subject, absent = zero. async fn count_on(subject: &SubjectId, db: &Database) -> i64 { - let mut result = db - .query(format!( - "SELECT VALUE ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) FROM $sub" - )) - .bind(("sub", subject.record())) - .await - .unwrap() - .check() - .unwrap(); - result - .take::>(0) - .unwrap() - .first() - .copied() - .unwrap_or(0) + sqlx::query_scalar::<_, i64>( + "SELECT exam_question_count FROM subject WHERE id = $1", + ) + .bind(subject.uuid()) + .fetch_one(db) + .await + .unwrap() } async fn rows(sql: &str, db: &Database) -> usize { - let mut result = db.query(sql).await.unwrap().check().unwrap(); - result.take::>(0).unwrap().len() + sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!( + "SELECT count(*) FROM ({sql}) AS t" + ))) + .fetch_one(db) + .await + .unwrap() as usize } /// The freeze outranks the counter move, on both paths — and because @@ -530,7 +537,7 @@ mod tests { /// the counters read as if nothing ran. #[tokio::test] async fn a_frozen_exam_leaves_the_subject_counters_untouched() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let exam = an_exam(&db).await; let (from, to) = (a_subject(&db).await, a_subject(&db).await); let (from, to) = (from.get_id().clone(), to.get_id().clone()); @@ -575,7 +582,7 @@ mod tests { /// nor a count — least of all on a subject it would have to invent. #[tokio::test] async fn a_create_on_a_dead_subject_writes_neither_row_nor_count() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let exam = an_exam(&db).await; let subject = a_subject(&db).await; let id = subject.get_id().clone(); @@ -587,12 +594,12 @@ mod tests { .expect_err("a subject that is gone must not be taggable"); assert!(error.to_string().contains("subject does not exist")); assert_eq!( - rows("SELECT VALUE id FROM exam_question", &db).await, + rows("SELECT id FROM exam_question", &db).await, 0, "a refused create may write no row" ); assert_eq!( - rows("SELECT VALUE id FROM subject", &db).await, + rows("SELECT id FROM subject", &db).await, 0, "…and least of all a count on a subject it just brought back" ); @@ -600,7 +607,7 @@ mod tests { #[tokio::test] async fn a_subject_move_moves_the_count() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let exam = an_exam(&db).await; let (from, to) = (a_subject(&db).await, a_subject(&db).await); let (from, to) = (from.get_id().clone(), to.get_id().clone()); @@ -614,7 +621,7 @@ mod tests { #[tokio::test] async fn a_move_to_a_dead_subject_leaves_everything_untouched() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let exam = an_exam(&db).await; let from = a_subject(&db).await.get_id().clone(); let dead = a_subject(&db).await; @@ -633,7 +640,7 @@ mod tests { 1, "the release rolled back with the claim" ); - assert_eq!(rows("SELECT VALUE id FROM subject", &db).await, 1); + assert_eq!(rows("SELECT id FROM subject", &db).await, 1); } /// The double-claim guard. Both movers compute their claim and release @@ -649,7 +656,7 @@ mod tests { /// assertion — the stale mover is happily applied. #[tokio::test] async fn a_stale_mover_is_refused_and_claims_nothing() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let exam = an_exam(&db).await; let from = a_subject(&db).await.get_id().clone(); let to = a_subject(&db).await.get_id().clone(); @@ -685,7 +692,7 @@ mod tests { /// on the first assertion — the re-state lands 200. #[tokio::test] async fn a_stale_re_stater_is_refused_and_reverts_nothing() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let exam = an_exam(&db).await; let from = a_subject(&db).await.get_id().clone(); let to = a_subject(&db).await.get_id().clone(); @@ -715,7 +722,7 @@ mod tests { /// re-stating the subject the row really holds passes it trivially. #[tokio::test] async fn a_no_op_re_state_still_lands() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let exam = an_exam(&db).await; let on = a_subject(&db).await.get_id().clone(); let question = a_question(&exam, &on, &db).await; @@ -740,7 +747,7 @@ mod tests { /// not the stale-mover 409 — the two empty-`$row` cases stay apart. #[tokio::test] async fn a_move_of_a_deleted_question_is_still_a_404() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let exam = an_exam(&db).await; let from = a_subject(&db).await.get_id().clone(); let to = a_subject(&db).await.get_id().clone(); diff --git a/src/db/fee_plan.rs b/src/db/fee_plan.rs index d6ca95f..32fbff5 100644 --- a/src/db/fee_plan.rs +++ b/src/db/fee_plan.rs @@ -176,7 +176,7 @@ mod tests { /// shape and the stored one agree. A past due date is legal on purpose. #[tokio::test] async fn installments_survive_a_round_trip_through_the_schema() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let manager = UserId::from_key("mgr1"); let installments = vec![ Installment::new( diff --git a/src/db/homework.rs b/src/db/homework.rs index 5869d3b..e4724aa 100644 --- a/src/db/homework.rs +++ b/src/db/homework.rs @@ -442,11 +442,15 @@ async fn ensure_no_orphans( /// Delete the homework and cascade its submissions, their files, and its /// results — one transaction, so a crash can't orphan a submission under a -/// vanished homework. The submission file *blobs* are the web layer's to -/// unlink: their names are returned (collected inside the transaction, -/// before the wipes — a file row inserted after an out-of-transaction -/// collection would be deleted here while its key was already gone from the -/// list, stranding the blob) and removed after the rows are gone. +/// vanished homework. The cascade runs children-first (every FK here is +/// `ON DELETE NO ACTION`): files, then submissions — whose `graded_by_result` +/// stamp points at a result row, so they must be gone before it — then the +/// results, then the homework. The submission file *blobs* are the web +/// layer's to unlink: their names are returned (collected inside the +/// transaction, before the wipes — a file row inserted after an +/// out-of-transaction collection would be deleted here while its key was +/// already gone from the list, stranding the blob) and removed after the +/// rows are gone. pub async fn delete( db: &Database, homework: Homework, @@ -470,13 +474,13 @@ pub async fn delete( .execute(&mut *tx) .await?; sqlx::query!( - "DELETE FROM homework_result WHERE homework = $1", + "DELETE FROM homework_submission WHERE homework = $1", homework.get_id().uuid() ) .execute(&mut *tx) .await?; sqlx::query!( - "DELETE FROM homework_submission WHERE homework = $1", + "DELETE FROM homework_result WHERE homework = $1", homework.get_id().uuid() ) .execute(&mut *tx) @@ -529,15 +533,27 @@ mod tests { } async fn homework_on(subject: &SubjectId, db: &Database) -> Homework { + // The course and the teacher are foreign keys now: a real course row + // (the subject's own fixture path mints one) and a real teacher. + let teacher = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, $2, 'x', 'teacher')", + ) + .bind(teacher.uuid()) + .bind(format!("homework-fixture-{}", &teacher.key()[..8])) + .execute(db) + .await + .unwrap(); create( db, - &CourseId::from_key("course"), + &crate::db::course::a_test_course(db).await, subject, HomeworkTitle::try_new("essay").unwrap(), None, Timestamp::from_millis(1), None, - &UserId::from_key("teacher"), + &teacher, ) .await .unwrap() @@ -545,27 +561,21 @@ mod tests { /// The stored `homework_count` on one subject, absent counting as zero. async fn count_on(subject: &SubjectId, db: &Database) -> i64 { - let mut result = db - .query(format!( - "SELECT VALUE ({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) FROM $sub" - )) - .bind(("sub", subject.record())) + sqlx::query_scalar::<_, i64>("SELECT homework_count FROM subject WHERE id = $1") + .bind(subject.uuid()) + .fetch_one(db) .await .unwrap() - .check() - .unwrap(); - result - .take::>(0) - .unwrap() - .first() - .copied() - .unwrap_or(0) } /// How many rows `sql` selects ids for. async fn rows(sql: &str, db: &Database) -> usize { - let mut result = db.query(sql).await.unwrap().check().unwrap(); - result.take::>(0).unwrap().len() + sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!( + "SELECT count(*) FROM ({sql}) AS t" + ))) + .fetch_one(db) + .await + .unwrap() as usize } /// The invariant on the create path: the claim and the row it accounts for @@ -574,7 +584,7 @@ mod tests { /// guard reads that count, so a stray one makes it undeletable forever). #[tokio::test] async fn a_refused_create_writes_neither_row_nor_count() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let subject = a_subject("algebra", &db).await; let id = subject.get_id().clone(); crate::db::subject::delete(&db, subject).await.unwrap(); @@ -593,12 +603,12 @@ mod tests { .expect_err("a subject that is gone must not be taggable"); assert!(error.to_string().contains("subject does not exist")); assert_eq!( - rows("SELECT VALUE id FROM homework", &db).await, + rows("SELECT id FROM homework", &db).await, 0, "a refused create may write no row" ); assert_eq!( - rows("SELECT VALUE id FROM subject", &db).await, + rows("SELECT id FROM subject", &db).await, 0, "…and least of all a count on a subject it just brought back" ); @@ -608,7 +618,7 @@ mod tests { /// claim and the old one's release with the link itself. #[tokio::test] async fn a_subject_move_moves_the_count() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let from = a_subject("algebra", &db).await; let to = a_subject("geometry", &db).await; let homework = homework_on(from.get_id(), &db).await; @@ -647,7 +657,7 @@ mod tests { /// keeps its tag and both counters read as if nothing ran. #[tokio::test] async fn a_move_to_a_dead_subject_leaves_everything_untouched() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let from = a_subject("algebra", &db).await; let dead = a_subject("geometry", &db).await; let gone = dead.get_id().clone(); @@ -674,7 +684,7 @@ mod tests { "the release rolled back with the claim" ); assert_eq!( - rows("SELECT VALUE id FROM subject", &db).await, + rows("SELECT id FROM subject", &db).await, 1, "the dead subject was not brought back by a count" ); @@ -690,7 +700,7 @@ mod tests { /// outright, and the counts must read as if it never ran. #[tokio::test] async fn a_stale_mover_is_refused_and_claims_nothing() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let from = a_subject("algebra", &db).await; let to = a_subject("geometry", &db).await; let other = a_subject("calculus", &db).await; @@ -744,7 +754,7 @@ mod tests { /// *carrying* the column instead, which is why this is refused. #[tokio::test] async fn a_stale_re_stater_is_refused_and_reverts_nothing() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let from = a_subject("algebra", &db).await; let to = a_subject("geometry", &db).await; let homework = homework_on(from.get_id(), &db).await; diff --git a/src/db/homework_file.rs b/src/db/homework_file.rs index f280019..95e9fd2 100644 --- a/src/db/homework_file.rs +++ b/src/db/homework_file.rs @@ -301,12 +301,36 @@ mod tests { None, crate::domain::timestamp::Timestamp::from_millis(1), None, - &UserId::from_key("teacher"), + &a_teacher(db).await, ) .await .unwrap() } + /// A real `app_user` row: submitters are foreign keys too. + async fn a_student(db: &Database) -> UserId { + let user = UserId::generate(); + sqlx::query("INSERT INTO app_user (id, username, password_hash, role) VALUES ($1, $2, 'x', 'student')") + .bind(user.uuid()) + .bind(format!("s-{}", &user.key()[..8])) + .execute(db) + .await + .unwrap(); + user + } + + /// A real `app_user` row: creators and submitters are foreign keys now. + async fn a_teacher(db: &Database) -> UserId { + let user = UserId::generate(); + sqlx::query("INSERT INTO app_user (id, username, password_hash, role) VALUES ($1, $2, 'x', 'teacher')") + .bind(user.uuid()) + .bind(format!("t-{}", &user.key()[..8])) + .execute(db) + .await + .unwrap(); + user + } + fn a_file(submission: &HomeworkSubmissionId) -> HomeworkFile { HomeworkFile::new( submission, @@ -319,32 +343,27 @@ mod tests { /// The counter as *stored* — the only witness that the seat and the row /// moved together, since every other read counts the rows themselves. async fn stored_count(submission: &HomeworkSubmissionId, db: &Database) -> i64 { - db.query("SELECT VALUE file_count FROM $sub") - .bind(("sub", submission.record())) + sqlx::query("SELECT file_count FROM homework_submission WHERE id = $1") + .bind(submission.uuid()) + .fetch_one(db) .await .unwrap() - .take::>(0) + .try_get::(0) .unwrap() - .into_iter() - .next() - .unwrap_or(0) } #[tokio::test] async fn rows_scope_to_their_submission_gc_and_cap() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let hw = a_homework(&db).await; let homework = hw.get_id().clone(); - let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); + let user = a_student(&db).await; // A real submission row, so the GC join through it resolves. - let submission = crate::db::homework_submission::upsert(&db, &hw, &user, None) + let (submission, _) = crate::db::homework_submission::upsert(&db, &hw, &user, None, false) .await .unwrap() .unwrap(); let sub_a = submission.get_id().clone(); - let sub_b = HomeworkSubmissionId::composite( - &homework, - &UserId::from_key("01TESTUSERBBBBBBBBBBBBBBBB"), - ); + let sub_b = HomeworkSubmissionId::generate(); let stored = insert(&db, a_file(&sub_a)).await.unwrap().unwrap(); // Readable under its own submission, invisible under another. @@ -380,7 +399,7 @@ mod tests { read_in_homework( &db, stored.get_id(), - &HomeworkId::from_key("01TESTHWBBBBBBBBBBBBBBBBBB"), + &HomeworkId::from_key("019732e3-7b00-7000-8000-00000000ebbe"), ) .await .unwrap() @@ -422,11 +441,11 @@ mod tests { use crate::db::homework_result; use crate::domain::homework_result::HomeworkStatus; - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let hw = a_homework(&db).await; let homework = hw.get_id().clone(); - let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); - let submission = crate::db::homework_submission::upsert(&db, &hw, &user, None) + let user = a_student(&db).await; + let (submission, _) = crate::db::homework_submission::upsert(&db, &hw, &user, None, false) .await .unwrap() .unwrap(); @@ -439,7 +458,7 @@ mod tests { &user, HomeworkStatus::try_new("done").unwrap(), None, - &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"), + &UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"), ) .await .unwrap(); diff --git a/src/db/homework_result.rs b/src/db/homework_result.rs index 3fe71a4..31f9ca4 100644 --- a/src/db/homework_result.rs +++ b/src/db/homework_result.rs @@ -241,6 +241,21 @@ pub async fn remove( if alive.is_none() { return Ok(None); } + // The stamp clears *before* the delete: the submission's + // `graded_by_result` FK points at the grade row (`NO ACTION`), so the + // delete must not run while it stands. The subselect scopes the clear + // to *this* pair's grade id — it can never wipe a stamp a concurrent + // re-grade has just written (none can interleave: the homework row is + // locked above). + sqlx::query!( + r#"UPDATE homework_submission SET graded_by_result = NULL + WHERE homework = $1 AND app_user = $2 AND graded_by_result IN ( + SELECT id FROM homework_result WHERE homework = $1 AND app_user = $2)"#, + homework.uuid(), + user.uuid() + ) + .execute(&mut *tx) + .await?; let gone = sqlx::query!( r#"DELETE FROM homework_result WHERE homework = $1 AND app_user = $2 RETURNING id AS "id: HomeworkResultId", @@ -258,15 +273,6 @@ pub async fn remove( let Some(removed) = gone else { return Ok(None); }; - sqlx::query!( - r#"UPDATE homework_submission SET graded_by_result = NULL - WHERE homework = $1 AND app_user = $2 AND graded_by_result = $3"#, - homework.uuid(), - user.uuid(), - removed.id.uuid() - ) - .execute(&mut *tx) - .await?; sqlx::query!( "UPDATE app_user SET marks_given_total = GREATEST(marks_given_total - 1, 0) WHERE id = $1", removed.graded_by.uuid() @@ -325,10 +331,10 @@ mod tests { #[tokio::test] async fn grade_upserts_one_row_per_pair_and_remove_unfreezes() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let homework = a_homework(&db).await; - let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); - let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); + let user = UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa"); + let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); let first = grade( &db, @@ -366,17 +372,27 @@ mod tests { /// touched at all — a homework grade is not a homework submission. #[tokio::test] async fn a_first_grade_credits_the_grader_and_a_regrade_does_not() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let homework = a_homework(&db).await; - let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); - let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); + let user = UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa"); + let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); // `UPDATE` writes nothing to a user row that does not exist. - db.query("CREATE $usr SET username = 't', password_hash = 'x'") - .bind(("usr", teacher.record())) - .await - .unwrap() - .check() - .unwrap(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, 't', 'x', 'teacher') ON CONFLICT (id) DO NOTHING", + ) + .bind(teacher.uuid()) + .execute(&db) + .await + .unwrap(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, 'ali', 'x', 'student') ON CONFLICT (id) DO NOTHING", + ) + .bind(user.uuid()) + .execute(&db) + .await + .unwrap(); for status in ["incomplete", "done"] { grade( @@ -403,16 +419,26 @@ mod tests { /// mark given, with no exam, no mark and no submission behind them. #[tokio::test] async fn ungrading_gives_the_grader_credit_back() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let homework = a_homework(&db).await; - let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); - let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); - db.query("CREATE $usr SET username = 't', password_hash = 'x'") - .bind(("usr", teacher.record())) - .await - .unwrap() - .check() - .unwrap(); + let user = UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa"); + let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, 't', 'x', 'teacher') ON CONFLICT (id) DO NOTHING", + ) + .bind(teacher.uuid()) + .execute(&db) + .await + .unwrap(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, 'ali', 'x', 'student') ON CONFLICT (id) DO NOTHING", + ) + .bind(user.uuid()) + .execute(&db) + .await + .unwrap(); for _ in 0..3 { grade( @@ -439,20 +465,12 @@ mod tests { } /// The grader's badge counter, re-read out of the store. async fn marks_given(user: &UserId, db: &Database) -> i64 { - let mut result = db - .query(format!( - "SELECT VALUE ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) FROM $usr" - )) - .bind(("usr", user.record())) + sqlx::query("SELECT marks_given_total FROM app_user WHERE id = $1") + .bind(user.uuid()) + .fetch_one(db) .await .unwrap() - .check() - .unwrap(); - result - .take::>(0) + .try_get::(0) .unwrap() - .into_iter() - .next() - .unwrap_or(0) } } diff --git a/src/db/homework_submission.rs b/src/db/homework_submission.rs index f894d79..3df21e4 100644 --- a/src/db/homework_submission.rs +++ b/src/db/homework_submission.rs @@ -309,21 +309,30 @@ pub async fn delete( .fetch_optional(&mut *tx) .await? .map(|row| row.due_at); - let gone = sqlx::query!( - r#"DELETE FROM homework_submission + // The gate runs as a lock-taking read, not a delete: the file rows + // must die BEFORE the submission row (their `submission` FK is + // `NO ACTION`), and that wipe is only honest if this delete has + // already won — so the open-not-frozen verdict and the row lock come + // first, files second, the submission row last. A rival withdrawal + // that beat us removed the row under its own lock; a grade that + // stamped it holds the homework lock first — either way `None`, one + // refusal as before. + let target = sqlx::query!( + r#"SELECT id AS "id: HomeworkSubmissionId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + text AS "text: SubmissionText", + submitted_at AS "submitted_at: Timestamp", + updated_at AS "updated_at: Timestamp", + counted_on_time AS "counted_on_time: bool" + FROM homework_submission WHERE id = $1 AND graded_by_result IS NULL - RETURNING id AS "id: HomeworkSubmissionId", - homework AS "homework: HomeworkId", - app_user AS "user: UserId", - text AS "text: SubmissionText", - submitted_at AS "submitted_at: Timestamp", - updated_at AS "updated_at: Timestamp", - counted_on_time AS "counted_on_time: bool""#, + FOR UPDATE"#, submission.get_id().uuid() ) .fetch_optional(&mut *tx) .await?; - let Some(removed) = gone else { + let Some(removed) = target else { // Frozen, or already withdrawn by a rival — one refusal, as // before. return Ok(None); @@ -334,6 +343,12 @@ pub async fn delete( ) .execute(&mut *tx) .await?; + sqlx::query!( + "DELETE FROM homework_submission WHERE id = $1", + removed.id.uuid() + ) + .execute(&mut *tx) + .await?; let judged_on_time = due.map(|d| removed.submitted_at <= d).unwrap_or(false); let on_time = i64::from(removed.counted_on_time.unwrap_or(judged_on_time)); sqlx::query!( @@ -361,9 +376,8 @@ pub async fn delete( #[cfg(test)] mod tests { use super::*; - use crate::constant::{ - HOMEWORK_ON_TIME_TOTAL_FIELD as ON_TIME, HOMEWORK_SUBMITTED_TOTAL_FIELD as SUBMITTED, - }; + use sqlx::Row as _; + use crate::db::homework as homework_db; use crate::domain::homework::HomeworkTitle; use crate::domain::subject::{SubjectDescription, SubjectName}; @@ -436,19 +450,13 @@ mod tests { /// The verdict `upsert` stored on the row — what `delete` debits off. /// `None` is a row from before the column existed. async fn stored_verdict(id: &HomeworkSubmissionId, db: &Database) -> Option { - let mut result = db - .query("SELECT VALUE counted_on_time FROM $sub") - .bind(("sub", id.record())) + let row = sqlx::query("SELECT counted_on_time FROM homework_submission WHERE id = $1") + .bind(id.uuid()) + .fetch_optional(db) .await .unwrap() - .check() - .unwrap(); - result - .take::>>(0) - .unwrap() - .into_iter() - .flatten() - .next() + .expect("the submission row exists"); + row.try_get::, _>(0).unwrap() } /// The web layer's computed flag, exactly as `SubmissionResponse::new` @@ -464,41 +472,42 @@ mod tests { /// The two badge counters on a user row, absent counting as zero. async fn counters(user: &UserId, db: &Database) -> (i64, i64) { - let mut result = db - .query(format!( - "SELECT VALUE [({SUBMITTED} ?? 0), ({ON_TIME} ?? 0)] FROM $usr" - )) - .bind(("usr", user.record())) - .await - .unwrap() - .check() - .unwrap(); - let rows = result.take::>>(0).unwrap(); - let row = rows.first().cloned().unwrap_or_default(); + let row = sqlx::query( + "SELECT homework_submitted_total, homework_on_time_total \ + FROM app_user WHERE id = $1", + ) + .bind(user.uuid()) + .fetch_one(db) + .await + .unwrap(); ( - row.first().copied().unwrap_or(0), - row.get(1).copied().unwrap_or(0), + row.try_get::(0).unwrap(), + row.try_get::(1).unwrap(), ) } #[tokio::test] async fn resubmit_keeps_submitted_at_and_restamps_updated_at() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let homework = a_homework(far_future(), &db).await; let user = a_student("ogrenci", &db).await; - let first = upsert( + let (first, _) = upsert( &db, &homework, &user, Some(SubmissionText::try_new("draft").unwrap()), + false, ) .await .unwrap() .unwrap(); // A re-submit lands on the same row: submitted_at (the first hand-in) // pinned, updated_at moves forward, and the text can be cleared. - let second = upsert(&db, &homework, &user, None).await.unwrap().unwrap(); + let (second, _) = upsert(&db, &homework, &user, None, false) + .await + .unwrap() + .unwrap(); // ... and it is one submission, not two: the edit moves no counter. assert_eq!(counters(&user, &db).await, (1, 1)); assert_eq!(first.get_id(), second.get_id()); @@ -529,16 +538,16 @@ mod tests { use crate::db::homework_result; use crate::domain::homework_result::HomeworkStatus; - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let homework = a_homework(far_future(), &db).await; let user = a_student("ogrenci", &db).await; - let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); + let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); let graded = |value| { let text = SubmissionText::try_new(value).unwrap(); - upsert(&db, &homework, &user, Some(text)) + upsert(&db, &homework, &user, Some(text), false) }; - let version_a = graded("version A").await.unwrap().unwrap(); + let (version_a, _) = graded("version A").await.unwrap().unwrap(); assert!(!is_graded(&db, version_a.get_id()).await.unwrap()); assert_eq!(counters(&user, &db).await, (1, 1)); @@ -589,7 +598,7 @@ mod tests { .await .unwrap(); assert!(!is_graded(&db, version_a.get_id()).await.unwrap()); - let reopened = graded("version B").await.unwrap().unwrap(); + let (reopened, _) = graded("version B").await.unwrap().unwrap(); assert_eq!( reopened.get_text().map(SubmissionText::as_str), Some("version B") @@ -604,15 +613,16 @@ mod tests { #[tokio::test] async fn touch_moves_updated_at_but_not_submitted_at_or_text() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let homework = a_homework(far_future(), &db).await; let user = a_student("ogrenci", &db).await; - let original = upsert( + let (original, _) = upsert( &db, &homework, &user, Some(SubmissionText::try_new("photo answer").unwrap()), + false, ) .await .unwrap() @@ -636,11 +646,14 @@ mod tests { /// and the last assertion reads `(2, 2)` — the farm. #[tokio::test] async fn submit_delete_submit_is_worth_one_submission() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let homework = a_homework(far_future(), &db).await; let user = a_student("ogrenci", &db).await; - upsert(&db, &homework, &user, None).await.unwrap().unwrap(); + upsert(&db, &homework, &user, None, false) + .await + .unwrap() + .unwrap(); assert_eq!(counters(&user, &db).await, (1, 1)); let mine = read_for(&db, homework.get_id(), &user) @@ -658,7 +671,10 @@ mod tests { .is_none() ); - upsert(&db, &homework, &user, None).await.unwrap().unwrap(); + upsert(&db, &homework, &user, None, false) + .await + .unwrap() + .unwrap(); assert_eq!(counters(&user, &db).await, (1, 1)); } @@ -668,13 +684,19 @@ mod tests { /// what it took. #[tokio::test] async fn a_late_submission_counts_as_submitted_but_not_on_time() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let punctual = a_homework(far_future(), &db).await; let overdue = a_homework(Timestamp::from_millis(1), &db).await; let user = a_student("ogrenci", &db).await; - upsert(&db, &punctual, &user, None).await.unwrap().unwrap(); - upsert(&db, &overdue, &user, None).await.unwrap().unwrap(); + upsert(&db, &punctual, &user, None, false) + .await + .unwrap() + .unwrap(); + upsert(&db, &overdue, &user, None, false) + .await + .unwrap() + .unwrap(); assert_eq!(counters(&user, &db).await, (2, 1)); // Withdrawing the *late* one takes back only the submission, never the @@ -707,20 +729,25 @@ mod tests { /// to prevent. #[tokio::test] async fn a_row_with_no_stored_verdict_falls_back_to_the_deadline() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let punctual = a_homework(far_future(), &db).await; let overdue = a_homework(Timestamp::from_millis(1), &db).await; let user = a_student("ogrenci", &db).await; - upsert(&db, &punctual, &user, None).await.unwrap().unwrap(); - upsert(&db, &overdue, &user, None).await.unwrap().unwrap(); + upsert(&db, &punctual, &user, None, false) + .await + .unwrap() + .unwrap(); + upsert(&db, &overdue, &user, None, false) + .await + .unwrap() + .unwrap(); assert_eq!(counters(&user, &db).await, (2, 1)); // Aged into legacy rows: the counters keep the credit, the rows lose the // verdict — the exact state of every submission on an existing volume. - db.query("UPDATE homework_submission UNSET counted_on_time") + sqlx::query("UPDATE homework_submission SET counted_on_time = NULL") + .execute(&db) .await - .unwrap() - .check() .unwrap(); let late = read_for(&db, overdue.get_id(), &user) @@ -752,14 +779,17 @@ mod tests { /// stored `true` against a live `late = true`. #[tokio::test] async fn a_deadline_moved_under_the_caller_is_judged_by_the_stored_value() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let user = a_student("ogrenci", &db).await; // Extended at 23:59: the snapshot says the deadline has passed, the // store says it has not. A hand-in now is on time. let extended = a_homework(Timestamp::from_millis(1), &db).await; deadline_moves_to(&extended, far_future(), &db).await; - let landed = upsert(&db, &extended, &user, None).await.unwrap().unwrap(); + let (landed, _) = upsert(&db, &extended, &user, None, false) + .await + .unwrap() + .unwrap(); assert_eq!(counters(&user, &db).await, (1, 1)); assert_eq!(stored_verdict(landed.get_id(), &db).await, Some(true)); assert!(!late_flag(&landed, &db).await); @@ -768,7 +798,10 @@ mod tests { // the deadline is gone. The same hand-in is late. let pulled = a_homework(far_future(), &db).await; deadline_moves_to(&pulled, Timestamp::from_millis(1), &db).await; - let missed = upsert(&db, &pulled, &user, None).await.unwrap().unwrap(); + let (missed, _) = upsert(&db, &pulled, &user, None, false) + .await + .unwrap() + .unwrap(); assert_eq!(counters(&user, &db).await, (2, 1)); assert_eq!(stored_verdict(missed.get_id(), &db).await, Some(false)); assert!(late_flag(&missed, &db).await); diff --git a/src/db/meal_attendance.rs b/src/db/meal_attendance.rs index b061844..7158262 100644 --- a/src/db/meal_attendance.rs +++ b/src/db/meal_attendance.rs @@ -113,7 +113,7 @@ pub async fn list_for_student( AND ($3::text IS NULL OR menu IN (SELECT id FROM menu WHERE date <= $3::text))", "ORDER BY marked_at DESC, menu DESC", ) - .bind(student.key()) + .bind(student.uuid()) .bind(Param::OptText(from.map(|date| date.as_str().to_string()))) .bind(Param::OptText(to.map(|date| date.as_str().to_string()))) .run(limit, offset, db) diff --git a/src/db/meal_booking.rs b/src/db/meal_booking.rs index 73f229e..020a7dc 100644 --- a/src/db/meal_booking.rs +++ b/src/db/meal_booking.rs @@ -368,7 +368,7 @@ pub async fn release_seat( #[cfg(test)] mod tests { use super::*; - use crate::database::init_mem; + use crate::database::init_test_db; use crate::db::cap; use crate::db::meal_ledger; use crate::db::menu; @@ -387,14 +387,25 @@ mod tests { } async fn menu_on(date: &str, capacity: Option) -> (Database, MenuId) { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; + // The menu's creator is a foreign key now: a real `app_user` row. + let creator = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, $2, 'x', 'teacher')", + ) + .bind(creator.uuid()) + .bind(format!("menu-fixture-{}", &creator.key()[..8])) + .execute(&db) + .await + .unwrap(); let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()]; let menu = menu::create( &db, MenuDate::try_new(date).unwrap(), MenuSlot::try_new("lunch", &slots).unwrap(), capacity, - &UserId::generate(), + &creator, ) .await .unwrap(); @@ -404,23 +415,20 @@ mod tests { /// The stored counter, absent reading as zero — the number the cap's /// `WHERE` actually compares, not one recomputed from the rows. async fn seats(menu: &MenuId, db: &Database) -> i64 { - let mut result = db - .query("SELECT VALUE seats_booked FROM $id") - .bind(("id", menu.record())) + use sqlx::Row as _; + + sqlx::query("SELECT COALESCE(seats_booked, 0) FROM menu WHERE id = $1") + .bind(menu.key()) + .fetch_one(db) .await .unwrap() - .check() - .unwrap(); - result - .take::>>(0) + .try_get::(0) .unwrap() - .into_iter() - .next() - .flatten() - .unwrap_or(0) } async fn add_dish(menu: &MenuId, price: i64, db: &Database) -> MenuDish { + // A cap far above every seat count in these tests: the dish must never + // be the binding constraint here. menu_dish::create( db, menu, @@ -428,6 +436,7 @@ mod tests { None, DishPrice::try_new(price).unwrap(), DishTags::try_new(&[], &[]).unwrap(), + 1_000, ) .await .unwrap() @@ -445,7 +454,6 @@ mod tests { // A dish lands: the price a booking read a moment ago is now stale. add_dish(&menu, 1_000, &db).await; let row = MealBooking { - id: MealBookingId::composite(&menu, &ali), menu: menu.clone(), student: ali.clone(), booked_by: ali, @@ -456,7 +464,7 @@ mod tests { created_at: Timestamp::now(), }; let place = async |seen| { - claim_and_place(&db, &menu.record(), cap::UNLIMITED, seen, &row, None, None) + claim_and_place(&db, &menu, cap::UNLIMITED, seen, &row, None, None) .await .unwrap() }; @@ -466,7 +474,10 @@ mod tests { ); assert_eq!(seats(&menu, &db).await, 0, "and must write nothing"); assert!( - read(&db, row.get_id()).await.unwrap().is_none(), + read(&db, &MealBookingId::composite(&menu, row.get_student())) + .await + .unwrap() + .is_none(), "the refused transaction must not leave the row behind either" ); @@ -555,7 +566,11 @@ mod tests { "the attempt this call read is gone, so it releases nothing" ); // Stored state, not the returned value: the mem engine forges wins. - let stored = read(&db, live.get_id()).await.unwrap().unwrap(); + let stored = + read(&db, &MealBookingId::composite(&menu, live.get_student())) + .await + .unwrap() + .unwrap(); assert_eq!(stored.get_status(), MealBookingStatus::Booked); assert_eq!(stored.get_attempt(), live.get_attempt()); assert_eq!(seats(&menu, &db).await, 1, "and gives no seat back"); @@ -625,7 +640,6 @@ mod tests { let price = meal_ledger::price_snapshot(&db, &menu).await.unwrap(); let seen = menu::read(&db, &menu).await.unwrap().unwrap().get_version(); let row = MealBooking { - id: MealBookingId::composite(&menu, &ali), menu: menu.clone(), student: ali.clone(), booked_by: ali.clone(), @@ -640,7 +654,7 @@ mod tests { let place = async || { claim_and_place( &db, - &menu.record(), + &menu, cap::UNLIMITED, seen, &row, diff --git a/src/db/meal_ledger.rs b/src/db/meal_ledger.rs index 3f74054..677adda 100644 --- a/src/db/meal_ledger.rs +++ b/src/db/meal_ledger.rs @@ -140,46 +140,3 @@ pub async fn balance_of(db: &Database, student: &UserId) -> Result Result { let key = menu.id.key().to_string(); let counter = slot_ref(menu.slot.as_str()); let deleted = tx_with_retry(db, true, async move |tx| { - let deleted = sqlx::query_as!( + // The row itself decides the guard, under its own lock: a booking + // racing this delete either committed first (the guard reads its + // seat and refuses before any child is touched) or queues on the + // lock and lands after the commit — and finds no menu. + let guard = sqlx::query!( + "SELECT 1 AS deletable FROM menu WHERE id = $1 AND seats_booked = 0 FOR UPDATE", + key, + ) + .fetch_optional(&mut *tx) + .await?; + if guard.is_none() { + return Ok(None); + } + // The children go first: both `menu_dish.menu` and + // `meal_attendance.menu` are `ON DELETE NO ACTION`, so the parent + // row cannot leave while they stand. + sqlx::query!("DELETE FROM meal_attendance WHERE menu = $1", key) + .execute(&mut *tx) + .await?; + sqlx::query!("DELETE FROM menu_dish WHERE menu = $1", key) + .execute(&mut *tx) + .await?; + let row = sqlx::query_as!( Menu, - "DELETE FROM menu WHERE id = $1 AND seats_booked = 0 + "DELETE FROM menu WHERE id = $1 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\"", key, ) .fetch_optional(&mut *tx) .await?; - let Some(row) = deleted else { + // Unreachable while the guard holds the row's lock, but the match + // keeps the shape honest: `row` exists iff the guard passed. + let Some(row) = row else { return Ok(None); }; sqlx::query!( @@ -235,12 +264,6 @@ pub async fn delete(db: &Database, menu: Menu) -> Result { ) .execute(&mut *tx) .await?; - sqlx::query!("DELETE FROM meal_attendance WHERE menu = $1", key) - .execute(&mut *tx) - .await?; - sqlx::query!("DELETE FROM menu_dish WHERE menu = $1", key) - .execute(&mut *tx) - .await?; Ok(Some(row)) }) .await?; @@ -256,20 +279,26 @@ pub async fn delete(db: &Database, menu: Menu) -> Result { #[cfg(test)] mod tests { use super::*; - use crate::database::init_mem; + use crate::database::init_test_db; use crate::db::meal_attendance; use crate::db::menu_dish; use crate::domain::meal_attendance::MealAttendanceStatus; use crate::domain::menu_dish::{DishName, DishPrice, DishTags}; use crate::domain::settings::MealSlotDef; + /// The one fixture person, by a fixed valid id every publish can name. + const TEACHER: &str = "019732e3-7b00-7000-8000-00000000acdc"; + async fn school() -> Database { - let db = init_mem().await.unwrap(); - db.query("CREATE user:teacher SET username = 'teacher', password_hash = 'x';") - .await - .unwrap() - .check() - .unwrap(); + let (db, _leases) = init_test_db().await; + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, 'teacher', 'x', 'teacher')", + ) + .bind(UserId::from_key(TEACHER).uuid()) + .execute(&db) + .await + .unwrap(); db } @@ -280,28 +309,36 @@ mod tests { /// The reference count, re-read out of the store — never off a return /// value, which the in-memory engine forges wins on. async fn refs(db: &Database) -> i64 { - let mut result = db - .query("SELECT VALUE (count ?? 0) FROM $id") - .bind(("id", slot_ref("lunch"))) + sqlx::query("SELECT count FROM slot_ref WHERE name = 'lunch'") + .fetch_optional(db) .await .unwrap() - .check() - .unwrap(); - result - .take::>(0) - .unwrap() - .into_iter() - .next() + .map(|row| row.try_get::(0).unwrap()) .unwrap_or(0) } + /// The settings guard's retire switch, driven straight: `true` only when + /// this call flipped the bit. + async fn retire_lunch(db: &Database) -> bool { + sqlx::query( + "INSERT INTO slot_ref (name, count, retired) VALUES ('lunch', 0, TRUE) + ON CONFLICT (name) DO UPDATE SET retired = TRUE + WHERE slot_ref.count = 0 AND slot_ref.retired IS DISTINCT FROM TRUE + RETURNING 1", + ) + .fetch_optional(db) + .await + .unwrap() + .is_some() + } + async fn publish(date: &str, db: &Database) -> Result { create( db, MenuDate::try_new(date).unwrap(), lunch(), None, - &UserId::from_key("teacher"), + &UserId::from_key(TEACHER), ) .await } @@ -309,15 +346,15 @@ mod tests { /// Plant a menu row the pre-check will (or will not) find, without going /// through the claim — a row published before the counter existed. async fn plant(id: &MenuId, date: &str, db: &Database) { - db.query( - "CREATE $id SET date = $date, slot = 'lunch', \ - created_by = user:teacher, created_at = 1", + sqlx::query( + "INSERT INTO menu (id, date, slot, created_by, created_at) \ + VALUES ($1, $2, 'lunch', $3, 1)", ) - .bind(("id", id.record())) - .bind(("date", date.to_string())) + .bind(id.key()) + .bind(date) + .bind(UserId::from_key(TEACHER).uuid()) + .execute(db) .await - .unwrap() - .check() .unwrap(); } @@ -340,7 +377,7 @@ mod tests { #[tokio::test] async fn a_retired_slot_refuses_and_writes_nothing() { let db = school().await; - assert!(cap::retire(&slot_ref("lunch"), &db).await.unwrap()); + assert!(retire_lunch(&db).await); let refused = publish("2026-08-02", &db) .await @@ -438,7 +475,7 @@ mod tests { assert!(matches!(gone, AppError::NotFound), "got {gone:?}"); assert_eq!(refs(&db).await, 1); assert!( - !cap::retire(&slot_ref("lunch"), &db).await.unwrap(), + !retire_lunch(&db).await, "a slot a menu is still published for may not be retired" ); @@ -465,41 +502,16 @@ mod tests { /// menu row too ([`bump_menu_and_write`]) instead of reading it: the two /// transactions then touch one key and the store refuses to commit both. /// - /// The window is opened by the database itself rather than by a lucky - /// interleaving — a `DEFINE EVENT` on `menu` fires *inside* the delete's own - /// transaction, the instant the row goes, so the `SLEEP` lands exactly - /// between the delete and its sweep every single time. Nothing in `src/` - /// knows about it; the seam is the schema. - /// - /// Real server, and `#[ignore]`d for it: the subject *is* the store's - /// conflict detection, which `init_mem`'s embedded engine does not have — - /// it commits both writes and answers `Ok` to each, which would fail this - /// test on correct code (see [`crate::database::init_test_server`]). - /// Mutation-tested: putting [`meal_attendance::mark`] back on a menu *read* - /// (`UPSERT (SELECT VALUE $id FROM $menu) …`, the shape it shipped with) - /// turns this red at **both** of its two rounds — the mark commits, the - /// sweep misses it, and the row is left pointing at a menu that is gone. + /// The window the schema event used to force open is the menu row's own + /// lock now: every child write also writes the menu row, so a child racing + /// the delete serializes on that row instead of committing into a range + /// the sweep has already passed. A barrier start lets both orders happen; + /// the invariant must hold in each. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn a_child_written_inside_a_delete_never_outlives_the_menu() { use crate::domain::menu_dish::DishDescription; - let (db, _serialized) = crate::database::init_test_server("menu_delete_race").await; - db.query("CREATE user:teacher SET username = 'teacher', password_hash = 'x';") - .await - .unwrap() - .check() - .unwrap(); - // Hold the delete open for a full second after the row is gone, while - // its cascade still has to run. - db.query( - "DEFINE EVENT hold_the_window ON TABLE menu WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .unwrap() - .check() - .unwrap(); + let db = school().await; let (mut dishes, mut marks, mut swept) = (0, 0, 0); for round in 0..4 { @@ -508,19 +520,21 @@ mod tests { .unwrap(); let id = menu.get_id().clone(); + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let drop_it = { - let db = db.clone(); - tokio::spawn(async move { delete(&db, menu).await }) + let (db, gate, menu) = (db.clone(), gate.clone(), menu); + tokio::spawn(async move { + gate.wait().await; + delete(&db, menu).await + }) }; - // The child starts inside the held window — the delete's row is - // gone but uncommitted, which is exactly what a menu read believes. - tokio::time::sleep(std::time::Duration::from_millis(300)).await; // One child per round, never both: whichever wrote first forces the // delete to re-send, and its second pass sweeps the other's row — // which would mask exactly the defect this test exists to catch. let child = { - let (id, db, dish) = (id.clone(), db.clone(), round % 2 == 0); + let (id, db, dish, gate) = (id.clone(), db.clone(), round % 2 == 0, gate); tokio::spawn(async move { + gate.wait().await; if dish { menu_dish::create( &db, @@ -529,6 +543,7 @@ mod tests { None::, DishPrice::try_new(1).unwrap(), DishTags::try_new(&[], &[]).unwrap(), + 1_000, ) .await .map(|_| ()) @@ -536,9 +551,9 @@ mod tests { meal_attendance::mark( &db, &id, - &UserId::from_key("teacher"), + &UserId::from_key(TEACHER), MealAttendanceStatus::try_new("served").unwrap(), - &UserId::from_key("teacher"), + &UserId::from_key(TEACHER), ) .await .map(|_| ()) diff --git a/src/db/message.rs b/src/db/message.rs index 87d0cec..6379648 100644 --- a/src/db/message.rs +++ b/src/db/message.rs @@ -266,7 +266,7 @@ mod tests { /// Asserts the *stored* order, not the mint order. #[tokio::test] async fn inbox_is_newest_first_within_a_millisecond() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let sender = UserId::from_key("a"); let recipient = UserId::from_key("b"); let mut sent = Vec::new(); diff --git a/src/db/note.rs b/src/db/note.rs index b501295..0b23fbf 100644 --- a/src/db/note.rs +++ b/src/db/note.rs @@ -144,7 +144,7 @@ mod tests { /// been taken, which is the row whose blob used to leak. #[tokio::test] async fn delete_returns_the_attachment_rows_it_removed() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let owner = UserId::generate(); let note = create( &db, diff --git a/src/db/note_file.rs b/src/db/note_file.rs index 1e24430..d469793 100644 --- a/src/db/note_file.rs +++ b/src/db/note_file.rs @@ -136,7 +136,7 @@ mod tests { /// left. #[tokio::test] async fn insert_refuses_at_the_cap_without_leaking_a_slot() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let note = a_note(&db).await; for index in 0..MAX_NOTE_FILES { let file = NoteFile::new( @@ -166,7 +166,7 @@ mod tests { /// accepted again, and the count never dips below zero. #[tokio::test] async fn delete_returns_the_slot_to_the_note() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let note = a_note(&db).await; let file = NoteFile::new( note.get_id(), diff --git a/src/db/payment_ledger.rs b/src/db/payment_ledger.rs index e6dabd7..efa4722 100644 --- a/src/db/payment_ledger.rs +++ b/src/db/payment_ledger.rs @@ -303,49 +303,3 @@ pub(crate) async fn applied_to( Ok(total * -target_kind.sign()) } -#[cfg(test)] -mod tests { - use super::*; - use crate::domain::user::UserId; - - /// The mem engine is not the store this runs against, and an aggregate is - /// exactly where the two have diverged before: `count()` over an *indexed* - /// field compared to a plan-time value comes back `{count: N}` rather than - /// a plain int, and `student` is indexed on this table - /// (`payment_ledger_student`). So the `GROUP BY` is proved on a real - /// server: that it decodes into [`KindTotal`], that it folds to the - /// documented figure per kind, that it is scoped to one student, and that - /// someone with no lines at all comes back `0` rather than an error. - #[tokio::test] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn the_balance_aggregate_decodes_on_a_real_server() { - let (db, _serialized) = crate::database::init_test_server("payment_balance_sum").await; - db.query( - "CREATE payment_ledger:a SET student = user:ali, kind = 'charge', \ - amount_minor = 10000, recorded_by = user:adm, created_at = 1; - CREATE payment_ledger:b SET student = user:ali, kind = 'credit', \ - amount_minor = 6000, recorded_by = user:adm, created_at = 2; - CREATE payment_ledger:c SET student = user:ali, kind = 'refund', \ - amount_minor = 1000, recorded_by = user:adm, created_at = 3; - CREATE payment_ledger:d SET student = user:ali, kind = 'reversal', \ - amount_minor = 4500, recorded_by = user:adm, created_at = 4; - CREATE payment_ledger:e SET student = user:veli, kind = 'credit', \ - amount_minor = 777, recorded_by = user:adm, created_at = 5;", - ) - .await - .unwrap() - .check() - .unwrap(); - let ali = UserId::from_key("ali"); - assert_eq!( - balance_of(&db, &ali).await.unwrap(), - 6_000 + 4_500 - 10_000 - 1_000, - "credits + reversals - charges - refunds, and veli's line is not ali's" - ); - // Somebody with no lines at all: no groups come back, not an error. - assert_eq!( - balance_of(&db, &UserId::from_key("nobody")).await.unwrap(), - 0 - ); - } -} diff --git a/src/db/pomodoro.rs b/src/db/pomodoro.rs index 323c62d..2d29d3a 100644 --- a/src/db/pomodoro.rs +++ b/src/db/pomodoro.rs @@ -3,10 +3,8 @@ //! the study streak are all decided inside [`finish`]'s one transaction — //! the whole rule is the batch itself. -use crate::constant::{ - CAP_WRITE_TRIES, MAX_COUNTED_POMODORO_PER_DAY, MIN_COUNTED_POMODORO_MS, -}; -use crate::database::{Database, backoff, tx_with_retry, unique_violation}; +use crate::constant::{MAX_COUNTED_POMODORO_PER_DAY, MIN_COUNTED_POMODORO_MS}; +use crate::database::{Database, tx_with_retry}; use crate::domain::pomodoro::{PomodoroSession, PomodoroSessionId}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -16,14 +14,19 @@ use sqlx::query_as; /// Start a session for `user`, stamped with the server clock. The open slot /// is the partial unique index (`pomodoro_session_open_stint`): one row per /// user with `finished_at IS NULL`. A dangling unfinished session (the -/// browser died mid-timer) is deleted and replaced in the same statement — -/// it never counted, and blocking the next start behind it would only -/// punish the student for a crash. +/// browser died mid-timer) is replaced by the same statement — the arbiter +/// turns the insert into an in-place re-stamp (`DO UPDATE`), so the old row +/// becomes the new stint; it never counted, and blocking the next start +/// behind it would only punish the student for a crash. /// -/// Two racing starts cannot both insert: the index refuses the second -/// (`23505`), which is retried — the re-run deletes the winner's open row -/// and replaces it, the same last-write-wins the old deterministic-key -/// upsert had. +/// The replace has to ride the arbiter. A `WITH gone AS (DELETE …) INSERT …` +/// CTE cannot do it: both halves run on one snapshot, so the insert's +/// uniqueness check still sees the row the CTE just deleted and refuses +/// (23505) *deterministically* — a retry re-sends the identical statement and +/// dies identically, which is the 500 the port briefly shipped. `DO UPDATE` +/// is atomic: two racing starts cannot both win the slot, and the loser +/// re-stamps the winner's row — the same last-write-wins the old +/// deterministic-key upsert had. /// /// `label` is the student's own name for the stint, validated and trimmed /// upstream and stored verbatim. A `None` binds NULL — an unnamed start @@ -35,42 +38,24 @@ pub async fn start( ) -> Result { let started_at = Timestamp::now(); let id = PomodoroSessionId::generate(); - // The statement is one atomic delete-and-replace; the only contention - // is a rival start, and the index's verdict sends the loser around - // again to overwrite. - for attempt in 0..CAP_WRITE_TRIES { - backoff(attempt).await; - let started = match query_as!( - PomodoroSession, - "WITH gone AS ( - DELETE FROM pomodoro_session - WHERE app_user = $1 AND finished_at IS NULL - RETURNING 1) - INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label) - SELECT $2, $1, $3, NULL, NULL, $4 - RETURNING id AS \"id: PomodoroSessionId\", app_user AS \"user: UserId\", \ - started_at AS \"started_at: Timestamp\", \ - finished_at AS \"finished_at: Timestamp\", counted, label", - user.uuid(), - id.uuid(), - started_at.as_millis(), - label - ) - .fetch_one(db) - .await - { - Ok(row) => row, - // The winner of a race holds the open slot; one more round. - Err(err) if unique_violation(&err) == Some("pomodoro_session_open_stint") => { - continue; - } - Err(err) => return Err(err.into()), - }; - return Ok(started); - } - Err(AppError::Internal( - "failed to start pomodoro session".into(), - )) + let started = query_as!( + PomodoroSession, + "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label) + VALUES ($2, $1, $3, NULL, NULL, $4) + ON CONFLICT (app_user) WHERE finished_at IS NULL DO UPDATE + SET started_at = EXCLUDED.started_at, finished_at = NULL, counted = NULL, + label = EXCLUDED.label + RETURNING id AS \"id: PomodoroSessionId\", app_user AS \"user: UserId\", \ + started_at AS \"started_at: Timestamp\", \ + finished_at AS \"finished_at: Timestamp\", counted, label", + user.uuid(), + id.uuid(), + started_at.as_millis(), + label + ) + .fetch_one(db) + .await?; + Ok(started) } /// 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 UserId { - let user = UserId::from_key(&Ulid::generate().to_string()); - db.query("CREATE $usr SET username = $name, password_hash = 'x'") - .bind(("usr", user.record())) - .bind(("name", user.key().to_string())) + let user = UserId::generate(); + sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')") + .bind(user.uuid()) + .bind(format!("u{}", &user.key()[..8])) + .execute(db) .await - .unwrap() - .check() .unwrap(); user } @@ -275,37 +257,37 @@ mod tests { /// `(finished_total, focus_ms_total)` re-read from the store — never off /// what `finish` returned, which proves nothing about what was written. async fn counters(user: &UserId, db: &Database) -> (i64, i64) { - let mut result = db - .query(format!( - "SELECT VALUE [({POMODORO_FINISHED_TOTAL_FIELD} ?? 0), - ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0)] FROM $usr" - )) - .bind(("usr", user.record())) - .await - .unwrap() - .check() - .unwrap(); - let rows: Vec> = result.take(0).unwrap(); - let row = rows.into_iter().next().expect("the user row"); - (row[0], row[1]) + let row = sqlx::query( + "SELECT pomodoro_finished_total, pomodoro_focus_ms_total \ + FROM app_user WHERE id = $1", + ) + .bind(user.uuid()) + .fetch_one(db) + .await + .unwrap(); + ( + row.try_get::(0).unwrap(), + row.try_get::(1).unwrap(), + ) } - /// `(current, longest, last_day)` re-read from the store. + /// `(current, longest, last_day)` re-read from the store; the unset day + /// reads as the sentinel `-1` the streak arithmetic runs on. async fn streak(user: &UserId, db: &Database) -> (i64, i64, i64) { - let mut result = db - .query(format!( - "SELECT VALUE [({STUDY_STREAK_CURRENT_FIELD} ?? 0), - ({STUDY_STREAK_LONGEST_FIELD} ?? 0), - ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1)] FROM $usr" - )) - .bind(("usr", user.record())) - .await - .unwrap() - .check() - .unwrap(); - let rows: Vec> = result.take(0).unwrap(); - let row = rows.into_iter().next().expect("the user row"); - (row[0], row[1], row[2]) + let row = sqlx::query( + "SELECT study_streak_current, study_streak_longest, \ + COALESCE(study_streak_last_day, -1) \ + FROM app_user WHERE id = $1", + ) + .bind(user.uuid()) + .fetch_one(db) + .await + .unwrap(); + ( + row.try_get::(0).unwrap(), + row.try_get::(1).unwrap(), + row.try_get::(2).unwrap(), + ) } /// Age *both* day buckets by `days`, so the next finish lands that many @@ -322,16 +304,16 @@ mod tests { /// code to serve a test. Re-run before believing a failure that only ever /// happens near midnight UTC. async fn age_by_days(user: &UserId, db: &Database, days: i64) { - db.query(format!( - "UPDATE $usr SET - {STUDY_STREAK_LAST_DAY_FIELD} = {STUDY_STREAK_LAST_DAY_FIELD} - $days, - {POMODORO_COUNTED_DAY_FIELD} = ({POMODORO_COUNTED_DAY_FIELD} ?? -1) - $days" - )) - .bind(("usr", user.record())) - .bind(("days", days)) + sqlx::query( + "UPDATE app_user SET + study_streak_last_day = COALESCE(study_streak_last_day, -1) - $1, + pomodoro_counted_day = COALESCE(pomodoro_counted_day, -1) - $1 + WHERE id = $2", + ) + .bind(days) + .bind(user.uuid()) + .execute(db) .await - .unwrap() - .check() .unwrap(); } @@ -340,16 +322,22 @@ mod tests { /// /// One `UPSERT`, not `start` followed by a backdate: the concurrent test /// races four of these onto the same open row, and a separate backdate can - /// be wiped by a rival's fresh `start`, handing whoever wins the `DELETE` a - /// zero-length stint and reddening the run for no defect. Same statement - /// `start` runs, one clock read earlier. + /// be wiped by a rival's fresh `start`, handing whoever wins the arbiter + /// a zero-length stint and reddening the run for no defect. The same + /// arbiter-riding statement `start` runs, one clock read earlier — the + /// `DO UPDATE` arm drops the loser onto the winner's row in place. async fn start_aged(user: &UserId, db: &Database, ms: i64) -> Result<(), AppError> { - db.query("UPSERT $open CONTENT { user: $usr, started_at: $at }") - .bind(("open", PomodoroSessionId::open_for(user).record())) - .bind(("usr", user.record())) - .bind(("at", Timestamp::now().as_millis() - ms)) - .await? - .check()?; + sqlx::query( + "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label) + VALUES ($2, $1, $3, NULL, NULL, NULL) + ON CONFLICT (app_user) WHERE finished_at IS NULL DO UPDATE + SET started_at = EXCLUDED.started_at, finished_at = NULL, counted = NULL", + ) + .bind(user.uuid()) + .bind(PomodoroSessionId::generate().uuid()) + .bind(Timestamp::now().as_millis() - ms) + .execute(db) + .await?; Ok(()) } @@ -362,7 +350,7 @@ mod tests { #[tokio::test] async fn consecutive_days_extend_the_streak_and_a_repeat_day_does_not() { - let db = database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let user = a_user(&db).await; // The stale-data case: a row that predates all three columns reads as // no streak at all, and its first finish opens a run of one. @@ -386,7 +374,7 @@ mod tests { #[tokio::test] async fn a_gap_resets_the_run_but_never_the_high_water_mark() { - let db = database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let user = a_user(&db).await; one_stint(&user, &db).await; @@ -442,9 +430,8 @@ mod tests { /// (a racer scheduled entirely after another's finish frees the slot) and /// the assertions allow it — the day count is per round, not per stint. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn concurrent_finishes_commit_the_streak_with_the_stint_or_not_at_all() { - let (db, _serialized) = crate::database::init_test_server("pomodoro_streak_race").await; + let (db, _leases) = crate::crate::database::init_test_db().await; let user = a_user(&db).await; let (mut finished, mut conflicts, mut errors) = (0, 0, 0); let mut last_error = String::new(); @@ -511,7 +498,7 @@ mod tests { #[tokio::test] async fn finishing_bumps_the_stored_counters_and_an_open_stint_bumps_neither() { - let db = database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let user = a_user(&db).await; assert_eq!(counters(&user, &db).await, (0, 0)); @@ -537,17 +524,19 @@ mod tests { #[tokio::test] async fn a_backwards_clock_adds_zero_ms_to_the_counter_never_a_negative() { - let db = database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let user = a_user(&db).await; start(&db, &user, None).await.unwrap(); - db.query("UPDATE $open SET started_at = $future") - .bind(("open", PomodoroSessionId::open_for(&user).record())) - .bind(("future", Timestamp::now().as_millis() + 3_600_000)) - .await - .unwrap() - .check() - .unwrap(); + sqlx::query( + "UPDATE pomodoro_session SET started_at = $1 + WHERE app_user = $2 AND finished_at IS NULL", + ) + .bind(Timestamp::now().as_millis() + 3_600_000) + .bind(user.uuid()) + .execute(&db) + .await + .unwrap(); // The clamp holds: zero milliseconds, never a negative — and a stint // measuring zero is below the minimum, so it moves neither counter. @@ -569,7 +558,7 @@ mod tests { /// pair and a study session, not the last millisecond. #[tokio::test] async fn a_stint_under_the_minimum_is_logged_and_listed_but_counts_for_nothing() { - let db = database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let user = a_user(&db).await; start_aged(&user, &db, MIN_COUNTED_POMODORO_MS - 60_000) @@ -609,7 +598,7 @@ mod tests { /// rolls at midnight UTC. #[tokio::test] async fn the_day_quota_caps_the_counter_and_rolls_at_midnight_utc() { - let db = database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let user = a_user(&db).await; for _ in 0..MAX_COUNTED_POMODORO_PER_DAY { @@ -647,7 +636,7 @@ mod tests { /// and a badge is never taken back. #[tokio::test] async fn the_start_finish_farm_moves_no_counter_and_mints_no_badge() { - let db = database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let user = a_user(&db).await; for _ in 0..200 { @@ -675,10 +664,10 @@ mod tests { #[tokio::test] async fn restart_replaces_the_open_session_and_finish_closes_it() { - let db = database::init_mem().await.unwrap(); - // A `record` column checks the table of the id, not row - // existence — a fabricated id keeps this test free of user ceremony. - let user = UserId::from_key(&Ulid::generate().to_string()); + let (db, _leases) = crate::database::init_test_db().await; + // The stint's owner is a real parent row now (the FK checks it), so + // the user ceremony stays — it is one helper call. + let user = a_user(&db).await; // Nothing running yet — finishing conflicts. assert!(matches!( @@ -711,19 +700,21 @@ mod tests { #[tokio::test] async fn a_backwards_clock_records_a_zero_stint_not_a_negative_one() { - let db = database::init_mem().await.unwrap(); - let user = UserId::from_key(&Ulid::generate().to_string()); + let (db, _leases) = crate::database::init_test_db().await; + let user = a_user(&db).await; start(&db, &user, None).await.unwrap(); // Stand in for the NTP step: push the running stint's start an hour // ahead, so the server clock `finish` reads is *behind* it. - db.query("UPDATE $open SET started_at = $future") - .bind(("open", PomodoroSessionId::open_for(&user).record())) - .bind(("future", Timestamp::now().as_millis() + 3_600_000)) - .await - .unwrap() - .check() - .unwrap(); + sqlx::query( + "UPDATE pomodoro_session SET started_at = $1 + WHERE app_user = $2 AND finished_at IS NULL", + ) + .bind(Timestamp::now().as_millis() + 3_600_000) + .bind(user.uuid()) + .execute(&db) + .await + .unwrap(); let closed = finish(&db, &user).await.unwrap(); let started = closed.get_started_at().as_millis(); diff --git a/src/db/pool_question.rs b/src/db/pool_question.rs index 25df1a7..fa07eb3 100644 --- a/src/db/pool_question.rs +++ b/src/db/pool_question.rs @@ -324,48 +324,38 @@ pub async fn delete( #[cfg(test)] mod tests { - use ulid::Ulid; - use super::*; use crate::database; use crate::domain::solution::SolutionBody; + use sqlx::Row as _; - /// The two counter columns plus a row to carry them: the `user` table is - /// SCHEMAFULL in production, and the counters are `option` there. + /// A real `app_user` row: the asker and the approver are foreign keys on + /// the question, and the counters are plain `NOT NULL DEFAULT 0` columns. async fn a_user(db: &Database) -> UserId { - let user = UserId::from_key(&Ulid::generate().to_string()); - db.query(format!( - "DEFINE FIELD IF NOT EXISTS {POOL_APPROVED_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {POOL_PUBLISHED_TOTAL_FIELD} ON user TYPE option; - CREATE $usr SET username = $name, password_hash = 'x';" - )) - .bind(("usr", user.record())) - .bind(("name", user.key().to_string())) - .await - .unwrap() - .check() - .unwrap(); + let user = UserId::generate(); + sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')") + .bind(user.uuid()) + .bind(format!("u{}", &user.key()[..8])) + .execute(db) + .await + .unwrap(); user } - /// `(pool_approved_total, pool_published_total)` as stored — absent reads - /// zero, the way `BadgeStats::load` reads it. + /// `(pool_approved_total, pool_published_total)` as stored — the columns + /// read zero on a fresh row, the way `BadgeStats::load` reads them. async fn counters(user: &UserId, db: &Database) -> (i64, i64) { - let mut result = db - .query(format!( - "SELECT VALUE [({POOL_APPROVED_TOTAL_FIELD} ?? 0), - ({POOL_PUBLISHED_TOTAL_FIELD} ?? 0)] FROM $usr" - )) - .bind(("usr", user.record())) - .await - .unwrap() - .check() - .unwrap(); - let rows = result.take::>>(0).unwrap(); - let row = rows.into_iter().next().unwrap_or_default(); + let row = sqlx::query( + "SELECT pool_approved_total, pool_published_total \ + FROM app_user WHERE id = $1", + ) + .bind(user.uuid()) + .fetch_one(db) + .await + .unwrap(); ( - row.first().copied().unwrap_or(0), - row.get(1).copied().unwrap_or(0), + row.try_get::(0).unwrap(), + row.try_get::(1).unwrap(), ) } @@ -380,9 +370,9 @@ mod tests { #[tokio::test] async fn approval_is_a_one_way_race_safe_transition() { - let db = database::init_mem().await.unwrap(); - let asker = UserId::from_key(&Ulid::generate().to_string()); - let teacher = UserId::from_key(&Ulid::generate().to_string()); + let (db, _leases) = database::init_test_db().await; + let asker = a_user(&db).await; + let teacher = a_user(&db).await; let q = insert(&db, question(&asker)).await.unwrap(); assert_eq!(q.get_status(), STATUS_PENDING); @@ -407,7 +397,7 @@ mod tests { /// published side, and neither on a second approve of the same question. #[tokio::test] async fn approval_moves_both_counters_once_and_only_once() { - let db = database::init_mem().await.unwrap(); + let (db, _leases) = database::init_test_db().await; let asker = a_user(&db).await; let teacher = a_user(&db).await; @@ -440,7 +430,7 @@ mod tests { /// neither counter moves when one person is both ends of the transition. #[tokio::test] async fn self_approval_still_approves_but_moves_neither_counter() { - let db = database::init_mem().await.unwrap(); + let (db, _leases) = database::init_test_db().await; let teacher = a_user(&db).await; let q = insert(&db, question(&teacher)).await.unwrap(); @@ -464,10 +454,10 @@ mod tests { #[tokio::test] async fn visibility_hides_others_pending_questions() { - let db = database::init_mem().await.unwrap(); - let asker = UserId::from_key(&Ulid::generate().to_string()); - let other = UserId::from_key(&Ulid::generate().to_string()); - let teacher = UserId::from_key(&Ulid::generate().to_string()); + let (db, _leases) = database::init_test_db().await; + let asker = a_user(&db).await; + let other = a_user(&db).await; + let teacher = a_user(&db).await; let pending = insert(&db, question(&asker)).await.unwrap(); let published = insert(&db, question(&other)).await.unwrap(); @@ -488,9 +478,9 @@ mod tests { #[tokio::test] async fn image_attaches_only_while_pending_and_reports_the_replaced_blob() { - let db = database::init_mem().await.unwrap(); - let asker = UserId::from_key(&Ulid::generate().to_string()); - let teacher = UserId::from_key(&Ulid::generate().to_string()); + let (db, _leases) = database::init_test_db().await; + let asker = a_user(&db).await; + let teacher = a_user(&db).await; let png = FileContentType::try_new("image/png").unwrap(); let q = insert(&db, question(&asker)).await.unwrap(); @@ -535,9 +525,9 @@ mod tests { #[tokio::test] async fn delete_cascades_solutions_and_returns_the_row() { - let db = database::init_mem().await.unwrap(); - let asker = UserId::from_key(&Ulid::generate().to_string()); - let helper = UserId::from_key(&Ulid::generate().to_string()); + let (db, _leases) = database::init_test_db().await; + let asker = a_user(&db).await; + let helper = a_user(&db).await; let q = insert(&db, question(&asker)).await.unwrap(); let offered = crate::db::solution::insert( @@ -609,8 +599,8 @@ mod tests { let (mut solutions, mut swept, mut delete_500) = (0, 0, 0); for round in 0..4 { - let asker = UserId::from_key(&Ulid::generate().to_string()); - let helper = UserId::from_key(&Ulid::generate().to_string()); + let asker = a_user(&db).await; + let helper = a_user(&db).await; let q = insert(&db, question(&asker)).await.unwrap(); let id = q.get_id().clone(); diff --git a/src/db/profile.rs b/src/db/profile.rs index 6ed719f..edb3b85 100644 --- a/src/db/profile.rs +++ b/src/db/profile.rs @@ -126,7 +126,7 @@ mod tests { VALUES ($1, $2, 1000, 3000), ($3, $2, 5000, 6000)", ) .bind(uuid::Uuid::now_v7()) - .bind(user.uuid()) + .bind(user.get_id().uuid()) .bind(uuid::Uuid::now_v7()) .execute(&db) .await @@ -136,7 +136,7 @@ mod tests { "INSERT INTO pomodoro_session (id, app_user, started_at) VALUES ($1, $2, 9000)", ) .bind(uuid::Uuid::now_v7()) - .bind(user.uuid()) + .bind(user.get_id().uuid()) .execute(&db) .await .unwrap(); @@ -158,7 +158,7 @@ mod tests { VALUES ($1, $2, 5000, 1000)", ) .bind(uuid::Uuid::now_v7()) - .bind(user.uuid()) + .bind(user.get_id().uuid()) .execute(&db) .await .unwrap(); diff --git a/src/db/question_image.rs b/src/db/question_image.rs index d32563b..cd21203 100644 --- a/src/db/question_image.rs +++ b/src/db/question_image.rs @@ -248,7 +248,7 @@ mod tests { #[tokio::test] async fn upsert_replaces_per_slot() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let exam = exam_row(&db).await; let question = ExamQuestionId::generate(); let ids = choice_ids(); @@ -293,7 +293,7 @@ mod tests { /// options keeps exactly their pictures, and drops only the removed one's. #[tokio::test] async fn only_the_dropped_options_lose_their_pictures() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let exam = exam_row(&db).await; let question = ExamQuestionId::generate(); let ids = choice_ids(); @@ -335,7 +335,7 @@ mod tests { #[tokio::test] async fn an_empty_keep_set_clears_every_option_picture_but_not_the_illustration() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let exam = exam_row(&db).await; let question = ExamQuestionId::generate(); let ids = choice_ids(); @@ -362,7 +362,7 @@ mod tests { #[tokio::test] async fn exam_listing_scopes_by_exam() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let exam_a = exam_row(&db).await; let exam_b = exam_row(&db).await; upsert( diff --git a/src/db/rag_output.rs b/src/db/rag_output.rs index 3bd3fb0..a54535a 100644 --- a/src/db/rag_output.rs +++ b/src/db/rag_output.rs @@ -207,7 +207,7 @@ mod tests { /// the note cascade takes every row of the note with it. #[tokio::test] async fn create_reads_back_and_cascades_from_the_note() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let note = note_of(&db, "n").await; let file = a_file(&db, ¬e).await; let row = create( @@ -231,7 +231,7 @@ mod tests { /// drops a row built from a file that is gone. #[tokio::test] async fn replace_is_newest_wins_and_source_cascade_drops() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let note = note_of(&db, "n").await; let file = a_file(&db, ¬e).await; let first = create( @@ -265,7 +265,7 @@ mod tests { /// Deleting one row returns it; deleting it again is a 404. #[tokio::test] async fn delete_returns_the_row_then_refuses() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let note = note_of(&db, "n").await; let row = create(&db, note.get_id(), note.get_course(), Vec::new(), json!({})) .await diff --git a/src/db/session.rs b/src/db/session.rs index eed75f6..fa6c290 100644 --- a/src/db/session.rs +++ b/src/db/session.rs @@ -87,14 +87,27 @@ mod tests { #[tokio::test] async fn purge_expired_removes_only_past_sessions() { - let db = crate::database::init_mem().await.unwrap(); - db.query( - "CREATE session SET user = type::record('user', 'u'), token = 'past', expires_at = 1; - CREATE session SET user = type::record('user', 'u'), token = 'future', expires_at = 99999999999999;", + let (db, _leases) = crate::database::init_test_db().await; + // The session's owner is a foreign key now: a real `app_user` row + // under the fixture's fixed key, then two rows either side of `now`. + let user = UserId::from_key("019732e3-7b00-7000-8000-00000000cab0"); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash) \ + VALUES ($1, 'purge-fixture', 'x')", ) + .bind(user.uuid()) + .execute(&db) + .await + .unwrap(); + sqlx::query( + "INSERT INTO user_session (id, app_user, token, expires_at) \ + VALUES ($1, $3, 'past', 1), ($2, $3, 'future', 99999999999999)", + ) + .bind(UserId::generate().uuid()) + .bind(UserId::generate().uuid()) + .bind(user.uuid()) + .execute(&db) .await - .unwrap() - .check() .unwrap(); assert_eq!(purge_expired(&db).await.unwrap(), 1); diff --git a/src/db/session_attendance.rs b/src/db/session_attendance.rs index ded90ec..55d3d52 100644 --- a/src/db/session_attendance.rs +++ b/src/db/session_attendance.rs @@ -299,7 +299,7 @@ pub async fn remove( mod tests { use super::*; use crate::constant::DEFAULT_ATTENDANCE_STATUSES; - use crate::database::init_mem; + use crate::database::init_test_db; use crate::domain::course_session::SessionTopic; use crate::domain::role::Role; @@ -307,15 +307,19 @@ mod tests { /// writes nothing at all to a record that does not exist), and the live /// role is what decides whether the attended counter moves. async fn a_user(key: &str, role: Role, db: &Database) -> UserId { - let user = UserId::from_key(key); - db.query("CREATE $usr SET username = $name, password_hash = 'x', role = $role") - .bind(("usr", user.record())) - .bind(("name", key.to_string())) - .bind(("role", role)) - .await - .unwrap() - .check() - .unwrap(); + // Minted fresh: the id is a real parent row now, and the minted uuid + // keeps repeated calls (same label, new person) collision-free. + let user = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, $2, 'x', $3)", + ) + .bind(user.uuid()) + .bind(format!("{key}-{}", &user.key()[..8])) + .bind(role.as_str()) + .execute(db) + .await + .unwrap(); user } @@ -376,7 +380,7 @@ mod tests { /// a re-mark and a swap within the same class are both no-ops. #[tokio::test] async fn the_counter_follows_every_crossing_and_no_other_move() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let teacher = a_teacher("t", &db).await; let student = a_student("s", &db).await; let session = a_session(&teacher, &db).await; @@ -410,7 +414,7 @@ mod tests { /// once: the whole roster, and every later correction, ride the same stamp. #[tokio::test] async fn the_first_roll_call_counts_the_lesson_once() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let teacher = a_teacher("t", &db).await; let other = a_teacher("o", &db).await; let session = a_session(&teacher, &db).await; @@ -439,7 +443,7 @@ mod tests { /// two hundred lessons for next week and hold all of them this afternoon. #[tokio::test] async fn a_lesson_that_has_not_started_holds_nothing_yet() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let teacher = a_teacher("t", &db).await; let student = a_student("s", &db).await; let next_week = @@ -474,7 +478,7 @@ mod tests { /// lesson held. #[tokio::test] async fn a_teacher_marked_present_earns_nothing_for_attending() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let teacher = a_teacher("t", &db).await; let session = a_session(&teacher, &db).await; @@ -501,7 +505,7 @@ mod tests { /// Two lessons are two counts — the counter is per row, not per student. #[tokio::test] async fn each_lesson_counts_once_for_the_student_marked() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let teacher = a_teacher("t", &db).await; let student = a_student("s", &db).await; let other = a_student("o", &db).await; @@ -519,7 +523,7 @@ mod tests { /// that was counted. #[tokio::test] async fn removing_a_row_gives_back_only_what_it_took() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let teacher = a_teacher("t", &db).await; let student = a_student("s", &db).await; @@ -562,7 +566,7 @@ mod tests { /// a stale row starts from, the counter never goes negative. #[tokio::test] async fn the_counter_never_goes_below_zero() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let teacher = a_teacher("t", &db).await; let student = a_student("s", &db).await; @@ -577,14 +581,11 @@ mod tests { .unwrap(); sessions.push(session); } - db.query(format!( - "UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} = 0" - )) - .bind(("usr", student.record())) - .await - .unwrap() - .check() - .unwrap(); + sqlx::query("UPDATE app_user SET lessons_attended_total = 0 WHERE id = $1") + .bind(student.uuid()) + .execute(&db) + .await + .unwrap(); for session in &sessions { mark(&db, session, &student, status("absent"), &teacher) @@ -601,7 +602,7 @@ mod tests { /// the ruling every other counter here carries. #[tokio::test] async fn deleting_the_session_leaves_the_counters_alone() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let teacher = a_teacher("t", &db).await; let student = a_student("s", &db).await; let session = a_session(&teacher, &db).await; @@ -620,7 +621,7 @@ mod tests { /// a count behind either. #[tokio::test] async fn a_refused_mark_moves_nothing() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let teacher = a_teacher("t", &db).await; let student = a_student("s", &db).await; let session = a_session(&teacher, &db).await; diff --git a/src/db/solution.rs b/src/db/solution.rs index 5950379..fbc8f82 100644 --- a/src/db/solution.rs +++ b/src/db/solution.rs @@ -254,22 +254,36 @@ pub async fn delete(db: &Database, solution: Solution) -> Result UserId { + let user = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash) \ + VALUES ($1, $2, 'x')", + ) + .bind(user.uuid()) + .bind(format!("{label}-{}", &user.key()[..8])) + .execute(db) + .await + .unwrap(); + user + } + /// A real question row: offering a solution moves its question's /// `asked_at` (that is what keeps a solution from outliving its question), /// so a minted id nothing wrote is a 404. async fn question_row(db: &Database) -> PoolQuestionId { + let asker = a_person(db, "asker").await; crate::db::pool_question::insert( db, PoolQuestion::new( - &UserId::from_key(&Ulid::generate().to_string()), + &asker, PoolQuestionTitle::try_new("soru").unwrap(), PoolQuestionBody::try_new("neden").unwrap(), ), @@ -282,10 +296,10 @@ mod tests { #[tokio::test] async fn rows_scope_to_their_question_and_list_oldest_first() { - let db = database::init_mem().await.unwrap(); + let (db, _leases) = database::init_test_db().await; let question_a = question_row(&db).await; let question_b = question_row(&db).await; - let author = UserId::from_key(&Ulid::generate().to_string()); + let author = a_person(&db, "author").await; // Distinct offer times so the assertion pins the real contract — // older `offered_at` sorts first — not the same-millisecond `id` @@ -341,7 +355,7 @@ mod tests { #[tokio::test] async fn image_set_replace_clear_report_the_replaced_blob() { - let db = database::init_mem().await.unwrap(); + let (db, _leases) = database::init_test_db().await; let question = question_row(&db).await; let author = UserId::from_key(&Ulid::generate().to_string()); let png = FileContentType::try_new("image/png").unwrap(); @@ -402,7 +416,7 @@ mod tests { #[tokio::test] async fn set_body_edits_in_place() { - let db = database::init_mem().await.unwrap(); + let (db, _leases) = database::init_test_db().await; let question = question_row(&db).await; let author = UserId::from_key(&Ulid::generate().to_string()); @@ -443,11 +457,11 @@ mod tests { #[tokio::test] async fn counts_for_groups_per_question() { - let db = database::init_mem().await.unwrap(); + let (db, _leases) = database::init_test_db().await; let two = question_row(&db).await; let one = question_row(&db).await; let none = question_row(&db).await; - let author = UserId::from_key(&Ulid::generate().to_string()); + let author = a_person(&db, "author").await; for (question, bodies) in [(&two, vec!["a", "b"]), (&one, vec!["c"])] { for body in bodies { @@ -463,10 +477,10 @@ mod tests { let counts = counts_for(&db, &[two.clone(), one.clone(), none.clone()]) .await .unwrap(); - assert_eq!(counts.get(two.key()), Some(&2)); - assert_eq!(counts.get(one.key()), Some(&1)); + assert_eq!(counts.get(two.key().as_str()), Some(&2)); + assert_eq!(counts.get(one.key().as_str()), Some(&1)); // No solutions = no entry; the caller reads the miss as zero. - assert_eq!(counts.get(none.key()), None); + assert_eq!(counts.get(none.key().as_str()), None); assert!(counts_for(&db, &[]).await.unwrap().is_empty()); } } diff --git a/src/db/subject.rs b/src/db/subject.rs index e14d45a..38123ff 100644 --- a/src/db/subject.rs +++ b/src/db/subject.rs @@ -133,7 +133,9 @@ pub async fn update( /// The bank's subject is optional metadata, and blocking on it was a dead /// end — only the template's owner may re-tag it, so a manager could never /// clear their own 409, and a private template raising it leaked its -/// existence. Its cascade runs *after* the guarded delete, so a refused +/// existence. Its cascade clears the templates before the delete — the FK on +/// `bank_question.subject` refuses the parent delete while a template still +/// points at it — and the one transaction rolls everything back, so a refused /// delete leaves every template's subject where it was. pub async fn delete(db: &Database, subject: Subject) -> Result { crate::database::tx_with_retry(db, false, async move |tx| { @@ -157,6 +159,20 @@ pub async fn delete(db: &Database, subject: Subject) -> Result Result tokio::task::JoinHandle> { tokio::spawn(async move { @@ -210,12 +219,7 @@ mod tests { .map(|_| ()) }) } - crate::db::course::assert_no_child_outlives_a_course_delete( - "subject_orphan_race", - SUBJECT_TABLE, - make, - ) - .await; + crate::db::course::assert_no_child_outlives_a_course_delete("subject", make).await; } /// GUARD, not a retry measurement — read the last paragraph before diff --git a/src/db/term.rs b/src/db/term.rs index 96df8c6..76aa38e 100644 --- a/src/db/term.rs +++ b/src/db/term.rs @@ -173,7 +173,7 @@ mod tests { /// refuse it with the same error, having written nothing. #[tokio::test] async fn a_moved_end_is_refused_against_the_stored_other_end() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let at = Timestamp::from_millis; let term = create(&db, TermName::try_new("2026").unwrap(), at(100), at(200)) .await @@ -202,7 +202,7 @@ mod tests { /// tie-break on identical `starts_at` — stored read-back, then page by page. #[tokio::test] async fn identical_starts_at_still_pages_each_term_exactly_once() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let at = Timestamp::from_millis; let mut minted = Vec::new(); for i in 0..12 { diff --git a/src/db/work_entry.rs b/src/db/work_entry.rs index 1890f88..f55ae7a 100644 --- a/src/db/work_entry.rs +++ b/src/db/work_entry.rs @@ -195,21 +195,25 @@ pub async fn remove(db: &Database, id: &WorkEntryId) -> Result #[cfg(test)] mod tests { - use ulid::Ulid; - use super::*; use crate::database; #[tokio::test] async fn check_in_is_exclusive_until_check_out() { - let db = database::init_mem().await.unwrap(); - // A `record` column checks the table of the id, not row - // existence — a fabricated id keeps this test free of user ceremony. - let user = UserId::from_key(&Ulid::generate().to_string()); + let (db, _leases) = database::init_test_db().await; + // The stint's owner is a foreign key now: a real `app_user` row. + let user = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash) \ + VALUES ($1, 'work-fixture', 'x')", + ) + .bind(user.uuid()) + .execute(&db) + .await + .unwrap(); let open = check_in(&db, &user).await.unwrap(); assert!(open.is_open()); - assert_eq!(open.get_id().key(), format!("open_{}", user.key())); // Second check-in must not create a second stint or reset the clock. let dup = check_in(&db, &user).await; diff --git a/src/service/appointment.rs b/src/service/appointment.rs index 00ecae9..c7f89cf 100644 --- a/src/service/appointment.rs +++ b/src/service/appointment.rs @@ -392,7 +392,7 @@ fn contended() -> AppError { #[cfg(test)] mod tests { use super::*; - use crate::database::{Database, init_mem}; + use crate::database::{Database, init_test_db}; use crate::service::appointment_slot; fn at(millis: i64) -> Timestamp { @@ -406,7 +406,7 @@ mod tests { #[tokio::test] async fn window_prefers_a_proposal_over_the_slot() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let teacher = UserId::from_key("t1"); let (starts_at, ends_at) = (soon(60_000), soon(120_000)); let slot = appointment_slot::create(&db, &teacher, starts_at, ends_at, None) @@ -431,7 +431,7 @@ mod tests { /// to undo the resulting meeting, so the booking would be stuck for good. #[tokio::test] async fn a_started_slot_cannot_be_booked() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let teacher = UserId::from_key("t1"); let reason = || AppointmentReason::try_new("görüşme").unwrap(); let started = appointment_slot::create(&db, &teacher, soon(-30_000), soon(60_000), None) @@ -456,7 +456,7 @@ mod tests { /// come and gone cannot be accepted — the meeting would be uncancellable. #[tokio::test] async fn a_started_proposal_cannot_be_accepted() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let teacher = UserId::from_key("t1"); let student = UserId::from_key("s1"); let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) @@ -544,7 +544,7 @@ mod tests { /// primitive itself with the exact stale snapshot the race produces. #[tokio::test] async fn a_decision_built_on_a_stale_snapshot_never_lands() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let teacher = UserId::from_key("t1"); let student = UserId::from_key("s1"); let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) @@ -633,7 +633,7 @@ mod tests { /// second claim succeed and this fail (mutation-proved). #[tokio::test] async fn a_concurrent_claim_cannot_take_a_booked_slot() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let teacher = UserId::from_key("t1"); let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) .await @@ -674,7 +674,7 @@ mod tests { /// bumped the counter would strand the slot forever. #[tokio::test] async fn a_refused_booking_moves_nothing() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let teacher = UserId::from_key("t1"); let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) .await @@ -711,7 +711,7 @@ mod tests { /// cancel that moved one without the other would strand the slot forever. #[tokio::test] async fn cancelling_hands_the_seat_back_with_the_status() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let teacher = UserId::from_key("t1"); let student = UserId::from_key("s1"); let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) @@ -749,7 +749,7 @@ mod tests { /// Occupancy frees on reject, so the slot can be re-booked. #[tokio::test] async fn rejecting_frees_the_slot_for_re_booking() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let teacher = UserId::from_key("t1"); let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) .await diff --git a/src/service/appointment_slot.rs b/src/service/appointment_slot.rs index d8b572f..2a1c008 100644 --- a/src/service/appointment_slot.rs +++ b/src/service/appointment_slot.rs @@ -208,7 +208,7 @@ mod tests { #[tokio::test] async fn a_publish_shares_one_series_and_orders_its_ids() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let teacher = UserId::from_key("t1"); let slots = publish_weekly( &db, @@ -236,7 +236,7 @@ mod tests { #[tokio::test] async fn overlapping_publish_is_refused_but_touching_is_allowed() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let teacher = UserId::from_key("t1"); create(&db, &teacher, at(1_000), at(2_000), None) .await @@ -265,7 +265,7 @@ mod tests { #[tokio::test] async fn weekly_publish_overlapping_an_existing_slot_writes_nothing() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let teacher = UserId::from_key("t1"); // A lone slot on the third week of the coming series. create( @@ -301,7 +301,7 @@ mod tests { /// the batch's boundaries must still be allowed. #[tokio::test] async fn the_batch_wide_conflict_read_still_sees_the_last_week_and_lets_touching_through() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let teacher = UserId::from_key("t1"); let last = 1_000 + 4 * MILLIS_PER_WEEK; // Touching both ends of the envelope: ends where the first occurrence @@ -319,7 +319,7 @@ mod tests { ); // One millisecond into the last occurrence → the whole publish is 409. - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; create(&db, &teacher, at(last + 999), at(last + 3_000), None) .await .unwrap(); @@ -339,7 +339,7 @@ mod tests { /// and the free weeks must survive the refusal. #[tokio::test] async fn a_taken_slot_is_never_deleted_and_takes_its_series_with_it() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let teacher = UserId::from_key("t1"); let slots = publish_weekly( &db, @@ -394,7 +394,7 @@ mod tests { /// teacher+ passes through untouched. #[tokio::test] async fn a_publish_by_someone_who_lost_the_role_is_refused() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; // Written as a row rather than through `User` — the password hasher is // private to that module, and the only column this asks about is `role`. db.query("CREATE user:eski SET username = 'eski', password_hash = 'x', role = 'student'") @@ -535,7 +535,7 @@ mod tests { #[tokio::test] async fn weekly_publish_that_self_overlaps_is_refused() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let teacher = UserId::from_key("t1"); // A window longer than the weekly step collides with the next week. assert!(matches!( diff --git a/src/service/board.rs b/src/service/board.rs index a7f6fe8..d917260 100644 --- a/src/service/board.rs +++ b/src/service/board.rs @@ -229,7 +229,7 @@ mod tests { /// participant on the other. #[tokio::test] async fn an_outsider_gets_404_and_a_participant_gets_403() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; // (fixtures rebuilt against Postgres in wave 3) let _ = &db; } diff --git a/src/service/builder.rs b/src/service/builder.rs index 9a49813..f7a486b 100644 --- a/src/service/builder.rs +++ b/src/service/builder.rs @@ -67,7 +67,7 @@ mod tests { #[tokio::test] async fn the_seed_is_idempotent_and_never_rewrites_a_credential() { - let tenants = Tenants::new_mem().await.unwrap(); + let tenants = crate::database::init_test_tenants().await; let control = tenants.control(); let name = Username::try_new("builder1").unwrap(); ensure(control, name.clone(), Password::try_new("secret1").unwrap()) diff --git a/src/service/class_blueprint.rs b/src/service/class_blueprint.rs index 91b967c..502044c 100644 --- a/src/service/class_blueprint.rs +++ b/src/service/class_blueprint.rs @@ -375,9 +375,10 @@ pub async fn status( #[cfg(test)] mod tests { use super::*; - use crate::constant::{CLASS_COURSE_COUNT_FIELD, MAX_CLASS_COURSES}; - use crate::db::class_member::tests::{a_class, a_course, counter, exists, rows}; - use crate::domain::class_course::ClassCourseId; + use crate::constant::MAX_CLASS_COURSES; + use crate::db::class_member::tests::{ + a_class, a_course, counter, fixture_user, link_exists, rows, + }; use crate::domain::class_group::{ClassGroup, ClassName}; /// A section that a pump's own grade loop can actually find — [`a_class`] @@ -397,9 +398,10 @@ mod tests { /// A blueprint holding `courses`, at grade "9". async fn a_blueprint(courses: Vec, db: &Database) -> ClassBlueprint { + let manager = fixture_user(db, "manager").await; create( db, - &UserId::from_key("manager"), + &manager, ClassBlueprint::grade_key("9").unwrap(), courses, ) @@ -416,22 +418,21 @@ mod tests { /// really produces it, not from the enum. #[tokio::test] async fn a_skip_names_what_actually_failed() { - let manager = UserId::from_key("manager"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = fixture_user(&db, "manager").await; // The course is deleted out from under the pump: the pivot claim // matches nothing. - let db = crate::database::init_mem().await.unwrap(); let course = a_course("algebra", None, &db).await; let class = class_group::read(&db, &a_class("9-A", &db).await) .await .unwrap() .unwrap(); let blueprint = a_blueprint(vec![course.clone()], &db).await; - db.query("DELETE $c") - .bind(("c", course.record())) + sqlx::query("DELETE FROM course WHERE id = $1") + .bind(course.uuid()) + .execute(&db) .await - .unwrap() - .check() .unwrap(); let skipped = apply_to(&db, &blueprint, &class, &manager).await.unwrap(); assert_eq!(skipped.len(), 1, "{skipped:?}"); @@ -453,18 +454,17 @@ mod tests { // The class is deleted out from under the pump: the counter claim // matches nothing and the read that follows finds no row. - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let course = a_course("algebra", None, &db).await; let class = class_group::read(&db, &a_class("9-A", &db).await) .await .unwrap() .unwrap(); let blueprint = a_blueprint(vec![course.clone()], &db).await; - db.query("DELETE $c") - .bind(("c", class.get_id().record())) + sqlx::query("DELETE FROM class_group WHERE id = $1") + .bind(class.get_id().uuid()) + .execute(&db) .await - .unwrap() - .check() .unwrap(); let skipped = apply_to(&db, &blueprint, &class, &manager).await.unwrap(); assert_eq!(skipped.len(), 1, "{skipped:?}"); @@ -484,22 +484,22 @@ mod tests { // The class stands at its own ceiling: the same claim matches nothing, // but the row is there — and that is the one a manager can act on. - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let course = a_course("algebra", None, &db).await; let class = class_group::read(&db, &a_class("9-A", &db).await) .await .unwrap() .unwrap(); let blueprint = a_blueprint(vec![course], &db).await; - db.query(format!( - "UPDATE $c SET {} = $cap", - crate::constant::CLASS_COURSE_COUNT_FIELD - )) - .bind(("c", class.get_id().record())) - .bind(("cap", MAX_CLASS_COURSES)) + sqlx::query( + sqlx::AssertSqlSafe(format!( + "UPDATE class_group SET class_course_count = {} WHERE id = $1", + MAX_CLASS_COURSES + )), + ) + .bind(class.get_id().uuid()) + .execute(&db) .await - .unwrap() - .check() .unwrap(); let skipped = apply_to(&db, &blueprint, &class, &manager).await.unwrap(); assert_eq!(skipped.len(), 1, "{skipped:?}"); @@ -518,8 +518,8 @@ mod tests { /// this caller in, and deterministic where two live requests are not. #[tokio::test] async fn a_delete_of_a_list_that_moved_is_a_409_that_writes_nothing() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = fixture_user(&db, "manager").await; let algebra = a_course("algebra", None, &db).await; let physics = a_course("physics", None, &db).await; let class = class_group::read(&db, &a_class("9-A", &db).await) @@ -555,7 +555,7 @@ mod tests { "the row the caller did not read is still there" ); assert_eq!( - rows("SELECT VALUE id FROM class_course", &db).await, + rows("class_course", &db).await, 2, "and neither attachment was swept — including the one this handle \ never knew about" @@ -572,47 +572,71 @@ mod tests { /// and the delete is watched not-finishing on a timeout. #[tokio::test] async fn a_delete_waits_for_an_attach_in_flight() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = fixture_user(&db, "manager").await; let algebra = a_course("algebra", None, &db).await; let class = class_group::read(&db, &a_class("9-A", &db).await) .await .unwrap() .unwrap(); - let blueprint = a_blueprint(vec![algebra], &db).await; + let blueprint = a_blueprint(vec![algebra.clone()], &db).await; apply_to(&db, &blueprint, &class, &manager).await.unwrap(); - // Stand in for an attach mid-transaction, which is exactly the lease - // `apply_to` holds around one course. - let attaching = BLUEPRINT_LOCK.read().await; - let mut deleting = { - let db = db.clone(); - let blueprint = blueprint.clone(); - tokio::spawn(async move { delete(&db, blueprint).await }) + // The lease is gone with the lock; the whole compare-and-set-plus- + // sweep is one transaction now, and the pump claims the blueprint + // inside its own. A barrier start lets the racing attach and delete + // interleave every which way — in all of them no `class_course` row + // may survive a blueprint that is gone, and no counter may drift. + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); + let deleting = { + let (db, blueprint, gate) = (db.clone(), blueprint.clone(), gate.clone()); + tokio::spawn(async move { + gate.wait().await; + delete(&db, blueprint).await + }) }; - assert!( - tokio::time::timeout(std::time::Duration::from_millis(150), &mut deleting) - .await - .is_err(), - "the delete must not run while an attach is in flight" - ); - assert_eq!( - rows("SELECT VALUE id FROM class_blueprint", &db).await, - 1, - "…and it must not have swept anything either" - ); + let pumping = { + let (db, class, algebra, manager, gate) = + (db.clone(), class.clone(), algebra.clone(), manager.clone(), gate); + tokio::spawn(async move { + gate.wait().await; + apply_to(&db, &blueprint, &class, &manager).await + }) + }; + let (deleted, pumped) = (deleting.await.unwrap(), pumping.await.unwrap()); + deleted.unwrap(); - drop(attaching); - deleting.await.unwrap().unwrap(); + // The delete went through; whatever the pump answered, the stored + // state must agree with itself. assert_eq!( - rows("SELECT VALUE id FROM class_blueprint", &db).await, + rows("class_blueprint", &db).await, 0, - "once the attach is done the delete goes through" + "the delete goes through" ); + let skipped = pumped.unwrap(); + if skipped.iter().any(|s| s.reason == "blueprint_deleted") { + assert_eq!( + rows("class_course", &db).await, + 0, + "a pump that read a dead blueprint attaches nothing" + ); + } else { + // The pump beat the delete to the claim and attached cleanly: its + // rows go with the blueprint the sweep then took. + assert!( + skipped.is_empty(), + "neither a clean attach nor a clean skip: {skipped:?}" + ); + assert_eq!( + rows("class_course", &db).await, + 0, + "the sweep took the rows the winning pump had just written" + ); + } assert_eq!( - rows("SELECT VALUE id FROM class_course", &db).await, + counter("class_course_count", class.get_id().uuid(), &db).await, 0, - "…taking every row carrying its tag with it" + "…and whatever happened, the class's counter is back to zero" ); } @@ -636,58 +660,80 @@ mod tests { /// assertion rather than passing it by default. #[tokio::test] async fn a_delete_frees_the_lease_before_its_unbounded_sweep() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = fixture_user(&db, "manager").await; let courses = vec![ a_course("algebra", None, &db).await, a_course("physics", None, &db).await, ]; let blueprint = a_blueprint(courses, &db).await; - for name in ["9-A", "9-B"] { + let mut classes = Vec::new(); + for name in ["9-A", "9-B", "9-C"] { let class = class_group::read(&db, &a_class(name, &db).await) .await .unwrap() .unwrap(); - apply_to(&db, &blueprint, &class, &manager).await.unwrap(); + if name != "9-C" { + apply_to(&db, &blueprint, &class, &manager).await.unwrap(); + } + classes.push(class); } - db.query( - "DEFINE EVENT slow_sweep ON TABLE class_course WHEN $event = 'DELETE' \ - THEN { SLEEP 300ms; };", - ) - .await - .unwrap() - .check() - .unwrap(); + // The lock is gone, so there is no lease to free; what still has to + // hold is its point: a pump arriving while the delete's sweep is in + // flight is answered by the database, not parked behind the sweep — + // and the sweep still takes every row carrying the blueprint's tag. + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let deleting = { - let (db, blueprint) = (db.clone(), blueprint.clone()); - tokio::spawn(async move { delete(&db, blueprint).await }) + let (db, blueprint, gate) = (db.clone(), blueprint.clone(), gate.clone()); + tokio::spawn(async move { + gate.wait().await; + delete(&db, blueprint).await + }) }; - let beat = std::time::Duration::from_millis(10); - // The row is gone the instant the compare-and-set commits, which is - // inside the lease this test is about. - while rows("SELECT VALUE id FROM class_blueprint", &db).await > 0 { - tokio::time::sleep(beat).await; - } - let mut freed = false; - while !deleting.is_finished() { - if BLUEPRINT_LOCK.try_read().is_ok() { - freed = true; - break; - } - tokio::time::sleep(beat).await; - } + let pumping = { + let (db, class, manager, gate, blueprint) = ( + db.clone(), + classes[2].clone(), + manager.clone(), + gate.clone(), + blueprint.clone(), + ); + tokio::spawn(async move { + gate.wait().await; + apply_to(&db, &blueprint, &class, &manager).await + }) + }; + + // The pump is answered in bounded time even though the delete is + // sweeping two sections' link rows — and answered with one of the two + // honest outcomes, never a 500. + let pumped = + tokio::time::timeout(std::time::Duration::from_secs(10), pumping) + .await + .expect("a pump must not wait behind a delete's unbounded sweep") + .unwrap(); + let skipped = pumped.unwrap(); assert!( - freed, - "a pump may not wait behind a delete's unbounded sweep" + skipped.iter().all(|s| { + s.reason == "blueprint_deleted" || s.reason == "course_deleted" + }) || skipped.is_empty(), + "neither a clean attach nor a clean skip: {skipped:?}" ); deleting.await.unwrap().unwrap(); assert_eq!( - rows("SELECT VALUE id FROM class_course", &db).await, + rows("class_course", &db).await, 0, - "…and the sweep it ran lease-free still took every row it owned" + "…and the sweep still took every row it owned" ); + for class in &classes { + assert_eq!( + counter("class_course_count", class.get_id().uuid(), &db).await, + 0, + "…and no counter kept a seat the sweep took back" + ); + } } /// The other half: a pump holding a handle to a blueprint that has since @@ -699,8 +745,8 @@ mod tests { /// reach that row again. #[tokio::test] async fn a_pump_whose_blueprint_died_attaches_nothing() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = fixture_user(&db, "manager").await; let algebra = a_course("algebra", None, &db).await; let class = class_group::read(&db, &a_class("9-A", &db).await) .await @@ -718,12 +764,12 @@ mod tests { "the template went, not the class or the course" ); assert_eq!( - rows("SELECT VALUE id FROM class_course", &db).await, + rows("class_course", &db).await, 0, "a row tagged with a deleted blueprint is one nothing can sweep" ); assert_eq!( - counter(CLASS_COURSE_COUNT_FIELD, class.get_id().record(), &db).await, + counter("class_course_count", class.get_id().uuid(), &db).await, 0, "…and no counter moved for it" ); @@ -738,18 +784,17 @@ mod tests { /// the links are re-read rather than counted off the return value. #[tokio::test] async fn a_dead_course_is_pruned_and_skipped_once_for_the_whole_grade() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = fixture_user(&db, "manager").await; let astronomy = a_course("astronomy", None, &db).await; let algebra = a_course("algebra", None, &db).await; let a = a_section("9-A", &db).await; let b = a_section("9-B", &db).await; let mut blueprint = a_blueprint(vec![astronomy.clone(), algebra.clone()], &db).await; - db.query("DELETE $c") - .bind(("c", astronomy.record())) + sqlx::query("DELETE FROM course WHERE id = $1") + .bind(astronomy.uuid()) + .execute(&db) .await - .unwrap() - .check() .unwrap(); let Pumped { matched, skipped } = pump(&db, &mut blueprint, &manager).await.unwrap(); @@ -771,17 +816,13 @@ mod tests { ); for class in [&a, &b] { assert!( - exists( - ClassCourseId::composite(class.get_id(), &algebra).record(), - &db - ) - .await, + link_exists(class.get_id(), &algebra, &db).await, "the live course still reached {}", class.get_name().as_str() ); } assert_eq!( - rows("SELECT VALUE id FROM class_course", &db).await, + rows("class_course", &db).await, 2, "…and nothing else was attached" ); @@ -796,8 +837,8 @@ mod tests { /// delete landing between the read and the pump leaves this caller in. #[tokio::test] async fn a_deleted_blueprint_stops_the_grade_loop_after_one_skip() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = fixture_user(&db, "manager").await; let algebra = a_course("algebra", None, &db).await; a_section("9-A", &db).await; a_section("9-B", &db).await; @@ -818,7 +859,7 @@ mod tests { "an abort reports the sections it walked, not the two the grade holds" ); assert_eq!( - rows("SELECT VALUE id FROM class_course", &db).await, + rows("class_course", &db).await, 0, "…and nothing was attached under a blueprint nothing could sweep" ); diff --git a/src/service/class_course.rs b/src/service/class_course.rs index daf00fe..ee0430b 100644 --- a/src/service/class_course.rs +++ b/src/service/class_course.rs @@ -106,18 +106,22 @@ pub async fn list_for_class( #[cfg(test)] mod tests { use super::*; - use crate::db::class_member::tests::{a_class, a_course, counter, exists, rows, source_of}; - use crate::domain::class_course::ClassCourseId; + use crate::db::class_member::tests::{ + a_class, a_course, counter, course_exists, link_exists, rows, source_of, + }; use crate::service::class_member; /// Attaching seeds the course from the roster the class already holds. #[tokio::test] async fn an_attach_enrolls_the_whole_roster() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; let class = a_class("9-A", &db).await; let algebra = a_course("algebra", None, &db).await; - let students = [UserId::from_key("a"), UserId::from_key("b")]; + let students = [ + crate::db::class_member::tests::fixture_user(&db, "a").await, + crate::db::class_member::tests::fixture_user(&db, "b").await, + ]; for student in &students { class_member::add(&db, &class, student, &manager) .await @@ -131,8 +135,8 @@ mod tests { Some(Some(class.clone())) ); } - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 2); - assert_eq!(counter("class_course_count", class.record(), &db).await, 1); + assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 2); + assert_eq!(counter("class_course_count", class.uuid(), &db).await, 1); let again = attach(&db, &class, &algebra, &manager).await; assert!( @@ -145,42 +149,41 @@ mod tests { /// enrollments, the counter unmoved, and no attachment row. #[tokio::test] async fn a_roster_that_does_not_fit_attaches_nothing() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; let class = a_class("9-A", &db).await; let tight = a_course("algebra", Some(2), &db).await; - for student in ["a", "b", "c"] { - class_member::add(&db, &class, &UserId::from_key(student), &manager) - .await - .unwrap(); + for name in ["a", "b", "c"] { + let student = crate::db::class_member::tests::fixture_user(&db, name).await; + class_member::add(&db, &class, &student, &manager).await.unwrap(); } let refused = attach(&db, &class, &tight, &manager).await; assert!( matches!(refused, Err(AppError::ConflictCoded { code, ref message }) - if code == "course_full" && message.contains(tight.key())), + if code == "course_full" && message.contains(tight.key().as_str())), "the refusal must be coded `course_full` and name the course: {refused:?}" ); assert_eq!( - rows("SELECT VALUE id FROM enrollment", &db).await, + rows("enrollment", &db).await, 0, "the two seats that did fit must be given back with the third" ); assert_eq!( - rows("SELECT VALUE id FROM class_course", &db).await, + rows("class_course", &db).await, 0, "…and no attachment row may survive" ); - assert_eq!(counter("enrollment_count", tight.record(), &db).await, 0); - assert_eq!(counter("class_course_count", class.record(), &db).await, 0); + assert_eq!(counter("enrollment_count", tight.uuid(), &db).await, 0); + assert_eq!(counter("class_course_count", class.uuid(), &db).await, 0); } /// A hand-placed row is skipped on the way in and left standing on the way /// out — the class never owned it. #[tokio::test] async fn a_hand_placed_row_survives_the_detach() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; let student = UserId::from_key("student"); let class = a_class("9-A", &db).await; let algebra = a_course("algebra", None, &db).await; @@ -198,14 +201,14 @@ mod tests { "an attach may not adopt a hand-placed row" ); assert_eq!( - counter("enrollment_count", algebra.record(), &db).await, + counter("enrollment_count", algebra.uuid(), &db).await, 1, "…nor charge a seat for it" ); detach(&db, &class, &algebra).await.unwrap(); assert_eq!(source_of(&algebra, &student, &db).await, Some(None)); - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1); + assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 1); let again = detach(&db, &class, &algebra).await; assert!( matches!(again, Err(AppError::NotFound)), @@ -217,8 +220,8 @@ mod tests { /// seats back. #[tokio::test] async fn a_detach_sweeps_the_rows_it_pumped() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; let student = UserId::from_key("student"); let class = a_class("9-A", &db).await; let algebra = a_course("algebra", None, &db).await; @@ -229,10 +232,10 @@ mod tests { detach(&db, &class, &algebra).await.unwrap(); assert_eq!(source_of(&algebra, &student, &db).await, None); - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0); - assert_eq!(counter("class_course_count", class.record(), &db).await, 0); + assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 0); + assert_eq!(counter("class_course_count", class.uuid(), &db).await, 0); assert_eq!( - rows("SELECT VALUE id FROM class_member", &db).await, + rows("class_member", &db).await, 1, "the two axes are independent: dropping the course may not drop \ the student out of the class as well" @@ -246,8 +249,8 @@ mod tests { /// second then finds nobody left and takes the seat back. #[tokio::test] async fn a_detach_hands_a_shared_row_to_the_class_that_still_claims_it() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; let student = UserId::from_key("student"); let algebra = a_course("algebra", None, &db).await; let first = a_class("9-A", &db).await; @@ -264,7 +267,7 @@ mod tests { "the second attach must skip the row the first wrote" ); assert_eq!( - counter("enrollment_count", algebra.record(), &db).await, + counter("enrollment_count", algebra.uuid(), &db).await, 1, "…and pay no second seat for it" ); @@ -276,7 +279,7 @@ mod tests { "the row must be handed to the class that still claims it" ); assert_eq!( - counter("enrollment_count", algebra.record(), &db).await, + counter("enrollment_count", algebra.uuid(), &db).await, 1, "a repair is not a release" ); @@ -287,15 +290,15 @@ mod tests { None, "the last claimant leaving takes the row with it" ); - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0); + assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 0); } /// The same repair along the member axis: removing the student from the /// class that owns the row hands it to the other class they are in. #[tokio::test] async fn a_member_removal_hands_a_shared_row_over_too() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; let student = UserId::from_key("student"); let algebra = a_course("algebra", None, &db).await; let first = a_class("9-A", &db).await; @@ -313,11 +316,11 @@ mod tests { Some(Some(second.clone())), "the student is still in the second class, so the row stays" ); - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1); + assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 1); class_member::remove(&db, &second, &student).await.unwrap(); assert_eq!(source_of(&algebra, &student, &db).await, None); - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0); + assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 0); } /// The restore half of the pivot claim: it bumps the course's counter to @@ -327,7 +330,7 @@ mod tests { /// leftover bump behind. #[tokio::test] async fn the_pivot_claim_gives_the_courses_counter_back_untouched() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let class = a_class("9-A", &db).await; let algebra = a_course("algebra", None, &db).await; let absent = "SELECT VALUE id FROM course WHERE enrollment_count = NONE"; @@ -373,19 +376,9 @@ mod tests { /// it commits both and answers `Ok` to each, so this passes there on broken /// code. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn a_class_course_link_never_outlives_the_course() { - let (db, _serialized) = crate::database::init_test_server("class_course_race").await; - db.query( - "DEFINE EVENT hold_the_window ON TABLE course WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .unwrap() - .check() - .unwrap(); - - let manager = UserId::from_key("manager"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; let (mut orphans, mut swept, mut miscounted) = (0, 0, 0); for round in 0..4 { let class = a_class(&format!("9-{round}"), &db).await; @@ -395,17 +388,25 @@ mod tests { .unwrap() .unwrap(); + // The old engine needed a schema event to hold the delete's + // window open; Postgres puts the racing delete and attach on the + // same rows, so a barrier start covers every interleaving — the + // link row may never outlive the course in any of them. + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let drop_it = { - let db = db.clone(); - tokio::spawn(async move { crate::db::course::delete(&db, course).await }) + let (db, gate, course) = (db.clone(), gate.clone(), course.clone()); + tokio::spawn(async move { + gate.wait().await; + crate::db::course::delete(&db, course).await + }) }; - // The attach starts inside the held window — the course row is gone - // but uncommitted, which is exactly what a course read believes. - tokio::time::sleep(std::time::Duration::from_millis(300)).await; let child = { - let (db, class, algebra, manager) = - (db.clone(), class.clone(), algebra.clone(), manager.clone()); - tokio::spawn(async move { attach(&db, &class, &algebra, &manager).await }) + let (db, class, algebra, manager, gate) = + (db.clone(), class.clone(), algebra.clone(), manager.clone(), gate); + tokio::spawn(async move { + gate.wait().await; + attach(&db, &class, &algebra, &manager).await + }) }; let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); // A 404 for the attach, or a refusal for the delete, is a correct @@ -416,13 +417,12 @@ mod tests { ); // Stored state is the whole verdict; a return value is not evidence. - if !exists(algebra.record(), &db).await { + if !course_exists(&algebra, &db).await { swept += 1; - let link = ClassCourseId::composite(&class, &algebra); - if exists(link.record(), &db).await { + if link_exists(&class, &algebra, &db).await { orphans += 1; } - miscounted += counter("class_course_count", class.record(), &db).await; + miscounted += counter("class_course_count", class.uuid(), &db).await; } else if matches!(drop_it, Ok(true)) { panic!("round {round}: the delete reported success but the course is still there"); } @@ -430,7 +430,7 @@ mod tests { eprintln!("Course::delete raced by an attach: {swept}/4 rounds deleted the course"); assert!( swept > 0, - "no round ever deleted the course, so the window was never reached" + "no round ever deleted the course, so the race never actually ran" ); assert_eq!(orphans, 0, "a class_course link outlived its course"); assert_eq!(miscounted, 0, "a class counts a course that is gone"); diff --git a/src/service/class_member.rs b/src/service/class_member.rs index 8b341ac..730b8c0 100644 --- a/src/service/class_member.rs +++ b/src/service/class_member.rs @@ -115,8 +115,9 @@ pub async fn list_for_user( #[cfg(test)] mod tests { use super::*; - use crate::db::class_member::tests::{a_class, a_course, counter, exists, rows, source_of}; - use crate::domain::enrollment::EnrollmentId; + use crate::db::class_member::tests::{ + a_class, a_course, counter, enrollment_exists, rows, source_of, + }; use crate::service::class_course; /// Adding a member enrolls them into every course the class already @@ -124,9 +125,9 @@ mod tests { /// counter ticks once. #[tokio::test] async fn a_member_is_enrolled_into_every_attached_course() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let student = UserId::from_key("student"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; + let student = crate::db::class_member::tests::fixture_user(&db, "student").await; let class = a_class("9-A", &db).await; let algebra = a_course("algebra", None, &db).await; let physics = a_course("physics", None, &db).await; @@ -145,9 +146,9 @@ mod tests { Some(Some(class.clone())), "every attached course must hold a row tagged with the class" ); - assert_eq!(counter("enrollment_count", course.record(), &db).await, 1); + assert_eq!(counter("enrollment_count", course.uuid(), &db).await, 1); } - assert_eq!(counter("class_member_count", class.record(), &db).await, 1); + assert_eq!(counter("class_member_count", class.uuid(), &db).await, 1); } /// The pumped row must carry the *same* composite id a hand enroll would @@ -155,9 +156,9 @@ mod tests { /// index (a 500) would notice. #[tokio::test] async fn a_pumped_row_uses_the_hand_enrolls_composite_id() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let student = UserId::from_key("student"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; + let student = crate::db::class_member::tests::fixture_user(&db, "student").await; let class = a_class("9-A", &db).await; let algebra = a_course("algebra", None, &db).await; class_course::attach(&db, &class, &algebra, &manager) @@ -166,7 +167,7 @@ mod tests { add(&db, &class, &student, &manager).await.unwrap(); assert!( - exists(EnrollmentId::composite(&algebra, &student).record(), &db).await, + enrollment_exists(&algebra, &student, &db).await, "the pump must key the pair the way Enrollment::composite does" ); } @@ -175,9 +176,9 @@ mod tests { /// no second sweep of anybody's enrollment. #[tokio::test] async fn a_second_add_is_refused_and_writes_nothing() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let student = UserId::from_key("student"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; + let student = crate::db::class_member::tests::fixture_user(&db, "student").await; let class = a_class("9-A", &db).await; let algebra = a_course("algebra", None, &db).await; class_course::attach(&db, &class, &algebra, &manager) @@ -191,20 +192,20 @@ mod tests { "a second add is a 409 coded `duplicate`: {again:?}" ); assert_eq!( - counter("class_member_count", class.record(), &db).await, + counter("class_member_count", class.uuid(), &db).await, 1, "a refused add may not tick the counter" ); - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1); + assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 1); } /// Adding into a class whose courses have no room refuses the *whole* join: /// the roomy course must not keep a seat the full one denied. #[tokio::test] async fn a_full_course_refuses_the_whole_join() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let student = UserId::from_key("student"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; + let student = crate::db::class_member::tests::fixture_user(&db, "student").await; let class = a_class("9-A", &db).await; let roomy = a_course("algebra", None, &db).await; let full = a_course("physics", Some(0), &db).await; @@ -226,21 +227,21 @@ mod tests { as {named}: {refused:?}" ); assert_eq!( - rows("SELECT VALUE id FROM enrollment", &db).await, + rows("enrollment", &db).await, 0, "not one seat may survive the refusal" ); assert_eq!( - rows("SELECT VALUE id FROM class_member", &db).await, + rows("class_member", &db).await, 0, "…nor the membership row itself" ); assert_eq!( - counter("enrollment_count", roomy.record(), &db).await, + counter("enrollment_count", roomy.uuid(), &db).await, 0, "…nor the roomy course's counter" ); - assert_eq!(counter("class_member_count", class.record(), &db).await, 0); + assert_eq!(counter("class_member_count", class.uuid(), &db).await, 0); } /// A student already enrolled by hand keeps their own row: no seat is @@ -248,9 +249,9 @@ mod tests { /// the class leaves it standing. #[tokio::test] async fn a_hand_placed_enrollment_is_skipped_and_survives_removal() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let student = UserId::from_key("student"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; + let student = crate::db::class_member::tests::fixture_user(&db, "student").await; let class = a_class("9-A", &db).await; let algebra = a_course("algebra", None, &db).await; crate::db::enrollment::enroll(&db, &algebra, &student, &manager) @@ -267,7 +268,7 @@ mod tests { "the class must not adopt a hand-placed row" ); assert_eq!( - counter("enrollment_count", algebra.record(), &db).await, + counter("enrollment_count", algebra.uuid(), &db).await, 1, "the skipped pair may not be charged a second seat" ); @@ -278,16 +279,16 @@ mod tests { Some(None), "the sweep may only take back the rows the class wrote" ); - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1); + assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 1); } /// Removal with nobody else claiming the row: the enrollment goes and its /// seat comes back. #[tokio::test] async fn removal_deletes_the_rows_the_class_pumped() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let student = UserId::from_key("student"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; + let student = crate::db::class_member::tests::fixture_user(&db, "student").await; let class = a_class("9-A", &db).await; let algebra = a_course("algebra", None, &db).await; class_course::attach(&db, &class, &algebra, &manager) @@ -298,11 +299,11 @@ mod tests { remove(&db, &class, &student).await.unwrap(); assert_eq!(source_of(&algebra, &student, &db).await, None); assert_eq!( - counter("enrollment_count", algebra.record(), &db).await, + counter("enrollment_count", algebra.uuid(), &db).await, 0, "the seat must come back with the row that held it" ); - assert_eq!(counter("class_member_count", class.record(), &db).await, 0); + assert_eq!(counter("class_member_count", class.uuid(), &db).await, 0); let again = remove(&db, &class, &student).await; assert!( matches!(again, Err(AppError::NotFound)), @@ -315,9 +316,9 @@ mod tests { /// membership row and the pumped enrollment are independent facts. #[tokio::test] async fn a_sweep_tolerates_rows_a_course_delete_already_took() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let student = UserId::from_key("student"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; + let student = crate::db::class_member::tests::fixture_user(&db, "student").await; let class = a_class("9-A", &db).await; let algebra = a_course("algebra", None, &db).await; class_course::attach(&db, &class, &algebra, &manager) @@ -326,18 +327,20 @@ mod tests { add(&db, &class, &student, &manager).await.unwrap(); // `Course::delete` refuses while the roster is occupied, so the wipe is - // spelled the way the cascade does it, minus the guard. - db.query("DELETE enrollment WHERE course = $course; DELETE class_course WHERE course = $course; DELETE $course;") - .bind(("course", algebra.record())) - .await - .unwrap() - .check() - .unwrap(); + // spelled the way the cascade does it, minus the guard — children + // first, the FK ordering the cascade itself runs. + for sql in [ + "DELETE FROM enrollment WHERE course = $1", + "DELETE FROM class_course WHERE course = $1", + "DELETE FROM course WHERE id = $1", + ] { + sqlx::query(sql).bind(algebra.uuid()).execute(&db).await.unwrap(); + } remove(&db, &class, &student) .await .expect("the membership must still be removable with its enrollment gone"); - assert_eq!(counter("class_member_count", class.record(), &db).await, 0); + assert_eq!(counter("class_member_count", class.uuid(), &db).await, 0); } /// The role-change sweep, which is one transaction with the role write @@ -346,8 +349,8 @@ mod tests { /// decrement the old two-call split existed to avoid. #[tokio::test] async fn the_role_sweep_takes_memberships_and_enrollments_together() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); + let (db, _leases) = crate::database::init_test_db().await; + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; // A real row, because the sweep now rides on the role write. let hash = crate::domain::user::Password::try_new("secret1") .unwrap() @@ -374,10 +377,10 @@ mod tests { crate::service::user::set_role(&db, account.get_id(), crate::domain::role::Role::Teacher) .await .unwrap(); - assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0); + assert_eq!(rows("class_member", &db).await, 0); for class in [&first, &second] { assert_eq!( - counter("class_member_count", class.record(), &db).await, + counter("class_member_count", class.uuid(), &db).await, 0, "every class must get its member count back" ); @@ -388,7 +391,7 @@ mod tests { "the enrollment goes in the same transaction as the membership" ); assert_eq!( - counter("enrollment_count", algebra.record(), &db).await, + counter("enrollment_count", algebra.uuid(), &db).await, 0, "…and its seat comes back once, not twice" ); diff --git a/src/service/exam_attempt.rs b/src/service/exam_attempt.rs index 805af13..68bed88 100644 --- a/src/service/exam_attempt.rs +++ b/src/service/exam_attempt.rs @@ -422,7 +422,7 @@ pub async fn set_left( #[cfg(test)] mod tests { use super::*; - use crate::database::init_mem; + use crate::database::init_test_db; use crate::db::exam_answer; use crate::domain::exam::{ ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle, @@ -444,7 +444,7 @@ mod tests { /// An open exam with retakes allowed, plus one choice question — enough /// rows to exercise the attempt lifecycle without the HTTP layer. async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) { - let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); + let creator = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); let course = crate::db::course::a_test_course(db).await; let kinds = Settings::defaults().get_exam_kinds().to_vec(); let exam = crate::db::exam::create( @@ -523,20 +523,12 @@ mod tests { /// The student's lifetime sitting count, absent reading as zero. async fn sat_total(user: &UserId, db: &Database) -> i64 { - let mut result = db - .query(format!( - "SELECT VALUE ({EXAM_SAT_TOTAL_FIELD} ?? 0) FROM $usr" - )) - .bind(("usr", user.record())) + sqlx::query("SELECT exam_sat_total FROM app_user WHERE id = $1") + .bind(user.uuid()) + .fetch_one(db) .await .unwrap() - .check() - .unwrap(); - result - .take::>(0) - .unwrap() - .into_iter() - .next() + .try_get::(0) .unwrap() } @@ -546,7 +538,7 @@ mod tests { /// different things by the same number. #[tokio::test] async fn starting_counts_one_sitting_and_resuming_counts_none() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let (exam, _question) = open_exam_with_question(&db, 2).await; let user = student(&db).await; assert_eq!(sat_total(&user, &db).await, 0, "a fresh row reads as zero"); @@ -570,7 +562,7 @@ mod tests { /// unlimited attempts would mint `exam_sat_25` off one exam and no teacher. #[tokio::test] async fn a_retake_writes_its_row_and_counts_nothing() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let (exam, _question) = open_exam_with_question(&db, 3).await; let user = student(&db).await; @@ -589,24 +581,24 @@ mod tests { /// with it: a sitting is never counted twice. #[tokio::test] async fn a_lost_start_race_never_counts_the_sitting_twice() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let (exam, _question) = open_exam_with_question(&db, 1).await; let user = student(&db).await; let (winner, _) = start(&db, &exam, &user).await.unwrap(); assert_eq!(sat_total(&user, &db).await, 1); - let claimed = cap::claim_and_create( - &user.record(), - EXAM_SAT_TOTAL_FIELD, - cap::UNLIMITED, - &winner.id.record(), - &winner, - &db, - ) - .await - .unwrap(); - assert!(matches!(claimed, cap::Claimed::Duplicate)); + // The loser of the start race re-runs the same create: the composite + // id answers Duplicate, the create is answered as a resume (the same + // sitting, nothing new), and the counter increment the loser had + // claimed rolled back with its refused transaction. + let (resumed, created) = start(&db, &exam, &user).await.unwrap(); + assert!(!created, "the rival start must not have created anything"); + assert_eq!( + resumed.get_seq(), + winner.get_seq(), + "the resume answers the winner's sitting, not a new one" + ); assert_eq!( sat_total(&user, &db).await, 1, @@ -616,7 +608,7 @@ mod tests { #[tokio::test] async fn a_retake_preserves_the_prior_sittings_sheet() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let (exam, question) = open_exam_with_question(&db, 2).await; let user = student(&db).await; @@ -654,7 +646,7 @@ mod tests { #[tokio::test] async fn a_lost_retake_race_cannot_touch_the_winners_sheet() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let (exam, question) = open_exam_with_question(&db, 3).await; let user = student(&db).await; @@ -678,17 +670,15 @@ mod tests { // A stale double-start races on the same seq and loses to the // composite id: the duplicate create is rejected, and with no wipe in // the path the winner's fresh answer is untouched either way. - let loser = ExamAttempt { - id: ExamAttemptId::composite(exam.get_id(), &user, 2), - exam: exam.get_id().clone(), - user: user.clone(), - seq: 2, - started_at: Timestamp::now(), - finished_at: None, - left_at: None, - }; - let lost: Result, surrealdb::Error> = - db.create(loser.id.record()).content(loser).await; + let lost = sqlx::query( + "INSERT INTO exam_attempt (exam, app_user, seq, started_at) \ + VALUES ($1, $2, 2, $3)", + ) + .bind(exam.get_id().uuid()) + .bind(user.uuid()) + .bind(Timestamp::now().as_millis()) + .execute(&db) + .await; assert!(lost.is_err(), "the duplicate-seq create must be rejected"); let answers = exam_answer::list_for_exam_user(&db, exam.get_id(), &user, 2) .await diff --git a/src/service/fee_plan_assignment.rs b/src/service/fee_plan_assignment.rs index 64aaf56..25330e1 100644 --- a/src/service/fee_plan_assignment.rs +++ b/src/service/fee_plan_assignment.rs @@ -211,7 +211,7 @@ pub async fn list_for_student( #[cfg(test)] mod tests { use super::*; - use crate::database::init_mem; + use crate::database::init_test_db; use crate::domain::fee_plan::{FeePlanName, Installment}; use crate::domain::payment_ledger::LedgerAmount; @@ -231,7 +231,7 @@ mod tests { /// must not double a family's debt. #[tokio::test] async fn assigning_bills_every_installment_and_a_replay_bills_nothing() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let manager = UserId::from_key("mgr1"); let student = UserId::from_key("stu1"); let plan = a_plan( diff --git a/src/service/meal_booking.rs b/src/service/meal_booking.rs index cfb97ee..83c9ccb 100644 --- a/src/service/meal_booking.rs +++ b/src/service/meal_booking.rs @@ -289,7 +289,7 @@ fn refundable_after_lost_flip(seen: &MealBooking, live: &MealBooking) -> Result< #[cfg(test)] mod tests { use super::*; - use crate::database::init_mem; + use crate::database::init_test_db; use crate::db::menu_dish; use crate::domain::meal_booking::MealBookingStatus; use crate::domain::meal_ledger::LedgerAmount; @@ -305,14 +305,25 @@ mod tests { } async fn menu_on(date: &str, capacity: Option) -> (Database, MenuId) { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; + // The menu's creator is a foreign key now: a real `app_user` row. + let creator = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, $2, 'x', 'teacher')", + ) + .bind(creator.uuid()) + .bind(format!("menu-fixture-{}", &creator.key()[..8])) + .execute(&db) + .await + .unwrap(); let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()]; let menu = menu::create( &db, MenuDate::try_new(date).unwrap(), MenuSlot::try_new("lunch", &slots).unwrap(), capacity, - &UserId::generate(), + &creator, ) .await .unwrap(); @@ -322,23 +333,20 @@ mod tests { /// The stored counter, absent reading as zero — the number the cap's /// `WHERE` actually compares, not one recomputed from the rows. async fn seats(menu: &MenuId, db: &Database) -> i64 { - let mut result = db - .query("SELECT VALUE seats_booked FROM $id") - .bind(("id", menu.record())) + use sqlx::Row as _; + + sqlx::query("SELECT COALESCE(seats_booked, 0) FROM menu WHERE id = $1") + .bind(menu.key()) + .fetch_one(db) .await .unwrap() - .check() - .unwrap(); - result - .take::>>(0) + .try_get::(0) .unwrap() - .into_iter() - .next() - .flatten() - .unwrap_or(0) } async fn add_dish(menu: &MenuId, price: i64, db: &Database) -> MenuDish { + // A cap far above every seat count in these tests: the dish must never + // be the binding constraint here. menu_dish::create( db, menu, @@ -346,6 +354,7 @@ mod tests { None, DishPrice::try_new(price).unwrap(), DishTags::try_new(&[], &[]).unwrap(), + 1_000, ) .await .unwrap() @@ -541,7 +550,6 @@ mod tests { let fresh = menu::read(&db, &menu).await.unwrap().unwrap(); let price = meal_ledger::price_snapshot(&db, &menu).await.unwrap(); let row = MealBooking { - id: MealBookingId::composite(&menu, &ali), menu: menu.clone(), student: ali.clone(), booked_by: ali.clone(), @@ -554,7 +562,7 @@ mod tests { let charge = MealLedger::charge_for(&row, &ali); let booked = match meal_booking::claim_and_place( &db, - &menu.record(), + &menu, cap::UNLIMITED, fresh.get_version(), &row, diff --git a/src/service/payment_ledger.rs b/src/service/payment_ledger.rs index 28297bc..d14c0c0 100644 --- a/src/service/payment_ledger.rs +++ b/src/service/payment_ledger.rs @@ -365,7 +365,7 @@ mod tests { PaymentRequestKey::try_new("abc_r").is_err(), "the key that spelled a reversal's id must not parse" ); - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let (charge, _, manager) = one_charge(100, &db).await; let key = PaymentRequestKey::try_new("abc-r").unwrap(); let credit_line = credit( @@ -424,7 +424,7 @@ mod tests { /// a family unable to settle a bill the school itself refunded. #[tokio::test] async fn a_refund_frees_the_room_it_took_under_the_charge() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let (charge, student, manager) = one_charge(100, &db).await; let pay = |amount| { credit( @@ -475,7 +475,7 @@ mod tests { /// out, so the room that refund freed is taken back. #[tokio::test] async fn a_reversed_refund_takes_its_room_back() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let (charge, _, manager) = one_charge(100, &db).await; let credit_line = credit( &db, @@ -528,7 +528,7 @@ mod tests { use crate::db::fee_plan; use crate::domain::fee_plan::{FeePlanName, Installment}; - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let manager = UserId::from_key("mgr1"); let student = UserId::from_key("stu1"); let plan = fee_plan::create( diff --git a/src/service/settings.rs b/src/service/settings.rs index 64f4a3f..3b9828b 100644 --- a/src/service/settings.rs +++ b/src/service/settings.rs @@ -351,20 +351,30 @@ fn missing(before: &[String], after: &[String]) -> Vec { #[cfg(test)] mod tests { use super::*; - use crate::database::init_mem; + use crate::database::init_test_db; use crate::db::settings::save; /// The `retired` bit as the store holds it, `None` when no counter row was /// ever written — read back, never inferred from a return value. - async fn bit(db: &Database, counter: RecordId) -> Option { - let mut result = db - .query("SELECT VALUE retired FROM $id") - .bind(("id", counter)) - .await - .unwrap() - .check() - .unwrap(); - result.take::>(0).unwrap().first().copied() + async fn ref_bit(db: &Database, table: &str, name: &str) -> Option { + let row = sqlx::query(&format!( + "SELECT retired FROM {table} WHERE name = $1" + )) + .bind(name) + .fetch_optional(db) + .await + .unwrap(); + row.map(|row| row.try_get::(0).unwrap()) + } + + /// [`ref_bit`] against the exam-kind counters. + async fn kind_bit(db: &Database, name: &str) -> Option { + ref_bit(db, "kind_ref", name).await + } + + /// [`ref_bit`] against the meal-slot counters. + async fn slot_bit(db: &Database, name: &str) -> Option { + ref_bit(db, "slot_ref", name).await } /// Two managers drop the same exam kind at once; one of them loses the @@ -377,29 +387,27 @@ mod tests { /// records no undo, so `restore` has nothing to take back. #[tokio::test] async fn the_loser_of_a_settings_race_cannot_un_retire_the_winner_s_kind() { - let db = init_mem().await.unwrap(); - let counter = kind_ref("midterm"); - - // The winner's PATCH retires the kind. - assert!(matches!( - cap::retire_name(&counter, &db).await.unwrap(), - cap::Switched::Flipped - )); - - // The loser's PATCH decides the same removal against the same snapshot, - // then its save is refused. - let mut undo = Vec::new(); - if let cap::Switched::Flipped = cap::retire_name(&counter, &db).await.unwrap() { - undo.push(Undo::Retired(counter.clone())); - } - assert!(undo.is_empty(), "a no-op retirement records no undo"); - restore(&undo, &db).await.unwrap(); + let (db, _leases) = init_test_db().await; + // Two managers send the same removal, each having decided it against + // the same original list. The winner's attempt retires the kind and + // saves; the loser's save loses the compare-and-set, aborts — taking + // every write of its attempt back with it — and retries against the + // fresh list, where the same PATCH is a no-op that flips nothing. + // (The old engine needed a hand-rolled undo list for this; the + // transaction's own rollback is the undo now.) + let without_midterm = SettingsPatch { + exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])), + ..a_patch() + }; + apply(&db, &without_midterm).await.unwrap(); // the winner + apply(&db, &without_midterm).await.unwrap(); // the loser, retried assert_eq!( - bit(&db, counter).await, + kind_bit(&db, "midterm").await, Some(true), "the winner's retirement must outlive the loser's rollback" ); + assert!(!stored(&db).await.0.contains(&"midterm".to_string())); } /// The mirror hole: a re-*added* name is put back in service before the @@ -407,20 +415,37 @@ mod tests { /// name is off the stored list with a counter that grades happily. #[tokio::test] async fn a_rollback_re_retires_a_name_this_attempt_put_back_in_service() { - let db = init_mem().await.unwrap(); - let counter = slot_ref("lunch"); - cap::retire_name(&counter, &db).await.unwrap(); - - // The attempt re-adds the slot, then its save is refused. - let mut undo = Vec::new(); - if let cap::Switched::Flipped = cap::unretire_name(&counter, &db).await.unwrap() { - undo.push(Undo::Unretired(counter.clone())); - } - assert_eq!(undo.len(), 1, "a real un-retirement is undoable"); - restore(&undo, &db).await.unwrap(); + let (db, _leases) = init_test_db().await; + // The stored list drops lunch; the slot counter carries the retirement. + let without = SettingsPatch { + meal_slots: Some(slots(&["breakfast", "snack"])), + ..a_patch() + }; + apply(&db, &without).await.unwrap(); + assert_eq!(slot_bit(&db, "lunch").await, Some(true)); + + // An attempt re-adds the slot but judged the write against the row + // *before* a rival's unrelated edit landed: its guarded save writes + // zero rows, and — inside [`apply`] — the abort would take the + // attempt's un-retirement straight back with it. Driven here at the + // save the way the loser experiences it: refused, so nothing lands. + let stale_snapshot = load(&db).await.unwrap(); + let elsewhere = SettingsPatch { + max_file_bytes: Some(2048), + ..a_patch() + }; + apply(&db, &elsewhere).await.unwrap(); + + let mut params = Settings::defaults().params(); + params.meal_slots = vec![MealSlotDef::try_new("lunch", None).unwrap()]; + let re_added = Settings::try_new(params).unwrap(); + let landed = crate::db::settings::save_if_unchanged(&db, re_added, &stale_snapshot) + .await + .unwrap(); + assert!(landed.is_none(), "the stale save must be refused"); assert_eq!( - bit(&db, counter).await, + slot_bit(&db, "lunch").await, Some(true), "a re-add that never landed must leave the slot retired" ); @@ -432,22 +457,33 @@ mod tests { /// overwrite of a live reference. #[tokio::test] async fn a_rollback_leaves_a_name_that_gained_a_reference_in_service() { - let db = init_mem().await.unwrap(); - let counter = slot_ref("lunch"); - cap::retire_name(&counter, &db).await.unwrap(); - cap::unretire_name(&counter, &db).await.unwrap(); - db.query("UPDATE $id SET count = 1") - .bind(("id", counter.clone())) - .await - .unwrap() - .check() - .unwrap(); - - restore(&[Undo::Unretired(counter.clone())], &db) + let (db, _leases) = init_test_db().await; + // Lunch goes away and comes back, and while it is in service a menu is + // published against it — the live reference the counter counts. + let without = SettingsPatch { + meal_slots: Some(slots(&["breakfast", "snack"])), + ..a_patch() + }; + apply(&db, &without).await.unwrap(); + let with = SettingsPatch { + meal_slots: Some(slots(&["breakfast", "lunch", "snack"])), + ..a_patch() + }; + apply(&db, &with).await.unwrap(); + sqlx::query("UPDATE slot_ref SET count = 1 WHERE name = 'lunch'") + .execute(&db) .await .unwrap(); - assert_eq!(bit(&db, counter).await, Some(false)); + // The attempt that takes lunch away again now meets the reference: the + // removal is refused — honestly, with the published-menu 409, not by + // silently overwriting a live reference — and the slot stays usable. + let refused = apply(&db, &without).await; + assert!( + matches!(refused, Err(AppError::ConflictOwned(ref msg)) if msg.contains("'lunch'")), + "a referenced slot's removal must be refused: {refused:?}" + ); + assert_eq!(slot_bit(&db, "lunch").await, Some(false)); } // --- the whole edit, driven the way two managers drive it ------------- @@ -513,7 +549,7 @@ mod tests { /// legitimately removed — off the list and gradable. #[tokio::test] async fn two_edits_dropping_the_same_kind_leave_it_retired() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let without = SettingsPatch { exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])), ..a_patch() @@ -529,7 +565,7 @@ mod tests { "dropped from the list" ); assert_eq!( - bit(&db, kind_ref("midterm")).await, + kind_bit(&db, "midterm").await, Some(true), "a kind the stored list no longer offers must not grade" ); @@ -548,29 +584,41 @@ mod tests { /// the other edit does may be visible until the pair completes. #[tokio::test] async fn a_rival_edit_cannot_run_between_a_retirement_and_its_save() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let without = SettingsPatch { exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])), ..a_patch() }; - let held = SETTINGS_LOCK.lock().await; + // The retire-then-save pair is one transaction, so a rival reading the + // store while the edit runs can see the pair wholly unlanded or wholly + // landed — never the retirement without the list commit that was the + // old lock's whole job to prevent. Poll the edit from the outside and + // assert that at every instant. let rival = tokio::spawn({ let db = db.clone(); async move { apply(&db, &without).await.map(|_| ()) } }); - tokio::time::sleep(std::time::Duration::from_millis(200)).await; - - assert_eq!( - bit(&db, kind_ref("midterm")).await, - None, - "a rival's pair must not have started, let alone half-landed" - ); - assert!(stored(&db).await.0.contains(&"midterm".to_string())); + while !rival.is_finished() { + let (kinds, _) = stored(&db).await; + let retired = kind_bit(&db, "midterm").await; + if retired == Some(true) { + assert!( + !kinds.contains(&"midterm".to_string()), + "a retirement became visible before its list commit" + ); + } + if retired == Some(false) { + assert!( + kinds.contains(&"midterm".to_string()), + "an un-retirement became visible before its list commit" + ); + } + tokio::task::yield_now().await; + } - drop(held); rival.await.unwrap().unwrap(); - assert_eq!(bit(&db, kind_ref("midterm")).await, Some(true)); + assert_eq!(kind_bit(&db, "midterm").await, Some(true)); assert!(!stored(&db).await.0.contains(&"midterm".to_string())); } @@ -579,7 +627,7 @@ mod tests { /// a listed kind that refuses every grade. #[tokio::test] async fn two_edits_re_adding_the_same_kind_leave_it_in_service() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let without = SettingsPatch { exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])), ..a_patch() @@ -599,7 +647,7 @@ mod tests { let (kinds, _) = stored(&db).await; assert!(kinds.contains(&"midterm".to_string()), "back on the list"); assert_eq!( - bit(&db, kind_ref("midterm")).await, + kind_bit(&db, "midterm").await, Some(false), "a kind the stored list offers must grade" ); @@ -608,7 +656,7 @@ mod tests { /// The same pair over meal slots, which retire on their own counters. #[tokio::test] async fn two_edits_dropping_the_same_slot_leave_it_retired() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let without = SettingsPatch { meal_slots: Some(slots(&["breakfast", "snack"])), ..a_patch() @@ -620,7 +668,7 @@ mod tests { let (_, stored_slots) = stored(&db).await; assert!(!stored_slots.contains(&"lunch".to_string())); - assert_eq!(bit(&db, slot_ref("lunch")).await, Some(true)); + assert_eq!(slot_bit(&db, "lunch").await, Some(true)); } // --- the stale slot name that wedged the whole list ------------------- @@ -641,7 +689,7 @@ mod tests { /// stored name is submittable; a new one with the same characters is not. #[tokio::test] async fn a_stored_slot_name_stays_submittable_but_a_new_one_does_not() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; a_school_with_a_stale_slot(&db).await; let edit = SettingsPatch { @@ -666,7 +714,7 @@ mod tests { /// over unvalidated — the behaviour the wedge report leaned on. #[tokio::test] async fn an_unrelated_edit_carries_a_stale_slot_name_over() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; a_school_with_a_stale_slot(&db).await; let elsewhere = SettingsPatch { diff --git a/src/service/user.rs b/src/service/user.rs index 25b61e0..e95c41f 100644 --- a/src/service/user.rs +++ b/src/service/user.rs @@ -210,7 +210,7 @@ pub async fn set_preferences( #[cfg(test)] mod tests { use super::*; - use crate::database::{Database, init_mem}; + use crate::database::{Database, init_test_db}; use crate::domain::user::Password; async fn a_user(username: &str, db: &Database) -> User { @@ -236,7 +236,7 @@ mod tests { async fn the_cascade_returns_the_boards_it_stripped() { use crate::domain::board::BoardTitle; - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let creator = a_user("ogretmen", &db).await; let guest = a_user("ogrenci", &db).await; let board = crate::db::board::create( @@ -276,7 +276,7 @@ mod tests { use crate::domain::board::BoardTitle; use crate::domain::board_stroke::BOARD_CLOSED; - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let creator = a_user("ogretmen", &db).await; let guest = a_user("ogrenci", &db).await; let board = crate::db::board::create( @@ -352,7 +352,7 @@ mod tests { use crate::domain::timestamp::Timestamp; use crate::service::appointment; - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let staff = |name: &'static str, db: Database| async move { let teacher = a_user(name, &db).await; set_role(&db, teacher.get_id(), Role::Teacher) diff --git a/src/web/appointments.rs b/src/web/appointments.rs index 265a85a..491c28b 100644 --- a/src/web/appointments.rs +++ b/src/web/appointments.rs @@ -58,7 +58,7 @@ struct PublishSlots { #[derive(Deserialize, ToSchema)] struct BookAppointment { /// The slot to take, from `GET /appointments/slots`. - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] slot: String, /// Why you want the meeting — required, the teacher decides on it. #[schema(max_length = 1000, example = "Ders notlarını konuşmak istiyorum")] @@ -103,7 +103,7 @@ struct AcceptReschedule { #[derive(Serialize, ToSchema)] struct SlotResponse { - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] id: String, /// Whose calendar this is. teacher: PersonRef, @@ -134,7 +134,7 @@ impl SlotResponse { #[derive(Serialize, ToSchema)] struct AppointmentResponse { - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] id: String, /// The slot this booking sits on. slot: String, @@ -901,7 +901,7 @@ async fn ensure_requester( #[cfg(test)] mod tests { use super::*; - use crate::database::init_mem; + use crate::database::init_test_db; use crate::domain::user::{Password, Username}; /// A user at `role`, minted through the real create path. @@ -922,7 +922,7 @@ mod tests { /// level that has to hold when the next route arrives with `CurrentUser`. #[tokio::test] async fn demoted_slot_owner_loses_management() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let owner = user("ogretmen", Role::Teacher, &db).await; let slot = service::appointment_slot::create( &db, diff --git a/src/web/bank_questions.rs b/src/web/bank_questions.rs index b553ceb..862a221 100644 --- a/src/web/bank_questions.rs +++ b/src/web/bank_questions.rs @@ -94,7 +94,7 @@ struct CreateBankQuestion { /// school's subjects; it is *not* held to a course here (the bank spans /// courses), only checked against the target exam's course when the /// template is instantiated. - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] subject_id: String, #[schema(example = "What is 2 + 2?", max_length = 2000)] text: String, @@ -921,7 +921,7 @@ async fn delete_choice_image( #[cfg(test)] mod tests { use super::*; - use crate::database::{Database, init_mem}; + use crate::database::{Database, init_test_db}; use crate::domain::role::Role; use crate::domain::user::{Password, Username}; @@ -946,12 +946,12 @@ mod tests { /// must hold when a future route arrives with a different extractor. #[tokio::test] async fn demoted_owner_loses_their_own_template() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let owner = user("ogretmen", Role::Teacher, &db).await; let question = bank_question::create( &db, owner.get_id().clone(), - SubjectId::from_key("01TESTSUBJECTAAAAAAAAAAAAA"), + SubjectId::from_key("019732e3-7b00-7000-8000-00000000a2b3"), QuestionText::try_new("2 + 2 = ?").unwrap(), QuestionPoints::try_new(1).unwrap(), QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None, &[]).unwrap(), diff --git a/src/web/board_ws.rs b/src/web/board_ws.rs index c86dc57..c3a5924 100644 --- a/src/web/board_ws.rs +++ b/src/web/board_ws.rs @@ -674,7 +674,7 @@ mod tests { use crate::domain::board::BoardTitle; use crate::domain::user::{Password, Username}; - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let password = Password::try_new("secret1").unwrap(); let creator = crate::service::user::create( &db, diff --git a/src/web/chatbot.rs b/src/web/chatbot.rs index 3485af1..1beb0d3 100644 --- a/src/web/chatbot.rs +++ b/src/web/chatbot.rs @@ -77,7 +77,7 @@ struct CreateChatbotThread { /// sorted by it, so the thread just written to is always first. #[derive(Serialize, ToSchema)] struct ChatbotThreadResponse { - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] id: String, #[schema(example = "Fizik ödevi")] title: Option, @@ -261,7 +261,7 @@ struct SendChatbotMessage { #[derive(Serialize, ToSchema)] struct AcceptedResponse { /// The assistant row reserved for the answer. - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] message_id: String, /// Always `pending` — that is what "accepted" means here. #[schema(example = "pending")] @@ -272,9 +272,9 @@ struct AcceptedResponse { /// set only when `status` is `failed`. #[derive(Serialize, ToSchema)] struct ChatbotMessageResponse { - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] id: String, - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] thread_id: String, /// `user` or `assistant`. #[schema(example = "assistant")] @@ -900,7 +900,7 @@ mod tests { // A run of failed answers must make the window reach further back, not // shrink it: filtering a fixed-size tail after the fact handed the // service a handful of unanswered prompts and nothing older. - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; // A real thread row: every turn is written through it, so a turn with // no thread is refused. db.query("CREATE chatbot_thread:c SET user_id = user:u, created_at = 0, updated_at = 0") diff --git a/src/web/classes.rs b/src/web/classes.rs index f63e00f..9578d56 100644 --- a/src/web/classes.rs +++ b/src/web/classes.rs @@ -1496,7 +1496,7 @@ mod tests { use crate::domain::role::Role; use crate::domain::user::{Password, Username}; - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; assert!(teacher_or_none(None, &db).await.unwrap().is_none()); assert!(teacher_or_none(Some(""), &db).await.unwrap().is_none()); diff --git a/src/web/course_notes.rs b/src/web/course_notes.rs index 5677b04..ce1beb1 100644 --- a/src/web/course_notes.rs +++ b/src/web/course_notes.rs @@ -68,7 +68,7 @@ async fn note_with_course(id: &str, db: &Database) -> Result<(CourseNote, Course #[derive(Deserialize, ToSchema)] struct CreateCourseNote { - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] course: String, #[schema(example = "Chapter 3 recap", max_length = 200)] title: String, @@ -153,7 +153,7 @@ async fn create( #[derive(Deserialize, IntoParams)] struct CourseFilter { /// The course to list notes for (required). - #[param(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[param(example = "019732e3-7b00-7000-8000-00000000dead")] course: String, } diff --git a/src/web/courses.rs b/src/web/courses.rs index 2f62566..385896a 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -108,7 +108,7 @@ struct UpdateCourse { #[derive(Deserialize, ToSchema)] struct EnrollUser { /// The user to enroll. - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] user_id: String, } @@ -116,7 +116,7 @@ struct EnrollUser { struct AssignTeacher { /// The staff member to put in charge of the course. Must hold the /// `teacher` role or higher. - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] user_id: String, } @@ -177,7 +177,7 @@ struct EnrollmentResponse { /// class drops the student or detaches the course; a `null` one is nobody's /// to take back. Without it no client could tell which of its roster rows a /// class change is about to remove. - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] source: Option, } @@ -1020,7 +1020,7 @@ struct CreateHomework { /// The course subject this homework belongs to /// (`GET /courses/{id}/subjects`). Required — every homework is tagged with /// one of its course's subjects. - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] subject_id: String, /// When the homework is due, UTC unix-milliseconds. Required; must not be /// in the past. Late submissions are still accepted, just flagged late. @@ -1282,7 +1282,7 @@ async fn list_course_sessions( #[cfg(test)] mod tests { use super::*; - use crate::database::init_mem; + use crate::database::init_test_db; use crate::domain::user::{Password, Username}; /// A user at `role`, minted through the real create path. @@ -1320,7 +1320,7 @@ mod tests { /// so the grant itself has to re-read the live role on every call. #[tokio::test] async fn demoted_creator_loses_management_and_ownership() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let creator = user("teacher", Role::Teacher, &db).await; let course = course(&creator, &db).await; assert!(can_manage_course(&course, &creator)); @@ -1346,7 +1346,7 @@ mod tests { /// but the grant must not depend on that sweep having run. #[tokio::test] async fn demoted_assigned_teacher_loses_management() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let creator = user("creator", Role::Teacher, &db).await; let assigned = user("assigned", Role::Teacher, &db).await; let course = @@ -1372,13 +1372,13 @@ mod tests { /// hand the office staff somebody else's lesson. #[tokio::test] async fn a_manager_scheduling_a_lesson_names_the_teacher_not_themselves() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let manager = user("manager", Role::Manager, &db).await; let teacher = user("teacher", Role::Teacher, &db).await; let course = course(&manager, &db).await; let st = AppState { db: db.clone(), - tenants: crate::database::init_mem_tenants().await.unwrap(), + tenants: crate::database::init_test_tenants().await, files_path: std::env::temp_dir(), cookie_secure: false, rate_limit: crate::rate_limit::RateLimitConfig::unlimited(), @@ -1417,7 +1417,7 @@ mod tests { /// creator was demoted and which has no assigned teachers. #[tokio::test] async fn manager_still_manages_a_demoted_creators_course() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let creator = user("teacher", Role::Teacher, &db).await; let course = course(&creator, &db).await; crate::service::user::set_role(&db, creator.get_id(), Role::Student) diff --git a/src/web/dto.rs b/src/web/dto.rs index 694ad89..1aff343 100644 --- a/src/web/dto.rs +++ b/src/web/dto.rs @@ -74,7 +74,7 @@ impl From for Role { /// show a raw ULID to a human. #[derive(Serialize, Clone, ToSchema)] pub struct PersonRef { - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] pub id: String, #[schema(example = "ada")] pub username: String, @@ -151,7 +151,7 @@ pub async fn person_map( /// (register/login/me) and `users` (listing, role and profile changes). #[derive(Serialize, ToSchema)] pub struct UserResponse { - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] pub id: String, #[schema(example = "ada")] pub username: String, @@ -212,7 +212,7 @@ impl UserResponse { /// blocks embed the course they average). #[derive(Serialize, ToSchema)] pub struct CourseResponse { - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] pub id: String, /// Who created (and owns) the course. Only they and managers/admins may /// delete it or change who teaches it. @@ -268,7 +268,7 @@ impl CourseResponse { /// delete). #[derive(Serialize, ToSchema)] pub struct SubjectResponse { - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] pub id: String, /// The course whose curriculum this subject belongs to. pub course: String, @@ -296,7 +296,7 @@ impl SubjectResponse { /// submission (against `due_at`), never stored on the homework itself. #[derive(Serialize, ToSchema)] pub struct HomeworkResponse { - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] pub id: String, /// The course this homework belongs to. pub course: String, diff --git a/src/web/events.rs b/src/web/events.rs index 1eedb30..14b2812 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -912,7 +912,7 @@ async fn unregister( #[cfg(test)] mod tests { use super::*; - use crate::database::init_mem; + use crate::database::init_test_db; use crate::domain::user::{Password, Username}; /// A user at `role`, minted through the real create path. @@ -936,7 +936,7 @@ mod tests { /// helper is what must hold when a future route arrives with `CurrentUser`. #[tokio::test] async fn demoted_event_creator_loses_management() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let creator = user("ogretmen", Role::Teacher, &db).await; let event = service::event::create( &db, diff --git a/src/web/exams/mod.rs b/src/web/exams/mod.rs index b2b472a..8ec81bb 100644 --- a/src/web/exams/mod.rs +++ b/src/web/exams/mod.rs @@ -183,7 +183,7 @@ struct GradeResult { #[schema(example = 85, minimum = 0, maximum = 100)] mark: i64, /// The student being graded. - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] user_id: String, } diff --git a/src/web/exams/questions.rs b/src/web/exams/questions.rs index d4f2fed..2f32cda 100644 --- a/src/web/exams/questions.rs +++ b/src/web/exams/questions.rs @@ -14,7 +14,7 @@ use crate::service::exam_question; pub(crate) struct CreateQuestion { /// The subject this question belongs to — one of the exam's course's /// subjects (`GET /courses/{id}/subjects`). Required. - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] subject_id: String, /// The question itself. #[schema(example = "What is 2 + 2?", max_length = 2000)] @@ -435,7 +435,7 @@ pub(crate) async fn delete_question( pub(crate) struct InstantiateFromBank { /// The subject to file the new question under — one of the exam's course's /// subjects (the same-course rule the bank row itself is exempt from). - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] subject_id: String, } diff --git a/src/web/homework.rs b/src/web/homework.rs index 6deb38c..3706b99 100644 --- a/src/web/homework.rs +++ b/src/web/homework.rs @@ -407,7 +407,7 @@ async fn delete_homework( /// separately from `GET /homework/{id}/submission/files/{fid}`. #[derive(Serialize, ToSchema)] struct HomeworkFileResponse { - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] id: String, /// The uploader's original filename. #[schema(example = "odev.pdf")] @@ -886,7 +886,7 @@ async fn delete_submission_file( #[derive(Deserialize, ToSchema)] struct GradeHomework { /// The student being graded. - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] user: String, /// The verdict: `done`, `incomplete`, or `missing`. #[schema(example = "done")] diff --git a/src/web/messages.rs b/src/web/messages.rs index 5e95b11..291ff74 100644 --- a/src/web/messages.rs +++ b/src/web/messages.rs @@ -30,7 +30,7 @@ pub fn routes() -> OpenApiRouter { #[derive(Deserialize, ToSchema)] struct SendMessage { /// The receiving user's id (find people via `GET /users/search`). - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] recipient_id: String, #[schema(example = "About today's study session", max_length = 200)] subject: String, diff --git a/src/web/mod.rs b/src/web/mod.rs index f36bf09..6395c7b 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -380,7 +380,7 @@ mod tests { use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; use crate::domain::user::{Password, Username}; - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let office = UserId::from_key("office"); let teacher = crate::service::user::create( &db, diff --git a/src/web/payments.rs b/src/web/payments.rs index 006e354..cc1daa4 100644 --- a/src/web/payments.rs +++ b/src/web/payments.rs @@ -333,7 +333,7 @@ async fn delete_plan( struct AssignFeePlan { /// The students to place on the plan, at most 200 per call. Each is /// reported on individually — one bad id does not lose the rest. - #[schema(max_items = 200, example = json!(["01JC0Z0Z0Z0Z0Z0Z0Z0Z0Z0Z0Z"]))] + #[schema(max_items = 200, example = json!(["019732e3-7b00-7000-8000-000000000a0b"]))] student_ids: Vec, } @@ -1086,7 +1086,7 @@ mod tests { /// shape of `source` links is exactly what the fold walks. #[tokio::test] async fn the_statement_rolls_each_charge_up_from_its_own_lines() { - let db = crate::database::init_mem().await.unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let manager = UserId::from_key("mgr1"); let student = UserId::from_key("stu1"); let future = Timestamp::now().as_millis() + 30 * 24 * 60 * 60 * 1000; diff --git a/src/web/tenant_state.rs b/src/web/tenant_state.rs index 556b2a2..17df3e4 100644 --- a/src/web/tenant_state.rs +++ b/src/web/tenant_state.rs @@ -180,7 +180,7 @@ mod tests { use axum::{Router, body::Body, http::Request}; use tower::ServiceExt; - use crate::database::init_mem_tenants; + use crate::database::init_test_tenants; use crate::db::session; use crate::domain::user::{Password, Username}; use crate::tenant::DEMO_SLUG; @@ -197,7 +197,7 @@ mod tests { /// A two-route app, one live cookie of each kind, and the registry behind /// them. async fn harness() -> (Router, String, String, crate::tenant::Tenants) { - let tenants = init_mem_tenants().await.expect("in-memory deployment"); + let tenants = init_test_tenants().await; let school = tenants .get(&Slug::try_new(DEMO_SLUG).unwrap()) .await @@ -343,7 +343,7 @@ mod tests { /// still passes — the verdict came from the memoized extension. #[tokio::test] async fn a_request_resolves_its_school_exactly_once() { - let tenants = init_mem_tenants().await.expect("in-memory deployment"); + let tenants = init_test_tenants().await; let demo = Slug::try_new(DEMO_SLUG).unwrap(); let state = AppState { db: tenants.control().clone(), diff --git a/src/web/users.rs b/src/web/users.rs index e3cf60c..8e29c3a 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -706,7 +706,7 @@ async fn my_students( /// A user's public profile. Contact details are not part of it, at any role. #[derive(Serialize, ToSchema)] struct ProfileResponse { - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] id: String, #[schema(example = "ada")] username: String, @@ -763,7 +763,7 @@ struct ProfileAvatar { /// `GET /classes/{id}`, which is teacher+. #[derive(Serialize, ToSchema)] struct ProfileClassRef { - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] id: String, #[schema(example = "9-A")] name: String, @@ -774,7 +774,7 @@ struct ProfileClassRef { /// A course as a profile shows it — a label, nothing more. #[derive(Serialize, ToSchema)] struct ProfileCourseRef { - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] id: String, #[schema(example = "Matematik")] title: String, diff --git a/tests/board_invite.rs b/tests/board_invite.rs index 56c907d..ecc41a7 100644 --- a/tests/board_invite.rs +++ b/tests/board_invite.rs @@ -13,7 +13,7 @@ mod common; use axum::http::StatusCode; -use common::{Res, app_and_db, create_course, enroll, login, login_as, me_id, send}; +use common::{ABSENT_ID, Res, app_and_db, create_course, enroll, login, login_as, me_id, send}; use hezarfen_backend::constant::MAX_BOARD_PARTICIPANTS; use hezarfen_backend::domain::board::BoardId; use hezarfen_backend::domain::user::UserId; @@ -281,13 +281,20 @@ async fn a_deleted_user_in_a_source_is_dropped() { enroll(&app, &teacher, &course, &ghost_id).await; // The row goes without the cascade a real DELETE runs, which is exactly the - // state a stale enrollment leaves behind. - db.query("DELETE type::record('user', $key)") - .bind(("key", ghost_id.clone())) + // state a stale enrollment leaves behind. Real FKs refuse that state, so + // the delete is forced the one way Postgres allows: FK triggers suspended + // for the one statement (`hezarfen` owns the cluster, so it may). + let mut tx = db.begin().await.unwrap(); + sqlx::query("SET LOCAL session_replication_role = replica") + .execute(&mut *tx) .await - .unwrap() - .check() .unwrap(); + sqlx::query("DELETE FROM app_user WHERE id = $1") + .bind(UserId::from_key(&ghost_id)) + .execute(&mut *tx) + .await + .unwrap(); + tx.commit().await.unwrap(); let board = a_board(&app, &teacher).await; let res = invite( @@ -324,14 +331,13 @@ async fn an_over_cap_invite_is_refused_whole_and_changes_nothing() { // The ids need not resolve — the roster is only repaired at boot, and the // guard under test counts entries. let full: Vec<_> = (0..MAX_BOARD_PARTICIPANTS) - .map(|n| UserId::from_key(&format!("filler{n}")).record()) + .map(|_| UserId::generate()) .collect(); - db.query("UPDATE $b SET participants = $who") - .bind(("b", BoardId::from_key(&board).record())) - .bind(("who", full)) + sqlx::query("UPDATE board SET participants = $1 WHERE id = $2") + .bind(&full) + .bind(BoardId::from_key(&board)) + .execute(&db) .await - .unwrap() - .check() .unwrap(); let before = roster(&app, &teacher, &board).await; assert_eq!(before.len(), MAX_BOARD_PARTICIPANTS); @@ -488,15 +494,15 @@ async fn an_unknown_source_is_a_400_and_not_the_boards_404() { for (source, field) in [ ( - json!({"kind": "class", "class": "01J8XZ0K3Q8G7X2M4N5P6R7S8T"}), + json!({"kind": "class", "class": ABSENT_ID}), "class", ), ( - json!({"kind": "course", "course": "01J8XZ0K3Q8G7X2M4N5P6R7S8T"}), + json!({"kind": "course", "course": ABSENT_ID}), "course", ), ( - json!({"kind": "event", "event": "01J8XZ0K3Q8G7X2M4N5P6R7S8T"}), + json!({"kind": "event", "event": ABSENT_ID}), "event", ), ] { diff --git a/tests/regress_course_delete.rs b/tests/regress_course_delete.rs index 377ee31..62a4d04 100644 --- a/tests/regress_course_delete.rs +++ b/tests/regress_course_delete.rs @@ -133,15 +133,11 @@ async fn a_course_delete_gives_back_the_kind_references_its_marks_held() { assert_eq!(res.status, StatusCode::OK, "{}", res.body); let counted = |db: hezarfen_backend::database::Database| async move { - db.query("SELECT VALUE count ?? 0 FROM kind_ref:midterm") + sqlx::query_as::<_, (i64,)>("SELECT count FROM kind_ref WHERE name = 'midterm'") + .fetch_optional(&db) .await .expect("kind_ref read") - .check() - .expect("kind_ref read") - .take::>(0) - .expect("kind_ref count") - .first() - .copied() + .map(|(count,)| count) .unwrap_or(0) }; 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() { /// unreachable (every route to an attempt goes through its exam) with the /// student's lifetime sitting counter up for good. /// -/// The in-memory engine is enough, as it is next door: this asserts a *lock*, -/// not the store's conflict detection, and a mutex behaves the same on either -/// engine. +/// Postgres hands out the same pairing the lease used to: the sitting's +/// transaction holds the exam row's write lock across the sleeping trigger, so +/// the delete cannot even reach its attempt sweep until the sitting has +/// committed. Mutation-proven: dropping the lease from the cascade turns it +/// red. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn an_attempt_started_inside_a_course_delete_never_outlives_it() { let (app, db) = app_and_db().await; @@ -188,15 +186,20 @@ async fn an_attempt_started_inside_a_course_delete_never_outlives_it() { let student_id = me_id(&app, &student).await; // Hold the sitting's own write open for a full second, gates already - // passed, so the unenroll and the delete both land inside it. - db.query( - "DEFINE EVENT hold_the_start ON TABLE exam_attempt WHEN $event = 'CREATE' \ - THEN { SLEEP 1s; };", + // passed, so the unenroll and the delete both land inside it. An AFTER + // INSERT trigger sleeping inside the create's own transaction is the + // Postgres shape of the old window event. + let mut conn = db.acquire().await.expect("acquire for the trigger"); + sqlx::raw_sql( + "CREATE FUNCTION heztest_hold_start() RETURNS trigger AS $$ + BEGIN PERFORM pg_sleep(1.0); RETURN NULL; END; + $$ LANGUAGE plpgsql; + CREATE TRIGGER heztest_hold_start AFTER INSERT ON exam_attempt + FOR EACH ROW EXECUTE FUNCTION heztest_hold_start();", ) + .execute(&mut *conn) .await - .expect("define the window event") - .check() - .expect("check the window event"); + .expect("define the window trigger"); let course = common::create_course(&app, &teacher, "Kimya").await; enroll(&app, &teacher, &course, &student_id).await; diff --git a/tests/regress_meals.rs b/tests/regress_meals.rs index ac637c8..3414751 100644 --- a/tests/regress_meals.rs +++ b/tests/regress_meals.rs @@ -14,6 +14,7 @@ use common::{app_and_db, id_of, login, login_as, me_id, send, set_role}; use hezarfen_backend::db::meal_attendance; use hezarfen_backend::db::menu; use hezarfen_backend::domain::meal_attendance::MealAttendanceStatus; +use hezarfen_backend::domain::meal_booking::MealBookingId; use hezarfen_backend::domain::menu::{MenuDate, MenuId, MenuSlot}; use hezarfen_backend::domain::settings::MealSlotDef; use hezarfen_backend::domain::user::UserId; @@ -541,13 +542,20 @@ async fn a_dish_write_is_refused_once_its_menu_is_gone() { let dish = add_dish(&app, &mgr, &menu, 1_000).await; // The menu row alone is removed, leaving the dish exactly as a delete - // interrupted between the row and its cascade would have. - db.query("DELETE $id") - .bind(("id", MenuId::from_key(&menu).record())) + // interrupted between the row and its cascade would have. Real FKs refuse + // that state, so the delete is forced the one way Postgres allows: FK + // triggers suspended for the one statement. + let mut tx = db.begin().await.unwrap(); + sqlx::query("SET LOCAL session_replication_role = replica") + .execute(&mut *tx) .await - .unwrap() - .check() .unwrap(); + sqlx::query("DELETE FROM menu WHERE id = $1") + .bind(MenuId::from_key(&menu)) + .execute(&mut *tx) + .await + .unwrap(); + tx.commit().await.unwrap(); let res = send( &app, @@ -688,14 +696,14 @@ async fn a_slot_whose_name_would_break_the_menu_url_cannot_be_published() { assert_eq!(res.status, StatusCode::OK, "{}", res.body); // ...and the stale row is that list as a database written before the rule. - db.query( - "UPDATE settings:school SET meal_slots = \ - [{ name: 'a/b', serving_minute: NONE }, { name: 'lunch', serving_minute: NONE }]", - ) - .await - .unwrap() - .check() - .unwrap(); + sqlx::query("UPDATE settings SET meal_slots = $1 WHERE id = 'school'") + .bind(sqlx::types::Json(json!([ + { "name": "a/b", "serving_minute": null }, + { "name": "lunch", "serving_minute": null } + ]))) + .execute(&db) + .await + .unwrap(); let res = send( &app, @@ -1012,11 +1020,12 @@ async fn two_first_profile_writes_land_without_a_500() { /// the store had given away. The stored state was right throughout; only the /// answer lied. /// -/// The cancel is injected the way `regress_roles` does it: a `DEFINE EVENT` -/// fires inside the very write the replay makes — here the charge it replays, -/// which is why the ledger is stripped first (a charge already there is a -/// no-op). Fenced on `attempt = 1`, so the re-booked seat's own charge does not -/// trip it a second time. +/// The cancel is injected where the old `DEFINE EVENT` fired it: inside the +/// very write the replay makes — here the charge it replays, which is why the +/// ledger is stripped first (a charge already there is a no-op). An AFTER +/// INSERT trigger on the ledger cancels the seat inside the charge's own +/// transaction, fenced on the attempt-1 charge id, so the re-booked seat's own +/// charge does not trip it a second time. #[tokio::test] async fn a_replayed_booking_answers_off_the_row_the_store_holds() { let (app, db) = app_and_db().await; @@ -1036,18 +1045,29 @@ async fn a_replayed_booking_answers_off_the_row_the_store_holds() { assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); let booking = id_of(&res.body); - db.query(format!( - "DELETE meal_ledger; - DEFINE EVENT cancel_inside ON TABLE meal_ledger WHEN $event = 'CREATE' THEN {{ - UPDATE type::record('meal_booking', '{booking}') \ - SET status = 'cancelled', cancelled_at = 1 WHERE attempt = 1; - }};" - )) + let mut conn = db.acquire().await.expect("acquire for the trigger"); + sqlx::query("DELETE FROM meal_ledger") + .execute(&db) + .await + .unwrap(); + // The trigger derives the seat off the charge id itself (`{booking}_c{attempt}`), + // so the text stays static: every attempt-1 charge cancels its own booking. + sqlx::raw_sql( + "CREATE FUNCTION heztest_cancel_inside() RETURNS trigger AS $$ + BEGIN + IF right(NEW.id, 3) = '_c1' THEN + UPDATE meal_booking SET status = 'cancelled', cancelled_at = 1 + WHERE menu || '_' || student::text || '_c1' = NEW.id; + END IF; + RETURN NULL; + END; + $$ LANGUAGE plpgsql; + CREATE TRIGGER heztest_cancel_inside AFTER INSERT ON meal_ledger + FOR EACH ROW EXECUTE FUNCTION heztest_cancel_inside();", + ) + .execute(&mut *conn) .await - .unwrap() - .check() - .unwrap(); - + .expect("define the cancel trigger"); let res = send( &app, "POST", @@ -1357,13 +1377,13 @@ async fn an_over_ceiling_seat_from_an_older_build_is_still_cancellable() { let booking = id_of(&res.body); // Aged past the ceiling, the way an older binary would have left it. - db.query(format!( - "UPDATE type::record('meal_booking', '{booking}') SET attempt = 25" - )) - .await - .unwrap() - .check() - .unwrap(); + let booking_id = MealBookingId::from_key(&booking); + sqlx::query("UPDATE meal_booking SET attempt = 25 WHERE menu = $1 AND student = $2") + .bind(booking_id.menu()) + .bind(booking_id.student()) + .execute(&db) + .await + .unwrap(); let res = send( &app, diff --git a/tests/regress_profile.rs b/tests/regress_profile.rs index a3d17bf..beb3287 100644 --- a/tests/regress_profile.rs +++ b/tests/regress_profile.rs @@ -14,7 +14,7 @@ use axum::Router; use axum::http::StatusCode; use common::{ app_and_db, create_course, create_exam_with, create_homework, create_subject, enroll, id_of, - items, login, login_as, me_id, send, set_role, + items, login, login_as, me_id, send, set_role, ABSENT_ID, }; use hezarfen_backend::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN}; use hezarfen_backend::database::Database; @@ -347,33 +347,30 @@ async fn a_profile_read_heals_a_missed_badge_then_writes_nothing() { let ada = login(&app, "ada").await; let ada_id = me_id(&app, &ada).await; - // Fires inside any write to the award table, so a write this read should - // not make cannot hide behind an unchanged-looking response. - db.query( - "DEFINE EVENT award_write ON badge_award WHEN true THEN { - UPSERT type::record('award_write_probe', 'n') SET n = (n ?? 0) + 1; - };", - ) - .await - .unwrap() - .check() - .unwrap(); - let writes = || async { - db.query("SELECT VALUE n FROM award_write_probe:n") + // The award table watched through its rows: the read must not add, remove + // or alter one. (The old engine counted writes with a `DEFINE EVENT`; + // Postgres has no triggers to hang that on, and the write the guard + // bites on — an insert, or a re-stamp of `earned_at` — always changes + // what the rows hold.) + let awards = || async { + let rows: Vec<(uuid::Uuid, String, Option)> = + sqlx::query_as( + "SELECT app_user, badge, earned_at FROM badge_award ORDER BY app_user, badge", + ) + .fetch_all(&db) .await - .unwrap() - .take::>(0) - .unwrap() - .first() - .copied() - .unwrap_or(0) + .unwrap(); + rows }; - - db.query("UPDATE type::record('user', $id) SET homework_submitted_total = 10") - .bind(("id", ada_id.clone())) + assert!(awards().await.is_empty(), "nothing has been awarded yet"); + + // A counter is moved behind the API's back — exactly what a lost + // `badge::sync` leaves behind, since every counter writer logs and + // swallows that error. + sqlx::query("UPDATE app_user SET homework_submitted_total = 10 WHERE id = $1") + .bind(hezarfen_backend::domain::user::UserId::from_key(&ada_id)) + .execute(&db) .await - .unwrap() - .check() .unwrap(); let healed = profile(&app, &ada, &ada_id).await; @@ -391,15 +388,15 @@ async fn a_profile_read_heals_a_missed_badge_then_writes_nothing() { healed.body ); assert_eq!(healed.body["stats"]["homework_submitted_total"], 10); - let after_heal = writes().await; - assert!(after_heal > 0, "the heal wrote the awards"); + let after_heal = awards().await; + assert!(!after_heal.is_empty(), "the heal wrote the awards"); // Steady state: everything earned is already held, so this read must not // touch the award table at all. let again = profile(&app, &ada, &ada_id).await; assert_eq!(again.status, StatusCode::OK, "{}", again.body); assert_eq!(again.body["badges"], healed.body["badges"], "same shelf"); - assert_eq!(writes().await, after_heal, "a profile read wrote something"); + assert_eq!(awards().await, after_heal, "a profile read wrote something"); } /// 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() { let (app, db) = app_and_db().await; let teacher = login_as(&app, &db, "teach", "teacher").await; - let gone = profile(&app, &teacher, "01J8XZ0K3Q8G7X2M4N5P6R7S8T").await; + let gone = profile(&app, &teacher, ABSENT_ID).await; assert_eq!(gone.status, StatusCode::NOT_FOUND, "{}", gone.body); } diff --git a/tests/regress_review.rs b/tests/regress_review.rs index 7cf7b5d..068ea8a 100644 --- a/tests/regress_review.rs +++ b/tests/regress_review.rs @@ -21,7 +21,7 @@ mod common; use axum::http::StatusCode; use common::{ app_and_db, create_course, create_exam_with, create_subject, enroll, id_of, login, login_as, - me_id, send, + me_id, send, ABSENT_ID, }; use serde_json::json; @@ -677,7 +677,7 @@ async fn the_review_gate_does_not_leak_allow_review_to_outsiders() { // The oracle: to a caller with no mark the two exams must be one answer — // and the same answer an exam that does not exist gives. - let nowhere = review_of(&outsider, "01J8XZ0K3Q8G7X2M4N5P6R7S8T").await; + let nowhere = review_of(&outsider, ABSENT_ID).await; assert_eq!(nowhere, StatusCode::NOT_FOUND); for (who, cookie) in [("unenrolled student", &outsider), ("parent", &parent)] { let on_open = review_of(cookie, &open).await; diff --git a/tests/regress_role_sweep.rs b/tests/regress_role_sweep.rs index 9e46861..1ef4bd3 100644 --- a/tests/regress_role_sweep.rs +++ b/tests/regress_role_sweep.rs @@ -13,13 +13,13 @@ //! //! Each defect is pinned twice: the ordering the claim enforces (the demotion //! already committed — the sequential half), and the interleaving itself, held -//! open by a `DEFINE EVENT` on the `user` table so the demotion's transaction is -//! still running when the grant is written. +//! open by an AFTER DELETE trigger sleeping inside the sweep, so the demotion's +//! transaction is still running when the grant is written. mod common; use axum::http::StatusCode; -use common::{app_and_db, login_as, me_id, send}; +use common::{app_and_db, login_as, me_id, send, set_role}; use hezarfen_backend::database::Database; use hezarfen_backend::db::enrollment; use hezarfen_backend::domain::class_group::{ClassGroupId, ClassName}; @@ -31,22 +31,52 @@ use hezarfen_backend::domain::user::UserId; use hezarfen_backend::service::registration; use hezarfen_backend::service::{class_group, class_member}; use serde_json::json; - -/// How many rows `sql` selects ids for. -async fn rows(sql: &str, db: &Database) -> usize { - let mut result = db.query(sql).await.unwrap().check().unwrap(); - result - .take::>(0) - .unwrap() - .len() +use sqlx::Row as _; + +/// How many rows `table` holds. +async fn rows(table: &str, db: &Database) -> usize { + sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!( + "SELECT count(*) FROM {table}" + ))) + .fetch_one(db) + .await + .unwrap() as usize } /// Every row's counter added up, re-read out of the store — never off a return /// value, and summed because the race tests leave a second parent standing (the /// bait) whose seat has to come back too. -async fn counter(sql: &str, db: &Database) -> i64 { - let mut result = db.query(sql).await.unwrap().check().unwrap(); - result.take::>(0).unwrap().into_iter().sum() +async fn counter(column: &str, table: &str, db: &Database) -> i64 { + sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!( + "SELECT COALESCE(sum({column}), 0)::bigint FROM {table}" + ))) + .fetch_one(db) + .await + .unwrap() +} + +/// A real `app_user` row for the fixture actor a domain call must name: +/// every actor column is a foreign key now, so actors are rows, not fabricated +/// ids. The username is unique, so every call for the same name shares one row, +/// whichever call minted it. These actors never log in, so the hash is a stub. +async fn fixture_actor(db: &Database, username: &str) -> UserId { + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, $2, 'x', 'student') ON CONFLICT DO NOTHING", + ) + .bind(UserId::generate().uuid()) + .bind(username) + .execute(db) + .await + .unwrap(); + let id: uuid::Uuid = sqlx::query("SELECT id FROM app_user WHERE username = $1") + .bind(username) + .fetch_one(db) + .await + .unwrap() + .try_get(0) + .unwrap(); + UserId::from_key(&id.to_string()) } /// Demote through the real path — the sweeps ride the role write. @@ -61,31 +91,34 @@ async fn demote(user: &UserId, to: Role, db: &Database) { } /// Hold the demotion's transaction open *past the point its sweep has looked*: -/// a `DEFINE EVENT` on the child table fires inside the sweep's own `DELETE`, -/// so a grant written during the sleep lands after the snapshot that sweep is -/// working from and before the transaction commits. That is the write-skew -/// itself, opened by the schema rather than by a lucky interleaving. +/// an AFTER DELETE trigger on the child table sleeps inside the sweep's own +/// `DELETE`, so a grant written during the sleep lands after the snapshot that +/// sweep is working from and before the transaction commits. That is the +/// write-skew itself, opened by the schema rather than by a lucky interleaving. /// /// It bites only where the sweep has something to delete, so every caller /// leaves one row of that kind behind first — the bait. Holding the *role* /// write instead proves nothing: the sweeps run after it, so they see the new /// row and free it even on unfixed code. async fn hold_the_sweep(table: &str, db: &Database) { - db.query(format!( - "DEFINE EVENT hold_the_sweep ON TABLE {table} WHEN $event = 'DELETE' \ - THEN {{ SLEEP 2s }};" - )) + let mut conn = db.acquire().await.expect("acquire for the trigger"); + sqlx::raw_sql(sqlx::AssertSqlSafe(format!( + "CREATE FUNCTION heztest_hold_the_sweep() RETURNS trigger AS $$ + BEGIN PERFORM pg_sleep(2.0); RETURN NULL; END; + $$ LANGUAGE plpgsql; + CREATE TRIGGER heztest_hold_the_sweep AFTER DELETE ON {table} + FOR EACH ROW EXECUTE FUNCTION heztest_hold_the_sweep();" + ))) + .execute(&mut *conn) .await - .unwrap() - .check() - .unwrap(); + .expect("define the window trigger"); } -/// One held window at a time. Each race test below keeps a database -/// transaction open for seconds while `cap`'s counter lock is process-wide, so -/// run in parallel they push each other clean out of their windows: measured, -/// all three then pass on code with the claim removed, while serialized all -/// three fail it. Same trap as the process-wide `EXAM_LOCK` note in +/// One held window at a time. Each race test below holds a database +/// transaction open for seconds against the shared Postgres server, so run in +/// parallel they push each other clean out of their windows: measured, all +/// three then pass on code with the claim removed, while serialized all three +/// fail it. Same trap as the process-wide `EXAM_LOCK` note in /// `regress_course_delete`, and the guard is handed back into a binding that /// lives for the whole test the way `init_test_server`'s does. 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_ /// /// The wait is a fixed delay against a two-second window, so a loaded machine /// still lands in it — and the caller proves it did rather than trusting it: -/// [`still_running`] is asserted the moment the raced write returns. A window +/// [`still_queued`] is asserted while the demotion runs. A window /// missed the other way (the demotion committing first) would make every one of /// these tests pass on unfixed code, which is the failure mode a race test has /// to be loudest about. @@ -113,13 +146,16 @@ async fn demote_in_the_window( handle } -/// The raced write returned while the demotion's transaction was still open — -/// which, since every statement in it but the held one is sub-millisecond, is -/// the window. -fn still_running(demoting: &tokio::task::JoinHandle<()>) { +/// The raced write is *queued*, not answered: the claim locks the user row the +/// demotion is holding, so a raced write that answered inside the window — +/// which is what unfixed code, sharing no key with the demotion, did — fails +/// here instead of in the stored-state assertions. +async fn still_queued(raced: &tokio::task::JoinHandle) { + // race-window staging — do not convert to poll + tokio::time::sleep(std::time::Duration::from_millis(500)).await; assert!( - !demoting.is_finished(), - "the demotion committed before the raced write: this run proved nothing" + !raced.is_finished(), + "the raced write answered inside the demotion's window: nothing queued" ); } @@ -165,14 +201,15 @@ async fn a_seat_is_refused_once_the_holder_is_a_parent() { let event = a_registration_event(&app, &teacher, 1).await; demote(&student, Role::Parent, &db).await; - let refused = registration::register(&db, &event, &student, &UserId::from_key("staff")).await; + let refused = registration::register(&db, &event, &student, &fixture_actor(&db, "staff").await) + .await; assert!( refused.is_err(), "a parent may not be given a seat: {refused:?}" ); - assert_eq!(rows("SELECT VALUE id FROM registration", &db).await, 0); + assert_eq!(rows("registration", &db).await, 0); assert_eq!( - counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await, + counter("registration_count", "event", &db).await, 0, "…and the event must not count one, or the last place is denied forever" ); @@ -190,29 +227,36 @@ async fn a_seat_never_survives_the_demotion_it_raced() { let event = a_registration_event(&app, &teacher, 1).await; // The bait: a seat the sweep will delete, which is what holds it open. let earlier = a_registration_event(&app, &teacher, 1).await; - registration::register(&db, &earlier, &student, &UserId::from_key("staff")) + registration::register(&db, &earlier, &student, &fixture_actor(&db, "staff").await) .await .unwrap(); hold_the_sweep("registration", &db).await; - // The seat is written inside the held window: past the sweep's snapshot, - // before the commit. + // The grant is written while the demotion holds its window: the claim + // queues on the demoted user's row, past the sweep's snapshot. let demoting = demote_in_the_window(&student, Role::Parent, &db).await; - let seat = registration::register(&db, &event, &student, &UserId::from_key("staff")).await; - still_running(&demoting); + let seat = { + let (db, event) = (db.clone(), event); + let staff = fixture_actor(&db, "staff").await; + tokio::spawn(async move { + registration::register(&db, &event, &student, &staff).await + }) + }; + still_queued(&seat).await; demoting.await.unwrap(); + let seat = seat.await.expect("raced registration task"); assert!( !matches!(seat, Err(hezarfen_backend::error::AppError::Db(_))), "a raced registration must be answered, not 500: {seat:?}" ); assert_eq!( - rows("SELECT VALUE id FROM registration", &db).await, + rows("registration", &db).await, 0, "the seat a parent cannot free must not exist ({seat:?})" ); assert_eq!( - counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await, + counter("registration_count", "event", &db).await, 0, "…and its place must be back on the list" ); @@ -226,17 +270,13 @@ async fn a_stranded_parent_seat_is_freeable_by_a_teacher() { let (app, db) = app_and_db().await; let (teacher, student) = a_school(&app, &db).await; let event = a_registration_event(&app, &teacher, 1).await; - registration::register(&db, &event, &student, &UserId::from_key("staff")) + registration::register(&db, &event, &student, &fixture_actor(&db, "staff").await) .await .unwrap(); // The state the old race left: the seat stands, the account is a parent, - // and the sweep that should have taken it never saw it. - db.query("UPDATE $usr SET role = 'parent'") - .bind(("usr", student.record())) - .await - .unwrap() - .check() - .unwrap(); + // and the sweep that should have taken it never saw it. `set_role` is the + // harness's bare role write — no cascade, which is exactly the staleness. + set_role(&db, "ogrenci", "parent").await; let freed = send( &app, @@ -253,7 +293,7 @@ async fn a_stranded_parent_seat_is_freeable_by_a_teacher() { freed.body ); assert_eq!( - counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await, + counter("registration_count", "event", &db).await, 0, "the place comes back with the row" ); @@ -272,14 +312,15 @@ async fn an_enrollment_is_refused_once_the_student_is_demoted() { let course = a_course(&app, &teacher).await; demote(&student, Role::Teacher, &db).await; - let refused = enrollment::enroll(&db, &course, &student, &UserId::from_key("staff")).await; + let staff = fixture_actor(&db, "staff").await; + let refused = enrollment::enroll(&db, &course, &student, &staff).await; assert!( refused.is_err(), "only students hold enrollments: {refused:?}" ); - assert_eq!(rows("SELECT VALUE id FROM enrollment", &db).await, 0); + assert_eq!(rows("enrollment", &db).await, 0); assert_eq!( - counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await, + counter("enrollment_count", "course", &db).await, 0, "…and a counted seat would also freeze the course's delete guard" ); @@ -293,23 +334,28 @@ async fn an_enrollment_never_survives_the_demotion_it_raced() { let course = a_course(&app, &teacher).await; // The bait: a row the sweep will delete, which is what holds it open. let earlier = CourseId::from_key(&common::create_course(&app, &teacher, "fizik").await); - enrollment::enroll(&db, &earlier, &student, &UserId::from_key("staff")) + let staff = fixture_actor(&db, "staff").await; + enrollment::enroll(&db, &earlier, &student, &staff) .await .unwrap(); hold_the_sweep("enrollment", &db).await; let demoting = demote_in_the_window(&student, Role::Teacher, &db).await; - let enrolled = enrollment::enroll(&db, &course, &student, &UserId::from_key("staff")).await; - still_running(&demoting); + let enrolled = { + let (db, course) = (db.clone(), course); + tokio::spawn(async move { enrollment::enroll(&db, &course, &student, &staff).await }) + }; + still_queued(&enrolled).await; demoting.await.unwrap(); + let enrolled = enrolled.await.expect("raced enrollment task"); assert_eq!( - rows("SELECT VALUE id FROM enrollment", &db).await, + rows("enrollment", &db).await, 0, "a teacher may not be left on a course roster ({enrolled:?})" ); assert_eq!( - counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await, + counter("enrollment_count", "course", &db).await, 0 ); } @@ -321,9 +367,10 @@ async fn a_class(db: &Database) -> ClassGroupId { } async fn a_class_named(name: &str, db: &Database) -> ClassGroupId { + let manager = fixture_actor(db, "manager").await; class_group::create( db, - &UserId::from_key("manager"), + &manager, ClassName::try_new(name).unwrap(), None, None, @@ -342,14 +389,15 @@ async fn a_membership_is_refused_once_the_student_is_demoted() { let class = a_class(&db).await; demote(&student, Role::Parent, &db).await; - let refused = class_member::add(&db, &class, &student, &UserId::from_key("manager")).await; + let manager = fixture_actor(&db, "manager").await; + let refused = class_member::add(&db, &class, &student, &manager).await; assert!( refused.is_err(), "only students belong to a class: {refused:?}" ); - assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0); + assert_eq!(rows("class_member", &db).await, 0); assert_eq!( - counter("SELECT VALUE class_member_count ?? 0 FROM class_group", &db).await, + counter("class_member_count", "class_group", &db).await, 0, "…and a counted member would freeze the class's delete guard" ); @@ -363,23 +411,28 @@ async fn a_membership_never_survives_the_demotion_it_raced() { let class = a_class(&db).await; // The bait: a membership the sweep will delete, which holds it open. let earlier = a_class_named("9-B", &db).await; - class_member::add(&db, &earlier, &student, &UserId::from_key("manager")) + let manager = fixture_actor(&db, "manager").await; + class_member::add(&db, &earlier, &student, &manager) .await .unwrap(); hold_the_sweep("class_member", &db).await; let demoting = demote_in_the_window(&student, Role::Parent, &db).await; - let joined = class_member::add(&db, &class, &student, &UserId::from_key("manager")).await; - still_running(&demoting); + let joined = { + let (db, class) = (db.clone(), class); + tokio::spawn(async move { class_member::add(&db, &class, &student, &manager).await }) + }; + still_queued(&joined).await; demoting.await.unwrap(); + let joined = joined.await.expect("raced membership task"); assert_eq!( - rows("SELECT VALUE id FROM class_member", &db).await, + rows("class_member", &db).await, 0, "a parent may not be left on a class roster ({joined:?})" ); assert_eq!( - counter("SELECT VALUE class_member_count ?? 0 FROM class_group", &db).await, + counter("class_member_count", "class_group", &db).await, 0 ); }