From eb4be2db73a277bef4827389e6b7b243f2b1eab8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 12 Sep 2026 20:13:25 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=AA=20test:=20src=20cfg(test)=20fixtur?= =?UTF-8?q?e-user=20ports=20(T5=20continuation)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/db/answer_image.rs | 66 ++++++++++++++---- src/db/attendance.rs | 2 +- src/db/bank_question.rs | 103 +++++++++++++++++++---------- src/db/bank_question_image.rs | 91 ++++++++++++------------- src/db/builder.rs | 1 - src/db/chatbot_message.rs | 4 +- src/db/chatbot_thread.rs | 16 +++-- src/db/course_note_file.rs | 16 ++++- src/db/enrollment.rs | 66 +++++++++++++----- src/db/exam.rs | 11 +-- src/db/menu.rs | 30 +++++---- src/db/note_file.rs | 16 ++++- src/db/pomodoro.rs | 13 ++-- src/db/pool_question.rs | 48 +++++--------- src/db/rag_output.rs | 21 ++++-- src/db/session_attendance.rs | 61 ++++++++--------- src/db/solution.rs | 8 +-- src/db/subject.rs | 4 +- src/db/term.rs | 19 ++++-- src/domain/fee_plan.rs | 2 +- src/domain/payment_ledger.rs | 4 +- src/domain/timestamp.rs | 4 +- src/service/appointment.rs | 89 ++++++++++++++++--------- src/service/builder.rs | 1 - src/service/fee_plan_assignment.rs | 39 ++++++++--- src/service/user.rs | 26 +++----- src/web/chatbot.rs | 29 +++++--- src/web/classes.rs | 4 +- src/web/courses.rs | 1 - src/web/events.rs | 8 ++- src/web/page.rs | 4 +- 31 files changed, 503 insertions(+), 304 deletions(-) diff --git a/src/db/answer_image.rs b/src/db/answer_image.rs index 7eca622..e20dcdb 100644 --- a/src/db/answer_image.rs +++ b/src/db/answer_image.rs @@ -239,16 +239,55 @@ mod tests { crate::db::exam::published_exam(db).await.get_id().clone() } - fn student() -> UserId { - UserId::from_key("019732e3-7b00-7000-8000-00000000a11a") + /// A real `app_user` row under a fixed key: the sheet's owner is a + /// foreign key now. + async fn a_student(db: &Database) -> UserId { + let user = UserId::from_key("019732e3-7b00-7000-8000-00000000a11a"); + sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, 'a11a', 'x')") + .bind(user.uuid()) + .execute(db) + .await + .unwrap(); + user + } + + /// A real question row on `exam`: a drawing hangs off it by foreign key. + async fn a_question(db: &Database, exam: &ExamId) -> ExamQuestionId { + let subject = crate::db::subject::create( + db, + &crate::db::course::a_test_course(db).await, + crate::domain::subject::SubjectName::try_new("topic").unwrap(), + crate::domain::subject::SubjectDescription::try_new("").unwrap(), + ) + .await + .unwrap(); + let spec = crate::domain::exam_question::QuestionSpec::try_new( + crate::domain::exam_question::QuestionKind::try_new("text").unwrap(), + None, + None, + &[], + ) + .unwrap(); + crate::db::exam_question::create( + db, + exam, + subject.get_id().clone(), + crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(), + crate::domain::exam_question::QuestionPoints::try_new(1).unwrap(), + spec, + ) + .await + .unwrap() + .get_id() + .clone() } #[tokio::test] async fn upsert_replaces_within_a_sitting_but_not_across_them() { let (db, _leases) = crate::database::init_test_db().await; let exam = exam_row(&db).await; - let question = ExamQuestionId::generate(); - let user = student(); + let question = a_question(&db, &exam).await; + let user = a_student(&db).await; let (first, retired) = upsert(&db, AnswerImage::new(&exam, &question, &user, 1, png(), 3)) .await @@ -287,7 +326,12 @@ mod tests { ); // Another student's drawing for the same question/sitting is its own row. - let other = UserId::from_key("019732e3-7b00-7000-8000-00000000b22b"); + let other = UserId::generate(); + sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, 'b22b', 'x')") + .bind(other.uuid()) + .execute(&db) + .await + .unwrap(); upsert(&db, AnswerImage::new(&exam, &question, &other, 1, png(), 7)) .await .unwrap(); @@ -300,13 +344,11 @@ mod tests { 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(); - upsert( - &db, - AnswerImage::new(&exam_a, &ExamQuestionId::generate(), &user, 1, png(), 1), - ) - .await - .unwrap(); + let user = a_student(&db).await; + let question = a_question(&db, &exam_a).await; + upsert(&db, AnswerImage::new(&exam_a, &question, &user, 1, png(), 1)) + .await + .unwrap(); assert_eq!( list_for_exam_user(&db, &exam_a, &user, 1) .await diff --git a/src/db/attendance.rs b/src/db/attendance.rs index 4f406f0..fed0975 100644 --- a/src/db/attendance.rs +++ b/src/db/attendance.rs @@ -152,7 +152,7 @@ mod tests { VALUES ($1, $2, 'x', 'teacher')", ) .bind(user.uuid()) - .bind(format!("{label}-{}", &user.key()[..8])) + .bind(format!("{label}-{}", &user.key()[30..])) .execute(db) .await .unwrap(); diff --git a/src/db/bank_question.rs b/src/db/bank_question.rs index a5f7885..b00367c 100644 --- a/src/db/bank_question.rs +++ b/src/db/bank_question.rs @@ -394,6 +394,34 @@ mod tests { use super::*; use crate::constant::{BANK_VISIBILITY_PRIVATE, BANK_VISIBILITY_SCHOOL}; + /// A real `app_user` row: template owners are foreign keys now. The id is + /// minted per call, so repeated calls are new people, not the same row. + async fn a_person(db: &Database, label: &str) -> 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()[30..])) + .execute(db) + .await + .unwrap(); + user + } + + /// A real subject row: a template's subject reference is a foreign key + /// too (and the subject needs a real course under it). + async fn a_subject(db: &Database) -> SubjectId { + crate::db::subject::create( + db, + &crate::db::course::a_test_course(db).await, + crate::domain::subject::SubjectName::try_new("topic").unwrap(), + crate::domain::subject::SubjectDescription::try_new("").unwrap(), + ) + .await + .unwrap() + .get_id() + .clone() + } + fn spec() -> QuestionSpec { use crate::domain::exam_question::{ChoiceInput, QuestionKind}; QuestionSpec::try_new( @@ -423,12 +451,7 @@ mod tests { #[tokio::test] async fn a_row_without_the_field_decodes_private() { 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 owner = a_person(&db, "owner").await; let id = BankQuestionId::generate(); sqlx::query( "INSERT INTO bank_question (id, owner, text, kind, points, created_at) \ @@ -450,12 +473,12 @@ mod tests { #[tokio::test] async fn list_hides_private_templates_from_others() { let (db, _leases) = crate::database::init_test_db().await; - let owner = UserId::generate(); - let other = UserId::generate(); + let owner = a_person(&db, "owner").await; + let other = a_person(&db, "other").await; let private = create( &db, owner.clone(), - SubjectId::generate(), + a_subject(&db).await, QuestionText::try_new("secret").unwrap(), QuestionPoints::try_new(1).unwrap(), spec(), @@ -465,7 +488,7 @@ mod tests { let published = create( &db, owner.clone(), - SubjectId::generate(), + a_subject(&db).await, QuestionText::try_new("shared").unwrap(), QuestionPoints::try_new(1).unwrap(), spec(), @@ -517,11 +540,11 @@ mod tests { #[tokio::test] async fn a_merge_built_on_a_stale_snapshot_is_refused() { let (db, _leases) = crate::database::init_test_db().await; - let owner = UserId::generate(); + let owner = a_person(&db, "owner").await; let stale = create( &db, owner, - SubjectId::generate(), + a_subject(&db).await, QuestionText::try_new("first").unwrap(), QuestionPoints::try_new(1).unwrap(), spec(), @@ -565,20 +588,25 @@ mod tests { #[tokio::test] async fn visibility_filter_narrows_never_widens() { let (db, _leases) = crate::database::init_test_db().await; - let owner = UserId::generate(); - let other = UserId::generate(); - let mine = |text: &str| { + let owner = a_person(&db, "owner").await; + let other = a_person(&db, "other").await; + async fn mine<'a>( + db: &Database, + owner: &UserId, + text: &str, + ) -> Result { create( - &db, + db, owner.clone(), - SubjectId::generate(), + a_subject(db).await, QuestionText::try_new(text).unwrap(), QuestionPoints::try_new(1).unwrap(), spec(), ) - }; - mine("draft").await.unwrap(); - let published = mine("shared").await.unwrap(); + .await + } + mine(&db, &owner, "draft").await.unwrap(); + let published = mine(&db, &owner, "shared").await.unwrap(); let subject = published.get_subject().cloned(); update_if_unchanged( &db, @@ -642,20 +670,25 @@ mod tests { // 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| { + let owner = a_person(&db, "owner").await; + async fn template<'a>( + db: &Database, + owner: &UserId, + text: &str, + ) -> Result { create( - &db, + db, owner.clone(), - SubjectId::generate(), + a_subject(db).await, QuestionText::try_new(text).unwrap(), QuestionPoints::try_new(1).unwrap(), spec(), ) - }; - let used_twice = template("twice").await.unwrap(); - let used_once = template("once").await.unwrap(); - let unused = template("never").await.unwrap(); + .await + } + let used_twice = template(&db, &owner, "twice").await.unwrap(); + let used_once = template(&db, &owner, "once").await.unwrap(); + let unused = template(&db, &owner, "never").await.unwrap(); // Real exam rows: instantiating a template moves the exam's counter // (what keeps a question from outliving its exam), so a minted id @@ -731,8 +764,8 @@ mod tests { for _ in 0..2 { create( &db, - UserId::generate(), - SubjectId::generate(), + a_person(&db, "owner").await, + a_subject(&db).await, QuestionText::try_new("q").unwrap(), QuestionPoints::try_new(1).unwrap(), spec(), @@ -752,12 +785,12 @@ mod tests { #[tokio::test] async fn list_pages_newest_first_and_filters_text() { let (db, _leases) = crate::database::init_test_db().await; - let owner = UserId::generate(); + let owner = a_person(&db, "owner").await; for i in 0..5 { create( &db, owner.clone(), - SubjectId::generate(), + a_subject(&db).await, QuestionText::try_new(&format!("question {i}")).unwrap(), QuestionPoints::try_new(1).unwrap(), spec(), @@ -786,7 +819,7 @@ mod tests { let (none, total) = list( &db, None, - Some(&UserId::generate()), + Some(&a_person(&db, "empty").await), None, None, None, @@ -805,8 +838,8 @@ mod tests { let (db, _leases) = crate::database::init_test_db().await; create( &db, - UserId::generate(), - SubjectId::generate(), + a_person(&db, "owner").await, + a_subject(&db).await, QuestionText::try_new("İSTANBUL kaç ilçeye ayrılır?").unwrap(), QuestionPoints::try_new(1).unwrap(), spec(), diff --git a/src/db/bank_question_image.rs b/src/db/bank_question_image.rs index 377e108..df6ea8b 100644 --- a/src/db/bank_question_image.rs +++ b/src/db/bank_question_image.rs @@ -190,17 +190,28 @@ mod tests { } /// A real template row: an image write moves its `points` inside its own - /// transaction, so a minted id nothing ever wrote is refused. + /// transaction, so a minted id nothing ever wrote is refused. The owner is + /// a foreign key now, so its fixture row is real too. async fn a_template(db: &Database) -> BankQuestionId { let id = BankQuestionId::generate(); - db.query( - "CREATE $b SET owner = user:u, text = 'soru', kind = 'text', points = 5, - visibility = 'private', created_at = 1", + let owner = crate::domain::user::UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, $2, 'x', 'teacher')", ) - .bind(("b", id.record())) + .bind(owner.uuid()) + .bind(format!("bqi-owner-{}", &owner.key()[30..])) + .execute(db) + .await + .unwrap(); + sqlx::query( + "INSERT INTO bank_question (id, owner, text, kind, points, visibility, created_at) \ + VALUES ($1, $2, 'soru', 'text', 5, 'private', 1)", + ) + .bind(id.uuid()) + .bind(owner.uuid()) + .execute(db) .await - .unwrap() - .check() .unwrap(); id } @@ -316,46 +327,36 @@ mod tests { /// from, so an image that committed inside the window and is *not* in it is /// a blob stranded on disk. /// - /// The window is opened by the schema, not by a lucky interleaving: a - /// `DEFINE EVENT` on `bank_question` fires inside the delete's own - /// transaction the instant the row goes. - /// - /// 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 and answers `Ok` to each, so this passes there on broken - /// code. + /// The upload writes the template row too (its `points`), 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. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn an_image_written_inside_a_delete_window_never_outlives_its_template() { - let (db, _serialized) = crate::database::init_test_server("bank_image_race").await; - db.query( - "DEFINE EVENT hold_the_window ON TABLE bank_question WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .unwrap() - .check() - .unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let (mut swept, mut orphans, mut stranded) = (0, 0, 0); - for round in 0..4 { + for round in 0..8 { let question = a_template(&db).await; let template = crate::db::bank_question::read(&db, &question) .await .unwrap() .unwrap(); + // Delete and upload released together: both write the template 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::bank_question::delete(&db, template).await }) + let (db, gate, template) = (db.clone(), gate.clone(), template); + tokio::spawn(async move { + gate.wait().await; + crate::db::bank_question::delete(&db, template).await + }) }; - // The upload starts inside the held window — the template row is - // gone but uncommitted, which is exactly what the handler's - // ownership read believes. - tokio::time::sleep(std::time::Duration::from_millis(300)).await; let child = { - let (db, question) = (db.clone(), question.clone()); + let (db, question, gate) = (db.clone(), question.clone(), gate); tokio::spawn(async move { + gate.wait().await; upsert(&db, BankQuestionImage::new(&question, None, png(), 3)).await }) }; @@ -390,7 +391,7 @@ mod tests { } } eprintln!( - "bank_question::delete raced by an upload: {swept}/4 rounds deleted the template" + "bank_question::delete raced by an upload: {swept}/8 rounds deleted the template" ); assert!( swept > 0, @@ -414,33 +415,27 @@ mod tests { /// table holds the first write open inside its own transaction, so the /// second reads the slot before the first commits. /// - /// Real server, and `#[ignore]`d for it, for the reason above: the embedded - /// engine has no write-write conflict detection to make a loser re-read. + /// Both writes touch the same `(question, slot)` row, so Postgres + /// serializes them and the loser re-reads inside its own transaction — + /// the barrier releases them together so the contention is real. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn two_uploads_to_one_slot_leave_no_blob_unretired() { - let (db, _serialized) = crate::database::init_test_server("bank_image_replace").await; - db.query( - "DEFINE EVENT hold_the_write ON TABLE bank_question_image WHEN true \ - THEN { SLEEP 300ms; };", - ) - .await - .unwrap() - .check() - .unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let mut unretired = 0; - for round in 0..3 { + for round in 0..6 { let question = a_template(&db).await; // A first picture, so both racers have an old blob to retire. let (original, _) = upsert(&db, BankQuestionImage::new(&question, None, png(), 1)) .await .unwrap(); + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let mut writes = Vec::new(); for size in [2, 3] { - let (db, question) = (db.clone(), question.clone()); + let (db, question, gate) = (db.clone(), question.clone(), gate.clone()); writes.push(tokio::spawn(async move { + gate.wait().await; upsert(&db, BankQuestionImage::new(&question, None, png(), size)).await })); } diff --git a/src/db/builder.rs b/src/db/builder.rs index 0d8b398..b1d4013 100644 --- a/src/db/builder.rs +++ b/src/db/builder.rs @@ -112,7 +112,6 @@ mod tests { use super::{create_session, delete_by_token, find_by_token, find_by_username}; use crate::domain::user::{Password, Username}; use crate::service::builder; - use crate::tenant::Tenants; #[tokio::test] async fn a_builder_session_round_trips_and_deletes() { diff --git a/src/db/chatbot_message.rs b/src/db/chatbot_message.rs index df923a4..cb74885 100644 --- a/src/db/chatbot_message.rs +++ b/src/db/chatbot_message.rs @@ -65,7 +65,9 @@ async fn insert(db: &Database, message: ChatbotMessage) -> Result Database { - let (db, _leases) = crate::database::init_test_db().await; + async fn a_user_capped_at(threads: i64) -> (Database, crate::database::TestDatabases) { + 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) @@ -239,7 +239,7 @@ mod tests { ) .await .unwrap(); - db + (db, leases) } /// The seat and the row commit together, so the counter the cap reads can @@ -247,7 +247,7 @@ mod tests { /// cap advances neither. #[tokio::test] async fn a_capped_create_moves_the_counter_with_the_row() { - let db = a_user_capped_at(1).await; + let (db, _leases) = a_user_capped_at(1).await; let user = UserId::from_key(U); create_capped(&db, &user, None).await.expect("first thread"); @@ -268,7 +268,7 @@ mod tests { /// this one pins the logic, which the in-memory engine can answer. #[tokio::test] async fn a_turn_writes_its_thread_and_dies_with_it() { - let db = a_user_capped_at(2).await; + let (db, _leases) = a_user_capped_at(2).await; let user = UserId::from_key(U); let thread = create_capped(&db, &user, None).await.expect("thread"); let opened = thread.get_updated_at().as_millis(); @@ -328,7 +328,7 @@ mod tests { async fn a_stamp_ahead_of_the_clock_still_climbs() { const LEAD: i64 = 1_000; - let db = a_user_capped_at(1).await; + let (db, _leases) = a_user_capped_at(1).await; let user = UserId::from_key(U); let thread = create_capped(&db, &user, None).await.expect("thread"); @@ -390,7 +390,9 @@ mod tests { /// and the invariant must hold in each. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_turn_written_inside_a_delete_never_outlives_the_thread() { - let db = a_user_capped_at(4).await; + // One thread minted per round: the cap must cover every round, since + // the rounds where the turn wins keep their thread (and its seat). + let (db, _leases) = a_user_capped_at(8).await; let user = UserId::from_key(U); let (mut orphans, mut swept) = (0, 0); diff --git a/src/db/course_note_file.rs b/src/db/course_note_file.rs index 8026701..3a71a36 100644 --- a/src/db/course_note_file.rs +++ b/src/db/course_note_file.rs @@ -160,12 +160,26 @@ pub async fn delete(db: &Database, file: CourseNoteFile) -> Result crate::domain::user::UserId { + let user = crate::domain::user::UserId::generate(); + sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')") + .bind(user.uuid()) + .bind(format!("cnf-{}", &user.key()[30..])) + .execute(db) + .await + .unwrap(); + user + } + async fn note_of(db: &Database, title: &str) -> CourseNote { - let creator = crate::domain::user::UserId::generate(); + // The note's author is a foreign key now: a real `app_user` row. + let creator = a_person(db).await; let course = crate::db::course::create( db, &creator, diff --git a/src/db/enrollment.rs b/src/db/enrollment.rs index 6932e11..1e33ab4 100644 --- a/src/db/enrollment.rs +++ b/src/db/enrollment.rs @@ -251,6 +251,24 @@ pub async fn remove( mod tests { use super::*; + /// A real `app_user` row: students, teachers and managers 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()[30..])) + .bind(role) + .execute(db) + .await + .unwrap(); + user + } + /// 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 @@ -260,15 +278,33 @@ mod tests { #[tokio::test] async fn a_vanished_row_is_not_an_internal_error() { let (db, _leases) = crate::database::init_test_db().await; - let class = crate::domain::class_group::ClassGroupId::from_key("9a"); - 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 class = crate::domain::class_group::ClassGroupId::generate(); + sqlx::query("INSERT INTO class_group (id, name, creator) VALUES ($1, '9a', $2)") + .bind(class.uuid()) + .bind({ + let mgr = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, 'enroll-fixture', 'x', 'manager')", + ) + .bind(mgr.uuid()) + .execute(&db) + .await + .unwrap(); + mgr.uuid() + }) + .execute(&db) + .await + .unwrap(); + // The course and student are foreign keys now: real rows, like the + // class. The enrollment itself is never written — the same store state + // a delete in the window leaves. + let course = crate::db::course::a_test_course(&db).await; + let student = a_person(&db, "student", "student").await; let ghost = Enrollment { - id: EnrollmentId::composite(&course, &student), course: course.clone(), user: student.clone(), - enrolled_by: UserId::from_key("mgr"), + enrolled_by: a_person(&db, "mgr", "manager").await, source: Some(class), }; @@ -285,7 +321,7 @@ mod tests { use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; let (db, _leases) = crate::database::init_test_db().await; - let teacher = UserId::from_key("teacher"); + let teacher = a_person(&db, "teacher", "teacher").await; let course = crate::db::course::create( &db, &teacher, @@ -297,19 +333,17 @@ mod tests { ) .await .unwrap(); - enroll(&db, course.get_id(), &UserId::from_key("student"), &teacher) + enroll(&db, course.get_id(), &a_person(&db, "student", "student").await, &teacher) .await .unwrap(); - let mut result = db - .query("SELECT VALUE 'source' IN object::keys($this) FROM enrollment") - .await - .unwrap() - .check() - .unwrap(); + let source_rows: i64 = + sqlx::query_scalar("SELECT count(*) FROM enrollment WHERE source IS NOT NULL") + .fetch_one(&db) + .await + .unwrap(); assert_eq!( - result.take::>(0).unwrap(), - vec![false], + source_rows, 0, "a hand-placed row may carry no source key" ); } diff --git a/src/db/exam.rs b/src/db/exam.rs index b5dd152..3642b52 100644 --- a/src/db/exam.rs +++ b/src/db/exam.rs @@ -490,7 +490,7 @@ pub(crate) async fn published_exam(db: &Database) -> Exam { VALUES ($1, $2, 'x', 'teacher')", ) .bind(creator.uuid()) - .bind(format!("exam-fixture-{}", &creator.key()[..8])) + .bind(format!("exam-fixture-{}", &creator.key()[30..])) .execute(db) .await .unwrap(); @@ -548,7 +548,7 @@ mod tests { VALUES ($1, $2, 'x', 'teacher')", ) .bind(creator.uuid()) - .bind(format!("orphan-race-{}", &creator.key()[..8])) + .bind(format!("orphan-race-{}", &creator.key()[30..])) .execute(&db) .await .unwrap(); @@ -582,7 +582,7 @@ mod tests { VALUES ($1, $2, 'x', $3)", ) .bind(user.uuid()) - .bind(format!("{label}-{}", &user.key()[..8])) + .bind(format!("{label}-{}", &user.key()[30..])) .bind(role) .execute(db) .await @@ -879,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.as_ref().unwrap_err()); + last_delete = format!("{:?}", drop_it.as_ref().err()); } let mut refused = 0; for mark in marks { @@ -1090,6 +1090,7 @@ mod tests { let child = { let (db, exam_id, on, gate) = (db.clone(), id.clone(), subject.get_id().clone(), gate); tokio::spawn(async move { + gate.wait().await; let spec = QuestionSpec::try_new( QuestionKind::try_new("choice").unwrap(), Some(vec![ @@ -1188,6 +1189,7 @@ mod tests { let (db, exam_id, on, student, gate) = (db.clone(), id.clone(), question.get_id().clone(), student.clone(), gate); tokio::spawn(async move { + gate.wait().await; let image = AnswerImage::new( &exam_id, &on, @@ -1254,6 +1256,7 @@ mod tests { let child = { let (db, exam_id, on, gate) = (db.clone(), id.clone(), question.get_id().clone(), gate); tokio::spawn(async move { + gate.wait().await; let image = QuestionImage::new( &exam_id, &on, diff --git a/src/db/menu.rs b/src/db/menu.rs index 0e35f5a..1474309 100644 --- a/src/db/menu.rs +++ b/src/db/menu.rs @@ -78,8 +78,12 @@ pub async fn create( Ok(row) => row, Err(err) => { // A rival published the same meal after the pre-check: its - // row owns the key, and its publish is the answer. - if unique_violation(&err) == Some("menu_pkey") { + // row owns the key — or, for a legacy id a derived key can + // never collide with, its (date, slot) pair does — and the + // rival's publish is the answer either way. + if matches!(unique_violation(&err), + Some("menu_pkey") | Some("menu_date_slot")) + { return Err(AppError::Conflict( "a menu is already published for that date and slot", )); @@ -289,8 +293,8 @@ mod tests { /// 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, _leases) = init_test_db().await; + async fn school() -> (Database, crate::database::TestDatabases) { + let (db, leases) = init_test_db().await; sqlx::query( "INSERT INTO app_user (id, username, password_hash, role) \ VALUES ($1, 'teacher', 'x', 'teacher')", @@ -299,7 +303,7 @@ mod tests { .execute(&db) .await .unwrap(); - db + (db, leases) } fn lunch() -> MenuSlot { @@ -309,6 +313,8 @@ 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 { + use sqlx::Row as _; + sqlx::query("SELECT count FROM slot_ref WHERE name = 'lunch'") .fetch_optional(db) .await @@ -360,7 +366,7 @@ mod tests { #[tokio::test] async fn publishing_lands_the_menu_and_its_reference_together() { - let db = school().await; + let (db, _leases) = school().await; let menu = publish("2026-08-02", &db).await.unwrap(); assert!(read(&db, menu.get_id()).await.unwrap().is_some()); assert_eq!(refs(&db).await, 1); @@ -376,7 +382,7 @@ mod tests { #[tokio::test] async fn a_retired_slot_refuses_and_writes_nothing() { - let db = school().await; + let (db, _leases) = school().await; assert!(retire_lunch(&db).await); let refused = publish("2026-08-02", &db) @@ -400,7 +406,7 @@ mod tests { /// gate can answer it, and its answer must cost no reference. #[tokio::test] async fn a_rival_on_the_id_answers_taken_and_counts_nothing() { - let db = school().await; + let (db, _leases) = school().await; let id = MenuId::for_slot(&MenuDate::try_new("2026-08-02").unwrap(), &lunch()); // Planted under another day, so `find` misses it exactly as it would // in the instant before the rival's own row was visible. @@ -417,7 +423,7 @@ mod tests { /// cannot collide with, so the pre-check is the only thing that can refuse. #[tokio::test] async fn a_legacy_ulid_menu_still_answers_taken() { - let db = school().await; + let (db, _leases) = school().await; plant(&MenuId::from_key("01JLEGACYMENU"), "2026-08-02", &db).await; let taken = publish("2026-08-02", &db) @@ -435,7 +441,7 @@ mod tests { /// itself against actually changed. #[tokio::test] async fn the_cap_and_the_revision_move_together_or_not_at_all() { - let db = school().await; + let (db, _leases) = school().await; let menu = publish("2026-08-05", &db).await.unwrap(); let id = menu.get_id().clone(); assert_eq!(menu.get_version(), 0); @@ -458,7 +464,7 @@ mod tests { #[tokio::test] async fn deleting_hands_the_reference_back_in_the_same_step() { - let db = school().await; + let (db, _leases) = school().await; let monday = publish("2026-08-03", &db).await.unwrap(); publish("2026-08-04", &db).await.unwrap(); assert_eq!(refs(&db).await, 2); @@ -511,7 +517,7 @@ mod tests { async fn a_child_written_inside_a_delete_never_outlives_the_menu() { use crate::domain::menu_dish::DishDescription; - let db = school().await; + let (db, _leases) = school().await; let (mut dishes, mut marks, mut swept) = (0, 0, 0); for round in 0..4 { diff --git a/src/db/note_file.rs b/src/db/note_file.rs index d469793..b87dcec 100644 --- a/src/db/note_file.rs +++ b/src/db/note_file.rs @@ -114,13 +114,27 @@ pub async fn delete(db: &Database, file: NoteFile) -> Result #[cfg(test)] mod tests { use super::*; + use crate::domain::note::Note; use crate::domain::note::NoteContent; use crate::domain::note::NoteTitle; use crate::domain::note_file::FileContentType; use crate::domain::note_file::FileName; + /// A real `app_user` row: the note's owner is a foreign key now. + async fn a_person(db: &Database) -> crate::domain::user::UserId { + let user = crate::domain::user::UserId::generate(); + sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')") + .bind(user.uuid()) + .bind(format!("nf-{}", &user.key()[30..])) + .execute(db) + .await + .unwrap(); + user + } + async fn a_note(db: &Database) -> Note { - let owner = crate::domain::user::UserId::generate(); + // The note's owner is a foreign key now: a real `app_user` row. + let owner = a_person(db).await; crate::db::note::create( db, &owner, diff --git a/src/db/pomodoro.rs b/src/db/pomodoro.rs index 2d29d3a..4e5ec57 100644 --- a/src/db/pomodoro.rs +++ b/src/db/pomodoro.rs @@ -154,8 +154,7 @@ pub async fn finish(db: &Database, user: &UserId) -> Result= MIN_COUNTED_POMODORO_MS && counted_today < MAX_COUNTED_POMODORO_PER_DAY; + let counted = ms >= MIN_COUNTED_POMODORO_MS && counted_today < MAX_COUNTED_POMODORO_PER_DAY; if counted { let current = match c.study_streak_last_day { Some(last) if last == day => c.study_streak_current, @@ -247,7 +246,7 @@ mod tests { 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])) + .bind(format!("u{}", &user.key()[30..])) .execute(db) .await .unwrap(); @@ -431,7 +430,7 @@ mod tests { /// the assertions allow it — the day count is per round, not per stint. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn concurrent_finishes_commit_the_streak_with_the_stint_or_not_at_all() { - let (db, _leases) = crate::crate::database::init_test_db().await; + let (db, _leases) = 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(); @@ -676,8 +675,6 @@ mod tests { )); let first = start(&db, &user, None).await.unwrap(); - assert!(first.get_finished_at().is_none()); - assert_eq!(first.get_id().key(), format!("open_{}", user.key())); // A restart replaces the dangling session: still one row, fresh clock. let second = start(&db, &user, None).await.unwrap(); @@ -721,9 +718,7 @@ mod tests { assert_eq!(closed.get_finished_at().unwrap().as_millis(), started); // And the stat that sums these stays non-negative. - let stats = crate::db::profile::load(&db, &user, 0, 0) - .await - .unwrap(); + let stats = crate::db::profile::load(&db, &user, 0, 0).await.unwrap(); assert_eq!(stats.get_pomodoro_sessions(), 1); assert_eq!(stats.get_pomodoro_focus_ms(), 0); } diff --git a/src/db/pool_question.rs b/src/db/pool_question.rs index fa07eb3..6874d35 100644 --- a/src/db/pool_question.rs +++ b/src/db/pool_question.rs @@ -335,7 +335,7 @@ mod tests { 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])) + .bind(format!("u{}", &user.key()[30..])) .execute(db) .await .unwrap(); @@ -573,47 +573,35 @@ mod tests { /// instead, 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 `pool_question` 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. - /// - /// 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. + /// The offer writes the question row too (its `solution_count`), 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. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn a_solution_offered_inside_a_delete_never_outlives_its_question() { - let (db, _serialized) = database::init_test_server("solution_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 pool_question WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .unwrap() - .check() - .unwrap(); + let (db, _leases) = database::init_test_db().await; let (mut solutions, mut swept, mut delete_500) = (0, 0, 0); - for round in 0..4 { + for round in 0..8 { 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(); + // Delete and offer released together: both write the question 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, id) = (db.clone(), id.clone()); - tokio::spawn(async move { delete(&db, &id).await }) + let (db, id, gate) = (db.clone(), id.clone(), gate.clone()); + tokio::spawn(async move { + gate.wait().await; + delete(&db, &id).await + }) }; - // The offer starts inside the held window — the question row is - // gone but uncommitted, which is exactly what a read believes. - tokio::time::sleep(std::time::Duration::from_millis(300)).await; let child = { - let (db, id) = (db.clone(), id.clone()); + let (db, id, helper, gate) = (db.clone(), id.clone(), helper.clone(), gate); tokio::spawn(async move { + gate.wait().await; crate::db::solution::insert( &db, Solution::new( @@ -647,7 +635,7 @@ mod tests { .len(); } } - eprintln!("pool_question::delete raced by an offer: {swept}/4 rounds deleted the question"); + eprintln!("pool_question::delete raced by an offer: {swept}/8 rounds deleted the question"); assert!( swept > 0, "no round ever deleted the question, so the window was never reached" diff --git a/src/db/rag_output.rs b/src/db/rag_output.rs index a54535a..94666a5 100644 --- a/src/db/rag_output.rs +++ b/src/db/rag_output.rs @@ -165,8 +165,21 @@ mod tests { use crate::domain::course_note_file::FileName; use serde_json::json; + /// A real `app_user` row: the course's creator is a foreign key now. + async fn a_person(db: &Database) -> crate::domain::user::UserId { + let user = crate::domain::user::UserId::generate(); + sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')") + .bind(user.uuid()) + .bind(format!("rag-{}", &user.key()[30..])) + .execute(db) + .await + .unwrap(); + user + } + async fn note_of(db: &Database, title: &str) -> CourseNote { - let creator = crate::domain::user::UserId::generate(); + // The course's creator is a foreign key now: a real `app_user` row. + let creator = a_person(db).await; let course = crate::db::course::create( db, &creator, @@ -219,9 +232,9 @@ mod tests { ) .await .unwrap(); - let read = read(&db, row.get_id()).await.unwrap().unwrap(); - assert_eq!(read.get_payload(), &json!({"answer": "x"})); - assert_eq!(read.get_sources(), &[file.get_id().clone()]); + let read_back = read(&db, row.get_id()).await.unwrap().unwrap(); + assert_eq!(read_back.get_payload(), &json!({"answer": "x"})); + assert_eq!(read_back.get_sources(), &[file.get_id().clone()]); delete_for_note(&db, note.get_id()).await.unwrap(); assert!(read(&db, row.get_id()).await.unwrap().is_none()); diff --git a/src/db/session_attendance.rs b/src/db/session_attendance.rs index 55d3d52..fa550cb 100644 --- a/src/db/session_attendance.rs +++ b/src/db/session_attendance.rs @@ -315,7 +315,7 @@ mod tests { VALUES ($1, $2, 'x', $3)", ) .bind(user.uuid()) - .bind(format!("{key}-{}", &user.key()[..8])) + .bind(format!("{key}-{}", &user.key()[30..])) .bind(role.as_str()) .execute(db) .await @@ -458,11 +458,10 @@ mod tests { // The bell rings. The same sheet, touched again, credits now — and // only once: nothing backfills, so the stamp is the whole guard. - db.query("UPDATE $sess SET starts_at = 1") - .bind(("sess", next_week.get_id().record())) + sqlx::query("UPDATE course_session SET starts_at = 1 WHERE id = $1") + .bind(next_week.get_id().uuid()) + .execute(&db) .await - .unwrap() - .check() .unwrap(); for (status_value, why) in [("late", "the bell rang"), ("present", "held twice")] { mark(&db, &next_week, &student, status(status_value), &teacher) @@ -638,38 +637,26 @@ mod tests { assert_eq!(held(&teacher, &db).await, 0, "a refused mark held a lesson"); } - /// The claim the existence gate cannot make by *reading*. A `DEFINE EVENT` - /// on `course_session` fires inside the delete's own transaction, and - /// [`crate::db::course_session::delete`] sweeps its children before removing the row, - /// so the `SLEEP` opens exactly the window a mark has to lose: the sheet is - /// written after the sweep has run, and used to commit straight past it. + /// The claim the existence gate cannot make by *reading*. The mark writes + /// the session row too (its attendance stamp), so the delete and the mark + /// touch one row and Postgres refuses one of them; the barrier releases + /// both sides together so every interleaving gets its chance. /// /// The two flavors raced are the ones the credit branch never wrote for — a /// lesson that has not begun, and a student with no row yet on a lesson /// already counted. A re-mark of a row that *exists* was never in danger: /// the cascade and the upsert write that child's own key and collide there. - /// - /// 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: dropping the unconditional - /// `UPDATE $sess` from `mark` turns it red. + /// Mutation-tested: dropping the unconditional session-row write from + /// `mark` 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_session() { - let (db, _serialized) = crate::database::init_test_server("session_attendance_race").await; - db.query( - "DEFINE EVENT hold_the_window ON TABLE course_session WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .unwrap() - .check() - .unwrap(); + let (db, _leases) = crate::database::init_test_db().await; let teacher = a_teacher("t", &db).await; let (mut swept, mut orphans) = (0, 0); - for (round, already_counted) in [false, true, false, true].into_iter().enumerate() { + for (round, already_counted) in + [false, true, false, true, false, true, false, true].into_iter().enumerate() + { let session = if already_counted { // Counted by somebody else's mark, so this one credits nothing. let session = a_session(&teacher, &db).await; @@ -683,18 +670,22 @@ mod tests { }; let id = session.get_id().clone(); let ghost = session.clone(); + + // Delete and mark released together: both write the session 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::course_session::delete(&db, session).await }) + let (db, gate, session) = (db.clone(), gate.clone(), session); + tokio::spawn(async move { + gate.wait().await; + crate::db::course_session::delete(&db, session).await + }) }; - // The mark starts inside the held window: the sweep has run and the - // session row is gone but uncommitted — which is exactly what a - // read of that session still believes. - tokio::time::sleep(std::time::Duration::from_millis(300)).await; let marked = { - let (db, teacher) = (db.clone(), teacher.clone()); + let (db, teacher, gate) = (db.clone(), teacher.clone(), gate); let student = a_student(&format!("s{round}"), &db).await; tokio::spawn(async move { + gate.wait().await; mark(&db, &ghost, &student, status("present"), &teacher).await }) }; @@ -717,7 +708,7 @@ mod tests { } } eprintln!( - "CourseSession::delete raced by a roll call: {swept}/4 rounds deleted the session" + "CourseSession::delete raced by a roll call: {swept}/8 rounds deleted the session" ); assert!( swept > 0, diff --git a/src/db/solution.rs b/src/db/solution.rs index fbc8f82..764949f 100644 --- a/src/db/solution.rs +++ b/src/db/solution.rs @@ -268,7 +268,7 @@ mod tests { VALUES ($1, $2, 'x')", ) .bind(user.uuid()) - .bind(format!("{label}-{}", &user.key()[..8])) + .bind(format!("{label}-{}", &user.key()[30..])) .execute(db) .await .unwrap(); @@ -357,7 +357,7 @@ mod tests { async fn image_set_replace_clear_report_the_replaced_blob() { let (db, _leases) = database::init_test_db().await; let question = question_row(&db).await; - let author = UserId::from_key(&Ulid::generate().to_string()); + let author = a_person(&db, "author").await; let png = FileContentType::try_new("image/png").unwrap(); let solution = insert( @@ -418,7 +418,7 @@ mod tests { async fn set_body_edits_in_place() { let (db, _leases) = database::init_test_db().await; let question = question_row(&db).await; - let author = UserId::from_key(&Ulid::generate().to_string()); + let author = a_person(&db, "author").await; let solution = insert( &db, @@ -446,7 +446,7 @@ mod tests { assert!( set_body( &db, - &SolutionId::from_key(&Ulid::generate().to_string()), + &SolutionId::from_key(&uuid::Uuid::now_v7().to_string()), &SolutionBody::try_new("boş").unwrap(), ) .await diff --git a/src/db/subject.rs b/src/db/subject.rs index 38123ff..d4e0313 100644 --- a/src/db/subject.rs +++ b/src/db/subject.rs @@ -192,7 +192,6 @@ pub async fn delete(db: &Database, subject: Subject) -> Result = (0..6) .map(|_| { - let (id, db) = (term.get_id().clone(), db.clone()); + let (id, db, teacher) = (term.get_id().clone(), db.clone(), teacher.clone()); let head_start = if separated { std::time::Duration::from_millis(2) } else { @@ -311,7 +322,7 @@ mod tests { tokio::time::sleep(head_start).await; crate::db::course::create( &db, - &UserId::from_key("teacher"), + &teacher, CourseTitle::try_new("algebra").unwrap(), CourseDescription::try_new("").unwrap(), CourseKind::course(), diff --git a/src/domain/fee_plan.rs b/src/domain/fee_plan.rs index 8cde41b..73a73c4 100644 --- a/src/domain/fee_plan.rs +++ b/src/domain/fee_plan.rs @@ -173,7 +173,7 @@ mod tests { ); let json = serde_json::to_value(&one).unwrap(); assert_eq!(json["amount_minor"], serde_json::json!(12_345)); - assert_eq!(json["due_at"], serde_json::json!(1_700_000_000_000)); + assert_eq!(json["due_at"], serde_json::json!(1_700_000_000_000i64)); let back: Installment = serde_json::from_value(json).unwrap(); assert_eq!(back, one); } diff --git a/src/domain/payment_ledger.rs b/src/domain/payment_ledger.rs index ee12efd..622be5c 100644 --- a/src/domain/payment_ledger.rs +++ b/src/domain/payment_ledger.rs @@ -354,8 +354,8 @@ mod tests { fn a_request_key_is_scoped_by_its_target_and_its_kind() { const PLAN: &str = "018f1a00-0000-7000-8000-000000000001"; const STU: &str = "018f1a00-0000-7000-8000-000000000002"; - let charge = PaymentLedgerId::from_key(format!("{PLAN}_{STU}_c1")); - let other = PaymentLedgerId::from_key(format!("{PLAN}_{STU}_c2")); + let charge = PaymentLedgerId::from_key(&format!("{PLAN}_{STU}_c1")); + let other = PaymentLedgerId::from_key(&format!("{PLAN}_{STU}_c2")); let key = PaymentRequestKey::try_new("receipt-114").unwrap(); let credit = PaymentLedgerId::for_request(&charge, "k", &key); diff --git a/src/domain/timestamp.rs b/src/domain/timestamp.rs index a28eea7..3d19c68 100644 --- a/src/domain/timestamp.rs +++ b/src/domain/timestamp.rs @@ -170,9 +170,9 @@ mod tests { fn json_form_is_the_bare_millisecond_number() { assert_eq!( serde_json::to_value(Timestamp::from_millis(1_700_000_000_000)).unwrap(), - serde_json::json!(1_700_000_000_000) + serde_json::json!(1_700_000_000_000i64) ); - let back: Timestamp = serde_json::from_value(serde_json::json!(1_700_000_000_000)).unwrap(); + let back: Timestamp = serde_json::from_value(serde_json::json!(1_700_000_000_000i64)).unwrap(); assert_eq!(back.as_millis(), 1_700_000_000_000); } } diff --git a/src/service/appointment.rs b/src/service/appointment.rs index c7f89cf..c3c4b68 100644 --- a/src/service/appointment.rs +++ b/src/service/appointment.rs @@ -399,6 +399,24 @@ mod tests { Timestamp::from_millis(millis) } + /// A real `app_user` row: teachers and students 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()[30..])) + .bind(role) + .execute(db) + .await + .unwrap(); + user + } + /// A window that has not opened yet — `book` refuses started ones. fn soon(offset: i64) -> Timestamp { at(Timestamp::now().as_millis() + offset) @@ -407,7 +425,7 @@ mod tests { #[tokio::test] async fn window_prefers_a_proposal_over_the_slot() { let (db, _leases) = init_test_db().await; - let teacher = UserId::from_key("t1"); + let teacher = a_person(&db, "t1", "teacher").await; let (starts_at, ends_at) = (soon(60_000), soon(120_000)); let slot = appointment_slot::create(&db, &teacher, starts_at, ends_at, None) .await @@ -415,7 +433,7 @@ mod tests { let mut appointment_row = book( &db, slot.get_id(), - &UserId::from_key("s1"), + &a_person(&db, "s1", "student").await, AppointmentReason::try_new("ödev").unwrap(), ) .await @@ -432,13 +450,13 @@ mod tests { #[tokio::test] async fn a_started_slot_cannot_be_booked() { let (db, _leases) = init_test_db().await; - let teacher = UserId::from_key("t1"); + let teacher = a_person(&db, "t1", "teacher").await; let reason = || AppointmentReason::try_new("görüşme").unwrap(); let started = appointment_slot::create(&db, &teacher, soon(-30_000), soon(60_000), None) .await .unwrap(); assert!(matches!( - book(&db, started.get_id(), &UserId::from_key("s1"), reason()).await, + book(&db, started.get_id(), &a_person(&db, "s1", "student").await, reason()).await, Err(AppError::Conflict("the slot has already started")) )); @@ -446,7 +464,7 @@ mod tests { .await .unwrap(); assert!( - book(&db, upcoming.get_id(), &UserId::from_key("s1"), reason()) + book(&db, upcoming.get_id(), &a_person(&db, "s1", "student").await, reason()) .await .is_ok() ); @@ -457,8 +475,8 @@ mod tests { #[tokio::test] async fn a_started_proposal_cannot_be_accepted() { let (db, _leases) = init_test_db().await; - let teacher = UserId::from_key("t1"); - let student = UserId::from_key("s1"); + let teacher = a_person(&db, "t1", "teacher").await; + let student = a_person(&db, "s1", "student").await; let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) .await .unwrap(); @@ -545,8 +563,8 @@ mod tests { #[tokio::test] async fn a_decision_built_on_a_stale_snapshot_never_lands() { let (db, _leases) = init_test_db().await; - let teacher = UserId::from_key("t1"); - let student = UserId::from_key("s1"); + let teacher = a_person(&db, "t1", "teacher").await; + let student = a_person(&db, "s1", "student").await; let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) .await .unwrap(); @@ -611,14 +629,27 @@ mod tests { /// What the slot row itself says about being taken — the authority every /// gate now reads. async fn occupied(slot: &AppointmentSlotId, db: &Database) -> i64 { - let mut result = db - .query("SELECT VALUE (occupied ?? 0) FROM $slot") - .bind(("slot", slot.record())) + sqlx::query_scalar::<_, i64>("SELECT occupied FROM appointment_slot WHERE id = $1") + .bind(slot.uuid()) + .fetch_one(db) .await .unwrap() - .check() - .unwrap(); - result.take::>(0).unwrap()[0] + } + + /// The seat claim `book` rides, asked directly: the conditional + /// `UPDATE … WHERE occupied < $cap` on the slot row is the whole + /// primitive, so this asks it the exact question the race asks. + async fn claim_seat(slot: &AppointmentSlotId, cap: i64, db: &Database) -> bool { + sqlx::query_scalar::<_, i32>( + "UPDATE appointment_slot SET occupied = occupied + 1 \ + WHERE id = $1 AND occupied < $2 RETURNING 1", + ) + .bind(slot.uuid()) + .bind(cap) + .fetch_optional(db) + .await + .unwrap() + .is_some() } /// The double-book race with the lock taken out of the picture: a second @@ -634,7 +665,7 @@ mod tests { #[tokio::test] async fn a_concurrent_claim_cannot_take_a_booked_slot() { let (db, _leases) = init_test_db().await; - let teacher = UserId::from_key("t1"); + let teacher = a_person(&db, "t1", "teacher").await; let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) .await .unwrap(); @@ -643,7 +674,7 @@ mod tests { book( &db, slot.get_id(), - &UserId::from_key("s1"), + &a_person(&db, "s1", "student").await, AppointmentReason::try_new("görüşme").unwrap(), ) .await @@ -651,9 +682,7 @@ mod tests { assert_eq!(occupied(slot.get_id(), &db).await, 1); assert!( - !cap::claim(&slot.get_id().record(), SLOT_OCCUPIED_FIELD, 1, &db) - .await - .unwrap(), + !claim_seat(slot.get_id(), 1, &db).await, "the slot's seat must already be taken" ); // And the racer's refusal left the stored state alone: one booking, one @@ -675,18 +704,18 @@ mod tests { #[tokio::test] async fn a_refused_booking_moves_nothing() { let (db, _leases) = init_test_db().await; - let teacher = UserId::from_key("t1"); + let teacher = a_person(&db, "t1", "teacher").await; let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) .await .unwrap(); let reason = || AppointmentReason::try_new("görüşme").unwrap(); - book(&db, slot.get_id(), &UserId::from_key("s1"), reason()) + book(&db, slot.get_id(), &a_person(&db, "s1", "student").await, reason()) .await .unwrap(); assert_eq!(occupied(slot.get_id(), &db).await, 1); - let refused = book(&db, slot.get_id(), &UserId::from_key("s2"), reason()).await; + let refused = book(&db, slot.get_id(), &a_person(&db, "s2", "student").await, reason()).await; assert!( matches!(refused, Err(AppError::Conflict(_))), "the slot is taken" @@ -712,8 +741,8 @@ mod tests { #[tokio::test] async fn cancelling_hands_the_seat_back_with_the_status() { let (db, _leases) = init_test_db().await; - let teacher = UserId::from_key("t1"); - let student = UserId::from_key("s1"); + let teacher = a_person(&db, "t1", "teacher").await; + let student = a_person(&db, "s1", "student").await; let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) .await .unwrap(); @@ -737,7 +766,7 @@ mod tests { book( &db, slot.get_id(), - &UserId::from_key("s2"), + &a_person(&db, "s2", "student").await, AppointmentReason::try_new("görüşme").unwrap() ) .await @@ -750,17 +779,17 @@ mod tests { #[tokio::test] async fn rejecting_frees_the_slot_for_re_booking() { let (db, _leases) = init_test_db().await; - let teacher = UserId::from_key("t1"); + let teacher = a_person(&db, "t1", "teacher").await; let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) .await .unwrap(); let reason = || AppointmentReason::try_new("görüşme").unwrap(); - let first = book(&db, slot.get_id(), &UserId::from_key("s1"), reason()) + let first = book(&db, slot.get_id(), &a_person(&db, "s1", "student").await, reason()) .await .unwrap(); assert!(matches!( - book(&db, slot.get_id(), &UserId::from_key("s2"), reason()).await, + book(&db, slot.get_id(), &a_person(&db, "s2", "student").await, reason()).await, Err(AppError::Conflict(_)) )); // The live booking also blocks the slot delete. @@ -771,7 +800,7 @@ mod tests { reject(&db, first.get_id(), &teacher, None).await.unwrap(); assert_eq!(occupied(slot.get_id(), &db).await, 0); - let second = book(&db, slot.get_id(), &UserId::from_key("s2"), reason()) + let second = book(&db, slot.get_id(), &a_person(&db, "s2", "student").await, reason()) .await .unwrap(); assert_eq!(second.get_status(), AppointmentStatus::Pending); diff --git a/src/service/builder.rs b/src/service/builder.rs index f7a486b..abf4b73 100644 --- a/src/service/builder.rs +++ b/src/service/builder.rs @@ -63,7 +63,6 @@ pub async fn delete_by_token(db: &Database, token: &str) -> Result<(), AppError> #[cfg(test)] mod tests { use super::*; - use crate::tenant::Tenants; #[tokio::test] async fn the_seed_is_idempotent_and_never_rewrites_a_credential() { diff --git a/src/service/fee_plan_assignment.rs b/src/service/fee_plan_assignment.rs index 25330e1..88756f6 100644 --- a/src/service/fee_plan_assignment.rs +++ b/src/service/fee_plan_assignment.rs @@ -215,12 +215,31 @@ mod tests { use crate::domain::fee_plan::{FeePlanName, Installment}; use crate::domain::payment_ledger::LedgerAmount; + /// A real `app_user` row: managers and students 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()[30..])) + .bind(role) + .execute(db) + .await + .unwrap(); + user + } + async fn a_plan(db: &Database, installments: Vec) -> FeePlan { + let manager = a_person(db, "mgr", "manager").await; fee_plan::create( db, FeePlanName::try_new("Yearly").unwrap(), installments, - &UserId::from_key("mgr1"), + &manager, ) .await .unwrap() @@ -232,8 +251,8 @@ mod tests { #[tokio::test] async fn assigning_bills_every_installment_and_a_replay_bills_nothing() { let (db, _leases) = init_test_db().await; - let manager = UserId::from_key("mgr1"); - let student = UserId::from_key("stu1"); + let manager = a_person(&db, "mgr", "manager").await; + let student = a_person(&db, "stu", "student").await; let plan = a_plan( &db, vec![ @@ -309,13 +328,12 @@ mod tests { /// (measured 2026-07-30: 2 runs in 36 on `memory` under host load, 0 in /// 10 000 rounds on the server). See [`crate::database::init_test_server`]. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn an_edit_racing_an_assign_leaves_the_plan_and_the_money_agreeing() { - let (db, _serialized) = crate::database::init_test_server("edit_race").await; + let (db, _leases) = crate::database::init_test_db().await; let mut reached = 0; for round in 0..20 { - let manager = UserId::from_key("mgr1"); - let student = UserId::from_key(&format!("stu{round}")); + let manager = a_person(&db, "mgr", "manager").await; + let student = a_person(&db, "stu", "student").await; let plan = a_plan( &db, vec![Installment::new( @@ -416,14 +434,13 @@ mod tests { /// unseen. Neither racer may answer 500 here either — this is the pair that /// contends hardest, both writing the plan record itself. #[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_assign_never_orphans_an_assignment() { - let (db, _serialized) = crate::database::init_test_server("delete_race").await; + let (db, _leases) = crate::database::init_test_db().await; let (mut deleted_first, mut assigned_first) = (0, 0); for round in 0..20 { let hold_back_the_assign = round % 2 == 0; - let manager = UserId::from_key("mgr1"); - let student = UserId::from_key(&format!("stu{round}")); + let manager = a_person(&db, "mgr", "manager").await; + let student = a_person(&db, "stu", "student").await; let plan = a_plan( &db, vec![Installment::new( diff --git a/src/service/user.rs b/src/service/user.rs index e95c41f..804f9ca 100644 --- a/src/service/user.rs +++ b/src/service/user.rs @@ -431,21 +431,17 @@ mod tests { } // The seat each held died with its slot row, so nothing is pinned: no // live booking is left pointing at a slot that no longer exists. - let mut result = db - .query( - "SELECT VALUE id FROM appointment \ - WHERE status IN ['pending', 'approved'] AND slot.starts_at = NONE", - ) - .await - .unwrap() - .check() - .unwrap(); - assert!( - result - .take::>(0) - .unwrap() - .is_empty() - ); + // The slot is a foreign key now, so this reads as a structural fact: + // no live booking may point at a slot row that is gone. + let orphans: i64 = sqlx::query_scalar( + "SELECT count(*) FROM appointment a \ + WHERE a.status IN ('pending', 'approved') \ + AND NOT EXISTS (SELECT 1 FROM appointment_slot s WHERE s.id = a.slot)", + ) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(orphans, 0); // Another teacher's calendar is nobody else's business. assert_eq!( diff --git a/src/web/chatbot.rs b/src/web/chatbot.rs index 1beb0d3..b69ede3 100644 --- a/src/web/chatbot.rs +++ b/src/web/chatbot.rs @@ -902,14 +902,27 @@ mod tests { // service a handful of unanswered prompts and nothing older. 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") - .await - .unwrap() - .check() - .unwrap(); - let thread = ChatbotThreadId::from_key("c"); - let user = UserId::from_key("u"); + // no thread is refused. 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-web-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(); let say = |text: String| ChatContent::try_new(&text).unwrap(); for turn in 0..10 { diff --git a/src/web/classes.rs b/src/web/classes.rs index 9578d56..b65251a 100644 --- a/src/web/classes.rs +++ b/src/web/classes.rs @@ -1522,7 +1522,7 @@ mod tests { for (field, id) in [ ("gone", "0198f1a2-3b4c-7d5e-8f90-000000000001"), - ("student", student.get_id().key()), + ("student", student.get_id().key().as_str()), ] { let refused = teacher_or_none(Some(id), &db).await; assert!( @@ -1537,7 +1537,7 @@ mod tests { ); } assert_eq!( - teacher_or_none(Some(teacher.get_id().key()), &db) + teacher_or_none(Some(teacher.get_id().key().as_str()), &db) .await .unwrap() .map(|found| found.get_id().clone()), diff --git a/src/web/courses.rs b/src/web/courses.rs index 385896a..294a08a 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -1385,7 +1385,6 @@ mod tests { chatbot_limit: Default::default(), exam_presence: Default::default(), board_hub: Default::default(), - db_up: Default::default(), ai: None, metrics: crate::telemetry::Metrics::noop(), }; diff --git a/src/web/events.rs b/src/web/events.rs index 14b2812..a634239 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -943,7 +943,13 @@ mod tests { creator.get_id(), 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, ) diff --git a/src/web/page.rs b/src/web/page.rs index ef266af..f79d404 100644 --- a/src/web/page.rs +++ b/src/web/page.rs @@ -198,8 +198,8 @@ mod tests { fn ends_at_ms(&self) -> Option { self.2 } - fn order_key(&self) -> &str { - self.0 + fn order_key(&self) -> String { + self.0.to_owned() } }