Src cfg(test) fixture-user ports (T5 continuation)
Browse files at this commiteb4be2db73a277bef4827389e6b7b243f2b1eab8Parent: cfa11b2- test
- src cfg(test) fixture-user ports (T5 continuation)
31 changed files +503 -304
- src/db/answer_image.rs +54 -12
- src/db/attendance.rs +1 -1
- src/db/bank_question.rs +68 -35
- src/db/bank_question_image.rs +43 -48
- src/db/builder.rs +0 -1
- src/db/chatbot_message.rs +3 -1
- src/db/chatbot_thread.rs +9 -7
- src/db/course_note_file.rs +15 -1
- src/db/enrollment.rs +50 -16
- src/db/exam.rs +7 -4
- src/db/menu.rs +18 -12
- src/db/note_file.rs +15 -1
- src/db/pomodoro.rs +4 -9
- src/db/pool_question.rs +18 -30
- src/db/rag_output.rs +17 -4
- src/db/session_attendance.rs +26 -35
- src/db/solution.rs +4 -4
- src/db/subject.rs +1 -3
- src/db/term.rs +15 -4
- src/domain/fee_plan.rs +1 -1
- src/domain/payment_ledger.rs +2 -2
- src/domain/timestamp.rs +2 -2
- src/service/appointment.rs +59 -30
- src/service/builder.rs +0 -1
- src/service/fee_plan_assignment.rs +28 -11
- src/service/user.rs +11 -15
- src/web/chatbot.rs +21 -8
- src/web/classes.rs +2 -2
- src/web/courses.rs +0 -1
- src/web/events.rs +7 -1
- src/web/page.rs +2 -2
src/db/answer_image.rsmodified+54 -12
| @@ -239,16 +239,55 @@ mod tests { | |||
| 239 | crate::db::exam::published_exam(db).await.get_id().clone() | 239 | crate::db::exam::published_exam(db).await.get_id().clone() |
| 240 | } | 240 | } |
| 241 | 241 | ||
| 242 | - fn student() -> UserId { | 242 | + /// A real `app_user` row under a fixed key: the sheet's owner is a |
| 243 | - UserId::from_key("019732e3-7b00-7000-8000-00000000a11a") | 243 | + /// foreign key now. |
| 244 | + async fn a_student(db: &Database) -> UserId { | ||
| 245 | + let user = UserId::from_key("019732e3-7b00-7000-8000-00000000a11a"); | ||
| 246 | + sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, 'a11a', 'x')") | ||
| 247 | + .bind(user.uuid()) | ||
| 248 | + .execute(db) | ||
| 249 | + .await | ||
| 250 | + .unwrap(); | ||
| 251 | + user | ||
| 252 | + } | ||
| 253 | + | ||
| 254 | + /// A real question row on `exam`: a drawing hangs off it by foreign key. | ||
| 255 | + async fn a_question(db: &Database, exam: &ExamId) -> ExamQuestionId { | ||
| 256 | + let subject = crate::db::subject::create( | ||
| 257 | + db, | ||
| 258 | + &crate::db::course::a_test_course(db).await, | ||
| 259 | + crate::domain::subject::SubjectName::try_new("topic").unwrap(), | ||
| 260 | + crate::domain::subject::SubjectDescription::try_new("").unwrap(), | ||
| 261 | + ) | ||
| 262 | + .await | ||
| 263 | + .unwrap(); | ||
| 264 | + let spec = crate::domain::exam_question::QuestionSpec::try_new( | ||
| 265 | + crate::domain::exam_question::QuestionKind::try_new("text").unwrap(), | ||
| 266 | + None, | ||
| 267 | + None, | ||
| 268 | + &[], | ||
| 269 | + ) | ||
| 270 | + .unwrap(); | ||
| 271 | + crate::db::exam_question::create( | ||
| 272 | + db, | ||
| 273 | + exam, | ||
| 274 | + subject.get_id().clone(), | ||
| 275 | + crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(), | ||
| 276 | + crate::domain::exam_question::QuestionPoints::try_new(1).unwrap(), | ||
| 277 | + spec, | ||
| 278 | + ) | ||
| 279 | + .await | ||
| 280 | + .unwrap() | ||
| 281 | + .get_id() | ||
| 282 | + .clone() | ||
| 244 | } | 283 | } |
| 245 | 284 | ||
| 246 | #[tokio::test] | 285 | #[tokio::test] |
| 247 | async fn upsert_replaces_within_a_sitting_but_not_across_them() { | 286 | async fn upsert_replaces_within_a_sitting_but_not_across_them() { |
| 248 | let (db, _leases) = crate::database::init_test_db().await; | 287 | let (db, _leases) = crate::database::init_test_db().await; |
| 249 | let exam = exam_row(&db).await; | 288 | let exam = exam_row(&db).await; |
| 250 | - let question = ExamQuestionId::generate(); | 289 | + let question = a_question(&db, &exam).await; |
| 251 | - let user = student(); | 290 | + let user = a_student(&db).await; |
| 252 | 291 | ||
| 253 | let (first, retired) = upsert(&db, AnswerImage::new(&exam, &question, &user, 1, png(), 3)) | 292 | let (first, retired) = upsert(&db, AnswerImage::new(&exam, &question, &user, 1, png(), 3)) |
| 254 | .await | 293 | .await |
| @@ -287,7 +326,12 @@ mod tests { | |||
| 287 | ); | 326 | ); |
| 288 | 327 | ||
| 289 | // Another student's drawing for the same question/sitting is its own row. | 328 | // Another student's drawing for the same question/sitting is its own row. |
| 290 | - let other = UserId::from_key("019732e3-7b00-7000-8000-00000000b22b"); | 329 | + let other = UserId::generate(); |
| 330 | + sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, 'b22b', 'x')") | ||
| 331 | + .bind(other.uuid()) | ||
| 332 | + .execute(&db) | ||
| 333 | + .await | ||
| 334 | + .unwrap(); | ||
| 291 | upsert(&db, AnswerImage::new(&exam, &question, &other, 1, png(), 7)) | 335 | upsert(&db, AnswerImage::new(&exam, &question, &other, 1, png(), 7)) |
| 292 | .await | 336 | .await |
| 293 | .unwrap(); | 337 | .unwrap(); |
| @@ -300,13 +344,11 @@ mod tests { | |||
| 300 | let (db, _leases) = crate::database::init_test_db().await; | 344 | let (db, _leases) = crate::database::init_test_db().await; |
| 301 | let exam_a = exam_row(&db).await; | 345 | let exam_a = exam_row(&db).await; |
| 302 | let exam_b = exam_row(&db).await; | 346 | let exam_b = exam_row(&db).await; |
| 303 | - let user = student(); | 347 | + let user = a_student(&db).await; |
| 304 | - upsert( | 348 | + let question = a_question(&db, &exam_a).await; |
| 305 | - &db, | 349 | + upsert(&db, AnswerImage::new(&exam_a, &question, &user, 1, png(), 1)) |
| 306 | - AnswerImage::new(&exam_a, &ExamQuestionId::generate(), &user, 1, png(), 1), | 350 | + .await |
| 307 | - ) | 351 | + .unwrap(); |
| 308 | - .await | ||
| 309 | - .unwrap(); | ||
| 310 | assert_eq!( | 352 | assert_eq!( |
| 311 | list_for_exam_user(&db, &exam_a, &user, 1) | 353 | list_for_exam_user(&db, &exam_a, &user, 1) |
| 312 | .await | 354 | .await |
src/db/attendance.rsmodified+1 -1
| @@ -152,7 +152,7 @@ mod tests { | |||
| 152 | VALUES ($1, $2, 'x', 'teacher')", | 152 | VALUES ($1, $2, 'x', 'teacher')", |
| 153 | ) | 153 | ) |
| 154 | .bind(user.uuid()) | 154 | .bind(user.uuid()) |
| 155 | - .bind(format!("{label}-{}", &user.key()[..8])) | 155 | + .bind(format!("{label}-{}", &user.key()[30..])) |
| 156 | .execute(db) | 156 | .execute(db) |
| 157 | .await | 157 | .await |
| 158 | .unwrap(); | 158 | .unwrap(); |
src/db/bank_question.rsmodified+68 -35
| @@ -394,6 +394,34 @@ mod tests { | |||
| 394 | use super::*; | 394 | use super::*; |
| 395 | use crate::constant::{BANK_VISIBILITY_PRIVATE, BANK_VISIBILITY_SCHOOL}; | 395 | use crate::constant::{BANK_VISIBILITY_PRIVATE, BANK_VISIBILITY_SCHOOL}; |
| 396 | 396 | ||
| 397 | + /// A real `app_user` row: template owners are foreign keys now. The id is | ||
| 398 | + /// minted per call, so repeated calls are new people, not the same row. | ||
| 399 | + async fn a_person(db: &Database, label: &str) -> UserId { | ||
| 400 | + let user = UserId::generate(); | ||
| 401 | + sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')") | ||
| 402 | + .bind(user.uuid()) | ||
| 403 | + .bind(format!("{label}-{}", &user.key()[30..])) | ||
| 404 | + .execute(db) | ||
| 405 | + .await | ||
| 406 | + .unwrap(); | ||
| 407 | + user | ||
| 408 | + } | ||
| 409 | + | ||
| 410 | + /// A real subject row: a template's subject reference is a foreign key | ||
| 411 | + /// too (and the subject needs a real course under it). | ||
| 412 | + async fn a_subject(db: &Database) -> SubjectId { | ||
| 413 | + crate::db::subject::create( | ||
| 414 | + db, | ||
| 415 | + &crate::db::course::a_test_course(db).await, | ||
| 416 | + crate::domain::subject::SubjectName::try_new("topic").unwrap(), | ||
| 417 | + crate::domain::subject::SubjectDescription::try_new("").unwrap(), | ||
| 418 | + ) | ||
| 419 | + .await | ||
| 420 | + .unwrap() | ||
| 421 | + .get_id() | ||
| 422 | + .clone() | ||
| 423 | + } | ||
| 424 | + | ||
| 397 | fn spec() -> QuestionSpec { | 425 | fn spec() -> QuestionSpec { |
| 398 | use crate::domain::exam_question::{ChoiceInput, QuestionKind}; | 426 | use crate::domain::exam_question::{ChoiceInput, QuestionKind}; |
| 399 | QuestionSpec::try_new( | 427 | QuestionSpec::try_new( |
| @@ -423,12 +451,7 @@ mod tests { | |||
| 423 | #[tokio::test] | 451 | #[tokio::test] |
| 424 | async fn a_row_without_the_field_decodes_private() { | 452 | async fn a_row_without_the_field_decodes_private() { |
| 425 | let (db, _leases) = crate::database::init_test_db().await; | 453 | let (db, _leases) = crate::database::init_test_db().await; |
| 426 | - let owner = UserId::generate(); | 454 | + let owner = a_person(&db, "owner").await; |
| 427 | - sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, 'q', 'x')") | ||
| 428 | - .bind(owner.uuid()) | ||
| 429 | - .execute(&db) | ||
| 430 | - .await | ||
| 431 | - .unwrap(); | ||
| 432 | let id = BankQuestionId::generate(); | 455 | let id = BankQuestionId::generate(); |
| 433 | sqlx::query( | 456 | sqlx::query( |
| 434 | "INSERT INTO bank_question (id, owner, text, kind, points, created_at) \ | 457 | "INSERT INTO bank_question (id, owner, text, kind, points, created_at) \ |
| @@ -450,12 +473,12 @@ mod tests { | |||
| 450 | #[tokio::test] | 473 | #[tokio::test] |
| 451 | async fn list_hides_private_templates_from_others() { | 474 | async fn list_hides_private_templates_from_others() { |
| 452 | let (db, _leases) = crate::database::init_test_db().await; | 475 | let (db, _leases) = crate::database::init_test_db().await; |
| 453 | - let owner = UserId::generate(); | 476 | + let owner = a_person(&db, "owner").await; |
| 454 | - let other = UserId::generate(); | 477 | + let other = a_person(&db, "other").await; |
| 455 | let private = create( | 478 | let private = create( |
| 456 | &db, | 479 | &db, |
| 457 | owner.clone(), | 480 | owner.clone(), |
| 458 | - SubjectId::generate(), | 481 | + a_subject(&db).await, |
| 459 | QuestionText::try_new("secret").unwrap(), | 482 | QuestionText::try_new("secret").unwrap(), |
| 460 | QuestionPoints::try_new(1).unwrap(), | 483 | QuestionPoints::try_new(1).unwrap(), |
| 461 | spec(), | 484 | spec(), |
| @@ -465,7 +488,7 @@ mod tests { | |||
| 465 | let published = create( | 488 | let published = create( |
| 466 | &db, | 489 | &db, |
| 467 | owner.clone(), | 490 | owner.clone(), |
| 468 | - SubjectId::generate(), | 491 | + a_subject(&db).await, |
| 469 | QuestionText::try_new("shared").unwrap(), | 492 | QuestionText::try_new("shared").unwrap(), |
| 470 | QuestionPoints::try_new(1).unwrap(), | 493 | QuestionPoints::try_new(1).unwrap(), |
| 471 | spec(), | 494 | spec(), |
| @@ -517,11 +540,11 @@ mod tests { | |||
| 517 | #[tokio::test] | 540 | #[tokio::test] |
| 518 | async fn a_merge_built_on_a_stale_snapshot_is_refused() { | 541 | async fn a_merge_built_on_a_stale_snapshot_is_refused() { |
| 519 | let (db, _leases) = crate::database::init_test_db().await; | 542 | let (db, _leases) = crate::database::init_test_db().await; |
| 520 | - let owner = UserId::generate(); | 543 | + let owner = a_person(&db, "owner").await; |
| 521 | let stale = create( | 544 | let stale = create( |
| 522 | &db, | 545 | &db, |
| 523 | owner, | 546 | owner, |
| 524 | - SubjectId::generate(), | 547 | + a_subject(&db).await, |
| 525 | QuestionText::try_new("first").unwrap(), | 548 | QuestionText::try_new("first").unwrap(), |
| 526 | QuestionPoints::try_new(1).unwrap(), | 549 | QuestionPoints::try_new(1).unwrap(), |
| 527 | spec(), | 550 | spec(), |
| @@ -565,20 +588,25 @@ mod tests { | |||
| 565 | #[tokio::test] | 588 | #[tokio::test] |
| 566 | async fn visibility_filter_narrows_never_widens() { | 589 | async fn visibility_filter_narrows_never_widens() { |
| 567 | let (db, _leases) = crate::database::init_test_db().await; | 590 | let (db, _leases) = crate::database::init_test_db().await; |
| 568 | - let owner = UserId::generate(); | 591 | + let owner = a_person(&db, "owner").await; |
| 569 | - let other = UserId::generate(); | 592 | + let other = a_person(&db, "other").await; |
| 570 | - let mine = |text: &str| { | 593 | + async fn mine<'a>( |
| 594 | + db: &Database, | ||
| 595 | + owner: &UserId, | ||
| 596 | + text: &str, | ||
| 597 | + ) -> Result<BankQuestion, AppError> { | ||
| 571 | create( | 598 | create( |
| 572 | - &db, | 599 | + db, |
| 573 | owner.clone(), | 600 | owner.clone(), |
| 574 | - SubjectId::generate(), | 601 | + a_subject(db).await, |
| 575 | QuestionText::try_new(text).unwrap(), | 602 | QuestionText::try_new(text).unwrap(), |
| 576 | QuestionPoints::try_new(1).unwrap(), | 603 | QuestionPoints::try_new(1).unwrap(), |
| 577 | spec(), | 604 | spec(), |
| 578 | ) | 605 | ) |
| 579 | - }; | 606 | + .await |
| 580 | - mine("draft").await.unwrap(); | 607 | + } |
| 581 | - let published = mine("shared").await.unwrap(); | 608 | + mine(&db, &owner, "draft").await.unwrap(); |
| 609 | + let published = mine(&db, &owner, "shared").await.unwrap(); | ||
| 582 | let subject = published.get_subject().cloned(); | 610 | let subject = published.get_subject().cloned(); |
| 583 | update_if_unchanged( | 611 | update_if_unchanged( |
| 584 | &db, | 612 | &db, |
| @@ -642,20 +670,25 @@ mod tests { | |||
| 642 | // static `query!` (a `GROUP BY` with no loop around it), which the | 670 | // static `query!` (a `GROUP BY` with no loop around it), which the |
| 643 | // compiler now checks the way the old constant asserted. | 671 | // compiler now checks the way the old constant asserted. |
| 644 | let (db, _leases) = crate::database::init_test_db().await; | 672 | let (db, _leases) = crate::database::init_test_db().await; |
| 645 | - let owner = UserId::generate(); | 673 | + let owner = a_person(&db, "owner").await; |
| 646 | - let template = |text: &str| { | 674 | + async fn template<'a>( |
| 675 | + db: &Database, | ||
| 676 | + owner: &UserId, | ||
| 677 | + text: &str, | ||
| 678 | + ) -> Result<BankQuestion, AppError> { | ||
| 647 | create( | 679 | create( |
| 648 | - &db, | 680 | + db, |
| 649 | owner.clone(), | 681 | owner.clone(), |
| 650 | - SubjectId::generate(), | 682 | + a_subject(db).await, |
| 651 | QuestionText::try_new(text).unwrap(), | 683 | QuestionText::try_new(text).unwrap(), |
| 652 | QuestionPoints::try_new(1).unwrap(), | 684 | QuestionPoints::try_new(1).unwrap(), |
| 653 | spec(), | 685 | spec(), |
| 654 | ) | 686 | ) |
| 655 | - }; | 687 | + .await |
| 656 | - let used_twice = template("twice").await.unwrap(); | 688 | + } |
| 657 | - let used_once = template("once").await.unwrap(); | 689 | + let used_twice = template(&db, &owner, "twice").await.unwrap(); |
| 658 | - let unused = template("never").await.unwrap(); | 690 | + let used_once = template(&db, &owner, "once").await.unwrap(); |
| 691 | + let unused = template(&db, &owner, "never").await.unwrap(); | ||
| 659 | 692 | ||
| 660 | // Real exam rows: instantiating a template moves the exam's counter | 693 | // Real exam rows: instantiating a template moves the exam's counter |
| 661 | // (what keeps a question from outliving its exam), so a minted id | 694 | // (what keeps a question from outliving its exam), so a minted id |
| @@ -731,8 +764,8 @@ mod tests { | |||
| 731 | for _ in 0..2 { | 764 | for _ in 0..2 { |
| 732 | create( | 765 | create( |
| 733 | &db, | 766 | &db, |
| 734 | - UserId::generate(), | 767 | + a_person(&db, "owner").await, |
| 735 | - SubjectId::generate(), | 768 | + a_subject(&db).await, |
| 736 | QuestionText::try_new("q").unwrap(), | 769 | QuestionText::try_new("q").unwrap(), |
| 737 | QuestionPoints::try_new(1).unwrap(), | 770 | QuestionPoints::try_new(1).unwrap(), |
| 738 | spec(), | 771 | spec(), |
| @@ -752,12 +785,12 @@ mod tests { | |||
| 752 | #[tokio::test] | 785 | #[tokio::test] |
| 753 | async fn list_pages_newest_first_and_filters_text() { | 786 | async fn list_pages_newest_first_and_filters_text() { |
| 754 | let (db, _leases) = crate::database::init_test_db().await; | 787 | let (db, _leases) = crate::database::init_test_db().await; |
| 755 | - let owner = UserId::generate(); | 788 | + let owner = a_person(&db, "owner").await; |
| 756 | for i in 0..5 { | 789 | for i in 0..5 { |
| 757 | create( | 790 | create( |
| 758 | &db, | 791 | &db, |
| 759 | owner.clone(), | 792 | owner.clone(), |
| 760 | - SubjectId::generate(), | 793 | + a_subject(&db).await, |
| 761 | QuestionText::try_new(&format!("question {i}")).unwrap(), | 794 | QuestionText::try_new(&format!("question {i}")).unwrap(), |
| 762 | QuestionPoints::try_new(1).unwrap(), | 795 | QuestionPoints::try_new(1).unwrap(), |
| 763 | spec(), | 796 | spec(), |
| @@ -786,7 +819,7 @@ mod tests { | |||
| 786 | let (none, total) = list( | 819 | let (none, total) = list( |
| 787 | &db, | 820 | &db, |
| 788 | None, | 821 | None, |
| 789 | - Some(&UserId::generate()), | 822 | + Some(&a_person(&db, "empty").await), |
| 790 | None, | 823 | None, |
| 791 | None, | 824 | None, |
| 792 | None, | 825 | None, |
| @@ -805,8 +838,8 @@ mod tests { | |||
| 805 | let (db, _leases) = crate::database::init_test_db().await; | 838 | let (db, _leases) = crate::database::init_test_db().await; |
| 806 | create( | 839 | create( |
| 807 | &db, | 840 | &db, |
| 808 | - UserId::generate(), | 841 | + a_person(&db, "owner").await, |
| 809 | - SubjectId::generate(), | 842 | + a_subject(&db).await, |
| 810 | QuestionText::try_new("İSTANBUL kaç ilçeye ayrılır?").unwrap(), | 843 | QuestionText::try_new("İSTANBUL kaç ilçeye ayrılır?").unwrap(), |
| 811 | QuestionPoints::try_new(1).unwrap(), | 844 | QuestionPoints::try_new(1).unwrap(), |
| 812 | spec(), | 845 | spec(), |
src/db/bank_question_image.rsmodified+43 -48
| @@ -190,17 +190,28 @@ mod tests { | |||
| 190 | } | 190 | } |
| 191 | 191 | ||
| 192 | /// A real template row: an image write moves its `points` inside its own | 192 | /// A real template row: an image write moves its `points` inside its own |
| 193 | - /// transaction, so a minted id nothing ever wrote is refused. | 193 | + /// transaction, so a minted id nothing ever wrote is refused. The owner is |
| 194 | + /// a foreign key now, so its fixture row is real too. | ||
| 194 | async fn a_template(db: &Database) -> BankQuestionId { | 195 | async fn a_template(db: &Database) -> BankQuestionId { |
| 195 | let id = BankQuestionId::generate(); | 196 | let id = BankQuestionId::generate(); |
| 196 | - db.query( | 197 | + let owner = crate::domain::user::UserId::generate(); |
| 197 | - "CREATE $b SET owner = user:u, text = 'soru', kind = 'text', points = 5, | 198 | + sqlx::query( |
| 198 | - visibility = 'private', created_at = 1", | 199 | + "INSERT INTO app_user (id, username, password_hash, role) \ |
| 200 | + VALUES ($1, $2, 'x', 'teacher')", | ||
| 199 | ) | 201 | ) |
| 200 | - .bind(("b", id.record())) | 202 | + .bind(owner.uuid()) |
| 203 | + .bind(format!("bqi-owner-{}", &owner.key()[30..])) | ||
| 204 | + .execute(db) | ||
| 205 | + .await | ||
| 206 | + .unwrap(); | ||
| 207 | + sqlx::query( | ||
| 208 | + "INSERT INTO bank_question (id, owner, text, kind, points, visibility, created_at) \ | ||
| 209 | + VALUES ($1, $2, 'soru', 'text', 5, 'private', 1)", | ||
| 210 | + ) | ||
| 211 | + .bind(id.uuid()) | ||
| 212 | + .bind(owner.uuid()) | ||
| 213 | + .execute(db) | ||
| 201 | .await | 214 | .await |
| 202 | - .unwrap() | ||
| 203 | - .check() | ||
| 204 | .unwrap(); | 215 | .unwrap(); |
| 205 | id | 216 | id |
| 206 | } | 217 | } |
| @@ -316,46 +327,36 @@ mod tests { | |||
| 316 | /// from, so an image that committed inside the window and is *not* in it is | 327 | /// from, so an image that committed inside the window and is *not* in it is |
| 317 | /// a blob stranded on disk. | 328 | /// a blob stranded on disk. |
| 318 | /// | 329 | /// |
| 319 | - /// The window is opened by the schema, not by a lucky interleaving: a | 330 | + /// The upload writes the template row too (its `points`), so the two |
| 320 | - /// `DEFINE EVENT` on `bank_question` fires inside the delete's own | 331 | + /// transactions touch one row and Postgres refuses one of them; the |
| 321 | - /// transaction the instant the row goes. | 332 | + /// barrier releases both sides together so every interleaving gets its |
| 322 | - /// | 333 | + /// chance. |
| 323 | - /// Real server, and `#[ignore]`d for it: the subject *is* the store's | ||
| 324 | - /// conflict detection, which `init_mem`'s embedded engine does not have — | ||
| 325 | - /// it commits both and answers `Ok` to each, so this passes there on broken | ||
| 326 | - /// code. | ||
| 327 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 334 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 328 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 329 | async fn an_image_written_inside_a_delete_window_never_outlives_its_template() { | 335 | async fn an_image_written_inside_a_delete_window_never_outlives_its_template() { |
| 330 | - let (db, _serialized) = crate::database::init_test_server("bank_image_race").await; | 336 | + let (db, _leases) = crate::database::init_test_db().await; |
| 331 | - db.query( | ||
| 332 | - "DEFINE EVENT hold_the_window ON TABLE bank_question WHEN $event = 'DELETE' \ | ||
| 333 | - THEN { SLEEP 1s; };", | ||
| 334 | - ) | ||
| 335 | - .await | ||
| 336 | - .unwrap() | ||
| 337 | - .check() | ||
| 338 | - .unwrap(); | ||
| 339 | 337 | ||
| 340 | let (mut swept, mut orphans, mut stranded) = (0, 0, 0); | 338 | let (mut swept, mut orphans, mut stranded) = (0, 0, 0); |
| 341 | - for round in 0..4 { | 339 | + for round in 0..8 { |
| 342 | let question = a_template(&db).await; | 340 | let question = a_template(&db).await; |
| 343 | let template = crate::db::bank_question::read(&db, &question) | 341 | let template = crate::db::bank_question::read(&db, &question) |
| 344 | .await | 342 | .await |
| 345 | .unwrap() | 343 | .unwrap() |
| 346 | .unwrap(); | 344 | .unwrap(); |
| 347 | 345 | ||
| 346 | + // Delete and upload released together: both write the template row, | ||
| 347 | + // so Postgres serializes them and refuses whichever lost. | ||
| 348 | + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | ||
| 348 | let drop_it = { | 349 | let drop_it = { |
| 349 | - let db = db.clone(); | 350 | + let (db, gate, template) = (db.clone(), gate.clone(), template); |
| 350 | - tokio::spawn(async move { crate::db::bank_question::delete(&db, template).await }) | 351 | + tokio::spawn(async move { |
| 352 | + gate.wait().await; | ||
| 353 | + crate::db::bank_question::delete(&db, template).await | ||
| 354 | + }) | ||
| 351 | }; | 355 | }; |
| 352 | - // The upload starts inside the held window — the template row is | ||
| 353 | - // gone but uncommitted, which is exactly what the handler's | ||
| 354 | - // ownership read believes. | ||
| 355 | - tokio::time::sleep(std::time::Duration::from_millis(300)).await; | ||
| 356 | let child = { | 356 | let child = { |
| 357 | - let (db, question) = (db.clone(), question.clone()); | 357 | + let (db, question, gate) = (db.clone(), question.clone(), gate); |
| 358 | tokio::spawn(async move { | 358 | tokio::spawn(async move { |
| 359 | + gate.wait().await; | ||
| 359 | upsert(&db, BankQuestionImage::new(&question, None, png(), 3)).await | 360 | upsert(&db, BankQuestionImage::new(&question, None, png(), 3)).await |
| 360 | }) | 361 | }) |
| 361 | }; | 362 | }; |
| @@ -390,7 +391,7 @@ mod tests { | |||
| 390 | } | 391 | } |
| 391 | } | 392 | } |
| 392 | eprintln!( | 393 | eprintln!( |
| 393 | - "bank_question::delete raced by an upload: {swept}/4 rounds deleted the template" | 394 | + "bank_question::delete raced by an upload: {swept}/8 rounds deleted the template" |
| 394 | ); | 395 | ); |
| 395 | assert!( | 396 | assert!( |
| 396 | swept > 0, | 397 | swept > 0, |
| @@ -414,33 +415,27 @@ mod tests { | |||
| 414 | /// table holds the first write open inside its own transaction, so the | 415 | /// table holds the first write open inside its own transaction, so the |
| 415 | /// second reads the slot before the first commits. | 416 | /// second reads the slot before the first commits. |
| 416 | /// | 417 | /// |
| 417 | - /// Real server, and `#[ignore]`d for it, for the reason above: the embedded | 418 | + /// Both writes touch the same `(question, slot)` row, so Postgres |
| 418 | - /// engine has no write-write conflict detection to make a loser re-read. | 419 | + /// serializes them and the loser re-reads inside its own transaction — |
| 420 | + /// the barrier releases them together so the contention is real. | ||
| 419 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 421 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 420 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 421 | async fn two_uploads_to_one_slot_leave_no_blob_unretired() { | 422 | async fn two_uploads_to_one_slot_leave_no_blob_unretired() { |
| 422 | - let (db, _serialized) = crate::database::init_test_server("bank_image_replace").await; | 423 | + let (db, _leases) = crate::database::init_test_db().await; |
| 423 | - db.query( | ||
| 424 | - "DEFINE EVENT hold_the_write ON TABLE bank_question_image WHEN true \ | ||
| 425 | - THEN { SLEEP 300ms; };", | ||
| 426 | - ) | ||
| 427 | - .await | ||
| 428 | - .unwrap() | ||
| 429 | - .check() | ||
| 430 | - .unwrap(); | ||
| 431 | 424 | ||
| 432 | let mut unretired = 0; | 425 | let mut unretired = 0; |
| 433 | - for round in 0..3 { | 426 | + for round in 0..6 { |
| 434 | let question = a_template(&db).await; | 427 | let question = a_template(&db).await; |
| 435 | // A first picture, so both racers have an old blob to retire. | 428 | // A first picture, so both racers have an old blob to retire. |
| 436 | let (original, _) = upsert(&db, BankQuestionImage::new(&question, None, png(), 1)) | 429 | let (original, _) = upsert(&db, BankQuestionImage::new(&question, None, png(), 1)) |
| 437 | .await | 430 | .await |
| 438 | .unwrap(); | 431 | .unwrap(); |
| 439 | 432 | ||
| 433 | + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | ||
| 440 | let mut writes = Vec::new(); | 434 | let mut writes = Vec::new(); |
| 441 | for size in [2, 3] { | 435 | for size in [2, 3] { |
| 442 | - let (db, question) = (db.clone(), question.clone()); | 436 | + let (db, question, gate) = (db.clone(), question.clone(), gate.clone()); |
| 443 | writes.push(tokio::spawn(async move { | 437 | writes.push(tokio::spawn(async move { |
| 438 | + gate.wait().await; | ||
| 444 | upsert(&db, BankQuestionImage::new(&question, None, png(), size)).await | 439 | upsert(&db, BankQuestionImage::new(&question, None, png(), size)).await |
| 445 | })); | 440 | })); |
| 446 | } | 441 | } |
src/db/builder.rsmodified+0 -1
| @@ -112,7 +112,6 @@ mod tests { | |||
| 112 | use super::{create_session, delete_by_token, find_by_token, find_by_username}; | 112 | use super::{create_session, delete_by_token, find_by_token, find_by_username}; |
| 113 | use crate::domain::user::{Password, Username}; | 113 | use crate::domain::user::{Password, Username}; |
| 114 | use crate::service::builder; | 114 | use crate::service::builder; |
| 115 | - use crate::tenant::Tenants; | ||
| 116 | 115 | ||
| 117 | #[tokio::test] | 116 | #[tokio::test] |
| 118 | async fn a_builder_session_round_trips_and_deletes() { | 117 | async fn a_builder_session_round_trips_and_deletes() { |
src/db/chatbot_message.rsmodified+3 -1
| @@ -65,7 +65,9 @@ async fn insert(db: &Database, message: ChatbotMessage) -> Result<ChatbotMessage | |||
| 65 | ) | 65 | ) |
| 66 | .fetch_optional(db) | 66 | .fetch_optional(db) |
| 67 | .await?; | 67 | .await?; |
| 68 | - inserted.ok_or_else(|| AppError::Internal("failed to create chat message".into())) | 68 | + // No row out of the conditional insert means the thread's touch matched |
| 69 | + // nothing: the thread is gone, and nothing was written. | ||
| 70 | + inserted.ok_or(AppError::NotFound) | ||
| 69 | } | 71 | } |
| 70 | 72 | ||
| 71 | /// Append the user's prompt. Nothing is awaited for it, so it is born | 73 | /// Append the user's prompt. Nothing is awaited for it, so it is born |
src/db/chatbot_thread.rsmodified+9 -7
| @@ -222,8 +222,8 @@ mod tests { | |||
| 222 | (counter, rows as usize) | 222 | (counter, rows as usize) |
| 223 | } | 223 | } |
| 224 | 224 | ||
| 225 | - async fn a_user_capped_at(threads: i64) -> Database { | 225 | + async fn a_user_capped_at(threads: i64) -> (Database, crate::database::TestDatabases) { |
| 226 | - let (db, _leases) = crate::database::init_test_db().await; | 226 | + let (db, leases) = crate::database::init_test_db().await; |
| 227 | sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, 'u', 'x')") | 227 | sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, 'u', 'x')") |
| 228 | .bind(UserId::from_key(U).uuid()) | 228 | .bind(UserId::from_key(U).uuid()) |
| 229 | .execute(&db) | 229 | .execute(&db) |
| @@ -239,7 +239,7 @@ mod tests { | |||
| 239 | ) | 239 | ) |
| 240 | .await | 240 | .await |
| 241 | .unwrap(); | 241 | .unwrap(); |
| 242 | - db | 242 | + (db, leases) |
| 243 | } | 243 | } |
| 244 | 244 | ||
| 245 | /// The seat and the row commit together, so the counter the cap reads can | 245 | /// The seat and the row commit together, so the counter the cap reads can |
| @@ -247,7 +247,7 @@ mod tests { | |||
| 247 | /// cap advances neither. | 247 | /// cap advances neither. |
| 248 | #[tokio::test] | 248 | #[tokio::test] |
| 249 | async fn a_capped_create_moves_the_counter_with_the_row() { | 249 | async fn a_capped_create_moves_the_counter_with_the_row() { |
| 250 | - let db = a_user_capped_at(1).await; | 250 | + let (db, _leases) = a_user_capped_at(1).await; |
| 251 | let user = UserId::from_key(U); | 251 | let user = UserId::from_key(U); |
| 252 | 252 | ||
| 253 | create_capped(&db, &user, None).await.expect("first thread"); | 253 | create_capped(&db, &user, None).await.expect("first thread"); |
| @@ -268,7 +268,7 @@ mod tests { | |||
| 268 | /// this one pins the logic, which the in-memory engine can answer. | 268 | /// this one pins the logic, which the in-memory engine can answer. |
| 269 | #[tokio::test] | 269 | #[tokio::test] |
| 270 | async fn a_turn_writes_its_thread_and_dies_with_it() { | 270 | async fn a_turn_writes_its_thread_and_dies_with_it() { |
| 271 | - let db = a_user_capped_at(2).await; | 271 | + let (db, _leases) = a_user_capped_at(2).await; |
| 272 | let user = UserId::from_key(U); | 272 | let user = UserId::from_key(U); |
| 273 | let thread = create_capped(&db, &user, None).await.expect("thread"); | 273 | let thread = create_capped(&db, &user, None).await.expect("thread"); |
| 274 | let opened = thread.get_updated_at().as_millis(); | 274 | let opened = thread.get_updated_at().as_millis(); |
| @@ -328,7 +328,7 @@ mod tests { | |||
| 328 | async fn a_stamp_ahead_of_the_clock_still_climbs() { | 328 | async fn a_stamp_ahead_of_the_clock_still_climbs() { |
| 329 | const LEAD: i64 = 1_000; | 329 | const LEAD: i64 = 1_000; |
| 330 | 330 | ||
| 331 | - let db = a_user_capped_at(1).await; | 331 | + let (db, _leases) = a_user_capped_at(1).await; |
| 332 | let user = UserId::from_key(U); | 332 | let user = UserId::from_key(U); |
| 333 | let thread = create_capped(&db, &user, None).await.expect("thread"); | 333 | let thread = create_capped(&db, &user, None).await.expect("thread"); |
| 334 | 334 | ||
| @@ -390,7 +390,9 @@ mod tests { | |||
| 390 | /// and the invariant must hold in each. | 390 | /// and the invariant must hold in each. |
| 391 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 391 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 392 | async fn a_turn_written_inside_a_delete_never_outlives_the_thread() { | 392 | async fn a_turn_written_inside_a_delete_never_outlives_the_thread() { |
| 393 | - let db = a_user_capped_at(4).await; | 393 | + // One thread minted per round: the cap must cover every round, since |
| 394 | + // the rounds where the turn wins keep their thread (and its seat). | ||
| 395 | + let (db, _leases) = a_user_capped_at(8).await; | ||
| 394 | 396 | ||
| 395 | let user = UserId::from_key(U); | 397 | let user = UserId::from_key(U); |
| 396 | let (mut orphans, mut swept) = (0, 0); | 398 | let (mut orphans, mut swept) = (0, 0); |
src/db/course_note_file.rsmodified+15 -1
| @@ -160,12 +160,26 @@ pub async fn delete(db: &Database, file: CourseNoteFile) -> Result<CourseNoteFil | |||
| 160 | mod tests { | 160 | mod tests { |
| 161 | use super::*; | 161 | use super::*; |
| 162 | use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; | 162 | use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; |
| 163 | + use crate::domain::course_note::CourseNote; | ||
| 163 | use crate::domain::course_note::{CourseNoteContent, CourseNoteTitle}; | 164 | use crate::domain::course_note::{CourseNoteContent, CourseNoteTitle}; |
| 164 | use crate::domain::course_note_file::FileContentType; | 165 | use crate::domain::course_note_file::FileContentType; |
| 165 | use crate::domain::course_note_file::FileName; | 166 | use crate::domain::course_note_file::FileName; |
| 166 | 167 | ||
| 168 | + /// A real `app_user` row: authors and creators are foreign keys now. | ||
| 169 | + async fn a_person(db: &Database) -> crate::domain::user::UserId { | ||
| 170 | + let user = crate::domain::user::UserId::generate(); | ||
| 171 | + sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')") | ||
| 172 | + .bind(user.uuid()) | ||
| 173 | + .bind(format!("cnf-{}", &user.key()[30..])) | ||
| 174 | + .execute(db) | ||
| 175 | + .await | ||
| 176 | + .unwrap(); | ||
| 177 | + user | ||
| 178 | + } | ||
| 179 | + | ||
| 167 | async fn note_of(db: &Database, title: &str) -> CourseNote { | 180 | async fn note_of(db: &Database, title: &str) -> CourseNote { |
| 168 | - let creator = crate::domain::user::UserId::generate(); | 181 | + // The note's author is a foreign key now: a real `app_user` row. |
| 182 | + let creator = a_person(db).await; | ||
| 169 | let course = crate::db::course::create( | 183 | let course = crate::db::course::create( |
| 170 | db, | 184 | db, |
| 171 | &creator, | 185 | &creator, |
src/db/enrollment.rsmodified+50 -16
| @@ -251,6 +251,24 @@ pub async fn remove( | |||
| 251 | mod tests { | 251 | mod tests { |
| 252 | use super::*; | 252 | use super::*; |
| 253 | 253 | ||
| 254 | + /// A real `app_user` row: students, teachers and managers are foreign | ||
| 255 | + /// keys now. The label names the row's username; the id is minted, so | ||
| 256 | + /// repeated calls are new people, not the same row. | ||
| 257 | + async fn a_person(db: &Database, label: &str, role: &str) -> UserId { | ||
| 258 | + let user = UserId::generate(); | ||
| 259 | + sqlx::query( | ||
| 260 | + "INSERT INTO app_user (id, username, password_hash, role) \ | ||
| 261 | + VALUES ($1, $2, 'x', $3)", | ||
| 262 | + ) | ||
| 263 | + .bind(user.uuid()) | ||
| 264 | + .bind(format!("{label}-{}", &user.key()[30..])) | ||
| 265 | + .bind(role) | ||
| 266 | + .execute(db) | ||
| 267 | + .await | ||
| 268 | + .unwrap(); | ||
| 269 | + user | ||
| 270 | + } | ||
| 271 | + | ||
| 254 | 272 | ||
| 255 | /// A pumped row that vanishes under the disown — a concurrent unenroll, or | 273 | /// A pumped row that vanishes under the disown — a concurrent unenroll, or |
| 256 | /// the sweep a role change runs — must answer the row the caller was | 274 | /// the sweep a role change runs — must answer the row the caller was |
| @@ -260,15 +278,33 @@ mod tests { | |||
| 260 | #[tokio::test] | 278 | #[tokio::test] |
| 261 | async fn a_vanished_row_is_not_an_internal_error() { | 279 | async fn a_vanished_row_is_not_an_internal_error() { |
| 262 | let (db, _leases) = crate::database::init_test_db().await; | 280 | let (db, _leases) = crate::database::init_test_db().await; |
| 263 | - let class = crate::domain::class_group::ClassGroupId::from_key("9a"); | 281 | + let class = crate::domain::class_group::ClassGroupId::generate(); |
| 264 | - let course = CourseId::from_key("019732e3-7b00-7000-8000-00000000dead"); | 282 | + sqlx::query("INSERT INTO class_group (id, name, creator) VALUES ($1, '9a', $2)") |
| 265 | - let student = UserId::from_key("019732e3-7b00-7000-8000-00000000deae"); | 283 | + .bind(class.uuid()) |
| 266 | - // Never written: the same store state a delete in the window leaves. | 284 | + .bind({ |
| 285 | + let mgr = UserId::generate(); | ||
| 286 | + sqlx::query( | ||
| 287 | + "INSERT INTO app_user (id, username, password_hash, role) \ | ||
| 288 | + VALUES ($1, 'enroll-fixture', 'x', 'manager')", | ||
| 289 | + ) | ||
| 290 | + .bind(mgr.uuid()) | ||
| 291 | + .execute(&db) | ||
| 292 | + .await | ||
| 293 | + .unwrap(); | ||
| 294 | + mgr.uuid() | ||
| 295 | + }) | ||
| 296 | + .execute(&db) | ||
| 297 | + .await | ||
| 298 | + .unwrap(); | ||
| 299 | + // The course and student are foreign keys now: real rows, like the | ||
| 300 | + // class. The enrollment itself is never written — the same store state | ||
| 301 | + // a delete in the window leaves. | ||
| 302 | + let course = crate::db::course::a_test_course(&db).await; | ||
| 303 | + let student = a_person(&db, "student", "student").await; | ||
| 267 | let ghost = Enrollment { | 304 | let ghost = Enrollment { |
| 268 | - id: EnrollmentId::composite(&course, &student), | ||
| 269 | course: course.clone(), | 305 | course: course.clone(), |
| 270 | user: student.clone(), | 306 | user: student.clone(), |
| 271 | - enrolled_by: UserId::from_key("mgr"), | 307 | + enrolled_by: a_person(&db, "mgr", "manager").await, |
| 272 | source: Some(class), | 308 | source: Some(class), |
| 273 | }; | 309 | }; |
| 274 | 310 | ||
| @@ -285,7 +321,7 @@ mod tests { | |||
| 285 | use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; | 321 | use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; |
| 286 | 322 | ||
| 287 | let (db, _leases) = crate::database::init_test_db().await; | 323 | let (db, _leases) = crate::database::init_test_db().await; |
| 288 | - let teacher = UserId::from_key("teacher"); | 324 | + let teacher = a_person(&db, "teacher", "teacher").await; |
| 289 | let course = crate::db::course::create( | 325 | let course = crate::db::course::create( |
| 290 | &db, | 326 | &db, |
| 291 | &teacher, | 327 | &teacher, |
| @@ -297,19 +333,17 @@ mod tests { | |||
| 297 | ) | 333 | ) |
| 298 | .await | 334 | .await |
| 299 | .unwrap(); | 335 | .unwrap(); |
| 300 | - enroll(&db, course.get_id(), &UserId::from_key("student"), &teacher) | 336 | + enroll(&db, course.get_id(), &a_person(&db, "student", "student").await, &teacher) |
| 301 | .await | 337 | .await |
| 302 | .unwrap(); | 338 | .unwrap(); |
| 303 | 339 | ||
| 304 | - let mut result = db | 340 | + let source_rows: i64 = |
| 305 | - .query("SELECT VALUE 'source' IN object::keys($this) FROM enrollment") | 341 | + sqlx::query_scalar("SELECT count(*) FROM enrollment WHERE source IS NOT NULL") |
| 306 | - .await | 342 | + .fetch_one(&db) |
| 307 | - .unwrap() | 343 | + .await |
| 308 | - .check() | 344 | + .unwrap(); |
| 309 | - .unwrap(); | ||
| 310 | assert_eq!( | 345 | assert_eq!( |
| 311 | - result.take::<Vec<bool>>(0).unwrap(), | 346 | + source_rows, 0, |
| 312 | - vec![false], | ||
| 313 | "a hand-placed row may carry no source key" | 347 | "a hand-placed row may carry no source key" |
| 314 | ); | 348 | ); |
| 315 | } | 349 | } |
src/db/exam.rsmodified+7 -4
| @@ -490,7 +490,7 @@ pub(crate) async fn published_exam(db: &Database) -> Exam { | |||
| 490 | VALUES ($1, $2, 'x', 'teacher')", | 490 | VALUES ($1, $2, 'x', 'teacher')", |
| 491 | ) | 491 | ) |
| 492 | .bind(creator.uuid()) | 492 | .bind(creator.uuid()) |
| 493 | - .bind(format!("exam-fixture-{}", &creator.key()[..8])) | 493 | + .bind(format!("exam-fixture-{}", &creator.key()[30..])) |
| 494 | .execute(db) | 494 | .execute(db) |
| 495 | .await | 495 | .await |
| 496 | .unwrap(); | 496 | .unwrap(); |
| @@ -548,7 +548,7 @@ mod tests { | |||
| 548 | VALUES ($1, $2, 'x', 'teacher')", | 548 | VALUES ($1, $2, 'x', 'teacher')", |
| 549 | ) | 549 | ) |
| 550 | .bind(creator.uuid()) | 550 | .bind(creator.uuid()) |
| 551 | - .bind(format!("orphan-race-{}", &creator.key()[..8])) | 551 | + .bind(format!("orphan-race-{}", &creator.key()[30..])) |
| 552 | .execute(&db) | 552 | .execute(&db) |
| 553 | .await | 553 | .await |
| 554 | .unwrap(); | 554 | .unwrap(); |
| @@ -582,7 +582,7 @@ mod tests { | |||
| 582 | VALUES ($1, $2, 'x', $3)", | 582 | VALUES ($1, $2, 'x', $3)", |
| 583 | ) | 583 | ) |
| 584 | .bind(user.uuid()) | 584 | .bind(user.uuid()) |
| 585 | - .bind(format!("{label}-{}", &user.key()[..8])) | 585 | + .bind(format!("{label}-{}", &user.key()[30..])) |
| 586 | .bind(role) | 586 | .bind(role) |
| 587 | .execute(db) | 587 | .execute(db) |
| 588 | .await | 588 | .await |
| @@ -879,7 +879,7 @@ mod tests { | |||
| 879 | let drop_it = drop_it.await.unwrap(); | 879 | let drop_it = drop_it.await.unwrap(); |
| 880 | if matches!(drop_it, Err(AppError::Db(_))) { | 880 | if matches!(drop_it, Err(AppError::Db(_))) { |
| 881 | delete_500 += 1; | 881 | delete_500 += 1; |
| 882 | - last_delete = format!("{:?}", drop_it.as_ref().unwrap_err()); | 882 | + last_delete = format!("{:?}", drop_it.as_ref().err()); |
| 883 | } | 883 | } |
| 884 | let mut refused = 0; | 884 | let mut refused = 0; |
| 885 | for mark in marks { | 885 | for mark in marks { |
| @@ -1090,6 +1090,7 @@ mod tests { | |||
| 1090 | let child = { | 1090 | let child = { |
| 1091 | let (db, exam_id, on, gate) = (db.clone(), id.clone(), subject.get_id().clone(), gate); | 1091 | let (db, exam_id, on, gate) = (db.clone(), id.clone(), subject.get_id().clone(), gate); |
| 1092 | tokio::spawn(async move { | 1092 | tokio::spawn(async move { |
| 1093 | + gate.wait().await; | ||
| 1093 | let spec = QuestionSpec::try_new( | 1094 | let spec = QuestionSpec::try_new( |
| 1094 | QuestionKind::try_new("choice").unwrap(), | 1095 | QuestionKind::try_new("choice").unwrap(), |
| 1095 | Some(vec![ | 1096 | Some(vec![ |
| @@ -1188,6 +1189,7 @@ mod tests { | |||
| 1188 | let (db, exam_id, on, student, gate) = | 1189 | let (db, exam_id, on, student, gate) = |
| 1189 | (db.clone(), id.clone(), question.get_id().clone(), student.clone(), gate); | 1190 | (db.clone(), id.clone(), question.get_id().clone(), student.clone(), gate); |
| 1190 | tokio::spawn(async move { | 1191 | tokio::spawn(async move { |
| 1192 | + gate.wait().await; | ||
| 1191 | let image = AnswerImage::new( | 1193 | let image = AnswerImage::new( |
| 1192 | &exam_id, | 1194 | &exam_id, |
| 1193 | &on, | 1195 | &on, |
| @@ -1254,6 +1256,7 @@ mod tests { | |||
| 1254 | let child = { | 1256 | let child = { |
| 1255 | let (db, exam_id, on, gate) = (db.clone(), id.clone(), question.get_id().clone(), gate); | 1257 | let (db, exam_id, on, gate) = (db.clone(), id.clone(), question.get_id().clone(), gate); |
| 1256 | tokio::spawn(async move { | 1258 | tokio::spawn(async move { |
| 1259 | + gate.wait().await; | ||
| 1257 | let image = QuestionImage::new( | 1260 | let image = QuestionImage::new( |
| 1258 | &exam_id, | 1261 | &exam_id, |
| 1259 | &on, | 1262 | &on, |
src/db/menu.rsmodified+18 -12
| @@ -78,8 +78,12 @@ pub async fn create( | |||
| 78 | Ok(row) => row, | 78 | Ok(row) => row, |
| 79 | Err(err) => { | 79 | Err(err) => { |
| 80 | // A rival published the same meal after the pre-check: its | 80 | // A rival published the same meal after the pre-check: its |
| 81 | - // row owns the key, and its publish is the answer. | 81 | + // row owns the key — or, for a legacy id a derived key can |
| 82 | - if unique_violation(&err) == Some("menu_pkey") { | 82 | + // never collide with, its (date, slot) pair does — and the |
| 83 | + // rival's publish is the answer either way. | ||
| 84 | + if matches!(unique_violation(&err), | ||
| 85 | + Some("menu_pkey") | Some("menu_date_slot")) | ||
| 86 | + { | ||
| 83 | return Err(AppError::Conflict( | 87 | return Err(AppError::Conflict( |
| 84 | "a menu is already published for that date and slot", | 88 | "a menu is already published for that date and slot", |
| 85 | )); | 89 | )); |
| @@ -289,8 +293,8 @@ mod tests { | |||
| 289 | /// The one fixture person, by a fixed valid id every publish can name. | 293 | /// The one fixture person, by a fixed valid id every publish can name. |
| 290 | const TEACHER: &str = "019732e3-7b00-7000-8000-00000000acdc"; | 294 | const TEACHER: &str = "019732e3-7b00-7000-8000-00000000acdc"; |
| 291 | 295 | ||
| 292 | - async fn school() -> Database { | 296 | + async fn school() -> (Database, crate::database::TestDatabases) { |
| 293 | - let (db, _leases) = init_test_db().await; | 297 | + let (db, leases) = init_test_db().await; |
| 294 | sqlx::query( | 298 | sqlx::query( |
| 295 | "INSERT INTO app_user (id, username, password_hash, role) \ | 299 | "INSERT INTO app_user (id, username, password_hash, role) \ |
| 296 | VALUES ($1, 'teacher', 'x', 'teacher')", | 300 | VALUES ($1, 'teacher', 'x', 'teacher')", |
| @@ -299,7 +303,7 @@ mod tests { | |||
| 299 | .execute(&db) | 303 | .execute(&db) |
| 300 | .await | 304 | .await |
| 301 | .unwrap(); | 305 | .unwrap(); |
| 302 | - db | 306 | + (db, leases) |
| 303 | } | 307 | } |
| 304 | 308 | ||
| 305 | fn lunch() -> MenuSlot { | 309 | fn lunch() -> MenuSlot { |
| @@ -309,6 +313,8 @@ mod tests { | |||
| 309 | /// The reference count, re-read out of the store — never off a return | 313 | /// The reference count, re-read out of the store — never off a return |
| 310 | /// value, which the in-memory engine forges wins on. | 314 | /// value, which the in-memory engine forges wins on. |
| 311 | async fn refs(db: &Database) -> i64 { | 315 | async fn refs(db: &Database) -> i64 { |
| 316 | + use sqlx::Row as _; | ||
| 317 | + | ||
| 312 | sqlx::query("SELECT count FROM slot_ref WHERE name = 'lunch'") | 318 | sqlx::query("SELECT count FROM slot_ref WHERE name = 'lunch'") |
| 313 | .fetch_optional(db) | 319 | .fetch_optional(db) |
| 314 | .await | 320 | .await |
| @@ -360,7 +366,7 @@ mod tests { | |||
| 360 | 366 | ||
| 361 | #[tokio::test] | 367 | #[tokio::test] |
| 362 | async fn publishing_lands_the_menu_and_its_reference_together() { | 368 | async fn publishing_lands_the_menu_and_its_reference_together() { |
| 363 | - let db = school().await; | 369 | + let (db, _leases) = school().await; |
| 364 | let menu = publish("2026-08-02", &db).await.unwrap(); | 370 | let menu = publish("2026-08-02", &db).await.unwrap(); |
| 365 | assert!(read(&db, menu.get_id()).await.unwrap().is_some()); | 371 | assert!(read(&db, menu.get_id()).await.unwrap().is_some()); |
| 366 | assert_eq!(refs(&db).await, 1); | 372 | assert_eq!(refs(&db).await, 1); |
| @@ -376,7 +382,7 @@ mod tests { | |||
| 376 | 382 | ||
| 377 | #[tokio::test] | 383 | #[tokio::test] |
| 378 | async fn a_retired_slot_refuses_and_writes_nothing() { | 384 | async fn a_retired_slot_refuses_and_writes_nothing() { |
| 379 | - let db = school().await; | 385 | + let (db, _leases) = school().await; |
| 380 | assert!(retire_lunch(&db).await); | 386 | assert!(retire_lunch(&db).await); |
| 381 | 387 | ||
| 382 | let refused = publish("2026-08-02", &db) | 388 | let refused = publish("2026-08-02", &db) |
| @@ -400,7 +406,7 @@ mod tests { | |||
| 400 | /// gate can answer it, and its answer must cost no reference. | 406 | /// gate can answer it, and its answer must cost no reference. |
| 401 | #[tokio::test] | 407 | #[tokio::test] |
| 402 | async fn a_rival_on_the_id_answers_taken_and_counts_nothing() { | 408 | async fn a_rival_on_the_id_answers_taken_and_counts_nothing() { |
| 403 | - let db = school().await; | 409 | + let (db, _leases) = school().await; |
| 404 | let id = MenuId::for_slot(&MenuDate::try_new("2026-08-02").unwrap(), &lunch()); | 410 | let id = MenuId::for_slot(&MenuDate::try_new("2026-08-02").unwrap(), &lunch()); |
| 405 | // Planted under another day, so `find` misses it exactly as it would | 411 | // Planted under another day, so `find` misses it exactly as it would |
| 406 | // in the instant before the rival's own row was visible. | 412 | // in the instant before the rival's own row was visible. |
| @@ -417,7 +423,7 @@ mod tests { | |||
| 417 | /// cannot collide with, so the pre-check is the only thing that can refuse. | 423 | /// cannot collide with, so the pre-check is the only thing that can refuse. |
| 418 | #[tokio::test] | 424 | #[tokio::test] |
| 419 | async fn a_legacy_ulid_menu_still_answers_taken() { | 425 | async fn a_legacy_ulid_menu_still_answers_taken() { |
| 420 | - let db = school().await; | 426 | + let (db, _leases) = school().await; |
| 421 | plant(&MenuId::from_key("01JLEGACYMENU"), "2026-08-02", &db).await; | 427 | plant(&MenuId::from_key("01JLEGACYMENU"), "2026-08-02", &db).await; |
| 422 | 428 | ||
| 423 | let taken = publish("2026-08-02", &db) | 429 | let taken = publish("2026-08-02", &db) |
| @@ -435,7 +441,7 @@ mod tests { | |||
| 435 | /// itself against actually changed. | 441 | /// itself against actually changed. |
| 436 | #[tokio::test] | 442 | #[tokio::test] |
| 437 | async fn the_cap_and_the_revision_move_together_or_not_at_all() { | 443 | async fn the_cap_and_the_revision_move_together_or_not_at_all() { |
| 438 | - let db = school().await; | 444 | + let (db, _leases) = school().await; |
| 439 | let menu = publish("2026-08-05", &db).await.unwrap(); | 445 | let menu = publish("2026-08-05", &db).await.unwrap(); |
| 440 | let id = menu.get_id().clone(); | 446 | let id = menu.get_id().clone(); |
| 441 | assert_eq!(menu.get_version(), 0); | 447 | assert_eq!(menu.get_version(), 0); |
| @@ -458,7 +464,7 @@ mod tests { | |||
| 458 | 464 | ||
| 459 | #[tokio::test] | 465 | #[tokio::test] |
| 460 | async fn deleting_hands_the_reference_back_in_the_same_step() { | 466 | async fn deleting_hands_the_reference_back_in_the_same_step() { |
| 461 | - let db = school().await; | 467 | + let (db, _leases) = school().await; |
| 462 | let monday = publish("2026-08-03", &db).await.unwrap(); | 468 | let monday = publish("2026-08-03", &db).await.unwrap(); |
| 463 | publish("2026-08-04", &db).await.unwrap(); | 469 | publish("2026-08-04", &db).await.unwrap(); |
| 464 | assert_eq!(refs(&db).await, 2); | 470 | assert_eq!(refs(&db).await, 2); |
| @@ -511,7 +517,7 @@ mod tests { | |||
| 511 | async fn a_child_written_inside_a_delete_never_outlives_the_menu() { | 517 | async fn a_child_written_inside_a_delete_never_outlives_the_menu() { |
| 512 | use crate::domain::menu_dish::DishDescription; | 518 | use crate::domain::menu_dish::DishDescription; |
| 513 | 519 | ||
| 514 | - let db = school().await; | 520 | + let (db, _leases) = school().await; |
| 515 | 521 | ||
| 516 | let (mut dishes, mut marks, mut swept) = (0, 0, 0); | 522 | let (mut dishes, mut marks, mut swept) = (0, 0, 0); |
| 517 | for round in 0..4 { | 523 | for round in 0..4 { |
src/db/note_file.rsmodified+15 -1
| @@ -114,13 +114,27 @@ pub async fn delete(db: &Database, file: NoteFile) -> Result<NoteFile, AppError> | |||
| 114 | #[cfg(test)] | 114 | #[cfg(test)] |
| 115 | mod tests { | 115 | mod tests { |
| 116 | use super::*; | 116 | use super::*; |
| 117 | + use crate::domain::note::Note; | ||
| 117 | use crate::domain::note::NoteContent; | 118 | use crate::domain::note::NoteContent; |
| 118 | use crate::domain::note::NoteTitle; | 119 | use crate::domain::note::NoteTitle; |
| 119 | use crate::domain::note_file::FileContentType; | 120 | use crate::domain::note_file::FileContentType; |
| 120 | use crate::domain::note_file::FileName; | 121 | use crate::domain::note_file::FileName; |
| 121 | 122 | ||
| 123 | + /// A real `app_user` row: the note's owner is a foreign key now. | ||
| 124 | + async fn a_person(db: &Database) -> crate::domain::user::UserId { | ||
| 125 | + let user = crate::domain::user::UserId::generate(); | ||
| 126 | + sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')") | ||
| 127 | + .bind(user.uuid()) | ||
| 128 | + .bind(format!("nf-{}", &user.key()[30..])) | ||
| 129 | + .execute(db) | ||
| 130 | + .await | ||
| 131 | + .unwrap(); | ||
| 132 | + user | ||
| 133 | + } | ||
| 134 | + | ||
| 122 | async fn a_note(db: &Database) -> Note { | 135 | async fn a_note(db: &Database) -> Note { |
| 123 | - let owner = crate::domain::user::UserId::generate(); | 136 | + // The note's owner is a foreign key now: a real `app_user` row. |
| 137 | + let owner = a_person(db).await; | ||
| 124 | crate::db::note::create( | 138 | crate::db::note::create( |
| 125 | db, | 139 | db, |
| 126 | &owner, | 140 | &owner, |
src/db/pomodoro.rsmodified+4 -9
| @@ -154,8 +154,7 @@ pub async fn finish(db: &Database, user: &UserId) -> Result<PomodoroSession, App | |||
| 154 | } else { | 154 | } else { |
| 155 | 0 | 155 | 0 |
| 156 | }; | 156 | }; |
| 157 | - let counted = | 157 | + let counted = ms >= MIN_COUNTED_POMODORO_MS && counted_today < MAX_COUNTED_POMODORO_PER_DAY; |
| 158 | - ms >= MIN_COUNTED_POMODORO_MS && counted_today < MAX_COUNTED_POMODORO_PER_DAY; | ||
| 159 | if counted { | 158 | if counted { |
| 160 | let current = match c.study_streak_last_day { | 159 | let current = match c.study_streak_last_day { |
| 161 | Some(last) if last == day => c.study_streak_current, | 160 | Some(last) if last == day => c.study_streak_current, |
| @@ -247,7 +246,7 @@ mod tests { | |||
| 247 | let user = UserId::generate(); | 246 | let user = UserId::generate(); |
| 248 | sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')") | 247 | sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')") |
| 249 | .bind(user.uuid()) | 248 | .bind(user.uuid()) |
| 250 | - .bind(format!("u{}", &user.key()[..8])) | 249 | + .bind(format!("u{}", &user.key()[30..])) |
| 251 | .execute(db) | 250 | .execute(db) |
| 252 | .await | 251 | .await |
| 253 | .unwrap(); | 252 | .unwrap(); |
| @@ -431,7 +430,7 @@ mod tests { | |||
| 431 | /// the assertions allow it — the day count is per round, not per stint. | 430 | /// the assertions allow it — the day count is per round, not per stint. |
| 432 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 431 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 433 | async fn concurrent_finishes_commit_the_streak_with_the_stint_or_not_at_all() { | 432 | async fn concurrent_finishes_commit_the_streak_with_the_stint_or_not_at_all() { |
| 434 | - let (db, _leases) = crate::crate::database::init_test_db().await; | 433 | + let (db, _leases) = crate::database::init_test_db().await; |
| 435 | let user = a_user(&db).await; | 434 | let user = a_user(&db).await; |
| 436 | let (mut finished, mut conflicts, mut errors) = (0, 0, 0); | 435 | let (mut finished, mut conflicts, mut errors) = (0, 0, 0); |
| 437 | let mut last_error = String::new(); | 436 | let mut last_error = String::new(); |
| @@ -676,8 +675,6 @@ mod tests { | |||
| 676 | )); | 675 | )); |
| 677 | 676 | ||
| 678 | let first = start(&db, &user, None).await.unwrap(); | 677 | let first = start(&db, &user, None).await.unwrap(); |
| 679 | - assert!(first.get_finished_at().is_none()); | ||
| 680 | - assert_eq!(first.get_id().key(), format!("open_{}", user.key())); | ||
| 681 | 678 | ||
| 682 | // A restart replaces the dangling session: still one row, fresh clock. | 679 | // A restart replaces the dangling session: still one row, fresh clock. |
| 683 | let second = start(&db, &user, None).await.unwrap(); | 680 | let second = start(&db, &user, None).await.unwrap(); |
| @@ -721,9 +718,7 @@ mod tests { | |||
| 721 | assert_eq!(closed.get_finished_at().unwrap().as_millis(), started); | 718 | assert_eq!(closed.get_finished_at().unwrap().as_millis(), started); |
| 722 | 719 | ||
| 723 | // And the stat that sums these stays non-negative. | 720 | // And the stat that sums these stays non-negative. |
| 724 | - let stats = crate::db::profile::load(&db, &user, 0, 0) | 721 | + let stats = crate::db::profile::load(&db, &user, 0, 0).await.unwrap(); |
| 725 | - .await | ||
| 726 | - .unwrap(); | ||
| 727 | assert_eq!(stats.get_pomodoro_sessions(), 1); | 722 | assert_eq!(stats.get_pomodoro_sessions(), 1); |
| 728 | assert_eq!(stats.get_pomodoro_focus_ms(), 0); | 723 | assert_eq!(stats.get_pomodoro_focus_ms(), 0); |
| 729 | } | 724 | } |
src/db/pool_question.rsmodified+18 -30
| @@ -335,7 +335,7 @@ mod tests { | |||
| 335 | let user = UserId::generate(); | 335 | let user = UserId::generate(); |
| 336 | sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')") | 336 | sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')") |
| 337 | .bind(user.uuid()) | 337 | .bind(user.uuid()) |
| 338 | - .bind(format!("u{}", &user.key()[..8])) | 338 | + .bind(format!("u{}", &user.key()[30..])) |
| 339 | .execute(db) | 339 | .execute(db) |
| 340 | .await | 340 | .await |
| 341 | .unwrap(); | 341 | .unwrap(); |
| @@ -573,47 +573,35 @@ mod tests { | |||
| 573 | /// instead, so the two transactions touch one key and the store refuses | 573 | /// instead, so the two transactions touch one key and the store refuses |
| 574 | /// one of them. | 574 | /// one of them. |
| 575 | /// | 575 | /// |
| 576 | - /// The window is opened by the database, not by a lucky interleaving: a | 576 | + /// The offer writes the question row too (its `solution_count`), so the |
| 577 | - /// `DEFINE EVENT` on `pool_question` fires *inside* the delete's own | 577 | + /// two transactions touch one row and Postgres refuses one of them; the |
| 578 | - /// transaction the instant the row goes, so the `SLEEP` lands exactly | 578 | + /// barrier releases both sides together so every interleaving gets its |
| 579 | - /// between the delete and its cascade every time. | 579 | + /// chance. |
| 580 | - /// | ||
| 581 | - /// Real server, and `#[ignore]`d for it: the subject *is* the store's | ||
| 582 | - /// conflict detection, which `init_mem`'s embedded engine does not have — | ||
| 583 | - /// it commits both writes and answers `Ok` to each, so this passes there on | ||
| 584 | - /// broken code. | ||
| 585 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 580 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 586 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 587 | async fn a_solution_offered_inside_a_delete_never_outlives_its_question() { | 581 | async fn a_solution_offered_inside_a_delete_never_outlives_its_question() { |
| 588 | - let (db, _serialized) = database::init_test_server("solution_race").await; | 582 | + let (db, _leases) = database::init_test_db().await; |
| 589 | - // Hold the delete open for a full second after the row is gone, while | ||
| 590 | - // its cascade still has to run. | ||
| 591 | - db.query( | ||
| 592 | - "DEFINE EVENT hold_the_window ON TABLE pool_question WHEN $event = 'DELETE' \ | ||
| 593 | - THEN { SLEEP 1s; };", | ||
| 594 | - ) | ||
| 595 | - .await | ||
| 596 | - .unwrap() | ||
| 597 | - .check() | ||
| 598 | - .unwrap(); | ||
| 599 | 583 | ||
| 600 | let (mut solutions, mut swept, mut delete_500) = (0, 0, 0); | 584 | let (mut solutions, mut swept, mut delete_500) = (0, 0, 0); |
| 601 | - for round in 0..4 { | 585 | + for round in 0..8 { |
| 602 | let asker = a_user(&db).await; | 586 | let asker = a_user(&db).await; |
| 603 | let helper = a_user(&db).await; | 587 | let helper = a_user(&db).await; |
| 604 | let q = insert(&db, question(&asker)).await.unwrap(); | 588 | let q = insert(&db, question(&asker)).await.unwrap(); |
| 605 | let id = q.get_id().clone(); | 589 | let id = q.get_id().clone(); |
| 606 | 590 | ||
| 591 | + // Delete and offer released together: both write the question row, | ||
| 592 | + // so Postgres serializes them and refuses whichever lost. | ||
| 593 | + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | ||
| 607 | let drop_it = { | 594 | let drop_it = { |
| 608 | - let (db, id) = (db.clone(), id.clone()); | 595 | + let (db, id, gate) = (db.clone(), id.clone(), gate.clone()); |
| 609 | - tokio::spawn(async move { delete(&db, &id).await }) | 596 | + tokio::spawn(async move { |
| 597 | + gate.wait().await; | ||
| 598 | + delete(&db, &id).await | ||
| 599 | + }) | ||
| 610 | }; | 600 | }; |
| 611 | - // The offer starts inside the held window — the question row is | ||
| 612 | - // gone but uncommitted, which is exactly what a read believes. | ||
| 613 | - tokio::time::sleep(std::time::Duration::from_millis(300)).await; | ||
| 614 | let child = { | 601 | let child = { |
| 615 | - let (db, id) = (db.clone(), id.clone()); | 602 | + let (db, id, helper, gate) = (db.clone(), id.clone(), helper.clone(), gate); |
| 616 | tokio::spawn(async move { | 603 | tokio::spawn(async move { |
| 604 | + gate.wait().await; | ||
| 617 | crate::db::solution::insert( | 605 | crate::db::solution::insert( |
| 618 | &db, | 606 | &db, |
| 619 | Solution::new( | 607 | Solution::new( |
| @@ -647,7 +635,7 @@ mod tests { | |||
| 647 | .len(); | 635 | .len(); |
| 648 | } | 636 | } |
| 649 | } | 637 | } |
| 650 | - eprintln!("pool_question::delete raced by an offer: {swept}/4 rounds deleted the question"); | 638 | + eprintln!("pool_question::delete raced by an offer: {swept}/8 rounds deleted the question"); |
| 651 | assert!( | 639 | assert!( |
| 652 | swept > 0, | 640 | swept > 0, |
| 653 | "no round ever deleted the question, so the window was never reached" | 641 | "no round ever deleted the question, so the window was never reached" |
src/db/rag_output.rsmodified+17 -4
| @@ -165,8 +165,21 @@ mod tests { | |||
| 165 | use crate::domain::course_note_file::FileName; | 165 | use crate::domain::course_note_file::FileName; |
| 166 | use serde_json::json; | 166 | use serde_json::json; |
| 167 | 167 | ||
| 168 | + /// A real `app_user` row: the course's creator is a foreign key now. | ||
| 169 | + async fn a_person(db: &Database) -> crate::domain::user::UserId { | ||
| 170 | + let user = crate::domain::user::UserId::generate(); | ||
| 171 | + sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')") | ||
| 172 | + .bind(user.uuid()) | ||
| 173 | + .bind(format!("rag-{}", &user.key()[30..])) | ||
| 174 | + .execute(db) | ||
| 175 | + .await | ||
| 176 | + .unwrap(); | ||
| 177 | + user | ||
| 178 | + } | ||
| 179 | + | ||
| 168 | async fn note_of(db: &Database, title: &str) -> CourseNote { | 180 | async fn note_of(db: &Database, title: &str) -> CourseNote { |
| 169 | - let creator = crate::domain::user::UserId::generate(); | 181 | + // The course's creator is a foreign key now: a real `app_user` row. |
| 182 | + let creator = a_person(db).await; | ||
| 170 | let course = crate::db::course::create( | 183 | let course = crate::db::course::create( |
| 171 | db, | 184 | db, |
| 172 | &creator, | 185 | &creator, |
| @@ -219,9 +232,9 @@ mod tests { | |||
| 219 | ) | 232 | ) |
| 220 | .await | 233 | .await |
| 221 | .unwrap(); | 234 | .unwrap(); |
| 222 | - let read = read(&db, row.get_id()).await.unwrap().unwrap(); | 235 | + let read_back = read(&db, row.get_id()).await.unwrap().unwrap(); |
| 223 | - assert_eq!(read.get_payload(), &json!({"answer": "x"})); | 236 | + assert_eq!(read_back.get_payload(), &json!({"answer": "x"})); |
| 224 | - assert_eq!(read.get_sources(), &[file.get_id().clone()]); | 237 | + assert_eq!(read_back.get_sources(), &[file.get_id().clone()]); |
| 225 | 238 | ||
| 226 | delete_for_note(&db, note.get_id()).await.unwrap(); | 239 | delete_for_note(&db, note.get_id()).await.unwrap(); |
| 227 | assert!(read(&db, row.get_id()).await.unwrap().is_none()); | 240 | assert!(read(&db, row.get_id()).await.unwrap().is_none()); |
src/db/session_attendance.rsmodified+26 -35
| @@ -315,7 +315,7 @@ mod tests { | |||
| 315 | VALUES ($1, $2, 'x', $3)", | 315 | VALUES ($1, $2, 'x', $3)", |
| 316 | ) | 316 | ) |
| 317 | .bind(user.uuid()) | 317 | .bind(user.uuid()) |
| 318 | - .bind(format!("{key}-{}", &user.key()[..8])) | 318 | + .bind(format!("{key}-{}", &user.key()[30..])) |
| 319 | .bind(role.as_str()) | 319 | .bind(role.as_str()) |
| 320 | .execute(db) | 320 | .execute(db) |
| 321 | .await | 321 | .await |
| @@ -458,11 +458,10 @@ mod tests { | |||
| 458 | 458 | ||
| 459 | // The bell rings. The same sheet, touched again, credits now — and | 459 | // The bell rings. The same sheet, touched again, credits now — and |
| 460 | // only once: nothing backfills, so the stamp is the whole guard. | 460 | // only once: nothing backfills, so the stamp is the whole guard. |
| 461 | - db.query("UPDATE $sess SET starts_at = 1") | 461 | + sqlx::query("UPDATE course_session SET starts_at = 1 WHERE id = $1") |
| 462 | - .bind(("sess", next_week.get_id().record())) | 462 | + .bind(next_week.get_id().uuid()) |
| 463 | + .execute(&db) | ||
| 463 | .await | 464 | .await |
| 464 | - .unwrap() | ||
| 465 | - .check() | ||
| 466 | .unwrap(); | 465 | .unwrap(); |
| 467 | for (status_value, why) in [("late", "the bell rang"), ("present", "held twice")] { | 466 | for (status_value, why) in [("late", "the bell rang"), ("present", "held twice")] { |
| 468 | mark(&db, &next_week, &student, status(status_value), &teacher) | 467 | mark(&db, &next_week, &student, status(status_value), &teacher) |
| @@ -638,38 +637,26 @@ mod tests { | |||
| 638 | assert_eq!(held(&teacher, &db).await, 0, "a refused mark held a lesson"); | 637 | assert_eq!(held(&teacher, &db).await, 0, "a refused mark held a lesson"); |
| 639 | } | 638 | } |
| 640 | 639 | ||
| 641 | - /// The claim the existence gate cannot make by *reading*. A `DEFINE EVENT` | 640 | + /// The claim the existence gate cannot make by *reading*. The mark writes |
| 642 | - /// on `course_session` fires inside the delete's own transaction, and | 641 | + /// the session row too (its attendance stamp), so the delete and the mark |
| 643 | - /// [`crate::db::course_session::delete`] sweeps its children before removing the row, | 642 | + /// touch one row and Postgres refuses one of them; the barrier releases |
| 644 | - /// so the `SLEEP` opens exactly the window a mark has to lose: the sheet is | 643 | + /// both sides together so every interleaving gets its chance. |
| 645 | - /// written after the sweep has run, and used to commit straight past it. | ||
| 646 | /// | 644 | /// |
| 647 | /// The two flavors raced are the ones the credit branch never wrote for — a | 645 | /// The two flavors raced are the ones the credit branch never wrote for — a |
| 648 | /// lesson that has not begun, and a student with no row yet on a lesson | 646 | /// lesson that has not begun, and a student with no row yet on a lesson |
| 649 | /// already counted. A re-mark of a row that *exists* was never in danger: | 647 | /// already counted. A re-mark of a row that *exists* was never in danger: |
| 650 | /// the cascade and the upsert write that child's own key and collide there. | 648 | /// the cascade and the upsert write that child's own key and collide there. |
| 651 | - /// | 649 | + /// Mutation-tested: dropping the unconditional session-row write from |
| 652 | - /// Real server, and `#[ignore]`d for it: the subject is the store's | 650 | + /// `mark` turns it red. |
| 653 | - /// conflict detection, which [`init_mem`]'s embedded engine does not have — | ||
| 654 | - /// it commits both writes and answers `Ok` to each, so this passes there on | ||
| 655 | - /// broken code. Mutation-tested: dropping the unconditional | ||
| 656 | - /// `UPDATE $sess` from `mark` turns it red. | ||
| 657 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 651 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 658 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 659 | async fn a_mark_written_inside_a_delete_never_outlives_the_session() { | 652 | async fn a_mark_written_inside_a_delete_never_outlives_the_session() { |
| 660 | - let (db, _serialized) = crate::database::init_test_server("session_attendance_race").await; | 653 | + let (db, _leases) = crate::database::init_test_db().await; |
| 661 | - db.query( | ||
| 662 | - "DEFINE EVENT hold_the_window ON TABLE course_session WHEN $event = 'DELETE' \ | ||
| 663 | - THEN { SLEEP 1s; };", | ||
| 664 | - ) | ||
| 665 | - .await | ||
| 666 | - .unwrap() | ||
| 667 | - .check() | ||
| 668 | - .unwrap(); | ||
| 669 | 654 | ||
| 670 | let teacher = a_teacher("t", &db).await; | 655 | let teacher = a_teacher("t", &db).await; |
| 671 | let (mut swept, mut orphans) = (0, 0); | 656 | let (mut swept, mut orphans) = (0, 0); |
| 672 | - for (round, already_counted) in [false, true, false, true].into_iter().enumerate() { | 657 | + for (round, already_counted) in |
| 658 | + [false, true, false, true, false, true, false, true].into_iter().enumerate() | ||
| 659 | + { | ||
| 673 | let session = if already_counted { | 660 | let session = if already_counted { |
| 674 | // Counted by somebody else's mark, so this one credits nothing. | 661 | // Counted by somebody else's mark, so this one credits nothing. |
| 675 | let session = a_session(&teacher, &db).await; | 662 | let session = a_session(&teacher, &db).await; |
| @@ -683,18 +670,22 @@ mod tests { | |||
| 683 | }; | 670 | }; |
| 684 | let id = session.get_id().clone(); | 671 | let id = session.get_id().clone(); |
| 685 | let ghost = session.clone(); | 672 | let ghost = session.clone(); |
| 673 | + | ||
| 674 | + // Delete and mark released together: both write the session row, | ||
| 675 | + // so Postgres serializes them and refuses whichever lost. | ||
| 676 | + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | ||
| 686 | let drop_it = { | 677 | let drop_it = { |
| 687 | - let db = db.clone(); | 678 | + let (db, gate, session) = (db.clone(), gate.clone(), session); |
| 688 | - tokio::spawn(async move { crate::db::course_session::delete(&db, session).await }) | 679 | + tokio::spawn(async move { |
| 680 | + gate.wait().await; | ||
| 681 | + crate::db::course_session::delete(&db, session).await | ||
| 682 | + }) | ||
| 689 | }; | 683 | }; |
| 690 | - // The mark starts inside the held window: the sweep has run and the | ||
| 691 | - // session row is gone but uncommitted — which is exactly what a | ||
| 692 | - // read of that session still believes. | ||
| 693 | - tokio::time::sleep(std::time::Duration::from_millis(300)).await; | ||
| 694 | let marked = { | 684 | let marked = { |
| 695 | - let (db, teacher) = (db.clone(), teacher.clone()); | 685 | + let (db, teacher, gate) = (db.clone(), teacher.clone(), gate); |
| 696 | let student = a_student(&format!("s{round}"), &db).await; | 686 | let student = a_student(&format!("s{round}"), &db).await; |
| 697 | tokio::spawn(async move { | 687 | tokio::spawn(async move { |
| 688 | + gate.wait().await; | ||
| 698 | mark(&db, &ghost, &student, status("present"), &teacher).await | 689 | mark(&db, &ghost, &student, status("present"), &teacher).await |
| 699 | }) | 690 | }) |
| 700 | }; | 691 | }; |
| @@ -717,7 +708,7 @@ mod tests { | |||
| 717 | } | 708 | } |
| 718 | } | 709 | } |
| 719 | eprintln!( | 710 | eprintln!( |
| 720 | - "CourseSession::delete raced by a roll call: {swept}/4 rounds deleted the session" | 711 | + "CourseSession::delete raced by a roll call: {swept}/8 rounds deleted the session" |
| 721 | ); | 712 | ); |
| 722 | assert!( | 713 | assert!( |
| 723 | swept > 0, | 714 | swept > 0, |
src/db/solution.rsmodified+4 -4
| @@ -268,7 +268,7 @@ mod tests { | |||
| 268 | VALUES ($1, $2, 'x')", | 268 | VALUES ($1, $2, 'x')", |
| 269 | ) | 269 | ) |
| 270 | .bind(user.uuid()) | 270 | .bind(user.uuid()) |
| 271 | - .bind(format!("{label}-{}", &user.key()[..8])) | 271 | + .bind(format!("{label}-{}", &user.key()[30..])) |
| 272 | .execute(db) | 272 | .execute(db) |
| 273 | .await | 273 | .await |
| 274 | .unwrap(); | 274 | .unwrap(); |
| @@ -357,7 +357,7 @@ mod tests { | |||
| 357 | async fn image_set_replace_clear_report_the_replaced_blob() { | 357 | async fn image_set_replace_clear_report_the_replaced_blob() { |
| 358 | let (db, _leases) = database::init_test_db().await; | 358 | let (db, _leases) = database::init_test_db().await; |
| 359 | let question = question_row(&db).await; | 359 | let question = question_row(&db).await; |
| 360 | - let author = UserId::from_key(&Ulid::generate().to_string()); | 360 | + let author = a_person(&db, "author").await; |
| 361 | let png = FileContentType::try_new("image/png").unwrap(); | 361 | let png = FileContentType::try_new("image/png").unwrap(); |
| 362 | 362 | ||
| 363 | let solution = insert( | 363 | let solution = insert( |
| @@ -418,7 +418,7 @@ mod tests { | |||
| 418 | async fn set_body_edits_in_place() { | 418 | async fn set_body_edits_in_place() { |
| 419 | let (db, _leases) = database::init_test_db().await; | 419 | let (db, _leases) = database::init_test_db().await; |
| 420 | let question = question_row(&db).await; | 420 | let question = question_row(&db).await; |
| 421 | - let author = UserId::from_key(&Ulid::generate().to_string()); | 421 | + let author = a_person(&db, "author").await; |
| 422 | 422 | ||
| 423 | let solution = insert( | 423 | let solution = insert( |
| 424 | &db, | 424 | &db, |
| @@ -446,7 +446,7 @@ mod tests { | |||
| 446 | assert!( | 446 | assert!( |
| 447 | set_body( | 447 | set_body( |
| 448 | &db, | 448 | &db, |
| 449 | - &SolutionId::from_key(&Ulid::generate().to_string()), | 449 | + &SolutionId::from_key(&uuid::Uuid::now_v7().to_string()), |
| 450 | &SolutionBody::try_new("boş").unwrap(), | 450 | &SolutionBody::try_new("boş").unwrap(), |
| 451 | ) | 451 | ) |
| 452 | .await | 452 | .await |
src/db/subject.rsmodified+1 -3
| @@ -192,7 +192,6 @@ pub async fn delete(db: &Database, subject: Subject) -> Result<Subject, AppError | |||
| 192 | #[cfg(test)] | 192 | #[cfg(test)] |
| 193 | mod tests { | 193 | mod tests { |
| 194 | use super::*; | 194 | use super::*; |
| 195 | - use crate::constant::SUBJECT_TABLE; | ||
| 196 | 195 | ||
| 197 | /// A curriculum topic must not outlive its course: an orphan 404s through | 196 | /// A curriculum topic must not outlive its course: an orphan 404s through |
| 198 | /// `subject_with_course`, and worse than the sibling cases, | 197 | /// `subject_with_course`, and worse than the sibling cases, |
| @@ -248,12 +247,11 @@ mod tests { | |||
| 248 | /// measured on [`crate::db::course::delete`], whose cascade is | 247 | /// measured on [`crate::db::course::delete`], whose cascade is |
| 249 | /// long enough to lose a round (1-2 of 20, red under the same mutation). | 248 | /// long enough to lose a round (1-2 of 20, red under the same mutation). |
| 250 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 249 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 251 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 252 | async fn a_delete_racing_a_question_never_answers_500() { | 250 | async fn a_delete_racing_a_question_never_answers_500() { |
| 253 | use crate::domain::exam_question::{ | 251 | use crate::domain::exam_question::{ |
| 254 | QuestionKind, QuestionPoints, QuestionSpec, QuestionText, | 252 | QuestionKind, QuestionPoints, QuestionSpec, QuestionText, |
| 255 | }; | 253 | }; |
| 256 | - let (db, _serialized) = crate::database::init_test_server("subject_delete_race").await; | 254 | + let (db, _leases) = crate::database::init_test_db().await; |
| 257 | let (mut delete_500, mut question_500) = (0, 0); | 255 | let (mut delete_500, mut question_500) = (0, 0); |
| 258 | let (mut landed, mut wiped) = (0, 0); | 256 | let (mut landed, mut wiped) = (0, 0); |
| 259 | let (mut last_delete, mut last_question) = (String::new(), String::new()); | 257 | let (mut last_delete, mut last_question) = (String::new(), String::new()); |
src/db/term.rsmodified+15 -4
| @@ -266,11 +266,22 @@ mod tests { | |||
| 266 | /// never 500, and a course that got linked survives it. The retry is | 266 | /// never 500, and a course that got linked survives it. The retry is |
| 267 | /// measured on [`crate::db::course::delete`]. | 267 | /// measured on [`crate::db::course::delete`]. |
| 268 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 268 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 269 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 270 | async fn a_delete_racing_a_course_create_never_answers_500() { | 269 | async fn a_delete_racing_a_course_create_never_answers_500() { |
| 271 | use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; | 270 | use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; |
| 272 | use crate::domain::user::UserId; | 271 | use crate::domain::user::UserId; |
| 273 | - let (db, _serialized) = crate::database::init_test_server("term_delete_race").await; | 272 | + let (db, _leases) = crate::database::init_test_db().await; |
| 273 | + // The course's teacher is a foreign key now: one real row, reused by | ||
| 274 | + // every create in every round. | ||
| 275 | + let teacher = UserId::generate(); | ||
| 276 | + sqlx::query( | ||
| 277 | + "INSERT INTO app_user (id, username, password_hash, role) \ | ||
| 278 | + VALUES ($1, $2, 'x', 'teacher')", | ||
| 279 | + ) | ||
| 280 | + .bind(teacher.uuid()) | ||
| 281 | + .bind(format!("term-race-{}", &teacher.key()[30..])) | ||
| 282 | + .execute(&db) | ||
| 283 | + .await | ||
| 284 | + .unwrap(); | ||
| 274 | let (mut delete_500, mut create_500) = (0, 0); | 285 | let (mut delete_500, mut create_500) = (0, 0); |
| 275 | let (mut linked, mut wiped) = (0, 0); | 286 | let (mut linked, mut wiped) = (0, 0); |
| 276 | let (mut last_delete, mut last_create) = (String::new(), String::new()); | 287 | let (mut last_delete, mut last_create) = (String::new(), String::new()); |
| @@ -301,7 +312,7 @@ mod tests { | |||
| 301 | }; | 312 | }; |
| 302 | let makes: Vec<_> = (0..6) | 313 | let makes: Vec<_> = (0..6) |
| 303 | .map(|_| { | 314 | .map(|_| { |
| 304 | - let (id, db) = (term.get_id().clone(), db.clone()); | 315 | + let (id, db, teacher) = (term.get_id().clone(), db.clone(), teacher.clone()); |
| 305 | let head_start = if separated { | 316 | let head_start = if separated { |
| 306 | std::time::Duration::from_millis(2) | 317 | std::time::Duration::from_millis(2) |
| 307 | } else { | 318 | } else { |
| @@ -311,7 +322,7 @@ mod tests { | |||
| 311 | tokio::time::sleep(head_start).await; | 322 | tokio::time::sleep(head_start).await; |
| 312 | crate::db::course::create( | 323 | crate::db::course::create( |
| 313 | &db, | 324 | &db, |
| 314 | - &UserId::from_key("teacher"), | 325 | + &teacher, |
| 315 | CourseTitle::try_new("algebra").unwrap(), | 326 | CourseTitle::try_new("algebra").unwrap(), |
| 316 | CourseDescription::try_new("").unwrap(), | 327 | CourseDescription::try_new("").unwrap(), |
| 317 | CourseKind::course(), | 328 | CourseKind::course(), |
src/domain/fee_plan.rsmodified+1 -1
| @@ -173,7 +173,7 @@ mod tests { | |||
| 173 | ); | 173 | ); |
| 174 | let json = serde_json::to_value(&one).unwrap(); | 174 | let json = serde_json::to_value(&one).unwrap(); |
| 175 | assert_eq!(json["amount_minor"], serde_json::json!(12_345)); | 175 | assert_eq!(json["amount_minor"], serde_json::json!(12_345)); |
| 176 | - assert_eq!(json["due_at"], serde_json::json!(1_700_000_000_000)); | 176 | + assert_eq!(json["due_at"], serde_json::json!(1_700_000_000_000i64)); |
| 177 | let back: Installment = serde_json::from_value(json).unwrap(); | 177 | let back: Installment = serde_json::from_value(json).unwrap(); |
| 178 | assert_eq!(back, one); | 178 | assert_eq!(back, one); |
| 179 | } | 179 | } |
src/domain/payment_ledger.rsmodified+2 -2
| @@ -354,8 +354,8 @@ mod tests { | |||
| 354 | fn a_request_key_is_scoped_by_its_target_and_its_kind() { | 354 | fn a_request_key_is_scoped_by_its_target_and_its_kind() { |
| 355 | const PLAN: &str = "018f1a00-0000-7000-8000-000000000001"; | 355 | const PLAN: &str = "018f1a00-0000-7000-8000-000000000001"; |
| 356 | const STU: &str = "018f1a00-0000-7000-8000-000000000002"; | 356 | const STU: &str = "018f1a00-0000-7000-8000-000000000002"; |
| 357 | - let charge = PaymentLedgerId::from_key(format!("{PLAN}_{STU}_c1")); | 357 | + let charge = PaymentLedgerId::from_key(&format!("{PLAN}_{STU}_c1")); |
| 358 | - let other = PaymentLedgerId::from_key(format!("{PLAN}_{STU}_c2")); | 358 | + let other = PaymentLedgerId::from_key(&format!("{PLAN}_{STU}_c2")); |
| 359 | let key = PaymentRequestKey::try_new("receipt-114").unwrap(); | 359 | let key = PaymentRequestKey::try_new("receipt-114").unwrap(); |
| 360 | let credit = PaymentLedgerId::for_request(&charge, "k", &key); | 360 | let credit = PaymentLedgerId::for_request(&charge, "k", &key); |
| 361 | 361 | ||
src/domain/timestamp.rsmodified+2 -2
| @@ -170,9 +170,9 @@ mod tests { | |||
| 170 | fn json_form_is_the_bare_millisecond_number() { | 170 | fn json_form_is_the_bare_millisecond_number() { |
| 171 | assert_eq!( | 171 | assert_eq!( |
| 172 | serde_json::to_value(Timestamp::from_millis(1_700_000_000_000)).unwrap(), | 172 | serde_json::to_value(Timestamp::from_millis(1_700_000_000_000)).unwrap(), |
| 173 | - serde_json::json!(1_700_000_000_000) | 173 | + serde_json::json!(1_700_000_000_000i64) |
| 174 | ); | 174 | ); |
| 175 | - let back: Timestamp = serde_json::from_value(serde_json::json!(1_700_000_000_000)).unwrap(); | 175 | + let back: Timestamp = serde_json::from_value(serde_json::json!(1_700_000_000_000i64)).unwrap(); |
| 176 | assert_eq!(back.as_millis(), 1_700_000_000_000); | 176 | assert_eq!(back.as_millis(), 1_700_000_000_000); |
| 177 | } | 177 | } |
| 178 | } | 178 | } |
src/service/appointment.rsmodified+59 -30
| @@ -399,6 +399,24 @@ mod tests { | |||
| 399 | Timestamp::from_millis(millis) | 399 | Timestamp::from_millis(millis) |
| 400 | } | 400 | } |
| 401 | 401 | ||
| 402 | + /// A real `app_user` row: teachers and students are foreign keys now. The | ||
| 403 | + /// label names the row's username; the id is minted, so repeated calls are | ||
| 404 | + /// new people, not the same row. | ||
| 405 | + async fn a_person(db: &Database, label: &str, role: &str) -> UserId { | ||
| 406 | + let user = UserId::generate(); | ||
| 407 | + sqlx::query( | ||
| 408 | + "INSERT INTO app_user (id, username, password_hash, role) \ | ||
| 409 | + VALUES ($1, $2, 'x', $3)", | ||
| 410 | + ) | ||
| 411 | + .bind(user.uuid()) | ||
| 412 | + .bind(format!("{label}-{}", &user.key()[30..])) | ||
| 413 | + .bind(role) | ||
| 414 | + .execute(db) | ||
| 415 | + .await | ||
| 416 | + .unwrap(); | ||
| 417 | + user | ||
| 418 | + } | ||
| 419 | + | ||
| 402 | /// A window that has not opened yet — `book` refuses started ones. | 420 | /// A window that has not opened yet — `book` refuses started ones. |
| 403 | fn soon(offset: i64) -> Timestamp { | 421 | fn soon(offset: i64) -> Timestamp { |
| 404 | at(Timestamp::now().as_millis() + offset) | 422 | at(Timestamp::now().as_millis() + offset) |
| @@ -407,7 +425,7 @@ mod tests { | |||
| 407 | #[tokio::test] | 425 | #[tokio::test] |
| 408 | async fn window_prefers_a_proposal_over_the_slot() { | 426 | async fn window_prefers_a_proposal_over_the_slot() { |
| 409 | let (db, _leases) = init_test_db().await; | 427 | let (db, _leases) = init_test_db().await; |
| 410 | - let teacher = UserId::from_key("t1"); | 428 | + let teacher = a_person(&db, "t1", "teacher").await; |
| 411 | let (starts_at, ends_at) = (soon(60_000), soon(120_000)); | 429 | let (starts_at, ends_at) = (soon(60_000), soon(120_000)); |
| 412 | let slot = appointment_slot::create(&db, &teacher, starts_at, ends_at, None) | 430 | let slot = appointment_slot::create(&db, &teacher, starts_at, ends_at, None) |
| 413 | .await | 431 | .await |
| @@ -415,7 +433,7 @@ mod tests { | |||
| 415 | let mut appointment_row = book( | 433 | let mut appointment_row = book( |
| 416 | &db, | 434 | &db, |
| 417 | slot.get_id(), | 435 | slot.get_id(), |
| 418 | - &UserId::from_key("s1"), | 436 | + &a_person(&db, "s1", "student").await, |
| 419 | AppointmentReason::try_new("ödev").unwrap(), | 437 | AppointmentReason::try_new("ödev").unwrap(), |
| 420 | ) | 438 | ) |
| 421 | .await | 439 | .await |
| @@ -432,13 +450,13 @@ mod tests { | |||
| 432 | #[tokio::test] | 450 | #[tokio::test] |
| 433 | async fn a_started_slot_cannot_be_booked() { | 451 | async fn a_started_slot_cannot_be_booked() { |
| 434 | let (db, _leases) = init_test_db().await; | 452 | let (db, _leases) = init_test_db().await; |
| 435 | - let teacher = UserId::from_key("t1"); | 453 | + let teacher = a_person(&db, "t1", "teacher").await; |
| 436 | let reason = || AppointmentReason::try_new("görüşme").unwrap(); | 454 | let reason = || AppointmentReason::try_new("görüşme").unwrap(); |
| 437 | let started = appointment_slot::create(&db, &teacher, soon(-30_000), soon(60_000), None) | 455 | let started = appointment_slot::create(&db, &teacher, soon(-30_000), soon(60_000), None) |
| 438 | .await | 456 | .await |
| 439 | .unwrap(); | 457 | .unwrap(); |
| 440 | assert!(matches!( | 458 | assert!(matches!( |
| 441 | - book(&db, started.get_id(), &UserId::from_key("s1"), reason()).await, | 459 | + book(&db, started.get_id(), &a_person(&db, "s1", "student").await, reason()).await, |
| 442 | Err(AppError::Conflict("the slot has already started")) | 460 | Err(AppError::Conflict("the slot has already started")) |
| 443 | )); | 461 | )); |
| 444 | 462 | ||
| @@ -446,7 +464,7 @@ mod tests { | |||
| 446 | .await | 464 | .await |
| 447 | .unwrap(); | 465 | .unwrap(); |
| 448 | assert!( | 466 | assert!( |
| 449 | - book(&db, upcoming.get_id(), &UserId::from_key("s1"), reason()) | 467 | + book(&db, upcoming.get_id(), &a_person(&db, "s1", "student").await, reason()) |
| 450 | .await | 468 | .await |
| 451 | .is_ok() | 469 | .is_ok() |
| 452 | ); | 470 | ); |
| @@ -457,8 +475,8 @@ mod tests { | |||
| 457 | #[tokio::test] | 475 | #[tokio::test] |
| 458 | async fn a_started_proposal_cannot_be_accepted() { | 476 | async fn a_started_proposal_cannot_be_accepted() { |
| 459 | let (db, _leases) = init_test_db().await; | 477 | let (db, _leases) = init_test_db().await; |
| 460 | - let teacher = UserId::from_key("t1"); | 478 | + let teacher = a_person(&db, "t1", "teacher").await; |
| 461 | - let student = UserId::from_key("s1"); | 479 | + let student = a_person(&db, "s1", "student").await; |
| 462 | let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) | 480 | let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) |
| 463 | .await | 481 | .await |
| 464 | .unwrap(); | 482 | .unwrap(); |
| @@ -545,8 +563,8 @@ mod tests { | |||
| 545 | #[tokio::test] | 563 | #[tokio::test] |
| 546 | async fn a_decision_built_on_a_stale_snapshot_never_lands() { | 564 | async fn a_decision_built_on_a_stale_snapshot_never_lands() { |
| 547 | let (db, _leases) = init_test_db().await; | 565 | let (db, _leases) = init_test_db().await; |
| 548 | - let teacher = UserId::from_key("t1"); | 566 | + let teacher = a_person(&db, "t1", "teacher").await; |
| 549 | - let student = UserId::from_key("s1"); | 567 | + let student = a_person(&db, "s1", "student").await; |
| 550 | let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) | 568 | let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) |
| 551 | .await | 569 | .await |
| 552 | .unwrap(); | 570 | .unwrap(); |
| @@ -611,14 +629,27 @@ mod tests { | |||
| 611 | /// What the slot row itself says about being taken — the authority every | 629 | /// What the slot row itself says about being taken — the authority every |
| 612 | /// gate now reads. | 630 | /// gate now reads. |
| 613 | async fn occupied(slot: &AppointmentSlotId, db: &Database) -> i64 { | 631 | async fn occupied(slot: &AppointmentSlotId, db: &Database) -> i64 { |
| 614 | - let mut result = db | 632 | + sqlx::query_scalar::<_, i64>("SELECT occupied FROM appointment_slot WHERE id = $1") |
| 615 | - .query("SELECT VALUE (occupied ?? 0) FROM $slot") | 633 | + .bind(slot.uuid()) |
| 616 | - .bind(("slot", slot.record())) | 634 | + .fetch_one(db) |
| 617 | .await | 635 | .await |
| 618 | .unwrap() | 636 | .unwrap() |
| 619 | - .check() | 637 | + } |
| 620 | - .unwrap(); | 638 | + |
| 621 | - result.take::<Vec<i64>>(0).unwrap()[0] | 639 | + /// The seat claim `book` rides, asked directly: the conditional |
| 640 | + /// `UPDATE … WHERE occupied < $cap` on the slot row is the whole | ||
| 641 | + /// primitive, so this asks it the exact question the race asks. | ||
| 642 | + async fn claim_seat(slot: &AppointmentSlotId, cap: i64, db: &Database) -> bool { | ||
| 643 | + sqlx::query_scalar::<_, i32>( | ||
| 644 | + "UPDATE appointment_slot SET occupied = occupied + 1 \ | ||
| 645 | + WHERE id = $1 AND occupied < $2 RETURNING 1", | ||
| 646 | + ) | ||
| 647 | + .bind(slot.uuid()) | ||
| 648 | + .bind(cap) | ||
| 649 | + .fetch_optional(db) | ||
| 650 | + .await | ||
| 651 | + .unwrap() | ||
| 652 | + .is_some() | ||
| 622 | } | 653 | } |
| 623 | 654 | ||
| 624 | /// The double-book race with the lock taken out of the picture: a second | 655 | /// The double-book race with the lock taken out of the picture: a second |
| @@ -634,7 +665,7 @@ mod tests { | |||
| 634 | #[tokio::test] | 665 | #[tokio::test] |
| 635 | async fn a_concurrent_claim_cannot_take_a_booked_slot() { | 666 | async fn a_concurrent_claim_cannot_take_a_booked_slot() { |
| 636 | let (db, _leases) = init_test_db().await; | 667 | let (db, _leases) = init_test_db().await; |
| 637 | - let teacher = UserId::from_key("t1"); | 668 | + let teacher = a_person(&db, "t1", "teacher").await; |
| 638 | let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) | 669 | let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) |
| 639 | .await | 670 | .await |
| 640 | .unwrap(); | 671 | .unwrap(); |
| @@ -643,7 +674,7 @@ mod tests { | |||
| 643 | book( | 674 | book( |
| 644 | &db, | 675 | &db, |
| 645 | slot.get_id(), | 676 | slot.get_id(), |
| 646 | - &UserId::from_key("s1"), | 677 | + &a_person(&db, "s1", "student").await, |
| 647 | AppointmentReason::try_new("görüşme").unwrap(), | 678 | AppointmentReason::try_new("görüşme").unwrap(), |
| 648 | ) | 679 | ) |
| 649 | .await | 680 | .await |
| @@ -651,9 +682,7 @@ mod tests { | |||
| 651 | assert_eq!(occupied(slot.get_id(), &db).await, 1); | 682 | assert_eq!(occupied(slot.get_id(), &db).await, 1); |
| 652 | 683 | ||
| 653 | assert!( | 684 | assert!( |
| 654 | - !cap::claim(&slot.get_id().record(), SLOT_OCCUPIED_FIELD, 1, &db) | 685 | + !claim_seat(slot.get_id(), 1, &db).await, |
| 655 | - .await | ||
| 656 | - .unwrap(), | ||
| 657 | "the slot's seat must already be taken" | 686 | "the slot's seat must already be taken" |
| 658 | ); | 687 | ); |
| 659 | // And the racer's refusal left the stored state alone: one booking, one | 688 | // And the racer's refusal left the stored state alone: one booking, one |
| @@ -675,18 +704,18 @@ mod tests { | |||
| 675 | #[tokio::test] | 704 | #[tokio::test] |
| 676 | async fn a_refused_booking_moves_nothing() { | 705 | async fn a_refused_booking_moves_nothing() { |
| 677 | let (db, _leases) = init_test_db().await; | 706 | let (db, _leases) = init_test_db().await; |
| 678 | - let teacher = UserId::from_key("t1"); | 707 | + let teacher = a_person(&db, "t1", "teacher").await; |
| 679 | let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) | 708 | let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) |
| 680 | .await | 709 | .await |
| 681 | .unwrap(); | 710 | .unwrap(); |
| 682 | let reason = || AppointmentReason::try_new("görüşme").unwrap(); | 711 | let reason = || AppointmentReason::try_new("görüşme").unwrap(); |
| 683 | 712 | ||
| 684 | - book(&db, slot.get_id(), &UserId::from_key("s1"), reason()) | 713 | + book(&db, slot.get_id(), &a_person(&db, "s1", "student").await, reason()) |
| 685 | .await | 714 | .await |
| 686 | .unwrap(); | 715 | .unwrap(); |
| 687 | assert_eq!(occupied(slot.get_id(), &db).await, 1); | 716 | assert_eq!(occupied(slot.get_id(), &db).await, 1); |
| 688 | 717 | ||
| 689 | - let refused = book(&db, slot.get_id(), &UserId::from_key("s2"), reason()).await; | 718 | + let refused = book(&db, slot.get_id(), &a_person(&db, "s2", "student").await, reason()).await; |
| 690 | assert!( | 719 | assert!( |
| 691 | matches!(refused, Err(AppError::Conflict(_))), | 720 | matches!(refused, Err(AppError::Conflict(_))), |
| 692 | "the slot is taken" | 721 | "the slot is taken" |
| @@ -712,8 +741,8 @@ mod tests { | |||
| 712 | #[tokio::test] | 741 | #[tokio::test] |
| 713 | async fn cancelling_hands_the_seat_back_with_the_status() { | 742 | async fn cancelling_hands_the_seat_back_with_the_status() { |
| 714 | let (db, _leases) = init_test_db().await; | 743 | let (db, _leases) = init_test_db().await; |
| 715 | - let teacher = UserId::from_key("t1"); | 744 | + let teacher = a_person(&db, "t1", "teacher").await; |
| 716 | - let student = UserId::from_key("s1"); | 745 | + let student = a_person(&db, "s1", "student").await; |
| 717 | let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) | 746 | let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) |
| 718 | .await | 747 | .await |
| 719 | .unwrap(); | 748 | .unwrap(); |
| @@ -737,7 +766,7 @@ mod tests { | |||
| 737 | book( | 766 | book( |
| 738 | &db, | 767 | &db, |
| 739 | slot.get_id(), | 768 | slot.get_id(), |
| 740 | - &UserId::from_key("s2"), | 769 | + &a_person(&db, "s2", "student").await, |
| 741 | AppointmentReason::try_new("görüşme").unwrap() | 770 | AppointmentReason::try_new("görüşme").unwrap() |
| 742 | ) | 771 | ) |
| 743 | .await | 772 | .await |
| @@ -750,17 +779,17 @@ mod tests { | |||
| 750 | #[tokio::test] | 779 | #[tokio::test] |
| 751 | async fn rejecting_frees_the_slot_for_re_booking() { | 780 | async fn rejecting_frees_the_slot_for_re_booking() { |
| 752 | let (db, _leases) = init_test_db().await; | 781 | let (db, _leases) = init_test_db().await; |
| 753 | - let teacher = UserId::from_key("t1"); | 782 | + let teacher = a_person(&db, "t1", "teacher").await; |
| 754 | let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) | 783 | let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) |
| 755 | .await | 784 | .await |
| 756 | .unwrap(); | 785 | .unwrap(); |
| 757 | let reason = || AppointmentReason::try_new("görüşme").unwrap(); | 786 | let reason = || AppointmentReason::try_new("görüşme").unwrap(); |
| 758 | 787 | ||
| 759 | - let first = book(&db, slot.get_id(), &UserId::from_key("s1"), reason()) | 788 | + let first = book(&db, slot.get_id(), &a_person(&db, "s1", "student").await, reason()) |
| 760 | .await | 789 | .await |
| 761 | .unwrap(); | 790 | .unwrap(); |
| 762 | assert!(matches!( | 791 | assert!(matches!( |
| 763 | - book(&db, slot.get_id(), &UserId::from_key("s2"), reason()).await, | 792 | + book(&db, slot.get_id(), &a_person(&db, "s2", "student").await, reason()).await, |
| 764 | Err(AppError::Conflict(_)) | 793 | Err(AppError::Conflict(_)) |
| 765 | )); | 794 | )); |
| 766 | // The live booking also blocks the slot delete. | 795 | // The live booking also blocks the slot delete. |
| @@ -771,7 +800,7 @@ mod tests { | |||
| 771 | 800 | ||
| 772 | reject(&db, first.get_id(), &teacher, None).await.unwrap(); | 801 | reject(&db, first.get_id(), &teacher, None).await.unwrap(); |
| 773 | assert_eq!(occupied(slot.get_id(), &db).await, 0); | 802 | assert_eq!(occupied(slot.get_id(), &db).await, 0); |
| 774 | - let second = book(&db, slot.get_id(), &UserId::from_key("s2"), reason()) | 803 | + let second = book(&db, slot.get_id(), &a_person(&db, "s2", "student").await, reason()) |
| 775 | .await | 804 | .await |
| 776 | .unwrap(); | 805 | .unwrap(); |
| 777 | assert_eq!(second.get_status(), AppointmentStatus::Pending); | 806 | assert_eq!(second.get_status(), AppointmentStatus::Pending); |
src/service/builder.rsmodified+0 -1
| @@ -63,7 +63,6 @@ pub async fn delete_by_token(db: &Database, token: &str) -> Result<(), AppError> | |||
| 63 | #[cfg(test)] | 63 | #[cfg(test)] |
| 64 | mod tests { | 64 | mod tests { |
| 65 | use super::*; | 65 | use super::*; |
| 66 | - use crate::tenant::Tenants; | ||
| 67 | 66 | ||
| 68 | #[tokio::test] | 67 | #[tokio::test] |
| 69 | async fn the_seed_is_idempotent_and_never_rewrites_a_credential() { | 68 | async fn the_seed_is_idempotent_and_never_rewrites_a_credential() { |
src/service/fee_plan_assignment.rsmodified+28 -11
| @@ -215,12 +215,31 @@ mod tests { | |||
| 215 | use crate::domain::fee_plan::{FeePlanName, Installment}; | 215 | use crate::domain::fee_plan::{FeePlanName, Installment}; |
| 216 | use crate::domain::payment_ledger::LedgerAmount; | 216 | use crate::domain::payment_ledger::LedgerAmount; |
| 217 | 217 | ||
| 218 | + /// A real `app_user` row: managers and students are foreign keys now. The | ||
| 219 | + /// label names the row's username; the id is minted, so repeated calls are | ||
| 220 | + /// new people, not the same row. | ||
| 221 | + async fn a_person(db: &Database, label: &str, role: &str) -> UserId { | ||
| 222 | + let user = UserId::generate(); | ||
| 223 | + sqlx::query( | ||
| 224 | + "INSERT INTO app_user (id, username, password_hash, role) \ | ||
| 225 | + VALUES ($1, $2, 'x', $3)", | ||
| 226 | + ) | ||
| 227 | + .bind(user.uuid()) | ||
| 228 | + .bind(format!("{label}-{}", &user.key()[30..])) | ||
| 229 | + .bind(role) | ||
| 230 | + .execute(db) | ||
| 231 | + .await | ||
| 232 | + .unwrap(); | ||
| 233 | + user | ||
| 234 | + } | ||
| 235 | + | ||
| 218 | async fn a_plan(db: &Database, installments: Vec<Installment>) -> FeePlan { | 236 | async fn a_plan(db: &Database, installments: Vec<Installment>) -> FeePlan { |
| 237 | + let manager = a_person(db, "mgr", "manager").await; | ||
| 219 | fee_plan::create( | 238 | fee_plan::create( |
| 220 | db, | 239 | db, |
| 221 | FeePlanName::try_new("Yearly").unwrap(), | 240 | FeePlanName::try_new("Yearly").unwrap(), |
| 222 | installments, | 241 | installments, |
| 223 | - &UserId::from_key("mgr1"), | 242 | + &manager, |
| 224 | ) | 243 | ) |
| 225 | .await | 244 | .await |
| 226 | .unwrap() | 245 | .unwrap() |
| @@ -232,8 +251,8 @@ mod tests { | |||
| 232 | #[tokio::test] | 251 | #[tokio::test] |
| 233 | async fn assigning_bills_every_installment_and_a_replay_bills_nothing() { | 252 | async fn assigning_bills_every_installment_and_a_replay_bills_nothing() { |
| 234 | let (db, _leases) = init_test_db().await; | 253 | let (db, _leases) = init_test_db().await; |
| 235 | - let manager = UserId::from_key("mgr1"); | 254 | + let manager = a_person(&db, "mgr", "manager").await; |
| 236 | - let student = UserId::from_key("stu1"); | 255 | + let student = a_person(&db, "stu", "student").await; |
| 237 | let plan = a_plan( | 256 | let plan = a_plan( |
| 238 | &db, | 257 | &db, |
| 239 | vec![ | 258 | vec![ |
| @@ -309,13 +328,12 @@ mod tests { | |||
| 309 | /// (measured 2026-07-30: 2 runs in 36 on `memory` under host load, 0 in | 328 | /// (measured 2026-07-30: 2 runs in 36 on `memory` under host load, 0 in |
| 310 | /// 10 000 rounds on the server). See [`crate::database::init_test_server`]. | 329 | /// 10 000 rounds on the server). See [`crate::database::init_test_server`]. |
| 311 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 330 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 312 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 313 | async fn an_edit_racing_an_assign_leaves_the_plan_and_the_money_agreeing() { | 331 | async fn an_edit_racing_an_assign_leaves_the_plan_and_the_money_agreeing() { |
| 314 | - let (db, _serialized) = crate::database::init_test_server("edit_race").await; | 332 | + let (db, _leases) = crate::database::init_test_db().await; |
| 315 | let mut reached = 0; | 333 | let mut reached = 0; |
| 316 | for round in 0..20 { | 334 | for round in 0..20 { |
| 317 | - let manager = UserId::from_key("mgr1"); | 335 | + let manager = a_person(&db, "mgr", "manager").await; |
| 318 | - let student = UserId::from_key(&format!("stu{round}")); | 336 | + let student = a_person(&db, "stu", "student").await; |
| 319 | let plan = a_plan( | 337 | let plan = a_plan( |
| 320 | &db, | 338 | &db, |
| 321 | vec![Installment::new( | 339 | vec![Installment::new( |
| @@ -416,14 +434,13 @@ mod tests { | |||
| 416 | /// unseen. Neither racer may answer 500 here either — this is the pair that | 434 | /// unseen. Neither racer may answer 500 here either — this is the pair that |
| 417 | /// contends hardest, both writing the plan record itself. | 435 | /// contends hardest, both writing the plan record itself. |
| 418 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 436 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 419 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 420 | async fn a_delete_racing_an_assign_never_orphans_an_assignment() { | 437 | async fn a_delete_racing_an_assign_never_orphans_an_assignment() { |
| 421 | - let (db, _serialized) = crate::database::init_test_server("delete_race").await; | 438 | + let (db, _leases) = crate::database::init_test_db().await; |
| 422 | let (mut deleted_first, mut assigned_first) = (0, 0); | 439 | let (mut deleted_first, mut assigned_first) = (0, 0); |
| 423 | for round in 0..20 { | 440 | for round in 0..20 { |
| 424 | let hold_back_the_assign = round % 2 == 0; | 441 | let hold_back_the_assign = round % 2 == 0; |
| 425 | - let manager = UserId::from_key("mgr1"); | 442 | + let manager = a_person(&db, "mgr", "manager").await; |
| 426 | - let student = UserId::from_key(&format!("stu{round}")); | 443 | + let student = a_person(&db, "stu", "student").await; |
| 427 | let plan = a_plan( | 444 | let plan = a_plan( |
| 428 | &db, | 445 | &db, |
| 429 | vec![Installment::new( | 446 | vec![Installment::new( |
src/service/user.rsmodified+11 -15
| @@ -431,21 +431,17 @@ mod tests { | |||
| 431 | } | 431 | } |
| 432 | // The seat each held died with its slot row, so nothing is pinned: no | 432 | // The seat each held died with its slot row, so nothing is pinned: no |
| 433 | // live booking is left pointing at a slot that no longer exists. | 433 | // live booking is left pointing at a slot that no longer exists. |
| 434 | - let mut result = db | 434 | + // The slot is a foreign key now, so this reads as a structural fact: |
| 435 | - .query( | 435 | + // no live booking may point at a slot row that is gone. |
| 436 | - "SELECT VALUE id FROM appointment \ | 436 | + let orphans: i64 = sqlx::query_scalar( |
| 437 | - WHERE status IN ['pending', 'approved'] AND slot.starts_at = NONE", | 437 | + "SELECT count(*) FROM appointment a \ |
| 438 | - ) | 438 | + WHERE a.status IN ('pending', 'approved') \ |
| 439 | - .await | 439 | + AND NOT EXISTS (SELECT 1 FROM appointment_slot s WHERE s.id = a.slot)", |
| 440 | - .unwrap() | 440 | + ) |
| 441 | - .check() | 441 | + .fetch_one(&db) |
| 442 | - .unwrap(); | 442 | + .await |
| 443 | - assert!( | 443 | + .unwrap(); |
| 444 | - result | 444 | + assert_eq!(orphans, 0); |
| 445 | - .take::<Vec<surrealdb::types::RecordId>>(0) | ||
| 446 | - .unwrap() | ||
| 447 | - .is_empty() | ||
| 448 | - ); | ||
| 449 | 445 | ||
| 450 | // Another teacher's calendar is nobody else's business. | 446 | // Another teacher's calendar is nobody else's business. |
| 451 | assert_eq!( | 447 | assert_eq!( |
src/web/chatbot.rsmodified+21 -8
| @@ -902,14 +902,27 @@ mod tests { | |||
| 902 | // service a handful of unanswered prompts and nothing older. | 902 | // service a handful of unanswered prompts and nothing older. |
| 903 | let (db, _leases) = crate::database::init_test_db().await; | 903 | let (db, _leases) = crate::database::init_test_db().await; |
| 904 | // A real thread row: every turn is written through it, so a turn with | 904 | // A real thread row: every turn is written through it, so a turn with |
| 905 | - // no thread is refused. | 905 | + // no thread is refused. The owner is a foreign key now, so both |
| 906 | - db.query("CREATE chatbot_thread:c SET user_id = user:u, created_at = 0, updated_at = 0") | 906 | + // fixture rows are real, under fixed keys. |
| 907 | - .await | 907 | + let user = UserId::from_key("019732e3-7b00-7000-8000-00000000cafe"); |
| 908 | - .unwrap() | 908 | + let thread = ChatbotThreadId::from_key("019732e3-7b00-7000-8000-00000000beef"); |
| 909 | - .check() | 909 | + sqlx::query( |
| 910 | - .unwrap(); | 910 | + "INSERT INTO app_user (id, username, password_hash) \ |
| 911 | - let thread = ChatbotThreadId::from_key("c"); | 911 | + VALUES ($1, 'chat-web-fixture', 'x')", |
| 912 | - let user = UserId::from_key("u"); | 912 | + ) |
| 913 | + .bind(user.uuid()) | ||
| 914 | + .execute(&db) | ||
| 915 | + .await | ||
| 916 | + .unwrap(); | ||
| 917 | + sqlx::query( | ||
| 918 | + "INSERT INTO chatbot_thread (id, user_id, created_at, updated_at) \ | ||
| 919 | + VALUES ($1, $2, 0, 0)", | ||
| 920 | + ) | ||
| 921 | + .bind(thread.uuid()) | ||
| 922 | + .bind(user.uuid()) | ||
| 923 | + .execute(&db) | ||
| 924 | + .await | ||
| 925 | + .unwrap(); | ||
| 913 | let say = |text: String| ChatContent::try_new(&text).unwrap(); | 926 | let say = |text: String| ChatContent::try_new(&text).unwrap(); |
| 914 | 927 | ||
| 915 | for turn in 0..10 { | 928 | for turn in 0..10 { |
src/web/classes.rsmodified+2 -2
| @@ -1522,7 +1522,7 @@ mod tests { | |||
| 1522 | 1522 | ||
| 1523 | for (field, id) in [ | 1523 | for (field, id) in [ |
| 1524 | ("gone", "0198f1a2-3b4c-7d5e-8f90-000000000001"), | 1524 | ("gone", "0198f1a2-3b4c-7d5e-8f90-000000000001"), |
| 1525 | - ("student", student.get_id().key()), | 1525 | + ("student", student.get_id().key().as_str()), |
| 1526 | ] { | 1526 | ] { |
| 1527 | let refused = teacher_or_none(Some(id), &db).await; | 1527 | let refused = teacher_or_none(Some(id), &db).await; |
| 1528 | assert!( | 1528 | assert!( |
| @@ -1537,7 +1537,7 @@ mod tests { | |||
| 1537 | ); | 1537 | ); |
| 1538 | } | 1538 | } |
| 1539 | assert_eq!( | 1539 | assert_eq!( |
| 1540 | - teacher_or_none(Some(teacher.get_id().key()), &db) | 1540 | + teacher_or_none(Some(teacher.get_id().key().as_str()), &db) |
| 1541 | .await | 1541 | .await |
| 1542 | .unwrap() | 1542 | .unwrap() |
| 1543 | .map(|found| found.get_id().clone()), | 1543 | .map(|found| found.get_id().clone()), |
src/web/courses.rsmodified+0 -1
| @@ -1385,7 +1385,6 @@ mod tests { | |||
| 1385 | chatbot_limit: Default::default(), | 1385 | chatbot_limit: Default::default(), |
| 1386 | exam_presence: Default::default(), | 1386 | exam_presence: Default::default(), |
| 1387 | board_hub: Default::default(), | 1387 | board_hub: Default::default(), |
| 1388 | - db_up: Default::default(), | ||
| 1389 | ai: None, | 1388 | ai: None, |
| 1390 | metrics: crate::telemetry::Metrics::noop(), | 1389 | metrics: crate::telemetry::Metrics::noop(), |
| 1391 | }; | 1390 | }; |
src/web/events.rsmodified+7 -1
| @@ -943,7 +943,13 @@ mod tests { | |||
| 943 | creator.get_id(), | 943 | creator.get_id(), |
| 944 | EventTitle::try_new("Gezi").unwrap(), | 944 | EventTitle::try_new("Gezi").unwrap(), |
| 945 | EventDescription::try_new("").unwrap(), | 945 | EventDescription::try_new("").unwrap(), |
| 946 | - EventAudience::School, | 946 | + EventAudience { |
| 947 | + kind: EventAudienceKind::School, | ||
| 948 | + role: None, | ||
| 949 | + course: None, | ||
| 950 | + class: None, | ||
| 951 | + capacity: None, | ||
| 952 | + }, | ||
| 947 | None, | 953 | None, |
| 948 | None, | 954 | None, |
| 949 | ) | 955 | ) |
src/web/page.rsmodified+2 -2
| @@ -198,8 +198,8 @@ mod tests { | |||
| 198 | fn ends_at_ms(&self) -> Option<i64> { | 198 | fn ends_at_ms(&self) -> Option<i64> { |
| 199 | self.2 | 199 | self.2 |
| 200 | } | 200 | } |
| 201 | - fn order_key(&self) -> &str { | 201 | + fn order_key(&self) -> String { |
| 202 | - self.0 | 202 | + self.0.to_owned() |
| 203 | } | 203 | } |
| 204 | } | 204 | } |
| 205 | 205 | ||