diff --git a/README.md b/README.md index 91d76a8..d3e5c89 100644 --- a/README.md +++ b/README.md @@ -2768,6 +2768,13 @@ src/ names the class that pumped it, absent when hand-placed) class_group.rs ClassGroupId · ClassName · ClassGrade · ClassGroup (a şube; deletable only with no members and no attached courses) + class_member.rs ClassMember (one student in a class; adding them enrolls + them into every course the class holds) + class_course.rs ClassCourse (one course on a class; attaching it enrolls + the class's whole roster) + class_pump.rs attach/detach (the shared transaction behind both of those: + link row, class counter and the enrollments it implies move + together or not at all) exam.rs ExamId · ExamTitle · ExamDescription · ExamKind · ExamWeight · ExamMode · ExamDuration · ExamSchedule · Exam (belongs to a course) exam_attempt.rs ExamAttemptId · AttemptStatus · ExamAttempt (numbered sittings per exam+user, metered by max_attempts) diff --git a/src/domain/class_course.rs b/src/domain/class_course.rs new file mode 100644 index 0000000..cff2498 --- /dev/null +++ b/src/domain/class_course.rs @@ -0,0 +1,372 @@ +//! A course attached to a class, and the enrollments that attachment implies. +//! +//! The mirror of [`crate::domain::class_member`] along the pump's other axis: +//! attaching a course enrolls the class's whole roster into it, detaching it +//! sweeps the rows that attach wrote. + +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; + +use crate::constant::CLASS_COURSE_TABLE; +use crate::database::Database; +use crate::domain::class_group::ClassGroupId; +use crate::domain::class_pump::{Attached, Axis, Sweep, attach, detach, link_id}; +use crate::domain::course::CourseId; +use crate::domain::page::PagedList; +use crate::domain::user::UserId; +use crate::error::AppError; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct ClassCourseId(RecordId); + +impl ClassCourseId { + /// The record one (class, course) pair always maps to. + pub fn composite(class: &ClassGroupId, course: &CourseId) -> Self { + Self(link_id(CLASS_COURSE_TABLE, class, course.key())) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +/// One course a class is attached to. `attached_by` is who attached it. +#[derive(Debug, Clone, SurrealValue)] +pub struct ClassCourse { + id: ClassCourseId, + class: ClassGroupId, + course: CourseId, + attached_by: UserId, +} + +impl ClassCourse { + pub fn get_id(&self) -> &ClassCourseId { + &self.id + } + + pub fn get_class(&self) -> &ClassGroupId { + &self.class + } + + pub fn get_course(&self) -> &CourseId { + &self.course + } + + pub fn get_attached_by(&self) -> &UserId { + &self.attached_by + } + + /// Attach `course` to `class` and enroll the class's whole roster into it, + /// in one transaction. + /// + /// Students already in the course keep the rows they have — no seat + /// charged, `source` untouched — and a roster that does not fit refuses the + /// whole attach rather than filling the course to its cap and stopping. + pub async fn attach( + class: &ClassGroupId, + course: &CourseId, + attached_by: &UserId, + db: &Database, + ) -> Result { + let link = ClassCourse { + id: ClassCourseId::composite(class, course), + class: class.clone(), + course: course.clone(), + attached_by: attached_by.clone(), + }; + match attach( + class, + Axis::Course, + &link.id.record(), + &link, + course.record(), + attached_by.record(), + db, + ) + .await? + { + Attached::Made(saved) => Ok(saved), + Attached::Duplicate => Err(AppError::Conflict("the course is already on this class")), + Attached::Gone => Err(AppError::NotFound), + Attached::Full(full) => Err(AppError::ConflictOwned(format!( + "{full} cannot hold the whole class" + ))), + } + } + + /// Detach `course` from `class` and sweep the enrollments the class pumped + /// into it. A course that was not attached is a [`AppError::NotFound`], + /// raised here rather than left to each caller to re-derive from a boolean. + /// + /// A student another attached class still claims keeps their row, re-tagged + /// to that class (see [`crate::domain::class_pump::detach`]). + pub async fn detach( + class: &ClassGroupId, + course: &CourseId, + db: &Database, + ) -> Result<(), AppError> { + let gone = detach( + "$link", + Axis::Course, + Sweep::Rows, + &[( + "link".into(), + ClassCourseId::composite(class, course) + .record() + .into_value(), + )], + db, + ) + .await?; + (gone > 0).then_some(()).ok_or(AppError::NotFound) + } + + /// The courses a class is attached to, newest first. + pub async fn list_for_class( + class: &ClassGroupId, + limit: Option, + offset: i64, + db: &Database, + ) -> Result<(Vec, i64), AppError> { + PagedList::new( + format!("{CLASS_COURSE_TABLE} WHERE class = $class"), + "ORDER BY id DESC", + ) + .bind("class", class.record()) + .run(limit, offset, db) + .await + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::class_member::ClassMember; + use crate::domain::class_member::tests::{a_class, a_course, counter, rows, source_of}; + use crate::domain::enrollment::Enrollment; + + /// Attaching seeds the course from the roster the class already holds. + #[tokio::test] + async fn an_attach_enrolls_the_whole_roster() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let class = a_class("9-A", &db).await; + let algebra = a_course("algebra", None, &db).await; + let students = [UserId::from_key("a"), UserId::from_key("b")]; + for student in &students { + ClassMember::add(&class, student, &manager, &db) + .await + .unwrap(); + } + + ClassCourse::attach(&class, &algebra, &manager, &db) + .await + .unwrap(); + for student in &students { + assert_eq!( + source_of(&algebra, student, &db).await, + Some(Some(class.clone())) + ); + } + assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 2); + assert_eq!(counter("class_course_count", class.record(), &db).await, 1); + + let again = ClassCourse::attach(&class, &algebra, &manager, &db).await; + assert!( + matches!(again, Err(AppError::Conflict(_))), + "a second attach is a 409: {again:?}" + ); + } + + /// A course with room for only part of the roster takes none of it: zero + /// enrollments, the counter unmoved, and no attachment row. + #[tokio::test] + async fn a_roster_that_does_not_fit_attaches_nothing() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let class = a_class("9-A", &db).await; + let tight = a_course("algebra", Some(2), &db).await; + for student in ["a", "b", "c"] { + ClassMember::add(&class, &UserId::from_key(student), &manager, &db) + .await + .unwrap(); + } + + let refused = ClassCourse::attach(&class, &tight, &manager, &db).await; + assert!( + matches!(refused, Err(AppError::ConflictOwned(ref message)) if message.contains(tight.key())), + "the refusal must name the course: {refused:?}" + ); + assert_eq!( + rows("SELECT VALUE id FROM enrollment", &db).await, + 0, + "the two seats that did fit must be given back with the third" + ); + assert_eq!( + rows("SELECT VALUE id FROM class_course", &db).await, + 0, + "…and no attachment row may survive" + ); + assert_eq!(counter("enrollment_count", tight.record(), &db).await, 0); + assert_eq!(counter("class_course_count", class.record(), &db).await, 0); + } + + /// A hand-placed row is skipped on the way in and left standing on the way + /// out — the class never owned it. + #[tokio::test] + async fn a_hand_placed_row_survives_the_detach() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let class = a_class("9-A", &db).await; + let algebra = a_course("algebra", None, &db).await; + Enrollment::enroll(&algebra, &student, &manager, &db) + .await + .unwrap(); + ClassMember::add(&class, &student, &manager, &db) + .await + .unwrap(); + + ClassCourse::attach(&class, &algebra, &manager, &db) + .await + .unwrap(); + assert_eq!( + source_of(&algebra, &student, &db).await, + Some(None), + "an attach may not adopt a hand-placed row" + ); + assert_eq!( + counter("enrollment_count", algebra.record(), &db).await, + 1, + "…nor charge a seat for it" + ); + + ClassCourse::detach(&class, &algebra, &db).await.unwrap(); + assert_eq!(source_of(&algebra, &student, &db).await, Some(None)); + assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1); + let again = ClassCourse::detach(&class, &algebra, &db).await; + assert!( + matches!(again, Err(AppError::NotFound)), + "a second detach is a 404: {again:?}" + ); + } + + /// Detaching with nobody else claiming the rows deletes them and gives the + /// seats back. + #[tokio::test] + async fn a_detach_sweeps_the_rows_it_pumped() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let class = a_class("9-A", &db).await; + let algebra = a_course("algebra", None, &db).await; + ClassMember::add(&class, &student, &manager, &db) + .await + .unwrap(); + ClassCourse::attach(&class, &algebra, &manager, &db) + .await + .unwrap(); + + ClassCourse::detach(&class, &algebra, &db).await.unwrap(); + assert_eq!(source_of(&algebra, &student, &db).await, None); + assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0); + assert_eq!(counter("class_course_count", class.record(), &db).await, 0); + assert_eq!( + rows("SELECT VALUE id FROM class_member", &db).await, + 1, + "the two axes are independent: dropping the course may not drop \ + the student out of the class as well" + ); + } + + /// Two classes, one course, one student in both: the second attach skipped + /// the row the first wrote, so the row names only the first class — and + /// detaching *that* class must hand the row to the second rather than + /// unenroll a student the second is still responsible for. Detaching the + /// second then finds nobody left and takes the seat back. + #[tokio::test] + async fn a_detach_hands_a_shared_row_to_the_class_that_still_claims_it() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let algebra = a_course("algebra", None, &db).await; + let first = a_class("9-A", &db).await; + let second = a_class("club", &db).await; + for class in [&first, &second] { + ClassMember::add(class, &student, &manager, &db) + .await + .unwrap(); + ClassCourse::attach(class, &algebra, &manager, &db) + .await + .unwrap(); + } + assert_eq!( + source_of(&algebra, &student, &db).await, + Some(Some(first.clone())), + "the second attach must skip the row the first wrote" + ); + assert_eq!( + counter("enrollment_count", algebra.record(), &db).await, + 1, + "…and pay no second seat for it" + ); + + ClassCourse::detach(&first, &algebra, &db).await.unwrap(); + assert_eq!( + source_of(&algebra, &student, &db).await, + Some(Some(second.clone())), + "the row must be handed to the class that still claims it" + ); + assert_eq!( + counter("enrollment_count", algebra.record(), &db).await, + 1, + "a repair is not a release" + ); + + ClassCourse::detach(&second, &algebra, &db).await.unwrap(); + assert_eq!( + source_of(&algebra, &student, &db).await, + None, + "the last claimant leaving takes the row with it" + ); + assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0); + } + + /// The same repair along the member axis: removing the student from the + /// class that owns the row hands it to the other class they are in. + #[tokio::test] + async fn a_member_removal_hands_a_shared_row_over_too() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let algebra = a_course("algebra", None, &db).await; + let first = a_class("9-A", &db).await; + let second = a_class("club", &db).await; + for class in [&first, &second] { + ClassCourse::attach(class, &algebra, &manager, &db) + .await + .unwrap(); + ClassMember::add(class, &student, &manager, &db) + .await + .unwrap(); + } + + ClassMember::remove(&first, &student, &db).await.unwrap(); + assert_eq!( + source_of(&algebra, &student, &db).await, + Some(Some(second.clone())), + "the student is still in the second class, so the row stays" + ); + assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1); + + ClassMember::remove(&second, &student, &db).await.unwrap(); + assert_eq!(source_of(&algebra, &student, &db).await, None); + assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0); + } +} diff --git a/src/domain/class_member.rs b/src/domain/class_member.rs new file mode 100644 index 0000000..eaeff53 --- /dev/null +++ b/src/domain/class_member.rs @@ -0,0 +1,525 @@ +//! A student's place in a class, and the enrollments that place implies. +//! +//! Both writes here are one call into [`crate::domain::class_pump`]: this file +//! only names the axis, the counter and the composite id, because adding a +//! member and attaching a course to the class are the same pump seen from its +//! two ends. + +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; + +use crate::constant::CLASS_MEMBER_TABLE; +use crate::database::Database; +use crate::domain::class_group::ClassGroupId; +use crate::domain::class_pump::{Attached, Axis, Sweep, attach, detach, link_id}; +use crate::domain::page::PagedList; +use crate::domain::user::UserId; +use crate::error::AppError; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct ClassMemberId(RecordId); + +impl ClassMemberId { + /// The record one (class, user) pair always maps to. + pub fn composite(class: &ClassGroupId, user: &UserId) -> Self { + Self(link_id(CLASS_MEMBER_TABLE, class, user.key())) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +/// One student in one class. `added_by` is who put them there. +#[derive(Debug, Clone, SurrealValue)] +pub struct ClassMember { + id: ClassMemberId, + class: ClassGroupId, + user: UserId, + added_by: UserId, +} + +impl ClassMember { + pub fn get_id(&self) -> &ClassMemberId { + &self.id + } + + pub fn get_class(&self) -> &ClassGroupId { + &self.class + } + + pub fn get_user(&self) -> &UserId { + &self.user + } + + pub fn get_added_by(&self) -> &UserId { + &self.added_by + } + + /// Put `user` in `class` and enroll them into every course the class is + /// already attached to, in one transaction. + /// + /// A student already enrolled in one of those courses keeps the row they + /// have — no seat is charged and their `source` is untouched, so a + /// hand-placed enrollment is never adopted by the class — and a course with + /// no free seat refuses the *whole* join rather than half of it. + pub async fn add( + class: &ClassGroupId, + user: &UserId, + added_by: &UserId, + db: &Database, + ) -> Result { + let member = ClassMember { + id: ClassMemberId::composite(class, user), + class: class.clone(), + user: user.clone(), + added_by: added_by.clone(), + }; + match attach( + class, + Axis::Member, + &member.id.record(), + &member, + user.record(), + added_by.record(), + db, + ) + .await? + { + Attached::Made(saved) => Ok(saved), + Attached::Duplicate => Err(AppError::Conflict("the student is already in this class")), + Attached::Gone => Err(AppError::NotFound), + Attached::Full(course) => Err(AppError::ConflictOwned(format!( + "{course} is full, so the class cannot take this student" + ))), + } + } + + /// Take `user` out of `class` and sweep the enrollments the class pumped + /// for them. A student who was not in the class is a + /// [`AppError::NotFound`], raised here rather than left to each caller to + /// re-derive from a boolean. + /// + /// An enrollment another attached class still claims is re-tagged to that + /// class instead of deleted (see [`crate::domain::class_pump::detach`]). + pub async fn remove( + class: &ClassGroupId, + user: &UserId, + db: &Database, + ) -> Result<(), AppError> { + let gone = detach( + "$link", + Axis::Member, + Sweep::Rows, + &[( + "link".into(), + ClassMemberId::composite(class, user).record().into_value(), + )], + db, + ) + .await?; + (gone > 0).then_some(()).ok_or(AppError::NotFound) + } + + /// Drop every class `user` belongs to, giving each class its member count + /// back — and nothing else. The enrollments are + /// [`crate::domain::enrollment::Enrollment::delete_for_user`]'s to delete; + /// this sweeping them too would decrement the same seats twice. + pub async fn delete_for_user(user: &UserId, db: &Database) -> Result<(), AppError> { + detach( + &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"), + Axis::Member, + Sweep::CounterOnly, + &[("usr".into(), user.record().into_value())], + db, + ) + .await?; + Ok(()) + } + + /// The class's roster, newest first. + pub async fn list_for_class( + class: &ClassGroupId, + limit: Option, + offset: i64, + db: &Database, + ) -> Result<(Vec, i64), AppError> { + PagedList::new( + format!("{CLASS_MEMBER_TABLE} WHERE class = $class"), + "ORDER BY id DESC", + ) + .bind("class", class.record()) + .run(limit, offset, db) + .await + } +} + +#[cfg(test)] +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::enrollment::Enrollment; + + pub(crate) async fn a_class(name: &str, db: &Database) -> ClassGroupId { + ClassGroup::create( + &UserId::from_key("manager"), + ClassName::try_new(name).unwrap(), + None, + None, + db, + ) + .await + .unwrap() + .get_id() + .clone() + } + + pub(crate) async fn a_course(title: &str, capacity: Option, db: &Database) -> CourseId { + Course::create( + &UserId::from_key("manager"), + CourseTitle::try_new(title).unwrap(), + CourseDescription::try_new("").unwrap(), + CourseKind::course(), + None, + capacity, + db, + ) + .await + .unwrap() + .get_id() + .clone() + } + + /// A counter, re-read out of the store — never off a return value, which + /// the in-memory engine forges wins on (see [`crate::domain::cap`]). + pub(crate) async fn counter(field: &str, of: RecordId, db: &Database) -> i64 { + let mut result = db + .query(format!("SELECT VALUE {field} ?? 0 FROM $of")) + .bind(("of", of)) + .await + .unwrap() + .check() + .unwrap(); + result + .take::>(0) + .unwrap() + .first() + .copied() + .unwrap() + } + + /// How many rows `sql` selects ids for. + pub(crate) async fn rows(sql: &str, db: &Database) -> usize { + let mut result = db.query(sql).await.unwrap().check().unwrap(); + result.take::>(0).unwrap().len() + } + + /// Whether `id` names a live row. + pub(crate) async fn exists(id: RecordId, db: &Database) -> bool { + let mut result = db + .query("SELECT VALUE id FROM $id") + .bind(("id", id)) + .await + .unwrap() + .check() + .unwrap(); + !result.take::>(0).unwrap().is_empty() + } + + /// The class that wrote an enrollment, or `None` for a hand-placed row. + pub(crate) async fn source_of( + course: &CourseId, + user: &UserId, + db: &Database, + ) -> Option> { + Enrollment::read_for_user(course, user, db) + .await + .unwrap() + .map(|row| row.get_source().cloned()) + } + + #[tokio::test] + async fn a_member_is_enrolled_into_every_attached_course() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let class = a_class("9-A", &db).await; + let algebra = a_course("algebra", None, &db).await; + let physics = a_course("physics", None, &db).await; + ClassCourse::attach(&class, &algebra, &manager, &db) + .await + .unwrap(); + ClassCourse::attach(&class, &physics, &manager, &db) + .await + .unwrap(); + + ClassMember::add(&class, &student, &manager, &db) + .await + .unwrap(); + + for course in [&algebra, &physics] { + assert_eq!( + source_of(course, &student, &db).await, + Some(Some(class.clone())), + "every attached course must hold a row tagged with the class" + ); + assert_eq!(counter("enrollment_count", course.record(), &db).await, 1); + } + assert_eq!(counter("class_member_count", class.record(), &db).await, 1); + } + + /// The pumped row must carry the *same* composite id a hand enroll would + /// mint, or the two paths would key one pair two ways and only the unique + /// index (a 500) would notice. + #[tokio::test] + async fn a_pumped_row_uses_the_hand_enrolls_composite_id() { + use crate::domain::enrollment::EnrollmentId; + + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let class = a_class("9-A", &db).await; + let algebra = a_course("algebra", None, &db).await; + ClassCourse::attach(&class, &algebra, &manager, &db) + .await + .unwrap(); + ClassMember::add(&class, &student, &manager, &db) + .await + .unwrap(); + + assert!( + exists(EnrollmentId::composite(&algebra, &student).record(), &db).await, + "the pump must key the pair the way Enrollment::composite does" + ); + } + + /// Re-adding is a 409, and it must cost nothing: no second counter tick and + /// no second sweep of anybody's enrollment. + #[tokio::test] + async fn a_second_add_is_refused_and_writes_nothing() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let class = a_class("9-A", &db).await; + let algebra = a_course("algebra", None, &db).await; + ClassCourse::attach(&class, &algebra, &manager, &db) + .await + .unwrap(); + ClassMember::add(&class, &student, &manager, &db) + .await + .unwrap(); + + let again = ClassMember::add(&class, &student, &manager, &db).await; + assert!( + matches!(again, Err(AppError::Conflict(_))), + "a second add is a 409: {again:?}" + ); + assert_eq!( + counter("class_member_count", class.record(), &db).await, + 1, + "a refused add may not tick the counter" + ); + assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1); + } + + /// Adding into a class whose courses have no room refuses the *whole* join: + /// the roomy course must not keep a seat the full one denied. + #[tokio::test] + async fn a_full_course_refuses_the_whole_join() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let class = a_class("9-A", &db).await; + let roomy = a_course("algebra", None, &db).await; + let full = a_course("physics", Some(0), &db).await; + ClassCourse::attach(&class, &roomy, &manager, &db) + .await + .unwrap(); + ClassCourse::attach(&class, &full, &manager, &db) + .await + .unwrap(); + + // The whole record id, not just the key: a caller reading the 409 must + // not have to guess which table the name came from. + let named = format!("{}:{}", crate::constant::COURSE_TABLE, full.key()); + let refused = ClassMember::add(&class, &student, &manager, &db).await; + assert!( + matches!(refused, Err(AppError::ConflictOwned(ref message)) if message.contains(&named)), + "the refusal must name the course that had no seat as {named}: {refused:?}" + ); + assert_eq!( + rows("SELECT VALUE id FROM enrollment", &db).await, + 0, + "not one seat may survive the refusal" + ); + assert_eq!( + rows("SELECT VALUE id FROM class_member", &db).await, + 0, + "…nor the membership row itself" + ); + assert_eq!( + counter("enrollment_count", roomy.record(), &db).await, + 0, + "…nor the roomy course's counter" + ); + assert_eq!(counter("class_member_count", class.record(), &db).await, 0); + } + + /// A student already enrolled by hand keeps their own row: no seat is + /// charged for them, the row's `source` stays empty, and removing them from + /// the class leaves it standing. + #[tokio::test] + async fn a_hand_placed_enrollment_is_skipped_and_survives_removal() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let class = a_class("9-A", &db).await; + let algebra = a_course("algebra", None, &db).await; + Enrollment::enroll(&algebra, &student, &manager, &db) + .await + .unwrap(); + ClassCourse::attach(&class, &algebra, &manager, &db) + .await + .unwrap(); + + ClassMember::add(&class, &student, &manager, &db) + .await + .unwrap(); + assert_eq!( + source_of(&algebra, &student, &db).await, + Some(None), + "the class must not adopt a hand-placed row" + ); + assert_eq!( + counter("enrollment_count", algebra.record(), &db).await, + 1, + "the skipped pair may not be charged a second seat" + ); + + ClassMember::remove(&class, &student, &db).await.unwrap(); + assert_eq!( + source_of(&algebra, &student, &db).await, + Some(None), + "the sweep may only take back the rows the class wrote" + ); + assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1); + } + + /// Removal with nobody else claiming the row: the enrollment goes and its + /// seat comes back. + #[tokio::test] + async fn removal_deletes_the_rows_the_class_pumped() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let class = a_class("9-A", &db).await; + let algebra = a_course("algebra", None, &db).await; + ClassCourse::attach(&class, &algebra, &manager, &db) + .await + .unwrap(); + ClassMember::add(&class, &student, &manager, &db) + .await + .unwrap(); + + ClassMember::remove(&class, &student, &db).await.unwrap(); + assert_eq!(source_of(&algebra, &student, &db).await, None); + assert_eq!( + counter("enrollment_count", algebra.record(), &db).await, + 0, + "the seat must come back with the row that held it" + ); + assert_eq!(counter("class_member_count", class.record(), &db).await, 0); + let again = ClassMember::remove(&class, &student, &db).await; + assert!( + matches!(again, Err(AppError::NotFound)), + "a second removal is a 404, not a second sweep: {again:?}" + ); + } + + /// A member who is not in any attached course still removes cleanly, and a + /// course deleted out from under the class leaves nothing to sweep — the + /// membership row and the pumped enrollment are independent facts. + #[tokio::test] + async fn a_sweep_tolerates_rows_a_course_delete_already_took() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let class = a_class("9-A", &db).await; + let algebra = a_course("algebra", None, &db).await; + ClassCourse::attach(&class, &algebra, &manager, &db) + .await + .unwrap(); + ClassMember::add(&class, &student, &manager, &db) + .await + .unwrap(); + + // `Course::delete` refuses while the roster is occupied, so the wipe is + // spelled the way the cascade does it, minus the guard. + db.query("DELETE enrollment WHERE course = $course; DELETE class_course WHERE course = $course; DELETE $course;") + .bind(("course", algebra.record())) + .await + .unwrap() + .check() + .unwrap(); + + ClassMember::remove(&class, &student, &db) + .await + .expect("the membership must still be removable with its enrollment gone"); + assert_eq!(counter("class_member_count", class.record(), &db).await, 0); + } + + /// The role-demotion sweep: memberships go and their counters come back, + /// while the enrollment rows are left for `Enrollment::delete_for_user`. + /// Decrementing those seats here as well would take each one back twice. + #[tokio::test] + async fn delete_for_user_leaves_the_enrollments_alone() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let first = a_class("9-A", &db).await; + let second = a_class("club", &db).await; + let algebra = a_course("algebra", None, &db).await; + ClassCourse::attach(&first, &algebra, &manager, &db) + .await + .unwrap(); + ClassMember::add(&first, &student, &manager, &db) + .await + .unwrap(); + ClassMember::add(&second, &student, &manager, &db) + .await + .unwrap(); + + ClassMember::delete_for_user(&student, &db).await.unwrap(); + assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0); + for class in [&first, &second] { + assert_eq!( + counter("class_member_count", class.record(), &db).await, + 0, + "every class must get its member count back" + ); + } + assert_eq!( + source_of(&algebra, &student, &db).await, + Some(Some(first.clone())), + "the enrollment is the other sweep's to delete" + ); + assert_eq!( + counter("enrollment_count", algebra.record(), &db).await, + 1, + "…and its seat is the other sweep's to release" + ); + + // Which is exactly what the demotion calls next, and the seat comes + // back once, not twice. + Enrollment::delete_for_user(&student, &db).await.unwrap(); + assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0); + } +} diff --git a/src/domain/class_pump.rs b/src/domain/class_pump.rs new file mode 100644 index 0000000..1c81ee7 --- /dev/null +++ b/src/domain/class_pump.rs @@ -0,0 +1,434 @@ +//! The pump behind the class layer: one link row changed, and every +//! `enrollment` row that link implies reconciled with it, in one transaction. +//! +//! A class (şube) has two link tables — `class_member` (a student in it) and +//! `class_course` (a course attached to it) — and the *product* of the two is +//! the roster it owes: every member is enrolled in every attached course, in +//! real `enrollment` rows tagged [`source`](crate::domain::enrollment) with the +//! class that wrote them. Adding a member and attaching a course are therefore +//! the same operation seen along its two axes, and so are removing one and +//! detaching the other. That axis is what these two primitives take as a +//! parameter, so the four public operations are each a couple of lines. +//! +//! What is *not* one primitive is attach and detach. They share no statement: +//! one gates on "this pair already holds a row" and claims two counters +//! upwards, the other gates on nothing, releases, and has to decide per +//! enrollment row whether a *rival* class still claims it. Folding them behind +//! a direction flag would be one function containing two, so the seam stays +//! where the SQL puts it. +//! +//! Everything here writes counters the way [`crate::domain::cap`] does — a +//! single-record conditional `UPDATE`, never a count-then-write — and every +//! `??` is parenthesized, because `n ?? 0 < $cap` parses as `n ?? (0 < $cap)` +//! and is truthy for every row. + +use surrealdb::types::{RecordId, SurrealValue, Value}; + +use crate::constant::{ + CLASS_COURSE_COUNT_FIELD, CLASS_COURSE_TABLE, CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE, + ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE, +}; +use crate::database::{Database, transaction_with_retry}; +use crate::domain::cap; +use crate::domain::class_group::ClassGroupId; +use crate::error::AppError; + +/// The `THROW` markers [`attach`] aborts with. `FULL_MARK` is a *prefix*: the +/// record id of the course that had no seat is appended to it, because "the +/// class does not fit" is unanswerable without knowing which course to raise +/// the capacity of, and the loop only learns that at runtime. The whole id and +/// not just the key, so the refusal names something a caller can look up +/// without knowing which table it came from. +const HELD_MARK: &str = "class_held"; +const GONE_MARK: &str = "class_gone"; +const FULL_MARK: &str = "class_full:"; + +/// What [`attach`] settled. +pub(crate) enum Attached { + /// The link row, the counter and every enrollment it implied committed + /// together. + Made(T), + /// The link already exists — nothing was written, and no seat was spent + /// finding that out. + Duplicate, + /// The class row is gone (a concurrent delete won). Nothing was written. + Gone, + /// One of the courses had no free seat, named by its key. Nothing was + /// written — not one of the earlier seats in the same run, which is the + /// whole point of doing this in a transaction. + Full(String), +} + +/// Which way the pump runs: the loop below needs a `(course, user)` pair per +/// enrollment, and each caller supplies one side as a constant and reads the +/// other off the class's *other* link table. +pub(crate) enum Axis { + /// A student joining: the courses come from `class_course`. + Member, + /// A course arriving: the students come from `class_member`. + Course, +} + +impl Axis { + /// The `SELECT` that yields this run's `(course, user)` pairs, with `$pivot` + /// bound to the fixed side. In-crate text, never client input. + fn pairs(&self) -> String { + match self { + Axis::Member => format!( + "SELECT VALUE {{ course: course, user: $pivot }} \ + FROM {CLASS_COURSE_TABLE} WHERE class = $class" + ), + Axis::Course => format!( + "SELECT VALUE {{ course: $pivot, user: user }} \ + FROM {CLASS_MEMBER_TABLE} WHERE class = $class" + ), + } + } + + /// The enrollment rows a *detached* link of this axis is responsible for, + /// as a `WHERE` fragment over `enrollment`. Read off the deleted link row + /// rather than a bound parameter, so one loop serves a single detach and a + /// user's whole membership alike. + fn scope(&self) -> &'static str { + match self { + Axis::Member => "user = $link.user", + Axis::Course => "course = $link.course", + } + } + + /// The class counter this axis's link rows are counted on. Taken off the + /// axis rather than passed in beside it, because the two are one fact and a + /// call site that paired the member axis with the course counter would + /// compile, pass every test — both are `&str` — and desync the class delete + /// guard forever. + fn counter(&self) -> &'static str { + match self { + Axis::Member => CLASS_MEMBER_COUNT_FIELD, + Axis::Course => CLASS_COURSE_COUNT_FIELD, + } + } +} + +/// Whether a [`detach`] also reconciles the enrollment rows its links pumped. +pub(crate) enum Sweep { + /// Repair or delete them, per the rule in [`detach`]. + Rows, + /// Release the counters and touch nothing else, because something else owns + /// the enrollment side of this same event. + CounterOnly, +} + +/// Write `link` and enroll everything it implies, or write nothing at all. +/// +/// The order is the one [`cap::claim_and_create`] settled on and for the same +/// reason: the link is looked for *before* any counter moves, so "you are +/// already in" outranks "there is no room" — a caller whose row a rival placed +/// a moment ago must not be told a course is full about seats they already +/// hold. +/// +/// The class counter is claimed by a conditional write rather than a bare +/// increment, so a class deleted out from under this run matches nothing and +/// the whole cascade aborts: [`Attached::Gone`] instead of a counter on a row +/// that no longer exists. +/// +/// Every enrollment in the loop is *skipped* when the pair already has a row — +/// no seat charged, and the existing row's `source` left exactly as it was, so +/// a hand-placed student is never quietly adopted by a class. Only the pairs +/// that had no row at all are charged, each against its own course's capacity. +/// +/// On admissibility ([`crate::database::transaction_with_retry`]): every +/// `CREATE` here is preceded by its own in-transaction existence check, so an +/// "already exists" can only come from a rival that landed inside that window — +/// and re-sending the whole cascade then *sees* the row and takes the other +/// branch. The retry converges instead of re-asking a settled question, which +/// is the restriction's actual test. +pub(crate) async fn attach( + class: &ClassGroupId, + axis: Axis, + link: &RecordId, + row: &T, + pivot: RecordId, + by: RecordId, + db: &Database, +) -> Result, AppError> { + let count_field = axis.counter(); + let pairs = axis.pairs(); + let sql = format!( + "BEGIN TRANSACTION; + LET $held = (SELECT VALUE id FROM $link); + IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }}; + LET $counted = (UPDATE $class SET {count_field} = ({count_field} ?? 0) + 1 \ + WHERE ({count_field} ?? 0) < $unlimited RETURN VALUE id); + IF array::len($counted) = 0 {{ THROW '{GONE_MARK}' }}; + CREATE $link CONTENT $row; + FOR $pair IN (({pairs}) ?? []) {{ + LET $seat_of = type::record('{ENROLLMENT_TABLE}', string::concat( + record::id($pair.course), '_', record::id($pair.user))); + IF array::len((SELECT VALUE id FROM $seat_of)) = 0 {{ + LET $seat = (UPDATE $pair.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}' + $pair.course + }}; + CREATE $seat_of CONTENT {{ course: $pair.course, user: $pair.user, \ + enrolled_by: $by, source: $class }}; + }}; + }}; + COMMIT TRANSACTION;" + ); + let (mut result, mut errors) = transaction_with_retry( + db, + &sql, + &[ + ("class".into(), class.record().into_value()), + ("link".into(), link.clone().into_value()), + ("row".into(), row.clone().into_value()), + ("pivot".into(), pivot.into_value()), + ("by".into(), by.into_value()), + ("unlimited".into(), cap::UNLIMITED.into_value()), + ], + &[HELD_MARK, GONE_MARK, FULL_MARK], + ) + .await?; + // "Already linked" is read first: it outranks both refusals below, and the + // gate aborts before either could fire. + // + // Only the `THROW` is read, never an `is_already_exists` off the `CREATE` + // itself. A rival landing in the window between the gate and the create + // makes the store answer "already exists", which + // [`transaction_with_retry`] treats as a lost round and re-sends — and that + // re-send is the right answer, because the second pass *sees* the row at + // the gate. Reading it here would also mis-file the enrollment `CREATE`'s + // version of the same answer as "already in this class". + if errors + .values() + .any(|error| error.to_string().contains(HELD_MARK)) + { + return Ok(Attached::Duplicate); + } + if errors + .values() + .any(|error| error.to_string().contains(GONE_MARK)) + { + return Ok(Attached::Gone); + } + if let Some(course) = errors + .values() + .find_map(|error| full_course(&error.to_string())) + { + return Ok(Attached::Full(course)); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Slots count BEGIN, two LETs and two IFs: the CREATE is slot 5. + result + .take::>(5)? + .into_iter() + .next() + .map(Attached::Made) + .ok_or_else(|| AppError::Internal("the class pump wrote no link row".into())) +} + +/// The course id out of a `class_full::` abort. Table names and the +/// generated ULID keys here are alphanumeric and `:` joins them, so the id ends +/// where the store's own wrapping around the thrown text begins. +fn full_course(message: &str) -> Option { + let id: String = message + .split_once(FULL_MARK)? + .1 + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | ':')) + .collect(); + (!id.is_empty()).then_some(id) +} + +/// Drop the link rows `links` names, give each class its counter back, and +/// sweep the enrollment rows those links pumped. Answers how many link rows +/// went, so a caller whose link was a single pair can turn zero into a 404. +/// +/// The sweep is *repair-first*: an enrollment this class wrote is only deleted +/// once no other class still claims it. Two classes attached to the same course +/// share a student — the second attach skipped the row the first had already +/// written, so the row carries only the first class's name — and deleting it on +/// the first class's way out would unenroll a student the second class is still +/// responsible for. So the row is re-tagged to that rival instead, and only a +/// row nobody is left to claim is deleted and its seat given back. The heir is +/// the lowest class id among the claimants: a deterministic pick, so a repeat +/// of the same sweep lands on the same class. +/// +/// Sweeps tolerate rows that are already gone. `Course::delete` wipes a +/// course's enrollments wholesale while the `class_member` rows survive it, so +/// "this class has a member" and "that member has a live pumped row" are +/// independent facts and the loop simply finds nothing to sweep. +/// +/// [`Sweep::CounterOnly`] is the deliberate half of this: dropping a *user's* +/// whole membership releases the counters and nothing else, because +/// `Enrollment::delete_for_user` owns the enrollment side of that same event and +/// a second decrement of the same seat is a bug, not a belt. +/// +/// Admissible by construction: `DELETE` and `UPDATE` only, so no statement in +/// the cascade can answer "already exists" and every lost round is a plain +/// re-send. +pub(crate) async fn detach( + links: &str, + axis: Axis, + sweep: Sweep, + bindings: &[(String, Value)], + db: &Database, +) -> Result { + let count_field = axis.counter(); + let sweep = match sweep { + Sweep::CounterOnly => String::new(), + Sweep::Rows => { + let scope = axis.scope(); + format!( + "FOR $row IN ((SELECT id, course, user FROM {ENROLLMENT_TABLE} \ + WHERE {scope} AND source = $link.class) ?? []) {{ + LET $rivals = (SELECT VALUE class FROM {CLASS_COURSE_TABLE} \ + WHERE course = $row.course AND class != $link.class); + LET $heir = array::first(array::sort((SELECT VALUE class \ + FROM {CLASS_MEMBER_TABLE} WHERE user = $row.user AND class IN $rivals))); + IF $heir != NONE {{ + UPDATE $row.id SET source = $heir; + }} ELSE {{ + DELETE $row.id; + UPDATE $row.course SET {ENROLLMENT_COUNT_FIELD} = \ + math::max([({ENROLLMENT_COUNT_FIELD} ?? 0) - 1, 0]); + }}; + }};" + ) + } + }; + let sql = format!( + "BEGIN TRANSACTION; + LET $gone = (DELETE {links} RETURN BEFORE); + FOR $link IN ($gone ?? []) {{ + UPDATE $link.class SET {count_field} = math::max([({count_field} ?? 0) - 1, 0]); + {sweep} + }}; + RETURN array::len($gone); + COMMIT TRANSACTION;" + ); + let (mut result, mut errors) = transaction_with_retry(db, &sql, bindings, &[]).await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Slots count BEGIN, the LET and the FOR: the RETURN is slot 3. + Ok(result.take::>(3)?.into_iter().next().unwrap_or(0)) +} + +/// A composite id for a `(class, other)` link, the shape +/// [`crate::domain::enrollment::EnrollmentId::composite`] uses: the same pair +/// always maps to the same record, so one row per pair holds by construction +/// and a duplicate is something the store can *see* rather than something a +/// find-then-insert has to race. +pub(crate) fn link_id(table: &str, class: &ClassGroupId, other: &str) -> RecordId { + RecordId::new(table, format!("{}_{}", class.key(), other)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::constant::{CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE}; + use crate::domain::class_group::ClassGroupId; + use crate::domain::class_member::ClassMember; + use crate::domain::class_member::tests::{a_class, counter, rows}; + use crate::domain::user::UserId; + use crate::error::AppError; + + /// The class counter is claimed conditionally, so a class that is not there + /// stops the cascade before anything is written — rather than leaving a + /// counter, a link row and a pumped enrollment hanging off a record that + /// does not exist. + #[tokio::test] + async fn an_attach_onto_a_missing_class_writes_nothing() { + let db = crate::database::init_mem().await.unwrap(); + let ghost = ClassGroupId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"); + + let refused = ClassMember::add( + &ghost, + &UserId::from_key("student"), + &UserId::from_key("manager"), + &db, + ) + .await; + assert!( + matches!(refused, Err(AppError::NotFound)), + "a class that is gone is a 404, not a counter on nothing: {refused:?}" + ); + assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0); + assert_eq!(rows("SELECT VALUE id FROM class_group", &db).await, 0); + } + + /// [`detach`] is written to take *many* link rows at once — that is what + /// makes a user's whole membership one statement — and every one of them + /// releases its own class's counter. Called straight, because the public + /// `delete_for_user` throws the count away. + #[tokio::test] + async fn a_detach_releases_every_class_it_unlinked() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let classes = [ + a_class("9-A", &db).await, + a_class("9-B", &db).await, + a_class("club", &db).await, + ]; + for class in &classes { + ClassMember::add(class, &student, &manager, &db) + .await + .unwrap(); + } + + let gone = detach( + &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"), + Axis::Member, + Sweep::CounterOnly, + &[("usr".into(), student.record().into_value())], + &db, + ) + .await + .unwrap(); + assert_eq!( + gone, 3, + "every link row must be counted, not just the first" + ); + for class in &classes { + assert_eq!( + counter(CLASS_MEMBER_COUNT_FIELD, class.record(), &db).await, + 0, + "each class gets its own counter back" + ); + } + + // And a run that unlinks nothing answers zero, which is what turns a + // single-pair detach into a 404 instead of a silent success. + let again = detach( + &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"), + Axis::Member, + Sweep::CounterOnly, + &[("usr".into(), student.record().into_value())], + &db, + ) + .await + .unwrap(); + assert_eq!(again, 0); + } + + #[test] + fn a_full_abort_names_its_course() { + assert_eq!( + full_course("An error occurred: class_full:course:01J8XZ0K3Q"), + Some("course:01J8XZ0K3Q".to_string()) + ); + assert_eq!( + full_course("class_full:course:algebra'"), + Some("course:algebra".into()) + ); + assert_eq!(full_course("class_held"), None); + assert_eq!(full_course("class_full:"), None); + } +} diff --git a/src/domain/mod.rs b/src/domain/mod.rs index cad8891..e7beaf1 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -13,7 +13,10 @@ pub mod board_stroke; pub mod cap; pub mod chatbot_message; pub mod chatbot_thread; +pub mod class_course; pub mod class_group; +pub mod class_member; +pub mod class_pump; pub mod course; pub mod course_session; pub mod dietary_profile; diff --git a/src/web/users.rs b/src/web/users.rs index 66d35af..6756db5 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -7,6 +7,7 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::database::Database; +use crate::domain::class_member::ClassMember; use crate::domain::course::Course; use crate::domain::enrollment::Enrollment; use crate::domain::parent_link::ParentLink; @@ -398,7 +399,13 @@ async fn set_role( // Parent links get the same sweep on both sides: only students are // observed and only parents observe, so a role change off either end // drops the rows instead of leaving dead grants around. + // The class memberships go first and the enrollments second: the class + // sweep deliberately leaves the enrollment rows alone, so running it after + // would find nothing to repair and running it before costs nothing either + // way. Both are needed — a membership left behind would keep pumping the + // user back into courses and make its class undeletable. if role != Role::Student { + ClassMember::delete_for_user(&target, &st.db).await?; Enrollment::delete_for_user(&target, &st.db).await?; ParentLink::delete_where_student(&target, &st.db).await?; }