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

appointment.rs453 lines, 19.3 KiBHistoryRawDownload
1//! The `appointment` table: row reads and listings, the overlap probe behind
2//! the booking guard, the seat claim the booking writes through, and the
3//! compare-and-set every decision writes. The workflows live in
4//! [`crate::service::appointment`] (no lock anymore: occupancy is a
5//! conditional counter write, the decision CAS is one statement, and the
6//! approval's overlap decision is a serializable transaction documented at
7//! its own site).
8
9use crate::database::{Database, tx_with_retry};
10use crate::db::cap::Claimed;
11use crate::db::page::PagedList;
12use crate::domain::appointment::{
13 Appointment, AppointmentId, AppointmentReason, AppointmentStatus,
14};
15use crate::domain::appointment_slot::AppointmentSlotId;
16use crate::domain::timestamp::Timestamp;
17use crate::domain::user::UserId;
18use crate::error::AppError;
19use sqlx::{PgConnection, Postgres, query, query_as};
20
21/// Is `[starts_at, ends_at)` already taken for either party? Both sides are
22/// checked: a teacher can't be in two meetings at once, and neither can a
23/// requester (a parent with two children's teachers, say).
24///
25/// Only *approved* bookings block — a pending request is a wish, not a
26/// commitment, so several may queue on overlapping times and the first
27/// approval wins. `except` skips one row, so re-checking a booking against
28/// the world never trips over itself.
29///
30/// The effective window (the proposal when one stands, the slot's own
31/// otherwise) is computed in the query and compared in Rust: one round
32/// trip, and the comparison stays a plain, unit-tested predicate. A booking
33/// whose slot was withdrawn since (no window left to stand on) is skipped.
34pub async fn conflicts(
35 db: &Database,
36 teacher: &UserId,
37 requester: &UserId,
38 starts_at: Timestamp,
39 ends_at: Timestamp,
40 except: Option<&AppointmentId>,
41) -> Result<bool, AppError> {
42 conflicts_on(db, teacher, requester, starts_at, ends_at, except).await
43}
44
45/// [`conflicts`] against any executor — the approval decision re-asks this
46/// inside its own transaction, so the verdict it acts on is the one its
47/// snapshot holds.
48pub(crate) async fn conflicts_on<'e, E>(
49 executor: E,
50 teacher: &UserId,
51 requester: &UserId,
52 starts_at: Timestamp,
53 ends_at: Timestamp,
54 except: Option<&AppointmentId>,
55) -> Result<bool, AppError>
56where
57 E: sqlx::Executor<'e, Database = Postgres>,
58{
59 let windows = query!(
60 "SELECT COALESCE(a.proposed_starts_at, s.starts_at) AS starts_at, \
61 COALESCE(a.proposed_ends_at, s.ends_at) AS ends_at \
62 FROM appointment a JOIN appointment_slot s ON a.slot = s.id \
63 WHERE a.status = 'approved' \
64 AND ($3::uuid IS NULL OR a.id <> $3) \
65 AND (a.requester = $2 OR s.teacher = $1)",
66 teacher.uuid(),
67 requester.uuid(),
68 except.map(|id| id.uuid()),
69 )
70 .fetch_all(executor)
71 .await?;
72 Ok(windows
73 .into_iter()
74 .filter_map(|window| {
75 Some((
76 Timestamp::from_millis(window.starts_at?),
77 Timestamp::from_millis(window.ends_at?),
78 ))
79 })
80 .any(|(booked_starts_at, booked_ends_at)| {
81 Appointment::overlaps(starts_at, ends_at, booked_starts_at, booked_ends_at)
82 }))
83}
84
85pub(crate) async fn read_on<'e, E>(
86 executor: E,
87 id: &AppointmentId,
88) -> Result<Option<Appointment>, AppError>
89where
90 E: sqlx::Executor<'e, Database = Postgres>,
91{
92 let appointment = query_as!(
93 Appointment,
94 "SELECT id AS \"id: AppointmentId\", slot AS \"slot: AppointmentSlotId\", requester AS \"requester: UserId\", \
95 status AS \"status: AppointmentStatus\", reason AS \"reason: AppointmentReason\", \
96 proposed_starts_at AS \"proposed_starts_at: Timestamp\", \
97 proposed_ends_at AS \"proposed_ends_at: Timestamp\", \
98 proposed_by AS \"proposed_by: UserId\", decided_by AS \"decided_by: UserId\", \
99 cancelled_by AS \"cancelled_by: UserId\", \
100 cancel_reason AS \"cancel_reason: AppointmentReason\", \
101 reject_reason AS \"reject_reason: AppointmentReason\", \
102 created_at AS \"created_at: Timestamp\" \
103 FROM appointment WHERE id = $1",
104 id.uuid()
105 )
106 .fetch_optional(executor)
107 .await?;
108 Ok(appointment)
109}
110
111pub async fn read(db: &Database, id: &AppointmentId) -> Result<Option<Appointment>, AppError> {
112 read_on(db, id).await
113}
114
115/// The row, insisting it is still open for a decision.
116pub async fn read_pending(db: &Database, id: &AppointmentId) -> Result<Appointment, AppError> {
117 read_pending_on(db, id).await
118}
119
120/// [`read_pending`] against any executor (the approval's transaction).
121pub(crate) async fn read_pending_on<'e, E>(
122 executor: E,
123 id: &AppointmentId,
124) -> Result<Appointment, AppError>
125where
126 E: sqlx::Executor<'e, Database = Postgres>,
127{
128 let appointment = read_on(executor, id).await?.ok_or(AppError::NotFound)?;
129 if appointment.get_status() != AppointmentStatus::Pending {
130 return Err(AppError::Conflict("the appointment is no longer pending"));
131 }
132 Ok(appointment)
133}
134
135/// The optional filters and the page of [`list_for_requester`], in one
136/// struct — the fields outgrew a readable argument list. The default is
137/// the unfiltered, unpaged read.
138#[derive(Default)]
139pub struct RequesterListParams<'a> {
140 pub status: Option<AppointmentStatus>,
141 /// The meeting's effective start bounds, `[after, before)`.
142 pub starts_after: Option<Timestamp>,
143 pub starts_before: Option<Timestamp>,
144 /// The booked slot's teacher.
145 pub teacher: Option<&'a UserId>,
146 /// `None` = the full list.
147 pub limit: Option<i64>,
148 pub offset: i64,
149}
150
151/// The caller's own bookings, newest first. The optional filters narrow the
152/// read: `status` matches the stored state, `starts_after`/`starts_before`
153/// bound the meeting's effective start — a standing proposal, the slot's
154/// window otherwise — from below (inclusive) and above (exclusive, so a
155/// month is `[start, next_start)`), and `teacher` is the booked slot's
156/// teacher — which needs the slot row, so the read runs over a derived table
157/// the window and its count share. A booking whose slot is gone has no
158/// meeting time and no teacher, so any of those three filters drops it; with
159/// no filter the read stays the plain single-table one, so today's rows
160/// (dangling bookings included) are untouched.
161pub async fn list_for_requester(
162 db: &Database,
163 requester: &UserId,
164 params: RequesterListParams<'_>,
165) -> Result<(Vec<Appointment>, i64), AppError> {
166 let RequesterListParams {
167 status,
168 starts_after,
169 starts_before,
170 teacher,
171 limit,
172 offset,
173 } = params;
174 // Spell the appointment columns against the join alias, so the derived
175 // table's row keeps the exact names [`Appointment`] decodes and the
176 // slot's duplicate column names never leak in. The plain shape aliases
177 // the table too, so the one clause builder speaks both shapes.
178 const JOINED: &str = "(SELECT a.id, a.slot, a.requester, a.status, a.reason, \
179 a.proposed_starts_at, a.proposed_ends_at, a.proposed_by, a.decided_by, \
180 a.cancelled_by, a.cancel_reason, a.reject_reason, a.created_at \
181 FROM appointment a LEFT JOIN appointment_slot s ON a.slot = s.id \
182 WHERE a.requester = $1";
183 let joined = teacher.is_some() || starts_after.is_some() || starts_before.is_some();
184 let mut from_where = if joined {
185 JOINED.to_string()
186 } else {
187 "appointment a WHERE a.requester = $1".to_string()
188 };
189 // The meeting's start: a standing proposal overrides the slot's window
190 // (the same rule [`Appointment::window`] applies), so the predicate
191 // coalesces them — and these clauses only ever ride the joined shape,
192 // where the slot row is in hand.
193 let mut next = 2;
194 if status.is_some() {
195 from_where.push_str(&format!(" AND a.status = ${next}"));
196 next += 1;
197 }
198 if starts_after.is_some() {
199 from_where.push_str(&format!(
200 " AND COALESCE(a.proposed_starts_at, s.starts_at) >= ${next}"
201 ));
202 next += 1;
203 }
204 if starts_before.is_some() {
205 from_where.push_str(&format!(
206 " AND COALESCE(a.proposed_starts_at, s.starts_at) < ${next}"
207 ));
208 next += 1;
209 }
210 if teacher.is_some() {
211 from_where.push_str(&format!(" AND s.teacher = ${next}"));
212 }
213 // Close the derived table when the read is the joined shape; the plain
214 // single-table shape opened none.
215 if joined {
216 from_where.push(')');
217 }
218 let mut list = PagedList::new(from_where, "ORDER BY id DESC").bind(requester.uuid());
219 if let Some(status) = status {
220 list = list.bind(status.as_str().to_string());
221 }
222 if let Some(after) = starts_after {
223 list = list.bind(after.as_millis());
224 }
225 if let Some(before) = starts_before {
226 list = list.bind(before.as_millis());
227 }
228 if let Some(teacher) = teacher {
229 list = list.bind(teacher.uuid());
230 }
231 list.run(limit, offset, db).await
232}
233
234/// Every booking aimed at `teacher`, across all their slots — the
235/// teacher's request inbox. The teacher lives on the slot row now, so
236/// this is a join; the page and its count share the one predicate, and
237/// the columns are spelled out so the join's duplicate slot-column names
238/// can never leak into the row decode. `status` narrows to one booking
239/// state and `starts_after`/`starts_before` to meetings whose effective
240/// start (a standing proposal, the slot's window otherwise) sits in
241/// `[after, before)` — both bounds optional, both in the SQL, so the
242/// count always describes exactly the rows the window pages over.
243pub async fn list_for_teacher(
244 db: &Database,
245 teacher: &UserId,
246 status: Option<AppointmentStatus>,
247 starts_after: Option<Timestamp>,
248 starts_before: Option<Timestamp>,
249 limit: Option<i64>,
250 offset: i64,
251) -> Result<(Vec<Appointment>, i64), AppError> {
252 // The join wrapped as one derived table, so [`PagedList`]'s `SELECT *`
253 // still sees exactly the appointment columns.
254 let mut from_where = String::from(
255 "(SELECT a.id, a.slot, a.requester, a.status, a.reason, \
256 a.proposed_starts_at, a.proposed_ends_at, a.proposed_by, a.decided_by, \
257 a.cancelled_by, a.cancel_reason, a.reject_reason, a.created_at \
258 FROM appointment a JOIN appointment_slot s ON a.slot = s.id \
259 WHERE s.teacher = $1",
260 );
261 let mut next = 2;
262 if status.is_some() {
263 from_where.push_str(&format!(" AND a.status = ${next}"));
264 next += 1;
265 }
266 if starts_after.is_some() {
267 from_where.push_str(&format!(
268 " AND COALESCE(a.proposed_starts_at, s.starts_at) >= ${next}"
269 ));
270 next += 1;
271 }
272 if starts_before.is_some() {
273 from_where.push_str(&format!(
274 " AND COALESCE(a.proposed_starts_at, s.starts_at) < ${next}"
275 ));
276 }
277 // Close the derived table the clauses were appended into.
278 from_where.push(')');
279 let mut list = PagedList::new(from_where, "ORDER BY id DESC").bind(teacher.uuid());
280 if let Some(status) = status {
281 list = list.bind(status.as_str().to_string());
282 }
283 if let Some(after) = starts_after {
284 list = list.bind(after.as_millis());
285 }
286 if let Some(before) = starts_before {
287 list = list.bind(before.as_millis());
288 }
289 list.run(limit, offset, db).await
290}
291
292pub async fn list_for_slot(
293 db: &Database,
294 slot: &AppointmentSlotId,
295) -> Result<Vec<Appointment>, AppError> {
296 let rows = query_as!(
297 Appointment,
298 "SELECT id AS \"id: AppointmentId\", slot AS \"slot: AppointmentSlotId\", requester AS \"requester: UserId\", \
299 status AS \"status: AppointmentStatus\", reason AS \"reason: AppointmentReason\", \
300 proposed_starts_at AS \"proposed_starts_at: Timestamp\", \
301 proposed_ends_at AS \"proposed_ends_at: Timestamp\", \
302 proposed_by AS \"proposed_by: UserId\", decided_by AS \"decided_by: UserId\", \
303 cancelled_by AS \"cancelled_by: UserId\", \
304 cancel_reason AS \"cancel_reason: AppointmentReason\", \
305 reject_reason AS \"reject_reason: AppointmentReason\", \
306 created_at AS \"created_at: Timestamp\" \
307 FROM appointment WHERE slot = $1 ORDER BY id DESC",
308 slot.uuid()
309 )
310 .fetch_all(db)
311 .await?;
312 Ok(rows)
313}
314
315/// Request `slot`: take the slot's one seat and write the pending booking
316/// in a single statement — two racing requests cannot both find the slot
317/// free however they interleave, and a refused insert takes its own seat
318/// bump back with it. Zero rows means "full, or the slot was deleted since
319/// the caller read it": the marker is one, and the caller re-reads to pick
320/// the 404/409.
321pub(crate) async fn claim_slot_and_create(
322 db: &Database,
323 appointment: Appointment,
324) -> Result<Claimed<Appointment>, AppError> {
325 match query_as!(
326 Appointment,
327 "WITH seat AS (
328 UPDATE appointment_slot SET occupied = occupied + 1
329 WHERE id = $1 AND occupied < 1
330 RETURNING 1)
331 INSERT INTO appointment (id, slot, requester, status, reason, proposed_starts_at, \
332 proposed_ends_at, proposed_by, decided_by, cancelled_by, \
333 cancel_reason, reject_reason, created_at)
334 SELECT $2, $1, $3, 'pending', $4, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $5
335 WHERE EXISTS (SELECT 1 FROM seat)
336 RETURNING id AS \"id: AppointmentId\", slot AS \"slot: AppointmentSlotId\", requester AS \"requester: UserId\", \
337 status AS \"status: AppointmentStatus\", reason AS \"reason: AppointmentReason\", \
338 proposed_starts_at AS \"proposed_starts_at: Timestamp\", \
339 proposed_ends_at AS \"proposed_ends_at: Timestamp\", \
340 proposed_by AS \"proposed_by: UserId\", decided_by AS \"decided_by: UserId\", \
341 cancelled_by AS \"cancelled_by: UserId\", \
342 cancel_reason AS \"cancel_reason: AppointmentReason\", \
343 reject_reason AS \"reject_reason: AppointmentReason\", \
344 created_at AS \"created_at: Timestamp\"",
345 appointment
346 .get_slot()
347 .map(|s| s.uuid())
348 .expect("a new booking always carries its slot"),
349 appointment.get_id().uuid(),
350 appointment.get_requester().uuid(),
351 appointment.get_reason().as_str(),
352 appointment.get_created_at().as_millis(),
353 )
354 .fetch_optional(db)
355 .await
356 {
357 Ok(Some(row)) => Ok(Claimed::Made(row)),
358 Ok(None) => Ok(Claimed::Full),
359 // The id is freshly minted on a table keyed by it; no rival can
360 // have aimed at it, and the seat gate excludes any slot the insert
361 // could dangle from — no other verdict exists on this path.
362 Err(err) => Err(err.into()),
363 }
364}
365
366/// Write the decision only while the stored row still carries the state it
367/// was validated against. `None` means it does not: another decision landed
368/// between the read and the write, so reload, re-validate, and try again.
369///
370/// Four columns discriminate every write, and `status` alone would not:
371/// `propose` leaves a pending booking pending, so an approval built from a
372/// snapshot taken *before* that proposal would sail through a status-only
373/// guard and confirm the meeting at the old, superseded time. With the
374/// proposed window and `decided_by` alongside it, every mutator moves at
375/// least one of the four. The fields only a terminal transition writes
376/// (`cancelled_by`, `cancel_reason`, `reject_reason`) need no compare of
377/// their own: they always travel with a `status` change into a state no
378/// later decision is allowed from. Absent values compare truthfully under
379/// `IS NOT DISTINCT FROM`.
380///
381/// A transition out of a live status (reject, cancel) hands the slot's
382/// `occupied` seat back in the same transaction — the counter is the
383/// authority on whether the slot is taken, so it must move if and only if
384/// the status did. The decrement is gated on the CAS having written
385/// something, so a lost race frees nothing.
386pub async fn save_if_unchanged(
387 db: &Database,
388 expected: &Appointment,
389 new: Appointment,
390) -> Result<Option<Appointment>, AppError> {
391 // Owned capture (`Send` rule of `tx_with_retry` closures).
392 let expected = expected.clone();
393 tx_with_retry(db, false, async move |tx| {
394 decision_cas(&mut *tx, &expected, new.clone()).await
395 })
396 .await
397}
398
399/// The decision's compare-and-set against any executor: one conditional
400/// `UPDATE`, plus the seat release when the status left the live set. A
401/// single statement decides under Postgres's row locking, so no retry
402/// budget and no store-level "write conflict" class exists anymore — a miss
403/// is simply `None`, the reload-and-re-decide answer.
404pub(crate) async fn decision_cas(
405 tx: &mut PgConnection,
406 expected: &Appointment,
407 new: Appointment,
408) -> Result<Option<Appointment>, AppError> {
409 let frees_the_slot = expected.get_status().is_live() && !new.get_status().is_live();
410 let done = query_as!(
411 Appointment,
412 "UPDATE appointment SET status = $2, proposed_starts_at = $3, proposed_ends_at = $4, \
413 proposed_by = $5, decided_by = $6, cancelled_by = $7, cancel_reason = $8, \
414 reject_reason = $9 \
415 WHERE id = $1 AND status = $10 \
416 AND proposed_starts_at IS NOT DISTINCT FROM $11 \
417 AND proposed_ends_at IS NOT DISTINCT FROM $12 \
418 AND decided_by IS NOT DISTINCT FROM $13 \
419 RETURNING id AS \"id: AppointmentId\", slot AS \"slot: AppointmentSlotId\", requester AS \"requester: UserId\", \
420 status AS \"status: AppointmentStatus\", reason AS \"reason: AppointmentReason\", \
421 proposed_starts_at AS \"proposed_starts_at: Timestamp\", \
422 proposed_ends_at AS \"proposed_ends_at: Timestamp\", \
423 proposed_by AS \"proposed_by: UserId\", decided_by AS \"decided_by: UserId\", \
424 cancelled_by AS \"cancelled_by: UserId\", \
425 cancel_reason AS \"cancel_reason: AppointmentReason\", \
426 reject_reason AS \"reject_reason: AppointmentReason\", \
427 created_at AS \"created_at: Timestamp\"",
428 new.get_id().uuid(),
429 new.get_status().as_str(),
430 new.get_proposed_starts_at().map(|t| t.as_millis()),
431 new.get_proposed_ends_at().map(|t| t.as_millis()),
432 new.get_proposed_by().map(|u| u.uuid()),
433 new.get_decided_by().map(|u| u.uuid()),
434 new.get_cancelled_by().map(|u| u.uuid()),
435 new.get_cancel_reason().map(|r| r.as_str().to_string()),
436 new.get_reject_reason().map(|r| r.as_str().to_string()),
437 expected.get_status().as_str(),
438 expected.get_proposed_starts_at().map(|t| t.as_millis()),
439 expected.get_proposed_ends_at().map(|t| t.as_millis()),
440 expected.get_decided_by().map(|u| u.uuid()),
441 )
442 .fetch_optional(&mut *tx)
443 .await?;
444 if frees_the_slot && done.is_some() {
445 sqlx::query!(
446 "UPDATE appointment_slot SET occupied = GREATEST(occupied - 1, 0) WHERE id = $1",
447 expected.get_slot().map(|s| s.uuid()),
448 )
449 .execute(tx)
450 .await?;
451 }
452 Ok(done)
453}