diff --git a/src/db/appointment_slot.rs b/src/db/appointment_slot.rs new file mode 100644 index 0000000..0776ae9 --- /dev/null +++ b/src/db/appointment_slot.rs @@ -0,0 +1,255 @@ +//! The `appointment_slot` table: row reads and listings, the overlap probes +//! behind the publish guard, the role-claimed INSERT every publish writes +//! through, and the delete whose own `WHERE` is the no-live-booking guard. +//! The workflows that sequence these under +//! [`crate::service::appointment::APPOINTMENT_LOCK`] live in +//! [`crate::service::appointment_slot`]. + +use surrealdb::types::{RecordId, SurrealValue}; + +use crate::constant::{APPOINTMENT_SLOT_TABLE, ROLES}; +use crate::database::{Database, transaction_with_retry}; +use crate::db::cap; +use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId, SlotSeries}; +use crate::domain::role::Role; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// The publisher fell below `teacher` while the publish was in flight. +const UNFIT_MARK: &str = "slot_not_staff"; + +/// Write a whole publish — one occurrence or fifty-two — while the publisher +/// still *holds* a teaching role. +/// +/// Every row here names the teacher, so the write touches no key a demotion +/// touches: [`crate::domain::user::User::set_role`] sweeps the slots its own +/// snapshot can see, and a slot landing after that snapshot would survive it +/// under a role that may not publish — reachable by no route afterwards, +/// since the calendar hides a demoted teacher's slots and the deletes are +/// `teacher`-gated. So the teacher's own record is claimed beside the insert +/// ([`cap::role_claim`]), which is the key the demotion writes: either the +/// sweep sees these slots, or this write sees the new role and publishes +/// nothing. +/// +/// The bar is read off the hierarchy rather than spelled out, so a new role +/// cannot drift out of it. +/// +/// Admissible for [`transaction_with_retry`]: the claim is `SELECT`/`UPDATE` +/// only, and the `INSERT` carries freshly minted ULIDs on a table with no +/// `UNIQUE` index, so no rival can make it answer "already exists". +pub async fn insert_claimed( + db: &Database, + teacher: &UserId, + rows: Vec, +) -> Result, AppError> { + let staff = ROLES + .iter() + .filter(|role| role.at_least(Role::Teacher)) + .map(|role| format!("'{}'", role.as_str())) + .collect::>() + .join(", "); + let held = cap::role_claim("teacher", &format!("NOT IN [{staff}]"), UNFIT_MARK); + let sql = format!( + "BEGIN TRANSACTION;\n{};\nINSERT INTO {APPOINTMENT_SLOT_TABLE} $rows;\n\ + COMMIT TRANSACTION;", + held.join(";\n") + ); + let (mut result, mut errors) = transaction_with_retry( + db, + &sql, + &[ + ("teacher".into(), teacher.record().into_value()), + ("rows".into(), rows.into_value()), + ], + &[UNFIT_MARK], + ) + .await?; + // Demoted while this ran — the same refusal `RequireTeacher` makes a + // moment earlier, and the only one that can arrive after it. + if errors + .values() + .any(|error| error.to_string().contains(UNFIT_MARK)) + { + return Err(AppError::Forbidden( + "that account no longer holds a teaching role", + )); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // BEGIN plus the claim's own statements — counted, not tallied by hand, + // so a statement added there cannot read back the wrong result. + Ok(result.take::>(held.len() + 1)?) +} + +/// Does the teacher already have a published slot whose window collides with +/// `[starts_at, ends_at)`? Half-open, so a slot ending exactly where the new +/// one starts is *not* a conflict — that is how a teacher's hour is carved +/// into back-to-back slots. Caller must hold +/// [`crate::service::appointment::APPOINTMENT_LOCK`] for the +/// answer to still be true by the time the insert lands. +pub async fn conflicts_existing( + db: &Database, + teacher: &UserId, + starts_at: Timestamp, + ends_at: Timestamp, +) -> Result { + let mut result = db + .query( + "SELECT VALUE id FROM appointment_slot \ + WHERE teacher = $teacher AND starts_at < $ends AND ends_at > $starts \ + LIMIT 1", + ) + .bind(("teacher", teacher.record())) + .bind(("starts", starts_at.as_millis())) + .bind(("ends", ends_at.as_millis())) + .await? + .check()?; + Ok(!result.take::>(0)?.is_empty()) +} + +/// Every window this teacher already published that intersects the envelope +/// `[from, to)`. One read for a whole batch: a stored row that overlaps *any* +/// window in the batch necessarily overlaps the envelope spanning them all, +/// so filtering the envelope and comparing in memory is exactly the +/// per-window [`conflicts_existing`] check, +/// hoisted out of the loop — which is what keeps +/// [`crate::service::appointment::APPOINTMENT_LOCK`] down +/// to two round trips instead of one per occurrence. +pub async fn windows_in_span( + db: &Database, + teacher: &UserId, + from: Timestamp, + to: Timestamp, +) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM appointment_slot \ + WHERE teacher = $teacher AND starts_at < $to AND ends_at > $from", + ) + .bind(("teacher", teacher.record())) + .bind(("from", from.as_millis())) + .bind(("to", to.as_millis())) + .await? + .check()?; + Ok(result + .take::>(0)? + .into_iter() + .map(|slot| (slot.starts_at, slot.ends_at)) + .collect()) +} + +pub async fn read( + db: &Database, + id: &AppointmentSlotId, +) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +/// A teacher's own calendar, earliest first. +pub async fn list_for_teacher( + db: &Database, + teacher: &UserId, +) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM appointment_slot WHERE teacher = $teacher \ + ORDER BY starts_at ASC, id ASC", + ) + .bind(("teacher", teacher.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Every slot whose window has not opened yet, earliest first — the bookable +/// calendar a requester browses. +/// +/// The bound is `starts_at`, not `ends_at`, so that this window is exactly +/// the one [`crate::service::appointment::book`] accepts: a slot already underway is +/// unbookable (`cancel` could never undo the booking), and offering it would +/// be a calendar entry that can only answer `409`. The publish-time 60s skew +/// grace deliberately does not apply here either — `book` does not grant it, +/// and a slot published a moment after its own start is unbookable from +/// birth, so it belongs on nobody's calendar. +pub async fn list_upcoming( + db: &Database, + from: Timestamp, +) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM appointment_slot WHERE starts_at > $from \ + ORDER BY starts_at ASC, id ASC", + ) + .bind(("from", from.as_millis())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +pub async fn list_for_series( + db: &Database, + series: &SlotSeries, +) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM appointment_slot WHERE series = $series \ + ORDER BY starts_at ASC, id ASC", + ) + .bind(("series", series.as_str().to_string())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Shared body of both deletes: drop every named slot, but only while its +/// `occupied` counter says nobody is waiting on it — the delete's own +/// `WHERE` is the guard, which is what makes it hold against a booking +/// landing in the middle of it (a separate read-then-delete could not). +/// +/// All-or-nothing across the whole list: if fewer rows go than were named, +/// the transaction is thrown away, so a series never loses its free weeks +/// and keeps the booked one. Whether that shortfall was a live booking or a +/// slot that no longer exists is read off what survived — the occupied rows +/// are still there, a vanished one is not — which is the 409/404 the caller +/// used to get from a separate check. +pub async fn delete_free(db: &Database, ids: &[AppointmentSlotId]) -> Result<(), AppError> { + let records: Vec = ids.iter().map(|id| id.record()).collect(); + let (_, mut errors) = transaction_with_retry( + db, + "BEGIN TRANSACTION; + LET $gone = (DELETE $slots WHERE (occupied ?? 0) = 0 RETURN BEFORE); + IF array::len($gone) != array::len($slots) { + THROW IF array::len((SELECT VALUE id FROM appointment_slot + WHERE id IN $slots)) > 0 { 'slot_occupied' } ELSE { 'slot_missing' } + }; + DELETE appointment WHERE slot IN $slots; + RETURN $gone; + COMMIT TRANSACTION;", + &[("slots".into(), records.into_value())], + &["slot_occupied", "slot_missing"], + ) + .await?; + // An aborted transaction errors every slot; only the THROW's own slot + // names the marker (the `Exam::update` treatment), and a round lost to + // a booking landing on `occupied` mid-flight is re-sent rather than + // reported (see [`transaction_with_retry`]). + let thrown = |marker: &str| { + errors + .values() + .any(|error| error.to_string().contains(marker)) + }; + if thrown("slot_occupied") { + return Err(AppError::Conflict( + "the slot has a pending or approved booking", + )); + } + if thrown("slot_missing") { + return Err(AppError::NotFound); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + Ok(()) +} diff --git a/src/db/mod.rs b/src/db/mod.rs index 1ad9342..91a3bf1 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -1,6 +1,7 @@ //! The only layer that executes queries. pub mod appointment; +pub mod appointment_slot; pub mod cap; pub mod course; pub mod exam_attempt; diff --git a/src/domain/appointment_slot.rs b/src/domain/appointment_slot.rs index f99eb10..6e55f51 100644 --- a/src/domain/appointment_slot.rs +++ b/src/domain/appointment_slot.rs @@ -1,36 +1,33 @@ -//! A teacher's published availability: "I am free here, book me". A slot is -//! nearly pure calendar: the one piece of booking state it carries is the -//! `occupied` counter (a [`cap`](crate::db::cap) of one), taken when a -//! booking is made and given back in the same transaction as the reject or -//! cancel that settles it — so the slot frees itself again, and unlike a UNIQUE -//! index it does not keep a dead booking's seat. Stored rather than counted -//! from the [`Appointment`] rows because a conditional write on one row is the -//! only guard a concurrent booking cannot outrun. +//! A teacher's published availability: "I am free here, book me". This module +//! is the pure row shape: the validated note, the ids, and +//! [`AppointmentSlot::weekly_windows`], the concrete windows a recurring +//! publish unfolds into at write time — each occurrence keeps the same +//! `series` id, so no recurrence rule is ever evaluated at read time and +//! cancelling one week is a plain row delete. //! -//! A recurring publish is expanded into concrete rows here, at write time, -//! sharing one `series` id — no recurrence rule is ever evaluated at read -//! time. Cancelling one week is then a plain row delete, and the whole series -//! is still addressable through its id. +//! The one piece of booking state a slot carries is the `occupied` counter (a +//! [`cap`](crate::db::cap) of one), taken when a booking is made and given +//! back in the same transaction as the reject or cancel that settles it — so +//! the slot frees itself again, and unlike a UNIQUE index it does not keep a +//! dead booking's seat. Stored rather than counted from the +//! [appointment](crate::domain::appointment::Appointment) rows because a +//! conditional write on one row is the only guard a concurrent booking cannot +//! outrun. The reads and writes behind it live in +//! [`crate::db::appointment_slot`]; the publish and delete workflows under +//! [`crate::service::appointment::APPOINTMENT_LOCK`] live in +//! [`crate::service::appointment_slot`]. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{ - APPOINTMENT_SLOT_TABLE, MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK, ROLES, + APPOINTMENT_SLOT_TABLE, MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK, }; -use crate::database::{Database, transaction_with_retry}; -use crate::domain::appointment::Appointment; -use crate::service::appointment::APPOINTMENT_LOCK; -use crate::db::cap; use crate::domain::monotonic_id::next_ulid; -use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use crate::validate::validate_optional; -/// The publisher fell below `teacher` while the publish was in flight. -const UNFIT_MARK: &str = "slot_not_staff"; - // Slot ids come from [`crate::domain::monotonic_id`]: a recurring publish // writes its whole expansion inside one millisecond, which random ULID low // bits would scramble against the `id` tie-break of the `ORDER BY starts_at, @@ -101,13 +98,13 @@ impl SlotNote { /// overlapping, which is exactly how a teacher's hour is carved up. #[derive(Debug, Clone, SurrealValue)] pub struct AppointmentSlot { - id: AppointmentSlotId, - teacher: UserId, - starts_at: Timestamp, - ends_at: Timestamp, - note: Option, - series: Option, - created_at: Timestamp, + pub(crate) id: AppointmentSlotId, + pub(crate) teacher: UserId, + pub(crate) starts_at: Timestamp, + pub(crate) ends_at: Timestamp, + pub(crate) note: Option, + pub(crate) series: Option, + pub(crate) created_at: Timestamp, } impl AppointmentSlot { @@ -142,7 +139,10 @@ impl AppointmentSlot { /// A slot must cover a real span of time — an empty or inverted window /// could never be booked, and would break the touching-is-not-overlapping /// rule the conflict guard rests on. - fn check_window(starts_at: Timestamp, ends_at: Timestamp) -> Result<(), ValidationError> { + pub(crate) fn check_window( + starts_at: Timestamp, + ends_at: Timestamp, + ) -> Result<(), ValidationError> { if starts_at.as_millis() >= ends_at.as_millis() { return Err(ValidationError::Invalid { field: "ends_at", @@ -202,387 +202,14 @@ impl AppointmentSlot { }) .collect() } - - /// Write a whole publish — one occurrence or fifty-two — while the publisher - /// still *holds* a teaching role. - /// - /// Every row here names the teacher, so the write touches no key a demotion - /// touches: [`crate::domain::user::User::set_role`] sweeps the slots its own - /// snapshot can see, and a slot landing after that snapshot would survive it - /// under a role that may not publish — reachable by no route afterwards, - /// since the calendar hides a demoted teacher's slots and the deletes are - /// `teacher`-gated. So the teacher's own record is claimed beside the insert - /// ([`cap::role_claim`]), which is the key the demotion writes: either the - /// sweep sees these slots, or this write sees the new role and publishes - /// nothing. - /// - /// The bar is read off the hierarchy rather than spelled out, so a new role - /// cannot drift out of it. - /// - /// Admissible for [`transaction_with_retry`]: the claim is `SELECT`/`UPDATE` - /// only, and the `INSERT` carries freshly minted ULIDs on a table with no - /// `UNIQUE` index, so no rival can make it answer "already exists". - async fn insert_claimed( - teacher: &UserId, - rows: Vec, - db: &Database, - ) -> Result, AppError> { - let staff = ROLES - .iter() - .filter(|role| role.at_least(Role::Teacher)) - .map(|role| format!("'{}'", role.as_str())) - .collect::>() - .join(", "); - let held = cap::role_claim("teacher", &format!("NOT IN [{staff}]"), UNFIT_MARK); - let sql = format!( - "BEGIN TRANSACTION;\n{};\nINSERT INTO {APPOINTMENT_SLOT_TABLE} $rows;\n\ - COMMIT TRANSACTION;", - held.join(";\n") - ); - let (mut result, mut errors) = transaction_with_retry( - db, - &sql, - &[ - ("teacher".into(), teacher.record().into_value()), - ("rows".into(), rows.into_value()), - ], - &[UNFIT_MARK], - ) - .await?; - // Demoted while this ran — the same refusal `RequireTeacher` makes a - // moment earlier, and the only one that can arrive after it. - if errors - .values() - .any(|error| error.to_string().contains(UNFIT_MARK)) - { - return Err(AppError::Forbidden( - "that account no longer holds a teaching role", - )); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // BEGIN plus the claim's own statements — counted, not tallied by hand, - // so a statement added there cannot read back the wrong result. - Ok(result.take::>(held.len() + 1)?) - } - - /// Does the teacher already have a published slot whose window collides with - /// `[starts_at, ends_at)`? Half-open, so a slot ending exactly where the new - /// one starts is *not* a conflict — that is how a teacher's hour is carved - /// into back-to-back slots. Caller must hold - /// [`crate::service::appointment::APPOINTMENT_LOCK`] for the - /// answer to still be true by the time the insert lands. - async fn conflicts_existing( - teacher: &UserId, - starts_at: Timestamp, - ends_at: Timestamp, - db: &Database, - ) -> Result { - let mut result = db - .query( - "SELECT VALUE id FROM appointment_slot \ - WHERE teacher = $teacher AND starts_at < $ends AND ends_at > $starts \ - LIMIT 1", - ) - .bind(("teacher", teacher.record())) - .bind(("starts", starts_at.as_millis())) - .bind(("ends", ends_at.as_millis())) - .await? - .check()?; - Ok(!result.take::>(0)?.is_empty()) - } - - /// Every window this teacher already published that intersects the envelope - /// `[from, to)`. One read for a whole batch: a stored row that overlaps *any* - /// window in the batch necessarily overlaps the envelope spanning them all, - /// so filtering the envelope and comparing in memory is exactly the - /// per-window [`conflicts_existing`](Self::conflicts_existing) check, - /// hoisted out of the loop — which is what keeps - /// [`crate::service::appointment::APPOINTMENT_LOCK`] down - /// to two round trips instead of one per occurrence. - async fn windows_in_span( - teacher: &UserId, - from: Timestamp, - to: Timestamp, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM appointment_slot \ - WHERE teacher = $teacher AND starts_at < $to AND ends_at > $from", - ) - .bind(("teacher", teacher.record())) - .bind(("from", from.as_millis())) - .bind(("to", to.as_millis())) - .await? - .check()?; - Ok(result - .take::>(0)? - .into_iter() - .map(|slot| (slot.starts_at, slot.ends_at)) - .collect()) - } - - /// Publish one slot. - pub async fn create( - teacher: &UserId, - starts_at: Timestamp, - ends_at: Timestamp, - note: Option, - db: &Database, - ) -> Result { - Self::check_window(starts_at, ends_at)?; - // Check-then-insert under the lock so a concurrent publish or booking - // can't slip a colliding window in between. - let _guard = APPOINTMENT_LOCK.lock().await; - if Self::conflicts_existing(teacher, starts_at, ends_at, db).await? { - return Err(AppError::ConflictOwned( - "this time overlaps a slot you have already published".into(), - )); - } - Self::insert_claimed( - teacher, - vec![AppointmentSlot { - id: AppointmentSlotId::generate(), - teacher: teacher.clone(), - starts_at, - ends_at, - note, - series: None, - created_at: Timestamp::now(), - }], - db, - ) - .await? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to create appointment slot".into())) - } - - /// Publish the same weekly window repeatedly, up to `until`. Every row - /// carries the same [`SlotSeries`], so the whole publish stays addressable - /// (and deletable) as one thing while each occurrence remains an ordinary, - /// independently bookable and independently cancellable slot. - pub async fn publish_weekly( - teacher: &UserId, - starts_at: Timestamp, - ends_at: Timestamp, - note: Option, - until: Timestamp, - db: &Database, - ) -> Result, AppError> { - let windows = Self::weekly_windows(starts_at, ends_at, until)?; - // Validate the whole batch before writing a single row: all-or-nothing, - // so a mid-series collision never leaves stray weeks behind. Held under - // the lock from the check through the write, matching `create`. - let _guard = APPOINTMENT_LOCK.lock().await; - // (a) against the slots already in the database. `weekly_windows` walks - // forward, so the first and last occurrence bound every one of them. - let (first, last) = (windows[0], windows[windows.len() - 1]); - let published = Self::windows_in_span(teacher, first.0, last.1, db).await?; - for (i, &(w_start, w_end)) in windows.iter().enumerate() { - if published - .iter() - .any(|&(p_start, p_end)| Appointment::overlaps(w_start, w_end, p_start, p_end)) - { - return Err(AppError::ConflictOwned( - "a repeated slot overlaps one you have already published".into(), - )); - } - // (b) against every earlier occurrence in this same batch — catches - // a duration longer than the weekly step overlapping itself. - if windows[..i] - .iter() - .any(|&(o_start, o_end)| Appointment::overlaps(w_start, w_end, o_start, o_end)) - { - return Err(AppError::ConflictOwned( - "the repeated slots overlap each other".into(), - )); - } - } - let series = SlotSeries::generate(); - let now = Timestamp::now(); - let rows: Vec = windows - .iter() - .map(|&(starts_at, ends_at)| AppointmentSlot { - id: AppointmentSlotId::generate(), - teacher: teacher.clone(), - starts_at, - ends_at, - note: note.clone(), - series: Some(series.clone()), - created_at: now, - }) - .collect(); - // One `INSERT`, therefore all-or-nothing: SurrealDB rolls the whole - // publish back on any error. The row-by-row loop this replaces did not - // — a database error at week 7 of 10 answered 500 with six stray weeks - // already published, a half-series nobody asked for. It is also a single - // round trip, so the lock is held for two queries whatever the - // occurrence count, instead of 1 + N (up to 52) sequential ones. - let mut created = Self::insert_claimed(teacher, rows, db).await?; - if created.len() != windows.len() { - return Err(AppError::Internal(format!( - "published {} of {} appointment slots", - created.len(), - windows.len() - ))); - } - // `INSERT` makes no promise about the order it echoes rows back in, and - // the response is rendered as the published calendar. - created.sort_by_key(|slot| slot.starts_at.as_millis()); - Ok(created) - } - - pub async fn read( - id: &AppointmentSlotId, - db: &Database, - ) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - /// A teacher's own calendar, earliest first. - pub async fn list_for_teacher( - teacher: &UserId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM appointment_slot WHERE teacher = $teacher \ - ORDER BY starts_at ASC, id ASC", - ) - .bind(("teacher", teacher.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Every slot whose window has not opened yet, earliest first — the bookable - /// calendar a requester browses. - /// - /// The bound is `starts_at`, not `ends_at`, so that this window is exactly - /// the one [`crate::service::appointment::book`] accepts: a slot already underway is - /// unbookable (`cancel` could never undo the booking), and offering it would - /// be a calendar entry that can only answer `409`. The publish-time 60s skew - /// grace deliberately does not apply here either — `book` does not grant it, - /// and a slot published a moment after its own start is unbookable from - /// birth, so it belongs on nobody's calendar. - pub async fn list_upcoming( - from: Timestamp, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM appointment_slot WHERE starts_at > $from \ - ORDER BY starts_at ASC, id ASC", - ) - .bind(("from", from.as_millis())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - pub async fn list_for_series( - series: &SlotSeries, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM appointment_slot WHERE series = $series \ - ORDER BY starts_at ASC, id ASC", - ) - .bind(("series", series.as_str().to_string())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Delete one slot, refusing (409) while a live booking sits on it — the - /// requester is expecting that meeting, so it must be rejected first. - /// Settled bookings (rejected/cancelled) are history of a slot that is - /// going away, so they cascade out with it, like [`Event::delete`]'s rows. - /// - /// The guard is the delete's own `WHERE`, so no booking can land between a - /// check and the row going away. - pub async fn delete(self, db: &Database) -> Result { - Self::delete_free(std::slice::from_ref(&self.id), db).await?; - Ok(self) - } - - /// Delete a whole recurring publish, all-or-nothing: if *any* occurrence - /// still holds a live booking the entire series is refused, so the teacher - /// deals with the person waiting instead of silently keeping a stray week. - pub async fn delete_series( - series: &SlotSeries, - db: &Database, - ) -> Result, AppError> { - let slots = Self::list_for_series(series, db).await?; - if slots.is_empty() { - return Err(AppError::NotFound); - } - let ids: Vec = slots.iter().map(|slot| slot.id.clone()).collect(); - Self::delete_free(&ids, db).await?; - Ok(slots) - } - - /// Shared body of both deletes: drop every named slot, but only while its - /// `occupied` counter says nobody is waiting on it — the delete's own - /// `WHERE` is the guard, which is what makes it hold against a booking - /// landing in the middle of it (a separate read-then-delete could not). - /// - /// All-or-nothing across the whole list: if fewer rows go than were named, - /// the transaction is thrown away, so a series never loses its free weeks - /// and keeps the booked one. Whether that shortfall was a live booking or a - /// slot that no longer exists is read off what survived — the occupied rows - /// are still there, a vanished one is not — which is the 409/404 the caller - /// used to get from a separate check. - async fn delete_free(ids: &[AppointmentSlotId], db: &Database) -> Result<(), AppError> { - let records: Vec = ids.iter().map(|id| id.record()).collect(); - let (_, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - LET $gone = (DELETE $slots WHERE (occupied ?? 0) = 0 RETURN BEFORE); - IF array::len($gone) != array::len($slots) { - THROW IF array::len((SELECT VALUE id FROM appointment_slot - WHERE id IN $slots)) > 0 { 'slot_occupied' } ELSE { 'slot_missing' } - }; - DELETE appointment WHERE slot IN $slots; - RETURN $gone; - COMMIT TRANSACTION;", - &[("slots".into(), records.into_value())], - &["slot_occupied", "slot_missing"], - ) - .await?; - // An aborted transaction errors every slot; only the THROW's own slot - // names the marker (the `Exam::update` treatment), and a round lost to - // a booking landing on `occupied` mid-flight is re-sent rather than - // reported (see [`transaction_with_retry`]). - let thrown = |marker: &str| { - errors - .values() - .any(|error| error.to_string().contains(marker)) - }; - if thrown("slot_occupied") { - return Err(AppError::Conflict( - "the slot has a pending or approved booking", - )); - } - if thrown("slot_missing") { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - Ok(()) - } } #[cfg(test)] mod tests { use super::*; - use crate::constant::{MILLIS_PER_DAY, SLOT_OCCUPIED_FIELD}; - use crate::db::cap; + use crate::constant::{ + MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_DAY, MILLIS_PER_WEEK, + }; fn at(millis: i64) -> Timestamp { Timestamp::from_millis(millis) @@ -674,407 +301,4 @@ mod tests { 1 ); } - - /// Every occurrence of one publish must carry the same series id, and ids - /// minted back-to-back must stay in write order (the `ORDER BY` tie-break). - #[tokio::test] - async fn a_publish_shares_one_series_and_orders_its_ids() { - let db = crate::database::init_mem().await.unwrap(); - let teacher = UserId::from_key("t1"); - let slots = AppointmentSlot::publish_weekly( - &teacher, - at(1_000), - at(2_000), - Some(SlotNote::try_new("veli toplantısı").unwrap()), - at(1_000 + 4 * MILLIS_PER_WEEK), - &db, - ) - .await - .unwrap(); - - assert_eq!(slots.len(), 5); - let series = slots[0].get_series().cloned().unwrap(); - assert!(slots.iter().all(|slot| slot.get_series() == Some(&series))); - assert!( - slots - .windows(2) - .all(|pair| pair[0].get_id().key() < pair[1].get_id().key()) - ); - - let listed = AppointmentSlot::list_for_series(&series, &db) - .await - .unwrap(); - assert_eq!(listed.len(), 5); - } - - #[tokio::test] - async fn overlapping_publish_is_refused_but_touching_is_allowed() { - let db = crate::database::init_mem().await.unwrap(); - let teacher = UserId::from_key("t1"); - AppointmentSlot::create(&teacher, at(1_000), at(2_000), None, &db) - .await - .unwrap(); - - // Overlaps the existing [1000,2000) → 409. - assert!(matches!( - AppointmentSlot::create(&teacher, at(1_500), at(2_500), None, &db).await, - Err(AppError::ConflictOwned(_)) - )); - // Touching at the boundary (ends where the next starts) → allowed. - assert!( - AppointmentSlot::create(&teacher, at(2_000), at(3_000), None, &db) - .await - .is_ok() - ); - assert!( - AppointmentSlot::create(&teacher, at(0), at(1_000), None, &db) - .await - .is_ok() - ); - // A different teacher sharing the same window is fine. - let other = UserId::from_key("t2"); - assert!( - AppointmentSlot::create(&other, at(1_000), at(2_000), None, &db) - .await - .is_ok() - ); - } - - #[tokio::test] - async fn weekly_publish_overlapping_an_existing_slot_writes_nothing() { - let db = crate::database::init_mem().await.unwrap(); - let teacher = UserId::from_key("t1"); - // A lone slot on the third week of the coming series. - AppointmentSlot::create( - &teacher, - at(1_000 + 2 * MILLIS_PER_WEEK), - at(2_000 + 2 * MILLIS_PER_WEEK), - None, - &db, - ) - .await - .unwrap(); - - let before = AppointmentSlot::list_for_teacher(&teacher, &db) - .await - .unwrap() - .len(); - assert!(matches!( - AppointmentSlot::publish_weekly( - &teacher, - at(1_000), - at(2_000), - None, - at(1_000 + 4 * MILLIS_PER_WEEK), - &db, - ) - .await, - Err(AppError::ConflictOwned(_)) - )); - // All-or-nothing: not one occurrence of the rejected series was written. - assert_eq!( - AppointmentSlot::list_for_teacher(&teacher, &db) - .await - .unwrap() - .len(), - before - ); - } - - /// The existing-slot check is one envelope-wide read instead of a query per - /// occurrence, so the edges of that envelope are what could go wrong: a - /// clash on the *last* week must still be caught, and a slot merely touching - /// the batch's boundaries must still be allowed. - #[tokio::test] - async fn the_batch_wide_conflict_read_still_sees_the_last_week_and_lets_touching_through() { - let db = crate::database::init_mem().await.unwrap(); - let teacher = UserId::from_key("t1"); - let last = 1_000 + 4 * MILLIS_PER_WEEK; - // Touching both ends of the envelope: ends where the first occurrence - // starts, and starts where the last one ends. - AppointmentSlot::create(&teacher, at(0), at(1_000), None, &db) - .await - .unwrap(); - AppointmentSlot::create(&teacher, at(last + 1_000), at(last + 2_000), None, &db) - .await - .unwrap(); - assert_eq!( - AppointmentSlot::publish_weekly(&teacher, at(1_000), at(2_000), None, at(last), &db) - .await - .unwrap() - .len(), - 5 - ); - - // One millisecond into the last occurrence → the whole publish is 409. - let db = crate::database::init_mem().await.unwrap(); - AppointmentSlot::create(&teacher, at(last + 999), at(last + 3_000), None, &db) - .await - .unwrap(); - assert!(matches!( - AppointmentSlot::publish_weekly(&teacher, at(1_000), at(2_000), None, at(last), &db) - .await, - Err(AppError::ConflictOwned(_)) - )); - assert_eq!( - AppointmentSlot::list_for_teacher(&teacher, &db) - .await - .unwrap() - .len(), - 1 - ); - } - - /// The delete-vs-book race: a booking that lands between this delete's read - /// and its write must still keep the slot alive, so the guard has to be the - /// delete's own `WHERE` — here driven by taking the seat the way that - /// booking would, with no booking row to read. - /// - /// A series is all-or-nothing: one taken week refuses the whole publish, - /// and the free weeks must survive the refusal. - #[tokio::test] - async fn a_taken_slot_is_never_deleted_and_takes_its_series_with_it() { - let db = crate::database::init_mem().await.unwrap(); - let teacher = UserId::from_key("t1"); - let slots = AppointmentSlot::publish_weekly( - &teacher, - at(1_000), - at(2_000), - None, - at(1_000 + 2 * MILLIS_PER_WEEK), - &db, - ) - .await - .unwrap(); - let series = slots[0].get_series().cloned().unwrap(); - - // A free slot goes, and its series is deletable while every week is free. - assert!(slots[0].clone().delete(&db).await.is_ok()); - // The seat on the middle week is taken — no booking row, exactly as a - // racing booking would leave it mid-flight. - assert!( - cap::claim(&slots[1].get_id().record(), SLOT_OCCUPIED_FIELD, 1, &db) - .await - .unwrap() - ); - assert!(matches!( - slots[1].clone().delete(&db).await, - Err(AppError::Conflict( - "the slot has a pending or approved booking" - )) - )); - assert!(matches!( - AppointmentSlot::delete_series(&series, &db).await, - Err(AppError::Conflict(_)) - )); - // Refused, not half-applied: the free third week is still published. - assert_eq!( - AppointmentSlot::list_for_series(&series, &db) - .await - .unwrap() - .len(), - 2 - ); - - // A slot that is simply gone is a 404, not a 409 — the delete tells the - // two shortfalls apart by what survived it. - assert!(matches!( - slots[0].clone().delete(&db).await, - Err(AppError::NotFound) - )); - } - - /// The claim on the publisher's own record, asked exactly the way the race - /// asks it: a publish whose `RequireTeacher` snapshot predates a demotion - /// must not land, because the sweep in that demotion has already chosen the - /// slots it will take and would leave this one behind — under a role that - /// can neither list nor delete it. - /// - /// Both halves matter: a row that is *not there* claims nothing (every other - /// test here publishes for a teacher with no user row at all), and a live - /// teacher+ passes through untouched. - #[tokio::test] - async fn a_publish_by_someone_who_lost_the_role_is_refused() { - let db = crate::database::init_mem().await.unwrap(); - // Written as a row rather than through `User` — the password hasher is - // private to that module, and the only column this asks about is `role`. - db.query("CREATE user:eski SET username = 'eski', password_hash = 'x', role = 'student'") - .await - .unwrap() - .check() - .unwrap(); - - // The row says `student`, so the claim refuses — one-off and weekly - // alike, since both go through the same write. - let teacher = UserId::from_key("eski"); - assert!(matches!( - AppointmentSlot::create(&teacher, at(1_000), at(2_000), None, &db).await, - Err(AppError::Forbidden(_)) - )); - assert!(matches!( - AppointmentSlot::publish_weekly( - &teacher, - at(1_000), - at(2_000), - None, - at(1_000 + MILLIS_PER_WEEK), - &db, - ) - .await, - Err(AppError::Forbidden(_)) - )); - assert!( - AppointmentSlot::list_for_teacher(&teacher, &db) - .await - .unwrap() - .is_empty(), - "a refused publish must write nothing" - ); - - // Promoted, the very same publish lands. - db.query("UPDATE user:eski SET role = 'teacher'") - .await - .unwrap() - .check() - .unwrap(); - AppointmentSlot::create(&teacher, at(1_000), at(2_000), None, &db) - .await - .unwrap(); - assert_eq!( - AppointmentSlot::list_for_teacher(&teacher, &db) - .await - .unwrap() - .len(), - 1 - ); - } - - /// The other half of that claim: the publish that arrives *while* the - /// demotion is running. Its sweep has already chosen the slots it will take - /// ([`crate::domain::user::User::set_role`] reads them into `$slots` before - /// it deletes), so a row landing after that read shares no key with anything - /// the demotion writes and survives it — a slot owned by someone who can - /// neither list nor delete it, forever. The claim on the user record is what - /// puts the two transactions on one key. - /// - /// Real server, and `#[ignore]`d for it, like every other race here: the - /// subject *is* the store's conflict detection, which `init_mem`'s embedded - /// engine does not have — it commits both sides and answers `Ok` to each, so - /// this passes there on broken code. - /// - /// The window is opened by the schema rather than by a lucky interleaving: a - /// `DEFINE EVENT` on the sweep's own `DELETE` holds the demotion open inside - /// its transaction, well past the read that chose `$slots`, so the publish - /// lands in the middle of it every round. - /// - /// Stored state is the verdict, not the return value: whether the publish is - /// refused outright or swept along with the rest of the calendar, no slot may - /// outlive the role. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn a_publish_landing_inside_a_demotion_never_outlives_the_role() { - use crate::domain::role::Role; - use crate::domain::user::User; - - let (db, _serialized) = crate::database::init_test_server("slot_demotion_race").await; - let (mut raced, mut published, mut stranded) = (0, 0, 0); - for round in 0..4 { - let key = format!("t{round}"); - let teacher = UserId::from_key(&key); - db.query(format!( - "CREATE user:{key} SET username = '{key}', password_hash = 'x', \ - role = '{}';", - Role::Teacher.as_str() - )) - .await - .unwrap() - .check() - .unwrap(); - // A slot for the sweep to delete — that delete is the seam. - AppointmentSlot::create(&teacher, at(1_000), at(2_000), None, &db) - .await - .unwrap(); - db.query(format!( - "DEFINE EVENT OVERWRITE hold_the_sweep ON TABLE {APPOINTMENT_SLOT_TABLE} \ - WHEN $event = 'DELETE' THEN {{ IF $before.teacher = \ - type::record('user', '{key}') {{ SLEEP 300ms }} }};" - )) - .await - .unwrap() - .check() - .unwrap(); - - let demoting = { - let db = db.clone(); - let target = teacher.clone(); - tokio::spawn(async move { - User::read(&target, &db) - .await - .unwrap() - .unwrap() - .set_role(Role::Student, &db) - .await - }) - }; - tokio::time::sleep(std::time::Duration::from_millis(50)).await; - if !demoting.is_finished() { - raced += 1; - } - // The publish a `RequireTeacher` snapshot taken a moment ago allows. - let landed = AppointmentSlot::create( - &teacher, - at(MILLIS_PER_WEEK), - at(MILLIS_PER_WEEK + 1_000), - None, - &db, - ) - .await; - let swept = demoting.await.unwrap(); - assert!(swept.is_ok(), "round {round}: the demotion itself failed"); - if landed.is_ok() { - published += 1; - } - if !AppointmentSlot::list_for_teacher(&teacher, &db) - .await - .unwrap() - .is_empty() - { - stranded += 1; - } - } - eprintln!( - "a publish racing a demotion: {raced}/4 rounds landed inside it, \ - {published} publishes committed" - ); - assert!(raced > 0, "no round ever reached the race"); - assert_eq!( - stranded, 0, - "a slot survived under a role that can neither list nor delete it" - ); - } - - #[tokio::test] - async fn weekly_publish_that_self_overlaps_is_refused() { - let db = crate::database::init_mem().await.unwrap(); - let teacher = UserId::from_key("t1"); - // A window longer than the weekly step collides with the next week. - assert!(matches!( - AppointmentSlot::publish_weekly( - &teacher, - at(0), - at(MILLIS_PER_WEEK + 1), - None, - at(MILLIS_PER_WEEK), - &db, - ) - .await, - Err(AppError::ConflictOwned(_)) - )); - assert!( - AppointmentSlot::list_for_teacher(&teacher, &db) - .await - .unwrap() - .is_empty() - ); - } } diff --git a/src/domain/user.rs b/src/domain/user.rs index 38e7ebd..4b3cb69 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -772,7 +772,7 @@ impl User { // `Appointment::book` claims the slot row this deletes, so the two // collide in the store and the loser re-sends. A slot *published* // concurrently shares no key with any of this, which is why - // `AppointmentSlot::insert_claimed` claims the user row instead. + // `crate::db::appointment_slot::insert_claimed` claims the user row instead. batch.push(format!( "DELETE {APPOINTMENT_SLOT_TABLE} WHERE id IN $slots" )); @@ -1079,8 +1079,8 @@ mod tests { #[tokio::test] async fn a_demotion_withdraws_the_calendar_and_settles_its_bookings() { use crate::domain::appointment::AppointmentReason; - use crate::domain::appointment_slot::AppointmentSlot; use crate::service::appointment; + use crate::service::appointment_slot; let db = init_mem().await.unwrap(); let staff = |name: &'static str, db: Database| async move { @@ -1099,7 +1099,7 @@ mod tests { let slot = |owner: &User, offset: i64, db: Database| { let owner = owner.get_id().clone(); async move { - AppointmentSlot::create(&owner, soon(offset), soon(offset + 60_000), None, &db) + appointment_slot::create(&db, &owner, soon(offset), soon(offset + 60_000), None) .await .unwrap() } @@ -1127,14 +1127,14 @@ mod tests { // The calendar is gone, the booked weeks included. assert!( - AppointmentSlot::list_for_teacher(teacher.get_id(), &db) + appointment_slot::list_for_teacher(&db, teacher.get_id()) .await .unwrap() .is_empty() ); for slot in [&free, &asked, &agreed] { assert!( - AppointmentSlot::read(slot.get_id(), &db) + appointment_slot::read(&db, slot.get_id()) .await .unwrap() .is_none(), @@ -1167,7 +1167,7 @@ mod tests { // Another teacher's calendar is nobody else's business. assert_eq!( - AppointmentSlot::list_for_teacher(other.get_id(), &db) + appointment_slot::list_for_teacher(&db, other.get_id()) .await .unwrap() .len(), diff --git a/src/service/appointment.rs b/src/service/appointment.rs index 2795225..d7a6864 100644 --- a/src/service/appointment.rs +++ b/src/service/appointment.rs @@ -13,11 +13,12 @@ use tokio::sync::Mutex; use crate::constant::{CAS_UPDATE_RETRIES, SLOT_OCCUPIED_FIELD}; use crate::database::Database; use crate::db::appointment; +use crate::db::appointment_slot; use crate::db::cap; use crate::domain::appointment::{ Appointment, AppointmentId, AppointmentReason, AppointmentStatus, }; -use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId}; +use crate::domain::appointment_slot::AppointmentSlotId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -62,7 +63,7 @@ pub async fn book( reason: AppointmentReason, ) -> Result { let _guard = APPOINTMENT_LOCK.lock().await; - let slot_row = AppointmentSlot::read(slot, db) + let slot_row = appointment_slot::read(db, slot) .await? .ok_or(AppError::NotFound)?; // A window that has opened is history, not a plan: `cancel` refuses to @@ -123,7 +124,7 @@ pub async fn book( { cap::Claimed::Made(created) => Ok(created), cap::Claimed::Full => { - if AppointmentSlot::read(slot, db).await?.is_none() { + if appointment_slot::read(db, slot).await?.is_none() { return Err(AppError::NotFound); } Err(AppError::Conflict("the slot is already booked")) @@ -136,10 +137,7 @@ pub async fn book( /// The row, for callers that only inspect it — the web layer's authorization /// gates read through here. -pub async fn read( - db: &Database, - id: &AppointmentId, -) -> Result, AppError> { +pub async fn read(db: &Database, id: &AppointmentId) -> Result, AppError> { appointment::read(db, id).await } @@ -216,7 +214,7 @@ async fn approve_inner( } _ => {} } - let slot = AppointmentSlot::read(&expected.slot, db) + let slot = appointment_slot::read(db, &expected.slot) .await? .ok_or(AppError::NotFound)?; let (starts_at, ends_at) = expected.window(&slot); @@ -296,7 +294,7 @@ pub async fn cancel( if !expected.status.is_live() { return Err(AppError::Conflict("the appointment is already settled")); } - let slot = AppointmentSlot::read(&expected.slot, db) + let slot = appointment_slot::read(db, &expected.slot) .await? .ok_or(AppError::NotFound)?; if expected.window(&slot).0.as_millis() <= Timestamp::now().as_millis() { @@ -395,6 +393,7 @@ fn contended() -> AppError { mod tests { use super::*; use crate::database::{Database, init_mem}; + use crate::service::appointment_slot; fn at(millis: i64) -> Timestamp { Timestamp::from_millis(millis) @@ -410,7 +409,7 @@ mod tests { let db = init_mem().await.unwrap(); let teacher = UserId::from_key("t1"); let (starts_at, ends_at) = (soon(60_000), soon(120_000)); - let slot = AppointmentSlot::create(&teacher, starts_at, ends_at, None, &db) + let slot = appointment_slot::create(&db, &teacher, starts_at, ends_at, None) .await .unwrap(); let mut appointment_row = book( @@ -435,7 +434,7 @@ mod tests { let db = init_mem().await.unwrap(); let teacher = UserId::from_key("t1"); let reason = || AppointmentReason::try_new("görüşme").unwrap(); - let started = AppointmentSlot::create(&teacher, soon(-30_000), soon(60_000), None, &db) + let started = appointment_slot::create(&db, &teacher, soon(-30_000), soon(60_000), None) .await .unwrap(); assert!(matches!( @@ -443,12 +442,14 @@ mod tests { Err(AppError::Conflict("the slot has already started")) )); - let upcoming = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) + let upcoming = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) .await .unwrap(); - assert!(book(&db, upcoming.get_id(), &UserId::from_key("s1"), reason()) - .await - .is_ok()); + assert!( + book(&db, upcoming.get_id(), &UserId::from_key("s1"), reason()) + .await + .is_ok() + ); } /// Approval judges the *effective* window, so a proposal whose time has @@ -458,7 +459,7 @@ mod tests { let db = init_mem().await.unwrap(); let teacher = UserId::from_key("t1"); let student = UserId::from_key("s1"); - let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) + let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) .await .unwrap(); let booking = book( @@ -492,8 +493,14 @@ mod tests { .unwrap() .unwrap(); assert!(matches!( - accept_proposal(&db, booking.get_id(), &student, passed_starts_at, passed_ends_at) - .await, + accept_proposal( + &db, + booking.get_id(), + &student, + passed_starts_at, + passed_ends_at + ) + .await, Err(AppError::Conflict("that time has already started")) )); // Refused, not half-applied: still pending, still decidable at a time @@ -507,8 +514,14 @@ mod tests { // Accepting a window that is *not* the standing proposal is refused — // the pin is what the requester saw, not a request to move the meeting. assert!(matches!( - accept_proposal(&db, booking.get_id(), &student, passed_starts_at, passed_ends_at) - .await, + accept_proposal( + &db, + booking.get_id(), + &student, + passed_starts_at, + passed_ends_at + ) + .await, Err(AppError::Conflict( "the proposed time has changed; \ re-read the booking and accept the new one" @@ -534,7 +547,7 @@ mod tests { let db = init_mem().await.unwrap(); let teacher = UserId::from_key("t1"); let student = UserId::from_key("s1"); - let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) + let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) .await .unwrap(); let booking = book( @@ -551,9 +564,15 @@ mod tests { // `pending` status. let stale = booking.clone(); let (proposed_starts_at, proposed_ends_at) = (soon(180_000), soon(240_000)); - propose(&db, booking.get_id(), proposed_starts_at, proposed_ends_at, &teacher) - .await - .unwrap(); + propose( + &db, + booking.get_id(), + proposed_starts_at, + proposed_ends_at, + &teacher, + ) + .await + .unwrap(); let mut late = stale.clone(); late.status = AppointmentStatus::Approved; @@ -616,7 +635,7 @@ mod tests { async fn a_concurrent_claim_cannot_take_a_booked_slot() { let db = init_mem().await.unwrap(); let teacher = UserId::from_key("t1"); - let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) + let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) .await .unwrap(); assert_eq!(occupied(slot.get_id(), &db).await, 0); @@ -657,7 +676,7 @@ mod tests { async fn a_refused_booking_moves_nothing() { let db = init_mem().await.unwrap(); let teacher = UserId::from_key("t1"); - let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) + let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) .await .unwrap(); let reason = || AppointmentReason::try_new("görüşme").unwrap(); @@ -695,7 +714,7 @@ mod tests { let db = init_mem().await.unwrap(); let teacher = UserId::from_key("t1"); let student = UserId::from_key("s1"); - let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) + let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) .await .unwrap(); let booking = book( @@ -709,21 +728,21 @@ mod tests { approve(&db, booking.get_id(), &teacher).await.unwrap(); assert_eq!(occupied(slot.get_id(), &db).await, 1, "approval holds it"); - cancel(&db, booking.get_id(), &student, None) - .await - .unwrap(); + cancel(&db, booking.get_id(), &student, None).await.unwrap(); assert_eq!(occupied(slot.get_id(), &db).await, 0); // Cancelling twice is refused, so the seat cannot go back twice either. assert!(cancel(&db, booking.get_id(), &student, None).await.is_err()); assert_eq!(occupied(slot.get_id(), &db).await, 0); - assert!(book( - &db, - slot.get_id(), - &UserId::from_key("s2"), - AppointmentReason::try_new("görüşme").unwrap() - ) - .await - .is_ok()); + assert!( + book( + &db, + slot.get_id(), + &UserId::from_key("s2"), + AppointmentReason::try_new("görüşme").unwrap() + ) + .await + .is_ok() + ); assert_eq!(occupied(slot.get_id(), &db).await, 1); } @@ -732,7 +751,7 @@ mod tests { async fn rejecting_frees_the_slot_for_re_booking() { let db = init_mem().await.unwrap(); let teacher = UserId::from_key("t1"); - let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) + let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None) .await .unwrap(); let reason = || AppointmentReason::try_new("görüşme").unwrap(); @@ -746,13 +765,11 @@ mod tests { )); // The live booking also blocks the slot delete. assert!(matches!( - slot.clone().delete(&db).await, + appointment_slot::delete(&db, slot.clone()).await, Err(AppError::Conflict(_)) )); - reject(&db, first.get_id(), &teacher, None) - .await - .unwrap(); + reject(&db, first.get_id(), &teacher, None).await.unwrap(); assert_eq!(occupied(slot.get_id(), &db).await, 0); let second = book(&db, slot.get_id(), &UserId::from_key("s2"), reason()) .await diff --git a/src/service/appointment_slot.rs b/src/service/appointment_slot.rs new file mode 100644 index 0000000..8b1bef6 --- /dev/null +++ b/src/service/appointment_slot.rs @@ -0,0 +1,556 @@ +//! Slot publishing and withdrawal: the one-off and weekly publishes, the +//! single and series deletes, and the reads the web layer renders the +//! calendar from. Row reads, listings, the overlap probes, the role-claimed +//! INSERT, and the guarded delete live in [`crate::db::appointment_slot`]. +//! +//! Publishing holds [`APPOINTMENT_LOCK`] from the conflict check through the +//! write — the same lock the booking path takes — so a concurrent publish or +//! booking cannot slip a colliding window in between the check and the +//! insert. + +use crate::database::Database; +use crate::db::appointment_slot; +use crate::domain::appointment::Appointment; +use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId, SlotNote, SlotSeries}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +use super::appointment::APPOINTMENT_LOCK; + +/// The row, for callers that only inspect it — the web layer's gates read +/// through here. +pub async fn read( + db: &Database, + id: &AppointmentSlotId, +) -> Result, AppError> { + appointment_slot::read(db, id).await +} + +/// A teacher's own calendar, earliest first — the web layer's calendar read. +pub async fn list_for_teacher( + db: &Database, + teacher: &UserId, +) -> Result, AppError> { + appointment_slot::list_for_teacher(db, teacher).await +} + +/// Every slot whose window has not opened yet, earliest first — the bookable +/// calendar a requester browses. +pub async fn list_upcoming( + db: &Database, + from: Timestamp, +) -> Result, AppError> { + appointment_slot::list_upcoming(db, from).await +} + +/// Every slot of one recurring publish, earliest first. +pub async fn list_for_series( + db: &Database, + series: &SlotSeries, +) -> Result, AppError> { + appointment_slot::list_for_series(db, series).await +} + +/// Publish one slot. +pub async fn create( + db: &Database, + teacher: &UserId, + starts_at: Timestamp, + ends_at: Timestamp, + note: Option, +) -> Result { + AppointmentSlot::check_window(starts_at, ends_at)?; + // Check-then-insert under the lock so a concurrent publish or booking + // can't slip a colliding window in between. + let _guard = APPOINTMENT_LOCK.lock().await; + if appointment_slot::conflicts_existing(db, teacher, starts_at, ends_at).await? { + return Err(AppError::ConflictOwned( + "this time overlaps a slot you have already published".into(), + )); + } + appointment_slot::insert_claimed( + db, + teacher, + vec![AppointmentSlot { + id: AppointmentSlotId::generate(), + teacher: teacher.clone(), + starts_at, + ends_at, + note, + series: None, + created_at: Timestamp::now(), + }], + ) + .await? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to create appointment slot".into())) +} + +/// Publish the same weekly window repeatedly, up to `until`. Every row +/// carries the same [`SlotSeries`], so the whole publish stays addressable +/// (and deletable) as one thing while each occurrence remains an ordinary, +/// independently bookable and independently cancellable slot. +pub async fn publish_weekly( + db: &Database, + teacher: &UserId, + starts_at: Timestamp, + ends_at: Timestamp, + note: Option, + until: Timestamp, +) -> Result, AppError> { + let windows = AppointmentSlot::weekly_windows(starts_at, ends_at, until)?; + // Validate the whole batch before writing a single row: all-or-nothing, + // so a mid-series collision never leaves stray weeks behind. Held under + // the lock from the check through the write, matching `create`. + let _guard = APPOINTMENT_LOCK.lock().await; + // (a) against the slots already in the database. `weekly_windows` walks + // forward, so the first and last occurrence bound every one of them. + let (first, last) = (windows[0], windows[windows.len() - 1]); + let published = appointment_slot::windows_in_span(db, teacher, first.0, last.1).await?; + for (i, &(w_start, w_end)) in windows.iter().enumerate() { + if published + .iter() + .any(|&(p_start, p_end)| Appointment::overlaps(w_start, w_end, p_start, p_end)) + { + return Err(AppError::ConflictOwned( + "a repeated slot overlaps one you have already published".into(), + )); + } + // (b) against every earlier occurrence in this same batch — catches + // a duration longer than the weekly step overlapping itself. + if windows[..i] + .iter() + .any(|&(o_start, o_end)| Appointment::overlaps(w_start, w_end, o_start, o_end)) + { + return Err(AppError::ConflictOwned( + "the repeated slots overlap each other".into(), + )); + } + } + let series = SlotSeries::generate(); + let now = Timestamp::now(); + let rows: Vec = windows + .iter() + .map(|&(starts_at, ends_at)| AppointmentSlot { + id: AppointmentSlotId::generate(), + teacher: teacher.clone(), + starts_at, + ends_at, + note: note.clone(), + series: Some(series.clone()), + created_at: now, + }) + .collect(); + // One `INSERT`, therefore all-or-nothing: SurrealDB rolls the whole + // publish back on any error. The row-by-row loop this replaces did not + // — a database error at week 7 of 10 answered 500 with six stray weeks + // already published, a half-series nobody asked for. It is also a single + // round trip, so the lock is held for two queries whatever the + // occurrence count, instead of 1 + N (up to 52) sequential ones. + let mut created = appointment_slot::insert_claimed(db, teacher, rows).await?; + if created.len() != windows.len() { + return Err(AppError::Internal(format!( + "published {} of {} appointment slots", + created.len(), + windows.len() + ))); + } + // `INSERT` makes no promise about the order it echoes rows back in, and + // the response is rendered as the published calendar. + created.sort_by_key(|slot| slot.starts_at.as_millis()); + Ok(created) +} + +/// Delete one slot, refusing (409) while a live booking sits on it — the +/// requester is expecting that meeting, so it must be rejected first. +/// Settled bookings (rejected/cancelled) are history of a slot that is +/// going away, so they cascade out with it, like `Event::delete`'s rows. +/// +/// The guard is the delete's own `WHERE`, so no booking can land between a +/// check and the row going away. +pub async fn delete(db: &Database, slot: AppointmentSlot) -> Result { + appointment_slot::delete_free(db, std::slice::from_ref(slot.get_id())).await?; + Ok(slot) +} + +/// Delete a whole recurring publish, all-or-nothing: if *any* occurrence +/// still holds a live booking the entire series is refused, so the teacher +/// deals with the person waiting instead of silently keeping a stray week. +pub async fn delete_series( + db: &Database, + series: &SlotSeries, +) -> Result, AppError> { + let slots = appointment_slot::list_for_series(db, series).await?; + if slots.is_empty() { + return Err(AppError::NotFound); + } + let ids: Vec = slots.iter().map(|slot| slot.id.clone()).collect(); + appointment_slot::delete_free(db, &ids).await?; + Ok(slots) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::constant::{APPOINTMENT_SLOT_TABLE, MILLIS_PER_WEEK, SLOT_OCCUPIED_FIELD}; + use crate::db::cap; + + fn at(millis: i64) -> Timestamp { + Timestamp::from_millis(millis) + } + + #[tokio::test] + async fn a_publish_shares_one_series_and_orders_its_ids() { + let db = crate::database::init_mem().await.unwrap(); + let teacher = UserId::from_key("t1"); + let slots = publish_weekly( + &db, + &teacher, + at(1_000), + at(2_000), + Some(SlotNote::try_new("veli toplantısı").unwrap()), + at(1_000 + 4 * MILLIS_PER_WEEK), + ) + .await + .unwrap(); + + assert_eq!(slots.len(), 5); + let series = slots[0].get_series().cloned().unwrap(); + assert!(slots.iter().all(|slot| slot.get_series() == Some(&series))); + assert!( + slots + .windows(2) + .all(|pair| pair[0].get_id().key() < pair[1].get_id().key()) + ); + + let listed = list_for_series(&db, &series).await.unwrap(); + assert_eq!(listed.len(), 5); + } + + #[tokio::test] + async fn overlapping_publish_is_refused_but_touching_is_allowed() { + let db = crate::database::init_mem().await.unwrap(); + let teacher = UserId::from_key("t1"); + create(&db, &teacher, at(1_000), at(2_000), None) + .await + .unwrap(); + + // Overlaps the existing [1000,2000) → 409. + assert!(matches!( + create(&db, &teacher, at(1_500), at(2_500), None).await, + Err(AppError::ConflictOwned(_)) + )); + // Touching at the boundary (ends where the next starts) → allowed. + assert!( + create(&db, &teacher, at(2_000), at(3_000), None) + .await + .is_ok() + ); + assert!(create(&db, &teacher, at(0), at(1_000), None).await.is_ok()); + // A different teacher sharing the same window is fine. + let other = UserId::from_key("t2"); + assert!( + create(&db, &other, at(1_000), at(2_000), None) + .await + .is_ok() + ); + } + + #[tokio::test] + async fn weekly_publish_overlapping_an_existing_slot_writes_nothing() { + let db = crate::database::init_mem().await.unwrap(); + let teacher = UserId::from_key("t1"); + // A lone slot on the third week of the coming series. + create( + &db, + &teacher, + at(1_000 + 2 * MILLIS_PER_WEEK), + at(2_000 + 2 * MILLIS_PER_WEEK), + None, + ) + .await + .unwrap(); + + let before = list_for_teacher(&db, &teacher).await.unwrap().len(); + assert!(matches!( + publish_weekly( + &db, + &teacher, + at(1_000), + at(2_000), + None, + at(1_000 + 4 * MILLIS_PER_WEEK), + ) + .await, + Err(AppError::ConflictOwned(_)) + )); + // All-or-nothing: not one occurrence of the rejected series was written. + assert_eq!(list_for_teacher(&db, &teacher).await.unwrap().len(), before); + } + + /// The existing-slot check is one envelope-wide read instead of a query per + /// occurrence, so the edges of that envelope are what could go wrong: a + /// clash on the *last* week must still be caught, and a slot merely touching + /// the batch's boundaries must still be allowed. + #[tokio::test] + async fn the_batch_wide_conflict_read_still_sees_the_last_week_and_lets_touching_through() { + let db = crate::database::init_mem().await.unwrap(); + let teacher = UserId::from_key("t1"); + let last = 1_000 + 4 * MILLIS_PER_WEEK; + // Touching both ends of the envelope: ends where the first occurrence + // starts, and starts where the last one ends. + create(&db, &teacher, at(0), at(1_000), None).await.unwrap(); + create(&db, &teacher, at(last + 1_000), at(last + 2_000), None) + .await + .unwrap(); + assert_eq!( + publish_weekly(&db, &teacher, at(1_000), at(2_000), None, at(last)) + .await + .unwrap() + .len(), + 5 + ); + + // One millisecond into the last occurrence → the whole publish is 409. + let db = crate::database::init_mem().await.unwrap(); + create(&db, &teacher, at(last + 999), at(last + 3_000), None) + .await + .unwrap(); + assert!(matches!( + publish_weekly(&db, &teacher, at(1_000), at(2_000), None, at(last)).await, + Err(AppError::ConflictOwned(_)) + )); + assert_eq!(list_for_teacher(&db, &teacher).await.unwrap().len(), 1); + } + + /// The delete-vs-book race: a booking that lands between this delete's read + /// and its write must still keep the slot alive, so the guard has to be the + /// delete's own `WHERE` — here driven by taking the seat the way that + /// booking would, with no booking row to read. + /// + /// A series is all-or-nothing: one taken week refuses the whole publish, + /// and the free weeks must survive the refusal. + #[tokio::test] + async fn a_taken_slot_is_never_deleted_and_takes_its_series_with_it() { + let db = crate::database::init_mem().await.unwrap(); + let teacher = UserId::from_key("t1"); + let slots = publish_weekly( + &db, + &teacher, + at(1_000), + at(2_000), + None, + at(1_000 + 2 * MILLIS_PER_WEEK), + ) + .await + .unwrap(); + let series = slots[0].get_series().cloned().unwrap(); + + // A free slot goes, and its series is deletable while every week is free. + assert!(delete(&db, slots[0].clone()).await.is_ok()); + // The seat on the middle week is taken — no booking row, exactly as a + // racing booking would leave it mid-flight. + assert!( + cap::claim(&slots[1].get_id().record(), SLOT_OCCUPIED_FIELD, 1, &db) + .await + .unwrap() + ); + assert!(matches!( + delete(&db, slots[1].clone()).await, + Err(AppError::Conflict( + "the slot has a pending or approved booking" + )) + )); + assert!(matches!( + delete_series(&db, &series).await, + Err(AppError::Conflict(_)) + )); + // Refused, not half-applied: the free third week is still published. + assert_eq!(list_for_series(&db, &series).await.unwrap().len(), 2); + + // A slot that is simply gone is a 404, not a 409 — the delete tells the + // two shortfalls apart by what survived it. + assert!(matches!( + delete(&db, slots[0].clone()).await, + Err(AppError::NotFound) + )); + } + + /// The claim on the publisher's own record, asked exactly the way the race + /// asks it: a publish whose `RequireTeacher` snapshot predates a demotion + /// must not land, because the sweep in that demotion has already chosen the + /// slots it will take and would leave this one behind — under a role that + /// can neither list nor delete it. + /// + /// Both halves matter: a row that is *not there* claims nothing (every other + /// test here publishes for a teacher with no user row at all), and a live + /// teacher+ passes through untouched. + #[tokio::test] + async fn a_publish_by_someone_who_lost_the_role_is_refused() { + let db = crate::database::init_mem().await.unwrap(); + // Written as a row rather than through `User` — the password hasher is + // private to that module, and the only column this asks about is `role`. + db.query("CREATE user:eski SET username = 'eski', password_hash = 'x', role = 'student'") + .await + .unwrap() + .check() + .unwrap(); + + // The row says `student`, so the claim refuses — one-off and weekly + // alike, since both go through the same write. + let teacher = UserId::from_key("eski"); + assert!(matches!( + create(&db, &teacher, at(1_000), at(2_000), None).await, + Err(AppError::Forbidden(_)) + )); + assert!(matches!( + publish_weekly( + &db, + &teacher, + at(1_000), + at(2_000), + None, + at(1_000 + MILLIS_PER_WEEK), + ) + .await, + Err(AppError::Forbidden(_)) + )); + assert!( + list_for_teacher(&db, &teacher).await.unwrap().is_empty(), + "a refused publish must write nothing" + ); + + // Promoted, the very same publish lands. + db.query("UPDATE user:eski SET role = 'teacher'") + .await + .unwrap() + .check() + .unwrap(); + create(&db, &teacher, at(1_000), at(2_000), None) + .await + .unwrap(); + assert_eq!(list_for_teacher(&db, &teacher).await.unwrap().len(), 1); + } + + /// The other half of that claim: the publish that arrives *while* the + /// demotion is running. Its sweep has already chosen the slots it will take + /// ([`crate::domain::user::User::set_role`] reads them into `$slots` before + /// it deletes), so a row landing after that read shares no key with anything + /// the demotion writes and survives it — a slot owned by someone who can + /// neither list nor delete it, forever. The claim on the user record is what + /// puts the two transactions on one key. + /// + /// Real server, and `#[ignore]`d for it, like every other race here: the + /// subject *is* the store's conflict detection, which `init_mem`'s embedded + /// engine does not have — it commits both sides and answers `Ok` to each, so + /// this passes there on broken code. + /// + /// The window is opened by the schema rather than by a lucky interleaving: a + /// `DEFINE EVENT` on the sweep's own `DELETE` holds the demotion open inside + /// its transaction, well past the read that chose `$slots`, so the publish + /// lands in the middle of it every round. + /// + /// Stored state is the verdict, not the return value: whether the publish is + /// refused outright or swept along with the rest of the calendar, no slot may + /// outlive the role. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_publish_landing_inside_a_demotion_never_outlives_the_role() { + use crate::domain::role::Role; + use crate::domain::user::User; + + let (db, _serialized) = crate::database::init_test_server("slot_demotion_race").await; + let (mut raced, mut published, mut stranded) = (0, 0, 0); + for round in 0..4 { + let key = format!("t{round}"); + let teacher = UserId::from_key(&key); + db.query(format!( + "CREATE user:{key} SET username = '{key}', password_hash = 'x', \ + role = '{}';", + Role::Teacher.as_str() + )) + .await + .unwrap() + .check() + .unwrap(); + // A slot for the sweep to delete — that delete is the seam. + create(&db, &teacher, at(1_000), at(2_000), None) + .await + .unwrap(); + db.query(format!( + "DEFINE EVENT OVERWRITE hold_the_sweep ON TABLE {APPOINTMENT_SLOT_TABLE} \ + WHEN $event = 'DELETE' THEN {{ IF $before.teacher = \ + type::record('user', '{key}') {{ SLEEP 300ms }} }};" + )) + .await + .unwrap() + .check() + .unwrap(); + + let demoting = { + let db = db.clone(); + let target = teacher.clone(); + tokio::spawn(async move { + User::read(&target, &db) + .await + .unwrap() + .unwrap() + .set_role(Role::Student, &db) + .await + }) + }; + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + if !demoting.is_finished() { + raced += 1; + } + // The publish a `RequireTeacher` snapshot taken a moment ago allows. + let landed = create( + &db, + &teacher, + at(MILLIS_PER_WEEK), + at(MILLIS_PER_WEEK + 1_000), + None, + ) + .await; + let swept = demoting.await.unwrap(); + assert!(swept.is_ok(), "round {round}: the demotion itself failed"); + if landed.is_ok() { + published += 1; + } + if !list_for_teacher(&db, &teacher).await.unwrap().is_empty() { + stranded += 1; + } + } + eprintln!( + "a publish racing a demotion: {raced}/4 rounds landed inside it, \ + {published} publishes committed" + ); + assert!(raced > 0, "no round ever reached the race"); + assert_eq!( + stranded, 0, + "a slot survived under a role that can neither list nor delete it" + ); + } + + #[tokio::test] + async fn weekly_publish_that_self_overlaps_is_refused() { + let db = crate::database::init_mem().await.unwrap(); + let teacher = UserId::from_key("t1"); + // A window longer than the weekly step collides with the next week. + assert!(matches!( + publish_weekly( + &db, + &teacher, + at(0), + at(MILLIS_PER_WEEK + 1), + None, + at(MILLIS_PER_WEEK), + ) + .await, + Err(AppError::ConflictOwned(_)) + )); + assert!(list_for_teacher(&db, &teacher).await.unwrap().is_empty()); + } +} diff --git a/src/service/mod.rs b/src/service/mod.rs index 892e3cd..ee52ad1 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -2,6 +2,7 @@ //! SurrealQL text. pub mod appointment; +pub mod appointment_slot; pub mod course; pub mod exam_attempt; pub mod note; diff --git a/src/web/appointments.rs b/src/web/appointments.rs index 8822e22..90a2b3c 100644 --- a/src/web/appointments.rs +++ b/src/web/appointments.rs @@ -216,7 +216,7 @@ async fn appointment_responses( ) -> Result, AppError> { let mut slots = Vec::with_capacity(rows.len()); for row in rows { - slots.push(AppointmentSlot::read(row.get_slot(), db).await?); + slots.push(service::appointment_slot::read(db, row.get_slot()).await?); } // Collected eagerly rather than as a lazy iterator: a borrowing closure // held across the `person_map` await makes the handler's future @@ -274,8 +274,10 @@ async fn for_decision( user: &User, db: &Database, ) -> Result { - let appointment = service::appointment::read(db, id).await?.ok_or(AppError::NotFound)?; - let slot = AppointmentSlot::read(appointment.get_slot(), db) + let appointment = service::appointment::read(db, id) + .await? + .ok_or(AppError::NotFound)?; + let slot = service::appointment_slot::read(db, appointment.get_slot()) .await? .ok_or(AppError::NotFound)?; if !can_manage(&slot, user) { @@ -341,10 +343,20 @@ async fn publish_slots( reason: "is required with repeat_weekly", }))?; check_not_past("until", Some(until))?; - AppointmentSlot::publish_weekly(user.get_id(), starts_at, ends_at, note, until, &st.db) - .await? + service::appointment_slot::publish_weekly( + &st.db, + user.get_id(), + starts_at, + ends_at, + note, + until, + ) + .await? } else { - vec![AppointmentSlot::create(user.get_id(), starts_at, ends_at, note, &st.db).await?] + vec![ + service::appointment_slot::create(&st.db, user.get_id(), starts_at, ends_at, note) + .await?, + ] }; let people = PersonRef::map_of(&[&user]); @@ -397,11 +409,11 @@ async fn list_slots( let (limit, offset) = page.resolve()?; let (slots, people) = if user.get_role().at_least(Role::Teacher) { ( - AppointmentSlot::list_for_teacher(user.get_id(), &st.db).await?, + service::appointment_slot::list_for_teacher(&st.db, user.get_id()).await?, PersonRef::map_of(&[&user]), ) } else { - let mut slots = AppointmentSlot::list_upcoming(Timestamp::now(), &st.db).await?; + let mut slots = service::appointment_slot::list_upcoming(&st.db, Timestamp::now()).await?; // The teachers' live rows, not the slots' word for it: a demotion // leaves the calendar behind, and an inert slot must not be offered. // Keying the person map off that same read makes the filter free. @@ -453,7 +465,7 @@ async fn delete_slot( RequireTeacher(user): RequireTeacher, Path(id): Path, ) -> Result { - let slot = AppointmentSlot::read(&AppointmentSlotId::from_key(&id), &st.db) + let slot = service::appointment_slot::read(&st.db, &AppointmentSlotId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; if !can_manage(&slot, &user) { @@ -461,7 +473,7 @@ async fn delete_slot( "only the slot's teacher or a manager/admin can delete it", )); } - slot.delete(&st.db).await?; + service::appointment_slot::delete(&st.db, slot).await?; Ok(StatusCode::NO_CONTENT) } @@ -491,7 +503,7 @@ async fn delete_slot_series( let series = SlotSeries::from_key(&series); // Every occurrence of one publish carries the same teacher, so the first // row answers the ownership question for all of them. - let slot = AppointmentSlot::list_for_series(&series, &st.db) + let slot = service::appointment_slot::list_for_series(&st.db, &series) .await? .into_iter() .next() @@ -501,7 +513,7 @@ async fn delete_slot_series( "only the slot's teacher or a manager/admin can delete it", )); } - AppointmentSlot::delete_series(&series, &st.db).await?; + service::appointment_slot::delete_series(&st.db, &series).await?; Ok(StatusCode::NO_CONTENT) } @@ -541,7 +553,7 @@ async fn book( )); } let slot_id = AppointmentSlotId::from_key(&req.slot); - let slot = AppointmentSlot::read(&slot_id, &st.db) + let slot = service::appointment_slot::read(&st.db, &slot_id) .await? .ok_or(AppError::NotFound)?; // The slot row is not the grant: a teacher demoted since publishing keeps @@ -555,8 +567,7 @@ async fn book( )); } let reason = AppointmentReason::try_new(&req.reason)?; - let appointment = - service::appointment::book(&st.db, &slot_id, user.get_id(), reason).await?; + let appointment = service::appointment::book(&st.db, &slot_id, user.get_id(), reason).await?; Ok(( StatusCode::CREATED, one_appointment(appointment, &st.db).await?, @@ -867,7 +878,9 @@ async fn ensure_requester( user: &User, db: &Database, ) -> Result { - let appointment = service::appointment::read(db, id).await?.ok_or(AppError::NotFound)?; + let appointment = service::appointment::read(db, id) + .await? + .ok_or(AppError::NotFound)?; if appointment.get_requester() != user.get_id() { return Err(AppError::Forbidden( "only the requester can answer a counter-proposal", @@ -902,12 +915,12 @@ mod tests { async fn demoted_slot_owner_loses_management() { let db = init_mem().await.unwrap(); let owner = user("ogretmen", Role::Teacher, &db).await; - let slot = AppointmentSlot::create( + let slot = service::appointment_slot::create( + &db, owner.get_id(), Timestamp::from_millis(1_000), Timestamp::from_millis(2_000), None, - &db, ) .await .unwrap();