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

registration.rs140 lines, 5.2 KiBHistoryRawDownload
1//! The `registration` table: the seat reads, the per-event listing, and
2//! the delete that returns the seat in the same transaction. The register
3//! workflow itself (the cap claim and its conflict mapping) lives in
4//! [`crate::service::registration`].
5
6use crate::database::{Database, tx_with_retry, unique_violation};
7use crate::db::cap::Claimed;
8use crate::domain::event::EventId;
9use crate::domain::registration::Registration;
10use crate::domain::timestamp::Timestamp;
11use crate::domain::user::UserId;
12use crate::error::AppError;
13use sqlx::query_as;
14
15/// Some(_) iff `user` holds a seat on `event` — the audience point check.
16pub async fn read_for_user(
17 db: &Database,
18 event: &EventId,
19 user: &UserId,
20) -> Result<Option<Registration>, AppError> {
21 let seat = query_as!(
22 Registration,
23 "SELECT event AS \"event: EventId\", app_user AS \"user: UserId\", \
24 registered_by AS \"registered_by: UserId\" \
25 FROM registration
26 WHERE event = $1 AND app_user = $2
27 LIMIT 1",
28 event.uuid(),
29 user.uuid()
30 )
31 .fetch_optional(db)
32 .await?;
33 Ok(seat)
34}
35
36pub async fn list_for_event(db: &Database, event: &EventId) -> Result<Vec<Registration>, AppError> {
37 let seats = query_as!(
38 Registration,
39 "SELECT event AS \"event: EventId\", app_user AS \"user: UserId\", \
40 registered_by AS \"registered_by: UserId\" \
41 FROM registration
42 WHERE event = $1
43 ORDER BY event DESC, app_user DESC",
44 event.uuid()
45 )
46 .fetch_all(db)
47 .await?;
48 Ok(seats)
49}
50
51/// Take a seat for `user` on `event` — the cap claim of one: the seat bump,
52/// the holder's role handshake, and the row insert are a single statement,
53/// so neither a racing placement nor a concurrent capacity lowering can
54/// over-admit (the capacity is read off the event row as it is decided, not
55/// off a snapshot), and a demotion to `parent` cannot strand a seat the
56/// sweep would miss: the handshake takes the holder's row
57/// `FOR NO KEY UPDATE`, the same key the demotion writes, so either this
58/// sees the parent and inserts nothing, or the sweep sees this row.
59///
60/// The verdict maps exactly like the old guard layer's: `Made` — seated;
61/// `Duplicate` — a rival placement of the same pair won (23505 on
62/// `registration_event_user`); `Full` — the event is at its capacity, was
63/// deleted, or the holder fell to `parent` (all one marker; the caller
64/// re-reads to pick the message).
65pub(crate) async fn claim_seat(
66 db: &Database,
67 event: &EventId,
68 user: &UserId,
69 registered_by: &UserId,
70) -> Result<Claimed<Registration>, AppError> {
71 let created_at = Timestamp::now().as_millis();
72 match query_as!(
73 Registration,
74 "WITH person AS (
75 -- The lock handshake comes FIRST: FOR NO KEY UPDATE waits out a
76 -- racing demotion and re-checks the role against the committed
77 -- row. A data-modifying CTE executes even when the INSERT below
78 -- matches nothing, so the bump must depend on this CTE's result —
79 -- the EXISTS reference in `seat` forces that order.
80 SELECT 1 FROM app_user WHERE id = $2 AND role IS DISTINCT FROM 'parent'
81 FOR NO KEY UPDATE),
82 seat AS (
83 UPDATE event SET registration_count = registration_count + 1
84 WHERE id = $1
85 AND (audience_capacity IS NULL OR registration_count < audience_capacity)
86 AND EXISTS (SELECT 1 FROM person)
87 RETURNING 1)
88 INSERT INTO registration (event, app_user, registered_by, created_at)
89 SELECT $1, $2, $3, $4
90 WHERE EXISTS (SELECT 1 FROM seat)
91 RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", registered_by AS \"registered_by: UserId\"",
92 event.uuid(),
93 user.uuid(),
94 registered_by.uuid(),
95 created_at,
96 )
97 .fetch_optional(db)
98 .await
99 {
100 Ok(Some(row)) => Ok(Claimed::Made(row)),
101 Ok(None) => Ok(Claimed::Full),
102 Err(err) if unique_violation(&err) == Some("registration_event_user") => {
103 Ok(Claimed::Duplicate)
104 }
105 Err(err) => Err(err.into()),
106 }
107}
108
109pub async fn remove(
110 db: &Database,
111 event: &EventId,
112 user: &UserId,
113) -> Result<Option<Registration>, AppError> {
114 // The seat comes back in the same transaction as the row that held it.
115 // Owned captures (`Send` rule of `tx_with_retry` closures).
116 let event = event.clone();
117 let user = *user;
118 tx_with_retry(db, false, async move |tx| {
119 let gone = query_as!(
120 Registration,
121 "DELETE FROM registration WHERE event = $1 AND app_user = $2
122 RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", registered_by AS \"registered_by: UserId\"",
123 event.uuid(),
124 user.uuid()
125 )
126 .fetch_optional(&mut *tx)
127 .await?;
128 if gone.is_some() {
129 sqlx::query!(
130 "UPDATE event SET registration_count = GREATEST(registration_count - 1, 0)
131 WHERE id = $1",
132 event.uuid()
133 )
134 .execute(&mut *tx)
135 .await?;
136 }
137 Ok(gone)
138 })
139 .await
140}