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.rs563 lines, 21.5 KiBHistoryRawDownload
1//! The `class_blueprint` table: the row keyed by its ladder rung, the
2//! compare-and-set writes the edit and the delete go through, and the reads
3//! the sweep and the status screen are built on. The workflows that sequence
4//! these — and the row lock that serializes a delete against the attaches
5//! made on the blueprint's behalf — live in [`crate::service::class_blueprint`].
6
7use sqlx::postgres::PgConnection;
8
9use std::collections::HashMap;
10
11use crate::constant::CLASS_BLUEPRINT_TABLE;
12use crate::database::{Database, tx_with_retry, unique_violation};
13use crate::db::class_pump;
14use crate::db::page::PagedList;
15use crate::domain::class_blueprint::{ClassBlueprint, ClassBlueprintId};
16use crate::domain::class_group::ClassGroupId;
17use crate::domain::grade::GradeLevel;
18use crate::domain::course::CourseId;
19use crate::domain::monotonic_id::next_uuid;
20use crate::domain::user::UserId;
21use crate::error::{AppError, ValidationError};
22
23/// The stored columns of one `class_blueprint` row. A template's course list
24/// is *not* one of them — it lives across the `blueprint_course` junction and
25/// is joined on in a batch after the read ([`with_courses`]), because the
26/// paged list here reads whole rows (`SELECT *`), a shape no aggregate column
27/// can ride.
28#[derive(Debug, sqlx::FromRow)]
29struct BlueprintRow {
30 /// The surrogate uuid primary key — the key the junction rows reference.
31 #[sqlx(rename = "id")]
32 key: uuid::Uuid,
33 grade_level: GradeLevel,
34 creator: UserId,
35}
36
37impl BlueprintRow {
38 fn into_blueprint(self, courses: Vec<CourseId>) -> ClassBlueprint {
39 ClassBlueprint {
40 // The API identity is the ladder rung, which the key column also
41 // stores — the id *is* the grade level.
42 id: ClassBlueprintId::for_grade(&self.grade_level),
43 grade_level: self.grade_level,
44 courses,
45 creator: self.creator,
46 }
47 }
48}
49
50/// The stored course list of one blueprint, sorted by course. Every read goes
51/// through this ordering, which is what makes the compare-and-set below a
52/// plain vector comparison: both sides of it are junction reads.
53async fn junction_courses<'e, E>(
54 executor: E,
55 blueprint: uuid::Uuid,
56) -> Result<Vec<CourseId>, AppError>
57where
58 E: sqlx::PgExecutor<'e>,
59{
60 let rows = sqlx::query!(
61 r#"SELECT course AS "course: CourseId" FROM blueprint_course
62 WHERE blueprint = $1 ORDER BY course"#,
63 blueprint,
64 )
65 .fetch_all(executor)
66 .await?;
67 Ok(rows.into_iter().map(|row| row.course).collect())
68}
69
70/// Join the stored course lists onto a batch of blueprint rows, one junction
71/// read for the lot.
72async fn with_courses(
73 db: &Database,
74 rows: Vec<BlueprintRow>,
75) -> Result<Vec<ClassBlueprint>, AppError> {
76 if rows.is_empty() {
77 return Ok(Vec::new());
78 }
79 let keys: Vec<uuid::Uuid> = rows.iter().map(|row| row.key).collect();
80 let links = sqlx::query!(
81 r#"SELECT blueprint, course AS "course: CourseId" FROM blueprint_course
82 WHERE blueprint = ANY($1) ORDER BY blueprint, course"#,
83 &keys,
84 )
85 .fetch_all(db)
86 .await?;
87 let mut by_blueprint: HashMap<uuid::Uuid, Vec<CourseId>> = HashMap::new();
88 for link in links {
89 by_blueprint
90 .entry(link.blueprint)
91 .or_default()
92 .push(link.course);
93 }
94 Ok(rows
95 .into_iter()
96 .map(|row| {
97 let courses = by_blueprint.remove(&row.key).unwrap_or_default();
98 row.into_blueprint(courses)
99 })
100 .collect())
101}
102
103/// One `class_course` row, projected down to the pair that answers "does this
104/// section carry that course". `source` is deliberately not read: a link of any
105#[derive(Debug, sqlx::FromRow)]
106pub struct Held {
107 pub(crate) class: ClassGroupId,
108 pub(crate) course: CourseId,
109}
110
111/// Prove every course a template is about to name is still there, *inside* the
112/// transaction that stores the list.
113///
114/// The caller's own pre-flight read is not that proof: it is a read of
115/// `course` in a request that then writes `class_blueprint`, and two
116/// transactions that read and write crossed records interleave freely under
117/// READ COMMITTED. `DELETE /courses/{id}` sweeps every template naming the
118/// course as part of its cascade, so a delete landing between the read and the
119/// write sweeps a row that is not there yet and the list keeps an id nothing
120/// points at. A `FOR KEY SHARE` row lock per course is the proof: it is the
121/// weakest strength a course `DELETE` cannot take, so the delete waits behind
122/// this transaction and finds the list that names the course already stored —
123/// and sweeps it.
124///
125/// One lock per course, the list being at most `MAX_CLASS_COURSES` long —
126/// the same pass-per-course the old in-transaction loop made.
127async fn courses_alive(tx: &mut PgConnection, courses: &[CourseId]) -> Result<(), AppError> {
128 for course in courses {
129 let alive = sqlx::query_scalar!(
130 r#"SELECT 1 AS "one" FROM course WHERE id = $1 FOR KEY SHARE"#,
131 course as _
132 )
133 .fetch_optional(&mut *tx)
134 .await?
135 .is_some();
136 if !alive {
137 return Err(no_such_course());
138 }
139 }
140 Ok(())
141}
142
143/// The refusal a locked course read answers when the course is gone: the
144/// same `400` the caller's pre-flight read raises, since it is the same fact
145/// one instant later.
146fn no_such_course() -> AppError {
147 AppError::Validation(ValidationError::Invalid {
148 field: "course_ids",
149 reason: "one of these courses does not exist",
150 })
151}
152
153/// Write the blueprint's row — and its `blueprint_course` rows, in the same
154/// transaction, under the same per-course proof ([`courses_alive`]). A second
155/// blueprint for the same grade is a 409 the store itself decides — the grade
156/// carries a UNIQUE constraint, so the duplicate is seen rather than raced
157/// (`23505` on `class_blueprint_grade_key`, mapped right here: a duplicate is
158/// a decision, never a retry). The surrogate `id` is minted here and never
159/// read back: the ladder rung stays the only identity the API speaks.
160pub async fn create(
161 db: &Database,
162 creator: &UserId,
163 grade_level: GradeLevel,
164 courses: Vec<CourseId>,
165) -> Result<ClassBlueprint, AppError> {
166 let blueprint = ClassBlueprint {
167 id: ClassBlueprintId::for_grade(&grade_level),
168 grade_level,
169 courses: courses.clone(),
170 creator: *creator,
171 };
172 let creator = *creator;
173 let id = next_uuid();
174 tx_with_retry(db, false, async move |tx| {
175 courses_alive(tx, &courses).await?;
176 let inserted = sqlx::query!(
177 r#"INSERT INTO class_blueprint (id, grade_level, creator)
178 VALUES ($1, $2, $3)"#,
179 id,
180 grade_level as _,
181 creator as _
182 )
183 .execute(&mut *tx)
184 .await;
185 match inserted {
186 Ok(_) => {
187 sqlx::query!(
188 r#"INSERT INTO blueprint_course (blueprint, course)
189 SELECT $1, x FROM unnest($2::uuid[]) AS t(x)
190 ON CONFLICT DO NOTHING"#,
191 id,
192 courses as _,
193 )
194 .execute(&mut *tx)
195 .await?;
196 Ok(blueprint.clone())
197 }
198 Err(e) if unique_violation(&e) == Some("class_blueprint_grade_key") => Err(
199 AppError::Conflict("a blueprint already exists for that grade"),
200 ),
201 Err(e) => Err(e.into()),
202 }
203 })
204 .await
205}
206
207pub async fn read(
208 db: &Database,
209 id: &ClassBlueprintId,
210) -> Result<Option<ClassBlueprint>, AppError> {
211 let row = sqlx::query_as!(
212 BlueprintRow,
213 r#"SELECT id AS "key: uuid::Uuid", grade_level AS "grade_level: GradeLevel",
214 creator AS "creator: UserId"
215 FROM class_blueprint WHERE grade_level = $1"#,
216 id as _
217 )
218 .fetch_optional(db)
219 .await?;
220 match row {
221 Some(row) => {
222 let courses = junction_courses(db, row.key).await?;
223 Ok(Some(row.into_blueprint(courses)))
224 }
225 None => Ok(None),
226 }
227}
228
229/// Every blueprint, by ladder rung — the id *is* the rung, so this is the
230/// only ordering that means anything here.
231pub async fn list_all(
232 db: &Database,
233 limit: Option<i64>,
234 offset: i64,
235) -> Result<(Vec<ClassBlueprint>, i64), AppError> {
236 let (rows, total) = PagedList::new(CLASS_BLUEPRINT_TABLE, "ORDER BY grade_level ASC")
237 .run::<BlueprintRow>(limit, offset, db)
238 .await?;
239 Ok((with_courses(db, rows).await?, total))
240}
241
242/// Write the course list only while the stored rows still answer to the list
243/// this caller read: two managers editing the same grade cannot have one's
244/// list silently pump the other's diff. `None` means the claim matched
245/// nothing — the row is gone, or its list moved since the caller read it, and
246/// only the caller can tell those apart (the workflow re-reads and answers a
247/// `409` or a `404`).
248///
249/// The write is a claim (`FOR UPDATE` on the row), a comparison (the stored
250/// `blueprint_course` rows, read under that lock, against `held` — both
251/// sorted the same way, so the comparison is a plain vector equality), then
252/// the diff: rows `wanted` dropped are deleted, rows it added are inserted.
253/// All of it rides one transaction, and the row lock it holds is the same
254/// strength the blueprint delete takes, so a pump's `FOR KEY SHARE` claim on
255/// this row waits out the whole write exactly as it waits out a delete.
256///
257/// A template naming a course that is gone refuses inside the transaction
258/// with the pre-flight `400` ([`courses_alive`]).
259pub async fn set_courses_if_unchanged(
260 db: &Database,
261 id: &ClassBlueprintId,
262 held: Vec<CourseId>,
263 wanted: Vec<CourseId>,
264) -> Result<Option<ClassBlueprint>, AppError> {
265 let grade = id.get();
266 let mut held = held;
267 held.sort_by_key(|course| course.uuid());
268 let keys: Vec<uuid::Uuid> = wanted.iter().map(CourseId::uuid).collect();
269 tx_with_retry(db, false, async move |tx| {
270 courses_alive(tx, &wanted).await?;
271 let row = sqlx::query!(
272 r#"SELECT id AS "key: uuid::Uuid", grade_level AS "grade_level: GradeLevel",
273 creator AS "creator: UserId"
274 FROM class_blueprint WHERE grade_level = $1 FOR UPDATE"#,
275 grade,
276 )
277 .fetch_optional(&mut *tx)
278 .await?;
279 let Some(row) = row else {
280 return Ok(None);
281 };
282 let stored = junction_courses(&mut *tx, row.key).await?;
283 if stored != held {
284 return Ok(None);
285 }
286 // The diff, from the list this caller stored: rows it dropped go,
287 // rows it added come (a duplicate in `wanted` is one row — the
288 // workflow deduplicates, and the key does the rest).
289 sqlx::query!(
290 r#"DELETE FROM blueprint_course
291 WHERE blueprint = $1 AND NOT (course = ANY($2))"#,
292 row.key,
293 &keys,
294 )
295 .execute(&mut *tx)
296 .await?;
297 sqlx::query!(
298 r#"INSERT INTO blueprint_course (blueprint, course)
299 SELECT $1, x FROM unnest($2::uuid[]) AS t(x)
300 ON CONFLICT DO NOTHING"#,
301 row.key,
302 &keys,
303 )
304 .execute(&mut *tx)
305 .await?;
306 Ok(Some(ClassBlueprint {
307 id: ClassBlueprintId::for_grade(&row.grade_level),
308 grade_level: row.grade_level,
309 courses: wanted.clone(),
310 creator: row.creator,
311 }))
312 })
313 .await
314}
315
316/// Delete the row — but only while its stored list is still the one this
317/// caller read; the edit race answers the caller, not a silent delete of
318/// somebody else's additions. `false` means the claim matched nothing: the
319/// row is gone, or its list moved since the caller read it, and only the
320/// caller can tell those apart.
321///
322/// The `DELETE` is also the whole of the serialization against the attaches
323/// made on this blueprint's behalf: a sourced attach holds a `FOR KEY SHARE`
324/// on this row across its transaction ([`class_pump::attach_course`]), so its
325/// row lands before this delete's sweep runs or not at all — the invariant the
326/// old process-wide write lease held, now on the row itself.
327pub async fn delete_if_unchanged(
328 db: &Database,
329 id: &ClassBlueprintId,
330 held: Vec<CourseId>,
331) -> Result<bool, AppError> {
332 tx_with_retry(db, false, async move |tx| {
333 delete_claimed(&mut *tx, id, &held).await
334 })
335 .await
336}
337
338/// [`delete_if_unchanged`] inside the caller's transaction — the blueprint
339/// delete rides the row lock its claim took, so the sourced links are swept
340/// while the window the claim opened is still closed. The claim and the
341/// comparison re-run here: in the delete workflow's own transaction the
342/// [`held_courses_for_update`] claim has already settled both, so they are a
343/// formality; the standalone path above gets its whole CAS from this one
344/// body.
345pub(crate) async fn delete_if_unchanged_in(
346 tx: &mut sqlx::PgConnection,
347 id: &ClassBlueprintId,
348 held: &[CourseId],
349) -> Result<bool, AppError> {
350 delete_claimed(tx, id, held).await
351}
352
353/// The delete's core: claim the row, compare the stored junction rows with
354/// `held`, and take the junction rows before the blueprint row they
355/// reference — the `NO ACTION` foreign key is checked the moment the final
356/// `DELETE` runs.
357async fn delete_claimed(
358 tx: &mut PgConnection,
359 id: &ClassBlueprintId,
360 held: &[CourseId],
361) -> Result<bool, AppError> {
362 let row = sqlx::query!(
363 r#"SELECT id AS "key: uuid::Uuid" FROM class_blueprint
364 WHERE grade_level = $1 FOR UPDATE"#,
365 id as _,
366 )
367 .fetch_optional(&mut *tx)
368 .await?;
369 let Some(row) = row else {
370 return Ok(false);
371 };
372 let mut held = held.to_vec();
373 held.sort_by_key(|course| course.uuid());
374 let stored = junction_courses(&mut *tx, row.key).await?;
375 if stored != held {
376 return Ok(false);
377 }
378 sqlx::query!(
379 r#"DELETE FROM blueprint_course WHERE blueprint = $1"#,
380 row.key
381 )
382 .execute(&mut *tx)
383 .await?;
384 sqlx::query!(r#"DELETE FROM class_blueprint WHERE id = $1"#, row.key)
385 .execute(&mut *tx)
386 .await?;
387 Ok(true)
388}
389
390/// The stored course list of one blueprint, read `FOR UPDATE` — the claim
391/// the delete holds across its sweep, so a sourced attach (whose own
392/// transaction takes `FOR KEY SHARE` on this row before inserting) either
393/// commits before the claim and is swept, or waits past it and finds no
394/// row. `None` when the blueprint is gone.
395pub(crate) async fn held_courses_for_update(
396 tx: &mut sqlx::PgConnection,
397 id: &ClassBlueprintId,
398) -> Result<Option<Vec<CourseId>>, AppError> {
399 let row = sqlx::query!(
400 r#"SELECT id AS "key: uuid::Uuid" FROM class_blueprint
401 WHERE grade_level = $1 FOR UPDATE"#,
402 id as _,
403 )
404 .fetch_optional(&mut *tx)
405 .await?;
406 match row {
407 Some(row) => Ok(Some(junction_courses(&mut *tx, row.key).await?)),
408 None => Ok(None),
409 }
410}
411
412/// Every `class_course` row held by any of `classes`, projected down to the
413/// pair — the read [`crate::service::class_blueprint::status`] diffs the
414/// template against.
415pub async fn held_links(db: &Database, classes: Vec<ClassGroupId>) -> Result<Vec<Held>, AppError> {
416 let rows = sqlx::query!(
417 r#"SELECT class AS "class: ClassGroupId", course AS "course: CourseId"
418 FROM class_course WHERE class = ANY($1)"#,
419 classes as _
420 )
421 .fetch_all(db)
422 .await?;
423 Ok(rows
424 .into_iter()
425 .map(|row| Held {
426 class: row.class,
427 course: row.course,
428 })
429 .collect())
430}
431
432/// Drop a course that no longer exists out of a blueprint's list.
433///
434/// The delete does this itself now — twice over: the course's own cascade
435/// sweeps `blueprint_course` (the junction row is a foreign key now, so a
436/// template physically cannot keep naming a course whose row is gone) in the
437/// same transaction that takes the course's `class_course` links. This used
438/// to be the *only* thing that could remove such an id, and that was the bug:
439/// it fires only while walking a section, so a grade with no sections could
440/// never reach it, and the repair every doc surface pointed at (`PATCH` the
441/// list back as it stands) is a `400` for naming a course that does not
442/// exist. A permanent dangling id, and no call that could clear it.
443///
444/// What is left for this to do is the **window** the sweep cannot cover: a
445/// pump walks a snapshot of the list it read, so a course deleted after
446/// that read is still attempted, and the delete's sweep has already run
447/// past a row it will not visit again. The skip is then reported once for
448/// the run that found it (later classes in the same
449/// [`crate::service::class_blueprint::pump`] skip it by its dead-course set
450/// rather than re-attempting and re-pruning it), and this write is a no-op
451/// against a list the cascade already trimmed. It also clears ids written
452/// before that cascade existed.
453///
454/// Not a compare-and-set, unlike
455/// [`crate::service::class_blueprint::set_courses`]: "a course that does
456/// not exist is not in this list" holds for every version of the list, so
457/// there is nothing a concurrent edit could make this write wrong about,
458/// and re-running it changes nothing. No sweep follows it either — the
459/// attachments it would sweep are exactly the ones the course's own delete
460/// already took.
461pub async fn prune(
462 db: &Database,
463 id: &ClassBlueprintId,
464 course: &CourseId,
465) -> Result<(), AppError> {
466 sqlx::query!(
467 r#"DELETE FROM blueprint_course
468 WHERE course = $2
469 AND blueprint = (SELECT id FROM class_blueprint WHERE grade_level = $1)"#,
470 id as _,
471 course as _,
472 )
473 .execute(db)
474 .await?;
475 Ok(())
476}
477
478/// A blueprint's attachments that `keep` does not justify: every
479/// `class_course` row carrying its tag for a course outside that list. The
480/// delete passes `&[]` and so takes all of them.
481///
482/// Read off the *stored* list rather than a diff against a handle, which is
483/// what makes a repeated call a repair rather than a no-op: whatever a
484/// half-finished sweep left behind is exactly what the next one finds.
485///
486/// `source` is the whole filter, so a row without the tag — a hand attach —
487/// is never matched, and a class that acquired the same course by hand keeps
488/// it. The rows are read rather than derived from the classes at this grade:
489/// a class whose grade was edited after the pump still carries this
490/// blueprint's attachments, and only the tag can find it.
491///
492/// The stored tag is the blueprint's surrogate uuid, not the grade label the
493/// API speaks — the query translates the label to it.
494pub async fn sourced_links(
495 db: &Database,
496 id: &ClassBlueprintId,
497 keep: &[CourseId],
498) -> Result<Vec<Held>, AppError> {
499 let keep: Vec<CourseId> = keep.to_vec();
500 let rows = sqlx::query!(
501 r#"SELECT class AS "class: ClassGroupId", course AS "course: CourseId"
502 FROM class_course
503 WHERE source = (SELECT id FROM class_blueprint WHERE grade_level = $1)
504 AND course <> ALL($2)"#,
505 id as _,
506 keep as _
507 )
508 .fetch_all(db)
509 .await?;
510 Ok(rows
511 .into_iter()
512 .map(|row| Held {
513 class: row.class,
514 course: row.course,
515 })
516 .collect())
517}
518
519/// Detach the link rows [`sourced_links`] named and sweep the enrollments
520/// they pumped. The sweep underneath is the pump's own, so a student a
521/// second class still claims is re-tagged rather than unenrolled.
522///
523/// Each detach re-asserts the tag: the link's identity is the (class, course)
524/// pair and says nothing about provenance, so a row a *new* blueprint at the
525/// same grade attached while this ran would otherwise be swept by the old
526/// one's tail.
527///
528/// One transaction per *link row*, which is the module note's "one
529/// transaction per (class, course)" and the mirror of the pump's
530/// best-effort rule. One statement per course would be shorter, but it puts
531/// every section at the grade into a single unbounded transaction: its write
532/// loop is one enrollment sweep per (class, member) with no ceiling over the
533/// class count, and a failure anywhere in it rolls back the whole grade —
534/// so one contended section keeps the other eleven attached to a course the
535/// template no longer holds. Per row, a failure leaves the pairs already
536/// detached detached, each with its counter released and its enrollments
537/// swept, and the rest exactly as they were: a partial removal the next call
538/// finishes.
539///
540/// Answers the **blob keys** every detach's cascade removed — the
541/// question/answer images and homework files of each swept instance subtree —
542/// for the caller's route to unlink after the commits. Each detach commits its
543/// own transaction, so the keys of the rows already swept come back even when
544/// a later link refuses ([`crate::db::class_pump::detach_course`] answers
545/// `None` for a pair that held no instance, which contributes nothing); a
546/// failure before a link's detach returns the Err and drops the keys gathered
547/// so far, which is the same accepted window
548/// [`crate::service::course::delete`] documents: at worst an unreachable blob.
549pub async fn drop_links(
550 db: &Database,
551 id: &ClassBlueprintId,
552 links: Vec<Held>,
553) -> Result<Vec<String>, AppError> {
554 let mut blobs = Vec::new();
555 for link in links {
556 if let Some(keys) =
557 class_pump::detach_course(db, &link.class, &link.course, Some(id)).await?
558 {
559 blobs.extend(keys);
560 }
561 }
562 Ok(blobs)
563}