forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBaf331ecAhmet Kaan Gümüş2 months ago451 commits

class_pump.rs1105 lines, 45.3 KiBHistoryRawDownload
1//! The pump behind the class layer: one link row changed, and every
2//! `enrollment` row that link implies reconciled with it, in one transaction.
3//!
4//! A class section (şube) has two link tables — `class_member` (a student in
5//! it) and `class_course` (a course attached to it) — and the *product* of the
6//! two is the roster it owes: every member is enrolled in every attached
7//! course, in real `enrollment` rows tagged [`source`](crate::domain::enrollment)
8//! with the class that wrote them. Adding a member and attaching a course are
9//! therefore the same operation seen along its two axes, and so are removing
10//! one and detaching the other.
11//!
12//! What is *not* one primitive is attach and detach. They share no statement:
13//! one gates on "this pair already holds a row" and claims a counter upwards,
14//! the other gates on nothing, releases, and has to decide per enrollment row
15//! whether a *rival* class still claims it.
16//!
17//! Every invariant is one Postgres statement or one row lock, in the shapes
18//! [`crate::db::cap`] documents: the class counter is claimed by a conditional
19//! `UPDATE` fused with the link's `INSERT` (one CTE — a refused insert takes
20//! its own seat bump back), a duplicate is the link table's natural composite
21//! primary key answering as `23505`, a gone parent is a real `FOREIGN KEY`
22//! answering as `23503`, and the row locks (`FOR KEY SHARE` / `FOR NO KEY
23//! UPDATE`) put each transaction on the very record a racing writer must
24//! touch. A refusal is an early `Err` (or an `Ok` verdict) from the
25//! [`crate::database::tx_with_retry`] closure — a decision, never a retry.
26
27use sqlx::postgres::PgConnection;
28
29use crate::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};
30use crate::database::{Database, foreign_key_violation, tx_with_retry, unique_violation};
31use crate::db::cap;
32use crate::domain::class_blueprint::ClassBlueprintId;
33use crate::domain::class_course::ClassCourse;
34use crate::domain::class_group::ClassGroupId;
35use crate::domain::class_member::ClassMember;
36use crate::domain::course::CourseId;
37use crate::domain::role::Role;
38use crate::domain::timestamp::Timestamp;
39use crate::domain::user::UserId;
40use crate::error::AppError;
41
42/// What [`attach_course`]'s attach settled. The caller answers each verdict —
43/// a hand attach turns them into this route's errors; a blueprint pump reads
44/// them and carries on ([`crate::domain::class_blueprint`]).
45#[derive(Debug)]
46pub(crate) enum Attached<T> {
47 /// The link row, the counter and every enrollment it implied committed
48 /// together.
49 Made(T),
50 /// The link already exists — nothing was written, and no seat was spent
51 /// finding that out.
52 Duplicate,
53 /// The class row is gone (a concurrent delete won). Nothing was written.
54 Gone,
55 /// The *pivot* — on the course axis, the course being attached — is gone.
56 /// Nothing was written. Told apart from [`Attached::Gone`] because the two
57 /// send a caller to look at different records, and a report that guesses
58 /// between them names the wrong one half the time.
59 ///
60 /// On the **member** axis the pivot is the student, and this means their
61 /// row is gone *or* their role no longer is `student`. Its one caller
62 /// answers that as the `400` the route's own read already answers, never
63 /// as [`Attached::refusal_code`]'s `course_deleted` — which is the course
64 /// axis's word for it and would name a record this refusal is not about.
65 PivotGone,
66 /// The class is at its own ceiling on this axis. Nothing was written, and
67 /// it is told apart from [`Attached::Gone`] because a full class is a
68 /// standing row someone can make room in, not a 404.
69 ClassFull,
70 /// The class stands *above* the ceiling on the other axis, so the write
71 /// loop this attach would run is longer than any transaction is allowed to
72 /// be. Only a class predating the ceilings can be here, and only its own
73 /// axis can make room — which is why it is not [`Attached::ClassFull`].
74 ClassOverloaded,
75 /// One of the courses had no free seat, named by its key. Nothing was
76 /// written — not one of the earlier seats in the same run, which is the
77 /// whole point of doing this in a transaction.
78 Full(String),
79 /// One of the courses the class carries no longer exists, named by its id:
80 /// a stale `class_course` link. Nothing was written, and no capacity anyone
81 /// can raise will change that answer.
82 CourseGone(String),
83 /// The blueprint this attach was sourced from is gone — a delete landed
84 /// between the pump reading the template and this transaction running.
85 /// Nothing was written, which is the point: a row tagged with a blueprint
86 /// that no longer exists is one nothing can ever sweep. Only a sourced
87 /// attach can be answered this.
88 SourceGone,
89}
90
91impl<T> Attached<T> {
92 /// This refusal as a **machine code**, or `None` for the attach that
93 /// landed. The client owns the wording and the language; this only says
94 /// *which* refusal it was — the shape every other enum here has (roles,
95 /// course kinds, the badge catalog).
96 ///
97 /// The single home for that vocabulary, because both readers answer it: a
98 /// blueprint pump reports it as a skip
99 /// ([`crate::domain::class_blueprint`]) and a hand attach as the `code` on
100 /// its `409` ([`crate::error::AppError::ConflictCoded`]). Spelled once, so
101 /// one cause can never grow two codes.
102 ///
103 /// Each code names the record that actually failed. The two "gone" answers
104 /// are a *class* delete ([`Attached::Gone`] → `class_deleted`) and a
105 /// *course* delete ([`Attached::PivotGone`] → `course_deleted`) — and
106 /// telling a manager the class vanished when the course did sends them to
107 /// look at a section that is standing right there. `linked_course_missing`
108 /// is a third: *another* course already attached to this class no longer
109 /// exists, and it must be detached before this attach can be retried.
110 /// `blueprint_deleted` is a pump losing the template itself mid-run — the
111 /// only refusal that says nothing about the (class, course) pair it names.
112 ///
113 /// The `axis` is a parameter because two of these answers name a *different
114 /// ceiling* on each of them: [`Attached::ClassFull`] is the ceiling of the
115 /// axis being attached and [`Attached::ClassOverloaded`] the other axis's,
116 /// so a member add's "full" is a full roster where a course attach's is a
117 /// full course list ([`Axis::at_ceiling_code`]). Read blind, the same code
118 /// worded a full roster as a full course list.
119 pub(crate) fn refusal_code(&self, axis: &Axis) -> Option<&'static str> {
120 match self {
121 Attached::Made(_) => None,
122 Attached::Duplicate => Some("duplicate"),
123 Attached::Gone => Some("class_deleted"),
124 Attached::PivotGone => Some("course_deleted"),
125 Attached::ClassFull => Some(axis.at_ceiling_code()),
126 Attached::ClassOverloaded => Some(axis.other().over_ceiling_code()),
127 Attached::Full(_) => Some("course_full"),
128 Attached::CourseGone(_) => Some("linked_course_missing"),
129 Attached::SourceGone => Some("blueprint_deleted"),
130 }
131 }
132}
133
134/// Which way the pump runs: the loop below needs a `(course, user)` pair per
135/// enrollment, and each caller supplies one side as a constant and reads the
136/// other off the class's *other* link table.
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
138pub(crate) enum Axis {
139 /// A student joining: the courses come from `class_course`.
140 Member,
141 /// A course arriving: the students come from `class_member`.
142 Course,
143}
144
145impl Axis {
146 /// The class counter this axis's link rows are counted on. Taken off the
147 /// axis rather than passed in beside it, because the two are one fact and a
148 /// call site that paired the member axis with the course counter would
149 /// compile, pass every test — both are `&'static str` — and desync the
150 /// class delete guard forever.
151 fn counter(self) -> &'static str {
152 match self {
153 Axis::Member => "class_member_count",
154 Axis::Course => "class_course_count",
155 }
156 }
157
158 /// How many link rows this axis's counter may reach.
159 ///
160 /// This is what makes the pair loop in [`add_member`]/[`attach_course`]
161 /// finite, and it does it *crosswise*: the member axis's loop iterates the
162 /// class's `class_course` rows, which the course axis's counter caps, and
163 /// the course axis's loop iterates its `class_member` rows, which the
164 /// member axis's counter caps. So bounding the two counters bounds both
165 /// write loops — one transaction can never carry more than
166 /// `MAX_CLASS_MEMBERS`/`MAX_CLASS_COURSES` enrollment writes.
167 ///
168 /// Crosswise is also why the claim alone is not enough. It bounds the axis
169 /// being *added*, and the loop it runs is the length of the *other* one: a
170 /// class that already holds more members than `MAX_CLASS_MEMBERS` — the
171 /// layer shipped before either ceiling existed, so a real volume can carry
172 /// one — could still have a course attached, and that attach writes one
173 /// enrollment per member. So the attach checks the other axis too
174 /// ([`Axis::other`]), and the bound holds for stale classes as well.
175 fn cap(self) -> i64 {
176 match self {
177 Axis::Member => MAX_CLASS_MEMBERS,
178 Axis::Course => MAX_CLASS_COURSES,
179 }
180 }
181
182 /// The refusal code for "the class is *at* this axis's ceiling"
183 /// ([`Attached::ClassFull`]), taken off the axis beside the `cap` it
184 /// reports, because that ceiling and its name are one fact.
185 fn at_ceiling_code(self) -> &'static str {
186 match self {
187 Axis::Member => "class_at_roster_ceiling",
188 Axis::Course => "class_at_course_ceiling",
189 }
190 }
191
192 /// The refusal code for "the class stands *above* this axis's ceiling", so
193 /// the other axis's attach would run a write loop longer than a transaction
194 /// may be ([`Attached::ClassOverloaded`]). Answered off the axis that is
195 /// over, never the one being attached — the two are always different axes,
196 /// which is exactly what the blind version got wrong.
197 fn over_ceiling_code(self) -> &'static str {
198 match self {
199 Axis::Member => "class_roster_too_large",
200 Axis::Course => "class_course_list_too_large",
201 }
202 }
203
204 /// The axis whose link rows this one's write loop iterates — its counter is
205 /// the length of that loop, and its ceiling is therefore the second half of
206 /// the bound.
207 fn other(self) -> Axis {
208 match self {
209 Axis::Member => Axis::Course,
210 Axis::Course => Axis::Member,
211 }
212 }
213}
214
215/// The pivot of an attach: the row the link hangs off on its own axis, which
216/// must still be there — and, on the member axis, still name a `student` —
217/// when the transaction runs.
218enum Pivot<'a> {
219 User(&'a UserId),
220 Course(&'a CourseId),
221}
222
223/// The verdicts the shared prechecks can settle before any counter moves.
224enum Early {
225 Duplicate,
226 SourceGone,
227 PivotGone,
228 Overloaded,
229}
230
231fn refusal_of<T>(early: Early) -> Attached<T> {
232 match early {
233 Early::Duplicate => Attached::Duplicate,
234 Early::SourceGone => Attached::SourceGone,
235 Early::PivotGone => Attached::PivotGone,
236 Early::Overloaded => Attached::ClassOverloaded,
237 }
238}
239
240/// The gates that run before any counter moves, in the order their answers
241/// outrank each other:
242///
243/// 1. **Duplicate** — "you are already in" outranks "there is no room": a
244/// caller whose row a rival placed a moment ago must not be told a course
245/// is full about seats they already hold. (The link table's own primary key
246/// re-answers this below as `23505` for a rival landing inside the window —
247/// same verdict, no second seat.)
248/// 2. **Source** — the blueprint that asked for this attach is still there. A
249/// `FOR KEY SHARE` row lock on the blueprint row: it serializes the attach
250/// against the blueprint's own delete — the closure the old process-wide
251/// lease provided, now on the row itself. A concurrent blueprint `DELETE`
252/// waits behind it and its sweep finds the committed row, while an attach
253/// starting after the delete finds no row and writes nothing. `KEY SHARE`
254/// is the weakest strength that blocks the delete, so two sourced attaches
255/// still run concurrently, exactly as they did under the old shared read
256/// lease.
257/// 3. **Pivot** — the member axis takes the [`cap` role-claim
258/// recipe](crate::db::cap)'s `FOR NO KEY UPDATE` handshake on the user row:
259/// a role change away from `student` sweeps this membership, and demotion
260/// and join now serialize on that row lock in both directions. The course
261/// axis takes a `FOR KEY SHARE` on the course row, which a concurrent
262/// course delete cannot take — the old bump-and-restore existence proof,
263/// now a plain lock.
264/// 4. **Overloaded** — the *other* axis standing above its own ceiling, which
265/// no claim on this axis can see, and which is what bounds this
266/// transaction's write loop.
267async fn early_verdicts(
268 tx: &mut PgConnection,
269 class: &ClassGroupId,
270 axis: Axis,
271 pivot: Pivot<'_>,
272 source: Option<&ClassBlueprintId>,
273) -> Result<Option<Early>, AppError> {
274 let held = match pivot {
275 Pivot::User(user) => sqlx::query_scalar!(
276 r#"SELECT 1 AS "one" FROM class_member WHERE class = $1 AND app_user = $2"#,
277 class as _,
278 user as _
279 )
280 .fetch_optional(&mut *tx)
281 .await?
282 .is_some(),
283 Pivot::Course(course) => sqlx::query_scalar!(
284 r#"SELECT 1 AS "one" FROM class_course WHERE class = $1 AND course = $2"#,
285 class as _,
286 course as _
287 )
288 .fetch_optional(&mut *tx)
289 .await?
290 .is_some(),
291 };
292 if held {
293 return Ok(Some(Early::Duplicate));
294 }
295 if let Some(source) = source {
296 let alive = sqlx::query_scalar!(
297 r#"SELECT 1 AS "one" FROM class_blueprint WHERE grade = $1 FOR KEY SHARE"#,
298 source as _
299 )
300 .fetch_optional(&mut *tx)
301 .await?
302 .is_some();
303 if !alive {
304 return Ok(Some(Early::SourceGone));
305 }
306 }
307 match pivot {
308 Pivot::User(user) => {
309 let row = sqlx::query!(
310 r#"SELECT role AS "role: Role" FROM app_user WHERE id = $1 FOR NO KEY UPDATE"#,
311 user as _
312 )
313 .fetch_optional(&mut *tx)
314 .await?;
315 if row.map(|row| row.role) != Some(Role::Student) {
316 return Ok(Some(Early::PivotGone));
317 }
318 }
319 Pivot::Course(course) => {
320 let alive = sqlx::query_scalar!(
321 r#"SELECT 1 AS "one" FROM course WHERE id = $1 FOR KEY SHARE"#,
322 course as _
323 )
324 .fetch_optional(&mut *tx)
325 .await?
326 .is_some();
327 if !alive {
328 return Ok(Some(Early::PivotGone));
329 }
330 }
331 }
332 // Read off the class row inside the transaction that claims it, so the
333 // count this refuses on is the one the pair loop below would iterate.
334 let over = match axis.other() {
335 Axis::Member => sqlx::query_scalar!(
336 r#"SELECT 1 AS "one" FROM class_group
337 WHERE id = $1 AND class_member_count > $2"#,
338 class as _,
339 Axis::Member.cap(),
340 )
341 .fetch_optional(&mut *tx)
342 .await?
343 .is_some(),
344 Axis::Course => sqlx::query_scalar!(
345 r#"SELECT 1 AS "one" FROM class_group
346 WHERE id = $1 AND class_course_count > $2"#,
347 class as _,
348 Axis::Course.cap(),
349 )
350 .fetch_optional(&mut *tx)
351 .await?
352 .is_some(),
353 };
354 Ok(over.then_some(Early::Overloaded))
355}
356
357/// Write the member link and enroll the student into every course the class is
358/// already attached to, or write nothing at all.
359///
360/// A student already enrolled in one of those courses keeps the row they
361/// have — no seat is charged, and the existing row's `source` is left exactly
362/// as it was, so a hand-placed student is never quietly adopted by a class.
363/// A course with no free seat refuses the *whole* join rather than half of it.
364///
365/// The class counter is claimed by the conditional half of the CTE below
366/// rather than a bare increment, so a class deleted out from under this run
367/// matches nothing and the whole cascade aborts: [`Attached::Gone`] instead of
368/// a counter on a row that no longer exists. The same write carries
369/// [`Axis::Member`]'s cap, which is what keeps the pair loop — and therefore
370/// this transaction — finite: [`Attached::ClassFull`] once the class is at its
371/// ceiling. Claim and insert are one statement, so a refused insert takes its
372/// own seat bump back.
373pub(crate) async fn add_member(
374 db: &Database,
375 class: &ClassGroupId,
376 user: &UserId,
377 by: &UserId,
378) -> Result<Attached<ClassMember>, AppError> {
379 let added_at = Timestamp::now();
380 let class = class.clone();
381 let (user, by) = (*user, *by);
382 tx_with_retry(db, false, async move |tx| {
383 if let Some(early) =
384 early_verdicts(tx, &class, Axis::Member, Pivot::User(&user), None).await?
385 {
386 return Ok(refusal_of(early));
387 }
388 // The claim and the link are one statement (the cap recipe's CTE): the
389 // conditional `UPDATE` on the class row gates the `INSERT`, so a full
390 // or gone class writes nothing at all.
391 let inserted = match sqlx::query_scalar!(
392 r#"WITH seat AS (
393 UPDATE class_group SET class_member_count = class_member_count + 1
394 WHERE id = $1 AND class_member_count < $2
395 RETURNING 1)
396 INSERT INTO class_member (class, app_user, added_by, added_at)
397 SELECT $1, $3, $4, $5 WHERE EXISTS (SELECT 1 FROM seat)
398 RETURNING 1 AS "one""#,
399 class as _,
400 Axis::Member.cap(),
401 user as _,
402 by as _,
403 added_at as _
404 )
405 .fetch_optional(&mut *tx)
406 .await
407 {
408 Ok(result) => result,
409 // A rival landed in the window between the gate and the insert:
410 // the link table's own primary key answers, same verdict as the
411 // gate, no second seat.
412 Err(e) if unique_violation(&e) == Some("class_member_class_user") => {
413 return Ok(Attached::Duplicate);
414 }
415 // The student row vanished mid-run despite the locked pivot claim.
416 Err(e) if foreign_key_violation(&e) => return Ok(Attached::PivotGone),
417 Err(e) => return Err(e.into()),
418 };
419 if inserted.is_none() {
420 // Full, or the class is gone — the claim matches nothing either
421 // way, and only this path pays for the read that tells them apart.
422 let standing = sqlx::query_scalar!(
423 r#"SELECT 1 AS "one" FROM class_group WHERE id = $1"#,
424 class as _
425 )
426 .fetch_optional(&mut *tx)
427 .await?
428 .is_some();
429 return Ok(if standing {
430 Attached::ClassFull
431 } else {
432 Attached::Gone
433 });
434 }
435 let courses: Vec<uuid::Uuid> = sqlx::query_scalar!(
436 r#"SELECT course AS "course: uuid::Uuid" FROM class_course WHERE class = $1"#,
437 class as _
438 )
439 .fetch_all(&mut *tx)
440 .await?;
441 let pairs = courses.into_iter().map(|course| (course, user.uuid()));
442 match enroll_pairs(tx, &class, pairs, &by).await? {
443 Sweep::Done => {}
444 Sweep::CourseGone(course) => return Ok(Attached::CourseGone(course)),
445 Sweep::Full(course) => return Ok(Attached::Full(course)),
446 }
447 Ok(Attached::Made(ClassMember {
448 class: class.clone(),
449 user,
450 added_by: by,
451 added_at: Some(added_at),
452 }))
453 })
454 .await
455}
456
457/// Write the course link and enroll the class's whole roster into it, or
458/// write nothing at all.
459///
460/// Students already in the course keep the rows they have — no seat charged,
461/// `source` untouched — and a roster that does not fit refuses the whole
462/// attach rather than filling the course to its cap and stopping.
463///
464/// `source` is the blueprint whose behalf this attach runs on, and supplying
465/// it adds one more claim: that it is still there when the transaction runs
466/// ([`Attached::SourceGone`]) — the `FOR KEY SHARE` lock that serializes this
467/// transaction against the blueprint's own delete. A hand attach owns itself
468/// and passes `None`.
469pub(crate) async fn attach_course(
470 db: &Database,
471 class: &ClassGroupId,
472 course: &CourseId,
473 by: &UserId,
474 source: Option<&ClassBlueprintId>,
475) -> Result<Attached<ClassCourse>, AppError> {
476 let attached_at = Timestamp::now();
477 let class = class.clone();
478 let course = course.clone();
479 let by = *by;
480 let source = source.cloned();
481 tx_with_retry(db, false, async move |tx| {
482 if let Some(early) = early_verdicts(
483 tx,
484 &class,
485 Axis::Course,
486 Pivot::Course(&course),
487 source.as_ref(),
488 )
489 .await?
490 {
491 return Ok(refusal_of(early));
492 }
493 let inserted = match sqlx::query_scalar!(
494 r#"WITH seat AS (
495 UPDATE class_group SET class_course_count = class_course_count + 1
496 WHERE id = $1 AND class_course_count < $2
497 RETURNING 1)
498 INSERT INTO class_course (class, course, attached_by, attached_at, source)
499 SELECT $1, $3, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat)
500 RETURNING 1 AS "one""#,
501 class as _,
502 Axis::Course.cap(),
503 course as _,
504 by as _,
505 attached_at as _,
506 source as _
507 )
508 .fetch_optional(&mut *tx)
509 .await
510 {
511 Ok(result) => result,
512 Err(e) if unique_violation(&e) == Some("class_course_class_course") => {
513 return Ok(Attached::Duplicate);
514 }
515 Err(e) if foreign_key_violation(&e) => return Ok(Attached::PivotGone),
516 Err(e) => return Err(e.into()),
517 };
518 if inserted.is_none() {
519 let standing = sqlx::query_scalar!(
520 r#"SELECT 1 AS "one" FROM class_group WHERE id = $1"#,
521 class as _
522 )
523 .fetch_optional(&mut *tx)
524 .await?
525 .is_some();
526 return Ok(if standing {
527 Attached::ClassFull
528 } else {
529 Attached::Gone
530 });
531 }
532 let members: Vec<uuid::Uuid> = sqlx::query_scalar!(
533 r#"SELECT app_user AS "app_user: uuid::Uuid" FROM class_member WHERE class = $1"#,
534 class as _
535 )
536 .fetch_all(&mut *tx)
537 .await?;
538 let pairs = members.into_iter().map(|user| (course.uuid(), user));
539 match enroll_pairs(tx, &class, pairs, &by).await? {
540 Sweep::Done => {}
541 Sweep::CourseGone(course) => return Ok(Attached::CourseGone(course)),
542 Sweep::Full(course) => return Ok(Attached::Full(course)),
543 }
544 Ok(Attached::Made(ClassCourse {
545 class: class.clone(),
546 course: course.clone(),
547 attached_by: by,
548 source: source.clone(),
549 attached_at: Some(attached_at),
550 }))
551 })
552 .await
553}
554
555/// What the shared enrollment loop settled for its pairs.
556enum Sweep {
557 /// Every pair holds the row it owes.
558 Done,
559 /// One of the pairs' courses is gone, named by its key: a stale link.
560 CourseGone(String),
561 /// One of the pairs' courses has no free seat, named by its key.
562 Full(String),
563}
564
565/// Enroll every `(course, user)` pair that has no row yet, each against its
566/// own course's capacity, skipping — never charging — the pairs that do.
567///
568/// Per pair, in the order the refusals outrank each other: the pair's own row
569/// answers "already enrolled" (skip, no seat); the course row answers "gone"
570/// *before* the seat claim, so a stale link is never mis-reported as a
571/// capacity problem; the seat claim is a conditional `UPDATE` on the course
572/// row (live cap — `capacity` as it stands at write time, `NULL` reading as
573/// unlimited); and the insert rides the seat it claimed. A rival that lands
574/// between the gate and the insert answers `23505`, and the bump is given
575/// back before the skip — the outcome a re-sent transaction used to reach by
576/// seeing the rival's row at its gate.
577///
578/// Every abort stops the loop inside the caller's transaction: not one of the
579/// earlier seats in the same run survives, which is the whole point of doing
580/// this in a transaction.
581async fn enroll_pairs(
582 tx: &mut PgConnection,
583 class: &ClassGroupId,
584 pairs: impl Iterator<Item = (uuid::Uuid, uuid::Uuid)>,
585 by: &UserId,
586) -> Result<Sweep, AppError> {
587 for (course, user) in pairs {
588 let held = sqlx::query_scalar!(
589 r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#,
590 course,
591 user
592 )
593 .fetch_optional(&mut *tx)
594 .await?
595 .is_some();
596 if held {
597 continue;
598 }
599 let alive = sqlx::query_scalar!(r#"SELECT 1 AS "one" FROM course WHERE id = $1"#, course)
600 .fetch_optional(&mut *tx)
601 .await?
602 .is_some();
603 if !alive {
604 return Ok(Sweep::CourseGone(course.to_string()));
605 }
606 let seat = sqlx::query_scalar!(
607 r#"UPDATE course SET enrollment_count = enrollment_count + 1
608 WHERE id = $1 AND enrollment_count < COALESCE(capacity, $2)
609 RETURNING 1 AS "one""#,
610 course,
611 cap::UNLIMITED,
612 )
613 .fetch_optional(&mut *tx)
614 .await?
615 .is_some();
616 if !seat {
617 return Ok(Sweep::Full(course.to_string()));
618 }
619 let wrote = sqlx::query_scalar!(
620 r#"INSERT INTO enrollment (course, app_user, enrolled_by, source)
621 VALUES ($1, $2, $3, $4)
622 ON CONFLICT (course, app_user) DO NOTHING
623 RETURNING 1 AS "one""#,
624 course,
625 user,
626 by as _,
627 class as _
628 )
629 .fetch_optional(&mut *tx)
630 .await;
631 match wrote {
632 Ok(Some(_)) => {}
633 // A rival placed the pair in the window: their row stands, no
634 // second seat, and the claim this run took is given back — the
635 // skip wins over the capacity answer, exactly as a re-sent
636 // transaction found the row at its gate.
637 Ok(None) => {
638 sqlx::query!(
639 r#"UPDATE course SET enrollment_count = enrollment_count - 1
640 WHERE id = $1"#,
641 course
642 )
643 .execute(&mut *tx)
644 .await?;
645 }
646 Err(e) if unique_violation(&e) == Some("enrollment_course_user") => {
647 sqlx::query!(
648 r#"UPDATE course SET enrollment_count = enrollment_count - 1
649 WHERE id = $1"#,
650 course
651 )
652 .execute(&mut *tx)
653 .await?;
654 }
655 Err(e) => return Err(e.into()),
656 }
657 }
658 Ok(Sweep::Done)
659}
660
661// The sweep a role change *off` `student` owes — every class membership (each
662// class getting its member count back) and every enrollment row (each course
663// getting its seat back) — is two of the arms of
664// [`crate::service::user::set_role`], because it belongs in the same
665// transaction as the role write that invalidates them. It stays one fact with
666// the counters either way: released separately, a failure between the halves
667// left enrollment rows tagged `source = class_group:X` while the class had its
668// counters back, so the class passed its zero-zero delete guard and the rows
669// were left pointing at a class no sweep could ever reach again.
670
671/// Take a student out of a class and sweep the enrollments the class pumped
672/// for them. Answers how many link rows went (0 or 1), so the caller can turn
673/// zero into a 404.
674///
675/// The sweep is *repair-first*: an enrollment this class wrote is only deleted
676/// once no other class still claims it. Two classes attached to the same
677/// course share a student — the second attach skipped the row the first had
678/// already written, so the row carries only the first class's name — and
679/// deleting it on the first class's way out would unenroll a student the
680/// second class is still responsible for. So the row is re-tagged to that
681/// rival instead, and only a row nobody is left to claim is deleted and its
682/// seat given back. The heir is the lowest class id among the claimants: a
683/// deterministic pick (uuid order is mint order), so a repeat of the same
684/// sweep lands on the same class.
685///
686/// That pick is then **claimed** — a `FOR NO KEY UPDATE` read of the heir's
687/// class row, no counter moved — before the row is handed over. Both reads
688/// behind it are pure, and this sweep is long — one pass per enrollment row
689/// the link implies — so `DELETE /classes/{heir}/members/{user}` and
690/// `DELETE /classes/{heir}/courses/{course}` could both commit inside it and
691/// leave the row tagged with a class holding neither link: a `class_group`
692/// whose own 0/0 delete guard then passes, stranding an enrollment nothing can
693/// ever sweep. Every one of those writers moves a counter on the heir's own
694/// row, so the row lock here puts this transaction on the record they write
695/// and the two settle in either order. A claim that matches nothing is an
696/// heir whose class row is gone — a stale link outliving its class — and it
697/// takes the release arm rather than tagging the row with an id no route can
698/// reach.
699///
700/// Sweeps tolerate rows that are already gone. A course delete wipes a
701/// course's enrollments wholesale while the `class_member` rows survive it, so
702/// "this class has a member" and "that member has a live pumped row" are
703/// independent facts and the loop simply finds nothing to sweep.
704pub(crate) async fn remove_member(
705 db: &Database,
706 class: &ClassGroupId,
707 user: &UserId,
708) -> Result<i64, AppError> {
709 let class = class.clone();
710 let user = *user;
711 tx_with_retry(db, true, async move |tx| {
712 let gone = sqlx::query_scalar!(
713 r#"DELETE FROM class_member WHERE class = $1 AND app_user = $2
714 RETURNING 1 AS "one""#,
715 class as _,
716 user as _
717 )
718 .fetch_optional(&mut *tx)
719 .await?;
720 let Some(_) = gone else {
721 return Ok(0);
722 };
723 sqlx::query!(
724 r#"UPDATE class_group
725 SET class_member_count = GREATEST(class_member_count - 1, 0)
726 WHERE id = $1"#,
727 class as _
728 )
729 .execute(&mut *tx)
730 .await?;
731 let rows = sqlx::query!(
732 r#"SELECT course AS "course: uuid::Uuid", app_user AS "app_user: uuid::Uuid"
733 FROM enrollment WHERE app_user = $1 AND source = $2"#,
734 user as _,
735 class as _
736 )
737 .fetch_all(&mut *tx)
738 .await?
739 .into_iter()
740 .map(|row| (row.course, row.app_user))
741 .collect::<Vec<_>>();
742 sweep_enrollments(tx, &class, rows).await?;
743 Ok(1)
744 })
745 .await
746}
747
748/// Detach `course` from `class` and sweep the enrollments the class pumped
749/// into it. `source`, when given, re-asserts the provenance tag on the link's
750/// own delete — a blueprint sweep may only take back rows its own tag owns.
751/// Answers how many link rows went, so a caller whose link was a single pair
752/// can turn zero into a 404. The sweep underneath is the shared one: a student
753/// a second class still claims is re-tagged rather than unenrolled.
754pub(crate) async fn detach_course(
755 db: &Database,
756 class: &ClassGroupId,
757 course: &CourseId,
758 source: Option<&ClassBlueprintId>,
759) -> Result<i64, AppError> {
760 let class = class.clone();
761 let course = course.clone();
762 let source = source.cloned();
763 tx_with_retry(db, true, async move |tx| {
764 let gone = match &source {
765 Some(source) => {
766 sqlx::query_scalar!(
767 r#"DELETE FROM class_course WHERE class = $1 AND course = $2 AND source = $3
768 RETURNING 1 AS "one""#,
769 class as _,
770 course as _,
771 source as _
772 )
773 .fetch_optional(&mut *tx)
774 .await?
775 }
776 None => {
777 sqlx::query_scalar!(
778 r#"DELETE FROM class_course WHERE class = $1 AND course = $2
779 RETURNING 1 AS "one""#,
780 class as _,
781 course as _
782 )
783 .fetch_optional(&mut *tx)
784 .await?
785 }
786 };
787 let Some(_) = gone else {
788 return Ok(0);
789 };
790 sqlx::query!(
791 r#"UPDATE class_group
792 SET class_course_count = GREATEST(class_course_count - 1, 0)
793 WHERE id = $1"#,
794 class as _
795 )
796 .execute(&mut *tx)
797 .await?;
798 let rows = sqlx::query!(
799 r#"SELECT course AS "course: uuid::Uuid", app_user AS "app_user: uuid::Uuid"
800 FROM enrollment WHERE course = $1 AND source = $2"#,
801 course as _,
802 class as _
803 )
804 .fetch_all(&mut *tx)
805 .await?
806 .into_iter()
807 .map(|row| (row.course, row.app_user))
808 .collect::<Vec<_>>();
809 sweep_enrollments(tx, &class, rows).await?;
810 Ok(1)
811 })
812 .await
813}
814
815/// The repair-first tail both detaches share: for every enrollment row the
816/// deleted link owned, hand it to a rival class that still claims it, or
817/// delete it and give the course its seat back.
818///
819/// The heir is the lowest class id among the rivals that carry both this
820/// course *and* the student — the same deterministic pick on every repeat. Its
821/// class row is read `FOR NO KEY UPDATE` (a claim that moves no counter: the
822/// class_member row already covers the student, and the enrollment is counted
823/// on the course) so a concurrent member/course write on the heir serializes
824/// behind this transaction; a claim matching nothing is a gone heir, and the
825/// row takes the release arm.
826async fn sweep_enrollments(
827 tx: &mut PgConnection,
828 class: &ClassGroupId,
829 rows: Vec<(uuid::Uuid, uuid::Uuid)>,
830) -> Result<(), AppError> {
831 for (course, user) in rows {
832 let heir = sqlx::query_scalar!(
833 r#"SELECT cm.class AS "class: uuid::Uuid"
834 FROM class_member cm
835 JOIN class_course cc ON cc.class = cm.class AND cc.course = $1
836 WHERE cm.app_user = $2 AND cm.class <> $3
837 ORDER BY cm.class
838 LIMIT 1"#,
839 course,
840 user,
841 class as _
842 )
843 .fetch_optional(&mut *tx)
844 .await?;
845 let Some(heir) = heir else {
846 release(tx, course, user).await?;
847 continue;
848 };
849 let claimed = sqlx::query_scalar!(
850 r#"SELECT class_member_count AS "heir_count: i64" FROM class_group
851 WHERE id = $1 FOR NO KEY UPDATE"#,
852 heir
853 )
854 .fetch_optional(&mut *tx)
855 .await?;
856 if claimed.is_none() {
857 release(tx, course, user).await?;
858 continue;
859 }
860 sqlx::query!(
861 r#"UPDATE enrollment SET source = $1 WHERE course = $2 AND app_user = $3"#,
862 heir,
863 course,
864 user
865 )
866 .execute(&mut *tx)
867 .await?;
868 }
869 Ok(())
870}
871
872/// Nobody is left to claim the row: it goes, and its seat with it. The seat
873/// is only given back when the delete actually took the row — a course
874/// delete's wholesale sweep may have taken both while this transaction read
875/// them, and both halves vanish together there.
876async fn release(
877 tx: &mut PgConnection,
878 course: uuid::Uuid,
879 user: uuid::Uuid,
880) -> Result<(), AppError> {
881 let deleted = sqlx::query!(
882 r#"DELETE FROM enrollment WHERE course = $1 AND app_user = $2"#,
883 course,
884 user
885 )
886 .execute(&mut *tx)
887 .await?
888 .rows_affected();
889 if deleted > 0 {
890 sqlx::query!(
891 r#"UPDATE course SET enrollment_count = GREATEST(enrollment_count - 1, 0)
892 WHERE id = $1"#,
893 course
894 )
895 .execute(&mut *tx)
896 .await?;
897 }
898 Ok(())
899}
900#[cfg(test)]
901mod tests {
902 use super::*;
903 use crate::constant::{CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE};
904 use crate::db::class_member::tests::{a_class, counter, rows};
905 use crate::domain::class_group::ClassGroupId;
906 use crate::domain::user::UserId;
907 use crate::error::AppError;
908 use crate::service::{class_course, class_member};
909
910 /// The class counter is claimed conditionally, so a class that is not there
911 /// stops the cascade before anything is written — rather than leaving a
912 /// counter, a link row and a pumped enrollment hanging off a record that
913 /// does not exist.
914 #[tokio::test]
915 async fn an_attach_onto_a_missing_class_writes_nothing() {
916 let db = crate::database::init_mem().await.unwrap();
917 let ghost = ClassGroupId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T");
918
919 let refused = class_member::add(
920 &db,
921 &ghost,
922 &UserId::from_key("student"),
923 &UserId::from_key("manager"),
924 )
925 .await;
926 assert!(
927 matches!(refused, Err(AppError::NotFound)),
928 "a class that is gone is a 404, not a counter on nothing: {refused:?}"
929 );
930 assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0);
931 assert_eq!(rows("SELECT VALUE id FROM class_group", &db).await, 0);
932 }
933
934 /// [`detach`] is written to take *many* link rows at once — that is what
935 /// makes a user's whole membership one statement — and every one of them
936 /// releases its own class's counter. Called straight, because the public
937 /// `delete_for_user` throws the count away.
938 #[tokio::test]
939 async fn a_detach_releases_every_class_it_unlinked() {
940 let db = crate::database::init_mem().await.unwrap();
941 let manager = UserId::from_key("manager");
942 let student = UserId::from_key("student");
943 let classes = [
944 a_class("9-A", &db).await,
945 a_class("9-B", &db).await,
946 a_class("club", &db).await,
947 ];
948 for class in &classes {
949 class_member::add(&db, class, &student, &manager)
950 .await
951 .unwrap();
952 }
953
954 let gone = detach(
955 &db,
956 &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"),
957 Axis::Member,
958 &[("usr".into(), student.record().into_value())],
959 )
960 .await
961 .unwrap();
962 assert_eq!(
963 gone, 3,
964 "every link row must be counted, not just the first"
965 );
966 for class in &classes {
967 assert_eq!(
968 counter(CLASS_MEMBER_COUNT_FIELD, class.record(), &db).await,
969 0,
970 "each class gets its own counter back"
971 );
972 }
973
974 // And a run that unlinks nothing answers zero, which is what turns a
975 // single-pair detach into a 404 instead of a silent success.
976 let again = detach(
977 &db,
978 &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"),
979 Axis::Member,
980 &[("usr".into(), student.record().into_value())],
981 )
982 .await
983 .unwrap();
984 assert_eq!(again, 0);
985 }
986
987 /// The heir a sweep hands a shared enrollment to must still hold *both*
988 /// links when the transaction commits — not merely when it read them.
989 ///
990 /// Two classes carry one course and one student, so the row names the first
991 /// and the second is its heir. While that first class's detach sweeps — a
992 /// pass per enrollment row, up to a full roster long — the heir drops the
993 /// student and detaches the course, both committed. Its two reads see an
994 /// heir that is already gone, and its write set (its own class, its own
995 /// link, the enrollment) touches nothing the heir's two deletes wrote: with
996 /// no read-set conflict detection, both sides commit and the row is left
997 /// tagged with a class holding neither link, which then passes its own 0/0
998 /// delete guard. The claim on the heir's counter is what puts the two
999 /// transactions on one record.
1000 ///
1001 /// Real server, and `#[ignore]`d for it, exactly like
1002 /// [`crate::domain::class_course`]'s course-delete twin: the subject *is*
1003 /// the store's conflict detection, which `init_mem`'s embedded engine does
1004 /// not have — it commits both sides and answers `Ok` to each, so this passes
1005 /// there on broken code.
1006 ///
1007 /// The window is opened by the schema rather than by a lucky interleaving: a
1008 /// `DEFINE EVENT` on `class_course` scoped to the *owner's* link holds that
1009 /// detach open at its first statement, so the heir's two calls land inside
1010 /// its transaction every time — and the heir's own detach, on another class,
1011 /// is not slowed by it.
1012 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1013 #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
1014 async fn a_detached_row_is_never_handed_to_a_class_that_let_it_go() {
1015 use crate::db::class_member::tests::{a_course, source_of};
1016
1017 let (db, _serialized) = crate::database::init_test_server("class_heir_race").await;
1018 let manager = UserId::from_key("manager");
1019 let student = UserId::from_key("student");
1020 let (mut raced, mut stranded) = (0, 0);
1021 for round in 0..4 {
1022 let algebra = a_course(&format!("algebra{round}"), None, &db).await;
1023 let owner = a_class(&format!("9-{round}-owner"), &db).await;
1024 let heir = a_class(&format!("9-{round}-heir"), &db).await;
1025 for class in [&owner, &heir] {
1026 class_member::add(&db, class, &student, &manager)
1027 .await
1028 .unwrap();
1029 class_course::attach(&db, class, &algebra, &manager)
1030 .await
1031 .unwrap();
1032 }
1033 assert_eq!(
1034 source_of(&algebra, &student, &db).await,
1035 Some(Some(owner.clone())),
1036 "round {round}: the row must start out owned by the first class"
1037 );
1038 db.query(format!(
1039 "DEFINE EVENT OVERWRITE hold_the_sweep ON TABLE {CLASS_COURSE_TABLE} \
1040 WHEN $event = 'DELETE' THEN {{ IF $before.class = \
1041 type::record('class_group', '{}') {{ SLEEP 2s }} }};",
1042 owner.key()
1043 ))
1044 .await
1045 .unwrap()
1046 .check()
1047 .unwrap();
1048
1049 let detaching = {
1050 let (db, owner, algebra) = (db.clone(), owner.clone(), algebra.clone());
1051 tokio::spawn(async move { class_course::detach(&db, &owner, &algebra).await })
1052 };
1053 tokio::time::sleep(std::time::Duration::from_millis(500)).await;
1054 assert!(
1055 !detaching.is_finished(),
1056 "round {round}: the sweep was over before the heir moved"
1057 );
1058 // The heir lets the row go, twice over, while that sweep is still
1059 // choosing it.
1060 class_member::remove(&db, &heir, &student).await.unwrap();
1061 class_course::detach(&db, &heir, &algebra).await.unwrap();
1062 let swept = detaching.await.unwrap();
1063 assert!(
1064 !matches!(swept, Err(AppError::Db(_))),
1065 "round {round}: a raced detach must be answered, not 500: {swept:?}"
1066 );
1067
1068 // Stored state is the whole verdict; a return value is not evidence.
1069 if swept.is_ok() {
1070 raced += 1;
1071 }
1072 if source_of(&algebra, &student, &db).await == Some(Some(heir.clone())) {
1073 stranded += 1;
1074 }
1075 }
1076 eprintln!("a detach raced by its heir: {raced}/4 rounds swept");
1077 assert!(raced > 0, "no round ever committed its sweep");
1078 assert_eq!(
1079 stranded, 0,
1080 "an enrollment was left tagged with a class holding neither link"
1081 );
1082 }
1083
1084 #[test]
1085 fn a_full_abort_names_its_course() {
1086 assert_eq!(
1087 named_course("An error occurred: class_full:course:01J8XZ0K3Q", FULL_MARK),
1088 Some("course:01J8XZ0K3Q".to_string())
1089 );
1090 assert_eq!(
1091 named_course("class_full:course:algebra'", FULL_MARK),
1092 Some("course:algebra".into())
1093 );
1094 assert_eq!(named_course("class_held", FULL_MARK), None);
1095 assert_eq!(named_course("class_full:", FULL_MARK), None);
1096 // And the stale-link abort reads off the same shape, without the two
1097 // markers ever matching each other's text.
1098 assert_eq!(
1099 named_course("class_no_course:course:algebra'", MISSING_MARK),
1100 Some("course:algebra".into())
1101 );
1102 assert_eq!(named_course("class_no_course:course:a", FULL_MARK), None);
1103 assert_eq!(named_course("class_full:course:a", MISSING_MARK), None);
1104 }
1105}