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

course_session.rs455 lines, 18.4 KiBHistoryRawDownload
1//! The `course_session` table: reads, an instance's timetable listing, the
2//! request-scoped field update, and the delete that sweeps roll-call rows in
3//! one transaction. Creation stands on the instance foreign key, so a lesson
4//! can never outlive the class×course instance it is a lesson of; the
5//! web-facing doors and the teacher-resolution rule live in
6//! [`crate::service::course_session`].
7
8use crate::constant::COURSE_SESSION_TABLE;
9use crate::database::{
10 Database, foreign_key_violation, tx_with_retry, unique_violation,
11};
12use crate::db::field_update::FieldUpdate;
13use crate::db::page::PagedList;
14use crate::domain::class_course::ClassCourseId;
15use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic};
16use crate::domain::timestamp::{Timestamp, range_error};
17use crate::domain::user::UserId;
18use crate::error::AppError;
19
20pub async fn create(
21 db: &Database,
22 class_course: &ClassCourseId,
23 teacher: &UserId,
24 topic: SessionTopic,
25 starts_at: Timestamp,
26 ends_at: Option<Timestamp>,
27) -> Result<CourseSession, AppError> {
28 let session = CourseSession {
29 id: CourseSessionId::generate(),
30 class_course: class_course.clone(),
31 teacher: *teacher,
32 topic,
33 starts_at,
34 ends_at,
35 };
36 // The instance foreign key is the existence proof the old
37 // bump-and-restore "touch" trick faked: a lesson whose instance is
38 // already gone — or which is detached while this insert is in flight — is
39 // refused here, so a lesson can never outlive the instance and 404
40 // through the session reads forever — unreadable, unpatchable,
41 // undeletable. `23503` is the parent-gone refusal, the same answer the
42 // touch produced.
43 let created = sqlx::query_as!(
44 CourseSession,
45 r#"INSERT INTO course_session (id, class_course, teacher, topic, starts_at, ends_at)
46 VALUES ($1, $2, $3, $4, $5, $6)
47 RETURNING id AS "id: CourseSessionId",
48 class_course AS "class_course: ClassCourseId",
49 teacher AS "teacher: UserId", topic AS "topic: SessionTopic",
50 starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp""#,
51 session.id.uuid(),
52 session.class_course.uuid(),
53 session.teacher.uuid(),
54 session.topic.as_str(),
55 session.starts_at.as_millis(),
56 session.ends_at.map(|at| at.as_millis()),
57 )
58 .fetch_one(db)
59 .await;
60 match created {
61 Ok(created) => Ok(created),
62 Err(err) if foreign_key_violation(&err) => Err(AppError::NotFound),
63 // `23505` — the section's own `UNIQUE (class_course, starts_at)`: a
64 // lesson already starts at that instant (a hand-created one, or one a
65 // concurrent materialize just minted). The same refusal the
66 // weekly-plan duplicate answers with.
67 Err(err) if unique_violation(&err).is_some() => Err(AppError::ConflictCoded {
68 code: "session_time_taken",
69 message: "this section already has a lesson starting then".into(),
70 }),
71 Err(err) => Err(err.into()),
72 }
73}
74
75/// One session to batch-insert: everything the materializer already decided.
76/// The wire shape of [`insert_many`], not a door of its own.
77#[derive(Debug, Clone)]
78pub struct NewSession {
79 pub id: CourseSessionId,
80 pub class_course: ClassCourseId,
81 pub teacher: UserId,
82 pub topic: SessionTopic,
83 pub starts_at: Timestamp,
84 pub ends_at: Timestamp,
85}
86
87/// Insert a batch of generated sessions in one statement, skipping the starts
88/// this section already holds (`ON CONFLICT DO NOTHING` against
89/// `UNIQUE (class_course, starts_at)`). The returned rows are exactly the rows
90/// that landed, so the caller's `created` count is truthful. No transaction of
91/// its own: the caller's (or none — the conflict skip makes a partial batch a
92/// safe outcome either way). Empty input never touches the database.
93pub async fn insert_many(
94 db: &Database,
95 rows: &[NewSession],
96) -> Result<Vec<CourseSession>, AppError> {
97 if rows.is_empty() {
98 return Ok(Vec::new());
99 }
100 let mut conn = db.acquire().await?;
101 insert_many_tx(&mut conn, rows).await
102}
103
104/// The transaction-scoped twin of [`insert_many`]: the very same statement,
105/// bound to the caller's own connection, so a batch its transaction rolls back
106/// never lands. The materializer is the caller — its row lock and its insert
107/// must be the one transaction, and a pooled insert inside that window would
108/// commit on its own.
109pub(crate) async fn insert_many_tx(
110 tx: &mut sqlx::PgConnection,
111 rows: &[NewSession],
112) -> Result<Vec<CourseSession>, AppError> {
113 if rows.is_empty() {
114 return Ok(Vec::new());
115 }
116 let ids: Vec<uuid::Uuid> = rows.iter().map(|row| row.id.uuid()).collect();
117 let class_courses: Vec<uuid::Uuid> = rows.iter().map(|row| row.class_course.uuid()).collect();
118 let teachers: Vec<uuid::Uuid> = rows.iter().map(|row| row.teacher.uuid()).collect();
119 let topics: Vec<String> = rows.iter().map(|row| row.topic.as_str().to_owned()).collect();
120 let starts: Vec<i64> = rows.iter().map(|row| row.starts_at.as_millis()).collect();
121 let ends: Vec<i64> = rows.iter().map(|row| row.ends_at.as_millis()).collect();
122 let inserted = sqlx::query_as!(
123 CourseSession,
124 r#"INSERT INTO course_session (id, class_course, teacher, topic, starts_at, ends_at)
125 SELECT * FROM unnest($1::uuid[], $2::uuid[], $3::uuid[], $4::text[], $5::bigint[], $6::bigint[])
126 ON CONFLICT (class_course, starts_at) DO NOTHING
127 RETURNING id AS "id: CourseSessionId",
128 class_course AS "class_course: ClassCourseId",
129 teacher AS "teacher: UserId", topic AS "topic: SessionTopic",
130 starts_at AS "starts_at: Timestamp", ends_at AS "ends_at?: Timestamp""#,
131 &ids,
132 &class_courses,
133 &teachers,
134 &topics,
135 &starts,
136 &ends,
137 )
138 .fetch_all(&mut *tx)
139 .await?;
140 Ok(inserted)
141}
142
143/// The instants this section already holds a lesson at — the materializer's
144/// skip set, one read for the whole range.
145pub async fn existing_starts(
146 db: &Database,
147 instance: &ClassCourseId,
148) -> Result<std::collections::HashSet<i64>, AppError> {
149 let rows = sqlx::query_scalar!(
150 r#"SELECT starts_at FROM course_session WHERE class_course = $1"#,
151 instance.uuid(),
152 )
153 .fetch_all(db)
154 .await?;
155 Ok(rows.into_iter().collect())
156}
157
158pub async fn read(db: &Database, id: &CourseSessionId) -> Result<Option<CourseSession>, AppError> {
159 let session = sqlx::query_as!(
160 CourseSession,
161 r#"SELECT id AS "id: CourseSessionId",
162 class_course AS "class_course: ClassCourseId",
163 teacher AS "teacher: UserId", topic AS "topic: SessionTopic",
164 starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp"
165 FROM course_session WHERE id = $1"#,
166 id.uuid(),
167 )
168 .fetch_optional(db)
169 .await?;
170 Ok(session)
171}
172
173/// An instance's sessions, most recent lesson first. Ordered by `starts_at`
174/// (not id): a timetable is read by when the lesson happens, not by when
175/// the row was created.
176///
177/// `starts_after`/`starts_before` narrow the list to a half-open
178/// `[starts_after, starts_before)` on `starts_at` — a calendar month is
179/// `[month_start, next_month_start)` — with the page and the count sharing
180/// the one `WHERE`. Absent bounds leave today's unfiltered read.
181pub async fn list_for_class_course(
182 db: &Database,
183 class_course: &ClassCourseId,
184 starts_after: Option<i64>,
185 starts_before: Option<i64>,
186 limit: Option<i64>,
187 offset: i64,
188) -> Result<(Vec<CourseSession>, i64), AppError> {
189 let from_where = match (starts_after, starts_before) {
190 (Some(_), Some(_)) => {
191 "course_session WHERE class_course = $1 AND starts_at >= $2 AND starts_at < $3"
192 }
193 (Some(_), None) => "course_session WHERE class_course = $1 AND starts_at >= $2",
194 (None, Some(_)) => "course_session WHERE class_course = $1 AND starts_at < $2",
195 (None, None) => "course_session WHERE class_course = $1",
196 };
197 let mut list = PagedList::new(from_where, "ORDER BY starts_at DESC, id DESC")
198 .bind(class_course.uuid());
199 if let Some(after) = starts_after {
200 list = list.bind(after);
201 }
202 if let Some(before) = starts_before {
203 list = list.bind(before);
204 }
205 list.run::<CourseSession>(limit, offset, db).await
206}
207
208/// Request-scoped: the handler holds nothing across its read and this
209/// write — the range check rides in the `WHERE` — so a field the request
210/// omitted (`None`) is not written at all. Re-sending the snapshot's value
211/// instead would revert a concurrent PATCH of that field — scoping the
212/// `SET` alone does not stop that, the values have to come from the
213/// request. `ends_at` is nullable, so it takes the outer/inner
214/// `Option<Option<_>>`: `None` = omitted (keep), `Some(None)` = clear.
215pub async fn update(
216 db: &Database,
217 session: CourseSession,
218 teacher: Option<UserId>,
219 topic: Option<SessionTopic>,
220 starts_at: Option<Timestamp>,
221 ends_at: Option<Option<Timestamp>>,
222) -> Result<CourseSession, AppError> {
223 let updated = FieldUpdate::new(COURSE_SESSION_TABLE, session.id.uuid())
224 .set(
225 "teacher",
226 teacher.map(|teacher| crate::db::page::Param::Uuid(teacher.uuid())),
227 )
228 .set("topic", topic.map(|topic| topic.as_str().to_owned()))
229 .set("starts_at", starts_at.map(|at| at.as_millis()))
230 .set(
231 "ends_at",
232 ends_at.map(|ends_at| crate::db::page::Param::OptI64(ends_at.map(|at| at.as_millis()))),
233 )
234 .ordered("starts_at", "ends_at", range_error())
235 .run::<CourseSession>(db)
236 .await;
237 match updated {
238 Ok(updated) => Ok(updated),
239 // `23505` — the section's own `UNIQUE (class_course, starts_at)`: the
240 // PATCH moved this lesson onto an instant the section already holds
241 // (a hand-created one, or one a concurrent materialize just minted).
242 // The same coded refusal `create` answers with, never a raw 500.
243 Err(AppError::Db(err)) if unique_violation(&err).is_some() => Err(AppError::ConflictCoded {
244 code: "session_time_taken",
245 message: "this section already has a lesson starting then".into(),
246 }),
247 Err(err) => Err(err),
248 }
249}
250
251/// Delete the session and cascade-remove its roll-call rows, in one
252/// transaction: as two unbatched queries a failure between them stranded
253/// roll-call rows on a session that was already gone. The other half of
254/// that invariant is [`crate::db::session_attendance::mark`], whose
255/// session-row lock makes a mark and this delete take turns — a mark
256/// committing after this cascade cannot name a session that is gone.
257pub async fn delete(db: &Database, session: CourseSession) -> Result<CourseSession, AppError> {
258 // Cascade mode: a roll-call row written *after* the sweep's snapshot (a
259 // mark racing the delete) still references the session when the session
260 // row goes, and that 23503 means "a racing writer is mid-flight" — the
261 // re-send sweeps the settled rows and succeeds.
262 tx_with_retry(db, true, async move |tx| {
263 // Roll-call rows first: the session row's own FK would refuse the
264 // delete while they exist. An empty first sweep is fine — the
265 // session may simply have had none.
266 sqlx::query!(
267 r#"DELETE FROM session_attendance WHERE session = $1"#,
268 session.id.uuid(),
269 )
270 .execute(&mut *tx)
271 .await?;
272 let deleted = sqlx::query_as!(
273 CourseSession,
274 r#"DELETE FROM course_session WHERE id = $1
275 RETURNING id AS "id: CourseSessionId",
276 class_course AS "class_course: ClassCourseId",
277 teacher AS "teacher: UserId", topic AS "topic: SessionTopic",
278 starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp""#,
279 session.id.uuid(),
280 )
281 .fetch_optional(&mut *tx)
282 .await?;
283 deleted.ok_or(AppError::NotFound)
284 })
285 .await
286}
287
288#[cfg(test)]
289mod tests {
290 use super::*;
291
292 /// A lesson must not outlive the course it is a lesson of: an orphan 404s
293 /// forever through `session_with_course` — unreadable, unpatchable,
294 /// undeletable.
295 ///
296 /// [`create`] therefore *writes* the course row rather than
297 /// reading it ([`cap::touch_and_create`]); the harness and the window it
298 /// races in are documented on
299 /// [`crate::db::course::assert_no_child_outlives_a_course_delete`].
300 /// Mutation-tested: with the bare `db.create` this shipped with, all four
301 /// rounds orphan.
302 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
303 async fn a_session_never_outlives_its_course() {
304 use crate::domain::course::CourseId;
305 use crate::domain::user::UserId;
306
307 fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> {
308 tokio::spawn(async move {
309 // The creator is a foreign key now: a real `app_user` row.
310 let creator = UserId::generate();
311 sqlx::query(
312 "INSERT INTO app_user (id, username, created_at, role) \
313 VALUES ($1, $2, 0, 'teacher')",
314 )
315 .bind(creator.uuid())
316 .bind(format!("session-race-{}", &creator.key()[30..]))
317 .execute(&db)
318 .await
319 .unwrap();
320 // The lesson hangs off the instance now, so the round has to
321 // attach one — that claim is exactly what the racing delete
322 // contends on, and a course already gone refuses right here.
323 let class = crate::db::class_group::create(
324 &db,
325 &creator,
326 crate::domain::class_group::ClassName::try_new("9-A").unwrap(),
327 crate::domain::grade::GradeLevel::new(9).unwrap(),
328 None,
329 None,
330 )
331 .await?
332 .get_id()
333 .clone();
334 let instance = crate::service::class_course::attach(&db, &class, &course, &creator)
335 .await?
336 .get_id()
337 .clone();
338 create(
339 &db,
340 &instance,
341 &creator,
342 SessionTopic::try_new("limits").unwrap(),
343 Timestamp::from_millis(1),
344 None,
345 )
346 .await
347 .map(|_| ())
348 })
349 }
350 crate::db::course::assert_no_child_outlives_a_course_delete(
351 "course_session",
352 "SELECT count(*) FROM course_session s
353 JOIN class_course cc ON cc.id = s.class_course
354 WHERE cc.course = $1",
355 make,
356 )
357 .await;
358 }
359
360 /// One section, three lessons an hour apart across `now`. Starts differ
361 /// per row: the section's `UNIQUE (class_course, starts_at)` refuses a
362 /// shared instant, and the window bounds below hang off that middle
363 /// lesson's exact start.
364 async fn three_sessions(db: &Database) -> (ClassCourseId, i64) {
365 let (instance, _) = crate::db::course::a_test_instance(db).await;
366 let teacher = UserId::generate();
367 sqlx::query(
368 "INSERT INTO app_user (id, username, created_at, role) \
369 VALUES ($1, $2, 0, 'teacher')",
370 )
371 .bind(teacher.uuid())
372 .bind(format!("session-window-{}", &teacher.key()[30..]))
373 .execute(db)
374 .await
375 .unwrap();
376 let now = Timestamp::now().as_millis();
377 for starts_at in [now - 3_600_000, now, now + 3_600_000] {
378 create(
379 db,
380 &instance,
381 &teacher,
382 SessionTopic::try_new("limits").unwrap(),
383 Timestamp::from_millis(starts_at),
384 None,
385 )
386 .await
387 .unwrap();
388 }
389 (instance, now)
390 }
391
392 #[tokio::test]
393 async fn the_session_window_is_half_open_on_starts_at() {
394 let (db, _leases) = crate::database::init_test_db().await;
395 let (instance, now) = three_sessions(&db).await;
396
397 // Absent bounds: every session, most recent lesson first.
398 let (rows, total) = list_for_class_course(&db, &instance, None, None, None, 0)
399 .await
400 .unwrap();
401 assert_eq!(total, 3);
402 let starts: Vec<_> = rows.iter().map(|s| s.get_starts_at().as_millis()).collect();
403 assert_eq!(starts, vec![now + 3_600_000, now, now - 3_600_000]);
404
405 // starts_after is inclusive: the middle lesson (exactly `now`) stays,
406 // and the order does not flip.
407 let (rows, total) = list_for_class_course(&db, &instance, Some(now), None, None, 0)
408 .await
409 .unwrap();
410 assert_eq!(total, 2);
411 let starts: Vec<_> = rows.iter().map(|s| s.get_starts_at().as_millis()).collect();
412 assert_eq!(starts, vec![now + 3_600_000, now]);
413
414 // starts_before is strict: the middle lesson is out.
415 let (rows, total) = list_for_class_course(&db, &instance, None, Some(now), None, 0)
416 .await
417 .unwrap();
418 assert_eq!(total, 1);
419 assert_eq!(rows[0].get_starts_at().as_millis(), now - 3_600_000);
420
421 // The half-open pair pins exactly the middle lesson.
422 let (rows, total) = list_for_class_course(
423 &db,
424 &instance,
425 Some(now),
426 Some(now + 3_600_000),
427 None,
428 0,
429 )
430 .await
431 .unwrap();
432 assert_eq!((rows.len(), total), (1, 1));
433 assert_eq!(rows[0].get_starts_at().as_millis(), now);
434
435 // The limit pages the filtered set; total is the filtered count.
436 let (rows, total) = list_for_class_course(&db, &instance, Some(now), None, Some(1), 0)
437 .await
438 .unwrap();
439 assert_eq!((rows.len(), total), (1, 2));
440 assert_eq!(rows[0].get_starts_at().as_millis(), now + 3_600_000);
441
442 // An instant naming no lesson is an empty page, not an error.
443 let (rows, total) = list_for_class_course(
444 &db,
445 &instance,
446 Some(now + 30 * 86_400_000),
447 None,
448 None,
449 0,
450 )
451 .await
452 .unwrap();
453 assert!(rows.is_empty() && total == 0);
454 }
455}