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.rs1150 lines, 45.3 KiBHistoryRawDownload
1//! Appointment workflows: booking, the approve/reject/cancel decisions, and
2//! counter-proposals. Reads, listings, the overlap probe, the seat claim,
3//! and the compare-and-set live in [`crate::db::appointment`].
4//!
5//! There is no lock anymore. What the old APPOINTMENT_LOCK serialized is
6//! now three database guarantees:
7//!
8//! - **Occupancy** — booking claims the slot's seat and writes the row in
9//! one statement ([`crate::db::appointment::claim_slot_and_create`]); two
10//! racers cannot both find the slot free.
11//! - **Publish overlap** — the `appointment_slot_teacher_span` exclusion
12//! constraint refuses two overlapping published windows at the store.
13//! - **Double-booking** — the approval's "is anyone already committed at
14//! that time" is a predicate over *other* rows, which no single-record
15//! write can decide and no row lock can stand in for (the rows that would
16//! collide may not exist yet). That one decision runs **serializable** —
17//! the lane's single documented isolation escalation: two concurrent
18//! approvals of overlapping proposals read the same approved set, and SSI
19//! aborts the loser (`40001`), which [`tx_with_retry`] re-sends; the
20//! re-run sees the winner committed and refuses with the ordinary 409.
21
22use crate::constant::CAS_UPDATE_RETRIES;
23use crate::database::{Database, tx_with_retry};
24use crate::db::appointment;
25use crate::db::appointment_slot;
26use crate::db::cap::Claimed;
27use crate::domain::appointment::{
28 Appointment, AppointmentId, AppointmentReason, AppointmentStatus,
29};
30use crate::domain::appointment_slot::AppointmentSlotId;
31use crate::domain::timestamp::Timestamp;
32use crate::domain::user::UserId;
33use crate::error::{AppError, ValidationError};
34
35pub use crate::db::appointment::RequesterListParams;
36
37/// Request `slot`. Lands `pending`: publishing availability is not consent
38/// to a specific person and topic.
39///
40/// Refused (409) when the slot's window has already opened, when it is
41/// already taken, or when the requester is already committed elsewhere at
42/// that time. The slot is taken by the seat claim — a conditional
43/// single-record write the database decides — so two racing requests
44/// cannot both find it free however they interleave, and a crash between
45/// the two can no longer leave the slot occupied by a booking that does
46/// not exist. The requester's own overlap check is advisory here, exactly
47/// as under the lock: only *approved* bookings block, so two pending
48/// requests may queue on overlapping times, and the approval is where the
49/// authoritative refusal lands.
50pub async fn book(
51 db: &Database,
52 slot: &AppointmentSlotId,
53 requester: &UserId,
54 reason: AppointmentReason,
55) -> Result<Appointment, AppError> {
56 let slot_row = appointment_slot::read(db, slot)
57 .await?
58 .ok_or(AppError::NotFound)?;
59 // A window that has opened is history, not a plan: `cancel` refuses to
60 // call off a meeting that started, so such a booking would be stuck
61 // forever. `list_upcoming` is bounded on this same `starts_at`, so the
62 // calendar never offers one — but a slot whose start passed while the
63 // page was open, or an id kept from an earlier read, still reaches here.
64 // The publish-time 60s skew grace does not apply on either side.
65 if slot_row.get_starts_at().as_millis() <= Timestamp::now().as_millis() {
66 return Err(AppError::Conflict("the slot has already started"));
67 }
68 // The teacher's own overlaps are not checked here — an approved
69 // meeting of theirs elsewhere is the *approval*'s business, and
70 // refusing the request outright would hide a slot they published.
71 if appointment::conflicts(
72 db,
73 requester,
74 requester,
75 slot_row.get_starts_at(),
76 slot_row.get_ends_at(),
77 None,
78 )
79 .await?
80 {
81 return Err(AppError::Conflict(
82 "you already have an appointment at that time",
83 ));
84 }
85 // Last, so nothing above can refuse *after* the slot was taken. A slot
86 // deleted since the read above is gone, not full — the claim's `WHERE`
87 // finds no row either way, so the distinction is re-read rather than
88 // guessed.
89 let appointment_row = Appointment {
90 id: AppointmentId::generate(),
91 slot: Some(slot.clone()),
92 requester: *requester,
93 status: AppointmentStatus::Pending,
94 reason,
95 proposed_starts_at: None,
96 proposed_ends_at: None,
97 proposed_by: None,
98 decided_by: None,
99 cancelled_by: None,
100 cancel_reason: None,
101 reject_reason: None,
102 created_at: Timestamp::now(),
103 };
104 match appointment::claim_slot_and_create(db, appointment_row).await? {
105 Claimed::Made(created) => Ok(created),
106 Claimed::Full => {
107 if appointment_slot::read(db, slot).await?.is_none() {
108 return Err(AppError::NotFound);
109 }
110 Err(AppError::Conflict("the slot is already booked"))
111 }
112 // The id is freshly minted on a table keyed by it: no rival can
113 // have aimed at it.
114 Claimed::Duplicate => Err(AppError::Internal("appointment id collided".into())),
115 }
116}
117
118/// The row, for callers that only inspect it — the web layer's authorization
119/// gates read through here.
120pub async fn read(db: &Database, id: &AppointmentId) -> Result<Option<Appointment>, AppError> {
121 appointment::read(db, id).await
122}
123
124/// The requester's bookings, newest first — the web layer's paging read,
125/// narrowed by the door's optional `status`, `starts_after`/`starts_before`
126/// (the meeting's effective start, `[after, before)`) and `teacher` (the
127/// booked slot's teacher) filters.
128pub async fn list_for_requester(
129 db: &Database,
130 requester: &UserId,
131 params: RequesterListParams<'_>,
132) -> Result<(Vec<Appointment>, i64), AppError> {
133 appointment::list_for_requester(db, requester, params).await
134}
135
136/// Every booking aimed at `teacher`, newest first — the request inbox,
137/// narrowed by the door's optional `status` and `starts_after`/`starts_before`
138/// filters. The inbox is the teacher's own universe already, so it takes no
139/// teacher filter: narrowing is the web layer's call.
140pub async fn list_for_teacher(
141 db: &Database,
142 teacher: &UserId,
143 status: Option<AppointmentStatus>,
144 starts_after: Option<Timestamp>,
145 starts_before: Option<Timestamp>,
146 limit: Option<i64>,
147 offset: i64,
148) -> Result<(Vec<Appointment>, i64), AppError> {
149 appointment::list_for_teacher(db, teacher, status, starts_after, starts_before, limit, offset)
150 .await
151}
152
153/// Confirm the meeting at the slot's own window. Re-runs the double-booking
154/// guard for both teacher and requester *inside the decision transaction* —
155/// the authoritative check, since only approval commits anyone. Refused
156/// (409) when the effective window has already started; that also covers
157/// [`accept_proposal`], which lands here.
158///
159/// Also refused (409) while a counter-proposal stands: the effective window
160/// would then be the *proposed* one, and the deciding side here is the
161/// teacher's, so approving would commit the requester to a time only the
162/// teacher ever named. That move belongs to [`accept_proposal`], which the
163/// web layer opens to the requester alone.
164pub async fn approve(
165 db: &Database,
166 id: &AppointmentId,
167 decided_by: &UserId,
168) -> Result<Appointment, AppError> {
169 approve_inner(db, id, decided_by, None).await
170}
171
172/// The one approval path. `accepting` carries the window the caller is
173/// answering *for*, which is the only way a proposed one may be committed:
174/// it both marks the caller as the proposal's counterparty and pins which
175/// proposal they saw.
176///
177/// Read, gate, overlap probe and write are ONE serializable transaction:
178/// the overlap probe is a predicate over other approved rows, the one
179/// invariant in this lane no row lock can carry (see the module doc). The
180/// proposal pin is re-checked inside that same snapshot, so a proposal that
181/// moved between the requester's read and their accept is refused rather
182/// than committed.
183async fn approve_inner(
184 db: &Database,
185 id: &AppointmentId,
186 decided_by: &UserId,
187 accepting: Option<(Timestamp, Timestamp)>,
188) -> Result<Appointment, AppError> {
189 // Owned captures (`Send` rule of `tx_with_retry` closures).
190 let id = id.clone();
191 let decided_by = *decided_by;
192 tx_with_retry(db, false, async move |tx| {
193 // Serializable for the overlap decision below (module doc). `SET
194 // TRANSACTION` is legal only before the first query, so it goes
195 // first; a `40001` from SSI is re-sent by the retry loop, and the
196 // re-run re-reads everything against the committed winner.
197 sqlx::query!("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")
198 .execute(&mut *tx)
199 .await?;
200 let expected = appointment::read_pending_on(&mut *tx, &id).await?;
201 match accepting {
202 None if expected.has_proposal() => {
203 return Err(AppError::Conflict(
204 "a counter-proposal is standing; only the requester can accept it",
205 ));
206 }
207 Some(_) if !expected.has_proposal() => {
208 return Err(AppError::Conflict("no time has been proposed"));
209 }
210 // The proposal moved between the requester reading it and
211 // accepting it. Committing here would bind them to a window the
212 // teacher swapped in after they clicked, which is the whole
213 // thing the requester-only accept exists to prevent.
214 Some(accepted) if !expected.proposes(accepted) => {
215 return Err(AppError::Conflict(
216 "the proposed time has changed; re-read the booking and accept the new one",
217 ));
218 }
219 _ => {}
220 }
221 let slot_id = expected.get_slot().ok_or(AppError::NotFound)?.clone();
222 let slot = appointment_slot::read_on(&mut *tx, &slot_id)
223 .await?
224 .ok_or(AppError::NotFound)?;
225 let (starts_at, ends_at) = expected.window(&slot);
226 // The effective window — the proposal's when one stands — must still
227 // be ahead. Mutual agreement does not help: `cancel` refuses a
228 // meeting that started, so committing to a passed window would mint
229 // a booking nobody can ever undo. Refused, the row stays `pending`
230 // and the teacher can propose a time that can actually happen.
231 if starts_at.as_millis() <= Timestamp::now().as_millis() {
232 return Err(AppError::Conflict("that time has already started"));
233 }
234 if appointment::conflicts_on(
235 &mut *tx,
236 slot.get_teacher(),
237 expected.get_requester(),
238 starts_at,
239 ends_at,
240 Some(&id),
241 )
242 .await?
243 {
244 return Err(AppError::Conflict(
245 "that time collides with another approved appointment",
246 ));
247 }
248 let mut approved = expected.clone();
249 approved.status = AppointmentStatus::Approved;
250 approved.decided_by = Some(decided_by);
251 match appointment::decision_cas(&mut *tx, &expected, approved).await? {
252 Some(saved) => Ok(saved),
253 // Unreachable under the row lock this transaction holds — kept
254 // for the shape's honesty: a miss means re-decide, and the
255 // caller's answer to that is this 409.
256 None => Err(contended()),
257 }
258 })
259 .await
260}
261
262/// Turn the request down. Frees the slot — the seat goes back with the
263/// status flip, in one transaction. No lock needed and none taken: this
264/// decides nothing about anyone's calendar, and the write is its own guard.
265pub async fn reject(
266 db: &Database,
267 id: &AppointmentId,
268 decided_by: &UserId,
269 reason: Option<AppointmentReason>,
270) -> Result<Appointment, AppError> {
271 for _ in 0..CAS_UPDATE_RETRIES {
272 let expected = appointment::read_pending(db, id).await?;
273 let mut rejected = expected.clone();
274 rejected.status = AppointmentStatus::Rejected;
275 rejected.decided_by = Some(*decided_by);
276 rejected.reject_reason = reason.clone();
277 if let Some(saved) = appointment::save_if_unchanged(db, &expected, rejected).await? {
278 return Ok(saved);
279 }
280 }
281 Err(contended())
282}
283
284/// Call the meeting off. Legal from either live state, so an approved
285/// meeting can still be dropped; the slot frees up. The web layer opens
286/// this to the **requester only** — a teacher's way out is `reject` while
287/// the booking is pending, or `reschedule` (back to `pending`) then
288/// `reject` for an approved one — and `decline_reschedule`, the other
289/// caller, is the requester's too.
290///
291/// Refused (409) once the *effective* window has opened — a meeting that
292/// began is history, not a plan. The guard lives here rather than in the
293/// handler so every caller inherits it: `decline_reschedule` cancels
294/// through this same door and used to slip past a handler-only check.
295pub async fn cancel(
296 db: &Database,
297 id: &AppointmentId,
298 cancelled_by: &UserId,
299 reason: Option<AppointmentReason>,
300) -> Result<Appointment, AppError> {
301 for _ in 0..CAS_UPDATE_RETRIES {
302 let expected = appointment::read(db, id).await?.ok_or(AppError::NotFound)?;
303 if !expected.get_status().is_live() {
304 return Err(AppError::Conflict("the appointment is already settled"));
305 }
306 let slot = appointment_slot::read(db, expected.get_slot().ok_or(AppError::NotFound)?)
307 .await?
308 .ok_or(AppError::NotFound)?;
309 if expected.window(&slot).0.as_millis() <= Timestamp::now().as_millis() {
310 return Err(AppError::Conflict("the appointment has already started"));
311 }
312 let mut cancelled = expected.clone();
313 cancelled.status = AppointmentStatus::Cancelled;
314 cancelled.cancelled_by = Some(*cancelled_by);
315 cancelled.cancel_reason = reason.clone();
316 if let Some(saved) = appointment::save_if_unchanged(db, &expected, cancelled).await? {
317 return Ok(saved);
318 }
319 }
320 Err(contended())
321}
322
323/// Counter-propose another time on the same booking (no second row, so the
324/// reason and the history stay in one place).
325///
326/// The proposal sends the booking back to `pending`: a previously approved
327/// meeting is *not* committed at the new time until the other side accepts,
328/// and leaving it approved would silently move a confirmed appointment.
329///
330/// Refused (409) when the proposed window has already opened. The handler's
331/// `check_not_past` carries a 60s clock-skew grace, which is enough to
332/// propose a window that is already underway; `cancel` would then refuse to
333/// undo the booking, so it must not be offered in the first place.
334pub async fn propose(
335 db: &Database,
336 id: &AppointmentId,
337 starts_at: Timestamp,
338 ends_at: Timestamp,
339 proposed_by: &UserId,
340) -> Result<Appointment, AppError> {
341 if starts_at.as_millis() >= ends_at.as_millis() {
342 return Err(ValidationError::Invalid {
343 field: "proposed_ends_at",
344 reason: "must be after proposed_starts_at",
345 }
346 .into());
347 }
348 // No lock: a proposal commits nobody's calendar (the booking goes back
349 // to `pending`), and it neither takes nor frees the slot's seat.
350 for _ in 0..CAS_UPDATE_RETRIES {
351 let expected = appointment::read(db, id).await?.ok_or(AppError::NotFound)?;
352 if !expected.get_status().is_live() {
353 return Err(AppError::Conflict("the appointment is already settled"));
354 }
355 if starts_at.as_millis() <= Timestamp::now().as_millis() {
356 return Err(AppError::Conflict("that time has already started"));
357 }
358 let mut proposed = expected.clone();
359 proposed.status = AppointmentStatus::Pending;
360 proposed.decided_by = None;
361 proposed.proposed_starts_at = Some(starts_at);
362 proposed.proposed_ends_at = Some(ends_at);
363 proposed.proposed_by = Some(*proposed_by);
364 if let Some(saved) = appointment::save_if_unchanged(db, &expected, proposed).await? {
365 return Ok(saved);
366 }
367 }
368 Err(contended())
369}
370
371/// Accept the standing proposal — approval at the proposed time. The
372/// overlap guard runs again because the time moved.
373///
374/// `starts_at`/`ends_at` are the proposal the caller is answering, as they
375/// read it. They are not a request to move the meeting: they *pin* the one
376/// being accepted, and a proposal that has since been superseded is refused
377/// (409) rather than committed. `propose` takes no lock and the two calls
378/// are minutes apart, so nothing but this pin can tell "the requester
379/// agreed to 10:00" from "the requester's click landed on 23:00".
380pub async fn accept_proposal(
381 db: &Database,
382 id: &AppointmentId,
383 decided_by: &UserId,
384 starts_at: Timestamp,
385 ends_at: Timestamp,
386) -> Result<Appointment, AppError> {
387 // The same approval path re-reads inside its serializable transaction
388 // and reads the proposed window off the row, so accepting is approval —
389 // no second code path. Only this door passes `accepting`, and the web
390 // layer opens it to the requester alone.
391 approve_inner(db, id, decided_by, Some((starts_at, ends_at))).await
392}
393
394/// Every retry lost the row to another decision. A 409 rather than a 500: the
395/// caller's request was refused, nothing was half-applied, and re-reading the
396/// booking shows what happened to it.
397fn contended() -> AppError {
398 AppError::Conflict("the appointment is being decided elsewhere")
399}
400#[cfg(test)]
401mod tests {
402 use super::*;
403 use crate::database::{Database, init_test_db};
404 use crate::service::appointment_slot;
405
406 fn at(millis: i64) -> Timestamp {
407 Timestamp::from_millis(millis)
408 }
409
410 /// A real `app_user` row: teachers and students are foreign keys now. The
411 /// label names the row's username; the id is minted, so repeated calls are
412 /// new people, not the same row.
413 async fn a_person(db: &Database, label: &str, role: &str) -> UserId {
414 let user = UserId::generate();
415 sqlx::query(
416 "INSERT INTO app_user (id, username, created_at, role) \
417 VALUES ($1, $2, 0, $3)",
418 )
419 .bind(user.uuid())
420 .bind(format!("{label}-{}", &user.key()[30..]))
421 .bind(role)
422 .execute(db)
423 .await
424 .unwrap();
425 user
426 }
427
428 /// A window that has not opened yet — `book` refuses started ones.
429 fn soon(offset: i64) -> Timestamp {
430 at(Timestamp::now().as_millis() + offset)
431 }
432
433 #[tokio::test]
434 async fn window_prefers_a_proposal_over_the_slot() {
435 let (db, _leases) = init_test_db().await;
436 let teacher = a_person(&db, "t1", "teacher").await;
437 let (starts_at, ends_at) = (soon(60_000), soon(120_000));
438 let slot = appointment_slot::create(&db, &teacher, starts_at, ends_at, None)
439 .await
440 .unwrap();
441 let mut appointment_row = book(
442 &db,
443 slot.get_id(),
444 &a_person(&db, "s1", "student").await,
445 AppointmentReason::try_new("ödev").unwrap(),
446 )
447 .await
448 .unwrap();
449
450 assert_eq!(appointment_row.window(&slot), (starts_at, ends_at));
451 appointment_row.proposed_starts_at = Some(at(5_000));
452 appointment_row.proposed_ends_at = Some(at(6_000));
453 assert_eq!(appointment_row.window(&slot), (at(5_000), at(6_000)));
454 }
455
456 /// A slot whose window already opened is unbookable: `cancel` would refuse
457 /// to undo the resulting meeting, so the booking would be stuck for good.
458 #[tokio::test]
459 async fn a_started_slot_cannot_be_booked() {
460 let (db, _leases) = init_test_db().await;
461 let teacher = a_person(&db, "t1", "teacher").await;
462 let reason = || AppointmentReason::try_new("görüşme").unwrap();
463 let started = appointment_slot::create(&db, &teacher, soon(-30_000), soon(60_000), None)
464 .await
465 .unwrap();
466 assert!(matches!(
467 book(
468 &db,
469 started.get_id(),
470 &a_person(&db, "s1", "student").await,
471 reason()
472 )
473 .await,
474 Err(AppError::Conflict("the slot has already started"))
475 ));
476
477 let upcoming = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
478 .await
479 .unwrap();
480 assert!(
481 book(
482 &db,
483 upcoming.get_id(),
484 &a_person(&db, "s1", "student").await,
485 reason()
486 )
487 .await
488 .is_ok()
489 );
490 }
491
492 /// Approval judges the *effective* window, so a proposal whose time has
493 /// come and gone cannot be accepted — the meeting would be uncancellable.
494 #[tokio::test]
495 async fn a_started_proposal_cannot_be_accepted() {
496 let (db, _leases) = init_test_db().await;
497 let teacher = a_person(&db, "t1", "teacher").await;
498 let student = a_person(&db, "s1", "student").await;
499 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
500 .await
501 .unwrap();
502 let booking = book(
503 &db,
504 slot.get_id(),
505 &student,
506 AppointmentReason::try_new("görüşme").unwrap(),
507 )
508 .await
509 .unwrap();
510
511 // Proposing a window that already opened is refused up front — the
512 // handler's 60s skew grace would otherwise let one through.
513 assert!(matches!(
514 propose(&db, booking.get_id(), soon(-30_000), soon(30_000), &teacher).await,
515 Err(AppError::Conflict("that time has already started"))
516 ));
517 // And approval judges the effective window again, for a proposal whose
518 // time simply passed while it stood: forced onto the row directly,
519 // since `propose` no longer mints one.
520 let current = appointment::read(&db, booking.get_id())
521 .await
522 .unwrap()
523 .unwrap();
524 let (passed_starts_at, passed_ends_at) = (soon(-30_000), soon(30_000));
525 let mut standing = current.clone();
526 standing.proposed_starts_at = Some(passed_starts_at);
527 standing.proposed_ends_at = Some(passed_ends_at);
528 appointment::save_if_unchanged(&db, &current, standing)
529 .await
530 .unwrap()
531 .unwrap();
532 assert!(matches!(
533 accept_proposal(
534 &db,
535 booking.get_id(),
536 &student,
537 passed_starts_at,
538 passed_ends_at
539 )
540 .await,
541 Err(AppError::Conflict("that time has already started"))
542 ));
543 // Refused, not half-applied: still pending, still decidable at a time
544 // that can actually happen.
545 let after = appointment::read(&db, booking.get_id()).await.unwrap();
546 assert_eq!(after.unwrap().get_status(), AppointmentStatus::Pending);
547 let (starts_at, ends_at) = (soon(60_000), soon(120_000));
548 propose(&db, booking.get_id(), starts_at, ends_at, &teacher)
549 .await
550 .unwrap();
551 // Accepting a window that is *not* the standing proposal is refused —
552 // the pin is what the requester saw, not a request to move the meeting.
553 assert!(matches!(
554 accept_proposal(
555 &db,
556 booking.get_id(),
557 &student,
558 passed_starts_at,
559 passed_ends_at
560 )
561 .await,
562 Err(AppError::Conflict(
563 "the proposed time has changed; \
564 re-read the booking and accept the new one"
565 ))
566 ));
567 let accepted = accept_proposal(&db, booking.get_id(), &student, starts_at, ends_at)
568 .await
569 .unwrap();
570 assert_eq!(accepted.get_status(), AppointmentStatus::Approved);
571 }
572
573 /// The compare-and-set every decision writes through — the guard against a
574 /// decision built on a snapshot that has since moved, which no lock taken
575 /// after the read can catch. The interleaving that matters is the one a
576 /// status-only guard would miss, since `propose` leaves a pending booking
577 /// pending.
578 ///
579 /// Deliberately sequential: the mem engine answers `Ok` to a write it then
580 /// drops, so a `join!` of two decisions proves nothing. This drives the
581 /// primitive itself with the exact stale snapshot the race produces.
582 #[tokio::test]
583 async fn a_decision_built_on_a_stale_snapshot_never_lands() {
584 let (db, _leases) = init_test_db().await;
585 let teacher = a_person(&db, "t1", "teacher").await;
586 let student = a_person(&db, "s1", "student").await;
587 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
588 .await
589 .unwrap();
590 let booking = book(
591 &db,
592 slot.get_id(),
593 &student,
594 AppointmentReason::try_new("görüşme").unwrap(),
595 )
596 .await
597 .unwrap();
598
599 // One transaction counter-proposes. A second concurrent transaction
600 // is still holding the snapshot it read before that — same id, same
601 // `pending` status.
602 let stale = booking.clone();
603 let (proposed_starts_at, proposed_ends_at) = (soon(180_000), soon(240_000));
604 propose(
605 &db,
606 booking.get_id(),
607 proposed_starts_at,
608 proposed_ends_at,
609 &teacher,
610 )
611 .await
612 .unwrap();
613
614 let mut late = stale.clone();
615 late.status = AppointmentStatus::Approved;
616 late.decided_by = Some(teacher);
617 assert!(
618 appointment::save_if_unchanged(&db, &stale, late)
619 .await
620 .unwrap()
621 .is_none()
622 );
623
624 // The proposal survived: the row was not confirmed at the slot's old
625 // window behind the requester's back.
626 let after = appointment::read(&db, booking.get_id())
627 .await
628 .unwrap()
629 .unwrap();
630 assert_eq!(after.get_status(), AppointmentStatus::Pending);
631 assert_eq!(after.get_proposed_starts_at(), Some(proposed_starts_at));
632 assert_eq!(after.get_proposed_ends_at(), Some(proposed_ends_at));
633 assert_eq!(after.get_decided_by(), None);
634
635 // And the same decision, re-validated against the row as it now
636 // stands, does land — a miss is a retry signal, not a wall.
637 let mut fresh = after.clone();
638 fresh.status = AppointmentStatus::Approved;
639 fresh.decided_by = Some(teacher);
640 let saved = appointment::save_if_unchanged(&db, &after, fresh)
641 .await
642 .unwrap()
643 .expect("a current snapshot must write");
644 assert_eq!(saved.get_status(), AppointmentStatus::Approved);
645 assert_eq!(saved.get_proposed_starts_at(), Some(proposed_starts_at));
646 }
647
648 /// What the slot row itself says about being taken — the authority every
649 /// gate now reads.
650 async fn occupied(slot: &AppointmentSlotId, db: &Database) -> i64 {
651 sqlx::query_scalar::<_, i64>("SELECT occupied FROM appointment_slot WHERE id = $1")
652 .bind(slot.uuid())
653 .fetch_one(db)
654 .await
655 .unwrap()
656 }
657
658 /// The seat claim `book` rides, asked directly: the conditional
659 /// `UPDATE … WHERE occupied < $cap` on the slot row is the whole
660 /// primitive, so this asks it the exact question the race asks.
661 async fn claim_seat(slot: &AppointmentSlotId, cap: i64, db: &Database) -> bool {
662 sqlx::query_scalar::<_, i32>(
663 "UPDATE appointment_slot SET occupied = occupied + 1 \
664 WHERE id = $1 AND occupied < $2 RETURNING 1",
665 )
666 .bind(slot.uuid())
667 .bind(cap)
668 .fetch_optional(db)
669 .await
670 .unwrap()
671 .is_some()
672 }
673
674 /// The double-book race with the lock taken out of the picture: a second
675 /// booking arrives at the database with nothing between it and the slot but
676 /// the claim's own `WHERE`, which is what must refuse it. Driven
677 /// through [`cap::claim`] directly rather than through a `join!`, since the
678 /// in-memory engine can drop one of two concurrent writes to a record and
679 /// still answer `Ok` — this asks the primitive the exact question the race
680 /// asks it.
681 ///
682 /// Deleting the `WHERE (occupied ?? 0) < $cap` from `cap::claim` makes the
683 /// second claim succeed and this fail (mutation-proved).
684 #[tokio::test]
685 async fn a_concurrent_claim_cannot_take_a_booked_slot() {
686 let (db, _leases) = init_test_db().await;
687 let teacher = a_person(&db, "t1", "teacher").await;
688 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
689 .await
690 .unwrap();
691 assert_eq!(occupied(slot.get_id(), &db).await, 0);
692
693 book(
694 &db,
695 slot.get_id(),
696 &a_person(&db, "s1", "student").await,
697 AppointmentReason::try_new("görüşme").unwrap(),
698 )
699 .await
700 .unwrap();
701 assert_eq!(occupied(slot.get_id(), &db).await, 1);
702
703 assert!(
704 !claim_seat(slot.get_id(), 1, &db).await,
705 "the slot's seat must already be taken"
706 );
707 // And the racer's refusal left the stored state alone: one booking, one
708 // seat — not two of either.
709 assert_eq!(occupied(slot.get_id(), &db).await, 1);
710 assert_eq!(
711 appointment::list_for_slot(&db, slot.get_id())
712 .await
713 .unwrap()
714 .len(),
715 1
716 );
717 }
718
719 /// The seat and the booking row now land in one transaction, so the stored
720 /// state must move together: a taken slot refuses the next requester with
721 /// the counter *and* the row list untouched — a refusal that had already
722 /// bumped the counter would strand the slot forever.
723 #[tokio::test]
724 async fn a_refused_booking_moves_nothing() {
725 let (db, _leases) = init_test_db().await;
726 let teacher = a_person(&db, "t1", "teacher").await;
727 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
728 .await
729 .unwrap();
730 let reason = || AppointmentReason::try_new("görüşme").unwrap();
731
732 book(
733 &db,
734 slot.get_id(),
735 &a_person(&db, "s1", "student").await,
736 reason(),
737 )
738 .await
739 .unwrap();
740 assert_eq!(occupied(slot.get_id(), &db).await, 1);
741
742 let refused = book(
743 &db,
744 slot.get_id(),
745 &a_person(&db, "s2", "student").await,
746 reason(),
747 )
748 .await;
749 assert!(
750 matches!(refused, Err(AppError::Conflict(_))),
751 "the slot is taken"
752 );
753 assert_eq!(
754 occupied(slot.get_id(), &db).await,
755 1,
756 "the refusal took no seat"
757 );
758 assert_eq!(
759 appointment::list_for_slot(&db, slot.get_id())
760 .await
761 .unwrap()
762 .len(),
763 1,
764 "and wrote no row"
765 );
766 }
767
768 /// Cancelling gives the seat back in the same transaction as the status
769 /// flip — the counter is the only thing that says a slot is free, so a
770 /// cancel that moved one without the other would strand the slot forever.
771 #[tokio::test]
772 async fn cancelling_hands_the_seat_back_with_the_status() {
773 let (db, _leases) = init_test_db().await;
774 let teacher = a_person(&db, "t1", "teacher").await;
775 let student = a_person(&db, "s1", "student").await;
776 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
777 .await
778 .unwrap();
779 let booking = book(
780 &db,
781 slot.get_id(),
782 &student,
783 AppointmentReason::try_new("görüşme").unwrap(),
784 )
785 .await
786 .unwrap();
787 approve(&db, booking.get_id(), &teacher).await.unwrap();
788 assert_eq!(occupied(slot.get_id(), &db).await, 1, "approval holds it");
789
790 cancel(&db, booking.get_id(), &student, None).await.unwrap();
791 assert_eq!(occupied(slot.get_id(), &db).await, 0);
792 // Cancelling twice is refused, so the seat cannot go back twice either.
793 assert!(cancel(&db, booking.get_id(), &student, None).await.is_err());
794 assert_eq!(occupied(slot.get_id(), &db).await, 0);
795 assert!(
796 book(
797 &db,
798 slot.get_id(),
799 &a_person(&db, "s2", "student").await,
800 AppointmentReason::try_new("görüşme").unwrap()
801 )
802 .await
803 .is_ok()
804 );
805 assert_eq!(occupied(slot.get_id(), &db).await, 1);
806 }
807
808 /// Occupancy frees on reject, so the slot can be re-booked.
809 #[tokio::test]
810 async fn rejecting_frees_the_slot_for_re_booking() {
811 let (db, _leases) = init_test_db().await;
812 let teacher = a_person(&db, "t1", "teacher").await;
813 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
814 .await
815 .unwrap();
816 let reason = || AppointmentReason::try_new("görüşme").unwrap();
817
818 let first = book(
819 &db,
820 slot.get_id(),
821 &a_person(&db, "s1", "student").await,
822 reason(),
823 )
824 .await
825 .unwrap();
826 assert!(matches!(
827 book(
828 &db,
829 slot.get_id(),
830 &a_person(&db, "s2", "student").await,
831 reason()
832 )
833 .await,
834 Err(AppError::Conflict(_))
835 ));
836 // The live booking also blocks the slot delete.
837 assert!(matches!(
838 appointment_slot::delete(&db, slot.clone()).await,
839 Err(AppError::Conflict(_))
840 ));
841
842 reject(&db, first.get_id(), &teacher, None).await.unwrap();
843 assert_eq!(occupied(slot.get_id(), &db).await, 0);
844 let second = book(
845 &db,
846 slot.get_id(),
847 &a_person(&db, "s2", "student").await,
848 reason(),
849 )
850 .await
851 .unwrap();
852 assert_eq!(second.get_status(), AppointmentStatus::Pending);
853 assert_eq!(occupied(slot.get_id(), &db).await, 1);
854 }
855
856 /// The listing filters narrow each side's own universe: `status` to one
857 /// state, `starts_after` to meetings whose effective start (a standing
858 /// proposal, the slot's window otherwise) is at or after the instant,
859 /// `teacher` to the booked slot's teacher — and the paging window applies
860 /// after all of it, with `total` counting the filtered set, not the page.
861 /// Absent filters, the listings answer exactly as before, dangling rows
862 /// included.
863 #[tokio::test]
864 async fn listings_filter_by_status_start_and_teacher() {
865 let (db, _leases) = init_test_db().await;
866 let ali = a_person(&db, "ali", "teacher").await;
867 let ayse = a_person(&db, "ayse", "teacher").await;
868 let veli = a_person(&db, "veli", "student").await;
869 let reason = AppointmentReason::try_new("görüşme").unwrap();
870 let now = Timestamp::now().as_millis();
871 let at = |millis: i64| Timestamp::from_millis(millis);
872
873 let ali_slot =
874 appointment_slot::create(&db, &ali, at(now + 60_000), at(now + 120_000), None)
875 .await
876 .unwrap();
877 let ayse_slot =
878 appointment_slot::create(&db, &ayse, at(now + 200_000), at(now + 260_000), None)
879 .await
880 .unwrap();
881 let pending = book(&db, ali_slot.get_id(), &veli, reason.clone())
882 .await
883 .unwrap();
884 let approved = book(&db, ayse_slot.get_id(), &veli, reason.clone())
885 .await
886 .unwrap();
887 approve(&db, approved.get_id(), &ayse).await.unwrap();
888 let settled_slot =
889 appointment_slot::create(&db, &ali, at(now + 300_000), at(now + 360_000), None)
890 .await
891 .unwrap();
892 let cancelled = book(&db, settled_slot.get_id(), &veli, reason.clone())
893 .await
894 .unwrap();
895 cancel(&db, cancelled.get_id(), &veli, None).await.unwrap();
896
897 // Absent: all three, newest first — the shape today's callers see.
898 let (rows, total) =
899 list_for_requester(&db, &veli, RequesterListParams::default()).await.unwrap();
900 assert_eq!((rows.len(), total), (3, 3));
901
902 // status: only the approved one, and total is the filtered count.
903 let (rows, total) = list_for_requester(
904 &db,
905 &veli,
906 RequesterListParams {
907 status: Some(AppointmentStatus::Approved),
908 ..Default::default()
909 },
910 )
911 .await
912 .unwrap();
913 assert_eq!((rows.len(), total), (1, 1));
914 assert_eq!(rows[0].get_id(), approved.get_id());
915
916 // No state matches: an empty page, not an error.
917 let (rows, total) = list_for_requester(
918 &db,
919 &veli,
920 RequesterListParams {
921 status: Some(AppointmentStatus::Rejected),
922 ..Default::default()
923 },
924 )
925 .await
926 .unwrap();
927 assert_eq!((rows.len(), total), (0, 0));
928
929 // teacher joins through the slot: only the bookings on ali's slots.
930 let (rows, total) = list_for_requester(
931 &db,
932 &veli,
933 RequesterListParams {
934 teacher: Some(&ali),
935 ..Default::default()
936 },
937 )
938 .await
939 .unwrap();
940 assert_eq!((rows.len(), total), (2, 2));
941 assert!(rows.iter().all(|row| row.get_id() != approved.get_id()));
942
943 // starts_after judges the effective start: the pending meeting (at
944 // now + 60_000) is out; the approved and cancelled ones stay.
945 let (rows, total) = list_for_requester(
946 &db,
947 &veli,
948 RequesterListParams {
949 starts_after: Some(at(now + 150_000)),
950 ..Default::default()
951 },
952 )
953 .await
954 .unwrap();
955 assert_eq!((rows.len(), total), (2, 2));
956 assert!(rows.iter().all(|row| row.get_id() != pending.get_id()));
957
958 // The window applies after the filter; total stays the filtered count.
959 let (page1, total) = list_for_requester(
960 &db,
961 &veli,
962 RequesterListParams {
963 limit: Some(1),
964 ..Default::default()
965 },
966 )
967 .await
968 .unwrap();
969 assert_eq!((page1.len(), total), (1, 3));
970 let (page2, total) = list_for_requester(
971 &db,
972 &veli,
973 RequesterListParams {
974 limit: Some(1),
975 offset: 1,
976 ..Default::default()
977 },
978 )
979 .await
980 .unwrap();
981 assert_eq!((page2.len(), total), (1, 3));
982 assert_ne!(page1[0].get_id(), page2[0].get_id());
983
984 // A standing proposal moves the meeting's start for the cut: the
985 // pending booking proposes itself to now + 500_000, so it alone
986 // clears a cut at now + 400_000.
987 propose(&db, pending.get_id(), at(now + 500_000), at(now + 560_000), &ali)
988 .await
989 .unwrap();
990 let (rows, total) = list_for_requester(
991 &db,
992 &veli,
993 RequesterListParams {
994 starts_after: Some(at(now + 400_000)),
995 ..Default::default()
996 },
997 )
998 .await
999 .unwrap();
1000 assert_eq!((rows.len(), total), (1, 1));
1001 assert_eq!(rows[0].get_id(), pending.get_id());
1002
1003 // The inbox: ali's two bookings and never ayse's — the join's
1004 // teacher predicate is the whole visibility universe here.
1005 let (rows, total) =
1006 list_for_teacher(&db, &ali, None, None, None, None, 0).await.unwrap();
1007 assert_eq!((rows.len(), total), (2, 2));
1008 let (rows, total) = list_for_teacher(&db, &ali, Some(AppointmentStatus::Cancelled), None, None, None,
1009 0,
1010 )
1011 .await
1012 .unwrap();
1013 assert_eq!((rows.len(), total), (1, 1));
1014 assert_eq!(rows[0].get_id(), cancelled.get_id());
1015 let (_, total) =
1016 list_for_teacher(&db, &ali, None, Some(at(now + 400_000)), None, None, 0)
1017 .await
1018 .unwrap();
1019 assert_eq!(total, 1);
1020 let (rows, total) =
1021 list_for_teacher(&db, &ali, None, None, None, Some(1), 0).await.unwrap();
1022 assert_eq!((rows.len(), total), (1, 2));
1023
1024 // A settled booking whose slot is withdrawn still lists unfiltered —
1025 // today's shape — and the time and teacher filters drop it: it has
1026 // neither a meeting window nor a teacher any more. The guarded
1027 // delete sweeps its settled bookings along, so the dangling shape is
1028 // forced here the way a demotion sweep leaves it: the slot row goes,
1029 // and the slot's `ON DELETE SET NULL` strands the booking.
1030 sqlx::query("DELETE FROM appointment_slot WHERE id = $1")
1031 .bind(settled_slot.get_id().uuid())
1032 .execute(&db)
1033 .await
1034 .unwrap();
1035 let (rows, total) =
1036 list_for_requester(&db, &veli, RequesterListParams::default()).await.unwrap();
1037 assert_eq!((rows.len(), total), (3, 3), "the windowless row still lists");
1038 let (rows, total) = list_for_requester(
1039 &db,
1040 &veli,
1041 RequesterListParams {
1042 starts_after: Some(at(now)),
1043 ..Default::default()
1044 },
1045 )
1046 .await
1047 .unwrap();
1048 assert_eq!((rows.len(), total), (2, 2), "the windowless row has no start to match");
1049 assert!(rows.iter().all(|row| row.get_id() != cancelled.get_id()));
1050 let (rows, total) = list_for_requester(
1051 &db,
1052 &veli,
1053 RequesterListParams {
1054 teacher: Some(&ali),
1055 ..Default::default()
1056 },
1057 )
1058 .await
1059 .unwrap();
1060 assert_eq!((rows.len(), total), (1, 1), "a windowless row names no teacher");
1061 assert_eq!(rows[0].get_id(), pending.get_id());
1062 }
1063
1064 /// `starts_before` is the upper edge of a half-open month window: a row
1065 /// starting before the bound is out, a row inside it stays, the bound
1066 /// instant itself is excluded, and absent the set is unchanged.
1067 #[tokio::test]
1068 async fn starts_before_bounds_the_meeting_exclusively() {
1069 let (db, _leases) = init_test_db().await;
1070 let teacher = a_person(&db, "t1", "teacher").await;
1071 let veli = a_person(&db, "veli", "student").await;
1072 let reason = AppointmentReason::try_new("görüşme").unwrap();
1073 let now = Timestamp::now().as_millis();
1074 let at = |millis: i64| Timestamp::from_millis(millis);
1075
1076 // Two bookings: one before the bound, one after it.
1077 let early_slot =
1078 appointment_slot::create(&db, &teacher, at(now + 60_000), at(now + 120_000), None)
1079 .await
1080 .unwrap();
1081 let late_slot =
1082 appointment_slot::create(&db, &teacher, at(now + 200_000), at(now + 260_000), None)
1083 .await
1084 .unwrap();
1085 let early = book(&db, early_slot.get_id(), &veli, reason.clone())
1086 .await
1087 .unwrap();
1088 let late = book(&db, late_slot.get_id(), &veli, reason.clone())
1089 .await
1090 .unwrap();
1091
1092 // Absent: both — the set is unchanged without the bound.
1093 let (rows, total) =
1094 list_for_requester(&db, &veli, RequesterListParams::default()).await.unwrap();
1095 assert_eq!((rows.len(), total), (2, 2));
1096
1097 // before: only the early booking survives.
1098 let (rows, total) = list_for_requester(
1099 &db,
1100 &veli,
1101 RequesterListParams {
1102 starts_before: Some(at(now + 150_000)),
1103 ..Default::default()
1104 },
1105 )
1106 .await
1107 .unwrap();
1108 assert_eq!((rows.len(), total), (1, 1));
1109 assert_eq!(rows[0].get_id(), early.get_id());
1110
1111 // Half-open: the bound instant itself is outside the window, so a
1112 // cut exactly at the late meeting's start keeps only the early one —
1113 // and the inbox answers the same way.
1114 let (rows, total) = list_for_requester(
1115 &db,
1116 &veli,
1117 RequesterListParams {
1118 starts_before: Some(at(now + 200_000)),
1119 ..Default::default()
1120 },
1121 )
1122 .await
1123 .unwrap();
1124 assert_eq!((rows.len(), total), (1, 1));
1125 assert_eq!(rows[0].get_id(), early.get_id());
1126
1127 let (rows, total) =
1128 list_for_teacher(&db, &teacher, None, None, Some(at(now + 150_000)), None, 0)
1129 .await
1130 .unwrap();
1131 assert_eq!((rows.len(), total), (1, 1));
1132 assert_eq!(rows[0].get_id(), early.get_id());
1133
1134 // Composed with starts_after, the pair is the month window: only the
1135 // late meeting sits in [now + 150_000, now + 260_000).
1136 let (rows, total) = list_for_requester(
1137 &db,
1138 &veli,
1139 RequesterListParams {
1140 starts_after: Some(at(now + 150_000)),
1141 starts_before: Some(at(now + 260_000)),
1142 ..Default::default()
1143 },
1144 )
1145 .await
1146 .unwrap();
1147 assert_eq!((rows.len(), total), (1, 1));
1148 assert_eq!(rows[0].get_id(), late.get_id());
1149 }
1150}