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

event.rs571 lines, 23.1 KiBHistoryRawDownload
1//! The `event` table: row reads and listings, the cascading delete, and the
2//! audience's live membership resolution — the point check behind marking
3//! ([`includes`]) and the who-missed report's backbone ([`members`]).
4
5use crate::database::{Database, tx_with_retry};
6use crate::db::field_update::FieldUpdate;
7use crate::db::page::{PagedList, Param};
8use crate::domain::class_group::ClassGroupId;
9use crate::domain::course::CourseId;
10use crate::domain::event::{
11 Event, EventAudience, EventAudienceKind, EventDescription, EventId, EventTitle,
12};
13use crate::domain::role::Role;
14use crate::domain::timestamp::{Timestamp, range_error};
15use crate::domain::user::{User, UserId};
16use crate::error::AppError;
17use sqlx::query_as;
18
19/// Is `user` in this event's audience roster right now? The point check
20/// behind marking — cheaper than resolving the whole roster when the target
21/// is known. The audience comes off the row itself: the registration kind
22/// resolves against that event's signup rows.
23pub async fn includes(db: &Database, event: &Event, user: &User) -> Result<bool, AppError> {
24 match event.get_audience_kind() {
25 crate::domain::event::EventAudienceKind::School => Ok(true),
26 crate::domain::event::EventAudienceKind::Role => {
27 Ok(Some(user.get_role()) == event.get_audience_role())
28 }
29 crate::domain::event::EventAudienceKind::Course => match event.get_audience_course() {
30 Some(course) => {
31 Ok(crate::db::enrollment::user_is_in_course(db, course, user.get_id()).await?)
32 }
33 None => Ok(false),
34 },
35 // The (class, user) pair is the membership row's own key, so the point
36 // check is one existence probe — and `left_at IS NULL` makes it the
37 // *live* stint's, the row the partial unique index
38 // `class_member_live_pair` carries: a student who left the section is
39 // history, not audience, and a stale probe would let them be marked
40 // present at (and counted by) an event their section no longer
41 // attends.
42 crate::domain::event::EventAudienceKind::Class => match event.get_audience_class() {
43 Some(class) => {
44 let row = sqlx::query!(
45 "SELECT EXISTS(SELECT 1 FROM class_member
46 WHERE class = $1 AND app_user = $2 AND left_at IS NULL)
47 AS \"present!\"",
48 class.uuid(),
49 user.get_id().uuid()
50 )
51 .fetch_one(db)
52 .await?;
53 Ok(row.present)
54 }
55 None => Ok(false),
56 },
57 crate::domain::event::EventAudienceKind::Registration => Ok(
58 crate::db::registration::read_for_user(db, event.get_id(), user.get_id())
59 .await?
60 .is_some(),
61 ),
62 }
63}
64
65/// The event's full roster, as it stands right now — the who-missed
66/// report's backbone. Registered ids that no longer resolve to a user row
67/// are kept; the caller degrades their display like any stale reference.
68pub async fn members(db: &Database, event: &Event) -> Result<Vec<UserId>, AppError> {
69 match event.get_audience_kind() {
70 crate::domain::event::EventAudienceKind::School => {
71 Ok(crate::db::user::list_all(db, None, None, 0)
72 .await?
73 .0
74 .iter()
75 .map(|user| *user.get_id())
76 .collect())
77 }
78 crate::domain::event::EventAudienceKind::Role => match event.get_audience_role() {
79 Some(role) => Ok(crate::db::user::list_by_role(db, role)
80 .await?
81 .iter()
82 .map(|user| *user.get_id())
83 .collect()),
84 None => Ok(Vec::new()),
85 },
86 crate::domain::event::EventAudienceKind::Course => match event.get_audience_course() {
87 Some(course) => Ok(crate::db::enrollment::list_users_for_course(db, course).await?),
88 None => Ok(Vec::new()),
89 },
90 crate::domain::event::EventAudienceKind::Class => match event.get_audience_class() {
91 Some(class) => Ok(crate::db::class_member::list_for_class(db, class, None, 0)
92 .await?
93 .0
94 .iter()
95 .map(|member| *member.get_user())
96 .collect()),
97 None => Ok(Vec::new()),
98 },
99 crate::domain::event::EventAudienceKind::Registration => {
100 Ok(crate::db::registration::list_for_event(db, event.get_id())
101 .await?
102 .iter()
103 .map(|registration| *registration.get_user())
104 .collect())
105 }
106 }
107}
108
109pub async fn create(
110 db: &Database,
111 creator: &UserId,
112 title: EventTitle,
113 description: EventDescription,
114 audience: EventAudience,
115 starts_at: Option<Timestamp>,
116 ends_at: Option<Timestamp>,
117) -> Result<Event, AppError> {
118 // The audience payload moves as one unit with its kind; the validated
119 // bundle guarantees only the matching payload is ever non-NULL.
120 let created = query_as!(
121 Event,
122 "INSERT INTO event (id, creator, title, description, audience_kind, audience_role, \
123 audience_course, audience_class, audience_capacity, starts_at, ends_at)
124 VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
125 RETURNING id AS \"id: EventId\", creator AS \"creator: UserId\", title AS \"title: EventTitle\", description AS \"description: EventDescription\", \
126 audience_kind AS \"audience_kind: EventAudienceKind\", \
127 audience_role AS \"audience_role: Role\", \
128 audience_course AS \"audience_course: CourseId\", \
129 audience_class AS \"audience_class: ClassGroupId\", \
130 audience_capacity, starts_at AS \"starts_at: Timestamp\", \
131 ends_at AS \"ends_at: Timestamp\"",
132 EventId::generate().uuid(),
133 creator.uuid(),
134 title.as_str(),
135 description.as_str(),
136 audience.kind.as_str(),
137 audience.role.map(|r| r.as_str().to_string()),
138 audience.course.map(|c| c.uuid()),
139 audience.class.map(|c| c.uuid()),
140 audience.capacity,
141 starts_at.map(|t| t.as_millis()),
142 ends_at.map(|t| t.as_millis()),
143 )
144 .fetch_one(db)
145 .await?;
146 Ok(created)
147}
148
149pub async fn read(db: &Database, id: &EventId) -> Result<Option<Event>, AppError> {
150 let event = query_as!(
151 Event,
152 "SELECT id AS \"id: EventId\", creator AS \"creator: UserId\", title AS \"title: EventTitle\", description AS \"description: EventDescription\", \
153 audience_kind AS \"audience_kind: EventAudienceKind\", \
154 audience_role AS \"audience_role: Role\", \
155 audience_course AS \"audience_course: CourseId\", \
156 audience_class AS \"audience_class: ClassGroupId\", \
157 audience_capacity, starts_at AS \"starts_at: Timestamp\", \
158 ends_at AS \"ends_at: Timestamp\" \
159 FROM event WHERE id = $1",
160 id.uuid()
161 )
162 .fetch_optional(db)
163 .await?;
164 Ok(event)
165}
166
167/// The event list behind `GET /events`, paged by the database — the window is
168/// `LIMIT/OFFSET` in SQL, and `total` a `count(*)` over the same `WHERE`, so
169/// a schedule query never decodes the whole table to slice ten rows off it.
170///
171/// The four optional bounds are [`crate::web::page::WindowParams`]'s schedule
172/// window, validated upstream. All four absent is the unfiltered read,
173/// `ORDER BY id DESC` (newest first). Any bound set drops schedule-less rows
174/// (every predicate is `NULL`-rejecting) and flips the order to ascending by
175/// schedule — `starts_at`, falling back to `ends_at`, ties by id — the same
176/// order `WindowParams::apply` used to produce in Rust.
177pub async fn list_windowed(
178 db: &Database,
179 starts_after: Option<i64>,
180 ends_after: Option<i64>,
181 starts_before: Option<i64>,
182 ends_before: Option<i64>,
183 limit: Option<i64>,
184 offset: i64,
185) -> Result<(Vec<Event>, i64), AppError> {
186 // Conditions and binds move together: each bound appends its predicate
187 // with the placeholder number its bind position lands on.
188 let mut conds: Vec<String> = Vec::new();
189 let mut bounds: Vec<i64> = Vec::new();
190 let mut bound = |column: &str, op: &str, value: Option<i64>| {
191 if let Some(value) = value {
192 conds.push(format!("{column} {op} ${}", bounds.len() + 1));
193 bounds.push(value);
194 }
195 };
196 bound("starts_at", ">", starts_after);
197 bound("starts_at", "<", starts_before);
198 bound("COALESCE(ends_at, starts_at)", ">", ends_after);
199 bound("COALESCE(ends_at, starts_at)", "<", ends_before);
200 let windowed = !conds.is_empty();
201 let from_where = if windowed {
202 format!("event WHERE {}", conds.join(" AND "))
203 } else {
204 "event".to_owned()
205 };
206 let order = if windowed {
207 "ORDER BY COALESCE(starts_at, ends_at) ASC, id ASC"
208 } else {
209 "ORDER BY id DESC"
210 };
211 let mut list = PagedList::new(from_where, order);
212 for value in bounds {
213 list = list.bind(value);
214 }
215 list.run::<Event>(limit, offset, db).await
216}
217
218/// Request-scoped: the handler reads the event, then awaits the clock and a
219/// course lookup before saving, holding no lock, so an omitted field
220/// (`None`) is not written at all. Passing the snapshot's value back
221/// instead would revert a concurrent edit of that field — scoping the `SET`
222/// alone does not prevent that, the values have to come from the request.
223/// The schedule columns are nullable, so they take the outer/inner
224/// `Option<Option<_>>`: `None` = omitted (keep), `Some(None)` = clear.
225///
226/// The audience is five columns moving as one unit: when the request
227/// carries an audience, all five are written (the non-matching payload as
228/// NULL); when it carries none, none are.
229pub async fn update(
230 db: &Database,
231 event: Event,
232 title: Option<EventTitle>,
233 description: Option<EventDescription>,
234 audience: Option<EventAudience>,
235 starts_at: Option<Option<Timestamp>>,
236 ends_at: Option<Option<Timestamp>>,
237) -> Result<Event, AppError> {
238 FieldUpdate::new("event", event.get_id().uuid())
239 .set(
240 "title",
241 title.map(|title| Param::Text(title.as_str().to_string())),
242 )
243 .set(
244 "description",
245 description.map(|d| Param::Text(d.as_str().to_string())),
246 )
247 .set(
248 "audience_kind",
249 audience
250 .as_ref()
251 .map(|a| Param::Text(a.kind.as_str().to_string())),
252 )
253 .set(
254 "audience_role",
255 audience
256 .as_ref()
257 .map(|a| Param::OptText(a.role.map(|r| r.as_str().to_string()))),
258 )
259 .set(
260 "audience_course",
261 audience
262 .as_ref()
263 .map(|a| Param::OptUuid(a.course.as_ref().map(|c| c.uuid()))),
264 )
265 .set(
266 "audience_class",
267 audience
268 .as_ref()
269 .map(|a| Param::OptUuid(a.class.as_ref().map(|c| c.uuid()))),
270 )
271 .set(
272 "audience_capacity",
273 audience.as_ref().map(|a| Param::OptI64(a.capacity)),
274 )
275 .set(
276 "starts_at",
277 starts_at.map(|at| Param::OptI64(at.map(|at| at.as_millis()))),
278 )
279 .set(
280 "ends_at",
281 ends_at.map(|at| Param::OptI64(at.map(|at| at.as_millis()))),
282 )
283 .ordered("starts_at", "ends_at", range_error())
284 .run::<Event>(db)
285 .await
286}
287
288/// Delete the event and cascade-remove its attendance and signup rows.
289///
290/// Children first, all of it in one guarded transaction: run as separate
291/// statements, a registration or a mark committing in between would outlive
292/// its event — an orphan no read path can ever reach and no delete can ever
293/// reclaim, since every one of them is keyed on the event that is now gone.
294///
295/// `cascade` retry: a mark landing while the cascade is in flight contends
296/// for the event row (its insert's foreign key proves the event the moment
297/// it lands), so a lost round re-sends instead of answering 500.
298pub async fn delete(db: &Database, event: Event) -> Result<Event, AppError> {
299 tx_with_retry(db, true, async move |tx| {
300 sqlx::query!("DELETE FROM attendance WHERE event = $1", event.get_id().uuid())
301 .execute(&mut *tx)
302 .await?;
303 sqlx::query!(
304 "DELETE FROM registration WHERE event = $1",
305 event.get_id().uuid()
306 )
307 .execute(&mut *tx)
308 .await?;
309 let gone = query_as!(
310 Event,
311 "DELETE FROM event WHERE id = $1 \
312 RETURNING id AS \"id: EventId\", creator AS \"creator: UserId\", title AS \"title: EventTitle\", description AS \"description: EventDescription\", \
313 audience_kind AS \"audience_kind: EventAudienceKind\", \
314 audience_role AS \"audience_role: Role\", \
315 audience_course AS \"audience_course: CourseId\", \
316 audience_class AS \"audience_class: ClassGroupId\", \
317 audience_capacity, starts_at AS \"starts_at: Timestamp\", \
318 ends_at AS \"ends_at: Timestamp\"",
319 event.get_id().uuid()
320 )
321 .fetch_optional(&mut *tx)
322 .await?;
323 gone.ok_or(AppError::NotFound)
324 })
325 .await
326}
327
328#[cfg(test)]
329mod tests {
330 use super::*;
331
332 /// A real `app_user` row: the creator is a foreign key now.
333 async fn a_person(db: &Database, label: &str) -> UserId {
334 let user = UserId::generate();
335 sqlx::query(
336 "INSERT INTO app_user (id, username, created_at, role) \
337 VALUES ($1, $2, 0, 'teacher')",
338 )
339 .bind(user.uuid())
340 .bind(format!("{label}-{}", &user.key()[30..]))
341 .execute(db)
342 .await
343 .unwrap();
344 user
345 }
346
347 /// The forcing function behind the one rule with two spellings: the freeze
348 /// this file decides in Rust ([`Event::registration_capacity`]) and the
349 /// demotion sweep's SQL predicate, which `service::user::set_role` carries
350 /// because it frees a demoted parent's seats inside a transaction and
351 /// cannot call Rust from there. The predicate is copied here test-side on
352 /// purpose: the sweep lives in user.rs, and this test pins the copy.
353 ///
354 /// Every schedule shape is put to both, including the three the SQL is most
355 /// likely to get wrong: the ends_at-only event (`COALESCE` must fall through to
356 /// it), the boundary itself (closed *at* the instant, not after it — `>=` in
357 /// Rust, `<=` in SQL, and the two read opposite ways round; `now` is bound
358 /// to that exact instant so the boundary is really exercised), and an event
359 /// that takes no registrations at all, which Rust refuses one arm *earlier*
360 /// — so the SQL must not report it frozen, or a stray row on it would be
361 /// preserved forever instead of swept.
362 #[tokio::test]
363 async fn the_sql_freeze_guard_matches_the_rust_one() {
364 let (db, _leases) = crate::database::init_test_db().await;
365 let creator = a_person(&db, "event-guard").await;
366 // `audience_class` is a foreign key too: the class case needs a real group.
367 let class = ClassGroupId::generate();
368 sqlx::query("INSERT INTO class_group (id, name, creator, grade_level) VALUES ($1, 'g1', $2, 9)")
369 .bind(class.uuid())
370 .bind(creator.uuid())
371 .execute(&db)
372 .await
373 .unwrap();
374 let no_payload = |kind| EventAudience {
375 kind,
376 role: None,
377 course: None,
378 class: None,
379 capacity: None,
380 };
381 let now = Timestamp::now().as_millis();
382 let past = Some(Timestamp::from_millis(now - 60_000));
383 let future = Some(Timestamp::from_millis(now + 3_600_000));
384 let later = Some(Timestamp::from_millis(now + 7_200_000));
385 let signup = no_payload(EventAudienceKind::Registration);
386 let cases = [
387 ("timeless", signup.clone(), None, None),
388 ("deadline ahead", signup.clone(), None, future),
389 ("deadline passed", signup.clone(), None, past),
390 ("starts later", signup.clone(), future, later),
391 ("already started", signup.clone(), past, None),
392 ("started, ends later", signup.clone(), past, future),
393 (
394 "closing this instant",
395 signup.clone(),
396 Some(Timestamp::from_millis(now)),
397 None,
398 ),
399 // No signup list to freeze: `registration_capacity` refuses these on
400 // the audience, before it ever looks at the clock.
401 (
402 "started school event",
403 no_payload(EventAudienceKind::School),
404 past,
405 None,
406 ),
407 (
408 "started class event",
409 EventAudience {
410 class: Some(class),
411 ..no_payload(EventAudienceKind::Class)
412 },
413 past,
414 None,
415 ),
416 ];
417 for (name, audience, starts_at, ends_at) in cases {
418 let event = create(
419 &db,
420 &creator,
421 EventTitle::try_new(name).unwrap(),
422 EventDescription::try_new("").unwrap(),
423 audience,
424 starts_at,
425 ends_at,
426 )
427 .await
428 .unwrap();
429 let rust = matches!(
430 event.registration_capacity(),
431 Err(AppError::Conflict(_) | AppError::ConflictOwned(_))
432 );
433 // Test-side copy of the sweep predicate in `service::user::set_role`
434 // (src/db/user.rs): true == frozen, i.e. the demotion sweep would
435 // leave the signup rows exactly as they stand.
436 let sql = sqlx::query_scalar::<_, bool>(
437 "SELECT audience_kind = 'registration' \
438 AND COALESCE(starts_at, ends_at) IS NOT NULL \
439 AND COALESCE(starts_at, ends_at) <= $2 \
440 FROM event WHERE id = $1",
441 )
442 .bind(event.get_id().uuid())
443 .bind(now)
444 .fetch_one(&db)
445 .await
446 .unwrap();
447 assert_eq!(
448 sql, rust,
449 "the SQL freeze guard and registration_capacity disagree on a \
450 {name} event — the role cascade would rewrite a closed signup \
451 list, or strand a seat on an open one"
452 );
453 }
454 }
455
456 /// Four schedule shapes; creation order is id order (uuidv7), so the
457 /// unfiltered read is exactly the reverse of the creation order.
458 async fn four_events(db: &Database) -> (UserId, [EventId; 4]) {
459 let creator = a_person(db, "event-window").await;
460 let school = EventAudience {
461 kind: EventAudienceKind::School,
462 role: None,
463 course: None,
464 class: None,
465 capacity: None,
466 };
467 let now = Timestamp::now().as_millis();
468 let past = Timestamp::from_millis(now - 60_000);
469 let soon = Timestamp::from_millis(now + 30 * 60_000);
470 let future = Timestamp::from_millis(now + 3_600_000);
471 let later = Timestamp::from_millis(now + 2 * 3_600_000);
472 let mut ids = Vec::new();
473 for (starts_at, ends_at) in [
474 (None, None), // timeless — never survives a window
475 (Some(past), None), // already started
476 (Some(soon), None), // ends-only deadline... starts soon
477 (Some(future), Some(later)), // fully scheduled ahead
478 ] {
479 ids.push(
480 create(
481 db,
482 &creator,
483 EventTitle::try_new("window").unwrap(),
484 EventDescription::try_new("").unwrap(),
485 school.clone(),
486 starts_at,
487 ends_at,
488 )
489 .await
490 .unwrap()
491 .get_id()
492 .clone(),
493 );
494 }
495 (creator, ids.try_into().unwrap())
496 }
497
498 #[tokio::test]
499 async fn absent_window_is_the_unfiltered_newest_first_read() {
500 let (db, _leases) = crate::database::init_test_db().await;
501 let (_, ids) = four_events(&db).await;
502 let (events, total) = list_windowed(&db, None, None, None, None, None, 0)
503 .await
504 .unwrap();
505 assert_eq!(total, 4);
506 let listed: Vec<_> = events.iter().map(|event| event.get_id()).cloned().collect();
507 let expected: Vec<_> = ids.iter().rev().cloned().collect();
508 assert_eq!(listed, expected);
509 }
510
511 #[tokio::test]
512 async fn the_window_filters_and_orders_in_sql_with_a_filtered_total() {
513 let (db, _leases) = crate::database::init_test_db().await;
514 let (_, ids) = four_events(&db).await;
515 let [_, started, soon, ahead] = &ids;
516 let now = Timestamp::now().as_millis();
517
518 // ends_after: the timeless and the already-started drop; the ends-only
519 // event survives on its `ends_at` COALESCE fallback.
520 let (events, total) = list_windowed(&db, None, Some(now), None, None, None, 0)
521 .await
522 .unwrap();
523 assert_eq!(total, 2);
524 let keys: Vec<_> = events.iter().map(|event| event.get_id()).cloned().collect();
525 assert_eq!(keys, vec![soon.clone(), ahead.clone()]);
526
527 // A limit applies after the filter: one row out, total still two.
528 let (events, total) = list_windowed(&db, None, Some(now), None, None, Some(1), 0)
529 .await
530 .unwrap();
531 assert_eq!((events.len(), total), (1, 2));
532 assert_eq!(events[0].get_id(), soon);
533 // Offset runs inside the filtered set, not past it.
534 let (events, total) = list_windowed(&db, None, Some(now), None, None, None, 1)
535 .await
536 .unwrap();
537 assert_eq!((events.len(), total), (1, 2));
538 assert_eq!(events[0].get_id(), ahead);
539
540 // starts_before drops the start-less rows and everything starting at
541 // or after the cut (strict): the cut sits between `soon` (+30 min)
542 // and `ahead` (+1 h), so `started` and `soon` survive, schedule
543 // ascending.
544 let (events, total) = list_windowed(
545 &db,
546 None,
547 None,
548 Some(now + 45 * 60_000),
549 None,
550 None,
551 0,
552 )
553 .await
554 .unwrap();
555 assert_eq!(total, 2);
556 let keys: Vec<_> = events.iter().map(|event| event.get_id()).cloned().collect();
557 assert_eq!(keys, vec![started.clone(), soon.clone()]);
558
559 // ends_before: only the already-started, on its starts_at fallback.
560 let (_, total) = list_windowed(&db, None, None, None, Some(now - 30_000), None, 0)
561 .await
562 .unwrap();
563 assert_eq!(total, 1);
564
565 // A well-formed instant naming no row is an empty page, not an error.
566 let (events, total) = list_windowed(&db, Some(now + 30 * 86_400_000), None, None, None, None, 0)
567 .await
568 .unwrap();
569 assert!((events.is_empty()) && total == 0);
570 }
571}