Merge branch 'layer-split/catalog'
Browse files at this commit30 changed files +1093 -920
- src/db/course.rs +14 -13
- src/db/exam.rs +14 -13
- src/db/exam_attempt.rs +3 -3
- src/db/exam_question.rs +4 -4
- src/db/mod.rs +2 -0
- src/db/subject.rs +350 -0
- src/db/term.rs +352 -0
- src/domain/bank_question.rs +3 -3
- src/domain/class_group.rs +23 -20
- src/domain/homework.rs +9 -6
- src/domain/homework_file.rs +3 -3
- src/domain/homework_result.rs +3 -3
- src/domain/homework_submission.rs +3 -3
- src/domain/subject.rs +9 -348
- src/domain/term.rs +9 -354
- src/service/course.rs +3 -2
- src/service/exam_attempt.rs +3 -3
- src/service/mod.rs +2 -0
- src/service/subject.rs +89 -0
- src/service/term.rs +111 -0
- src/web/bank_questions.rs +20 -16
- src/web/classes.rs +4 -4
- src/web/courses.rs +21 -12
- src/web/exams/mod.rs +0 -1
- src/web/exams/questions.rs +5 -3
- src/web/homework.rs +4 -3
- src/web/subjects.rs +6 -45
- src/web/terms.rs +18 -52
- tests/regress_course_child_orphans.rs +5 -5
- tests/regress_course_delete.rs +1 -1
src/db/course.rsmodified+14 -13
| @@ -262,7 +262,7 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App | ||
| 262 | 262 | /// spanning every course — so their `source_exam` and `subject` links are |
| 263 | 263 | /// cleared instead, in this same transaction, exactly as |
| 264 | 264 | /// [`crate::db::exam::delete`] and |
| 265 | -/// [`crate::domain::subject::Subject::delete`] clear them one level down. | |
| 265 | +/// [`crate::db::subject::delete`] clear them one level down. | |
| 266 | 266 | /// Deleting a course must leave the bank where deleting each of its exams |
| 267 | 267 | /// and subjects by hand would have left it, or a template is left pointing |
| 268 | 268 | /// at a dead exam (permanently: nothing else ever visits that column) and |
| @@ -561,14 +561,15 @@ mod tests { | ||
| 561 | 561 | async fn a_term_is_deletable_only_once_no_course_links_it() { |
| 562 | 562 | let db = crate::database::init_mem().await.unwrap(); |
| 563 | 563 | let at = crate::domain::timestamp::Timestamp::from_millis; |
| 564 | - let term = Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), &db) | |
| 565 | - .await | |
| 566 | - .unwrap(); | |
| 564 | + let term = | |
| 565 | + crate::db::term::create(&db, TermName::try_new("2026").unwrap(), at(100), at(200)) | |
| 566 | + .await | |
| 567 | + .unwrap(); | |
| 567 | 568 | |
| 568 | 569 | let linked = course_on(Some(term.get_id().clone()), &db).await; |
| 569 | 570 | let patched = course_on(Some(term.get_id().clone()), &db).await; |
| 570 | 571 | assert!( |
| 571 | - !term.clone().delete(&db).await.unwrap(), | |
| 572 | + !crate::db::term::delete(&db, term.clone()).await.unwrap(), | |
| 572 | 573 | "two linked courses must refuse the delete" |
| 573 | 574 | ); |
| 574 | 575 | |
| @@ -576,16 +577,16 @@ mod tests { | ||
| 576 | 577 | .await |
| 577 | 578 | .unwrap(); |
| 578 | 579 | assert!( |
| 579 | - !term.clone().delete(&db).await.unwrap(), | |
| 580 | + !crate::db::term::delete(&db, term.clone()).await.unwrap(), | |
| 580 | 581 | "one link is still one link" |
| 581 | 582 | ); |
| 582 | 583 | |
| 583 | 584 | assert!(delete(&db, linked).await.unwrap()); |
| 584 | 585 | assert!( |
| 585 | - term.clone().delete(&db).await.unwrap(), | |
| 586 | + crate::db::term::delete(&db, term.clone()).await.unwrap(), | |
| 586 | 587 | "the last link gone, the term may go" |
| 587 | 588 | ); |
| 588 | - let again = term.delete(&db).await; | |
| 589 | + let again = crate::db::term::delete(&db, term).await; | |
| 589 | 590 | assert!( |
| 590 | 591 | matches!(again, Err(AppError::NotFound)), |
| 591 | 592 | "a second delete is a 404, not a refusal: {again:?}" |
| @@ -639,7 +640,7 @@ mod tests { | ||
| 639 | 640 | |
| 640 | 641 | async fn a_term(name: &str, db: &Database) -> Term { |
| 641 | 642 | let at = crate::domain::timestamp::Timestamp::from_millis; |
| 642 | - Term::create(TermName::try_new(name).unwrap(), at(100), at(200), db) | |
| 643 | + crate::db::term::create(db, TermName::try_new(name).unwrap(), at(100), at(200)) | |
| 643 | 644 | .await |
| 644 | 645 | .unwrap() |
| 645 | 646 | } |
| @@ -654,7 +655,7 @@ mod tests { | ||
| 654 | 655 | let db = crate::database::init_mem().await.unwrap(); |
| 655 | 656 | let term = a_term("2026", &db).await; |
| 656 | 657 | let id = term.get_id().clone(); |
| 657 | - assert!(term.delete(&db).await.unwrap()); | |
| 658 | + assert!(crate::db::term::delete(&db, term).await.unwrap()); | |
| 658 | 659 | |
| 659 | 660 | let error = create( |
| 660 | 661 | &db, |
| @@ -708,8 +709,8 @@ mod tests { | ||
| 708 | 709 | "the old term is free" |
| 709 | 710 | ); |
| 710 | 711 | assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); |
| 711 | - assert!(from.clone().delete(&db).await.unwrap()); | |
| 712 | - assert!(!to.clone().delete(&db).await.unwrap()); | |
| 712 | + assert!(crate::db::term::delete(&db, from.clone()).await.unwrap()); | |
| 713 | + assert!(!crate::db::term::delete(&db, to.clone()).await.unwrap()); | |
| 713 | 714 | } |
| 714 | 715 | |
| 715 | 716 | /// The double-claim guard. Both movers compute their claim and release from |
| @@ -887,7 +888,7 @@ mod tests { | ||
| 887 | 888 | let from = a_term("2026", &db).await; |
| 888 | 889 | let dead = a_term("2027", &db).await; |
| 889 | 890 | let dead_id = dead.get_id().clone(); |
| 890 | - assert!(dead.delete(&db).await.unwrap()); | |
| 891 | + assert!(crate::db::term::delete(&db, dead).await.unwrap()); | |
| 891 | 892 | let course = course_on(Some(from.get_id().clone()), &db).await; |
| 892 | 893 | |
| 893 | 894 | let error = update( |
src/db/exam.rsmodified+14 -13
| @@ -749,11 +749,11 @@ mod tests { | ||
| 749 | 749 | &[], |
| 750 | 750 | ) |
| 751 | 751 | .unwrap(); |
| 752 | - let subject = crate::domain::subject::Subject::create( | |
| 752 | + let subject = crate::db::subject::create( | |
| 753 | + db, | |
| 753 | 754 | &crate::db::course::a_test_course(db).await, |
| 754 | 755 | crate::domain::subject::SubjectName::try_new("topic").unwrap(), |
| 755 | 756 | crate::domain::subject::SubjectDescription::try_new("").unwrap(), |
| 756 | - db, | |
| 757 | 757 | ) |
| 758 | 758 | .await |
| 759 | 759 | .unwrap(); |
| @@ -863,7 +863,7 @@ mod tests { | ||
| 863 | 863 | /// The same defect on the teacher's side of the sheet, and a worse one: a |
| 864 | 864 | /// question written inside the delete window kept the reference it claimed |
| 865 | 865 | /// on its subject (the cascade's per-subject decrement counted only the |
| 866 | - /// rows it could see), and [`crate::domain::subject::Subject::delete`] is | |
| 866 | + /// rows it could see), and [`crate::db::subject::delete`] is | |
| 867 | 867 | /// gated on that count reading zero — a subject nobody could ever delete |
| 868 | 868 | /// again, hanging off an exam nobody could ever see. The freeze gate is a |
| 869 | 869 | /// *read* of `exam_attempt` and never survived this window; |
| @@ -878,7 +878,6 @@ mod tests { | ||
| 878 | 878 | use crate::domain::exam_question::{ |
| 879 | 879 | ChoiceInput, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, |
| 880 | 880 | }; |
| 881 | - use crate::domain::subject::Subject; | |
| 882 | 881 | let (db, _serialized) = crate::database::init_test_server("exam_question_race").await; |
| 883 | 882 | db.query( |
| 884 | 883 | "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \ |
| @@ -893,11 +892,11 @@ mod tests { | ||
| 893 | 892 | for round in 0..4 { |
| 894 | 893 | let exam = published(&db).await; |
| 895 | 894 | let id = exam.get_id().clone(); |
| 896 | - let subject = Subject::create( | |
| 895 | + let subject = crate::db::subject::create( | |
| 896 | + &db, | |
| 897 | 897 | &crate::db::course::a_test_course(&db).await, |
| 898 | 898 | crate::domain::subject::SubjectName::try_new("topic").unwrap(), |
| 899 | 899 | crate::domain::subject::SubjectDescription::try_new("").unwrap(), |
| 900 | - &db, | |
| 901 | 900 | ) |
| 902 | 901 | .await |
| 903 | 902 | .unwrap(); |
| @@ -952,13 +951,15 @@ mod tests { | ||
| 952 | 951 | .len(); |
| 953 | 952 | // The subject has to be free again: a stranded reference is the |
| 954 | 953 | // half of this bug a row count alone would not catch. |
| 955 | - if Subject::read(subject.get_id(), &db) | |
| 956 | - .await | |
| 957 | - .unwrap() | |
| 958 | - .unwrap() | |
| 959 | - .delete(&db) | |
| 960 | - .await | |
| 961 | - .is_err() | |
| 954 | + if crate::db::subject::delete( | |
| 955 | + &db, | |
| 956 | + crate::db::subject::read(&db, subject.get_id()) | |
| 957 | + .await | |
| 958 | + .unwrap() | |
| 959 | + .unwrap(), | |
| 960 | + ) | |
| 961 | + .await | |
| 962 | + .is_err() | |
| 962 | 963 | { |
| 963 | 964 | stuck += 1; |
| 964 | 965 | } |
src/db/exam_attempt.rsmodified+3 -3
| @@ -177,7 +177,7 @@ pub async fn any_for_exam(db: &Database, exam: &ExamId) -> Result<bool, AppError | ||
| 177 | 177 | /// An orphan here is not merely untidy: an `exam_question` that outlives |
| 178 | 178 | /// its exam keeps the reference it claimed on its subject (the cascade's |
| 179 | 179 | /// per-subject decrement counted the rows it could see), and |
| 180 | -/// [`crate::domain::subject::Subject::delete`] is gated on that count | |
| 180 | +/// [`crate::db::subject::delete`] is gated on that count | |
| 181 | 181 | /// reading zero — a subject nobody can ever delete again. |
| 182 | 182 | /// |
| 183 | 183 | /// The bump is restored *by captured value*, `NONE` included, so the row is |
| @@ -341,11 +341,11 @@ mod tests { | ||
| 341 | 341 | .unwrap(); |
| 342 | 342 | // A real subject row, not a minted id: a question claims a reference on |
| 343 | 343 | // its subject and is refused if that subject does not exist. |
| 344 | - let subject = crate::domain::subject::Subject::create( | |
| 344 | + let subject = crate::db::subject::create( | |
| 345 | + db, | |
| 345 | 346 | &crate::db::course::a_test_course(db).await, |
| 346 | 347 | crate::domain::subject::SubjectName::try_new("topic").unwrap(), |
| 347 | 348 | crate::domain::subject::SubjectDescription::try_new("").unwrap(), |
| 348 | - db, | |
| 349 | 349 | ) |
| 350 | 350 | .await |
| 351 | 351 | .unwrap(); |
src/db/exam_question.rsmodified+4 -4
| @@ -431,11 +431,11 @@ mod tests { | ||
| 431 | 431 | } |
| 432 | 432 | |
| 433 | 433 | async fn a_subject(db: &Database) -> Subject { |
| 434 | - Subject::create( | |
| 434 | + crate::db::subject::create( | |
| 435 | + db, | |
| 435 | 436 | &crate::db::course::a_test_course(db).await, |
| 436 | 437 | SubjectName::try_new("topic").unwrap(), |
| 437 | 438 | SubjectDescription::try_new("").unwrap(), |
| 438 | - db, | |
| 439 | 439 | ) |
| 440 | 440 | .await |
| 441 | 441 | .unwrap() |
| @@ -544,7 +544,7 @@ mod tests { | ||
| 544 | 544 | let exam = an_exam(&db).await; |
| 545 | 545 | let subject = a_subject(&db).await; |
| 546 | 546 | let id = subject.get_id().clone(); |
| 547 | - subject.delete(&db).await.unwrap(); | |
| 547 | + crate::db::subject::delete(&db, subject).await.unwrap(); | |
| 548 | 548 | |
| 549 | 549 | let (text, points, spec) = body(); |
| 550 | 550 | let error = create(&db, exam.get_id(), id, text, points, spec) |
| @@ -584,7 +584,7 @@ mod tests { | ||
| 584 | 584 | let from = a_subject(&db).await.get_id().clone(); |
| 585 | 585 | let dead = a_subject(&db).await; |
| 586 | 586 | let gone = dead.get_id().clone(); |
| 587 | - dead.delete(&db).await.unwrap(); | |
| 587 | + crate::db::subject::delete(&db, dead).await.unwrap(); | |
| 588 | 588 | let question = a_question(&exam, &from, &db).await; |
| 589 | 589 | |
| 590 | 590 | let error = moved(question.clone(), &gone, &db) |
src/db/mod.rsmodified+2 -0
| @@ -25,5 +25,7 @@ pub mod profile; | ||
| 25 | 25 | pub mod registration; |
| 26 | 26 | pub mod session; |
| 27 | 27 | pub mod settings; |
| 28 | +pub mod subject; | |
| 29 | +pub mod term; | |
| 28 | 30 | pub mod user; |
| 29 | 31 | pub mod work_entry; |
src/db/subject.rsadded+350 -0
| @@ -0,0 +1,350 @@ | ||
| 1 | +//! The `subject` table: the count-and-create that pins a topic to a live | |
| 2 | +//! course row, the bulk id listing, the field-scoped PATCH, and the guarded | |
| 3 | +//! delete whose `WHERE` reads the row's own reference counters. The type and | |
| 4 | +//! its validation live in [`crate::domain::subject`]. | |
| 5 | + | |
| 6 | +use surrealdb::types::{RecordId, SurrealValue}; | |
| 7 | + | |
| 8 | +use crate::constant::ENROLLMENT_COUNT_FIELD; | |
| 9 | +use crate::database::{Database, transaction_with_retry}; | |
| 10 | +use crate::db::cap; | |
| 11 | +use crate::db::field_update::FieldUpdate; | |
| 12 | +use crate::db::page::PagedList; | |
| 13 | +use crate::domain::course::CourseId; | |
| 14 | +use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName}; | |
| 15 | +use crate::error::AppError; | |
| 16 | + | |
| 17 | +pub async fn create( | |
| 18 | + db: &Database, | |
| 19 | + course: &CourseId, | |
| 20 | + name: SubjectName, | |
| 21 | + description: SubjectDescription, | |
| 22 | +) -> Result<Subject, AppError> { | |
| 23 | + let subject = Subject { | |
| 24 | + id: SubjectId::generate(), | |
| 25 | + course: course.clone(), | |
| 26 | + name, | |
| 27 | + description, | |
| 28 | + }; | |
| 29 | + // The course row is *written* (bumped and put back), not read, so this | |
| 30 | + // collides with `Course::delete`'s cascade: a topic that outlives its | |
| 31 | + // course 404s through `subject_with_course` forever, while | |
| 32 | + // `must_exist` still accepts its id — so a bank template can be | |
| 33 | + // tagged with a subject nobody can reach. See [`cap::touch_and_create`]. | |
| 34 | + cap::touch_and_create( | |
| 35 | + &course.record(), | |
| 36 | + ENROLLMENT_COUNT_FIELD, | |
| 37 | + &subject.id.record(), | |
| 38 | + &subject, | |
| 39 | + db, | |
| 40 | + ) | |
| 41 | + .await? | |
| 42 | + .ok_or(AppError::NotFound) | |
| 43 | +} | |
| 44 | + | |
| 45 | +pub async fn read(db: &Database, id: &SubjectId) -> Result<Option<Subject>, AppError> { | |
| 46 | + Ok(db.select(id.record()).await?) | |
| 47 | +} | |
| 48 | + | |
| 49 | +/// Several subjects in one query — the bulk half of a list endpoint that | |
| 50 | +/// names each row's subject (a read per row would be an N+1). | |
| 51 | +pub async fn list_by_ids(db: &Database, ids: &[&SubjectId]) -> Result<Vec<Subject>, AppError> { | |
| 52 | + if ids.is_empty() { | |
| 53 | + return Ok(Vec::new()); | |
| 54 | + } | |
| 55 | + let records: Vec<RecordId> = ids.iter().map(|id| id.record()).collect(); | |
| 56 | + let mut result = db | |
| 57 | + .query("SELECT * FROM subject WHERE id IN $ids") | |
| 58 | + .bind(("ids", records)) | |
| 59 | + .await? | |
| 60 | + .check()?; | |
| 61 | + Ok(result.take::<Vec<Subject>>(0)?) | |
| 62 | +} | |
| 63 | + | |
| 64 | +/// The course's subjects in curriculum order (ULID ids sort by creation). | |
| 65 | +pub async fn list_for_course( | |
| 66 | + db: &Database, | |
| 67 | + course: &CourseId, | |
| 68 | + limit: Option<i64>, | |
| 69 | + offset: i64, | |
| 70 | +) -> Result<(Vec<Subject>, i64), AppError> { | |
| 71 | + PagedList::new("subject WHERE course = $course", "ORDER BY id ASC") | |
| 72 | + .bind("course", course.record()) | |
| 73 | + .run(limit, offset, db) | |
| 74 | + .await | |
| 75 | +} | |
| 76 | + | |
| 77 | +/// Request-scoped: no lock spans the handler's read and this write, so an | |
| 78 | +/// omitted field (`None`) is not written at all. Passing the snapshot's | |
| 79 | +/// value back instead would revert a concurrent edit of that field — | |
| 80 | +/// scoping the `SET` alone does not prevent that, the values have to come | |
| 81 | +/// from the request. Neither column is nullable, so plain `Option` per | |
| 82 | +/// field says everything there is to say. | |
| 83 | +pub async fn update( | |
| 84 | + db: &Database, | |
| 85 | + subject: Subject, | |
| 86 | + name: Option<SubjectName>, | |
| 87 | + description: Option<SubjectDescription>, | |
| 88 | +) -> Result<Subject, AppError> { | |
| 89 | + FieldUpdate::new(subject.id.record()) | |
| 90 | + .set("name", name) | |
| 91 | + .set("description", description) | |
| 92 | + .run::<Subject>(db) | |
| 93 | + .await | |
| 94 | +} | |
| 95 | + | |
| 96 | +/// Delete the subject and clear it off every bank template that carried it | |
| 97 | +/// as origin metadata — one transaction, so a template can't be left | |
| 98 | +/// pointing at a subject that no longer exists. | |
| 99 | +/// | |
| 100 | +/// Exam questions and homework are *not* cascaded: their `subject` is a | |
| 101 | +/// required field that may not be orphaned, so either one still refuses the | |
| 102 | +/// delete with a 409. That refusal is the delete's own `WHERE`, read off the | |
| 103 | +/// two reference counters this row carries | |
| 104 | +/// ([`crate::constant::SUBJECT_QUESTION_COUNT_FIELD`] and its homework | |
| 105 | +/// twin), which is what makes it hold against a question created by a | |
| 106 | +/// request racing this one — the cross-table `SELECT … LIMIT 1` it replaces | |
| 107 | +/// was a count-then-delete no transaction serializes, pinned by three | |
| 108 | +/// process-wide locks that could not cover the round trip between them. | |
| 109 | +/// | |
| 110 | +/// Which of the two blocked is read off the counters *before* the delete, | |
| 111 | +/// purely to pick the message; the decision itself was already made by the | |
| 112 | +/// `WHERE`. | |
| 113 | +/// | |
| 114 | +/// The bank's subject is optional metadata, and blocking on it was a dead | |
| 115 | +/// end — only the template's owner may re-tag it, so a manager could never | |
| 116 | +/// clear their own 409, and a private template raising it leaked its | |
| 117 | +/// existence. Its cascade runs *after* the conditional delete, so a refused | |
| 118 | +/// delete leaves every template's subject where it was. | |
| 119 | +pub async fn delete(db: &Database, subject: Subject) -> Result<Subject, AppError> { | |
| 120 | + let (mut result, mut errors) = transaction_with_retry( | |
| 121 | + db, | |
| 122 | + "BEGIN TRANSACTION; | |
| 123 | + LET $held = (SELECT exam_question_count AS q, homework_count AS h FROM $sub); | |
| 124 | + LET $before = (DELETE $sub | |
| 125 | + WHERE (exam_question_count ?? 0) = 0 AND (homework_count ?? 0) = 0 | |
| 126 | + RETURN BEFORE); | |
| 127 | + IF array::len($before) = 0 { | |
| 128 | + THROW IF array::len($held) = 0 { 'subject_missing' } | |
| 129 | + ELSE IF ($held[0].q ?? 0) > 0 { 'subject_questions' } | |
| 130 | + ELSE { 'subject_homework' } | |
| 131 | + }; | |
| 132 | + UPDATE bank_question SET subject = NONE WHERE subject = $sub; | |
| 133 | + RETURN $before; | |
| 134 | + COMMIT TRANSACTION;", | |
| 135 | + &[("sub".into(), subject.id.record().into_value())], | |
| 136 | + &["subject_missing", "subject_questions", "subject_homework"], | |
| 137 | + ) | |
| 138 | + .await?; | |
| 139 | + // An aborted transaction errors every slot; only the THROW's own slot | |
| 140 | + // names the marker (the [`crate::db::appointment_slot`] treatment), | |
| 141 | + // and a lost round is re-sent rather than reported. | |
| 142 | + let thrown = |marker: &str| { | |
| 143 | + errors | |
| 144 | + .values() | |
| 145 | + .any(|error| error.to_string().contains(marker)) | |
| 146 | + }; | |
| 147 | + if thrown("subject_questions") { | |
| 148 | + return Err(AppError::Conflict( | |
| 149 | + "exam questions still reference this subject — re-tag or delete them first", | |
| 150 | + )); | |
| 151 | + } | |
| 152 | + if thrown("subject_homework") { | |
| 153 | + return Err(AppError::Conflict( | |
| 154 | + "homework still references this subject — re-tag or delete it first", | |
| 155 | + )); | |
| 156 | + } | |
| 157 | + if thrown("subject_missing") { | |
| 158 | + return Err(AppError::NotFound); | |
| 159 | + } | |
| 160 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | |
| 161 | + return Err(error.into()); | |
| 162 | + } | |
| 163 | + // Read through the trailing `RETURN`, not a counted slot — see | |
| 164 | + // [`crate::db::exam::delete`]. | |
| 165 | + let slot = result.num_statements().saturating_sub(2); | |
| 166 | + let deleted: Option<Subject> = result.take::<Vec<Subject>>(slot)?.into_iter().next(); | |
| 167 | + deleted.ok_or(AppError::NotFound) | |
| 168 | +} | |
| 169 | + | |
| 170 | +#[cfg(test)] | |
| 171 | +mod tests { | |
| 172 | + use super::*; | |
| 173 | + use crate::constant::SUBJECT_TABLE; | |
| 174 | + | |
| 175 | + /// A curriculum topic must not outlive its course: an orphan 404s through | |
| 176 | + /// `subject_with_course`, and worse than the sibling cases, | |
| 177 | + /// `must_exist` still *accepts* its id — so a bank template can be | |
| 178 | + /// tagged with a subject nobody can reach. | |
| 179 | + /// | |
| 180 | + /// [`create`] therefore *writes* the course row rather than | |
| 181 | + /// reading it ([`cap::touch_and_create`]); the harness and the window it | |
| 182 | + /// races in are documented on | |
| 183 | + /// [`crate::db::course::assert_no_child_outlives_a_course_delete`]. | |
| 184 | + /// Mutation-tested: with the bare `db.create` this shipped with, all four | |
| 185 | + /// rounds orphan. | |
| 186 | + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | |
| 187 | + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | |
| 188 | + async fn a_subject_never_outlives_its_course() { | |
| 189 | + fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> { | |
| 190 | + tokio::spawn(async move { | |
| 191 | + create( | |
| 192 | + &db, | |
| 193 | + &course, | |
| 194 | + SubjectName::try_new("Limits").unwrap(), | |
| 195 | + SubjectDescription::try_new("").unwrap(), | |
| 196 | + ) | |
| 197 | + .await | |
| 198 | + .map(|_| ()) | |
| 199 | + }) | |
| 200 | + } | |
| 201 | + crate::db::course::assert_no_child_outlives_a_course_delete( | |
| 202 | + "subject_orphan_race", | |
| 203 | + SUBJECT_TABLE, | |
| 204 | + make, | |
| 205 | + ) | |
| 206 | + .await; | |
| 207 | + } | |
| 208 | + | |
| 209 | + /// GUARD, not a retry measurement — read the last paragraph before | |
| 210 | + /// trusting this test with the retry. See | |
| 211 | + /// [`crate::db::course::delete`]'s race test for why the rate | |
| 212 | + /// is counted rather than asserted per round, and why this needs the real | |
| 213 | + /// server and a multi-threaded runtime. | |
| 214 | + /// | |
| 215 | + /// The racer is [`crate::db::exam_question::create`], which claims the subject's | |
| 216 | + /// question reference *before* it writes the row — a conditional write on | |
| 217 | + /// the same record the delete's `WHERE` reads. `Err(Conflict)` (still | |
| 218 | + /// referenced), `Err(NotFound)` and the claim's `Validation` miss are all | |
| 219 | + /// correct answers; only `AppError::Db` is the defect. What the two stored | |
| 220 | + /// counters below assert is that the sweep genuinely straddled the site: | |
| 221 | + /// some rounds the claims won, some rounds the delete did. | |
| 222 | + /// | |
| 223 | + /// What it does *not* prove is the retry. The 500 window here is the delete | |
| 224 | + /// passing its `WHERE` and then committing while a claim is in flight, and | |
| 225 | + /// this cascade is three statements long — measured at 0 conflicts in 100 | |
| 226 | + /// raced rounds, and the whole test stays green with | |
| 227 | + /// [`crate::database::transaction_with_retry`]'s loop cut to a single | |
| 228 | + /// attempt. Widening the sweep, staggering the burst and doubling it to 12 | |
| 229 | + /// racers all failed to open the window (they only move which side wins). | |
| 230 | + /// So this is a status-code-and-cascade guard: a raced delete answers 409 or | |
| 231 | + /// 404 and never 500, and a landed question survives it. The retry itself is | |
| 232 | + /// measured on [`crate::db::course::delete`], whose cascade is | |
| 233 | + /// long enough to lose a round (1-2 of 20, red under the same mutation). | |
| 234 | + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | |
| 235 | + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | |
| 236 | + async fn a_delete_racing_a_question_never_answers_500() { | |
| 237 | + use crate::domain::exam_question::{ | |
| 238 | + QuestionKind, QuestionPoints, QuestionSpec, QuestionText, | |
| 239 | + }; | |
| 240 | + let (db, _serialized) = crate::database::init_test_server("subject_delete_race").await; | |
| 241 | + let (mut delete_500, mut question_500) = (0, 0); | |
| 242 | + let (mut landed, mut wiped) = (0, 0); | |
| 243 | + let (mut last_delete, mut last_question) = (String::new(), String::new()); | |
| 244 | + for round in 0..20 { | |
| 245 | + let course = crate::db::course::a_test_course(&db).await; | |
| 246 | + // A real exam row per round: a question write moves its exam's | |
| 247 | + // counter, so a minted id nothing wrote is a 404 and no round would | |
| 248 | + // reach the subject race this test is about. | |
| 249 | + let exam = crate::db::exam::published_exam(&db).await.get_id().clone(); | |
| 250 | + let subject = create( | |
| 251 | + &db, | |
| 252 | + &course, | |
| 253 | + SubjectName::try_new("Limits").unwrap(), | |
| 254 | + SubjectDescription::try_new("").unwrap(), | |
| 255 | + ) | |
| 256 | + .await | |
| 257 | + .unwrap(); | |
| 258 | + | |
| 259 | + let separated = round % 4 == 0; | |
| 260 | + let drop_it = { | |
| 261 | + let (subject, db) = (subject.clone(), db.clone()); | |
| 262 | + // One round in four holds the racers back by a clear 2ms so the | |
| 263 | + // delete wins outright: the sub-millisecond sweep alone leaves | |
| 264 | + // them ahead of it nearly every round (measured 20 to 0), and | |
| 265 | + // both counters below have to see a side. The other three keep | |
| 266 | + // the sub-ms beat, which is the only spacing that overlaps at | |
| 267 | + // all — a whole millisecond either way separates them. | |
| 268 | + let beat = if separated { | |
| 269 | + std::time::Duration::ZERO | |
| 270 | + } else { | |
| 271 | + std::time::Duration::from_micros(round * 53 % 300) | |
| 272 | + }; | |
| 273 | + tokio::spawn(async move { | |
| 274 | + tokio::time::sleep(beat).await; | |
| 275 | + delete(&db, subject).await | |
| 276 | + }) | |
| 277 | + }; | |
| 278 | + let asks: Vec<_> = (0..6) | |
| 279 | + .map(|_| { | |
| 280 | + let (id, db, exam) = (subject.get_id().clone(), db.clone(), exam.clone()); | |
| 281 | + let head_start = if separated { | |
| 282 | + std::time::Duration::from_millis(2) | |
| 283 | + } else { | |
| 284 | + std::time::Duration::from_micros(round * 37 % 300) | |
| 285 | + }; | |
| 286 | + tokio::spawn(async move { | |
| 287 | + tokio::time::sleep(head_start).await; | |
| 288 | + crate::db::exam_question::create( | |
| 289 | + &db, | |
| 290 | + &exam, | |
| 291 | + id, | |
| 292 | + QuestionText::try_new("why").unwrap(), | |
| 293 | + QuestionPoints::try_new(1).unwrap(), | |
| 294 | + QuestionSpec::try_new( | |
| 295 | + QuestionKind::try_new("text").unwrap(), | |
| 296 | + None, | |
| 297 | + None, | |
| 298 | + &[], | |
| 299 | + ) | |
| 300 | + .unwrap(), | |
| 301 | + ) | |
| 302 | + .await | |
| 303 | + }) | |
| 304 | + }) | |
| 305 | + .collect(); | |
| 306 | + let drop_it = drop_it.await.unwrap(); | |
| 307 | + if matches!(drop_it, Err(AppError::Db(_))) { | |
| 308 | + delete_500 += 1; | |
| 309 | + last_delete = format!("{drop_it:?}"); | |
| 310 | + } | |
| 311 | + for ask in asks { | |
| 312 | + let ask = ask.await.unwrap(); | |
| 313 | + if matches!(ask, Err(AppError::Db(_))) { | |
| 314 | + question_500 += 1; | |
| 315 | + last_question = format!("{ask:?}"); | |
| 316 | + } | |
| 317 | + } | |
| 318 | + // Stored state, and both sides are needed: a question landing means | |
| 319 | + // the claim beat the guard, the subject being gone means the delete | |
| 320 | + // did. Seeing only one is a run that never swept across the window. | |
| 321 | + if read(&db, subject.get_id()).await.unwrap().is_none() { | |
| 322 | + wiped += 1; | |
| 323 | + } | |
| 324 | + if !crate::db::exam_question::list_for_exam(&db, &exam, None, 0) | |
| 325 | + .await | |
| 326 | + .unwrap() | |
| 327 | + .0 | |
| 328 | + .is_empty() | |
| 329 | + { | |
| 330 | + landed += 1; | |
| 331 | + } | |
| 332 | + } | |
| 333 | + eprintln!( | |
| 334 | + "Subject::delete raced: {delete_500}/20 delete 500s, {question_500} question 500s, \ | |
| 335 | + {landed} rounds with a question landed / {wiped} wiped" | |
| 336 | + ); | |
| 337 | + assert!( | |
| 338 | + landed > 0 && wiped > 0, | |
| 339 | + "the sweep never crossed the window ({landed} landed / {wiped} wiped)" | |
| 340 | + ); | |
| 341 | + assert_eq!( | |
| 342 | + delete_500, 0, | |
| 343 | + "a raced delete must be refused, not 500: {delete_500}/20 rounds, last {last_delete}" | |
| 344 | + ); | |
| 345 | + assert_eq!( | |
| 346 | + question_500, 0, | |
| 347 | + "a raced question create must retry, not 500: {question_500}/20 rounds, last {last_question}" | |
| 348 | + ); | |
| 349 | + } | |
| 350 | +} |
src/db/term.rsadded+352 -0
| @@ -0,0 +1,352 @@ | ||
| 1 | +//! The `term` table: the row mint, the paged calendar listing, the | |
| 2 | +//! field-scoped PATCH whose `WHERE` re-checks the merged range, the delete | |
| 3 | +//! guarded by the row's own reference counters, and the archive/unarchive | |
| 4 | +//! stamps. The type and the errors its guards hand out live in | |
| 5 | +//! [`crate::domain::term`]. | |
| 6 | + | |
| 7 | +use surrealdb::types::SurrealValue; | |
| 8 | + | |
| 9 | +use crate::constant::{COURSE_COUNT_FIELD, TERM_CLASS_COUNT_FIELD}; | |
| 10 | +use crate::database::{Database, write_with_retry}; | |
| 11 | +use crate::db::field_update::FieldUpdate; | |
| 12 | +use crate::db::page::PagedList; | |
| 13 | +use crate::domain::term::{Term, TermId, TermName}; | |
| 14 | +use crate::domain::timestamp::{Timestamp, range_error}; | |
| 15 | +use crate::error::AppError; | |
| 16 | + | |
| 17 | +pub async fn create( | |
| 18 | + db: &Database, | |
| 19 | + name: TermName, | |
| 20 | + starts_at: Timestamp, | |
| 21 | + ends_at: Timestamp, | |
| 22 | +) -> Result<Term, AppError> { | |
| 23 | + let term = Term { | |
| 24 | + id: TermId::generate(), | |
| 25 | + name, | |
| 26 | + starts_at, | |
| 27 | + ends_at, | |
| 28 | + archived_at: None, | |
| 29 | + }; | |
| 30 | + let created: Option<Term> = db.create(term.id.record()).content(term).await?; | |
| 31 | + created.ok_or_else(|| AppError::Internal("failed to create term".into())) | |
| 32 | +} | |
| 33 | + | |
| 34 | +pub async fn read(db: &Database, id: &TermId) -> Result<Option<Term>, AppError> { | |
| 35 | + Ok(db.select(id.record()).await?) | |
| 36 | +} | |
| 37 | + | |
| 38 | +/// Every term, newest first — the school calendar is small by nature. | |
| 39 | +pub async fn list_all( | |
| 40 | + db: &Database, | |
| 41 | + limit: Option<i64>, | |
| 42 | + offset: i64, | |
| 43 | +) -> Result<(Vec<Term>, i64), AppError> { | |
| 44 | + PagedList::new("term", "ORDER BY starts_at DESC, id DESC") | |
| 45 | + .run(limit, offset, db) | |
| 46 | + .await | |
| 47 | +} | |
| 48 | + | |
| 49 | +/// Write only the fields the PATCH carried — `None` means the request | |
| 50 | +/// omitted it, so the column is left alone rather than re-stated from the | |
| 51 | +/// snapshot this struct was read into. All three columns are non-nullable, | |
| 52 | +/// so "absent" and "null" both correctly mean "keep". | |
| 53 | +pub async fn update( | |
| 54 | + db: &Database, | |
| 55 | + term: Term, | |
| 56 | + name: Option<TermName>, | |
| 57 | + starts_at: Option<Timestamp>, | |
| 58 | + ends_at: Option<Timestamp>, | |
| 59 | +) -> Result<Term, AppError> { | |
| 60 | + FieldUpdate::new(term.id.record()) | |
| 61 | + .set("name", name) | |
| 62 | + .set("starts_at", starts_at) | |
| 63 | + .set("ends_at", ends_at) | |
| 64 | + .ordered("starts_at", "ends_at", range_error()) | |
| 65 | + .run::<Term>(db) | |
| 66 | + .await | |
| 67 | +} | |
| 68 | + | |
| 69 | +/// Delete the term, but only while no course *and no class* links it — | |
| 70 | +/// nothing here unlinks or cascades. `false` = refused, nothing was written. | |
| 71 | +/// | |
| 72 | +/// The roster of linking courses is the term's own `course_count` | |
| 73 | +/// refcount, claimed by [`crate::db::course::create`] and | |
| 74 | +/// `update` *before* they write a link, so the check and the delete are one | |
| 75 | +/// conditional write on one record: a course write racing this either | |
| 76 | +/// claims first (and the delete is refused) or finds the row gone (and is | |
| 77 | +/// refused itself, with the same 400 the lookup gives). `Err(NotFound)` | |
| 78 | +/// keeps the answer a concurrent *delete* used to get. | |
| 79 | +/// | |
| 80 | +/// Classes ([`crate::domain::class_group::ClassGroup`]) link a term the same | |
| 81 | +/// way and count on `class_count` — a column of their own, because | |
| 82 | +/// `course_count` is seeded at boot from the course rows alone. | |
| 83 | +pub async fn delete(db: &Database, term: Term) -> Result<bool, AppError> { | |
| 84 | + let sql = format!( | |
| 85 | + "DELETE $term WHERE ({COURSE_COUNT_FIELD} ?? 0) = 0 \ | |
| 86 | + AND ({TERM_CLASS_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE" | |
| 87 | + ); | |
| 88 | + // Through the retry, because the guard reads the very column a course | |
| 89 | + // create claims: a lost round writes nothing, and re-sending it is what | |
| 90 | + // keeps the answer the 404 or 409 it owes instead of a 500. | |
| 91 | + let gone: Vec<Term> = | |
| 92 | + write_with_retry(db, &sql, &[("term".into(), term.id.record().into_value())]).await?; | |
| 93 | + if !gone.is_empty() { | |
| 94 | + return Ok(true); | |
| 95 | + } | |
| 96 | + // Still linked or already gone: the one statement cannot tell those | |
| 97 | + // apart, and only the refusal path pays for the read that can. | |
| 98 | + match read(db, &term.id).await? { | |
| 99 | + Some(_) => Ok(false), | |
| 100 | + None => Err(AppError::NotFound), | |
| 101 | + } | |
| 102 | +} | |
| 103 | + | |
| 104 | +/// Freeze the term. Idempotent by construction: the `WHERE` only matches an | |
| 105 | +/// open row, so a repeat archive writes nothing and answers with the | |
| 106 | +/// *original* stamp — the year is not re-dated by a double click. | |
| 107 | +pub async fn archive(db: &Database, term: Term) -> Result<Term, AppError> { | |
| 108 | + stamp( | |
| 109 | + db, | |
| 110 | + term, | |
| 111 | + "UPDATE $term SET archived_at = $now WHERE archived_at = NONE RETURN AFTER", | |
| 112 | + Some(Timestamp::now()), | |
| 113 | + ) | |
| 114 | + .await | |
| 115 | +} | |
| 116 | + | |
| 117 | +/// Re-open the term; idempotent the same way. | |
| 118 | +pub async fn unarchive(db: &Database, term: Term) -> Result<Term, AppError> { | |
| 119 | + stamp( | |
| 120 | + db, | |
| 121 | + term, | |
| 122 | + "UPDATE $term SET archived_at = NONE WHERE archived_at != NONE RETURN AFTER", | |
| 123 | + None, | |
| 124 | + ) | |
| 125 | + .await | |
| 126 | +} | |
| 127 | + | |
| 128 | +/// One conditional write, through [`write_with_retry`] like every other | |
| 129 | +/// guarded single statement here; an empty result is the no-op case, and | |
| 130 | +/// only that path pays for the read that reports the stored row. | |
| 131 | +async fn stamp( | |
| 132 | + db: &Database, | |
| 133 | + term: Term, | |
| 134 | + sql: &str, | |
| 135 | + now: Option<Timestamp>, | |
| 136 | +) -> Result<Term, AppError> { | |
| 137 | + let mut bindings = vec![("term".into(), term.id.record().into_value())]; | |
| 138 | + if let Some(now) = now { | |
| 139 | + bindings.push(("now".into(), now.as_millis().into_value())); | |
| 140 | + } | |
| 141 | + let written: Vec<Term> = write_with_retry(db, sql, &bindings).await?; | |
| 142 | + if let Some(written) = written.into_iter().next() { | |
| 143 | + return Ok(written); | |
| 144 | + } | |
| 145 | + read(db, &term.id).await?.ok_or(AppError::NotFound) | |
| 146 | +} | |
| 147 | + | |
| 148 | +#[cfg(test)] | |
| 149 | +mod tests { | |
| 150 | + use super::*; | |
| 151 | + | |
| 152 | + /// The bite test for the `WHERE` guard that replaced `TERM_LOCK` on the | |
| 153 | + /// PATCH path: the handler's pre-flight check is not in play here, so only | |
| 154 | + /// the guard can refuse a moved end that inverts the range — and it must | |
| 155 | + /// refuse it with the same error, having written nothing. | |
| 156 | + #[tokio::test] | |
| 157 | + async fn a_moved_end_is_refused_against_the_stored_other_end() { | |
| 158 | + let db = crate::database::init_mem().await.unwrap(); | |
| 159 | + let at = Timestamp::from_millis; | |
| 160 | + let term = create(&db, TermName::try_new("2026").unwrap(), at(100), at(200)) | |
| 161 | + .await | |
| 162 | + .unwrap(); | |
| 163 | + | |
| 164 | + let refused = update(&db, term.clone(), None, None, Some(at(50))) | |
| 165 | + .await | |
| 166 | + .expect_err("an end before the stored start must be refused"); | |
| 167 | + assert!(refused.to_string().contains("at or after starts_at")); | |
| 168 | + let stored = read(&db, term.get_id()).await.unwrap().unwrap(); | |
| 169 | + assert_eq!( | |
| 170 | + stored.get_ends_at(), | |
| 171 | + at(200), | |
| 172 | + "nothing may have been written" | |
| 173 | + ); | |
| 174 | + | |
| 175 | + // A move that keeps the range ordered still lands, guard and all. | |
| 176 | + let moved = update(&db, term, None, None, Some(at(300))).await.unwrap(); | |
| 177 | + assert_eq!(moved.get_ends_at(), at(300)); | |
| 178 | + } | |
| 179 | + | |
| 180 | + /// Terms are listed newest-first *and* paged by offset, so the sort has to | |
| 181 | + /// be a total order: `starts_at` alone leaves rows that share an instant in | |
| 182 | + /// an arbitrary order, and offset paging over an unstable order can hand | |
| 183 | + /// the same row out twice while skipping another. Pins the `id DESC` | |
| 184 | + /// tie-break on identical `starts_at` — stored read-back, then page by page. | |
| 185 | + #[tokio::test] | |
| 186 | + async fn identical_starts_at_still_pages_each_term_exactly_once() { | |
| 187 | + let db = crate::database::init_mem().await.unwrap(); | |
| 188 | + let at = Timestamp::from_millis; | |
| 189 | + let mut minted = Vec::new(); | |
| 190 | + for i in 0..12 { | |
| 191 | + let term = create( | |
| 192 | + &db, | |
| 193 | + TermName::try_new(&format!("t{i}")).unwrap(), | |
| 194 | + at(100), | |
| 195 | + at(200), | |
| 196 | + ) | |
| 197 | + .await | |
| 198 | + .unwrap(); | |
| 199 | + minted.push(term.get_id().key().to_string()); | |
| 200 | + } | |
| 201 | + // Newest first: the tie-break runs the same way as the primary column. | |
| 202 | + minted.reverse(); | |
| 203 | + | |
| 204 | + let (listed, total) = list_all(&db, None, 0).await.unwrap(); | |
| 205 | + assert_eq!(total, 12); | |
| 206 | + let read_back: Vec<String> = listed | |
| 207 | + .iter() | |
| 208 | + .map(|row| row.get_id().key().to_string()) | |
| 209 | + .collect(); | |
| 210 | + assert_eq!(read_back, minted); | |
| 211 | + | |
| 212 | + // The assertion that catches skip/duplicate: walk it in pages of 5. | |
| 213 | + let mut paged = Vec::new(); | |
| 214 | + for offset in [0, 5, 10] { | |
| 215 | + let (page, total) = list_all(&db, Some(5), offset).await.unwrap(); | |
| 216 | + assert_eq!(total, 12); | |
| 217 | + paged.extend(page.iter().map(|row| row.get_id().key().to_string())); | |
| 218 | + } | |
| 219 | + assert_eq!(paged, minted, "every term exactly once, in list order"); | |
| 220 | + } | |
| 221 | + | |
| 222 | + /// GUARD, not a retry measurement — read the last paragraph before | |
| 223 | + /// trusting this test with the retry. See | |
| 224 | + /// [`crate::db::course::delete`]'s race test for why the rate is | |
| 225 | + /// counted rather than asserted per round. | |
| 226 | + /// | |
| 227 | + /// One conditional `DELETE … RETURN BEFORE` and a bare `.check()?`: no | |
| 228 | + /// transaction to abort, but also no [`crate::database::write_with_retry`], | |
| 229 | + /// which every other guarded single-statement write in the crate goes | |
| 230 | + /// through. A store answering "conflict, retry" therefore comes out as a | |
| 231 | + /// 500 instead of the 404 or 409 the request owes. | |
| 232 | + /// | |
| 233 | + /// The racer is [`crate::db::course::create`] against this | |
| 234 | + /// term: it claims `course_count` on the term row before it writes the | |
| 235 | + /// link, which is the same record and the same column the guard reads. Both | |
| 236 | + /// sides are swept across each other sub-millisecond, exactly as in | |
| 237 | + /// [`crate::db::subject::delete`]'s race test — a whole | |
| 238 | + /// millisecond of head start on either side separates them completely, and | |
| 239 | + /// the counters below assert the sweep straddled the site rather than | |
| 240 | + /// landing on one side of it (it used to alternate on `round % 2` and score | |
| 241 | + /// an exact 10/10, i.e. no overlap at all). | |
| 242 | + /// | |
| 243 | + /// And like that test it does *not* prove the retry: this site is one | |
| 244 | + /// statement, so the window in which a conflict could reach | |
| 245 | + /// [`write_with_retry`] is a single round trip wide — measured at 0 | |
| 246 | + /// conflicts in 100 raced rounds, green with the retry loop cut to a single | |
| 247 | + /// attempt. A status-code guard, then: a raced delete answers 409 or 404 and | |
| 248 | + /// never 500, and a course that got linked survives it. The retry is | |
| 249 | + /// measured on [`crate::db::course::delete`]. | |
| 250 | + #[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_course_create_never_answers_500() { | |
| 253 | + use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; | |
| 254 | + use crate::domain::user::UserId; | |
| 255 | + let (db, _serialized) = crate::database::init_test_server("term_delete_race").await; | |
| 256 | + let (mut delete_500, mut create_500) = (0, 0); | |
| 257 | + let (mut linked, mut wiped) = (0, 0); | |
| 258 | + let (mut last_delete, mut last_create) = (String::new(), String::new()); | |
| 259 | + let at = Timestamp::from_millis; | |
| 260 | + for round in 0..20 { | |
| 261 | + let term = create(&db, TermName::try_new("2026").unwrap(), at(100), at(200)) | |
| 262 | + .await | |
| 263 | + .unwrap(); | |
| 264 | + | |
| 265 | + let separated = round % 4 == 0; | |
| 266 | + let drop_it = { | |
| 267 | + let (term, db) = (term.clone(), db.clone()); | |
| 268 | + // One round in four holds the racers back by a clear 2ms so the | |
| 269 | + // delete wins outright: the sub-millisecond sweep alone leaves | |
| 270 | + // them ahead of it nearly every round (measured 20 to 0), and | |
| 271 | + // both counters below have to see a side. The other three keep | |
| 272 | + // the sub-ms beat, which is the only spacing that overlaps at | |
| 273 | + // all — a whole millisecond either way separates them. | |
| 274 | + let beat = if separated { | |
| 275 | + std::time::Duration::ZERO | |
| 276 | + } else { | |
| 277 | + std::time::Duration::from_micros(round * 53 % 300) | |
| 278 | + }; | |
| 279 | + tokio::spawn(async move { | |
| 280 | + tokio::time::sleep(beat).await; | |
| 281 | + delete(&db, term).await | |
| 282 | + }) | |
| 283 | + }; | |
| 284 | + let makes: Vec<_> = (0..6) | |
| 285 | + .map(|_| { | |
| 286 | + let (id, db) = (term.get_id().clone(), db.clone()); | |
| 287 | + let head_start = if separated { | |
| 288 | + std::time::Duration::from_millis(2) | |
| 289 | + } else { | |
| 290 | + std::time::Duration::from_micros(round * 37 % 300) | |
| 291 | + }; | |
| 292 | + tokio::spawn(async move { | |
| 293 | + tokio::time::sleep(head_start).await; | |
| 294 | + crate::db::course::create( | |
| 295 | + &db, | |
| 296 | + &UserId::from_key("teacher"), | |
| 297 | + CourseTitle::try_new("algebra").unwrap(), | |
| 298 | + CourseDescription::try_new("").unwrap(), | |
| 299 | + CourseKind::course(), | |
| 300 | + Some(id), | |
| 301 | + None, | |
| 302 | + ) | |
| 303 | + .await | |
| 304 | + }) | |
| 305 | + }) | |
| 306 | + .collect(); | |
| 307 | + let drop_it = drop_it.await.unwrap(); | |
| 308 | + if matches!(drop_it, Err(AppError::Db(_))) { | |
| 309 | + delete_500 += 1; | |
| 310 | + last_delete = format!("{drop_it:?}"); | |
| 311 | + } | |
| 312 | + // Stored state, both sides: a linked course means the claim beat the | |
| 313 | + // guard, a gone term means the delete did. | |
| 314 | + let mut landed = false; | |
| 315 | + for make in makes { | |
| 316 | + let make = make.await.unwrap(); | |
| 317 | + if matches!(make, Err(AppError::Db(_))) { | |
| 318 | + create_500 += 1; | |
| 319 | + last_create = format!("{make:?}"); | |
| 320 | + } | |
| 321 | + if let Ok(course) = &make | |
| 322 | + && crate::db::course::read(&db, course.get_id()) | |
| 323 | + .await | |
| 324 | + .unwrap() | |
| 325 | + .is_some() | |
| 326 | + { | |
| 327 | + landed = true; | |
| 328 | + } | |
| 329 | + } | |
| 330 | + linked += usize::from(landed); | |
| 331 | + if read(&db, term.get_id()).await.unwrap().is_none() { | |
| 332 | + wiped += 1; | |
| 333 | + } | |
| 334 | + } | |
| 335 | + eprintln!( | |
| 336 | + "Term::delete raced: {delete_500}/20 delete 500s, {create_500} create 500s, \ | |
| 337 | + {linked} rounds with a course linked / {wiped} wiped" | |
| 338 | + ); | |
| 339 | + assert!( | |
| 340 | + linked > 0 && wiped > 0, | |
| 341 | + "the sweep never crossed the window ({linked} linked / {wiped} wiped)" | |
| 342 | + ); | |
| 343 | + assert_eq!( | |
| 344 | + delete_500, 0, | |
| 345 | + "a raced delete must be refused, not 500: {delete_500}/20 rounds, last {last_delete}" | |
| 346 | + ); | |
| 347 | + assert_eq!( | |
| 348 | + create_500, 0, | |
| 349 | + "a raced course create must retry, not 500: {create_500}/20 rounds, last {last_create}" | |
| 350 | + ); | |
| 351 | + } | |
| 352 | +} |
src/domain/bank_question.rsmodified+3 -3
| @@ -115,7 +115,7 @@ impl BankQuestionId { | ||
| 115 | 115 | /// subject when a template is copied into an exam, not here. |
| 116 | 116 | /// |
| 117 | 117 | /// `subject` is optional because it is *only* metadata: deleting a subject |
| 118 | -/// clears it school-wide (see [`crate::domain::subject::Subject::delete`]) | |
| 118 | +/// clears it school-wide (see [`crate::db::subject::delete`]) | |
| 119 | 119 | /// rather than being blocked by the bank. Blocking would have been a dead end |
| 120 | 120 | /// — the bank is owner-or-admin editable, so a manager could not resolve their |
| 121 | 121 | /// own 409 — and an existence oracle, since another teacher's *private* |
| @@ -837,11 +837,11 @@ mod tests { | ||
| 837 | 837 | let other_exam = crate::db::exam::published_exam(&db).await.get_id().clone(); |
| 838 | 838 | // A real subject row: an exam question claims a reference on its |
| 839 | 839 | // subject, so a minted id it never wrote would be refused. |
| 840 | - let subject = crate::domain::subject::Subject::create( | |
| 840 | + let subject = crate::db::subject::create( | |
| 841 | + &db, | |
| 841 | 842 | &crate::db::course::a_test_course(&db).await, |
| 842 | 843 | crate::domain::subject::SubjectName::try_new("topic").unwrap(), |
| 843 | 844 | crate::domain::subject::SubjectDescription::try_new("").unwrap(), |
| 844 | - &db, | |
| 845 | 845 | ) |
| 846 | 846 | .await |
| 847 | 847 | .unwrap(); |
src/domain/class_group.rsmodified+23 -20
| @@ -19,11 +19,12 @@ use crate::constant::{ | ||
| 19 | 19 | use crate::database::{Database, transaction_with_retry}; |
| 20 | 20 | use crate::db::cap; |
| 21 | 21 | use crate::db::field_update::FieldUpdate; |
| 22 | -use crate::domain::monotonic_id::next_ulid; | |
| 23 | 22 | use crate::db::page::PagedList; |
| 24 | -use crate::domain::term::{self, TermId}; | |
| 23 | +use crate::domain::monotonic_id::next_ulid; | |
| 24 | +use crate::domain::term::{TermId, gone_error, ref_move}; | |
| 25 | 25 | use crate::domain::user::UserId; |
| 26 | 26 | use crate::error::{AppError, ValidationError}; |
| 27 | +use crate::service::term; | |
| 27 | 28 | use crate::validate::{validate_optional, validate_required}; |
| 28 | 29 | |
| 29 | 30 | /// The `THROW` marker the delete guard aborts with — a class that still holds |
| @@ -131,7 +132,7 @@ impl ClassGroup { | ||
| 131 | 132 | pub async fn require_open(&self, db: &Database) -> Result<(), AppError> { |
| 132 | 133 | match self.get_term() { |
| 133 | 134 | None => Ok(()), |
| 134 | - Some(term) => term::Term::require_open(term, db).await, | |
| 135 | + Some(term) => term::require_open(db, term).await, | |
| 135 | 136 | } |
| 136 | 137 | } |
| 137 | 138 | |
| @@ -184,7 +185,7 @@ impl ClassGroup { | ||
| 184 | 185 | cap::Claimed::Made(created) => Ok(created), |
| 185 | 186 | // Uncapped, so "full" can only mean the conditional write matched no |
| 186 | 187 | // term row at all — the claim doubles as the existence check. |
| 187 | - cap::Claimed::Full => Err(term::gone_error()), | |
| 188 | + cap::Claimed::Full => Err(gone_error()), | |
| 188 | 189 | // Unreachable: the id is a ULID this call just generated. |
| 189 | 190 | cap::Claimed::Duplicate => Err(AppError::Internal("failed to create class".into())), |
| 190 | 191 | } |
| @@ -240,7 +241,7 @@ impl ClassGroup { | ||
| 240 | 241 | teacher: Option<Option<UserId>>, |
| 241 | 242 | db: &Database, |
| 242 | 243 | ) -> Result<ClassGroup, AppError> { |
| 243 | - let (claim, release) = term::ref_move(self.term.as_ref(), &term); | |
| 244 | + let (claim, release) = ref_move(self.term.as_ref(), &term); | |
| 244 | 245 | let expected = self.term.as_ref().map(TermId::record); |
| 245 | 246 | FieldUpdate::new(self.id.record()) |
| 246 | 247 | .set("name", name) |
| @@ -258,7 +259,7 @@ impl ClassGroup { | ||
| 258 | 259 | expected, |
| 259 | 260 | claim, |
| 260 | 261 | release, |
| 261 | - term::gone_error(), | |
| 262 | + gone_error(), | |
| 262 | 263 | ) |
| 263 | 264 | .run::<ClassGroup>(db) |
| 264 | 265 | .await |
| @@ -409,7 +410,7 @@ mod tests { | ||
| 409 | 410 | |
| 410 | 411 | async fn a_term(db: &Database) -> Term { |
| 411 | 412 | let at = crate::domain::timestamp::Timestamp::from_millis; |
| 412 | - Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), db) | |
| 413 | + crate::db::term::create(db, TermName::try_new("2026").unwrap(), at(100), at(200)) | |
| 413 | 414 | .await |
| 414 | 415 | .unwrap() |
| 415 | 416 | } |
| @@ -570,7 +571,7 @@ mod tests { | ||
| 570 | 571 | "the courses' counter is seeded from course rows and must stay untouched" |
| 571 | 572 | ); |
| 572 | 573 | assert!( |
| 573 | - !term.clone().delete(&db).await.unwrap(), | |
| 574 | + !crate::db::term::delete(&db, term.clone()).await.unwrap(), | |
| 574 | 575 | "two linked classes must refuse the delete" |
| 575 | 576 | ); |
| 576 | 577 | |
| @@ -579,13 +580,13 @@ mod tests { | ||
| 579 | 580 | .await |
| 580 | 581 | .unwrap(); |
| 581 | 582 | assert!( |
| 582 | - !term.clone().delete(&db).await.unwrap(), | |
| 583 | + !crate::db::term::delete(&db, term.clone()).await.unwrap(), | |
| 583 | 584 | "one link is still one link" |
| 584 | 585 | ); |
| 585 | 586 | |
| 586 | 587 | assert!(linked.delete(&db).await.unwrap()); |
| 587 | 588 | assert!( |
| 588 | - term.clone().delete(&db).await.unwrap(), | |
| 589 | + crate::db::term::delete(&db, term.clone()).await.unwrap(), | |
| 589 | 590 | "the last link gone, the term may go" |
| 590 | 591 | ); |
| 591 | 592 | } |
| @@ -651,7 +652,7 @@ mod tests { | ||
| 651 | 652 | let db = crate::database::init_mem().await.unwrap(); |
| 652 | 653 | let term = a_term(&db).await; |
| 653 | 654 | let id = term.get_id().clone(); |
| 654 | - assert!(term.delete(&db).await.unwrap()); | |
| 655 | + assert!(crate::db::term::delete(&db, term).await.unwrap()); | |
| 655 | 656 | |
| 656 | 657 | let error = ClassGroup::create( |
| 657 | 658 | &UserId::from_key("manager"), |
| @@ -686,14 +687,15 @@ mod tests { | ||
| 686 | 687 | let db = crate::database::init_mem().await.unwrap(); |
| 687 | 688 | let at = crate::domain::timestamp::Timestamp::from_millis; |
| 688 | 689 | let from = a_term(&db).await; |
| 689 | - let to = Term::create(TermName::try_new("2027").unwrap(), at(100), at(200), &db) | |
| 690 | - .await | |
| 691 | - .unwrap(); | |
| 692 | - let dead = Term::create(TermName::try_new("2028").unwrap(), at(100), at(200), &db) | |
| 690 | + let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200)) | |
| 693 | 691 | .await |
| 694 | 692 | .unwrap(); |
| 693 | + let dead = | |
| 694 | + crate::db::term::create(&db, TermName::try_new("2028").unwrap(), at(100), at(200)) | |
| 695 | + .await | |
| 696 | + .unwrap(); | |
| 695 | 697 | let dead_id = dead.get_id().clone(); |
| 696 | - assert!(dead.delete(&db).await.unwrap()); | |
| 698 | + assert!(crate::db::term::delete(&db, dead).await.unwrap()); | |
| 697 | 699 | let class = class_on(Some(from.get_id().clone()), &db).await; |
| 698 | 700 | |
| 699 | 701 | let error = class |
| @@ -747,12 +749,13 @@ mod tests { | ||
| 747 | 749 | let db = crate::database::init_mem().await.unwrap(); |
| 748 | 750 | let at = crate::domain::timestamp::Timestamp::from_millis; |
| 749 | 751 | let from = a_term(&db).await; |
| 750 | - let to = Term::create(TermName::try_new("2027").unwrap(), at(100), at(200), &db) | |
| 751 | - .await | |
| 752 | - .unwrap(); | |
| 753 | - let other = Term::create(TermName::try_new("2028").unwrap(), at(100), at(200), &db) | |
| 752 | + let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200)) | |
| 754 | 753 | .await |
| 755 | 754 | .unwrap(); |
| 755 | + let other = | |
| 756 | + crate::db::term::create(&db, TermName::try_new("2028").unwrap(), at(100), at(200)) | |
| 757 | + .await | |
| 758 | + .unwrap(); | |
| 756 | 759 | let class = class_on(Some(from.get_id().clone()), &db).await; |
| 757 | 760 | let stale = class.clone(); |
| 758 | 761 | class |
src/domain/homework.rsmodified+9 -6
| @@ -421,11 +421,11 @@ mod tests { | ||
| 421 | 421 | use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; |
| 422 | 422 | |
| 423 | 423 | async fn a_subject(name: &str, db: &Database) -> Subject { |
| 424 | - Subject::create( | |
| 424 | + crate::db::subject::create( | |
| 425 | + db, | |
| 425 | 426 | &crate::db::course::a_test_course(db).await, |
| 426 | 427 | SubjectName::try_new(name).unwrap(), |
| 427 | 428 | SubjectDescription::try_new("").unwrap(), |
| 428 | - db, | |
| 429 | 429 | ) |
| 430 | 430 | .await |
| 431 | 431 | .unwrap() |
| @@ -480,7 +480,7 @@ mod tests { | ||
| 480 | 480 | let db = crate::database::init_mem().await.unwrap(); |
| 481 | 481 | let subject = a_subject("algebra", &db).await; |
| 482 | 482 | let id = subject.get_id().clone(); |
| 483 | - subject.delete(&db).await.unwrap(); | |
| 483 | + crate::db::subject::delete(&db, subject).await.unwrap(); | |
| 484 | 484 | |
| 485 | 485 | let error = Homework::create( |
| 486 | 486 | &CourseId::from_key("course"), |
| @@ -528,9 +528,12 @@ mod tests { | ||
| 528 | 528 | "the old subject is free" |
| 529 | 529 | ); |
| 530 | 530 | assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); |
| 531 | - assert!(from.delete(&db).await.is_ok(), "no reference left"); | |
| 532 | 531 | assert!( |
| 533 | - to.delete(&db).await.is_err(), | |
| 532 | + crate::db::subject::delete(&db, from).await.is_ok(), | |
| 533 | + "no reference left" | |
| 534 | + ); | |
| 535 | + assert!( | |
| 536 | + crate::db::subject::delete(&db, to).await.is_err(), | |
| 534 | 537 | "the reference moved here refuses the delete" |
| 535 | 538 | ); |
| 536 | 539 | } |
| @@ -544,7 +547,7 @@ mod tests { | ||
| 544 | 547 | let from = a_subject("algebra", &db).await; |
| 545 | 548 | let dead = a_subject("geometry", &db).await; |
| 546 | 549 | let gone = dead.get_id().clone(); |
| 547 | - dead.delete(&db).await.unwrap(); | |
| 550 | + crate::db::subject::delete(&db, dead).await.unwrap(); | |
| 548 | 551 | let homework = homework_on(from.get_id(), &db).await; |
| 549 | 552 | |
| 550 | 553 | let error = homework |
src/domain/homework_file.rsmodified+3 -3
| @@ -328,14 +328,14 @@ mod tests { | ||
| 328 | 328 | /// deadline off the entity now, so a bare id no longer does. |
| 329 | 329 | async fn a_homework(db: &Database) -> crate::domain::homework::Homework { |
| 330 | 330 | use crate::domain::homework::{Homework, HomeworkTitle}; |
| 331 | - use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; | |
| 331 | + use crate::domain::subject::{SubjectDescription, SubjectName}; | |
| 332 | 332 | |
| 333 | 333 | let course = crate::db::course::a_test_course(db).await; |
| 334 | - let subject = Subject::create( | |
| 334 | + let subject = crate::db::subject::create( | |
| 335 | + db, | |
| 335 | 336 | &course, |
| 336 | 337 | SubjectName::try_new("topic").unwrap(), |
| 337 | 338 | SubjectDescription::try_new("").unwrap(), |
| 338 | - db, | |
| 339 | 339 | ) |
| 340 | 340 | .await |
| 341 | 341 | .unwrap(); |
src/domain/homework_result.rsmodified+3 -3
| @@ -373,14 +373,14 @@ mod tests { | ||
| 373 | 373 | /// same way it already is for a submission. |
| 374 | 374 | async fn a_homework(db: &Database) -> HomeworkId { |
| 375 | 375 | use crate::domain::homework::{Homework, HomeworkTitle}; |
| 376 | - use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; | |
| 376 | + use crate::domain::subject::{SubjectDescription, SubjectName}; | |
| 377 | 377 | |
| 378 | 378 | let course = crate::db::course::a_test_course(db).await; |
| 379 | - let subject = Subject::create( | |
| 379 | + let subject = crate::db::subject::create( | |
| 380 | + db, | |
| 380 | 381 | &course, |
| 381 | 382 | SubjectName::try_new("topic").unwrap(), |
| 382 | 383 | SubjectDescription::try_new("").unwrap(), |
| 383 | - db, | |
| 384 | 384 | ) |
| 385 | 385 | .await |
| 386 | 386 | .unwrap(); |
src/domain/homework_submission.rsmodified+3 -3
| @@ -371,17 +371,17 @@ mod tests { | ||
| 371 | 371 | use super::*; |
| 372 | 372 | |
| 373 | 373 | use crate::domain::homework::HomeworkTitle; |
| 374 | - use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; | |
| 374 | + use crate::domain::subject::{SubjectDescription, SubjectName}; | |
| 375 | 375 | |
| 376 | 376 | /// A real homework row (and the subject it must reference) due at `due_at` — |
| 377 | 377 | /// `upsert` now reads the deadline off the entity, so the tests need one. |
| 378 | 378 | async fn a_homework(due_at: Timestamp, db: &Database) -> Homework { |
| 379 | 379 | let course = crate::db::course::a_test_course(db).await; |
| 380 | - let subject = Subject::create( | |
| 380 | + let subject = crate::db::subject::create( | |
| 381 | + db, | |
| 381 | 382 | &course, |
| 382 | 383 | SubjectName::try_new("topic").unwrap(), |
| 383 | 384 | SubjectDescription::try_new("").unwrap(), |
| 384 | - db, | |
| 385 | 385 | ) |
| 386 | 386 | .await |
| 387 | 387 | .unwrap(); |
src/domain/subject.rsmodified+9 -348
| @@ -1,15 +1,9 @@ | ||
| 1 | 1 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 2 | 2 | |
| 3 | -use crate::constant::{ | |
| 4 | - ENROLLMENT_COUNT_FIELD, MAX_SUBJECT_DESCRIPTION_LEN, MAX_SUBJECT_NAME_LEN, SUBJECT_TABLE, | |
| 5 | -}; | |
| 6 | -use crate::database::{Database, transaction_with_retry}; | |
| 7 | -use crate::db::cap; | |
| 8 | -use crate::db::field_update::FieldUpdate; | |
| 9 | -use crate::db::page::PagedList; | |
| 3 | +use crate::constant::{MAX_SUBJECT_DESCRIPTION_LEN, MAX_SUBJECT_NAME_LEN, SUBJECT_TABLE}; | |
| 10 | 4 | use crate::domain::course::CourseId; |
| 11 | 5 | use crate::domain::monotonic_id::next_ulid; |
| 12 | -use crate::error::{AppError, ValidationError}; | |
| 6 | +use crate::error::ValidationError; | |
| 13 | 7 | use crate::validate::{validate_optional, validate_required}; |
| 14 | 8 | |
| 15 | 9 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| @@ -17,9 +11,9 @@ pub struct SubjectId(RecordId); | ||
| 17 | 11 | |
| 18 | 12 | impl SubjectId { |
| 19 | 13 | /// Minted from the process-wide monotonic generator, not `Ulid::new()`: the |
| 20 | - /// id *is* the curriculum's order ([`Subject::list_for_course`] sorts | |
| 21 | - /// `id ASC`), and a random low half scrambles a burst of saves that lands | |
| 22 | - /// inside one millisecond. | |
| 14 | + /// id *is* the curriculum's order ([`crate::db::subject::list_for_course`] | |
| 15 | + /// sorts `id ASC`), and a random low half scrambles a burst of saves that | |
| 16 | + /// lands inside one millisecond. | |
| 23 | 17 | pub fn generate() -> Self { |
| 24 | 18 | Self(RecordId::new(SUBJECT_TABLE, next_ulid().to_string())) |
| 25 | 19 | } |
| @@ -74,10 +68,10 @@ impl SubjectDescription { | ||
| 74 | 68 | /// it would strand the questions tagged with it. |
| 75 | 69 | #[derive(Debug, Clone, SurrealValue)] |
| 76 | 70 | pub struct Subject { |
| 77 | - id: SubjectId, | |
| 78 | - course: CourseId, | |
| 79 | - name: SubjectName, | |
| 80 | - description: SubjectDescription, | |
| 71 | + pub(crate) id: SubjectId, | |
| 72 | + pub(crate) course: CourseId, | |
| 73 | + pub(crate) name: SubjectName, | |
| 74 | + pub(crate) description: SubjectDescription, | |
| 81 | 75 | } |
| 82 | 76 | |
| 83 | 77 | impl Subject { |
| @@ -96,199 +90,12 @@ impl Subject { | ||
| 96 | 90 | pub fn get_description(&self) -> &SubjectDescription { |
| 97 | 91 | &self.description |
| 98 | 92 | } |
| 99 | - | |
| 100 | - pub async fn create( | |
| 101 | - course: &CourseId, | |
| 102 | - name: SubjectName, | |
| 103 | - description: SubjectDescription, | |
| 104 | - db: &Database, | |
| 105 | - ) -> Result<Subject, AppError> { | |
| 106 | - let subject = Subject { | |
| 107 | - id: SubjectId::generate(), | |
| 108 | - course: course.clone(), | |
| 109 | - name, | |
| 110 | - description, | |
| 111 | - }; | |
| 112 | - // The course row is *written* (bumped and put back), not read, so this | |
| 113 | - // collides with `Course::delete`'s cascade: a topic that outlives its | |
| 114 | - // course 404s through `subject_with_course` forever, while | |
| 115 | - // `subject_must_exist` still accepts its id — so a bank template can be | |
| 116 | - // tagged with a subject nobody can reach. See [`cap::touch_and_create`]. | |
| 117 | - cap::touch_and_create( | |
| 118 | - &course.record(), | |
| 119 | - ENROLLMENT_COUNT_FIELD, | |
| 120 | - &subject.id.record(), | |
| 121 | - &subject, | |
| 122 | - db, | |
| 123 | - ) | |
| 124 | - .await? | |
| 125 | - .ok_or(AppError::NotFound) | |
| 126 | - } | |
| 127 | - | |
| 128 | - pub async fn read(id: &SubjectId, db: &Database) -> Result<Option<Subject>, AppError> { | |
| 129 | - Ok(db.select(id.record()).await?) | |
| 130 | - } | |
| 131 | - | |
| 132 | - /// Several subjects in one query — the bulk half of a list endpoint that | |
| 133 | - /// names each row's subject (a read per row would be an N+1). | |
| 134 | - pub async fn list_by_ids(ids: &[&SubjectId], db: &Database) -> Result<Vec<Subject>, AppError> { | |
| 135 | - if ids.is_empty() { | |
| 136 | - return Ok(Vec::new()); | |
| 137 | - } | |
| 138 | - let records: Vec<RecordId> = ids.iter().map(|id| id.record()).collect(); | |
| 139 | - let mut result = db | |
| 140 | - .query("SELECT * FROM subject WHERE id IN $ids") | |
| 141 | - .bind(("ids", records)) | |
| 142 | - .await? | |
| 143 | - .check()?; | |
| 144 | - Ok(result.take::<Vec<Subject>>(0)?) | |
| 145 | - } | |
| 146 | - | |
| 147 | - /// The course's subjects in curriculum order (ULID ids sort by creation). | |
| 148 | - pub async fn list_for_course( | |
| 149 | - course: &CourseId, | |
| 150 | - limit: Option<i64>, | |
| 151 | - offset: i64, | |
| 152 | - db: &Database, | |
| 153 | - ) -> Result<(Vec<Subject>, i64), AppError> { | |
| 154 | - PagedList::new("subject WHERE course = $course", "ORDER BY id ASC") | |
| 155 | - .bind("course", course.record()) | |
| 156 | - .run(limit, offset, db) | |
| 157 | - .await | |
| 158 | - } | |
| 159 | - | |
| 160 | - /// Request-scoped: no lock spans the handler's read and this write, so an | |
| 161 | - /// omitted field (`None`) is not written at all. Passing the snapshot's | |
| 162 | - /// value back instead would revert a concurrent edit of that field — | |
| 163 | - /// scoping the `SET` alone does not prevent that, the values have to come | |
| 164 | - /// from the request. Neither column is nullable, so plain `Option` per | |
| 165 | - /// field says everything there is to say. | |
| 166 | - pub async fn update( | |
| 167 | - self, | |
| 168 | - name: Option<SubjectName>, | |
| 169 | - description: Option<SubjectDescription>, | |
| 170 | - db: &Database, | |
| 171 | - ) -> Result<Subject, AppError> { | |
| 172 | - FieldUpdate::new(self.id.record()) | |
| 173 | - .set("name", name) | |
| 174 | - .set("description", description) | |
| 175 | - .run::<Subject>(db) | |
| 176 | - .await | |
| 177 | - } | |
| 178 | - | |
| 179 | - /// Delete the subject and clear it off every bank template that carried it | |
| 180 | - /// as origin metadata — one transaction, so a template can't be left | |
| 181 | - /// pointing at a subject that no longer exists. | |
| 182 | - /// | |
| 183 | - /// Exam questions and homework are *not* cascaded: their `subject` is a | |
| 184 | - /// required field that may not be orphaned, so either one still refuses the | |
| 185 | - /// delete with a 409. That refusal is the delete's own `WHERE`, read off the | |
| 186 | - /// two reference counters this row carries | |
| 187 | - /// ([`crate::constant::SUBJECT_QUESTION_COUNT_FIELD`] and its homework | |
| 188 | - /// twin), which is what makes it hold against a question created by a | |
| 189 | - /// request racing this one — the cross-table `SELECT … LIMIT 1` it replaces | |
| 190 | - /// was a count-then-delete no transaction serializes, pinned by three | |
| 191 | - /// process-wide locks that could not cover the round trip between them. | |
| 192 | - /// | |
| 193 | - /// Which of the two blocked is read off the counters *before* the delete, | |
| 194 | - /// purely to pick the message; the decision itself was already made by the | |
| 195 | - /// `WHERE`. | |
| 196 | - /// | |
| 197 | - /// The bank's subject is optional metadata, and blocking on it was a dead | |
| 198 | - /// end — only the template's owner may re-tag it, so a manager could never | |
| 199 | - /// clear their own 409, and a private template raising it leaked its | |
| 200 | - /// existence. Its cascade runs *after* the conditional delete, so a refused | |
| 201 | - /// delete leaves every template's subject where it was. | |
| 202 | - pub async fn delete(self, db: &Database) -> Result<Subject, AppError> { | |
| 203 | - let (mut result, mut errors) = transaction_with_retry( | |
| 204 | - db, | |
| 205 | - "BEGIN TRANSACTION; | |
| 206 | - LET $held = (SELECT exam_question_count AS q, homework_count AS h FROM $sub); | |
| 207 | - LET $before = (DELETE $sub | |
| 208 | - WHERE (exam_question_count ?? 0) = 0 AND (homework_count ?? 0) = 0 | |
| 209 | - RETURN BEFORE); | |
| 210 | - IF array::len($before) = 0 { | |
| 211 | - THROW IF array::len($held) = 0 { 'subject_missing' } | |
| 212 | - ELSE IF ($held[0].q ?? 0) > 0 { 'subject_questions' } | |
| 213 | - ELSE { 'subject_homework' } | |
| 214 | - }; | |
| 215 | - UPDATE bank_question SET subject = NONE WHERE subject = $sub; | |
| 216 | - RETURN $before; | |
| 217 | - COMMIT TRANSACTION;", | |
| 218 | - &[("sub".into(), self.id.record().into_value())], | |
| 219 | - &["subject_missing", "subject_questions", "subject_homework"], | |
| 220 | - ) | |
| 221 | - .await?; | |
| 222 | - // An aborted transaction errors every slot; only the THROW's own slot | |
| 223 | - // names the marker (the [`crate::domain::appointment_slot`] treatment), | |
| 224 | - // and a lost round is re-sent rather than reported. | |
| 225 | - let thrown = |marker: &str| { | |
| 226 | - errors | |
| 227 | - .values() | |
| 228 | - .any(|error| error.to_string().contains(marker)) | |
| 229 | - }; | |
| 230 | - if thrown("subject_questions") { | |
| 231 | - return Err(AppError::Conflict( | |
| 232 | - "exam questions still reference this subject — re-tag or delete them first", | |
| 233 | - )); | |
| 234 | - } | |
| 235 | - if thrown("subject_homework") { | |
| 236 | - return Err(AppError::Conflict( | |
| 237 | - "homework still references this subject — re-tag or delete it first", | |
| 238 | - )); | |
| 239 | - } | |
| 240 | - if thrown("subject_missing") { | |
| 241 | - return Err(AppError::NotFound); | |
| 242 | - } | |
| 243 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | |
| 244 | - return Err(error.into()); | |
| 245 | - } | |
| 246 | - // Read through the trailing `RETURN`, not a counted slot — see | |
| 247 | - // [`crate::db::exam::delete`]. | |
| 248 | - let slot = result.num_statements().saturating_sub(2); | |
| 249 | - let deleted: Option<Subject> = result.take::<Vec<Subject>>(slot)?.into_iter().next(); | |
| 250 | - deleted.ok_or(AppError::NotFound) | |
| 251 | - } | |
| 252 | 93 | } |
| 253 | 94 | |
| 254 | 95 | #[cfg(test)] |
| 255 | 96 | mod tests { |
| 256 | 97 | use super::*; |
| 257 | 98 | |
| 258 | - /// A curriculum topic must not outlive its course: an orphan 404s through | |
| 259 | - /// `subject_with_course`, and worse than the sibling cases, | |
| 260 | - /// `subject_must_exist` still *accepts* its id — so a bank template can be | |
| 261 | - /// tagged with a subject nobody can reach. | |
| 262 | - /// | |
| 263 | - /// [`Subject::create`] therefore *writes* the course row rather than | |
| 264 | - /// reading it ([`cap::touch_and_create`]); the harness and the window it | |
| 265 | - /// races in are documented on | |
| 266 | - /// [`crate::db::course::assert_no_child_outlives_a_course_delete`]. | |
| 267 | - /// Mutation-tested: with the bare `db.create` this shipped with, all four | |
| 268 | - /// rounds orphan. | |
| 269 | - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | |
| 270 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | |
| 271 | - async fn a_subject_never_outlives_its_course() { | |
| 272 | - fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> { | |
| 273 | - tokio::spawn(async move { | |
| 274 | - Subject::create( | |
| 275 | - &course, | |
| 276 | - SubjectName::try_new("Limits").unwrap(), | |
| 277 | - SubjectDescription::try_new("").unwrap(), | |
| 278 | - &db, | |
| 279 | - ) | |
| 280 | - .await | |
| 281 | - .map(|_| ()) | |
| 282 | - }) | |
| 283 | - } | |
| 284 | - crate::db::course::assert_no_child_outlives_a_course_delete( | |
| 285 | - "subject_orphan_race", | |
| 286 | - SUBJECT_TABLE, | |
| 287 | - make, | |
| 288 | - ) | |
| 289 | - .await; | |
| 290 | - } | |
| 291 | - | |
| 292 | 99 | /// A teacher entering a curriculum gets it back in the order they typed it: |
| 293 | 100 | /// `list_for_course` sorts `id ASC`, so the ids minted inside one |
| 294 | 101 | /// millisecond have to sort in mint order. Revert `generate` to |
| @@ -317,150 +124,4 @@ mod tests { | ||
| 317 | 124 | assert!(SubjectDescription::try_new("").is_ok()); |
| 318 | 125 | assert!(SubjectDescription::try_new(&"x".repeat(2_001)).is_err()); |
| 319 | 126 | } |
| 320 | - | |
| 321 | - /// GUARD, not a retry measurement — read the last paragraph before | |
| 322 | - /// trusting this test with the retry. See | |
| 323 | - /// [`crate::db::course::delete`]'s race test for why the rate | |
| 324 | - /// is counted rather than asserted per round, and why this needs the real | |
| 325 | - /// server and a multi-threaded runtime. | |
| 326 | - /// | |
| 327 | - /// The racer is [`crate::db::exam_question::create`], which claims the subject's | |
| 328 | - /// question reference *before* it writes the row — a conditional write on | |
| 329 | - /// the same record the delete's `WHERE` reads. `Err(Conflict)` (still | |
| 330 | - /// referenced), `Err(NotFound)` and the claim's `Validation` miss are all | |
| 331 | - /// correct answers; only `AppError::Db` is the defect. What the two stored | |
| 332 | - /// counters below assert is that the sweep genuinely straddled the site: | |
| 333 | - /// some rounds the claims won, some rounds the delete did. | |
| 334 | - /// | |
| 335 | - /// What it does *not* prove is the retry. The 500 window here is the delete | |
| 336 | - /// passing its `WHERE` and then committing while a claim is in flight, and | |
| 337 | - /// this cascade is three statements long — measured at 0 conflicts in 100 | |
| 338 | - /// raced rounds, and the whole test stays green with | |
| 339 | - /// [`crate::database::transaction_with_retry`]'s loop cut to a single | |
| 340 | - /// attempt. Widening the sweep, staggering the burst and doubling it to 12 | |
| 341 | - /// racers all failed to open the window (they only move which side wins). | |
| 342 | - /// So this is a status-code-and-cascade guard: a raced delete answers 409 or | |
| 343 | - /// 404 and never 500, and a landed question survives it. The retry itself is | |
| 344 | - /// measured on [`crate::db::course::delete`], whose cascade is | |
| 345 | - /// long enough to lose a round (1-2 of 20, red under the same mutation). | |
| 346 | - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | |
| 347 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | |
| 348 | - async fn a_delete_racing_a_question_never_answers_500() { | |
| 349 | - use crate::domain::exam_question::{ | |
| 350 | - QuestionKind, QuestionPoints, QuestionSpec, QuestionText, | |
| 351 | - }; | |
| 352 | - let (db, _serialized) = crate::database::init_test_server("subject_delete_race").await; | |
| 353 | - let (mut delete_500, mut question_500) = (0, 0); | |
| 354 | - let (mut landed, mut wiped) = (0, 0); | |
| 355 | - let (mut last_delete, mut last_question) = (String::new(), String::new()); | |
| 356 | - for round in 0..20 { | |
| 357 | - let course = crate::db::course::a_test_course(&db).await; | |
| 358 | - // A real exam row per round: a question write moves its exam's | |
| 359 | - // counter, so a minted id nothing wrote is a 404 and no round would | |
| 360 | - // reach the subject race this test is about. | |
| 361 | - let exam = crate::db::exam::published_exam(&db).await.get_id().clone(); | |
| 362 | - let subject = Subject::create( | |
| 363 | - &course, | |
| 364 | - SubjectName::try_new("Limits").unwrap(), | |
| 365 | - SubjectDescription::try_new("").unwrap(), | |
| 366 | - &db, | |
| 367 | - ) | |
| 368 | - .await | |
| 369 | - .unwrap(); | |
| 370 | - | |
| 371 | - let separated = round % 4 == 0; | |
| 372 | - let drop_it = { | |
| 373 | - let (subject, db) = (subject.clone(), db.clone()); | |
| 374 | - // One round in four holds the racers back by a clear 2ms so the | |
| 375 | - // delete wins outright: the sub-millisecond sweep alone leaves | |
| 376 | - // them ahead of it nearly every round (measured 20 to 0), and | |
| 377 | - // both counters below have to see a side. The other three keep | |
| 378 | - // the sub-ms beat, which is the only spacing that overlaps at | |
| 379 | - // all — a whole millisecond either way separates them. | |
| 380 | - let beat = if separated { | |
| 381 | - std::time::Duration::ZERO | |
| 382 | - } else { | |
| 383 | - std::time::Duration::from_micros(round * 53 % 300) | |
| 384 | - }; | |
| 385 | - tokio::spawn(async move { | |
| 386 | - tokio::time::sleep(beat).await; | |
| 387 | - subject.delete(&db).await | |
| 388 | - }) | |
| 389 | - }; | |
| 390 | - let asks: Vec<_> = (0..6) | |
| 391 | - .map(|_| { | |
| 392 | - let (id, db, exam) = (subject.get_id().clone(), db.clone(), exam.clone()); | |
| 393 | - let head_start = if separated { | |
| 394 | - std::time::Duration::from_millis(2) | |
| 395 | - } else { | |
| 396 | - std::time::Duration::from_micros(round * 37 % 300) | |
| 397 | - }; | |
| 398 | - tokio::spawn(async move { | |
| 399 | - tokio::time::sleep(head_start).await; | |
| 400 | - crate::db::exam_question::create( | |
| 401 | - &db, | |
| 402 | - &exam, | |
| 403 | - id, | |
| 404 | - QuestionText::try_new("why").unwrap(), | |
| 405 | - QuestionPoints::try_new(1).unwrap(), | |
| 406 | - QuestionSpec::try_new( | |
| 407 | - QuestionKind::try_new("text").unwrap(), | |
| 408 | - None, | |
| 409 | - None, | |
| 410 | - &[], | |
| 411 | - ) | |
| 412 | - .unwrap(), | |
| 413 | - ) | |
| 414 | - .await | |
| 415 | - }) | |
| 416 | - }) | |
| 417 | - .collect(); | |
| 418 | - let drop_it = drop_it.await.unwrap(); | |
| 419 | - if matches!(drop_it, Err(AppError::Db(_))) { | |
| 420 | - delete_500 += 1; | |
| 421 | - last_delete = format!("{drop_it:?}"); | |
| 422 | - } | |
| 423 | - for ask in asks { | |
| 424 | - let ask = ask.await.unwrap(); | |
| 425 | - if matches!(ask, Err(AppError::Db(_))) { | |
| 426 | - question_500 += 1; | |
| 427 | - last_question = format!("{ask:?}"); | |
| 428 | - } | |
| 429 | - } | |
| 430 | - // Stored state, and both sides are needed: a question landing means | |
| 431 | - // the claim beat the guard, the subject being gone means the delete | |
| 432 | - // did. Seeing only one is a run that never swept across the window. | |
| 433 | - if Subject::read(subject.get_id(), &db) | |
| 434 | - .await | |
| 435 | - .unwrap() | |
| 436 | - .is_none() | |
| 437 | - { | |
| 438 | - wiped += 1; | |
| 439 | - } | |
| 440 | - if !crate::db::exam_question::list_for_exam(&db, &exam, None, 0) | |
| 441 | - .await | |
| 442 | - .unwrap() | |
| 443 | - .0 | |
| 444 | - .is_empty() | |
| 445 | - { | |
| 446 | - landed += 1; | |
| 447 | - } | |
| 448 | - } | |
| 449 | - eprintln!( | |
| 450 | - "Subject::delete raced: {delete_500}/20 delete 500s, {question_500} question 500s, \ | |
| 451 | - {landed} rounds with a question landed / {wiped} wiped" | |
| 452 | - ); | |
| 453 | - assert!( | |
| 454 | - landed > 0 && wiped > 0, | |
| 455 | - "the sweep never crossed the window ({landed} landed / {wiped} wiped)" | |
| 456 | - ); | |
| 457 | - assert_eq!( | |
| 458 | - delete_500, 0, | |
| 459 | - "a raced delete must be refused, not 500: {delete_500}/20 rounds, last {last_delete}" | |
| 460 | - ); | |
| 461 | - assert_eq!( | |
| 462 | - question_500, 0, | |
| 463 | - "a raced question create must retry, not 500: {question_500}/20 rounds, last {last_question}" | |
| 464 | - ); | |
| 465 | - } | |
| 466 | 127 | } |
src/domain/term.rsmodified+9 -354
| @@ -8,12 +8,9 @@ | ||
| 8 | 8 | |
| 9 | 9 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 10 | 10 | |
| 11 | -use crate::constant::{COURSE_COUNT_FIELD, MAX_TERM_NAME_LEN, TERM_CLASS_COUNT_FIELD, TERM_TABLE}; | |
| 12 | -use crate::database::{Database, write_with_retry}; | |
| 13 | -use crate::db::field_update::FieldUpdate; | |
| 11 | +use crate::constant::{MAX_TERM_NAME_LEN, TERM_TABLE}; | |
| 14 | 12 | use crate::domain::monotonic_id::next_ulid; |
| 15 | -use crate::db::page::PagedList; | |
| 16 | -use crate::domain::timestamp::{Timestamp, range_error}; | |
| 13 | +use crate::domain::timestamp::Timestamp; | |
| 17 | 14 | use crate::error::{AppError, ValidationError}; |
| 18 | 15 | use crate::validate::validate_required; |
| 19 | 16 | |
| @@ -47,8 +44,8 @@ impl TermId { | ||
| 47 | 44 | |
| 48 | 45 | /// The answer every link to a term that is not there gets — the claim is a |
| 49 | 46 | /// conditional write on the term row, so a term a delete already removed |
| 50 | -/// matches nothing and the caller says exactly what `web::terms::resolve_term`'s | |
| 51 | -/// pre-flight lookup would have. | |
| 47 | +/// matches nothing and the caller says exactly what the link resolver's | |
| 48 | +/// pre-flight lookup ([`crate::service::term::resolve`]) would have. | |
| 52 | 49 | pub fn gone_error() -> AppError { |
| 53 | 50 | AppError::Validation(ValidationError::Invalid { |
| 54 | 51 | field: "term_id", |
| @@ -101,15 +98,15 @@ impl TermName { | ||
| 101 | 98 | /// term is a date range by definition. |
| 102 | 99 | #[derive(Debug, Clone, SurrealValue)] |
| 103 | 100 | pub struct Term { |
| 104 | - id: TermId, | |
| 105 | - name: TermName, | |
| 106 | - starts_at: Timestamp, | |
| 107 | - ends_at: Timestamp, | |
| 101 | + pub(crate) id: TermId, | |
| 102 | + pub(crate) name: TermName, | |
| 103 | + pub(crate) starts_at: Timestamp, | |
| 104 | + pub(crate) ends_at: Timestamp, | |
| 108 | 105 | /// When a manager archived this term; `None` = open. `#[surreal(default)]` |
| 109 | 106 | /// for the same reason `BankQuestion::subject` has one: rows written before |
| 110 | 107 | /// the column existed still decode, as open terms. |
| 111 | 108 | #[surreal(default)] |
| 112 | - archived_at: Option<Timestamp>, | |
| 109 | + pub(crate) archived_at: Option<Timestamp>, | |
| 113 | 110 | } |
| 114 | 111 | |
| 115 | 112 | impl Term { |
| @@ -136,223 +133,12 @@ impl Term { | ||
| 136 | 133 | pub fn is_archived(&self) -> bool { |
| 137 | 134 | self.archived_at.is_some() |
| 138 | 135 | } |
| 139 | - | |
| 140 | - pub async fn create( | |
| 141 | - name: TermName, | |
| 142 | - starts_at: Timestamp, | |
| 143 | - ends_at: Timestamp, | |
| 144 | - db: &Database, | |
| 145 | - ) -> Result<Term, AppError> { | |
| 146 | - let term = Term { | |
| 147 | - id: TermId::generate(), | |
| 148 | - name, | |
| 149 | - starts_at, | |
| 150 | - ends_at, | |
| 151 | - archived_at: None, | |
| 152 | - }; | |
| 153 | - let created: Option<Term> = db.create(term.id.record()).content(term).await?; | |
| 154 | - created.ok_or_else(|| AppError::Internal("failed to create term".into())) | |
| 155 | - } | |
| 156 | - | |
| 157 | - pub async fn read(id: &TermId, db: &Database) -> Result<Option<Term>, AppError> { | |
| 158 | - Ok(db.select(id.record()).await?) | |
| 159 | - } | |
| 160 | - | |
| 161 | - /// Every term, newest first — the school calendar is small by nature. | |
| 162 | - pub async fn list_all( | |
| 163 | - limit: Option<i64>, | |
| 164 | - offset: i64, | |
| 165 | - db: &Database, | |
| 166 | - ) -> Result<(Vec<Term>, i64), AppError> { | |
| 167 | - PagedList::new("term", "ORDER BY starts_at DESC, id DESC") | |
| 168 | - .run(limit, offset, db) | |
| 169 | - .await | |
| 170 | - } | |
| 171 | - | |
| 172 | - /// Write only the fields the PATCH carried — `None` means the request | |
| 173 | - /// omitted it, so the column is left alone rather than re-stated from the | |
| 174 | - /// snapshot this struct was read into. All three columns are non-nullable, | |
| 175 | - /// so "absent" and "null" both correctly mean "keep". | |
| 176 | - pub async fn update( | |
| 177 | - self, | |
| 178 | - name: Option<TermName>, | |
| 179 | - starts_at: Option<Timestamp>, | |
| 180 | - ends_at: Option<Timestamp>, | |
| 181 | - db: &Database, | |
| 182 | - ) -> Result<Term, AppError> { | |
| 183 | - FieldUpdate::new(self.id.record()) | |
| 184 | - .set("name", name) | |
| 185 | - .set("starts_at", starts_at) | |
| 186 | - .set("ends_at", ends_at) | |
| 187 | - .ordered("starts_at", "ends_at", range_error()) | |
| 188 | - .run::<Term>(db) | |
| 189 | - .await | |
| 190 | - } | |
| 191 | - | |
| 192 | - /// Delete the term, but only while no course *and no class* links it — | |
| 193 | - /// nothing here unlinks or cascades. `false` = refused, nothing was written. | |
| 194 | - /// | |
| 195 | - /// The roster of linking courses is the term's own `course_count` | |
| 196 | - /// refcount, claimed by [`crate::db::course::create`] and | |
| 197 | - /// `update` *before* they write a link, so the check and the delete are one | |
| 198 | - /// conditional write on one record: a course write racing this either | |
| 199 | - /// claims first (and the delete is refused) or finds the row gone (and is | |
| 200 | - /// refused itself, with the same 400 the lookup gives). `Err(NotFound)` | |
| 201 | - /// keeps the answer a concurrent *delete* used to get. | |
| 202 | - /// | |
| 203 | - /// Classes ([`crate::domain::class_group::ClassGroup`]) link a term the same | |
| 204 | - /// way and count on `class_count` — a column of their own, because | |
| 205 | - /// `course_count` is seeded at boot from the course rows alone. | |
| 206 | - pub async fn delete(self, db: &Database) -> Result<bool, AppError> { | |
| 207 | - let sql = format!( | |
| 208 | - "DELETE $term WHERE ({COURSE_COUNT_FIELD} ?? 0) = 0 \ | |
| 209 | - AND ({TERM_CLASS_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE" | |
| 210 | - ); | |
| 211 | - // Through the retry, because the guard reads the very column a course | |
| 212 | - // create claims: a lost round writes nothing, and re-sending it is what | |
| 213 | - // keeps the answer the 404 or 409 it owes instead of a 500. | |
| 214 | - let gone: Vec<Term> = | |
| 215 | - write_with_retry(db, &sql, &[("term".into(), self.id.record().into_value())]).await?; | |
| 216 | - if !gone.is_empty() { | |
| 217 | - return Ok(true); | |
| 218 | - } | |
| 219 | - // Still linked or already gone: the one statement cannot tell those | |
| 220 | - // apart, and only the refusal path pays for the read that can. | |
| 221 | - match Self::read(&self.id, db).await? { | |
| 222 | - Some(_) => Ok(false), | |
| 223 | - None => Err(AppError::NotFound), | |
| 224 | - } | |
| 225 | - } | |
| 226 | - | |
| 227 | - /// Freeze the term. Idempotent by construction: the `WHERE` only matches an | |
| 228 | - /// open row, so a repeat archive writes nothing and answers with the | |
| 229 | - /// *original* stamp — the year is not re-dated by a double click. | |
| 230 | - pub async fn archive(self, db: &Database) -> Result<Term, AppError> { | |
| 231 | - self.stamp( | |
| 232 | - "UPDATE $term SET archived_at = $now WHERE archived_at = NONE RETURN AFTER", | |
| 233 | - Some(Timestamp::now()), | |
| 234 | - db, | |
| 235 | - ) | |
| 236 | - .await | |
| 237 | - } | |
| 238 | - | |
| 239 | - /// Re-open the term; idempotent the same way. | |
| 240 | - pub async fn unarchive(self, db: &Database) -> Result<Term, AppError> { | |
| 241 | - self.stamp( | |
| 242 | - "UPDATE $term SET archived_at = NONE WHERE archived_at != NONE RETURN AFTER", | |
| 243 | - None, | |
| 244 | - db, | |
| 245 | - ) | |
| 246 | - .await | |
| 247 | - } | |
| 248 | - | |
| 249 | - /// One conditional write, through [`write_with_retry`] like every other | |
| 250 | - /// guarded single statement here; an empty result is the no-op case, and | |
| 251 | - /// only that path pays for the read that reports the stored row. | |
| 252 | - async fn stamp( | |
| 253 | - self, | |
| 254 | - sql: &str, | |
| 255 | - now: Option<Timestamp>, | |
| 256 | - db: &Database, | |
| 257 | - ) -> Result<Term, AppError> { | |
| 258 | - let mut bindings = vec![("term".into(), self.id.record().into_value())]; | |
| 259 | - if let Some(now) = now { | |
| 260 | - bindings.push(("now".into(), now.as_millis().into_value())); | |
| 261 | - } | |
| 262 | - let written: Vec<Term> = write_with_retry(db, sql, &bindings).await?; | |
| 263 | - if let Some(term) = written.into_iter().next() { | |
| 264 | - return Ok(term); | |
| 265 | - } | |
| 266 | - Self::read(&self.id, db).await?.ok_or(AppError::NotFound) | |
| 267 | - } | |
| 268 | - | |
| 269 | - /// Refuse when the named term is archived. A missing row is `Ok(())`: a | |
| 270 | - /// dangling link is not this guard's error, and the caller that cares | |
| 271 | - /// already answers it (see [`gone_error`]). | |
| 272 | - pub async fn require_open(id: &TermId, db: &Database) -> Result<(), AppError> { | |
| 273 | - match Self::read(id, db).await? { | |
| 274 | - Some(term) if term.is_archived() => Err(archived_error()), | |
| 275 | - _ => Ok(()), | |
| 276 | - } | |
| 277 | - } | |
| 278 | 136 | } |
| 279 | 137 | |
| 280 | 138 | #[cfg(test)] |
| 281 | 139 | mod tests { |
| 282 | 140 | use super::*; |
| 283 | 141 | |
| 284 | - /// The bite test for the `WHERE` guard that replaced `TERM_LOCK` on the | |
| 285 | - /// PATCH path: the handler's pre-flight check is not in play here, so only | |
| 286 | - /// the guard can refuse a moved end that inverts the range — and it must | |
| 287 | - /// refuse it with the same error, having written nothing. | |
| 288 | - #[tokio::test] | |
| 289 | - async fn a_moved_end_is_refused_against_the_stored_other_end() { | |
| 290 | - let db = crate::database::init_mem().await.unwrap(); | |
| 291 | - let at = Timestamp::from_millis; | |
| 292 | - let term = Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), &db) | |
| 293 | - .await | |
| 294 | - .unwrap(); | |
| 295 | - | |
| 296 | - let refused = term | |
| 297 | - .clone() | |
| 298 | - .update(None, None, Some(at(50)), &db) | |
| 299 | - .await | |
| 300 | - .expect_err("an end before the stored start must be refused"); | |
| 301 | - assert!(refused.to_string().contains("at or after starts_at")); | |
| 302 | - let stored = Term::read(term.get_id(), &db).await.unwrap().unwrap(); | |
| 303 | - assert_eq!( | |
| 304 | - stored.get_ends_at(), | |
| 305 | - at(200), | |
| 306 | - "nothing may have been written" | |
| 307 | - ); | |
| 308 | - | |
| 309 | - // A move that keeps the range ordered still lands, guard and all. | |
| 310 | - let moved = term.update(None, None, Some(at(300)), &db).await.unwrap(); | |
| 311 | - assert_eq!(moved.get_ends_at(), at(300)); | |
| 312 | - } | |
| 313 | - | |
| 314 | - /// Terms are listed newest-first *and* paged by offset, so the sort has to | |
| 315 | - /// be a total order: `starts_at` alone leaves rows that share an instant in | |
| 316 | - /// an arbitrary order, and offset paging over an unstable order can hand | |
| 317 | - /// the same row out twice while skipping another. Pins the `id DESC` | |
| 318 | - /// tie-break on identical `starts_at` — stored read-back, then page by page. | |
| 319 | - #[tokio::test] | |
| 320 | - async fn identical_starts_at_still_pages_each_term_exactly_once() { | |
| 321 | - let db = crate::database::init_mem().await.unwrap(); | |
| 322 | - let at = Timestamp::from_millis; | |
| 323 | - let mut minted = Vec::new(); | |
| 324 | - for i in 0..12 { | |
| 325 | - let term = Term::create( | |
| 326 | - TermName::try_new(&format!("t{i}")).unwrap(), | |
| 327 | - at(100), | |
| 328 | - at(200), | |
| 329 | - &db, | |
| 330 | - ) | |
| 331 | - .await | |
| 332 | - .unwrap(); | |
| 333 | - minted.push(term.get_id().key().to_string()); | |
| 334 | - } | |
| 335 | - // Newest first: the tie-break runs the same way as the primary column. | |
| 336 | - minted.reverse(); | |
| 337 | - | |
| 338 | - let (listed, total) = Term::list_all(None, 0, &db).await.unwrap(); | |
| 339 | - assert_eq!(total, 12); | |
| 340 | - let read_back: Vec<String> = listed | |
| 341 | - .iter() | |
| 342 | - .map(|row| row.get_id().key().to_string()) | |
| 343 | - .collect(); | |
| 344 | - assert_eq!(read_back, minted); | |
| 345 | - | |
| 346 | - // The assertion that catches skip/duplicate: walk it in pages of 5. | |
| 347 | - let mut paged = Vec::new(); | |
| 348 | - for offset in [0, 5, 10] { | |
| 349 | - let (page, total) = Term::list_all(Some(5), offset, &db).await.unwrap(); | |
| 350 | - assert_eq!(total, 12); | |
| 351 | - paged.extend(page.iter().map(|row| row.get_id().key().to_string())); | |
| 352 | - } | |
| 353 | - assert_eq!(paged, minted, "every term exactly once, in list order"); | |
| 354 | - } | |
| 355 | - | |
| 356 | 142 | #[tokio::test] |
| 357 | 143 | async fn name_is_required_and_bounded() { |
| 358 | 144 | assert!(TermName::try_new("2026 Fall").is_ok()); |
| @@ -360,135 +146,4 @@ mod tests { | ||
| 360 | 146 | assert!(TermName::try_new(" ").is_err()); |
| 361 | 147 | assert!(TermName::try_new(&"x".repeat(101)).is_err()); |
| 362 | 148 | } |
| 363 | - | |
| 364 | - /// GUARD, not a retry measurement — read the last paragraph before | |
| 365 | - /// trusting this test with the retry. See | |
| 366 | - /// [`crate::db::course::delete`]'s race test for why the rate is | |
| 367 | - /// counted rather than asserted per round. | |
| 368 | - /// | |
| 369 | - /// One conditional `DELETE … RETURN BEFORE` and a bare `.check()?`: no | |
| 370 | - /// transaction to abort, but also no [`crate::database::write_with_retry`], | |
| 371 | - /// which every other guarded single-statement write in the crate goes | |
| 372 | - /// through. A store answering "conflict, retry" therefore comes out as a | |
| 373 | - /// 500 instead of the 404 or 409 the request owes. | |
| 374 | - /// | |
| 375 | - /// The racer is [`crate::db::course::create`] against this | |
| 376 | - /// term: it claims `course_count` on the term row before it writes the | |
| 377 | - /// link, which is the same record and the same column the guard reads. Both | |
| 378 | - /// sides are swept across each other sub-millisecond, exactly as in | |
| 379 | - /// [`crate::domain::subject::Subject::delete`]'s race test — a whole | |
| 380 | - /// millisecond of head start on either side separates them completely, and | |
| 381 | - /// the counters below assert the sweep straddled the site rather than | |
| 382 | - /// landing on one side of it (it used to alternate on `round % 2` and score | |
| 383 | - /// an exact 10/10, i.e. no overlap at all). | |
| 384 | - /// | |
| 385 | - /// And like that test it does *not* prove the retry: this site is one | |
| 386 | - /// statement, so the window in which a conflict could reach | |
| 387 | - /// [`write_with_retry`] is a single round trip wide — measured at 0 | |
| 388 | - /// conflicts in 100 raced rounds, green with the retry loop cut to a single | |
| 389 | - /// attempt. A status-code guard, then: a raced delete answers 409 or 404 and | |
| 390 | - /// never 500, and a course that got linked survives it. The retry is | |
| 391 | - /// measured on [`crate::db::course::delete`]. | |
| 392 | - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | |
| 393 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | |
| 394 | - async fn a_delete_racing_a_course_create_never_answers_500() { | |
| 395 | - use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; | |
| 396 | - use crate::domain::user::UserId; | |
| 397 | - let (db, _serialized) = crate::database::init_test_server("term_delete_race").await; | |
| 398 | - let (mut delete_500, mut create_500) = (0, 0); | |
| 399 | - let (mut linked, mut wiped) = (0, 0); | |
| 400 | - let (mut last_delete, mut last_create) = (String::new(), String::new()); | |
| 401 | - let at = Timestamp::from_millis; | |
| 402 | - for round in 0..20 { | |
| 403 | - let term = Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), &db) | |
| 404 | - .await | |
| 405 | - .unwrap(); | |
| 406 | - | |
| 407 | - let separated = round % 4 == 0; | |
| 408 | - let drop_it = { | |
| 409 | - let (term, db) = (term.clone(), db.clone()); | |
| 410 | - // One round in four holds the racers back by a clear 2ms so the | |
| 411 | - // delete wins outright: the sub-millisecond sweep alone leaves | |
| 412 | - // them ahead of it nearly every round (measured 20 to 0), and | |
| 413 | - // both counters below have to see a side. The other three keep | |
| 414 | - // the sub-ms beat, which is the only spacing that overlaps at | |
| 415 | - // all — a whole millisecond either way separates them. | |
| 416 | - let beat = if separated { | |
| 417 | - std::time::Duration::ZERO | |
| 418 | - } else { | |
| 419 | - std::time::Duration::from_micros(round * 53 % 300) | |
| 420 | - }; | |
| 421 | - tokio::spawn(async move { | |
| 422 | - tokio::time::sleep(beat).await; | |
| 423 | - term.delete(&db).await | |
| 424 | - }) | |
| 425 | - }; | |
| 426 | - let makes: Vec<_> = (0..6) | |
| 427 | - .map(|_| { | |
| 428 | - let (id, db) = (term.get_id().clone(), db.clone()); | |
| 429 | - let head_start = if separated { | |
| 430 | - std::time::Duration::from_millis(2) | |
| 431 | - } else { | |
| 432 | - std::time::Duration::from_micros(round * 37 % 300) | |
| 433 | - }; | |
| 434 | - tokio::spawn(async move { | |
| 435 | - tokio::time::sleep(head_start).await; | |
| 436 | - crate::db::course::create( | |
| 437 | - &db, | |
| 438 | - &UserId::from_key("teacher"), | |
| 439 | - CourseTitle::try_new("algebra").unwrap(), | |
| 440 | - CourseDescription::try_new("").unwrap(), | |
| 441 | - CourseKind::course(), | |
| 442 | - Some(id), | |
| 443 | - None, | |
| 444 | - ) | |
| 445 | - .await | |
| 446 | - }) | |
| 447 | - }) | |
| 448 | - .collect(); | |
| 449 | - let drop_it = drop_it.await.unwrap(); | |
| 450 | - if matches!(drop_it, Err(AppError::Db(_))) { | |
| 451 | - delete_500 += 1; | |
| 452 | - last_delete = format!("{drop_it:?}"); | |
| 453 | - } | |
| 454 | - // Stored state, both sides: a linked course means the claim beat the | |
| 455 | - // guard, a gone term means the delete did. | |
| 456 | - let mut landed = false; | |
| 457 | - for make in makes { | |
| 458 | - let make = make.await.unwrap(); | |
| 459 | - if matches!(make, Err(AppError::Db(_))) { | |
| 460 | - create_500 += 1; | |
| 461 | - last_create = format!("{make:?}"); | |
| 462 | - } | |
| 463 | - if let Ok(course) = &make | |
| 464 | - && crate::db::course::read(&db, course.get_id()) | |
| 465 | - .await | |
| 466 | - .unwrap() | |
| 467 | - .is_some() | |
| 468 | - { | |
| 469 | - landed = true; | |
| 470 | - } | |
| 471 | - } | |
| 472 | - linked += usize::from(landed); | |
| 473 | - if Term::read(term.get_id(), &db).await.unwrap().is_none() { | |
| 474 | - wiped += 1; | |
| 475 | - } | |
| 476 | - } | |
| 477 | - eprintln!( | |
| 478 | - "Term::delete raced: {delete_500}/20 delete 500s, {create_500} create 500s, \ | |
| 479 | - {linked} rounds with a course linked / {wiped} wiped" | |
| 480 | - ); | |
| 481 | - assert!( | |
| 482 | - linked > 0 && wiped > 0, | |
| 483 | - "the sweep never crossed the window ({linked} linked / {wiped} wiped)" | |
| 484 | - ); | |
| 485 | - assert_eq!( | |
| 486 | - delete_500, 0, | |
| 487 | - "a raced delete must be refused, not 500: {delete_500}/20 rounds, last {last_delete}" | |
| 488 | - ); | |
| 489 | - assert_eq!( | |
| 490 | - create_500, 0, | |
| 491 | - "a raced course create must retry, not 500: {create_500}/20 rounds, last {last_create}" | |
| 492 | - ); | |
| 493 | - } | |
| 494 | 149 | } |
src/service/course.rsmodified+3 -2
| @@ -12,9 +12,10 @@ use crate::domain::course_note_file::CourseNoteFile; | ||
| 12 | 12 | use crate::domain::homework_file::HomeworkFile; |
| 13 | 13 | use crate::domain::question_image::QuestionImage; |
| 14 | 14 | use crate::domain::role::Role; |
| 15 | -use crate::domain::term::{self, TermId}; | |
| 15 | +use crate::domain::term::TermId; | |
| 16 | 16 | use crate::domain::user::UserId; |
| 17 | 17 | use crate::error::{AppError, ValidationError}; |
| 18 | +use crate::service::term; | |
| 18 | 19 | |
| 19 | 20 | /// Refuse the write when this course's term is archived — a pre-flight guard, |
| 20 | 21 | /// accepted race (see README concurrency model): a term archived after this |
| @@ -22,7 +23,7 @@ use crate::error::{AppError, ValidationError}; | ||
| 22 | 23 | pub async fn require_open(db: &Database, course: &Course) -> Result<(), AppError> { |
| 23 | 24 | match course.get_term() { |
| 24 | 25 | None => Ok(()), |
| 25 | - Some(term) => term::Term::require_open(term, db).await, | |
| 26 | + Some(term) => term::require_open(db, term).await, | |
| 26 | 27 | } |
| 27 | 28 | } |
| 28 | 29 |
src/service/exam_attempt.rsmodified+3 -3
| @@ -40,7 +40,7 @@ use crate::error::AppError; | ||
| 40 | 40 | /// subject delete's cascade — the only writer outside attempt starts, paired |
| 41 | 41 | /// with the question writes' subject check — is now a conditional statement on |
| 42 | 42 | /// the subject's own reference counter |
| 43 | -/// ([`crate::domain::subject::Subject::delete`]), which every question create, | |
| 43 | +/// ([`crate::db::subject::delete`]), which every question create, | |
| 44 | 44 | /// re-tag and delete moves. |
| 45 | 45 | // corner-cut: global RwLock, shard per-exam if save latency ever matters. |
| 46 | 46 | pub(crate) static EXAM_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(()); |
| @@ -522,11 +522,11 @@ mod tests { | ||
| 522 | 522 | .unwrap(); |
| 523 | 523 | // A real subject row, not a minted id: a question claims a reference on |
| 524 | 524 | // its subject and is refused if that subject does not exist. |
| 525 | - let subject = crate::domain::subject::Subject::create( | |
| 525 | + let subject = crate::db::subject::create( | |
| 526 | + db, | |
| 526 | 527 | &crate::db::course::a_test_course(db).await, |
| 527 | 528 | crate::domain::subject::SubjectName::try_new("topic").unwrap(), |
| 528 | 529 | crate::domain::subject::SubjectDescription::try_new("").unwrap(), |
| 529 | - db, | |
| 530 | 530 | ) |
| 531 | 531 | .await |
| 532 | 532 | .unwrap(); |
src/service/mod.rsmodified+2 -0
| @@ -23,5 +23,7 @@ pub mod profile; | ||
| 23 | 23 | pub mod registration; |
| 24 | 24 | pub mod session; |
| 25 | 25 | pub mod settings; |
| 26 | +pub mod subject; | |
| 27 | +pub mod term; | |
| 26 | 28 | pub mod user; |
| 27 | 29 | pub mod work_entry; |
src/service/subject.rsadded+89 -0
| @@ -0,0 +1,89 @@ | ||
| 1 | +//! Subject workflows: the two id resolvers every question/homework tag goes | |
| 2 | +//! through — the same-course rule for curriculum content, existence-only for | |
| 3 | +//! the bank's cross-course origin metadata — over the row writes in | |
| 4 | +//! [`crate::db::subject`]. | |
| 5 | + | |
| 6 | +use crate::database::Database; | |
| 7 | +use crate::db::subject; | |
| 8 | +use crate::domain::course::CourseId; | |
| 9 | +use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName}; | |
| 10 | +use crate::error::{AppError, ValidationError}; | |
| 11 | + | |
| 12 | +pub async fn create( | |
| 13 | + db: &Database, | |
| 14 | + course: &CourseId, | |
| 15 | + name: SubjectName, | |
| 16 | + description: SubjectDescription, | |
| 17 | +) -> Result<Subject, AppError> { | |
| 18 | + subject::create(db, course, name, description).await | |
| 19 | +} | |
| 20 | + | |
| 21 | +/// The subject row, for callers that only inspect it — the web layer's gates | |
| 22 | +/// read through here. | |
| 23 | +pub async fn read(db: &Database, id: &SubjectId) -> Result<Option<Subject>, AppError> { | |
| 24 | + subject::read(db, id).await | |
| 25 | +} | |
| 26 | + | |
| 27 | +/// Several subjects in one query — the bulk half of a list endpoint that | |
| 28 | +/// names each row's subject (a read per row would be an N+1). | |
| 29 | +pub async fn list_by_ids(db: &Database, ids: &[&SubjectId]) -> Result<Vec<Subject>, AppError> { | |
| 30 | + subject::list_by_ids(db, ids).await | |
| 31 | +} | |
| 32 | + | |
| 33 | +pub async fn list_for_course( | |
| 34 | + db: &Database, | |
| 35 | + course: &CourseId, | |
| 36 | + limit: Option<i64>, | |
| 37 | + offset: i64, | |
| 38 | +) -> Result<(Vec<Subject>, i64), AppError> { | |
| 39 | + subject::list_for_course(db, course, limit, offset).await | |
| 40 | +} | |
| 41 | + | |
| 42 | +pub async fn update( | |
| 43 | + db: &Database, | |
| 44 | + target: Subject, | |
| 45 | + name: Option<SubjectName>, | |
| 46 | + description: Option<SubjectDescription>, | |
| 47 | +) -> Result<Subject, AppError> { | |
| 48 | + subject::update(db, target, name, description).await | |
| 49 | +} | |
| 50 | + | |
| 51 | +pub async fn delete(db: &Database, target: Subject) -> Result<Subject, AppError> { | |
| 52 | + subject::delete(db, target).await | |
| 53 | +} | |
| 54 | + | |
| 55 | +/// Turn a request-supplied subject id into a validated reference, provided the | |
| 56 | +/// subject belongs to `course` — a question may only be tagged with a subject | |
| 57 | +/// of its own exam's course. Unknown or foreign subjects are a `400` naming | |
| 58 | +/// the field. Shared by the question create/update handlers. | |
| 59 | +pub async fn in_course(db: &Database, id: &str, course: &CourseId) -> Result<SubjectId, AppError> { | |
| 60 | + let subject = | |
| 61 | + subject::read(db, &SubjectId::from_key(id)) | |
| 62 | + .await? | |
| 63 | + .ok_or(AppError::Validation(ValidationError::Invalid { | |
| 64 | + field: "subject_id", | |
| 65 | + reason: "subject does not exist", | |
| 66 | + }))?; | |
| 67 | + if subject.get_course() != course { | |
| 68 | + return Err(AppError::Validation(ValidationError::Invalid { | |
| 69 | + field: "subject_id", | |
| 70 | + reason: "subject belongs to a different course", | |
| 71 | + })); | |
| 72 | + } | |
| 73 | + Ok(subject.get_id().clone()) | |
| 74 | +} | |
| 75 | + | |
| 76 | +/// Turn a request-supplied subject id into a validated reference, checking only | |
| 77 | +/// that the subject exists — no course tie. For the question bank, whose subject | |
| 78 | +/// is cross-course origin metadata: the same-course rule applies at instantiate | |
| 79 | +/// time, not here. An unknown subject is a `400` naming the field. | |
| 80 | +pub async fn must_exist(db: &Database, id: &str) -> Result<SubjectId, AppError> { | |
| 81 | + let subject = | |
| 82 | + subject::read(db, &SubjectId::from_key(id)) | |
| 83 | + .await? | |
| 84 | + .ok_or(AppError::Validation(ValidationError::Invalid { | |
| 85 | + field: "subject_id", | |
| 86 | + reason: "subject does not exist", | |
| 87 | + }))?; | |
| 88 | + Ok(subject.get_id().clone()) | |
| 89 | +} |
src/service/term.rsadded+111 -0
| @@ -0,0 +1,111 @@ | ||
| 1 | +//! Term workflows: the archived-refusal rule every write against past | |
| 2 | +//! structure pays — the link resolver every new course/class link passes | |
| 3 | +//! through, the row-level write gate, and the linked-refusal mapping on the | |
| 4 | +//! delete. The queries live in [`crate::db::term`]. | |
| 5 | + | |
| 6 | +use crate::database::Database; | |
| 7 | +use crate::db::term; | |
| 8 | +use crate::domain::term::{Term, TermId, TermName, archived_error}; | |
| 9 | +use crate::domain::timestamp::Timestamp; | |
| 10 | +use crate::error::{AppError, ValidationError}; | |
| 11 | + | |
| 12 | +pub async fn create( | |
| 13 | + db: &Database, | |
| 14 | + name: TermName, | |
| 15 | + starts_at: Timestamp, | |
| 16 | + ends_at: Timestamp, | |
| 17 | +) -> Result<Term, AppError> { | |
| 18 | + term::create(db, name, starts_at, ends_at).await | |
| 19 | +} | |
| 20 | + | |
| 21 | +/// The term row, for callers that only inspect it — the web layer's gates | |
| 22 | +/// read through here. | |
| 23 | +pub async fn read(db: &Database, id: &TermId) -> Result<Option<Term>, AppError> { | |
| 24 | + term::read(db, id).await | |
| 25 | +} | |
| 26 | + | |
| 27 | +pub async fn list_all( | |
| 28 | + db: &Database, | |
| 29 | + limit: Option<i64>, | |
| 30 | + offset: i64, | |
| 31 | +) -> Result<(Vec<Term>, i64), AppError> { | |
| 32 | + term::list_all(db, limit, offset).await | |
| 33 | +} | |
| 34 | + | |
| 35 | +/// Turn an optional request-supplied term id into a validated reference — | |
| 36 | +/// `None` stays `None`, an unknown id is a `400` naming the field, and an | |
| 37 | +/// *archived* one is a `409 term_archived`. That last refusal lives here | |
| 38 | +/// rather than in each handler because this is the single spot every new | |
| 39 | +/// link to a term passes through — course create/update and class | |
| 40 | +/// create/update alike: past years take no new structure. | |
| 41 | +pub async fn resolve(db: &Database, id: Option<&str>) -> Result<Option<TermId>, AppError> { | |
| 42 | + let Some(id) = id else { | |
| 43 | + return Ok(None); | |
| 44 | + }; | |
| 45 | + let resolved = term::read(db, &TermId::from_key(id)) | |
| 46 | + .await? | |
| 47 | + .ok_or(AppError::Validation(ValidationError::Invalid { | |
| 48 | + field: "term_id", | |
| 49 | + reason: "term does not exist", | |
| 50 | + }))?; | |
| 51 | + if resolved.is_archived() { | |
| 52 | + return Err(archived_error()); | |
| 53 | + } | |
| 54 | + Ok(Some(resolved.get_id().clone())) | |
| 55 | +} | |
| 56 | + | |
| 57 | +/// Refuse when the named term is archived. A missing row is `Ok(())`: a | |
| 58 | +/// dangling link is not this guard's error, and the caller that cares | |
| 59 | +/// already answers it (see [`crate::domain::term::gone_error`]). | |
| 60 | +pub async fn require_open(db: &Database, id: &TermId) -> Result<(), AppError> { | |
| 61 | + match term::read(db, id).await? { | |
| 62 | + Some(term) if term.is_archived() => Err(archived_error()), | |
| 63 | + _ => Ok(()), | |
| 64 | + } | |
| 65 | +} | |
| 66 | + | |
| 67 | +/// Refuse when this term row is archived — the read-only rule for past | |
| 68 | +/// structure, judged against a row the caller already read through [`read`]; | |
| 69 | +/// a missing row is the caller's 404, not this guard's answer. | |
| 70 | +pub fn require_writable(t: &Term) -> Result<(), AppError> { | |
| 71 | + if t.is_archived() { | |
| 72 | + return Err(archived_error()); | |
| 73 | + } | |
| 74 | + Ok(()) | |
| 75 | +} | |
| 76 | + | |
| 77 | +/// Update an open term; an archived one is refused — past years are | |
| 78 | +/// read-only. | |
| 79 | +pub async fn update( | |
| 80 | + db: &Database, | |
| 81 | + target: Term, | |
| 82 | + name: Option<TermName>, | |
| 83 | + starts_at: Option<Timestamp>, | |
| 84 | + ends_at: Option<Timestamp>, | |
| 85 | +) -> Result<Term, AppError> { | |
| 86 | + term::update(db, target, name, starts_at, ends_at).await | |
| 87 | +} | |
| 88 | + | |
| 89 | +/// Delete the term while nothing links it. The linked-refusal is the rule's | |
| 90 | +/// own answer, so the message the web layer used to pick is coded here; a | |
| 91 | +/// row that is already gone is the store's `404` ([`term::delete`]). | |
| 92 | +pub async fn delete(db: &Database, target: Term) -> Result<(), AppError> { | |
| 93 | + if term::delete(db, target).await? { | |
| 94 | + Ok(()) | |
| 95 | + } else { | |
| 96 | + Err(AppError::Conflict( | |
| 97 | + "courses are still linked to this term — unlink them first", | |
| 98 | + )) | |
| 99 | + } | |
| 100 | +} | |
| 101 | + | |
| 102 | +/// Archive a term; idempotent — an already-archived term answers with the | |
| 103 | +/// stamp it already had. | |
| 104 | +pub async fn archive(db: &Database, target: Term) -> Result<Term, AppError> { | |
| 105 | + term::archive(db, target).await | |
| 106 | +} | |
| 107 | + | |
| 108 | +/// Re-open an archived term; idempotent the same way. | |
| 109 | +pub async fn unarchive(db: &Database, target: Term) -> Result<Term, AppError> { | |
| 110 | + term::unarchive(db, target).await | |
| 111 | +} |
src/web/bank_questions.rsmodified+20 -16
| @@ -33,14 +33,14 @@ use crate::domain::exam_question::{ | ||
| 33 | 33 | }; |
| 34 | 34 | use crate::domain::note_file::FileContentType; |
| 35 | 35 | use crate::domain::role::Role; |
| 36 | -use crate::domain::subject::{Subject, SubjectId}; | |
| 36 | +use crate::domain::subject::SubjectId; | |
| 37 | 37 | use crate::domain::user::{User, UserId}; |
| 38 | 38 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 39 | +use crate::service; | |
| 39 | 40 | use crate::state::AppState; |
| 40 | 41 | |
| 41 | 42 | use super::dto::person_map; |
| 42 | 43 | use super::exams::ChoiceResponse; |
| 43 | -use super::subjects::subject_must_exist; | |
| 44 | 44 | use super::{ |
| 45 | 45 | ChoiceBody, ImageUpload, Page, PageParams, RequireTeacher, UploadFileForm, read_image_upload, |
| 46 | 46 | remove_blob, serve_inline_blob, set_or_clear, store_blob, |
| @@ -51,7 +51,7 @@ use super::{ | ||
| 51 | 51 | // `subject` off every template — and that delete no longer takes any lock: it |
| 52 | 52 | // is a conditional statement on the subject's own reference counters, which |
| 53 | 53 | // bank templates deliberately do not hold (blocking on them was a dead end; see |
| 54 | -// [`crate::domain::subject::Subject::delete`]). With the writer gone the three | |
| 54 | +// [`crate::db::subject::delete`]). With the writer gone the three | |
| 55 | 55 | // reader leases guarded nothing, and what they claimed to guard was already |
| 56 | 56 | // open in production: the lock lived in one process, and the deployment runs |
| 57 | 57 | // exactly one process (stop-the-world upgrades) — there is nothing else to |
| @@ -447,7 +447,7 @@ async fn create_question( | ||
| 447 | 447 | Json(req): Json<CreateBankQuestion>, |
| 448 | 448 | ) -> Result<(StatusCode, Json<BankQuestionResponse>), AppError> { |
| 449 | 449 | // Origin metadata only — no course to check it against, but it must exist. |
| 450 | - let subject = subject_must_exist(&req.subject_id, &st.db).await?; | |
| 450 | + let subject = service::subject::must_exist(&st.db, &req.subject_id).await?; | |
| 451 | 451 | let text = QuestionText::try_new(&req.text)?; |
| 452 | 452 | let points = QuestionPoints::try_new(req.points)?; |
| 453 | 453 | // Nothing stored to match against on create: every option is new and every |
| @@ -538,16 +538,17 @@ async fn list_questions( | ||
| 538 | 538 | .iter() |
| 539 | 539 | .filter_map(BankQuestion::get_subject) |
| 540 | 540 | .collect(); |
| 541 | - let subject_names: HashMap<String, String> = Subject::list_by_ids(&subject_ids, &st.db) | |
| 542 | - .await? | |
| 543 | - .iter() | |
| 544 | - .map(|subject| { | |
| 545 | - ( | |
| 546 | - subject.get_id().key().to_string(), | |
| 547 | - subject.get_name().as_str().to_string(), | |
| 548 | - ) | |
| 549 | - }) | |
| 550 | - .collect(); | |
| 541 | + let subject_names: HashMap<String, String> = | |
| 542 | + service::subject::list_by_ids(&st.db, &subject_ids) | |
| 543 | + .await? | |
| 544 | + .iter() | |
| 545 | + .map(|subject| { | |
| 546 | + ( | |
| 547 | + subject.get_id().key().to_string(), | |
| 548 | + subject.get_name().as_str().to_string(), | |
| 549 | + ) | |
| 550 | + }) | |
| 551 | + .collect(); | |
| 551 | 552 | let people = person_map(questions.iter().map(|q| q.get_owner().clone()), &st.db).await?; |
| 552 | 553 | |
| 553 | 554 | let empty: Vec<BankQuestionImage> = Vec::new(); |
| @@ -645,7 +646,7 @@ async fn update_question( | ||
| 645 | 646 | // Omitted keeps the stored subject — which may already be `None`, cleared |
| 646 | 647 | // by that subject's delete. |
| 647 | 648 | let subject = match req.subject_id { |
| 648 | - Some(ref subject_id) => Some(subject_must_exist(subject_id, &st.db).await?), | |
| 649 | + Some(ref subject_id) => Some(service::subject::must_exist(&st.db, subject_id).await?), | |
| 649 | 650 | None => question.get_subject().cloned(), |
| 650 | 651 | }; |
| 651 | 652 | let text = match req.text { |
| @@ -951,7 +952,10 @@ mod tests { | ||
| 951 | 952 | let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash) |
| 952 | 953 | .await |
| 953 | 954 | .unwrap(); |
| 954 | - crate::service::user::set_role(db, user.get_id(), role).await.unwrap().0 | |
| 955 | + crate::service::user::set_role(db, user.get_id(), role) | |
| 956 | + .await | |
| 957 | + .unwrap() | |
| 958 | + .0 | |
| 955 | 959 | } |
| 956 | 960 | |
| 957 | 961 | /// Every bank route is `RequireTeacher` today, so this is pinned at the |
src/web/classes.rsmodified+4 -4
| @@ -27,10 +27,10 @@ use crate::domain::user::{User, UserId}; | ||
| 27 | 27 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 28 | 28 | use crate::service::class_blueprint; |
| 29 | 29 | use crate::service::parent_link::ensure_can_observe; |
| 30 | +use crate::service::term; | |
| 30 | 31 | use crate::state::AppState; |
| 31 | 32 | |
| 32 | 33 | use super::courses::can_manage_course; |
| 33 | -use super::terms::resolve_term; | |
| 34 | 34 | use super::{ |
| 35 | 35 | CurrentUser, Page, PageParams, PersonRef, RequireManager, RequireTeacher, person_map, |
| 36 | 36 | set_or_clear, undo_if_demoted, |
| @@ -355,7 +355,7 @@ async fn create_class( | ||
| 355 | 355 | // Pre-flight only: `ClassGroup::create` claims a reference on the term |
| 356 | 356 | // before it writes the link, and a term deleted in between fails that claim |
| 357 | 357 | // with this very error — so an unknown id reads the same whichever side wins. |
| 358 | - let term = resolve_term(req.term_id.as_deref(), &st.db).await?; | |
| 358 | + let term = term::resolve(&st.db, req.term_id.as_deref()).await?; | |
| 359 | 359 | let teacher = teacher_or_none(req.teacher_id.as_deref(), &st.db).await?; |
| 360 | 360 | let class = ClassGroup::create( |
| 361 | 361 | user.get_id(), |
| @@ -554,7 +554,7 @@ async fn update_class( | ||
| 554 | 554 | ) -> Result<Json<ClassResponse>, AppError> { |
| 555 | 555 | let class = class_or_404(&id, &st.db).await?; |
| 556 | 556 | // The class's *current* term, so a move off an archived year is refused |
| 557 | - // too; `resolve_term` below holds the other end (the term moved onto). | |
| 557 | + // too; `term::resolve` below holds the other end (the term moved onto). | |
| 558 | 558 | class.require_open(&st.db).await?; |
| 559 | 559 | |
| 560 | 560 | // Only what the request actually carried is validated and written — an |
| @@ -567,7 +567,7 @@ async fn update_class( | ||
| 567 | 567 | }; |
| 568 | 568 | let term = match req.term_id { |
| 569 | 569 | // Explicit `null` clears the link; a value must name a real term. |
| 570 | - Some(ref update) => Some(resolve_term(update.as_deref(), &st.db).await?), | |
| 570 | + Some(ref update) => Some(term::resolve(&st.db, update.as_deref()).await?), | |
| 571 | 571 | None => None, |
| 572 | 572 | }; |
| 573 | 573 | let teacher = match req.teacher_id { |
src/web/courses.rsmodified+21 -12
| @@ -18,7 +18,7 @@ use crate::domain::exam::{ | ||
| 18 | 18 | }; |
| 19 | 19 | use crate::domain::homework::{Homework, HomeworkTitle}; |
| 20 | 20 | use crate::domain::role::Role; |
| 21 | -use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; | |
| 21 | +use crate::domain::subject::{SubjectDescription, SubjectName}; | |
| 22 | 22 | use crate::domain::timestamp::Timestamp; |
| 23 | 23 | use crate::domain::user::{User, UserId}; |
| 24 | 24 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| @@ -26,8 +26,6 @@ use crate::service; | ||
| 26 | 26 | use crate::state::AppState; |
| 27 | 27 | |
| 28 | 28 | use super::homework::{description_or_none, resolve_assigned}; |
| 29 | -use super::subjects::subject_in_course; | |
| 30 | -use super::terms::resolve_term; | |
| 31 | 29 | use super::{ |
| 32 | 30 | CourseResponse, CurrentUser, ExamResponse, HomeworkResponse, Page, PageParams, PersonRef, |
| 33 | 31 | RequireManager, RequireTeacher, SessionResponse, SubjectResponse, check_not_past, |
| @@ -326,7 +324,7 @@ async fn create_course( | ||
| 326 | 324 | // Pre-flight only: the create itself claims a reference on the term before |
| 327 | 325 | // it writes the link, and a term deleted in between fails that claim with |
| 328 | 326 | // this very error — so an unknown id reads the same whichever side wins. |
| 329 | - let term = resolve_term(req.term_id.as_deref(), &st.db).await?; | |
| 327 | + let term = service::term::resolve(&st.db, req.term_id.as_deref()).await?; | |
| 330 | 328 | check_capacity(req.capacity)?; |
| 331 | 329 | let course = service::course::create( |
| 332 | 330 | &st.db, |
| @@ -496,7 +494,7 @@ async fn update_course( | ||
| 496 | 494 | // (keep), an explicit `null` is `Some(None)` (write `NONE`). |
| 497 | 495 | let term = match req.term_id { |
| 498 | 496 | // Explicit `null` clears the link; a value must name a real term. |
| 499 | - Some(ref update) => Some(resolve_term(update.as_deref(), &st.db).await?), | |
| 497 | + Some(ref update) => Some(service::term::resolve(&st.db, update.as_deref()).await?), | |
| 500 | 498 | None => None, |
| 501 | 499 | }; |
| 502 | 500 | // Explicit `null` lifts the cap; a value must be positive. |
| @@ -964,7 +962,7 @@ async fn create_subject_in_course( | ||
| 964 | 962 | |
| 965 | 963 | let name = SubjectName::try_new(&req.name)?; |
| 966 | 964 | let description = SubjectDescription::try_new(&req.description.unwrap_or_default())?; |
| 967 | - let subject = Subject::create(course.get_id(), name, description, &st.db).await?; | |
| 965 | + let subject = service::subject::create(&st.db, course.get_id(), name, description).await?; | |
| 968 | 966 | Ok((StatusCode::CREATED, Json(SubjectResponse::new(&subject)))) |
| 969 | 967 | } |
| 970 | 968 | |
| @@ -1003,7 +1001,7 @@ async fn list_course_subjects( | ||
| 1003 | 1001 | )); |
| 1004 | 1002 | } |
| 1005 | 1003 | let (subjects, total) = |
| 1006 | - Subject::list_for_course(course.get_id(), limit, offset, &st.db).await?; | |
| 1004 | + service::subject::list_for_course(&st.db, course.get_id(), limit, offset).await?; | |
| 1007 | 1005 | let items = subjects.iter().map(SubjectResponse::new).collect(); |
| 1008 | 1006 | Ok(Json(Page::new(items, total, limit, offset))) |
| 1009 | 1007 | } |
| @@ -1082,7 +1080,7 @@ async fn create_homework_in_course( | ||
| 1082 | 1080 | // No lease: the create takes the subject's reference counter in the same |
| 1083 | 1081 | // breath as the row, and the subject delete is refused while that counter |
| 1084 | 1082 | // is non-zero — so the check below is only a pre-flight for the message. |
| 1085 | - let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; | |
| 1083 | + let subject = service::subject::in_course(&st.db, &req.subject_id, course.get_id()).await?; | |
| 1086 | 1084 | let assigned = resolve_assigned(req.assigned, course.get_id(), &st.db).await?; |
| 1087 | 1085 | let homework = Homework::create( |
| 1088 | 1086 | course.get_id(), |
| @@ -1297,7 +1295,10 @@ mod tests { | ||
| 1297 | 1295 | let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash) |
| 1298 | 1296 | .await |
| 1299 | 1297 | .unwrap(); |
| 1300 | - crate::service::user::set_role(db, user.get_id(), role).await.unwrap().0 | |
| 1298 | + crate::service::user::set_role(db, user.get_id(), role) | |
| 1299 | + .await | |
| 1300 | + .unwrap() | |
| 1301 | + .0 | |
| 1301 | 1302 | } |
| 1302 | 1303 | |
| 1303 | 1304 | /// A course `creator` made, with nobody assigned. |
| @@ -1326,7 +1327,10 @@ mod tests { | ||
| 1326 | 1327 | assert!(owns_course(&course, &creator)); |
| 1327 | 1328 | |
| 1328 | 1329 | for role in [Role::Student, Role::Parent] { |
| 1329 | - let demoted = crate::service::user::set_role(&db, creator.get_id(), role).await.unwrap().0; | |
| 1330 | + let demoted = crate::service::user::set_role(&db, creator.get_id(), role) | |
| 1331 | + .await | |
| 1332 | + .unwrap() | |
| 1333 | + .0; | |
| 1330 | 1334 | assert!( |
| 1331 | 1335 | !can_manage_course(&course, &demoted), |
| 1332 | 1336 | "{role:?} creator still manages the course" |
| @@ -1354,7 +1358,10 @@ mod tests { | ||
| 1354 | 1358 | // ...but never an owner, assigned or not. |
| 1355 | 1359 | assert!(!owns_course(&course, &assigned)); |
| 1356 | 1360 | |
| 1357 | - let demoted = crate::service::user::set_role(&db, assigned.get_id(), Role::Student).await.unwrap().0; | |
| 1361 | + let demoted = crate::service::user::set_role(&db, assigned.get_id(), Role::Student) | |
| 1362 | + .await | |
| 1363 | + .unwrap() | |
| 1364 | + .0; | |
| 1358 | 1365 | assert!(!can_manage_course(&course, &demoted)); |
| 1359 | 1366 | } |
| 1360 | 1367 | |
| @@ -1413,7 +1420,9 @@ mod tests { | ||
| 1413 | 1420 | let db = init_mem().await.unwrap(); |
| 1414 | 1421 | let creator = user("teacher", Role::Teacher, &db).await; |
| 1415 | 1422 | let course = course(&creator, &db).await; |
| 1416 | - crate::service::user::set_role(&db, creator.get_id(), Role::Student).await.unwrap(); | |
| 1423 | + crate::service::user::set_role(&db, creator.get_id(), Role::Student) | |
| 1424 | + .await | |
| 1425 | + .unwrap(); | |
| 1417 | 1426 | |
| 1418 | 1427 | for role in [Role::Manager, Role::Admin] { |
| 1419 | 1428 | let boss = user(&format!("boss{}", role.as_str()), role, &db).await; |
src/web/exams/mod.rsmodified+0 -1
| @@ -36,7 +36,6 @@ use crate::state::AppState; | ||
| 36 | 36 | |
| 37 | 37 | use super::bank_questions::BankQuestionResponse; |
| 38 | 38 | use super::courses::{can_manage_course, can_view_course, visible_courses}; |
| 39 | -use super::subjects::subject_in_course; | |
| 40 | 39 | use super::{ |
| 41 | 40 | ChoiceBody, CurrentUser, ExamResponse, ImageUpload, Page, PageParams, PersonRef, |
| 42 | 41 | RequireTeacher, Scheduled, UploadFileForm, WindowParams, blob_path, check_not_past, paginate, |
src/web/exams/questions.rsmodified+5 -3
| @@ -178,7 +178,7 @@ pub(crate) async fn create_question( | ||
| 178 | 178 | // freeze gate rides inside the insert's own transaction. |
| 179 | 179 | exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; |
| 180 | 180 | |
| 181 | - let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; | |
| 181 | + let subject = service::subject::in_course(&st.db, &req.subject_id, course.get_id()).await?; | |
| 182 | 182 | let text = QuestionText::try_new(&req.text)?; |
| 183 | 183 | let points = QuestionPoints::try_new(req.points)?; |
| 184 | 184 | // No stored choices to match against on create, so every option is new and |
| @@ -318,7 +318,9 @@ pub(crate) async fn update_question( | ||
| 318 | 318 | let question = exam_question::question_of_exam(exam.get_id(), &qid, &st.db).await?; |
| 319 | 319 | |
| 320 | 320 | let subject = match req.subject_id { |
| 321 | - Some(ref subject_id) => subject_in_course(subject_id, course.get_id(), &st.db).await?, | |
| 321 | + Some(ref subject_id) => { | |
| 322 | + service::subject::in_course(&st.db, subject_id, course.get_id()).await? | |
| 323 | + } | |
| 322 | 324 | None => question.get_subject().clone(), |
| 323 | 325 | }; |
| 324 | 326 | let text = match req.text { |
| @@ -475,7 +477,7 @@ pub(crate) async fn question_from_bank( | ||
| 475 | 477 | // No lease — same reasoning as `create_question`. The freeze gate rides in |
| 476 | 478 | // the insert's transaction. |
| 477 | 479 | exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; |
| 478 | - let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; | |
| 480 | + let subject = service::subject::in_course(&st.db, &req.subject_id, course.get_id()).await?; | |
| 479 | 481 | |
| 480 | 482 | let template = BankQuestion::read(&BankQuestionId::from_key(&bid), &st.db) |
| 481 | 483 | .await? |
src/web/homework.rsmodified+4 -3
| @@ -38,7 +38,6 @@ use crate::state::AppState; | ||
| 38 | 38 | |
| 39 | 39 | use super::courses::{can_manage_course, can_view_course, visible_courses}; |
| 40 | 40 | use super::notes::content_disposition; |
| 41 | -use super::subjects::subject_in_course; | |
| 42 | 41 | use super::{ |
| 43 | 42 | CurrentUser, HomeworkResponse, Page, PageParams, RequireTeacher, UploadFileForm, blob_path, |
| 44 | 43 | check_not_past, paginate, read_upload, remove_blob, set_or_clear, |
| @@ -73,7 +72,7 @@ use super::{ | ||
| 73 | 72 | /// |
| 74 | 73 | /// The subject rule has left: creating a homework and re-tagging one move the |
| 75 | 74 | /// subject's reference counter, and the subject delete is refused while that |
| 76 | -/// counter is non-zero ([`crate::domain::subject::Subject::delete`]), so | |
| 75 | +/// counter is non-zero ([`crate::db::subject::delete`]), so | |
| 77 | 76 | /// neither the create ([`super::courses`]) nor the outside writer the subject |
| 78 | 77 | /// delete used to take is on this list any more. |
| 79 | 78 | /// |
| @@ -372,7 +371,9 @@ async fn update_homework( | ||
| 372 | 371 | // A kept (absent) due date may already be past; a newly set one may not be. |
| 373 | 372 | check_not_past("due_at", due_at)?; |
| 374 | 373 | let subject = match req.subject_id { |
| 375 | - Some(ref subject_id) => Some(subject_in_course(subject_id, course.get_id(), &st.db).await?), | |
| 374 | + Some(ref subject_id) => { | |
| 375 | + Some(service::subject::in_course(&st.db, subject_id, course.get_id()).await?) | |
| 376 | + } | |
| 376 | 377 | None => None, |
| 377 | 378 | }; |
| 378 | 379 | // The orphan guard runs on exactly the requests that re-scope the audience. |
src/web/subjects.rsmodified+6 -45
| @@ -8,9 +8,10 @@ use utoipa_axum::router::OpenApiRouter; | ||
| 8 | 8 | use utoipa_axum::routes; |
| 9 | 9 | |
| 10 | 10 | use crate::database::Database; |
| 11 | -use crate::domain::course::{Course, CourseId}; | |
| 11 | +use crate::domain::course::Course; | |
| 12 | 12 | use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName}; |
| 13 | -use crate::error::{AppError, ErrorResponse, ValidationError}; | |
| 13 | +use crate::error::{AppError, ErrorResponse}; | |
| 14 | +use crate::service::subject; | |
| 14 | 15 | use crate::state::AppState; |
| 15 | 16 | |
| 16 | 17 | use super::courses::{can_manage_course, can_view_course}; |
| @@ -28,50 +29,10 @@ struct UpdateSubject { | ||
| 28 | 29 | description: Option<String>, |
| 29 | 30 | } |
| 30 | 31 | |
| 31 | -/// Turn a request-supplied subject id into a validated reference, provided the | |
| 32 | -/// subject belongs to `course` — a question may only be tagged with a subject | |
| 33 | -/// of its own exam's course. Unknown or foreign subjects are a `400` naming | |
| 34 | -/// the field. Shared by the question create/update handlers. | |
| 35 | -pub(crate) async fn subject_in_course( | |
| 36 | - id: &str, | |
| 37 | - course: &CourseId, | |
| 38 | - db: &Database, | |
| 39 | -) -> Result<SubjectId, AppError> { | |
| 40 | - let subject = | |
| 41 | - Subject::read(&SubjectId::from_key(id), db) | |
| 42 | - .await? | |
| 43 | - .ok_or(AppError::Validation(ValidationError::Invalid { | |
| 44 | - field: "subject_id", | |
| 45 | - reason: "subject does not exist", | |
| 46 | - }))?; | |
| 47 | - if subject.get_course() != course { | |
| 48 | - return Err(AppError::Validation(ValidationError::Invalid { | |
| 49 | - field: "subject_id", | |
| 50 | - reason: "subject belongs to a different course", | |
| 51 | - })); | |
| 52 | - } | |
| 53 | - Ok(subject.get_id().clone()) | |
| 54 | -} | |
| 55 | - | |
| 56 | -/// Turn a request-supplied subject id into a validated reference, checking only | |
| 57 | -/// that the subject exists — no course tie. For the question bank, whose subject | |
| 58 | -/// is cross-course origin metadata: the same-course rule applies at instantiate | |
| 59 | -/// time, not here. An unknown subject is a `400` naming the field. | |
| 60 | -pub(crate) async fn subject_must_exist(id: &str, db: &Database) -> Result<SubjectId, AppError> { | |
| 61 | - let subject = | |
| 62 | - Subject::read(&SubjectId::from_key(id), db) | |
| 63 | - .await? | |
| 64 | - .ok_or(AppError::Validation(ValidationError::Invalid { | |
| 65 | - field: "subject_id", | |
| 66 | - reason: "subject does not exist", | |
| 67 | - }))?; | |
| 68 | - Ok(subject.get_id().clone()) | |
| 69 | -} | |
| 70 | - | |
| 71 | 32 | /// The subject plus its course, or a 404 — every handler here gates on the |
| 72 | 33 | /// parent course, so they always travel together. |
| 73 | 34 | async fn subject_with_course(id: &str, db: &Database) -> Result<(Subject, Course), AppError> { |
| 74 | - let subject = Subject::read(&SubjectId::from_key(id), db) | |
| 35 | + let subject = subject::read(db, &SubjectId::from_key(id)) | |
| 75 | 36 | .await? |
| 76 | 37 | .ok_or(AppError::NotFound)?; |
| 77 | 38 | let course = crate::service::course::read(db, subject.get_course()) |
| @@ -154,7 +115,7 @@ async fn update_subject( | ||
| 154 | 115 | .map(SubjectDescription::try_new) |
| 155 | 116 | .transpose()?; |
| 156 | 117 | |
| 157 | - let updated = subject.update(name, description, &st.db).await?; | |
| 118 | + let updated = subject::update(&st.db, subject, name, description).await?; | |
| 158 | 119 | Ok(Json(SubjectResponse::new(&updated))) |
| 159 | 120 | } |
| 160 | 121 | |
| @@ -199,6 +160,6 @@ async fn delete_subject( | ||
| 199 | 160 | // three process-wide locks (the only site that held more than one) around |
| 200 | 161 | // two cross-table counts, which were stale by the time the delete landed and |
| 201 | 162 | // let a concurrent request create a question on a subject being deleted. |
| 202 | - subject.delete(&st.db).await?; | |
| 163 | + subject::delete(&st.db, subject).await?; | |
| 203 | 164 | Ok(StatusCode::NO_CONTENT) |
| 204 | 165 | } |
src/web/terms.rsmodified+18 -52
| @@ -7,10 +7,10 @@ use utoipa::ToSchema; | ||
| 7 | 7 | use utoipa_axum::router::OpenApiRouter; |
| 8 | 8 | use utoipa_axum::routes; |
| 9 | 9 | |
| 10 | -use crate::database::Database; | |
| 11 | -use crate::domain::term::{self, Term, TermId, TermName}; | |
| 10 | +use crate::domain::term::{Term, TermId, TermName}; | |
| 12 | 11 | use crate::domain::timestamp::Timestamp; |
| 13 | -use crate::error::{AppError, ErrorResponse, ValidationError}; | |
| 12 | +use crate::error::{AppError, ErrorResponse}; | |
| 13 | +use crate::service; | |
| 14 | 14 | use crate::state::AppState; |
| 15 | 15 | |
| 16 | 16 | use super::{CurrentUser, Page, PageParams, RequireManager, check_time_range}; |
| @@ -69,31 +69,6 @@ impl TermResponse { | ||
| 69 | 69 | } |
| 70 | 70 | } |
| 71 | 71 | |
| 72 | -/// Turn an optional request-supplied term id into a validated reference — | |
| 73 | -/// `None` stays `None`, an unknown id is a `400` naming the field, and an | |
| 74 | -/// *archived* one is a `409 term_archived`. That last refusal is here rather | |
| 75 | -/// than in each handler because this is the single spot every new link to a | |
| 76 | -/// term passes through — course create/update and class create/update alike: | |
| 77 | -/// past years take no new structure. | |
| 78 | -pub(crate) async fn resolve_term( | |
| 79 | - id: Option<&str>, | |
| 80 | - db: &Database, | |
| 81 | -) -> Result<Option<TermId>, AppError> { | |
| 82 | - let Some(id) = id else { | |
| 83 | - return Ok(None); | |
| 84 | - }; | |
| 85 | - let term = Term::read(&TermId::from_key(id), db) | |
| 86 | - .await? | |
| 87 | - .ok_or(AppError::Validation(ValidationError::Invalid { | |
| 88 | - field: "term_id", | |
| 89 | - reason: "term does not exist", | |
| 90 | - }))?; | |
| 91 | - if term.is_archived() { | |
| 92 | - return Err(term::archived_error()); | |
| 93 | - } | |
| 94 | - Ok(Some(term.get_id().clone())) | |
| 95 | -} | |
| 96 | - | |
| 97 | 72 | /// Create an academic term. Requires manager+. Past dates are allowed — |
| 98 | 73 | /// terms are calendar structure, not schedules. |
| 99 | 74 | #[utoipa::path( |
| @@ -119,7 +94,7 @@ async fn create_term( | ||
| 119 | 94 | let starts_at = Timestamp::from_millis(req.starts_at); |
| 120 | 95 | let ends_at = Timestamp::from_millis(req.ends_at); |
| 121 | 96 | check_time_range(Some(starts_at), Some(ends_at))?; |
| 122 | - let term = Term::create(name, starts_at, ends_at, &st.db).await?; | |
| 97 | + let term = service::term::create(&st.db, name, starts_at, ends_at).await?; | |
| 123 | 98 | Ok((StatusCode::CREATED, Json(TermResponse::new(&term)))) |
| 124 | 99 | } |
| 125 | 100 | |
| @@ -145,7 +120,7 @@ async fn list_terms( | ||
| 145 | 120 | Query(page): Query<PageParams>, |
| 146 | 121 | ) -> Result<Json<Page<TermResponse>>, AppError> { |
| 147 | 122 | let (limit, offset) = page.resolve()?; |
| 148 | - let (terms, total) = Term::list_all(limit, offset, &st.db).await?; | |
| 123 | + let (terms, total) = service::term::list_all(&st.db, limit, offset).await?; | |
| 149 | 124 | let items = terms.iter().map(TermResponse::new).collect(); |
| 150 | 125 | Ok(Json(Page::new(items, total, limit, offset))) |
| 151 | 126 | } |
| @@ -168,7 +143,7 @@ async fn get_term( | ||
| 168 | 143 | CurrentUser(_user): CurrentUser, |
| 169 | 144 | Path(id): Path<String>, |
| 170 | 145 | ) -> Result<Json<TermResponse>, AppError> { |
| 171 | - let term = Term::read(&TermId::from_key(&id), &st.db) | |
| 146 | + let term = service::term::read(&st.db, &TermId::from_key(&id)) | |
| 172 | 147 | .await? |
| 173 | 148 | .ok_or(AppError::NotFound)?; |
| 174 | 149 | Ok(Json(TermResponse::new(&term))) |
| @@ -203,21 +178,18 @@ async fn update_term( | ||
| 203 | 178 | let starts_at = req.starts_at.map(Timestamp::from_millis); |
| 204 | 179 | let ends_at = req.ends_at.map(Timestamp::from_millis); |
| 205 | 180 | |
| 206 | - let term = Term::read(&TermId::from_key(&id), &st.db) | |
| 181 | + let term = service::term::read(&st.db, &TermId::from_key(&id)) | |
| 207 | 182 | .await? |
| 208 | 183 | .ok_or(AppError::NotFound)?; |
| 209 | - if term.is_archived() { | |
| 210 | - return Err(term::archived_error()); | |
| 211 | - } | |
| 212 | - // Pre-flight only: the range check is re-made inside the UPDATE's `WHERE` | |
| 213 | - // (`Term::update`), so a concurrent move of the end this PATCH omits cannot | |
| 214 | - // slip an inverted range past this snapshot. | |
| 184 | + // Pre-flight only: the range check is re-made inside the UPDATE's own | |
| 185 | + // `WHERE` (the term update in the db layer), so a concurrent move of the | |
| 186 | + // end this PATCH omits cannot slip an inverted range past this snapshot. | |
| 215 | 187 | check_time_range( |
| 216 | 188 | Some(starts_at.unwrap_or_else(|| term.get_starts_at())), |
| 217 | 189 | Some(ends_at.unwrap_or_else(|| term.get_ends_at())), |
| 218 | 190 | )?; |
| 219 | 191 | |
| 220 | - let updated = term.update(name, starts_at, ends_at, &st.db).await?; | |
| 192 | + let updated = service::term::update(&st.db, term, name, starts_at, ends_at).await?; | |
| 221 | 193 | Ok(Json(TermResponse::new(&updated))) |
| 222 | 194 | } |
| 223 | 195 | |
| @@ -244,17 +216,11 @@ async fn delete_term( | ||
| 244 | 216 | RequireManager(_user): RequireManager, |
| 245 | 217 | Path(id): Path<String>, |
| 246 | 218 | ) -> Result<StatusCode, AppError> { |
| 247 | - let term = Term::read(&TermId::from_key(&id), &st.db) | |
| 219 | + let term = service::term::read(&st.db, &TermId::from_key(&id)) | |
| 248 | 220 | .await? |
| 249 | 221 | .ok_or(AppError::NotFound)?; |
| 250 | - if term.is_archived() { | |
| 251 | - return Err(term::archived_error()); | |
| 252 | - } | |
| 253 | - if !term.delete(&st.db).await? { | |
| 254 | - return Err(AppError::Conflict( | |
| 255 | - "courses are still linked to this term — unlink them first", | |
| 256 | - )); | |
| 257 | - } | |
| 222 | + service::term::require_writable(&term)?; | |
| 223 | + service::term::delete(&st.db, term).await?; | |
| 258 | 224 | Ok(StatusCode::NO_CONTENT) |
| 259 | 225 | } |
| 260 | 226 | |
| @@ -279,10 +245,10 @@ async fn archive_term( | ||
| 279 | 245 | RequireManager(_user): RequireManager, |
| 280 | 246 | Path(id): Path<String>, |
| 281 | 247 | ) -> Result<Json<TermResponse>, AppError> { |
| 282 | - let term = Term::read(&TermId::from_key(&id), &st.db) | |
| 248 | + let term = service::term::read(&st.db, &TermId::from_key(&id)) | |
| 283 | 249 | .await? |
| 284 | 250 | .ok_or(AppError::NotFound)?; |
| 285 | - let archived = term.archive(&st.db).await?; | |
| 251 | + let archived = service::term::archive(&st.db, term).await?; | |
| 286 | 252 | Ok(Json(TermResponse::new(&archived))) |
| 287 | 253 | } |
| 288 | 254 | |
| @@ -306,9 +272,9 @@ async fn unarchive_term( | ||
| 306 | 272 | RequireManager(_user): RequireManager, |
| 307 | 273 | Path(id): Path<String>, |
| 308 | 274 | ) -> Result<Json<TermResponse>, AppError> { |
| 309 | - let term = Term::read(&TermId::from_key(&id), &st.db) | |
| 275 | + let term = service::term::read(&st.db, &TermId::from_key(&id)) | |
| 310 | 276 | .await? |
| 311 | 277 | .ok_or(AppError::NotFound)?; |
| 312 | - let reopened = term.unarchive(&st.db).await?; | |
| 278 | + let reopened = service::term::unarchive(&st.db, term).await?; | |
| 313 | 279 | Ok(Json(TermResponse::new(&reopened))) |
| 314 | 280 | } |
tests/regress_course_child_orphans.rsmodified+5 -5
| @@ -12,7 +12,7 @@ | ||
| 12 | 12 | //! lists it to every manager+ — undeletable, |
| 13 | 13 | //! - an orphan `course_session` 404s forever through `session_with_course`, |
| 14 | 14 | //! - an orphan `subject` 404s through `subject_with_course`, but |
| 15 | -//! `subject_must_exist` still accepts its id, so a bank template can be | |
| 15 | +//! `must_exist` still accepts its id, so a bank template can be | |
| 16 | 16 | //! tagged with a subject nobody can reach. |
| 17 | 17 | //! |
| 18 | 18 | //! All three creates now go through `cap::touch_and_create`, which *moves* the |
| @@ -33,7 +33,7 @@ | ||
| 33 | 33 | //! per child beside the create it pins — |
| 34 | 34 | //! `db::exam::tests::an_exam_never_outlives_its_course`, |
| 35 | 35 | //! `db::course_session::tests::a_session_never_outlives_its_course`, |
| 36 | -//! `domain::subject::tests::a_subject_never_outlives_its_course` — over the | |
| 36 | +//! `db::subject::tests::a_subject_never_outlives_its_course` — over the | |
| 37 | 37 | //! shared harness `db::course::assert_no_child_outlives_a_course_delete`. |
| 38 | 38 | //! It is `#[ignore]`d and needs a real server, because the subject there *is* |
| 39 | 39 | //! the store's conflict detection, which the embedded engine does not have: it |
| @@ -58,7 +58,7 @@ use hezarfen_backend::domain::exam::{ | ||
| 58 | 58 | ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle, |
| 59 | 59 | }; |
| 60 | 60 | use hezarfen_backend::domain::settings::Settings; |
| 61 | -use hezarfen_backend::domain::subject::{Subject, SubjectDescription, SubjectName}; | |
| 61 | +use hezarfen_backend::domain::subject::{SubjectDescription, SubjectName}; | |
| 62 | 62 | use hezarfen_backend::domain::timestamp::Timestamp; |
| 63 | 63 | use hezarfen_backend::domain::user::UserId; |
| 64 | 64 | use hezarfen_backend::error::AppError; |
| @@ -138,11 +138,11 @@ fn make_session(course: CourseId, db: Database) -> JoinHandle<Result<(), AppErro | ||
| 138 | 138 | |
| 139 | 139 | fn make_subject(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>> { |
| 140 | 140 | tokio::spawn(async move { |
| 141 | - Subject::create( | |
| 141 | + hezarfen_backend::db::subject::create( | |
| 142 | + &db, | |
| 142 | 143 | &course, |
| 143 | 144 | SubjectName::try_new("Limits").unwrap(), |
| 144 | 145 | SubjectDescription::try_new("").unwrap(), |
| 145 | - &db, | |
| 146 | 146 | ) |
| 147 | 147 | .await |
| 148 | 148 | .map(|_| ()) |
tests/regress_course_delete.rsmodified+1 -1
| @@ -47,7 +47,7 @@ async fn drop_course(db: &hezarfen_backend::database::Database, course: &str) { | ||
| 47 | 47 | |
| 48 | 48 | /// A bank template outlives the course it was saved out of — it is a separate, |
| 49 | 49 | /// school-wide library — so the cascade owes it the same cleanup its children's |
| 50 | -/// own deletes perform: `Exam::delete` clears `source_exam`, `Subject::delete` | |
| 50 | +/// own deletes perform: `Exam::delete` clears `source_exam`, `db::subject::delete` | |
| 51 | 51 | /// clears `subject`. The course cascade deleted both rows and neither link, |
| 52 | 52 | /// leaving a template pointing at two ids that no longer exist — the |
| 53 | 53 | /// `source_exam` one forever (nothing else ever visits that column) and the |