forge
Explore
Log in

Don't you dare go Hollow

Split enrollment into domain/db/service layers

Browse files at this commit

1e68fc9a5900ff8229d80dd2cae27ab267e94aa4Ahmet Kaan GümüşParent: ad1326c
  • chore
    • split enrollment into domain/db/service layers
Show full message
🧹 chore: split enrollment into domain/db/service layers
src/db/course.rsmodified+7 -9
@@ -514,13 +514,11 @@ mod tests {
514 /// included. A `>= 0` guard passes the roster branch and fails here.514 /// included. A `>= 0` guard passes the roster branch and fails here.
515 #[tokio::test]515 #[tokio::test]
516 async fn a_course_with_a_roster_refuses_to_delete() {516 async fn a_course_with_a_roster_refuses_to_delete() {
517- use crate::domain::enrollment::Enrollment;
518-
519 let db = crate::database::init_mem().await.unwrap();517 let db = crate::database::init_mem().await.unwrap();
520 let teacher = UserId::from_key("teacher");518 let teacher = UserId::from_key("teacher");
521 let student = UserId::from_key("student");519 let student = UserId::from_key("student");
522 let course = course_on(None, &db).await;520 let course = course_on(None, &db).await;
523- Enrollment::enroll(course.get_id(), &student, &teacher, &db)521+ crate::db::enrollment::enroll(&db, course.get_id(), &student, &teacher)
524 .await522 .await
525 .unwrap();523 .unwrap();
526 524
@@ -533,14 +531,14 @@ mod tests {
533 "a refused delete may write nothing"531 "a refused delete may write nothing"
534 );532 );
535 assert!(533 assert!(
536- Enrollment::read_for_user(course.get_id(), &student, &db)534+ crate::db::enrollment::read_for_user(&db, course.get_id(), &student)
537 .await535 .await
538 .unwrap()536 .unwrap()
539 .is_some(),537 .is_some(),
540 "…the cascade least of all"538 "…the cascade least of all"
541 );539 );
542 540
543- Enrollment::remove(course.get_id(), &student, &db)541+ crate::db::enrollment::remove(&db, course.get_id(), &student)
544 .await542 .await
545 .unwrap();543 .unwrap();
546 assert!(delete(&db, course.clone()).await.unwrap());544 assert!(delete(&db, course.clone()).await.unwrap());
@@ -549,7 +547,7 @@ mod tests {
549 // The other half of the same guard: once the course row is gone the547 // The other half of the same guard: once the course row is gone the
550 // seat claim matches nothing, so a late enroll is a 404 rather than a548 // seat claim matches nothing, so a late enroll is a 404 rather than a
551 // roster row that outlived its course.549 // roster row that outlived its course.
552- let late = Enrollment::enroll(course.get_id(), &student, &teacher, &db)550+ let late = crate::db::enrollment::enroll(&db, course.get_id(), &student, &teacher)
553 .await551 .await
554 .expect_err("enrolling into a deleted course must fail");552 .expect_err("enrolling into a deleted course must fail");
555 assert!(matches!(late, AppError::NotFound), "got {late:?}");553 assert!(matches!(late, AppError::NotFound), "got {late:?}");
@@ -952,7 +950,6 @@ mod tests {
952 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]950 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
953 #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]951 #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
954 async fn a_delete_racing_an_enroll_never_answers_500() {952 async fn a_delete_racing_an_enroll_never_answers_500() {
955- use crate::domain::enrollment::Enrollment;
956 let (db, _serialized) = crate::database::init_test_server("course_delete_race").await;953 let (db, _serialized) = crate::database::init_test_server("course_delete_race").await;
957 let (mut delete_500, mut enroll_500, mut enrolled) = (0, 0, 0);954 let (mut delete_500, mut enroll_500, mut enrolled) = (0, 0, 0);
958 let (mut last_delete, mut last_enroll) = (String::new(), String::new());955 let (mut last_delete, mut last_enroll) = (String::new(), String::new());
@@ -978,7 +975,8 @@ mod tests {
978 let (id, db) = (course.get_id().clone(), db.clone());975 let (id, db) = (course.get_id().clone(), db.clone());
979 let student = UserId::from_key(&format!("stu{round}_{seat}"));976 let student = UserId::from_key(&format!("stu{round}_{seat}"));
980 tokio::spawn(async move {977 tokio::spawn(async move {
981- Enrollment::enroll(&id, &student, &UserId::from_key("mgr"), &db).await978+ crate::db::enrollment::enroll(&db, &id, &student, &UserId::from_key("mgr"))
979+ .await
982 })980 })
983 })981 })
984 .collect();982 .collect();
@@ -996,7 +994,7 @@ mod tests {
996 }994 }
997 // Stored state, not the return values: a seat that landed is what995 // Stored state, not the return values: a seat that landed is what
998 // the guard had to see.996 // the guard had to see.
999- if !Enrollment::list_for_course(course.get_id(), None, 0, &db)997+ if !crate::db::enrollment::list_for_course(&db, course.get_id(), None, 0)
1000 .await998 .await
1001 .unwrap()999 .unwrap()
1002 .01000 .0
src/db/enrollment.rsadded+362 -0
@@ -0,0 +1,362 @@
1+//! The `enrollment` table: the roster read and listing, the seat-returning
2+//! delete, and the enroll claim — the one transaction that checks the pair
3+//! free, the member still a student, and the roster under capacity while it
4+//! spends the seat. The target-user gates the HTTP handlers pay live in
5+//! [`crate::service::enrollment`].
6+
7+use surrealdb::types::SurrealValue;
8+
9+use crate::constant::ENROLLMENT_COUNT_FIELD;
10+use crate::database::{Database, transaction_with_retry};
11+use crate::db::cap;
12+use crate::db::page::PagedList;
13+use crate::domain::course::CourseId;
14+use crate::domain::enrollment::{Enrollment, EnrollmentId};
15+use crate::domain::role::Role;
16+use crate::domain::user::UserId;
17+use crate::error::{AppError, ValidationError};
18+
19+/// The `THROW` markers [`enroll`]'s claim aborts with: this pair
20+/// already holds a row, the roster is full, and the person being enrolled is no
21+/// longer a student.
22+const HELD_MARK: &str = "enroll_held";
23+const FULL_MARK: &str = "enroll_full";
24+const UNFIT_MARK: &str = "enroll_not_student";
25+
26+/// Enroll (idempotently) `user` into `course`. One row per (course, user),
27+/// keyed by a deterministic composite id, so concurrent enrolls of the same
28+/// pair converge on one row instead of racing the unique index into a 500:
29+/// the loser of the `CREATE` reads the winner's row back and returns it.
30+/// When the course carries a capacity, a full roster refuses new members
31+/// (409) — the seat is taken by a single-record conditional write on the
32+/// course row whose bound is the row's *own* `capacity` column, read inside
33+/// the same statement that spends the seat. A snapshot integer taken by a
34+/// read beforehand would be exactly the number a concurrent capacity PATCH
35+/// invalidates, which is what this promised and did not do. An already
36+/// enrolled user is returned as-is even when the roster is full, and never
37+/// charged a seat. The same claim is the delete guard's other half: it
38+/// matches nothing once the course row is gone, and while it holds a seat
39+/// the course cannot be deleted — so no roster row can outlive its course.
40+///
41+/// On admissibility ([`crate::database::transaction_with_retry`]): the
42+/// `CREATE` here *can* answer "already exists", but only to a rival that
43+/// landed inside this very window — and the re-send then sees that row at
44+/// the `$held` gate and takes the other branch, so the loop converges
45+/// instead of re-asking a settled question. Same shape, same reason, as
46+/// [`crate::domain::class_pump::attach`].
47+pub async fn enroll(
48+ db: &Database,
49+ course: &CourseId,
50+ user: &UserId,
51+ enrolled_by: &UserId,
52+) -> Result<Enrollment, AppError> {
53+ if let Some(existing) = read_for_user(db, course, user).await? {
54+ return disown_if_pumped(db, existing).await;
55+ }
56+ let enrollment = Enrollment {
57+ id: EnrollmentId::composite(course, user),
58+ course: course.clone(),
59+ user: user.clone(),
60+ enrolled_by: enrolled_by.clone(),
61+ // Hand-placed: no source key at all is written, which is what makes
62+ // a class sweep unable to take this row back.
63+ source: None,
64+ };
65+ // CREATE, not UPSERT, and in the seat's own transaction: a duplicate has
66+ // to be *seen*, or the pair's second writer would keep the seat it
67+ // claimed for a row that already existed and the counter would drift
68+ // above the roster forever.
69+ //
70+ // Parenthesized `??` throughout: `n ?? 0 < cap` parses as
71+ // `n ?? (0 < cap)`, which is truthy for every row and would enroll past
72+ // the capacity.
73+ //
74+ // The seat is claimed on the *course*, so the student's own row is
75+ // claimed beside it ([`cap::role_claim`]): a demotion's sweep runs on a
76+ // snapshot, and a row landing after it would count a seat for someone
77+ // who may not hold one, with nothing left to re-sweep. It rides between
78+ // the duplicate gate and the seat, so "you are already in" still
79+ // outranks it and it outranks a full roster.
80+ let held_by = cap::role_claim(
81+ "usr",
82+ &format!("!= '{}'", Role::Student.as_str()),
83+ UNFIT_MARK,
84+ );
85+ let hold = held_by.join(";\n ");
86+ let sql = format!(
87+ "BEGIN TRANSACTION;
88+ LET $held = (SELECT VALUE id FROM $id);
89+ IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }};
90+ {hold};
91+ LET $seat = (UPDATE $course SET {ENROLLMENT_COUNT_FIELD} = \
92+ ({ENROLLMENT_COUNT_FIELD} ?? 0) + 1 \
93+ WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) < (capacity ?? $unlimited) \
94+ RETURN VALUE id);
95+ IF array::len($seat) = 0 {{ THROW '{FULL_MARK}' }};
96+ CREATE $id CONTENT $row;
97+ COMMIT TRANSACTION;"
98+ );
99+ // The process still sends its counter writes one at a time (see
100+ // [`cap::counter_lock`]); this statement moves the same counter every
101+ // cap claim does.
102+ let _guard = cap::counter_lock().await;
103+ let (mut result, mut errors) = transaction_with_retry(
104+ db,
105+ &sql,
106+ &[
107+ ("id".into(), enrollment.id.record().into_value()),
108+ ("row".into(), enrollment.clone().into_value()),
109+ ("course".into(), course.record().into_value()),
110+ ("usr".into(), user.record().into_value()),
111+ ("unlimited".into(), cap::UNLIMITED.into_value()),
112+ ],
113+ &[HELD_MARK, FULL_MARK, UNFIT_MARK],
114+ )
115+ .await?;
116+ // Someone placed this pair first; their row is the answer, and no seat
117+ // was spent finding that out. It is read first: it outranks the refusal
118+ // below, and the gate aborts before the seat is touched.
119+ if errors
120+ .values()
121+ .any(|error| error.to_string().contains(HELD_MARK))
122+ {
123+ return match read_for_user(db, course, user).await? {
124+ Some(existing) => disown_if_pumped(db, existing).await,
125+ None => Err(AppError::Internal("failed to enroll user".into())),
126+ };
127+ }
128+ // Demoted while this ran: the same refusal the service's own gate makes
129+ // a moment earlier, and the only one that can arrive after it.
130+ if errors
131+ .values()
132+ .any(|error| error.to_string().contains(UNFIT_MARK))
133+ {
134+ return Err(AppError::Validation(ValidationError::Invalid {
135+ field: "user_id",
136+ reason: "only students can be enrolled in a course",
137+ }));
138+ }
139+ // Full, or the course is gone — the conditional write matches nothing
140+ // either way, and only this path pays for the read that tells them
141+ // apart.
142+ if errors
143+ .values()
144+ .any(|error| error.to_string().contains(FULL_MARK))
145+ {
146+ return match crate::db::course::read(db, course).await? {
147+ Some(_) => Err(AppError::Conflict("the course is full")),
148+ None => Err(AppError::NotFound),
149+ };
150+ }
151+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
152+ return Err(error.into());
153+ }
154+ // Slots count BEGIN, two LETs and two IFs, plus the holder claim's own
155+ // statements — counted, not tallied by hand, so a statement added there
156+ // cannot read back the wrong result.
157+ result
158+ .take::<Vec<Enrollment>>(5 + held_by.len())?
159+ .into_iter()
160+ .next()
161+ .ok_or_else(|| AppError::Internal("failed to enroll user".into()))
162+}
163+
164+/// A hand enroll landing on a row a class pumped takes the row *off* the
165+/// class: `source` goes, so no later class sweep can unenroll a student an
166+/// operator placed on purpose. The mirror of the rule the sweep already
167+/// holds in the other direction — a manual unenroll wins, permanently — and
168+/// without it "hand-placed" was a state only a first enroll could reach.
169+///
170+/// `UNSET`, not `= NONE`: absence *is* the meaning of this column (see the
171+/// struct doc), and it is what a hand enroll writes on the create path.
172+async fn disown_if_pumped(db: &Database, existing: Enrollment) -> Result<Enrollment, AppError> {
173+ if existing.source.is_none() {
174+ return Ok(existing);
175+ }
176+ let mut result = db
177+ .query("UPDATE $id UNSET source RETURN AFTER")
178+ .bind(("id", existing.id.record()))
179+ .await?
180+ .check()?;
181+ // A row that is no longer there is not an internal error: an unenroll
182+ // (or the class sweep a role change runs) landing between the read
183+ // above and this write matches nothing, and the caller asked to be
184+ // enrolled — which they were, by the row this call was handed. The
185+ // disown is all that is lost, and it is lost to a delete that took the
186+ // whole row with it.
187+ Ok(result
188+ .take::<Vec<Enrollment>>(0)?
189+ .into_iter()
190+ .next()
191+ .unwrap_or(existing))
192+}
193+
194+/// Some(_) iff `user` is enrolled in `course` — the grading gate.
195+pub async fn read_for_user(
196+ db: &Database,
197+ course: &CourseId,
198+ user: &UserId,
199+) -> Result<Option<Enrollment>, AppError> {
200+ let mut result = db
201+ .query("SELECT * FROM enrollment WHERE course = $course AND user = $usr LIMIT 1")
202+ .bind(("course", course.record()))
203+ .bind(("usr", user.record()))
204+ .await?
205+ .check()?;
206+ Ok(result.take::<Vec<Enrollment>>(0)?.into_iter().next())
207+}
208+
209+pub async fn list_for_course(
210+ db: &Database,
211+ course: &CourseId,
212+ limit: Option<i64>,
213+ offset: i64,
214+) -> Result<(Vec<Enrollment>, i64), AppError> {
215+ PagedList::new("enrollment WHERE course = $course", "ORDER BY id DESC")
216+ .bind("course", course.record())
217+ .run(limit, offset, db)
218+ .await
219+}
220+
221+pub async fn remove(
222+ db: &Database,
223+ course: &CourseId,
224+ user: &UserId,
225+) -> Result<Option<Enrollment>, AppError> {
226+ // The seat comes back in the same transaction as the row that held it,
227+ // so nothing but a lost transaction can drift the counter.
228+ let mut result = db
229+ .query(
230+ "BEGIN TRANSACTION;
231+ LET $gone = (DELETE enrollment WHERE course = $course AND user = $usr RETURN BEFORE);
232+ UPDATE $course SET enrollment_count = math::max([(enrollment_count ?? 0) - array::len($gone), 0]);
233+ RETURN $gone;
234+ COMMIT TRANSACTION;",
235+ )
236+ .bind(("course", course.record()))
237+ .bind(("usr", user.record()))
238+ .await?
239+ .check()?;
240+ Ok(result.take::<Vec<Enrollment>>(3)?.into_iter().next())
241+}
242+
243+#[cfg(test)]
244+mod tests {
245+ use super::*;
246+
247+ /// The boot repair of `enrollment_count` **against a real server**, and
248+ /// `#[ignore]`d for it: the pass counts rows off `enrollment`'s indexed
249+ /// `course` field, and an aggregate over an indexed field is exactly where
250+ /// the embedded engine and the server are known to differ (`count()` comes
251+ /// back `{count: N}` from one and a bare int from the other, which
252+ /// `option<int>` would refuse). `array::len` over ids is the spelling that
253+ /// dodges it — this is what proves it on the store that bites.
254+ ///
255+ /// Both halves in one boot: `staff` is the row the sweep deletes (their
256+ /// seat must come back), and `empty` is the course a *past* sweep already
257+ /// stranded — count above zero with no rows left, so it forms no group and
258+ /// only a per-course pass ever visits it. The second `migrate` pins that the
259+ /// repair converges rather than overwriting: it must write nothing.
260+ #[tokio::test]
261+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
262+ async fn the_count_repair_recounts_on_a_real_server() {
263+ let (db, _serialized) = crate::database::init_test_server("enrollment_repair").await;
264+ db.query(
265+ "CREATE user:t SET username = 't', password_hash = 'x', role = 'teacher';
266+ CREATE user:a SET username = 'a', password_hash = 'x', role = 'student';
267+ CREATE user:b SET username = 'b', password_hash = 'x', role = 'student';
268+ CREATE course:live SET creator = user:t, title = 'l', description = '',
269+ enrollment_count = 9;
270+ CREATE course:empty SET creator = user:t, title = 'e', description = '',
271+ enrollment_count = 4;
272+ CREATE enrollment:live_a SET course = course:live, user = user:a, enrolled_by = user:t;
273+ CREATE enrollment:live_b SET course = course:live, user = user:b, enrolled_by = user:t;
274+ CREATE enrollment:live_t SET course = course:live, user = user:t, enrolled_by = user:t;",
275+ )
276+ .await
277+ .unwrap()
278+ .check()
279+ .unwrap();
280+
281+ async fn counts(db: &Database) -> Vec<i64> {
282+ let mut result = db
283+ .query("SELECT VALUE enrollment_count FROM course ORDER BY id")
284+ .await
285+ .unwrap()
286+ .check()
287+ .unwrap();
288+ result.take::<Vec<i64>>(0).unwrap()
289+ }
290+
291+ crate::database::migrate(db.as_ref()).await.unwrap();
292+ // `course:empty` sorts before `course:live`: stranded count cleared, and
293+ // the live course recounted to its two students — the teacher's row was
294+ // swept and handed its seat back in the same boot.
295+ assert_eq!(counts(&db).await, vec![0, 2]);
296+
297+ crate::database::migrate(db.as_ref()).await.unwrap();
298+ assert_eq!(counts(&db).await, vec![0, 2], "the repair converges");
299+ }
300+
301+ /// A pumped row that vanishes under the disown — a concurrent unenroll, or
302+ /// the sweep a role change runs — must answer the row the caller was
303+ /// handed, not a 500. The `UPDATE` matches nothing and used to fall through
304+ /// to `AppError::Internal`, turning a race the old code answered 200 into a
305+ /// server error on an ordinary `POST /courses/{id}/enrollments`.
306+ #[tokio::test]
307+ async fn a_vanished_row_is_not_an_internal_error() {
308+ let db = crate::database::init_mem().await.unwrap();
309+ let class = crate::domain::class_group::ClassGroupId::from_key("9a");
310+ let course = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T");
311+ let student = UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8U");
312+ // Never written: the same store state a delete in the window leaves.
313+ let ghost = Enrollment {
314+ id: EnrollmentId::composite(&course, &student),
315+ course: course.clone(),
316+ user: student.clone(),
317+ enrolled_by: UserId::from_key("mgr"),
318+ source: Some(class),
319+ };
320+
321+ let answered = disown_if_pumped(&db, ghost).await.unwrap();
322+ assert_eq!(answered.get_user(), &student);
323+ assert_eq!(answered.get_course(), &course);
324+ }
325+
326+ /// And the other half of "absence is the meaning": a hand-placed enrollment
327+ /// must store *no* source key, or a class sweep would take back a row it
328+ /// never wrote. Asserted on the stored row, not the returned one.
329+ #[tokio::test]
330+ async fn a_hand_placed_enrollment_stores_no_source_key() {
331+ use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
332+
333+ let db = crate::database::init_mem().await.unwrap();
334+ let teacher = UserId::from_key("teacher");
335+ let course = crate::db::course::create(
336+ &db,
337+ &teacher,
338+ CourseTitle::try_new("algebra").unwrap(),
339+ CourseDescription::try_new("").unwrap(),
340+ CourseKind::course(),
341+ None,
342+ None,
343+ )
344+ .await
345+ .unwrap();
346+ enroll(&db, course.get_id(), &UserId::from_key("student"), &teacher)
347+ .await
348+ .unwrap();
349+
350+ let mut result = db
351+ .query("SELECT VALUE 'source' IN object::keys($this) FROM enrollment")
352+ .await
353+ .unwrap()
354+ .check()
355+ .unwrap();
356+ assert_eq!(
357+ result.take::<Vec<bool>>(0).unwrap(),
358+ vec![false],
359+ "a hand-placed row may carry no source key"
360+ );
361+ }
362+}
src/db/mod.rsmodified+1 -0
@@ -3,6 +3,7 @@
3 pub mod appointment;3 pub mod appointment;
4 pub mod cap;4 pub mod cap;
5 pub mod course;5 pub mod course;
6+pub mod enrollment;
6 pub mod exam_attempt;7 pub mod exam_attempt;
7 pub mod field_update;8 pub mod field_update;
8 pub mod note;9 pub mod note;
src/domain/class_course.rsmodified+2 -3
@@ -8,11 +8,11 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
8 8
9 use crate::constant::{CLASS_COURSE_TABLE, MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};9 use crate::constant::{CLASS_COURSE_TABLE, MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};
10 use crate::database::Database;10 use crate::database::Database;
11+use crate::db::page::PagedList;
11 use crate::domain::class_blueprint::ClassBlueprintId;12 use crate::domain::class_blueprint::ClassBlueprintId;
12 use crate::domain::class_group::ClassGroupId;13 use crate::domain::class_group::ClassGroupId;
13 use crate::domain::class_pump::{Attached, Axis, attach, detach, link_id};14 use crate::domain::class_pump::{Attached, Axis, attach, detach, link_id};
14 use crate::domain::course::CourseId;15 use crate::domain::course::CourseId;
15-use crate::db::page::PagedList;
16 use crate::domain::timestamp::Timestamp;16 use crate::domain::timestamp::Timestamp;
17 use crate::domain::user::UserId;17 use crate::domain::user::UserId;
18 use crate::error::AppError;18 use crate::error::AppError;
@@ -239,7 +239,6 @@ mod tests {
239 use super::*;239 use super::*;
240 use crate::domain::class_member::ClassMember;240 use crate::domain::class_member::ClassMember;
241 use crate::domain::class_member::tests::{a_class, a_course, counter, exists, rows, source_of};241 use crate::domain::class_member::tests::{a_class, a_course, counter, exists, rows, source_of};
242- use crate::domain::enrollment::Enrollment;
243 242
244 /// Attaching seeds the course from the roster the class already holds.243 /// Attaching seeds the course from the roster the class already holds.
245 #[tokio::test]244 #[tokio::test]
@@ -317,7 +316,7 @@ mod tests {
317 let student = UserId::from_key("student");316 let student = UserId::from_key("student");
318 let class = a_class("9-A", &db).await;317 let class = a_class("9-A", &db).await;
319 let algebra = a_course("algebra", None, &db).await;318 let algebra = a_course("algebra", None, &db).await;
320- Enrollment::enroll(&algebra, &student, &manager, &db)319+ crate::db::enrollment::enroll(&db, &algebra, &student, &manager)
321 .await320 .await
322 .unwrap();321 .unwrap();
323 ClassMember::add(&class, &student, &manager, &db)322 ClassMember::add(&class, &student, &manager, &db)
src/domain/class_member.rsmodified+3 -4
@@ -9,9 +9,9 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
9 9
10 use crate::constant::{CLASS_MEMBER_TABLE, MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};10 use crate::constant::{CLASS_MEMBER_TABLE, MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};
11 use crate::database::Database;11 use crate::database::Database;
12+use crate::db::page::PagedList;
12 use crate::domain::class_group::ClassGroupId;13 use crate::domain::class_group::ClassGroupId;
13 use crate::domain::class_pump::{Attached, Axis, attach, detach, link_id};14 use crate::domain::class_pump::{Attached, Axis, attach, detach, link_id};
14-use crate::db::page::PagedList;
15 use crate::domain::timestamp::Timestamp;15 use crate::domain::timestamp::Timestamp;
16 use crate::domain::user::UserId;16 use crate::domain::user::UserId;
17 use crate::error::{AppError, ValidationError};17 use crate::error::{AppError, ValidationError};
@@ -218,7 +218,6 @@ pub(crate) mod tests {
218 use crate::domain::class_course::ClassCourse;218 use crate::domain::class_course::ClassCourse;
219 use crate::domain::class_group::{ClassGroup, ClassName};219 use crate::domain::class_group::{ClassGroup, ClassName};
220 use crate::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle};220 use crate::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle};
221- use crate::domain::enrollment::Enrollment;
222 221
223 pub(crate) async fn a_class(name: &str, db: &Database) -> ClassGroupId {222 pub(crate) async fn a_class(name: &str, db: &Database) -> ClassGroupId {
224 ClassGroup::create(223 ClassGroup::create(
@@ -293,7 +292,7 @@ pub(crate) mod tests {
293 user: &UserId,292 user: &UserId,
294 db: &Database,293 db: &Database,
295 ) -> Option<Option<ClassGroupId>> {294 ) -> Option<Option<ClassGroupId>> {
296- Enrollment::read_for_user(course, user, db)295+ crate::db::enrollment::read_for_user(db, course, user)
297 .await296 .await
298 .unwrap()297 .unwrap()
299 .map(|row| row.get_source().cloned())298 .map(|row| row.get_source().cloned())
@@ -438,7 +437,7 @@ pub(crate) mod tests {
438 let student = UserId::from_key("student");437 let student = UserId::from_key("student");
439 let class = a_class("9-A", &db).await;438 let class = a_class("9-A", &db).await;
440 let algebra = a_course("algebra", None, &db).await;439 let algebra = a_course("algebra", None, &db).await;
441- Enrollment::enroll(&algebra, &student, &manager, &db)440+ crate::db::enrollment::enroll(&db, &algebra, &student, &manager)
442 .await441 .await
443 .unwrap();442 .unwrap();
444 ClassCourse::attach(&class, &algebra, &manager, &db)443 ClassCourse::attach(&class, &algebra, &manager, &db)
src/domain/class_pump.rsmodified+1 -1
@@ -50,7 +50,7 @@ use crate::error::AppError;
50 /// class is full" *or* "the class is gone" — one conditional write cannot say50 /// class is full" *or* "the class is gone" — one conditional write cannot say
51 /// which, so it stays one marker and the read that tells them apart is paid for51 /// which, so it stays one marker and the read that tells them apart is paid for
52 /// only on that path (the same shape as52 /// only on that path (the same shape as
53-/// [`crate::domain::enrollment::Enrollment::enroll`]). It is not `GONE_MARK`:53+/// [`crate::db::enrollment::enroll`]). It is not `GONE_MARK`:
54 /// that one is the *pivot* claim, which is a different row.54 /// that one is the *pivot* claim, which is a different row.
55 ///55 ///
56 /// `OVER_MARK` is the *other* axis already standing above its own ceiling —56 /// `OVER_MARK` is the *other* axis already standing above its own ceiling —
src/domain/enrollment.rsmodified+6 -351
@@ -1,21 +1,9 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 2
3-use crate::constant::{ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE};3+use crate::constant::ENROLLMENT_TABLE;
4-use crate::database::{Database, transaction_with_retry};
5-use crate::db::cap;
6 use crate::domain::class_group::ClassGroupId;4 use crate::domain::class_group::ClassGroupId;
7 use crate::domain::course::CourseId;5 use crate::domain::course::CourseId;
8-use crate::db::page::PagedList;
9-use crate::domain::role::Role;
10 use crate::domain::user::UserId;6 use crate::domain::user::UserId;
11-use crate::error::{AppError, ValidationError};
12-
13-/// The `THROW` markers [`Enrollment::enroll`]'s claim aborts with: this pair
14-/// already holds a row, the roster is full, and the person being enrolled is no
15-/// longer a student.
16-const HELD_MARK: &str = "enroll_held";
17-const FULL_MARK: &str = "enroll_full";
18-const UNFIT_MARK: &str = "enroll_not_student";
19 7
20 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]8 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
21 pub struct EnrollmentId(RecordId);9 pub struct EnrollmentId(RecordId);
@@ -54,11 +42,11 @@ impl EnrollmentId {
54 /// back the rows it wrote.42 /// back the rows it wrote.
55 #[derive(Debug, Clone, SurrealValue)]43 #[derive(Debug, Clone, SurrealValue)]
56 pub struct Enrollment {44 pub struct Enrollment {
57- id: EnrollmentId,45+ pub(crate) id: EnrollmentId,
58- course: CourseId,46+ pub(crate) course: CourseId,
59- user: UserId,47+ pub(crate) user: UserId,
60- enrolled_by: UserId,48+ pub(crate) enrolled_by: UserId,
61- source: Option<ClassGroupId>,49+ pub(crate) source: Option<ClassGroupId>,
62 }50 }
63 51
64 impl Enrollment {52 impl Enrollment {
@@ -82,223 +70,6 @@ impl Enrollment {
82 pub fn get_source(&self) -> Option<&ClassGroupId> {70 pub fn get_source(&self) -> Option<&ClassGroupId> {
83 self.source.as_ref()71 self.source.as_ref()
84 }72 }
85-
86- /// Enroll (idempotently) `user` into `course`. One row per (course, user),
87- /// keyed by a deterministic composite id, so concurrent enrolls of the same
88- /// pair converge on one row instead of racing the unique index into a 500:
89- /// the loser of the `CREATE` reads the winner's row back and returns it.
90- /// When the course carries a capacity, a full roster refuses new members
91- /// (409) — the seat is taken by a single-record conditional write on the
92- /// course row whose bound is the row's *own* `capacity` column, read inside
93- /// the same statement that spends the seat. A snapshot integer taken by a
94- /// read beforehand would be exactly the number a concurrent capacity PATCH
95- /// invalidates, which is what this promised and did not do. An already
96- /// enrolled user is returned as-is even when the roster is full, and never
97- /// charged a seat. The same claim is the delete guard's other half: it
98- /// matches nothing once the course row is gone, and while it holds a seat
99- /// the course cannot be deleted — so no roster row can outlive its course.
100- ///
101- /// On admissibility ([`crate::database::transaction_with_retry`]): the
102- /// `CREATE` here *can* answer "already exists", but only to a rival that
103- /// landed inside this very window — and the re-send then sees that row at
104- /// the `$held` gate and takes the other branch, so the loop converges
105- /// instead of re-asking a settled question. Same shape, same reason, as
106- /// [`crate::domain::class_pump::attach`].
107- pub async fn enroll(
108- course: &CourseId,
109- user: &UserId,
110- enrolled_by: &UserId,
111- db: &Database,
112- ) -> Result<Enrollment, AppError> {
113- if let Some(existing) = Self::read_for_user(course, user, db).await? {
114- return Self::disown_if_pumped(existing, db).await;
115- }
116- let enrollment = Enrollment {
117- id: EnrollmentId::composite(course, user),
118- course: course.clone(),
119- user: user.clone(),
120- enrolled_by: enrolled_by.clone(),
121- // Hand-placed: no source key at all is written, which is what makes
122- // a class sweep unable to take this row back.
123- source: None,
124- };
125- // CREATE, not UPSERT, and in the seat's own transaction: a duplicate has
126- // to be *seen*, or the pair's second writer would keep the seat it
127- // claimed for a row that already existed and the counter would drift
128- // above the roster forever.
129- //
130- // Parenthesized `??` throughout: `n ?? 0 < cap` parses as
131- // `n ?? (0 < cap)`, which is truthy for every row and would enroll past
132- // the capacity.
133- //
134- // The seat is claimed on the *course*, so the student's own row is
135- // claimed beside it ([`cap::role_claim`]): a demotion's sweep runs on a
136- // snapshot, and a row landing after it would count a seat for someone
137- // who may not hold one, with nothing left to re-sweep. It rides between
138- // the duplicate gate and the seat, so "you are already in" still
139- // outranks it and it outranks a full roster.
140- let held_by = cap::role_claim(
141- "usr",
142- &format!("!= '{}'", Role::Student.as_str()),
143- UNFIT_MARK,
144- );
145- let hold = held_by.join(";\n ");
146- let sql = format!(
147- "BEGIN TRANSACTION;
148- LET $held = (SELECT VALUE id FROM $id);
149- IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }};
150- {hold};
151- LET $seat = (UPDATE $course SET {ENROLLMENT_COUNT_FIELD} = \
152- ({ENROLLMENT_COUNT_FIELD} ?? 0) + 1 \
153- WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) < (capacity ?? $unlimited) \
154- RETURN VALUE id);
155- IF array::len($seat) = 0 {{ THROW '{FULL_MARK}' }};
156- CREATE $id CONTENT $row;
157- COMMIT TRANSACTION;"
158- );
159- // The process still sends its counter writes one at a time (see
160- // [`cap::counter_lock`]); this statement moves the same counter every
161- // cap claim does.
162- let _guard = cap::counter_lock().await;
163- let (mut result, mut errors) = transaction_with_retry(
164- db,
165- &sql,
166- &[
167- ("id".into(), enrollment.id.record().into_value()),
168- ("row".into(), enrollment.clone().into_value()),
169- ("course".into(), course.record().into_value()),
170- ("usr".into(), user.record().into_value()),
171- ("unlimited".into(), cap::UNLIMITED.into_value()),
172- ],
173- &[HELD_MARK, FULL_MARK, UNFIT_MARK],
174- )
175- .await?;
176- // Someone placed this pair first; their row is the answer, and no seat
177- // was spent finding that out. It is read first: it outranks the refusal
178- // below, and the gate aborts before the seat is touched.
179- if errors
180- .values()
181- .any(|error| error.to_string().contains(HELD_MARK))
182- {
183- return match Self::read_for_user(course, user, db).await? {
184- Some(existing) => Self::disown_if_pumped(existing, db).await,
185- None => Err(AppError::Internal("failed to enroll user".into())),
186- };
187- }
188- // Demoted while this ran: the same refusal the handler's own read makes
189- // a moment earlier, and the only one that can arrive after it.
190- if errors
191- .values()
192- .any(|error| error.to_string().contains(UNFIT_MARK))
193- {
194- return Err(AppError::Validation(ValidationError::Invalid {
195- field: "user_id",
196- reason: "only students can be enrolled in a course",
197- }));
198- }
199- // Full, or the course is gone — the conditional write matches nothing
200- // either way, and only this path pays for the read that tells them
201- // apart.
202- if errors
203- .values()
204- .any(|error| error.to_string().contains(FULL_MARK))
205- {
206- return match crate::db::course::read(db, course).await? {
207- Some(_) => Err(AppError::Conflict("the course is full")),
208- None => Err(AppError::NotFound),
209- };
210- }
211- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
212- return Err(error.into());
213- }
214- // Slots count BEGIN, two LETs and two IFs, plus the holder claim's own
215- // statements — counted, not tallied by hand, so a statement added there
216- // cannot read back the wrong result.
217- result
218- .take::<Vec<Enrollment>>(5 + held_by.len())?
219- .into_iter()
220- .next()
221- .ok_or_else(|| AppError::Internal("failed to enroll user".into()))
222- }
223-
224- /// A hand enroll landing on a row a class pumped takes the row *off* the
225- /// class: `source` goes, so no later class sweep can unenroll a student an
226- /// operator placed on purpose. The mirror of the rule the sweep already
227- /// holds in the other direction — a manual unenroll wins, permanently — and
228- /// without it "hand-placed" was a state only a first enroll could reach.
229- ///
230- /// `UNSET`, not `= NONE`: absence *is* the meaning of this column (see the
231- /// struct doc), and it is what a hand enroll writes on the create path.
232- async fn disown_if_pumped(existing: Enrollment, db: &Database) -> Result<Enrollment, AppError> {
233- if existing.source.is_none() {
234- return Ok(existing);
235- }
236- let mut result = db
237- .query("UPDATE $id UNSET source RETURN AFTER")
238- .bind(("id", existing.id.record()))
239- .await?
240- .check()?;
241- // A row that is no longer there is not an internal error: an unenroll
242- // (or the class sweep a role change runs) landing between the read
243- // above and this write matches nothing, and the caller asked to be
244- // enrolled — which they were, by the row this call was handed. The
245- // disown is all that is lost, and it is lost to a delete that took the
246- // whole row with it.
247- Ok(result
248- .take::<Vec<Enrollment>>(0)?
249- .into_iter()
250- .next()
251- .unwrap_or(existing))
252- }
253-
254- /// Some(_) iff `user` is enrolled in `course` — the grading gate.
255- pub async fn read_for_user(
256- course: &CourseId,
257- user: &UserId,
258- db: &Database,
259- ) -> Result<Option<Enrollment>, AppError> {
260- let mut result = db
261- .query("SELECT * FROM enrollment WHERE course = $course AND user = $usr LIMIT 1")
262- .bind(("course", course.record()))
263- .bind(("usr", user.record()))
264- .await?
265- .check()?;
266- Ok(result.take::<Vec<Enrollment>>(0)?.into_iter().next())
267- }
268-
269- pub async fn list_for_course(
270- course: &CourseId,
271- limit: Option<i64>,
272- offset: i64,
273- db: &Database,
274- ) -> Result<(Vec<Enrollment>, i64), AppError> {
275- PagedList::new("enrollment WHERE course = $course", "ORDER BY id DESC")
276- .bind("course", course.record())
277- .run(limit, offset, db)
278- .await
279- }
280-
281- pub async fn remove(
282- course: &CourseId,
283- user: &UserId,
284- db: &Database,
285- ) -> Result<Option<Enrollment>, AppError> {
286- // The seat comes back in the same transaction as the row that held it,
287- // so nothing but a lost transaction can drift the counter.
288- let mut result = db
289- .query(
290- "BEGIN TRANSACTION;
291- LET $gone = (DELETE enrollment WHERE course = $course AND user = $usr RETURN BEFORE);
292- UPDATE $course SET enrollment_count = math::max([(enrollment_count ?? 0) - array::len($gone), 0]);
293- RETURN $gone;
294- COMMIT TRANSACTION;",
295- )
296- .bind(("course", course.record()))
297- .bind(("usr", user.record()))
298- .await?
299- .check()?;
300- Ok(result.take::<Vec<Enrollment>>(3)?.into_iter().next())
301- }
302 }73 }
303 74
304 #[cfg(test)]75 #[cfg(test)]
@@ -331,120 +102,4 @@ mod tests {
331 let decoded = Enrollment::from_value(Value::Object(object)).unwrap();102 let decoded = Enrollment::from_value(Value::Object(object)).unwrap();
332 assert_eq!(decoded.get_source(), None);103 assert_eq!(decoded.get_source(), None);
333 }104 }
334-
335- /// The boot repair of `enrollment_count` **against a real server**, and
336- /// `#[ignore]`d for it: the pass counts rows off `enrollment`'s indexed
337- /// `course` field, and an aggregate over an indexed field is exactly where
338- /// the embedded engine and the server are known to differ (`count()` comes
339- /// back `{count: N}` from one and a bare int from the other, which
340- /// `option<int>` would refuse). `array::len` over ids is the spelling that
341- /// dodges it — this is what proves it on the store that bites.
342- ///
343- /// Both halves in one boot: `staff` is the row the sweep deletes (their
344- /// seat must come back), and `empty` is the course a *past* sweep already
345- /// stranded — count above zero with no rows left, so it forms no group and
346- /// only a per-course pass ever visits it. The second `migrate` pins that the
347- /// repair converges rather than overwriting: it must write nothing.
348- #[tokio::test]
349- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
350- async fn the_count_repair_recounts_on_a_real_server() {
351- let (db, _serialized) = crate::database::init_test_server("enrollment_repair").await;
352- db.query(
353- "CREATE user:t SET username = 't', password_hash = 'x', role = 'teacher';
354- CREATE user:a SET username = 'a', password_hash = 'x', role = 'student';
355- CREATE user:b SET username = 'b', password_hash = 'x', role = 'student';
356- CREATE course:live SET creator = user:t, title = 'l', description = '',
357- enrollment_count = 9;
358- CREATE course:empty SET creator = user:t, title = 'e', description = '',
359- enrollment_count = 4;
360- CREATE enrollment:live_a SET course = course:live, user = user:a, enrolled_by = user:t;
361- CREATE enrollment:live_b SET course = course:live, user = user:b, enrolled_by = user:t;
362- CREATE enrollment:live_t SET course = course:live, user = user:t, enrolled_by = user:t;",
363- )
364- .await
365- .unwrap()
366- .check()
367- .unwrap();
368-
369- async fn counts(db: &Database) -> Vec<i64> {
370- let mut result = db
371- .query("SELECT VALUE enrollment_count FROM course ORDER BY id")
372- .await
373- .unwrap()
374- .check()
375- .unwrap();
376- result.take::<Vec<i64>>(0).unwrap()
377- }
378-
379- crate::database::migrate(db.as_ref()).await.unwrap();
380- // `course:empty` sorts before `course:live`: stranded count cleared, and
381- // the live course recounted to its two students — the teacher's row was
382- // swept and handed its seat back in the same boot.
383- assert_eq!(counts(&db).await, vec![0, 2]);
384-
385- crate::database::migrate(db.as_ref()).await.unwrap();
386- assert_eq!(counts(&db).await, vec![0, 2], "the repair converges");
387- }
388-
389- /// A pumped row that vanishes under the disown — a concurrent unenroll, or
390- /// the sweep a role change runs — must answer the row the caller was
391- /// handed, not a 500. The `UPDATE` matches nothing and used to fall through
392- /// to `AppError::Internal`, turning a race the old code answered 200 into a
393- /// server error on an ordinary `POST /courses/{id}/enrollments`.
394- #[tokio::test]
395- async fn a_vanished_row_is_not_an_internal_error() {
396- let db = crate::database::init_mem().await.unwrap();
397- let class = crate::domain::class_group::ClassGroupId::from_key("9a");
398- let course = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T");
399- let student = UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8U");
400- // Never written: the same store state a delete in the window leaves.
401- let ghost = Enrollment {
402- id: EnrollmentId::composite(&course, &student),
403- course: course.clone(),
404- user: student.clone(),
405- enrolled_by: UserId::from_key("mgr"),
406- source: Some(class),
407- };
408-
409- let answered = Enrollment::disown_if_pumped(ghost, &db).await.unwrap();
410- assert_eq!(answered.get_user(), &student);
411- assert_eq!(answered.get_course(), &course);
412- }
413-
414- /// And the other half of "absence is the meaning": a hand-placed enrollment
415- /// must store *no* source key, or a class sweep would take back a row it
416- /// never wrote. Asserted on the stored row, not the returned one.
417- #[tokio::test]
418- async fn a_hand_placed_enrollment_stores_no_source_key() {
419- use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
420-
421- let db = crate::database::init_mem().await.unwrap();
422- let teacher = UserId::from_key("teacher");
423- let course = crate::db::course::create(
424- &db,
425- &teacher,
426- CourseTitle::try_new("algebra").unwrap(),
427- CourseDescription::try_new("").unwrap(),
428- CourseKind::course(),
429- None,
430- None,
431- )
432- .await
433- .unwrap();
434- Enrollment::enroll(course.get_id(), &UserId::from_key("student"), &teacher, &db)
435- .await
436- .unwrap();
437-
438- let mut result = db
439- .query("SELECT VALUE 'source' IN object::keys($this) FROM enrollment")
440- .await
441- .unwrap()
442- .check()
443- .unwrap();
444- assert_eq!(
445- result.take::<Vec<bool>>(0).unwrap(),
446- vec![false],
447- "a hand-placed row may carry no source key"
448- );
449- }
450 }105 }
src/domain/event.rsmodified+7 -5
@@ -7,7 +7,7 @@ use crate::database::{Database, transaction_with_retry};
7 use crate::domain::class_group::ClassGroupId;7 use crate::domain::class_group::ClassGroupId;
8 use crate::domain::class_member::{ClassMember, ClassMemberId};8 use crate::domain::class_member::{ClassMember, ClassMemberId};
9 use crate::domain::course::CourseId;9 use crate::domain::course::CourseId;
10-use crate::domain::enrollment::Enrollment;10+
11 use crate::db::field_update::FieldUpdate;11 use crate::db::field_update::FieldUpdate;
12 use crate::domain::monotonic_id::next_ulid;12 use crate::domain::monotonic_id::next_ulid;
13 use crate::domain::registration::Registration;13 use crate::domain::registration::Registration;
@@ -121,9 +121,11 @@ impl EventAudience {
121 EventAudience::School => Ok(true),121 EventAudience::School => Ok(true),
122 EventAudience::Role { role } => Ok(user.get_role() == *role),122 EventAudience::Role { role } => Ok(user.get_role() == *role),
123 EventAudience::Course { course } => {123 EventAudience::Course { course } => {
124- Ok(Enrollment::read_for_user(course, user.get_id(), db)124+ Ok(
125- .await?125+ crate::db::enrollment::read_for_user(db, course, user.get_id())
126- .is_some())126+ .await?
127+ .is_some(),
128+ )
127 }129 }
128 // The (class, user) pair is the membership row's own id, so the130 // The (class, user) pair is the membership row's own id, so the
129 // point check is a single select — no scan, no index needed.131 // point check is a single select — no scan, no index needed.
@@ -158,7 +160,7 @@ impl EventAudience {
158 .map(|user| user.get_id().clone())160 .map(|user| user.get_id().clone())
159 .collect()),161 .collect()),
160 EventAudience::Course { course } => {162 EventAudience::Course { course } => {
161- Ok(Enrollment::list_for_course(course, None, 0, db)163+ Ok(crate::db::enrollment::list_for_course(db, course, None, 0)
162 .await?164 .await?
163 .0165 .0
164 .iter()166 .iter()
src/migration_sql.rsmodified+1 -1
@@ -1035,7 +1035,7 @@ pub const BACKFILL: &str = "
1035 --1035 --
1036 -- Counting the rows cannot read *low*. The counter has exactly one meaning —1036 -- Counting the rows cannot read *low*. The counter has exactly one meaning —
1037 -- the live enrollment rows of this course — and every writer moves it with1037 -- the live enrollment rows of this course — and every writer moves it with
1038- -- the row in one transaction (`Enrollment::enroll`/`remove`, `set_role`'s1038+ -- the row in one transaction (`db::enrollment`'s `enroll`/`remove`, `set_role`'s
1039 -- demotion sweep, the class pump's attach and detach); `Course::delete` takes1039 -- demotion sweep, the class pump's attach and detach); `Course::delete` takes
1040 -- the rows *and* the course together, so no cascade leaves counted rows1040 -- the rows *and* the course together, so no cascade leaves counted rows
1041 -- behind. That is what separates it from the lifetime tallies below, which1041 -- behind. That is what separates it from the lifetime tallies below, which
src/service/enrollment.rsadded+70 -0
@@ -0,0 +1,70 @@
1+//! Enrollment workflows: the target-user gates the enroll/unenroll HTTP
2+//! handlers pay (the target must exist and still be a student; unenrolling a
3+//! pair with no row is a 404) wrapped around the atomic seat claim in
4+//! [`crate::db::enrollment`].
5+
6+use crate::database::Database;
7+use crate::db::enrollment;
8+use crate::domain::course::CourseId;
9+use crate::domain::enrollment::Enrollment;
10+use crate::domain::role::Role;
11+use crate::domain::user::{User, UserId};
12+use crate::error::{AppError, ValidationError};
13+
14+/// Enroll `target` into `course` on `enrolled_by`'s orders. The target-user
15+/// gates first — they are validation of the request, so a 400, and they run
16+/// in the order the handler used to: an unknown user outranks a non-student
17+/// one — then the claim (idempotent for an already-enrolled pair; 409 on a
18+/// full roster; 404 when the course is gone).
19+pub async fn enroll(
20+ db: &Database,
21+ course: &CourseId,
22+ target: &UserId,
23+ enrolled_by: &UserId,
24+) -> Result<Enrollment, AppError> {
25+ let Some(target_user) = User::read(target, db).await? else {
26+ return Err(AppError::Validation(ValidationError::Invalid {
27+ field: "user_id",
28+ reason: "target user does not exist",
29+ }));
30+ };
31+
32+ // Enrollment is student membership: it gates sitting exams, being graded,
33+ // and appearing on a lesson roster — all student-only. Staff run courses,
34+ // they don't enroll in them.
35+ if target_user.get_role() != Role::Student {
36+ return Err(AppError::Validation(ValidationError::Invalid {
37+ field: "user_id",
38+ reason: "only students can be enrolled in a course",
39+ }));
40+ }
41+
42+ enrollment::enroll(db, course, target, enrolled_by).await
43+}
44+
45+/// Unenroll `target` from `course`. `NotFound` when the pair holds no row —
46+/// unenrolling someone who was never enrolled removed nothing, so the web
47+/// layer must not pretend they did.
48+pub async fn unenroll(db: &Database, course: &CourseId, target: &UserId) -> Result<(), AppError> {
49+ enrollment::remove(db, course, target)
50+ .await?
51+ .ok_or(AppError::NotFound)?;
52+ Ok(())
53+}
54+
55+pub async fn read_for_user(
56+ db: &Database,
57+ course: &CourseId,
58+ user: &UserId,
59+) -> Result<Option<Enrollment>, AppError> {
60+ enrollment::read_for_user(db, course, user).await
61+}
62+
63+pub async fn list_for_course(
64+ db: &Database,
65+ course: &CourseId,
66+ limit: Option<i64>,
67+ offset: i64,
68+) -> Result<(Vec<Enrollment>, i64), AppError> {
69+ enrollment::list_for_course(db, course, limit, offset).await
70+}
src/service/exam_attempt.rsmodified+2 -2
@@ -8,7 +8,7 @@ use crate::database::Database;
8 use crate::db::cap;8 use crate::db::cap;
9 use crate::domain::badge;9 use crate::domain::badge;
10 use crate::domain::course::Course;10 use crate::domain::course::Course;
11-use crate::domain::enrollment::Enrollment;11+
12 use crate::domain::exam::{Exam, ExamId};12 use crate::domain::exam::{Exam, ExamId};
13 use crate::domain::exam_answer::ExamAnswer;13 use crate::domain::exam_answer::ExamAnswer;
14 use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt, ExamAttemptId};14 use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt, ExamAttemptId};
@@ -97,7 +97,7 @@ pub async fn ensure_student_now(user: &UserId, db: &Database) -> Result<(), AppE
97 /// an unenrollment mid-exam cuts them too. Finishing stays exempt: like the97 /// an unenrollment mid-exam cuts them too. Finishing stays exempt: like the
98 /// rejoin lock, submitting what's already saved writes nothing new.98 /// rejoin lock, submitting what's already saved writes nothing new.
99 pub async fn ensure_enrolled(exam: &Exam, user: &UserId, db: &Database) -> Result<(), AppError> {99 pub async fn ensure_enrolled(exam: &Exam, user: &UserId, db: &Database) -> Result<(), AppError> {
100- if Enrollment::read_for_user(exam.get_course(), user, db)100+ if crate::db::enrollment::read_for_user(db, exam.get_course(), user)
101 .await?101 .await?
102 .is_none()102 .is_none()
103 {103 {
src/service/mod.rsmodified+1 -0
@@ -3,6 +3,7 @@
3 3
4 pub mod appointment;4 pub mod appointment;
5 pub mod course;5 pub mod course;
6+pub mod enrollment;
6 pub mod exam_attempt;7 pub mod exam_attempt;
7 pub mod note;8 pub mod note;
8 pub mod payment_ledger;9 pub mod payment_ledger;
src/web/boards.rsmodified+8 -7
@@ -35,7 +35,6 @@ use crate::domain::board_stroke::BoardStroke;
35 use crate::domain::class_group::{ClassGroup, ClassGroupId};35 use crate::domain::class_group::{ClassGroup, ClassGroupId};
36 use crate::domain::class_member::ClassMember;36 use crate::domain::class_member::ClassMember;
37 use crate::domain::course::CourseId;37 use crate::domain::course::CourseId;
38-use crate::domain::enrollment::Enrollment;
39 use crate::domain::event::{Event, EventId};38 use crate::domain::event::{Event, EventId};
40 use crate::domain::role::Role;39 use crate::domain::role::Role;
41 use crate::domain::user::{User, UserId};40 use crate::domain::user::{User, UserId};
@@ -753,12 +752,14 @@ impl InviteSource {
753 "only the course creator, an assigned teacher, or a manager/admin can invite its roster",752 "only the course creator, an assigned teacher, or a manager/admin can invite its roster",
754 ));753 ));
755 }754 }
756- Ok(Enrollment::list_for_course(course.get_id(), None, 0, db)755+ Ok(
757- .await?756+ crate::service::enrollment::list_for_course(db, course.get_id(), None, 0)
758- .0757+ .await?
759- .iter()758+ .0
760- .map(|enrollment| enrollment.get_user().clone())759+ .iter()
761- .collect())760+ .map(|enrollment| enrollment.get_user().clone())
761+ .collect(),
762+ )
762 }763 }
763 InviteSource::Event { event } => {764 InviteSource::Event { event } => {
764 if !user.get_role().at_least(Role::Teacher) {765 if !user.get_role().at_least(Role::Teacher) {
src/web/courses.rsmodified+17 -34
@@ -240,7 +240,7 @@ pub(crate) async fn can_view_course(
240 return Ok(true);240 return Ok(true);
241 }241 }
242 Ok(242 Ok(
243- Enrollment::read_for_user(course.get_id(), user.get_id(), db)243+ service::enrollment::read_for_user(db, course.get_id(), user.get_id())
244 .await?244 .await?
245 .is_some(),245 .is_some(),
246 )246 )
@@ -265,7 +265,10 @@ pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result<Vec<Co
265 } else {265 } else {
266 Vec::new()266 Vec::new()
267 };267 };
268- for course in service::course::list_enrolled(db, user.get_id(), None, 0).await?.0 {268+ for course in service::course::list_enrolled(db, user.get_id(), None, 0)
269+ .await?
270+ .0
271+ {
269 if !courses272 if !courses
270 .iter()273 .iter()
271 .any(|known| known.get_id() == course.get_id())274 .any(|known| known.get_id() == course.get_id())
@@ -401,7 +404,8 @@ async fn my_courses(
401 Query(page): Query<PageParams>,404 Query(page): Query<PageParams>,
402 ) -> Result<Json<Page<CourseResponse>>, AppError> {405 ) -> Result<Json<Page<CourseResponse>>, AppError> {
403 let (limit, offset) = page.resolve()?;406 let (limit, offset) = page.resolve()?;
404- let (courses, total) = service::course::list_enrolled(&st.db, user.get_id(), limit, offset).await?;407+ let (courses, total) =
408+ service::course::list_enrolled(&st.db, user.get_id(), limit, offset).await?;
405 let people = person_map(courses.iter().flat_map(course_people), &st.db).await?;409 let people = person_map(courses.iter().flat_map(course_people), &st.db).await?;
406 let items = courses410 let items = courses
407 .iter()411 .iter()
@@ -690,25 +694,9 @@ async fn enroll(
690 service::course::require_open(&st.db, &course).await?;694 service::course::require_open(&st.db, &course).await?;
691 695
692 let target = UserId::from_key(&req.user_id);696 let target = UserId::from_key(&req.user_id);
693- let Some(target_user) = User::read(&target, &st.db).await? else {697+ let enrollment =
694- return Err(AppError::Validation(ValidationError::Invalid {698+ service::enrollment::enroll(&st.db, course.get_id(), &target, user.get_id()).await?;
695- field: "user_id",699+ let people = person_map([target, user.get_id().clone()], &st.db).await?;
696- reason: "target user does not exist",
697- }));
698- };
699-
700- // Enrollment is student membership: it gates sitting exams, being graded,
701- // and appearing on a lesson roster — all student-only. Staff run courses,
702- // they don't enroll in them.
703- if target_user.get_role() != Role::Student {
704- return Err(AppError::Validation(ValidationError::Invalid {
705- field: "user_id",
706- reason: "only students can be enrolled in a course",
707- }));
708- }
709-
710- let enrollment = Enrollment::enroll(course.get_id(), &target, user.get_id(), &st.db).await?;
711- let people = PersonRef::map_of(&[&target_user, &user]);
712 Ok(Json(EnrollmentResponse::new(&enrollment, &people)))700 Ok(Json(EnrollmentResponse::new(&enrollment, &people)))
713 }701 }
714 702
@@ -746,7 +734,8 @@ async fn list_roster(
746 "only the course creator, an assigned teacher, or a manager/admin can list the roster",734 "only the course creator, an assigned teacher, or a manager/admin can list the roster",
747 ));735 ));
748 }736 }
749- let (rows, total) = Enrollment::list_for_course(course.get_id(), limit, offset, &st.db).await?;737+ let (rows, total) =
738+ service::enrollment::list_for_course(&st.db, course.get_id(), limit, offset).await?;
750 // Join people onto the page alone — the lookup shrinks with the window.739 // Join people onto the page alone — the lookup shrinks with the window.
751 let people = person_map(740 let people = person_map(
752 rows.iter()741 rows.iter()
@@ -795,10 +784,7 @@ async fn unenroll(
795 ));784 ));
796 }785 }
797 service::course::require_open(&st.db, &course).await?;786 service::course::require_open(&st.db, &course).await?;
798- let removed = Enrollment::remove(course.get_id(), &UserId::from_key(&target), &st.db).await?;787+ service::enrollment::unenroll(&st.db, course.get_id(), &UserId::from_key(&target)).await?;
799- if removed.is_none() {
800- return Err(AppError::NotFound);
801- }
802 Ok(StatusCode::NO_CONTENT)788 Ok(StatusCode::NO_CONTENT)
803 }789 }
804 790
@@ -1359,13 +1345,10 @@ mod tests {
1359 let db = init_mem().await.unwrap();1345 let db = init_mem().await.unwrap();
1360 let creator = user("creator", Role::Teacher, &db).await;1346 let creator = user("creator", Role::Teacher, &db).await;
1361 let assigned = user("assigned", Role::Teacher, &db).await;1347 let assigned = user("assigned", Role::Teacher, &db).await;
1362- let course = service::course::assign_teacher(1348+ let course =
1363- &db,1349+ service::course::assign_teacher(&db, &course(&creator, &db).await, assigned.get_id())
1364- &course(&creator, &db).await,1350+ .await
1365- assigned.get_id(),1351+ .unwrap();
1366- )
1367- .await
1368- .unwrap();
1369 // Still teacher+: untouched by the floor.1352 // Still teacher+: untouched by the floor.
1370 assert!(can_manage_course(&course, &assigned));1353 assert!(can_manage_course(&course, &assigned));
1371 // ...but never an owner, assigned or not.1354 // ...but never an owner, assigned or not.
src/web/exams/attempts.rsmodified+2 -1
@@ -327,7 +327,8 @@ pub(crate) async fn live_snapshot(
327 db: &Database,327 db: &Database,
328 ) -> Result<ExamLiveResponse, AppError> {328 ) -> Result<ExamLiveResponse, AppError> {
329 let now = Timestamp::now();329 let now = Timestamp::now();
330- let (roster, _) = Enrollment::list_for_course(exam.get_course(), None, 0, db).await?;330+ let (roster, _) =
331+ crate::service::enrollment::list_for_course(db, exam.get_course(), None, 0).await?;
331 // Per student: their latest sitting (the one the monitor shows) plus how332 // Per student: their latest sitting (the one the monitor shows) plus how
332 // many they've used.333 // many they've used.
333 let mut attempts: HashMap<String, ExamAttempt> = HashMap::new();334 let mut attempts: HashMap<String, ExamAttempt> = HashMap::new();
src/web/exams/mod.rsmodified+2 -2
@@ -16,7 +16,7 @@ use crate::domain::answer_image::AnswerImage;
16 use crate::domain::badge;16 use crate::domain::badge;
17 use crate::domain::bank_question::{BankQuestion, BankQuestionId};17 use crate::domain::bank_question::{BankQuestion, BankQuestionId};
18 use crate::domain::bank_question_image::BankQuestionImage;18 use crate::domain::bank_question_image::BankQuestionImage;
19-use crate::domain::enrollment::Enrollment;19+
20 use crate::domain::exam::{20 use crate::domain::exam::{
21 Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode,21 Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode,
22 ExamSchedule, ExamTitle,22 ExamSchedule, ExamTitle,
@@ -688,7 +688,7 @@ async fn grade(
688 }688 }
689 689
690 // ... and be enrolled in the exam's course.690 // ... and be enrolled in the exam's course.
691- if Enrollment::read_for_user(exam.get_course(), &target, &st.db)691+ if service::enrollment::read_for_user(&st.db, exam.get_course(), &target)
692 .await?692 .await?
693 .is_none()693 .is_none()
694 {694 {
src/web/homework.rsmodified+14 -10
@@ -20,7 +20,7 @@ use crate::constant::{MAX_HOMEWORK_ASSIGNED, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVE
20 use crate::database::Database;20 use crate::database::Database;
21 use crate::domain::badge;21 use crate::domain::badge;
22 use crate::domain::course::{Course, CourseId};22 use crate::domain::course::{Course, CourseId};
23-use crate::domain::enrollment::Enrollment;23+
24 use crate::domain::exam_result::Mark;24 use crate::domain::exam_result::Mark;
25 use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle};25 use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle};
26 use crate::domain::homework_file::{HomeworkFile, HomeworkFileId};26 use crate::domain::homework_file::{HomeworkFile, HomeworkFileId};
@@ -135,7 +135,7 @@ pub(crate) async fn resolve_assigned(
135 let mut users = Vec::with_capacity(keys.len());135 let mut users = Vec::with_capacity(keys.len());
136 for key in keys {136 for key in keys {
137 let user = UserId::from_key(&key);137 let user = UserId::from_key(&key);
138- if Enrollment::read_for_user(course, &user, db)138+ if service::enrollment::read_for_user(db, course, &user)
139 .await?139 .await?
140 .is_none()140 .is_none()
141 {141 {
@@ -480,7 +480,10 @@ async fn delete_homework(
480 /// Submitting is course content, so leaving the course closes it; re-checked on480 /// Submitting is course content, so leaving the course closes it; re-checked on
481 /// every submission and file write, so an unenrollment mid-task bites the next.481 /// every submission and file write, so an unenrollment mid-task bites the next.
482 async fn ensure_enrolled(course: &CourseId, user: &UserId, db: &Database) -> Result<(), AppError> {482 async fn ensure_enrolled(course: &CourseId, user: &UserId, db: &Database) -> Result<(), AppError> {
483- if Enrollment::read_for_user(course, user, db).await?.is_none() {483+ if service::enrollment::read_for_user(db, course, user)
484+ .await?
485+ .is_none()
486+ {
484 return Err(AppError::Forbidden(487 return Err(AppError::Forbidden(
485 "you are not enrolled in this homework's course",488 "you are not enrolled in this homework's course",
486 ));489 ));
@@ -1177,7 +1180,7 @@ async fn grade_homework(
1177 }1180 }
1178 1181
1179 // ... enrolled in the homework's course ...1182 // ... enrolled in the homework's course ...
1180- if Enrollment::read_for_user(homework.get_course(), &target, &st.db)1183+ if service::enrollment::read_for_user(&st.db, homework.get_course(), &target)
1181 .await?1184 .await?
1182 .is_none()1185 .is_none()
1183 {1186 {
@@ -1355,12 +1358,13 @@ async fn list_homework_submissions(
1355 }1358 }
1356 let submissions = HomeworkSubmission::list_for_homework(homework.get_id(), &st.db).await?;1359 let submissions = HomeworkSubmission::list_for_homework(homework.get_id(), &st.db).await?;
1357 let results = HomeworkResult::list_for_homework(homework.get_id(), &st.db).await?;1360 let results = HomeworkResult::list_for_homework(homework.get_id(), &st.db).await?;
1358- let enrolled: Vec<String> = Enrollment::list_for_course(course.get_id(), None, 0, &st.db)1361+ let enrolled: Vec<String> =
1359- .await?1362+ service::enrollment::list_for_course(&st.db, course.get_id(), None, 0)
1360- .01363+ .await?
1361- .iter()1364+ .0
1362- .map(|enrollment| enrollment.get_user().key().to_string())1365+ .iter()
1363- .collect();1366+ .map(|enrollment| enrollment.get_user().key().to_string())
1367+ .collect();
1364 // The audience: the assigned subset as stored, or — whole-course — whoever1368 // The audience: the assigned subset as stored, or — whole-course — whoever
1365 // is enrolled right now. Anyone outside it who still owns a submission or1369 // is enrolled right now. Anyone outside it who still owns a submission or
1366 // grade is appended rather than dropped: their stale rows are exactly what1370 // grade is appended rather than dropped: their stale rows are exactly what
src/web/sessions.rsmodified+2 -2
@@ -14,7 +14,7 @@ use crate::domain::attendance::AttendanceStatus;
14 use crate::domain::badge;14 use crate::domain::badge;
15 use crate::domain::course::Course;15 use crate::domain::course::Course;
16 use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic};16 use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic};
17-use crate::domain::enrollment::Enrollment;17+
18 use crate::domain::role::Role;18 use crate::domain::role::Role;
19 use crate::domain::session_attendance::SessionAttendance;19 use crate::domain::session_attendance::SessionAttendance;
20 use crate::domain::timestamp::Timestamp;20 use crate::domain::timestamp::Timestamp;
@@ -349,7 +349,7 @@ async fn mark_roll_call(
349 reason: "only students can be marked present in a lesson",349 reason: "only students can be marked present in a lesson",
350 }));350 }));
351 }351 }
352- if Enrollment::read_for_user(session.get_course(), &target, &st.db)352+ if service::enrollment::read_for_user(&st.db, session.get_course(), &target)
353 .await?353 .await?
354 .is_none()354 .is_none()
355 {355 {
tests/regress_role_sweep.rsmodified+4 -4
@@ -21,10 +21,10 @@ mod common;
21 use axum::http::StatusCode;21 use axum::http::StatusCode;
22 use common::{app_and_db, login_as, me_id, send};22 use common::{app_and_db, login_as, me_id, send};
23 use hezarfen_backend::database::Database;23 use hezarfen_backend::database::Database;
24+use hezarfen_backend::db::enrollment;
24 use hezarfen_backend::domain::class_group::{ClassGroup, ClassGroupId, ClassName};25 use hezarfen_backend::domain::class_group::{ClassGroup, ClassGroupId, ClassName};
25 use hezarfen_backend::domain::class_member::ClassMember;26 use hezarfen_backend::domain::class_member::ClassMember;
26 use hezarfen_backend::domain::course::CourseId;27 use hezarfen_backend::domain::course::CourseId;
27-use hezarfen_backend::domain::enrollment::Enrollment;
28 use hezarfen_backend::domain::event::EventId;28 use hezarfen_backend::domain::event::EventId;
29 use hezarfen_backend::domain::registration::Registration;29 use hezarfen_backend::domain::registration::Registration;
30 use hezarfen_backend::domain::role::Role;30 use hezarfen_backend::domain::role::Role;
@@ -272,7 +272,7 @@ async fn an_enrollment_is_refused_once_the_student_is_demoted() {
272 let course = a_course(&app, &teacher).await;272 let course = a_course(&app, &teacher).await;
273 demote(&student, Role::Teacher, &db).await;273 demote(&student, Role::Teacher, &db).await;
274 274
275- let refused = Enrollment::enroll(&course, &student, &UserId::from_key("staff"), &db).await;275+ let refused = enrollment::enroll(&db, &course, &student, &UserId::from_key("staff")).await;
276 assert!(276 assert!(
277 refused.is_err(),277 refused.is_err(),
278 "only students hold enrollments: {refused:?}"278 "only students hold enrollments: {refused:?}"
@@ -293,13 +293,13 @@ async fn an_enrollment_never_survives_the_demotion_it_raced() {
293 let course = a_course(&app, &teacher).await;293 let course = a_course(&app, &teacher).await;
294 // The bait: a row the sweep will delete, which is what holds it open.294 // The bait: a row the sweep will delete, which is what holds it open.
295 let earlier = CourseId::from_key(&common::create_course(&app, &teacher, "fizik").await);295 let earlier = CourseId::from_key(&common::create_course(&app, &teacher, "fizik").await);
296- Enrollment::enroll(&earlier, &student, &UserId::from_key("staff"), &db)296+ enrollment::enroll(&db, &earlier, &student, &UserId::from_key("staff"))
297 .await297 .await
298 .unwrap();298 .unwrap();
299 hold_the_sweep("enrollment", &db).await;299 hold_the_sweep("enrollment", &db).await;
300 300
301 let demoting = demote_in_the_window(&student, Role::Teacher, &db).await;301 let demoting = demote_in_the_window(&student, Role::Teacher, &db).await;
302- let enrolled = Enrollment::enroll(&course, &student, &UserId::from_key("staff"), &db).await;302+ let enrolled = enrollment::enroll(&db, &course, &student, &UserId::from_key("staff")).await;
303 still_running(&demoting);303 still_running(&demoting);
304 demoting.await.unwrap();304 demoting.await.unwrap();
305 305