From 5711f4c68063d17ad7ccc6290cd037638e6adf44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 11 Sep 2026 09:05:54 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=B9=20chore:=20split=20course=20into?= =?UTF-8?q?=20domain/db/service=20layers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ai/server.rs | 4 +- src/db/course.rs | 1025 +++++++++++++++++++++++++ src/db/mod.rs | 1 + src/db/note.rs | 2 +- src/domain/bank_question.rs | 2 +- src/domain/class_blueprint.rs | 2 +- src/domain/class_course.rs | 8 +- src/domain/class_group.rs | 18 +- src/domain/class_member.rs | 6 +- src/domain/course.rs | 1013 +----------------------- src/domain/course_note.rs | 6 +- src/domain/course_note_file.rs | 6 +- src/domain/course_session.rs | 10 +- src/domain/enrollment.rs | 10 +- src/domain/event.rs | 2 +- src/domain/exam.rs | 22 +- src/domain/exam_answer.rs | 2 +- src/domain/exam_attempt.rs | 4 +- src/domain/exam_question.rs | 4 +- src/domain/homework.rs | 2 +- src/domain/homework_file.rs | 2 +- src/domain/homework_result.rs | 2 +- src/domain/homework_submission.rs | 2 +- src/domain/rag_output.rs | 6 +- src/domain/session_attendance.rs | 2 +- src/domain/subject.rs | 16 +- src/domain/term.rs | 19 +- src/service/course.rs | 181 +++++ src/service/mod.rs | 1 + src/web/attendance.rs | 2 +- src/web/boards.rs | 4 +- src/web/classes.rs | 18 +- src/web/course_notes.rs | 18 +- src/web/courses.rs | 153 ++-- src/web/events.rs | 4 +- src/web/exam_ws.rs | 4 +- src/web/exams/attempts.rs | 6 +- src/web/exams/images.rs | 6 +- src/web/exams/mod.rs | 10 +- src/web/exams/questions.rs | 12 +- src/web/homework.rs | 16 +- src/web/marks.rs | 4 +- src/web/mod.rs | 29 +- src/web/sessions.rs | 10 +- src/web/subjects.rs | 6 +- src/web/users.rs | 6 +- tests/integration.rs | 41 +- tests/regress_course_child_orphans.rs | 39 +- tests/regress_course_delete.rs | 10 +- 49 files changed, 1484 insertions(+), 1294 deletions(-) create mode 100644 src/db/course.rs create mode 100644 src/service/course.rs diff --git a/src/ai/server.rs b/src/ai/server.rs index 90a6886..6292f46 100644 --- a/src/ai/server.rs +++ b/src/ai/server.rs @@ -26,7 +26,7 @@ use crate::constant::{ REQUEST_TIMEOUT_SECS, }; use crate::database::Database; -use crate::domain::course::Course; + use crate::domain::course_note::CourseNote; use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId}; use crate::domain::user::{User, UserId}; @@ -639,7 +639,7 @@ async fn open_blob( .await .map_err(unavailable)? .ok_or_else(missing)?; - let course = Course::read(note.get_course(), &db) + let course = crate::service::course::read(&db, note.get_course()) .await .map_err(unavailable)? .ok_or_else(missing)?; diff --git a/src/db/course.rs b/src/db/course.rs new file mode 100644 index 0000000..4c08f7e --- /dev/null +++ b/src/db/course.rs @@ -0,0 +1,1025 @@ +//! The `course` table: the unit exams, sessions, subjects and enrollments +//! hang off. Listed newest first; deleted with its whole subtree in one +use surrealdb::types::{RecordId, SurrealValue}; + +use crate::constant::{ + CLASS_COURSE_COUNT_FIELD, COURSE_COUNT_FIELD, ENROLLMENT_COUNT_FIELD, REF_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::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; +use crate::domain::term::{self, TermId}; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// The `THROW` marker the delete guard aborts with — a roster that is not +/// empty, or a course row that is no longer there. +const ROSTER_MARK: &str = "course_roster"; + +/// Create the course, claiming a reference on the term it links (if any) in +/// the *same transaction* as the row: the claim is a conditional write on +/// the term row, so it fails when the term is already gone and it makes the +/// term undeletable the instant this link exists — and a crash can never +/// leave one without the other, which a claim sent as its own query could +/// (the count would strand and the term be undeletable forever). +pub async fn create( + db: &Database, + creator: &UserId, + title: CourseTitle, + description: CourseDescription, + kind: CourseKind, + term: Option, + capacity: Option, +) -> Result { + let course = Course { + id: CourseId::generate(), + creator: creator.clone(), + teachers: Vec::new(), + term, + capacity, + title, + description, + kind, + }; + let id = course.id.record(); + let Some(term) = course.term.clone() else { + let created: Option = db.create(id).content(course).await?; + return created.ok_or_else(|| AppError::Internal("failed to create course".into())); + }; + match cap::claim_and_create( + &term.record(), + COURSE_COUNT_FIELD, + cap::UNLIMITED, + &id, + &course, + db, + ) + .await? + { + cap::Claimed::Made(created) => Ok(created), + // Uncapped, so "full" can only mean the conditional write matched no + // term row at all — the existence check the pre-flight lookup makes. + cap::Claimed::Full => Err(term::gone_error()), + // Unreachable: the id is a ULID this call just generated. + cap::Claimed::Duplicate => Err(AppError::Internal("failed to create course".into())), + } +} + +pub async fn read(db: &Database, id: &CourseId) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +pub async fn list_all(db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM course ORDER BY id DESC") + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// The courses `user` is enrolled in — the spine of `/courses/me` and the +/// marks report. +pub async fn list_enrolled( + db: &Database, + user: &UserId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new( + "course WHERE id IN (SELECT VALUE course FROM enrollment WHERE user = $usr)", + "ORDER BY id DESC", + ) + .bind("usr", user.record()) + .run(limit, offset, db) + .await +} + +/// The courses `user` runs — the ones they created plus the ones a manager +/// assigned them to. A teacher's slice of the catalog. +/// +/// corner-cut: unpaged full table scan, and it stays one — every profile read +/// of a teacher pays it, so the ceiling is the course table's size. It +/// cannot be indexed away on SurrealDB 3.2.3: an index on `creator` alone +/// leaves the `OR` a `TableScan` (EXPLAIN), and the per-element index the +/// membership half would need (`DEFINE INDEX ... FIELDS teachers[*]`) is +/// *wrong*, not merely useless — with it, `$usr IN teachers` and +/// `teachers CONTAINS $usr` return **no rows at all**, which is what the +/// integration test `assigned_teacher_manages_course_without_owning_it` +/// catches. A plain `FIELDS teachers` index is correct but unused. The +/// upgrade path is structural: a `course_teacher` link table indexed on +/// `user`, the shape `enrollment` already has, turning this into two +/// index-backed reads. +pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM course WHERE creator = $usr OR $usr IN teachers ORDER BY id DESC") + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Load every course behind `ids` (one query) — the join half of the +/// attendance report's per-course blocks. +pub async fn list_by_ids(db: &Database, ids: &[CourseId]) -> Result, AppError> { + if ids.is_empty() { + return Ok(Vec::new()); + } + let records: Vec = ids.iter().map(CourseId::record).collect(); + let mut result = db + .query("SELECT * FROM course WHERE id IN $ids") + .bind(("ids", records)) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Request-scoped: `teachers` is written by [`assign_teacher`], +/// [`unassign_teacher`] and the demotion sweep, and nothing guards +/// the course row across the handler's read and this write (its `TERM_LOCK` +/// window guards the *term* it links, and the assign path takes no lock at +/// all) — so a field the request omitted (`None`) is not written at all. +/// Sending the snapshot's value back instead would revert a concurrent +/// edit of that field; scoping the `SET` alone does not stop that, the +/// values have to come from the request. `term` and `capacity` are +/// nullable, so they take the outer/inner `Option>`: `None` = +/// omitted (keep), `Some(None)` = clear. +pub async fn update( + db: &Database, + course: Course, + title: Option, + description: Option, + kind: Option, + term: Option>, + capacity: Option>, +) -> Result { + // A term move claims the new term and releases the old one inside the + // very transaction that moves the link, so no crash can leave a count + // without its link (the term would be undeletable forever) or a link + // without its count. A PATCH that carried no `term_id`, or re-stated the + // link it already had, moves neither counter. + let (claim, release) = term::ref_move(course.term.as_ref(), &term); + let expected = course.term.as_ref().map(TermId::record); + FieldUpdate::new(course.id.record()) + .set("title", title) + .set("description", description) + .set("kind", kind) + .set("term", term.map(|term| term.map(|term| term.record()))) + .set("capacity", capacity) + .refcount( + COURSE_COUNT_FIELD, + "term", + expected, + claim, + release, + term::gone_error(), + ) + .run::(db) + .await +} + +/// Assign `teacher` to run this course, or return the course untouched if +/// they already run it — assignment is idempotent, like enrollment. +/// Field-scoped, and the new list is folded server-side out of the *stored* +/// one: a course PATCH awaits a term lookup between its read and its write, +/// so a whole-row save from either side would revert the other. The +/// `array::distinct` keeps the assignment idempotent even when two requests +/// name the same teacher at once (the early return only sees a stale row). +pub async fn assign_teacher( + db: &Database, + course: Course, + teacher: &UserId, +) -> Result { + if course.is_assigned(teacher) { + return Ok(course); + } + let mut result = db + .query( + "UPDATE $id SET teachers = array::distinct(array::append(teachers, $usr)) + RETURN AFTER", + ) + .bind(("id", course.id.record())) + .bind(("usr", teacher.record())) + .await? + .check()?; + result + .take::>(0)? + .into_iter() + .next() + .ok_or(AppError::NotFound) +} + +/// Drop `teacher` from this course. `None` when they weren't assigned, so +/// the web layer can answer 404 instead of pretending it removed someone. +pub async fn unassign_teacher( + db: &Database, + course: Course, + teacher: &UserId, +) -> Result, AppError> { + if !course.is_assigned(teacher) { + return Ok(None); + } + // Same field-scoped story as [`assign_teacher`]; `-=` drops the + // one link off the stored list without touching the course's own text. + let mut result = db + .query("UPDATE $id SET teachers -= $usr RETURN AFTER") + .bind(("id", course.id.record())) + .bind(("usr", teacher.record())) + .await? + .check()?; + Ok(Some( + result + .take::>(0)? + .into_iter() + .next() + .ok_or(AppError::NotFound)?, + )) +} + +/// Strip `user` from every course they were assigned to — the sweep for a +/// user demoted below `teacher`, who may no longer run anything. +pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> { + db.query("UPDATE course SET teachers -= $usr WHERE $usr IN teachers") + .bind(("usr", user.record())) + .await? + .check()?; + Ok(()) +} + +/// Delete the course and cascade-remove everything inside it: results, +/// attempts, answers, and question/answer images of its exams, its +/// homework with their submissions, submission files, and grades, its +/// enrollments, the class attachments that pumped some of them (each class +/// gets its count back, or it would be undeletable over rows pointing at +/// nothing), its sessions with their roll call, its subjects, and the +/// exams themselves. The children go in one transaction so a crash can't +/// leave an exam pointing at a deleted course. The image and +/// homework-file *blobs* are the web layer's to remove — it collects +/// their names before calling this. +/// +/// **Bank templates** survive it — they are a separate, reusable library +/// spanning every course — so their `source_exam` and `subject` links are +/// cleared instead, in this same transaction, exactly as +/// [`crate::domain::exam::Exam::delete`] and +/// [`crate::domain::subject::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 +/// at a dead subject the next `PATCH` omitting `subject_id` writes straight +/// back. +/// +/// The **grade blueprints** naming it are swept in that same transaction. +/// Nothing else can reach them — a blueprint holds its courses as a list on +/// its own row, not as link rows this cascade could delete — and an id left +/// behind is permanent rather than merely stale: the pump's own +/// [`crate::domain::class_blueprint::ClassBlueprint::prune`] fires only +/// while walking a section, so a grade with no sections can never drop one, +/// and every `PATCH` of that template is refused for naming a course that +/// does not exist, which is precisely the call documented as the repair. +/// +/// It is a table scan, deliberately unindexed: `class_blueprint` holds one +/// row per grade label the school uses (a dozen), a course delete is rare, +/// and the per-element index the `WHERE` would want +/// (`FIELDS courses[*]`) is the one this store answers with **no rows at +/// all** — the trap [`list_for_teacher`] documents. +/// +/// The marks going with it give their exam kinds' references back, counted +/// per kind inside this same transaction — the mirror of `Exam::delete`. +/// Skipping it would leave every kind the course graded under counted +/// forever, and a counted kind can never leave the school's settings. +/// +/// `false` = refused, nothing was written: someone is still enrolled. The +/// roster is read off the course's own `enrollment_count`, so the check and +/// the delete are one conditional write on one record — an enroll racing +/// this either takes its seat first (and the delete is refused) or finds +/// the row gone (and is refused itself). `Err(NotFound)` +/// keeps the answer a concurrent *delete* used to get. +pub async fn delete(db: &Database, course: Course) -> Result { + let sql = format!( + "BEGIN TRANSACTION; + LET $gone = (DELETE $course WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE); + IF array::len($gone) = 0 {{ THROW '{ROSTER_MARK}' }}; + FOR $row IN $gone {{ + IF $row.term != NONE {{ + UPDATE $row.term SET {COURSE_COUNT_FIELD} = \ + math::max([({COURSE_COUNT_FIELD} ?? 0) - 1, 0]); + }}; + }}; + FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result + WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course) + GROUP BY kind) ?? []) {{ + UPDATE type::record('kind_ref', $row.kind) SET {REF_COUNT_FIELD} = \ + math::max([({REF_COUNT_FIELD} ?? 0) - $row.n, 0]) + }}; + DELETE exam_result WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); + DELETE exam_attempt WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); + DELETE exam_answer WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); + DELETE answer_image WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); + DELETE question_image WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); + DELETE exam_question WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); + DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course)); + DELETE homework_submission WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course); + DELETE homework_result WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course); + DELETE course_note_file WHERE course_note IN (SELECT VALUE id FROM course_note WHERE course = $course); + DELETE course_note WHERE course = $course; + LET $detached = (DELETE class_course WHERE course = $course RETURN BEFORE); + FOR $row IN ($detached ?? []) {{ + UPDATE $row.class SET {CLASS_COURSE_COUNT_FIELD} = \ + math::max([({CLASS_COURSE_COUNT_FIELD} ?? 0) - 1, 0]); + }}; + UPDATE class_blueprint SET courses -= $course WHERE $course IN courses; + DELETE session_attendance WHERE course = $course; + DELETE course_session WHERE course = $course; + DELETE enrollment WHERE course = $course; + UPDATE bank_question SET subject = NONE + WHERE subject IN (SELECT VALUE id FROM subject WHERE course = $course); + DELETE subject WHERE course = $course; + DELETE homework WHERE course = $course; + UPDATE bank_question SET source_exam = NONE + WHERE source_exam IN (SELECT VALUE id FROM exam WHERE course = $course); + DELETE exam WHERE course = $course; + COMMIT TRANSACTION;" + ); + // An aborted transaction errors *every* slot, most with a generic "not + // executed" — only the THROW's own slot names the marker, and a lost + // round is re-sent rather than reported (see [`transaction_with_retry`]). + let (_, mut errors) = transaction_with_retry( + db, + &sql, + &[("course".into(), course.id.record().into_value())], + &[ROSTER_MARK], + ) + .await?; + if errors + .values() + .any(|error| error.to_string().contains(ROSTER_MARK)) + { + // Full stop or already gone: the guard cannot tell those apart, and + // only the refusal path pays for the extra read that can. + return match read(db, &course.id).await? { + Some(_) => Ok(false), + None => Err(AppError::NotFound), + }; + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + Ok(true) +} + +/// A real course row, for the tests of every child that must now prove its +/// parent exists (`Exam`, `CourseSession`, `Subject` — see +/// [`cap::touch_and_create`]). A minted id nothing wrote is a 404 there, the +/// way a minted subject id already is for an exam question. +#[cfg(test)] +pub(crate) async fn a_test_course(db: &Database) -> CourseId { + create( + db, + &UserId::generate(), + CourseTitle::try_new("test course").unwrap(), + CourseDescription::try_new("").unwrap(), + CourseKind::course(), + None, + None, + ) + .await + .unwrap() + .id +} + +/// The race half of "a child of a course must not survive its deletion", run +/// for one child table: [`delete`] is held open by the schema and +/// `make` fires its create inside that window, four rounds. +/// +/// The harness lives here, beside the cascade being raced, and each child names +/// its own pin in its own module (`exam`, `course_session`, `subject`) — the +/// loop, the window and the verdict are one fact about *this* delete, and three +/// copies of it would drift into three different tests of three different +/// things. The sequential half — a create against a course that is already gone +/// — is `tests/regress_course_child_orphans.rs`, which needs no server. +/// +/// The window is opened by the database rather than by a lucky interleaving: a +/// `DEFINE EVENT` on `course` fires *inside* the delete's own transaction the +/// instant the row goes, so the `SLEEP` lands between the delete and its +/// `DELETE WHERE course = $course` sweep every time — and a create +/// fired into it reads a course that is still there (removed, uncommitted) +/// while the sweep already ran on a snapshot without its row. +/// +/// One child per round, for the reason the menu and `class_course` twins +/// document: a second writer makes the delete lose and re-send, and the re-sent +/// sweep clears the evidence. +/// +/// Real server, and every caller is `#[ignore]`d for it: the subject *is* the +/// store's conflict detection, which `init_mem`'s embedded engine does not +/// have — it commits both sides and answers `Ok` to each, so this passes there +/// on broken code. +#[cfg(test)] +pub(crate) async fn assert_no_child_outlives_a_course_delete( + scratch: &str, + table: &str, + make: fn(CourseId, Database) -> tokio::task::JoinHandle>, +) { + // The guard is held for the whole test: these bursts are sub-millisecond, + // and a sibling race test's burst pushes a delete clean out of its window. + let (db, _serialized) = crate::database::init_test_server(scratch).await; + db.query( + "DEFINE EVENT hold_the_window ON TABLE course WHEN $event = 'DELETE' \ + THEN { SLEEP 1s; };", + ) + .await + .expect("define the window event") + .check() + .expect("check the window event"); + + let (mut swept, mut orphans) = (0, 0); + for round in 0..4 { + let course = a_test_course(&db).await; + let drop_it = { + let (course, db) = (course.clone(), db.clone()); + tokio::spawn(async move { + delete( + &db, + read(&db, &course) + .await + .unwrap() + .expect("the course is there"), + ) + .await + }) + }; + // The create starts inside the held window. + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let child = make(course.clone(), db.clone()).await.unwrap(); + let dropped = drop_it.await.unwrap(); + + // A 404 for the create, or a refusal for the delete, is a correct + // answer — the only defect is stored state. Nothing may 500. + assert!( + !matches!(child, Err(AppError::Db(_))), + "{table} round {round}: a raced create must be answered, not 500: {child:?}" + ); + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "{table} round {round}: a raced delete must be answered, not 500: {dropped:?}" + ); + + // Stored state is the whole verdict; a return value is not evidence. + if read(&db, &course).await.unwrap().is_none() { + swept += 1; + let mut left = db + .query(format!( + "SELECT VALUE id FROM {table} WHERE course = $course" + )) + .bind(("course", course.record())) + .await + .unwrap() + .check() + .unwrap(); + orphans += left.take::>(0).unwrap().len(); + } else if matches!(dropped, Ok(true)) { + panic!("{table} round {round}: the delete reported success, the course is still there"); + } + } + eprintln!("Course::delete raced by a {table} create: {swept}/4 rounds deleted the course"); + assert!( + swept > 0, + "{table}: no round ever deleted the course, so the window was never reached" + ); + assert_eq!(orphans, 0, "{table}: a child outlived its course"); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::term::{Term, TermName}; + + async fn course_on(term: Option, db: &Database) -> Course { + create( + db, + &UserId::from_key("teacher"), + CourseTitle::try_new("algebra").unwrap(), + CourseDescription::try_new("").unwrap(), + CourseKind::course(), + term, + None, + ) + .await + .unwrap() + } + + /// The bite test for the delete guard that replaced `ENROLL_LOCK`: the + /// roster check is now the `WHERE` on the delete itself, so only the guard + /// can refuse — and it must refuse having written nothing, cascade + /// included. A `>= 0` guard passes the roster branch and fails here. + #[tokio::test] + async fn a_course_with_a_roster_refuses_to_delete() { + use crate::domain::enrollment::Enrollment; + + let db = crate::database::init_mem().await.unwrap(); + let teacher = UserId::from_key("teacher"); + let student = UserId::from_key("student"); + let course = course_on(None, &db).await; + Enrollment::enroll(course.get_id(), &student, &teacher, &db) + .await + .unwrap(); + + assert!( + !delete(&db, course.clone()).await.unwrap(), + "a non-empty roster must refuse the delete" + ); + assert!( + read(&db, course.get_id()).await.unwrap().is_some(), + "a refused delete may write nothing" + ); + assert!( + Enrollment::read_for_user(course.get_id(), &student, &db) + .await + .unwrap() + .is_some(), + "…the cascade least of all" + ); + + Enrollment::remove(course.get_id(), &student, &db) + .await + .unwrap(); + assert!(delete(&db, course.clone()).await.unwrap()); + assert!(read(&db, course.get_id()).await.unwrap().is_none()); + + // The other half of the same guard: once the course row is gone the + // seat claim matches nothing, so a late enroll is a 404 rather than a + // roster row that outlived its course. + let late = Enrollment::enroll(course.get_id(), &student, &teacher, &db) + .await + .expect_err("enrolling into a deleted course must fail"); + assert!(matches!(late, AppError::NotFound), "got {late:?}"); + } + + /// The bite test for the refcount that replaced `TERM_LOCK`: a term is + /// undeletable exactly while a course links it, and every way a link can + /// end — PATCH away, and the course's own delete — gives the reference + /// back. Dropping the release in `delete` leaves the term deletable never. + #[tokio::test] + async fn a_term_is_deletable_only_once_no_course_links_it() { + let db = crate::database::init_mem().await.unwrap(); + let at = crate::domain::timestamp::Timestamp::from_millis; + let term = Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), &db) + .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(), + "two linked courses must refuse the delete" + ); + + update(&db, patched, None, None, None, Some(None), None) + .await + .unwrap(); + assert!( + !term.clone().delete(&db).await.unwrap(), + "one link is still one link" + ); + + assert!(delete(&db, linked).await.unwrap()); + assert!( + term.clone().delete(&db).await.unwrap(), + "the last link gone, the term may go" + ); + let again = term.delete(&db).await; + assert!( + matches!(again, Err(AppError::NotFound)), + "a second delete is a 404, not a refusal: {again:?}" + ); + } + + /// The claim doubles as the existence check the lock used to make safe: + /// a term that is already gone cannot be linked, with the same 400 the + /// web layer's pre-flight lookup gives. + #[tokio::test] + async fn a_course_cannot_link_a_term_that_is_gone() { + let db = crate::database::init_mem().await.unwrap(); + let error = create( + &db, + &UserId::from_key("teacher"), + CourseTitle::try_new("algebra").unwrap(), + CourseDescription::try_new("").unwrap(), + CourseKind::course(), + Some(TermId::from_key("gone")), + None, + ) + .await + .expect_err("a missing term must not be linkable"); + assert!(error.to_string().contains("term does not exist")); + } + + /// The stored `course_count` on one term, absent counting as zero. + async fn count_on(term: &TermId, db: &Database) -> i64 { + let mut result = db + .query(format!( + "SELECT VALUE ({COURSE_COUNT_FIELD} ?? 0) FROM $term" + )) + .bind(("term", term.record())) + .await + .unwrap() + .check() + .unwrap(); + result + .take::>(0) + .unwrap() + .first() + .copied() + .unwrap_or(0) + } + + /// How many rows `sql` selects ids for. + async fn rows(sql: &str, db: &Database) -> usize { + let mut result = db.query(sql).await.unwrap().check().unwrap(); + result.take::>(0).unwrap().len() + } + + 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) + .await + .unwrap() + } + + /// The invariant, on the create path: a claim and the row it accounts for + /// commit together or not at all. A refused create must therefore leave + /// *neither* — no course row, and no count stranded on a term (which is + /// worse than it sounds: the term's delete guard reads that count, so a + /// stray one makes the term undeletable forever). + #[tokio::test] + async fn a_refused_create_writes_neither_row_nor_count() { + let db = crate::database::init_mem().await.unwrap(); + let term = a_term("2026", &db).await; + let id = term.get_id().clone(); + assert!(term.delete(&db).await.unwrap()); + + let error = create( + &db, + &UserId::from_key("teacher"), + CourseTitle::try_new("algebra").unwrap(), + CourseDescription::try_new("").unwrap(), + CourseKind::course(), + Some(id), + None, + ) + .await + .expect_err("a term that is gone must not be linkable"); + assert!(error.to_string().contains("term does not exist")); + assert_eq!( + rows("SELECT VALUE id FROM course", &db).await, + 0, + "a refused create may write no row" + ); + assert_eq!( + rows("SELECT VALUE id FROM term", &db).await, + 0, + "…and least of all a count on a term it just brought back" + ); + } + + /// The invariant on the PATCH path, both directions: a move carries the new + /// term's claim and the old term's release with the link itself. + #[tokio::test] + async fn a_term_move_moves_the_count() { + let db = crate::database::init_mem().await.unwrap(); + let from = a_term("2026", &db).await; + let to = a_term("2027", &db).await; + let course = course_on(Some(from.get_id().clone()), &db).await; + assert_eq!(count_on(from.get_id(), &db).await, 1); + + let moved = update( + &db, + course, + None, + None, + None, + Some(Some(to.get_id().clone())), + None, + ) + .await + .unwrap(); + assert_eq!(moved.get_term(), Some(to.get_id())); + assert_eq!( + count_on(from.get_id(), &db).await, + 0, + "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()); + } + + /// The double-claim guard. Both movers compute their claim and release from + /// the row as *they* read it, so two PATCHes moving the same course off the + /// same term both release it and both claim their target — two counts for + /// one link, and the loser's target is undeletable forever. The second call + /// here runs on the struct read before the first one landed, which is that + /// race with the interleaving pinned: it must be refused outright, and the + /// counts must read as if it never ran. + #[tokio::test] + async fn a_stale_mover_is_refused_and_claims_nothing() { + let db = crate::database::init_mem().await.unwrap(); + let from = a_term("2026", &db).await; + let to = a_term("2027", &db).await; + let other = a_term("2028", &db).await; + let course = course_on(Some(from.get_id().clone()), &db).await; + let stale = course.clone(); + update( + &db, + course, + None, + None, + None, + Some(Some(to.get_id().clone())), + None, + ) + .await + .unwrap(); + + let error = update( + &db, + stale.clone(), + None, + None, + None, + Some(Some(other.get_id().clone())), + None, + ) + .await + .expect_err("a mover that read a link it no longer holds must be refused"); + assert!( + matches!(error, AppError::Conflict(_)), + "a lost CAS is a conflict, not a 404 or a 500: {error:?}" + ); + let stored = read(&db, stale.get_id()).await.unwrap().unwrap(); + assert_eq!(stored.get_term(), Some(to.get_id()), "the winner's link"); + assert_eq!( + count_on(from.get_id(), &db).await, + 0, + "released once, not twice" + ); + assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once"); + assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed"); + + // Same race from the other end: the snapshot says *no* link, so the CAS + // is against an absent column — the shape a bound `NONE` has to match. + let unlinked = course_on(None, &db).await; + let stale = unlinked.clone(); + update( + &db, + unlinked, + None, + None, + None, + Some(Some(to.get_id().clone())), + None, + ) + .await + .unwrap(); + let error = update( + &db, + stale.clone(), + None, + None, + None, + Some(Some(other.get_id().clone())), + None, + ) + .await + .expect_err("a mover that read an absent link someone else filled must be refused"); + assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); + assert_eq!(count_on(to.get_id(), &db).await, 2, "one claim per link"); + assert_eq!( + count_on(other.get_id(), &db).await, + 0, + "still never claimed" + ); + // …and the unraced set still lands, so the CAS did not just break moves. + let stored = read(&db, stale.get_id()).await.unwrap().unwrap(); + assert_eq!(stored.get_term(), Some(to.get_id())); + } + + /// The same race with the counters taken out of it. A PATCH that re-states + /// the term its snapshot showed shifts *nothing* — [`term::ref_move`] hands + /// back no claim and no release — so if the guard were armed off the counter + /// move it would not be armed here at all, and the write would land: the + /// winner's link silently dragged back, its claim stranded on a term nothing + /// points at (undeletable forever) and the reverted-to term linked at a + /// count of zero (deletable while linked). The guard is armed by the request + /// *carrying* the column instead, which is why this is refused. + #[tokio::test] + async fn a_stale_re_stater_is_refused_and_reverts_nothing() { + let db = crate::database::init_mem().await.unwrap(); + let from = a_term("2026", &db).await; + let to = a_term("2027", &db).await; + let course = course_on(Some(from.get_id().clone()), &db).await; + let stale = course.clone(); + update( + &db, + course, + None, + None, + None, + Some(Some(to.get_id().clone())), + None, + ) + .await + .unwrap(); + + let error = update( + &db, + stale.clone(), + None, + None, + None, + Some(Some(from.get_id().clone())), + None, + ) + .await + .expect_err("re-stating a link someone else moved must be refused"); + assert!( + matches!(error, AppError::Conflict(_)), + "a lost CAS is a conflict, not a silent 200: {error:?}" + ); + let stored = read(&db, stale.get_id()).await.unwrap().unwrap(); + assert_eq!(stored.get_term(), Some(to.get_id()), "the winner's link"); + assert_eq!( + count_on(from.get_id(), &db).await, + 0, + "the reverted-to term must not end up linked at zero" + ); + assert_eq!( + count_on(to.get_id(), &db).await, + 1, + "…nor the winner's term counted with nothing pointing at it" + ); + + // A *genuine* no-op re-state — nobody moved underneath it — still lands, + // and still moves no counter: the CAS passes trivially. + let fresh = read(&db, stale.get_id()).await.unwrap().unwrap(); + let same = update( + &db, + fresh, + None, + None, + None, + Some(Some(to.get_id().clone())), + None, + ) + .await + .expect("re-stating the link the row really holds is not a conflict"); + assert_eq!(same.get_term(), Some(to.get_id())); + assert_eq!(count_on(from.get_id(), &db).await, 0, "nothing moved"); + assert_eq!(count_on(to.get_id(), &db).await, 1, "…in either direction"); + } + + /// The rollback proof. The transaction releases the old term *before* it + /// claims the new one, so a move to a term that is gone has already + /// decremented when the claim throws — the old count still being 1 is the + /// abort undoing a write that really happened, not a branch that never ran. + /// The title moves in the same PATCH, and must not stick either. + #[tokio::test] + async fn a_term_move_to_a_dead_term_leaves_everything_untouched() { + let db = crate::database::init_mem().await.unwrap(); + let 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()); + let course = course_on(Some(from.get_id().clone()), &db).await; + + let error = update( + &db, + course.clone(), + Some(CourseTitle::try_new("moved").unwrap()), + None, + None, + Some(Some(dead_id)), + None, + ) + .await + .expect_err("a term that is gone must not be linkable"); + assert!(error.to_string().contains("term does not exist")); + + let stored = read(&db, course.get_id()).await.unwrap().unwrap(); + assert_eq!(stored.get_term(), Some(from.get_id()), "the link stays put"); + assert_eq!( + stored.get_title().as_str(), + "algebra", + "…and so does the row" + ); + assert_eq!( + count_on(from.get_id(), &db).await, + 1, + "the release must roll back with the abort" + ); + assert_eq!( + rows("SELECT VALUE id FROM term", &db).await, + 1, + "the dead term must not be resurrected by the claim" + ); + } + + /// MEASUREMENT — the one race test that actually measures the retry, and + /// the only one of the four that does. The other three (subject, term, + /// exam) are status-code guards; each says so on itself. + /// + /// [`delete`] is one `BEGIN…COMMIT` whose guard reads + /// `enrollment_count` off the very record a concurrent enroll increments, + /// so the two contend by design, and its cascade is long enough that a + /// rival's write lands mid-transaction. Losing that round writes nothing, + /// which is what makes re-sending it the recovery. Without + /// [`crate::database::transaction_with_retry`] a lost round comes out as a + /// 500: mutation-tested by cutting that retry loop to one attempt, which + /// turns this test red at 1-2 of 20 rounds (3 runs in 5 — the window is + /// real but narrow, so a single green run under the mutation means nothing). + /// + /// A refusal (`Ok(false)`) or an `Err(NotFound)` is *correct* here and + /// must not fail this test: the only defect is `AppError::Db`. + /// + /// The rate is counted over the whole loop instead of asserted per round, + /// because a per-round `assert!` aborts at the first hit and would report + /// "1 of 1" for a bug the point of this test is to *quantify*. + /// + /// Multi-threaded and on a real server for the reasons spelled out on + /// [`crate::domain::fee_plan_assignment`]'s pair of race tests: the + /// current-thread runtime never interleaves the two, and the embedded + /// engine does not conflict-check concurrent writes to one record at all. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_delete_racing_an_enroll_never_answers_500() { + use crate::domain::enrollment::Enrollment; + let (db, _serialized) = crate::database::init_test_server("course_delete_race").await; + let (mut delete_500, mut enroll_500, mut enrolled) = (0, 0, 0); + let (mut last_delete, mut last_enroll) = (String::new(), String::new()); + for round in 0..20 { + let course = course_on(None, &db).await; + + // A *burst* of enrolls, and a delete held back by a sweeping beat. + // Released together the delete is one statement while an enroll + // spends two round trips reading before it claims, so it wins every + // round and the guard is never contended at all (measured: 0/20 + // seats placed). Six racers over a 0-3ms sweep put the single + // statement somewhere inside the counter writes instead. + let drop_it = { + let (course, db) = (course.clone(), db.clone()); + let beat = std::time::Duration::from_millis(round % 4); + tokio::spawn(async move { + tokio::time::sleep(beat).await; + delete(&db, course).await + }) + }; + let joins: Vec<_> = (0..6) + .map(|seat| { + let (id, db) = (course.get_id().clone(), db.clone()); + let student = UserId::from_key(&format!("stu{round}_{seat}")); + tokio::spawn(async move { + Enrollment::enroll(&id, &student, &UserId::from_key("mgr"), &db).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 join in joins { + let join = join.await.unwrap(); + if matches!(join, Err(AppError::Db(_))) { + enroll_500 += 1; + last_enroll = format!("{join:?}"); + } + } + // Stored state, not the return values: a seat that landed is what + // the guard had to see. + if !Enrollment::list_for_course(course.get_id(), None, 0, &db) + .await + .unwrap() + .0 + .is_empty() + { + enrolled += 1; + } + } + eprintln!( + "Course::delete raced: {delete_500}/20 delete 500s, {enroll_500} enroll 500s, \ + {enrolled}/20 rounds with a seat placed" + ); + assert!( + enrolled > 0, + "no round ever placed an enrollment, so the delete guard was never contended" + ); + assert_eq!( + delete_500, 0, + "a raced delete must be refused, not 500: {delete_500}/20 rounds, last {last_delete}" + ); + assert_eq!( + enroll_500, 0, + "a raced enroll must retry, not 500: {enroll_500}/20 rounds, last {last_enroll}" + ); + } +} diff --git a/src/db/mod.rs b/src/db/mod.rs index 32af5c7..517b2c1 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -1,6 +1,7 @@ //! The only layer that executes queries. pub mod cap; +pub mod course; pub mod field_update; pub mod note; pub mod page; diff --git a/src/db/note.rs b/src/db/note.rs index 662d640..eb1f0f1 100644 --- a/src/db/note.rs +++ b/src/db/note.rs @@ -86,7 +86,7 @@ pub async fn update( /// row pointing at nothing. /// /// Children first, in one transaction, the way -/// [`crate::domain::course::Course::delete`] does it: as two queries, an +/// [`crate::db::course::delete`] does it: as two queries, an /// upload that committed in between kept its row while the note went, and /// nothing could ever list or delete it again. pub async fn delete(db: &Database, note: Note) -> Result<(Note, Vec), AppError> { diff --git a/src/domain/bank_question.rs b/src/domain/bank_question.rs index 865afb9..e9e567c 100644 --- a/src/domain/bank_question.rs +++ b/src/domain/bank_question.rs @@ -846,7 +846,7 @@ mod tests { // 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( - &crate::domain::course::a_test_course(&db).await, + &crate::db::course::a_test_course(&db).await, crate::domain::subject::SubjectName::try_new("topic").unwrap(), crate::domain::subject::SubjectDescription::try_new("").unwrap(), &db, diff --git a/src/domain/class_blueprint.rs b/src/domain/class_blueprint.rs index 5fa26fb..734ebdb 100644 --- a/src/domain/class_blueprint.rs +++ b/src/domain/class_blueprint.rs @@ -702,7 +702,7 @@ impl ClassBlueprint { /// Drop a course that no longer exists out of this blueprint's list. /// /// The delete does this itself now: - /// [`crate::domain::course::Course::delete`] sweeps `class_blueprint` in + /// [`crate::db::course::delete`] sweeps `class_blueprint` in /// the same cascade that takes the course's `class_course` links, so a /// template stops naming a course the instant that course goes. This used /// to be the *only* thing that could remove such an id, and that was the diff --git a/src/domain/class_course.rs b/src/domain/class_course.rs index 837613f..a3c9ca6 100644 --- a/src/domain/class_course.rs +++ b/src/domain/class_course.rs @@ -239,7 +239,6 @@ mod tests { use super::*; use crate::domain::class_member::ClassMember; use crate::domain::class_member::tests::{a_class, a_course, counter, exists, rows, source_of}; - use crate::domain::course::Course; use crate::domain::enrollment::Enrollment; /// Attaching seeds the course from the roster the class already holds. @@ -532,11 +531,14 @@ mod tests { for round in 0..4 { let class = a_class(&format!("9-{round}"), &db).await; let algebra = a_course(&format!("algebra{round}"), None, &db).await; - let course = Course::read(&algebra, &db).await.unwrap().unwrap(); + let course = crate::db::course::read(&db, &algebra) + .await + .unwrap() + .unwrap(); let drop_it = { let db = db.clone(); - tokio::spawn(async move { course.delete(&db).await }) + tokio::spawn(async move { crate::db::course::delete(&db, course).await }) }; // The attach starts inside the held window — the course row is gone // but uncommitted, which is exactly what a course read believes. diff --git a/src/domain/class_group.rs b/src/domain/class_group.rs index 9b5aca2..6872794 100644 --- a/src/domain/class_group.rs +++ b/src/domain/class_group.rs @@ -146,7 +146,7 @@ impl ClassGroup { /// Create the class, claiming a reference on the term it links (if any) in /// the *same transaction* as the row, exactly as - /// [`crate::domain::course::Course::create`] does: the claim is a + /// [`crate::db::course::create`] does: the claim is a /// conditional write on the term row, so it fails when the term is already /// gone, it makes the term undeletable the instant this link exists, and no /// crash can leave either half without the other. @@ -230,7 +230,7 @@ impl ClassGroup { /// /// A term move claims the new term and releases the old one inside the very /// transaction that moves the link, exactly as in - /// [`crate::domain::course::Course::update`]: both counters and the link + /// [`crate::db::course::update`]: both counters and the link /// commit together, so no crash can strand a count on a term nothing links. pub async fn update( self, @@ -301,7 +301,7 @@ impl ClassGroup { /// Strip `user` from every class they were the homeroom teacher of — the /// sweep for a user demoted below `teacher`, who may no longer hold one. - /// The mirror of [`crate::domain::course::Course::unassign_everywhere`]; + /// The mirror of [`crate::db::course::unassign_everywhere`]; /// nothing is counted on this column, so there is no reference to give back. pub async fn unassign_everywhere(user: &UserId, db: &Database) -> Result<(), AppError> { db.query("UPDATE class_group SET teacher = NONE WHERE teacher = $usr") @@ -677,7 +677,7 @@ mod tests { } /// The class mirror of - /// [`crate::domain::course::Course`]'s move tests: a term move carries both + /// [`crate::db::course`]'s move tests: a term move carries both /// counters with the link, and a move to a term that is gone rolls the /// release back with the abort (the transaction releases before it claims, /// so the old count would be 0 if the abort did not undo it). @@ -794,24 +794,24 @@ mod tests { assert_eq!(count_on(to.get_id(), &db).await, 1, "still one seat"); } - /// [`crate::domain::course::Course::delete`]'s class sweep: deleting a course + /// [`crate::db::course::delete`]'s class sweep: deleting a course /// takes its `class_course` attachments with it and gives each class its /// count back, or the classes would be undeletable forever over rows that /// point at nothing. #[tokio::test] async fn deleting_a_course_sweeps_its_class_attachments() { - use crate::domain::course::{Course, CourseDescription, CourseKind, CourseTitle}; + use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; let db = crate::database::init_mem().await.unwrap(); let manager = UserId::from_key("manager"); - let course = Course::create( + let course = crate::db::course::create( + &db, &manager, CourseTitle::try_new("algebra").unwrap(), CourseDescription::try_new("").unwrap(), CourseKind::course(), None, None, - &db, ) .await .unwrap(); @@ -828,7 +828,7 @@ mod tests { .check() .unwrap(); - assert!(course.delete(&db).await.unwrap()); + assert!(crate::db::course::delete(&db, course).await.unwrap()); assert_eq!( rows("SELECT VALUE id FROM class_course", &db).await, 0, diff --git a/src/domain/class_member.rs b/src/domain/class_member.rs index dfd2132..11195f2 100644 --- a/src/domain/class_member.rs +++ b/src/domain/class_member.rs @@ -217,7 +217,7 @@ pub(crate) mod tests { use super::*; use crate::domain::class_course::ClassCourse; use crate::domain::class_group::{ClassGroup, ClassName}; - use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; + use crate::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle}; use crate::domain::enrollment::Enrollment; pub(crate) async fn a_class(name: &str, db: &Database) -> ClassGroupId { @@ -236,14 +236,14 @@ pub(crate) mod tests { } pub(crate) async fn a_course(title: &str, capacity: Option, db: &Database) -> CourseId { - Course::create( + crate::db::course::create( + db, &UserId::from_key("manager"), CourseTitle::try_new(title).unwrap(), CourseDescription::try_new("").unwrap(), CourseKind::course(), None, capacity, - db, ) .await .unwrap() diff --git a/src/domain/course.rs b/src/domain/course.rs index 9c34eec..31151f6 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -1,29 +1,18 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{ - CLASS_COURSE_COUNT_FIELD, COURSE_COUNT_FIELD, COURSE_TABLE, ENROLLMENT_COUNT_FIELD, - MAX_COURSE_DESCRIPTION_LEN, MAX_COURSE_TITLE_LEN, REF_COUNT_FIELD, -}; -use crate::database::{Database, transaction_with_retry}; -use crate::db::cap; -use crate::db::field_update::FieldUpdate; +use crate::constant::{COURSE_TABLE, MAX_COURSE_DESCRIPTION_LEN, MAX_COURSE_TITLE_LEN}; use crate::domain::monotonic_id::next_ulid; -use crate::db::page::PagedList; -use crate::domain::term::{self, TermId}; +use crate::domain::term::TermId; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; use crate::validate::{validate_course_kind, validate_optional, validate_required}; -/// The `THROW` marker the delete guard aborts with — a roster that is not -/// empty, or a course row that is no longer there. -const ROSTER_MARK: &str = "course_roster"; - #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct CourseId(RecordId); impl CourseId { /// Minted from the process-wide monotonic generator, not `Ulid::new()`: - /// courses list `id DESC` (newest first, [`Course::list_all`]), + /// courses list `id DESC` (newest first, [`crate::db::course::list_all`]), /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { Self(RecordId::new(COURSE_TABLE, next_ulid().to_string())) @@ -106,17 +95,20 @@ impl CourseKind { /// it. `teachers` are the staff a manager assigned to run it: full management /// rights inside the course, no power to delete it or change the assignment /// list. Rows written before the field existed decode with nobody assigned. +/// +/// Fields are crate-visible: [`crate::db::course`] mints the rows on create +/// and reads the id when updating and cascading a delete. #[derive(Debug, Clone, SurrealValue)] pub struct Course { - id: CourseId, - creator: UserId, + pub(crate) id: CourseId, + pub(crate) creator: UserId, #[surreal(default)] - teachers: Vec, - title: CourseTitle, - description: CourseDescription, - kind: CourseKind, - term: Option, - capacity: Option, + pub(crate) teachers: Vec, + pub(crate) title: CourseTitle, + pub(crate) description: CourseDescription, + pub(crate) kind: CourseKind, + pub(crate) term: Option, + pub(crate) capacity: Option, } impl Course { @@ -144,16 +136,6 @@ impl Course { self.term.as_ref() } - /// 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 - /// read still lets the write through. - 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, - } - } - /// The seat cap enforced at enroll time; `None` = unlimited. pub fn get_capacity(&self) -> Option { self.capacity @@ -173,877 +155,11 @@ impl Course { pub fn is_assigned(&self, user: &UserId) -> bool { self.teachers.contains(user) } - - /// Create the course, claiming a reference on the term it links (if any) in - /// the *same transaction* as the row: the claim is a conditional write on - /// the term row, so it fails when the term is already gone and it makes the - /// term undeletable the instant this link exists — and a crash can never - /// leave one without the other, which a claim sent as its own query could - /// (the count would strand and the term be undeletable forever). - pub async fn create( - creator: &UserId, - title: CourseTitle, - description: CourseDescription, - kind: CourseKind, - term: Option, - capacity: Option, - db: &Database, - ) -> Result { - let course = Course { - id: CourseId::generate(), - creator: creator.clone(), - teachers: Vec::new(), - term, - capacity, - title, - description, - kind, - }; - let id = course.id.record(); - let Some(term) = course.term.clone() else { - let created: Option = db.create(id).content(course).await?; - return created.ok_or_else(|| AppError::Internal("failed to create course".into())); - }; - match cap::claim_and_create( - &term.record(), - COURSE_COUNT_FIELD, - cap::UNLIMITED, - &id, - &course, - db, - ) - .await? - { - cap::Claimed::Made(created) => Ok(created), - // Uncapped, so "full" can only mean the conditional write matched no - // term row at all — the existence check the pre-flight lookup makes. - cap::Claimed::Full => Err(term::gone_error()), - // Unreachable: the id is a ULID this call just generated. - cap::Claimed::Duplicate => Err(AppError::Internal("failed to create course".into())), - } - } - - pub async fn read(id: &CourseId, db: &Database) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - pub async fn list_all(db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM course ORDER BY id DESC") - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// The courses `user` is enrolled in — the spine of `/courses/me` and the - /// marks report. - pub async fn list_enrolled( - user: &UserId, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new( - "course WHERE id IN (SELECT VALUE course FROM enrollment WHERE user = $usr)", - "ORDER BY id DESC", - ) - .bind("usr", user.record()) - .run(limit, offset, db) - .await - } - - /// The courses `user` runs — the ones they created plus the ones a manager - /// assigned them to. A teacher's slice of the catalog. - /// - /// corner-cut: unpaged full table scan, and it stays one — every profile read - /// of a teacher pays it, so the ceiling is the course table's size. It - /// cannot be indexed away on SurrealDB 3.2.3: an index on `creator` alone - /// leaves the `OR` a `TableScan` (EXPLAIN), and the per-element index the - /// membership half would need (`DEFINE INDEX ... FIELDS teachers[*]`) is - /// *wrong*, not merely useless — with it, `$usr IN teachers` and - /// `teachers CONTAINS $usr` return **no rows at all**, which is what the - /// integration test `assigned_teacher_manages_course_without_owning_it` - /// catches. A plain `FIELDS teachers` index is correct but unused. The - /// upgrade path is structural: a `course_teacher` link table indexed on - /// `user`, the shape `enrollment` already has, turning this into two - /// index-backed reads. - pub async fn list_for_teacher(user: &UserId, db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM course WHERE creator = $usr OR $usr IN teachers ORDER BY id DESC") - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Load every course behind `ids` (one query) — the join half of the - /// attendance report's per-course blocks. - pub async fn list_by_ids(ids: &[CourseId], db: &Database) -> Result, AppError> { - if ids.is_empty() { - return Ok(Vec::new()); - } - let records: Vec = ids.iter().map(CourseId::record).collect(); - let mut result = db - .query("SELECT * FROM course WHERE id IN $ids") - .bind(("ids", records)) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Request-scoped: `teachers` is written by [`Self::assign_teacher`], - /// [`Self::unassign_teacher`] and the demotion sweep, and nothing guards - /// the course row across the handler's read and this write (its `TERM_LOCK` - /// window guards the *term* it links, and the assign path takes no lock at - /// all) — so a field the request omitted (`None`) is not written at all. - /// Sending the snapshot's value back instead would revert a concurrent - /// edit of that field; scoping the `SET` alone does not stop that, the - /// values have to come from the request. `term` and `capacity` are - /// nullable, so they take the outer/inner `Option>`: `None` = - /// omitted (keep), `Some(None)` = clear. - pub async fn update( - self, - title: Option, - description: Option, - kind: Option, - term: Option>, - capacity: Option>, - db: &Database, - ) -> Result { - // A term move claims the new term and releases the old one inside the - // very transaction that moves the link, so no crash can leave a count - // without its link (the term would be undeletable forever) or a link - // without its count. A PATCH that carried no `term_id`, or re-stated the - // link it already had, moves neither counter. - let (claim, release) = term::ref_move(self.term.as_ref(), &term); - let expected = self.term.as_ref().map(TermId::record); - FieldUpdate::new(self.id.record()) - .set("title", title) - .set("description", description) - .set("kind", kind) - .set("term", term.map(|term| term.map(|term| term.record()))) - .set("capacity", capacity) - .refcount( - COURSE_COUNT_FIELD, - "term", - expected, - claim, - release, - term::gone_error(), - ) - .run::(db) - .await - } - - /// Assign `teacher` to run this course, or return the course untouched if - /// they already run it — assignment is idempotent, like enrollment. - /// Field-scoped, and the new list is folded server-side out of the *stored* - /// one: a course PATCH awaits a term lookup between its read and its write, - /// so a whole-row save from either side would revert the other. The - /// `array::distinct` keeps the assignment idempotent even when two requests - /// name the same teacher at once (the early return only sees a stale row). - pub async fn assign_teacher(self, teacher: &UserId, db: &Database) -> Result { - if self.is_assigned(teacher) { - return Ok(self); - } - let mut result = db - .query( - "UPDATE $id SET teachers = array::distinct(array::append(teachers, $usr)) - RETURN AFTER", - ) - .bind(("id", self.id.record())) - .bind(("usr", teacher.record())) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound) - } - - /// Drop `teacher` from this course. `None` when they weren't assigned, so - /// the web layer can answer 404 instead of pretending it removed someone. - pub async fn unassign_teacher( - self, - teacher: &UserId, - db: &Database, - ) -> Result, AppError> { - if !self.is_assigned(teacher) { - return Ok(None); - } - // Same field-scoped story as [`Self::assign_teacher`]; `-=` drops the - // one link off the stored list without touching the course's own text. - let mut result = db - .query("UPDATE $id SET teachers -= $usr RETURN AFTER") - .bind(("id", self.id.record())) - .bind(("usr", teacher.record())) - .await? - .check()?; - Ok(Some( - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound)?, - )) - } - - /// Strip `user` from every course they were assigned to — the sweep for a - /// user demoted below `teacher`, who may no longer run anything. - pub async fn unassign_everywhere(user: &UserId, db: &Database) -> Result<(), AppError> { - db.query("UPDATE course SET teachers -= $usr WHERE $usr IN teachers") - .bind(("usr", user.record())) - .await? - .check()?; - Ok(()) - } - - /// Delete the course and cascade-remove everything inside it: results, - /// attempts, answers, and question/answer images of its exams, its - /// homework with their submissions, submission files, and grades, its - /// enrollments, the class attachments that pumped some of them (each class - /// gets its count back, or it would be undeletable over rows pointing at - /// nothing), its sessions with their roll call, its subjects, and the - /// exams themselves. The children go in one transaction so a crash can't - /// leave an exam pointing at a deleted course. The image and - /// homework-file *blobs* are the web layer's to remove — it collects - /// their names before calling this. - /// - /// **Bank templates** survive it — they are a separate, reusable library - /// spanning every course — so their `source_exam` and `subject` links are - /// cleared instead, in this same transaction, exactly as - /// [`crate::domain::exam::Exam::delete`] and - /// [`crate::domain::subject::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 - /// at a dead subject the next `PATCH` omitting `subject_id` writes straight - /// back. - /// - /// The **grade blueprints** naming it are swept in that same transaction. - /// Nothing else can reach them — a blueprint holds its courses as a list on - /// its own row, not as link rows this cascade could delete — and an id left - /// behind is permanent rather than merely stale: the pump's own - /// [`crate::domain::class_blueprint::ClassBlueprint::prune`] fires only - /// while walking a section, so a grade with no sections can never drop one, - /// and every `PATCH` of that template is refused for naming a course that - /// does not exist, which is precisely the call documented as the repair. - /// - /// It is a table scan, deliberately unindexed: `class_blueprint` holds one - /// row per grade label the school uses (a dozen), a course delete is rare, - /// and the per-element index the `WHERE` would want - /// (`FIELDS courses[*]`) is the one this store answers with **no rows at - /// all** — the trap [`Self::list_for_teacher`] documents. - /// - /// The marks going with it give their exam kinds' references back, counted - /// per kind inside this same transaction — the mirror of `Exam::delete`. - /// Skipping it would leave every kind the course graded under counted - /// forever, and a counted kind can never leave the school's settings. - /// - /// `false` = refused, nothing was written: someone is still enrolled. The - /// roster is read off the course's own `enrollment_count`, so the check and - /// the delete are one conditional write on one record — an enroll racing - /// this either takes its seat first (and the delete is refused) or finds - /// the row gone (and is refused itself). `Err(NotFound)` - /// keeps the answer a concurrent *delete* used to get. - pub async fn delete(self, db: &Database) -> Result { - let sql = format!( - "BEGIN TRANSACTION; - LET $gone = (DELETE $course WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE); - IF array::len($gone) = 0 {{ THROW '{ROSTER_MARK}' }}; - FOR $row IN $gone {{ - IF $row.term != NONE {{ - UPDATE $row.term SET {COURSE_COUNT_FIELD} = \ - math::max([({COURSE_COUNT_FIELD} ?? 0) - 1, 0]); - }}; - }}; - FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result - WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course) - GROUP BY kind) ?? []) {{ - UPDATE type::record('kind_ref', $row.kind) SET {REF_COUNT_FIELD} = \ - math::max([({REF_COUNT_FIELD} ?? 0) - $row.n, 0]) - }}; - DELETE exam_result WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); - DELETE exam_attempt WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); - DELETE exam_answer WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); - DELETE answer_image WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); - DELETE question_image WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); - DELETE exam_question WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); - DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course)); - DELETE homework_submission WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course); - DELETE homework_result WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course); - DELETE course_note_file WHERE course_note IN (SELECT VALUE id FROM course_note WHERE course = $course); - DELETE course_note WHERE course = $course; - LET $detached = (DELETE class_course WHERE course = $course RETURN BEFORE); - FOR $row IN ($detached ?? []) {{ - UPDATE $row.class SET {CLASS_COURSE_COUNT_FIELD} = \ - math::max([({CLASS_COURSE_COUNT_FIELD} ?? 0) - 1, 0]); - }}; - UPDATE class_blueprint SET courses -= $course WHERE $course IN courses; - DELETE session_attendance WHERE course = $course; - DELETE course_session WHERE course = $course; - DELETE enrollment WHERE course = $course; - UPDATE bank_question SET subject = NONE - WHERE subject IN (SELECT VALUE id FROM subject WHERE course = $course); - DELETE subject WHERE course = $course; - DELETE homework WHERE course = $course; - UPDATE bank_question SET source_exam = NONE - WHERE source_exam IN (SELECT VALUE id FROM exam WHERE course = $course); - DELETE exam WHERE course = $course; - COMMIT TRANSACTION;" - ); - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the THROW's own slot names the marker, and a lost - // round is re-sent rather than reported (see [`transaction_with_retry`]). - let (_, mut errors) = transaction_with_retry( - db, - &sql, - &[("course".into(), self.id.record().into_value())], - &[ROSTER_MARK], - ) - .await?; - if errors - .values() - .any(|error| error.to_string().contains(ROSTER_MARK)) - { - // Full stop or already gone: the guard cannot tell those apart, and - // only the refusal path pays for the extra read that can. - return match Self::read(&self.id, db).await? { - Some(_) => Ok(false), - None => Err(AppError::NotFound), - }; - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - Ok(true) - } -} - -/// A real course row, for the tests of every child that must now prove its -/// parent exists (`Exam`, `CourseSession`, `Subject` — see -/// [`cap::touch_and_create`]). A minted id nothing wrote is a 404 there, the -/// way a minted subject id already is for an exam question. -#[cfg(test)] -pub(crate) async fn a_test_course(db: &Database) -> CourseId { - Course::create( - &UserId::generate(), - CourseTitle::try_new("test course").unwrap(), - CourseDescription::try_new("").unwrap(), - CourseKind::course(), - None, - None, - db, - ) - .await - .unwrap() - .id -} - -/// The race half of "a child of a course must not survive its deletion", run -/// for one child table: [`Course::delete`] is held open by the schema and -/// `make` fires its create inside that window, four rounds. -/// -/// The harness lives here, beside the cascade being raced, and each child names -/// its own pin in its own module (`exam`, `course_session`, `subject`) — the -/// loop, the window and the verdict are one fact about *this* delete, and three -/// copies of it would drift into three different tests of three different -/// things. The sequential half — a create against a course that is already gone -/// — is `tests/regress_course_child_orphans.rs`, which needs no server. -/// -/// The window is opened by the database rather than by a lucky interleaving: a -/// `DEFINE EVENT` on `course` fires *inside* the delete's own transaction the -/// instant the row goes, so the `SLEEP` lands between the delete and its -/// `DELETE WHERE course = $course` sweep every time — and a create -/// fired into it reads a course that is still there (removed, uncommitted) -/// while the sweep already ran on a snapshot without its row. -/// -/// One child per round, for the reason the menu and `class_course` twins -/// document: a second writer makes the delete lose and re-send, and the re-sent -/// sweep clears the evidence. -/// -/// Real server, and every caller is `#[ignore]`d for it: the subject *is* the -/// store's conflict detection, which `init_mem`'s embedded engine does not -/// have — it commits both sides and answers `Ok` to each, so this passes there -/// on broken code. -#[cfg(test)] -pub(crate) async fn assert_no_child_outlives_a_course_delete( - scratch: &str, - table: &str, - make: fn(CourseId, Database) -> tokio::task::JoinHandle>, -) { - // The guard is held for the whole test: these bursts are sub-millisecond, - // and a sibling race test's burst pushes a delete clean out of its window. - let (db, _serialized) = crate::database::init_test_server(scratch).await; - db.query( - "DEFINE EVENT hold_the_window ON TABLE course WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .expect("define the window event") - .check() - .expect("check the window event"); - - let (mut swept, mut orphans) = (0, 0); - for round in 0..4 { - let course = a_test_course(&db).await; - let drop_it = { - let (course, db) = (course.clone(), db.clone()); - tokio::spawn(async move { - Course::read(&course, &db) - .await - .unwrap() - .expect("the course is there") - .delete(&db) - .await - }) - }; - // The create starts inside the held window. - tokio::time::sleep(std::time::Duration::from_millis(300)).await; - let child = make(course.clone(), db.clone()).await.unwrap(); - let dropped = drop_it.await.unwrap(); - - // A 404 for the create, or a refusal for the delete, is a correct - // answer — the only defect is stored state. Nothing may 500. - assert!( - !matches!(child, Err(AppError::Db(_))), - "{table} round {round}: a raced create must be answered, not 500: {child:?}" - ); - assert!( - !matches!(dropped, Err(AppError::Db(_))), - "{table} round {round}: a raced delete must be answered, not 500: {dropped:?}" - ); - - // Stored state is the whole verdict; a return value is not evidence. - if Course::read(&course, &db).await.unwrap().is_none() { - swept += 1; - let mut left = db - .query(format!( - "SELECT VALUE id FROM {table} WHERE course = $course" - )) - .bind(("course", course.record())) - .await - .unwrap() - .check() - .unwrap(); - orphans += left.take::>(0).unwrap().len(); - } else if matches!(dropped, Ok(true)) { - panic!("{table} round {round}: the delete reported success, the course is still there"); - } - } - eprintln!("Course::delete raced by a {table} create: {swept}/4 rounds deleted the course"); - assert!( - swept > 0, - "{table}: no round ever deleted the course, so the window was never reached" - ); - assert_eq!(orphans, 0, "{table}: a child outlived its course"); } #[cfg(test)] mod tests { use super::*; - use crate::domain::term::{Term, TermName}; - - async fn course_on(term: Option, db: &Database) -> Course { - Course::create( - &UserId::from_key("teacher"), - CourseTitle::try_new("algebra").unwrap(), - CourseDescription::try_new("").unwrap(), - CourseKind::course(), - term, - None, - db, - ) - .await - .unwrap() - } - - /// The bite test for the delete guard that replaced `ENROLL_LOCK`: the - /// roster check is now the `WHERE` on the delete itself, so only the guard - /// can refuse — and it must refuse having written nothing, cascade - /// included. A `>= 0` guard passes the roster branch and fails here. - #[tokio::test] - async fn a_course_with_a_roster_refuses_to_delete() { - use crate::domain::enrollment::Enrollment; - - let db = crate::database::init_mem().await.unwrap(); - let teacher = UserId::from_key("teacher"); - let student = UserId::from_key("student"); - let course = course_on(None, &db).await; - Enrollment::enroll(course.get_id(), &student, &teacher, &db) - .await - .unwrap(); - - assert!( - !course.clone().delete(&db).await.unwrap(), - "a non-empty roster must refuse the delete" - ); - assert!( - Course::read(course.get_id(), &db).await.unwrap().is_some(), - "a refused delete may write nothing" - ); - assert!( - Enrollment::read_for_user(course.get_id(), &student, &db) - .await - .unwrap() - .is_some(), - "…the cascade least of all" - ); - - Enrollment::remove(course.get_id(), &student, &db) - .await - .unwrap(); - assert!(course.clone().delete(&db).await.unwrap()); - assert!(Course::read(course.get_id(), &db).await.unwrap().is_none()); - - // The other half of the same guard: once the course row is gone the - // seat claim matches nothing, so a late enroll is a 404 rather than a - // roster row that outlived its course. - let late = Enrollment::enroll(course.get_id(), &student, &teacher, &db) - .await - .expect_err("enrolling into a deleted course must fail"); - assert!(matches!(late, AppError::NotFound), "got {late:?}"); - } - - /// The bite test for the refcount that replaced `TERM_LOCK`: a term is - /// undeletable exactly while a course links it, and every way a link can - /// end — PATCH away, and the course's own delete — gives the reference - /// back. Dropping the release in `delete` leaves the term deletable never. - #[tokio::test] - async fn a_term_is_deletable_only_once_no_course_links_it() { - let db = crate::database::init_mem().await.unwrap(); - let at = crate::domain::timestamp::Timestamp::from_millis; - let term = Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), &db) - .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(), - "two linked courses must refuse the delete" - ); - - patched - .update(None, None, None, Some(None), None, &db) - .await - .unwrap(); - assert!( - !term.clone().delete(&db).await.unwrap(), - "one link is still one link" - ); - - assert!(linked.delete(&db).await.unwrap()); - assert!( - term.clone().delete(&db).await.unwrap(), - "the last link gone, the term may go" - ); - let again = term.delete(&db).await; - assert!( - matches!(again, Err(AppError::NotFound)), - "a second delete is a 404, not a refusal: {again:?}" - ); - } - - /// The claim doubles as the existence check the lock used to make safe: - /// a term that is already gone cannot be linked, with the same 400 the - /// web layer's pre-flight lookup gives. - #[tokio::test] - async fn a_course_cannot_link_a_term_that_is_gone() { - let db = crate::database::init_mem().await.unwrap(); - let error = Course::create( - &UserId::from_key("teacher"), - CourseTitle::try_new("algebra").unwrap(), - CourseDescription::try_new("").unwrap(), - CourseKind::course(), - Some(TermId::from_key("gone")), - None, - &db, - ) - .await - .expect_err("a missing term must not be linkable"); - assert!(error.to_string().contains("term does not exist")); - } - - /// The stored `course_count` on one term, absent counting as zero. - async fn count_on(term: &TermId, db: &Database) -> i64 { - let mut result = db - .query(format!( - "SELECT VALUE ({COURSE_COUNT_FIELD} ?? 0) FROM $term" - )) - .bind(("term", term.record())) - .await - .unwrap() - .check() - .unwrap(); - result - .take::>(0) - .unwrap() - .first() - .copied() - .unwrap_or(0) - } - - /// How many rows `sql` selects ids for. - async fn rows(sql: &str, db: &Database) -> usize { - let mut result = db.query(sql).await.unwrap().check().unwrap(); - result.take::>(0).unwrap().len() - } - - 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) - .await - .unwrap() - } - - /// The invariant, on the create path: a claim and the row it accounts for - /// commit together or not at all. A refused create must therefore leave - /// *neither* — no course row, and no count stranded on a term (which is - /// worse than it sounds: the term's delete guard reads that count, so a - /// stray one makes the term undeletable forever). - #[tokio::test] - async fn a_refused_create_writes_neither_row_nor_count() { - let db = crate::database::init_mem().await.unwrap(); - let term = a_term("2026", &db).await; - let id = term.get_id().clone(); - assert!(term.delete(&db).await.unwrap()); - - let error = Course::create( - &UserId::from_key("teacher"), - CourseTitle::try_new("algebra").unwrap(), - CourseDescription::try_new("").unwrap(), - CourseKind::course(), - Some(id), - None, - &db, - ) - .await - .expect_err("a term that is gone must not be linkable"); - assert!(error.to_string().contains("term does not exist")); - assert_eq!( - rows("SELECT VALUE id FROM course", &db).await, - 0, - "a refused create may write no row" - ); - assert_eq!( - rows("SELECT VALUE id FROM term", &db).await, - 0, - "…and least of all a count on a term it just brought back" - ); - } - - /// The invariant on the PATCH path, both directions: a move carries the new - /// term's claim and the old term's release with the link itself. - #[tokio::test] - async fn a_term_move_moves_the_count() { - let db = crate::database::init_mem().await.unwrap(); - let from = a_term("2026", &db).await; - let to = a_term("2027", &db).await; - let course = course_on(Some(from.get_id().clone()), &db).await; - assert_eq!(count_on(from.get_id(), &db).await, 1); - - let moved = course - .update(None, None, None, Some(Some(to.get_id().clone())), None, &db) - .await - .unwrap(); - assert_eq!(moved.get_term(), Some(to.get_id())); - assert_eq!( - count_on(from.get_id(), &db).await, - 0, - "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()); - } - - /// The double-claim guard. Both movers compute their claim and release from - /// the row as *they* read it, so two PATCHes moving the same course off the - /// same term both release it and both claim their target — two counts for - /// one link, and the loser's target is undeletable forever. The second call - /// here runs on the struct read before the first one landed, which is that - /// race with the interleaving pinned: it must be refused outright, and the - /// counts must read as if it never ran. - #[tokio::test] - async fn a_stale_mover_is_refused_and_claims_nothing() { - let db = crate::database::init_mem().await.unwrap(); - let from = a_term("2026", &db).await; - let to = a_term("2027", &db).await; - let other = a_term("2028", &db).await; - let course = course_on(Some(from.get_id().clone()), &db).await; - let stale = course.clone(); - course - .update(None, None, None, Some(Some(to.get_id().clone())), None, &db) - .await - .unwrap(); - - let error = stale - .clone() - .update( - None, - None, - None, - Some(Some(other.get_id().clone())), - None, - &db, - ) - .await - .expect_err("a mover that read a link it no longer holds must be refused"); - assert!( - matches!(error, AppError::Conflict(_)), - "a lost CAS is a conflict, not a 404 or a 500: {error:?}" - ); - let stored = Course::read(stale.get_id(), &db).await.unwrap().unwrap(); - assert_eq!(stored.get_term(), Some(to.get_id()), "the winner's link"); - assert_eq!( - count_on(from.get_id(), &db).await, - 0, - "released once, not twice" - ); - assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once"); - assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed"); - - // Same race from the other end: the snapshot says *no* link, so the CAS - // is against an absent column — the shape a bound `NONE` has to match. - let unlinked = course_on(None, &db).await; - let stale = unlinked.clone(); - unlinked - .update(None, None, None, Some(Some(to.get_id().clone())), None, &db) - .await - .unwrap(); - let error = stale - .clone() - .update( - None, - None, - None, - Some(Some(other.get_id().clone())), - None, - &db, - ) - .await - .expect_err("a mover that read an absent link someone else filled must be refused"); - assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); - assert_eq!(count_on(to.get_id(), &db).await, 2, "one claim per link"); - assert_eq!( - count_on(other.get_id(), &db).await, - 0, - "still never claimed" - ); - // …and the unraced set still lands, so the CAS did not just break moves. - let stored = Course::read(stale.get_id(), &db).await.unwrap().unwrap(); - assert_eq!(stored.get_term(), Some(to.get_id())); - } - - /// The same race with the counters taken out of it. A PATCH that re-states - /// the term its snapshot showed shifts *nothing* — [`term::ref_move`] hands - /// back no claim and no release — so if the guard were armed off the counter - /// move it would not be armed here at all, and the write would land: the - /// winner's link silently dragged back, its claim stranded on a term nothing - /// points at (undeletable forever) and the reverted-to term linked at a - /// count of zero (deletable while linked). The guard is armed by the request - /// *carrying* the column instead, which is why this is refused. - #[tokio::test] - async fn a_stale_re_stater_is_refused_and_reverts_nothing() { - let db = crate::database::init_mem().await.unwrap(); - let from = a_term("2026", &db).await; - let to = a_term("2027", &db).await; - let course = course_on(Some(from.get_id().clone()), &db).await; - let stale = course.clone(); - course - .update(None, None, None, Some(Some(to.get_id().clone())), None, &db) - .await - .unwrap(); - - let error = stale - .clone() - .update( - None, - None, - None, - Some(Some(from.get_id().clone())), - None, - &db, - ) - .await - .expect_err("re-stating a link someone else moved must be refused"); - assert!( - matches!(error, AppError::Conflict(_)), - "a lost CAS is a conflict, not a silent 200: {error:?}" - ); - let stored = Course::read(stale.get_id(), &db).await.unwrap().unwrap(); - assert_eq!(stored.get_term(), Some(to.get_id()), "the winner's link"); - assert_eq!( - count_on(from.get_id(), &db).await, - 0, - "the reverted-to term must not end up linked at zero" - ); - assert_eq!( - count_on(to.get_id(), &db).await, - 1, - "…nor the winner's term counted with nothing pointing at it" - ); - - // A *genuine* no-op re-state — nobody moved underneath it — still lands, - // and still moves no counter: the CAS passes trivially. - let fresh = Course::read(stale.get_id(), &db).await.unwrap().unwrap(); - let same = fresh - .update(None, None, None, Some(Some(to.get_id().clone())), None, &db) - .await - .expect("re-stating the link the row really holds is not a conflict"); - assert_eq!(same.get_term(), Some(to.get_id())); - assert_eq!(count_on(from.get_id(), &db).await, 0, "nothing moved"); - assert_eq!(count_on(to.get_id(), &db).await, 1, "…in either direction"); - } - - /// The rollback proof. The transaction releases the old term *before* it - /// claims the new one, so a move to a term that is gone has already - /// decremented when the claim throws — the old count still being 1 is the - /// abort undoing a write that really happened, not a branch that never ran. - /// The title moves in the same PATCH, and must not stick either. - #[tokio::test] - async fn a_term_move_to_a_dead_term_leaves_everything_untouched() { - let db = crate::database::init_mem().await.unwrap(); - let 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()); - let course = course_on(Some(from.get_id().clone()), &db).await; - - let error = course - .clone() - .update( - Some(CourseTitle::try_new("moved").unwrap()), - None, - None, - Some(Some(dead_id)), - None, - &db, - ) - .await - .expect_err("a term that is gone must not be linkable"); - assert!(error.to_string().contains("term does not exist")); - - let stored = Course::read(course.get_id(), &db).await.unwrap().unwrap(); - assert_eq!(stored.get_term(), Some(from.get_id()), "the link stays put"); - assert_eq!( - stored.get_title().as_str(), - "algebra", - "…and so does the row" - ); - assert_eq!( - count_on(from.get_id(), &db).await, - 1, - "the release must roll back with the abort" - ); - assert_eq!( - rows("SELECT VALUE id FROM term", &db).await, - 1, - "the dead term must not be resurrected by the claim" - ); - } #[tokio::test] async fn title_is_required() { @@ -1120,103 +236,4 @@ mod tests { assert!(decoded.get_teachers().is_empty()); assert!(!decoded.is_assigned(&assigned)); } - - /// MEASUREMENT — the one race test that actually measures the retry, and - /// the only one of the four that does. The other three (subject, term, - /// exam) are status-code guards; each says so on itself. - /// - /// `Course::delete` is one `BEGIN…COMMIT` whose guard reads - /// `enrollment_count` off the very record a concurrent enroll increments, - /// so the two contend by design, and its cascade is long enough that a - /// rival's write lands mid-transaction. Losing that round writes nothing, - /// which is what makes re-sending it the recovery. Without - /// [`crate::database::transaction_with_retry`] a lost round comes out as a - /// 500: mutation-tested by cutting that retry loop to one attempt, which - /// turns this test red at 1-2 of 20 rounds (3 runs in 5 — the window is - /// real but narrow, so a single green run under the mutation means nothing). - /// - /// A refusal (`Ok(false)`) or an `Err(NotFound)` is *correct* here and - /// must not fail this test: the only defect is `AppError::Db`. - /// - /// The rate is counted over the whole loop instead of asserted per round, - /// because a per-round `assert!` aborts at the first hit and would report - /// "1 of 1" for a bug the point of this test is to *quantify*. - /// - /// Multi-threaded and on a real server for the reasons spelled out on - /// [`crate::domain::fee_plan_assignment`]'s pair of race tests: the - /// current-thread runtime never interleaves the two, and the embedded - /// engine does not conflict-check concurrent writes to one record at all. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn a_delete_racing_an_enroll_never_answers_500() { - use crate::domain::enrollment::Enrollment; - let (db, _serialized) = crate::database::init_test_server("course_delete_race").await; - let (mut delete_500, mut enroll_500, mut enrolled) = (0, 0, 0); - let (mut last_delete, mut last_enroll) = (String::new(), String::new()); - for round in 0..20 { - let course = course_on(None, &db).await; - - // A *burst* of enrolls, and a delete held back by a sweeping beat. - // Released together the delete is one statement while an enroll - // spends two round trips reading before it claims, so it wins every - // round and the guard is never contended at all (measured: 0/20 - // seats placed). Six racers over a 0-3ms sweep put the single - // statement somewhere inside the counter writes instead. - let drop_it = { - let (course, db) = (course.clone(), db.clone()); - let beat = std::time::Duration::from_millis(round % 4); - tokio::spawn(async move { - tokio::time::sleep(beat).await; - course.delete(&db).await - }) - }; - let joins: Vec<_> = (0..6) - .map(|seat| { - let (id, db) = (course.get_id().clone(), db.clone()); - let student = UserId::from_key(&format!("stu{round}_{seat}")); - tokio::spawn(async move { - Enrollment::enroll(&id, &student, &UserId::from_key("mgr"), &db).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 join in joins { - let join = join.await.unwrap(); - if matches!(join, Err(AppError::Db(_))) { - enroll_500 += 1; - last_enroll = format!("{join:?}"); - } - } - // Stored state, not the return values: a seat that landed is what - // the guard had to see. - if !Enrollment::list_for_course(course.get_id(), None, 0, &db) - .await - .unwrap() - .0 - .is_empty() - { - enrolled += 1; - } - } - eprintln!( - "Course::delete raced: {delete_500}/20 delete 500s, {enroll_500} enroll 500s, \ - {enrolled}/20 rounds with a seat placed" - ); - assert!( - enrolled > 0, - "no round ever placed an enrollment, so the delete guard was never contended" - ); - assert_eq!( - delete_500, 0, - "a raced delete must be refused, not 500: {delete_500}/20 rounds, last {last_delete}" - ); - assert_eq!( - enroll_500, 0, - "a raced enroll must retry, not 500: {enroll_500}/20 rounds, last {last_enroll}" - ); - } } diff --git a/src/domain/course_note.rs b/src/domain/course_note.rs index c5e5ff3..d1bcfbf 100644 --- a/src/domain/course_note.rs +++ b/src/domain/course_note.rs @@ -225,19 +225,19 @@ mod tests { /// been taken, which is the row whose blob used to leak. #[tokio::test] async fn delete_returns_the_attachment_rows_it_removed() { - use crate::domain::course::{Course, CourseDescription, CourseKind, CourseTitle}; + use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; use crate::domain::course_note_file::{FileContentType, FileName}; let db = crate::database::init_mem().await.unwrap(); let creator = crate::domain::user::UserId::generate(); - let course = Course::create( + let course = crate::db::course::create( + &db, &creator, CourseTitle::try_new("Math").unwrap(), CourseDescription::try_new("").unwrap(), CourseKind::try_new("course").unwrap(), None, None, - &db, ) .await .unwrap(); diff --git a/src/domain/course_note_file.rs b/src/domain/course_note_file.rs index e6a7586..d3b2a6a 100644 --- a/src/domain/course_note_file.rs +++ b/src/domain/course_note_file.rs @@ -219,19 +219,19 @@ impl CourseNoteFile { #[cfg(test)] mod tests { use super::*; - use crate::domain::course::{Course, CourseDescription, CourseKind, CourseTitle}; + use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; async fn note_of(db: &Database, title: &str) -> CourseNote { let creator = crate::domain::user::UserId::generate(); - let course = Course::create( + let course = crate::db::course::create( + db, &creator, CourseTitle::try_new("c").unwrap(), CourseDescription::try_new("").unwrap(), CourseKind::try_new("course").unwrap(), None, None, - db, ) .await .unwrap(); diff --git a/src/domain/course_session.rs b/src/domain/course_session.rs index 0e5778b..813c6fc 100644 --- a/src/domain/course_session.rs +++ b/src/domain/course_session.rs @@ -222,7 +222,7 @@ mod tests { /// [`CourseSession::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::domain::course::assert_no_child_outlives_a_course_delete`]. + /// [`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)] @@ -242,11 +242,9 @@ mod tests { .map(|_| ()) }) } - crate::domain::course::assert_no_child_outlives_a_course_delete( - "session_orphan_race", - COURSE_SESSION_TABLE, - make, - ) + crate::db::course::assert_no_child_outlives_a_course_delete("session_orphan_race", + COURSE_SESSION_TABLE, + make,) .await; } diff --git a/src/domain/enrollment.rs b/src/domain/enrollment.rs index b0b192d..99ba4b5 100644 --- a/src/domain/enrollment.rs +++ b/src/domain/enrollment.rs @@ -4,7 +4,7 @@ use crate::constant::{ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE}; use crate::database::{Database, transaction_with_retry}; use crate::db::cap; use crate::domain::class_group::ClassGroupId; -use crate::domain::course::{Course, CourseId}; +use crate::domain::course::CourseId; use crate::db::page::PagedList; use crate::domain::role::Role; use crate::domain::user::UserId; @@ -203,7 +203,7 @@ impl Enrollment { .values() .any(|error| error.to_string().contains(FULL_MARK)) { - return match Course::read(course, db).await? { + return match crate::db::course::read(db, course).await? { Some(_) => Err(AppError::Conflict("the course is full")), None => Err(AppError::NotFound), }; @@ -416,18 +416,18 @@ mod tests { /// never wrote. Asserted on the stored row, not the returned one. #[tokio::test] async fn a_hand_placed_enrollment_stores_no_source_key() { - use crate::domain::course::{Course, CourseDescription, CourseKind, CourseTitle}; + use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; let db = crate::database::init_mem().await.unwrap(); let teacher = UserId::from_key("teacher"); - let course = Course::create( + let course = crate::db::course::create( + &db, &teacher, CourseTitle::try_new("algebra").unwrap(), CourseDescription::try_new("").unwrap(), CourseKind::course(), None, None, - &db, ) .await .unwrap(); diff --git a/src/domain/event.rs b/src/domain/event.rs index c85681c..0648d4e 100644 --- a/src/domain/event.rs +++ b/src/domain/event.rs @@ -311,7 +311,7 @@ impl Event { /// Delete the event and cascade-remove its attendance and signup rows. /// /// Children first, and all of it in one transaction the way - /// [`crate::domain::course::Course::delete`] does it: run as two queries, a + /// [`crate::db::course::delete`] does it: run as two queries, a /// registration or a mark that committed in between outlived its event — /// an orphan no read path can ever reach and no delete can ever reclaim, /// since every one of them is keyed on the event that is now gone. diff --git a/src/domain/exam.rs b/src/domain/exam.rs index bdb6c5f..c58c003 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -692,7 +692,7 @@ pub(crate) async fn published_exam(db: &Database) -> Exam { .to_vec(); Exam::create( &UserId::generate(), - &crate::domain::course::a_test_course(db).await, + &crate::db::course::a_test_course(db).await, ExamTitle::try_new("midterm").unwrap(), ExamDescription::try_new("").unwrap(), ExamKind::try_new("midterm", &allowed).unwrap(), @@ -723,7 +723,7 @@ mod tests { /// [`Exam::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::domain::course::assert_no_child_outlives_a_course_delete`]. + /// [`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)] @@ -751,11 +751,9 @@ mod tests { .map(|_| ()) }) } - crate::domain::course::assert_no_child_outlives_a_course_delete( - "exam_orphan_race", - EXAM_TABLE, - make, - ) + crate::db::course::assert_no_child_outlives_a_course_delete("exam_orphan_race", + EXAM_TABLE, + make,) .await; } @@ -968,7 +966,7 @@ mod tests { /// GUARD, not a retry measurement — read the last paragraph before /// trusting this test with the retry. See - /// [`crate::domain::course::Course::delete`]'s race test for why the rate is + /// [`crate::db::course::delete`]'s race test for why the rate is /// counted rather than asserted per round. /// /// This site has no `THROW` marker at all: it ends `.check()?`, which @@ -995,7 +993,7 @@ mod tests { /// attempt — the grades serialize behind `cap`'s claim lock, so they mostly /// queue rather than collide. So this guards the status codes and the /// cascade (marks either survive whole or are swept whole, never a 500). - /// The retry is measured on [`crate::domain::course::Course::delete`]. + /// The retry is measured on [`crate::db::course::delete`]. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn a_delete_racing_a_mark_never_answers_500() { @@ -1011,7 +1009,7 @@ mod tests { // A burst of marks and a delete held back by a sweeping beat: this // site has no guard to lose to, so a single racer released with it // simply finishes on one side of it. Same recipe as - // [`crate::domain::course::Course::delete`]'s race test. + // [`crate::db::course::delete`]'s race test. let drop_it = { let (exam, db) = (exam.clone(), db.clone()); // A wide sweep, not the 0-3ms the other three use: each grade @@ -1124,7 +1122,7 @@ mod tests { ) .unwrap(); let subject = crate::domain::subject::Subject::create( - &crate::domain::course::a_test_course(db).await, + &crate::db::course::a_test_course(db).await, crate::domain::subject::SubjectName::try_new("topic").unwrap(), crate::domain::subject::SubjectDescription::try_new("").unwrap(), db, @@ -1268,7 +1266,7 @@ mod tests { let exam = published(&db).await; let id = exam.get_id().clone(); let subject = Subject::create( - &crate::domain::course::a_test_course(&db).await, + &crate::db::course::a_test_course(&db).await, crate::domain::subject::SubjectName::try_new("topic").unwrap(), crate::domain::subject::SubjectDescription::try_new("").unwrap(), &db, diff --git a/src/domain/exam_answer.rs b/src/domain/exam_answer.rs index 38ba7dc..2689522 100644 --- a/src/domain/exam_answer.rs +++ b/src/domain/exam_answer.rs @@ -508,7 +508,7 @@ mod tests { .to_vec(); let exam = Exam::create( &student(), - &crate::domain::course::a_test_course(&db).await, + &crate::db::course::a_test_course(&db).await, ExamTitle::try_new("quiz").unwrap(), ExamDescription::try_new("").unwrap(), ExamKind::try_new("quiz", &kinds).unwrap(), diff --git a/src/domain/exam_attempt.rs b/src/domain/exam_attempt.rs index 9d100e0..ce12c3d 100644 --- a/src/domain/exam_attempt.rs +++ b/src/domain/exam_attempt.rs @@ -543,7 +543,7 @@ mod tests { /// rows to exercise the attempt lifecycle without the HTTP layer. async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) { let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); - let course = crate::domain::course::a_test_course(db).await; + let course = crate::db::course::a_test_course(db).await; let kinds = Settings::defaults().get_exam_kinds().to_vec(); let exam = Exam::create( &creator, @@ -580,7 +580,7 @@ mod tests { // 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( - &crate::domain::course::a_test_course(db).await, + &crate::db::course::a_test_course(db).await, crate::domain::subject::SubjectName::try_new("topic").unwrap(), crate::domain::subject::SubjectDescription::try_new("").unwrap(), db, diff --git a/src/domain/exam_question.rs b/src/domain/exam_question.rs index ce371e6..7b8329d 100644 --- a/src/domain/exam_question.rs +++ b/src/domain/exam_question.rs @@ -1094,7 +1094,7 @@ mod tests { let kinds = Settings::defaults().get_exam_kinds().to_vec(); Exam::create( &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"), - &crate::domain::course::a_test_course(db).await, + &crate::db::course::a_test_course(db).await, ExamTitle::try_new("practice").unwrap(), ExamDescription::try_new("").unwrap(), ExamKind::try_new("quiz", &kinds).unwrap(), @@ -1112,7 +1112,7 @@ mod tests { async fn a_subject(db: &Database) -> Subject { Subject::create( - &crate::domain::course::a_test_course(db).await, + &crate::db::course::a_test_course(db).await, SubjectName::try_new("topic").unwrap(), SubjectDescription::try_new("").unwrap(), db, diff --git a/src/domain/homework.rs b/src/domain/homework.rs index 6431149..f3b3d19 100644 --- a/src/domain/homework.rs +++ b/src/domain/homework.rs @@ -422,7 +422,7 @@ mod tests { async fn a_subject(name: &str, db: &Database) -> Subject { Subject::create( - &crate::domain::course::a_test_course(db).await, + &crate::db::course::a_test_course(db).await, SubjectName::try_new(name).unwrap(), SubjectDescription::try_new("").unwrap(), db, diff --git a/src/domain/homework_file.rs b/src/domain/homework_file.rs index 822391c..190b15e 100644 --- a/src/domain/homework_file.rs +++ b/src/domain/homework_file.rs @@ -330,7 +330,7 @@ mod tests { use crate::domain::homework::{Homework, HomeworkTitle}; use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; - let course = crate::domain::course::a_test_course(db).await; + let course = crate::db::course::a_test_course(db).await; let subject = Subject::create( &course, SubjectName::try_new("topic").unwrap(), diff --git a/src/domain/homework_result.rs b/src/domain/homework_result.rs index 79c725e..d2510a1 100644 --- a/src/domain/homework_result.rs +++ b/src/domain/homework_result.rs @@ -375,7 +375,7 @@ mod tests { use crate::domain::homework::{Homework, HomeworkTitle}; use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; - let course = crate::domain::course::a_test_course(db).await; + let course = crate::db::course::a_test_course(db).await; let subject = Subject::create( &course, SubjectName::try_new("topic").unwrap(), diff --git a/src/domain/homework_submission.rs b/src/domain/homework_submission.rs index 586fb6d..a7986b3 100644 --- a/src/domain/homework_submission.rs +++ b/src/domain/homework_submission.rs @@ -376,7 +376,7 @@ mod tests { /// 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::domain::course::a_test_course(db).await; + let course = crate::db::course::a_test_course(db).await; let subject = Subject::create( &course, SubjectName::try_new("topic").unwrap(), diff --git a/src/domain/rag_output.rs b/src/domain/rag_output.rs index 42fb038..b0356d3 100644 --- a/src/domain/rag_output.rs +++ b/src/domain/rag_output.rs @@ -185,21 +185,21 @@ impl RagOutput { #[cfg(test)] mod tests { use super::*; - use crate::domain::course::{Course, CourseDescription, CourseKind, CourseTitle}; + use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; use crate::domain::course_note_file::{CourseNoteFile, FileContentType, FileName}; use serde_json::json; async fn note_of(db: &Database, title: &str) -> CourseNote { let creator = crate::domain::user::UserId::generate(); - let course = Course::create( + let course = crate::db::course::create( + db, &creator, CourseTitle::try_new("c").unwrap(), CourseDescription::try_new("").unwrap(), CourseKind::try_new("course").unwrap(), None, None, - db, ) .await .unwrap(); diff --git a/src/domain/session_attendance.rs b/src/domain/session_attendance.rs index 132f147..8518219 100644 --- a/src/domain/session_attendance.rs +++ b/src/domain/session_attendance.rs @@ -385,7 +385,7 @@ mod tests { async fn a_session_at(teacher: &UserId, starts_at: i64, db: &Database) -> CourseSession { CourseSession::create( - &crate::domain::course::a_test_course(db).await, + &crate::db::course::a_test_course(db).await, teacher, SessionTopic::try_new("limits").unwrap(), Timestamp::from_millis(starts_at), diff --git a/src/domain/subject.rs b/src/domain/subject.rs index 9df7c9b..16337e6 100644 --- a/src/domain/subject.rs +++ b/src/domain/subject.rs @@ -263,7 +263,7 @@ mod tests { /// [`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::domain::course::assert_no_child_outlives_a_course_delete`]. + /// [`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)] @@ -281,11 +281,9 @@ mod tests { .map(|_| ()) }) } - crate::domain::course::assert_no_child_outlives_a_course_delete( - "subject_orphan_race", - SUBJECT_TABLE, - make, - ) + crate::db::course::assert_no_child_outlives_a_course_delete("subject_orphan_race", + SUBJECT_TABLE, + make,) .await; } @@ -320,7 +318,7 @@ mod tests { /// GUARD, not a retry measurement — read the last paragraph before /// trusting this test with the retry. See - /// [`crate::domain::course::Course::delete`]'s race test for why the rate + /// [`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. /// @@ -341,7 +339,7 @@ mod tests { /// 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::domain::course::Course::delete`], whose cascade 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"] @@ -354,7 +352,7 @@ mod tests { 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::domain::course::a_test_course(&db).await; + 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. diff --git a/src/domain/term.rs b/src/domain/term.rs index 79c060b..86131ec 100644 --- a/src/domain/term.rs +++ b/src/domain/term.rs @@ -193,7 +193,7 @@ impl Term { /// 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::domain::course::Course::create`] and + /// 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 @@ -363,7 +363,7 @@ mod tests { /// GUARD, not a retry measurement — read the last paragraph before /// trusting this test with the retry. See - /// [`crate::domain::course::Course::delete`]'s race test for why the rate is + /// [`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 @@ -372,7 +372,7 @@ mod tests { /// 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::domain::course::Course::create`] against this + /// 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 @@ -388,11 +388,11 @@ mod tests { /// 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::domain::course::Course::delete`]. + /// 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::{Course, CourseDescription, CourseKind, CourseTitle}; + 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); @@ -433,14 +433,14 @@ mod tests { }; tokio::spawn(async move { tokio::time::sleep(head_start).await; - Course::create( + crate::db::course::create( + &db, &UserId::from_key("teacher"), CourseTitle::try_new("algebra").unwrap(), CourseDescription::try_new("").unwrap(), CourseKind::course(), Some(id), None, - &db, ) .await }) @@ -461,7 +461,10 @@ mod tests { last_create = format!("{make:?}"); } if let Ok(course) = &make - && Course::read(course.get_id(), &db).await.unwrap().is_some() + && crate::db::course::read(&db, course.get_id()) + .await + .unwrap() + .is_some() { landed = true; } diff --git a/src/service/course.rs b/src/service/course.rs new file mode 100644 index 0000000..b11b863 --- /dev/null +++ b/src/service/course.rs @@ -0,0 +1,181 @@ +//! Course workflows: the archived-term gate every course-scoped write pays, +//! the staffing changes a manager makes, and the delete that collects the +//! image/homework/note-file blob keys under the exam and homework locks +//! before the cascade sweeps those rows. The queries live in +//! [`crate::db::course`]. + +use crate::database::Database; +use crate::db::course; +use crate::domain::answer_image::AnswerImage; +use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; +use crate::domain::course_note_file::CourseNoteFile; +use crate::domain::homework_file::HomeworkFile; +use crate::domain::question_image::QuestionImage; +use crate::domain::term::{self, TermId}; +use crate::domain::role::Role; +use crate::domain::user::{User, UserId}; +use crate::error::{AppError, ValidationError}; + +/// 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 +/// read still lets the write through. +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, + } +} + +pub async fn create( + db: &Database, + creator: &UserId, + title: CourseTitle, + description: CourseDescription, + kind: CourseKind, + term: Option, + capacity: Option, +) -> Result { + course::create(db, creator, title, description, kind, term, capacity).await +} + +pub async fn read(db: &Database, id: &CourseId) -> Result, AppError> { + course::read(db, id).await +} + +pub async fn list_all(db: &Database) -> Result, AppError> { + course::list_all(db).await +} + +pub async fn list_enrolled( + db: &Database, + user: &UserId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + course::list_enrolled(db, user, limit, offset).await +} + +pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result, AppError> { + course::list_for_teacher(db, user).await +} + +pub async fn list_by_ids(db: &Database, ids: &[CourseId]) -> Result, AppError> { + course::list_by_ids(db, ids).await +} + +/// Only what the request carried is written: an omitted field (`None`) is +/// not stored at all, so a concurrent PATCH of that field survives. +pub async fn update( + db: &Database, + course: Course, + title: Option, + description: Option, + kind: Option, + term: Option>, + capacity: Option>, +) -> Result { + course::update(db, course, title, description, kind, term, capacity).await +} + +/// Assign `target` to run `course`, or return the course untouched if they +/// already run it — assignment is idempotent, like enrollment. +/// +/// The assignee must already hold the `teacher` role or higher: assignment +/// hands out course-management rights, which every gate behind it re-checks +/// against the `teacher` bar — assigning anyone below it would write a row +/// that can never be used. +pub async fn assign_teacher( + db: &Database, + course: &Course, + target: &UserId, +) -> Result { + require_open(db, course).await?; + let Some(target_user) = User::read(target, db).await? else { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "target user does not exist", + })); + }; + if !target_user.get_role().at_least(Role::Teacher) { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "assigned teacher must hold the teacher role or higher", + })); + } + course::assign_teacher(db, course.clone(), target).await +} + +/// Drop `target` from this course's assigned teachers. `None` when they +/// weren't assigned, so the web layer can answer 404 instead of pretending +/// it removed someone. +pub async fn unassign_teacher( + db: &Database, + course: &Course, + target: &UserId, +) -> Result, AppError> { + require_open(db, course).await?; + course::unassign_teacher(db, course.clone(), target).await +} + +/// Strip `user` from every course they were assigned to — the sweep for a +/// user demoted below `teacher`, who may no longer run anything. +pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> { + course::unassign_everywhere(db, user).await +} + +/// What [`delete`] did: whether the course went, and the blob keys of the +/// rows its cascade removed — exactly whose files the web layer may unlink. +#[derive(Debug)] +pub struct DeleteOutcome { + /// `false` = refused, nothing was written: someone is still enrolled. + pub deleted: bool, + pub image_files: Vec, + pub answer_image_files: Vec, + pub homework_files: Vec, + pub course_note_files: Vec, +} + +/// Delete the course: collect the image/homework/note-file blob keys, then +/// run the cascading delete. +/// +/// Writer lease of [`crate::web::exams::EXAM_LOCK`] (moving to +/// `crate::service::exam_attempt` with the exam lane's split), for +/// `delete_exam`'s reason: this cascade sweeps the course's exams *and their +/// attempts*, and an attempt is the one exam child whose write cannot +/// collide with the sweep (its claim lands on the student's row, never the +/// exam's). Narrower here — the delete is refused while anyone is enrolled, +/// so a start would have to pass its enrollment gate and then have that +/// enrollment removed under it — but the hole is the same one and so is the +/// lease. +/// +/// And the homework half of the same cascade, for +/// [`crate::web::homework::delete_homework`]'s reason: it sweeps the +/// course's homework with its submissions, files and results, and grading +/// ([`crate::domain::homework_result::HomeworkResult::grade`]) writes a +/// result row against a homework it only *read*, which a delete committing +/// alongside is invisible to. Without this lease the grade lands behind the +/// sweep: an orphan `homework_result` under a vanished homework, plus a +/// `marks_given_total` on the grader no ungrade can reach. Lock order here +/// is EXAM_LOCK then HOMEWORK_LOCK, the only path that takes both. +/// +/// The keys are read before the delete because it takes their rows with it; +/// a refused delete just drops them unused. Unlinking the blobs stays the +/// web layer's job — a crash in between strands at worst an unreachable +/// blob. +pub async fn delete(db: &Database, course: &Course) -> Result { + require_open(db, course).await?; + let _guard = crate::web::exams::EXAM_LOCK.write().await; + let _homework_guard = crate::web::homework::HOMEWORK_LOCK.write().await; + let image_files = QuestionImage::file_keys_for_course(course.get_id(), db).await?; + let answer_image_files = AnswerImage::file_keys_for_course(course.get_id(), db).await?; + let homework_files = HomeworkFile::file_keys_for_course(course.get_id(), db).await?; + let course_note_files = CourseNoteFile::file_keys_for_course(course.get_id(), db).await?; + let deleted = course::delete(db, course.clone()).await?; + Ok(DeleteOutcome { + deleted, + image_files, + answer_image_files, + homework_files, + course_note_files, + }) +} diff --git a/src/service/mod.rs b/src/service/mod.rs index b8d74fb..56a0383 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -1,6 +1,7 @@ //! Business rules, workflow locks, multi-call orchestration; calls db::*; no //! SurrealQL text. +pub mod course; pub mod note; pub mod session; pub mod settings; diff --git a/src/web/attendance.rs b/src/web/attendance.rs index 9d3f24b..b59b474 100644 --- a/src/web/attendance.rs +++ b/src/web/attendance.rs @@ -117,7 +117,7 @@ async fn build_report( by_course.entry(key).or_default().push(row); } - let courses = Course::list_by_ids(&course_ids, db).await?; + let courses = crate::service::course::list_by_ids(db, &course_ids).await?; let course_by_key: HashMap<&str, &Course> = courses.iter().map(|c| (c.get_id().key(), c)).collect(); let people = person_map(courses.iter().flat_map(course_people), db).await?; diff --git a/src/web/boards.rs b/src/web/boards.rs index 3db2f17..ffa1993 100644 --- a/src/web/boards.rs +++ b/src/web/boards.rs @@ -34,7 +34,7 @@ use crate::domain::board::{BOARD_ROSTER_LOCK, Board, BoardId, BoardTitle}; use crate::domain::board_stroke::BoardStroke; use crate::domain::class_group::{ClassGroup, ClassGroupId}; use crate::domain::class_member::ClassMember; -use crate::domain::course::{Course, CourseId}; +use crate::domain::course::CourseId; use crate::domain::enrollment::Enrollment; use crate::domain::event::{Event, EventId}; use crate::domain::role::Role; @@ -742,7 +742,7 @@ impl InviteSource { .collect()) } InviteSource::Course { course } => { - let course = Course::read(&CourseId::from_key(&course), db) + let course = crate::service::course::read(db, &CourseId::from_key(&course)) .await? .ok_or(AppError::Validation(ValidationError::Invalid { field: "course", diff --git a/src/web/classes.rs b/src/web/classes.rs index fb24bb2..3208617 100644 --- a/src/web/classes.rs +++ b/src/web/classes.rs @@ -21,7 +21,7 @@ use crate::domain::class_blueprint::{ClassBlueprint, ClassBlueprintId, Pumped, S use crate::domain::class_course::ClassCourse; use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName}; use crate::domain::class_member::ClassMember; -use crate::domain::course::{Course, CourseId}; +use crate::domain::course::CourseId; use crate::domain::role::Role; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; @@ -872,7 +872,9 @@ async fn attach_course( Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { let class = class_or_404(&id, &st.db).await?; - let Some(course) = Course::read(&CourseId::from_key(&req.course_id), &st.db).await? else { + let Some(course) = crate::service::course::read(&st.db, &CourseId::from_key(&req.course_id)) + .await? + else { return Err(AppError::Validation(ValidationError::Invalid { field: "course_id", reason: "course does not exist", @@ -885,7 +887,7 @@ async fn attach_course( } // Both ends: neither a class nor a course on a past year takes a new link. class.require_open(&st.db).await?; - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; let link = ClassCourse::attach(class.get_id(), course.get_id(), user.get_id(), &st.db).await?; let people = PersonRef::map_of(&[&user]); @@ -966,7 +968,7 @@ async fn detach_course( // route answered 404 forever — which also left the class undeletable, its // attachment counter counting a row nothing could sweep. There is no roster // left to protect, and the caller is already teacher+. - let row = Course::read(&course, &st.db).await?; + let row = crate::service::course::read(&st.db, &course).await?; if let Some(row) = row.as_ref() && !can_manage_course(row, &user) { @@ -978,7 +980,7 @@ async fn detach_course( // has no term to read, and sweeping it is the whole point of the route. class.require_open(&st.db).await?; if let Some(row) = row.as_ref() { - row.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, row).await?; } ClassCourse::detach(class.get_id(), &course, &st.db).await?; Ok(StatusCode::NO_CONTENT) @@ -1150,7 +1152,7 @@ async fn resolve_courses(ids: &[String], db: &Database) -> Result, let mut courses = Vec::with_capacity(ids.len()); for id in ids { let course = CourseId::from_key(id); - if Course::read(&course, db).await?.is_none() { + if crate::service::course::read(db, &course).await?.is_none() { return Err(AppError::Validation(ValidationError::Invalid { field: "course_ids", reason: "one of these courses does not exist", @@ -1454,8 +1456,8 @@ async fn apply_blueprint( // already gone is the pump's own `skipped` business, not a term refusal. class.require_open(&st.db).await?; for id in blueprint.get_courses() { - if let Some(course) = Course::read(id, &st.db).await? { - course.require_open(&st.db).await?; + if let Some(course) = crate::service::course::read(&st.db, id).await? { + crate::service::course::require_open(&st.db, &course).await?; } } let skipped = blueprint.apply_to(&class, user.get_id(), &st.db).await?; diff --git a/src/web/course_notes.rs b/src/web/course_notes.rs index a71922a..163a6c9 100644 --- a/src/web/course_notes.rs +++ b/src/web/course_notes.rs @@ -60,7 +60,7 @@ async fn note_with_course(id: &str, db: &Database) -> Result<(CourseNote, Course let note = CourseNote::read(&CourseNoteId::from_key(id), db) .await? .ok_or(AppError::NotFound)?; - let course = Course::read(note.get_course(), db) + let course = crate::service::course::read(db, note.get_course()) .await? .ok_or(AppError::NotFound)?; Ok((note, course)) @@ -130,7 +130,7 @@ async fn create( RequireTeacher(user): RequireTeacher, Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { - let course = Course::read(&CourseId::from_key(&req.course), &st.db) + let course = crate::service::course::read(&st.db, &CourseId::from_key(&req.course)) .await? .ok_or(AppError::NotFound)?; if !can_manage_course(&course, &user) { @@ -138,7 +138,7 @@ async fn create( "only the course creator, an assigned teacher, or a manager/admin can add a course note", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; let title = CourseNoteTitle::try_new(&req.title)?; let content = CourseNoteContent::try_new(&req.content.unwrap_or_default())?; let note = CourseNote::create(course.get_id(), user.get_id(), title, content, &st.db).await?; @@ -179,7 +179,7 @@ async fn list( Query(filter): Query, Query(page): Query, ) -> Result>, AppError> { - let course = Course::read(&CourseId::from_key(&filter.course), &st.db) + let course = crate::service::course::read(&st.db, &CourseId::from_key(&filter.course)) .await? .ok_or(AppError::NotFound)?; if !can_view_course(&course, &user, &st.db).await? { @@ -254,7 +254,7 @@ async fn update( "only the course creator, an assigned teacher, or a manager/admin can edit this course note", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; let title = req .title @@ -300,7 +300,7 @@ async fn delete_one( "only the course creator, an assigned teacher, or a manager/admin can delete this course note", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; // Derived rows first, outside the note's own cascade transaction: they are // disposable, so failing here leaves the note intact and the 500 truthful, // whereas dropping them after the note would strand every blob on an error @@ -378,7 +378,7 @@ async fn upload_file( "only the course creator, an assigned teacher, or a manager/admin can add a file to this course note", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; // The 10-file cap is enforced inside `CourseNoteFile::insert` (count and // create under one lock) — checking it here too would just race. let limit = service::settings::load(&st.db).await?.get_max_file_bytes(); @@ -533,7 +533,7 @@ async fn delete_file( "only the course creator, an assigned teacher, or a manager/admin can delete this course note's files", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; let file = CourseNoteFile::read_for(&CourseNoteFileId::from_key(&file_id), note.get_id(), &st.db) .await? @@ -648,7 +648,7 @@ async fn delete_rag( "only the course creator, an assigned teacher, or a manager/admin can delete this course note's AI outputs", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; // Scoped to the note in the path, like `CourseNoteFile::read_for`: an // output of another note is a 404 here, never a cross-note delete. let output = RagOutput::read(&RagOutputId::from_key(&output_id), &st.db) diff --git a/src/web/courses.rs b/src/web/courses.rs index 9e83dfc..9a52348 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -10,9 +10,7 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::database::Database; -use crate::domain::answer_image::AnswerImage; use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; -use crate::domain::course_note_file::CourseNoteFile; use crate::domain::course_session::{CourseSession, SessionTopic}; use crate::domain::enrollment::Enrollment; use crate::domain::exam::{ @@ -20,8 +18,6 @@ use crate::domain::exam::{ ExamTitle, }; use crate::domain::homework::{Homework, HomeworkTitle}; -use crate::domain::homework_file::HomeworkFile; -use crate::domain::question_image::QuestionImage; use crate::domain::role::Role; use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; use crate::domain::timestamp::Timestamp; @@ -262,14 +258,14 @@ pub(crate) async fn can_view_course( /// visible only the way it is to any other student: by enrollment. pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result, AppError> { if user.get_role().at_least(Role::Manager) { - return Course::list_all(db).await; + return service::course::list_all(db).await; } let mut courses = if user.get_role().at_least(Role::Teacher) { - Course::list_for_teacher(user.get_id(), db).await? + service::course::list_for_teacher(db, user.get_id()).await? } else { Vec::new() }; - for course in Course::list_enrolled(user.get_id(), None, 0, db).await?.0 { + for course in service::course::list_enrolled(db, user.get_id(), None, 0).await?.0 { if !courses .iter() .any(|known| known.get_id() == course.get_id()) @@ -326,19 +322,19 @@ async fn create_course( Some(ref kind) => CourseKind::try_new(kind)?, None => CourseKind::course(), }; - // Pre-flight only: [`Course::create`] claims a reference on the term before + // 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?; check_capacity(req.capacity)?; - let course = Course::create( + let course = service::course::create( + &st.db, user.get_id(), title, description, kind, term, req.capacity, - &st.db, ) .await?; // The creator is the caller — already loaded, no extra lookup. @@ -405,7 +401,7 @@ async fn my_courses( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let (courses, total) = Course::list_enrolled(user.get_id(), limit, offset, &st.db).await?; + let (courses, total) = service::course::list_enrolled(&st.db, user.get_id(), limit, offset).await?; let people = person_map(courses.iter().flat_map(course_people), &st.db).await?; let items = courses .iter() @@ -436,7 +432,7 @@ async fn get_course( CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result, AppError> { - let course = Course::read(&CourseId::from_key(&id), &st.db) + let course = service::course::read(&st.db, &CourseId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; if !can_view_course(&course, &user, &st.db).await? { @@ -474,7 +470,7 @@ async fn update_course( Path(id): Path, Json(req): Json, ) -> Result, AppError> { - let course = Course::read(&CourseId::from_key(&id), &st.db) + let course = service::course::read(&st.db, &CourseId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; if !can_manage_course(&course, &user) { @@ -482,7 +478,7 @@ async fn update_course( "only the course creator, an assigned teacher, or a manager/admin can edit this course", )); } - course.require_open(&st.db).await?; + service::course::require_open(&st.db, &course).await?; // Only what the request actually carried is validated and written — an // omitted field stays `None` so the save never re-sends this snapshot's @@ -505,9 +501,8 @@ async fn update_course( check_capacity(req.capacity.flatten())?; let capacity = req.capacity; - let updated = course - .update(title, description, kind, term, capacity, &st.db) - .await?; + let updated = + service::course::update(&st.db, course, title, description, kind, term, capacity).await?; let people = person_map(course_people(&updated), &st.db).await?; Ok(Json(CourseResponse::new(&updated, &people))) } @@ -542,7 +537,7 @@ async fn delete_course( RequireTeacher(user): RequireTeacher, Path(id): Path, ) -> Result { - let course = Course::read(&CourseId::from_key(&id), &st.db) + let course = service::course::read(&st.db, &CourseId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; if !owns_course(&course, &user) { @@ -550,43 +545,21 @@ async fn delete_course( "only the course creator or a manager/admin can delete this course", )); } - course.require_open(&st.db).await?; - // Writer lease of [`EXAM_LOCK`], for `delete_exam`'s reason: this cascade - // sweeps the course's exams *and their attempts*, and an attempt is the one - // exam child whose write cannot collide with the sweep (its claim lands on - // the student's row, never the exam's). Narrower here — the delete is - // refused while anyone is enrolled, so a start would have to pass its - // enrollment gate and then have that enrollment removed under it — but the - // hole is the same one and so is the lease. - let _guard = crate::web::exams::EXAM_LOCK.write().await; - // And the homework half of the same cascade, for - // [`crate::web::homework::delete_homework`]'s reason: it sweeps the - // course's homework with its submissions, files and results, and grading - // ([`crate::domain::homework_result::HomeworkResult::grade`]) writes a - // result row against a homework it only *read*, which a delete committing - // alongside is invisible to. Without this lease the grade lands behind the - // sweep: an orphan `homework_result` under a vanished homework, plus a - // `marks_given_total` on the grader no ungrade can reach. Lock order here - // is EXAM_LOCK then HOMEWORK_LOCK, the only path that takes both. - let _homework_guard = crate::web::homework::HOMEWORK_LOCK.write().await; - // Rows go first (the delete cascades them), blobs after — a crash in - // between strands at worst an unreachable blob. The keys are read before - // the delete because it takes their rows with it; a refused delete just - // drops them unused. - let image_files = QuestionImage::file_keys_for_course(course.get_id(), &st.db).await?; - let answer_image_files = AnswerImage::file_keys_for_course(course.get_id(), &st.db).await?; - let homework_files = HomeworkFile::file_keys_for_course(course.get_id(), &st.db).await?; - let course_note_files = CourseNoteFile::file_keys_for_course(course.get_id(), &st.db).await?; - if !course.delete(&st.db).await? { + // The workflow — archived-term gate, EXAM_LOCK and HOMEWORK_LOCK writer + // leases, blob-key collection, cascade — is [`service::course::delete`]'s. + // Blob unlinking stays here because only the web layer knows `files_path`. + let outcome = service::course::delete(&st.db, &course).await?; + if !outcome.deleted { return Err(AppError::Conflict( "students are still enrolled in this course — remove them first", )); } - for file in image_files + for file in outcome + .image_files .iter() - .chain(&answer_image_files) - .chain(&homework_files) - .chain(&course_note_files) + .chain(&outcome.answer_image_files) + .chain(&outcome.homework_files) + .chain(&outcome.course_note_files) { remove_blob(&st.files_path, file).await; } @@ -624,29 +597,11 @@ async fn assign_teacher( Path(id): Path, Json(req): Json, ) -> Result, AppError> { - let course = Course::read(&CourseId::from_key(&id), &st.db) + let course = service::course::read(&st.db, &CourseId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; - course.require_open(&st.db).await?; - let target = UserId::from_key(&req.user_id); - let Some(target_user) = User::read(&target, &st.db).await? else { - return Err(AppError::Validation(ValidationError::Invalid { - field: "user_id", - reason: "target user does not exist", - })); - }; - // Assignment hands out course-management rights, which every gate behind - // it re-checks against the `teacher` bar — assigning anyone below it would - // write a row that can never be used. - if !target_user.get_role().at_least(Role::Teacher) { - return Err(AppError::Validation(ValidationError::Invalid { - field: "user_id", - reason: "assigned teacher must hold the teacher role or higher", - })); - } - - let updated = course.assign_teacher(&target, &st.db).await?; + let updated = service::course::assign_teacher(&st.db, &course, &target).await?; // The row is written; a demotion that raced the bar above swept the list // before this assignment was in it, and nothing re-sweeps (see // [`super::undo_if_demoted`]). @@ -680,13 +635,11 @@ async fn unassign_teacher( RequireManager(_manager): RequireManager, Path((id, target)): Path<(String, String)>, ) -> Result { - let course = Course::read(&CourseId::from_key(&id), &st.db) + let course = service::course::read(&st.db, &CourseId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; - course.require_open(&st.db).await?; - let removed = course - .unassign_teacher(&UserId::from_key(&target), &st.db) - .await?; + let removed = + service::course::unassign_teacher(&st.db, &course, &UserId::from_key(&target)).await?; if removed.is_none() { return Err(AppError::NotFound); } @@ -726,7 +679,7 @@ async fn enroll( Path(id): Path, Json(req): Json, ) -> Result, AppError> { - let course = Course::read(&CourseId::from_key(&id), &st.db) + let course = service::course::read(&st.db, &CourseId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; if !can_manage_course(&course, &user) { @@ -734,7 +687,7 @@ async fn enroll( "only the course creator, an assigned teacher, or a manager/admin can enroll users", )); } - course.require_open(&st.db).await?; + service::course::require_open(&st.db, &course).await?; let target = UserId::from_key(&req.user_id); let Some(target_user) = User::read(&target, &st.db).await? else { @@ -785,7 +738,7 @@ async fn list_roster( ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; // Course must exist — a missing course is a 404, not an empty roster. - let course = Course::read(&CourseId::from_key(&id), &st.db) + let course = service::course::read(&st.db, &CourseId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; if !can_manage_course(&course, &user) { @@ -833,7 +786,7 @@ async fn unenroll( RequireTeacher(user): RequireTeacher, Path((id, target)): Path<(String, String)>, ) -> Result { - let course = Course::read(&CourseId::from_key(&id), &st.db) + let course = service::course::read(&st.db, &CourseId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; if !can_manage_course(&course, &user) { @@ -841,7 +794,7 @@ async fn unenroll( "only the course creator, an assigned teacher, or a manager/admin can unenroll users", )); } - course.require_open(&st.db).await?; + service::course::require_open(&st.db, &course).await?; let removed = Enrollment::remove(course.get_id(), &UserId::from_key(&target), &st.db).await?; if removed.is_none() { return Err(AppError::NotFound); @@ -884,7 +837,7 @@ async fn create_exam_in_course( Path(id): Path, Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { - let course = Course::read(&CourseId::from_key(&id), &st.db) + let course = service::course::read(&st.db, &CourseId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; if !can_manage_course(&course, &user) { @@ -892,7 +845,7 @@ async fn create_exam_in_course( "only the course creator, an assigned teacher, or a manager/admin can add exams to this course", )); } - course.require_open(&st.db).await?; + service::course::require_open(&st.db, &course).await?; let title = ExamTitle::try_new(&req.title)?; let description = ExamDescription::try_new(&req.description.unwrap_or_default())?; @@ -955,7 +908,7 @@ async fn list_course_exams( ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; // Course must exist — a missing course is a 404, not an empty exam list. - let course = Course::read(&CourseId::from_key(&id), &st.db) + let course = service::course::read(&st.db, &CourseId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; if !can_view_course(&course, &user, &st.db).await? { @@ -1015,7 +968,7 @@ async fn create_subject_in_course( Path(id): Path, Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { - let course = Course::read(&CourseId::from_key(&id), &st.db) + let course = service::course::read(&st.db, &CourseId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; if !can_manage_course(&course, &user) { @@ -1023,7 +976,7 @@ async fn create_subject_in_course( "only the course creator, an assigned teacher, or a manager/admin can add subjects to this course", )); } - course.require_open(&st.db).await?; + service::course::require_open(&st.db, &course).await?; let name = SubjectName::try_new(&req.name)?; let description = SubjectDescription::try_new(&req.description.unwrap_or_default())?; @@ -1057,7 +1010,7 @@ async fn list_course_subjects( ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; // Course must exist — a missing course is a 404, not an empty list. - let course = Course::read(&CourseId::from_key(&id), &st.db) + let course = service::course::read(&st.db, &CourseId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; if !can_view_course(&course, &user, &st.db).await? { @@ -1125,7 +1078,7 @@ async fn create_homework_in_course( Path(id): Path, Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { - let course = Course::read(&CourseId::from_key(&id), &st.db) + let course = service::course::read(&st.db, &CourseId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; if !can_manage_course(&course, &user) { @@ -1133,7 +1086,7 @@ async fn create_homework_in_course( "only the course creator, an assigned teacher, or a manager/admin can add homework to this course", )); } - course.require_open(&st.db).await?; + service::course::require_open(&st.db, &course).await?; let title = HomeworkTitle::try_new(&req.title)?; let description = match req.description.as_deref() { @@ -1189,7 +1142,7 @@ async fn list_course_homework( ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; // Course must exist — a missing course is a 404, not an empty homework list. - let course = Course::read(&CourseId::from_key(&id), &st.db) + let course = service::course::read(&st.db, &CourseId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; if !can_view_course(&course, &user, &st.db).await? { @@ -1263,7 +1216,7 @@ async fn create_session_in_course( Path(id): Path, Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { - let course = Course::read(&CourseId::from_key(&id), &st.db) + let course = service::course::read(&st.db, &CourseId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; if !can_manage_course(&course, &user) { @@ -1271,7 +1224,7 @@ async fn create_session_in_course( "only the course creator, an assigned teacher, or a manager/admin can add sessions to this course", )); } - course.require_open(&st.db).await?; + service::course::require_open(&st.db, &course).await?; let topic = SessionTopic::try_new(&req.topic.unwrap_or_default())?; let teacher = resolve_session_teacher(req.teacher_id.as_deref(), &user, &st.db).await?; @@ -1323,7 +1276,7 @@ async fn list_course_sessions( ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; // Course must exist — a missing course is a 404, not an empty list. - let course = Course::read(&CourseId::from_key(&id), &st.db) + let course = service::course::read(&st.db, &CourseId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; if !can_view_course(&course, &user, &st.db).await? { @@ -1363,14 +1316,14 @@ mod tests { /// A course `creator` made, with nobody assigned. async fn course(creator: &User, db: &Database) -> Course { - Course::create( + service::course::create( + db, creator.get_id(), CourseTitle::try_new("Matematik").unwrap(), CourseDescription::try_new("").unwrap(), CourseKind::try_new("course").unwrap(), None, None, - db, ) .await .unwrap() @@ -1406,11 +1359,13 @@ mod tests { let db = init_mem().await.unwrap(); let creator = user("creator", Role::Teacher, &db).await; let assigned = user("assigned", Role::Teacher, &db).await; - let course = course(&creator, &db) - .await - .assign_teacher(assigned.get_id(), &db) - .await - .unwrap(); + let course = service::course::assign_teacher( + &db, + &course(&creator, &db).await, + assigned.get_id(), + ) + .await + .unwrap(); // Still teacher+: untouched by the floor. assert!(can_manage_course(&course, &assigned)); // ...but never an owner, assigned or not. diff --git a/src/web/events.rs b/src/web/events.rs index 6f0d101..6a2ef5e 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -12,7 +12,7 @@ use utoipa_axum::routes; use crate::database::Database; use crate::domain::attendance::{Attendance, AttendanceStatus}; use crate::domain::class_group::{ClassGroup, ClassGroupId}; -use crate::domain::course::{Course, CourseId}; +use crate::domain::course::CourseId; use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle}; use crate::domain::registration::Registration; use crate::domain::role::Role; @@ -91,7 +91,7 @@ impl AudienceDto { }), AudienceDto::Course { course } => { let course = CourseId::from_key(&course); - if Course::read(&course, db).await?.is_none() { + if crate::service::course::read(db, &course).await?.is_none() { return Err(AppError::Validation(ValidationError::Invalid { field: "audience", reason: "course does not exist", diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index e426f19..16ad239 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -152,7 +152,7 @@ pub async fn attempt_ws( ensure_enrolled(&exam, user.get_id(), &st.db).await?; let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; check_rejoin(&exam, &attempt)?; - course_of(&exam, &st.db).await?.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course_of(&exam, &st.db).await?).await?; let user_id = user.get_id().clone(); Ok(ws.on_upgrade(move |socket| room(socket, st, slug, exam, attempt, user_id))) @@ -463,7 +463,7 @@ async fn handle_message( // same error frame as every other conflict. async { let attempt = writable_room_attempt(&exam, attempt_id, user, db).await?; - course_of(&exam, db).await?.require_open(db).await?; + crate::service::course::require_open(db, &course_of(&exam, db).await?).await?; attempt.finish(db).await } .await diff --git a/src/web/exams/attempts.rs b/src/web/exams/attempts.rs index 143f22c..cadadd7 100644 --- a/src/web/exams/attempts.rs +++ b/src/web/exams/attempts.rs @@ -180,7 +180,7 @@ pub(crate) async fn start_attempt( ensure_sittable(&exam)?; ensure_student(&user)?; ensure_enrolled(&exam, user.get_id(), &st.db).await?; - course_of(&exam, &st.db).await?.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course_of(&exam, &st.db).await?).await?; let now = Timestamp::now(); if let Some(starts_at) = exam.get_starts_at() && now < starts_at @@ -307,7 +307,7 @@ pub(crate) async fn finish_attempt( { return Err(AppError::Conflict("time is up — the attempt has expired")); } - course_of(&exam, &st.db).await?.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course_of(&exam, &st.db).await?).await?; // Deliberately no rejoin check: a student locked out of the room may // still submit what they saved — finishing answers nothing new. @@ -699,7 +699,7 @@ pub(crate) async fn save_answer_in( ensure_student_now(attempt.get_user(), db).await?; ensure_enrolled(exam, attempt.get_user(), db).await?; check_rejoin(exam, attempt)?; - course_of(exam, db).await?.require_open(db).await?; + crate::service::course::require_open(db, &course_of(exam, db).await?).await?; let question = question_of_exam(exam.get_id(), question_id, db).await?; ExamAnswer::save( &question, diff --git a/src/web/exams/images.rs b/src/web/exams/images.rs index 42a90b8..a8c161f 100644 --- a/src/web/exams/images.rs +++ b/src/web/exams/images.rs @@ -99,7 +99,7 @@ pub(crate) async fn image_managed_exam( "only the course creator, an assigned teacher, or a manager/admin can manage question images", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; Ok(exam) } @@ -460,7 +460,7 @@ pub(crate) async fn upload_answer_image( ensure_student(&user)?; // Before the body is read: an archived term refuses the upload without // making the client push its bytes first. - course_of(&exam, &st.db).await?.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course_of(&exam, &st.db).await?).await?; // The body is consumed before the lock — a client's slow upload must not // stall the exam subsystem (mirrors the question-image upload). let ImageUpload { content_type, data } = read_image_upload(&st, &mut multipart).await?; @@ -540,7 +540,7 @@ pub(crate) async fn delete_answer_image( .await? .ok_or(AppError::NotFound)?; ensure_student(&user)?; - course_of(&exam, &st.db).await?.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course_of(&exam, &st.db).await?).await?; let _guard = EXAM_LOCK.read().await; let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; ensure_student_now(attempt.get_user(), &st.db).await?; diff --git a/src/web/exams/mod.rs b/src/web/exams/mod.rs index 7361018..ea0a0bd 100644 --- a/src/web/exams/mod.rs +++ b/src/web/exams/mod.rs @@ -266,7 +266,7 @@ struct ExamStatisticsResponse { /// The course an exam belongs to. A dangling reference means the course-delete /// cascade was violated — surface it loudly as a 500, not a user-facing 404. pub(crate) async fn course_of(exam: &Exam, db: &Database) -> Result { - Course::read(exam.get_course(), db) + crate::service::course::read(db, exam.get_course()) .await? .ok_or_else(|| AppError::Internal("exam references a missing course".into())) } @@ -433,7 +433,7 @@ async fn update_exam( "only the course creator, an assigned teacher, or a manager/admin can edit this exam", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; let title = match req.title { Some(ref title) => ExamTitle::try_new(title)?, @@ -591,7 +591,7 @@ async fn delete_exam( "only the course creator, an assigned teacher, or a manager/admin can delete this exam", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; // *Writer* lease of [`EXAM_LOCK`] across the whole cascade, blob names // included — the lease `delete_homework` has always held, and its absence // here is what made a sitting able to start inside this delete. Every other @@ -676,7 +676,7 @@ async fn grade( "only the course creator, an assigned teacher, or a manager/admin can grade this exam", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; // Pre-flight: `ExamResult::grade` re-makes this check inside the mark's own // transaction, so a re-draft landing after this read cannot leave a mark on // a hidden exam. @@ -883,7 +883,7 @@ async fn remove_result( "only the course creator, an assigned teacher, or a manager/admin can remove results", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; let removed = ExamResult::remove( exam.get_id(), &UserId::from_key(&target), diff --git a/src/web/exams/questions.rs b/src/web/exams/questions.rs index 1ca8c9a..9515435 100644 --- a/src/web/exams/questions.rs +++ b/src/web/exams/questions.rs @@ -219,7 +219,7 @@ pub(crate) async fn create_question( "only the course creator, an assigned teacher, or a manager/admin can author questions", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; // No lease: the subject check below is only a pre-flight for the message, // and the insert takes the subject's reference counter in the same breath — // a subject delete lands either wholly before it (400) or is refused. The @@ -358,7 +358,7 @@ pub(crate) async fn update_question( "only the course creator, an assigned teacher, or a manager/admin can edit questions", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; // No lease — see `create_question`; a re-tag moves the subject's reference // counter, and the freeze gate rides in the update's transaction. ensure_questions_editable(exam.get_id(), &st.db).await?; @@ -446,7 +446,7 @@ pub(crate) async fn delete_question( "only the course creator, an assigned teacher, or a manager/admin can delete questions", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; // No lock: the freeze gate is part of the delete's own transaction, and // this path checks no subject. The pre-flight below is the fast 409. ensure_questions_editable(exam.get_id(), &st.db).await?; @@ -518,7 +518,7 @@ pub(crate) async fn question_from_bank( "only the course creator, an assigned teacher, or a manager/admin can author questions", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; // No lease — same reasoning as `create_question`. The freeze gate rides in // the insert's transaction. ensure_questions_editable(exam.get_id(), &st.db).await?; @@ -649,7 +649,7 @@ pub(crate) async fn question_refresh_from_bank( "only the course creator, an assigned teacher, or a manager/admin can edit questions", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; // No lock: the question keeps its own subject here, so there is nothing to // pair with a subject delete, and the freeze gate rides in the overwrite's // transaction. @@ -774,7 +774,7 @@ pub(crate) async fn question_to_bank( "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; // No lease: `BANK_LOCK` is gone with the subject delete's writer lease, and // a template left holding a deleted subject reads as an empty // `subject_name` either way (see [`crate::web::bank_questions`]). diff --git a/src/web/homework.rs b/src/web/homework.rs index 0852606..38edeb1 100644 --- a/src/web/homework.rs +++ b/src/web/homework.rs @@ -166,7 +166,7 @@ async fn homework_with_course(id: &str, db: &Database) -> Result<(Homework, Cour let homework = Homework::read(&HomeworkId::from_key(id), db) .await? .ok_or(AppError::NotFound)?; - let course = Course::read(homework.get_course(), db) + let course = crate::service::course::read(db, homework.get_course()) .await? .ok_or(AppError::NotFound)?; Ok((homework, course)) @@ -345,7 +345,7 @@ async fn update_homework( "only the course creator, an assigned teacher, or a manager/admin can edit this homework", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; // Writer lease of [`HOMEWORK_LOCK`]: `ensure_no_orphans` below reads the // live submissions and results, and the row write depends on what it saw — @@ -465,7 +465,7 @@ async fn delete_homework( "only the course creator, an assigned teacher, or a manager/admin can delete this homework", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; let _guard = HOMEWORK_LOCK.write().await; let blob_keys = HomeworkFile::file_keys_for_homework(homework.get_id(), &st.db).await?; homework.delete(&st.db).await?; @@ -524,8 +524,8 @@ async fn gate_own_submission(id: &str, user: &User, db: &Database) -> Result Result<(), AppError> { - if let Some(course) = Course::read(homework.get_course(), db).await? { - course.require_open(db).await?; + if let Some(course) = crate::service::course::read(db, homework.get_course()).await? { + crate::service::course::require_open(db, &course).await?; } Ok(()) } @@ -1147,7 +1147,7 @@ async fn grade_homework( "only the course creator, an assigned teacher, or a manager/admin can grade this homework", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; let status = HomeworkStatus::try_new(&req.status)?; let mark = req.mark.map(Mark::try_new).transpose()?; @@ -1247,7 +1247,7 @@ async fn remove_homework_result( "only the course creator, an assigned teacher, or a manager/admin can remove grades", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; let removed = HomeworkResult::remove(homework.get_id(), &UserId::from_key(&target), &st.db).await?; if removed.is_none() { @@ -1481,7 +1481,7 @@ async fn homework_report( .ok_or(AppError::NotFound)?; // Only an exactly-teacher caller is narrowed to their managed courses; // manager+ and a linked parent read the full report (the marks idiom). - let (mut courses, _) = Course::list_enrolled(&target, None, 0, &st.db).await?; + let (mut courses, _) = crate::service::course::list_enrolled(&st.db, &target, None, 0).await?; if caller.get_role() == Role::Teacher { courses.retain(|course| can_manage_course(course, &caller)); } diff --git a/src/web/marks.rs b/src/web/marks.rs index f889137..5ea9970 100644 --- a/src/web/marks.rs +++ b/src/web/marks.rs @@ -9,7 +9,7 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::database::Database; -use crate::domain::course::Course; + use crate::domain::exam::Exam; use crate::domain::exam_result::ExamResult; use crate::domain::role::Role; @@ -96,7 +96,7 @@ async fn build_report( viewer: Option<&User>, db: &Database, ) -> Result { - let (mut courses, _) = Course::list_enrolled(user, None, 0, db).await?; + let (mut courses, _) = crate::service::course::list_enrolled(db, user, None, 0).await?; if let Some(viewer) = viewer { courses.retain(|course| can_manage_course(course, viewer)); } diff --git a/src/web/mod.rs b/src/web/mod.rs index 2cc4f0a..0a19a93 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -138,7 +138,7 @@ pub(crate) async fn undo_if_demoted(target: &UserId, db: &Database) -> Result<() return Ok(()); } crate::domain::class_group::ClassGroup::unassign_everywhere(target, db).await?; - crate::domain::course::Course::unassign_everywhere(target, db).await?; + crate::service::course::unassign_everywhere(db, target).await?; Err(AppError::Conflict( "that user was demoted below teacher while this request ran — the assignment was undone; re-read their role and retry", )) @@ -409,7 +409,7 @@ mod tests { #[tokio::test] async fn undo_if_demoted_repairs_both_assignments_or_neither() { use crate::domain::class_group::{ClassGroup, ClassName}; - use crate::domain::course::{Course, CourseDescription, CourseKind, CourseTitle}; + use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; use crate::domain::user::{Password, Username}; let db = crate::database::init_mem().await.unwrap(); @@ -441,19 +441,22 @@ mod tests { ) .await .unwrap(); - let course = Course::create( - &office, - CourseTitle::try_new("algebra").unwrap(), - CourseDescription::try_new("").unwrap(), - CourseKind::course(), - None, - None, + let course = crate::service::course::assign_teacher( db, + &crate::service::course::create( + db, + &office, + CourseTitle::try_new("algebra").unwrap(), + CourseDescription::try_new("").unwrap(), + CourseKind::course(), + None, + None, + ) + .await + .unwrap(), + teacher.get_id(), ) .await - .unwrap() - .assign_teacher(teacher.get_id(), db) - .await .unwrap(); (class, course) }; @@ -470,7 +473,7 @@ mod tests { .unwrap() .get_teacher() .cloned(), - Course::read(course, db) + crate::service::course::read(db, course) .await .unwrap() .unwrap() diff --git a/src/web/sessions.rs b/src/web/sessions.rs index 270bd0a..7d70fe1 100644 --- a/src/web/sessions.rs +++ b/src/web/sessions.rs @@ -122,7 +122,7 @@ async fn session_with_course(id: &str, db: &Database) -> Result<(CourseSession, let session = CourseSession::read(&CourseSessionId::from_key(id), db) .await? .ok_or(AppError::NotFound)?; - let course = Course::read(session.get_course(), db) + let course = crate::service::course::read(db, session.get_course()) .await? .ok_or(AppError::NotFound)?; Ok((session, course)) @@ -219,7 +219,7 @@ async fn update_session( "only the course creator, an assigned teacher, or a manager/admin can edit this session", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; let topic = req .topic @@ -277,7 +277,7 @@ async fn delete_session( "only the course creator, an assigned teacher, or a manager/admin can delete this session", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; session.delete(&st.db).await?; Ok(StatusCode::NO_CONTENT) } @@ -318,7 +318,7 @@ async fn mark_roll_call( "only the session's teacher or a course manager can take roll call", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; let school = service::settings::load(&st.db).await?; let status = AttendanceStatus::try_new(&req.status, school.get_attendance_statuses())?; @@ -458,7 +458,7 @@ async fn remove_roll_call( "only the session's teacher or a course manager can take roll call", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; let target = UserId::from_key(&target); // A staff row is management's to remove, keyed on the *target's live role* // rather than on `is_teacher`: reassigning a session's teacher used to hand diff --git a/src/web/subjects.rs b/src/web/subjects.rs index 303a71e..959a97a 100644 --- a/src/web/subjects.rs +++ b/src/web/subjects.rs @@ -74,7 +74,7 @@ async fn subject_with_course(id: &str, db: &Database) -> Result<(Subject, Course let subject = Subject::read(&SubjectId::from_key(id), db) .await? .ok_or(AppError::NotFound)?; - let course = Course::read(subject.get_course(), db) + let course = crate::service::course::read(db, subject.get_course()) .await? .ok_or(AppError::NotFound)?; Ok((subject, course)) @@ -142,7 +142,7 @@ async fn update_subject( "only the course creator, an assigned teacher, or a manager/admin can edit this subject", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; // Only what the request actually carried is validated and written — an // omitted field stays `None` so the save never re-sends this snapshot's @@ -193,7 +193,7 @@ async fn delete_subject( "only the course creator, an assigned teacher, or a manager/admin can delete this subject", )); } - course.require_open(&st.db).await?; + crate::service::course::require_open(&st.db, &course).await?; // No locks: the two checks *are* the delete's `WHERE`, decided against the // subject's own reference counters inside one statement. This used to be // three process-wide locks (the only site that held more than one) around diff --git a/src/web/users.rs b/src/web/users.rs index 3cd9ace..d9e2817 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -16,7 +16,7 @@ use crate::database::Database; use crate::domain::badge::{self, BadgeAward}; use crate::domain::class_group::{ClassGroup, ClassGroupId}; use crate::domain::class_member::ClassMember; -use crate::domain::course::Course; + use crate::domain::parent_link::ParentLink; use crate::domain::preferences::{Language, PaletteColor, Theme}; use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone, ProfileStats}; @@ -926,14 +926,14 @@ async fn profile_of( let (mut courses, course_total) = match user.get_role().at_least(Role::Teacher) { // The teacher read is unpaged, so the total is what came back. true => { - let courses = Course::list_for_teacher(id, &st.db).await?; + let courses = crate::service::course::list_for_teacher(&st.db, id).await?; let total = courses.len() as i64; (courses, total) } // Unfiltered readers can take the window from the database. false => { let window = readable.is_none().then_some(MAX_PROFILE_COURSES as i64); - Course::list_enrolled(id, window, 0, &st.db).await? + crate::service::course::list_enrolled(&st.db, id, window, 0).await? } }; if let Some(readable) = &readable { diff --git a/tests/integration.rs b/tests/integration.rs index 07cee12..31269b6 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -21298,8 +21298,9 @@ async fn refreshing_a_question_recopies_its_template() { /// inside the handler. #[tokio::test] async fn a_course_patch_does_not_clobber_a_concurrent_teacher_assignment() { + use hezarfen_backend::db::course; use hezarfen_backend::domain::course::{ - Course, CourseDescription, CourseId, CourseKind, CourseTitle, + CourseDescription, CourseId, CourseKind, CourseTitle, }; let (app, db) = app_and_db().await; @@ -21310,7 +21311,7 @@ async fn a_course_patch_does_not_clobber_a_concurrent_teacher_assignment() { let course = create_course(&app, &owner, "cclob_c").await; // The handler's read, then the assignment lands mid-window. - let stale = Course::read(&CourseId::from_key(&course), &db) + let stale = course::read(&db, &CourseId::from_key(&course)) .await .unwrap() .expect("course exists"); @@ -21324,17 +21325,17 @@ async fn a_course_patch_does_not_clobber_a_concurrent_teacher_assignment() { .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); - let updated = stale - .update( - Some(CourseTitle::try_new("renamed").unwrap()), - Some(CourseDescription::try_new("").unwrap()), - Some(CourseKind::course()), - None, - None, - &db, - ) - .await - .expect("update written"); + let updated = course::update( + &db, + stale, + Some(CourseTitle::try_new("renamed").unwrap()), + Some(CourseDescription::try_new("").unwrap()), + Some(CourseKind::course()), + None, + None, + ) + .await + .expect("update written"); assert_eq!( updated.get_teachers().len(), 1, @@ -21360,8 +21361,8 @@ async fn a_course_patch_does_not_clobber_a_concurrent_teacher_assignment() { /// the rename. `unassign_teacher` gets the same field-scoped treatment. #[tokio::test] async fn staffing_a_course_does_not_clobber_a_concurrent_edit() { - use hezarfen_backend::domain::course::{Course, CourseId}; - use hezarfen_backend::domain::user::UserId; + use hezarfen_backend::db::course; + use hezarfen_backend::domain::course::CourseId; let (app, db) = app_and_db().await; let owner = login_as(&app, &db, "cstaff_o", "teacher").await; @@ -21370,7 +21371,7 @@ async fn staffing_a_course_does_not_clobber_a_concurrent_edit() { let course = create_course(&app, &owner, "cstaff_c").await; // The handler's read, then someone else's edit lands mid-window. - let stale = Course::read(&CourseId::from_key(&course), &db) + let stale = course::read(&db, &CourseId::from_key(&course)) .await .unwrap() .expect("course exists"); @@ -21384,8 +21385,7 @@ async fn staffing_a_course_does_not_clobber_a_concurrent_edit() { .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); - let assigned = stale - .assign_teacher(&UserId::from_key(&helper_id), &db) + let assigned = course::assign_teacher(&db, stale, &UserId::from_key(&helper_id)) .await .expect("assignment written"); assert_eq!(assigned.get_title().as_str(), "edited by someone else"); @@ -21393,7 +21393,7 @@ async fn staffing_a_course_does_not_clobber_a_concurrent_edit() { assert_eq!(assigned.get_teachers().len(), 1); // Unassigning from a struct read before another edit is just as safe. - let stale = Course::read(&CourseId::from_key(&course), &db) + let stale = course::read(&db, &CourseId::from_key(&course)) .await .unwrap() .expect("course exists"); @@ -21406,8 +21406,7 @@ async fn staffing_a_course_does_not_clobber_a_concurrent_edit() { ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); - let dropped = stale - .unassign_teacher(&UserId::from_key(&helper_id), &db) + let dropped = course::unassign_teacher(&db, stale, &UserId::from_key(&helper_id)) .await .expect("unassignment written") .expect("teacher was assigned"); diff --git a/tests/regress_course_child_orphans.rs b/tests/regress_course_child_orphans.rs index 09b19e8..a7fa258 100644 --- a/tests/regress_course_child_orphans.rs +++ b/tests/regress_course_child_orphans.rs @@ -48,9 +48,8 @@ mod common; use axum::http::StatusCode; use common::{app_and_db, id_of, login_as, send, upload_course_note_file}; use hezarfen_backend::database::{self, Database}; -use hezarfen_backend::domain::course::{ - Course, CourseDescription, CourseId, CourseKind, CourseTitle, -}; +use hezarfen_backend::db::course; +use hezarfen_backend::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle}; use hezarfen_backend::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; use hezarfen_backend::domain::course_note_file::{CourseNoteFile, FileContentType, FileName}; use hezarfen_backend::domain::course_session::{CourseSession, SessionTopic}; @@ -70,14 +69,14 @@ fn teacher() -> UserId { } async fn a_course(db: &Database) -> CourseId { - Course::create( + course::create( + db, &teacher(), CourseTitle::try_new("Fizik").unwrap(), CourseDescription::try_new("").unwrap(), CourseKind::course(), None, None, - db, ) .await .unwrap() @@ -86,12 +85,14 @@ async fn a_course(db: &Database) -> CourseId { } async fn drop_course(course: &CourseId, db: &Database) -> Result { - Course::read(course, db) - .await - .unwrap() - .expect("the course is there") - .delete(db) - .await + course::delete( + db, + course::read(db, course) + .await + .unwrap() + .expect("the course is there"), + ) + .await } // --- the three creates, each as one spawnable unit ------------------------- @@ -324,13 +325,15 @@ async fn a_course_note_file_under_a_deleted_note_is_refused() { .await .unwrap(); assert!( - Course::read(&course, &db) - .await - .unwrap() - .unwrap() - .delete(&db) - .await - .unwrap(), + course::delete( + &db, + course::read(&db, &course) + .await + .unwrap() + .unwrap() + ) + .await + .unwrap(), "the course, and its note with it, goes" ); diff --git a/tests/regress_course_delete.rs b/tests/regress_course_delete.rs index b909eca..105f940 100644 --- a/tests/regress_course_delete.rs +++ b/tests/regress_course_delete.rs @@ -27,18 +27,22 @@ use common::{ app_and_db, create_course, create_exam, create_exam_with, create_subject, enroll, id_of, login, login_as, me_id, send, unenroll, }; -use hezarfen_backend::domain::course::{Course, CourseId}; +use hezarfen_backend::db::course; +use hezarfen_backend::domain::course::CourseId; use hezarfen_backend::domain::exam::ExamId; use hezarfen_backend::domain::exam_attempt::ExamAttempt; use serde_json::json; /// Delete `course` the way the handler would, minus its `EXAM_LOCK` lease. async fn drop_course(db: &hezarfen_backend::database::Database, course: &str) { - let row = Course::read(&CourseId::from_key(course), db) + let row = course::read(db, &CourseId::from_key(course)) .await .expect("read the course") .expect("the course exists"); - assert!(row.delete(db).await.expect("delete the course"), "refused"); + assert!( + course::delete(db, row).await.expect("delete the course"), + "refused" + ); } /// A bank template outlives the course it was saved out of — it is a separate,