diff --git a/src/db/course.rs b/src/db/course.rs index ce47891..0859b9a 100644 --- a/src/db/course.rs +++ b/src/db/course.rs @@ -1,11 +1,9 @@ //! 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}; +//! guarded cascade. -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::constant::COURSE_TABLE; +use crate::database::{Database, tx_with_retry, unique_violation}; use crate::db::cap; use crate::db::field_update::FieldUpdate; use crate::db::page::PagedList; @@ -14,16 +12,6 @@ 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, @@ -33,50 +21,87 @@ pub async fn create( term: Option, capacity: Option, ) -> Result { - let course = Course { - id: CourseId::generate(), - creator: creator.clone(), - teachers: Vec::new(), - term, - capacity, + let id = CourseId::generate(); + let Some(term) = term else { + let created = sqlx::query_as!( + Course, + r#"INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity) + VALUES ($1, $2, $3, $4, $5, $6, NULL, $7) + RETURNING id, creator, teachers, title, description, kind, term, capacity"#, + id, + creator, + Vec::::new(), + title, + description, + kind, + capacity, + ) + .fetch_one(db) + .await?; + return Ok(created); + }; + // Claim a reference on the term in the *same statement* 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). + let created = sqlx::query_as!( + Course, + r#"WITH seat AS ( + UPDATE term + SET course_count = course_count + 1 + WHERE id = $8 AND course_count < $9 + RETURNING 1) + INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity) + SELECT $1, $2, $3, $4, $5, $6, $8, $7 WHERE EXISTS (SELECT 1 FROM seat) + RETURNING id, creator, teachers, title, description, kind, term, capacity"#, + id, + creator, + Vec::::new(), 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, + capacity, + term, cap::UNLIMITED, - &id, - &course, - db, ) - .await? - { - cap::Claimed::Made(created) => Ok(created), + .fetch_one(db) + .await; + match created { + Ok(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())), + Err(sqlx::Error::RowNotFound) => Err(term::gone_error()), + // Unreachable: the id was minted above. + Err(err) if unique_violation(&err).is_some() => { + Err(AppError::Internal("failed to create course".into())) + } + Err(err) => Err(err.into()), } } pub async fn read(db: &Database, id: &CourseId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let course = sqlx::query_as!( + Course, + r#"SELECT id, creator, teachers, title, description, kind, term, capacity + FROM course WHERE id = $1"#, + id, + ) + .fetch_optional(db) + .await?; + Ok(course) } 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)?) + let rows = sqlx::query_as!( + Course, + r#"SELECT id, creator, teachers, title, description, kind, term, capacity + FROM course ORDER BY id DESC"#, + ) + .fetch_all(db) + .await?; + Ok(rows) } /// The courses `user` is enrolled in — the spine of `/courses/me` and the @@ -88,36 +113,38 @@ pub async fn list_enrolled( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - "course WHERE id IN (SELECT VALUE course FROM enrollment WHERE user = $usr)", + "course WHERE id IN (SELECT course FROM enrollment WHERE app_user = $1)", "ORDER BY id DESC", ) - .bind("usr", user.record()) - .run(limit, offset, db) + .bind(user.uuid()) + .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. +/// 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. +/// Under Postgres the `OR` halves could each use an index on `creator` / +/// `teachers` (a GIN), but the old per-element index the membership half +/// would have needed was *wrong*, not merely useless — `$usr IN teachers` +/// returned **no rows at all** with it, which is what the integration test +/// `assigned_teacher_manages_course_without_owning_it` catches. 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. No schema carries it yet, so the scan stays. 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)?) + let rows = sqlx::query_as!( + Course, + r#"SELECT id, creator, teachers, title, description, kind, term, capacity + FROM course WHERE creator = $1 OR $2 = ANY(teachers) ORDER BY id DESC"#, + user, + user, + ) + .fetch_all(db) + .await?; + Ok(rows) } /// Load every course behind `ids` (one query) — the join half of the @@ -126,13 +153,16 @@ pub async fn list_by_ids(db: &Database, ids: &[CourseId]) -> Result, 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)?) + let keys: Vec = ids.to_vec(); + let rows = sqlx::query_as!( + Course, + r#"SELECT id, creator, teachers, title, description, kind, term, capacity + FROM course WHERE id = ANY($1)"#, + keys, + ) + .fetch_all(db) + .await?; + Ok(rows) } /// Request-scoped: `teachers` is written by [`assign_teacher`], @@ -160,19 +190,25 @@ pub async fn update( // 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) + FieldUpdate::new(COURSE_TABLE, course.id.uuid()) + .set("title", title.map(|title| title.as_str().to_owned())) + .set( + "description", + description.map(|description| description.as_str().to_owned()), + ) + .set("kind", kind.map(|kind| kind.as_str().to_owned())) + .set( + "term", + term.map(|term| crate::db::page::Param::OptUuid(term.map(|term| term.uuid()))), + ) + .set("capacity", capacity.map(crate::db::page::Param::OptI64)) .refcount( - COURSE_COUNT_FIELD, "term", - expected, - claim, - release, + "course_count", + "term", + course.term.as_ref().map(|term| term.uuid()), + claim.map(|term| term.uuid()), + release.map(|term| term.uuid()), term::gone_error(), ) .run::(db) @@ -184,8 +220,9 @@ pub async fn update( /// 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). +/// `array_agg(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, @@ -194,20 +231,19 @@ pub async fn assign_teacher( 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) + let updated = sqlx::query_as!( + Course, + r#"UPDATE course + SET teachers = (SELECT array_agg(DISTINCT x) + FROM unnest(course.teachers || $2) AS x) + WHERE id = $1 + RETURNING id, creator, teachers, title, description, kind, term, capacity"#, + course.id, + teacher, + ) + .fetch_optional(db) + .await?; + updated.ok_or(AppError::NotFound) } /// Drop `teacher` from this course. `None` when they weren't assigned, so @@ -220,30 +256,32 @@ pub async fn unassign_teacher( 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)?, - )) + // Same field-scoped story as [`assign_teacher`]; `array_remove` drops + // the one link off the stored list without touching the course's own + // text. + let updated = sqlx::query_as!( + Course, + r#"UPDATE course SET teachers = array_remove(teachers, $2) + WHERE id = $1 + RETURNING id, creator, teachers, title, description, kind, term, capacity"#, + course.id, + teacher, + ) + .fetch_optional(db) + .await?; + Ok(updated) } /// 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()?; + sqlx::query!( + r#"UPDATE course SET teachers = array_remove(teachers, $1) + WHERE $1 = ANY(teachers)"#, + user, + ) + .execute(db) + .await?; Ok(()) } @@ -261,111 +299,233 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App /// **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::db::exam::delete`] and -/// [`crate::db::subject::delete`] clear them one level down. -/// Deleting a course must leave the bank where deleting each of its exams -/// and subjects by hand would have left it, or a template is left pointing -/// at a dead exam (permanently: nothing else ever visits that column) and -/// at a dead subject the next `PATCH` omitting `subject_id` writes straight -/// back. +/// [`crate::db::exam::delete`] and [`crate::db::subject::delete`] +/// clear them one level down. Deleting a course must leave the bank where +/// deleting each of its exams and subjects by hand would have left it, or +/// a template is left pointing at a dead exam (permanently: nothing else +/// ever visits that column) and 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::db::class_blueprint::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. +/// [`crate::db::class_blueprint::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. A dozen-row +/// table scanned unindexed, deliberately: a course delete is rare. /// -/// 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 **derived AI rows** (`rag_output` carries a denormalized `course` +/// besides its note link) and the event **audience links** are FK children +/// the old store let dangle: `rag_output` is disposable and dies here, and +/// an event whose audience was "this course's students" keeps standing with +/// `audience_course` cleared — an empty roster, exactly the documented +/// outcome of the class twin (`Course::delete` never touched `event`; it +/// still doesn't delete one). /// /// 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. /// +/// **Order is the foreign-key graph, children first** (the old store had +/// no FKs, so its order was free): exam results/attempts/answers/images +/// and question images before `exam_question`; `exam_question` before +/// `exam`; homework files before submissions before results before +/// `homework`; roll-call rows before `course_session`; note files and +/// rag rows before `course_note`; every one of them before the `course` +/// row itself, whose `NO ACTION` FKs are checked the moment the final +/// `DELETE` runs. +/// /// `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. +/// guard locks the course row (`FOR UPDATE`) and reads its own +/// `enrollment_count`, so 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 — and unlike the old one-statement guard, this one tells the two +/// apart without a second read. 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), + tx_with_retry(db, true, async |tx| { + // The guard and the lock: the row (and its roster count) cannot + // change under this transaction, and every enroll claim contends on + // this very row, so check and cascade are one decision. + let guard = sqlx::query!( + r#"SELECT enrollment_count, term FROM course WHERE id = $1 FOR UPDATE"#, + course.id, + ) + .fetch_optional(&mut *tx) + .await?; + let Some(guard) = guard else { + return Err(AppError::NotFound); }; - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - Ok(true) + if guard.enrollment_count != 0 { + return Ok(false); + } + // The exam ids are needed twice — the kind_ref refund and the bank's + // source_exam clear — and must be collected before the sweeps take + // the rows they name. + let exams: Vec = + sqlx::query!(r#"SELECT id FROM exam WHERE course = $1"#, course.id,) + .fetch_all(&mut *tx) + .await? + .into_iter() + .map(|row| row.id) + .collect(); + // Every mark the course ever gave gives its exam kind's reference + // back, counted per kind (mirrors `Exam::delete`). The kind rides + // the exam row — `exam_result` names its exam, not its kind. + sqlx::query!( + r#"UPDATE kind_ref k + SET count = GREATEST(k.count - s.n, 0) + FROM (SELECT e.kind, count(*) AS n FROM exam_result r + JOIN exam e ON r.exam = e.id + WHERE r.exam = ANY($1) GROUP BY e.kind) s + WHERE k.name = s.kind"#, + exams, + ) + .execute(&mut *tx) + .await?; + // The term gets its reference back inside the same transaction. + if let Some(term) = guard.term { + sqlx::query!( + r#"UPDATE term SET course_count = GREATEST(course_count - 1, 0) + WHERE id = $1"#, + term, + ) + .execute(&mut *tx) + .await?; + } + // Events aimed at this course keep standing, audience cleared. + sqlx::query!( + r#"UPDATE event SET audience_course = NULL WHERE audience_course = $1"#, + course.id, + ) + .execute(&mut *tx) + .await?; + // The exam subtree, deepest children first. + sqlx::query!(r#"DELETE FROM exam_result WHERE exam = ANY($1)"#, exams) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM exam_attempt WHERE exam = ANY($1)"#, exams) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM exam_answer WHERE exam = ANY($1)"#, exams) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM answer_image WHERE exam = ANY($1)"#, exams) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM question_image WHERE exam = ANY($1)"#, exams) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM exam_question WHERE exam = ANY($1)"#, exams) + .execute(&mut *tx) + .await?; + // The homework subtree: files, then submissions (whose graded_by + // link names a result deleted after them), then results. + sqlx::query!( + r#"DELETE FROM homework_file WHERE submission IN ( + SELECT id FROM homework_submission + WHERE homework IN (SELECT id FROM homework WHERE course = $1))"#, + course.id, + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + r#"DELETE FROM homework_submission WHERE homework IN ( + SELECT id FROM homework WHERE course = $1)"#, + course.id, + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + r#"DELETE FROM homework_result WHERE homework IN ( + SELECT id FROM homework WHERE course = $1)"#, + course.id, + ) + .execute(&mut *tx) + .await?; + // Derived AI rows for this course's notes. + sqlx::query!(r#"DELETE FROM rag_output WHERE course = $1"#, course.id) + .execute(&mut *tx) + .await?; + // Notes: files before their notes. + sqlx::query!( + r#"DELETE FROM course_note_file WHERE course_note IN ( + SELECT id FROM course_note WHERE course = $1)"#, + course.id, + ) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM course_note WHERE course = $1"#, course.id) + .execute(&mut *tx) + .await?; + // Class attachments: detach and hand each class its count back in + // one statement, then strike the course out of every blueprint. + sqlx::query!( + r#"WITH detached AS ( + DELETE FROM class_course WHERE course = $1 RETURNING class) + UPDATE class_group g + SET class_course_count = GREATEST(g.class_course_count - 1, 0) + FROM detached WHERE g.id = detached.class"#, + course.id, + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + r#"UPDATE class_blueprint SET courses = array_remove(courses, $1) + WHERE $1 = ANY(courses)"#, + course.id, + ) + .execute(&mut *tx) + .await?; + // Sessions with their roll call, then the roster itself. + sqlx::query!( + r#"DELETE FROM session_attendance WHERE course = $1"#, + course.id, + ) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM course_session WHERE course = $1"#, course.id) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM enrollment WHERE course = $1"#, course.id) + .execute(&mut *tx) + .await?; + // The bank keeps its templates; their links to this course's + // content go first, so the subject/exam deletes below cannot trip + // a foreign key behind them. + sqlx::query!( + r#"UPDATE bank_question SET subject = NULL + WHERE subject IN (SELECT id FROM subject WHERE course = $1)"#, + course.id, + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + r#"UPDATE bank_question SET source_exam = NULL WHERE source_exam = ANY($1)"#, + exams, + ) + .execute(&mut *tx) + .await?; + // Subjects before exams would trip `exam.subject` — exams go first. + sqlx::query!(r#"DELETE FROM exam WHERE course = $1"#, course.id) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM homework WHERE course = $1"#, course.id) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM subject WHERE course = $1"#, course.id) + .execute(&mut *tx) + .await?; + // Last: the course itself, now FK-silent. + sqlx::query!(r#"DELETE FROM course WHERE id = $1"#, course.id) + .execute(&mut *tx) + .await?; + Ok(true) + }) + .await } /// A real course row, for the tests of every child that must now prove its diff --git a/src/db/course_session.rs b/src/db/course_session.rs index ff7aea7..9950dfb 100644 --- a/src/db/course_session.rs +++ b/src/db/course_session.rs @@ -1,15 +1,11 @@ //! The `course_session` table: reads, a course's timetable listing, the //! request-scoped field update, and the delete that sweeps roll-call rows in -//! one transaction. Creation writes the course row through -//! [`cap::touch_and_create`] so a lesson can never outlive its course; the -//! web-facing doors and the teacher-resolution rule live in -//! [`crate::service::course_session`]. +//! one transaction. Creation stands on the course foreign key, so a lesson +//! can never outlive its course; the web-facing doors and the +//! teacher-resolution rule live in [`crate::service::course_session`]. -use surrealdb::types::SurrealValue; - -use crate::constant::ENROLLMENT_COUNT_FIELD; -use crate::database::{Database, transaction_with_retry}; -use crate::db::cap; +use crate::constant::COURSE_SESSION_TABLE; +use crate::database::{Database, foreign_key_violation, tx_with_retry}; use crate::db::field_update::FieldUpdate; use crate::db::page::PagedList; use crate::domain::course::CourseId; @@ -34,23 +30,44 @@ pub async fn create( starts_at, ends_at, }; - // The course row is *written* (bumped and put back), not read, so this - // collides with `Course::delete`'s cascade: a lesson that outlives its - // course 404s through `session_with_course` forever — unreadable, - // unpatchable, undeletable. See [`cap::touch_and_create`]. - cap::touch_and_create( - &course.record(), - ENROLLMENT_COUNT_FIELD, - &session.id.record(), - &session, - db, + // The course foreign key is the existence proof the old bump-and-restore + // "touch" trick faked: a lesson whose course is already gone — or which + // is deleted while this insert is in flight — is refused here, so a + // lesson can never outlive its course and 404 through + // `session_with_course` forever — unreadable, unpatchable, undeletable. + // `23503` is the parent-gone refusal, the same answer the touch + // produced. + let created = sqlx::query_as!( + CourseSession, + r#"INSERT INTO course_session (id, course, teacher, topic, starts_at, ends_at) + VALUES ($1, $2, $3, $4, $5, $6) + RETURNING id, course, teacher, topic, starts_at, ends_at"#, + session.id, + session.course, + session.teacher, + session.topic, + session.starts_at, + session.ends_at, ) - .await? - .ok_or(AppError::NotFound) + .fetch_one(db) + .await; + match created { + Ok(created) => Ok(created), + Err(err) if foreign_key_violation(&err) => Err(AppError::NotFound), + Err(err) => Err(err.into()), + } } pub async fn read(db: &Database, id: &CourseSessionId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let session = sqlx::query_as!( + CourseSession, + r#"SELECT id, course, teacher, topic, starts_at, ends_at + FROM course_session WHERE id = $1"#, + id, + ) + .fetch_optional(db) + .await?; + Ok(session) } /// A course's sessions, most recent lesson first. Ordered by `starts_at` @@ -63,11 +80,11 @@ pub async fn list_for_course( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - "course_session WHERE course = $course", + "course_session WHERE course = $1", "ORDER BY starts_at DESC, id DESC", ) - .bind("course", course.record()) - .run(limit, offset, db) + .bind(course.uuid()) + .run::(limit, offset, db) .await } @@ -86,11 +103,17 @@ pub async fn update( starts_at: Option, ends_at: Option>, ) -> Result { - FieldUpdate::new(session.id.record()) - .set("teacher", teacher.map(|teacher| teacher.record())) - .set("topic", topic) - .set("starts_at", starts_at) - .set("ends_at", ends_at) + FieldUpdate::new(COURSE_SESSION_TABLE, session.id.uuid()) + .set( + "teacher", + teacher.map(|teacher| crate::db::page::Param::Uuid(teacher.uuid())), + ) + .set("topic", topic.map(|topic| topic.as_str().to_owned())) + .set("starts_at", starts_at.map(|at| at.as_millis())) + .set( + "ends_at", + ends_at.map(|ends_at| crate::db::page::Param::OptI64(ends_at.map(|at| at.as_millis()))), + ) .ordered("starts_at", "ends_at", range_error()) .run::(db) .await @@ -99,32 +122,31 @@ pub async fn update( /// Delete the session and cascade-remove its roll-call rows, in one /// transaction: as two unbatched queries a failure between them stranded /// roll-call rows on a session that was already gone. The other half of -/// that invariant is [`crate::db::session_attendance::mark`], -/// which proves the session still exists inside its own write — a -/// transaction here cannot stop a mark that commits *after* this one. +/// that invariant is [`crate::db::session_attendance::mark`], whose +/// session-row lock makes a mark and this delete take turns — a mark +/// committing after this cascade cannot name a session that is gone. pub async fn delete(db: &Database, session: CourseSession) -> Result { - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - DELETE session_attendance WHERE session = $s; - LET $before = (DELETE $s RETURN BEFORE); - RETURN $before; - COMMIT TRANSACTION;", - &[("s".into(), session.id.record().into_value())], - // No THROW of its own — an unconditional cascade, so the only - // error worth telling apart is a lost round (see - // [`crate::db::exam::delete`]). - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Read through the trailing `RETURN`, never a hand-counted slot. - let slot = result.num_statements().saturating_sub(2); - let deleted: Option = - result.take::>(slot)?.into_iter().next(); - deleted.ok_or(AppError::NotFound) + tx_with_retry(db, false, async |tx| { + // Roll-call rows first: the session row's own FK would refuse the + // delete while they exist. An empty first sweep is fine — the + // session may simply have had none. + sqlx::query!( + r#"DELETE FROM session_attendance WHERE session = $1"#, + session.id, + ) + .execute(&mut *tx) + .await?; + let deleted = sqlx::query_as!( + CourseSession, + r#"DELETE FROM course_session WHERE id = $1 + RETURNING id, course, teacher, topic, starts_at, ends_at"#, + session.id, + ) + .fetch_optional(&mut *tx) + .await?; + deleted.ok_or(AppError::NotFound) + }) + .await } #[cfg(test)] diff --git a/src/db/enrollment.rs b/src/db/enrollment.rs index 7e122e2..fdffd98 100644 --- a/src/db/enrollment.rs +++ b/src/db/enrollment.rs @@ -1,49 +1,55 @@ //! The `enrollment` table: the roster read and listing, the seat-returning -//! delete, and the enroll claim — the one transaction that checks the pair -//! free, the member still a student, and the roster under capacity while it +//! delete, and the enroll claim — one transaction that checks the pair free, +//! the member still a student, and the roster under capacity while it //! spends the seat. The target-user gates the HTTP handlers pay live in //! [`crate::service::enrollment`]. -use surrealdb::types::SurrealValue; - -use crate::constant::ENROLLMENT_COUNT_FIELD; -use crate::database::{Database, transaction_with_retry}; +use crate::database::{Database, tx_with_retry, unique_violation}; use crate::db::cap; use crate::db::page::PagedList; use crate::domain::course::CourseId; -use crate::domain::enrollment::{Enrollment, EnrollmentId}; +use crate::domain::enrollment::Enrollment; use crate::domain::role::Role; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; -/// The `THROW` markers [`enroll`]'s claim aborts with: this pair -/// already holds a row, the roster is full, and the person being enrolled is no -/// longer a student. -const HELD_MARK: &str = "enroll_held"; -const FULL_MARK: &str = "enroll_full"; -const UNFIT_MARK: &str = "enroll_not_student"; +/// What [`enroll`]'s transaction settled on — the three old `THROW` markers +/// (`enroll_held`, `enroll_not_student`, `enroll_full`) as Rust verdicts. +enum Verdict { + /// This pair already holds a row. + Held, + /// The person being enrolled is no longer a student. + Unfit, + /// The roster is full — or the course is gone; the caller reads which. + Full, + /// The seat is spent and the row is written. + Made(Enrollment), +} + +/// The primary key the natural composite PK carries — the constraint name +/// that surfaces in SQLSTATE 23505 when a rival lands first. +const PAIR_CONSTRAINT: &str = "enrollment_course_user"; -/// Enroll (idempotently) `user` into `course`. One row per (course, user), -/// keyed by a deterministic composite id, so concurrent enrolls of the same -/// pair converge on one row instead of racing the unique index into a 500: -/// the loser of the `CREATE` reads the winner's row back and returns it. -/// When the course carries a capacity, a full roster refuses new members -/// (409) — the seat is taken by a single-record conditional write on the -/// course row whose bound is the row's *own* `capacity` column, read inside -/// the same statement that spends the seat. A snapshot integer taken by a -/// read beforehand would be exactly the number a concurrent capacity PATCH -/// invalidates, which is what this promised and did not do. An already -/// enrolled user is returned as-is even when the roster is full, and never -/// charged a seat. The same claim is the delete guard's other half: it -/// matches nothing once the course row is gone, and while it holds a seat -/// the course cannot be deleted — so no roster row can outlive its course. +/// Enroll (idempotently) `user` into `course`. The table's primary key *is* +/// the (course, user) pair, so concurrent enrolls of the same pair converge +/// on one row instead of racing into a 500: the loser reads the winner's row +/// back and returns it. When the course carries a capacity, a full roster +/// refuses new members (409) — the seat is taken by a single-record +/// conditional write on the course row whose bound is the row's *own* +/// `capacity` column, read inside the same statement that spends the seat. A +/// snapshot integer taken by a read beforehand would be exactly the number a +/// concurrent capacity PATCH invalidates. An already enrolled user is +/// returned as-is even when the roster is full, and never charged a seat. +/// The same claim is the delete guard's other half: it matches nothing once +/// the course row is gone, and while it holds a seat the course cannot be +/// deleted — so no roster row can outlive its course. /// -/// On admissibility ([`crate::database::transaction_with_retry`]): the -/// `CREATE` here *can* answer "already exists", but only to a rival that -/// landed inside this very window — and the re-send then sees that row at -/// the `$held` gate and takes the other branch, so the loop converges -/// instead of re-asking a settled question. Same shape, same reason, as -/// [`crate::db::class_pump::attach`]. +/// Gate order is the old THROW order: an existing pair outranks the role +/// check, which outranks a full roster. The role check takes the user row +/// `FOR NO KEY UPDATE`, the same row a demotion cascade updates before its +/// sweep, so grant and demotion serialize on the row lock in both +/// directions — a row landing after the sweep is impossible, and a demotion +/// landing before this check refuses it. pub async fn enroll( db: &Database, course: &CourseId, @@ -53,112 +59,89 @@ pub async fn enroll( if let Some(existing) = read_for_user(db, course, user).await? { return disown_if_pumped(db, existing).await; } - let enrollment = Enrollment { - id: EnrollmentId::composite(course, user), - course: course.clone(), - user: user.clone(), - enrolled_by: enrolled_by.clone(), - // Hand-placed: no source key at all is written, which is what makes - // a class sweep unable to take this row back. - source: None, + let verdict = tx_with_retry(db, false, async |tx| { + // The duplicate gate rides ahead of the role check, so "you are + // already in" still outranks everything. + let held = sqlx::query!( + r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#, + course, + user, + ) + .fetch_optional(&mut *tx) + .await?; + if held.is_some() { + return Ok(Verdict::Held); + } + // The role handshake: the live role decides, and the row lock makes + // the check and the insert one decision against a concurrent + // demotion (see the doc above). + let role = sqlx::query!( + r#"SELECT role FROM app_user WHERE id = $1 FOR NO KEY UPDATE"#, + user, + ) + .fetch_optional(&mut *tx) + .await?; + if role.map(|row| row.role).as_deref() != Some(Role::Student.as_str()) { + return Ok(Verdict::Unfit); + } + // The seat and the row in one statement (the cap recipe): a refused + // insert takes its own seat bump back; zero rows means the roster is + // full or the course is gone — only the caller pays for the read + // that tells those apart. + let row = sqlx::query_as!( + Enrollment, + r#"WITH seat AS ( + UPDATE course + SET enrollment_count = enrollment_count + 1 + WHERE id = $1 + AND enrollment_count < COALESCE(capacity, $2) + RETURNING 1) + INSERT INTO enrollment (course, app_user, enrolled_by, source) + SELECT $1, $3, $4, NULL WHERE EXISTS (SELECT 1 FROM seat) + RETURNING course, app_user AS "user", enrolled_by, source"#, + course, + cap::UNLIMITED, + user, + enrolled_by, + ) + .fetch_optional(&mut *tx) + .await?; + match row { + Some(row) => Ok(Verdict::Made(row)), + None => Ok(Verdict::Full), + } + }) + .await; + // The 23505 backstop folds into the Held verdict before the mapping: + // someone placed this pair between the gate and the insert, and their + // row is the answer — no seat was spent finding that out. + let verdict = match verdict { + Err(AppError::Db(err)) if unique_violation(&err) == Some(PAIR_CONSTRAINT) => { + Ok(Verdict::Held) + } + other => other, }; - // CREATE, not UPSERT, and in the seat's own transaction: a duplicate has - // to be *seen*, or the pair's second writer would keep the seat it - // claimed for a row that already existed and the counter would drift - // above the roster forever. - // - // Parenthesized `??` throughout: `n ?? 0 < cap` parses as - // `n ?? (0 < cap)`, which is truthy for every row and would enroll past - // the capacity. - // - // The seat is claimed on the *course*, so the student's own row is - // claimed beside it ([`cap::role_claim`]): a demotion's sweep runs on a - // snapshot, and a row landing after it would count a seat for someone - // who may not hold one, with nothing left to re-sweep. It rides between - // the duplicate gate and the seat, so "you are already in" still - // outranks it and it outranks a full roster. - let held_by = cap::role_claim( - "usr", - &format!("!= '{}'", Role::Student.as_str()), - UNFIT_MARK, - ); - let hold = held_by.join(";\n "); - let sql = format!( - "BEGIN TRANSACTION; - LET $held = (SELECT VALUE id FROM $id); - IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }}; - {hold}; - LET $seat = (UPDATE $course SET {ENROLLMENT_COUNT_FIELD} = \ - ({ENROLLMENT_COUNT_FIELD} ?? 0) + 1 \ - WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) < (capacity ?? $unlimited) \ - RETURN VALUE id); - IF array::len($seat) = 0 {{ THROW '{FULL_MARK}' }}; - CREATE $id CONTENT $row; - COMMIT TRANSACTION;" - ); - // The process still sends its counter writes one at a time (see - // [`cap::counter_lock`]); this statement moves the same counter every - // cap claim does. - let _guard = cap::counter_lock().await; - let (mut result, mut errors) = transaction_with_retry( - db, - &sql, - &[ - ("id".into(), enrollment.id.record().into_value()), - ("row".into(), enrollment.clone().into_value()), - ("course".into(), course.record().into_value()), - ("usr".into(), user.record().into_value()), - ("unlimited".into(), cap::UNLIMITED.into_value()), - ], - &[HELD_MARK, FULL_MARK, UNFIT_MARK], - ) - .await?; - // Someone placed this pair first; their row is the answer, and no seat - // was spent finding that out. It is read first: it outranks the refusal - // below, and the gate aborts before the seat is touched. - if errors - .values() - .any(|error| error.to_string().contains(HELD_MARK)) - { - return match read_for_user(db, course, user).await? { + match verdict { + Ok(Verdict::Made(row)) => Ok(row), + Ok(Verdict::Held) => match read_for_user(db, course, user).await? { Some(existing) => disown_if_pumped(db, existing).await, None => Err(AppError::Internal("failed to enroll user".into())), - }; - } - // Demoted while this ran: the same refusal the service's own gate makes - // a moment earlier, and the only one that can arrive after it. - if errors - .values() - .any(|error| error.to_string().contains(UNFIT_MARK)) - { - return Err(AppError::Validation(ValidationError::Invalid { + }, + // Demoted while this ran: the same refusal the service's own gate + // makes a moment earlier, and the only one that can arrive after it. + Ok(Verdict::Unfit) => Err(AppError::Validation(ValidationError::Invalid { field: "user_id", reason: "only students can be enrolled in a course", - })); - } - // Full, or the course is gone — the conditional write matches nothing - // either way, and only this path pays for the read that tells them - // apart. - if errors - .values() - .any(|error| error.to_string().contains(FULL_MARK)) - { - return match crate::db::course::read(db, course).await? { + })), + // Full, or the course is gone — the conditional write matches + // nothing either way, and only this path pays for the read that + // tells them apart. + Ok(Verdict::Full) => match crate::db::course::read(db, course).await? { Some(_) => Err(AppError::Conflict("the course is full")), None => Err(AppError::NotFound), - }; - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); + }, + Err(err) => Err(err), } - // Slots count BEGIN, two LETs and two IFs, plus the holder claim's own - // statements — counted, not tallied by hand, so a statement added there - // cannot read back the wrong result. - result - .take::>(5 + held_by.len())? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to enroll user".into())) } /// A hand enroll landing on a row a class pumped takes the row *off* the @@ -167,28 +150,30 @@ pub async fn enroll( /// holds in the other direction — a manual unenroll wins, permanently — and /// without it "hand-placed" was a state only a first enroll could reach. /// -/// `UNSET`, not `= NONE`: absence *is* the meaning of this column (see the -/// struct doc), and it is what a hand enroll writes on the create path. +/// `NULL`, not absence: the column is a nullable uuid whose NULL *is* the +/// meaning a missing key used to carry (see the struct doc), and it is what +/// a hand enroll writes on the create path too. async fn disown_if_pumped(db: &Database, existing: Enrollment) -> Result { - if existing.source.is_none() { + if existing.get_source().is_none() { return Ok(existing); } - let mut result = db - .query("UPDATE $id UNSET source RETURN AFTER") - .bind(("id", existing.id.record())) - .await? - .check()?; + let disowned = sqlx::query_as!( + Enrollment, + r#"UPDATE enrollment SET source = NULL + WHERE course = $1 AND app_user = $2 + RETURNING course, app_user AS "user", enrolled_by, source"#, + existing.get_course(), + existing.get_user(), + ) + .fetch_optional(db) + .await?; // A row that is no longer there is not an internal error: an unenroll // (or the class sweep a role change runs) landing between the read // above and this write matches nothing, and the caller asked to be // enrolled — which they were, by the row this call was handed. The // disown is all that is lost, and it is lost to a delete that took the // whole row with it. - Ok(result - .take::>(0)? - .into_iter() - .next() - .unwrap_or(existing)) + Ok(disowned.unwrap_or(existing)) } /// Some(_) iff `user` is enrolled in `course` — the grading gate. @@ -197,13 +182,16 @@ pub async fn read_for_user( course: &CourseId, user: &UserId, ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM enrollment WHERE course = $course AND user = $usr LIMIT 1") - .bind(("course", course.record())) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + let row = sqlx::query_as!( + Enrollment, + r#"SELECT course, app_user AS "user", enrolled_by, source + FROM enrollment WHERE course = $1 AND app_user = $2"#, + course, + user, + ) + .fetch_optional(db) + .await?; + Ok(row) } pub async fn list_for_course( @@ -212,32 +200,44 @@ pub async fn list_for_course( limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new("enrollment WHERE course = $course", "ORDER BY id DESC") - .bind("course", course.record()) - .run(limit, offset, db) - .await + // The old composite key `{course}_{user}` sorted by user within a + // course — its course prefix was constant — so the natural-PK columns + // sort the same way. + PagedList::new( + "enrollment WHERE course = $1", + "ORDER BY course DESC, app_user DESC", + ) + .bind(course.uuid()) + .run::(limit, offset, db) + .await } +/// Take the row and give its seat back in one statement, so nothing but a +/// lost transaction can drift the counter. `None` when the pair held no row. pub async fn remove( db: &Database, course: &CourseId, user: &UserId, ) -> Result, AppError> { - // The seat comes back in the same transaction as the row that held it, - // so nothing but a lost transaction can drift the counter. - let mut result = db - .query( - "BEGIN TRANSACTION; - LET $gone = (DELETE enrollment WHERE course = $course AND user = $usr RETURN BEFORE); - UPDATE $course SET enrollment_count = math::max([(enrollment_count ?? 0) - array::len($gone), 0]); - RETURN $gone; - COMMIT TRANSACTION;", - ) - .bind(("course", course.record())) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(3)?.into_iter().next()) + let gone = sqlx::query_as!( + Enrollment, + r#"WITH gone AS ( + DELETE FROM enrollment + WHERE course = $1 AND app_user = $2 + RETURNING course, app_user, enrolled_by, source), + seated AS ( + UPDATE course + SET enrollment_count = GREATEST( + enrollment_count - (SELECT count(*) FROM gone), 0) + WHERE id = $1 + RETURNING 1) + SELECT course, app_user AS "user", enrolled_by, source FROM gone"#, + course, + user, + ) + .fetch_optional(db) + .await?; + Ok(gone) } #[cfg(test)] diff --git a/src/db/session_attendance.rs b/src/db/session_attendance.rs index 4da8609..c18781a 100644 --- a/src/db/session_attendance.rs +++ b/src/db/session_attendance.rs @@ -4,60 +4,30 @@ //! management's, only students attend, enrollment) are //! [`crate::service::session_attendance`]'s to judge before calling here. -use surrealdb::types::SurrealValue; - -use crate::constant::{ - LESSON_COUNTED_AT_FIELD, LESSONS_ATTENDED_TOTAL_FIELD, LESSONS_HELD_TOTAL_FIELD, -}; -use crate::database::{Database, transaction_with_retry}; +use crate::database::{Database, tx_with_retry}; use crate::db::page::PagedList; use crate::domain::attendance::AttendanceStatus; use crate::domain::course_session::{CourseSession, CourseSessionId}; -use crate::domain::session_attendance::{ - SessionAttendance, SessionAttendanceId, counts_as_attended, -}; +use crate::domain::session_attendance::SessionAttendance; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; -/// Record (or overwrite) `user`'s status for the session. One row per -/// (session, user), keyed by a deterministic composite id so this is a -/// single atomic UPSERT — concurrent marks converge on the one row. -/// -/// The "session still exists" gate rides in the same transaction as the -/// mark, the mirror of the cascade in [`crate::db::course_session::delete`]: the -/// caller's pre-flight read sits four round trips in front of this write, -/// so a delete landing in that gap used to leave a roll-call row on a -/// session that was gone — and that row was *unremovable*, its only delete -/// route 404ing on the vanished session while the attendance report went -/// on counting it. A deleted session reads NONE, which is falsy, so the -/// gate is written as an explicit `IS NONE` (see -/// [`crate::domain::exam_result::ExamResult::grade`]). It reads the -/// session's `teacher` — required on every row, so NONE means "no row" just -/// as `id` did — because the counter below needs that teacher anyway, and -/// one read serves both. -/// -/// A read is not a claim, though: SurrealDB 3.2.3 conflict-checks write -/// sets, not read sets, so that gate alone only closes the *sequential* -/// order (delete committed, then the mark arrives). To make the two really -/// collide, this transaction also *writes* the session row, unconditionally -/// — the bump-and-restore of [`crate::domain::exam_answer::ExamAnswer::save`] -/// on the one column this write already owns, [`LESSON_COUNTED_AT_FIELD`]. -/// Unconditional is the whole point: the credit branch below writes that -/// column already, but it fires only for the first roll call of a lesson -/// that has begun, so a future-dated sheet and every re-mark of a counted -/// one touched nothing at all and committed happily beside -/// `DELETE /sessions/{id}`. Re-stating the value verbatim would not do -/// either — an `UPDATE` that leaves the document unchanged is elided and -/// never enters the write set — hence bump first, then either stamp -/// (credit branch) or put back exactly what was found, `NONE` included, so -/// the row is byte-identical and the once-per-lesson rule is untouched. +/// Record (or overwrite) `user`'s status for the session. The table's +/// primary key *is* the (session, user) pair, so the mark is a single +/// atomic upsert — concurrent marks converge on the one row. /// -/// Sound to re-send while the store answers "conflict, retry": the gate -/// reads the record a delete writes, so the two contend by design, and the -/// UPSERT cannot legitimately answer "already exists" — its composite id is -/// bijective with the `session_attendance_session_user` unique tuple, so -/// the index entry can only point at the row the id already names. +/// The "session still exists" gate is a row lock: the transaction takes the +/// session row `FOR NO KEY UPDATE` before anything else, so a session (or +/// course) delete cascading beneath this mark simply waits, and a delete +/// that got there first leaves this gate matching nothing — `404`, the +/// mirror of [`crate::db::course_session::delete`]. The caller's +/// pre-flight read sits several round trips in front of this write, which +/// is exactly the gap the old code had to fake with a bump-and-restore +/// write on the session row; the lock is the same serialization without +/// the trick. It also freezes `starts_at` and `held_counted_at` for the +/// transaction, so two simultaneous first marks take turns and the +/// lesson-held credit below is stamped exactly once. /// /// Two badge counters move in this same transaction, both of them read /// from the store rather than taken on the caller's word: @@ -65,27 +35,27 @@ use crate::error::AppError; /// - `lessons_attended_total`, on the person marked, as a *delta* rather /// than an increment, because this is an upsert: a re-mark that changes /// nothing must change nothing, and a teacher's correction must move it -/// back down. `$was` is read before the upsert overwrites it (`NONE` when -/// the pair has no row yet), so it writes only on a real crossing of the -/// attended line, and only for a **student** — attending lessons is a -/// student's badge, the same student-only rule enrolling and sitting an -/// exam already carry, so a teacher marked present in their own lesson -/// moves it in neither direction. The live `role` decides that, not the -/// role someone held when the row was written. +/// back down. The pair's stored status is read before the upsert +/// overwrites it (`None` when the pair has no row yet), so it writes +/// only on a real crossing of the attended line, and only for a +/// **student** — attending lessons is a student's badge, the same +/// student-only rule enrolling and sitting an exam already carry, so a +/// teacher marked present in their own lesson moves it in neither +/// direction. The live `role` decides that, not the role someone held +/// when the row was written. /// - `lessons_held_total`, on the *session's* teacher, exactly once per -/// session: the first roll call taken stamps -/// [`LESSON_COUNTED_AT_FIELD`] on the lesson and every later mark sees -/// the stamp and credits nothing. It counts lessons that actually -/// happened — scheduling one and cancelling it earns nothing, which is -/// why the credit does not live in `crate::db::course_session::create`. Two -/// simultaneous first marks both write the lesson row, so the store's own -/// conflict detection (and `transaction_with_retry` behind it) is what -/// keeps the stamp from being set twice. +/// session: the first roll call taken stamps `held_counted_at` on the +/// lesson and every later mark sees the stamp and credits nothing. It +/// counts lessons that actually happened — scheduling one and +/// cancelling it earns nothing, which is why the credit does not live +/// in `crate::db::course_session::create`. Two simultaneous first +/// marks serialize on the session row's lock, so the stamp cannot be +/// set twice. /// /// "Actually happened" is a clock reading, not a request count: the /// credit waits for the lesson's own `starts_at` to arrive. Roll call is -/// deliberately *not* time-gated — a teacher may open the sheet early and -/// is never refused — so without this a teacher could schedule two +/// deliberately *not* time-gated — a teacher may open the sheet early +/// and is never refused — so without this a teacher could schedule two /// hundred lessons for next week, mark one student in each, and hold two /// hundred lessons this afternoon. Because the stamp is written only on /// the branch that credits, a sheet opened early and touched again after @@ -100,9 +70,6 @@ use crate::error::AppError; /// credited — a student's real lessons eaten by someone else's farm. It /// is also nobody's self-service: only a teacher can mark a student, so /// the counter cannot be moved by the person it decorates. -/// -/// Both are floored/guarded rather than trusting the column to exist: a row -/// written before these columns carries none of them. // // corner-cut: that asymmetry leaves a teacher able to inflate a *student's* // attendance with future-dated lessons. Closing it needs the credit stamped @@ -117,76 +84,94 @@ pub async fn mark( status: AttendanceStatus, marked_by: &UserId, ) -> Result { - let attended = counts_as_attended(&status); + let attended = crate::domain::session_attendance::counts_as_attended(&status); let delta: i64 = if attended { 1 } else { -1 }; - let attendance = SessionAttendance { - id: SessionAttendanceId::composite(session.get_id(), user), - session: session.get_id().clone(), - course: session.get_course().clone(), - user: user.clone(), - status, - marked_by: marked_by.clone(), - }; - let (mut written, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $teacher = (SELECT VALUE teacher FROM ONLY $sess); - IF $teacher IS NONE {{ THROW 'session_missing' }}; - LET $counted = (SELECT VALUE {LESSON_COUNTED_AT_FIELD} FROM ONLY $sess); - LET $begun = ((SELECT VALUE starts_at FROM ONLY $sess) <= $stamp); - LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student'); - LET $was = ((SELECT VALUE status FROM ONLY $id) IN ['present', 'late']); - LET $after = (UPSERT $id CONTENT $row RETURN AFTER); - IF $student AND $was != $now {{ - UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} = - math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) + $delta, 0]) - }}; - UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = ({LESSON_COUNTED_AT_FIELD} ?? 0) + 1; - IF ($counted IS NONE) AND $begun {{ - UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $stamp; - UPDATE $teacher SET {LESSONS_HELD_TOTAL_FIELD} = - ({LESSONS_HELD_TOTAL_FIELD} ?? 0) + 1 - }} ELSE {{ - UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $counted - }}; - RETURN $after; - COMMIT TRANSACTION;" - ), - &[ - // `$session` is SurrealDB's own protected variable (the auth - // session): binding that name errors the whole query. - ("sess".into(), session.get_id().record().into_value()), - ("id".into(), attendance.id.record().into_value()), - ("usr".into(), user.record().into_value()), - ("now".into(), attended.into_value()), - ("delta".into(), delta.into_value()), - ("stamp".into(), Timestamp::now().into_value()), - ("row".into(), attendance.into_value()), - ], - &["session_missing"], - ) - .await?; - // An aborted transaction errors every slot and only the THROW's own - // slot names the marker, so a refusal is read by marker while a lost - // round was already re-sent — never reported as a 500. - if errors - .values() - .any(|error| error.to_string().contains("session_missing")) - { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is always the last statement before `COMMIT`, - // so its slot follows the statement count instead of a hand-kept one. - let slot = written.num_statements().saturating_sub(2); - written - .take::>(slot)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to mark session attendance".into())) + let now = Timestamp::now(); + tx_with_retry(db, false, async |tx| { + // The gate and the serialization point: a live session row, locked + // against the delete cascade and every rival mark. + let sess = sqlx::query!( + r#"SELECT teacher, starts_at, held_counted_at + FROM course_session WHERE id = $1 FOR NO KEY UPDATE"#, + session.id, + ) + .fetch_optional(&mut *tx) + .await?; + let Some(sess) = sess else { + return Err(AppError::NotFound); + }; + // The pair's stored status — the pre-image the attended delta is + // computed off. + let was = sqlx::query!( + r#"SELECT status FROM session_attendance + WHERE session = $1 AND app_user = $2"#, + session.id, + user, + ) + .fetch_optional(&mut *tx) + .await? + .map(|row| row.status); + // The live role of the person marked (a gone user row marks as + // non-student — no badge to move; the service gate has already + // refused a vanished target before this write ran). + let is_student = sqlx::query!( + r#"SELECT role = 'student' AS "is_student" FROM app_user WHERE id = $1"#, + user, + ) + .fetch_optional(&mut *tx) + .await? + .map(|row| row.is_student) + .unwrap_or(false); + let row = sqlx::query_as!( + SessionAttendance, + r#"INSERT INTO session_attendance (session, app_user, course, status, marked_by) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (session, app_user) DO UPDATE + SET status = EXCLUDED.status, marked_by = EXCLUDED.marked_by + RETURNING session, app_user AS "user", course, status, marked_by"#, + session.id, + user, + session.course, + status, + marked_by, + ) + .fetch_one(&mut *tx) + .await?; + // The attended badge: student-only, and only on a real crossing. + let was_attended = was + .as_deref() + .is_some_and(|was| was == "present" || was == "late"); + if is_student && was_attended != attended { + sqlx::query!( + r#"UPDATE app_user + SET lessons_attended_total = GREATEST(lessons_attended_total + $2, 0) + WHERE id = $1"#, + user, + delta, + ) + .execute(&mut *tx) + .await?; + } + // The held badge: once per lesson, and only once the lesson began. + if sess.held_counted_at.is_none() && sess.starts_at <= now.as_millis() { + sqlx::query!( + r#"UPDATE course_session SET held_counted_at = $2 WHERE id = $1"#, + session.id, + now.as_millis(), + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + r#"UPDATE app_user SET lessons_held_total = lessons_held_total + 1 + WHERE id = $1"#, + sess.teacher, + ) + .execute(&mut *tx) + .await?; + } + Ok(row) + }) + .await } pub async fn list_for_session( @@ -195,10 +180,16 @@ pub async fn list_for_session( limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new("session_attendance WHERE session = $s", "ORDER BY id DESC") - .bind("s", session.record()) - .run(limit, offset, db) - .await + // The old composite key `{session}_{user}` sorted by user within a + // session — its session prefix was constant — so the natural-PK + // columns sort the same way. + PagedList::new( + "session_attendance WHERE session = $1", + "ORDER BY session DESC, app_user DESC", + ) + .bind(session.uuid()) + .run::(limit, offset, db) + .await } /// Every roll-call row ever recorded for `user` — the session half of the @@ -209,12 +200,16 @@ pub async fn list_for_user( db: &Database, user: &UserId, ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM session_attendance WHERE user = $usr ORDER BY id DESC") - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + let rows = sqlx::query_as!( + SessionAttendance, + r#"SELECT session, app_user AS "user", course, status, marked_by + FROM session_attendance WHERE app_user = $1 + ORDER BY session DESC, app_user DESC"#, + user, + ) + .fetch_all(db) + .await?; + Ok(rows) } /// Clearing a row the student was counted for gives the count back, in the @@ -229,50 +224,60 @@ pub async fn list_for_user( /// /// Student-only on the same terms as the mark, and read from the store for /// the same reason. -/// -/// Sound to re-send: neither statement can answer "already exists". -// -// corner-cut: both ends read the *live* role, so a student promoted between -// being marked present and having that row corrected leaves the counter one -// high (the credit landed as a student, the refund is refused as staff). -// Upgrade path is stamping the credit on the roll-call row itself and -// refunding off that stamp, the way `counted_on_time` works for homework — -// not worth a column until a promotion mid-term is a real complaint. pub async fn remove( db: &Database, session: &CourseSessionId, user: &UserId, ) -> Result, AppError> { - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student'); - LET $gone = (DELETE session_attendance - WHERE session = $s AND user = $usr RETURN BEFORE); - IF $student AND array::len($gone) > 0 AND $gone[0].status IN ['present', 'late'] {{ - UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} = - math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) - 1, 0]) - }}; - RETURN $gone; - COMMIT TRANSACTION;" - ), - &[ - ("s".into(), session.record().into_value()), - ("usr".into(), user.record().into_value()), - ], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is always the last statement before `COMMIT`. - let slot = result.num_statements().saturating_sub(2); - Ok(result - .take::>(slot)? - .into_iter() - .next()) + tx_with_retry(db, false, async |tx| { + // The pre-image and the row's right to exist in one locked + // statement: the row cannot vanish (or change status) under this + // transaction, and `None` here is simply "nothing to remove". + let Some(gone) = sqlx::query_as!( + SessionAttendance, + r#"SELECT session, app_user AS "user", course, status, marked_by + FROM session_attendance + WHERE session = $1 AND app_user = $2 + FOR UPDATE"#, + session, + user, + ) + .fetch_optional(&mut *tx) + .await? + else { + return Ok(None); + }; + if crate::domain::session_attendance::counts_as_attended(&gone.status) { + // Student-only, live role: the same rule the mark pays. + let student = sqlx::query!( + r#"SELECT role = 'student' AS "is_student" FROM app_user WHERE id = $1"#, + user, + ) + .fetch_optional(&mut *tx) + .await? + .map(|row| row.is_student) + .unwrap_or(false); + if student { + sqlx::query!( + r#"UPDATE app_user + SET lessons_attended_total = GREATEST(lessons_attended_total - 1, 0) + WHERE id = $1"#, + user, + ) + .execute(&mut *tx) + .await?; + } + } + sqlx::query!( + r#"DELETE FROM session_attendance WHERE session = $1 AND app_user = $2"#, + session, + user, + ) + .execute(&mut *tx) + .await?; + Ok(Some(gone)) + }) + .await } #[cfg(test)] @@ -345,7 +350,10 @@ mod tests { } async fn held(user: &UserId, db: &Database) -> i64 { - crate::db::badge::load(db, user).await.unwrap().get_lessons_held() + crate::db::badge::load(db, user) + .await + .unwrap() + .get_lessons_held() } /// The whole transition table in one pass: an upsert may only move the diff --git a/src/db/subject.rs b/src/db/subject.rs index 69a7ada..de97b83 100644 --- a/src/db/subject.rs +++ b/src/db/subject.rs @@ -11,7 +11,6 @@ use crate::domain::course::CourseId; use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName}; use crate::error::AppError; - pub async fn create( db: &Database, course: &CourseId, diff --git a/src/domain/course.rs b/src/domain/course.rs index eef1e83..01d96e2 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -20,7 +20,7 @@ impl CourseId { /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that /// cannot take the newtype. Static `query!` binds take `self` directly. - pub fn uuid(&self) -> Uuid { + pub fn uuid(&self) -> uuid::Uuid { self.0 } @@ -33,8 +33,11 @@ impl CourseId { pub fn key(&self) -> String { self.0.to_string() } - } +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct CourseTitle(String); + impl CourseTitle { pub fn try_new(value: &str) -> Result { validate_required("title", value, MAX_COURSE_TITLE_LEN)?; diff --git a/src/domain/course_session.rs b/src/domain/course_session.rs index 7e8a2dd..159ec01 100644 --- a/src/domain/course_session.rs +++ b/src/domain/course_session.rs @@ -1,4 +1,4 @@ -use crate::constant::{MAX_SESSION_TOPIC_LEN}; +use crate::constant::MAX_SESSION_TOPIC_LEN; use crate::domain::course::CourseId; use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; @@ -21,7 +21,7 @@ impl CourseSessionId { /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that /// cannot take the newtype. Static `query!` binds take `self` directly. - pub fn uuid(&self) -> Uuid { + pub fn uuid(&self) -> uuid::Uuid { self.0 } @@ -34,8 +34,11 @@ impl CourseSessionId { pub fn key(&self) -> String { self.0.to_string() } - } +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct SessionTopic(String); + impl SessionTopic { pub fn try_new(value: &str) -> Result { validate_optional("topic", value, MAX_SESSION_TOPIC_LEN)?; diff --git a/src/domain/subject.rs b/src/domain/subject.rs index 00718b2..37e92c4 100644 --- a/src/domain/subject.rs +++ b/src/domain/subject.rs @@ -40,8 +40,11 @@ impl SubjectId { pub fn key(&self) -> String { self.0.to_string() } - } +#[derive(Debug, Clone, PartialEq, Eq, Type)] +#[sqlx(transparent)] +pub struct SubjectName(String); + impl SubjectName { pub fn try_new(value: &str) -> Result { validate_required("name", value, MAX_SUBJECT_NAME_LEN)?; @@ -109,9 +112,7 @@ mod tests { /// burst comes out shuffled. #[tokio::test] async fn ids_sort_in_creation_order() { - let ids: Vec = (0..500) - .map(|_| SubjectId::generate().key()) - .collect(); + let ids: Vec = (0..500).map(|_| SubjectId::generate().key()).collect(); let mut sorted = ids.clone(); sorted.sort(); assert_eq!(ids, sorted); diff --git a/src/domain/term.rs b/src/domain/term.rs index cb09148..2657b26 100644 --- a/src/domain/term.rs +++ b/src/domain/term.rs @@ -40,7 +40,6 @@ impl TermId { pub fn key(&self) -> String { self.0.to_string() } - } pub fn gone_error() -> AppError { AppError::Validation(ValidationError::Invalid { diff --git a/src/service/course.rs b/src/service/course.rs index 0b1d42b..cdbdb12 100644 --- a/src/service/course.rs +++ b/src/service/course.rs @@ -1,7 +1,7 @@ //! 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 +//! image/homework/note-file blob keys before the guarded cascade sweeps +//! those rows. The queries live in //! [`crate::db::course`]. use crate::database::Database; @@ -135,24 +135,13 @@ pub struct DeleteOutcome { /// Delete the course: collect the image/homework/note-file blob keys, then /// run the cascading delete. /// -/// Writer lease of [`crate::service::exam_attempt::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. -/// -/// 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::db::homework_result::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 old writer leases on the exam-attempt and homework state are gone +/// with the store that needed them: this cascade is one guarded +/// transaction whose retry answers a child write that raced it mid-sweep +/// (`is_retryable_cascade` — a foreign key naming a row the racing write +/// just landed), so an attempt started or a grade written beside the sweep +/// is either swept by the re-sent cascade or refused by the very foreign +/// key it would have orphaned. No lock can out-guard that. /// /// 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 @@ -160,8 +149,6 @@ pub struct DeleteOutcome { /// blob. pub async fn delete(db: &Database, course: &Course) -> Result { require_open(db, course).await?; - let _guard = crate::service::exam_attempt::EXAM_LOCK.write().await; - let _homework_guard = crate::service::homework::HOMEWORK_LOCK.write().await; let image_files = crate::db::question_image::file_keys_for_course(db, course.get_id()).await?; let answer_image_files = crate::db::answer_image::file_keys_for_course(db, course.get_id()).await?; diff --git a/src/web/courses.rs b/src/web/courses.rs index 147a78e..e3a7375 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -545,8 +545,8 @@ async fn delete_course( "only the course creator or a manager/admin can delete this course", )); } - // The workflow — archived-term gate, EXAM_LOCK and HOMEWORK_LOCK writer - // leases, blob-key collection, cascade — is [`service::course::delete`]'s. + // The workflow — archived-term gate, 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 {