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_blueprint.rs913 lines, 39.4 KiBHistoryRawDownload
1//! Grade-blueprint workflows: creating a template and pumping it across a
2//! whole grade, the edit that retro-pumps, the delete that takes the
3//! attachments it made with it, and the per-class apply they all share. The
4//! queries live in [`crate::db::class_blueprint`]; the row shape and the
5//! skip vocabulary in [`crate::domain::class_blueprint`].
6//!
7//! Two rules shape everything below.
8//!
9//! **An edit retro-pumps.** Changing the list reaches every class already at
10//! that grade, not just the ones made afterwards. That is an unbounded write
11//! loop — one transaction per (class, course), and no ceiling bounds the
12//! number of classes — chosen deliberately over a template that only new
13//! classes see.
14//!
15//! **A pump is best-effort.** Each (class, course) pair is one all-or-nothing
16//! transaction of the existing pump, and a pair that would breach a limit is
17//! *skipped and reported* rather than aborting the other classes' share. So a
18//! blueprint edit can leave a partial state — which is the point: one full
19//! course must not stop the other eleven sections from being stocked. Every
20//! skip is returned, naming the class, the course and the reason.
21//!
22//! Removal is the mirror, and it is where the provenance tag earns its keep:
23//! a `class_course` row this blueprint wrote carries `source`, a row a human
24//! attached carries no such key at all, and dropping a course from the
25//! blueprint sweeps only the former. The sweep is the pump's own
26//! [`crate::db::class_pump::detach`], so a class losing a course still
27//! repairs before it deletes — and it runs one transaction per pair too, for
28//! the same reason the pump does.
29
30use crate::database::Database;
31use crate::db::class_blueprint;
32use crate::db::class_course;
33use crate::db::class_group;
34use crate::db::class_pump::Attached;
35use crate::domain::class_blueprint::{
36 ClassBlueprint, ClassBlueprintId, Pumped, SectionStatus, Skip, skip_reason,
37};
38use crate::domain::class_group::{ClassGroup, ClassGroupId};
39use crate::domain::grade::GradeLevel;
40use crate::domain::course::CourseId;
41use crate::domain::user::UserId;
42use crate::error::AppError;
43
44/// Write the blueprint after settling the course list
45/// ([`ClassBlueprint::course_list`]) — the same validation, in the same
46/// order, the single write this replaced did. One blueprint per grade: a
47/// duplicate is a `409` the store itself decides.
48pub async fn create(
49 db: &Database,
50 creator: &UserId,
51 grade_level: GradeLevel,
52 courses: Vec<CourseId>,
53) -> Result<ClassBlueprint, AppError> {
54 let courses = ClassBlueprint::course_list(courses)?;
55 class_blueprint::create(db, creator, grade_level, courses).await
56}
57
58/// The row, for callers that only inspect it — the web layer's
59/// `blueprint_or_404` reads through here.
60pub async fn read(
61 db: &Database,
62 id: &ClassBlueprintId,
63) -> Result<Option<ClassBlueprint>, AppError> {
64 class_blueprint::read(db, id).await
65}
66
67/// Every blueprint, by grade label — the web layer's paged index.
68pub async fn list_all(
69 db: &Database,
70 limit: Option<i64>,
71 offset: i64,
72) -> Result<(Vec<ClassBlueprint>, i64), AppError> {
73 class_blueprint::list_all(db, limit, offset).await
74}
75
76/// Replace the course list, then reconcile every class at this grade with
77/// it: the courses this blueprint no longer holds are detached from the
78/// classes *it* attached them to, and the ones it holds are pumped into
79/// every class that fits.
80///
81/// The write is a compare-and-set on the list this caller read
82/// ([`class_blueprint::set_courses_if_unchanged`]), so two
83/// managers editing the same grade cannot have one's list silently pump the
84/// other's diff — the loser is a 409 and re-reads.
85///
86/// Removals run first: a course leaving frees a place under the per-class
87/// course ceiling that the same edit's additions can then use. What is swept
88/// is derived from the list this write **stored**, never from a diff against
89/// the list this handle read ([`class_blueprint::sourced_links`]): the sweep is N
90/// sequential transactions in one request, and a failure part-way through
91/// used to leave sections carrying courses the template no longer holds with
92/// no way back — a re-`PATCH` recomputed an empty diff, and the documented
93/// self-heal ("send the list it already holds") swept nothing. Derived from
94/// the stored list, that same re-`PATCH` finds the rows still tagged and
95/// finishes the job.
96///
97/// The price is the other direction: a rival edit that lands *and pumps*
98/// between this write and this sweep has its new course detached again,
99/// because this sweep asks the list it stored. That is a section short a
100/// templated course — what [`status`] reports and the next pump
101/// repairs — where the diff's failure was a row no call could reach.
102///
103/// Takes no lease of its own, deliberately: a lease held across its own pump
104/// would deadlock on the locks that pump takes, and it would close nothing
105/// anyway — the attach's claim asks whether the blueprint *exists*, not what
106/// it holds, so an edit racing a pump is only ever the retro-pump this
107/// feature is built on. Rows a racing edit leaves behind stay reachable,
108/// because [`delete`] sweeps the whole tag rather than a list.
109///
110/// Answers `(the stored template, what the pump did, the blob keys the
111/// removals swept)`: detaching an instance takes its exams'/homework's images
112/// and files with it ([`class_blueprint::drop_links`]), and those rows are
113/// gone by the time this returns, so the keys have to reach the caller's route
114/// to be unlinked. They ride out as a third element rather than inside
115/// [`Pumped`] — the pump never touched a blob, and said so.
116pub async fn set_courses(
117 db: &Database,
118 blueprint: ClassBlueprint,
119 courses: Vec<CourseId>,
120 by: &UserId,
121) -> Result<(ClassBlueprint, Pumped, Vec<String>), AppError> {
122 let wanted = ClassBlueprint::course_list(courses)?;
123 let Some(mut saved) = class_blueprint::set_courses_if_unchanged(
124 db,
125 &blueprint.id,
126 blueprint.courses.clone(),
127 wanted,
128 )
129 .await?
130 else {
131 // The conditional write matched nothing: the row is gone, or its
132 // list moved since this caller read it. Only this path pays for the
133 // read that tells those apart.
134 return match read(db, &blueprint.id).await? {
135 Some(_) => Err(AppError::Conflict(
136 "this blueprint changed since you read it — re-read and retry",
137 )),
138 None => Err(AppError::NotFound),
139 };
140 };
141 let doomed = class_blueprint::sourced_links(db, saved.get_id(), &saved.courses).await?;
142 let blob_keys = class_blueprint::drop_links(db, saved.get_id(), doomed).await?;
143 let pumped = pump(db, &mut saved, by).await?;
144 Ok((saved, pumped, blob_keys))
145}
146
147/// Delete the blueprint, taking every attachment it made with it. Courses a
148/// human attached to those classes by hand carry no `source` and are left
149/// exactly where they are — the same cut a single removal makes, applied to
150/// the whole list, because a template that is gone owns nothing.
151///
152/// The row goes **first**, and the sweep that follows is by the provenance
153/// tag rather than by the list this caller read. Sweeping first was the
154/// mirror image of a race: a `PATCH` adding a course and pumping it while
155/// this ran landed rows tagged with a blueprint the delete then removed,
156/// and nothing could ever sweep them again — the grade label *is* the
157/// primary key, so only a blueprint recreated at that grade could even name
158/// them. Never revert to sweep-first.
159///
160/// Deleting first plus the attach's in-transaction claim on this row
161/// ([`Attached::SourceGone`]) **closes** that window outright: the claim is
162/// not a bare read but a `FOR KEY SHARE` row lock on `class_blueprint`, the
163/// one strength a `DELETE` of the row cannot take. A sourced attach that
164/// started first holds the row and this delete's `DELETE` waits behind it —
165/// the row the attach commits is then in the set the sweep reads; an attach
166/// starting after the delete finds no row and writes nothing. (Under the
167/// old engine the claim was a plain read that no `BEGIN`/`COMMIT` pair
168/// serialized against this delete's write, and a process-wide `RwLock` had
169/// to stand in; the row lock is the same answer without the process.)
170///
171/// What is left is a **process crash** between the delete and the sweep.
172/// That leaves inert `class_course` rows tagged with a blueprint that is
173/// gone; they are still detachable one at a time at
174/// `DELETE /classes/{id}/courses/{course}`, and every counter stays exact
175/// because each detach is its own transaction.
176///
177/// The delete is a compare-and-set on the list this caller read, like
178/// [`set_courses`]: an edit landing in between is a `409` rather than
179/// a silent detach of somebody else's additions. Known hole, accepted: the
180/// grade label *is* the primary key and the comparison is by **content**, so
181/// a blueprint deleted and recreated at the same grade with the same list
182/// names the same course set as the stored junction rows, and this call
183/// deletes the *new* row.
184///
185/// Content-equal is intent-equal — the end state is the one the caller
186/// asked for — and telling the two apart needs a revision column on the
187/// row, which nothing else here would use.
188///
189/// Answers the blob keys the tag sweep's detaches removed
190/// ([`class_blueprint::drop_links`]): each detached instance took its exams'
191/// and homework's images and files with it, and the rows are gone by the time
192/// this returns, so those names have to reach the route to be unlinked. The
193/// keys are the sweep's, not the caller's — a hand-attached course carries no
194/// tag and is not swept, so nothing of its is in the list. A failure between
195/// the sweep and the commit drops them, the same accepted window the rest of
196/// this doc covers.
197pub async fn delete(db: &Database, blueprint: ClassBlueprint) -> Result<Vec<String>, AppError> {
198 // The claim, the sweep and the delete are one transaction — the shape
199 // Postgres demands and the doc above argues for. The old order (delete
200 // the row on the pool, then sweep) cannot work against an enforcing
201 // foreign key: the delete statement itself is refused the instant a
202 // sourced link it has not swept yet exists, and a link committing
203 // between the row lock's release and the sweep re-arms the same
204 // refusal. Holding the claim across the sweep closes the window: an
205 // attach in flight waits behind it and finds no row; an attach that
206 // committed first is in the set the sweep reads.
207 let mut tx = db.begin().await?;
208 let Some(stored) = class_blueprint::held_courses_for_update(&mut tx, &blueprint.id).await?
209 else {
210 // Gone before we claimed it.
211 return Err(AppError::NotFound);
212 };
213 if stored != blueprint.courses {
214 // The list moved since this caller read it: a 409, not a silent
215 // detach of somebody else's additions.
216 return Err(AppError::Conflict(
217 "this blueprint changed since you read it — re-read and retry",
218 ));
219 }
220 // The sweep runs on its own bounded transactions while this transaction
221 // holds the claim: it touches no `class_blueprint` rows, so it cannot
222 // deadlock against the lock it runs under.
223 let doomed = class_blueprint::sourced_links(db, &blueprint.id, &[]).await?;
224 let blob_keys = class_blueprint::drop_links(db, &blueprint.id, doomed).await?;
225 if !class_blueprint::delete_if_unchanged_in(&mut tx, &blueprint.id, &blueprint.courses).await? {
226 // The row was locked, matched at the claim, and vanished anyway:
227 // nothing does that but a bug.
228 return Err(AppError::Internal(
229 "the claimed blueprint row did not survive its own lock".into(),
230 ));
231 }
232 tx.commit().await?;
233 Ok(blob_keys)
234}
235
236/// Attach every course in this blueprint to `class`, skipping — never
237/// aborting on — the ones that do not fit. A course already on the class is
238/// a no-op, whoever attached it: this is what makes a pump repeatable, and
239/// what stops it re-tagging a hand-attached course as its own.
240///
241/// This is the *only* place a sourced attach is made — [`pump`], the
242/// create-time and per-class pumps in [`crate::web::classes`] all come
243/// through here — and each attach's transaction takes a `FOR KEY SHARE`
244/// lock on the blueprint row itself, one course at a time. A delete landing
245/// mid-pump is then clean by construction: the attaches that already
246/// committed are found by its tag sweep, and the ones that have not yet
247/// started meet the deleted row at their own in-transaction claim and
248/// answer `blueprint_deleted`. Per course rather than per pump, because the
249/// pump's loop is unbounded and a delete may not wait behind all of it.
250///
251/// One class, so `blueprint_deleted` is an ordinary skip here: the courses
252/// after it are not tried, because the template they would ask for is the
253/// one that just went.
254pub async fn apply_to(
255 db: &Database,
256 blueprint: &ClassBlueprint,
257 class: &ClassGroup,
258 by: &UserId,
259) -> Result<Vec<Skip>, AppError> {
260 let mut skipped = Vec::new();
261 apply_courses(db, blueprint, class, by, &mut Vec::new(), &mut skipped).await?;
262 Ok(skipped)
263}
264
265/// One class's share of a pump, and the body both callers above share.
266///
267/// `dead` is the courses this run already found deleted: they are not
268/// attempted again, so neither the skip nor [`class_blueprint::prune`]'s
269/// write repeats on the next section. A course newly found gone joins it.
270///
271/// Answers `false` when the blueprint itself is gone — a caller looping
272/// over classes must stop, because every remaining one would answer exactly
273/// the same.
274async fn apply_courses(
275 db: &Database,
276 blueprint: &ClassBlueprint,
277 class: &ClassGroup,
278 by: &UserId,
279 dead: &mut Vec<CourseId>,
280 skipped: &mut Vec<Skip>,
281) -> Result<bool, AppError> {
282 for course in &blueprint.courses {
283 if dead.contains(course) {
284 continue;
285 }
286 let landed =
287 class_course::attach_sourced(db, class.get_id(), course, by, Some(&blueprint.id))
288 .await?;
289 if matches!(landed, Attached::PivotGone) {
290 class_blueprint::prune(db, &blueprint.id, course).await?;
291 dead.push(course.clone());
292 }
293 if let Some(reason) = skip_reason(&landed) {
294 skipped.push(Skip {
295 class: class.get_id().clone(),
296 class_name: class.get_name().as_str().to_string(),
297 course: course.clone(),
298 reason,
299 });
300 }
301 if matches!(landed, Attached::SourceGone) {
302 return Ok(false);
303 }
304 }
305 Ok(true)
306}
307
308/// [`apply_to`] every class at this blueprint's grade. The write loop
309/// is one transaction per (class, course) and bounded by neither — see the
310/// module note.
311///
312/// Two things are said once for the whole run rather than once per section,
313/// since a section cannot make either of them untrue. A course that no
314/// longer exists is pruned and skipped on the first class that meets it and
315/// left out of every class after it. And a `blueprint_deleted` **aborts the
316/// grade loop**: the attach's `FOR KEY SHARE` row-lock claim makes that
317/// answer precisely "a delete landed mid-pump", so it is reported once and
318/// the remaining classes are not walked.
319///
320/// The abort is still a `Ok(..)`, not an error: the attaches that committed
321/// before the delete stand (its sweep took the ones it could reach), and a
322/// partial state reported in full is what best-effort means everywhere else
323/// here.
324///
325/// [`Pumped::matched`] is counted off this loop rather than asked of a
326/// second query — the sections the run *walked*, so an abort reports what
327/// it did and not what the grade holds.
328///
329/// `&mut`, because [`class_blueprint::prune`] writes the store and this
330/// handle is what both write routes render their response from: a course
331/// pruned mid-pump was still listed in the `201`/`200` that pruned it, while
332/// the `GET` a moment later did not have it.
333pub async fn pump(
334 db: &Database,
335 blueprint: &mut ClassBlueprint,
336 by: &UserId,
337) -> Result<Pumped, AppError> {
338 let mut pumped = Pumped {
339 matched: 0,
340 skipped: Vec::new(),
341 };
342 let mut dead = Vec::new();
343 for class in class_group::list_for_grade(db, blueprint.grade_level).await? {
344 pumped.matched += 1;
345 if !apply_courses(db, blueprint, &class, by, &mut dead, &mut pumped.skipped).await? {
346 break;
347 }
348 }
349 // Exactly the ids `prune` took out of the stored row, so the handle and
350 // the store say the same thing.
351 blueprint.courses.retain(|course| !dead.contains(course));
352 Ok(pumped)
353}
354
355/// How far every section at this grade stands from the template: the
356/// courses each one does not carry. Writes nothing — a pump's skip list
357/// lives only in the response that reported it, and this is the read that
358/// answers "which sections are still out of sync" afterwards.
359///
360/// **A link of any source counts as satisfied.** A course a human attached
361/// by hand fulfils the template exactly as a pumped one does — that is
362/// [`apply_to`]'s own idempotence rule, and a status read that
363/// disagreed with it would send managers chasing rows no pump will ever
364/// write.
365///
366/// A course id the blueprint holds but that no longer exists reads as
367/// missing from every section. It is the truth about the section, and this
368/// read cannot prune it the way a pump does ([`class_blueprint::prune`])
369/// without writing — but it is no longer a state a course delete leaves
370/// behind: the delete's own cascade takes the id out of every template
371/// naming it, so only a row written before that cascade existed, or one the
372/// pump's own window ([`class_blueprint::prune`]) is about to clear, can
373/// still show it.
374///
375/// Unpaged, like the [`crate::db::class_group::list_for_grade`] it is built on: the set
376/// is the class sections one school runs at one grade, and the caller is
377/// asking about all of them.
378pub async fn status(
379 db: &Database,
380 blueprint: &ClassBlueprint,
381) -> Result<Vec<SectionStatus>, AppError> {
382 let sections = class_group::list_for_grade(db, blueprint.grade_level).await?;
383 if sections.is_empty() {
384 return Ok(Vec::new());
385 }
386 let classes: Vec<ClassGroupId> = sections
387 .iter()
388 .map(|class| class.get_id().clone())
389 .collect();
390 let held = class_blueprint::held_links(db, classes).await?;
391 Ok(sections
392 .iter()
393 .map(|class| SectionStatus {
394 class: class.get_id().clone(),
395 class_name: class.get_name().as_str().to_string(),
396 missing: blueprint
397 .courses
398 .iter()
399 .filter(|course| {
400 !held
401 .iter()
402 .any(|row| &row.class == class.get_id() && &&row.course == course)
403 })
404 .cloned()
405 .collect(),
406 })
407 .collect())
408}
409
410#[cfg(test)]
411mod tests {
412 use super::*;
413 use crate::constant::MAX_CLASS_COURSES;
414 use crate::db::class_member::tests::{
415 a_class, a_course, counter, fixture_user, link_exists, rows,
416 };
417 use crate::domain::class_group::{ClassGroup, ClassName};
418
419 /// A section at the pump's own rung (9), so `list_for_grade` reaches it.
420 async fn a_section(name: &str, db: &Database) -> ClassGroup {
421 class_group::create(
422 db,
423 &fixture_user(db, "manager").await,
424 ClassName::try_new(name).unwrap(),
425 GradeLevel::new(9).unwrap(),
426 None,
427 None,
428 )
429 .await
430 .unwrap()
431 }
432
433 /// A blueprint holding `courses`, at rung 9.
434 async fn a_blueprint(courses: Vec<CourseId>, db: &Database) -> ClassBlueprint {
435 let manager = fixture_user(db, "manager").await;
436 create(db, &manager, GradeLevel::new(9).unwrap(), courses)
437 .await
438 .unwrap()
439 }
440
441 /// Every skip names the record that actually failed.
442 ///
443 /// The three refusals a manager can meet come out of two different claims
444 /// in one transaction, and they used to be reported by one string that
445 /// guessed: a deleted *course* was announced as a deleted *class*, on a
446 /// section standing right there. Each is provoked from the state that
447 /// really produces it, not from the enum.
448 #[tokio::test]
449 async fn a_skip_names_what_actually_failed() {
450 let (db, _leases) = crate::database::init_test_db().await;
451 let manager = fixture_user(&db, "manager").await;
452
453 // The course is deleted out from under the pump: the pivot claim
454 // matches nothing.
455 let course = a_course("algebra", &db).await;
456 let class = class_group::read(&db, &a_class("9-A", &db).await)
457 .await
458 .unwrap()
459 .unwrap();
460 let blueprint = a_blueprint(vec![course.clone()], &db).await;
461 // Children first, the ordering the course's own cascade runs: with the
462 // junction row standing, the raw course delete below is a foreign-key
463 // refusal. What is left is exactly the pump-window state the handle
464 // still walks.
465 sqlx::query("DELETE FROM blueprint_course WHERE course = $1")
466 .bind(course.uuid())
467 .execute(&db)
468 .await
469 .unwrap();
470 sqlx::query("DELETE FROM course WHERE id = $1")
471 .bind(course.uuid())
472 .execute(&db)
473 .await
474 .unwrap();
475 let skipped = apply_to(&db, &blueprint, &class, &manager).await.unwrap();
476 assert_eq!(skipped.len(), 1, "{skipped:?}");
477 assert_eq!(
478 skipped[0].reason, "course_deleted",
479 "the course went, not the class"
480 );
481 // …and the dangling id is taken out of the list, so the skip is
482 // reported once instead of on every pump forever.
483 assert!(
484 read(&db, blueprint.get_id())
485 .await
486 .unwrap()
487 .unwrap()
488 .get_courses()
489 .is_empty(),
490 "a course that no longer exists is pruned from the blueprint"
491 );
492
493 // The class is deleted out from under the pump: the counter claim
494 // matches nothing and the read that follows finds no row.
495 let (db, _leases) = crate::database::init_test_db().await;
496 let manager = fixture_user(&db, "manager").await;
497 let course = a_course("algebra", &db).await;
498 let class = class_group::read(&db, &a_class("9-A", &db).await)
499 .await
500 .unwrap()
501 .unwrap();
502 let blueprint = a_blueprint(vec![course.clone()], &db).await;
503 sqlx::query("DELETE FROM class_group WHERE id = $1")
504 .bind(class.get_id().uuid())
505 .execute(&db)
506 .await
507 .unwrap();
508 let skipped = apply_to(&db, &blueprint, &class, &manager).await.unwrap();
509 assert_eq!(skipped.len(), 1, "{skipped:?}");
510 assert_eq!(
511 skipped[0].reason, "class_deleted",
512 "the class went, not the course"
513 );
514 assert_eq!(
515 read(&db, blueprint.get_id())
516 .await
517 .unwrap()
518 .unwrap()
519 .get_courses(),
520 &[course],
521 "a live course is not pruned because a class vanished"
522 );
523
524 // The class stands at its own ceiling: the same claim matches nothing,
525 // but the row is there — and that is the one a manager can act on.
526 let (db, _leases) = crate::database::init_test_db().await;
527 let manager = fixture_user(&db, "manager").await;
528 let course = a_course("algebra", &db).await;
529 let class = class_group::read(&db, &a_class("9-A", &db).await)
530 .await
531 .unwrap()
532 .unwrap();
533 let blueprint = a_blueprint(vec![course], &db).await;
534 sqlx::query(sqlx::AssertSqlSafe(format!(
535 "UPDATE class_group SET class_course_count = {} WHERE id = $1",
536 MAX_CLASS_COURSES
537 )))
538 .bind(class.get_id().uuid())
539 .execute(&db)
540 .await
541 .unwrap();
542 let skipped = apply_to(&db, &blueprint, &class, &manager).await.unwrap();
543 assert_eq!(skipped.len(), 1, "{skipped:?}");
544 assert_eq!(
545 skipped[0].reason, "class_at_course_ceiling",
546 "a full class is not a deleted one"
547 );
548 }
549
550 /// The delete is a compare-and-set, and it runs *before* the sweep — so a
551 /// handle whose list moved cannot take the row, and nothing it would have
552 /// swept is touched either.
553 ///
554 /// Provoked with a stale handle rather than a concurrent request, which is
555 /// exactly the state a `PATCH` landing between the read and the delete puts
556 /// this caller in, and deterministic where two live requests are not.
557 #[tokio::test]
558 async fn a_delete_of_a_list_that_moved_is_a_409_that_writes_nothing() {
559 let (db, _leases) = crate::database::init_test_db().await;
560 let manager = fixture_user(&db, "manager").await;
561 let algebra = a_course("algebra", &db).await;
562 let physics = a_course("physics", &db).await;
563 let class = class_group::read(&db, &a_class("9-A", &db).await)
564 .await
565 .unwrap()
566 .unwrap();
567 let stale = a_blueprint(vec![algebra.clone()], &db).await;
568 apply_to(&db, &stale, &class, &manager).await.unwrap();
569
570 // The edit this caller did not see: it adds a course and pumps it into
571 // the section. (The pump is applied by hand because the helper class
572 // carries no grade for `set_courses`'s own loop to find.)
573 let (edited, _, _) = set_courses(
574 &db,
575 read(&db, stale.get_id()).await.unwrap().unwrap(),
576 vec![algebra, physics],
577 &manager,
578 )
579 .await
580 .unwrap();
581 apply_to(&db, &edited, &class, &manager).await.unwrap();
582
583 let refused = delete(&db, stale).await;
584 assert!(
585 matches!(refused, Err(AppError::Conflict(_))),
586 "a list that moved is a 409, not a silent delete: {refused:?}"
587 );
588 assert!(
589 read(&db, &ClassBlueprintId::from_key("9"))
590 .await
591 .unwrap()
592 .is_some(),
593 "the row the caller did not read is still there"
594 );
595 assert_eq!(
596 rows("class_course", &db).await,
597 2,
598 "and neither attachment was swept — including the one this handle \
599 never knew about"
600 );
601 }
602
603 /// The lease is real: a delete cannot start while a guarded attach holds
604 /// the read side.
605 ///
606 /// That is the whole point of the lock — without it a pump could commit its
607 /// `class_course` row *after* the delete had swept past, stranding a row
608 /// tagged with a blueprint nothing can reach. Two live requests would be a
609 /// coin flip the in-memory engine lies about, so the lease is held directly
610 /// and the delete is watched not-finishing on a timeout.
611 #[tokio::test]
612 async fn a_delete_waits_for_an_attach_in_flight() {
613 let (db, _leases) = crate::database::init_test_db().await;
614 let manager = fixture_user(&db, "manager").await;
615 let algebra = a_course("algebra", &db).await;
616 let class = class_group::read(&db, &a_class("9-A", &db).await)
617 .await
618 .unwrap()
619 .unwrap();
620 let blueprint = a_blueprint(vec![algebra.clone()], &db).await;
621 apply_to(&db, &blueprint, &class, &manager).await.unwrap();
622
623 // The lease is gone with the lock; the whole compare-and-set-plus-
624 // sweep is one transaction now, and the pump claims the blueprint
625 // inside its own. A barrier start lets the racing attach and delete
626 // interleave every which way — in all of them no `class_course` row
627 // may survive a blueprint that is gone, and no counter may drift.
628 let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
629 let deleting = {
630 let (db, blueprint, gate) = (db.clone(), blueprint.clone(), gate.clone());
631 tokio::spawn(async move {
632 gate.wait().await;
633 delete(&db, blueprint).await
634 })
635 };
636 let pumping = {
637 let (db, class, _algebra, manager, gate) =
638 (db.clone(), class.clone(), algebra.clone(), manager, gate);
639 tokio::spawn(async move {
640 gate.wait().await;
641 apply_to(&db, &blueprint, &class, &manager).await
642 })
643 };
644 let (deleted, pumped) = (deleting.await.unwrap(), pumping.await.unwrap());
645 deleted.unwrap();
646
647 // The delete went through; whatever the pump answered, the stored
648 // state must agree with itself.
649 assert_eq!(
650 rows("class_blueprint", &db).await,
651 0,
652 "the delete goes through"
653 );
654 let skipped = pumped.unwrap();
655 if skipped.iter().any(|s| s.reason == "blueprint_deleted") {
656 assert_eq!(
657 rows("class_course", &db).await,
658 0,
659 "a pump that read a dead blueprint attaches nothing"
660 );
661 } else {
662 // The pump beat the delete to the claim and attached cleanly: its
663 // rows go with the blueprint the sweep then took.
664 assert!(
665 skipped.is_empty(),
666 "neither a clean attach nor a clean skip: {skipped:?}"
667 );
668 assert_eq!(
669 rows("class_course", &db).await,
670 0,
671 "the sweep took the rows the winning pump had just written"
672 );
673 }
674 assert_eq!(
675 counter("class_course_count", class.get_id().uuid(), &db).await,
676 0,
677 "…and whatever happened, the class's counter is back to zero"
678 );
679 }
680
681 /// …and the other side of that lease: it is released before the detaching
682 /// starts, so a pump is *not* parked behind it.
683 ///
684 /// The sweep is one transaction per link row and bounded by nothing —
685 /// sections × courses, each walking up to a full roster — and `tokio`'s
686 /// `RwLock` is fair, so a lease held across it stalled every concurrent
687 /// `POST /classes` in the school, at every grade, for the whole delete. What
688 /// the lease has to cover is only the compare-and-set and the read that
689 /// fixes the row set, which `a_delete_waits_for_an_attach_in_flight` above
690 /// still pins from the other direction.
691 ///
692 /// The unbounded loop is stood in for by four slow rows: a `DEFINE EVENT` on
693 /// `class_course` fires inside each detaching transaction, so the delete is
694 /// provably still sweeping when the lease is asked for. Nothing here is
695 /// asserted off a fixed delay — the row going is what says the
696 /// compare-and-set has run, and one *moment* of a free lease while the sweep
697 /// is unfinished is the whole claim. A sweep that ended first fails the
698 /// assertion rather than passing it by default.
699 #[tokio::test]
700 async fn a_delete_frees_the_lease_before_its_unbounded_sweep() {
701 let (db, _leases) = crate::database::init_test_db().await;
702 let manager = fixture_user(&db, "manager").await;
703 let courses = vec![
704 a_course("algebra", &db).await,
705 a_course("physics", &db).await,
706 ];
707 let blueprint = a_blueprint(courses, &db).await;
708 let mut classes = Vec::new();
709 for name in ["9-A", "9-B", "9-C"] {
710 let class = class_group::read(&db, &a_class(name, &db).await)
711 .await
712 .unwrap()
713 .unwrap();
714 if name != "9-C" {
715 apply_to(&db, &blueprint, &class, &manager).await.unwrap();
716 }
717 classes.push(class);
718 }
719
720 // The lock is gone, so there is no lease to free; what still has to
721 // hold is its point: a pump arriving while the delete's sweep is in
722 // flight is answered by the database, not parked behind the sweep —
723 // and the sweep still takes every row carrying the blueprint's tag.
724 let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
725 let deleting = {
726 let (db, blueprint, gate) = (db.clone(), blueprint.clone(), gate.clone());
727 tokio::spawn(async move {
728 gate.wait().await;
729 delete(&db, blueprint).await
730 })
731 };
732 let pumping = {
733 let (db, class, manager, gate, blueprint) = (
734 db.clone(),
735 classes[2].clone(),
736 manager,
737 gate.clone(),
738 blueprint.clone(),
739 );
740 tokio::spawn(async move {
741 gate.wait().await;
742 apply_to(&db, &blueprint, &class, &manager).await
743 })
744 };
745
746 // The pump is answered in bounded time even though the delete is
747 // sweeping two sections' link rows — and answered with one of the two
748 // honest outcomes, never a 500.
749 let pumped = tokio::time::timeout(std::time::Duration::from_secs(10), pumping)
750 .await
751 .expect("a pump must not wait behind a delete's unbounded sweep")
752 .unwrap();
753 let skipped = pumped.unwrap();
754 assert!(
755 skipped
756 .iter()
757 .all(|s| { s.reason == "blueprint_deleted" || s.reason == "course_deleted" })
758 || skipped.is_empty(),
759 "neither a clean attach nor a clean skip: {skipped:?}"
760 );
761
762 deleting.await.unwrap().unwrap();
763 assert_eq!(
764 rows("class_course", &db).await,
765 0,
766 "…and the sweep still took every row it owned"
767 );
768 for class in &classes {
769 assert_eq!(
770 counter("class_course_count", class.get_id().uuid(), &db).await,
771 0,
772 "…and no counter kept a seat the sweep took back"
773 );
774 }
775 }
776
777 /// The other half: a pump holding a handle to a blueprint that has since
778 /// been deleted writes nothing at all, and says so with its own code.
779 ///
780 /// Without the in-transaction claim the attach would land a `class_course`
781 /// row tagged with a record that no longer exists — the delete's sweep has
782 /// already run, and the grade label *is* the id, so nothing could ever
783 /// reach that row again.
784 #[tokio::test]
785 async fn a_pump_whose_blueprint_died_attaches_nothing() {
786 let (db, _leases) = crate::database::init_test_db().await;
787 let manager = fixture_user(&db, "manager").await;
788 let algebra = a_course("algebra", &db).await;
789 let class = class_group::read(&db, &a_class("9-A", &db).await)
790 .await
791 .unwrap()
792 .unwrap();
793 let stale = a_blueprint(vec![algebra], &db).await;
794 delete(&db, read(&db, stale.get_id()).await.unwrap().unwrap())
795 .await
796 .unwrap();
797
798 let skipped = apply_to(&db, &stale, &class, &manager).await.unwrap();
799 assert_eq!(skipped.len(), 1, "{skipped:?}");
800 assert_eq!(
801 skipped[0].reason, "blueprint_deleted",
802 "the template went, not the class or the course"
803 );
804 assert_eq!(
805 rows("class_course", &db).await,
806 0,
807 "a row tagged with a deleted blueprint is one nothing can sweep"
808 );
809 assert_eq!(
810 counter("class_course_count", class.get_id().uuid(), &db).await,
811 0,
812 "…and no counter moved for it"
813 );
814 }
815
816 /// A course that no longer exists is pruned and reported **once for the
817 /// pump**, not once per section: twelve sections at a grade must not answer
818 /// one dead course with twelve identical skips and twelve identical prune
819 /// writes. The live course still reaches every section.
820 ///
821 /// Stored state is what is asserted — the in-memory engine forges wins, so
822 /// the links are re-read rather than counted off the return value.
823 #[tokio::test]
824 async fn a_dead_course_is_pruned_and_skipped_once_for_the_whole_grade() {
825 let (db, _leases) = crate::database::init_test_db().await;
826 let manager = fixture_user(&db, "manager").await;
827 let astronomy = a_course("astronomy", &db).await;
828 let algebra = a_course("algebra", &db).await;
829 let a = a_section("9-A", &db).await;
830 let b = a_section("9-B", &db).await;
831 let mut blueprint = a_blueprint(vec![astronomy.clone(), algebra.clone()], &db).await;
832 // Children first, the ordering the course's own cascade runs — the
833 // junction row standing would make the raw delete a foreign-key
834 // refusal. The handle below still walks the list it read.
835 sqlx::query("DELETE FROM blueprint_course WHERE course = $1")
836 .bind(astronomy.uuid())
837 .execute(&db)
838 .await
839 .unwrap();
840 sqlx::query("DELETE FROM course WHERE id = $1")
841 .bind(astronomy.uuid())
842 .execute(&db)
843 .await
844 .unwrap();
845
846 let Pumped { matched, skipped } = pump(&db, &mut blueprint, &manager).await.unwrap();
847 assert_eq!(matched, 2, "both sections at the grade were walked");
848 assert_eq!(
849 skipped.len(),
850 1,
851 "one dead course is one skip for the grade, not one per section: {skipped:?}"
852 );
853 assert_eq!(skipped[0].reason, "course_deleted");
854 assert_eq!(
855 read(&db, blueprint.get_id())
856 .await
857 .unwrap()
858 .unwrap()
859 .get_courses(),
860 std::slice::from_ref(&algebra),
861 "and the list is pruned to the course that still exists"
862 );
863 for class in [&a, &b] {
864 assert!(
865 link_exists(class.get_id(), &algebra, &db).await,
866 "the live course still reached {}",
867 class.get_name().as_str()
868 );
869 }
870 assert_eq!(
871 rows("class_course", &db).await,
872 2,
873 "…and nothing else was attached"
874 );
875 }
876
877 /// A blueprint that is gone ends the whole grade loop: the answer is about
878 /// the template, so every remaining section would only repeat it. Reported
879 /// once, and as `Ok` — best-effort, with whatever committed left standing.
880 ///
881 /// Provoked with a stale handle rather than a live interleaving, which the
882 /// in-memory engine cannot be made to produce; it is the same state a
883 /// delete landing between the read and the pump leaves this caller in.
884 #[tokio::test]
885 async fn a_deleted_blueprint_stops_the_grade_loop_after_one_skip() {
886 let (db, _leases) = crate::database::init_test_db().await;
887 let manager = fixture_user(&db, "manager").await;
888 let algebra = a_course("algebra", &db).await;
889 a_section("9-A", &db).await;
890 a_section("9-B", &db).await;
891 let mut stale = a_blueprint(vec![algebra], &db).await;
892 delete(&db, read(&db, stale.get_id()).await.unwrap().unwrap())
893 .await
894 .unwrap();
895
896 let Pumped { matched, skipped } = pump(&db, &mut stale, &manager).await.unwrap();
897 assert_eq!(
898 skipped.len(),
899 1,
900 "the template went once, not once per section: {skipped:?}"
901 );
902 assert_eq!(skipped[0].reason, "blueprint_deleted");
903 assert_eq!(
904 matched, 1,
905 "an abort reports the sections it walked, not the two the grade holds"
906 );
907 assert_eq!(
908 rows("class_course", &db).await,
909 0,
910 "…and nothing was attached under a blueprint nothing could sweep"
911 );
912 }
913}