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

attendance.rs292 lines, 11.4 KiBHistoryRawDownload
1//! The `attendance` table: event roll call. Every write is one guarded
2//! statement whose gates ride inside it, so the whole module is the
3//! persistence half; the workflow that decides it lives in
4//! [`crate::service::attendance`].
5
6use crate::database::{Database, tx_with_retry};
7use crate::db::page::PagedList;
8use crate::domain::attendance::{Attendance, AttendanceStatus};
9use crate::domain::event::EventId;
10use crate::domain::timestamp::Timestamp;
11use crate::domain::user::UserId;
12use crate::error::AppError;
13use sqlx::query_as;
14
15/// Record (or overwrite) `user`'s status for `event`. The pair is the
16/// table's primary key, so this is a single atomic upsert — concurrent
17/// marks for the same pair converge on the one row instead of racing.
18///
19/// The event's existence is proved by the foreign key itself: a mark naming
20/// an event whose row is gone is refused `23503`, mapped to the same 404 the
21/// old existence-proof transaction produced. No bump-and-restore trick, no
22/// retry loop — one statement decides.
23pub async fn mark(
24 db: &Database,
25 event: &EventId,
26 user: &UserId,
27 status: AttendanceStatus,
28 marked_by: &UserId,
29) -> Result<Attendance, AppError> {
30 // Owned captures (`Send` rule of `tx_with_retry`'s closure).
31 let event = event.clone();
32 let user = *user;
33 let marked_by = *marked_by;
34 tx_with_retry(db, false, async move |tx| {
35 // The existence gate and the collision key: the event row is locked
36 // inside the mark's own transaction, so a concurrent delete cascade
37 // either lands whole before the mark (404, nothing stored) or queues
38 // behind the mark's commit — and then its sweep, reading after that
39 // commit, takes the mark's row with it. Without the lock the insert
40 // never queued on the event at all: a mark racing
41 // `DELETE /events/{id}` could commit an orphan its cascade's
42 // already-run sweep never saw.
43 let live = sqlx::query!(
44 r#"SELECT 1 AS "one!: i64" FROM event WHERE id = $1 FOR NO KEY UPDATE"#,
45 event.uuid()
46 )
47 .fetch_optional(&mut *tx)
48 .await?;
49 if live.is_none() {
50 // The event row is gone: exactly today's "no such event" refusal.
51 // (The foreign keys name users the routes already authenticated;
52 // a violation there stays a database error, as before.)
53 return Err(AppError::NotFound);
54 }
55 let row = query_as!(
56 Attendance,
57 "INSERT INTO attendance (event, app_user, status, marked_by, marked_at)
58 VALUES ($1, $2, $3, $4, $5)
59 ON CONFLICT (event, app_user) DO UPDATE SET status = $3, marked_by = $4, marked_at = $5
60 RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", \
61 status AS \"status: AttendanceStatus\", marked_by AS \"marked_by: UserId\"",
62 event.uuid(),
63 user.uuid(),
64 status.as_str(),
65 marked_by.uuid(),
66 Timestamp::now().as_millis(),
67 )
68 .fetch_one(&mut *tx)
69 .await?;
70 Ok(row)
71 })
72 .await
73}
74
75pub async fn list_for_event(
76 db: &Database,
77 event: &EventId,
78 limit: Option<i64>,
79 offset: i64,
80) -> Result<(Vec<Attendance>, i64), AppError> {
81 // The composite key's text form ordered the old listing; on the natural
82 // key that order is (event, then user).
83 PagedList::new(
84 "attendance WHERE event = $1",
85 "ORDER BY event DESC, app_user DESC",
86 )
87 .bind(event.uuid())
88 .run(limit, offset, db)
89 .await
90}
91
92/// Every event-attendance row recorded for `user` — the events half of the
93/// attendance report.
94pub async fn list_for_user(db: &Database, user: &UserId) -> Result<Vec<Attendance>, AppError> {
95 let rows = query_as!(
96 Attendance,
97 "SELECT event AS \"event: EventId\", app_user AS \"user: UserId\", \
98 status AS \"status: AttendanceStatus\", \
99 marked_by AS \"marked_by: UserId\" \
100 FROM attendance
101 WHERE app_user = $1
102 ORDER BY event DESC, app_user DESC",
103 user.uuid()
104 )
105 .fetch_all(db)
106 .await?;
107 Ok(rows)
108}
109
110pub async fn remove(
111 db: &Database,
112 event: &EventId,
113 user: &UserId,
114) -> Result<Option<Attendance>, AppError> {
115 let gone = query_as!(
116 Attendance,
117 "DELETE FROM attendance WHERE event = $1 AND app_user = $2
118 RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", \
119 status AS \"status: AttendanceStatus\", \
120 marked_by AS \"marked_by: UserId\"",
121 event.uuid(),
122 user.uuid()
123 )
124 .fetch_optional(db)
125 .await?;
126 Ok(gone)
127}
128
129#[cfg(test)]
130mod tests {
131 use super::*;
132 use crate::domain::settings::Settings;
133
134 /// The session twin's race, one table over
135 /// ([`crate::db::session_attendance::mark`]): the event's delete sweeps its
136 /// attendance rows and removes the row in one transaction, and a mark that
137 /// wrote into the gap was a bare upsert nothing would ever sweep again.
138 /// The mark now writes the event row too (its seats counter), so the two
139 /// transactions touch one row and Postgres refuses one of them.
140 ///
141 /// Both orders are forced by awaiting one side to completion before the
142 /// other starts. A barrier is a coin toss under load, and a run where the
143 /// delete loses every overlapped round has still proved the invariant.
144 /// Mutation-tested: turning the claim back into a read turns the
145 /// write-first round red.
146 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
147 async fn a_mark_written_inside_a_delete_never_outlives_the_event() {
148 use crate::domain::event::{
149 EventAudience, EventAudienceKind, EventDescription, EventTitle,
150 };
151
152 // A real `app_user` row: markers, students and event creators are
153 // foreign keys now.
154 async fn a_person(db: &Database, label: &str) -> UserId {
155 let user = UserId::generate();
156 sqlx::query(
157 "INSERT INTO app_user (id, username, created_at, role) \
158 VALUES ($1, $2, 0, 'teacher')",
159 )
160 .bind(user.uuid())
161 .bind(format!("{label}-{}", &user.key()[30..]))
162 .execute(db)
163 .await
164 .unwrap();
165 user
166 }
167
168 async fn an_event(db: &Database, marker: &UserId) -> crate::domain::event::Event {
169 crate::db::event::create(
170 db,
171 marker,
172 EventTitle::try_new("gezi").unwrap(),
173 EventDescription::try_new("").unwrap(),
174 EventAudience {
175 kind: EventAudienceKind::School,
176 role: None,
177 course: None,
178 class: None,
179 capacity: None,
180 },
181 None,
182 None,
183 )
184 .await
185 .unwrap()
186 }
187
188 let (db, _leases) = crate::database::init_test_db().await;
189 let allowed: Vec<String> = Settings::defaults().get_attendance_statuses().to_vec();
190 let marker = a_person(&db, "marker").await;
191
192 // Delete-first: the event is gone before the mark starts.
193 {
194 let event = an_event(&db, &marker).await;
195 let id = event.get_id().clone();
196 let dropped = crate::db::event::delete(&db, event).await;
197 assert!(
198 !matches!(dropped, Err(AppError::Db(_))),
199 "delete-first: a delete must be answered, not 500: {dropped:?}"
200 );
201 assert!(
202 crate::db::event::read(&db, &id).await.unwrap().is_none(),
203 "delete-first: the event is still there after delete: {dropped:?}"
204 );
205 let student = a_person(&db, "df").await;
206 let status = AttendanceStatus::try_new("present", &allowed).unwrap();
207 let marked = mark(&db, &id, &student, status, &marker).await;
208 assert!(
209 !matches!(marked, Err(AppError::Db(_))),
210 "delete-first: a mark must be answered, not 500: {marked:?}"
211 );
212 assert_eq!(
213 list_for_event(&db, &id, None, 0).await.unwrap().0.len(),
214 0,
215 "a mark outlived its event"
216 );
217 }
218
219 // Write-first: the mark lands, then the delete sweeps it.
220 {
221 let event = an_event(&db, &marker).await;
222 let id = event.get_id().clone();
223 let student = a_person(&db, "wf").await;
224 let status = AttendanceStatus::try_new("present", &allowed).unwrap();
225 let marked = mark(&db, &id, &student, status, &marker).await;
226 assert!(
227 marked.is_ok(),
228 "write-first: the mark must land before the delete: {marked:?}"
229 );
230 let dropped = crate::db::event::delete(&db, event).await;
231 assert!(
232 !matches!(dropped, Err(AppError::Db(_))),
233 "write-first: a delete must be answered, not 500: {dropped:?}"
234 );
235 assert!(
236 crate::db::event::read(&db, &id).await.unwrap().is_none(),
237 "write-first: the event is still there"
238 );
239 assert_eq!(
240 list_for_event(&db, &id, None, 0).await.unwrap().0.len(),
241 0,
242 "a mark outlived its event"
243 );
244 }
245
246 // Overlapped rounds. Delete may lose every one of them.
247 let mut swept = 0;
248 for round in 0..4 {
249 let event = an_event(&db, &marker).await;
250 let id = event.get_id().clone();
251
252 let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
253 let drop_it = {
254 let (db, gate, event) = (db.clone(), gate.clone(), event);
255 tokio::spawn(async move {
256 gate.wait().await;
257 crate::db::event::delete(&db, event).await
258 })
259 };
260 let marked = {
261 let (db, id, marker, gate, allowed) = (db.clone(), id.clone(), marker, gate, allowed.clone());
262 let student = a_person(&db, "student").await;
263 let status = AttendanceStatus::try_new("present", &allowed).unwrap();
264 tokio::spawn(async move {
265 gate.wait().await;
266 mark(&db, &id, &student, status, &marker).await
267 })
268 };
269 let (drop_it, marked) = (drop_it.await.unwrap(), marked.await.unwrap());
270 assert!(
271 !matches!(marked, Err(AppError::Db(_))),
272 "round {round}: a raced mark must be answered, not 500: {marked:?}"
273 );
274 assert!(
275 !matches!(drop_it, Err(AppError::Db(_))),
276 "round {round}: a raced delete must be answered, not 500: {drop_it:?}"
277 );
278
279 if crate::db::event::read(&db, &id).await.unwrap().is_none() {
280 swept += 1;
281 assert_eq!(
282 list_for_event(&db, &id, None, 0).await.unwrap().0.len(),
283 0,
284 "round {round}: a mark outlived its event"
285 );
286 } else if drop_it.is_ok() {
287 panic!("round {round}: the delete reported success but the event is still there");
288 }
289 }
290 eprintln!("Event::delete raced by a mark: {swept}/4 concurrent rounds deleted the event");
291 }
292}