Merge branch 'layer-split/appointment'
Browse files at this commit10 changed files +1045 -978
- src/db/appointment.rs +200 -0
- src/db/mod.rs +1 -0
- src/domain/appointment.rs +43 -948
- src/domain/appointment_slot.rs +7 -4
- src/domain/user.rs +8 -7
- src/service/appointment.rs +763 -0
- src/service/mod.rs +1 -0
- src/web/appointments.rs +19 -16
- tests/integration.rs +1 -1
- tests/regress_appointments.rs +2 -2
src/db/appointment.rsadded+200 -0
| @@ -0,0 +1,200 @@ | |||
| 1 | +//! The `appointment` table: row reads and listings, the overlap probe behind | ||
| 2 | +//! the booking guard, and the compare-and-set every decision writes through. | ||
| 3 | +//! The workflows that sequence these under | ||
| 4 | +//! [`crate::service::appointment::APPOINTMENT_LOCK`] live in | ||
| 5 | +//! [`crate::service::appointment`]. | ||
| 6 | + | ||
| 7 | +use surrealdb::types::SurrealValue; | ||
| 8 | + | ||
| 9 | +use crate::database::{Database, lost_the_race}; | ||
| 10 | +use crate::db::page::PagedList; | ||
| 11 | +use crate::domain::appointment::{Appointment, AppointmentId, AppointmentStatus}; | ||
| 12 | +use crate::domain::appointment_slot::AppointmentSlotId; | ||
| 13 | +use crate::domain::timestamp::Timestamp; | ||
| 14 | +use crate::domain::user::UserId; | ||
| 15 | +use crate::error::AppError; | ||
| 16 | + | ||
| 17 | +/// The window an approved booking actually occupies, as read back from the | ||
| 18 | +/// database: the counter-proposed time when there is one, the slot's own | ||
| 19 | +/// otherwise. Optional fields because a dangling slot reference resolves to | ||
| 20 | +/// `NONE` — such a row is skipped rather than failing the whole guard. | ||
| 21 | +#[derive(Debug, Clone, SurrealValue)] | ||
| 22 | +struct BookedWindow { | ||
| 23 | + starts_at: Option<Timestamp>, | ||
| 24 | + ends_at: Option<Timestamp>, | ||
| 25 | +} | ||
| 26 | + | ||
| 27 | +/// Is `[starts_at, ends_at)` already taken for either party? Both sides are | ||
| 28 | +/// checked: a teacher can't be in two meetings at once, and neither can a | ||
| 29 | +/// requester (a parent with two children's teachers, say). | ||
| 30 | +/// | ||
| 31 | +/// Only *approved* bookings block — a pending request is a wish, not a | ||
| 32 | +/// commitment, so several may queue on overlapping times and the first | ||
| 33 | +/// approval wins. `except` skips one row, so re-checking a booking against | ||
| 34 | +/// the world never trips over itself. | ||
| 35 | +/// | ||
| 36 | +/// Caller must hold | ||
| 37 | +/// [`crate::service::appointment::APPOINTMENT_LOCK`] for the answer to still | ||
| 38 | +/// be true by the time it is acted on. | ||
| 39 | +pub async fn conflicts( | ||
| 40 | + db: &Database, | ||
| 41 | + teacher: &UserId, | ||
| 42 | + requester: &UserId, | ||
| 43 | + starts_at: Timestamp, | ||
| 44 | + ends_at: Timestamp, | ||
| 45 | + except: Option<&AppointmentId>, | ||
| 46 | +) -> Result<bool, AppError> { | ||
| 47 | + // The effective window is computed in the query (proposal overrides | ||
| 48 | + // the slot) but compared here: one round trip, and the comparison | ||
| 49 | + // itself stays a plain, unit-tested Rust predicate. | ||
| 50 | + let mut result = db | ||
| 51 | + .query( | ||
| 52 | + "SELECT \ | ||
| 53 | + (IF proposed_starts_at != NONE THEN proposed_starts_at \ | ||
| 54 | + ELSE slot.starts_at END) AS starts_at, \ | ||
| 55 | + (IF proposed_ends_at != NONE THEN proposed_ends_at \ | ||
| 56 | + ELSE slot.ends_at END) AS ends_at \ | ||
| 57 | + FROM appointment \ | ||
| 58 | + WHERE status = 'approved' AND id != $except \ | ||
| 59 | + AND (requester = $requester OR slot.teacher = $teacher)", | ||
| 60 | + ) | ||
| 61 | + .bind(("teacher", teacher.record())) | ||
| 62 | + .bind(("requester", requester.record())) | ||
| 63 | + .bind(("except", except.map(AppointmentId::record))) | ||
| 64 | + .await? | ||
| 65 | + .check()?; | ||
| 66 | + Ok(result | ||
| 67 | + .take::<Vec<BookedWindow>>(0)? | ||
| 68 | + .into_iter() | ||
| 69 | + .filter_map(|window| Some((window.starts_at?, window.ends_at?))) | ||
| 70 | + .any(|(booked_starts_at, booked_ends_at)| { | ||
| 71 | + Appointment::overlaps(starts_at, ends_at, booked_starts_at, booked_ends_at) | ||
| 72 | + })) | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +pub async fn read( | ||
| 76 | + db: &Database, | ||
| 77 | + id: &AppointmentId, | ||
| 78 | +) -> Result<Option<Appointment>, AppError> { | ||
| 79 | + Ok(db.select(id.record()).await?) | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +/// The row, insisting it is still open for a decision. | ||
| 83 | +pub async fn read_pending(db: &Database, id: &AppointmentId) -> Result<Appointment, AppError> { | ||
| 84 | + let appointment = read(db, id).await?.ok_or(AppError::NotFound)?; | ||
| 85 | + if appointment.status != AppointmentStatus::Pending { | ||
| 86 | + return Err(AppError::Conflict("the appointment is no longer pending")); | ||
| 87 | + } | ||
| 88 | + Ok(appointment) | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +pub async fn list_for_requester( | ||
| 92 | + db: &Database, | ||
| 93 | + requester: &UserId, | ||
| 94 | + limit: Option<i64>, | ||
| 95 | + offset: i64, | ||
| 96 | +) -> Result<(Vec<Appointment>, i64), AppError> { | ||
| 97 | + PagedList::new( | ||
| 98 | + "appointment WHERE requester = $requester", | ||
| 99 | + "ORDER BY id DESC", | ||
| 100 | + ) | ||
| 101 | + .bind("requester", requester.record()) | ||
| 102 | + .run(limit, offset, db) | ||
| 103 | + .await | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +/// Every booking aimed at `teacher`, across all their slots — the teacher's | ||
| 107 | +/// request inbox. | ||
| 108 | +pub async fn list_for_teacher( | ||
| 109 | + db: &Database, | ||
| 110 | + teacher: &UserId, | ||
| 111 | + limit: Option<i64>, | ||
| 112 | + offset: i64, | ||
| 113 | +) -> Result<(Vec<Appointment>, i64), AppError> { | ||
| 114 | + PagedList::new( | ||
| 115 | + "appointment WHERE slot.teacher = $teacher", | ||
| 116 | + "ORDER BY id DESC", | ||
| 117 | + ) | ||
| 118 | + .bind("teacher", teacher.record()) | ||
| 119 | + .run(limit, offset, db) | ||
| 120 | + .await | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +pub async fn list_for_slot( | ||
| 124 | + db: &Database, | ||
| 125 | + slot: &AppointmentSlotId, | ||
| 126 | +) -> Result<Vec<Appointment>, AppError> { | ||
| 127 | + let mut result = db | ||
| 128 | + .query("SELECT * FROM appointment WHERE slot = $slot ORDER BY id DESC") | ||
| 129 | + .bind(("slot", slot.record())) | ||
| 130 | + .await? | ||
| 131 | + .check()?; | ||
| 132 | + Ok(result.take::<Vec<Appointment>>(0)?) | ||
| 133 | +} | ||
| 134 | + | ||
| 135 | +/// Write the decision only while the stored row still carries the state it | ||
| 136 | +/// was validated against. `None` means it does not: another decision landed | ||
| 137 | +/// between the read and the write, so reload, re-validate, and try again. | ||
| 138 | +/// | ||
| 139 | +/// Four columns discriminate every write, and `status` alone would not: | ||
| 140 | +/// `propose` leaves a pending booking pending, so an approval built from a | ||
| 141 | +/// snapshot taken *before* that proposal would sail through a status-only | ||
| 142 | +/// guard and confirm the meeting at the old, superseded time. With the | ||
| 143 | +/// proposed window and `decided_by` alongside it, every mutator moves at | ||
| 144 | +/// least one of the four. The fields only a terminal transition writes | ||
| 145 | +/// (`cancelled_by`, `cancel_reason`, `reject_reason`) need no compare of | ||
| 146 | +/// their own: they always travel with a `status` change into a state no | ||
| 147 | +/// later decision is allowed from. All four are top-level columns, so an | ||
| 148 | +/// absent one reads back as `NONE` and `NONE = NONE` holds — the object-key | ||
| 149 | +/// dropping that forces `settings` to compare a rebuilt projection cannot | ||
| 150 | +/// bite here. | ||
| 151 | +/// | ||
| 152 | +/// A store-level write conflict is reported the same way as a miss: it | ||
| 153 | +/// means a concurrent write committed on this row, which is exactly the | ||
| 154 | +/// "reload and re-decide" case. | ||
| 155 | +/// | ||
| 156 | +/// A transition out of a live status (reject, cancel) hands the slot's | ||
| 157 | +/// `occupied` seat back, in this same transaction — the counter is the | ||
| 158 | +/// authority on whether the slot is taken, so it must move if and only if | ||
| 159 | +/// the status did. The decrement is `WHERE`-gated on the CAS having written | ||
| 160 | +/// something, so a lost race frees nothing. | ||
| 161 | +pub async fn save_if_unchanged( | ||
| 162 | + db: &Database, | ||
| 163 | + expected: &Appointment, | ||
| 164 | + new: Appointment, | ||
| 165 | +) -> Result<Option<Appointment>, AppError> { | ||
| 166 | + let frees_the_slot = expected.status.is_live() && !new.status.is_live(); | ||
| 167 | + let attempted = async { | ||
| 168 | + let mut result = db | ||
| 169 | + .query( | ||
| 170 | + "BEGIN TRANSACTION; | ||
| 171 | + LET $done = (UPDATE $id CONTENT $new \ | ||
| 172 | + WHERE status = $status \ | ||
| 173 | + AND proposed_starts_at = $proposed_starts_at \ | ||
| 174 | + AND proposed_ends_at = $proposed_ends_at \ | ||
| 175 | + AND decided_by = $decided_by); | ||
| 176 | + UPDATE $slot SET occupied = math::max([(occupied ?? 0) - 1, 0]) | ||
| 177 | + WHERE $frees AND array::len($done) > 0; | ||
| 178 | + RETURN $done; | ||
| 179 | + COMMIT TRANSACTION;", | ||
| 180 | + ) | ||
| 181 | + .bind(("slot", expected.slot.record())) | ||
| 182 | + .bind(("frees", frees_the_slot)) | ||
| 183 | + .bind(("id", expected.id.record())) | ||
| 184 | + .bind(("status", expected.status)) | ||
| 185 | + .bind(("proposed_starts_at", expected.proposed_starts_at)) | ||
| 186 | + .bind(("proposed_ends_at", expected.proposed_ends_at)) | ||
| 187 | + .bind(("decided_by", expected.decided_by.clone())) | ||
| 188 | + .bind(("new", new)) | ||
| 189 | + .await? | ||
| 190 | + .check()?; | ||
| 191 | + // BEGIN, the LET, and the counter write take a slot each. | ||
| 192 | + result.take::<Vec<Appointment>>(3) | ||
| 193 | + } | ||
| 194 | + .await; | ||
| 195 | + match attempted { | ||
| 196 | + Ok(rows) => Ok(rows.into_iter().next()), | ||
| 197 | + Err(err) if lost_the_race(&err) => Ok(None), | ||
| 198 | + Err(err) => Err(err.into()), | ||
| 199 | + } | ||
| 200 | +} | ||
src/db/mod.rsmodified+1 -0
| @@ -1,5 +1,6 @@ | |||
| 1 | //! The only layer that executes queries. | 1 | //! The only layer that executes queries. |
| 2 | 2 | ||
| 3 | +pub mod appointment; | ||
| 3 | pub mod cap; | 4 | pub mod cap; |
| 4 | pub mod field_update; | 5 | pub mod field_update; |
| 5 | pub mod note; | 6 | pub mod note; |
src/domain/appointment.rsmodified+43 -948
| @@ -2,77 +2,57 @@ | |||
| 2 | //! for the meeting with a reason; the teacher approves, rejects, or | 2 | //! for the meeting with a reason; the teacher approves, rejects, or |
| 3 | //! counter-proposes another time. | 3 | //! counter-proposes another time. |
| 4 | //! | 4 | //! |
| 5 | -//! Two *cross-record* invariants live here, guarded very differently: | 5 | +//! This module is the pure row shape: the validated reason and status, the |
| 6 | +//! id, and the two predicates every layer shares — [`Appointment::window`] | ||
| 7 | +//! (a proposal overrides the slot) and [`Appointment::overlaps`] (half-open | ||
| 8 | +//! windows, so back-to-back meetings do not collide). | ||
| 9 | +//! | ||
| 10 | +//! The *cross-record* invariants live one layer down: | ||
| 6 | //! | 11 | //! |
| 7 | //! - **One live booking per slot** — the `occupied` counter on the slot row, a | 12 | //! - **One live booking per slot** — the `occupied` counter on the slot row, a |
| 8 | -//! [`cap`](crate::db::cap) of one. Booking claims it *with* the booking | 13 | +//! [`cap`](crate::db::cap) of one. [`crate::service::appointment::book`] |
| 9 | -//! row ([`claim_and_create`](cap::claim_and_create)); | 14 | +//! claims it *with* the booking row |
| 10 | -//! rejecting or cancelling gives it back in the *same transaction* as the | 15 | +//! ([`cap::claim_and_create`](crate::db::cap::claim_and_create)); rejecting |
| 11 | -//! status flip, so the slot frees itself with nothing to sweep. Both are | 16 | +//! or cancelling gives it back in the *same transaction* as the status flip |
| 12 | -//! single-record conditional writes, so the store decides it, not a lock. | 17 | +//! ([`crate::db::appointment::save_if_unchanged`]), so the slot frees itself |
| 18 | +//! with nothing to sweep. Both are single-record conditional writes, so the | ||
| 19 | +//! store decides it, not a lock. | ||
| 13 | //! - **No double-booked person.** An approved meeting may not overlap another | 20 | //! - **No double-booked person.** An approved meeting may not overlap another |
| 14 | //! approved meeting of the same teacher *or* of the same requester. That is a | 21 | //! approved meeting of the same teacher *or* of the same requester. That is a |
| 15 | //! count-then-write over *many* rows, which a `BEGIN…COMMIT` does not | 22 | //! count-then-write over *many* rows, which a `BEGIN…COMMIT` does not |
| 16 | -//! serialize in SurrealDB (write-skew), so it stays under | 23 | +//! serialize in SurrealDB (write-skew), so booking and approval hold |
| 17 | -//! [`APPOINTMENT_LOCK`], which is the whole guarantee behind it. | 24 | +//! [`crate::service::appointment::APPOINTMENT_LOCK`], which is the whole |
| 25 | +//! guarantee behind it. | ||
| 18 | //! | 26 | //! |
| 19 | //! The *single-row* invariant — a decision must be written onto the state it | 27 | //! The *single-row* invariant — a decision must be written onto the state it |
| 20 | //! was validated against — is **not** the lock's job, and never was: a | 28 | //! was validated against — is **not** the lock's job, and never was: a |
| 21 | //! whole-row save built on a snapshot read before the lock was taken would | 29 | //! whole-row save built on a snapshot read before the lock was taken would |
| 22 | //! silently drop whatever landed in between. That one is a compare-and-set | 30 | //! silently drop whatever landed in between. That one is a compare-and-set |
| 23 | -//! ([`Appointment::save_if_unchanged`]), decided by the store. | 31 | +//! ([`crate::db::appointment::save_if_unchanged`]), decided by the store. |
| 24 | //! | 32 | //! |
| 25 | //! Overlap therefore rests on the lock alone — it is a predicate over *other* | 33 | //! Overlap therefore rests on the lock alone — it is a predicate over *other* |
| 26 | //! rows, with no single row to key a counter or a CAS on. That holds while | 34 | //! rows, with no single row to key a counter or a CAS on. That holds while |
| 27 | -//! every approving write takes [`APPOINTMENT_LOCK`]; one that skips it puts two | 35 | +//! every approving write takes the lock; one that skips it puts two |
| 28 | -//! meetings in one half-hour, so the rule is stated here rather than left to be | 36 | +//! meetings in one half-hour, so the rule is stated at the lock rather than |
| 29 | -//! noticed. The damage if it ever happens is one double-booked half-hour, | 37 | +//! left to be noticed. The damage if it ever happens is one double-booked |
| 30 | -//! visible to both parties and fixable by cancelling either side — no money, no | 38 | +//! half-hour, visible to both parties and fixable by cancelling either |
| 31 | -//! grade, no data loss. | 39 | +//! side — no money, no grade, no data loss. |
| 32 | 40 | ||
| 33 | use std::sync::LazyLock; | 41 | use std::sync::LazyLock; |
| 34 | 42 | ||
| 35 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 43 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 36 | -use tokio::sync::Mutex; | ||
| 37 | use ulid::Generator; | 44 | use ulid::Generator; |
| 38 | 45 | ||
| 39 | -use crate::constant::{ | 46 | +use crate::constant::{APPOINTMENT_TABLE, MAX_APPOINTMENT_REASON_LEN}; |
| 40 | - APPOINTMENT_TABLE, CAS_UPDATE_RETRIES, MAX_APPOINTMENT_REASON_LEN, SLOT_OCCUPIED_FIELD, | ||
| 41 | -}; | ||
| 42 | -use crate::database::{Database, lost_the_race}; | ||
| 43 | use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId}; | 47 | use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId}; |
| 44 | -use crate::db::cap; | ||
| 45 | -use crate::db::page::PagedList; | ||
| 46 | use crate::domain::timestamp::Timestamp; | 48 | use crate::domain::timestamp::Timestamp; |
| 47 | use crate::domain::user::UserId; | 49 | use crate::domain::user::UserId; |
| 48 | -use crate::error::{AppError, ValidationError}; | 50 | +use crate::error::ValidationError; |
| 49 | use crate::validate::validate_required; | 51 | use crate::validate::validate_required; |
| 50 | 52 | ||
| 51 | -/// Serializes the **overlap** check and the write it authorizes — nothing else. | ||
| 52 | -/// "Is this teacher (or this requester) already committed at that time" is a | ||
| 53 | -/// predicate over other appointment rows, and SurrealDB does not conflict-check | ||
| 54 | -/// a cross-record read against a concurrent insert, so the check and its write | ||
| 55 | -/// have to be one atomic step, and this lock is the only thing that makes them | ||
| 56 | -/// one. Occupancy is no longer its business: that is the slot's `occupied` | ||
| 57 | -/// counter, a conditional single-record write the store decides. | ||
| 58 | -/// | ||
| 59 | -/// So this is load-bearing, not a convenience: an approval path that does not | ||
| 60 | -/// take it can double-book a teacher, as the module doc records. | ||
| 61 | -/// | ||
| 62 | -/// Lock order: taken *before* `cap`'s `CLAIM_LOCK` (booking claims a slot while | ||
| 63 | -/// holding this) and never the other way round. No path ever holds this | ||
| 64 | -/// together with `ENROLL_LOCK`, | ||
| 65 | -/// `TERM_LOCK`, `EXAM_LOCK`, or `PRESENCE_LOCK` — appointments | ||
| 66 | -/// touch no roster, term, event seat, or exam room, and none of those touch | ||
| 67 | -/// appointments — so they cannot deadlock. Should a future path ever need two, | ||
| 68 | -/// take this one *last*. | ||
| 69 | -// corner-cut: global lock; per-teacher locks if appointment traffic ever grows | ||
| 70 | -// enough for the contention to matter. | ||
| 71 | -pub(crate) static APPOINTMENT_LOCK: Mutex<()> = Mutex::const_new(()); | ||
| 72 | - | ||
| 73 | /// Mints booking ids in write order — `Ulid::new()`'s random low bits sort | 53 | /// Mints booking ids in write order — `Ulid::new()`'s random low bits sort |
| 74 | /// arbitrarily within one millisecond, which would scramble the `id` tie-break | 54 | /// arbitrarily within one millisecond, which would scramble the `id` tie-break |
| 75 | -/// of the newest-first listings below. | 55 | +/// of the newest-first listings ([`crate::db::appointment::list_for_requester`]). |
| 76 | static IDS: LazyLock<std::sync::Mutex<Generator>> = | 56 | static IDS: LazyLock<std::sync::Mutex<Generator>> = |
| 77 | LazyLock::new(|| std::sync::Mutex::new(Generator::new())); | 57 | LazyLock::new(|| std::sync::Mutex::new(Generator::new())); |
| 78 | 58 | ||
| @@ -157,41 +137,34 @@ impl AppointmentReason { | |||
| 157 | } | 137 | } |
| 158 | } | 138 | } |
| 159 | 139 | ||
| 160 | -/// The window an approved booking actually occupies, as read back from the | 140 | +/// Fields are crate-visible: [`crate::db::appointment`] reads the columns its |
| 161 | -/// database: the counter-proposed time when there is one, the slot's own | 141 | +/// compare-and-set discriminates on, and [`crate::service::appointment`] |
| 162 | -/// otherwise. Optional fields because a dangling slot reference resolves to | 142 | +/// clones a fresh read and mutates the decision onto it. |
| 163 | -/// `NONE` — such a row is skipped rather than failing the whole guard. | ||
| 164 | -#[derive(Debug, Clone, SurrealValue)] | ||
| 165 | -struct BookedWindow { | ||
| 166 | - starts_at: Option<Timestamp>, | ||
| 167 | - ends_at: Option<Timestamp>, | ||
| 168 | -} | ||
| 169 | - | ||
| 170 | #[derive(Debug, Clone, SurrealValue)] | 143 | #[derive(Debug, Clone, SurrealValue)] |
| 171 | pub struct Appointment { | 144 | pub struct Appointment { |
| 172 | - id: AppointmentId, | 145 | + pub(crate) id: AppointmentId, |
| 173 | - slot: AppointmentSlotId, | 146 | + pub(crate) slot: AppointmentSlotId, |
| 174 | - requester: UserId, | 147 | + pub(crate) requester: UserId, |
| 175 | - status: AppointmentStatus, | 148 | + pub(crate) status: AppointmentStatus, |
| 176 | - reason: AppointmentReason, | 149 | + pub(crate) reason: AppointmentReason, |
| 177 | /// A counter-proposal from the teacher (or a new time the requester asks | 150 | /// A counter-proposal from the teacher (or a new time the requester asks |
| 178 | /// for). Set as a triple or not at all; once accepted it *is* the | 151 | /// for). Set as a triple or not at all; once accepted it *is* the |
| 179 | /// meeting's time, overriding the slot's own window. | 152 | /// meeting's time, overriding the slot's own window. |
| 180 | - proposed_starts_at: Option<Timestamp>, | 153 | + pub(crate) proposed_starts_at: Option<Timestamp>, |
| 181 | - proposed_ends_at: Option<Timestamp>, | 154 | + pub(crate) proposed_ends_at: Option<Timestamp>, |
| 182 | - proposed_by: Option<UserId>, | 155 | + pub(crate) proposed_by: Option<UserId>, |
| 183 | - decided_by: Option<UserId>, | 156 | + pub(crate) decided_by: Option<UserId>, |
| 184 | /// Who called the meeting off, and why, once it is `cancelled`. Both | 157 | /// Who called the meeting off, and why, once it is `cancelled`. Both |
| 185 | /// `#[surreal(default)]` so bookings written before cancellation records | 158 | /// `#[surreal(default)]` so bookings written before cancellation records |
| 186 | /// existed still read back (they resolve to `None`). | 159 | /// existed still read back (they resolve to `None`). |
| 187 | #[surreal(default)] | 160 | #[surreal(default)] |
| 188 | - cancelled_by: Option<UserId>, | 161 | + pub(crate) cancelled_by: Option<UserId>, |
| 189 | #[surreal(default)] | 162 | #[surreal(default)] |
| 190 | - cancel_reason: Option<AppointmentReason>, | 163 | + pub(crate) cancel_reason: Option<AppointmentReason>, |
| 191 | /// Why the request was turned down; the rejecter is already on `decided_by`. | 164 | /// Why the request was turned down; the rejecter is already on `decided_by`. |
| 192 | #[surreal(default)] | 165 | #[surreal(default)] |
| 193 | - reject_reason: Option<AppointmentReason>, | 166 | + pub(crate) reject_reason: Option<AppointmentReason>, |
| 194 | - created_at: Timestamp, | 167 | + pub(crate) created_at: Timestamp, |
| 195 | } | 168 | } |
| 196 | 169 | ||
| 197 | impl Appointment { | 170 | impl Appointment { |
| @@ -269,507 +242,18 @@ impl Appointment { | |||
| 269 | && a_ends_at.as_millis() > b_starts_at.as_millis() | 242 | && a_ends_at.as_millis() > b_starts_at.as_millis() |
| 270 | } | 243 | } |
| 271 | 244 | ||
| 272 | - /// Is `[starts_at, ends_at)` already taken for either party? Both sides are | ||
| 273 | - /// checked: a teacher can't be in two meetings at once, and neither can a | ||
| 274 | - /// requester (a parent with two children's teachers, say). | ||
| 275 | - /// | ||
| 276 | - /// Only *approved* bookings block — a pending request is a wish, not a | ||
| 277 | - /// commitment, so several may queue on overlapping times and the first | ||
| 278 | - /// approval wins. `except` skips one row, so re-checking a booking against | ||
| 279 | - /// the world never trips over itself. | ||
| 280 | - /// | ||
| 281 | - /// Caller must hold [`APPOINTMENT_LOCK`] for the answer to still be true | ||
| 282 | - /// by the time it is acted on. | ||
| 283 | - pub async fn conflicts( | ||
| 284 | - teacher: &UserId, | ||
| 285 | - requester: &UserId, | ||
| 286 | - starts_at: Timestamp, | ||
| 287 | - ends_at: Timestamp, | ||
| 288 | - except: Option<&AppointmentId>, | ||
| 289 | - db: &Database, | ||
| 290 | - ) -> Result<bool, AppError> { | ||
| 291 | - // The effective window is computed in the query (proposal overrides | ||
| 292 | - // the slot) but compared here: one round trip, and the comparison | ||
| 293 | - // itself stays a plain, unit-tested Rust predicate. | ||
| 294 | - let mut result = db | ||
| 295 | - .query( | ||
| 296 | - "SELECT \ | ||
| 297 | - (IF proposed_starts_at != NONE THEN proposed_starts_at \ | ||
| 298 | - ELSE slot.starts_at END) AS starts_at, \ | ||
| 299 | - (IF proposed_ends_at != NONE THEN proposed_ends_at \ | ||
| 300 | - ELSE slot.ends_at END) AS ends_at \ | ||
| 301 | - FROM appointment \ | ||
| 302 | - WHERE status = 'approved' AND id != $except \ | ||
| 303 | - AND (requester = $requester OR slot.teacher = $teacher)", | ||
| 304 | - ) | ||
| 305 | - .bind(("teacher", teacher.record())) | ||
| 306 | - .bind(("requester", requester.record())) | ||
| 307 | - .bind(("except", except.map(AppointmentId::record))) | ||
| 308 | - .await? | ||
| 309 | - .check()?; | ||
| 310 | - Ok(result | ||
| 311 | - .take::<Vec<BookedWindow>>(0)? | ||
| 312 | - .into_iter() | ||
| 313 | - .filter_map(|window| Some((window.starts_at?, window.ends_at?))) | ||
| 314 | - .any(|(booked_starts_at, booked_ends_at)| { | ||
| 315 | - Self::overlaps(starts_at, ends_at, booked_starts_at, booked_ends_at) | ||
| 316 | - })) | ||
| 317 | - } | ||
| 318 | - | ||
| 319 | - /// Request `slot`. Lands `pending`: publishing availability is not consent | ||
| 320 | - /// to a specific person and topic. | ||
| 321 | - /// | ||
| 322 | - /// Refused (409) when the slot's window has already opened, when it is | ||
| 323 | - /// already taken, or when the requester is already committed elsewhere at | ||
| 324 | - /// that time. The slot is taken by [`cap::claim_and_create`], which writes | ||
| 325 | - /// the booking in the *same transaction* as the seat — a conditional | ||
| 326 | - /// single-record write, so two racing requests cannot both find it free | ||
| 327 | - /// however they interleave, and a crash between the two can no longer leave | ||
| 328 | - /// the slot occupied by a booking that does not exist. The requester's own | ||
| 329 | - /// overlap is the lock's part. | ||
| 330 | - pub async fn book( | ||
| 331 | - slot: &AppointmentSlotId, | ||
| 332 | - requester: &UserId, | ||
| 333 | - reason: AppointmentReason, | ||
| 334 | - db: &Database, | ||
| 335 | - ) -> Result<Appointment, AppError> { | ||
| 336 | - let _guard = APPOINTMENT_LOCK.lock().await; | ||
| 337 | - let slot_row = AppointmentSlot::read(slot, db) | ||
| 338 | - .await? | ||
| 339 | - .ok_or(AppError::NotFound)?; | ||
| 340 | - // A window that has opened is history, not a plan: `cancel` refuses to | ||
| 341 | - // call off a meeting that started, so such a booking would be stuck | ||
| 342 | - // forever. `list_upcoming` is bounded on this same `starts_at`, so the | ||
| 343 | - // calendar never offers one — but a slot whose start passed while the | ||
| 344 | - // page was open, or an id kept from an earlier read, still reaches here. | ||
| 345 | - // The publish-time 60s skew grace does not apply on either side. | ||
| 346 | - if slot_row.get_starts_at().as_millis() <= Timestamp::now().as_millis() { | ||
| 347 | - return Err(AppError::Conflict("the slot has already started")); | ||
| 348 | - } | ||
| 349 | - // The teacher's own overlaps are not checked here — an approved | ||
| 350 | - // meeting of theirs elsewhere is the *approval*'s business, and | ||
| 351 | - // refusing the request outright would hide a slot they published. | ||
| 352 | - if Self::conflicts( | ||
| 353 | - requester, | ||
| 354 | - requester, | ||
| 355 | - slot_row.get_starts_at(), | ||
| 356 | - slot_row.get_ends_at(), | ||
| 357 | - None, | ||
| 358 | - db, | ||
| 359 | - ) | ||
| 360 | - .await? | ||
| 361 | - { | ||
| 362 | - return Err(AppError::Conflict( | ||
| 363 | - "you already have an appointment at that time", | ||
| 364 | - )); | ||
| 365 | - } | ||
| 366 | - // Last, so nothing above can refuse *after* the slot was taken. A slot | ||
| 367 | - // deleted since the read above is gone, not full — the claim's `WHERE` | ||
| 368 | - // finds no row either way, so the distinction is re-read rather than | ||
| 369 | - // guessed. | ||
| 370 | - let seat = slot.record(); | ||
| 371 | - let appointment = Appointment { | ||
| 372 | - id: AppointmentId::generate(), | ||
| 373 | - slot: slot.clone(), | ||
| 374 | - requester: requester.clone(), | ||
| 375 | - status: AppointmentStatus::Pending, | ||
| 376 | - reason, | ||
| 377 | - proposed_starts_at: None, | ||
| 378 | - proposed_ends_at: None, | ||
| 379 | - proposed_by: None, | ||
| 380 | - decided_by: None, | ||
| 381 | - cancelled_by: None, | ||
| 382 | - cancel_reason: None, | ||
| 383 | - reject_reason: None, | ||
| 384 | - created_at: Timestamp::now(), | ||
| 385 | - }; | ||
| 386 | - match cap::claim_and_create( | ||
| 387 | - &seat, | ||
| 388 | - SLOT_OCCUPIED_FIELD, | ||
| 389 | - 1, | ||
| 390 | - &appointment.id.record(), | ||
| 391 | - &appointment, | ||
| 392 | - db, | ||
| 393 | - ) | ||
| 394 | - .await? | ||
| 395 | - { | ||
| 396 | - cap::Claimed::Made(created) => Ok(created), | ||
| 397 | - cap::Claimed::Full => { | ||
| 398 | - if AppointmentSlot::read(slot, db).await?.is_none() { | ||
| 399 | - return Err(AppError::NotFound); | ||
| 400 | - } | ||
| 401 | - Err(AppError::Conflict("the slot is already booked")) | ||
| 402 | - } | ||
| 403 | - // The id is a freshly minted ULID on a table with no UNIQUE index, | ||
| 404 | - // so no rival can have aimed at it. | ||
| 405 | - cap::Claimed::Duplicate => Err(AppError::Internal("appointment id collided".into())), | ||
| 406 | - } | ||
| 407 | - } | ||
| 408 | - | ||
| 409 | - pub async fn read(id: &AppointmentId, db: &Database) -> Result<Option<Appointment>, AppError> { | ||
| 410 | - Ok(db.select(id.record()).await?) | ||
| 411 | - } | ||
| 412 | - | ||
| 413 | - pub async fn list_for_requester( | ||
| 414 | - requester: &UserId, | ||
| 415 | - limit: Option<i64>, | ||
| 416 | - offset: i64, | ||
| 417 | - db: &Database, | ||
| 418 | - ) -> Result<(Vec<Appointment>, i64), AppError> { | ||
| 419 | - PagedList::new( | ||
| 420 | - "appointment WHERE requester = $requester", | ||
| 421 | - "ORDER BY id DESC", | ||
| 422 | - ) | ||
| 423 | - .bind("requester", requester.record()) | ||
| 424 | - .run(limit, offset, db) | ||
| 425 | - .await | ||
| 426 | - } | ||
| 427 | - | ||
| 428 | - /// Every booking aimed at `teacher`, across all their slots — the teacher's | ||
| 429 | - /// request inbox. | ||
| 430 | - pub async fn list_for_teacher( | ||
| 431 | - teacher: &UserId, | ||
| 432 | - limit: Option<i64>, | ||
| 433 | - offset: i64, | ||
| 434 | - db: &Database, | ||
| 435 | - ) -> Result<(Vec<Appointment>, i64), AppError> { | ||
| 436 | - PagedList::new( | ||
| 437 | - "appointment WHERE slot.teacher = $teacher", | ||
| 438 | - "ORDER BY id DESC", | ||
| 439 | - ) | ||
| 440 | - .bind("teacher", teacher.record()) | ||
| 441 | - .run(limit, offset, db) | ||
| 442 | - .await | ||
| 443 | - } | ||
| 444 | - | ||
| 445 | - pub async fn list_for_slot( | ||
| 446 | - slot: &AppointmentSlotId, | ||
| 447 | - db: &Database, | ||
| 448 | - ) -> Result<Vec<Appointment>, AppError> { | ||
| 449 | - let mut result = db | ||
| 450 | - .query("SELECT * FROM appointment WHERE slot = $slot ORDER BY id DESC") | ||
| 451 | - .bind(("slot", slot.record())) | ||
| 452 | - .await? | ||
| 453 | - .check()?; | ||
| 454 | - Ok(result.take::<Vec<Appointment>>(0)?) | ||
| 455 | - } | ||
| 456 | - | ||
| 457 | - /// Confirm the meeting at the slot's own window. Re-runs the double-booking | ||
| 458 | - /// guard for both teacher and requester against a fresh read under | ||
| 459 | - /// [`APPOINTMENT_LOCK`] — the authoritative check, since only approval | ||
| 460 | - /// commits anyone. Refused (409) when the effective window has already | ||
| 461 | - /// started; that also covers [`accept_proposal`], which lands here. | ||
| 462 | - /// | ||
| 463 | - /// Also refused (409) while a counter-proposal stands: the effective window | ||
| 464 | - /// would then be the *proposed* one, and the deciding side here is the | ||
| 465 | - /// teacher's, so approving would commit the requester to a time only the | ||
| 466 | - /// teacher ever named. That move belongs to [`accept_proposal`], which the | ||
| 467 | - /// web layer opens to the requester alone. | ||
| 468 | - pub async fn approve( | ||
| 469 | - id: &AppointmentId, | ||
| 470 | - decided_by: &UserId, | ||
| 471 | - db: &Database, | ||
| 472 | - ) -> Result<Appointment, AppError> { | ||
| 473 | - Self::approve_inner(id, decided_by, None, db).await | ||
| 474 | - } | ||
| 475 | - | ||
| 476 | - /// The one approval path. `accepting` carries the window the caller is | ||
| 477 | - /// answering *for*, which is the only way a proposed one may be committed: | ||
| 478 | - /// it both marks the caller as the proposal's counterparty and pins which | ||
| 479 | - /// proposal they saw. Re-checked on every retry round, so a proposal that | ||
| 480 | - /// moved between the read and the write is refused rather than confirmed. | ||
| 481 | - async fn approve_inner( | ||
| 482 | - id: &AppointmentId, | ||
| 483 | - decided_by: &UserId, | ||
| 484 | - accepting: Option<(Timestamp, Timestamp)>, | ||
| 485 | - db: &Database, | ||
| 486 | - ) -> Result<Appointment, AppError> { | ||
| 487 | - let _guard = APPOINTMENT_LOCK.lock().await; | ||
| 488 | - for _ in 0..CAS_UPDATE_RETRIES { | ||
| 489 | - let expected = Self::read_pending(id, db).await?; | ||
| 490 | - match accepting { | ||
| 491 | - None if expected.has_proposal() => { | ||
| 492 | - return Err(AppError::Conflict( | ||
| 493 | - "a counter-proposal is standing; only the requester can accept it", | ||
| 494 | - )); | ||
| 495 | - } | ||
| 496 | - Some(_) if !expected.has_proposal() => { | ||
| 497 | - return Err(AppError::Conflict("no time has been proposed")); | ||
| 498 | - } | ||
| 499 | - // The proposal moved between the requester reading it and | ||
| 500 | - // accepting it. Committing here would bind them to a window the | ||
| 501 | - // teacher swapped in after they clicked, which is the whole | ||
| 502 | - // thing the requester-only accept exists to prevent. | ||
| 503 | - Some(accepted) if !expected.proposes(accepted) => { | ||
| 504 | - return Err(AppError::Conflict( | ||
| 505 | - "the proposed time has changed; re-read the booking and accept the new one", | ||
| 506 | - )); | ||
| 507 | - } | ||
| 508 | - _ => {} | ||
| 509 | - } | ||
| 510 | - let slot = AppointmentSlot::read(&expected.slot, db) | ||
| 511 | - .await? | ||
| 512 | - .ok_or(AppError::NotFound)?; | ||
| 513 | - let (starts_at, ends_at) = expected.window(&slot); | ||
| 514 | - // The effective window — the proposal's when one stands — must still | ||
| 515 | - // be ahead. Mutual agreement does not help: `cancel` refuses a | ||
| 516 | - // meeting that started, so committing to a passed window would mint | ||
| 517 | - // a booking nobody can ever undo. Refused, the row stays `pending` | ||
| 518 | - // and the teacher can propose a time that can actually happen. | ||
| 519 | - if starts_at.as_millis() <= Timestamp::now().as_millis() { | ||
| 520 | - return Err(AppError::Conflict("that time has already started")); | ||
| 521 | - } | ||
| 522 | - if Self::conflicts( | ||
| 523 | - slot.get_teacher(), | ||
| 524 | - &expected.requester, | ||
| 525 | - starts_at, | ||
| 526 | - ends_at, | ||
| 527 | - Some(id), | ||
| 528 | - db, | ||
| 529 | - ) | ||
| 530 | - .await? | ||
| 531 | - { | ||
| 532 | - return Err(AppError::Conflict( | ||
| 533 | - "that time collides with another approved appointment", | ||
| 534 | - )); | ||
| 535 | - } | ||
| 536 | - let mut approved = expected.clone(); | ||
| 537 | - approved.status = AppointmentStatus::Approved; | ||
| 538 | - approved.decided_by = Some(decided_by.clone()); | ||
| 539 | - if let Some(saved) = approved.save_if_unchanged(&expected, db).await? { | ||
| 540 | - return Ok(saved); | ||
| 541 | - } | ||
| 542 | - } | ||
| 543 | - Err(contended()) | ||
| 544 | - } | ||
| 545 | - | ||
| 546 | - /// Turn the request down. Frees the slot — the seat goes back with the | ||
| 547 | - /// status flip, in one transaction. No lock: this decides nothing about | ||
| 548 | - /// anyone's calendar, and the write is its own guard. | ||
| 549 | - pub async fn reject( | ||
| 550 | - id: &AppointmentId, | ||
| 551 | - decided_by: &UserId, | ||
| 552 | - reason: Option<AppointmentReason>, | ||
| 553 | - db: &Database, | ||
| 554 | - ) -> Result<Appointment, AppError> { | ||
| 555 | - for _ in 0..CAS_UPDATE_RETRIES { | ||
| 556 | - let expected = Self::read_pending(id, db).await?; | ||
| 557 | - let mut rejected = expected.clone(); | ||
| 558 | - rejected.status = AppointmentStatus::Rejected; | ||
| 559 | - rejected.decided_by = Some(decided_by.clone()); | ||
| 560 | - rejected.reject_reason = reason.clone(); | ||
| 561 | - if let Some(saved) = rejected.save_if_unchanged(&expected, db).await? { | ||
| 562 | - return Ok(saved); | ||
| 563 | - } | ||
| 564 | - } | ||
| 565 | - Err(contended()) | ||
| 566 | - } | ||
| 567 | - | ||
| 568 | - /// Call the meeting off. Legal from either live state, so an approved | ||
| 569 | - /// meeting can still be dropped; the slot frees up. The web layer opens | ||
| 570 | - /// this to the **requester only** — a teacher's way out is `reject` while | ||
| 571 | - /// the booking is pending, or `reschedule` (back to `pending`) then | ||
| 572 | - /// `reject` for an approved one — and `decline_reschedule`, the other | ||
| 573 | - /// caller, is the requester's too. | ||
| 574 | - /// | ||
| 575 | - /// Refused (409) once the *effective* window has opened — a meeting that | ||
| 576 | - /// began is history, not a plan. The guard lives here rather than in the | ||
| 577 | - /// handler so every caller inherits it: `decline_reschedule` cancels | ||
| 578 | - /// through this same door and used to slip past a handler-only check. | ||
| 579 | - pub async fn cancel( | ||
| 580 | - id: &AppointmentId, | ||
| 581 | - cancelled_by: &UserId, | ||
| 582 | - reason: Option<AppointmentReason>, | ||
| 583 | - db: &Database, | ||
| 584 | - ) -> Result<Appointment, AppError> { | ||
| 585 | - for _ in 0..CAS_UPDATE_RETRIES { | ||
| 586 | - let expected = Self::read(id, db).await?.ok_or(AppError::NotFound)?; | ||
| 587 | - if !expected.status.is_live() { | ||
| 588 | - return Err(AppError::Conflict("the appointment is already settled")); | ||
| 589 | - } | ||
| 590 | - let slot = AppointmentSlot::read(&expected.slot, db) | ||
| 591 | - .await? | ||
| 592 | - .ok_or(AppError::NotFound)?; | ||
| 593 | - if expected.window(&slot).0.as_millis() <= Timestamp::now().as_millis() { | ||
| 594 | - return Err(AppError::Conflict("the appointment has already started")); | ||
| 595 | - } | ||
| 596 | - let mut cancelled = expected.clone(); | ||
| 597 | - cancelled.status = AppointmentStatus::Cancelled; | ||
| 598 | - cancelled.cancelled_by = Some(cancelled_by.clone()); | ||
| 599 | - cancelled.cancel_reason = reason.clone(); | ||
| 600 | - if let Some(saved) = cancelled.save_if_unchanged(&expected, db).await? { | ||
| 601 | - return Ok(saved); | ||
| 602 | - } | ||
| 603 | - } | ||
| 604 | - Err(contended()) | ||
| 605 | - } | ||
| 606 | - | ||
| 607 | - /// Counter-propose another time on the same booking (no second row, so the | ||
| 608 | - /// reason and the history stay in one place). | ||
| 609 | - /// | ||
| 610 | - /// The proposal sends the booking back to `pending`: a previously approved | ||
| 611 | - /// meeting is *not* committed at the new time until the other side accepts, | ||
| 612 | - /// and leaving it approved would silently move a confirmed appointment. | ||
| 613 | - /// | ||
| 614 | - /// Refused (409) when the proposed window has already opened. The handler's | ||
| 615 | - /// `check_not_past` carries a 60s clock-skew grace, which is enough to | ||
| 616 | - /// propose a window that is already underway; `cancel` would then refuse to | ||
| 617 | - /// undo the booking, so it must not be offered in the first place. | ||
| 618 | - pub async fn propose( | ||
| 619 | - id: &AppointmentId, | ||
| 620 | - starts_at: Timestamp, | ||
| 621 | - ends_at: Timestamp, | ||
| 622 | - proposed_by: &UserId, | ||
| 623 | - db: &Database, | ||
| 624 | - ) -> Result<Appointment, AppError> { | ||
| 625 | - if starts_at.as_millis() >= ends_at.as_millis() { | ||
| 626 | - return Err(ValidationError::Invalid { | ||
| 627 | - field: "proposed_ends_at", | ||
| 628 | - reason: "must be after proposed_starts_at", | ||
| 629 | - } | ||
| 630 | - .into()); | ||
| 631 | - } | ||
| 632 | - // No lock: a proposal commits nobody's calendar (the booking goes back | ||
| 633 | - // to `pending`), and it neither takes nor frees the slot's seat. | ||
| 634 | - for _ in 0..CAS_UPDATE_RETRIES { | ||
| 635 | - let expected = Self::read(id, db).await?.ok_or(AppError::NotFound)?; | ||
| 636 | - if !expected.status.is_live() { | ||
| 637 | - return Err(AppError::Conflict("the appointment is already settled")); | ||
| 638 | - } | ||
| 639 | - if starts_at.as_millis() <= Timestamp::now().as_millis() { | ||
| 640 | - return Err(AppError::Conflict("that time has already started")); | ||
| 641 | - } | ||
| 642 | - let mut proposed = expected.clone(); | ||
| 643 | - proposed.status = AppointmentStatus::Pending; | ||
| 644 | - proposed.decided_by = None; | ||
| 645 | - proposed.proposed_starts_at = Some(starts_at); | ||
| 646 | - proposed.proposed_ends_at = Some(ends_at); | ||
| 647 | - proposed.proposed_by = Some(proposed_by.clone()); | ||
| 648 | - if let Some(saved) = proposed.save_if_unchanged(&expected, db).await? { | ||
| 649 | - return Ok(saved); | ||
| 650 | - } | ||
| 651 | - } | ||
| 652 | - Err(contended()) | ||
| 653 | - } | ||
| 654 | - | ||
| 655 | - /// Accept the standing proposal — approval at the proposed time. The | ||
| 656 | - /// overlap guard runs again because the time moved. | ||
| 657 | - /// | ||
| 658 | - /// `starts_at`/`ends_at` are the proposal the caller is answering, as they | ||
| 659 | - /// read it. They are not a request to move the meeting: they *pin* the one | ||
| 660 | - /// being accepted, and a proposal that has since been superseded is refused | ||
| 661 | - /// (409) rather than committed. `propose` takes no lock and the two calls | ||
| 662 | - /// are minutes apart, so nothing but this pin can tell "the requester | ||
| 663 | - /// agreed to 10:00" from "the requester's click landed on 23:00". | ||
| 664 | - pub async fn accept_proposal( | ||
| 665 | - id: &AppointmentId, | ||
| 666 | - decided_by: &UserId, | ||
| 667 | - starts_at: Timestamp, | ||
| 668 | - ends_at: Timestamp, | ||
| 669 | - db: &Database, | ||
| 670 | - ) -> Result<Appointment, AppError> { | ||
| 671 | - // The same approval path re-reads under the lock and reads the proposed | ||
| 672 | - // window off the row, so accepting is approval — no second code path. | ||
| 673 | - // Only this door passes `accepting`, and the web layer opens it to the | ||
| 674 | - // requester alone. | ||
| 675 | - Self::approve_inner(id, decided_by, Some((starts_at, ends_at)), db).await | ||
| 676 | - } | ||
| 677 | - | ||
| 678 | /// Is a counter-proposal standing? Both halves, exactly as [`window`](Self::window) | 245 | /// Is a counter-proposal standing? Both halves, exactly as [`window`](Self::window) |
| 679 | /// prefers them: a half-written triple is not a proposal and the slot's own | 246 | /// prefers them: a half-written triple is not a proposal and the slot's own |
| 680 | /// window still rules. | 247 | /// window still rules. |
| 681 | - fn has_proposal(&self) -> bool { | 248 | + pub(crate) fn has_proposal(&self) -> bool { |
| 682 | self.proposed_starts_at.is_some() && self.proposed_ends_at.is_some() | 249 | self.proposed_starts_at.is_some() && self.proposed_ends_at.is_some() |
| 683 | } | 250 | } |
| 684 | 251 | ||
| 685 | /// Is the standing proposal exactly this window? Milliseconds, the one form | 252 | /// Is the standing proposal exactly this window? Milliseconds, the one form |
| 686 | /// both the API and the row speak. | 253 | /// both the API and the row speak. |
| 687 | - fn proposes(&self, (starts_at, ends_at): (Timestamp, Timestamp)) -> bool { | 254 | + pub(crate) fn proposes(&self, (starts_at, ends_at): (Timestamp, Timestamp)) -> bool { |
| 688 | self.proposed_starts_at == Some(starts_at) && self.proposed_ends_at == Some(ends_at) | 255 | self.proposed_starts_at == Some(starts_at) && self.proposed_ends_at == Some(ends_at) |
| 689 | } | 256 | } |
| 690 | - | ||
| 691 | - /// The row, insisting it is still open for a decision. | ||
| 692 | - async fn read_pending(id: &AppointmentId, db: &Database) -> Result<Appointment, AppError> { | ||
| 693 | - let appointment = Self::read(id, db).await?.ok_or(AppError::NotFound)?; | ||
| 694 | - if appointment.status != AppointmentStatus::Pending { | ||
| 695 | - return Err(AppError::Conflict("the appointment is no longer pending")); | ||
| 696 | - } | ||
| 697 | - Ok(appointment) | ||
| 698 | - } | ||
| 699 | - | ||
| 700 | - /// Write the decision only while the stored row still carries the state it | ||
| 701 | - /// was validated against. `None` means it does not: another decision landed | ||
| 702 | - /// between the read and the write, so reload, re-validate, and try again. | ||
| 703 | - /// | ||
| 704 | - /// Four columns discriminate every write, and `status` alone would not: | ||
| 705 | - /// `propose` leaves a pending booking pending, so an approval built from a | ||
| 706 | - /// snapshot taken *before* that proposal would sail through a status-only | ||
| 707 | - /// guard and confirm the meeting at the old, superseded time. With the | ||
| 708 | - /// proposed window and `decided_by` alongside it, every mutator moves at | ||
| 709 | - /// least one of the four. The fields only a terminal transition writes | ||
| 710 | - /// (`cancelled_by`, `cancel_reason`, `reject_reason`) need no compare of | ||
| 711 | - /// their own: they always travel with a `status` change into a state no | ||
| 712 | - /// later decision is allowed from. All four are top-level columns, so an | ||
| 713 | - /// absent one reads back as `NONE` and `NONE = NONE` holds — the object-key | ||
| 714 | - /// dropping that forces `settings` to compare a rebuilt projection cannot | ||
| 715 | - /// bite here. | ||
| 716 | - /// | ||
| 717 | - /// A store-level write conflict is reported the same way as a miss: it | ||
| 718 | - /// means a concurrent write committed on this row, which is exactly the | ||
| 719 | - /// "reload and re-decide" case. | ||
| 720 | - /// | ||
| 721 | - /// A transition out of a live status (reject, cancel) hands the slot's | ||
| 722 | - /// `occupied` seat back, in this same transaction — the counter is the | ||
| 723 | - /// authority on whether the slot is taken, so it must move if and only if | ||
| 724 | - /// the status did. The decrement is `WHERE`-gated on the CAS having written | ||
| 725 | - /// something, so a lost race frees nothing. | ||
| 726 | - async fn save_if_unchanged( | ||
| 727 | - self, | ||
| 728 | - expected: &Appointment, | ||
| 729 | - db: &Database, | ||
| 730 | - ) -> Result<Option<Appointment>, AppError> { | ||
| 731 | - let frees_the_slot = expected.status.is_live() && !self.status.is_live(); | ||
| 732 | - let attempted = async { | ||
| 733 | - let mut result = db | ||
| 734 | - .query( | ||
| 735 | - "BEGIN TRANSACTION; | ||
| 736 | - LET $done = (UPDATE $id CONTENT $new \ | ||
| 737 | - WHERE status = $status \ | ||
| 738 | - AND proposed_starts_at = $proposed_starts_at \ | ||
| 739 | - AND proposed_ends_at = $proposed_ends_at \ | ||
| 740 | - AND decided_by = $decided_by); | ||
| 741 | - UPDATE $slot SET occupied = math::max([(occupied ?? 0) - 1, 0]) | ||
| 742 | - WHERE $frees AND array::len($done) > 0; | ||
| 743 | - RETURN $done; | ||
| 744 | - COMMIT TRANSACTION;", | ||
| 745 | - ) | ||
| 746 | - .bind(("slot", expected.slot.record())) | ||
| 747 | - .bind(("frees", frees_the_slot)) | ||
| 748 | - .bind(("id", expected.id.record())) | ||
| 749 | - .bind(("status", expected.status)) | ||
| 750 | - .bind(("proposed_starts_at", expected.proposed_starts_at)) | ||
| 751 | - .bind(("proposed_ends_at", expected.proposed_ends_at)) | ||
| 752 | - .bind(("decided_by", expected.decided_by.clone())) | ||
| 753 | - .bind(("new", self)) | ||
| 754 | - .await? | ||
| 755 | - .check()?; | ||
| 756 | - // BEGIN, the LET, and the counter write take a slot each. | ||
| 757 | - result.take::<Vec<Appointment>>(3) | ||
| 758 | - } | ||
| 759 | - .await; | ||
| 760 | - match attempted { | ||
| 761 | - Ok(rows) => Ok(rows.into_iter().next()), | ||
| 762 | - Err(err) if lost_the_race(&err) => Ok(None), | ||
| 763 | - Err(err) => Err(err.into()), | ||
| 764 | - } | ||
| 765 | - } | ||
| 766 | -} | ||
| 767 | - | ||
| 768 | -/// Every retry lost the row to another decision. A 409 rather than a 500: the | ||
| 769 | -/// caller's request was refused, nothing was half-applied, and re-reading the | ||
| 770 | -/// booking shows what happened to it. | ||
| 771 | -fn contended() -> AppError { | ||
| 772 | - AppError::Conflict("the appointment is being decided elsewhere") | ||
| 773 | } | 257 | } |
| 774 | 258 | ||
| 775 | #[cfg(test)] | 259 | #[cfg(test)] |
| @@ -781,11 +265,6 @@ mod tests { | |||
| 781 | Timestamp::from_millis(millis) | 265 | Timestamp::from_millis(millis) |
| 782 | } | 266 | } |
| 783 | 267 | ||
| 784 | - /// A window that has not opened yet — `book` refuses started ones. | ||
| 785 | - fn soon(offset: i64) -> Timestamp { | ||
| 786 | - at(Timestamp::now().as_millis() + offset) | ||
| 787 | - } | ||
| 788 | - | ||
| 789 | #[tokio::test] | 268 | #[tokio::test] |
| 790 | async fn reason_is_required_and_capped() { | 269 | async fn reason_is_required_and_capped() { |
| 791 | assert!(AppointmentReason::try_new("").is_err()); | 270 | assert!(AppointmentReason::try_new("").is_err()); |
| @@ -831,388 +310,4 @@ mod tests { | |||
| 831 | // Disjoint by a whole hour. | 310 | // Disjoint by a whole hour. |
| 832 | assert!(!Appointment::overlaps(at(0), at(30), at(90), at(120))); | 311 | assert!(!Appointment::overlaps(at(0), at(30), at(90), at(120))); |
| 833 | } | 312 | } |
| 834 | - | ||
| 835 | - #[tokio::test] | ||
| 836 | - async fn window_prefers_a_proposal_over_the_slot() { | ||
| 837 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 838 | - let teacher = UserId::from_key("t1"); | ||
| 839 | - let (starts_at, ends_at) = (soon(60_000), soon(120_000)); | ||
| 840 | - let slot = AppointmentSlot::create(&teacher, starts_at, ends_at, None, &db) | ||
| 841 | - .await | ||
| 842 | - .unwrap(); | ||
| 843 | - let mut appointment = Appointment::book( | ||
| 844 | - slot.get_id(), | ||
| 845 | - &UserId::from_key("s1"), | ||
| 846 | - AppointmentReason::try_new("ödev").unwrap(), | ||
| 847 | - &db, | ||
| 848 | - ) | ||
| 849 | - .await | ||
| 850 | - .unwrap(); | ||
| 851 | - | ||
| 852 | - assert_eq!(appointment.window(&slot), (starts_at, ends_at)); | ||
| 853 | - appointment.proposed_starts_at = Some(at(5_000)); | ||
| 854 | - appointment.proposed_ends_at = Some(at(6_000)); | ||
| 855 | - assert_eq!(appointment.window(&slot), (at(5_000), at(6_000))); | ||
| 856 | - } | ||
| 857 | - | ||
| 858 | - /// A slot whose window already opened is unbookable: `cancel` would refuse | ||
| 859 | - /// to undo the resulting meeting, so the booking would be stuck for good. | ||
| 860 | - #[tokio::test] | ||
| 861 | - async fn a_started_slot_cannot_be_booked() { | ||
| 862 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 863 | - let teacher = UserId::from_key("t1"); | ||
| 864 | - let reason = || AppointmentReason::try_new("görüşme").unwrap(); | ||
| 865 | - let started = AppointmentSlot::create(&teacher, soon(-30_000), soon(60_000), None, &db) | ||
| 866 | - .await | ||
| 867 | - .unwrap(); | ||
| 868 | - assert!(matches!( | ||
| 869 | - Appointment::book(started.get_id(), &UserId::from_key("s1"), reason(), &db).await, | ||
| 870 | - Err(AppError::Conflict("the slot has already started")) | ||
| 871 | - )); | ||
| 872 | - | ||
| 873 | - let upcoming = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) | ||
| 874 | - .await | ||
| 875 | - .unwrap(); | ||
| 876 | - assert!( | ||
| 877 | - Appointment::book(upcoming.get_id(), &UserId::from_key("s1"), reason(), &db) | ||
| 878 | - .await | ||
| 879 | - .is_ok() | ||
| 880 | - ); | ||
| 881 | - } | ||
| 882 | - | ||
| 883 | - /// Approval judges the *effective* window, so a proposal whose time has | ||
| 884 | - /// come and gone cannot be accepted — the meeting would be uncancellable. | ||
| 885 | - #[tokio::test] | ||
| 886 | - async fn a_started_proposal_cannot_be_accepted() { | ||
| 887 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 888 | - let teacher = UserId::from_key("t1"); | ||
| 889 | - let student = UserId::from_key("s1"); | ||
| 890 | - let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) | ||
| 891 | - .await | ||
| 892 | - .unwrap(); | ||
| 893 | - let booking = Appointment::book( | ||
| 894 | - slot.get_id(), | ||
| 895 | - &student, | ||
| 896 | - AppointmentReason::try_new("görüşme").unwrap(), | ||
| 897 | - &db, | ||
| 898 | - ) | ||
| 899 | - .await | ||
| 900 | - .unwrap(); | ||
| 901 | - | ||
| 902 | - // Proposing a window that already opened is refused up front — the | ||
| 903 | - // handler's 60s skew grace would otherwise let one through. | ||
| 904 | - assert!(matches!( | ||
| 905 | - Appointment::propose(booking.get_id(), soon(-30_000), soon(30_000), &teacher, &db) | ||
| 906 | - .await, | ||
| 907 | - Err(AppError::Conflict("that time has already started")) | ||
| 908 | - )); | ||
| 909 | - // And approval judges the effective window again, for a proposal whose | ||
| 910 | - // time simply passed while it stood: forced onto the row directly, | ||
| 911 | - // since `propose` no longer mints one. | ||
| 912 | - let current = Appointment::read(booking.get_id(), &db) | ||
| 913 | - .await | ||
| 914 | - .unwrap() | ||
| 915 | - .unwrap(); | ||
| 916 | - let (passed_starts_at, passed_ends_at) = (soon(-30_000), soon(30_000)); | ||
| 917 | - let mut standing = current.clone(); | ||
| 918 | - standing.proposed_starts_at = Some(passed_starts_at); | ||
| 919 | - standing.proposed_ends_at = Some(passed_ends_at); | ||
| 920 | - standing | ||
| 921 | - .save_if_unchanged(¤t, &db) | ||
| 922 | - .await | ||
| 923 | - .unwrap() | ||
| 924 | - .unwrap(); | ||
| 925 | - assert!(matches!( | ||
| 926 | - Appointment::accept_proposal( | ||
| 927 | - booking.get_id(), | ||
| 928 | - &student, | ||
| 929 | - passed_starts_at, | ||
| 930 | - passed_ends_at, | ||
| 931 | - &db | ||
| 932 | - ) | ||
| 933 | - .await, | ||
| 934 | - Err(AppError::Conflict("that time has already started")) | ||
| 935 | - )); | ||
| 936 | - // Refused, not half-applied: still pending, still decidable at a time | ||
| 937 | - // that can actually happen. | ||
| 938 | - let after = Appointment::read(booking.get_id(), &db).await.unwrap(); | ||
| 939 | - assert_eq!(after.unwrap().get_status(), AppointmentStatus::Pending); | ||
| 940 | - let (starts_at, ends_at) = (soon(60_000), soon(120_000)); | ||
| 941 | - Appointment::propose(booking.get_id(), starts_at, ends_at, &teacher, &db) | ||
| 942 | - .await | ||
| 943 | - .unwrap(); | ||
| 944 | - // Accepting a window that is *not* the standing proposal is refused — | ||
| 945 | - // the pin is what the requester saw, not a request to move the meeting. | ||
| 946 | - assert!(matches!( | ||
| 947 | - Appointment::accept_proposal( | ||
| 948 | - booking.get_id(), | ||
| 949 | - &student, | ||
| 950 | - passed_starts_at, | ||
| 951 | - passed_ends_at, | ||
| 952 | - &db | ||
| 953 | - ) | ||
| 954 | - .await, | ||
| 955 | - Err(AppError::Conflict( | ||
| 956 | - "the proposed time has changed; \ | ||
| 957 | - re-read the booking and accept the new one" | ||
| 958 | - )) | ||
| 959 | - )); | ||
| 960 | - let accepted = | ||
| 961 | - Appointment::accept_proposal(booking.get_id(), &student, starts_at, ends_at, &db) | ||
| 962 | - .await | ||
| 963 | - .unwrap(); | ||
| 964 | - assert_eq!(accepted.get_status(), AppointmentStatus::Approved); | ||
| 965 | - } | ||
| 966 | - | ||
| 967 | - /// The compare-and-set every decision writes through — the guard against a | ||
| 968 | - /// decision built on a snapshot that has since moved, which no lock taken | ||
| 969 | - /// after the read can catch. The interleaving that matters is the one a | ||
| 970 | - /// status-only guard would miss, since `propose` leaves a pending booking | ||
| 971 | - /// pending. | ||
| 972 | - /// | ||
| 973 | - /// Deliberately sequential: the mem engine answers `Ok` to a write it then | ||
| 974 | - /// drops, so a `join!` of two decisions proves nothing. This drives the | ||
| 975 | - /// primitive itself with the exact stale snapshot the race produces. | ||
| 976 | - #[tokio::test] | ||
| 977 | - async fn a_decision_built_on_a_stale_snapshot_never_lands() { | ||
| 978 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 979 | - let teacher = UserId::from_key("t1"); | ||
| 980 | - let student = UserId::from_key("s1"); | ||
| 981 | - let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) | ||
| 982 | - .await | ||
| 983 | - .unwrap(); | ||
| 984 | - let booking = Appointment::book( | ||
| 985 | - slot.get_id(), | ||
| 986 | - &student, | ||
| 987 | - AppointmentReason::try_new("görüşme").unwrap(), | ||
| 988 | - &db, | ||
| 989 | - ) | ||
| 990 | - .await | ||
| 991 | - .unwrap(); | ||
| 992 | - | ||
| 993 | - // One transaction counter-proposes. A second concurrent transaction | ||
| 994 | - // is still holding the snapshot it read before that — same id, same | ||
| 995 | - // `pending` status. | ||
| 996 | - let stale = booking.clone(); | ||
| 997 | - let (proposed_starts_at, proposed_ends_at) = (soon(180_000), soon(240_000)); | ||
| 998 | - Appointment::propose( | ||
| 999 | - booking.get_id(), | ||
| 1000 | - proposed_starts_at, | ||
| 1001 | - proposed_ends_at, | ||
| 1002 | - &teacher, | ||
| 1003 | - &db, | ||
| 1004 | - ) | ||
| 1005 | - .await | ||
| 1006 | - .unwrap(); | ||
| 1007 | - | ||
| 1008 | - let mut late = stale.clone(); | ||
| 1009 | - late.status = AppointmentStatus::Approved; | ||
| 1010 | - late.decided_by = Some(teacher.clone()); | ||
| 1011 | - assert!(late.save_if_unchanged(&stale, &db).await.unwrap().is_none()); | ||
| 1012 | - | ||
| 1013 | - // The proposal survived: the row was not confirmed at the slot's old | ||
| 1014 | - // window behind the requester's back. | ||
| 1015 | - let after = Appointment::read(booking.get_id(), &db) | ||
| 1016 | - .await | ||
| 1017 | - .unwrap() | ||
| 1018 | - .unwrap(); | ||
| 1019 | - assert_eq!(after.get_status(), AppointmentStatus::Pending); | ||
| 1020 | - assert_eq!(after.get_proposed_starts_at(), Some(proposed_starts_at)); | ||
| 1021 | - assert_eq!(after.get_proposed_ends_at(), Some(proposed_ends_at)); | ||
| 1022 | - assert_eq!(after.get_decided_by(), None); | ||
| 1023 | - | ||
| 1024 | - // And the same decision, re-validated against the row as it now | ||
| 1025 | - // stands, does land — a miss is a retry signal, not a wall. | ||
| 1026 | - let mut fresh = after.clone(); | ||
| 1027 | - fresh.status = AppointmentStatus::Approved; | ||
| 1028 | - fresh.decided_by = Some(teacher.clone()); | ||
| 1029 | - let saved = fresh | ||
| 1030 | - .save_if_unchanged(&after, &db) | ||
| 1031 | - .await | ||
| 1032 | - .unwrap() | ||
| 1033 | - .expect("a current snapshot must write"); | ||
| 1034 | - assert_eq!(saved.get_status(), AppointmentStatus::Approved); | ||
| 1035 | - assert_eq!(saved.get_proposed_starts_at(), Some(proposed_starts_at)); | ||
| 1036 | - } | ||
| 1037 | - | ||
| 1038 | - /// What the slot row itself says about being taken — the authority every | ||
| 1039 | - /// gate now reads. | ||
| 1040 | - async fn occupied(slot: &AppointmentSlotId, db: &Database) -> i64 { | ||
| 1041 | - let mut result = db | ||
| 1042 | - .query("SELECT VALUE (occupied ?? 0) FROM $slot") | ||
| 1043 | - .bind(("slot", slot.record())) | ||
| 1044 | - .await | ||
| 1045 | - .unwrap() | ||
| 1046 | - .check() | ||
| 1047 | - .unwrap(); | ||
| 1048 | - result.take::<Vec<i64>>(0).unwrap()[0] | ||
| 1049 | - } | ||
| 1050 | - | ||
| 1051 | - /// The double-book race with the lock taken out of the picture: a second | ||
| 1052 | - /// booking arrives at the database with nothing between it and the slot but | ||
| 1053 | - /// the claim's own `WHERE`, which is what must refuse it. Driven | ||
| 1054 | - /// through [`cap::claim`] directly rather than through a `join!`, since the | ||
| 1055 | - /// in-memory engine can drop one of two concurrent writes to a record and | ||
| 1056 | - /// still answer `Ok` — this asks the primitive the exact question the race | ||
| 1057 | - /// asks it. | ||
| 1058 | - /// | ||
| 1059 | - /// Deleting the `WHERE (occupied ?? 0) < $cap` from `cap::claim` makes the | ||
| 1060 | - /// second claim succeed and this fail (mutation-proved). | ||
| 1061 | - #[tokio::test] | ||
| 1062 | - async fn a_concurrent_claim_cannot_take_a_booked_slot() { | ||
| 1063 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 1064 | - let teacher = UserId::from_key("t1"); | ||
| 1065 | - let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) | ||
| 1066 | - .await | ||
| 1067 | - .unwrap(); | ||
| 1068 | - assert_eq!(occupied(slot.get_id(), &db).await, 0); | ||
| 1069 | - | ||
| 1070 | - Appointment::book( | ||
| 1071 | - slot.get_id(), | ||
| 1072 | - &UserId::from_key("s1"), | ||
| 1073 | - AppointmentReason::try_new("görüşme").unwrap(), | ||
| 1074 | - &db, | ||
| 1075 | - ) | ||
| 1076 | - .await | ||
| 1077 | - .unwrap(); | ||
| 1078 | - assert_eq!(occupied(slot.get_id(), &db).await, 1); | ||
| 1079 | - | ||
| 1080 | - assert!( | ||
| 1081 | - !cap::claim(&slot.get_id().record(), SLOT_OCCUPIED_FIELD, 1, &db) | ||
| 1082 | - .await | ||
| 1083 | - .unwrap(), | ||
| 1084 | - "the slot's seat must already be taken" | ||
| 1085 | - ); | ||
| 1086 | - // And the racer's refusal left the stored state alone: one booking, one | ||
| 1087 | - // seat — not two of either. | ||
| 1088 | - assert_eq!(occupied(slot.get_id(), &db).await, 1); | ||
| 1089 | - assert_eq!( | ||
| 1090 | - Appointment::list_for_slot(slot.get_id(), &db) | ||
| 1091 | - .await | ||
| 1092 | - .unwrap() | ||
| 1093 | - .len(), | ||
| 1094 | - 1 | ||
| 1095 | - ); | ||
| 1096 | - } | ||
| 1097 | - | ||
| 1098 | - /// The seat and the booking row now land in one transaction, so the stored | ||
| 1099 | - /// state must move together: a taken slot refuses the next requester with | ||
| 1100 | - /// the counter *and* the row list untouched — a refusal that had already | ||
| 1101 | - /// bumped the counter would strand the slot forever. | ||
| 1102 | - #[tokio::test] | ||
| 1103 | - async fn a_refused_booking_moves_nothing() { | ||
| 1104 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 1105 | - let teacher = UserId::from_key("t1"); | ||
| 1106 | - let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) | ||
| 1107 | - .await | ||
| 1108 | - .unwrap(); | ||
| 1109 | - let reason = || AppointmentReason::try_new("görüşme").unwrap(); | ||
| 1110 | - | ||
| 1111 | - Appointment::book(slot.get_id(), &UserId::from_key("s1"), reason(), &db) | ||
| 1112 | - .await | ||
| 1113 | - .unwrap(); | ||
| 1114 | - assert_eq!(occupied(slot.get_id(), &db).await, 1); | ||
| 1115 | - | ||
| 1116 | - let refused = | ||
| 1117 | - Appointment::book(slot.get_id(), &UserId::from_key("s2"), reason(), &db).await; | ||
| 1118 | - assert!( | ||
| 1119 | - matches!(refused, Err(AppError::Conflict(_))), | ||
| 1120 | - "the slot is taken" | ||
| 1121 | - ); | ||
| 1122 | - assert_eq!( | ||
| 1123 | - occupied(slot.get_id(), &db).await, | ||
| 1124 | - 1, | ||
| 1125 | - "the refusal took no seat" | ||
| 1126 | - ); | ||
| 1127 | - assert_eq!( | ||
| 1128 | - Appointment::list_for_slot(slot.get_id(), &db) | ||
| 1129 | - .await | ||
| 1130 | - .unwrap() | ||
| 1131 | - .len(), | ||
| 1132 | - 1, | ||
| 1133 | - "and wrote no row" | ||
| 1134 | - ); | ||
| 1135 | - } | ||
| 1136 | - | ||
| 1137 | - /// Cancelling gives the seat back in the same transaction as the status | ||
| 1138 | - /// flip — the counter is the only thing that says a slot is free, so a | ||
| 1139 | - /// cancel that moved one without the other would strand the slot forever. | ||
| 1140 | - #[tokio::test] | ||
| 1141 | - async fn cancelling_hands_the_seat_back_with_the_status() { | ||
| 1142 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 1143 | - let teacher = UserId::from_key("t1"); | ||
| 1144 | - let student = UserId::from_key("s1"); | ||
| 1145 | - let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) | ||
| 1146 | - .await | ||
| 1147 | - .unwrap(); | ||
| 1148 | - let booking = Appointment::book( | ||
| 1149 | - slot.get_id(), | ||
| 1150 | - &student, | ||
| 1151 | - AppointmentReason::try_new("görüşme").unwrap(), | ||
| 1152 | - &db, | ||
| 1153 | - ) | ||
| 1154 | - .await | ||
| 1155 | - .unwrap(); | ||
| 1156 | - Appointment::approve(booking.get_id(), &teacher, &db) | ||
| 1157 | - .await | ||
| 1158 | - .unwrap(); | ||
| 1159 | - assert_eq!(occupied(slot.get_id(), &db).await, 1, "approval holds it"); | ||
| 1160 | - | ||
| 1161 | - Appointment::cancel(booking.get_id(), &student, None, &db) | ||
| 1162 | - .await | ||
| 1163 | - .unwrap(); | ||
| 1164 | - assert_eq!(occupied(slot.get_id(), &db).await, 0); | ||
| 1165 | - // Cancelling twice is refused, so the seat cannot go back twice either. | ||
| 1166 | - assert!( | ||
| 1167 | - Appointment::cancel(booking.get_id(), &student, None, &db) | ||
| 1168 | - .await | ||
| 1169 | - .is_err() | ||
| 1170 | - ); | ||
| 1171 | - assert_eq!(occupied(slot.get_id(), &db).await, 0); | ||
| 1172 | - assert!( | ||
| 1173 | - Appointment::book( | ||
| 1174 | - slot.get_id(), | ||
| 1175 | - &UserId::from_key("s2"), | ||
| 1176 | - AppointmentReason::try_new("görüşme").unwrap(), | ||
| 1177 | - &db | ||
| 1178 | - ) | ||
| 1179 | - .await | ||
| 1180 | - .is_ok() | ||
| 1181 | - ); | ||
| 1182 | - assert_eq!(occupied(slot.get_id(), &db).await, 1); | ||
| 1183 | - } | ||
| 1184 | - | ||
| 1185 | - /// Occupancy frees on reject, so the slot can be re-booked. | ||
| 1186 | - #[tokio::test] | ||
| 1187 | - async fn rejecting_frees_the_slot_for_re_booking() { | ||
| 1188 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 1189 | - let teacher = UserId::from_key("t1"); | ||
| 1190 | - let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) | ||
| 1191 | - .await | ||
| 1192 | - .unwrap(); | ||
| 1193 | - let reason = || AppointmentReason::try_new("görüşme").unwrap(); | ||
| 1194 | - | ||
| 1195 | - let first = Appointment::book(slot.get_id(), &UserId::from_key("s1"), reason(), &db) | ||
| 1196 | - .await | ||
| 1197 | - .unwrap(); | ||
| 1198 | - assert!(matches!( | ||
| 1199 | - Appointment::book(slot.get_id(), &UserId::from_key("s2"), reason(), &db).await, | ||
| 1200 | - Err(AppError::Conflict(_)) | ||
| 1201 | - )); | ||
| 1202 | - // The live booking also blocks the slot delete. | ||
| 1203 | - assert!(matches!( | ||
| 1204 | - slot.clone().delete(&db).await, | ||
| 1205 | - Err(AppError::Conflict(_)) | ||
| 1206 | - )); | ||
| 1207 | - | ||
| 1208 | - Appointment::reject(first.get_id(), &teacher, None, &db) | ||
| 1209 | - .await | ||
| 1210 | - .unwrap(); | ||
| 1211 | - assert_eq!(occupied(slot.get_id(), &db).await, 0); | ||
| 1212 | - let second = Appointment::book(slot.get_id(), &UserId::from_key("s2"), reason(), &db) | ||
| 1213 | - .await | ||
| 1214 | - .unwrap(); | ||
| 1215 | - assert_eq!(second.get_status(), AppointmentStatus::Pending); | ||
| 1216 | - assert_eq!(occupied(slot.get_id(), &db).await, 1); | ||
| 1217 | - } | ||
| 1218 | } | 313 | } |
src/domain/appointment_slot.rsmodified+7 -4
| @@ -18,7 +18,8 @@ use crate::constant::{ | |||
| 18 | APPOINTMENT_SLOT_TABLE, MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK, ROLES, | 18 | APPOINTMENT_SLOT_TABLE, MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK, ROLES, |
| 19 | }; | 19 | }; |
| 20 | use crate::database::{Database, transaction_with_retry}; | 20 | use crate::database::{Database, transaction_with_retry}; |
| 21 | -use crate::domain::appointment::{APPOINTMENT_LOCK, Appointment}; | 21 | +use crate::domain::appointment::Appointment; |
| 22 | +use crate::service::appointment::APPOINTMENT_LOCK; | ||
| 22 | use crate::db::cap; | 23 | use crate::db::cap; |
| 23 | use crate::domain::monotonic_id::next_ulid; | 24 | use crate::domain::monotonic_id::next_ulid; |
| 24 | use crate::domain::role::Role; | 25 | use crate::domain::role::Role; |
| @@ -269,7 +270,8 @@ impl AppointmentSlot { | |||
| 269 | /// Does the teacher already have a published slot whose window collides with | 270 | /// Does the teacher already have a published slot whose window collides with |
| 270 | /// `[starts_at, ends_at)`? Half-open, so a slot ending exactly where the new | 271 | /// `[starts_at, ends_at)`? Half-open, so a slot ending exactly where the new |
| 271 | /// one starts is *not* a conflict — that is how a teacher's hour is carved | 272 | /// one starts is *not* a conflict — that is how a teacher's hour is carved |
| 272 | - /// into back-to-back slots. Caller must hold [`APPOINTMENT_LOCK`] for the | 273 | + /// into back-to-back slots. Caller must hold |
| 274 | + /// [`crate::service::appointment::APPOINTMENT_LOCK`] for the | ||
| 273 | /// answer to still be true by the time the insert lands. | 275 | /// answer to still be true by the time the insert lands. |
| 274 | async fn conflicts_existing( | 276 | async fn conflicts_existing( |
| 275 | teacher: &UserId, | 277 | teacher: &UserId, |
| @@ -296,7 +298,8 @@ impl AppointmentSlot { | |||
| 296 | /// window in the batch necessarily overlaps the envelope spanning them all, | 298 | /// window in the batch necessarily overlaps the envelope spanning them all, |
| 297 | /// so filtering the envelope and comparing in memory is exactly the | 299 | /// so filtering the envelope and comparing in memory is exactly the |
| 298 | /// per-window [`conflicts_existing`](Self::conflicts_existing) check, | 300 | /// per-window [`conflicts_existing`](Self::conflicts_existing) check, |
| 299 | - /// hoisted out of the loop — which is what keeps [`APPOINTMENT_LOCK`] down | 301 | + /// hoisted out of the loop — which is what keeps |
| 302 | + /// [`crate::service::appointment::APPOINTMENT_LOCK`] down | ||
| 300 | /// to two round trips instead of one per occurrence. | 303 | /// to two round trips instead of one per occurrence. |
| 301 | async fn windows_in_span( | 304 | async fn windows_in_span( |
| 302 | teacher: &UserId, | 305 | teacher: &UserId, |
| @@ -459,7 +462,7 @@ impl AppointmentSlot { | |||
| 459 | /// calendar a requester browses. | 462 | /// calendar a requester browses. |
| 460 | /// | 463 | /// |
| 461 | /// The bound is `starts_at`, not `ends_at`, so that this window is exactly | 464 | /// The bound is `starts_at`, not `ends_at`, so that this window is exactly |
| 462 | - /// the one [`Appointment::book`] accepts: a slot already underway is | 465 | + /// the one [`crate::service::appointment::book`] accepts: a slot already underway is |
| 463 | /// unbookable (`cancel` could never undo the booking), and offering it would | 466 | /// unbookable (`cancel` could never undo the booking), and offering it would |
| 464 | /// be a calendar entry that can only answer `409`. The publish-time 60s skew | 467 | /// be a calendar entry that can only answer `409`. The publish-time 60s skew |
| 465 | /// grace deliberately does not apply here either — `book` does not grant it, | 468 | /// grace deliberately does not apply here either — `book` does not grant it, |
src/domain/user.rsmodified+8 -7
| @@ -1078,8 +1078,9 @@ mod tests { | |||
| 1078 | /// no route can reach and a seat nothing can ever free. | 1078 | /// no route can reach and a seat nothing can ever free. |
| 1079 | #[tokio::test] | 1079 | #[tokio::test] |
| 1080 | async fn a_demotion_withdraws_the_calendar_and_settles_its_bookings() { | 1080 | async fn a_demotion_withdraws_the_calendar_and_settles_its_bookings() { |
| 1081 | - use crate::domain::appointment::{Appointment, AppointmentReason}; | 1081 | + use crate::domain::appointment::AppointmentReason; |
| 1082 | use crate::domain::appointment_slot::AppointmentSlot; | 1082 | use crate::domain::appointment_slot::AppointmentSlot; |
| 1083 | + use crate::service::appointment; | ||
| 1083 | 1084 | ||
| 1084 | let db = init_mem().await.unwrap(); | 1085 | let db = init_mem().await.unwrap(); |
| 1085 | let staff = |name: &'static str, db: Database| async move { | 1086 | let staff = |name: &'static str, db: Database| async move { |
| @@ -1109,16 +1110,16 @@ mod tests { | |||
| 1109 | let agreed = slot(&teacher, 300_000, db.clone()).await; | 1110 | let agreed = slot(&teacher, 300_000, db.clone()).await; |
| 1110 | let kept = slot(&other, 60_000, db.clone()).await; | 1111 | let kept = slot(&other, 60_000, db.clone()).await; |
| 1111 | 1112 | ||
| 1112 | - let pending = Appointment::book(asked.get_id(), student.get_id(), reason(), &db) | 1113 | + let pending = appointment::book(&db, asked.get_id(), student.get_id(), reason()) |
| 1113 | .await | 1114 | .await |
| 1114 | .unwrap(); | 1115 | .unwrap(); |
| 1115 | - let approved = Appointment::book(agreed.get_id(), student.get_id(), reason(), &db) | 1116 | + let approved = appointment::book(&db, agreed.get_id(), student.get_id(), reason()) |
| 1116 | .await | 1117 | .await |
| 1117 | .unwrap(); | 1118 | .unwrap(); |
| 1118 | - Appointment::approve(approved.get_id(), teacher.get_id(), &db) | 1119 | + appointment::approve(&db, approved.get_id(), teacher.get_id()) |
| 1119 | .await | 1120 | .await |
| 1120 | .unwrap(); | 1121 | .unwrap(); |
| 1121 | - let elsewhere = Appointment::book(kept.get_id(), student.get_id(), reason(), &db) | 1122 | + let elsewhere = appointment::book(&db, kept.get_id(), student.get_id(), reason()) |
| 1122 | .await | 1123 | .await |
| 1123 | .unwrap(); | 1124 | .unwrap(); |
| 1124 | 1125 | ||
| @@ -1143,7 +1144,7 @@ mod tests { | |||
| 1143 | // Both bookings — the pending request and the confirmed meeting — ended | 1144 | // Both bookings — the pending request and the confirmed meeting — ended |
| 1144 | // in a state their requester can still read, saying who dropped it. | 1145 | // in a state their requester can still read, saying who dropped it. |
| 1145 | for booking in [&pending, &approved] { | 1146 | for booking in [&pending, &approved] { |
| 1146 | - let after = Appointment::read(booking.get_id(), &db) | 1147 | + let after = appointment::read(&db, booking.get_id()) |
| 1147 | .await | 1148 | .await |
| 1148 | .unwrap() | 1149 | .unwrap() |
| 1149 | .expect("the requester keeps the row"); | 1150 | .expect("the requester keeps the row"); |
| @@ -1173,7 +1174,7 @@ mod tests { | |||
| 1173 | 1 | 1174 | 1 |
| 1174 | ); | 1175 | ); |
| 1175 | assert_eq!( | 1176 | assert_eq!( |
| 1176 | - Appointment::read(elsewhere.get_id(), &db) | 1177 | + appointment::read(&db, elsewhere.get_id()) |
| 1177 | .await | 1178 | .await |
| 1178 | .unwrap() | 1179 | .unwrap() |
| 1179 | .unwrap() | 1180 | .unwrap() |
src/service/appointment.rsadded+763 -0
| @@ -0,0 +1,763 @@ | |||
| 1 | +//! Appointment workflows: booking, the approve/reject/cancel decisions, and | ||
| 2 | +//! counter-proposals. Reads, listings, the overlap probe, and the | ||
| 3 | +//! compare-and-set live in [`crate::db::appointment`]; the slot's seat is | ||
| 4 | +//! [`crate::db::cap`]'s claim. | ||
| 5 | +//! | ||
| 6 | +//! The overlap guarantee is [`APPOINTMENT_LOCK`]: booking and approval hold | ||
| 7 | +//! it across "is this person already committed at that time" and the write | ||
| 8 | +//! that commits — a predicate over *other* rows that no single-record | ||
| 9 | +//! conditional write can decide. | ||
| 10 | + | ||
| 11 | +use tokio::sync::Mutex; | ||
| 12 | + | ||
| 13 | +use crate::constant::{CAS_UPDATE_RETRIES, SLOT_OCCUPIED_FIELD}; | ||
| 14 | +use crate::database::Database; | ||
| 15 | +use crate::db::appointment; | ||
| 16 | +use crate::db::cap; | ||
| 17 | +use crate::domain::appointment::{ | ||
| 18 | + Appointment, AppointmentId, AppointmentReason, AppointmentStatus, | ||
| 19 | +}; | ||
| 20 | +use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId}; | ||
| 21 | +use crate::domain::timestamp::Timestamp; | ||
| 22 | +use crate::domain::user::UserId; | ||
| 23 | +use crate::error::{AppError, ValidationError}; | ||
| 24 | + | ||
| 25 | +/// Serializes the **overlap** check and the write it authorizes — nothing else. | ||
| 26 | +/// "Is this teacher (or this requester) already committed at that time" is a | ||
| 27 | +/// predicate over other appointment rows, and SurrealDB does not conflict-check | ||
| 28 | +/// a cross-record read against a concurrent insert, so the check and its write | ||
| 29 | +/// have to be one atomic step, and this lock is the only thing that makes them | ||
| 30 | +/// one. Occupancy is no longer its business: that is the slot's `occupied` | ||
| 31 | +/// counter, a conditional single-record write the store decides. | ||
| 32 | +/// | ||
| 33 | +/// So this is load-bearing, not a convenience: an approval path that does not | ||
| 34 | +/// take it can double-book a teacher, as the domain's module doc records. | ||
| 35 | +/// | ||
| 36 | +/// Lock order: taken *before* `cap`'s `CLAIM_LOCK` (booking claims a slot while | ||
| 37 | +/// holding this) and never the other way round. No path ever holds this | ||
| 38 | +/// together with `ENROLL_LOCK`, | ||
| 39 | +/// `TERM_LOCK`, `EXAM_LOCK`, or `PRESENCE_LOCK` — appointments | ||
| 40 | +/// touch no roster, term, event seat, or exam room, and none of those touch | ||
| 41 | +/// appointments — so they cannot deadlock. Should a future path ever need two, | ||
| 42 | +/// take this one *last*. | ||
| 43 | +// corner-cut: global lock; per-teacher locks if appointment traffic ever grows | ||
| 44 | +// enough for the contention to matter. | ||
| 45 | +pub(crate) static APPOINTMENT_LOCK: Mutex<()> = Mutex::const_new(()); | ||
| 46 | + | ||
| 47 | +/// Request `slot`. Lands `pending`: publishing availability is not consent | ||
| 48 | +/// to a specific person and topic. | ||
| 49 | +/// | ||
| 50 | +/// Refused (409) when the slot's window has already opened, when it is | ||
| 51 | +/// already taken, or when the requester is already committed elsewhere at | ||
| 52 | +/// that time. The slot is taken by [`cap::claim_and_create`], which writes | ||
| 53 | +/// the booking in the *same transaction* as the seat — a conditional | ||
| 54 | +/// single-record write, so two racing requests cannot both find it free | ||
| 55 | +/// however they interleave, and a crash between the two can no longer leave | ||
| 56 | +/// the slot occupied by a booking that does not exist. The requester's own | ||
| 57 | +/// overlap is the lock's part. | ||
| 58 | +pub async fn book( | ||
| 59 | + db: &Database, | ||
| 60 | + slot: &AppointmentSlotId, | ||
| 61 | + requester: &UserId, | ||
| 62 | + reason: AppointmentReason, | ||
| 63 | +) -> Result<Appointment, AppError> { | ||
| 64 | + let _guard = APPOINTMENT_LOCK.lock().await; | ||
| 65 | + let slot_row = AppointmentSlot::read(slot, db) | ||
| 66 | + .await? | ||
| 67 | + .ok_or(AppError::NotFound)?; | ||
| 68 | + // A window that has opened is history, not a plan: `cancel` refuses to | ||
| 69 | + // call off a meeting that started, so such a booking would be stuck | ||
| 70 | + // forever. `list_upcoming` is bounded on this same `starts_at`, so the | ||
| 71 | + // calendar never offers one — but a slot whose start passed while the | ||
| 72 | + // page was open, or an id kept from an earlier read, still reaches here. | ||
| 73 | + // The publish-time 60s skew grace does not apply on either side. | ||
| 74 | + if slot_row.get_starts_at().as_millis() <= Timestamp::now().as_millis() { | ||
| 75 | + return Err(AppError::Conflict("the slot has already started")); | ||
| 76 | + } | ||
| 77 | + // The teacher's own overlaps are not checked here — an approved | ||
| 78 | + // meeting of theirs elsewhere is the *approval*'s business, and | ||
| 79 | + // refusing the request outright would hide a slot they published. | ||
| 80 | + if appointment::conflicts( | ||
| 81 | + db, | ||
| 82 | + requester, | ||
| 83 | + requester, | ||
| 84 | + slot_row.get_starts_at(), | ||
| 85 | + slot_row.get_ends_at(), | ||
| 86 | + None, | ||
| 87 | + ) | ||
| 88 | + .await? | ||
| 89 | + { | ||
| 90 | + return Err(AppError::Conflict( | ||
| 91 | + "you already have an appointment at that time", | ||
| 92 | + )); | ||
| 93 | + } | ||
| 94 | + // Last, so nothing above can refuse *after* the slot was taken. A slot | ||
| 95 | + // deleted since the read above is gone, not full — the claim's `WHERE` | ||
| 96 | + // finds no row either way, so the distinction is re-read rather than | ||
| 97 | + // guessed. | ||
| 98 | + let seat = slot.record(); | ||
| 99 | + let appointment_row = Appointment { | ||
| 100 | + id: AppointmentId::generate(), | ||
| 101 | + slot: slot.clone(), | ||
| 102 | + requester: requester.clone(), | ||
| 103 | + status: AppointmentStatus::Pending, | ||
| 104 | + reason, | ||
| 105 | + proposed_starts_at: None, | ||
| 106 | + proposed_ends_at: None, | ||
| 107 | + proposed_by: None, | ||
| 108 | + decided_by: None, | ||
| 109 | + cancelled_by: None, | ||
| 110 | + cancel_reason: None, | ||
| 111 | + reject_reason: None, | ||
| 112 | + created_at: Timestamp::now(), | ||
| 113 | + }; | ||
| 114 | + match cap::claim_and_create( | ||
| 115 | + &seat, | ||
| 116 | + SLOT_OCCUPIED_FIELD, | ||
| 117 | + 1, | ||
| 118 | + &appointment_row.id.record(), | ||
| 119 | + &appointment_row, | ||
| 120 | + db, | ||
| 121 | + ) | ||
| 122 | + .await? | ||
| 123 | + { | ||
| 124 | + cap::Claimed::Made(created) => Ok(created), | ||
| 125 | + cap::Claimed::Full => { | ||
| 126 | + if AppointmentSlot::read(slot, db).await?.is_none() { | ||
| 127 | + return Err(AppError::NotFound); | ||
| 128 | + } | ||
| 129 | + Err(AppError::Conflict("the slot is already booked")) | ||
| 130 | + } | ||
| 131 | + // The id is a freshly minted ULID on a table with no UNIQUE index, | ||
| 132 | + // so no rival can have aimed at it. | ||
| 133 | + cap::Claimed::Duplicate => Err(AppError::Internal("appointment id collided".into())), | ||
| 134 | + } | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +/// The row, for callers that only inspect it — the web layer's authorization | ||
| 138 | +/// gates read through here. | ||
| 139 | +pub async fn read( | ||
| 140 | + db: &Database, | ||
| 141 | + id: &AppointmentId, | ||
| 142 | +) -> Result<Option<Appointment>, AppError> { | ||
| 143 | + appointment::read(db, id).await | ||
| 144 | +} | ||
| 145 | + | ||
| 146 | +/// The requester's bookings, newest first — the web layer's paging read. | ||
| 147 | +pub async fn list_for_requester( | ||
| 148 | + db: &Database, | ||
| 149 | + requester: &UserId, | ||
| 150 | + limit: Option<i64>, | ||
| 151 | + offset: i64, | ||
| 152 | +) -> Result<(Vec<Appointment>, i64), AppError> { | ||
| 153 | + appointment::list_for_requester(db, requester, limit, offset).await | ||
| 154 | +} | ||
| 155 | + | ||
| 156 | +/// Every booking aimed at `teacher`, newest first — the request inbox. | ||
| 157 | +pub async fn list_for_teacher( | ||
| 158 | + db: &Database, | ||
| 159 | + teacher: &UserId, | ||
| 160 | + limit: Option<i64>, | ||
| 161 | + offset: i64, | ||
| 162 | +) -> Result<(Vec<Appointment>, i64), AppError> { | ||
| 163 | + appointment::list_for_teacher(db, teacher, limit, offset).await | ||
| 164 | +} | ||
| 165 | + | ||
| 166 | +/// Confirm the meeting at the slot's own window. Re-runs the double-booking | ||
| 167 | +/// guard for both teacher and requester against a fresh read under | ||
| 168 | +/// [`APPOINTMENT_LOCK`] — the authoritative check, since only approval | ||
| 169 | +/// commits anyone. Refused (409) when the effective window has already | ||
| 170 | +/// started; that also covers [`accept_proposal`], which lands here. | ||
| 171 | +/// | ||
| 172 | +/// Also refused (409) while a counter-proposal stands: the effective window | ||
| 173 | +/// would then be the *proposed* one, and the deciding side here is the | ||
| 174 | +/// teacher's, so approving would commit the requester to a time only the | ||
| 175 | +/// teacher ever named. That move belongs to [`accept_proposal`], which the | ||
| 176 | +/// web layer opens to the requester alone. | ||
| 177 | +pub async fn approve( | ||
| 178 | + db: &Database, | ||
| 179 | + id: &AppointmentId, | ||
| 180 | + decided_by: &UserId, | ||
| 181 | +) -> Result<Appointment, AppError> { | ||
| 182 | + approve_inner(db, id, decided_by, None).await | ||
| 183 | +} | ||
| 184 | + | ||
| 185 | +/// The one approval path. `accepting` carries the window the caller is | ||
| 186 | +/// answering *for*, which is the only way a proposed one may be committed: | ||
| 187 | +/// it both marks the caller as the proposal's counterparty and pins which | ||
| 188 | +/// proposal they saw. Re-checked on every retry round, so a proposal that | ||
| 189 | +/// moved between the read and the write is refused rather than confirmed. | ||
| 190 | +async fn approve_inner( | ||
| 191 | + db: &Database, | ||
| 192 | + id: &AppointmentId, | ||
| 193 | + decided_by: &UserId, | ||
| 194 | + accepting: Option<(Timestamp, Timestamp)>, | ||
| 195 | +) -> Result<Appointment, AppError> { | ||
| 196 | + let _guard = APPOINTMENT_LOCK.lock().await; | ||
| 197 | + for _ in 0..CAS_UPDATE_RETRIES { | ||
| 198 | + let expected = appointment::read_pending(db, id).await?; | ||
| 199 | + match accepting { | ||
| 200 | + None if expected.has_proposal() => { | ||
| 201 | + return Err(AppError::Conflict( | ||
| 202 | + "a counter-proposal is standing; only the requester can accept it", | ||
| 203 | + )); | ||
| 204 | + } | ||
| 205 | + Some(_) if !expected.has_proposal() => { | ||
| 206 | + return Err(AppError::Conflict("no time has been proposed")); | ||
| 207 | + } | ||
| 208 | + // The proposal moved between the requester reading it and | ||
| 209 | + // accepting it. Committing here would bind them to a window the | ||
| 210 | + // teacher swapped in after they clicked, which is the whole | ||
| 211 | + // thing the requester-only accept exists to prevent. | ||
| 212 | + Some(accepted) if !expected.proposes(accepted) => { | ||
| 213 | + return Err(AppError::Conflict( | ||
| 214 | + "the proposed time has changed; re-read the booking and accept the new one", | ||
| 215 | + )); | ||
| 216 | + } | ||
| 217 | + _ => {} | ||
| 218 | + } | ||
| 219 | + let slot = AppointmentSlot::read(&expected.slot, db) | ||
| 220 | + .await? | ||
| 221 | + .ok_or(AppError::NotFound)?; | ||
| 222 | + let (starts_at, ends_at) = expected.window(&slot); | ||
| 223 | + // The effective window — the proposal's when one stands — must still | ||
| 224 | + // be ahead. Mutual agreement does not help: `cancel` refuses a | ||
| 225 | + // meeting that started, so committing to a passed window would mint | ||
| 226 | + // a booking nobody can ever undo. Refused, the row stays `pending` | ||
| 227 | + // and the teacher can propose a time that can actually happen. | ||
| 228 | + if starts_at.as_millis() <= Timestamp::now().as_millis() { | ||
| 229 | + return Err(AppError::Conflict("that time has already started")); | ||
| 230 | + } | ||
| 231 | + if appointment::conflicts( | ||
| 232 | + db, | ||
| 233 | + slot.get_teacher(), | ||
| 234 | + &expected.requester, | ||
| 235 | + starts_at, | ||
| 236 | + ends_at, | ||
| 237 | + Some(id), | ||
| 238 | + ) | ||
| 239 | + .await? | ||
| 240 | + { | ||
| 241 | + return Err(AppError::Conflict( | ||
| 242 | + "that time collides with another approved appointment", | ||
| 243 | + )); | ||
| 244 | + } | ||
| 245 | + let mut approved = expected.clone(); | ||
| 246 | + approved.status = AppointmentStatus::Approved; | ||
| 247 | + approved.decided_by = Some(decided_by.clone()); | ||
| 248 | + if let Some(saved) = appointment::save_if_unchanged(db, &expected, approved).await? { | ||
| 249 | + return Ok(saved); | ||
| 250 | + } | ||
| 251 | + } | ||
| 252 | + Err(contended()) | ||
| 253 | +} | ||
| 254 | + | ||
| 255 | +/// Turn the request down. Frees the slot — the seat goes back with the | ||
| 256 | +/// status flip, in one transaction. No lock: this decides nothing about | ||
| 257 | +/// anyone's calendar, and the write is its own guard. | ||
| 258 | +pub async fn reject( | ||
| 259 | + db: &Database, | ||
| 260 | + id: &AppointmentId, | ||
| 261 | + decided_by: &UserId, | ||
| 262 | + reason: Option<AppointmentReason>, | ||
| 263 | +) -> Result<Appointment, AppError> { | ||
| 264 | + for _ in 0..CAS_UPDATE_RETRIES { | ||
| 265 | + let expected = appointment::read_pending(db, id).await?; | ||
| 266 | + let mut rejected = expected.clone(); | ||
| 267 | + rejected.status = AppointmentStatus::Rejected; | ||
| 268 | + rejected.decided_by = Some(decided_by.clone()); | ||
| 269 | + rejected.reject_reason = reason.clone(); | ||
| 270 | + if let Some(saved) = appointment::save_if_unchanged(db, &expected, rejected).await? { | ||
| 271 | + return Ok(saved); | ||
| 272 | + } | ||
| 273 | + } | ||
| 274 | + Err(contended()) | ||
| 275 | +} | ||
| 276 | + | ||
| 277 | +/// Call the meeting off. Legal from either live state, so an approved | ||
| 278 | +/// meeting can still be dropped; the slot frees up. The web layer opens | ||
| 279 | +/// this to the **requester only** — a teacher's way out is `reject` while | ||
| 280 | +/// the booking is pending, or `reschedule` (back to `pending`) then | ||
| 281 | +/// `reject` for an approved one — and `decline_reschedule`, the other | ||
| 282 | +/// caller, is the requester's too. | ||
| 283 | +/// | ||
| 284 | +/// Refused (409) once the *effective* window has opened — a meeting that | ||
| 285 | +/// began is history, not a plan. The guard lives here rather than in the | ||
| 286 | +/// handler so every caller inherits it: `decline_reschedule` cancels | ||
| 287 | +/// through this same door and used to slip past a handler-only check. | ||
| 288 | +pub async fn cancel( | ||
| 289 | + db: &Database, | ||
| 290 | + id: &AppointmentId, | ||
| 291 | + cancelled_by: &UserId, | ||
| 292 | + reason: Option<AppointmentReason>, | ||
| 293 | +) -> Result<Appointment, AppError> { | ||
| 294 | + for _ in 0..CAS_UPDATE_RETRIES { | ||
| 295 | + let expected = appointment::read(db, id).await?.ok_or(AppError::NotFound)?; | ||
| 296 | + if !expected.status.is_live() { | ||
| 297 | + return Err(AppError::Conflict("the appointment is already settled")); | ||
| 298 | + } | ||
| 299 | + let slot = AppointmentSlot::read(&expected.slot, db) | ||
| 300 | + .await? | ||
| 301 | + .ok_or(AppError::NotFound)?; | ||
| 302 | + if expected.window(&slot).0.as_millis() <= Timestamp::now().as_millis() { | ||
| 303 | + return Err(AppError::Conflict("the appointment has already started")); | ||
| 304 | + } | ||
| 305 | + let mut cancelled = expected.clone(); | ||
| 306 | + cancelled.status = AppointmentStatus::Cancelled; | ||
| 307 | + cancelled.cancelled_by = Some(cancelled_by.clone()); | ||
| 308 | + cancelled.cancel_reason = reason.clone(); | ||
| 309 | + if let Some(saved) = appointment::save_if_unchanged(db, &expected, cancelled).await? { | ||
| 310 | + return Ok(saved); | ||
| 311 | + } | ||
| 312 | + } | ||
| 313 | + Err(contended()) | ||
| 314 | +} | ||
| 315 | + | ||
| 316 | +/// Counter-propose another time on the same booking (no second row, so the | ||
| 317 | +/// reason and the history stay in one place). | ||
| 318 | +/// | ||
| 319 | +/// The proposal sends the booking back to `pending`: a previously approved | ||
| 320 | +/// meeting is *not* committed at the new time until the other side accepts, | ||
| 321 | +/// and leaving it approved would silently move a confirmed appointment. | ||
| 322 | +/// | ||
| 323 | +/// Refused (409) when the proposed window has already opened. The handler's | ||
| 324 | +/// `check_not_past` carries a 60s clock-skew grace, which is enough to | ||
| 325 | +/// propose a window that is already underway; `cancel` would then refuse to | ||
| 326 | +/// undo the booking, so it must not be offered in the first place. | ||
| 327 | +pub async fn propose( | ||
| 328 | + db: &Database, | ||
| 329 | + id: &AppointmentId, | ||
| 330 | + starts_at: Timestamp, | ||
| 331 | + ends_at: Timestamp, | ||
| 332 | + proposed_by: &UserId, | ||
| 333 | +) -> Result<Appointment, AppError> { | ||
| 334 | + if starts_at.as_millis() >= ends_at.as_millis() { | ||
| 335 | + return Err(ValidationError::Invalid { | ||
| 336 | + field: "proposed_ends_at", | ||
| 337 | + reason: "must be after proposed_starts_at", | ||
| 338 | + } | ||
| 339 | + .into()); | ||
| 340 | + } | ||
| 341 | + // No lock: a proposal commits nobody's calendar (the booking goes back | ||
| 342 | + // to `pending`), and it neither takes nor frees the slot's seat. | ||
| 343 | + for _ in 0..CAS_UPDATE_RETRIES { | ||
| 344 | + let expected = appointment::read(db, id).await?.ok_or(AppError::NotFound)?; | ||
| 345 | + if !expected.status.is_live() { | ||
| 346 | + return Err(AppError::Conflict("the appointment is already settled")); | ||
| 347 | + } | ||
| 348 | + if starts_at.as_millis() <= Timestamp::now().as_millis() { | ||
| 349 | + return Err(AppError::Conflict("that time has already started")); | ||
| 350 | + } | ||
| 351 | + let mut proposed = expected.clone(); | ||
| 352 | + proposed.status = AppointmentStatus::Pending; | ||
| 353 | + proposed.decided_by = None; | ||
| 354 | + proposed.proposed_starts_at = Some(starts_at); | ||
| 355 | + proposed.proposed_ends_at = Some(ends_at); | ||
| 356 | + proposed.proposed_by = Some(proposed_by.clone()); | ||
| 357 | + if let Some(saved) = appointment::save_if_unchanged(db, &expected, proposed).await? { | ||
| 358 | + return Ok(saved); | ||
| 359 | + } | ||
| 360 | + } | ||
| 361 | + Err(contended()) | ||
| 362 | +} | ||
| 363 | + | ||
| 364 | +/// Accept the standing proposal — approval at the proposed time. The | ||
| 365 | +/// overlap guard runs again because the time moved. | ||
| 366 | +/// | ||
| 367 | +/// `starts_at`/`ends_at` are the proposal the caller is answering, as they | ||
| 368 | +/// read it. They are not a request to move the meeting: they *pin* the one | ||
| 369 | +/// being accepted, and a proposal that has since been superseded is refused | ||
| 370 | +/// (409) rather than committed. `propose` takes no lock and the two calls | ||
| 371 | +/// are minutes apart, so nothing but this pin can tell "the requester | ||
| 372 | +/// agreed to 10:00" from "the requester's click landed on 23:00". | ||
| 373 | +pub async fn accept_proposal( | ||
| 374 | + db: &Database, | ||
| 375 | + id: &AppointmentId, | ||
| 376 | + decided_by: &UserId, | ||
| 377 | + starts_at: Timestamp, | ||
| 378 | + ends_at: Timestamp, | ||
| 379 | +) -> Result<Appointment, AppError> { | ||
| 380 | + // The same approval path re-reads under the lock and reads the proposed | ||
| 381 | + // window off the row, so accepting is approval — no second code path. | ||
| 382 | + // Only this door passes `accepting`, and the web layer opens it to the | ||
| 383 | + // requester alone. | ||
| 384 | + approve_inner(db, id, decided_by, Some((starts_at, ends_at))).await | ||
| 385 | +} | ||
| 386 | + | ||
| 387 | +/// Every retry lost the row to another decision. A 409 rather than a 500: the | ||
| 388 | +/// caller's request was refused, nothing was half-applied, and re-reading the | ||
| 389 | +/// booking shows what happened to it. | ||
| 390 | +fn contended() -> AppError { | ||
| 391 | + AppError::Conflict("the appointment is being decided elsewhere") | ||
| 392 | +} | ||
| 393 | + | ||
| 394 | +#[cfg(test)] | ||
| 395 | +mod tests { | ||
| 396 | + use super::*; | ||
| 397 | + use crate::database::{Database, init_mem}; | ||
| 398 | + | ||
| 399 | + fn at(millis: i64) -> Timestamp { | ||
| 400 | + Timestamp::from_millis(millis) | ||
| 401 | + } | ||
| 402 | + | ||
| 403 | + /// A window that has not opened yet — `book` refuses started ones. | ||
| 404 | + fn soon(offset: i64) -> Timestamp { | ||
| 405 | + at(Timestamp::now().as_millis() + offset) | ||
| 406 | + } | ||
| 407 | + | ||
| 408 | + #[tokio::test] | ||
| 409 | + async fn window_prefers_a_proposal_over_the_slot() { | ||
| 410 | + let db = init_mem().await.unwrap(); | ||
| 411 | + let teacher = UserId::from_key("t1"); | ||
| 412 | + let (starts_at, ends_at) = (soon(60_000), soon(120_000)); | ||
| 413 | + let slot = AppointmentSlot::create(&teacher, starts_at, ends_at, None, &db) | ||
| 414 | + .await | ||
| 415 | + .unwrap(); | ||
| 416 | + let mut appointment_row = book( | ||
| 417 | + &db, | ||
| 418 | + slot.get_id(), | ||
| 419 | + &UserId::from_key("s1"), | ||
| 420 | + AppointmentReason::try_new("ödev").unwrap(), | ||
| 421 | + ) | ||
| 422 | + .await | ||
| 423 | + .unwrap(); | ||
| 424 | + | ||
| 425 | + assert_eq!(appointment_row.window(&slot), (starts_at, ends_at)); | ||
| 426 | + appointment_row.proposed_starts_at = Some(at(5_000)); | ||
| 427 | + appointment_row.proposed_ends_at = Some(at(6_000)); | ||
| 428 | + assert_eq!(appointment_row.window(&slot), (at(5_000), at(6_000))); | ||
| 429 | + } | ||
| 430 | + | ||
| 431 | + /// A slot whose window already opened is unbookable: `cancel` would refuse | ||
| 432 | + /// to undo the resulting meeting, so the booking would be stuck for good. | ||
| 433 | + #[tokio::test] | ||
| 434 | + async fn a_started_slot_cannot_be_booked() { | ||
| 435 | + let db = init_mem().await.unwrap(); | ||
| 436 | + let teacher = UserId::from_key("t1"); | ||
| 437 | + let reason = || AppointmentReason::try_new("görüşme").unwrap(); | ||
| 438 | + let started = AppointmentSlot::create(&teacher, soon(-30_000), soon(60_000), None, &db) | ||
| 439 | + .await | ||
| 440 | + .unwrap(); | ||
| 441 | + assert!(matches!( | ||
| 442 | + book(&db, started.get_id(), &UserId::from_key("s1"), reason()).await, | ||
| 443 | + Err(AppError::Conflict("the slot has already started")) | ||
| 444 | + )); | ||
| 445 | + | ||
| 446 | + let upcoming = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) | ||
| 447 | + .await | ||
| 448 | + .unwrap(); | ||
| 449 | + assert!(book(&db, upcoming.get_id(), &UserId::from_key("s1"), reason()) | ||
| 450 | + .await | ||
| 451 | + .is_ok()); | ||
| 452 | + } | ||
| 453 | + | ||
| 454 | + /// Approval judges the *effective* window, so a proposal whose time has | ||
| 455 | + /// come and gone cannot be accepted — the meeting would be uncancellable. | ||
| 456 | + #[tokio::test] | ||
| 457 | + async fn a_started_proposal_cannot_be_accepted() { | ||
| 458 | + let db = init_mem().await.unwrap(); | ||
| 459 | + let teacher = UserId::from_key("t1"); | ||
| 460 | + let student = UserId::from_key("s1"); | ||
| 461 | + let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) | ||
| 462 | + .await | ||
| 463 | + .unwrap(); | ||
| 464 | + let booking = book( | ||
| 465 | + &db, | ||
| 466 | + slot.get_id(), | ||
| 467 | + &student, | ||
| 468 | + AppointmentReason::try_new("görüşme").unwrap(), | ||
| 469 | + ) | ||
| 470 | + .await | ||
| 471 | + .unwrap(); | ||
| 472 | + | ||
| 473 | + // Proposing a window that already opened is refused up front — the | ||
| 474 | + // handler's 60s skew grace would otherwise let one through. | ||
| 475 | + assert!(matches!( | ||
| 476 | + propose(&db, booking.get_id(), soon(-30_000), soon(30_000), &teacher).await, | ||
| 477 | + Err(AppError::Conflict("that time has already started")) | ||
| 478 | + )); | ||
| 479 | + // And approval judges the effective window again, for a proposal whose | ||
| 480 | + // time simply passed while it stood: forced onto the row directly, | ||
| 481 | + // since `propose` no longer mints one. | ||
| 482 | + let current = appointment::read(&db, booking.get_id()) | ||
| 483 | + .await | ||
| 484 | + .unwrap() | ||
| 485 | + .unwrap(); | ||
| 486 | + let (passed_starts_at, passed_ends_at) = (soon(-30_000), soon(30_000)); | ||
| 487 | + let mut standing = current.clone(); | ||
| 488 | + standing.proposed_starts_at = Some(passed_starts_at); | ||
| 489 | + standing.proposed_ends_at = Some(passed_ends_at); | ||
| 490 | + appointment::save_if_unchanged(&db, ¤t, standing) | ||
| 491 | + .await | ||
| 492 | + .unwrap() | ||
| 493 | + .unwrap(); | ||
| 494 | + assert!(matches!( | ||
| 495 | + accept_proposal(&db, booking.get_id(), &student, passed_starts_at, passed_ends_at) | ||
| 496 | + .await, | ||
| 497 | + Err(AppError::Conflict("that time has already started")) | ||
| 498 | + )); | ||
| 499 | + // Refused, not half-applied: still pending, still decidable at a time | ||
| 500 | + // that can actually happen. | ||
| 501 | + let after = appointment::read(&db, booking.get_id()).await.unwrap(); | ||
| 502 | + assert_eq!(after.unwrap().get_status(), AppointmentStatus::Pending); | ||
| 503 | + let (starts_at, ends_at) = (soon(60_000), soon(120_000)); | ||
| 504 | + propose(&db, booking.get_id(), starts_at, ends_at, &teacher) | ||
| 505 | + .await | ||
| 506 | + .unwrap(); | ||
| 507 | + // Accepting a window that is *not* the standing proposal is refused — | ||
| 508 | + // the pin is what the requester saw, not a request to move the meeting. | ||
| 509 | + assert!(matches!( | ||
| 510 | + accept_proposal(&db, booking.get_id(), &student, passed_starts_at, passed_ends_at) | ||
| 511 | + .await, | ||
| 512 | + Err(AppError::Conflict( | ||
| 513 | + "the proposed time has changed; \ | ||
| 514 | + re-read the booking and accept the new one" | ||
| 515 | + )) | ||
| 516 | + )); | ||
| 517 | + let accepted = accept_proposal(&db, booking.get_id(), &student, starts_at, ends_at) | ||
| 518 | + .await | ||
| 519 | + .unwrap(); | ||
| 520 | + assert_eq!(accepted.get_status(), AppointmentStatus::Approved); | ||
| 521 | + } | ||
| 522 | + | ||
| 523 | + /// The compare-and-set every decision writes through — the guard against a | ||
| 524 | + /// decision built on a snapshot that has since moved, which no lock taken | ||
| 525 | + /// after the read can catch. The interleaving that matters is the one a | ||
| 526 | + /// status-only guard would miss, since `propose` leaves a pending booking | ||
| 527 | + /// pending. | ||
| 528 | + /// | ||
| 529 | + /// Deliberately sequential: the mem engine answers `Ok` to a write it then | ||
| 530 | + /// drops, so a `join!` of two decisions proves nothing. This drives the | ||
| 531 | + /// primitive itself with the exact stale snapshot the race produces. | ||
| 532 | + #[tokio::test] | ||
| 533 | + async fn a_decision_built_on_a_stale_snapshot_never_lands() { | ||
| 534 | + let db = init_mem().await.unwrap(); | ||
| 535 | + let teacher = UserId::from_key("t1"); | ||
| 536 | + let student = UserId::from_key("s1"); | ||
| 537 | + let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) | ||
| 538 | + .await | ||
| 539 | + .unwrap(); | ||
| 540 | + let booking = book( | ||
| 541 | + &db, | ||
| 542 | + slot.get_id(), | ||
| 543 | + &student, | ||
| 544 | + AppointmentReason::try_new("görüşme").unwrap(), | ||
| 545 | + ) | ||
| 546 | + .await | ||
| 547 | + .unwrap(); | ||
| 548 | + | ||
| 549 | + // One transaction counter-proposes. A second concurrent transaction | ||
| 550 | + // is still holding the snapshot it read before that — same id, same | ||
| 551 | + // `pending` status. | ||
| 552 | + let stale = booking.clone(); | ||
| 553 | + let (proposed_starts_at, proposed_ends_at) = (soon(180_000), soon(240_000)); | ||
| 554 | + propose(&db, booking.get_id(), proposed_starts_at, proposed_ends_at, &teacher) | ||
| 555 | + .await | ||
| 556 | + .unwrap(); | ||
| 557 | + | ||
| 558 | + let mut late = stale.clone(); | ||
| 559 | + late.status = AppointmentStatus::Approved; | ||
| 560 | + late.decided_by = Some(teacher.clone()); | ||
| 561 | + assert!( | ||
| 562 | + appointment::save_if_unchanged(&db, &stale, late) | ||
| 563 | + .await | ||
| 564 | + .unwrap() | ||
| 565 | + .is_none() | ||
| 566 | + ); | ||
| 567 | + | ||
| 568 | + // The proposal survived: the row was not confirmed at the slot's old | ||
| 569 | + // window behind the requester's back. | ||
| 570 | + let after = appointment::read(&db, booking.get_id()) | ||
| 571 | + .await | ||
| 572 | + .unwrap() | ||
| 573 | + .unwrap(); | ||
| 574 | + assert_eq!(after.get_status(), AppointmentStatus::Pending); | ||
| 575 | + assert_eq!(after.get_proposed_starts_at(), Some(proposed_starts_at)); | ||
| 576 | + assert_eq!(after.get_proposed_ends_at(), Some(proposed_ends_at)); | ||
| 577 | + assert_eq!(after.get_decided_by(), None); | ||
| 578 | + | ||
| 579 | + // And the same decision, re-validated against the row as it now | ||
| 580 | + // stands, does land — a miss is a retry signal, not a wall. | ||
| 581 | + let mut fresh = after.clone(); | ||
| 582 | + fresh.status = AppointmentStatus::Approved; | ||
| 583 | + fresh.decided_by = Some(teacher.clone()); | ||
| 584 | + let saved = appointment::save_if_unchanged(&db, &after, fresh) | ||
| 585 | + .await | ||
| 586 | + .unwrap() | ||
| 587 | + .expect("a current snapshot must write"); | ||
| 588 | + assert_eq!(saved.get_status(), AppointmentStatus::Approved); | ||
| 589 | + assert_eq!(saved.get_proposed_starts_at(), Some(proposed_starts_at)); | ||
| 590 | + } | ||
| 591 | + | ||
| 592 | + /// What the slot row itself says about being taken — the authority every | ||
| 593 | + /// gate now reads. | ||
| 594 | + async fn occupied(slot: &AppointmentSlotId, db: &Database) -> i64 { | ||
| 595 | + let mut result = db | ||
| 596 | + .query("SELECT VALUE (occupied ?? 0) FROM $slot") | ||
| 597 | + .bind(("slot", slot.record())) | ||
| 598 | + .await | ||
| 599 | + .unwrap() | ||
| 600 | + .check() | ||
| 601 | + .unwrap(); | ||
| 602 | + result.take::<Vec<i64>>(0).unwrap()[0] | ||
| 603 | + } | ||
| 604 | + | ||
| 605 | + /// The double-book race with the lock taken out of the picture: a second | ||
| 606 | + /// booking arrives at the database with nothing between it and the slot but | ||
| 607 | + /// the claim's own `WHERE`, which is what must refuse it. Driven | ||
| 608 | + /// through [`cap::claim`] directly rather than through a `join!`, since the | ||
| 609 | + /// in-memory engine can drop one of two concurrent writes to a record and | ||
| 610 | + /// still answer `Ok` — this asks the primitive the exact question the race | ||
| 611 | + /// asks it. | ||
| 612 | + /// | ||
| 613 | + /// Deleting the `WHERE (occupied ?? 0) < $cap` from `cap::claim` makes the | ||
| 614 | + /// second claim succeed and this fail (mutation-proved). | ||
| 615 | + #[tokio::test] | ||
| 616 | + async fn a_concurrent_claim_cannot_take_a_booked_slot() { | ||
| 617 | + let db = init_mem().await.unwrap(); | ||
| 618 | + let teacher = UserId::from_key("t1"); | ||
| 619 | + let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) | ||
| 620 | + .await | ||
| 621 | + .unwrap(); | ||
| 622 | + assert_eq!(occupied(slot.get_id(), &db).await, 0); | ||
| 623 | + | ||
| 624 | + book( | ||
| 625 | + &db, | ||
| 626 | + slot.get_id(), | ||
| 627 | + &UserId::from_key("s1"), | ||
| 628 | + AppointmentReason::try_new("görüşme").unwrap(), | ||
| 629 | + ) | ||
| 630 | + .await | ||
| 631 | + .unwrap(); | ||
| 632 | + assert_eq!(occupied(slot.get_id(), &db).await, 1); | ||
| 633 | + | ||
| 634 | + assert!( | ||
| 635 | + !cap::claim(&slot.get_id().record(), SLOT_OCCUPIED_FIELD, 1, &db) | ||
| 636 | + .await | ||
| 637 | + .unwrap(), | ||
| 638 | + "the slot's seat must already be taken" | ||
| 639 | + ); | ||
| 640 | + // And the racer's refusal left the stored state alone: one booking, one | ||
| 641 | + // seat — not two of either. | ||
| 642 | + assert_eq!(occupied(slot.get_id(), &db).await, 1); | ||
| 643 | + assert_eq!( | ||
| 644 | + appointment::list_for_slot(&db, slot.get_id()) | ||
| 645 | + .await | ||
| 646 | + .unwrap() | ||
| 647 | + .len(), | ||
| 648 | + 1 | ||
| 649 | + ); | ||
| 650 | + } | ||
| 651 | + | ||
| 652 | + /// The seat and the booking row now land in one transaction, so the stored | ||
| 653 | + /// state must move together: a taken slot refuses the next requester with | ||
| 654 | + /// the counter *and* the row list untouched — a refusal that had already | ||
| 655 | + /// bumped the counter would strand the slot forever. | ||
| 656 | + #[tokio::test] | ||
| 657 | + async fn a_refused_booking_moves_nothing() { | ||
| 658 | + let db = init_mem().await.unwrap(); | ||
| 659 | + let teacher = UserId::from_key("t1"); | ||
| 660 | + let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) | ||
| 661 | + .await | ||
| 662 | + .unwrap(); | ||
| 663 | + let reason = || AppointmentReason::try_new("görüşme").unwrap(); | ||
| 664 | + | ||
| 665 | + book(&db, slot.get_id(), &UserId::from_key("s1"), reason()) | ||
| 666 | + .await | ||
| 667 | + .unwrap(); | ||
| 668 | + assert_eq!(occupied(slot.get_id(), &db).await, 1); | ||
| 669 | + | ||
| 670 | + let refused = book(&db, slot.get_id(), &UserId::from_key("s2"), reason()).await; | ||
| 671 | + assert!( | ||
| 672 | + matches!(refused, Err(AppError::Conflict(_))), | ||
| 673 | + "the slot is taken" | ||
| 674 | + ); | ||
| 675 | + assert_eq!( | ||
| 676 | + occupied(slot.get_id(), &db).await, | ||
| 677 | + 1, | ||
| 678 | + "the refusal took no seat" | ||
| 679 | + ); | ||
| 680 | + assert_eq!( | ||
| 681 | + appointment::list_for_slot(&db, slot.get_id()) | ||
| 682 | + .await | ||
| 683 | + .unwrap() | ||
| 684 | + .len(), | ||
| 685 | + 1, | ||
| 686 | + "and wrote no row" | ||
| 687 | + ); | ||
| 688 | + } | ||
| 689 | + | ||
| 690 | + /// Cancelling gives the seat back in the same transaction as the status | ||
| 691 | + /// flip — the counter is the only thing that says a slot is free, so a | ||
| 692 | + /// cancel that moved one without the other would strand the slot forever. | ||
| 693 | + #[tokio::test] | ||
| 694 | + async fn cancelling_hands_the_seat_back_with_the_status() { | ||
| 695 | + let db = init_mem().await.unwrap(); | ||
| 696 | + let teacher = UserId::from_key("t1"); | ||
| 697 | + let student = UserId::from_key("s1"); | ||
| 698 | + let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) | ||
| 699 | + .await | ||
| 700 | + .unwrap(); | ||
| 701 | + let booking = book( | ||
| 702 | + &db, | ||
| 703 | + slot.get_id(), | ||
| 704 | + &student, | ||
| 705 | + AppointmentReason::try_new("görüşme").unwrap(), | ||
| 706 | + ) | ||
| 707 | + .await | ||
| 708 | + .unwrap(); | ||
| 709 | + approve(&db, booking.get_id(), &teacher).await.unwrap(); | ||
| 710 | + assert_eq!(occupied(slot.get_id(), &db).await, 1, "approval holds it"); | ||
| 711 | + | ||
| 712 | + cancel(&db, booking.get_id(), &student, None) | ||
| 713 | + .await | ||
| 714 | + .unwrap(); | ||
| 715 | + assert_eq!(occupied(slot.get_id(), &db).await, 0); | ||
| 716 | + // Cancelling twice is refused, so the seat cannot go back twice either. | ||
| 717 | + assert!(cancel(&db, booking.get_id(), &student, None).await.is_err()); | ||
| 718 | + assert_eq!(occupied(slot.get_id(), &db).await, 0); | ||
| 719 | + assert!(book( | ||
| 720 | + &db, | ||
| 721 | + slot.get_id(), | ||
| 722 | + &UserId::from_key("s2"), | ||
| 723 | + AppointmentReason::try_new("görüşme").unwrap() | ||
| 724 | + ) | ||
| 725 | + .await | ||
| 726 | + .is_ok()); | ||
| 727 | + assert_eq!(occupied(slot.get_id(), &db).await, 1); | ||
| 728 | + } | ||
| 729 | + | ||
| 730 | + /// Occupancy frees on reject, so the slot can be re-booked. | ||
| 731 | + #[tokio::test] | ||
| 732 | + async fn rejecting_frees_the_slot_for_re_booking() { | ||
| 733 | + let db = init_mem().await.unwrap(); | ||
| 734 | + let teacher = UserId::from_key("t1"); | ||
| 735 | + let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) | ||
| 736 | + .await | ||
| 737 | + .unwrap(); | ||
| 738 | + let reason = || AppointmentReason::try_new("görüşme").unwrap(); | ||
| 739 | + | ||
| 740 | + let first = book(&db, slot.get_id(), &UserId::from_key("s1"), reason()) | ||
| 741 | + .await | ||
| 742 | + .unwrap(); | ||
| 743 | + assert!(matches!( | ||
| 744 | + book(&db, slot.get_id(), &UserId::from_key("s2"), reason()).await, | ||
| 745 | + Err(AppError::Conflict(_)) | ||
| 746 | + )); | ||
| 747 | + // The live booking also blocks the slot delete. | ||
| 748 | + assert!(matches!( | ||
| 749 | + slot.clone().delete(&db).await, | ||
| 750 | + Err(AppError::Conflict(_)) | ||
| 751 | + )); | ||
| 752 | + | ||
| 753 | + reject(&db, first.get_id(), &teacher, None) | ||
| 754 | + .await | ||
| 755 | + .unwrap(); | ||
| 756 | + assert_eq!(occupied(slot.get_id(), &db).await, 0); | ||
| 757 | + let second = book(&db, slot.get_id(), &UserId::from_key("s2"), reason()) | ||
| 758 | + .await | ||
| 759 | + .unwrap(); | ||
| 760 | + assert_eq!(second.get_status(), AppointmentStatus::Pending); | ||
| 761 | + assert_eq!(occupied(slot.get_id(), &db).await, 1); | ||
| 762 | + } | ||
| 763 | +} | ||
src/service/mod.rsmodified+1 -0
| @@ -1,6 +1,7 @@ | |||
| 1 | //! Business rules, workflow locks, multi-call orchestration; calls db::*; no | 1 | //! Business rules, workflow locks, multi-call orchestration; calls db::*; no |
| 2 | //! SurrealQL text. | 2 | //! SurrealQL text. |
| 3 | 3 | ||
| 4 | +pub mod appointment; | ||
| 4 | pub mod note; | 5 | pub mod note; |
| 5 | pub mod payment_ledger; | 6 | pub mod payment_ledger; |
| 6 | pub mod session; | 7 | pub mod session; |
src/web/appointments.rsmodified+19 -16
| @@ -16,6 +16,7 @@ use crate::domain::role::Role; | |||
| 16 | use crate::domain::timestamp::Timestamp; | 16 | use crate::domain::timestamp::Timestamp; |
| 17 | use crate::domain::user::{User, UserId}; | 17 | use crate::domain::user::{User, UserId}; |
| 18 | use crate::error::{AppError, ErrorResponse, ValidationError}; | 18 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 19 | +use crate::service; | ||
| 19 | use crate::state::AppState; | 20 | use crate::state::AppState; |
| 20 | 21 | ||
| 21 | use super::{ | 22 | use super::{ |
| @@ -273,7 +274,7 @@ async fn for_decision( | |||
| 273 | user: &User, | 274 | user: &User, |
| 274 | db: &Database, | 275 | db: &Database, |
| 275 | ) -> Result<Appointment, AppError> { | 276 | ) -> Result<Appointment, AppError> { |
| 276 | - let appointment = Appointment::read(id, db).await?.ok_or(AppError::NotFound)?; | 277 | + let appointment = service::appointment::read(db, id).await?.ok_or(AppError::NotFound)?; |
| 277 | let slot = AppointmentSlot::read(appointment.get_slot(), db) | 278 | let slot = AppointmentSlot::read(appointment.get_slot(), db) |
| 278 | .await? | 279 | .await? |
| 279 | .ok_or(AppError::NotFound)?; | 280 | .ok_or(AppError::NotFound)?; |
| @@ -554,7 +555,8 @@ async fn book( | |||
| 554 | )); | 555 | )); |
| 555 | } | 556 | } |
| 556 | let reason = AppointmentReason::try_new(&req.reason)?; | 557 | let reason = AppointmentReason::try_new(&req.reason)?; |
| 557 | - let appointment = Appointment::book(&slot_id, user.get_id(), reason, &st.db).await?; | 558 | + let appointment = |
| 559 | + service::appointment::book(&st.db, &slot_id, user.get_id(), reason).await?; | ||
| 558 | Ok(( | 560 | Ok(( |
| 559 | StatusCode::CREATED, | 561 | StatusCode::CREATED, |
| 560 | one_appointment(appointment, &st.db).await?, | 562 | one_appointment(appointment, &st.db).await?, |
| @@ -585,9 +587,9 @@ async fn list_appointments( | |||
| 585 | ) -> Result<Json<Page<AppointmentResponse>>, AppError> { | 587 | ) -> Result<Json<Page<AppointmentResponse>>, AppError> { |
| 586 | let (limit, offset) = page.resolve()?; | 588 | let (limit, offset) = page.resolve()?; |
| 587 | let (rows, total) = if user.get_role().at_least(Role::Teacher) { | 589 | let (rows, total) = if user.get_role().at_least(Role::Teacher) { |
| 588 | - Appointment::list_for_teacher(user.get_id(), limit, offset, &st.db).await? | 590 | + service::appointment::list_for_teacher(&st.db, user.get_id(), limit, offset).await? |
| 589 | } else { | 591 | } else { |
| 590 | - Appointment::list_for_requester(user.get_id(), limit, offset, &st.db).await? | 592 | + service::appointment::list_for_requester(&st.db, user.get_id(), limit, offset).await? |
| 591 | }; | 593 | }; |
| 592 | // Join slots and people onto the page alone — the lookup shrinks with it. | 594 | // Join slots and people onto the page alone — the lookup shrinks with it. |
| 593 | let items = appointment_responses(&rows, &st.db).await?; | 595 | let items = appointment_responses(&rows, &st.db).await?; |
| @@ -626,7 +628,7 @@ async fn approve( | |||
| 626 | ) -> Result<Json<AppointmentResponse>, AppError> { | 628 | ) -> Result<Json<AppointmentResponse>, AppError> { |
| 627 | let id = AppointmentId::from_key(&id); | 629 | let id = AppointmentId::from_key(&id); |
| 628 | for_decision(&id, &user, &st.db).await?; | 630 | for_decision(&id, &user, &st.db).await?; |
| 629 | - let appointment = Appointment::approve(&id, user.get_id(), &st.db).await?; | 631 | + let appointment = service::appointment::approve(&st.db, &id, user.get_id()).await?; |
| 630 | one_appointment(appointment, &st.db).await | 632 | one_appointment(appointment, &st.db).await |
| 631 | } | 633 | } |
| 632 | 634 | ||
| @@ -664,7 +666,7 @@ async fn reject( | |||
| 664 | Some(reason) if !reason.trim().is_empty() => Some(AppointmentReason::try_new(&reason)?), | 666 | Some(reason) if !reason.trim().is_empty() => Some(AppointmentReason::try_new(&reason)?), |
| 665 | _ => None, | 667 | _ => None, |
| 666 | }; | 668 | }; |
| 667 | - let appointment = Appointment::reject(&id, user.get_id(), reason, &st.db).await?; | 669 | + let appointment = service::appointment::reject(&st.db, &id, user.get_id(), reason).await?; |
| 668 | one_appointment(appointment, &st.db).await | 670 | one_appointment(appointment, &st.db).await |
| 669 | } | 671 | } |
| 670 | 672 | ||
| @@ -700,7 +702,7 @@ async fn cancel( | |||
| 700 | body: Option<Json<CancelRequest>>, | 702 | body: Option<Json<CancelRequest>>, |
| 701 | ) -> Result<Json<AppointmentResponse>, AppError> { | 703 | ) -> Result<Json<AppointmentResponse>, AppError> { |
| 702 | let id = AppointmentId::from_key(&id); | 704 | let id = AppointmentId::from_key(&id); |
| 703 | - let appointment = Appointment::read(&id, &st.db) | 705 | + let appointment = service::appointment::read(&st.db, &id) |
| 704 | .await? | 706 | .await? |
| 705 | .ok_or(AppError::NotFound)?; | 707 | .ok_or(AppError::NotFound)?; |
| 706 | // Only the requester (student/parent) may cancel. Teachers/managers end a | 708 | // Only the requester (student/parent) may cancel. Teachers/managers end a |
| @@ -716,10 +718,10 @@ async fn cancel( | |||
| 716 | Some(reason) if !reason.trim().is_empty() => Some(AppointmentReason::try_new(&reason)?), | 718 | Some(reason) if !reason.trim().is_empty() => Some(AppointmentReason::try_new(&reason)?), |
| 717 | _ => None, | 719 | _ => None, |
| 718 | }; | 720 | }; |
| 719 | - // The started-window guard lives in `Appointment::cancel`, under the lock | 721 | + // The started-window guard lives in `service::appointment::cancel`, under |
| 720 | - // and on a fresh read — a pre-lock copy of it here would only be a staler | 722 | + // the lock and on a fresh read — a pre-lock copy of it here would only be |
| 721 | - // second opinion, and `decline_reschedule` would still bypass it. | 723 | + // a staler second opinion, and `decline_reschedule` would still bypass it. |
| 722 | - let appointment = Appointment::cancel(&id, user.get_id(), reason, &st.db).await?; | 724 | + let appointment = service::appointment::cancel(&st.db, &id, user.get_id(), reason).await?; |
| 723 | one_appointment(appointment, &st.db).await | 725 | one_appointment(appointment, &st.db).await |
| 724 | } | 726 | } |
| 725 | 727 | ||
| @@ -767,7 +769,8 @@ async fn reschedule( | |||
| 767 | 769 | ||
| 768 | let id = AppointmentId::from_key(&id); | 770 | let id = AppointmentId::from_key(&id); |
| 769 | for_decision(&id, &user, &st.db).await?; | 771 | for_decision(&id, &user, &st.db).await?; |
| 770 | - let appointment = Appointment::propose(&id, starts_at, ends_at, user.get_id(), &st.db).await?; | 772 | + let appointment = |
| 773 | + service::appointment::propose(&st.db, &id, starts_at, ends_at, user.get_id()).await?; | ||
| 771 | one_appointment(appointment, &st.db).await | 774 | one_appointment(appointment, &st.db).await |
| 772 | } | 775 | } |
| 773 | 776 | ||
| @@ -812,12 +815,12 @@ async fn accept_reschedule( | |||
| 812 | // requester's answer to "which proposal?" — the domain compares them to the | 815 | // requester's answer to "which proposal?" — the domain compares them to the |
| 813 | // row and refuses anything else, so a past or inverted pair is simply a | 816 | // row and refuses anything else, so a past or inverted pair is simply a |
| 814 | // mismatch (409), never a booking. | 817 | // mismatch (409), never a booking. |
| 815 | - let appointment = Appointment::accept_proposal( | 818 | + let appointment = service::appointment::accept_proposal( |
| 819 | + &st.db, | ||
| 816 | &id, | 820 | &id, |
| 817 | user.get_id(), | 821 | user.get_id(), |
| 818 | Timestamp::from_millis(req.proposed_starts_at), | 822 | Timestamp::from_millis(req.proposed_starts_at), |
| 819 | Timestamp::from_millis(req.proposed_ends_at), | 823 | Timestamp::from_millis(req.proposed_ends_at), |
| 820 | - &st.db, | ||
| 821 | ) | 824 | ) |
| 822 | .await?; | 825 | .await?; |
| 823 | one_appointment(appointment, &st.db).await | 826 | one_appointment(appointment, &st.db).await |
| @@ -853,7 +856,7 @@ async fn decline_reschedule( | |||
| 853 | if appointment.get_proposed_starts_at().is_none() { | 856 | if appointment.get_proposed_starts_at().is_none() { |
| 854 | return Err(AppError::Conflict("no time has been proposed")); | 857 | return Err(AppError::Conflict("no time has been proposed")); |
| 855 | } | 858 | } |
| 856 | - let appointment = Appointment::cancel(&id, user.get_id(), None, &st.db).await?; | 859 | + let appointment = service::appointment::cancel(&st.db, &id, user.get_id(), None).await?; |
| 857 | one_appointment(appointment, &st.db).await | 860 | one_appointment(appointment, &st.db).await |
| 858 | } | 861 | } |
| 859 | 862 | ||
| @@ -864,7 +867,7 @@ async fn ensure_requester( | |||
| 864 | user: &User, | 867 | user: &User, |
| 865 | db: &Database, | 868 | db: &Database, |
| 866 | ) -> Result<Appointment, AppError> { | 869 | ) -> Result<Appointment, AppError> { |
| 867 | - let appointment = Appointment::read(id, db).await?.ok_or(AppError::NotFound)?; | 870 | + let appointment = service::appointment::read(db, id).await?.ok_or(AppError::NotFound)?; |
| 868 | if appointment.get_requester() != user.get_id() { | 871 | if appointment.get_requester() != user.get_id() { |
| 869 | return Err(AppError::Forbidden( | 872 | return Err(AppError::Forbidden( |
| 870 | "only the requester can answer a counter-proposal", | 873 | "only the requester can answer a counter-proposal", |
tests/integration.rsmodified+1 -1
| @@ -17733,7 +17733,7 @@ async fn declining_a_reschedule_cancels_the_booking() { | |||
| 17733 | } | 17733 | } |
| 17734 | 17734 | ||
| 17735 | /// Declining cancels, so it answers to the cancel deadline. The guard lives in | 17735 | /// Declining cancels, so it answers to the cancel deadline. The guard lives in |
| 17736 | -/// `Appointment::cancel` itself — when it sat in the cancel *handler*, decline | 17736 | +/// `service::appointment::cancel` itself — when it sat in the cancel *handler*, decline |
| 17737 | /// went straight past it and called off a meeting already underway. | 17737 | /// went straight past it and called off a meeting already underway. |
| 17738 | #[tokio::test] | 17738 | #[tokio::test] |
| 17739 | async fn declining_a_started_reschedule_is_refused() { | 17739 | async fn declining_a_started_reschedule_is_refused() { |
tests/regress_appointments.rsmodified+2 -2
| @@ -337,7 +337,7 @@ async fn an_answer_resolves_its_own_prompt_across_an_interleave() { | |||
| 337 | // The store property behind `APPOINTMENT_LOCK`. | 337 | // The store property behind `APPOINTMENT_LOCK`. |
| 338 | // --------------------------------------------------------------------------- | 338 | // --------------------------------------------------------------------------- |
| 339 | 339 | ||
| 340 | -/// The overlap check exactly as [`Appointment::conflicts`] asks it, then the | 340 | +/// The overlap check exactly as [`crate::db::appointment::conflicts`] asks it, then the |
| 341 | /// approval it authorizes — one `BEGIN…COMMIT`, with a `SLEEP` between the two | 341 | /// approval it authorizes — one `BEGIN…COMMIT`, with a `SLEEP` between the two |
| 342 | /// so both racers read before either writes. Deterministic: the window is wide | 342 | /// so both racers read before either writes. Deterministic: the window is wide |
| 343 | /// enough that no scheduling jitter can order the read of one after the write | 343 | /// enough that no scheduling jitter can order the read of one after the write |
| @@ -438,7 +438,7 @@ async fn pending_at( | |||
| 438 | /// counter or a compare-and-set on. | 438 | /// counter or a compare-and-set on. |
| 439 | /// | 439 | /// |
| 440 | /// Which is why every approving path takes | 440 | /// Which is why every approving path takes |
| 441 | -/// `domain::appointment::APPOINTMENT_LOCK`, an in-process mutex — it is the | 441 | +/// `service::appointment::APPOINTMENT_LOCK`, an in-process mutex — it is the |
| 442 | /// *only* thing preventing a double-booked teacher today, and this test is what | 442 | /// *only* thing preventing a double-booked teacher today, and this test is what |
| 443 | /// that claim rests on. The lock is bypassed here on purpose: the racing | 443 | /// that claim rests on. The lock is bypassed here on purpose: the racing |
| 444 | /// approvals are sent as raw transactions, so what is measured is the store. | 444 | /// approvals are sent as raw transactions, so what is measured is the store. |