diff --git a/src/db/course.rs b/src/db/course.rs index 48e48dd..ce47891 100644 --- a/src/db/course.rs +++ b/src/db/course.rs @@ -262,7 +262,7 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App /// spanning every course — so their `source_exam` and `subject` links are /// cleared instead, in this same transaction, exactly as /// [`crate::db::exam::delete`] and -/// [`crate::domain::subject::Subject::delete`] clear them one level down. +/// [`crate::db::subject::delete`] clear them one level down. /// Deleting a course must leave the bank where deleting each of its exams /// and subjects by hand would have left it, or a template is left pointing /// at a dead exam (permanently: nothing else ever visits that column) and @@ -561,14 +561,15 @@ mod tests { async fn a_term_is_deletable_only_once_no_course_links_it() { let db = crate::database::init_mem().await.unwrap(); let at = crate::domain::timestamp::Timestamp::from_millis; - let term = Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), &db) - .await - .unwrap(); + let term = + crate::db::term::create(&db, TermName::try_new("2026").unwrap(), at(100), at(200)) + .await + .unwrap(); let linked = course_on(Some(term.get_id().clone()), &db).await; let patched = course_on(Some(term.get_id().clone()), &db).await; assert!( - !term.clone().delete(&db).await.unwrap(), + !crate::db::term::delete(&db, term.clone()).await.unwrap(), "two linked courses must refuse the delete" ); @@ -576,16 +577,16 @@ mod tests { .await .unwrap(); assert!( - !term.clone().delete(&db).await.unwrap(), + !crate::db::term::delete(&db, term.clone()).await.unwrap(), "one link is still one link" ); assert!(delete(&db, linked).await.unwrap()); assert!( - term.clone().delete(&db).await.unwrap(), + crate::db::term::delete(&db, term.clone()).await.unwrap(), "the last link gone, the term may go" ); - let again = term.delete(&db).await; + let again = crate::db::term::delete(&db, term).await; assert!( matches!(again, Err(AppError::NotFound)), "a second delete is a 404, not a refusal: {again:?}" @@ -639,7 +640,7 @@ mod tests { async fn a_term(name: &str, db: &Database) -> Term { let at = crate::domain::timestamp::Timestamp::from_millis; - Term::create(TermName::try_new(name).unwrap(), at(100), at(200), db) + crate::db::term::create(db, TermName::try_new(name).unwrap(), at(100), at(200)) .await .unwrap() } @@ -654,7 +655,7 @@ mod tests { let db = crate::database::init_mem().await.unwrap(); let term = a_term("2026", &db).await; let id = term.get_id().clone(); - assert!(term.delete(&db).await.unwrap()); + assert!(crate::db::term::delete(&db, term).await.unwrap()); let error = create( &db, @@ -708,8 +709,8 @@ mod tests { "the old term is free" ); assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); - assert!(from.clone().delete(&db).await.unwrap()); - assert!(!to.clone().delete(&db).await.unwrap()); + assert!(crate::db::term::delete(&db, from.clone()).await.unwrap()); + assert!(!crate::db::term::delete(&db, to.clone()).await.unwrap()); } /// The double-claim guard. Both movers compute their claim and release from @@ -887,7 +888,7 @@ mod tests { let from = a_term("2026", &db).await; let dead = a_term("2027", &db).await; let dead_id = dead.get_id().clone(); - assert!(dead.delete(&db).await.unwrap()); + assert!(crate::db::term::delete(&db, dead).await.unwrap()); let course = course_on(Some(from.get_id().clone()), &db).await; let error = update( diff --git a/src/db/exam.rs b/src/db/exam.rs index f8d639a..b27d4cd 100644 --- a/src/db/exam.rs +++ b/src/db/exam.rs @@ -749,11 +749,11 @@ mod tests { &[], ) .unwrap(); - let subject = crate::domain::subject::Subject::create( + let subject = crate::db::subject::create( + db, &crate::db::course::a_test_course(db).await, crate::domain::subject::SubjectName::try_new("topic").unwrap(), crate::domain::subject::SubjectDescription::try_new("").unwrap(), - db, ) .await .unwrap(); @@ -863,7 +863,7 @@ mod tests { /// The same defect on the teacher's side of the sheet, and a worse one: a /// question written inside the delete window kept the reference it claimed /// on its subject (the cascade's per-subject decrement counted only the - /// rows it could see), and [`crate::domain::subject::Subject::delete`] is + /// rows it could see), and [`crate::db::subject::delete`] is /// gated on that count reading zero — a subject nobody could ever delete /// again, hanging off an exam nobody could ever see. The freeze gate is a /// *read* of `exam_attempt` and never survived this window; @@ -878,7 +878,6 @@ mod tests { use crate::domain::exam_question::{ ChoiceInput, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, }; - use crate::domain::subject::Subject; let (db, _serialized) = crate::database::init_test_server("exam_question_race").await; db.query( "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \ @@ -893,11 +892,11 @@ mod tests { for round in 0..4 { let exam = published(&db).await; let id = exam.get_id().clone(); - let subject = Subject::create( + let subject = crate::db::subject::create( + &db, &crate::db::course::a_test_course(&db).await, crate::domain::subject::SubjectName::try_new("topic").unwrap(), crate::domain::subject::SubjectDescription::try_new("").unwrap(), - &db, ) .await .unwrap(); @@ -952,13 +951,15 @@ mod tests { .len(); // The subject has to be free again: a stranded reference is the // half of this bug a row count alone would not catch. - if Subject::read(subject.get_id(), &db) - .await - .unwrap() - .unwrap() - .delete(&db) - .await - .is_err() + if crate::db::subject::delete( + &db, + crate::db::subject::read(&db, subject.get_id()) + .await + .unwrap() + .unwrap(), + ) + .await + .is_err() { stuck += 1; } diff --git a/src/db/exam_attempt.rs b/src/db/exam_attempt.rs index 0e07a1b..1a0e68c 100644 --- a/src/db/exam_attempt.rs +++ b/src/db/exam_attempt.rs @@ -177,7 +177,7 @@ pub async fn any_for_exam(db: &Database, exam: &ExamId) -> Result Subject { - Subject::create( + crate::db::subject::create( + db, &crate::db::course::a_test_course(db).await, SubjectName::try_new("topic").unwrap(), SubjectDescription::try_new("").unwrap(), - db, ) .await .unwrap() @@ -544,7 +544,7 @@ mod tests { let exam = an_exam(&db).await; let subject = a_subject(&db).await; let id = subject.get_id().clone(); - subject.delete(&db).await.unwrap(); + crate::db::subject::delete(&db, subject).await.unwrap(); let (text, points, spec) = body(); let error = create(&db, exam.get_id(), id, text, points, spec) @@ -584,7 +584,7 @@ mod tests { let from = a_subject(&db).await.get_id().clone(); let dead = a_subject(&db).await; let gone = dead.get_id().clone(); - dead.delete(&db).await.unwrap(); + crate::db::subject::delete(&db, dead).await.unwrap(); let question = a_question(&exam, &from, &db).await; let error = moved(question.clone(), &gone, &db) diff --git a/src/db/mod.rs b/src/db/mod.rs index 0907e20..4780c07 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -25,5 +25,7 @@ pub mod profile; pub mod registration; pub mod session; pub mod settings; +pub mod subject; +pub mod term; pub mod user; pub mod work_entry; diff --git a/src/db/subject.rs b/src/db/subject.rs new file mode 100644 index 0000000..71389d8 --- /dev/null +++ b/src/db/subject.rs @@ -0,0 +1,350 @@ +//! The `subject` table: the count-and-create that pins a topic to a live +//! course row, the bulk id listing, the field-scoped PATCH, and the guarded +//! delete whose `WHERE` reads the row's own reference counters. The type and +//! its validation live in [`crate::domain::subject`]. + +use surrealdb::types::{RecordId, SurrealValue}; + +use crate::constant::ENROLLMENT_COUNT_FIELD; +use crate::database::{Database, transaction_with_retry}; +use crate::db::cap; +use crate::db::field_update::FieldUpdate; +use crate::db::page::PagedList; +use crate::domain::course::CourseId; +use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName}; +use crate::error::AppError; + +pub async fn create( + db: &Database, + course: &CourseId, + name: SubjectName, + description: SubjectDescription, +) -> Result { + let subject = Subject { + id: SubjectId::generate(), + course: course.clone(), + name, + description, + }; + // The course row is *written* (bumped and put back), not read, so this + // collides with `Course::delete`'s cascade: a topic that outlives its + // course 404s through `subject_with_course` forever, while + // `must_exist` still accepts its id — so a bank template can be + // tagged with a subject nobody can reach. See [`cap::touch_and_create`]. + cap::touch_and_create( + &course.record(), + ENROLLMENT_COUNT_FIELD, + &subject.id.record(), + &subject, + db, + ) + .await? + .ok_or(AppError::NotFound) +} + +pub async fn read(db: &Database, id: &SubjectId) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +/// Several subjects in one query — the bulk half of a list endpoint that +/// names each row's subject (a read per row would be an N+1). +pub async fn list_by_ids(db: &Database, ids: &[&SubjectId]) -> Result, AppError> { + if ids.is_empty() { + return Ok(Vec::new()); + } + let records: Vec = ids.iter().map(|id| id.record()).collect(); + let mut result = db + .query("SELECT * FROM subject WHERE id IN $ids") + .bind(("ids", records)) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// The course's subjects in curriculum order (ULID ids sort by creation). +pub async fn list_for_course( + db: &Database, + course: &CourseId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new("subject WHERE course = $course", "ORDER BY id ASC") + .bind("course", course.record()) + .run(limit, offset, db) + .await +} + +/// Request-scoped: no lock spans the handler's read and this write, so an +/// omitted field (`None`) is not written at all. Passing the snapshot's +/// value back instead would revert a concurrent edit of that field — +/// scoping the `SET` alone does not prevent that, the values have to come +/// from the request. Neither column is nullable, so plain `Option` per +/// field says everything there is to say. +pub async fn update( + db: &Database, + subject: Subject, + name: Option, + description: Option, +) -> Result { + FieldUpdate::new(subject.id.record()) + .set("name", name) + .set("description", description) + .run::(db) + .await +} + +/// Delete the subject and clear it off every bank template that carried it +/// as origin metadata — one transaction, so a template can't be left +/// pointing at a subject that no longer exists. +/// +/// Exam questions and homework are *not* cascaded: their `subject` is a +/// required field that may not be orphaned, so either one still refuses the +/// delete with a 409. That refusal is the delete's own `WHERE`, read off the +/// two reference counters this row carries +/// ([`crate::constant::SUBJECT_QUESTION_COUNT_FIELD`] and its homework +/// twin), which is what makes it hold against a question created by a +/// request racing this one — the cross-table `SELECT … LIMIT 1` it replaces +/// was a count-then-delete no transaction serializes, pinned by three +/// process-wide locks that could not cover the round trip between them. +/// +/// Which of the two blocked is read off the counters *before* the delete, +/// purely to pick the message; the decision itself was already made by the +/// `WHERE`. +/// +/// The bank's subject is optional metadata, and blocking on it was a dead +/// end — only the template's owner may re-tag it, so a manager could never +/// clear their own 409, and a private template raising it leaked its +/// existence. Its cascade runs *after* the conditional delete, so a refused +/// delete leaves every template's subject where it was. +pub async fn delete(db: &Database, subject: Subject) -> Result { + let (mut result, mut errors) = transaction_with_retry( + db, + "BEGIN TRANSACTION; + LET $held = (SELECT exam_question_count AS q, homework_count AS h FROM $sub); + LET $before = (DELETE $sub + WHERE (exam_question_count ?? 0) = 0 AND (homework_count ?? 0) = 0 + RETURN BEFORE); + IF array::len($before) = 0 { + THROW IF array::len($held) = 0 { 'subject_missing' } + ELSE IF ($held[0].q ?? 0) > 0 { 'subject_questions' } + ELSE { 'subject_homework' } + }; + UPDATE bank_question SET subject = NONE WHERE subject = $sub; + RETURN $before; + COMMIT TRANSACTION;", + &[("sub".into(), subject.id.record().into_value())], + &["subject_missing", "subject_questions", "subject_homework"], + ) + .await?; + // An aborted transaction errors every slot; only the THROW's own slot + // names the marker (the [`crate::db::appointment_slot`] treatment), + // and a lost round is re-sent rather than reported. + let thrown = |marker: &str| { + errors + .values() + .any(|error| error.to_string().contains(marker)) + }; + if thrown("subject_questions") { + return Err(AppError::Conflict( + "exam questions still reference this subject — re-tag or delete them first", + )); + } + if thrown("subject_homework") { + return Err(AppError::Conflict( + "homework still references this subject — re-tag or delete it first", + )); + } + if thrown("subject_missing") { + return Err(AppError::NotFound); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Read through the trailing `RETURN`, not a counted slot — see + // [`crate::db::exam::delete`]. + let slot = result.num_statements().saturating_sub(2); + let deleted: Option = result.take::>(slot)?.into_iter().next(); + deleted.ok_or(AppError::NotFound) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::constant::SUBJECT_TABLE; + + /// A curriculum topic must not outlive its course: an orphan 404s through + /// `subject_with_course`, and worse than the sibling cases, + /// `must_exist` still *accepts* its id — so a bank template can be + /// tagged with a subject nobody can reach. + /// + /// [`create`] therefore *writes* the course row rather than + /// reading it ([`cap::touch_and_create`]); the harness and the window it + /// races in are documented on + /// [`crate::db::course::assert_no_child_outlives_a_course_delete`]. + /// Mutation-tested: with the bare `db.create` this shipped with, all four + /// rounds orphan. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_subject_never_outlives_its_course() { + fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle> { + tokio::spawn(async move { + create( + &db, + &course, + SubjectName::try_new("Limits").unwrap(), + SubjectDescription::try_new("").unwrap(), + ) + .await + .map(|_| ()) + }) + } + crate::db::course::assert_no_child_outlives_a_course_delete( + "subject_orphan_race", + SUBJECT_TABLE, + make, + ) + .await; + } + + /// GUARD, not a retry measurement — read the last paragraph before + /// trusting this test with the retry. See + /// [`crate::db::course::delete`]'s race test for why the rate + /// is counted rather than asserted per round, and why this needs the real + /// server and a multi-threaded runtime. + /// + /// The racer is [`crate::db::exam_question::create`], which claims the subject's + /// question reference *before* it writes the row — a conditional write on + /// the same record the delete's `WHERE` reads. `Err(Conflict)` (still + /// referenced), `Err(NotFound)` and the claim's `Validation` miss are all + /// correct answers; only `AppError::Db` is the defect. What the two stored + /// counters below assert is that the sweep genuinely straddled the site: + /// some rounds the claims won, some rounds the delete did. + /// + /// What it does *not* prove is the retry. The 500 window here is the delete + /// passing its `WHERE` and then committing while a claim is in flight, and + /// this cascade is three statements long — measured at 0 conflicts in 100 + /// raced rounds, and the whole test stays green with + /// [`crate::database::transaction_with_retry`]'s loop cut to a single + /// attempt. Widening the sweep, staggering the burst and doubling it to 12 + /// racers all failed to open the window (they only move which side wins). + /// So this is a status-code-and-cascade guard: a raced delete answers 409 or + /// 404 and never 500, and a landed question survives it. The retry itself is + /// measured on [`crate::db::course::delete`], whose cascade is + /// long enough to lose a round (1-2 of 20, red under the same mutation). + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_delete_racing_a_question_never_answers_500() { + use crate::domain::exam_question::{ + QuestionKind, QuestionPoints, QuestionSpec, QuestionText, + }; + let (db, _serialized) = crate::database::init_test_server("subject_delete_race").await; + let (mut delete_500, mut question_500) = (0, 0); + let (mut landed, mut wiped) = (0, 0); + let (mut last_delete, mut last_question) = (String::new(), String::new()); + for round in 0..20 { + let course = crate::db::course::a_test_course(&db).await; + // A real exam row per round: a question write moves its exam's + // counter, so a minted id nothing wrote is a 404 and no round would + // reach the subject race this test is about. + let exam = crate::db::exam::published_exam(&db).await.get_id().clone(); + let subject = create( + &db, + &course, + SubjectName::try_new("Limits").unwrap(), + SubjectDescription::try_new("").unwrap(), + ) + .await + .unwrap(); + + let separated = round % 4 == 0; + let drop_it = { + let (subject, db) = (subject.clone(), db.clone()); + // One round in four holds the racers back by a clear 2ms so the + // delete wins outright: the sub-millisecond sweep alone leaves + // them ahead of it nearly every round (measured 20 to 0), and + // both counters below have to see a side. The other three keep + // the sub-ms beat, which is the only spacing that overlaps at + // all — a whole millisecond either way separates them. + let beat = if separated { + std::time::Duration::ZERO + } else { + std::time::Duration::from_micros(round * 53 % 300) + }; + tokio::spawn(async move { + tokio::time::sleep(beat).await; + delete(&db, subject).await + }) + }; + let asks: Vec<_> = (0..6) + .map(|_| { + let (id, db, exam) = (subject.get_id().clone(), db.clone(), exam.clone()); + let head_start = if separated { + std::time::Duration::from_millis(2) + } else { + std::time::Duration::from_micros(round * 37 % 300) + }; + tokio::spawn(async move { + tokio::time::sleep(head_start).await; + crate::db::exam_question::create( + &db, + &exam, + id, + QuestionText::try_new("why").unwrap(), + QuestionPoints::try_new(1).unwrap(), + QuestionSpec::try_new( + QuestionKind::try_new("text").unwrap(), + None, + None, + &[], + ) + .unwrap(), + ) + .await + }) + }) + .collect(); + let drop_it = drop_it.await.unwrap(); + if matches!(drop_it, Err(AppError::Db(_))) { + delete_500 += 1; + last_delete = format!("{drop_it:?}"); + } + for ask in asks { + let ask = ask.await.unwrap(); + if matches!(ask, Err(AppError::Db(_))) { + question_500 += 1; + last_question = format!("{ask:?}"); + } + } + // Stored state, and both sides are needed: a question landing means + // the claim beat the guard, the subject being gone means the delete + // did. Seeing only one is a run that never swept across the window. + if read(&db, subject.get_id()).await.unwrap().is_none() { + wiped += 1; + } + if !crate::db::exam_question::list_for_exam(&db, &exam, None, 0) + .await + .unwrap() + .0 + .is_empty() + { + landed += 1; + } + } + eprintln!( + "Subject::delete raced: {delete_500}/20 delete 500s, {question_500} question 500s, \ + {landed} rounds with a question landed / {wiped} wiped" + ); + assert!( + landed > 0 && wiped > 0, + "the sweep never crossed the window ({landed} landed / {wiped} wiped)" + ); + assert_eq!( + delete_500, 0, + "a raced delete must be refused, not 500: {delete_500}/20 rounds, last {last_delete}" + ); + assert_eq!( + question_500, 0, + "a raced question create must retry, not 500: {question_500}/20 rounds, last {last_question}" + ); + } +} diff --git a/src/db/term.rs b/src/db/term.rs new file mode 100644 index 0000000..8b21ac0 --- /dev/null +++ b/src/db/term.rs @@ -0,0 +1,352 @@ +//! The `term` table: the row mint, the paged calendar listing, the +//! field-scoped PATCH whose `WHERE` re-checks the merged range, the delete +//! guarded by the row's own reference counters, and the archive/unarchive +//! stamps. The type and the errors its guards hand out live in +//! [`crate::domain::term`]. + +use surrealdb::types::SurrealValue; + +use crate::constant::{COURSE_COUNT_FIELD, TERM_CLASS_COUNT_FIELD}; +use crate::database::{Database, write_with_retry}; +use crate::db::field_update::FieldUpdate; +use crate::db::page::PagedList; +use crate::domain::term::{Term, TermId, TermName}; +use crate::domain::timestamp::{Timestamp, range_error}; +use crate::error::AppError; + +pub async fn create( + db: &Database, + name: TermName, + starts_at: Timestamp, + ends_at: Timestamp, +) -> Result { + let term = Term { + id: TermId::generate(), + name, + starts_at, + ends_at, + archived_at: None, + }; + let created: Option = db.create(term.id.record()).content(term).await?; + created.ok_or_else(|| AppError::Internal("failed to create term".into())) +} + +pub async fn read(db: &Database, id: &TermId) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +/// Every term, newest first — the school calendar is small by nature. +pub async fn list_all( + db: &Database, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new("term", "ORDER BY starts_at DESC, id DESC") + .run(limit, offset, db) + .await +} + +/// Write only the fields the PATCH carried — `None` means the request +/// omitted it, so the column is left alone rather than re-stated from the +/// snapshot this struct was read into. All three columns are non-nullable, +/// so "absent" and "null" both correctly mean "keep". +pub async fn update( + db: &Database, + term: Term, + name: Option, + starts_at: Option, + ends_at: Option, +) -> Result { + FieldUpdate::new(term.id.record()) + .set("name", name) + .set("starts_at", starts_at) + .set("ends_at", ends_at) + .ordered("starts_at", "ends_at", range_error()) + .run::(db) + .await +} + +/// Delete the term, but only while no course *and no class* links it — +/// nothing here unlinks or cascades. `false` = refused, nothing was written. +/// +/// The roster of linking courses is the term's own `course_count` +/// refcount, claimed by [`crate::db::course::create`] and +/// `update` *before* they write a link, so the check and the delete are one +/// conditional write on one record: a course write racing this either +/// claims first (and the delete is refused) or finds the row gone (and is +/// refused itself, with the same 400 the lookup gives). `Err(NotFound)` +/// keeps the answer a concurrent *delete* used to get. +/// +/// Classes ([`crate::domain::class_group::ClassGroup`]) link a term the same +/// way and count on `class_count` — a column of their own, because +/// `course_count` is seeded at boot from the course rows alone. +pub async fn delete(db: &Database, term: Term) -> Result { + let sql = format!( + "DELETE $term WHERE ({COURSE_COUNT_FIELD} ?? 0) = 0 \ + AND ({TERM_CLASS_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE" + ); + // Through the retry, because the guard reads the very column a course + // create claims: a lost round writes nothing, and re-sending it is what + // keeps the answer the 404 or 409 it owes instead of a 500. + let gone: Vec = + write_with_retry(db, &sql, &[("term".into(), term.id.record().into_value())]).await?; + if !gone.is_empty() { + return Ok(true); + } + // Still linked or already gone: the one statement cannot tell those + // apart, and only the refusal path pays for the read that can. + match read(db, &term.id).await? { + Some(_) => Ok(false), + None => Err(AppError::NotFound), + } +} + +/// Freeze the term. Idempotent by construction: the `WHERE` only matches an +/// open row, so a repeat archive writes nothing and answers with the +/// *original* stamp — the year is not re-dated by a double click. +pub async fn archive(db: &Database, term: Term) -> Result { + stamp( + db, + term, + "UPDATE $term SET archived_at = $now WHERE archived_at = NONE RETURN AFTER", + Some(Timestamp::now()), + ) + .await +} + +/// Re-open the term; idempotent the same way. +pub async fn unarchive(db: &Database, term: Term) -> Result { + stamp( + db, + term, + "UPDATE $term SET archived_at = NONE WHERE archived_at != NONE RETURN AFTER", + None, + ) + .await +} + +/// One conditional write, through [`write_with_retry`] like every other +/// guarded single statement here; an empty result is the no-op case, and +/// only that path pays for the read that reports the stored row. +async fn stamp( + db: &Database, + term: Term, + sql: &str, + now: Option, +) -> Result { + let mut bindings = vec![("term".into(), term.id.record().into_value())]; + if let Some(now) = now { + bindings.push(("now".into(), now.as_millis().into_value())); + } + let written: Vec = write_with_retry(db, sql, &bindings).await?; + if let Some(written) = written.into_iter().next() { + return Ok(written); + } + read(db, &term.id).await?.ok_or(AppError::NotFound) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The bite test for the `WHERE` guard that replaced `TERM_LOCK` on the + /// PATCH path: the handler's pre-flight check is not in play here, so only + /// the guard can refuse a moved end that inverts the range — and it must + /// refuse it with the same error, having written nothing. + #[tokio::test] + async fn a_moved_end_is_refused_against_the_stored_other_end() { + let db = crate::database::init_mem().await.unwrap(); + let at = Timestamp::from_millis; + let term = create(&db, TermName::try_new("2026").unwrap(), at(100), at(200)) + .await + .unwrap(); + + let refused = update(&db, term.clone(), None, None, Some(at(50))) + .await + .expect_err("an end before the stored start must be refused"); + assert!(refused.to_string().contains("at or after starts_at")); + let stored = read(&db, term.get_id()).await.unwrap().unwrap(); + assert_eq!( + stored.get_ends_at(), + at(200), + "nothing may have been written" + ); + + // A move that keeps the range ordered still lands, guard and all. + let moved = update(&db, term, None, None, Some(at(300))).await.unwrap(); + assert_eq!(moved.get_ends_at(), at(300)); + } + + /// Terms are listed newest-first *and* paged by offset, so the sort has to + /// be a total order: `starts_at` alone leaves rows that share an instant in + /// an arbitrary order, and offset paging over an unstable order can hand + /// the same row out twice while skipping another. Pins the `id DESC` + /// tie-break on identical `starts_at` — stored read-back, then page by page. + #[tokio::test] + async fn identical_starts_at_still_pages_each_term_exactly_once() { + let db = crate::database::init_mem().await.unwrap(); + let at = Timestamp::from_millis; + let mut minted = Vec::new(); + for i in 0..12 { + let term = create( + &db, + TermName::try_new(&format!("t{i}")).unwrap(), + at(100), + at(200), + ) + .await + .unwrap(); + minted.push(term.get_id().key().to_string()); + } + // Newest first: the tie-break runs the same way as the primary column. + minted.reverse(); + + let (listed, total) = list_all(&db, None, 0).await.unwrap(); + assert_eq!(total, 12); + let read_back: Vec = listed + .iter() + .map(|row| row.get_id().key().to_string()) + .collect(); + assert_eq!(read_back, minted); + + // The assertion that catches skip/duplicate: walk it in pages of 5. + let mut paged = Vec::new(); + for offset in [0, 5, 10] { + let (page, total) = list_all(&db, Some(5), offset).await.unwrap(); + assert_eq!(total, 12); + paged.extend(page.iter().map(|row| row.get_id().key().to_string())); + } + assert_eq!(paged, minted, "every term exactly once, in list order"); + } + + /// GUARD, not a retry measurement — read the last paragraph before + /// trusting this test with the retry. See + /// [`crate::db::course::delete`]'s race test for why the rate is + /// counted rather than asserted per round. + /// + /// One conditional `DELETE … RETURN BEFORE` and a bare `.check()?`: no + /// transaction to abort, but also no [`crate::database::write_with_retry`], + /// which every other guarded single-statement write in the crate goes + /// through. A store answering "conflict, retry" therefore comes out as a + /// 500 instead of the 404 or 409 the request owes. + /// + /// The racer is [`crate::db::course::create`] against this + /// term: it claims `course_count` on the term row before it writes the + /// link, which is the same record and the same column the guard reads. Both + /// sides are swept across each other sub-millisecond, exactly as in + /// [`crate::db::subject::delete`]'s race test — a whole + /// millisecond of head start on either side separates them completely, and + /// the counters below assert the sweep straddled the site rather than + /// landing on one side of it (it used to alternate on `round % 2` and score + /// an exact 10/10, i.e. no overlap at all). + /// + /// And like that test it does *not* prove the retry: this site is one + /// statement, so the window in which a conflict could reach + /// [`write_with_retry`] is a single round trip wide — measured at 0 + /// conflicts in 100 raced rounds, green with the retry loop cut to a single + /// attempt. A status-code guard, then: a raced delete answers 409 or 404 and + /// never 500, and a course that got linked survives it. The retry is + /// measured on [`crate::db::course::delete`]. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_delete_racing_a_course_create_never_answers_500() { + use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; + use crate::domain::user::UserId; + let (db, _serialized) = crate::database::init_test_server("term_delete_race").await; + let (mut delete_500, mut create_500) = (0, 0); + let (mut linked, mut wiped) = (0, 0); + let (mut last_delete, mut last_create) = (String::new(), String::new()); + let at = Timestamp::from_millis; + for round in 0..20 { + let term = create(&db, TermName::try_new("2026").unwrap(), at(100), at(200)) + .await + .unwrap(); + + let separated = round % 4 == 0; + let drop_it = { + let (term, db) = (term.clone(), db.clone()); + // One round in four holds the racers back by a clear 2ms so the + // delete wins outright: the sub-millisecond sweep alone leaves + // them ahead of it nearly every round (measured 20 to 0), and + // both counters below have to see a side. The other three keep + // the sub-ms beat, which is the only spacing that overlaps at + // all — a whole millisecond either way separates them. + let beat = if separated { + std::time::Duration::ZERO + } else { + std::time::Duration::from_micros(round * 53 % 300) + }; + tokio::spawn(async move { + tokio::time::sleep(beat).await; + delete(&db, term).await + }) + }; + let makes: Vec<_> = (0..6) + .map(|_| { + let (id, db) = (term.get_id().clone(), db.clone()); + let head_start = if separated { + std::time::Duration::from_millis(2) + } else { + std::time::Duration::from_micros(round * 37 % 300) + }; + tokio::spawn(async move { + tokio::time::sleep(head_start).await; + crate::db::course::create( + &db, + &UserId::from_key("teacher"), + CourseTitle::try_new("algebra").unwrap(), + CourseDescription::try_new("").unwrap(), + CourseKind::course(), + Some(id), + None, + ) + .await + }) + }) + .collect(); + let drop_it = drop_it.await.unwrap(); + if matches!(drop_it, Err(AppError::Db(_))) { + delete_500 += 1; + last_delete = format!("{drop_it:?}"); + } + // Stored state, both sides: a linked course means the claim beat the + // guard, a gone term means the delete did. + let mut landed = false; + for make in makes { + let make = make.await.unwrap(); + if matches!(make, Err(AppError::Db(_))) { + create_500 += 1; + last_create = format!("{make:?}"); + } + if let Ok(course) = &make + && crate::db::course::read(&db, course.get_id()) + .await + .unwrap() + .is_some() + { + landed = true; + } + } + linked += usize::from(landed); + if read(&db, term.get_id()).await.unwrap().is_none() { + wiped += 1; + } + } + eprintln!( + "Term::delete raced: {delete_500}/20 delete 500s, {create_500} create 500s, \ + {linked} rounds with a course linked / {wiped} wiped" + ); + assert!( + linked > 0 && wiped > 0, + "the sweep never crossed the window ({linked} linked / {wiped} wiped)" + ); + assert_eq!( + delete_500, 0, + "a raced delete must be refused, not 500: {delete_500}/20 rounds, last {last_delete}" + ); + assert_eq!( + create_500, 0, + "a raced course create must retry, not 500: {create_500}/20 rounds, last {last_create}" + ); + } +} diff --git a/src/domain/bank_question.rs b/src/domain/bank_question.rs index 3ae60bf..19e6c8b 100644 --- a/src/domain/bank_question.rs +++ b/src/domain/bank_question.rs @@ -115,7 +115,7 @@ impl BankQuestionId { /// subject when a template is copied into an exam, not here. /// /// `subject` is optional because it is *only* metadata: deleting a subject -/// clears it school-wide (see [`crate::domain::subject::Subject::delete`]) +/// clears it school-wide (see [`crate::db::subject::delete`]) /// rather than being blocked by the bank. Blocking would have been a dead end /// — the bank is owner-or-admin editable, so a manager could not resolve their /// own 409 — and an existence oracle, since another teacher's *private* @@ -837,11 +837,11 @@ mod tests { let other_exam = crate::db::exam::published_exam(&db).await.get_id().clone(); // A real subject row: an exam question claims a reference on its // subject, so a minted id it never wrote would be refused. - let subject = crate::domain::subject::Subject::create( + let subject = crate::db::subject::create( + &db, &crate::db::course::a_test_course(&db).await, crate::domain::subject::SubjectName::try_new("topic").unwrap(), crate::domain::subject::SubjectDescription::try_new("").unwrap(), - &db, ) .await .unwrap(); diff --git a/src/domain/class_group.rs b/src/domain/class_group.rs index 6872794..a56779c 100644 --- a/src/domain/class_group.rs +++ b/src/domain/class_group.rs @@ -19,11 +19,12 @@ use crate::constant::{ use crate::database::{Database, transaction_with_retry}; use crate::db::cap; use crate::db::field_update::FieldUpdate; -use crate::domain::monotonic_id::next_ulid; use crate::db::page::PagedList; -use crate::domain::term::{self, TermId}; +use crate::domain::monotonic_id::next_ulid; +use crate::domain::term::{TermId, gone_error, ref_move}; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; +use crate::service::term; use crate::validate::{validate_optional, validate_required}; /// The `THROW` marker the delete guard aborts with — a class that still holds @@ -131,7 +132,7 @@ impl ClassGroup { pub async fn require_open(&self, db: &Database) -> Result<(), AppError> { match self.get_term() { None => Ok(()), - Some(term) => term::Term::require_open(term, db).await, + Some(term) => term::require_open(db, term).await, } } @@ -184,7 +185,7 @@ impl ClassGroup { cap::Claimed::Made(created) => Ok(created), // Uncapped, so "full" can only mean the conditional write matched no // term row at all — the claim doubles as the existence check. - cap::Claimed::Full => Err(term::gone_error()), + cap::Claimed::Full => Err(gone_error()), // Unreachable: the id is a ULID this call just generated. cap::Claimed::Duplicate => Err(AppError::Internal("failed to create class".into())), } @@ -240,7 +241,7 @@ impl ClassGroup { teacher: Option>, db: &Database, ) -> Result { - let (claim, release) = term::ref_move(self.term.as_ref(), &term); + let (claim, release) = ref_move(self.term.as_ref(), &term); let expected = self.term.as_ref().map(TermId::record); FieldUpdate::new(self.id.record()) .set("name", name) @@ -258,7 +259,7 @@ impl ClassGroup { expected, claim, release, - term::gone_error(), + gone_error(), ) .run::(db) .await @@ -409,7 +410,7 @@ mod tests { async fn a_term(db: &Database) -> Term { let at = crate::domain::timestamp::Timestamp::from_millis; - Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), db) + crate::db::term::create(db, TermName::try_new("2026").unwrap(), at(100), at(200)) .await .unwrap() } @@ -570,7 +571,7 @@ mod tests { "the courses' counter is seeded from course rows and must stay untouched" ); assert!( - !term.clone().delete(&db).await.unwrap(), + !crate::db::term::delete(&db, term.clone()).await.unwrap(), "two linked classes must refuse the delete" ); @@ -579,13 +580,13 @@ mod tests { .await .unwrap(); assert!( - !term.clone().delete(&db).await.unwrap(), + !crate::db::term::delete(&db, term.clone()).await.unwrap(), "one link is still one link" ); assert!(linked.delete(&db).await.unwrap()); assert!( - term.clone().delete(&db).await.unwrap(), + crate::db::term::delete(&db, term.clone()).await.unwrap(), "the last link gone, the term may go" ); } @@ -651,7 +652,7 @@ mod tests { let db = crate::database::init_mem().await.unwrap(); let term = a_term(&db).await; let id = term.get_id().clone(); - assert!(term.delete(&db).await.unwrap()); + assert!(crate::db::term::delete(&db, term).await.unwrap()); let error = ClassGroup::create( &UserId::from_key("manager"), @@ -686,14 +687,15 @@ mod tests { let db = crate::database::init_mem().await.unwrap(); let at = crate::domain::timestamp::Timestamp::from_millis; let from = a_term(&db).await; - let to = Term::create(TermName::try_new("2027").unwrap(), at(100), at(200), &db) - .await - .unwrap(); - let dead = Term::create(TermName::try_new("2028").unwrap(), at(100), at(200), &db) + let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200)) .await .unwrap(); + let dead = + crate::db::term::create(&db, TermName::try_new("2028").unwrap(), at(100), at(200)) + .await + .unwrap(); let dead_id = dead.get_id().clone(); - assert!(dead.delete(&db).await.unwrap()); + assert!(crate::db::term::delete(&db, dead).await.unwrap()); let class = class_on(Some(from.get_id().clone()), &db).await; let error = class @@ -747,12 +749,13 @@ mod tests { let db = crate::database::init_mem().await.unwrap(); let at = crate::domain::timestamp::Timestamp::from_millis; let from = a_term(&db).await; - let to = Term::create(TermName::try_new("2027").unwrap(), at(100), at(200), &db) - .await - .unwrap(); - let other = Term::create(TermName::try_new("2028").unwrap(), at(100), at(200), &db) + let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200)) .await .unwrap(); + let other = + crate::db::term::create(&db, TermName::try_new("2028").unwrap(), at(100), at(200)) + .await + .unwrap(); let class = class_on(Some(from.get_id().clone()), &db).await; let stale = class.clone(); class diff --git a/src/domain/homework.rs b/src/domain/homework.rs index 5a323ac..dca363e 100644 --- a/src/domain/homework.rs +++ b/src/domain/homework.rs @@ -421,11 +421,11 @@ mod tests { use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; async fn a_subject(name: &str, db: &Database) -> Subject { - Subject::create( + crate::db::subject::create( + db, &crate::db::course::a_test_course(db).await, SubjectName::try_new(name).unwrap(), SubjectDescription::try_new("").unwrap(), - db, ) .await .unwrap() @@ -480,7 +480,7 @@ mod tests { let db = crate::database::init_mem().await.unwrap(); let subject = a_subject("algebra", &db).await; let id = subject.get_id().clone(); - subject.delete(&db).await.unwrap(); + crate::db::subject::delete(&db, subject).await.unwrap(); let error = Homework::create( &CourseId::from_key("course"), @@ -528,9 +528,12 @@ mod tests { "the old subject is free" ); assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); - assert!(from.delete(&db).await.is_ok(), "no reference left"); assert!( - to.delete(&db).await.is_err(), + crate::db::subject::delete(&db, from).await.is_ok(), + "no reference left" + ); + assert!( + crate::db::subject::delete(&db, to).await.is_err(), "the reference moved here refuses the delete" ); } @@ -544,7 +547,7 @@ mod tests { let from = a_subject("algebra", &db).await; let dead = a_subject("geometry", &db).await; let gone = dead.get_id().clone(); - dead.delete(&db).await.unwrap(); + crate::db::subject::delete(&db, dead).await.unwrap(); let homework = homework_on(from.get_id(), &db).await; let error = homework diff --git a/src/domain/homework_file.rs b/src/domain/homework_file.rs index 190b15e..a62cbaf 100644 --- a/src/domain/homework_file.rs +++ b/src/domain/homework_file.rs @@ -328,14 +328,14 @@ mod tests { /// deadline off the entity now, so a bare id no longer does. async fn a_homework(db: &Database) -> crate::domain::homework::Homework { use crate::domain::homework::{Homework, HomeworkTitle}; - use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; + use crate::domain::subject::{SubjectDescription, SubjectName}; let course = crate::db::course::a_test_course(db).await; - let subject = Subject::create( + let subject = crate::db::subject::create( + db, &course, SubjectName::try_new("topic").unwrap(), SubjectDescription::try_new("").unwrap(), - db, ) .await .unwrap(); diff --git a/src/domain/homework_result.rs b/src/domain/homework_result.rs index d2510a1..80ffb12 100644 --- a/src/domain/homework_result.rs +++ b/src/domain/homework_result.rs @@ -373,14 +373,14 @@ mod tests { /// same way it already is for a submission. async fn a_homework(db: &Database) -> HomeworkId { use crate::domain::homework::{Homework, HomeworkTitle}; - use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; + use crate::domain::subject::{SubjectDescription, SubjectName}; let course = crate::db::course::a_test_course(db).await; - let subject = Subject::create( + let subject = crate::db::subject::create( + db, &course, SubjectName::try_new("topic").unwrap(), SubjectDescription::try_new("").unwrap(), - db, ) .await .unwrap(); diff --git a/src/domain/homework_submission.rs b/src/domain/homework_submission.rs index ffd65f3..76cac33 100644 --- a/src/domain/homework_submission.rs +++ b/src/domain/homework_submission.rs @@ -371,17 +371,17 @@ mod tests { use super::*; use crate::domain::homework::HomeworkTitle; - use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; + use crate::domain::subject::{SubjectDescription, SubjectName}; /// A real homework row (and the subject it must reference) due at `due_at` — /// `upsert` now reads the deadline off the entity, so the tests need one. async fn a_homework(due_at: Timestamp, db: &Database) -> Homework { let course = crate::db::course::a_test_course(db).await; - let subject = Subject::create( + let subject = crate::db::subject::create( + db, &course, SubjectName::try_new("topic").unwrap(), SubjectDescription::try_new("").unwrap(), - db, ) .await .unwrap(); diff --git a/src/domain/subject.rs b/src/domain/subject.rs index 0e64f06..f6d0575 100644 --- a/src/domain/subject.rs +++ b/src/domain/subject.rs @@ -1,15 +1,9 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{ - ENROLLMENT_COUNT_FIELD, MAX_SUBJECT_DESCRIPTION_LEN, MAX_SUBJECT_NAME_LEN, SUBJECT_TABLE, -}; -use crate::database::{Database, transaction_with_retry}; -use crate::db::cap; -use crate::db::field_update::FieldUpdate; -use crate::db::page::PagedList; +use crate::constant::{MAX_SUBJECT_DESCRIPTION_LEN, MAX_SUBJECT_NAME_LEN, SUBJECT_TABLE}; use crate::domain::course::CourseId; use crate::domain::monotonic_id::next_ulid; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; use crate::validate::{validate_optional, validate_required}; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] @@ -17,9 +11,9 @@ pub struct SubjectId(RecordId); impl SubjectId { /// Minted from the process-wide monotonic generator, not `Ulid::new()`: the - /// id *is* the curriculum's order ([`Subject::list_for_course`] sorts - /// `id ASC`), and a random low half scrambles a burst of saves that lands - /// inside one millisecond. + /// id *is* the curriculum's order ([`crate::db::subject::list_for_course`] + /// sorts `id ASC`), and a random low half scrambles a burst of saves that + /// lands inside one millisecond. pub fn generate() -> Self { Self(RecordId::new(SUBJECT_TABLE, next_ulid().to_string())) } @@ -74,10 +68,10 @@ impl SubjectDescription { /// it would strand the questions tagged with it. #[derive(Debug, Clone, SurrealValue)] pub struct Subject { - id: SubjectId, - course: CourseId, - name: SubjectName, - description: SubjectDescription, + pub(crate) id: SubjectId, + pub(crate) course: CourseId, + pub(crate) name: SubjectName, + pub(crate) description: SubjectDescription, } impl Subject { @@ -96,199 +90,12 @@ impl Subject { pub fn get_description(&self) -> &SubjectDescription { &self.description } - - pub async fn create( - course: &CourseId, - name: SubjectName, - description: SubjectDescription, - db: &Database, - ) -> Result { - let subject = Subject { - id: SubjectId::generate(), - course: course.clone(), - name, - description, - }; - // The course row is *written* (bumped and put back), not read, so this - // collides with `Course::delete`'s cascade: a topic that outlives its - // course 404s through `subject_with_course` forever, while - // `subject_must_exist` still accepts its id — so a bank template can be - // tagged with a subject nobody can reach. See [`cap::touch_and_create`]. - cap::touch_and_create( - &course.record(), - ENROLLMENT_COUNT_FIELD, - &subject.id.record(), - &subject, - db, - ) - .await? - .ok_or(AppError::NotFound) - } - - pub async fn read(id: &SubjectId, db: &Database) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - /// Several subjects in one query — the bulk half of a list endpoint that - /// names each row's subject (a read per row would be an N+1). - pub async fn list_by_ids(ids: &[&SubjectId], db: &Database) -> Result, AppError> { - if ids.is_empty() { - return Ok(Vec::new()); - } - let records: Vec = ids.iter().map(|id| id.record()).collect(); - let mut result = db - .query("SELECT * FROM subject WHERE id IN $ids") - .bind(("ids", records)) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// The course's subjects in curriculum order (ULID ids sort by creation). - pub async fn list_for_course( - course: &CourseId, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new("subject WHERE course = $course", "ORDER BY id ASC") - .bind("course", course.record()) - .run(limit, offset, db) - .await - } - - /// Request-scoped: no lock spans the handler's read and this write, so an - /// omitted field (`None`) is not written at all. Passing the snapshot's - /// value back instead would revert a concurrent edit of that field — - /// scoping the `SET` alone does not prevent that, the values have to come - /// from the request. Neither column is nullable, so plain `Option` per - /// field says everything there is to say. - pub async fn update( - self, - name: Option, - description: Option, - db: &Database, - ) -> Result { - FieldUpdate::new(self.id.record()) - .set("name", name) - .set("description", description) - .run::(db) - .await - } - - /// Delete the subject and clear it off every bank template that carried it - /// as origin metadata — one transaction, so a template can't be left - /// pointing at a subject that no longer exists. - /// - /// Exam questions and homework are *not* cascaded: their `subject` is a - /// required field that may not be orphaned, so either one still refuses the - /// delete with a 409. That refusal is the delete's own `WHERE`, read off the - /// two reference counters this row carries - /// ([`crate::constant::SUBJECT_QUESTION_COUNT_FIELD`] and its homework - /// twin), which is what makes it hold against a question created by a - /// request racing this one — the cross-table `SELECT … LIMIT 1` it replaces - /// was a count-then-delete no transaction serializes, pinned by three - /// process-wide locks that could not cover the round trip between them. - /// - /// Which of the two blocked is read off the counters *before* the delete, - /// purely to pick the message; the decision itself was already made by the - /// `WHERE`. - /// - /// The bank's subject is optional metadata, and blocking on it was a dead - /// end — only the template's owner may re-tag it, so a manager could never - /// clear their own 409, and a private template raising it leaked its - /// existence. Its cascade runs *after* the conditional delete, so a refused - /// delete leaves every template's subject where it was. - pub async fn delete(self, db: &Database) -> Result { - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - LET $held = (SELECT exam_question_count AS q, homework_count AS h FROM $sub); - LET $before = (DELETE $sub - WHERE (exam_question_count ?? 0) = 0 AND (homework_count ?? 0) = 0 - RETURN BEFORE); - IF array::len($before) = 0 { - THROW IF array::len($held) = 0 { 'subject_missing' } - ELSE IF ($held[0].q ?? 0) > 0 { 'subject_questions' } - ELSE { 'subject_homework' } - }; - UPDATE bank_question SET subject = NONE WHERE subject = $sub; - RETURN $before; - COMMIT TRANSACTION;", - &[("sub".into(), self.id.record().into_value())], - &["subject_missing", "subject_questions", "subject_homework"], - ) - .await?; - // An aborted transaction errors every slot; only the THROW's own slot - // names the marker (the [`crate::domain::appointment_slot`] treatment), - // and a lost round is re-sent rather than reported. - let thrown = |marker: &str| { - errors - .values() - .any(|error| error.to_string().contains(marker)) - }; - if thrown("subject_questions") { - return Err(AppError::Conflict( - "exam questions still reference this subject — re-tag or delete them first", - )); - } - if thrown("subject_homework") { - return Err(AppError::Conflict( - "homework still references this subject — re-tag or delete it first", - )); - } - if thrown("subject_missing") { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Read through the trailing `RETURN`, not a counted slot — see - // [`crate::db::exam::delete`]. - let slot = result.num_statements().saturating_sub(2); - let deleted: Option = result.take::>(slot)?.into_iter().next(); - deleted.ok_or(AppError::NotFound) - } } #[cfg(test)] mod tests { use super::*; - /// A curriculum topic must not outlive its course: an orphan 404s through - /// `subject_with_course`, and worse than the sibling cases, - /// `subject_must_exist` still *accepts* its id — so a bank template can be - /// tagged with a subject nobody can reach. - /// - /// [`Subject::create`] therefore *writes* the course row rather than - /// reading it ([`cap::touch_and_create`]); the harness and the window it - /// races in are documented on - /// [`crate::db::course::assert_no_child_outlives_a_course_delete`]. - /// Mutation-tested: with the bare `db.create` this shipped with, all four - /// rounds orphan. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn a_subject_never_outlives_its_course() { - fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle> { - tokio::spawn(async move { - Subject::create( - &course, - SubjectName::try_new("Limits").unwrap(), - SubjectDescription::try_new("").unwrap(), - &db, - ) - .await - .map(|_| ()) - }) - } - crate::db::course::assert_no_child_outlives_a_course_delete( - "subject_orphan_race", - SUBJECT_TABLE, - make, - ) - .await; - } - /// A teacher entering a curriculum gets it back in the order they typed it: /// `list_for_course` sorts `id ASC`, so the ids minted inside one /// millisecond have to sort in mint order. Revert `generate` to @@ -317,150 +124,4 @@ mod tests { assert!(SubjectDescription::try_new("").is_ok()); assert!(SubjectDescription::try_new(&"x".repeat(2_001)).is_err()); } - - /// GUARD, not a retry measurement — read the last paragraph before - /// trusting this test with the retry. See - /// [`crate::db::course::delete`]'s race test for why the rate - /// is counted rather than asserted per round, and why this needs the real - /// server and a multi-threaded runtime. - /// - /// The racer is [`crate::db::exam_question::create`], which claims the subject's - /// question reference *before* it writes the row — a conditional write on - /// the same record the delete's `WHERE` reads. `Err(Conflict)` (still - /// referenced), `Err(NotFound)` and the claim's `Validation` miss are all - /// correct answers; only `AppError::Db` is the defect. What the two stored - /// counters below assert is that the sweep genuinely straddled the site: - /// some rounds the claims won, some rounds the delete did. - /// - /// What it does *not* prove is the retry. The 500 window here is the delete - /// passing its `WHERE` and then committing while a claim is in flight, and - /// this cascade is three statements long — measured at 0 conflicts in 100 - /// raced rounds, and the whole test stays green with - /// [`crate::database::transaction_with_retry`]'s loop cut to a single - /// attempt. Widening the sweep, staggering the burst and doubling it to 12 - /// racers all failed to open the window (they only move which side wins). - /// So this is a status-code-and-cascade guard: a raced delete answers 409 or - /// 404 and never 500, and a landed question survives it. The retry itself is - /// measured on [`crate::db::course::delete`], whose cascade is - /// long enough to lose a round (1-2 of 20, red under the same mutation). - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn a_delete_racing_a_question_never_answers_500() { - use crate::domain::exam_question::{ - QuestionKind, QuestionPoints, QuestionSpec, QuestionText, - }; - let (db, _serialized) = crate::database::init_test_server("subject_delete_race").await; - let (mut delete_500, mut question_500) = (0, 0); - let (mut landed, mut wiped) = (0, 0); - let (mut last_delete, mut last_question) = (String::new(), String::new()); - for round in 0..20 { - let course = crate::db::course::a_test_course(&db).await; - // A real exam row per round: a question write moves its exam's - // counter, so a minted id nothing wrote is a 404 and no round would - // reach the subject race this test is about. - let exam = crate::db::exam::published_exam(&db).await.get_id().clone(); - let subject = Subject::create( - &course, - SubjectName::try_new("Limits").unwrap(), - SubjectDescription::try_new("").unwrap(), - &db, - ) - .await - .unwrap(); - - let separated = round % 4 == 0; - let drop_it = { - let (subject, db) = (subject.clone(), db.clone()); - // One round in four holds the racers back by a clear 2ms so the - // delete wins outright: the sub-millisecond sweep alone leaves - // them ahead of it nearly every round (measured 20 to 0), and - // both counters below have to see a side. The other three keep - // the sub-ms beat, which is the only spacing that overlaps at - // all — a whole millisecond either way separates them. - let beat = if separated { - std::time::Duration::ZERO - } else { - std::time::Duration::from_micros(round * 53 % 300) - }; - tokio::spawn(async move { - tokio::time::sleep(beat).await; - subject.delete(&db).await - }) - }; - let asks: Vec<_> = (0..6) - .map(|_| { - let (id, db, exam) = (subject.get_id().clone(), db.clone(), exam.clone()); - let head_start = if separated { - std::time::Duration::from_millis(2) - } else { - std::time::Duration::from_micros(round * 37 % 300) - }; - tokio::spawn(async move { - tokio::time::sleep(head_start).await; - crate::db::exam_question::create( - &db, - &exam, - id, - QuestionText::try_new("why").unwrap(), - QuestionPoints::try_new(1).unwrap(), - QuestionSpec::try_new( - QuestionKind::try_new("text").unwrap(), - None, - None, - &[], - ) - .unwrap(), - ) - .await - }) - }) - .collect(); - let drop_it = drop_it.await.unwrap(); - if matches!(drop_it, Err(AppError::Db(_))) { - delete_500 += 1; - last_delete = format!("{drop_it:?}"); - } - for ask in asks { - let ask = ask.await.unwrap(); - if matches!(ask, Err(AppError::Db(_))) { - question_500 += 1; - last_question = format!("{ask:?}"); - } - } - // Stored state, and both sides are needed: a question landing means - // the claim beat the guard, the subject being gone means the delete - // did. Seeing only one is a run that never swept across the window. - if Subject::read(subject.get_id(), &db) - .await - .unwrap() - .is_none() - { - wiped += 1; - } - if !crate::db::exam_question::list_for_exam(&db, &exam, None, 0) - .await - .unwrap() - .0 - .is_empty() - { - landed += 1; - } - } - eprintln!( - "Subject::delete raced: {delete_500}/20 delete 500s, {question_500} question 500s, \ - {landed} rounds with a question landed / {wiped} wiped" - ); - assert!( - landed > 0 && wiped > 0, - "the sweep never crossed the window ({landed} landed / {wiped} wiped)" - ); - assert_eq!( - delete_500, 0, - "a raced delete must be refused, not 500: {delete_500}/20 rounds, last {last_delete}" - ); - assert_eq!( - question_500, 0, - "a raced question create must retry, not 500: {question_500}/20 rounds, last {last_question}" - ); - } } diff --git a/src/domain/term.rs b/src/domain/term.rs index 86131ec..270eaed 100644 --- a/src/domain/term.rs +++ b/src/domain/term.rs @@ -8,12 +8,9 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{COURSE_COUNT_FIELD, MAX_TERM_NAME_LEN, TERM_CLASS_COUNT_FIELD, TERM_TABLE}; -use crate::database::{Database, write_with_retry}; -use crate::db::field_update::FieldUpdate; +use crate::constant::{MAX_TERM_NAME_LEN, TERM_TABLE}; use crate::domain::monotonic_id::next_ulid; -use crate::db::page::PagedList; -use crate::domain::timestamp::{Timestamp, range_error}; +use crate::domain::timestamp::Timestamp; use crate::error::{AppError, ValidationError}; use crate::validate::validate_required; @@ -47,8 +44,8 @@ impl TermId { /// The answer every link to a term that is not there gets — the claim is a /// conditional write on the term row, so a term a delete already removed -/// matches nothing and the caller says exactly what `web::terms::resolve_term`'s -/// pre-flight lookup would have. +/// matches nothing and the caller says exactly what the link resolver's +/// pre-flight lookup ([`crate::service::term::resolve`]) would have. pub fn gone_error() -> AppError { AppError::Validation(ValidationError::Invalid { field: "term_id", @@ -101,15 +98,15 @@ impl TermName { /// term is a date range by definition. #[derive(Debug, Clone, SurrealValue)] pub struct Term { - id: TermId, - name: TermName, - starts_at: Timestamp, - ends_at: Timestamp, + pub(crate) id: TermId, + pub(crate) name: TermName, + pub(crate) starts_at: Timestamp, + pub(crate) ends_at: Timestamp, /// When a manager archived this term; `None` = open. `#[surreal(default)]` /// for the same reason `BankQuestion::subject` has one: rows written before /// the column existed still decode, as open terms. #[surreal(default)] - archived_at: Option, + pub(crate) archived_at: Option, } impl Term { @@ -136,223 +133,12 @@ impl Term { pub fn is_archived(&self) -> bool { self.archived_at.is_some() } - - pub async fn create( - name: TermName, - starts_at: Timestamp, - ends_at: Timestamp, - db: &Database, - ) -> Result { - let term = Term { - id: TermId::generate(), - name, - starts_at, - ends_at, - archived_at: None, - }; - let created: Option = db.create(term.id.record()).content(term).await?; - created.ok_or_else(|| AppError::Internal("failed to create term".into())) - } - - pub async fn read(id: &TermId, db: &Database) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - /// Every term, newest first — the school calendar is small by nature. - pub async fn list_all( - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new("term", "ORDER BY starts_at DESC, id DESC") - .run(limit, offset, db) - .await - } - - /// Write only the fields the PATCH carried — `None` means the request - /// omitted it, so the column is left alone rather than re-stated from the - /// snapshot this struct was read into. All three columns are non-nullable, - /// so "absent" and "null" both correctly mean "keep". - pub async fn update( - self, - name: Option, - starts_at: Option, - ends_at: Option, - db: &Database, - ) -> Result { - FieldUpdate::new(self.id.record()) - .set("name", name) - .set("starts_at", starts_at) - .set("ends_at", ends_at) - .ordered("starts_at", "ends_at", range_error()) - .run::(db) - .await - } - - /// Delete the term, but only while no course *and no class* links it — - /// nothing here unlinks or cascades. `false` = refused, nothing was written. - /// - /// The roster of linking courses is the term's own `course_count` - /// refcount, claimed by [`crate::db::course::create`] and - /// `update` *before* they write a link, so the check and the delete are one - /// conditional write on one record: a course write racing this either - /// claims first (and the delete is refused) or finds the row gone (and is - /// refused itself, with the same 400 the lookup gives). `Err(NotFound)` - /// keeps the answer a concurrent *delete* used to get. - /// - /// Classes ([`crate::domain::class_group::ClassGroup`]) link a term the same - /// way and count on `class_count` — a column of their own, because - /// `course_count` is seeded at boot from the course rows alone. - pub async fn delete(self, db: &Database) -> Result { - let sql = format!( - "DELETE $term WHERE ({COURSE_COUNT_FIELD} ?? 0) = 0 \ - AND ({TERM_CLASS_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE" - ); - // Through the retry, because the guard reads the very column a course - // create claims: a lost round writes nothing, and re-sending it is what - // keeps the answer the 404 or 409 it owes instead of a 500. - let gone: Vec = - write_with_retry(db, &sql, &[("term".into(), self.id.record().into_value())]).await?; - if !gone.is_empty() { - return Ok(true); - } - // Still linked or already gone: the one statement cannot tell those - // apart, and only the refusal path pays for the read that can. - match Self::read(&self.id, db).await? { - Some(_) => Ok(false), - None => Err(AppError::NotFound), - } - } - - /// Freeze the term. Idempotent by construction: the `WHERE` only matches an - /// open row, so a repeat archive writes nothing and answers with the - /// *original* stamp — the year is not re-dated by a double click. - pub async fn archive(self, db: &Database) -> Result { - self.stamp( - "UPDATE $term SET archived_at = $now WHERE archived_at = NONE RETURN AFTER", - Some(Timestamp::now()), - db, - ) - .await - } - - /// Re-open the term; idempotent the same way. - pub async fn unarchive(self, db: &Database) -> Result { - self.stamp( - "UPDATE $term SET archived_at = NONE WHERE archived_at != NONE RETURN AFTER", - None, - db, - ) - .await - } - - /// One conditional write, through [`write_with_retry`] like every other - /// guarded single statement here; an empty result is the no-op case, and - /// only that path pays for the read that reports the stored row. - async fn stamp( - self, - sql: &str, - now: Option, - db: &Database, - ) -> Result { - let mut bindings = vec![("term".into(), self.id.record().into_value())]; - if let Some(now) = now { - bindings.push(("now".into(), now.as_millis().into_value())); - } - let written: Vec = write_with_retry(db, sql, &bindings).await?; - if let Some(term) = written.into_iter().next() { - return Ok(term); - } - Self::read(&self.id, db).await?.ok_or(AppError::NotFound) - } - - /// Refuse when the named term is archived. A missing row is `Ok(())`: a - /// dangling link is not this guard's error, and the caller that cares - /// already answers it (see [`gone_error`]). - pub async fn require_open(id: &TermId, db: &Database) -> Result<(), AppError> { - match Self::read(id, db).await? { - Some(term) if term.is_archived() => Err(archived_error()), - _ => Ok(()), - } - } } #[cfg(test)] mod tests { use super::*; - /// The bite test for the `WHERE` guard that replaced `TERM_LOCK` on the - /// PATCH path: the handler's pre-flight check is not in play here, so only - /// the guard can refuse a moved end that inverts the range — and it must - /// refuse it with the same error, having written nothing. - #[tokio::test] - async fn a_moved_end_is_refused_against_the_stored_other_end() { - let db = crate::database::init_mem().await.unwrap(); - let at = Timestamp::from_millis; - let term = Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), &db) - .await - .unwrap(); - - let refused = term - .clone() - .update(None, None, Some(at(50)), &db) - .await - .expect_err("an end before the stored start must be refused"); - assert!(refused.to_string().contains("at or after starts_at")); - let stored = Term::read(term.get_id(), &db).await.unwrap().unwrap(); - assert_eq!( - stored.get_ends_at(), - at(200), - "nothing may have been written" - ); - - // A move that keeps the range ordered still lands, guard and all. - let moved = term.update(None, None, Some(at(300)), &db).await.unwrap(); - assert_eq!(moved.get_ends_at(), at(300)); - } - - /// Terms are listed newest-first *and* paged by offset, so the sort has to - /// be a total order: `starts_at` alone leaves rows that share an instant in - /// an arbitrary order, and offset paging over an unstable order can hand - /// the same row out twice while skipping another. Pins the `id DESC` - /// tie-break on identical `starts_at` — stored read-back, then page by page. - #[tokio::test] - async fn identical_starts_at_still_pages_each_term_exactly_once() { - let db = crate::database::init_mem().await.unwrap(); - let at = Timestamp::from_millis; - let mut minted = Vec::new(); - for i in 0..12 { - let term = Term::create( - TermName::try_new(&format!("t{i}")).unwrap(), - at(100), - at(200), - &db, - ) - .await - .unwrap(); - minted.push(term.get_id().key().to_string()); - } - // Newest first: the tie-break runs the same way as the primary column. - minted.reverse(); - - let (listed, total) = Term::list_all(None, 0, &db).await.unwrap(); - assert_eq!(total, 12); - let read_back: Vec = listed - .iter() - .map(|row| row.get_id().key().to_string()) - .collect(); - assert_eq!(read_back, minted); - - // The assertion that catches skip/duplicate: walk it in pages of 5. - let mut paged = Vec::new(); - for offset in [0, 5, 10] { - let (page, total) = Term::list_all(Some(5), offset, &db).await.unwrap(); - assert_eq!(total, 12); - paged.extend(page.iter().map(|row| row.get_id().key().to_string())); - } - assert_eq!(paged, minted, "every term exactly once, in list order"); - } - #[tokio::test] async fn name_is_required_and_bounded() { assert!(TermName::try_new("2026 Fall").is_ok()); @@ -360,135 +146,4 @@ mod tests { assert!(TermName::try_new(" ").is_err()); assert!(TermName::try_new(&"x".repeat(101)).is_err()); } - - /// GUARD, not a retry measurement — read the last paragraph before - /// trusting this test with the retry. See - /// [`crate::db::course::delete`]'s race test for why the rate is - /// counted rather than asserted per round. - /// - /// One conditional `DELETE … RETURN BEFORE` and a bare `.check()?`: no - /// transaction to abort, but also no [`crate::database::write_with_retry`], - /// which every other guarded single-statement write in the crate goes - /// through. A store answering "conflict, retry" therefore comes out as a - /// 500 instead of the 404 or 409 the request owes. - /// - /// The racer is [`crate::db::course::create`] against this - /// term: it claims `course_count` on the term row before it writes the - /// link, which is the same record and the same column the guard reads. Both - /// sides are swept across each other sub-millisecond, exactly as in - /// [`crate::domain::subject::Subject::delete`]'s race test — a whole - /// millisecond of head start on either side separates them completely, and - /// the counters below assert the sweep straddled the site rather than - /// landing on one side of it (it used to alternate on `round % 2` and score - /// an exact 10/10, i.e. no overlap at all). - /// - /// And like that test it does *not* prove the retry: this site is one - /// statement, so the window in which a conflict could reach - /// [`write_with_retry`] is a single round trip wide — measured at 0 - /// conflicts in 100 raced rounds, green with the retry loop cut to a single - /// attempt. A status-code guard, then: a raced delete answers 409 or 404 and - /// never 500, and a course that got linked survives it. The retry is - /// measured on [`crate::db::course::delete`]. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn a_delete_racing_a_course_create_never_answers_500() { - use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; - use crate::domain::user::UserId; - let (db, _serialized) = crate::database::init_test_server("term_delete_race").await; - let (mut delete_500, mut create_500) = (0, 0); - let (mut linked, mut wiped) = (0, 0); - let (mut last_delete, mut last_create) = (String::new(), String::new()); - let at = Timestamp::from_millis; - for round in 0..20 { - let term = Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), &db) - .await - .unwrap(); - - let separated = round % 4 == 0; - let drop_it = { - let (term, db) = (term.clone(), db.clone()); - // One round in four holds the racers back by a clear 2ms so the - // delete wins outright: the sub-millisecond sweep alone leaves - // them ahead of it nearly every round (measured 20 to 0), and - // both counters below have to see a side. The other three keep - // the sub-ms beat, which is the only spacing that overlaps at - // all — a whole millisecond either way separates them. - let beat = if separated { - std::time::Duration::ZERO - } else { - std::time::Duration::from_micros(round * 53 % 300) - }; - tokio::spawn(async move { - tokio::time::sleep(beat).await; - term.delete(&db).await - }) - }; - let makes: Vec<_> = (0..6) - .map(|_| { - let (id, db) = (term.get_id().clone(), db.clone()); - let head_start = if separated { - std::time::Duration::from_millis(2) - } else { - std::time::Duration::from_micros(round * 37 % 300) - }; - tokio::spawn(async move { - tokio::time::sleep(head_start).await; - crate::db::course::create( - &db, - &UserId::from_key("teacher"), - CourseTitle::try_new("algebra").unwrap(), - CourseDescription::try_new("").unwrap(), - CourseKind::course(), - Some(id), - None, - ) - .await - }) - }) - .collect(); - let drop_it = drop_it.await.unwrap(); - if matches!(drop_it, Err(AppError::Db(_))) { - delete_500 += 1; - last_delete = format!("{drop_it:?}"); - } - // Stored state, both sides: a linked course means the claim beat the - // guard, a gone term means the delete did. - let mut landed = false; - for make in makes { - let make = make.await.unwrap(); - if matches!(make, Err(AppError::Db(_))) { - create_500 += 1; - last_create = format!("{make:?}"); - } - if let Ok(course) = &make - && crate::db::course::read(&db, course.get_id()) - .await - .unwrap() - .is_some() - { - landed = true; - } - } - linked += usize::from(landed); - if Term::read(term.get_id(), &db).await.unwrap().is_none() { - wiped += 1; - } - } - eprintln!( - "Term::delete raced: {delete_500}/20 delete 500s, {create_500} create 500s, \ - {linked} rounds with a course linked / {wiped} wiped" - ); - assert!( - linked > 0 && wiped > 0, - "the sweep never crossed the window ({linked} linked / {wiped} wiped)" - ); - assert_eq!( - delete_500, 0, - "a raced delete must be refused, not 500: {delete_500}/20 rounds, last {last_delete}" - ); - assert_eq!( - create_500, 0, - "a raced course create must retry, not 500: {create_500}/20 rounds, last {last_create}" - ); - } } diff --git a/src/service/course.rs b/src/service/course.rs index df515be..03035ed 100644 --- a/src/service/course.rs +++ b/src/service/course.rs @@ -12,9 +12,10 @@ use crate::domain::course_note_file::CourseNoteFile; use crate::domain::homework_file::HomeworkFile; use crate::domain::question_image::QuestionImage; use crate::domain::role::Role; -use crate::domain::term::{self, TermId}; +use crate::domain::term::TermId; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; +use crate::service::term; /// Refuse the write when this course's term is archived — a pre-flight guard, /// accepted race (see README concurrency model): a term archived after this @@ -22,7 +23,7 @@ use crate::error::{AppError, ValidationError}; pub async fn require_open(db: &Database, course: &Course) -> Result<(), AppError> { match course.get_term() { None => Ok(()), - Some(term) => term::Term::require_open(term, db).await, + Some(term) => term::require_open(db, term).await, } } diff --git a/src/service/exam_attempt.rs b/src/service/exam_attempt.rs index 12a250c..bda756b 100644 --- a/src/service/exam_attempt.rs +++ b/src/service/exam_attempt.rs @@ -40,7 +40,7 @@ use crate::error::AppError; /// subject delete's cascade — the only writer outside attempt starts, paired /// with the question writes' subject check — is now a conditional statement on /// the subject's own reference counter -/// ([`crate::domain::subject::Subject::delete`]), which every question create, +/// ([`crate::db::subject::delete`]), which every question create, /// re-tag and delete moves. // corner-cut: global RwLock, shard per-exam if save latency ever matters. pub(crate) static EXAM_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(()); @@ -522,11 +522,11 @@ mod tests { .unwrap(); // A real subject row, not a minted id: a question claims a reference on // its subject and is refused if that subject does not exist. - let subject = crate::domain::subject::Subject::create( + let subject = crate::db::subject::create( + db, &crate::db::course::a_test_course(db).await, crate::domain::subject::SubjectName::try_new("topic").unwrap(), crate::domain::subject::SubjectDescription::try_new("").unwrap(), - db, ) .await .unwrap(); diff --git a/src/service/mod.rs b/src/service/mod.rs index 1265c46..c10835d 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -23,5 +23,7 @@ pub mod profile; pub mod registration; pub mod session; pub mod settings; +pub mod subject; +pub mod term; pub mod user; pub mod work_entry; diff --git a/src/service/subject.rs b/src/service/subject.rs new file mode 100644 index 0000000..156e3d7 --- /dev/null +++ b/src/service/subject.rs @@ -0,0 +1,89 @@ +//! Subject workflows: the two id resolvers every question/homework tag goes +//! through — the same-course rule for curriculum content, existence-only for +//! the bank's cross-course origin metadata — over the row writes in +//! [`crate::db::subject`]. + +use crate::database::Database; +use crate::db::subject; +use crate::domain::course::CourseId; +use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName}; +use crate::error::{AppError, ValidationError}; + +pub async fn create( + db: &Database, + course: &CourseId, + name: SubjectName, + description: SubjectDescription, +) -> Result { + subject::create(db, course, name, description).await +} + +/// The subject row, for callers that only inspect it — the web layer's gates +/// read through here. +pub async fn read(db: &Database, id: &SubjectId) -> Result, AppError> { + subject::read(db, id).await +} + +/// Several subjects in one query — the bulk half of a list endpoint that +/// names each row's subject (a read per row would be an N+1). +pub async fn list_by_ids(db: &Database, ids: &[&SubjectId]) -> Result, AppError> { + subject::list_by_ids(db, ids).await +} + +pub async fn list_for_course( + db: &Database, + course: &CourseId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + subject::list_for_course(db, course, limit, offset).await +} + +pub async fn update( + db: &Database, + target: Subject, + name: Option, + description: Option, +) -> Result { + subject::update(db, target, name, description).await +} + +pub async fn delete(db: &Database, target: Subject) -> Result { + subject::delete(db, target).await +} + +/// Turn a request-supplied subject id into a validated reference, provided the +/// subject belongs to `course` — a question may only be tagged with a subject +/// of its own exam's course. Unknown or foreign subjects are a `400` naming +/// the field. Shared by the question create/update handlers. +pub async fn in_course(db: &Database, id: &str, course: &CourseId) -> Result { + let subject = + subject::read(db, &SubjectId::from_key(id)) + .await? + .ok_or(AppError::Validation(ValidationError::Invalid { + field: "subject_id", + reason: "subject does not exist", + }))?; + if subject.get_course() != course { + return Err(AppError::Validation(ValidationError::Invalid { + field: "subject_id", + reason: "subject belongs to a different course", + })); + } + Ok(subject.get_id().clone()) +} + +/// Turn a request-supplied subject id into a validated reference, checking only +/// that the subject exists — no course tie. For the question bank, whose subject +/// is cross-course origin metadata: the same-course rule applies at instantiate +/// time, not here. An unknown subject is a `400` naming the field. +pub async fn must_exist(db: &Database, id: &str) -> Result { + let subject = + subject::read(db, &SubjectId::from_key(id)) + .await? + .ok_or(AppError::Validation(ValidationError::Invalid { + field: "subject_id", + reason: "subject does not exist", + }))?; + Ok(subject.get_id().clone()) +} diff --git a/src/service/term.rs b/src/service/term.rs new file mode 100644 index 0000000..7f75039 --- /dev/null +++ b/src/service/term.rs @@ -0,0 +1,111 @@ +//! Term workflows: the archived-refusal rule every write against past +//! structure pays — the link resolver every new course/class link passes +//! through, the row-level write gate, and the linked-refusal mapping on the +//! delete. The queries live in [`crate::db::term`]. + +use crate::database::Database; +use crate::db::term; +use crate::domain::term::{Term, TermId, TermName, archived_error}; +use crate::domain::timestamp::Timestamp; +use crate::error::{AppError, ValidationError}; + +pub async fn create( + db: &Database, + name: TermName, + starts_at: Timestamp, + ends_at: Timestamp, +) -> Result { + term::create(db, name, starts_at, ends_at).await +} + +/// The term row, for callers that only inspect it — the web layer's gates +/// read through here. +pub async fn read(db: &Database, id: &TermId) -> Result, AppError> { + term::read(db, id).await +} + +pub async fn list_all( + db: &Database, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + term::list_all(db, limit, offset).await +} + +/// Turn an optional request-supplied term id into a validated reference — +/// `None` stays `None`, an unknown id is a `400` naming the field, and an +/// *archived* one is a `409 term_archived`. That last refusal lives here +/// rather than in each handler because this is the single spot every new +/// link to a term passes through — course create/update and class +/// create/update alike: past years take no new structure. +pub async fn resolve(db: &Database, id: Option<&str>) -> Result, AppError> { + let Some(id) = id else { + return Ok(None); + }; + let resolved = term::read(db, &TermId::from_key(id)) + .await? + .ok_or(AppError::Validation(ValidationError::Invalid { + field: "term_id", + reason: "term does not exist", + }))?; + if resolved.is_archived() { + return Err(archived_error()); + } + Ok(Some(resolved.get_id().clone())) +} + +/// Refuse when the named term is archived. A missing row is `Ok(())`: a +/// dangling link is not this guard's error, and the caller that cares +/// already answers it (see [`crate::domain::term::gone_error`]). +pub async fn require_open(db: &Database, id: &TermId) -> Result<(), AppError> { + match term::read(db, id).await? { + Some(term) if term.is_archived() => Err(archived_error()), + _ => Ok(()), + } +} + +/// Refuse when this term row is archived — the read-only rule for past +/// structure, judged against a row the caller already read through [`read`]; +/// a missing row is the caller's 404, not this guard's answer. +pub fn require_writable(t: &Term) -> Result<(), AppError> { + if t.is_archived() { + return Err(archived_error()); + } + Ok(()) +} + +/// Update an open term; an archived one is refused — past years are +/// read-only. +pub async fn update( + db: &Database, + target: Term, + name: Option, + starts_at: Option, + ends_at: Option, +) -> Result { + term::update(db, target, name, starts_at, ends_at).await +} + +/// Delete the term while nothing links it. The linked-refusal is the rule's +/// own answer, so the message the web layer used to pick is coded here; a +/// row that is already gone is the store's `404` ([`term::delete`]). +pub async fn delete(db: &Database, target: Term) -> Result<(), AppError> { + if term::delete(db, target).await? { + Ok(()) + } else { + Err(AppError::Conflict( + "courses are still linked to this term — unlink them first", + )) + } +} + +/// Archive a term; idempotent — an already-archived term answers with the +/// stamp it already had. +pub async fn archive(db: &Database, target: Term) -> Result { + term::archive(db, target).await +} + +/// Re-open an archived term; idempotent the same way. +pub async fn unarchive(db: &Database, target: Term) -> Result { + term::unarchive(db, target).await +} diff --git a/src/web/bank_questions.rs b/src/web/bank_questions.rs index cc2cd42..7a8476e 100644 --- a/src/web/bank_questions.rs +++ b/src/web/bank_questions.rs @@ -33,14 +33,14 @@ use crate::domain::exam_question::{ }; use crate::domain::note_file::FileContentType; use crate::domain::role::Role; -use crate::domain::subject::{Subject, SubjectId}; +use crate::domain::subject::SubjectId; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::service; use crate::state::AppState; use super::dto::person_map; use super::exams::ChoiceResponse; -use super::subjects::subject_must_exist; use super::{ ChoiceBody, ImageUpload, Page, PageParams, RequireTeacher, UploadFileForm, read_image_upload, remove_blob, serve_inline_blob, set_or_clear, store_blob, @@ -51,7 +51,7 @@ use super::{ // `subject` off every template — and that delete no longer takes any lock: it // is a conditional statement on the subject's own reference counters, which // bank templates deliberately do not hold (blocking on them was a dead end; see -// [`crate::domain::subject::Subject::delete`]). With the writer gone the three +// [`crate::db::subject::delete`]). With the writer gone the three // reader leases guarded nothing, and what they claimed to guard was already // open in production: the lock lived in one process, and the deployment runs // exactly one process (stop-the-world upgrades) — there is nothing else to @@ -447,7 +447,7 @@ async fn create_question( Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { // Origin metadata only — no course to check it against, but it must exist. - let subject = subject_must_exist(&req.subject_id, &st.db).await?; + let subject = service::subject::must_exist(&st.db, &req.subject_id).await?; let text = QuestionText::try_new(&req.text)?; let points = QuestionPoints::try_new(req.points)?; // Nothing stored to match against on create: every option is new and every @@ -538,16 +538,17 @@ async fn list_questions( .iter() .filter_map(BankQuestion::get_subject) .collect(); - let subject_names: HashMap = Subject::list_by_ids(&subject_ids, &st.db) - .await? - .iter() - .map(|subject| { - ( - subject.get_id().key().to_string(), - subject.get_name().as_str().to_string(), - ) - }) - .collect(); + let subject_names: HashMap = + service::subject::list_by_ids(&st.db, &subject_ids) + .await? + .iter() + .map(|subject| { + ( + subject.get_id().key().to_string(), + subject.get_name().as_str().to_string(), + ) + }) + .collect(); let people = person_map(questions.iter().map(|q| q.get_owner().clone()), &st.db).await?; let empty: Vec = Vec::new(); @@ -645,7 +646,7 @@ async fn update_question( // Omitted keeps the stored subject — which may already be `None`, cleared // by that subject's delete. let subject = match req.subject_id { - Some(ref subject_id) => Some(subject_must_exist(subject_id, &st.db).await?), + Some(ref subject_id) => Some(service::subject::must_exist(&st.db, subject_id).await?), None => question.get_subject().cloned(), }; let text = match req.text { @@ -951,7 +952,10 @@ mod tests { let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash) .await .unwrap(); - crate::service::user::set_role(db, user.get_id(), role).await.unwrap().0 + crate::service::user::set_role(db, user.get_id(), role) + .await + .unwrap() + .0 } /// Every bank route is `RequireTeacher` today, so this is pinned at the diff --git a/src/web/classes.rs b/src/web/classes.rs index dc88ebd..5109c87 100644 --- a/src/web/classes.rs +++ b/src/web/classes.rs @@ -27,10 +27,10 @@ use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::service::class_blueprint; use crate::service::parent_link::ensure_can_observe; +use crate::service::term; use crate::state::AppState; use super::courses::can_manage_course; -use super::terms::resolve_term; use super::{ CurrentUser, Page, PageParams, PersonRef, RequireManager, RequireTeacher, person_map, set_or_clear, undo_if_demoted, @@ -355,7 +355,7 @@ async fn create_class( // Pre-flight only: `ClassGroup::create` claims a reference on the term // before it writes the link, and a term deleted in between fails that claim // with this very error — so an unknown id reads the same whichever side wins. - let term = resolve_term(req.term_id.as_deref(), &st.db).await?; + let term = term::resolve(&st.db, req.term_id.as_deref()).await?; let teacher = teacher_or_none(req.teacher_id.as_deref(), &st.db).await?; let class = ClassGroup::create( user.get_id(), @@ -554,7 +554,7 @@ async fn update_class( ) -> Result, AppError> { let class = class_or_404(&id, &st.db).await?; // The class's *current* term, so a move off an archived year is refused - // too; `resolve_term` below holds the other end (the term moved onto). + // too; `term::resolve` below holds the other end (the term moved onto). class.require_open(&st.db).await?; // Only what the request actually carried is validated and written — an @@ -567,7 +567,7 @@ async fn update_class( }; let term = match req.term_id { // Explicit `null` clears the link; a value must name a real term. - Some(ref update) => Some(resolve_term(update.as_deref(), &st.db).await?), + Some(ref update) => Some(term::resolve(&st.db, update.as_deref()).await?), None => None, }; let teacher = match req.teacher_id { diff --git a/src/web/courses.rs b/src/web/courses.rs index f599d1c..1654b1f 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -18,7 +18,7 @@ use crate::domain::exam::{ }; use crate::domain::homework::{Homework, HomeworkTitle}; use crate::domain::role::Role; -use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; +use crate::domain::subject::{SubjectDescription, SubjectName}; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; @@ -26,8 +26,6 @@ use crate::service; use crate::state::AppState; use super::homework::{description_or_none, resolve_assigned}; -use super::subjects::subject_in_course; -use super::terms::resolve_term; use super::{ CourseResponse, CurrentUser, ExamResponse, HomeworkResponse, Page, PageParams, PersonRef, RequireManager, RequireTeacher, SessionResponse, SubjectResponse, check_not_past, @@ -326,7 +324,7 @@ async fn create_course( // Pre-flight only: the create itself claims a reference on the term before // it writes the link, and a term deleted in between fails that claim with // this very error — so an unknown id reads the same whichever side wins. - let term = resolve_term(req.term_id.as_deref(), &st.db).await?; + let term = service::term::resolve(&st.db, req.term_id.as_deref()).await?; check_capacity(req.capacity)?; let course = service::course::create( &st.db, @@ -496,7 +494,7 @@ async fn update_course( // (keep), an explicit `null` is `Some(None)` (write `NONE`). let term = match req.term_id { // Explicit `null` clears the link; a value must name a real term. - Some(ref update) => Some(resolve_term(update.as_deref(), &st.db).await?), + Some(ref update) => Some(service::term::resolve(&st.db, update.as_deref()).await?), None => None, }; // Explicit `null` lifts the cap; a value must be positive. @@ -964,7 +962,7 @@ async fn create_subject_in_course( let name = SubjectName::try_new(&req.name)?; let description = SubjectDescription::try_new(&req.description.unwrap_or_default())?; - let subject = Subject::create(course.get_id(), name, description, &st.db).await?; + let subject = service::subject::create(&st.db, course.get_id(), name, description).await?; Ok((StatusCode::CREATED, Json(SubjectResponse::new(&subject)))) } @@ -1003,7 +1001,7 @@ async fn list_course_subjects( )); } let (subjects, total) = - Subject::list_for_course(course.get_id(), limit, offset, &st.db).await?; + service::subject::list_for_course(&st.db, course.get_id(), limit, offset).await?; let items = subjects.iter().map(SubjectResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -1082,7 +1080,7 @@ async fn create_homework_in_course( // No lease: the create takes the subject's reference counter in the same // breath as the row, and the subject delete is refused while that counter // is non-zero — so the check below is only a pre-flight for the message. - let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; + let subject = service::subject::in_course(&st.db, &req.subject_id, course.get_id()).await?; let assigned = resolve_assigned(req.assigned, course.get_id(), &st.db).await?; let homework = Homework::create( course.get_id(), @@ -1297,7 +1295,10 @@ mod tests { let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash) .await .unwrap(); - crate::service::user::set_role(db, user.get_id(), role).await.unwrap().0 + crate::service::user::set_role(db, user.get_id(), role) + .await + .unwrap() + .0 } /// A course `creator` made, with nobody assigned. @@ -1326,7 +1327,10 @@ mod tests { assert!(owns_course(&course, &creator)); for role in [Role::Student, Role::Parent] { - let demoted = crate::service::user::set_role(&db, creator.get_id(), role).await.unwrap().0; + let demoted = crate::service::user::set_role(&db, creator.get_id(), role) + .await + .unwrap() + .0; assert!( !can_manage_course(&course, &demoted), "{role:?} creator still manages the course" @@ -1354,7 +1358,10 @@ mod tests { // ...but never an owner, assigned or not. assert!(!owns_course(&course, &assigned)); - let demoted = crate::service::user::set_role(&db, assigned.get_id(), Role::Student).await.unwrap().0; + let demoted = crate::service::user::set_role(&db, assigned.get_id(), Role::Student) + .await + .unwrap() + .0; assert!(!can_manage_course(&course, &demoted)); } @@ -1413,7 +1420,9 @@ mod tests { let db = init_mem().await.unwrap(); let creator = user("teacher", Role::Teacher, &db).await; let course = course(&creator, &db).await; - crate::service::user::set_role(&db, creator.get_id(), Role::Student).await.unwrap(); + crate::service::user::set_role(&db, creator.get_id(), Role::Student) + .await + .unwrap(); for role in [Role::Manager, Role::Admin] { let boss = user(&format!("boss{}", role.as_str()), role, &db).await; diff --git a/src/web/exams/mod.rs b/src/web/exams/mod.rs index 6cf2ea8..3ae63eb 100644 --- a/src/web/exams/mod.rs +++ b/src/web/exams/mod.rs @@ -36,7 +36,6 @@ use crate::state::AppState; use super::bank_questions::BankQuestionResponse; use super::courses::{can_manage_course, can_view_course, visible_courses}; -use super::subjects::subject_in_course; use super::{ ChoiceBody, CurrentUser, ExamResponse, ImageUpload, Page, PageParams, PersonRef, RequireTeacher, Scheduled, UploadFileForm, WindowParams, blob_path, check_not_past, paginate, diff --git a/src/web/exams/questions.rs b/src/web/exams/questions.rs index 5e46570..fda8965 100644 --- a/src/web/exams/questions.rs +++ b/src/web/exams/questions.rs @@ -178,7 +178,7 @@ pub(crate) async fn create_question( // freeze gate rides inside the insert's own transaction. exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; - let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; + let subject = service::subject::in_course(&st.db, &req.subject_id, course.get_id()).await?; let text = QuestionText::try_new(&req.text)?; let points = QuestionPoints::try_new(req.points)?; // No stored choices to match against on create, so every option is new and @@ -318,7 +318,9 @@ pub(crate) async fn update_question( let question = exam_question::question_of_exam(exam.get_id(), &qid, &st.db).await?; let subject = match req.subject_id { - Some(ref subject_id) => subject_in_course(subject_id, course.get_id(), &st.db).await?, + Some(ref subject_id) => { + service::subject::in_course(&st.db, subject_id, course.get_id()).await? + } None => question.get_subject().clone(), }; let text = match req.text { @@ -475,7 +477,7 @@ pub(crate) async fn question_from_bank( // No lease — same reasoning as `create_question`. The freeze gate rides in // the insert's transaction. exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; - let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; + let subject = service::subject::in_course(&st.db, &req.subject_id, course.get_id()).await?; let template = BankQuestion::read(&BankQuestionId::from_key(&bid), &st.db) .await? diff --git a/src/web/homework.rs b/src/web/homework.rs index 5cf7487..b2253c3 100644 --- a/src/web/homework.rs +++ b/src/web/homework.rs @@ -38,7 +38,6 @@ use crate::state::AppState; use super::courses::{can_manage_course, can_view_course, visible_courses}; use super::notes::content_disposition; -use super::subjects::subject_in_course; use super::{ CurrentUser, HomeworkResponse, Page, PageParams, RequireTeacher, UploadFileForm, blob_path, check_not_past, paginate, read_upload, remove_blob, set_or_clear, @@ -73,7 +72,7 @@ use super::{ /// /// The subject rule has left: creating a homework and re-tagging one move the /// subject's reference counter, and the subject delete is refused while that -/// counter is non-zero ([`crate::domain::subject::Subject::delete`]), so +/// counter is non-zero ([`crate::db::subject::delete`]), so /// neither the create ([`super::courses`]) nor the outside writer the subject /// delete used to take is on this list any more. /// @@ -372,7 +371,9 @@ async fn update_homework( // A kept (absent) due date may already be past; a newly set one may not be. check_not_past("due_at", due_at)?; let subject = match req.subject_id { - Some(ref subject_id) => Some(subject_in_course(subject_id, course.get_id(), &st.db).await?), + Some(ref subject_id) => { + Some(service::subject::in_course(&st.db, subject_id, course.get_id()).await?) + } None => None, }; // The orphan guard runs on exactly the requests that re-scope the audience. diff --git a/src/web/subjects.rs b/src/web/subjects.rs index 959a97a..33c1052 100644 --- a/src/web/subjects.rs +++ b/src/web/subjects.rs @@ -8,9 +8,10 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::database::Database; -use crate::domain::course::{Course, CourseId}; +use crate::domain::course::Course; use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName}; -use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::error::{AppError, ErrorResponse}; +use crate::service::subject; use crate::state::AppState; use super::courses::{can_manage_course, can_view_course}; @@ -28,50 +29,10 @@ struct UpdateSubject { description: Option, } -/// Turn a request-supplied subject id into a validated reference, provided the -/// subject belongs to `course` — a question may only be tagged with a subject -/// of its own exam's course. Unknown or foreign subjects are a `400` naming -/// the field. Shared by the question create/update handlers. -pub(crate) async fn subject_in_course( - id: &str, - course: &CourseId, - db: &Database, -) -> Result { - let subject = - Subject::read(&SubjectId::from_key(id), db) - .await? - .ok_or(AppError::Validation(ValidationError::Invalid { - field: "subject_id", - reason: "subject does not exist", - }))?; - if subject.get_course() != course { - return Err(AppError::Validation(ValidationError::Invalid { - field: "subject_id", - reason: "subject belongs to a different course", - })); - } - Ok(subject.get_id().clone()) -} - -/// Turn a request-supplied subject id into a validated reference, checking only -/// that the subject exists — no course tie. For the question bank, whose subject -/// is cross-course origin metadata: the same-course rule applies at instantiate -/// time, not here. An unknown subject is a `400` naming the field. -pub(crate) async fn subject_must_exist(id: &str, db: &Database) -> Result { - let subject = - Subject::read(&SubjectId::from_key(id), db) - .await? - .ok_or(AppError::Validation(ValidationError::Invalid { - field: "subject_id", - reason: "subject does not exist", - }))?; - Ok(subject.get_id().clone()) -} - /// The subject plus its course, or a 404 — every handler here gates on the /// parent course, so they always travel together. async fn subject_with_course(id: &str, db: &Database) -> Result<(Subject, Course), AppError> { - let subject = Subject::read(&SubjectId::from_key(id), db) + let subject = subject::read(db, &SubjectId::from_key(id)) .await? .ok_or(AppError::NotFound)?; let course = crate::service::course::read(db, subject.get_course()) @@ -154,7 +115,7 @@ async fn update_subject( .map(SubjectDescription::try_new) .transpose()?; - let updated = subject.update(name, description, &st.db).await?; + let updated = subject::update(&st.db, subject, name, description).await?; Ok(Json(SubjectResponse::new(&updated))) } @@ -199,6 +160,6 @@ async fn delete_subject( // three process-wide locks (the only site that held more than one) around // two cross-table counts, which were stale by the time the delete landed and // let a concurrent request create a question on a subject being deleted. - subject.delete(&st.db).await?; + subject::delete(&st.db, subject).await?; Ok(StatusCode::NO_CONTENT) } diff --git a/src/web/terms.rs b/src/web/terms.rs index 4506b15..c98a85b 100644 --- a/src/web/terms.rs +++ b/src/web/terms.rs @@ -7,10 +7,10 @@ use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; -use crate::database::Database; -use crate::domain::term::{self, Term, TermId, TermName}; +use crate::domain::term::{Term, TermId, TermName}; use crate::domain::timestamp::Timestamp; -use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::error::{AppError, ErrorResponse}; +use crate::service; use crate::state::AppState; use super::{CurrentUser, Page, PageParams, RequireManager, check_time_range}; @@ -69,31 +69,6 @@ impl TermResponse { } } -/// Turn an optional request-supplied term id into a validated reference — -/// `None` stays `None`, an unknown id is a `400` naming the field, and an -/// *archived* one is a `409 term_archived`. That last refusal is here rather -/// than in each handler because this is the single spot every new link to a -/// term passes through — course create/update and class create/update alike: -/// past years take no new structure. -pub(crate) async fn resolve_term( - id: Option<&str>, - db: &Database, -) -> Result, AppError> { - let Some(id) = id else { - return Ok(None); - }; - let term = Term::read(&TermId::from_key(id), db) - .await? - .ok_or(AppError::Validation(ValidationError::Invalid { - field: "term_id", - reason: "term does not exist", - }))?; - if term.is_archived() { - return Err(term::archived_error()); - } - Ok(Some(term.get_id().clone())) -} - /// Create an academic term. Requires manager+. Past dates are allowed — /// terms are calendar structure, not schedules. #[utoipa::path( @@ -119,7 +94,7 @@ async fn create_term( let starts_at = Timestamp::from_millis(req.starts_at); let ends_at = Timestamp::from_millis(req.ends_at); check_time_range(Some(starts_at), Some(ends_at))?; - let term = Term::create(name, starts_at, ends_at, &st.db).await?; + let term = service::term::create(&st.db, name, starts_at, ends_at).await?; Ok((StatusCode::CREATED, Json(TermResponse::new(&term)))) } @@ -145,7 +120,7 @@ async fn list_terms( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let (terms, total) = Term::list_all(limit, offset, &st.db).await?; + let (terms, total) = service::term::list_all(&st.db, limit, offset).await?; let items = terms.iter().map(TermResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -168,7 +143,7 @@ async fn get_term( CurrentUser(_user): CurrentUser, Path(id): Path, ) -> Result, AppError> { - let term = Term::read(&TermId::from_key(&id), &st.db) + let term = service::term::read(&st.db, &TermId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; Ok(Json(TermResponse::new(&term))) @@ -203,21 +178,18 @@ async fn update_term( let starts_at = req.starts_at.map(Timestamp::from_millis); let ends_at = req.ends_at.map(Timestamp::from_millis); - let term = Term::read(&TermId::from_key(&id), &st.db) + let term = service::term::read(&st.db, &TermId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; - if term.is_archived() { - return Err(term::archived_error()); - } - // Pre-flight only: the range check is re-made inside the UPDATE's `WHERE` - // (`Term::update`), so a concurrent move of the end this PATCH omits cannot - // slip an inverted range past this snapshot. + // Pre-flight only: the range check is re-made inside the UPDATE's own + // `WHERE` (the term update in the db layer), so a concurrent move of the + // end this PATCH omits cannot slip an inverted range past this snapshot. check_time_range( Some(starts_at.unwrap_or_else(|| term.get_starts_at())), Some(ends_at.unwrap_or_else(|| term.get_ends_at())), )?; - let updated = term.update(name, starts_at, ends_at, &st.db).await?; + let updated = service::term::update(&st.db, term, name, starts_at, ends_at).await?; Ok(Json(TermResponse::new(&updated))) } @@ -244,17 +216,11 @@ async fn delete_term( RequireManager(_user): RequireManager, Path(id): Path, ) -> Result { - let term = Term::read(&TermId::from_key(&id), &st.db) + let term = service::term::read(&st.db, &TermId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; - if term.is_archived() { - return Err(term::archived_error()); - } - if !term.delete(&st.db).await? { - return Err(AppError::Conflict( - "courses are still linked to this term — unlink them first", - )); - } + service::term::require_writable(&term)?; + service::term::delete(&st.db, term).await?; Ok(StatusCode::NO_CONTENT) } @@ -279,10 +245,10 @@ async fn archive_term( RequireManager(_user): RequireManager, Path(id): Path, ) -> Result, AppError> { - let term = Term::read(&TermId::from_key(&id), &st.db) + let term = service::term::read(&st.db, &TermId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; - let archived = term.archive(&st.db).await?; + let archived = service::term::archive(&st.db, term).await?; Ok(Json(TermResponse::new(&archived))) } @@ -306,9 +272,9 @@ async fn unarchive_term( RequireManager(_user): RequireManager, Path(id): Path, ) -> Result, AppError> { - let term = Term::read(&TermId::from_key(&id), &st.db) + let term = service::term::read(&st.db, &TermId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; - let reopened = term.unarchive(&st.db).await?; + let reopened = service::term::unarchive(&st.db, term).await?; Ok(Json(TermResponse::new(&reopened))) } diff --git a/tests/regress_course_child_orphans.rs b/tests/regress_course_child_orphans.rs index b5d2c2f..2c48c69 100644 --- a/tests/regress_course_child_orphans.rs +++ b/tests/regress_course_child_orphans.rs @@ -12,7 +12,7 @@ //! lists it to every manager+ — undeletable, //! - an orphan `course_session` 404s forever through `session_with_course`, //! - an orphan `subject` 404s through `subject_with_course`, but -//! `subject_must_exist` still accepts its id, so a bank template can be +//! `must_exist` still accepts its id, so a bank template can be //! tagged with a subject nobody can reach. //! //! All three creates now go through `cap::touch_and_create`, which *moves* the @@ -33,7 +33,7 @@ //! per child beside the create it pins — //! `db::exam::tests::an_exam_never_outlives_its_course`, //! `db::course_session::tests::a_session_never_outlives_its_course`, -//! `domain::subject::tests::a_subject_never_outlives_its_course` — over the +//! `db::subject::tests::a_subject_never_outlives_its_course` — over the //! shared harness `db::course::assert_no_child_outlives_a_course_delete`. //! It is `#[ignore]`d and needs a real server, because the subject there *is* //! the store's conflict detection, which the embedded engine does not have: it @@ -58,7 +58,7 @@ use hezarfen_backend::domain::exam::{ ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle, }; use hezarfen_backend::domain::settings::Settings; -use hezarfen_backend::domain::subject::{Subject, SubjectDescription, SubjectName}; +use hezarfen_backend::domain::subject::{SubjectDescription, SubjectName}; use hezarfen_backend::domain::timestamp::Timestamp; use hezarfen_backend::domain::user::UserId; use hezarfen_backend::error::AppError; @@ -138,11 +138,11 @@ fn make_session(course: CourseId, db: Database) -> JoinHandle JoinHandle> { tokio::spawn(async move { - Subject::create( + hezarfen_backend::db::subject::create( + &db, &course, SubjectName::try_new("Limits").unwrap(), SubjectDescription::try_new("").unwrap(), - &db, ) .await .map(|_| ()) diff --git a/tests/regress_course_delete.rs b/tests/regress_course_delete.rs index 5eabdfe..377ee31 100644 --- a/tests/regress_course_delete.rs +++ b/tests/regress_course_delete.rs @@ -47,7 +47,7 @@ async fn drop_course(db: &hezarfen_backend::database::Database, course: &str) { /// A bank template outlives the course it was saved out of — it is a separate, /// school-wide library — so the cascade owes it the same cleanup its children's -/// own deletes perform: `Exam::delete` clears `source_exam`, `Subject::delete` +/// own deletes perform: `Exam::delete` clears `source_exam`, `db::subject::delete` /// clears `subject`. The course cascade deleted both rows and neither link, /// leaving a template pointing at two ids that no longer exist — the /// `source_exam` one forever (nothing else ever visits that column) and the