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

term.rs466 lines, 19.2 KiBHistoryRawDownload
1//! The `term` table: the row mint, the paged calendar listing, the
2//! field-scoped PATCH whose `WHERE` re-checks the merged range, the delete
3//! guarded by the row's own reference counters, and the archive/unarchive
4//! stamps. The type and the errors its guards hand out live in
5//! [`crate::domain::term`].
6
7use crate::constant::TERM_TABLE;
8use crate::database::Database;
9use crate::db::field_update::FieldUpdate;
10use crate::db::page::PagedList;
11use crate::domain::academic_year::AcademicYearId;
12use crate::domain::term::{Term, TermId, TermName};
13use crate::domain::timestamp::{Timestamp, range_error};
14use crate::error::{AppError, ValidationError};
15
16pub async fn create(
17 db: &Database,
18 name: TermName,
19 year: AcademicYearId,
20 starts_at: Timestamp,
21 ends_at: Timestamp,
22) -> Result<Term, AppError> {
23 let term = Term {
24 id: TermId::generate(),
25 year,
26 name,
27 starts_at,
28 ends_at,
29 archived_at: None,
30 };
31 // The year is claimed in the same statement as the row: `academic_year.
32 // term_count` + 1 is what the year's own delete guard reads, and
33 // claim-and-insert in one CTE means no crash can strand one half without
34 // the other. A year that is gone matches nothing — the `gone_error` the
35 // web layer's own read answers one instant earlier.
36 let created = sqlx::query_as!(
37 Term,
38 r#"WITH room AS (
39 UPDATE academic_year SET term_count = term_count + 1
40 WHERE id = $5
41 RETURNING 1)
42 INSERT INTO term (id, name, year, starts_at, ends_at, archived_at)
43 SELECT $1, $2, $5, $3, $4, NULL WHERE EXISTS (SELECT 1 FROM room)
44 RETURNING id AS "id: TermId", year AS "year: AcademicYearId",
45 name AS "name: TermName",
46 starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp",
47 archived_at AS "archived_at: Timestamp""#,
48 term.id.uuid(),
49 term.name.as_str(),
50 term.starts_at.as_millis(),
51 term.ends_at.as_millis(),
52 term.year.uuid(),
53 )
54 .fetch_optional(db)
55 .await?;
56 created.ok_or_else(|| {
57 AppError::Validation(ValidationError::Invalid {
58 field: "year",
59 reason: "academic year does not exist",
60 })
61 })
62}
63
64pub async fn read(db: &Database, id: &TermId) -> Result<Option<Term>, AppError> {
65 let term = sqlx::query_as!(
66 Term,
67 r#"SELECT id AS "id: TermId", year AS "year: AcademicYearId",
68 name AS "name: TermName",
69 starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp",
70 archived_at AS "archived_at: Timestamp" FROM term WHERE id = $1"#,
71 id.uuid(),
72 )
73 .fetch_optional(db)
74 .await?;
75 Ok(term)
76}
77
78/// Every term, newest first — the school calendar is small by nature.
79pub async fn list_all(
80 db: &Database,
81 limit: Option<i64>,
82 offset: i64,
83) -> Result<(Vec<Term>, i64), AppError> {
84 PagedList::new("term", "ORDER BY starts_at DESC, id DESC")
85 .run::<Term>(limit, offset, db)
86 .await
87}
88
89/// Write only the fields the PATCH carried — `None` means the request
90/// omitted it, so the column is left alone rather than re-stated from the
91/// snapshot this struct was read into. All three columns are non-nullable,
92/// so "absent" and "null" both correctly mean "keep".
93pub async fn update(
94 db: &Database,
95 term: Term,
96 name: Option<TermName>,
97 starts_at: Option<Timestamp>,
98 ends_at: Option<Timestamp>,
99) -> Result<Term, AppError> {
100 FieldUpdate::new(TERM_TABLE, term.id.uuid())
101 .set("name", name.map(|name| name.as_str().to_owned()))
102 .set("starts_at", starts_at.map(|at| at.as_millis()))
103 .set("ends_at", ends_at.map(|at| at.as_millis()))
104 .ordered("starts_at", "ends_at", range_error())
105 .run::<Term>(db)
106 .await
107}
108
109/// Delete the term, but only while nothing links it — nothing here unlinks or
110/// cascades. `false` = refused, nothing was written.
111///
112/// Two children refuse it. Exams are counted by the term's own `exam_count`
113/// refcount, claimed by [`crate::db::exam::create`] *before* it writes the
114/// link, so the check and the delete are one conditional write on one record:
115/// an exam write racing this either claims first (and the delete is refused)
116/// or finds the row gone (and is refused itself). A frozen report card
117/// ([`crate::db::karne`]) has no counter — it is written once per archived
118/// term — so its existence is the `NOT EXISTS` half of the same guard: a
119/// term a family holds a report card for is history, not a calendar entry.
120///
121/// The referencing foreign keys (`exam.term`, `karne_snapshot.term`, both
122/// `NO ACTION`) are the backstop behind the guard, not a second one: while
123/// the count is honest the `WHERE` decides every race on its own, because the
124/// claim path locks this very row before it writes a link. `Err(NotFound)`
125/// keeps the answer a concurrent *delete* used to get.
126///
127/// The year is handed its reference back in the *same statement* — a
128/// `DELETE … RETURNING year` feeding the decrement, the shape
129/// [`crate::db::course::delete`] uses for its classes — so a year whose last
130/// term was just deleted is deletable the moment this lands. The counter
131/// lives on the year row and only this statement may release it: without the
132/// release the year's own `term_count = 0` delete guard could never pass
133/// again, and a year nobody links would be undeletable forever.
134pub async fn delete(db: &Database, term: Term) -> Result<bool, AppError> {
135 let gone = sqlx::query!(
136 r#"WITH gone AS (
137 DELETE FROM term
138 WHERE id = $1 AND exam_count = 0
139 AND NOT EXISTS (SELECT 1 FROM karne_snapshot WHERE term = $1)
140 RETURNING year)
141 UPDATE academic_year
142 SET term_count = GREATEST(term_count - 1, 0)
143 FROM gone
144 WHERE academic_year.id = gone.year"#,
145 term.id.uuid(),
146 )
147 .execute(db)
148 .await?;
149 if gone.rows_affected() > 0 {
150 return Ok(true);
151 }
152 // Still linked or already gone: the one statement cannot tell those
153 // apart, and only the refusal path pays for the read that can.
154 match read(db, &term.id).await? {
155 Some(_) => Ok(false),
156 None => Err(AppError::NotFound),
157 }
158}
159
160/// Freeze the term. Idempotent by construction: the `WHERE` only matches an
161/// open row, so a repeat archive writes nothing and answers with the
162/// *original* stamp — the year is not re-dated by a double click.
163pub async fn archive(db: &Database, term: Term) -> Result<Term, AppError> {
164 let written = sqlx::query_as!(
165 Term,
166 r#"UPDATE term SET archived_at = $2
167 WHERE id = $1 AND archived_at IS NULL
168 RETURNING id AS "id: TermId", year AS "year: AcademicYearId",
169 name AS "name: TermName",
170 starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp",
171 archived_at AS "archived_at: Timestamp""#,
172 term.id.uuid(),
173 Timestamp::now().as_millis(),
174 )
175 .fetch_optional(db)
176 .await?;
177 match written {
178 Some(written) => Ok(written),
179 // A repeat archive (or a term deleted under the request): the stored
180 // row is the answer, and only the no-op path pays for the read.
181 None => read(db, &term.id).await?.ok_or(AppError::NotFound),
182 }
183}
184
185/// Re-open the term; idempotent the same way.
186pub async fn unarchive(db: &Database, term: Term) -> Result<Term, AppError> {
187 let written = sqlx::query_as!(
188 Term,
189 r#"UPDATE term SET archived_at = NULL
190 WHERE id = $1 AND archived_at IS NOT NULL
191 RETURNING id AS "id: TermId", year AS "year: AcademicYearId",
192 name AS "name: TermName",
193 starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp",
194 archived_at AS "archived_at: Timestamp""#,
195 term.id.uuid(),
196 )
197 .fetch_optional(db)
198 .await?;
199 match written {
200 Some(written) => Ok(written),
201 None => read(db, &term.id).await?.ok_or(AppError::NotFound),
202 }
203}
204
205/// A real term behind a real academic year — the parent every exam names and
206/// the grading slice every term-keyed read scopes to. Minted per call.
207#[cfg(test)]
208pub(crate) async fn a_test_term(db: &Database) -> TermId {
209 let year = crate::db::academic_year::a_test_year(db).await;
210 let term = create(
211 db,
212 TermName::try_new("1. Dönem").unwrap(),
213 year,
214 Timestamp::from_millis(0),
215 Timestamp::from_millis(1),
216 )
217 .await
218 .unwrap();
219 *term.get_id()
220}
221
222#[cfg(test)]
223mod tests {
224 use super::*;
225
226 /// The bite test for the `WHERE` guard that replaced `TERM_LOCK` on the
227 /// PATCH path: the handler's pre-flight check is not in play here, so only
228 /// the guard can refuse a moved end that inverts the range — and it must
229 /// refuse it with the same error, having written nothing.
230 #[tokio::test]
231 async fn a_moved_end_is_refused_against_the_stored_other_end() {
232 let (db, _leases) = crate::database::init_test_db().await;
233 let at = Timestamp::from_millis;
234 let term = create(
235 &db,
236 TermName::try_new("2026").unwrap(),
237 crate::db::academic_year::a_test_year(&db).await,
238 at(100),
239 at(200),
240 )
241 .await
242 .unwrap();
243
244 let refused = update(&db, term.clone(), None, None, Some(at(50)))
245 .await
246 .expect_err("an end before the stored start must be refused");
247 assert!(refused.to_string().contains("at or after starts_at"));
248 let stored = read(&db, term.get_id()).await.unwrap().unwrap();
249 assert_eq!(
250 stored.get_ends_at(),
251 at(200),
252 "nothing may have been written"
253 );
254
255 // A move that keeps the range ordered still lands, guard and all.
256 let moved = update(&db, term, None, None, Some(at(300))).await.unwrap();
257 assert_eq!(moved.get_ends_at(), at(300));
258 }
259
260 /// Terms are listed newest-first *and* paged by offset, so the sort has to
261 /// be a total order: `starts_at` alone leaves rows that share an instant in
262 /// an arbitrary order, and offset paging over an unstable order can hand
263 /// the same row out twice while skipping another. Pins the `id DESC`
264 /// tie-break on identical `starts_at` — stored read-back, then page by page.
265 #[tokio::test]
266 async fn identical_starts_at_still_pages_each_term_exactly_once() {
267 let (db, _leases) = crate::database::init_test_db().await;
268 let at = Timestamp::from_millis;
269 let year = crate::db::academic_year::a_test_year(&db).await;
270 let mut minted = Vec::new();
271 for i in 0..12 {
272 let term = create(
273 &db,
274 TermName::try_new(&format!("t{i}")).unwrap(),
275 year,
276 at(100),
277 at(200),
278 )
279 .await
280 .unwrap();
281 minted.push(term.get_id().key().to_string());
282 }
283 // Newest first: the tie-break runs the same way as the primary column.
284 minted.reverse();
285
286 let (listed, total) = list_all(&db, None, 0).await.unwrap();
287 assert_eq!(total, 12);
288 let read_back: Vec<String> = listed
289 .iter()
290 .map(|row| row.get_id().key().to_string())
291 .collect();
292 assert_eq!(read_back, minted);
293
294 // The assertion that catches skip/duplicate: walk it in pages of 5.
295 let mut paged = Vec::new();
296 for offset in [0, 5, 10] {
297 let (page, total) = list_all(&db, Some(5), offset).await.unwrap();
298 assert_eq!(total, 12);
299 paged.extend(page.iter().map(|row| row.get_id().key().to_string()));
300 }
301 assert_eq!(paged, minted, "every term exactly once, in list order");
302 }
303
304 /// GUARD, not a retry measurement — read the last paragraph before
305 /// trusting this test with the retry. See
306 /// [`crate::db::course::delete`]'s race test for why the rate is
307 /// counted rather than asserted per round.
308 ///
309 /// One conditional `DELETE … RETURN BEFORE` and a bare `.check()?`: no
310 /// transaction to abort, but also no [`crate::database::write_with_retry`],
311 /// which every other guarded single-statement write in the crate goes
312 /// through. A store answering "conflict, retry" therefore comes out as a
313 /// 500 instead of the 404 or 409 the request owes.
314 ///
315 /// The racer is [`crate::db::exam::create`] against this
316 /// term: it claims `exam_count` on the term row before it writes the
317 /// link, which is the same record and the same column the guard reads. Both
318 /// sides are swept across each other sub-millisecond, exactly as in
319 /// [`crate::db::subject::delete`]'s race test — a whole
320 /// millisecond of head start on either side separates them completely, and
321 /// the counters below assert the sweep straddled the site rather than
322 /// landing on one side of it (it used to alternate on `round % 2` and score
323 /// an exact 10/10, i.e. no overlap at all).
324 ///
325 /// And like that test it does *not* prove the retry: this site is one
326 /// statement, so the window in which a conflict could reach
327 /// [`write_with_retry`] is a single round trip wide — measured at 0
328 /// conflicts in 100 raced rounds, green with the retry loop cut to a single
329 /// attempt. A status-code guard, then: a raced delete answers 409 or 404 and
330 /// never 500, and an exam that got linked survives it. The retry is
331 /// measured on [`crate::db::course::delete`].
332 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
333 async fn a_delete_racing_an_exam_create_never_answers_500() {
334 use crate::domain::exam::{
335 ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle,
336 };
337 use crate::domain::user::UserId;
338 let (db, _leases) = crate::database::init_test_db().await;
339 // The exam's parents are foreign keys now: one real instance — with
340 // its class and course — reused by every create in every round, and
341 // one real creator.
342 let (instance, _course) = crate::db::course::a_test_instance(&db).await;
343 let teacher = UserId::generate();
344 sqlx::query(
345 "INSERT INTO app_user (id, username, created_at, role) \
346 VALUES ($1, $2, 0, 'teacher')",
347 )
348 .bind(teacher.uuid())
349 .bind(format!("term-race-{}", &teacher.key()[30..]))
350 .execute(&db)
351 .await
352 .unwrap();
353 let kinds = crate::domain::settings::Settings::defaults()
354 .get_exam_kinds()
355 .to_vec();
356 let year = crate::db::academic_year::a_test_year(&db).await;
357 let (mut delete_500, mut create_500) = (0, 0);
358 let (mut linked, mut wiped) = (0, 0);
359 let (mut last_delete, mut last_create) = (String::new(), String::new());
360 let at = Timestamp::from_millis;
361 for round in 0..20 {
362 let term = create(
363 &db,
364 TermName::try_new("2026").unwrap(),
365 year,
366 at(100),
367 at(200),
368 )
369 .await
370 .unwrap();
371
372 let separated = round % 4 == 0;
373 let drop_it = {
374 let (term, db) = (term.clone(), db.clone());
375 // One round in four holds the racers back by a clear 2ms so the
376 // delete wins outright: the sub-millisecond sweep alone leaves
377 // them ahead of it nearly every round (measured 20 to 0), and
378 // both counters below have to see a side. The other three keep
379 // the sub-ms beat, which is the only spacing that overlaps at
380 // all — a whole millisecond either way separates them.
381 let beat = if separated {
382 std::time::Duration::ZERO
383 } else {
384 std::time::Duration::from_micros(round * 53 % 300)
385 };
386 tokio::spawn(async move {
387 tokio::time::sleep(beat).await;
388 delete(&db, term).await
389 })
390 };
391 let makes: Vec<_> = (0..6)
392 .map(|_| {
393 let (instance, db, teacher, kinds) =
394 (instance.clone(), db.clone(), teacher, kinds.clone());
395 let term = *term.get_id();
396 let head_start = if separated {
397 std::time::Duration::from_millis(2)
398 } else {
399 std::time::Duration::from_micros(round * 37 % 300)
400 };
401 tokio::spawn(async move {
402 tokio::time::sleep(head_start).await;
403 crate::db::exam::create(
404 &db,
405 &teacher,
406 &instance,
407 &term,
408 ExamTitle::try_new("algebra").unwrap(),
409 ExamDescription::try_new("").unwrap(),
410 ExamKind::try_new("yazili", &kinds).unwrap(),
411 ExamSchedule::try_new(None, None, None, None).unwrap(),
412 ExamAttemptLimit::try_new(1).unwrap(),
413 true,
414 false,
415 false,
416 )
417 .await
418 })
419 })
420 .collect();
421 let drop_it = drop_it.await.unwrap();
422 if matches!(drop_it, Err(AppError::Db(_))) {
423 delete_500 += 1;
424 last_delete = format!("{drop_it:?}");
425 }
426 // Stored state, both sides: a linked exam means the claim beat the
427 // guard, a gone term means the delete did.
428 let mut landed = false;
429 for make in makes {
430 let make = make.await.unwrap();
431 if matches!(make, Err(AppError::Db(_))) {
432 create_500 += 1;
433 last_create = format!("{make:?}");
434 }
435 if let Ok(exam) = &make
436 && crate::db::exam::read(&db, exam.get_id())
437 .await
438 .unwrap()
439 .is_some()
440 {
441 landed = true;
442 }
443 }
444 linked += usize::from(landed);
445 if read(&db, term.get_id()).await.unwrap().is_none() {
446 wiped += 1;
447 }
448 }
449 eprintln!(
450 "Term::delete raced: {delete_500}/20 delete 500s, {create_500} create 500s, \
451 {linked} rounds with an exam linked / {wiped} wiped"
452 );
453 assert!(
454 linked > 0 && wiped > 0,
455 "the sweep never crossed the window ({linked} linked / {wiped} wiped)"
456 );
457 assert_eq!(
458 delete_500, 0,
459 "a raced delete must be refused, not 500: {delete_500}/20 rounds, last {last_delete}"
460 );
461 assert_eq!(
462 create_500, 0,
463 "a raced exam create must retry, not 500: {create_500}/20 rounds, last {last_create}"
464 );
465 }
466}