forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

enrollment.rs478 lines, 19.4 KiBHistoryRawDownload
1//! The `enrollment` table: the roster read and listing, the counter-returning
2//! delete, and the enroll claim — one transaction that checks the pair free
3//! and the member still a student. The target-user gates the HTTP handlers pay
4//! live in [`crate::service::enrollment`].
5//!
6//! Enrollment keys on the *instance* now (D4): a student is enrolled in the
7//! Matematik that 5-A teaches, not in a school-wide Matematik row. The seat
8//! gate is gone with the catalog's `capacity` (D5) — the roster counter is a
9//! count, not a ceiling — so the only refusals left are "already enrolled"
10//! (which is an idempotent hit, not an error) and "that user is not a
11//! student".
12
13use crate::database::{Database, tx_with_retry, unique_violation};
14use crate::db::page::PagedList;
15use crate::domain::class_course::ClassCourseId;
16use crate::domain::class_group::ClassGroupId;
17use crate::domain::course::CourseId;
18use crate::domain::enrollment::Enrollment;
19use crate::domain::exam::ExamId;
20use crate::domain::role::Role;
21use crate::domain::timestamp::Timestamp;
22use crate::domain::user::UserId;
23use crate::error::{AppError, ValidationError};
24
25/// What [`enroll`]'s transaction settled on.
26enum Verdict {
27 /// This pair already holds a row.
28 Held,
29 /// The person being enrolled is no longer a student.
30 Unfit,
31 /// The row is written.
32 Made(Enrollment),
33}
34
35/// Enroll (idempotently) `user` into one instance. The table's primary key
36/// *is* the (instance, user) pair, so concurrent enrolls of the same pair
37/// converge on one row instead of racing into a 500: the loser reads the
38/// winner's row back and returns it. An already enrolled user is returned
39/// as-is — the counter moves once, and never twice for one row — except that a
40/// row a class pumped is *disowned* on the way out (see
41/// [`disown_if_pumped`]): the operator's hand enroll is what the row now
42/// records.
43///
44/// `source` is the class the roster pump wrote this row on behalf of, or
45/// `None` for a hand-placed (elective) enrollment. The two halves of that
46/// rule: only a row carrying the key is a class's to take back
47/// ([`crate::db::class_pump`]), and a hand unenroll wins permanently.
48///
49/// The `enrollment_count` counter moves in the same statement as the row (a
50/// refused insert takes its own bump back), so the instance's roster size
51/// cannot drift from the rows behind it.
52///
53/// Gate order is the old THROW order: an existing pair outranks the role
54/// check. The role check takes the user row `FOR NO KEY UPDATE`, the same row
55/// a demotion cascade updates before its sweep, so grant and demotion
56/// serialize on the row lock in both directions — a row landing after the
57/// sweep is impossible, and a demotion landing before this check refuses it.
58pub async fn enroll(
59 db: &Database,
60 class_course: &ClassCourseId,
61 user: &UserId,
62 enrolled_by: &UserId,
63 source: Option<&ClassGroupId>,
64) -> Result<Enrollment, AppError> {
65 if let Some(existing) = read_for_user(db, class_course, user).await? {
66 return disown_if_pumped(db, existing).await;
67 }
68 let instance = class_course.clone();
69 let (user_id, enrolled_by_id) = (*user, *enrolled_by);
70 let source_id = source.map(ClassGroupId::uuid);
71 let created_at = Timestamp::now();
72 let verdict = tx_with_retry(db, false, async move |tx| {
73 // The duplicate gate rides ahead of the role check, so "you are
74 // already in" still outranks everything.
75 let held = sqlx::query!(
76 r#"SELECT 1 AS "one" FROM enrollment WHERE class_course = $1 AND app_user = $2"#,
77 instance.uuid(),
78 user_id.uuid(),
79 )
80 .fetch_optional(&mut *tx)
81 .await?;
82 if held.is_some() {
83 return Ok(Verdict::Held);
84 }
85 // The role handshake: the live role decides, and the row lock makes
86 // the check and the insert one decision against a concurrent
87 // demotion (see the doc above).
88 let role = sqlx::query!(
89 r#"SELECT role FROM app_user WHERE id = $1 FOR NO KEY UPDATE"#,
90 user_id.uuid(),
91 )
92 .fetch_optional(&mut *tx)
93 .await?;
94 if role.map(|row| row.role).as_deref() != Some(Role::Student.as_str()) {
95 return Ok(Verdict::Unfit);
96 }
97 // The counter and the row in one statement: zero rows means the
98 // instance is gone — the `404` the caller's own read gives an
99 // instant earlier.
100 let row = sqlx::query_as!(
101 Enrollment,
102 r#"WITH seat AS (
103 UPDATE class_course
104 SET enrollment_count = enrollment_count + 1
105 WHERE id = $1
106 RETURNING 1)
107 INSERT INTO enrollment (class_course, app_user, enrolled_by, source, created_at)
108 SELECT $1, $2, $3, $4, $5 WHERE EXISTS (SELECT 1 FROM seat)
109 RETURNING class_course AS "class_course: ClassCourseId",
110 app_user AS "user: UserId", enrolled_by AS "enrolled_by: UserId",
111 source AS "source: ClassGroupId",
112 created_at AS "created_at: Timestamp""#,
113 instance.uuid(),
114 user_id.uuid(),
115 enrolled_by_id.uuid(),
116 source_id,
117 created_at.as_millis(),
118 )
119 .fetch_optional(&mut *tx)
120 .await?;
121 match row {
122 Some(row) => Ok(Verdict::Made(row)),
123 None => {
124 // A same-student racer whose held-check predated the winner's
125 // commit queues on the role lock and wakes to its own row
126 // already there: that is the replay, not a refusal. Fresh
127 // snapshot per statement, so this read sees the committed
128 // winner.
129 let now_held = sqlx::query!(
130 r#"SELECT 1 AS "one" FROM enrollment
131 WHERE class_course = $1 AND app_user = $2"#,
132 instance.uuid(),
133 user_id.uuid(),
134 )
135 .fetch_optional(&mut *tx)
136 .await?;
137 if now_held.is_some() {
138 return Ok(Verdict::Held);
139 }
140 // No row and no winner: the instance itself is gone.
141 Err(AppError::NotFound)
142 }
143 }
144 })
145 .await;
146 // The 23505 backstop folds into the Held verdict before the mapping:
147 // someone placed this pair between the gate and the insert, and their
148 // row is the answer — no counter move was spent finding that out.
149 let verdict = match verdict {
150 Err(AppError::Db(err))
151 if unique_violation(&err) == Some("enrollment_class_course_user") =>
152 {
153 Ok(Verdict::Held)
154 }
155 other => other,
156 };
157 match verdict {
158 Ok(Verdict::Made(row)) => Ok(row),
159 Ok(Verdict::Held) => match read_for_user(db, class_course, user).await? {
160 Some(existing) => Ok(existing),
161 None => Err(AppError::Internal("failed to enroll user".into())),
162 },
163 // Demoted while this ran: the same refusal the service's own gate
164 // makes a moment earlier, and the only one that can arrive after it.
165 Ok(Verdict::Unfit) => Err(AppError::Validation(ValidationError::Invalid {
166 field: "user_id",
167 reason: "only students can be enrolled in a course",
168 })),
169 Err(err) => Err(err),
170 }
171}
172
173/// A hand enroll landing on a row a class pumped takes the row *off* the
174/// class: `source` goes, so no later class sweep can unenroll a student an
175/// operator placed on purpose. The mirror of the rule the sweep already holds
176/// in the other direction — a manual unenroll wins, permanently — and without
177/// it "hand-placed" was a state only a first enroll could reach.
178///
179/// `NULL`, not absence: the column is a nullable uuid whose NULL *is* the
180/// meaning a missing key used to carry, and it is what a hand enroll writes on
181/// the create path too.
182async fn disown_if_pumped(db: &Database, existing: Enrollment) -> Result<Enrollment, AppError> {
183 if existing.get_source().is_none() {
184 return Ok(existing);
185 }
186 let disowned = sqlx::query_as!(
187 Enrollment,
188 r#"UPDATE enrollment SET source = NULL
189 WHERE class_course = $1 AND app_user = $2
190 RETURNING class_course AS "class_course: ClassCourseId",
191 app_user AS "user: UserId", enrolled_by AS "enrolled_by: UserId",
192 source AS "source: ClassGroupId",
193 created_at AS "created_at: Timestamp""#,
194 existing.get_class_course().uuid(),
195 existing.get_user().uuid(),
196 )
197 .fetch_optional(db)
198 .await?;
199 // A row that is no longer there is not an internal error: an unenroll (or
200 // the class sweep a role change runs) landing between the read above and
201 // this write matches nothing, and the caller asked to be enrolled — which
202 // they were, by the row this call was handed. The disown is all that is
203 // lost, and it is lost to a delete that took the whole row with it.
204 Ok(disowned.unwrap_or(existing))
205}
206
207/// Some(_) iff `user` is enrolled in that instance — the grading gate.
208pub async fn read_for_user(
209 db: &Database,
210 class_course: &ClassCourseId,
211 user: &UserId,
212) -> Result<Option<Enrollment>, AppError> {
213 let row = sqlx::query_as!(
214 Enrollment,
215 r#"SELECT class_course AS "class_course: ClassCourseId", app_user AS "user: UserId",
216 enrolled_by AS "enrolled_by: UserId", source AS "source: ClassGroupId",
217 created_at AS "created_at: Timestamp"
218 FROM enrollment WHERE class_course = $1 AND app_user = $2"#,
219 class_course.uuid(),
220 user.uuid(),
221 )
222 .fetch_optional(db)
223 .await?;
224 Ok(row)
225}
226
227/// Every instance `user` holds an enrollment row on, in one statement for the
228/// whole set — the read behind the surfaces that must list a section a **hand**
229/// enrollment reaches. A hand-placed row (and a class row an operator later
230/// disowned, `source` NULL) is on no class roster, so
231/// [`crate::service::instance::visible_instances`] — keyed on the class — never
232/// sees it; `/courses/me` and the profile course block listed it before the
233/// section split, so they union this in. Ordered by instance id for a stable
234/// answer; a user with no enrollment reads an empty list, and the caller
235/// resolves the ids through [`crate::db::class_course`] (one batch read).
236pub async fn list_for_user(db: &Database, user: &UserId) -> Result<Vec<Enrollment>, AppError> {
237 let rows = sqlx::query_as!(
238 Enrollment,
239 r#"SELECT class_course AS "class_course: ClassCourseId", app_user AS "user: UserId",
240 enrolled_by AS "enrolled_by: UserId", source AS "source: ClassGroupId",
241 created_at AS "created_at: Timestamp"
242 FROM enrollment WHERE app_user = $1 ORDER BY class_course"#,
243 user.uuid(),
244 )
245 .fetch_all(db)
246 .await?;
247 Ok(rows)
248}
249
250/// The roster an exam is sat by: every enrollment of every instance the exam
251/// is addressed to (`exam_audience`, D2), deduped by student — the live
252/// monitor's roster read, and the one that makes an announced-to section's
253/// sitters visible to it. For an exam nobody was announced to this is the
254/// owner instance's roster, row for row.
255///
256/// `DISTINCT ON (app_user)` because a student enrolled in two addressed
257/// instances sits once: the roster is a set of people, and the monitor joins
258/// it with one attempt/mark map per person.
259pub async fn list_for_exam_audience(
260 db: &Database,
261 exam: &ExamId,
262) -> Result<Vec<Enrollment>, AppError> {
263 let rows = sqlx::query_as!(
264 Enrollment,
265 r#"SELECT DISTINCT ON (e.app_user)
266 e.class_course AS "class_course: ClassCourseId",
267 e.app_user AS "user: UserId",
268 e.enrolled_by AS "enrolled_by: UserId",
269 e.source AS "source: ClassGroupId",
270 e.created_at AS "created_at: Timestamp"
271 FROM enrollment e
272 JOIN exam_audience a ON a.class_course = e.class_course
273 WHERE a.exam = $1
274 ORDER BY e.app_user, e.created_at, e.class_course"#,
275 exam.uuid(),
276 )
277 .fetch_all(db)
278 .await?;
279 Ok(rows)
280}
281
282/// Whether `user` is one of `course`'s students right now — the point probe
283/// behind an event addressed at a course.
284///
285/// The two membership tiers again: an enrollment in any of the course's
286/// instances, or an individual club/supervised-study membership. Both are existence
287/// probes on their own indexes; one entity's audience must not fold a whole
288/// roster to answer yes.
289pub async fn user_is_in_course(
290 db: &Database,
291 course: &CourseId,
292 user: &UserId,
293) -> Result<bool, AppError> {
294 let row = sqlx::query!(
295 r#"SELECT 1 AS "one" FROM (
296 SELECT e.app_user FROM enrollment e
297 WHERE e.app_user = $2
298 AND e.class_course IN (SELECT id FROM class_course WHERE course = $1)
299 UNION ALL
300 SELECT m.app_user FROM course_membership m
301 WHERE m.course = $1 AND m.app_user = $2
302 ) people LIMIT 1"#,
303 course.uuid(),
304 user.uuid(),
305 )
306 .fetch_optional(db)
307 .await?;
308 Ok(row.is_some())
309}
310
311/// Every student the catalog course reaches right now — the union of its
312/// instances' rosters and its own individual memberships.
313///
314/// One course's "students" is two populations since D9 split the two tiers: a
315/// course reaches them through the instance a section teaches (enrollment), and
316/// a club or supervised study through the school-scoped membership. A reader
317/// that wants the course's audience — an event addressed at the course, a
318/// who-missed report — means both, and deduping in SQL keeps a student who is
319/// in two of its instances on the list once.
320pub async fn list_users_for_course(
321 db: &Database,
322 course: &CourseId,
323) -> Result<Vec<UserId>, AppError> {
324 let rows = sqlx::query!(
325 r#"SELECT DISTINCT app_user AS "user!: UserId" FROM (
326 SELECT e.app_user FROM enrollment e
327 JOIN class_course cc ON cc.id = e.class_course
328 WHERE cc.course = $1
329 UNION ALL
330 SELECT m.app_user FROM course_membership m WHERE m.course = $1
331 ) people ORDER BY app_user"#,
332 course.uuid(),
333 )
334 .fetch_all(db)
335 .await?;
336 Ok(rows.into_iter().map(|row| row.user).collect())
337}
338
339/// The instance's roster, newest first — the natural-PK columns sort the way
340/// the old composite key did, with its instance prefix constant.
341pub async fn list_for_class_course(
342 db: &Database,
343 class_course: &ClassCourseId,
344 limit: Option<i64>,
345 offset: i64,
346) -> Result<(Vec<Enrollment>, i64), AppError> {
347 PagedList::new(
348 "enrollment WHERE class_course = $1",
349 "ORDER BY class_course DESC, app_user DESC",
350 )
351 .bind(class_course.uuid())
352 .run::<Enrollment>(limit, offset, db)
353 .await
354}
355
356/// Take the row and give the instance's roster counter back in one statement,
357/// so nothing but a lost transaction can drift the counter. `None` when the
358/// pair held no row.
359pub async fn remove(
360 db: &Database,
361 class_course: &ClassCourseId,
362 user: &UserId,
363) -> Result<Option<Enrollment>, AppError> {
364 let gone = sqlx::query_as!(
365 Enrollment,
366 r#"WITH gone AS (
367 DELETE FROM enrollment
368 WHERE class_course = $1 AND app_user = $2
369 RETURNING class_course, app_user, enrolled_by, source, created_at),
370 seated AS (
371 UPDATE class_course
372 SET enrollment_count = GREATEST(
373 enrollment_count - (SELECT count(*) FROM gone), 0)
374 WHERE id = $1
375 RETURNING 1)
376 SELECT class_course AS "class_course: ClassCourseId",
377 app_user AS "user: UserId", enrolled_by AS "enrolled_by: UserId",
378 source AS "source: ClassGroupId", created_at AS "created_at: Timestamp"
379 FROM gone"#,
380 class_course.uuid(),
381 user.uuid(),
382 )
383 .fetch_optional(db)
384 .await?;
385 Ok(gone)
386}
387
388#[cfg(test)]
389mod tests {
390 use super::*;
391
392 /// A real `app_user` row: students, teachers and managers are foreign
393 /// keys now. The label names the row's username; the id is minted, so
394 /// repeated calls are new people, not the same row.
395 async fn a_person(db: &Database, label: &str, role: &str) -> UserId {
396 let user = UserId::generate();
397 sqlx::query(
398 "INSERT INTO app_user (id, username, created_at, role) \
399 VALUES ($1, $2, 0, $3)",
400 )
401 .bind(user.uuid())
402 .bind(format!("{label}-{}", &user.key()[30..]))
403 .bind(role)
404 .execute(db)
405 .await
406 .unwrap();
407 user
408 }
409
410 /// A real instance — class, course and the link between them — because
411 /// the enrollment's own key is a foreign key now.
412 async fn an_instance(db: &Database) -> (ClassCourseId, UserId) {
413 use crate::db::class_member::tests::{a_class, a_course};
414 use crate::domain::class_course::ClassCourseId;
415
416 let manager = crate::db::class_member::tests::fixture_user(db, "manager").await;
417 let class = a_class("9-A", db).await;
418 let course = a_course("algebra", db).await;
419 crate::service::class_course::attach(db, &class, &course, &manager)
420 .await
421 .unwrap();
422 let id: uuid::Uuid = sqlx::query_scalar("SELECT id FROM class_course WHERE class = $1")
423 .bind(class.uuid())
424 .fetch_one(db)
425 .await
426 .unwrap();
427 (
428 ClassCourseId::from_key(&id.to_string()),
429 a_person(db, "student", "student").await,
430 )
431 }
432
433 /// Enrollment is idempotent and the roster counter moves once: a repeat
434 /// enroll answers the row already there and leaves the counter as it
435 /// stands.
436 #[tokio::test]
437 async fn a_repeat_enroll_moves_the_counter_once() {
438 let (db, _leases) = crate::database::init_test_db().await;
439 let (instance, student) = an_instance(&db).await;
440 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
441
442 for _ in 0..2 {
443 enroll(&db, &instance, &student, &manager, None)
444 .await
445 .unwrap();
446 }
447 assert_eq!(
448 crate::db::class_member::tests::counter("enrollment_count", instance.uuid(), &db).await,
449 1,
450 "one row, one count"
451 );
452 }
453
454 /// A hand-placed enrollment carries no source key, and removing it gives
455 /// the counter back in the same statement.
456 #[tokio::test]
457 async fn a_hand_placed_row_carries_no_source_and_gives_its_count_back() {
458 let (db, _leases) = crate::database::init_test_db().await;
459 let (instance, student) = an_instance(&db).await;
460 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
461
462 let row = enroll(&db, &instance, &student, &manager, None)
463 .await
464 .unwrap();
465 assert!(
466 row.get_source().is_none(),
467 "a hand-placed row may carry no source key"
468 );
469
470 let removed = remove(&db, &instance, &student).await.unwrap();
471 assert!(removed.is_some(), "the row was there to take back");
472 assert_eq!(
473 crate::db::class_member::tests::counter("enrollment_count", instance.uuid(), &db).await,
474 0,
475 "the counter goes back with the row"
476 );
477 }
478}