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

class_pump.rs1161 lines, 50.4 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 has two link tables — `class_member` (a student in
5//! it) and `class_course` (a course attached to it, as that class×course
6//! *instance*) — and the *product* of the two is the roster it owes: every
7//! live member is enrolled in every instance the class carries, in real
8//! `enrollment` rows tagged [`source`](crate::domain::enrollment) with the
9//! class that wrote them. Adding a member and attaching a course are
10//! therefore the same operation seen along its two axes, and so are ending
11//! one and detaching the other.
12//!
13//! What is *not* one primitive is attach and detach. They share no statement:
14//! one gates on "this pair already holds a row" and claims a counter upwards,
15//! the other takes the instance and everything the class taught under it, and
16//! the member exits release the enrollment rows the ended stint owned — one
17//! row per *instance*, so a section's exit never touches the seat the student
18//! holds in another section.
19//!
20//! Every invariant is one Postgres statement or one row lock, in the shapes
21//! [`crate::db::cap`] documents: the class counter is claimed by a conditional
22//! `UPDATE` fused with the link's `INSERT` (one CTE — a refused insert takes
23//! its own bump back), a duplicate live stint is the partial unique index
24//! `class_member_live_pair` answering as `23505` (and enrollment's natural
25//! `(class_course, app_user)` key doing the same job through `ON CONFLICT`),
26//! a gone parent is a real `FOREIGN KEY` answering as `23503`, and the row
27//! locks (`FOR KEY SHARE` / `FOR NO KEY UPDATE` / `FOR UPDATE`) put each
28//! transaction on the very record a racing writer must touch. A refusal is an
29//! early `Err` (or an `Ok` verdict) from the
30//! [`crate::database::tx_with_retry`] closure — a decision, never a retry.
31
32use sqlx::postgres::PgConnection;
33
34use crate::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};
35use crate::database::{Database, foreign_key_violation, tx_with_retry, unique_violation};
36use crate::domain::class_blueprint::ClassBlueprintId;
37use crate::domain::class_course::{ClassCourse, ClassCourseId};
38use crate::domain::class_group::ClassGroupId;
39use crate::domain::class_member::{ClassMember, ClassMemberId};
40use crate::domain::course::CourseId;
41use crate::domain::course::CourseKind;
42use crate::domain::grade::GradeLevel;
43use crate::domain::role::Role;
44use crate::domain::timestamp::Timestamp;
45use crate::domain::user::UserId;
46use crate::error::{AppError, ValidationError};
47
48/// What [`attach_course`]'s attach settled. The caller answers each verdict —
49/// a hand attach turns them into this route's errors; a blueprint pump reads
50/// them and carries on ([`crate::domain::class_blueprint`]).
51#[derive(Debug)]
52pub(crate) enum Attached<T> {
53 /// The link row, the counter and every enrollment it implied committed
54 /// together.
55 Made(T),
56 /// The link already exists — nothing was written, and no seat was spent
57 /// finding that out.
58 Duplicate,
59 /// The class row is gone (a concurrent delete won). Nothing was written.
60 Gone,
61 /// The *pivot* — on the course axis, the course being attached — is gone.
62 /// Nothing was written. Told apart from [`Attached::Gone`] because the two
63 /// send a caller to look at different records, and a report that guesses
64 /// between them names the wrong one half the time.
65 ///
66 /// On the **member** axis the pivot is the student, and this means their
67 /// row is gone *or* their role no longer is `student`. Its one caller
68 /// answers that as the `400` the route's own read already answers, never
69 /// as [`Attached::refusal_code`]'s `course_deleted` — which is the course
70 /// axis's word for it and would name a record this refusal is not about.
71 PivotGone,
72 /// The class is at its own ceiling on this axis. Nothing was written, and
73 /// it is told apart from [`Attached::Gone`] because a full class is a
74 /// standing row someone can make room in, not a 404.
75 ClassFull,
76 /// The class stands *above* the ceiling on the other axis, so the write
77 /// loop this attach would run is longer than any transaction is allowed to
78 /// be. Only a class predating the ceilings can be here, and only its own
79 /// axis can make room — which is why it is not [`Attached::ClassFull`].
80 ClassOverloaded,
81 /// One of the class's instances no longer exists, named by its id: a
82 /// `class_course` row a concurrent detach took while this pump was walking
83 /// its pairs. Nothing was written — not one of the earlier rows in the
84 /// same run, which is the whole point of doing this in a transaction. No
85 /// capacity anyone can raise will change that answer; the attach must be
86 /// retried against the class as it now stands.
87 CourseGone(String),
88 /// The blueprint this attach was sourced from is gone — a delete landed
89 /// between the pump reading the template and this transaction running.
90 /// Nothing was written, which is the point: a row tagged with a blueprint
91 /// that no longer exists is one nothing can ever sweep. Only a sourced
92 /// attach can be answered this.
93 SourceGone,
94}
95
96impl<T> Attached<T> {
97 /// This refusal as a **machine code**, or `None` for the attach that
98 /// landed. The client owns the wording and the language; this only says
99 /// *which* refusal it was — the shape every other enum here has (roles,
100 /// course kinds, the badge catalog).
101 ///
102 /// The single home for that vocabulary, because both readers answer it: a
103 /// blueprint pump reports it as a skip
104 /// ([`crate::domain::class_blueprint`]) and a hand attach as the `code` on
105 /// its `409` ([`crate::error::AppError::ConflictCoded`]). Spelled once, so
106 /// one cause can never grow two codes.
107 ///
108 /// Each code names the record that actually failed. The two "gone" answers
109 /// are a *class* delete ([`Attached::Gone`] → `class_deleted`) and a
110 /// *course* delete ([`Attached::PivotGone`] → `course_deleted`) — and
111 /// telling a manager the class vanished when the course did sends them to
112 /// look at a section that is standing right there. `linked_course_missing`
113 /// is a third: one of the class's *instances* vanished while the pump was
114 /// walking its pairs (a concurrent detach), so the attach must be retried
115 /// against the class as it now stands.
116 /// `blueprint_deleted` is a pump losing the template itself mid-run — the
117 /// only refusal that says nothing about the (class, course) pair it names.
118 ///
119 /// The `axis` is a parameter because two of these answers name a *different
120 /// ceiling* on each of them: [`Attached::ClassFull`] is the ceiling of the
121 /// axis being attached and [`Attached::ClassOverloaded`] the other axis's,
122 /// so a member add's "full" is a full roster where a course attach's is a
123 /// full course list ([`Axis::at_ceiling_code`]). Read blind, the same code
124 /// worded a full roster as a full course list.
125 pub(crate) fn refusal_code(&self, axis: &Axis) -> Option<&'static str> {
126 match self {
127 Attached::Made(_) => None,
128 Attached::Duplicate => Some("duplicate"),
129 Attached::Gone => Some("class_deleted"),
130 Attached::PivotGone => Some("course_deleted"),
131 Attached::ClassFull => Some(axis.at_ceiling_code()),
132 Attached::ClassOverloaded => Some(axis.other().over_ceiling_code()),
133 Attached::CourseGone(_) => Some("linked_course_missing"),
134 Attached::SourceGone => Some("blueprint_deleted"),
135 }
136 }
137}
138
139/// Which way the pump runs: the loop below needs a `(course, user)` pair per
140/// enrollment, and each caller supplies one side as a constant and reads the
141/// other off the class's *other* link table.
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub(crate) enum Axis {
144 /// A student joining: the courses come from `class_course`.
145 Member,
146 /// A course arriving: the students come from `class_member`.
147 Course,
148}
149
150impl Axis {
151 /// How many link rows this axis's counter may reach.
152 ///
153 /// This is what makes the pair loop in [`add_member`]/[`attach_course`]
154 /// finite, and it does it *crosswise*: the member axis's loop iterates the
155 /// class's `class_course` rows, which the course axis's counter caps, and
156 /// the course axis's loop iterates its `class_member` rows, which the
157 /// member axis's counter caps. So bounding the two counters bounds both
158 /// write loops — one transaction can never carry more than
159 /// `MAX_CLASS_MEMBERS`/`MAX_CLASS_COURSES` enrollment writes.
160 ///
161 /// Crosswise is also why the claim alone is not enough. It bounds the axis
162 /// being *added*, and the loop it runs is the length of the *other* one: a
163 /// class that already holds more members than `MAX_CLASS_MEMBERS` — the
164 /// layer shipped before either ceiling existed, so a real volume can carry
165 /// one — could still have a course attached, and that attach writes one
166 /// enrollment per member. So the attach checks the other axis too
167 /// ([`Axis::other`]), and the bound holds for stale classes as well.
168 fn cap(self) -> i64 {
169 match self {
170 Axis::Member => MAX_CLASS_MEMBERS,
171 Axis::Course => MAX_CLASS_COURSES,
172 }
173 }
174
175 /// The refusal code for "the class is *at* this axis's ceiling"
176 /// ([`Attached::ClassFull`]), taken off the axis beside the `cap` it
177 /// reports, because that ceiling and its name are one fact.
178 fn at_ceiling_code(self) -> &'static str {
179 match self {
180 Axis::Member => "class_at_roster_ceiling",
181 Axis::Course => "class_at_course_ceiling",
182 }
183 }
184
185 /// The refusal code for "the class stands *above* this axis's ceiling", so
186 /// the other axis's attach would run a write loop longer than a transaction
187 /// may be ([`Attached::ClassOverloaded`]). Answered off the axis that is
188 /// over, never the one being attached — the two are always different axes,
189 /// which is exactly what the blind version got wrong.
190 fn over_ceiling_code(self) -> &'static str {
191 match self {
192 Axis::Member => "class_roster_too_large",
193 Axis::Course => "class_course_list_too_large",
194 }
195 }
196
197 /// The axis whose link rows this one's write loop iterates — its counter is
198 /// the length of that loop, and its ceiling is therefore the second half of
199 /// the bound.
200 fn other(self) -> Axis {
201 match self {
202 Axis::Member => Axis::Course,
203 Axis::Course => Axis::Member,
204 }
205 }
206}
207
208/// The pivot of an attach: the row the link hangs off on its own axis, which
209/// must still be there — and, on the member axis, still name a `student` —
210/// when the transaction runs.
211enum Pivot<'a> {
212 User(&'a UserId),
213 Course(&'a CourseId),
214}
215
216/// The verdicts the shared prechecks can settle before any counter moves.
217enum Early {
218 Duplicate,
219 SourceGone,
220 PivotGone,
221 Overloaded,
222}
223
224fn refusal_of<T>(early: Early) -> Attached<T> {
225 match early {
226 Early::Duplicate => Attached::Duplicate,
227 Early::SourceGone => Attached::SourceGone,
228 Early::PivotGone => Attached::PivotGone,
229 Early::Overloaded => Attached::ClassOverloaded,
230 }
231}
232
233/// The gates that run before any counter moves, in the order their answers
234/// outrank each other:
235///
236/// 1. **Duplicate** — "you are already in" outranks every other answer: a
237/// caller whose row a rival placed a moment ago must be told they are in,
238/// not refused for a class ceiling they are not near. The member axis reads
239/// a **live** stint (a left one claims nothing, so rejoining is not a
240/// duplicate); the course axis reads the (class, course) pair. (The link
241/// tables re-answer this below — `23505` on the live-stint partial index,
242/// `ON CONFLICT DO NOTHING` on the enrollment pair — for a rival landing
243/// inside the window: same verdict, no second count.)
244/// 2. **Source** — the blueprint that asked for this attach is still there. A
245/// `FOR KEY SHARE` row lock on the blueprint row: it serializes the attach
246/// against the blueprint's own delete — the closure the old process-wide
247/// lease provided, now on the row itself. A concurrent blueprint `DELETE`
248/// waits behind it and its sweep finds the committed row, while an attach
249/// starting after the delete finds no row and writes nothing. `KEY SHARE`
250/// is the weakest strength that blocks the delete, so two sourced attaches
251/// still run concurrently, exactly as they did under the old shared read
252/// lease.
253///
254/// The same locked read resolves the surrogate `id` the link row will
255/// store: the stored tag is that uuid, not the grade label the API
256/// speaks, and it rides out of this gate to the insert below.
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>, Option<uuid::Uuid>, Option<CourseKind>), AppError> {
274 let held = match pivot {
275 Pivot::User(user) => sqlx::query_scalar!(
276 r#"SELECT 1 AS "one" FROM class_member
277 WHERE class = $1 AND app_user = $2 AND left_at IS NULL"#,
278 class as _,
279 user as _
280 )
281 .fetch_optional(&mut *tx)
282 .await?
283 .is_some(),
284 Pivot::Course(course) => sqlx::query_scalar!(
285 r#"SELECT 1 AS "one" FROM class_course WHERE class = $1 AND course = $2"#,
286 class as _,
287 course as _
288 )
289 .fetch_optional(&mut *tx)
290 .await?
291 .is_some(),
292 };
293 if held {
294 return Ok((Some(Early::Duplicate), None, None));
295 }
296 // The lock and the resolution are one read: the stored `source` is the
297 // blueprint's surrogate uuid, and the row this read returns it from is
298 // the very row the KEY SHARE lock holds against the blueprint's delete.
299 let mut source_id = None;
300 if let Some(source) = source {
301 let locked = sqlx::query_scalar!(
302 r#"SELECT id FROM class_blueprint WHERE grade_level = $1 FOR KEY SHARE"#,
303 source as _
304 )
305 .fetch_optional(&mut *tx)
306 .await?;
307 let Some(id) = locked else {
308 return Ok((Some(Early::SourceGone), None, None));
309 };
310 source_id = Some(id);
311 }
312 let mut kind = None;
313 match pivot {
314 Pivot::User(user) => {
315 let row = sqlx::query!(
316 r#"SELECT role AS "role: Role" FROM app_user WHERE id = $1 FOR NO KEY UPDATE"#,
317 user as _
318 )
319 .fetch_optional(&mut *tx)
320 .await?;
321 if row.map(|row| row.role) != Some(Role::Student) {
322 return Ok((Some(Early::PivotGone), None, None));
323 }
324 }
325 Pivot::Course(course) => {
326 // The lock and the kind in one read: the same `FOR KEY SHARE` the
327 // attach needs against a concurrent course delete answers what
328 // kind of course it is locking — and only a class-delivered ders
329 // may become an instance (the gate lives in [`attach_course`]).
330 let locked = sqlx::query!(
331 r#"SELECT kind AS "kind: CourseKind" FROM course WHERE id = $1 FOR KEY SHARE"#,
332 course as _
333 )
334 .fetch_optional(&mut *tx)
335 .await?;
336 let Some(locked_kind) = locked else {
337 return Ok((Some(Early::PivotGone), None, None));
338 };
339 kind = Some(locked_kind.kind);
340 }
341 }
342 // Read off the class row inside the transaction that claims it, so the
343 // count this refuses on is the one the pair loop below would iterate.
344 let over = match axis.other() {
345 Axis::Member => sqlx::query_scalar!(
346 r#"SELECT 1 AS "one" FROM class_group
347 WHERE id = $1 AND class_member_count > $2"#,
348 class as _,
349 Axis::Member.cap(),
350 )
351 .fetch_optional(&mut *tx)
352 .await?
353 .is_some(),
354 Axis::Course => sqlx::query_scalar!(
355 r#"SELECT 1 AS "one" FROM class_group
356 WHERE id = $1 AND class_course_count > $2"#,
357 class as _,
358 Axis::Course.cap(),
359 )
360 .fetch_optional(&mut *tx)
361 .await?
362 .is_some(),
363 };
364 Ok((over.then_some(Early::Overloaded), source_id, kind))
365}
366
367/// Write the member stint and enroll the student into every instance the
368/// class already carries, or write nothing at all.
369///
370/// A student already enrolled in one of those instances keeps the row they
371/// have — no count charged, and the existing row's `source` is left exactly
372/// as it was, so a hand-placed student is never quietly adopted by a class.
373///
374/// The class counter is claimed by the conditional half of the CTE below
375/// rather than a bare increment, so a class deleted out from under this run
376/// matches nothing and the whole cascade aborts: [`Attached::Gone`] instead of
377/// a counter on a row that no longer exists. The same write carries
378/// [`Axis::Member`]'s cap, which is what keeps the pair loop — and therefore
379/// this transaction — finite: [`Attached::ClassFull`] once the class is at its
380/// ceiling. Claim and insert are one statement, so a refused insert takes its
381/// own seat bump back.
382///
383/// The stint is live (`left_at` NULL) by construction, which is the row the
384/// partial unique index `class_member_live_pair` guards: a rival landing in
385/// the window is answered as [`Attached::Duplicate`] rather than a second
386/// live stint for the same pair. A student who left earlier keeps their
387/// history row — it claims nothing.
388pub(crate) async fn add_member(
389 db: &Database,
390 class: &ClassGroupId,
391 user: &UserId,
392 by: &UserId,
393) -> Result<Attached<ClassMember>, AppError> {
394 add_member_sourced(db, class, user, by, None).await
395}
396
397/// [`add_member`] carrying the stint's *provenance*: the section the student was
398/// copied from, written into `source_class_group` in the same statement as
399/// the row. `None` is the hand add — a student someone put here, who came
400/// from nowhere (the pump is the only writer of this column, and a rollover
401/// is the only caller that has a source to name).
402///
403/// Everything else — the claim, the cap, the duplicate verdict, the pair loop
404/// — is identical, and deliberately so: the tag rides the member axis's own
405/// single statement rather than a follow-up write, so a crash cannot leave a
406/// copied stint that lost its provenance.
407pub(crate) async fn add_member_sourced(
408 db: &Database,
409 class: &ClassGroupId,
410 user: &UserId,
411 by: &UserId,
412 source: Option<&ClassGroupId>,
413) -> Result<Attached<ClassMember>, AppError> {
414 let joined_at = Timestamp::now();
415 let class = class.clone();
416 let source = source.cloned();
417 let (user, by) = (*user, *by);
418 let id = ClassMemberId::generate();
419 let outcome = tx_with_retry(db, false, async move |tx| {
420 let (early, _, _) = early_verdicts(tx, &class, Axis::Member, Pivot::User(&user), None).await?;
421 if let Some(early) = early {
422 return Ok(refusal_of(early));
423 }
424 // The claim and the link are one statement (the cap recipe's CTE): the
425 // conditional `UPDATE` on the class row gates the `INSERT`, so a full
426 // or gone class writes nothing at all.
427 let inserted = match sqlx::query_scalar!(
428 r#"WITH seat AS (
429 UPDATE class_group SET class_member_count = class_member_count + 1
430 WHERE id = $1 AND class_member_count < $2
431 RETURNING 1)
432 INSERT INTO class_member (id, class, app_user, added_by, joined_at, left_at,
433 source_class_group)
434 SELECT $3, $1, $4, $5, $6, NULL, $7 WHERE EXISTS (SELECT 1 FROM seat)
435 RETURNING 1 AS "one""#,
436 class as _,
437 Axis::Member.cap(),
438 id.uuid(),
439 user as _,
440 by as _,
441 joined_at as _,
442 source.as_ref().map(ClassGroupId::uuid),
443 )
444 .fetch_optional(&mut *tx)
445 .await
446 {
447 Ok(result) => result,
448 // A rival landed in the window between the gate and the insert:
449 // the live-stint partial index answers, same verdict as the gate,
450 // no second seat. (A left row is not in that index, so a rejoin
451 // after a leave is never a duplicate.)
452 Err(e) if unique_violation(&e) == Some("class_member_live_pair") => {
453 return Ok(Attached::Duplicate);
454 }
455 // The student row vanished mid-run despite the locked pivot claim.
456 Err(e) if foreign_key_violation(&e) => return Ok(Attached::PivotGone),
457 Err(e) => return Err(e.into()),
458 };
459 if inserted.is_none() {
460 // Full, or the class is gone — the claim matches nothing either
461 // way, and only this path pays for the read that tells them apart.
462 let standing = sqlx::query_scalar!(
463 r#"SELECT 1 AS "one" FROM class_group WHERE id = $1"#,
464 class as _
465 )
466 .fetch_optional(&mut *tx)
467 .await?
468 .is_some();
469 return Ok(if standing {
470 Attached::ClassFull
471 } else {
472 Attached::Gone
473 });
474 }
475 // The pairs are the class's *instances*, one per attached course: the
476 // member axis now enrolls into the class×course instance, not into a
477 // school-wide course row.
478 let instances: Vec<uuid::Uuid> = sqlx::query_scalar!(
479 r#"SELECT id AS "id: uuid::Uuid" FROM class_course WHERE class = $1"#,
480 class as _
481 )
482 .fetch_all(&mut *tx)
483 .await?;
484 let pairs = instances
485 .into_iter()
486 .map(|instance| (instance, user.uuid()));
487 enroll_pairs(tx, &class, pairs, &by).await?;
488 Ok(Attached::Made(ClassMember {
489 id: id.clone(),
490 class: class.clone(),
491 user,
492 added_by: by,
493 joined_at,
494 left_at: None,
495 source_class_group: source.clone(),
496 }))
497 })
498 .await;
499 map_sweep_abort(outcome)
500}
501
502/// Write the instance and enroll the class's whole live roster into it, or
503/// write nothing at all.
504///
505/// Students already enrolled in it keep the rows they have — no count charged,
506/// `source` untouched. There is no roster-size gate any more (D5: the
507/// counter is a count, not a capacity), so the only refusals left are the
508/// class's own ceilings, a vanished pivot, and a course kind that is not
509/// class-delivered (a 400 straight out of the transaction).
510///
511/// `source` is the blueprint whose behalf this attach runs on, and supplying
512/// it adds one more claim: that it is still there when the transaction runs
513/// ([`Attached::SourceGone`]) — the `FOR KEY SHARE` lock that serializes this
514/// transaction against the blueprint's own delete. A hand attach owns itself
515/// and passes `None`.
516///
517/// The instance's own id is minted here (v7, so a class's instances list in
518/// creation order) and its content columns are born `NULL` — the *inherit*
519/// state: what the section teaches is whatever its grade-level
520/// [`crate::domain::course_offering::CourseOffering`] says, and through it
521/// the catalog course. That template is resolved (auto-created empty, with
522/// `created_by` naming the attaching actor, when the (course, grade_level)
523/// pair has none yet) in this same transaction — the class row is read under
524/// `FOR KEY SHARE`, so the offering the insert names is the one for the
525/// grade the class carries *at the attach*, not at the caller's read. A
526/// PATCH on `/instances` overrides the content afterwards.
527///
528/// Only a **class-delivered** course
529/// ([`CourseKind::is_class_delivered`], `kind = 'course'`) becomes an
530/// instance: a club or an etüt is joined individually and is refused with a
531/// 400, whatever axis asked for the attach.
532///
533/// Two counters ride the write, both in this one transaction: the class's
534/// `class_course_count` (claimed by the conditional CTE, so a full or gone
535/// class writes nothing) and the *catalog's* `class_course_count` — how many
536/// sections teach this course, which is what [`crate::db::course::delete`]'s
537/// guard reads. This is the only insert path into `class_course`; every layer
538/// above it (hand attach, blueprint pump, rollover copy) reaches the counter
539/// through here.
540pub(crate) async fn attach_course(
541 db: &Database,
542 class: &ClassGroupId,
543 course: &CourseId,
544 by: &UserId,
545 source: Option<&ClassBlueprintId>,
546) -> Result<Attached<ClassCourse>, AppError> {
547 let attached_at = Timestamp::now();
548 let class = class.clone();
549 let course = course.clone();
550 let by = *by;
551 let source = source.cloned();
552 let id = ClassCourseId::generate();
553 let outcome = tx_with_retry(db, false, async move |tx| {
554 let (early, source_id, kind) = early_verdicts(
555 tx,
556 &class,
557 Axis::Course,
558 Pivot::Course(&course),
559 source.as_ref(),
560 )
561 .await?;
562 if let Some(early) = early {
563 return Ok(refusal_of(early));
564 }
565 let Some(kind) = kind else {
566 // Unreachable on this axis — the course pivot always answers its
567 // kind when it is alive. A future axis change should surface as
568 // this 500, not as a wrong-looking refusal.
569 return Err(AppError::Internal(
570 "a course attach locked a course but read no kind".into(),
571 ));
572 };
573 if !kind.is_class_delivered() {
574 // The gate from the locked row itself, so a concurrent kind
575 // change cannot slip between a pre-flight check and the insert.
576 // A blueprint listing a study/club aborts that whole pump run
577 // with this 400 — fail-closed, naming the row to fix.
578 return Err(AppError::Validation(ValidationError::Invalid {
579 field: "course",
580 reason: "only a ders attaches to a class — a club or etüt is joined individually, not attached",
581 }));
582 }
583 // The class's own grade, locked: the offering the insert names is the
584 // one for the grade the class carries *now* (a concurrent grade move
585 // waits behind this KEY SHARE). A gone class answers `Gone` — the
586 // same verdict the seat claim below would have produced, one read
587 // earlier.
588 let grade_level = sqlx::query_scalar!(
589 r#"SELECT grade_level AS "grade_level: GradeLevel" FROM class_group
590 WHERE id = $1 FOR KEY SHARE"#,
591 class as _
592 )
593 .fetch_optional(&mut *tx)
594 .await?;
595 let Some(grade_level) = grade_level else {
596 return Ok(Attached::Gone);
597 };
598 // The template the instance teaches from: found, or minted empty
599 // (every content column NULL — inherit the catalog) with this actor
600 // as its `created_by`. Race-closed inside `ensure_tx`. Minted before
601 // the seat claim, so a refused attach (a full class) may leave an
602 // empty template behind — harmless: an empty template inherits the
603 // catalog exactly as no template would, and the next attach at that
604 // grade reuses it.
605 let offering =
606 crate::db::course_offering::ensure_tx(tx, &course, grade_level, &by).await?;
607 let inserted = match sqlx::query_scalar!(
608 r#"WITH seat AS (
609 UPDATE class_group SET class_course_count = class_course_count + 1
610 WHERE id = $1 AND class_course_count < $2
611 RETURNING 1)
612 INSERT INTO class_course (id, class, course, attached_by, attached_at, source, offering)
613 SELECT $3, $1, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM seat)
614 RETURNING 1 AS "one""#,
615 class as _,
616 Axis::Course.cap(),
617 id.uuid(),
618 course as _,
619 by as _,
620 attached_at as _,
621 source_id,
622 offering as _,
623 )
624 .fetch_optional(&mut *tx)
625 .await
626 {
627 Ok(result) => result,
628 Err(e) if unique_violation(&e) == Some("class_course_class_course") => {
629 return Ok(Attached::Duplicate);
630 }
631 Err(e) if foreign_key_violation(&e) => return Ok(Attached::PivotGone),
632 Err(e) => return Err(e.into()),
633 };
634 if inserted.is_none() {
635 let standing = sqlx::query_scalar!(
636 r#"SELECT 1 AS "one" FROM class_group WHERE id = $1"#,
637 class as _
638 )
639 .fetch_optional(&mut *tx)
640 .await?
641 .is_some();
642 return Ok(if standing {
643 Attached::ClassFull
644 } else {
645 Attached::Gone
646 });
647 }
648 // The catalog's own counter: how many sections teach this course. It is
649 // what [`crate::db::course::delete`]'s guard reads — a course a class
650 // still teaches may not go — and this insert is the only place it can
651 // be claimed. It is a *count*, not a capacity (D5: nothing is refused
652 // for being near it), so it is a plain increment in the same
653 // transaction as the row: the link and its count commit together, and
654 // the early refusals above (a full or gone class, a lost insert) have
655 // already returned, so no give-back path exists to get wrong.
656 sqlx::query!(
657 r#"UPDATE course SET class_course_count = class_course_count + 1 WHERE id = $1"#,
658 course as _
659 )
660 .execute(&mut *tx)
661 .await?;
662 // The roster is the class's *live* stints: a student who left holds no
663 // seat and is enrolled in nothing the class attaches afterwards.
664 let members: Vec<uuid::Uuid> = sqlx::query_scalar!(
665 r#"SELECT app_user AS "app_user: uuid::Uuid" FROM class_member
666 WHERE class = $1 AND left_at IS NULL"#,
667 class as _
668 )
669 .fetch_all(&mut *tx)
670 .await?;
671 let pairs = members.into_iter().map(|user| (id.uuid(), user));
672 enroll_pairs(tx, &class, pairs, &by).await?;
673 // The counter the pair loop just moved, read back inside the
674 // transaction so the returned row reports the roster it now has
675 // rather than the empty one it was inserted with.
676 let enrollment_count = sqlx::query_scalar!(
677 r#"SELECT enrollment_count AS "count: i64" FROM class_course WHERE id = $1"#,
678 id.uuid()
679 )
680 .fetch_one(&mut *tx)
681 .await?;
682 Ok(Attached::Made(ClassCourse {
683 id: id.clone(),
684 class: class.clone(),
685 course: course.clone(),
686 offering: offering.clone(),
687 attached_by: by,
688 source,
689 title: None,
690 description: None,
691 ders_saati: None,
692 counts_toward_karne: None,
693 subjects_inherited: true,
694 exam_weights_inherited: true,
695 weekly_plan_inherited: true,
696 enrollment_count,
697 attached_at,
698 }))
699 })
700 .await;
701 map_sweep_abort(outcome)
702}
703
704/// Abort markers the pair loop raises where the old transaction `THROW` did,
705/// in the [`crate::db::field_update`] style: a refusal found *after* earlier
706/// pairs wrote must take the whole run down with it — returning it as `Ok`
707/// would COMMIT the partial enrollment. The marker carries the instance's id
708/// and is mapped back to [`Attached`] right after [`tx_with_retry`] returns
709/// ([`map_sweep_abort`]); it never reaches the wire.
710const COURSE_GONE_MARK: &str = "class_pump_course_gone:";
711
712/// The pair loop's abort markers back into their [`Attached`] refusals —
713/// every other outcome passes through untouched.
714fn map_sweep_abort<T>(outcome: Result<Attached<T>, AppError>) -> Result<Attached<T>, AppError> {
715 match outcome {
716 Err(AppError::Internal(m)) if m.starts_with(COURSE_GONE_MARK) => Ok(Attached::CourseGone(
717 m[COURSE_GONE_MARK.len()..].to_string(),
718 )),
719 other => other,
720 }
721}
722
723/// Enroll every `(instance, user)` pair that has no row yet, and charge the
724/// instance's roster counter only for the rows actually written.
725///
726/// Per pair, in the order the answers outrank each other: the pair's own row
727/// answers "already enrolled" (skip, no count moved); the counter claim is a
728/// plain increment on the instance row, so it doubles as the existence check —
729/// a claim matching nothing is an instance a concurrent detach took, which is
730/// the abort marker rather than a refusal of this pair alone; and then the
731/// row is inserted with `ON CONFLICT DO NOTHING`, so a rival landing between
732/// the gate and the insert leaves *their* row standing and this run gives its
733/// own claim back before the skip.
734///
735/// Every abort stops the loop inside the caller's transaction: not one of the
736/// earlier rows in the same run survives, which is the whole point of doing
737/// this in a transaction.
738async fn enroll_pairs(
739 tx: &mut PgConnection,
740 class: &ClassGroupId,
741 pairs: impl Iterator<Item = (uuid::Uuid, uuid::Uuid)>,
742 by: &UserId,
743) -> Result<(), AppError> {
744 let now = Timestamp::now();
745 for (instance, user) in pairs {
746 let held = sqlx::query_scalar!(
747 r#"SELECT 1 AS "one" FROM enrollment WHERE class_course = $1 AND app_user = $2"#,
748 instance,
749 user
750 )
751 .fetch_optional(&mut *tx)
752 .await?
753 .is_some();
754 if held {
755 continue;
756 }
757 // The claim doubles as the existence check: there is no capacity to
758 // refuse on, so an increment that matches no row means the instance is
759 // gone — a stale link, never a full roster.
760 let claimed = sqlx::query_scalar!(
761 r#"UPDATE class_course SET enrollment_count = enrollment_count + 1
762 WHERE id = $1
763 RETURNING 1 AS "one""#,
764 instance,
765 )
766 .fetch_optional(&mut *tx)
767 .await?
768 .is_some();
769 if !claimed {
770 return Err(AppError::Internal(format!("{COURSE_GONE_MARK}{instance}")));
771 }
772 let wrote = sqlx::query_scalar!(
773 r#"INSERT INTO enrollment (class_course, app_user, enrolled_by, source, created_at)
774 VALUES ($1, $2, $3, $4, $5)
775 ON CONFLICT (class_course, app_user) DO NOTHING
776 RETURNING 1 AS "one""#,
777 instance,
778 user,
779 by as _,
780 class as _,
781 now.as_millis()
782 )
783 .fetch_optional(&mut *tx)
784 .await;
785 match wrote {
786 Ok(Some(_)) => {}
787 // A rival placed the pair in the window: their row stands, no
788 // second count, and the claim this run took is given back — the
789 // skip wins, exactly as a re-sent transaction found the row at its
790 // gate.
791 Ok(None) => {
792 sqlx::query!(
793 r#"UPDATE class_course
794 SET enrollment_count = GREATEST(enrollment_count - 1, 0)
795 WHERE id = $1"#,
796 instance
797 )
798 .execute(&mut *tx)
799 .await?;
800 }
801 Err(e) => return Err(e.into()),
802 }
803 }
804 Ok(())
805}
806
807// The sweep a role change *off` `student` owes — every class membership (each
808// class getting its member count back) and every enrollment row (each course
809// getting its seat back) — is two of the arms of
810// [`crate::service::user::set_role`], because it belongs in the same
811// transaction as the role write that invalidates them. It stays one fact with
812// the counters either way: released separately, a failure between the halves
813// left enrollment rows tagged `source = class_group:X` while the class had its
814// counters back, so the class passed its zero-zero delete guard and the rows
815// were left pointing at a class no sweep could ever reach again.
816
817/// Take a student out of a class and sweep the enrollments the class pumped
818/// for them. Answers how many stints went (0 or 1), so the caller can turn
819/// zero into a 404.
820///
821/// This is the hard form — the row is deleted — and it is kept only for the
822/// transfer rollback path, where the stint being undone must leave no trace.
823/// The route uses [`leave_member`], which stamps `left_at` and keeps the
824/// history.
825pub(crate) async fn remove_member(
826 db: &Database,
827 class: &ClassGroupId,
828 user: &UserId,
829) -> Result<i64, AppError> {
830 drop_member(db, class, user, false).await
831}
832
833/// The same exit, soft: `left_at` is stamped and the row stays as history.
834/// The roster read and the cap both filter on `left_at IS NULL`, so the
835/// student holds no seat from this moment — and a rejoin later inserts a
836/// fresh live row beside this one (the partial unique index only guards the
837/// live stint), which is how "left in October, came back in January" is
838/// represented.
839///
840/// Both exits take the user row `FOR NO KEY UPDATE` first — the same lock the
841/// pump's pivot claim and a role-change sweep take — so a demotion cannot
842/// interleave with this write in either direction.
843pub(crate) async fn leave_member(
844 db: &Database,
845 class: &ClassGroupId,
846 user: &UserId,
847) -> Result<i64, AppError> {
848 drop_member(db, class, user, true).await
849}
850
851/// The one body both exits run: find the live stint, end it, give the class
852/// its seat back, and release the enrollments the class pumped for the
853/// student.
854///
855/// The sweep's rule, and it is the whole rule: **every row the ended stint
856/// owned goes, and each instance gets its roster count back**. An enrollment
857/// is keyed `(class_course, app_user)` — one row per *instance* — so a student
858/// in two sections that teach the same course holds two rows, one on each
859/// section's instance, and the seat they keep is the other section's own row,
860/// written when they joined it. Handing this row over to a rival class (the
861/// pre-remodel rule, when one school-wide course carried one roster) would
862/// leave the leaving section's roster, exams and roll-call still listing a
863/// student who left it, with its `enrollment_count` inflated on top — a
864/// "repair" that repairs nothing, because there was never a shortage of rows
865/// to repair.
866///
867/// Only the rows *this class* wrote are in the list ([`drop_member`] reads
868/// `source = <class>`), so a hand-placed enrollment — the operator's own, or
869/// one a section handed over before this rule — is never touched.
870///
871/// Sweeps tolerate rows that are already gone: an instance detach wipes its
872/// own enrollments wholesale while the `class_member` rows survive it, so
873/// "this class has a member" and "that member has a live pumped row" are
874/// independent facts and the loop simply finds nothing to sweep (and, because
875/// [`release`] only gives a count back for a row it actually deleted, takes
876/// nothing back twice).
877async fn drop_member(
878 db: &Database,
879 class: &ClassGroupId,
880 user: &UserId,
881 soft: bool,
882) -> Result<i64, AppError> {
883 let class = class.clone();
884 let user = *user;
885 let now = Timestamp::now();
886 tx_with_retry(db, true, async move |tx| {
887 // The role-claim handshake: the same `FOR NO KEY UPDATE` the pump's
888 // pivot takes, so a demotion's sweep and this exit serialize on the
889 // user row rather than interleaving.
890 sqlx::query!(
891 r#"SELECT role FROM app_user WHERE id = $1 FOR NO KEY UPDATE"#,
892 user as _
893 )
894 .fetch_optional(&mut *tx)
895 .await?;
896 let gone = if soft {
897 sqlx::query_scalar!(
898 r#"UPDATE class_member SET left_at = $3
899 WHERE class = $1 AND app_user = $2 AND left_at IS NULL
900 RETURNING 1 AS "one""#,
901 class as _,
902 user as _,
903 now as _
904 )
905 .fetch_optional(&mut *tx)
906 .await?
907 } else {
908 sqlx::query_scalar!(
909 r#"DELETE FROM class_member
910 WHERE class = $1 AND app_user = $2 AND left_at IS NULL
911 RETURNING 1 AS "one""#,
912 class as _,
913 user as _
914 )
915 .fetch_optional(&mut *tx)
916 .await?
917 };
918 let Some(_) = gone else {
919 return Ok(0);
920 };
921 sqlx::query!(
922 r#"UPDATE class_group
923 SET class_member_count = GREATEST(class_member_count - 1, 0)
924 WHERE id = $1"#,
925 class as _
926 )
927 .execute(&mut *tx)
928 .await?;
929 // Only the rows *this class* wrote: a hand-placed enrollment is the
930 // operator's and is never taken back by a class sweep.
931 let rows = sqlx::query!(
932 r#"SELECT class_course AS "class_course: uuid::Uuid",
933 app_user AS "app_user: uuid::Uuid"
934 FROM enrollment WHERE app_user = $1 AND source = $2"#,
935 user as _,
936 class as _
937 )
938 .fetch_all(&mut *tx)
939 .await?
940 .into_iter()
941 .map(|row| (row.class_course, row.app_user))
942 .collect::<Vec<_>>();
943 // Every row this class's tag owns goes, and each instance gets its
944 // roster count back — see the doc above: the student's seat in a
945 // second section teaching the same course is that section's *own* row, so
946 // there is no heir to hand this one over to.
947 for (instance, member) in rows {
948 release(tx, instance, member).await?;
949 }
950 Ok(1)
951 })
952 .await
953}
954
955/// Detach one instance from its class and sweep what hangs off it. `source`,
956/// when given, re-asserts the provenance tag on the link's own delete — a
957/// blueprint sweep may only take back rows its own tag owns. Answers the blob
958/// keys of the image and homework-file rows the sweep removed, or `None` when
959/// the pair held no instance at all (nothing written), so a caller whose link
960/// was a single pair can turn `None` into a 404 while a detach that removed an
961/// instance carrying no uploads still reads as one that went.
962///
963/// The instance is the anchor now, so detaching it takes everything the class
964/// taught under it: its exams (with their results and questions), its sessions
965/// with their roll call, its homework with its submissions, its roster and its
966/// teacher links. That is the same cascade a course delete runs
967/// ([`crate::db::course::sweep_instance_subtree`]), scoped to one instance —
968/// and it has to be, because every one of those rows names the instance as its
969/// parent key (`ON DELETE NO ACTION`), so deleting the instance while they
970/// stand is refused by the store itself.
971///
972/// The sweep runs behind a `FOR UPDATE` claim on the instance row: a rival
973/// detach waits here and finds nothing left to sweep, so exactly one
974/// transaction unlinks the pair and gives the class its counter back — and
975/// with it the catalog's `class_course_count`, the count
976/// [`crate::db::course::delete`]'s guard reads (`course::delete` needs no
977/// release of its own: it deletes the course row the counter lives on).
978/// This is the only delete path for an instance that does *not* remove the
979/// course: the hand detach and the blueprint sweep both come through it.
980///
981/// The image and homework-file *blobs* the cascade removes come back as keys
982/// and are unlinked by the caller, after the commit — the same shape
983/// [`crate::service::course::delete`] has. The rows are gone the moment this
984/// returns, so a caller that drops the list strands the bytes on disk with
985/// nothing left pointing at them.
986pub(crate) async fn detach_course(
987 db: &Database,
988 class: &ClassGroupId,
989 course: &CourseId,
990 source: Option<&ClassBlueprintId>,
991) -> Result<Option<Vec<String>>, AppError> {
992 let class = class.clone();
993 let course = course.clone();
994 let source = source.cloned();
995 tx_with_retry(db, true, async move |tx| {
996 // The claim and the resolution in one read: the row this returns is
997 // the very row the lock holds against a rival detach.
998 let target = match &source {
999 Some(source) => {
1000 sqlx::query_scalar!(
1001 r#"SELECT id AS "id: uuid::Uuid" FROM class_course
1002 WHERE class = $1 AND course = $2
1003 AND source = (SELECT id FROM class_blueprint WHERE grade_level = $3)
1004 FOR UPDATE"#,
1005 class as _,
1006 course as _,
1007 source as _
1008 )
1009 .fetch_optional(&mut *tx)
1010 .await?
1011 }
1012 None => {
1013 sqlx::query_scalar!(
1014 r#"SELECT id AS "id: uuid::Uuid" FROM class_course
1015 WHERE class = $1 AND course = $2 FOR UPDATE"#,
1016 class as _,
1017 course as _
1018 )
1019 .fetch_optional(&mut *tx)
1020 .await?
1021 }
1022 };
1023 let Some(instance) = target else {
1024 return Ok(None);
1025 };
1026 let blobs = crate::db::course::sweep_instance_subtree(&mut *tx, instance).await?;
1027 sqlx::query!(r#"DELETE FROM class_course WHERE id = $1"#, instance)
1028 .execute(&mut *tx)
1029 .await?;
1030 sqlx::query!(
1031 r#"UPDATE class_group
1032 SET class_course_count = GREATEST(class_course_count - 1, 0)
1033 WHERE id = $1"#,
1034 class as _
1035 )
1036 .execute(&mut *tx)
1037 .await?;
1038 // …and the catalog's own counter: the course is taught in one fewer
1039 // section from this commit. Same transaction as the delete, so the link
1040 // and its count move together — `course::delete`'s guard reads this,
1041 // and a course whose last instance was just detached is deletable the
1042 // moment this lands. `GREATEST` for the same reason the class counter
1043 // uses it: a drift can only ever be repaired downward, never refused.
1044 sqlx::query!(
1045 r#"UPDATE course SET class_course_count = GREATEST(class_course_count - 1, 0)
1046 WHERE id = $1"#,
1047 course as _
1048 )
1049 .execute(&mut *tx)
1050 .await?;
1051 Ok(Some(blobs))
1052 })
1053 .await
1054}
1055
1056/// The row goes, and the instance's roster count with it. It is the *only*
1057/// fate for an enrollment a section's exit owns: the roster is per instance
1058/// (D4), so a student who is also in another section teaching the same course
1059/// keeps their seat there through that section's own row — see
1060/// [`drop_member`].
1061///
1062/// The count is only given back when the delete actually took the row — an
1063/// instance detach's wholesale sweep may have taken both while this
1064/// transaction read them, and both halves vanish together there.
1065async fn release(
1066 tx: &mut PgConnection,
1067 instance: uuid::Uuid,
1068 user: uuid::Uuid,
1069) -> Result<(), AppError> {
1070 let deleted = sqlx::query!(
1071 r#"DELETE FROM enrollment WHERE class_course = $1 AND app_user = $2"#,
1072 instance,
1073 user
1074 )
1075 .execute(&mut *tx)
1076 .await?
1077 .rows_affected();
1078 if deleted > 0 {
1079 sqlx::query!(
1080 r#"UPDATE class_course
1081 SET enrollment_count = GREATEST(enrollment_count - 1, 0)
1082 WHERE id = $1"#,
1083 instance
1084 )
1085 .execute(&mut *tx)
1086 .await?;
1087 }
1088 Ok(())
1089}
1090
1091#[cfg(test)]
1092mod tests {
1093
1094 use crate::db::class_member::tests::{a_class, counter, fixture_user, rows};
1095 use crate::domain::class_group::ClassGroupId;
1096 use crate::error::AppError;
1097 use crate::service::class_member;
1098
1099 /// The class counter is claimed conditionally, so a class that is not there
1100 /// stops the cascade before anything is written — rather than leaving a
1101 /// counter, a link row and a pumped enrollment hanging off a record that
1102 /// does not exist.
1103 #[tokio::test]
1104 async fn an_attach_onto_a_missing_class_writes_nothing() {
1105 let (db, _leases) = crate::database::init_test_db().await;
1106 let ghost = ClassGroupId::from_key("019732e3-7b00-7000-8000-00000000dead");
1107
1108 let refused = class_member::add(
1109 &db,
1110 &ghost,
1111 &fixture_user(&db, "student").await,
1112 &fixture_user(&db, "manager").await,
1113 )
1114 .await;
1115 assert!(
1116 matches!(refused, Err(AppError::NotFound)),
1117 "a class that is gone is a 404, not a counter on nothing: {refused:?}"
1118 );
1119 assert_eq!(rows("class_member", &db).await, 0);
1120 assert_eq!(rows("class_group", &db).await, 0);
1121 }
1122
1123 /// The role-change sweep takes a user's whole membership apart, link row
1124 /// by link row (one transaction per pair since the Postgres port), and
1125 /// every one of them releases its own class's counter.
1126 #[tokio::test]
1127 async fn a_detach_releases_every_class_it_unlinked() {
1128 let (db, _leases) = crate::database::init_test_db().await;
1129 let manager = fixture_user(&db, "manager").await;
1130 let student = fixture_user(&db, "student").await;
1131 let classes = [
1132 a_class("9-A", &db).await,
1133 a_class("9-B", &db).await,
1134 a_class("club", &db).await,
1135 ];
1136 for class in &classes {
1137 class_member::add(&db, class, &student, &manager)
1138 .await
1139 .unwrap();
1140 }
1141
1142 for class in &classes {
1143 class_member::remove(&db, class, &student).await.unwrap();
1144 }
1145 for class in &classes {
1146 assert_eq!(
1147 counter("class_member_count", class.uuid(), &db).await,
1148 0,
1149 "each class gets its own counter back"
1150 );
1151 }
1152
1153 // And unlinking nobody is a 404, not a silent success — the shape a
1154 // single-pair detach answers with.
1155 let again = class_member::remove(&db, &classes[0], &student).await;
1156 assert!(
1157 matches!(again, Err(AppError::NotFound)),
1158 "a second removal is a 404, not a silent no-op: {again:?}"
1159 );
1160 }
1161}