From 1e68fc9a5900ff8229d80dd2cae27ab267e94aa4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 11 Sep 2026 09:57:06 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=B9=20chore:=20split=20enrollment=20in?= =?UTF-8?q?to=20domain/db/service=20layers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/db/course.rs | 16 +- src/db/enrollment.rs | 362 ++++++++++++++++++++++++++++++++++++ src/db/mod.rs | 1 + src/domain/class_course.rs | 5 +- src/domain/class_member.rs | 7 +- src/domain/class_pump.rs | 2 +- src/domain/enrollment.rs | 357 +---------------------------------- src/domain/event.rs | 12 +- src/migration_sql.rs | 2 +- src/service/enrollment.rs | 70 +++++++ src/service/exam_attempt.rs | 4 +- src/service/mod.rs | 1 + src/web/boards.rs | 15 +- src/web/courses.rs | 51 ++--- src/web/exams/attempts.rs | 3 +- src/web/exams/mod.rs | 4 +- src/web/homework.rs | 24 ++- src/web/sessions.rs | 4 +- tests/regress_role_sweep.rs | 8 +- 19 files changed, 512 insertions(+), 436 deletions(-) create mode 100644 src/db/enrollment.rs create mode 100644 src/service/enrollment.rs diff --git a/src/db/course.rs b/src/db/course.rs index 4c08f7e..7e02180 100644 --- a/src/db/course.rs +++ b/src/db/course.rs @@ -514,13 +514,11 @@ mod tests { /// included. A `>= 0` guard passes the roster branch and fails here. #[tokio::test] async fn a_course_with_a_roster_refuses_to_delete() { - use crate::domain::enrollment::Enrollment; - let db = crate::database::init_mem().await.unwrap(); let teacher = UserId::from_key("teacher"); let student = UserId::from_key("student"); let course = course_on(None, &db).await; - Enrollment::enroll(course.get_id(), &student, &teacher, &db) + crate::db::enrollment::enroll(&db, course.get_id(), &student, &teacher) .await .unwrap(); @@ -533,14 +531,14 @@ mod tests { "a refused delete may write nothing" ); assert!( - Enrollment::read_for_user(course.get_id(), &student, &db) + crate::db::enrollment::read_for_user(&db, course.get_id(), &student) .await .unwrap() .is_some(), "…the cascade least of all" ); - Enrollment::remove(course.get_id(), &student, &db) + crate::db::enrollment::remove(&db, course.get_id(), &student) .await .unwrap(); assert!(delete(&db, course.clone()).await.unwrap()); @@ -549,7 +547,7 @@ mod tests { // The other half of the same guard: once the course row is gone the // seat claim matches nothing, so a late enroll is a 404 rather than a // roster row that outlived its course. - let late = Enrollment::enroll(course.get_id(), &student, &teacher, &db) + let late = crate::db::enrollment::enroll(&db, course.get_id(), &student, &teacher) .await .expect_err("enrolling into a deleted course must fail"); assert!(matches!(late, AppError::NotFound), "got {late:?}"); @@ -952,7 +950,6 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn a_delete_racing_an_enroll_never_answers_500() { - use crate::domain::enrollment::Enrollment; let (db, _serialized) = crate::database::init_test_server("course_delete_race").await; let (mut delete_500, mut enroll_500, mut enrolled) = (0, 0, 0); let (mut last_delete, mut last_enroll) = (String::new(), String::new()); @@ -978,7 +975,8 @@ mod tests { let (id, db) = (course.get_id().clone(), db.clone()); let student = UserId::from_key(&format!("stu{round}_{seat}")); tokio::spawn(async move { - Enrollment::enroll(&id, &student, &UserId::from_key("mgr"), &db).await + crate::db::enrollment::enroll(&db, &id, &student, &UserId::from_key("mgr")) + .await }) }) .collect(); @@ -996,7 +994,7 @@ mod tests { } // Stored state, not the return values: a seat that landed is what // the guard had to see. - if !Enrollment::list_for_course(course.get_id(), None, 0, &db) + if !crate::db::enrollment::list_for_course(&db, course.get_id(), None, 0) .await .unwrap() .0 diff --git a/src/db/enrollment.rs b/src/db/enrollment.rs new file mode 100644 index 0000000..50acecb --- /dev/null +++ b/src/db/enrollment.rs @@ -0,0 +1,362 @@ +//! 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 +//! 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::db::cap; +use crate::db::page::PagedList; +use crate::domain::course::CourseId; +use crate::domain::enrollment::{Enrollment, EnrollmentId}; +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"; + +/// 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. +/// +/// 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::domain::class_pump::attach`]. +pub async fn enroll( + db: &Database, + course: &CourseId, + user: &UserId, + enrolled_by: &UserId, +) -> Result { + 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, + }; + // 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? { + 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 { + 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? { + 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()); + } + // 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 +/// class: `source` goes, so no later class sweep can unenroll a student an +/// operator placed on purpose. The mirror of the rule the sweep already +/// 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. +async fn disown_if_pumped(db: &Database, existing: Enrollment) -> Result { + if existing.source.is_none() { + return Ok(existing); + } + let mut result = db + .query("UPDATE $id UNSET source RETURN AFTER") + .bind(("id", existing.id.record())) + .await? + .check()?; + // 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)) +} + +/// Some(_) iff `user` is enrolled in `course` — the grading gate. +pub async fn read_for_user( + db: &Database, + 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()) +} + +pub async fn list_for_course( + db: &Database, + course: &CourseId, + 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 +} + +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()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The boot repair of `enrollment_count` **against a real server**, and + /// `#[ignore]`d for it: the pass counts rows off `enrollment`'s indexed + /// `course` field, and an aggregate over an indexed field is exactly where + /// the embedded engine and the server are known to differ (`count()` comes + /// back `{count: N}` from one and a bare int from the other, which + /// `option` would refuse). `array::len` over ids is the spelling that + /// dodges it — this is what proves it on the store that bites. + /// + /// Both halves in one boot: `staff` is the row the sweep deletes (their + /// seat must come back), and `empty` is the course a *past* sweep already + /// stranded — count above zero with no rows left, so it forms no group and + /// only a per-course pass ever visits it. The second `migrate` pins that the + /// repair converges rather than overwriting: it must write nothing. + #[tokio::test] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn the_count_repair_recounts_on_a_real_server() { + let (db, _serialized) = crate::database::init_test_server("enrollment_repair").await; + db.query( + "CREATE user:t SET username = 't', password_hash = 'x', role = 'teacher'; + CREATE user:a SET username = 'a', password_hash = 'x', role = 'student'; + CREATE user:b SET username = 'b', password_hash = 'x', role = 'student'; + CREATE course:live SET creator = user:t, title = 'l', description = '', + enrollment_count = 9; + CREATE course:empty SET creator = user:t, title = 'e', description = '', + enrollment_count = 4; + CREATE enrollment:live_a SET course = course:live, user = user:a, enrolled_by = user:t; + CREATE enrollment:live_b SET course = course:live, user = user:b, enrolled_by = user:t; + CREATE enrollment:live_t SET course = course:live, user = user:t, enrolled_by = user:t;", + ) + .await + .unwrap() + .check() + .unwrap(); + + async fn counts(db: &Database) -> Vec { + let mut result = db + .query("SELECT VALUE enrollment_count FROM course ORDER BY id") + .await + .unwrap() + .check() + .unwrap(); + result.take::>(0).unwrap() + } + + crate::database::migrate(db.as_ref()).await.unwrap(); + // `course:empty` sorts before `course:live`: stranded count cleared, and + // the live course recounted to its two students — the teacher's row was + // swept and handed its seat back in the same boot. + assert_eq!(counts(&db).await, vec![0, 2]); + + crate::database::migrate(db.as_ref()).await.unwrap(); + assert_eq!(counts(&db).await, vec![0, 2], "the repair converges"); + } + + /// A pumped row that vanishes under the disown — a concurrent unenroll, or + /// the sweep a role change runs — must answer the row the caller was + /// handed, not a 500. The `UPDATE` matches nothing and used to fall through + /// to `AppError::Internal`, turning a race the old code answered 200 into a + /// server error on an ordinary `POST /courses/{id}/enrollments`. + #[tokio::test] + async fn a_vanished_row_is_not_an_internal_error() { + let db = crate::database::init_mem().await.unwrap(); + let class = crate::domain::class_group::ClassGroupId::from_key("9a"); + let course = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"); + let student = UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8U"); + // Never written: the same store state a delete in the window leaves. + let ghost = Enrollment { + id: EnrollmentId::composite(&course, &student), + course: course.clone(), + user: student.clone(), + enrolled_by: UserId::from_key("mgr"), + source: Some(class), + }; + + let answered = disown_if_pumped(&db, ghost).await.unwrap(); + assert_eq!(answered.get_user(), &student); + assert_eq!(answered.get_course(), &course); + } + + /// And the other half of "absence is the meaning": a hand-placed enrollment + /// must store *no* source key, or a class sweep would take back a row it + /// never wrote. Asserted on the stored row, not the returned one. + #[tokio::test] + async fn a_hand_placed_enrollment_stores_no_source_key() { + use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; + + let db = crate::database::init_mem().await.unwrap(); + let teacher = UserId::from_key("teacher"); + let course = crate::db::course::create( + &db, + &teacher, + CourseTitle::try_new("algebra").unwrap(), + CourseDescription::try_new("").unwrap(), + CourseKind::course(), + None, + None, + ) + .await + .unwrap(); + enroll(&db, course.get_id(), &UserId::from_key("student"), &teacher) + .await + .unwrap(); + + let mut result = db + .query("SELECT VALUE 'source' IN object::keys($this) FROM enrollment") + .await + .unwrap() + .check() + .unwrap(); + assert_eq!( + result.take::>(0).unwrap(), + vec![false], + "a hand-placed row may carry no source key" + ); + } +} diff --git a/src/db/mod.rs b/src/db/mod.rs index 1ad9342..ac485cd 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -3,6 +3,7 @@ pub mod appointment; pub mod cap; pub mod course; +pub mod enrollment; pub mod exam_attempt; pub mod field_update; pub mod note; diff --git a/src/domain/class_course.rs b/src/domain/class_course.rs index a3c9ca6..a2d747c 100644 --- a/src/domain/class_course.rs +++ b/src/domain/class_course.rs @@ -8,11 +8,11 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{CLASS_COURSE_TABLE, MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; use crate::database::Database; +use crate::db::page::PagedList; use crate::domain::class_blueprint::ClassBlueprintId; use crate::domain::class_group::ClassGroupId; use crate::domain::class_pump::{Attached, Axis, attach, detach, link_id}; use crate::domain::course::CourseId; -use crate::db::page::PagedList; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; @@ -239,7 +239,6 @@ mod tests { use super::*; use crate::domain::class_member::ClassMember; use crate::domain::class_member::tests::{a_class, a_course, counter, exists, rows, source_of}; - use crate::domain::enrollment::Enrollment; /// Attaching seeds the course from the roster the class already holds. #[tokio::test] @@ -317,7 +316,7 @@ mod tests { 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) + crate::db::enrollment::enroll(&db, &algebra, &student, &manager) .await .unwrap(); ClassMember::add(&class, &student, &manager, &db) diff --git a/src/domain/class_member.rs b/src/domain/class_member.rs index 11195f2..e7725b6 100644 --- a/src/domain/class_member.rs +++ b/src/domain/class_member.rs @@ -9,9 +9,9 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{CLASS_MEMBER_TABLE, MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; use crate::database::Database; +use crate::db::page::PagedList; use crate::domain::class_group::ClassGroupId; use crate::domain::class_pump::{Attached, Axis, attach, detach, link_id}; -use crate::db::page::PagedList; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -218,7 +218,6 @@ pub(crate) mod tests { use crate::domain::class_course::ClassCourse; use crate::domain::class_group::{ClassGroup, ClassName}; use crate::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle}; - use crate::domain::enrollment::Enrollment; pub(crate) async fn a_class(name: &str, db: &Database) -> ClassGroupId { ClassGroup::create( @@ -293,7 +292,7 @@ pub(crate) mod tests { user: &UserId, db: &Database, ) -> Option> { - Enrollment::read_for_user(course, user, db) + crate::db::enrollment::read_for_user(db, course, user) .await .unwrap() .map(|row| row.get_source().cloned()) @@ -438,7 +437,7 @@ pub(crate) mod tests { 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) + crate::db::enrollment::enroll(&db, &algebra, &student, &manager) .await .unwrap(); ClassCourse::attach(&class, &algebra, &manager, &db) diff --git a/src/domain/class_pump.rs b/src/domain/class_pump.rs index ceae88c..fd63e6c 100644 --- a/src/domain/class_pump.rs +++ b/src/domain/class_pump.rs @@ -50,7 +50,7 @@ use crate::error::AppError; /// class is full" *or* "the class is gone" — one conditional write cannot say /// which, so it stays one marker and the read that tells them apart is paid for /// only on that path (the same shape as -/// [`crate::domain::enrollment::Enrollment::enroll`]). It is not `GONE_MARK`: +/// [`crate::db::enrollment::enroll`]). It is not `GONE_MARK`: /// that one is the *pivot* claim, which is a different row. /// /// `OVER_MARK` is the *other* axis already standing above its own ceiling — diff --git a/src/domain/enrollment.rs b/src/domain/enrollment.rs index 99ba4b5..d1f13ba 100644 --- a/src/domain/enrollment.rs +++ b/src/domain/enrollment.rs @@ -1,21 +1,9 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE}; -use crate::database::{Database, transaction_with_retry}; -use crate::db::cap; +use crate::constant::ENROLLMENT_TABLE; use crate::domain::class_group::ClassGroupId; use crate::domain::course::CourseId; -use crate::db::page::PagedList; -use crate::domain::role::Role; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; - -/// The `THROW` markers [`Enrollment::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"; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct EnrollmentId(RecordId); @@ -54,11 +42,11 @@ impl EnrollmentId { /// back the rows it wrote. #[derive(Debug, Clone, SurrealValue)] pub struct Enrollment { - id: EnrollmentId, - course: CourseId, - user: UserId, - enrolled_by: UserId, - source: Option, + pub(crate) id: EnrollmentId, + pub(crate) course: CourseId, + pub(crate) user: UserId, + pub(crate) enrolled_by: UserId, + pub(crate) source: Option, } impl Enrollment { @@ -82,223 +70,6 @@ impl Enrollment { pub fn get_source(&self) -> Option<&ClassGroupId> { self.source.as_ref() } - - /// 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. - /// - /// 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::domain::class_pump::attach`]. - pub async fn enroll( - course: &CourseId, - user: &UserId, - enrolled_by: &UserId, - db: &Database, - ) -> Result { - if let Some(existing) = Self::read_for_user(course, user, db).await? { - return Self::disown_if_pumped(existing, db).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, - }; - // 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 Self::read_for_user(course, user, db).await? { - Some(existing) => Self::disown_if_pumped(existing, db).await, - None => Err(AppError::Internal("failed to enroll user".into())), - }; - } - // Demoted while this ran: the same refusal the handler's own read 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 { - 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? { - 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()); - } - // 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 - /// class: `source` goes, so no later class sweep can unenroll a student an - /// operator placed on purpose. The mirror of the rule the sweep already - /// 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. - async fn disown_if_pumped(existing: Enrollment, db: &Database) -> Result { - if existing.source.is_none() { - return Ok(existing); - } - let mut result = db - .query("UPDATE $id UNSET source RETURN AFTER") - .bind(("id", existing.id.record())) - .await? - .check()?; - // 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)) - } - - /// Some(_) iff `user` is enrolled in `course` — the grading gate. - pub async fn read_for_user( - course: &CourseId, - user: &UserId, - db: &Database, - ) -> 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()) - } - - pub async fn list_for_course( - course: &CourseId, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new("enrollment WHERE course = $course", "ORDER BY id DESC") - .bind("course", course.record()) - .run(limit, offset, db) - .await - } - - pub async fn remove( - course: &CourseId, - user: &UserId, - db: &Database, - ) -> 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()) - } } #[cfg(test)] @@ -331,120 +102,4 @@ mod tests { let decoded = Enrollment::from_value(Value::Object(object)).unwrap(); assert_eq!(decoded.get_source(), None); } - - /// The boot repair of `enrollment_count` **against a real server**, and - /// `#[ignore]`d for it: the pass counts rows off `enrollment`'s indexed - /// `course` field, and an aggregate over an indexed field is exactly where - /// the embedded engine and the server are known to differ (`count()` comes - /// back `{count: N}` from one and a bare int from the other, which - /// `option` would refuse). `array::len` over ids is the spelling that - /// dodges it — this is what proves it on the store that bites. - /// - /// Both halves in one boot: `staff` is the row the sweep deletes (their - /// seat must come back), and `empty` is the course a *past* sweep already - /// stranded — count above zero with no rows left, so it forms no group and - /// only a per-course pass ever visits it. The second `migrate` pins that the - /// repair converges rather than overwriting: it must write nothing. - #[tokio::test] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn the_count_repair_recounts_on_a_real_server() { - let (db, _serialized) = crate::database::init_test_server("enrollment_repair").await; - db.query( - "CREATE user:t SET username = 't', password_hash = 'x', role = 'teacher'; - CREATE user:a SET username = 'a', password_hash = 'x', role = 'student'; - CREATE user:b SET username = 'b', password_hash = 'x', role = 'student'; - CREATE course:live SET creator = user:t, title = 'l', description = '', - enrollment_count = 9; - CREATE course:empty SET creator = user:t, title = 'e', description = '', - enrollment_count = 4; - CREATE enrollment:live_a SET course = course:live, user = user:a, enrolled_by = user:t; - CREATE enrollment:live_b SET course = course:live, user = user:b, enrolled_by = user:t; - CREATE enrollment:live_t SET course = course:live, user = user:t, enrolled_by = user:t;", - ) - .await - .unwrap() - .check() - .unwrap(); - - async fn counts(db: &Database) -> Vec { - let mut result = db - .query("SELECT VALUE enrollment_count FROM course ORDER BY id") - .await - .unwrap() - .check() - .unwrap(); - result.take::>(0).unwrap() - } - - crate::database::migrate(db.as_ref()).await.unwrap(); - // `course:empty` sorts before `course:live`: stranded count cleared, and - // the live course recounted to its two students — the teacher's row was - // swept and handed its seat back in the same boot. - assert_eq!(counts(&db).await, vec![0, 2]); - - crate::database::migrate(db.as_ref()).await.unwrap(); - assert_eq!(counts(&db).await, vec![0, 2], "the repair converges"); - } - - /// A pumped row that vanishes under the disown — a concurrent unenroll, or - /// the sweep a role change runs — must answer the row the caller was - /// handed, not a 500. The `UPDATE` matches nothing and used to fall through - /// to `AppError::Internal`, turning a race the old code answered 200 into a - /// server error on an ordinary `POST /courses/{id}/enrollments`. - #[tokio::test] - async fn a_vanished_row_is_not_an_internal_error() { - let db = crate::database::init_mem().await.unwrap(); - let class = crate::domain::class_group::ClassGroupId::from_key("9a"); - let course = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"); - let student = UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8U"); - // Never written: the same store state a delete in the window leaves. - let ghost = Enrollment { - id: EnrollmentId::composite(&course, &student), - course: course.clone(), - user: student.clone(), - enrolled_by: UserId::from_key("mgr"), - source: Some(class), - }; - - let answered = Enrollment::disown_if_pumped(ghost, &db).await.unwrap(); - assert_eq!(answered.get_user(), &student); - assert_eq!(answered.get_course(), &course); - } - - /// And the other half of "absence is the meaning": a hand-placed enrollment - /// must store *no* source key, or a class sweep would take back a row it - /// never wrote. Asserted on the stored row, not the returned one. - #[tokio::test] - async fn a_hand_placed_enrollment_stores_no_source_key() { - use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; - - let db = crate::database::init_mem().await.unwrap(); - let teacher = UserId::from_key("teacher"); - let course = crate::db::course::create( - &db, - &teacher, - CourseTitle::try_new("algebra").unwrap(), - CourseDescription::try_new("").unwrap(), - CourseKind::course(), - None, - None, - ) - .await - .unwrap(); - Enrollment::enroll(course.get_id(), &UserId::from_key("student"), &teacher, &db) - .await - .unwrap(); - - let mut result = db - .query("SELECT VALUE 'source' IN object::keys($this) FROM enrollment") - .await - .unwrap() - .check() - .unwrap(); - assert_eq!( - result.take::>(0).unwrap(), - vec![false], - "a hand-placed row may carry no source key" - ); - } } diff --git a/src/domain/event.rs b/src/domain/event.rs index 0648d4e..6fa6645 100644 --- a/src/domain/event.rs +++ b/src/domain/event.rs @@ -7,7 +7,7 @@ use crate::database::{Database, transaction_with_retry}; use crate::domain::class_group::ClassGroupId; use crate::domain::class_member::{ClassMember, ClassMemberId}; use crate::domain::course::CourseId; -use crate::domain::enrollment::Enrollment; + use crate::db::field_update::FieldUpdate; use crate::domain::monotonic_id::next_ulid; use crate::domain::registration::Registration; @@ -121,9 +121,11 @@ impl EventAudience { EventAudience::School => Ok(true), EventAudience::Role { role } => Ok(user.get_role() == *role), EventAudience::Course { course } => { - Ok(Enrollment::read_for_user(course, user.get_id(), db) - .await? - .is_some()) + Ok( + crate::db::enrollment::read_for_user(db, course, user.get_id()) + .await? + .is_some(), + ) } // The (class, user) pair is the membership row's own id, so the // point check is a single select — no scan, no index needed. @@ -158,7 +160,7 @@ impl EventAudience { .map(|user| user.get_id().clone()) .collect()), EventAudience::Course { course } => { - Ok(Enrollment::list_for_course(course, None, 0, db) + Ok(crate::db::enrollment::list_for_course(db, course, None, 0) .await? .0 .iter() diff --git a/src/migration_sql.rs b/src/migration_sql.rs index e4f77fe..2f8e14a 100644 --- a/src/migration_sql.rs +++ b/src/migration_sql.rs @@ -1035,7 +1035,7 @@ pub const BACKFILL: &str = " -- -- Counting the rows cannot read *low*. The counter has exactly one meaning — -- the live enrollment rows of this course — and every writer moves it with - -- the row in one transaction (`Enrollment::enroll`/`remove`, `set_role`'s + -- the row in one transaction (`db::enrollment`'s `enroll`/`remove`, `set_role`'s -- demotion sweep, the class pump's attach and detach); `Course::delete` takes -- the rows *and* the course together, so no cascade leaves counted rows -- behind. That is what separates it from the lifetime tallies below, which diff --git a/src/service/enrollment.rs b/src/service/enrollment.rs new file mode 100644 index 0000000..e901e32 --- /dev/null +++ b/src/service/enrollment.rs @@ -0,0 +1,70 @@ +//! Enrollment workflows: the target-user gates the enroll/unenroll HTTP +//! handlers pay (the target must exist and still be a student; unenrolling a +//! pair with no row is a 404) wrapped around the atomic seat claim in +//! [`crate::db::enrollment`]. + +use crate::database::Database; +use crate::db::enrollment; +use crate::domain::course::CourseId; +use crate::domain::enrollment::Enrollment; +use crate::domain::role::Role; +use crate::domain::user::{User, UserId}; +use crate::error::{AppError, ValidationError}; + +/// Enroll `target` into `course` on `enrolled_by`'s orders. The target-user +/// gates first — they are validation of the request, so a 400, and they run +/// in the order the handler used to: an unknown user outranks a non-student +/// one — then the claim (idempotent for an already-enrolled pair; 409 on a +/// full roster; 404 when the course is gone). +pub async fn enroll( + db: &Database, + course: &CourseId, + target: &UserId, + enrolled_by: &UserId, +) -> Result { + let Some(target_user) = User::read(target, db).await? else { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "target user does not exist", + })); + }; + + // Enrollment is student membership: it gates sitting exams, being graded, + // and appearing on a lesson roster — all student-only. Staff run courses, + // they don't enroll in them. + if target_user.get_role() != Role::Student { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "only students can be enrolled in a course", + })); + } + + enrollment::enroll(db, course, target, enrolled_by).await +} + +/// Unenroll `target` from `course`. `NotFound` when the pair holds no row — +/// unenrolling someone who was never enrolled removed nothing, so the web +/// layer must not pretend they did. +pub async fn unenroll(db: &Database, course: &CourseId, target: &UserId) -> Result<(), AppError> { + enrollment::remove(db, course, target) + .await? + .ok_or(AppError::NotFound)?; + Ok(()) +} + +pub async fn read_for_user( + db: &Database, + course: &CourseId, + user: &UserId, +) -> Result, AppError> { + enrollment::read_for_user(db, course, user).await +} + +pub async fn list_for_course( + db: &Database, + course: &CourseId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + enrollment::list_for_course(db, course, limit, offset).await +} diff --git a/src/service/exam_attempt.rs b/src/service/exam_attempt.rs index 70c965d..9c907b2 100644 --- a/src/service/exam_attempt.rs +++ b/src/service/exam_attempt.rs @@ -8,7 +8,7 @@ use crate::database::Database; use crate::db::cap; use crate::domain::badge; use crate::domain::course::Course; -use crate::domain::enrollment::Enrollment; + use crate::domain::exam::{Exam, ExamId}; use crate::domain::exam_answer::ExamAnswer; use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt, ExamAttemptId}; @@ -97,7 +97,7 @@ pub async fn ensure_student_now(user: &UserId, db: &Database) -> Result<(), AppE /// an unenrollment mid-exam cuts them too. Finishing stays exempt: like the /// rejoin lock, submitting what's already saved writes nothing new. pub async fn ensure_enrolled(exam: &Exam, user: &UserId, db: &Database) -> Result<(), AppError> { - if Enrollment::read_for_user(exam.get_course(), user, db) + if crate::db::enrollment::read_for_user(db, exam.get_course(), user) .await? .is_none() { diff --git a/src/service/mod.rs b/src/service/mod.rs index 892e3cd..6cce670 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -3,6 +3,7 @@ pub mod appointment; pub mod course; +pub mod enrollment; pub mod exam_attempt; pub mod note; pub mod payment_ledger; diff --git a/src/web/boards.rs b/src/web/boards.rs index ffa1993..f5d2568 100644 --- a/src/web/boards.rs +++ b/src/web/boards.rs @@ -35,7 +35,6 @@ use crate::domain::board_stroke::BoardStroke; use crate::domain::class_group::{ClassGroup, ClassGroupId}; use crate::domain::class_member::ClassMember; use crate::domain::course::CourseId; -use crate::domain::enrollment::Enrollment; use crate::domain::event::{Event, EventId}; use crate::domain::role::Role; use crate::domain::user::{User, UserId}; @@ -753,12 +752,14 @@ impl InviteSource { "only the course creator, an assigned teacher, or a manager/admin can invite its roster", )); } - Ok(Enrollment::list_for_course(course.get_id(), None, 0, db) - .await? - .0 - .iter() - .map(|enrollment| enrollment.get_user().clone()) - .collect()) + Ok( + crate::service::enrollment::list_for_course(db, course.get_id(), None, 0) + .await? + .0 + .iter() + .map(|enrollment| enrollment.get_user().clone()) + .collect(), + ) } InviteSource::Event { event } => { if !user.get_role().at_least(Role::Teacher) { diff --git a/src/web/courses.rs b/src/web/courses.rs index 9a52348..3e6838b 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -240,7 +240,7 @@ pub(crate) async fn can_view_course( return Ok(true); } Ok( - Enrollment::read_for_user(course.get_id(), user.get_id(), db) + service::enrollment::read_for_user(db, course.get_id(), user.get_id()) .await? .is_some(), ) @@ -265,7 +265,10 @@ pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let (courses, total) = service::course::list_enrolled(&st.db, user.get_id(), limit, offset).await?; + let (courses, total) = + service::course::list_enrolled(&st.db, user.get_id(), limit, offset).await?; let people = person_map(courses.iter().flat_map(course_people), &st.db).await?; let items = courses .iter() @@ -690,25 +694,9 @@ async fn enroll( service::course::require_open(&st.db, &course).await?; let target = UserId::from_key(&req.user_id); - let Some(target_user) = User::read(&target, &st.db).await? else { - return Err(AppError::Validation(ValidationError::Invalid { - field: "user_id", - reason: "target user does not exist", - })); - }; - - // Enrollment is student membership: it gates sitting exams, being graded, - // and appearing on a lesson roster — all student-only. Staff run courses, - // they don't enroll in them. - if target_user.get_role() != Role::Student { - return Err(AppError::Validation(ValidationError::Invalid { - field: "user_id", - reason: "only students can be enrolled in a course", - })); - } - - let enrollment = Enrollment::enroll(course.get_id(), &target, user.get_id(), &st.db).await?; - let people = PersonRef::map_of(&[&target_user, &user]); + let enrollment = + service::enrollment::enroll(&st.db, course.get_id(), &target, user.get_id()).await?; + let people = person_map([target, user.get_id().clone()], &st.db).await?; Ok(Json(EnrollmentResponse::new(&enrollment, &people))) } @@ -746,7 +734,8 @@ async fn list_roster( "only the course creator, an assigned teacher, or a manager/admin can list the roster", )); } - let (rows, total) = Enrollment::list_for_course(course.get_id(), limit, offset, &st.db).await?; + let (rows, total) = + service::enrollment::list_for_course(&st.db, course.get_id(), limit, offset).await?; // Join people onto the page alone — the lookup shrinks with the window. let people = person_map( rows.iter() @@ -795,10 +784,7 @@ async fn unenroll( )); } service::course::require_open(&st.db, &course).await?; - let removed = Enrollment::remove(course.get_id(), &UserId::from_key(&target), &st.db).await?; - if removed.is_none() { - return Err(AppError::NotFound); - } + service::enrollment::unenroll(&st.db, course.get_id(), &UserId::from_key(&target)).await?; Ok(StatusCode::NO_CONTENT) } @@ -1359,13 +1345,10 @@ mod tests { let db = init_mem().await.unwrap(); let creator = user("creator", Role::Teacher, &db).await; let assigned = user("assigned", Role::Teacher, &db).await; - let course = service::course::assign_teacher( - &db, - &course(&creator, &db).await, - assigned.get_id(), - ) - .await - .unwrap(); + let course = + service::course::assign_teacher(&db, &course(&creator, &db).await, assigned.get_id()) + .await + .unwrap(); // Still teacher+: untouched by the floor. assert!(can_manage_course(&course, &assigned)); // ...but never an owner, assigned or not. diff --git a/src/web/exams/attempts.rs b/src/web/exams/attempts.rs index 1a9068d..2a9c852 100644 --- a/src/web/exams/attempts.rs +++ b/src/web/exams/attempts.rs @@ -327,7 +327,8 @@ pub(crate) async fn live_snapshot( db: &Database, ) -> Result { let now = Timestamp::now(); - let (roster, _) = Enrollment::list_for_course(exam.get_course(), None, 0, db).await?; + let (roster, _) = + crate::service::enrollment::list_for_course(db, exam.get_course(), None, 0).await?; // Per student: their latest sitting (the one the monitor shows) plus how // many they've used. let mut attempts: HashMap = HashMap::new(); diff --git a/src/web/exams/mod.rs b/src/web/exams/mod.rs index 0011dff..8510736 100644 --- a/src/web/exams/mod.rs +++ b/src/web/exams/mod.rs @@ -16,7 +16,7 @@ use crate::domain::answer_image::AnswerImage; use crate::domain::badge; use crate::domain::bank_question::{BankQuestion, BankQuestionId}; use crate::domain::bank_question_image::BankQuestionImage; -use crate::domain::enrollment::Enrollment; + use crate::domain::exam::{ Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode, ExamSchedule, ExamTitle, @@ -688,7 +688,7 @@ async fn grade( } // ... and be enrolled in the exam's course. - if Enrollment::read_for_user(exam.get_course(), &target, &st.db) + if service::enrollment::read_for_user(&st.db, exam.get_course(), &target) .await? .is_none() { diff --git a/src/web/homework.rs b/src/web/homework.rs index dd767b3..c769569 100644 --- a/src/web/homework.rs +++ b/src/web/homework.rs @@ -20,7 +20,7 @@ use crate::constant::{MAX_HOMEWORK_ASSIGNED, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVE use crate::database::Database; use crate::domain::badge; use crate::domain::course::{Course, CourseId}; -use crate::domain::enrollment::Enrollment; + use crate::domain::exam_result::Mark; use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle}; use crate::domain::homework_file::{HomeworkFile, HomeworkFileId}; @@ -135,7 +135,7 @@ pub(crate) async fn resolve_assigned( let mut users = Vec::with_capacity(keys.len()); for key in keys { let user = UserId::from_key(&key); - if Enrollment::read_for_user(course, &user, db) + if service::enrollment::read_for_user(db, course, &user) .await? .is_none() { @@ -480,7 +480,10 @@ async fn delete_homework( /// Submitting is course content, so leaving the course closes it; re-checked on /// every submission and file write, so an unenrollment mid-task bites the next. async fn ensure_enrolled(course: &CourseId, user: &UserId, db: &Database) -> Result<(), AppError> { - if Enrollment::read_for_user(course, user, db).await?.is_none() { + if service::enrollment::read_for_user(db, course, user) + .await? + .is_none() + { return Err(AppError::Forbidden( "you are not enrolled in this homework's course", )); @@ -1177,7 +1180,7 @@ async fn grade_homework( } // ... enrolled in the homework's course ... - if Enrollment::read_for_user(homework.get_course(), &target, &st.db) + if service::enrollment::read_for_user(&st.db, homework.get_course(), &target) .await? .is_none() { @@ -1355,12 +1358,13 @@ async fn list_homework_submissions( } let submissions = HomeworkSubmission::list_for_homework(homework.get_id(), &st.db).await?; let results = HomeworkResult::list_for_homework(homework.get_id(), &st.db).await?; - let enrolled: Vec = Enrollment::list_for_course(course.get_id(), None, 0, &st.db) - .await? - .0 - .iter() - .map(|enrollment| enrollment.get_user().key().to_string()) - .collect(); + let enrolled: Vec = + service::enrollment::list_for_course(&st.db, course.get_id(), None, 0) + .await? + .0 + .iter() + .map(|enrollment| enrollment.get_user().key().to_string()) + .collect(); // The audience: the assigned subset as stored, or — whole-course — whoever // is enrolled right now. Anyone outside it who still owns a submission or // grade is appended rather than dropped: their stale rows are exactly what diff --git a/src/web/sessions.rs b/src/web/sessions.rs index 7d70fe1..ddc4aeb 100644 --- a/src/web/sessions.rs +++ b/src/web/sessions.rs @@ -14,7 +14,7 @@ use crate::domain::attendance::AttendanceStatus; use crate::domain::badge; use crate::domain::course::Course; use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic}; -use crate::domain::enrollment::Enrollment; + use crate::domain::role::Role; use crate::domain::session_attendance::SessionAttendance; use crate::domain::timestamp::Timestamp; @@ -349,7 +349,7 @@ async fn mark_roll_call( reason: "only students can be marked present in a lesson", })); } - if Enrollment::read_for_user(session.get_course(), &target, &st.db) + if service::enrollment::read_for_user(&st.db, session.get_course(), &target) .await? .is_none() { diff --git a/tests/regress_role_sweep.rs b/tests/regress_role_sweep.rs index 3ff91b5..08686b6 100644 --- a/tests/regress_role_sweep.rs +++ b/tests/regress_role_sweep.rs @@ -21,10 +21,10 @@ mod common; use axum::http::StatusCode; use common::{app_and_db, login_as, me_id, send}; use hezarfen_backend::database::Database; +use hezarfen_backend::db::enrollment; use hezarfen_backend::domain::class_group::{ClassGroup, ClassGroupId, ClassName}; use hezarfen_backend::domain::class_member::ClassMember; use hezarfen_backend::domain::course::CourseId; -use hezarfen_backend::domain::enrollment::Enrollment; use hezarfen_backend::domain::event::EventId; use hezarfen_backend::domain::registration::Registration; use hezarfen_backend::domain::role::Role; @@ -272,7 +272,7 @@ async fn an_enrollment_is_refused_once_the_student_is_demoted() { let course = a_course(&app, &teacher).await; demote(&student, Role::Teacher, &db).await; - let refused = Enrollment::enroll(&course, &student, &UserId::from_key("staff"), &db).await; + let refused = enrollment::enroll(&db, &course, &student, &UserId::from_key("staff")).await; assert!( refused.is_err(), "only students hold enrollments: {refused:?}" @@ -293,13 +293,13 @@ async fn an_enrollment_never_survives_the_demotion_it_raced() { let course = a_course(&app, &teacher).await; // The bait: a row the sweep will delete, which is what holds it open. let earlier = CourseId::from_key(&common::create_course(&app, &teacher, "fizik").await); - Enrollment::enroll(&earlier, &student, &UserId::from_key("staff"), &db) + enrollment::enroll(&db, &earlier, &student, &UserId::from_key("staff")) .await .unwrap(); hold_the_sweep("enrollment", &db).await; let demoting = demote_in_the_window(&student, Role::Teacher, &db).await; - let enrolled = Enrollment::enroll(&course, &student, &UserId::from_key("staff"), &db).await; + let enrolled = enrollment::enroll(&db, &course, &student, &UserId::from_key("staff")).await; still_running(&demoting); demoting.await.unwrap();