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

subject.rs369 lines, 16.0 KiBHistoryRawDownload
1//! The `subject` table: the count-and-create that pins a topic to a live
2//! course row, the bulk id listing, the field-scoped PATCH, and the guarded
3//! delete whose guard reads the row's own reference counters. The type and
4//! its validation live in [`crate::domain::subject`].
5
6use crate::constant::SUBJECT_TABLE;
7use crate::database::Database;
8use crate::db::field_update::FieldUpdate;
9use crate::db::page::PagedList;
10use crate::domain::course::CourseId;
11use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName};
12use crate::error::AppError;
13
14pub async fn create(
15 db: &Database,
16 course: &CourseId,
17 name: SubjectName,
18 description: SubjectDescription,
19) -> Result<Subject, AppError> {
20 let subject = Subject {
21 id: SubjectId::generate(),
22 course: course.clone(),
23 name,
24 description,
25 };
26 // The course foreign key is the existence proof the old bump-and-restore
27 // "touch" trick faked: a topic whose course is already gone — or which is
28 // deleted while this insert is in flight — is refused here, so a subject
29 // can never outlive its course and a bank template can never be tagged
30 // with a subject nobody can reach. `23503` is the parent-gone refusal,
31 // the same answer the touch produced.
32 let created = sqlx::query_as!(
33 Subject,
34 r#"INSERT INTO subject (id, course, name, description, exam_question_count, homework_count)
35 VALUES ($1, $2, $3, $4, 0, 0)
36 RETURNING id AS "id: SubjectId",
37 course AS "course: CourseId",
38 name AS "name: SubjectName",
39 description AS "description: SubjectDescription""#,
40 subject.id.uuid(),
41 subject.course.uuid(),
42 subject.name.as_str(),
43 subject.description.as_str(),
44 )
45 .fetch_one(db)
46 .await;
47 match created {
48 Ok(created) => Ok(created),
49 Err(err) if crate::database::foreign_key_violation(&err) => Err(AppError::NotFound),
50 Err(err) => Err(err.into()),
51 }
52}
53
54pub async fn read(db: &Database, id: &SubjectId) -> Result<Option<Subject>, AppError> {
55 let subject = sqlx::query_as!(
56 Subject,
57 r#"SELECT id AS "id: SubjectId", course AS "course: CourseId", name AS "name: SubjectName", description AS "description: SubjectDescription" FROM subject WHERE id = $1"#,
58 id.uuid(),
59 )
60 .fetch_optional(db)
61 .await?;
62 Ok(subject)
63}
64
65/// Several subjects in one query — the bulk half of a list endpoint that
66/// names each row's subject (a read per row would be an N+1).
67pub async fn list_by_ids(db: &Database, ids: &[&SubjectId]) -> Result<Vec<Subject>, AppError> {
68 if ids.is_empty() {
69 return Ok(Vec::new());
70 }
71 let keys: Vec<uuid::Uuid> = ids.iter().map(|id| id.uuid()).collect();
72 let rows = sqlx::query_as!(
73 Subject,
74 r#"SELECT id AS "id: SubjectId", course AS "course: CourseId", name AS "name: SubjectName", description AS "description: SubjectDescription" FROM subject WHERE id = ANY($1)"#,
75 &keys,
76 )
77 .fetch_all(db)
78 .await?;
79 Ok(rows)
80}
81
82/// The course's subjects in curriculum order (uuid ids sort by creation).
83pub async fn list_for_course(
84 db: &Database,
85 course: &CourseId,
86 limit: Option<i64>,
87 offset: i64,
88) -> Result<(Vec<Subject>, i64), AppError> {
89 PagedList::new("subject WHERE course = $1", "ORDER BY id ASC")
90 .bind(course.uuid())
91 .run::<Subject>(limit, offset, db)
92 .await
93}
94
95/// Request-scoped: no lock spans the handler's read and this write, so an
96/// omitted field (`None`) is not written at all. Passing the snapshot's
97/// value back instead would revert a concurrent edit of that field —
98/// scoping the `SET` alone does not prevent that, the values have to come
99/// from the request. Neither column is nullable, so plain `Option` per
100/// field says everything there is to say.
101pub async fn update(
102 db: &Database,
103 subject: Subject,
104 name: Option<SubjectName>,
105 description: Option<SubjectDescription>,
106) -> Result<Subject, AppError> {
107 FieldUpdate::new(SUBJECT_TABLE, subject.id.uuid())
108 .set("name", name.map(|name| name.as_str().to_owned()))
109 .set("description", description.map(|d| d.as_str().to_owned()))
110 .run::<Subject>(db)
111 .await
112}
113
114/// Delete the subject and clear it off every bank template that carried it
115/// as origin metadata — one transaction, so a template can't be left
116/// pointing at a subject that no longer exists.
117///
118/// Exam questions and homework are *not* cascaded: their `subject` is a
119/// required field that may not be orphaned, so either one still refuses the
120/// delete with a 409. That refusal is this transaction's own check, read
121/// off the two reference counters this row carries
122/// (`exam_question_count` and its homework twin) under a `FOR UPDATE` row
123/// lock — the lock *is* the guard, because every counter writer must
124/// update this same row, so no question can land between the check and the
125/// delete. The old store could not conflict-check the cross-table shape,
126/// which is why the check had to be the `DELETE`'s own `WHERE`; here the
127/// row lock does it and the `WHERE` reads off the same columns.
128///
129/// Which of the two blocked is read off the counters *before* the delete,
130/// purely to pick the message; the decision itself was already made by the
131/// check.
132///
133/// The bank's subject is optional metadata, and blocking on it was a dead
134/// end — only the template's owner may re-tag it, so a manager could never
135/// clear their own 409, and a private template raising it leaked its
136/// existence. Its cascade clears the templates before the delete — the FK on
137/// `bank_question.subject` refuses the parent delete while a template still
138/// points at it — and the one transaction rolls everything back, so a refused
139/// delete leaves every template's subject where it was.
140pub async fn delete(db: &Database, subject: Subject) -> Result<Subject, AppError> {
141 crate::database::tx_with_retry(db, false, async move |tx| {
142 // The pre-image read and the guard in one locked statement: the row
143 // (and its counters) cannot change under this transaction.
144 let held = sqlx::query!(
145 r#"SELECT exam_question_count, homework_count
146 FROM subject WHERE id = $1 FOR UPDATE"#,
147 subject.id.uuid(),
148 )
149 .fetch_optional(&mut *tx)
150 .await?;
151 let held = held.ok_or(AppError::NotFound)?;
152 if held.exam_question_count > 0 {
153 return Err(AppError::Conflict(
154 "exam questions still reference this subject — re-tag or delete them first",
155 ));
156 }
157 if held.homework_count > 0 {
158 return Err(AppError::Conflict(
159 "homework still references this subject — re-tag or delete it first",
160 ));
161 }
162 // The bank's cascade clears the templates *before* the delete:
163 // `bank_question.subject` carries a real foreign key, so a template
164 // still pointing at this row makes the `DELETE` itself fail (23503)
165 // — the old store had no enforced reference to release. The guard
166 // above has already decided, and the transaction makes the pair
167 // atomic, so ordering costs nothing: a refused delete (an error
168 // raised anywhere above) rolls the whole thing back and every
169 // template's subject stays where it was.
170 sqlx::query!(
171 r#"UPDATE bank_question SET subject = NULL WHERE subject = $1"#,
172 subject.id.uuid(),
173 )
174 .execute(&mut *tx)
175 .await?;
176 let deleted = sqlx::query_as!(
177 Subject,
178 r#"DELETE FROM subject WHERE id = $1
179 RETURNING id AS "id: SubjectId",
180 course AS "course: CourseId",
181 name AS "name: SubjectName",
182 description AS "description: SubjectDescription""#,
183 subject.id.uuid(),
184 )
185 .fetch_one(&mut *tx)
186 .await?;
187 Ok(deleted)
188 })
189 .await
190}
191
192#[cfg(test)]
193mod tests {
194 use super::*;
195
196 /// A curriculum topic must not outlive its course: an orphan 404s through
197 /// `subject_with_course`, and worse than the sibling cases,
198 /// `must_exist` still *accepts* its id — so a bank template can be
199 /// tagged with a subject nobody can reach.
200 ///
201 /// [`create`] therefore *writes* the course row rather than
202 /// reading it ([`cap::touch_and_create`]); the harness and the window it
203 /// races in are documented on
204 /// [`crate::db::course::assert_no_child_outlives_a_course_delete`].
205 /// Mutation-tested: with the bare `db.create` this shipped with, all four
206 /// rounds orphan.
207 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
208 async fn a_subject_never_outlives_its_course() {
209 fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> {
210 tokio::spawn(async move {
211 create(
212 &db,
213 &course,
214 SubjectName::try_new("Limits").unwrap(),
215 SubjectDescription::try_new("").unwrap(),
216 )
217 .await
218 .map(|_| ())
219 })
220 }
221 crate::db::course::assert_no_child_outlives_a_course_delete(
222 "subject",
223 "SELECT count(*) FROM subject WHERE course = $1",
224 make,
225 )
226 .await;
227 }
228
229 /// GUARD, not a retry measurement — read the last paragraph before
230 /// trusting this test with the retry. See
231 /// [`crate::db::course::delete`]'s race test for why the rate
232 /// is counted rather than asserted per round, and why this needs the real
233 /// server and a multi-threaded runtime.
234 ///
235 /// The racer is [`crate::db::exam_question::create`], which claims the subject's
236 /// question reference *before* it writes the row — a conditional write on
237 /// the same record the delete's `WHERE` reads. `Err(Conflict)` (still
238 /// referenced), `Err(NotFound)` and the claim's `Validation` miss are all
239 /// correct answers; only `AppError::Db` is the defect. What the two stored
240 /// counters below assert is that the sweep genuinely straddled the site:
241 /// some rounds the claims won, some rounds the delete did.
242 ///
243 /// What it does *not* prove is the retry. The 500 window here is the delete
244 /// passing its `WHERE` and then committing while a claim is in flight, and
245 /// this cascade is three statements long — measured at 0 conflicts in 100
246 /// raced rounds, and the whole test stays green with
247 /// [`crate::database::transaction_with_retry`]'s loop cut to a single
248 /// attempt. Widening the sweep, staggering the burst and doubling it to 12
249 /// racers all failed to open the window (they only move which side wins).
250 /// So this is a status-code-and-cascade guard: a raced delete answers 409 or
251 /// 404 and never 500, and a landed question survives it. The retry itself is
252 /// measured on [`crate::db::course::delete`], whose cascade is
253 /// long enough to lose a round (1-2 of 20, red under the same mutation).
254 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
255 async fn a_delete_racing_a_question_never_answers_500() {
256 use crate::domain::exam_question::{
257 QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
258 };
259 let (db, _leases) = crate::database::init_test_db().await;
260 let (mut delete_500, mut question_500) = (0, 0);
261 let (mut landed, mut wiped) = (0, 0);
262 let (mut last_delete, mut last_question) = (String::new(), String::new());
263 for round in 0..20 {
264 let course = crate::db::course::a_test_course(&db).await;
265 // A real exam row per round: a question write moves its exam's
266 // counter, so a minted id nothing wrote is a 404 and no round would
267 // reach the subject race this test is about.
268 let exam = crate::db::exam::published_exam(&db).await.get_id().clone();
269 let subject = create(
270 &db,
271 &course,
272 SubjectName::try_new("Limits").unwrap(),
273 SubjectDescription::try_new("").unwrap(),
274 )
275 .await
276 .unwrap();
277
278 let separated = round % 4 == 0;
279 let drop_it = {
280 let (subject, db) = (subject.clone(), db.clone());
281 // One round in four holds the racers back by a clear 2ms so the
282 // delete wins outright: the sub-millisecond sweep alone leaves
283 // them ahead of it nearly every round (measured 20 to 0), and
284 // both counters below have to see a side. The other three keep
285 // the sub-ms beat, which is the only spacing that overlaps at
286 // all — a whole millisecond either way separates them.
287 let beat = if separated {
288 std::time::Duration::ZERO
289 } else {
290 std::time::Duration::from_micros(round * 53 % 300)
291 };
292 tokio::spawn(async move {
293 tokio::time::sleep(beat).await;
294 delete(&db, subject).await
295 })
296 };
297 let asks: Vec<_> = (0..6)
298 .map(|_| {
299 let (id, db, exam) = (*subject.get_id(), db.clone(), exam.clone());
300 let head_start = if separated {
301 std::time::Duration::from_millis(2)
302 } else {
303 std::time::Duration::from_micros(round * 37 % 300)
304 };
305 tokio::spawn(async move {
306 tokio::time::sleep(head_start).await;
307 crate::db::exam_question::create(
308 &db,
309 &exam,
310 id,
311 QuestionText::try_new("why").unwrap(),
312 QuestionPoints::try_new(1).unwrap(),
313 QuestionSpec::try_new(
314 QuestionKind::try_new("text").unwrap(),
315 None,
316 None,
317 &[],
318 )
319 .unwrap(),
320 )
321 .await
322 })
323 })
324 .collect();
325 let drop_it = drop_it.await.unwrap();
326 if matches!(drop_it, Err(AppError::Db(_))) {
327 delete_500 += 1;
328 last_delete = format!("{drop_it:?}");
329 }
330 for ask in asks {
331 let ask = ask.await.unwrap();
332 if matches!(ask, Err(AppError::Db(_))) {
333 question_500 += 1;
334 last_question = format!("{ask:?}");
335 }
336 }
337 // Stored state, and both sides are needed: a question landing means
338 // the claim beat the guard, the subject being gone means the delete
339 // did. Seeing only one is a run that never swept across the window.
340 if read(&db, subject.get_id()).await.unwrap().is_none() {
341 wiped += 1;
342 }
343 if !crate::db::exam_question::list_for_exam(&db, &exam, None, 0)
344 .await
345 .unwrap()
346 .0
347 .is_empty()
348 {
349 landed += 1;
350 }
351 }
352 eprintln!(
353 "Subject::delete raced: {delete_500}/20 delete 500s, {question_500} question 500s, \
354 {landed} rounds with a question landed / {wiped} wiped"
355 );
356 assert!(
357 landed > 0 && wiped > 0,
358 "the sweep never crossed the window ({landed} landed / {wiped} wiped)"
359 );
360 assert_eq!(
361 delete_500, 0,
362 "a raced delete must be refused, not 500: {delete_500}/20 rounds, last {last_delete}"
363 );
364 assert_eq!(
365 question_500, 0,
366 "a raced question create must retry, not 500: {question_500}/20 rounds, last {last_question}"
367 );
368 }
369}