forge
Explore
Log in

Don't you dare go Hollow

Split appointment_slot into domain/db/service layers

Browse files at this commit

23330b09da1412ce83836bd278c44e4439c5cc77Ahmet Kaan GümüşParent: ad1326c
  • chore
    • split appointment_slot into domain/db/service layers
Show full message
🧹 chore: split appointment_slot into domain/db/service layers
src/db/appointment_slot.rsadded+255 -0
@@ -0,0 +1,255 @@
1+//! The `appointment_slot` table: row reads and listings, the overlap probes
2+//! behind the publish guard, the role-claimed INSERT every publish writes
3+//! through, and the delete whose own `WHERE` is the no-live-booking guard.
4+//! The workflows that sequence these under
5+//! [`crate::service::appointment::APPOINTMENT_LOCK`] live in
6+//! [`crate::service::appointment_slot`].
7+
8+use surrealdb::types::{RecordId, SurrealValue};
9+
10+use crate::constant::{APPOINTMENT_SLOT_TABLE, ROLES};
11+use crate::database::{Database, transaction_with_retry};
12+use crate::db::cap;
13+use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId, SlotSeries};
14+use crate::domain::role::Role;
15+use crate::domain::timestamp::Timestamp;
16+use crate::domain::user::UserId;
17+use crate::error::AppError;
18+
19+/// The publisher fell below `teacher` while the publish was in flight.
20+const UNFIT_MARK: &str = "slot_not_staff";
21+
22+/// Write a whole publish — one occurrence or fifty-two — while the publisher
23+/// still *holds* a teaching role.
24+///
25+/// Every row here names the teacher, so the write touches no key a demotion
26+/// touches: [`crate::domain::user::User::set_role`] sweeps the slots its own
27+/// snapshot can see, and a slot landing after that snapshot would survive it
28+/// under a role that may not publish — reachable by no route afterwards,
29+/// since the calendar hides a demoted teacher's slots and the deletes are
30+/// `teacher`-gated. So the teacher's own record is claimed beside the insert
31+/// ([`cap::role_claim`]), which is the key the demotion writes: either the
32+/// sweep sees these slots, or this write sees the new role and publishes
33+/// nothing.
34+///
35+/// The bar is read off the hierarchy rather than spelled out, so a new role
36+/// cannot drift out of it.
37+///
38+/// Admissible for [`transaction_with_retry`]: the claim is `SELECT`/`UPDATE`
39+/// only, and the `INSERT` carries freshly minted ULIDs on a table with no
40+/// `UNIQUE` index, so no rival can make it answer "already exists".
41+pub async fn insert_claimed(
42+ db: &Database,
43+ teacher: &UserId,
44+ rows: Vec<AppointmentSlot>,
45+) -> Result<Vec<AppointmentSlot>, AppError> {
46+ let staff = ROLES
47+ .iter()
48+ .filter(|role| role.at_least(Role::Teacher))
49+ .map(|role| format!("'{}'", role.as_str()))
50+ .collect::<Vec<_>>()
51+ .join(", ");
52+ let held = cap::role_claim("teacher", &format!("NOT IN [{staff}]"), UNFIT_MARK);
53+ let sql = format!(
54+ "BEGIN TRANSACTION;\n{};\nINSERT INTO {APPOINTMENT_SLOT_TABLE} $rows;\n\
55+ COMMIT TRANSACTION;",
56+ held.join(";\n")
57+ );
58+ let (mut result, mut errors) = transaction_with_retry(
59+ db,
60+ &sql,
61+ &[
62+ ("teacher".into(), teacher.record().into_value()),
63+ ("rows".into(), rows.into_value()),
64+ ],
65+ &[UNFIT_MARK],
66+ )
67+ .await?;
68+ // Demoted while this ran — the same refusal `RequireTeacher` makes a
69+ // moment earlier, and the only one that can arrive after it.
70+ if errors
71+ .values()
72+ .any(|error| error.to_string().contains(UNFIT_MARK))
73+ {
74+ return Err(AppError::Forbidden(
75+ "that account no longer holds a teaching role",
76+ ));
77+ }
78+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
79+ return Err(error.into());
80+ }
81+ // BEGIN plus the claim's own statements — counted, not tallied by hand,
82+ // so a statement added there cannot read back the wrong result.
83+ Ok(result.take::<Vec<AppointmentSlot>>(held.len() + 1)?)
84+}
85+
86+/// Does the teacher already have a published slot whose window collides with
87+/// `[starts_at, ends_at)`? Half-open, so a slot ending exactly where the new
88+/// one starts is *not* a conflict — that is how a teacher's hour is carved
89+/// into back-to-back slots. Caller must hold
90+/// [`crate::service::appointment::APPOINTMENT_LOCK`] for the
91+/// answer to still be true by the time the insert lands.
92+pub async fn conflicts_existing(
93+ db: &Database,
94+ teacher: &UserId,
95+ starts_at: Timestamp,
96+ ends_at: Timestamp,
97+) -> Result<bool, AppError> {
98+ let mut result = db
99+ .query(
100+ "SELECT VALUE id FROM appointment_slot \
101+ WHERE teacher = $teacher AND starts_at < $ends AND ends_at > $starts \
102+ LIMIT 1",
103+ )
104+ .bind(("teacher", teacher.record()))
105+ .bind(("starts", starts_at.as_millis()))
106+ .bind(("ends", ends_at.as_millis()))
107+ .await?
108+ .check()?;
109+ Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
110+}
111+
112+/// Every window this teacher already published that intersects the envelope
113+/// `[from, to)`. One read for a whole batch: a stored row that overlaps *any*
114+/// window in the batch necessarily overlaps the envelope spanning them all,
115+/// so filtering the envelope and comparing in memory is exactly the
116+/// per-window [`conflicts_existing`] check,
117+/// hoisted out of the loop — which is what keeps
118+/// [`crate::service::appointment::APPOINTMENT_LOCK`] down
119+/// to two round trips instead of one per occurrence.
120+pub async fn windows_in_span(
121+ db: &Database,
122+ teacher: &UserId,
123+ from: Timestamp,
124+ to: Timestamp,
125+) -> Result<Vec<(Timestamp, Timestamp)>, AppError> {
126+ let mut result = db
127+ .query(
128+ "SELECT * FROM appointment_slot \
129+ WHERE teacher = $teacher AND starts_at < $to AND ends_at > $from",
130+ )
131+ .bind(("teacher", teacher.record()))
132+ .bind(("from", from.as_millis()))
133+ .bind(("to", to.as_millis()))
134+ .await?
135+ .check()?;
136+ Ok(result
137+ .take::<Vec<AppointmentSlot>>(0)?
138+ .into_iter()
139+ .map(|slot| (slot.starts_at, slot.ends_at))
140+ .collect())
141+}
142+
143+pub async fn read(
144+ db: &Database,
145+ id: &AppointmentSlotId,
146+) -> Result<Option<AppointmentSlot>, AppError> {
147+ Ok(db.select(id.record()).await?)
148+}
149+
150+/// A teacher's own calendar, earliest first.
151+pub async fn list_for_teacher(
152+ db: &Database,
153+ teacher: &UserId,
154+) -> Result<Vec<AppointmentSlot>, AppError> {
155+ let mut result = db
156+ .query(
157+ "SELECT * FROM appointment_slot WHERE teacher = $teacher \
158+ ORDER BY starts_at ASC, id ASC",
159+ )
160+ .bind(("teacher", teacher.record()))
161+ .await?
162+ .check()?;
163+ Ok(result.take::<Vec<AppointmentSlot>>(0)?)
164+}
165+
166+/// Every slot whose window has not opened yet, earliest first — the bookable
167+/// calendar a requester browses.
168+///
169+/// The bound is `starts_at`, not `ends_at`, so that this window is exactly
170+/// the one [`crate::service::appointment::book`] accepts: a slot already underway is
171+/// unbookable (`cancel` could never undo the booking), and offering it would
172+/// be a calendar entry that can only answer `409`. The publish-time 60s skew
173+/// grace deliberately does not apply here either — `book` does not grant it,
174+/// and a slot published a moment after its own start is unbookable from
175+/// birth, so it belongs on nobody's calendar.
176+pub async fn list_upcoming(
177+ db: &Database,
178+ from: Timestamp,
179+) -> Result<Vec<AppointmentSlot>, AppError> {
180+ let mut result = db
181+ .query(
182+ "SELECT * FROM appointment_slot WHERE starts_at > $from \
183+ ORDER BY starts_at ASC, id ASC",
184+ )
185+ .bind(("from", from.as_millis()))
186+ .await?
187+ .check()?;
188+ Ok(result.take::<Vec<AppointmentSlot>>(0)?)
189+}
190+
191+pub async fn list_for_series(
192+ db: &Database,
193+ series: &SlotSeries,
194+) -> Result<Vec<AppointmentSlot>, AppError> {
195+ let mut result = db
196+ .query(
197+ "SELECT * FROM appointment_slot WHERE series = $series \
198+ ORDER BY starts_at ASC, id ASC",
199+ )
200+ .bind(("series", series.as_str().to_string()))
201+ .await?
202+ .check()?;
203+ Ok(result.take::<Vec<AppointmentSlot>>(0)?)
204+}
205+
206+/// Shared body of both deletes: drop every named slot, but only while its
207+/// `occupied` counter says nobody is waiting on it — the delete's own
208+/// `WHERE` is the guard, which is what makes it hold against a booking
209+/// landing in the middle of it (a separate read-then-delete could not).
210+///
211+/// All-or-nothing across the whole list: if fewer rows go than were named,
212+/// the transaction is thrown away, so a series never loses its free weeks
213+/// and keeps the booked one. Whether that shortfall was a live booking or a
214+/// slot that no longer exists is read off what survived — the occupied rows
215+/// are still there, a vanished one is not — which is the 409/404 the caller
216+/// used to get from a separate check.
217+pub async fn delete_free(db: &Database, ids: &[AppointmentSlotId]) -> Result<(), AppError> {
218+ let records: Vec<RecordId> = ids.iter().map(|id| id.record()).collect();
219+ let (_, mut errors) = transaction_with_retry(
220+ db,
221+ "BEGIN TRANSACTION;
222+ LET $gone = (DELETE $slots WHERE (occupied ?? 0) = 0 RETURN BEFORE);
223+ IF array::len($gone) != array::len($slots) {
224+ THROW IF array::len((SELECT VALUE id FROM appointment_slot
225+ WHERE id IN $slots)) > 0 { 'slot_occupied' } ELSE { 'slot_missing' }
226+ };
227+ DELETE appointment WHERE slot IN $slots;
228+ RETURN $gone;
229+ COMMIT TRANSACTION;",
230+ &[("slots".into(), records.into_value())],
231+ &["slot_occupied", "slot_missing"],
232+ )
233+ .await?;
234+ // An aborted transaction errors every slot; only the THROW's own slot
235+ // names the marker (the `Exam::update` treatment), and a round lost to
236+ // a booking landing on `occupied` mid-flight is re-sent rather than
237+ // reported (see [`transaction_with_retry`]).
238+ let thrown = |marker: &str| {
239+ errors
240+ .values()
241+ .any(|error| error.to_string().contains(marker))
242+ };
243+ if thrown("slot_occupied") {
244+ return Err(AppError::Conflict(
245+ "the slot has a pending or approved booking",
246+ ));
247+ }
248+ if thrown("slot_missing") {
249+ return Err(AppError::NotFound);
250+ }
251+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
252+ return Err(error.into());
253+ }
254+ Ok(())
255+}
src/db/mod.rsmodified+1 -0
@@ -1,6 +1,7 @@
11 //! The only layer that executes queries.
22
33 pub mod appointment;
4+pub mod appointment_slot;
45 pub mod cap;
56 pub mod course;
67 pub mod exam_attempt;
src/domain/appointment_slot.rsmodified+32 -808
@@ -1,36 +1,33 @@
1-//! A teacher's published availability: "I am free here, book me". A slot is
2-//! nearly pure calendar: the one piece of booking state it carries is the
3-//! `occupied` counter (a [`cap`](crate::db::cap) of one), taken when a
4-//! booking is made and given back in the same transaction as the reject or
5-//! cancel that settles it — so the slot frees itself again, and unlike a UNIQUE
6-//! index it does not keep a dead booking's seat. Stored rather than counted
7-//! from the [`Appointment`] rows because a conditional write on one row is the
8-//! only guard a concurrent booking cannot outrun.
1+//! A teacher's published availability: "I am free here, book me". This module
2+//! is the pure row shape: the validated note, the ids, and
3+//! [`AppointmentSlot::weekly_windows`], the concrete windows a recurring
4+//! publish unfolds into at write time — each occurrence keeps the same
5+//! `series` id, so no recurrence rule is ever evaluated at read time and
6+//! cancelling one week is a plain row delete.
97 //!
10-//! A recurring publish is expanded into concrete rows here, at write time,
11-//! sharing one `series` id — no recurrence rule is ever evaluated at read
12-//! time. Cancelling one week is then a plain row delete, and the whole series
13-//! is still addressable through its id.
8+//! The one piece of booking state a slot carries is the `occupied` counter (a
9+//! [`cap`](crate::db::cap) of one), taken when a booking is made and given
10+//! back in the same transaction as the reject or cancel that settles it — so
11+//! the slot frees itself again, and unlike a UNIQUE index it does not keep a
12+//! dead booking's seat. Stored rather than counted from the
13+//! [appointment](crate::domain::appointment::Appointment) rows because a
14+//! conditional write on one row is the only guard a concurrent booking cannot
15+//! outrun. The reads and writes behind it live in
16+//! [`crate::db::appointment_slot`]; the publish and delete workflows under
17+//! [`crate::service::appointment::APPOINTMENT_LOCK`] live in
18+//! [`crate::service::appointment_slot`].
1419
1520 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
1621
1722 use crate::constant::{
18- APPOINTMENT_SLOT_TABLE, MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK, ROLES,
23+ APPOINTMENT_SLOT_TABLE, MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK,
1924 };
20-use crate::database::{Database, transaction_with_retry};
21-use crate::domain::appointment::Appointment;
22-use crate::service::appointment::APPOINTMENT_LOCK;
23-use crate::db::cap;
2425 use crate::domain::monotonic_id::next_ulid;
25-use crate::domain::role::Role;
2626 use crate::domain::timestamp::Timestamp;
2727 use crate::domain::user::UserId;
2828 use crate::error::{AppError, ValidationError};
2929 use crate::validate::validate_optional;
3030
31-/// The publisher fell below `teacher` while the publish was in flight.
32-const UNFIT_MARK: &str = "slot_not_staff";
33-
3431 // Slot ids come from [`crate::domain::monotonic_id`]: a recurring publish
3532 // writes its whole expansion inside one millisecond, which random ULID low
3633 // bits would scramble against the `id` tie-break of the `ORDER BY starts_at,
@@ -101,13 +98,13 @@ impl SlotNote {
10198 /// overlapping, which is exactly how a teacher's hour is carved up.
10299 #[derive(Debug, Clone, SurrealValue)]
103100 pub struct AppointmentSlot {
104- id: AppointmentSlotId,
105- teacher: UserId,
106- starts_at: Timestamp,
107- ends_at: Timestamp,
108- note: Option<SlotNote>,
109- series: Option<SlotSeries>,
110- created_at: Timestamp,
101+ pub(crate) id: AppointmentSlotId,
102+ pub(crate) teacher: UserId,
103+ pub(crate) starts_at: Timestamp,
104+ pub(crate) ends_at: Timestamp,
105+ pub(crate) note: Option<SlotNote>,
106+ pub(crate) series: Option<SlotSeries>,
107+ pub(crate) created_at: Timestamp,
111108 }
112109
113110 impl AppointmentSlot {
@@ -142,7 +139,10 @@ impl AppointmentSlot {
142139 /// A slot must cover a real span of time — an empty or inverted window
143140 /// could never be booked, and would break the touching-is-not-overlapping
144141 /// rule the conflict guard rests on.
145- fn check_window(starts_at: Timestamp, ends_at: Timestamp) -> Result<(), ValidationError> {
142+ pub(crate) fn check_window(
143+ starts_at: Timestamp,
144+ ends_at: Timestamp,
145+ ) -> Result<(), ValidationError> {
146146 if starts_at.as_millis() >= ends_at.as_millis() {
147147 return Err(ValidationError::Invalid {
148148 field: "ends_at",
@@ -202,387 +202,14 @@ impl AppointmentSlot {
202202 })
203203 .collect()
204204 }
205-
206- /// Write a whole publish — one occurrence or fifty-two — while the publisher
207- /// still *holds* a teaching role.
208- ///
209- /// Every row here names the teacher, so the write touches no key a demotion
210- /// touches: [`crate::domain::user::User::set_role`] sweeps the slots its own
211- /// snapshot can see, and a slot landing after that snapshot would survive it
212- /// under a role that may not publish — reachable by no route afterwards,
213- /// since the calendar hides a demoted teacher's slots and the deletes are
214- /// `teacher`-gated. So the teacher's own record is claimed beside the insert
215- /// ([`cap::role_claim`]), which is the key the demotion writes: either the
216- /// sweep sees these slots, or this write sees the new role and publishes
217- /// nothing.
218- ///
219- /// The bar is read off the hierarchy rather than spelled out, so a new role
220- /// cannot drift out of it.
221- ///
222- /// Admissible for [`transaction_with_retry`]: the claim is `SELECT`/`UPDATE`
223- /// only, and the `INSERT` carries freshly minted ULIDs on a table with no
224- /// `UNIQUE` index, so no rival can make it answer "already exists".
225- async fn insert_claimed(
226- teacher: &UserId,
227- rows: Vec<AppointmentSlot>,
228- db: &Database,
229- ) -> Result<Vec<AppointmentSlot>, AppError> {
230- let staff = ROLES
231- .iter()
232- .filter(|role| role.at_least(Role::Teacher))
233- .map(|role| format!("'{}'", role.as_str()))
234- .collect::<Vec<_>>()
235- .join(", ");
236- let held = cap::role_claim("teacher", &format!("NOT IN [{staff}]"), UNFIT_MARK);
237- let sql = format!(
238- "BEGIN TRANSACTION;\n{};\nINSERT INTO {APPOINTMENT_SLOT_TABLE} $rows;\n\
239- COMMIT TRANSACTION;",
240- held.join(";\n")
241- );
242- let (mut result, mut errors) = transaction_with_retry(
243- db,
244- &sql,
245- &[
246- ("teacher".into(), teacher.record().into_value()),
247- ("rows".into(), rows.into_value()),
248- ],
249- &[UNFIT_MARK],
250- )
251- .await?;
252- // Demoted while this ran — the same refusal `RequireTeacher` makes a
253- // moment earlier, and the only one that can arrive after it.
254- if errors
255- .values()
256- .any(|error| error.to_string().contains(UNFIT_MARK))
257- {
258- return Err(AppError::Forbidden(
259- "that account no longer holds a teaching role",
260- ));
261- }
262- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
263- return Err(error.into());
264- }
265- // BEGIN plus the claim's own statements — counted, not tallied by hand,
266- // so a statement added there cannot read back the wrong result.
267- Ok(result.take::<Vec<AppointmentSlot>>(held.len() + 1)?)
268- }
269-
270- /// Does the teacher already have a published slot whose window collides with
271- /// `[starts_at, ends_at)`? Half-open, so a slot ending exactly where the new
272- /// one starts is *not* a conflict — that is how a teacher's hour is carved
273- /// into back-to-back slots. Caller must hold
274- /// [`crate::service::appointment::APPOINTMENT_LOCK`] for the
275- /// answer to still be true by the time the insert lands.
276- async fn conflicts_existing(
277- teacher: &UserId,
278- starts_at: Timestamp,
279- ends_at: Timestamp,
280- db: &Database,
281- ) -> Result<bool, AppError> {
282- let mut result = db
283- .query(
284- "SELECT VALUE id FROM appointment_slot \
285- WHERE teacher = $teacher AND starts_at < $ends AND ends_at > $starts \
286- LIMIT 1",
287- )
288- .bind(("teacher", teacher.record()))
289- .bind(("starts", starts_at.as_millis()))
290- .bind(("ends", ends_at.as_millis()))
291- .await?
292- .check()?;
293- Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
294- }
295-
296- /// Every window this teacher already published that intersects the envelope
297- /// `[from, to)`. One read for a whole batch: a stored row that overlaps *any*
298- /// window in the batch necessarily overlaps the envelope spanning them all,
299- /// so filtering the envelope and comparing in memory is exactly the
300- /// per-window [`conflicts_existing`](Self::conflicts_existing) check,
301- /// hoisted out of the loop — which is what keeps
302- /// [`crate::service::appointment::APPOINTMENT_LOCK`] down
303- /// to two round trips instead of one per occurrence.
304- async fn windows_in_span(
305- teacher: &UserId,
306- from: Timestamp,
307- to: Timestamp,
308- db: &Database,
309- ) -> Result<Vec<(Timestamp, Timestamp)>, AppError> {
310- let mut result = db
311- .query(
312- "SELECT * FROM appointment_slot \
313- WHERE teacher = $teacher AND starts_at < $to AND ends_at > $from",
314- )
315- .bind(("teacher", teacher.record()))
316- .bind(("from", from.as_millis()))
317- .bind(("to", to.as_millis()))
318- .await?
319- .check()?;
320- Ok(result
321- .take::<Vec<AppointmentSlot>>(0)?
322- .into_iter()
323- .map(|slot| (slot.starts_at, slot.ends_at))
324- .collect())
325- }
326-
327- /// Publish one slot.
328- pub async fn create(
329- teacher: &UserId,
330- starts_at: Timestamp,
331- ends_at: Timestamp,
332- note: Option<SlotNote>,
333- db: &Database,
334- ) -> Result<AppointmentSlot, AppError> {
335- Self::check_window(starts_at, ends_at)?;
336- // Check-then-insert under the lock so a concurrent publish or booking
337- // can't slip a colliding window in between.
338- let _guard = APPOINTMENT_LOCK.lock().await;
339- if Self::conflicts_existing(teacher, starts_at, ends_at, db).await? {
340- return Err(AppError::ConflictOwned(
341- "this time overlaps a slot you have already published".into(),
342- ));
343- }
344- Self::insert_claimed(
345- teacher,
346- vec![AppointmentSlot {
347- id: AppointmentSlotId::generate(),
348- teacher: teacher.clone(),
349- starts_at,
350- ends_at,
351- note,
352- series: None,
353- created_at: Timestamp::now(),
354- }],
355- db,
356- )
357- .await?
358- .into_iter()
359- .next()
360- .ok_or_else(|| AppError::Internal("failed to create appointment slot".into()))
361- }
362-
363- /// Publish the same weekly window repeatedly, up to `until`. Every row
364- /// carries the same [`SlotSeries`], so the whole publish stays addressable
365- /// (and deletable) as one thing while each occurrence remains an ordinary,
366- /// independently bookable and independently cancellable slot.
367- pub async fn publish_weekly(
368- teacher: &UserId,
369- starts_at: Timestamp,
370- ends_at: Timestamp,
371- note: Option<SlotNote>,
372- until: Timestamp,
373- db: &Database,
374- ) -> Result<Vec<AppointmentSlot>, AppError> {
375- let windows = Self::weekly_windows(starts_at, ends_at, until)?;
376- // Validate the whole batch before writing a single row: all-or-nothing,
377- // so a mid-series collision never leaves stray weeks behind. Held under
378- // the lock from the check through the write, matching `create`.
379- let _guard = APPOINTMENT_LOCK.lock().await;
380- // (a) against the slots already in the database. `weekly_windows` walks
381- // forward, so the first and last occurrence bound every one of them.
382- let (first, last) = (windows[0], windows[windows.len() - 1]);
383- let published = Self::windows_in_span(teacher, first.0, last.1, db).await?;
384- for (i, &(w_start, w_end)) in windows.iter().enumerate() {
385- if published
386- .iter()
387- .any(|&(p_start, p_end)| Appointment::overlaps(w_start, w_end, p_start, p_end))
388- {
389- return Err(AppError::ConflictOwned(
390- "a repeated slot overlaps one you have already published".into(),
391- ));
392- }
393- // (b) against every earlier occurrence in this same batch — catches
394- // a duration longer than the weekly step overlapping itself.
395- if windows[..i]
396- .iter()
397- .any(|&(o_start, o_end)| Appointment::overlaps(w_start, w_end, o_start, o_end))
398- {
399- return Err(AppError::ConflictOwned(
400- "the repeated slots overlap each other".into(),
401- ));
402- }
403- }
404- let series = SlotSeries::generate();
405- let now = Timestamp::now();
406- let rows: Vec<AppointmentSlot> = windows
407- .iter()
408- .map(|&(starts_at, ends_at)| AppointmentSlot {
409- id: AppointmentSlotId::generate(),
410- teacher: teacher.clone(),
411- starts_at,
412- ends_at,
413- note: note.clone(),
414- series: Some(series.clone()),
415- created_at: now,
416- })
417- .collect();
418- // One `INSERT`, therefore all-or-nothing: SurrealDB rolls the whole
419- // publish back on any error. The row-by-row loop this replaces did not
420- // — a database error at week 7 of 10 answered 500 with six stray weeks
421- // already published, a half-series nobody asked for. It is also a single
422- // round trip, so the lock is held for two queries whatever the
423- // occurrence count, instead of 1 + N (up to 52) sequential ones.
424- let mut created = Self::insert_claimed(teacher, rows, db).await?;
425- if created.len() != windows.len() {
426- return Err(AppError::Internal(format!(
427- "published {} of {} appointment slots",
428- created.len(),
429- windows.len()
430- )));
431- }
432- // `INSERT` makes no promise about the order it echoes rows back in, and
433- // the response is rendered as the published calendar.
434- created.sort_by_key(|slot| slot.starts_at.as_millis());
435- Ok(created)
436- }
437-
438- pub async fn read(
439- id: &AppointmentSlotId,
440- db: &Database,
441- ) -> Result<Option<AppointmentSlot>, AppError> {
442- Ok(db.select(id.record()).await?)
443- }
444-
445- /// A teacher's own calendar, earliest first.
446- pub async fn list_for_teacher(
447- teacher: &UserId,
448- db: &Database,
449- ) -> Result<Vec<AppointmentSlot>, AppError> {
450- let mut result = db
451- .query(
452- "SELECT * FROM appointment_slot WHERE teacher = $teacher \
453- ORDER BY starts_at ASC, id ASC",
454- )
455- .bind(("teacher", teacher.record()))
456- .await?
457- .check()?;
458- Ok(result.take::<Vec<AppointmentSlot>>(0)?)
459- }
460-
461- /// Every slot whose window has not opened yet, earliest first — the bookable
462- /// calendar a requester browses.
463- ///
464- /// The bound is `starts_at`, not `ends_at`, so that this window is exactly
465- /// the one [`crate::service::appointment::book`] accepts: a slot already underway is
466- /// unbookable (`cancel` could never undo the booking), and offering it would
467- /// be a calendar entry that can only answer `409`. The publish-time 60s skew
468- /// grace deliberately does not apply here either — `book` does not grant it,
469- /// and a slot published a moment after its own start is unbookable from
470- /// birth, so it belongs on nobody's calendar.
471- pub async fn list_upcoming(
472- from: Timestamp,
473- db: &Database,
474- ) -> Result<Vec<AppointmentSlot>, AppError> {
475- let mut result = db
476- .query(
477- "SELECT * FROM appointment_slot WHERE starts_at > $from \
478- ORDER BY starts_at ASC, id ASC",
479- )
480- .bind(("from", from.as_millis()))
481- .await?
482- .check()?;
483- Ok(result.take::<Vec<AppointmentSlot>>(0)?)
484- }
485-
486- pub async fn list_for_series(
487- series: &SlotSeries,
488- db: &Database,
489- ) -> Result<Vec<AppointmentSlot>, AppError> {
490- let mut result = db
491- .query(
492- "SELECT * FROM appointment_slot WHERE series = $series \
493- ORDER BY starts_at ASC, id ASC",
494- )
495- .bind(("series", series.as_str().to_string()))
496- .await?
497- .check()?;
498- Ok(result.take::<Vec<AppointmentSlot>>(0)?)
499- }
500-
501- /// Delete one slot, refusing (409) while a live booking sits on it — the
502- /// requester is expecting that meeting, so it must be rejected first.
503- /// Settled bookings (rejected/cancelled) are history of a slot that is
504- /// going away, so they cascade out with it, like [`Event::delete`]'s rows.
505- ///
506- /// The guard is the delete's own `WHERE`, so no booking can land between a
507- /// check and the row going away.
508- pub async fn delete(self, db: &Database) -> Result<AppointmentSlot, AppError> {
509- Self::delete_free(std::slice::from_ref(&self.id), db).await?;
510- Ok(self)
511- }
512-
513- /// Delete a whole recurring publish, all-or-nothing: if *any* occurrence
514- /// still holds a live booking the entire series is refused, so the teacher
515- /// deals with the person waiting instead of silently keeping a stray week.
516- pub async fn delete_series(
517- series: &SlotSeries,
518- db: &Database,
519- ) -> Result<Vec<AppointmentSlot>, AppError> {
520- let slots = Self::list_for_series(series, db).await?;
521- if slots.is_empty() {
522- return Err(AppError::NotFound);
523- }
524- let ids: Vec<AppointmentSlotId> = slots.iter().map(|slot| slot.id.clone()).collect();
525- Self::delete_free(&ids, db).await?;
526- Ok(slots)
527- }
528-
529- /// Shared body of both deletes: drop every named slot, but only while its
530- /// `occupied` counter says nobody is waiting on it — the delete's own
531- /// `WHERE` is the guard, which is what makes it hold against a booking
532- /// landing in the middle of it (a separate read-then-delete could not).
533- ///
534- /// All-or-nothing across the whole list: if fewer rows go than were named,
535- /// the transaction is thrown away, so a series never loses its free weeks
536- /// and keeps the booked one. Whether that shortfall was a live booking or a
537- /// slot that no longer exists is read off what survived — the occupied rows
538- /// are still there, a vanished one is not — which is the 409/404 the caller
539- /// used to get from a separate check.
540- async fn delete_free(ids: &[AppointmentSlotId], db: &Database) -> Result<(), AppError> {
541- let records: Vec<RecordId> = ids.iter().map(|id| id.record()).collect();
542- let (_, mut errors) = transaction_with_retry(
543- db,
544- "BEGIN TRANSACTION;
545- LET $gone = (DELETE $slots WHERE (occupied ?? 0) = 0 RETURN BEFORE);
546- IF array::len($gone) != array::len($slots) {
547- THROW IF array::len((SELECT VALUE id FROM appointment_slot
548- WHERE id IN $slots)) > 0 { 'slot_occupied' } ELSE { 'slot_missing' }
549- };
550- DELETE appointment WHERE slot IN $slots;
551- RETURN $gone;
552- COMMIT TRANSACTION;",
553- &[("slots".into(), records.into_value())],
554- &["slot_occupied", "slot_missing"],
555- )
556- .await?;
557- // An aborted transaction errors every slot; only the THROW's own slot
558- // names the marker (the `Exam::update` treatment), and a round lost to
559- // a booking landing on `occupied` mid-flight is re-sent rather than
560- // reported (see [`transaction_with_retry`]).
561- let thrown = |marker: &str| {
562- errors
563- .values()
564- .any(|error| error.to_string().contains(marker))
565- };
566- if thrown("slot_occupied") {
567- return Err(AppError::Conflict(
568- "the slot has a pending or approved booking",
569- ));
570- }
571- if thrown("slot_missing") {
572- return Err(AppError::NotFound);
573- }
574- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
575- return Err(error.into());
576- }
577- Ok(())
578- }
579205 }
580206
581207 #[cfg(test)]
582208 mod tests {
583209 use super::*;
584- use crate::constant::{MILLIS_PER_DAY, SLOT_OCCUPIED_FIELD};
585- use crate::db::cap;
210+ use crate::constant::{
211+ MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_DAY, MILLIS_PER_WEEK,
212+ };
586213
587214 fn at(millis: i64) -> Timestamp {
588215 Timestamp::from_millis(millis)
@@ -674,407 +301,4 @@ mod tests {
674301 1
675302 );
676303 }
677-
678- /// Every occurrence of one publish must carry the same series id, and ids
679- /// minted back-to-back must stay in write order (the `ORDER BY` tie-break).
680- #[tokio::test]
681- async fn a_publish_shares_one_series_and_orders_its_ids() {
682- let db = crate::database::init_mem().await.unwrap();
683- let teacher = UserId::from_key("t1");
684- let slots = AppointmentSlot::publish_weekly(
685- &teacher,
686- at(1_000),
687- at(2_000),
688- Some(SlotNote::try_new("veli toplantısı").unwrap()),
689- at(1_000 + 4 * MILLIS_PER_WEEK),
690- &db,
691- )
692- .await
693- .unwrap();
694-
695- assert_eq!(slots.len(), 5);
696- let series = slots[0].get_series().cloned().unwrap();
697- assert!(slots.iter().all(|slot| slot.get_series() == Some(&series)));
698- assert!(
699- slots
700- .windows(2)
701- .all(|pair| pair[0].get_id().key() < pair[1].get_id().key())
702- );
703-
704- let listed = AppointmentSlot::list_for_series(&series, &db)
705- .await
706- .unwrap();
707- assert_eq!(listed.len(), 5);
708- }
709-
710- #[tokio::test]
711- async fn overlapping_publish_is_refused_but_touching_is_allowed() {
712- let db = crate::database::init_mem().await.unwrap();
713- let teacher = UserId::from_key("t1");
714- AppointmentSlot::create(&teacher, at(1_000), at(2_000), None, &db)
715- .await
716- .unwrap();
717-
718- // Overlaps the existing [1000,2000) → 409.
719- assert!(matches!(
720- AppointmentSlot::create(&teacher, at(1_500), at(2_500), None, &db).await,
721- Err(AppError::ConflictOwned(_))
722- ));
723- // Touching at the boundary (ends where the next starts) → allowed.
724- assert!(
725- AppointmentSlot::create(&teacher, at(2_000), at(3_000), None, &db)
726- .await
727- .is_ok()
728- );
729- assert!(
730- AppointmentSlot::create(&teacher, at(0), at(1_000), None, &db)
731- .await
732- .is_ok()
733- );
734- // A different teacher sharing the same window is fine.
735- let other = UserId::from_key("t2");
736- assert!(
737- AppointmentSlot::create(&other, at(1_000), at(2_000), None, &db)
738- .await
739- .is_ok()
740- );
741- }
742-
743- #[tokio::test]
744- async fn weekly_publish_overlapping_an_existing_slot_writes_nothing() {
745- let db = crate::database::init_mem().await.unwrap();
746- let teacher = UserId::from_key("t1");
747- // A lone slot on the third week of the coming series.
748- AppointmentSlot::create(
749- &teacher,
750- at(1_000 + 2 * MILLIS_PER_WEEK),
751- at(2_000 + 2 * MILLIS_PER_WEEK),
752- None,
753- &db,
754- )
755- .await
756- .unwrap();
757-
758- let before = AppointmentSlot::list_for_teacher(&teacher, &db)
759- .await
760- .unwrap()
761- .len();
762- assert!(matches!(
763- AppointmentSlot::publish_weekly(
764- &teacher,
765- at(1_000),
766- at(2_000),
767- None,
768- at(1_000 + 4 * MILLIS_PER_WEEK),
769- &db,
770- )
771- .await,
772- Err(AppError::ConflictOwned(_))
773- ));
774- // All-or-nothing: not one occurrence of the rejected series was written.
775- assert_eq!(
776- AppointmentSlot::list_for_teacher(&teacher, &db)
777- .await
778- .unwrap()
779- .len(),
780- before
781- );
782- }
783-
784- /// The existing-slot check is one envelope-wide read instead of a query per
785- /// occurrence, so the edges of that envelope are what could go wrong: a
786- /// clash on the *last* week must still be caught, and a slot merely touching
787- /// the batch's boundaries must still be allowed.
788- #[tokio::test]
789- async fn the_batch_wide_conflict_read_still_sees_the_last_week_and_lets_touching_through() {
790- let db = crate::database::init_mem().await.unwrap();
791- let teacher = UserId::from_key("t1");
792- let last = 1_000 + 4 * MILLIS_PER_WEEK;
793- // Touching both ends of the envelope: ends where the first occurrence
794- // starts, and starts where the last one ends.
795- AppointmentSlot::create(&teacher, at(0), at(1_000), None, &db)
796- .await
797- .unwrap();
798- AppointmentSlot::create(&teacher, at(last + 1_000), at(last + 2_000), None, &db)
799- .await
800- .unwrap();
801- assert_eq!(
802- AppointmentSlot::publish_weekly(&teacher, at(1_000), at(2_000), None, at(last), &db)
803- .await
804- .unwrap()
805- .len(),
806- 5
807- );
808-
809- // One millisecond into the last occurrence → the whole publish is 409.
810- let db = crate::database::init_mem().await.unwrap();
811- AppointmentSlot::create(&teacher, at(last + 999), at(last + 3_000), None, &db)
812- .await
813- .unwrap();
814- assert!(matches!(
815- AppointmentSlot::publish_weekly(&teacher, at(1_000), at(2_000), None, at(last), &db)
816- .await,
817- Err(AppError::ConflictOwned(_))
818- ));
819- assert_eq!(
820- AppointmentSlot::list_for_teacher(&teacher, &db)
821- .await
822- .unwrap()
823- .len(),
824- 1
825- );
826- }
827-
828- /// The delete-vs-book race: a booking that lands between this delete's read
829- /// and its write must still keep the slot alive, so the guard has to be the
830- /// delete's own `WHERE` — here driven by taking the seat the way that
831- /// booking would, with no booking row to read.
832- ///
833- /// A series is all-or-nothing: one taken week refuses the whole publish,
834- /// and the free weeks must survive the refusal.
835- #[tokio::test]
836- async fn a_taken_slot_is_never_deleted_and_takes_its_series_with_it() {
837- let db = crate::database::init_mem().await.unwrap();
838- let teacher = UserId::from_key("t1");
839- let slots = AppointmentSlot::publish_weekly(
840- &teacher,
841- at(1_000),
842- at(2_000),
843- None,
844- at(1_000 + 2 * MILLIS_PER_WEEK),
845- &db,
846- )
847- .await
848- .unwrap();
849- let series = slots[0].get_series().cloned().unwrap();
850-
851- // A free slot goes, and its series is deletable while every week is free.
852- assert!(slots[0].clone().delete(&db).await.is_ok());
853- // The seat on the middle week is taken — no booking row, exactly as a
854- // racing booking would leave it mid-flight.
855- assert!(
856- cap::claim(&slots[1].get_id().record(), SLOT_OCCUPIED_FIELD, 1, &db)
857- .await
858- .unwrap()
859- );
860- assert!(matches!(
861- slots[1].clone().delete(&db).await,
862- Err(AppError::Conflict(
863- "the slot has a pending or approved booking"
864- ))
865- ));
866- assert!(matches!(
867- AppointmentSlot::delete_series(&series, &db).await,
868- Err(AppError::Conflict(_))
869- ));
870- // Refused, not half-applied: the free third week is still published.
871- assert_eq!(
872- AppointmentSlot::list_for_series(&series, &db)
873- .await
874- .unwrap()
875- .len(),
876- 2
877- );
878-
879- // A slot that is simply gone is a 404, not a 409 — the delete tells the
880- // two shortfalls apart by what survived it.
881- assert!(matches!(
882- slots[0].clone().delete(&db).await,
883- Err(AppError::NotFound)
884- ));
885- }
886-
887- /// The claim on the publisher's own record, asked exactly the way the race
888- /// asks it: a publish whose `RequireTeacher` snapshot predates a demotion
889- /// must not land, because the sweep in that demotion has already chosen the
890- /// slots it will take and would leave this one behind — under a role that
891- /// can neither list nor delete it.
892- ///
893- /// Both halves matter: a row that is *not there* claims nothing (every other
894- /// test here publishes for a teacher with no user row at all), and a live
895- /// teacher+ passes through untouched.
896- #[tokio::test]
897- async fn a_publish_by_someone_who_lost_the_role_is_refused() {
898- let db = crate::database::init_mem().await.unwrap();
899- // Written as a row rather than through `User` — the password hasher is
900- // private to that module, and the only column this asks about is `role`.
901- db.query("CREATE user:eski SET username = 'eski', password_hash = 'x', role = 'student'")
902- .await
903- .unwrap()
904- .check()
905- .unwrap();
906-
907- // The row says `student`, so the claim refuses — one-off and weekly
908- // alike, since both go through the same write.
909- let teacher = UserId::from_key("eski");
910- assert!(matches!(
911- AppointmentSlot::create(&teacher, at(1_000), at(2_000), None, &db).await,
912- Err(AppError::Forbidden(_))
913- ));
914- assert!(matches!(
915- AppointmentSlot::publish_weekly(
916- &teacher,
917- at(1_000),
918- at(2_000),
919- None,
920- at(1_000 + MILLIS_PER_WEEK),
921- &db,
922- )
923- .await,
924- Err(AppError::Forbidden(_))
925- ));
926- assert!(
927- AppointmentSlot::list_for_teacher(&teacher, &db)
928- .await
929- .unwrap()
930- .is_empty(),
931- "a refused publish must write nothing"
932- );
933-
934- // Promoted, the very same publish lands.
935- db.query("UPDATE user:eski SET role = 'teacher'")
936- .await
937- .unwrap()
938- .check()
939- .unwrap();
940- AppointmentSlot::create(&teacher, at(1_000), at(2_000), None, &db)
941- .await
942- .unwrap();
943- assert_eq!(
944- AppointmentSlot::list_for_teacher(&teacher, &db)
945- .await
946- .unwrap()
947- .len(),
948- 1
949- );
950- }
951-
952- /// The other half of that claim: the publish that arrives *while* the
953- /// demotion is running. Its sweep has already chosen the slots it will take
954- /// ([`crate::domain::user::User::set_role`] reads them into `$slots` before
955- /// it deletes), so a row landing after that read shares no key with anything
956- /// the demotion writes and survives it — a slot owned by someone who can
957- /// neither list nor delete it, forever. The claim on the user record is what
958- /// puts the two transactions on one key.
959- ///
960- /// Real server, and `#[ignore]`d for it, like every other race here: the
961- /// subject *is* the store's conflict detection, which `init_mem`'s embedded
962- /// engine does not have — it commits both sides and answers `Ok` to each, so
963- /// this passes there on broken code.
964- ///
965- /// The window is opened by the schema rather than by a lucky interleaving: a
966- /// `DEFINE EVENT` on the sweep's own `DELETE` holds the demotion open inside
967- /// its transaction, well past the read that chose `$slots`, so the publish
968- /// lands in the middle of it every round.
969- ///
970- /// Stored state is the verdict, not the return value: whether the publish is
971- /// refused outright or swept along with the rest of the calendar, no slot may
972- /// outlive the role.
973- #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
974- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
975- async fn a_publish_landing_inside_a_demotion_never_outlives_the_role() {
976- use crate::domain::role::Role;
977- use crate::domain::user::User;
978-
979- let (db, _serialized) = crate::database::init_test_server("slot_demotion_race").await;
980- let (mut raced, mut published, mut stranded) = (0, 0, 0);
981- for round in 0..4 {
982- let key = format!("t{round}");
983- let teacher = UserId::from_key(&key);
984- db.query(format!(
985- "CREATE user:{key} SET username = '{key}', password_hash = 'x', \
986- role = '{}';",
987- Role::Teacher.as_str()
988- ))
989- .await
990- .unwrap()
991- .check()
992- .unwrap();
993- // A slot for the sweep to delete — that delete is the seam.
994- AppointmentSlot::create(&teacher, at(1_000), at(2_000), None, &db)
995- .await
996- .unwrap();
997- db.query(format!(
998- "DEFINE EVENT OVERWRITE hold_the_sweep ON TABLE {APPOINTMENT_SLOT_TABLE} \
999- WHEN $event = 'DELETE' THEN {{ IF $before.teacher = \
1000- type::record('user', '{key}') {{ SLEEP 300ms }} }};"
1001- ))
1002- .await
1003- .unwrap()
1004- .check()
1005- .unwrap();
1006-
1007- let demoting = {
1008- let db = db.clone();
1009- let target = teacher.clone();
1010- tokio::spawn(async move {
1011- User::read(&target, &db)
1012- .await
1013- .unwrap()
1014- .unwrap()
1015- .set_role(Role::Student, &db)
1016- .await
1017- })
1018- };
1019- tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1020- if !demoting.is_finished() {
1021- raced += 1;
1022- }
1023- // The publish a `RequireTeacher` snapshot taken a moment ago allows.
1024- let landed = AppointmentSlot::create(
1025- &teacher,
1026- at(MILLIS_PER_WEEK),
1027- at(MILLIS_PER_WEEK + 1_000),
1028- None,
1029- &db,
1030- )
1031- .await;
1032- let swept = demoting.await.unwrap();
1033- assert!(swept.is_ok(), "round {round}: the demotion itself failed");
1034- if landed.is_ok() {
1035- published += 1;
1036- }
1037- if !AppointmentSlot::list_for_teacher(&teacher, &db)
1038- .await
1039- .unwrap()
1040- .is_empty()
1041- {
1042- stranded += 1;
1043- }
1044- }
1045- eprintln!(
1046- "a publish racing a demotion: {raced}/4 rounds landed inside it, \
1047- {published} publishes committed"
1048- );
1049- assert!(raced > 0, "no round ever reached the race");
1050- assert_eq!(
1051- stranded, 0,
1052- "a slot survived under a role that can neither list nor delete it"
1053- );
1054- }
1055-
1056- #[tokio::test]
1057- async fn weekly_publish_that_self_overlaps_is_refused() {
1058- let db = crate::database::init_mem().await.unwrap();
1059- let teacher = UserId::from_key("t1");
1060- // A window longer than the weekly step collides with the next week.
1061- assert!(matches!(
1062- AppointmentSlot::publish_weekly(
1063- &teacher,
1064- at(0),
1065- at(MILLIS_PER_WEEK + 1),
1066- None,
1067- at(MILLIS_PER_WEEK),
1068- &db,
1069- )
1070- .await,
1071- Err(AppError::ConflictOwned(_))
1072- ));
1073- assert!(
1074- AppointmentSlot::list_for_teacher(&teacher, &db)
1075- .await
1076- .unwrap()
1077- .is_empty()
1078- );
1079- }
1080304 }
src/domain/user.rsmodified+6 -6
@@ -772,7 +772,7 @@ impl User {
772772 // `Appointment::book` claims the slot row this deletes, so the two
773773 // collide in the store and the loser re-sends. A slot *published*
774774 // concurrently shares no key with any of this, which is why
775- // `AppointmentSlot::insert_claimed` claims the user row instead.
775+ // `crate::db::appointment_slot::insert_claimed` claims the user row instead.
776776 batch.push(format!(
777777 "DELETE {APPOINTMENT_SLOT_TABLE} WHERE id IN $slots"
778778 ));
@@ -1079,8 +1079,8 @@ mod tests {
10791079 #[tokio::test]
10801080 async fn a_demotion_withdraws_the_calendar_and_settles_its_bookings() {
10811081 use crate::domain::appointment::AppointmentReason;
1082- use crate::domain::appointment_slot::AppointmentSlot;
10831082 use crate::service::appointment;
1083+ use crate::service::appointment_slot;
10841084
10851085 let db = init_mem().await.unwrap();
10861086 let staff = |name: &'static str, db: Database| async move {
@@ -1099,7 +1099,7 @@ mod tests {
10991099 let slot = |owner: &User, offset: i64, db: Database| {
11001100 let owner = owner.get_id().clone();
11011101 async move {
1102- AppointmentSlot::create(&owner, soon(offset), soon(offset + 60_000), None, &db)
1102+ appointment_slot::create(&db, &owner, soon(offset), soon(offset + 60_000), None)
11031103 .await
11041104 .unwrap()
11051105 }
@@ -1127,14 +1127,14 @@ mod tests {
11271127
11281128 // The calendar is gone, the booked weeks included.
11291129 assert!(
1130- AppointmentSlot::list_for_teacher(teacher.get_id(), &db)
1130+ appointment_slot::list_for_teacher(&db, teacher.get_id())
11311131 .await
11321132 .unwrap()
11331133 .is_empty()
11341134 );
11351135 for slot in [&free, &asked, &agreed] {
11361136 assert!(
1137- AppointmentSlot::read(slot.get_id(), &db)
1137+ appointment_slot::read(&db, slot.get_id())
11381138 .await
11391139 .unwrap()
11401140 .is_none(),
@@ -1167,7 +1167,7 @@ mod tests {
11671167
11681168 // Another teacher's calendar is nobody else's business.
11691169 assert_eq!(
1170- AppointmentSlot::list_for_teacher(other.get_id(), &db)
1170+ appointment_slot::list_for_teacher(&db, other.get_id())
11711171 .await
11721172 .unwrap()
11731173 .len(),
src/service/appointment.rsmodified+60 -43
@@ -13,11 +13,12 @@ use tokio::sync::Mutex;
1313 use crate::constant::{CAS_UPDATE_RETRIES, SLOT_OCCUPIED_FIELD};
1414 use crate::database::Database;
1515 use crate::db::appointment;
16+use crate::db::appointment_slot;
1617 use crate::db::cap;
1718 use crate::domain::appointment::{
1819 Appointment, AppointmentId, AppointmentReason, AppointmentStatus,
1920 };
20-use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId};
21+use crate::domain::appointment_slot::AppointmentSlotId;
2122 use crate::domain::timestamp::Timestamp;
2223 use crate::domain::user::UserId;
2324 use crate::error::{AppError, ValidationError};
@@ -62,7 +63,7 @@ pub async fn book(
6263 reason: AppointmentReason,
6364 ) -> Result<Appointment, AppError> {
6465 let _guard = APPOINTMENT_LOCK.lock().await;
65- let slot_row = AppointmentSlot::read(slot, db)
66+ let slot_row = appointment_slot::read(db, slot)
6667 .await?
6768 .ok_or(AppError::NotFound)?;
6869 // A window that has opened is history, not a plan: `cancel` refuses to
@@ -123,7 +124,7 @@ pub async fn book(
123124 {
124125 cap::Claimed::Made(created) => Ok(created),
125126 cap::Claimed::Full => {
126- if AppointmentSlot::read(slot, db).await?.is_none() {
127+ if appointment_slot::read(db, slot).await?.is_none() {
127128 return Err(AppError::NotFound);
128129 }
129130 Err(AppError::Conflict("the slot is already booked"))
@@ -136,10 +137,7 @@ pub async fn book(
136137
137138 /// The row, for callers that only inspect it — the web layer's authorization
138139 /// gates read through here.
139-pub async fn read(
140- db: &Database,
141- id: &AppointmentId,
142-) -> Result<Option<Appointment>, AppError> {
140+pub async fn read(db: &Database, id: &AppointmentId) -> Result<Option<Appointment>, AppError> {
143141 appointment::read(db, id).await
144142 }
145143
@@ -216,7 +214,7 @@ async fn approve_inner(
216214 }
217215 _ => {}
218216 }
219- let slot = AppointmentSlot::read(&expected.slot, db)
217+ let slot = appointment_slot::read(db, &expected.slot)
220218 .await?
221219 .ok_or(AppError::NotFound)?;
222220 let (starts_at, ends_at) = expected.window(&slot);
@@ -296,7 +294,7 @@ pub async fn cancel(
296294 if !expected.status.is_live() {
297295 return Err(AppError::Conflict("the appointment is already settled"));
298296 }
299- let slot = AppointmentSlot::read(&expected.slot, db)
297+ let slot = appointment_slot::read(db, &expected.slot)
300298 .await?
301299 .ok_or(AppError::NotFound)?;
302300 if expected.window(&slot).0.as_millis() <= Timestamp::now().as_millis() {
@@ -395,6 +393,7 @@ fn contended() -> AppError {
395393 mod tests {
396394 use super::*;
397395 use crate::database::{Database, init_mem};
396+ use crate::service::appointment_slot;
398397
399398 fn at(millis: i64) -> Timestamp {
400399 Timestamp::from_millis(millis)
@@ -410,7 +409,7 @@ mod tests {
410409 let db = init_mem().await.unwrap();
411410 let teacher = UserId::from_key("t1");
412411 let (starts_at, ends_at) = (soon(60_000), soon(120_000));
413- let slot = AppointmentSlot::create(&teacher, starts_at, ends_at, None, &db)
412+ let slot = appointment_slot::create(&db, &teacher, starts_at, ends_at, None)
414413 .await
415414 .unwrap();
416415 let mut appointment_row = book(
@@ -435,7 +434,7 @@ mod tests {
435434 let db = init_mem().await.unwrap();
436435 let teacher = UserId::from_key("t1");
437436 let reason = || AppointmentReason::try_new("görüşme").unwrap();
438- let started = AppointmentSlot::create(&teacher, soon(-30_000), soon(60_000), None, &db)
437+ let started = appointment_slot::create(&db, &teacher, soon(-30_000), soon(60_000), None)
439438 .await
440439 .unwrap();
441440 assert!(matches!(
@@ -443,12 +442,14 @@ mod tests {
443442 Err(AppError::Conflict("the slot has already started"))
444443 ));
445444
446- let upcoming = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db)
445+ let upcoming = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
447446 .await
448447 .unwrap();
449- assert!(book(&db, upcoming.get_id(), &UserId::from_key("s1"), reason())
450- .await
451- .is_ok());
448+ assert!(
449+ book(&db, upcoming.get_id(), &UserId::from_key("s1"), reason())
450+ .await
451+ .is_ok()
452+ );
452453 }
453454
454455 /// Approval judges the *effective* window, so a proposal whose time has
@@ -458,7 +459,7 @@ mod tests {
458459 let db = init_mem().await.unwrap();
459460 let teacher = UserId::from_key("t1");
460461 let student = UserId::from_key("s1");
461- let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db)
462+ let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
462463 .await
463464 .unwrap();
464465 let booking = book(
@@ -492,8 +493,14 @@ mod tests {
492493 .unwrap()
493494 .unwrap();
494495 assert!(matches!(
495- accept_proposal(&db, booking.get_id(), &student, passed_starts_at, passed_ends_at)
496- .await,
496+ accept_proposal(
497+ &db,
498+ booking.get_id(),
499+ &student,
500+ passed_starts_at,
501+ passed_ends_at
502+ )
503+ .await,
497504 Err(AppError::Conflict("that time has already started"))
498505 ));
499506 // Refused, not half-applied: still pending, still decidable at a time
@@ -507,8 +514,14 @@ mod tests {
507514 // Accepting a window that is *not* the standing proposal is refused —
508515 // the pin is what the requester saw, not a request to move the meeting.
509516 assert!(matches!(
510- accept_proposal(&db, booking.get_id(), &student, passed_starts_at, passed_ends_at)
511- .await,
517+ accept_proposal(
518+ &db,
519+ booking.get_id(),
520+ &student,
521+ passed_starts_at,
522+ passed_ends_at
523+ )
524+ .await,
512525 Err(AppError::Conflict(
513526 "the proposed time has changed; \
514527 re-read the booking and accept the new one"
@@ -534,7 +547,7 @@ mod tests {
534547 let db = init_mem().await.unwrap();
535548 let teacher = UserId::from_key("t1");
536549 let student = UserId::from_key("s1");
537- let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db)
550+ let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
538551 .await
539552 .unwrap();
540553 let booking = book(
@@ -551,9 +564,15 @@ mod tests {
551564 // `pending` status.
552565 let stale = booking.clone();
553566 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();
567+ propose(
568+ &db,
569+ booking.get_id(),
570+ proposed_starts_at,
571+ proposed_ends_at,
572+ &teacher,
573+ )
574+ .await
575+ .unwrap();
557576
558577 let mut late = stale.clone();
559578 late.status = AppointmentStatus::Approved;
@@ -616,7 +635,7 @@ mod tests {
616635 async fn a_concurrent_claim_cannot_take_a_booked_slot() {
617636 let db = init_mem().await.unwrap();
618637 let teacher = UserId::from_key("t1");
619- let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db)
638+ let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
620639 .await
621640 .unwrap();
622641 assert_eq!(occupied(slot.get_id(), &db).await, 0);
@@ -657,7 +676,7 @@ mod tests {
657676 async fn a_refused_booking_moves_nothing() {
658677 let db = init_mem().await.unwrap();
659678 let teacher = UserId::from_key("t1");
660- let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db)
679+ let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
661680 .await
662681 .unwrap();
663682 let reason = || AppointmentReason::try_new("görüşme").unwrap();
@@ -695,7 +714,7 @@ mod tests {
695714 let db = init_mem().await.unwrap();
696715 let teacher = UserId::from_key("t1");
697716 let student = UserId::from_key("s1");
698- let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db)
717+ let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
699718 .await
700719 .unwrap();
701720 let booking = book(
@@ -709,21 +728,21 @@ mod tests {
709728 approve(&db, booking.get_id(), &teacher).await.unwrap();
710729 assert_eq!(occupied(slot.get_id(), &db).await, 1, "approval holds it");
711730
712- cancel(&db, booking.get_id(), &student, None)
713- .await
714- .unwrap();
731+ cancel(&db, booking.get_id(), &student, None).await.unwrap();
715732 assert_eq!(occupied(slot.get_id(), &db).await, 0);
716733 // Cancelling twice is refused, so the seat cannot go back twice either.
717734 assert!(cancel(&db, booking.get_id(), &student, None).await.is_err());
718735 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());
736+ assert!(
737+ book(
738+ &db,
739+ slot.get_id(),
740+ &UserId::from_key("s2"),
741+ AppointmentReason::try_new("görüşme").unwrap()
742+ )
743+ .await
744+ .is_ok()
745+ );
727746 assert_eq!(occupied(slot.get_id(), &db).await, 1);
728747 }
729748
@@ -732,7 +751,7 @@ mod tests {
732751 async fn rejecting_frees_the_slot_for_re_booking() {
733752 let db = init_mem().await.unwrap();
734753 let teacher = UserId::from_key("t1");
735- let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db)
754+ let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
736755 .await
737756 .unwrap();
738757 let reason = || AppointmentReason::try_new("görüşme").unwrap();
@@ -746,13 +765,11 @@ mod tests {
746765 ));
747766 // The live booking also blocks the slot delete.
748767 assert!(matches!(
749- slot.clone().delete(&db).await,
768+ appointment_slot::delete(&db, slot.clone()).await,
750769 Err(AppError::Conflict(_))
751770 ));
752771
753- reject(&db, first.get_id(), &teacher, None)
754- .await
755- .unwrap();
772+ reject(&db, first.get_id(), &teacher, None).await.unwrap();
756773 assert_eq!(occupied(slot.get_id(), &db).await, 0);
757774 let second = book(&db, slot.get_id(), &UserId::from_key("s2"), reason())
758775 .await
src/service/appointment_slot.rsadded+556 -0
@@ -0,0 +1,556 @@
1+//! Slot publishing and withdrawal: the one-off and weekly publishes, the
2+//! single and series deletes, and the reads the web layer renders the
3+//! calendar from. Row reads, listings, the overlap probes, the role-claimed
4+//! INSERT, and the guarded delete live in [`crate::db::appointment_slot`].
5+//!
6+//! Publishing holds [`APPOINTMENT_LOCK`] from the conflict check through the
7+//! write — the same lock the booking path takes — so a concurrent publish or
8+//! booking cannot slip a colliding window in between the check and the
9+//! insert.
10+
11+use crate::database::Database;
12+use crate::db::appointment_slot;
13+use crate::domain::appointment::Appointment;
14+use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId, SlotNote, SlotSeries};
15+use crate::domain::timestamp::Timestamp;
16+use crate::domain::user::UserId;
17+use crate::error::AppError;
18+
19+use super::appointment::APPOINTMENT_LOCK;
20+
21+/// The row, for callers that only inspect it — the web layer's gates read
22+/// through here.
23+pub async fn read(
24+ db: &Database,
25+ id: &AppointmentSlotId,
26+) -> Result<Option<AppointmentSlot>, AppError> {
27+ appointment_slot::read(db, id).await
28+}
29+
30+/// A teacher's own calendar, earliest first — the web layer's calendar read.
31+pub async fn list_for_teacher(
32+ db: &Database,
33+ teacher: &UserId,
34+) -> Result<Vec<AppointmentSlot>, AppError> {
35+ appointment_slot::list_for_teacher(db, teacher).await
36+}
37+
38+/// Every slot whose window has not opened yet, earliest first — the bookable
39+/// calendar a requester browses.
40+pub async fn list_upcoming(
41+ db: &Database,
42+ from: Timestamp,
43+) -> Result<Vec<AppointmentSlot>, AppError> {
44+ appointment_slot::list_upcoming(db, from).await
45+}
46+
47+/// Every slot of one recurring publish, earliest first.
48+pub async fn list_for_series(
49+ db: &Database,
50+ series: &SlotSeries,
51+) -> Result<Vec<AppointmentSlot>, AppError> {
52+ appointment_slot::list_for_series(db, series).await
53+}
54+
55+/// Publish one slot.
56+pub async fn create(
57+ db: &Database,
58+ teacher: &UserId,
59+ starts_at: Timestamp,
60+ ends_at: Timestamp,
61+ note: Option<SlotNote>,
62+) -> Result<AppointmentSlot, AppError> {
63+ AppointmentSlot::check_window(starts_at, ends_at)?;
64+ // Check-then-insert under the lock so a concurrent publish or booking
65+ // can't slip a colliding window in between.
66+ let _guard = APPOINTMENT_LOCK.lock().await;
67+ if appointment_slot::conflicts_existing(db, teacher, starts_at, ends_at).await? {
68+ return Err(AppError::ConflictOwned(
69+ "this time overlaps a slot you have already published".into(),
70+ ));
71+ }
72+ appointment_slot::insert_claimed(
73+ db,
74+ teacher,
75+ vec![AppointmentSlot {
76+ id: AppointmentSlotId::generate(),
77+ teacher: teacher.clone(),
78+ starts_at,
79+ ends_at,
80+ note,
81+ series: None,
82+ created_at: Timestamp::now(),
83+ }],
84+ )
85+ .await?
86+ .into_iter()
87+ .next()
88+ .ok_or_else(|| AppError::Internal("failed to create appointment slot".into()))
89+}
90+
91+/// Publish the same weekly window repeatedly, up to `until`. Every row
92+/// carries the same [`SlotSeries`], so the whole publish stays addressable
93+/// (and deletable) as one thing while each occurrence remains an ordinary,
94+/// independently bookable and independently cancellable slot.
95+pub async fn publish_weekly(
96+ db: &Database,
97+ teacher: &UserId,
98+ starts_at: Timestamp,
99+ ends_at: Timestamp,
100+ note: Option<SlotNote>,
101+ until: Timestamp,
102+) -> Result<Vec<AppointmentSlot>, AppError> {
103+ let windows = AppointmentSlot::weekly_windows(starts_at, ends_at, until)?;
104+ // Validate the whole batch before writing a single row: all-or-nothing,
105+ // so a mid-series collision never leaves stray weeks behind. Held under
106+ // the lock from the check through the write, matching `create`.
107+ let _guard = APPOINTMENT_LOCK.lock().await;
108+ // (a) against the slots already in the database. `weekly_windows` walks
109+ // forward, so the first and last occurrence bound every one of them.
110+ let (first, last) = (windows[0], windows[windows.len() - 1]);
111+ let published = appointment_slot::windows_in_span(db, teacher, first.0, last.1).await?;
112+ for (i, &(w_start, w_end)) in windows.iter().enumerate() {
113+ if published
114+ .iter()
115+ .any(|&(p_start, p_end)| Appointment::overlaps(w_start, w_end, p_start, p_end))
116+ {
117+ return Err(AppError::ConflictOwned(
118+ "a repeated slot overlaps one you have already published".into(),
119+ ));
120+ }
121+ // (b) against every earlier occurrence in this same batch — catches
122+ // a duration longer than the weekly step overlapping itself.
123+ if windows[..i]
124+ .iter()
125+ .any(|&(o_start, o_end)| Appointment::overlaps(w_start, w_end, o_start, o_end))
126+ {
127+ return Err(AppError::ConflictOwned(
128+ "the repeated slots overlap each other".into(),
129+ ));
130+ }
131+ }
132+ let series = SlotSeries::generate();
133+ let now = Timestamp::now();
134+ let rows: Vec<AppointmentSlot> = windows
135+ .iter()
136+ .map(|&(starts_at, ends_at)| AppointmentSlot {
137+ id: AppointmentSlotId::generate(),
138+ teacher: teacher.clone(),
139+ starts_at,
140+ ends_at,
141+ note: note.clone(),
142+ series: Some(series.clone()),
143+ created_at: now,
144+ })
145+ .collect();
146+ // One `INSERT`, therefore all-or-nothing: SurrealDB rolls the whole
147+ // publish back on any error. The row-by-row loop this replaces did not
148+ // — a database error at week 7 of 10 answered 500 with six stray weeks
149+ // already published, a half-series nobody asked for. It is also a single
150+ // round trip, so the lock is held for two queries whatever the
151+ // occurrence count, instead of 1 + N (up to 52) sequential ones.
152+ let mut created = appointment_slot::insert_claimed(db, teacher, rows).await?;
153+ if created.len() != windows.len() {
154+ return Err(AppError::Internal(format!(
155+ "published {} of {} appointment slots",
156+ created.len(),
157+ windows.len()
158+ )));
159+ }
160+ // `INSERT` makes no promise about the order it echoes rows back in, and
161+ // the response is rendered as the published calendar.
162+ created.sort_by_key(|slot| slot.starts_at.as_millis());
163+ Ok(created)
164+}
165+
166+/// Delete one slot, refusing (409) while a live booking sits on it — the
167+/// requester is expecting that meeting, so it must be rejected first.
168+/// Settled bookings (rejected/cancelled) are history of a slot that is
169+/// going away, so they cascade out with it, like `Event::delete`'s rows.
170+///
171+/// The guard is the delete's own `WHERE`, so no booking can land between a
172+/// check and the row going away.
173+pub async fn delete(db: &Database, slot: AppointmentSlot) -> Result<AppointmentSlot, AppError> {
174+ appointment_slot::delete_free(db, std::slice::from_ref(slot.get_id())).await?;
175+ Ok(slot)
176+}
177+
178+/// Delete a whole recurring publish, all-or-nothing: if *any* occurrence
179+/// still holds a live booking the entire series is refused, so the teacher
180+/// deals with the person waiting instead of silently keeping a stray week.
181+pub async fn delete_series(
182+ db: &Database,
183+ series: &SlotSeries,
184+) -> Result<Vec<AppointmentSlot>, AppError> {
185+ let slots = appointment_slot::list_for_series(db, series).await?;
186+ if slots.is_empty() {
187+ return Err(AppError::NotFound);
188+ }
189+ let ids: Vec<AppointmentSlotId> = slots.iter().map(|slot| slot.id.clone()).collect();
190+ appointment_slot::delete_free(db, &ids).await?;
191+ Ok(slots)
192+}
193+
194+#[cfg(test)]
195+mod tests {
196+ use super::*;
197+ use crate::constant::{APPOINTMENT_SLOT_TABLE, MILLIS_PER_WEEK, SLOT_OCCUPIED_FIELD};
198+ use crate::db::cap;
199+
200+ fn at(millis: i64) -> Timestamp {
201+ Timestamp::from_millis(millis)
202+ }
203+
204+ #[tokio::test]
205+ async fn a_publish_shares_one_series_and_orders_its_ids() {
206+ let db = crate::database::init_mem().await.unwrap();
207+ let teacher = UserId::from_key("t1");
208+ let slots = publish_weekly(
209+ &db,
210+ &teacher,
211+ at(1_000),
212+ at(2_000),
213+ Some(SlotNote::try_new("veli toplantısı").unwrap()),
214+ at(1_000 + 4 * MILLIS_PER_WEEK),
215+ )
216+ .await
217+ .unwrap();
218+
219+ assert_eq!(slots.len(), 5);
220+ let series = slots[0].get_series().cloned().unwrap();
221+ assert!(slots.iter().all(|slot| slot.get_series() == Some(&series)));
222+ assert!(
223+ slots
224+ .windows(2)
225+ .all(|pair| pair[0].get_id().key() < pair[1].get_id().key())
226+ );
227+
228+ let listed = list_for_series(&db, &series).await.unwrap();
229+ assert_eq!(listed.len(), 5);
230+ }
231+
232+ #[tokio::test]
233+ async fn overlapping_publish_is_refused_but_touching_is_allowed() {
234+ let db = crate::database::init_mem().await.unwrap();
235+ let teacher = UserId::from_key("t1");
236+ create(&db, &teacher, at(1_000), at(2_000), None)
237+ .await
238+ .unwrap();
239+
240+ // Overlaps the existing [1000,2000) → 409.
241+ assert!(matches!(
242+ create(&db, &teacher, at(1_500), at(2_500), None).await,
243+ Err(AppError::ConflictOwned(_))
244+ ));
245+ // Touching at the boundary (ends where the next starts) → allowed.
246+ assert!(
247+ create(&db, &teacher, at(2_000), at(3_000), None)
248+ .await
249+ .is_ok()
250+ );
251+ assert!(create(&db, &teacher, at(0), at(1_000), None).await.is_ok());
252+ // A different teacher sharing the same window is fine.
253+ let other = UserId::from_key("t2");
254+ assert!(
255+ create(&db, &other, at(1_000), at(2_000), None)
256+ .await
257+ .is_ok()
258+ );
259+ }
260+
261+ #[tokio::test]
262+ async fn weekly_publish_overlapping_an_existing_slot_writes_nothing() {
263+ let db = crate::database::init_mem().await.unwrap();
264+ let teacher = UserId::from_key("t1");
265+ // A lone slot on the third week of the coming series.
266+ create(
267+ &db,
268+ &teacher,
269+ at(1_000 + 2 * MILLIS_PER_WEEK),
270+ at(2_000 + 2 * MILLIS_PER_WEEK),
271+ None,
272+ )
273+ .await
274+ .unwrap();
275+
276+ let before = list_for_teacher(&db, &teacher).await.unwrap().len();
277+ assert!(matches!(
278+ publish_weekly(
279+ &db,
280+ &teacher,
281+ at(1_000),
282+ at(2_000),
283+ None,
284+ at(1_000 + 4 * MILLIS_PER_WEEK),
285+ )
286+ .await,
287+ Err(AppError::ConflictOwned(_))
288+ ));
289+ // All-or-nothing: not one occurrence of the rejected series was written.
290+ assert_eq!(list_for_teacher(&db, &teacher).await.unwrap().len(), before);
291+ }
292+
293+ /// The existing-slot check is one envelope-wide read instead of a query per
294+ /// occurrence, so the edges of that envelope are what could go wrong: a
295+ /// clash on the *last* week must still be caught, and a slot merely touching
296+ /// the batch's boundaries must still be allowed.
297+ #[tokio::test]
298+ async fn the_batch_wide_conflict_read_still_sees_the_last_week_and_lets_touching_through() {
299+ let db = crate::database::init_mem().await.unwrap();
300+ let teacher = UserId::from_key("t1");
301+ let last = 1_000 + 4 * MILLIS_PER_WEEK;
302+ // Touching both ends of the envelope: ends where the first occurrence
303+ // starts, and starts where the last one ends.
304+ create(&db, &teacher, at(0), at(1_000), None).await.unwrap();
305+ create(&db, &teacher, at(last + 1_000), at(last + 2_000), None)
306+ .await
307+ .unwrap();
308+ assert_eq!(
309+ publish_weekly(&db, &teacher, at(1_000), at(2_000), None, at(last))
310+ .await
311+ .unwrap()
312+ .len(),
313+ 5
314+ );
315+
316+ // One millisecond into the last occurrence → the whole publish is 409.
317+ let db = crate::database::init_mem().await.unwrap();
318+ create(&db, &teacher, at(last + 999), at(last + 3_000), None)
319+ .await
320+ .unwrap();
321+ assert!(matches!(
322+ publish_weekly(&db, &teacher, at(1_000), at(2_000), None, at(last)).await,
323+ Err(AppError::ConflictOwned(_))
324+ ));
325+ assert_eq!(list_for_teacher(&db, &teacher).await.unwrap().len(), 1);
326+ }
327+
328+ /// The delete-vs-book race: a booking that lands between this delete's read
329+ /// and its write must still keep the slot alive, so the guard has to be the
330+ /// delete's own `WHERE` — here driven by taking the seat the way that
331+ /// booking would, with no booking row to read.
332+ ///
333+ /// A series is all-or-nothing: one taken week refuses the whole publish,
334+ /// and the free weeks must survive the refusal.
335+ #[tokio::test]
336+ async fn a_taken_slot_is_never_deleted_and_takes_its_series_with_it() {
337+ let db = crate::database::init_mem().await.unwrap();
338+ let teacher = UserId::from_key("t1");
339+ let slots = publish_weekly(
340+ &db,
341+ &teacher,
342+ at(1_000),
343+ at(2_000),
344+ None,
345+ at(1_000 + 2 * MILLIS_PER_WEEK),
346+ )
347+ .await
348+ .unwrap();
349+ let series = slots[0].get_series().cloned().unwrap();
350+
351+ // A free slot goes, and its series is deletable while every week is free.
352+ assert!(delete(&db, slots[0].clone()).await.is_ok());
353+ // The seat on the middle week is taken — no booking row, exactly as a
354+ // racing booking would leave it mid-flight.
355+ assert!(
356+ cap::claim(&slots[1].get_id().record(), SLOT_OCCUPIED_FIELD, 1, &db)
357+ .await
358+ .unwrap()
359+ );
360+ assert!(matches!(
361+ delete(&db, slots[1].clone()).await,
362+ Err(AppError::Conflict(
363+ "the slot has a pending or approved booking"
364+ ))
365+ ));
366+ assert!(matches!(
367+ delete_series(&db, &series).await,
368+ Err(AppError::Conflict(_))
369+ ));
370+ // Refused, not half-applied: the free third week is still published.
371+ assert_eq!(list_for_series(&db, &series).await.unwrap().len(), 2);
372+
373+ // A slot that is simply gone is a 404, not a 409 — the delete tells the
374+ // two shortfalls apart by what survived it.
375+ assert!(matches!(
376+ delete(&db, slots[0].clone()).await,
377+ Err(AppError::NotFound)
378+ ));
379+ }
380+
381+ /// The claim on the publisher's own record, asked exactly the way the race
382+ /// asks it: a publish whose `RequireTeacher` snapshot predates a demotion
383+ /// must not land, because the sweep in that demotion has already chosen the
384+ /// slots it will take and would leave this one behind — under a role that
385+ /// can neither list nor delete it.
386+ ///
387+ /// Both halves matter: a row that is *not there* claims nothing (every other
388+ /// test here publishes for a teacher with no user row at all), and a live
389+ /// teacher+ passes through untouched.
390+ #[tokio::test]
391+ async fn a_publish_by_someone_who_lost_the_role_is_refused() {
392+ let db = crate::database::init_mem().await.unwrap();
393+ // Written as a row rather than through `User` — the password hasher is
394+ // private to that module, and the only column this asks about is `role`.
395+ db.query("CREATE user:eski SET username = 'eski', password_hash = 'x', role = 'student'")
396+ .await
397+ .unwrap()
398+ .check()
399+ .unwrap();
400+
401+ // The row says `student`, so the claim refuses — one-off and weekly
402+ // alike, since both go through the same write.
403+ let teacher = UserId::from_key("eski");
404+ assert!(matches!(
405+ create(&db, &teacher, at(1_000), at(2_000), None).await,
406+ Err(AppError::Forbidden(_))
407+ ));
408+ assert!(matches!(
409+ publish_weekly(
410+ &db,
411+ &teacher,
412+ at(1_000),
413+ at(2_000),
414+ None,
415+ at(1_000 + MILLIS_PER_WEEK),
416+ )
417+ .await,
418+ Err(AppError::Forbidden(_))
419+ ));
420+ assert!(
421+ list_for_teacher(&db, &teacher).await.unwrap().is_empty(),
422+ "a refused publish must write nothing"
423+ );
424+
425+ // Promoted, the very same publish lands.
426+ db.query("UPDATE user:eski SET role = 'teacher'")
427+ .await
428+ .unwrap()
429+ .check()
430+ .unwrap();
431+ create(&db, &teacher, at(1_000), at(2_000), None)
432+ .await
433+ .unwrap();
434+ assert_eq!(list_for_teacher(&db, &teacher).await.unwrap().len(), 1);
435+ }
436+
437+ /// The other half of that claim: the publish that arrives *while* the
438+ /// demotion is running. Its sweep has already chosen the slots it will take
439+ /// ([`crate::domain::user::User::set_role`] reads them into `$slots` before
440+ /// it deletes), so a row landing after that read shares no key with anything
441+ /// the demotion writes and survives it — a slot owned by someone who can
442+ /// neither list nor delete it, forever. The claim on the user record is what
443+ /// puts the two transactions on one key.
444+ ///
445+ /// Real server, and `#[ignore]`d for it, like every other race here: the
446+ /// subject *is* the store's conflict detection, which `init_mem`'s embedded
447+ /// engine does not have — it commits both sides and answers `Ok` to each, so
448+ /// this passes there on broken code.
449+ ///
450+ /// The window is opened by the schema rather than by a lucky interleaving: a
451+ /// `DEFINE EVENT` on the sweep's own `DELETE` holds the demotion open inside
452+ /// its transaction, well past the read that chose `$slots`, so the publish
453+ /// lands in the middle of it every round.
454+ ///
455+ /// Stored state is the verdict, not the return value: whether the publish is
456+ /// refused outright or swept along with the rest of the calendar, no slot may
457+ /// outlive the role.
458+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
459+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
460+ async fn a_publish_landing_inside_a_demotion_never_outlives_the_role() {
461+ use crate::domain::role::Role;
462+ use crate::domain::user::User;
463+
464+ let (db, _serialized) = crate::database::init_test_server("slot_demotion_race").await;
465+ let (mut raced, mut published, mut stranded) = (0, 0, 0);
466+ for round in 0..4 {
467+ let key = format!("t{round}");
468+ let teacher = UserId::from_key(&key);
469+ db.query(format!(
470+ "CREATE user:{key} SET username = '{key}', password_hash = 'x', \
471+ role = '{}';",
472+ Role::Teacher.as_str()
473+ ))
474+ .await
475+ .unwrap()
476+ .check()
477+ .unwrap();
478+ // A slot for the sweep to delete — that delete is the seam.
479+ create(&db, &teacher, at(1_000), at(2_000), None)
480+ .await
481+ .unwrap();
482+ db.query(format!(
483+ "DEFINE EVENT OVERWRITE hold_the_sweep ON TABLE {APPOINTMENT_SLOT_TABLE} \
484+ WHEN $event = 'DELETE' THEN {{ IF $before.teacher = \
485+ type::record('user', '{key}') {{ SLEEP 300ms }} }};"
486+ ))
487+ .await
488+ .unwrap()
489+ .check()
490+ .unwrap();
491+
492+ let demoting = {
493+ let db = db.clone();
494+ let target = teacher.clone();
495+ tokio::spawn(async move {
496+ User::read(&target, &db)
497+ .await
498+ .unwrap()
499+ .unwrap()
500+ .set_role(Role::Student, &db)
501+ .await
502+ })
503+ };
504+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
505+ if !demoting.is_finished() {
506+ raced += 1;
507+ }
508+ // The publish a `RequireTeacher` snapshot taken a moment ago allows.
509+ let landed = create(
510+ &db,
511+ &teacher,
512+ at(MILLIS_PER_WEEK),
513+ at(MILLIS_PER_WEEK + 1_000),
514+ None,
515+ )
516+ .await;
517+ let swept = demoting.await.unwrap();
518+ assert!(swept.is_ok(), "round {round}: the demotion itself failed");
519+ if landed.is_ok() {
520+ published += 1;
521+ }
522+ if !list_for_teacher(&db, &teacher).await.unwrap().is_empty() {
523+ stranded += 1;
524+ }
525+ }
526+ eprintln!(
527+ "a publish racing a demotion: {raced}/4 rounds landed inside it, \
528+ {published} publishes committed"
529+ );
530+ assert!(raced > 0, "no round ever reached the race");
531+ assert_eq!(
532+ stranded, 0,
533+ "a slot survived under a role that can neither list nor delete it"
534+ );
535+ }
536+
537+ #[tokio::test]
538+ async fn weekly_publish_that_self_overlaps_is_refused() {
539+ let db = crate::database::init_mem().await.unwrap();
540+ let teacher = UserId::from_key("t1");
541+ // A window longer than the weekly step collides with the next week.
542+ assert!(matches!(
543+ publish_weekly(
544+ &db,
545+ &teacher,
546+ at(0),
547+ at(MILLIS_PER_WEEK + 1),
548+ None,
549+ at(MILLIS_PER_WEEK),
550+ )
551+ .await,
552+ Err(AppError::ConflictOwned(_))
553+ ));
554+ assert!(list_for_teacher(&db, &teacher).await.unwrap().is_empty());
555+ }
556+}
src/service/mod.rsmodified+1 -0
@@ -2,6 +2,7 @@
22 //! SurrealQL text.
33
44 pub mod appointment;
5+pub mod appointment_slot;
56 pub mod course;
67 pub mod exam_attempt;
78 pub mod note;
src/web/appointments.rsmodified+31 -18
@@ -216,7 +216,7 @@ async fn appointment_responses(
216216 ) -> Result<Vec<AppointmentResponse>, AppError> {
217217 let mut slots = Vec::with_capacity(rows.len());
218218 for row in rows {
219- slots.push(AppointmentSlot::read(row.get_slot(), db).await?);
219+ slots.push(service::appointment_slot::read(db, row.get_slot()).await?);
220220 }
221221 // Collected eagerly rather than as a lazy iterator: a borrowing closure
222222 // held across the `person_map` await makes the handler's future
@@ -274,8 +274,10 @@ async fn for_decision(
274274 user: &User,
275275 db: &Database,
276276 ) -> Result<Appointment, AppError> {
277- let appointment = service::appointment::read(db, id).await?.ok_or(AppError::NotFound)?;
278- let slot = AppointmentSlot::read(appointment.get_slot(), db)
277+ let appointment = service::appointment::read(db, id)
278+ .await?
279+ .ok_or(AppError::NotFound)?;
280+ let slot = service::appointment_slot::read(db, appointment.get_slot())
279281 .await?
280282 .ok_or(AppError::NotFound)?;
281283 if !can_manage(&slot, user) {
@@ -341,10 +343,20 @@ async fn publish_slots(
341343 reason: "is required with repeat_weekly",
342344 }))?;
343345 check_not_past("until", Some(until))?;
344- AppointmentSlot::publish_weekly(user.get_id(), starts_at, ends_at, note, until, &st.db)
345- .await?
346+ service::appointment_slot::publish_weekly(
347+ &st.db,
348+ user.get_id(),
349+ starts_at,
350+ ends_at,
351+ note,
352+ until,
353+ )
354+ .await?
346355 } else {
347- vec![AppointmentSlot::create(user.get_id(), starts_at, ends_at, note, &st.db).await?]
356+ vec![
357+ service::appointment_slot::create(&st.db, user.get_id(), starts_at, ends_at, note)
358+ .await?,
359+ ]
348360 };
349361
350362 let people = PersonRef::map_of(&[&user]);
@@ -397,11 +409,11 @@ async fn list_slots(
397409 let (limit, offset) = page.resolve()?;
398410 let (slots, people) = if user.get_role().at_least(Role::Teacher) {
399411 (
400- AppointmentSlot::list_for_teacher(user.get_id(), &st.db).await?,
412+ service::appointment_slot::list_for_teacher(&st.db, user.get_id()).await?,
401413 PersonRef::map_of(&[&user]),
402414 )
403415 } else {
404- let mut slots = AppointmentSlot::list_upcoming(Timestamp::now(), &st.db).await?;
416+ let mut slots = service::appointment_slot::list_upcoming(&st.db, Timestamp::now()).await?;
405417 // The teachers' live rows, not the slots' word for it: a demotion
406418 // leaves the calendar behind, and an inert slot must not be offered.
407419 // Keying the person map off that same read makes the filter free.
@@ -453,7 +465,7 @@ async fn delete_slot(
453465 RequireTeacher(user): RequireTeacher,
454466 Path(id): Path<String>,
455467 ) -> Result<StatusCode, AppError> {
456- let slot = AppointmentSlot::read(&AppointmentSlotId::from_key(&id), &st.db)
468+ let slot = service::appointment_slot::read(&st.db, &AppointmentSlotId::from_key(&id))
457469 .await?
458470 .ok_or(AppError::NotFound)?;
459471 if !can_manage(&slot, &user) {
@@ -461,7 +473,7 @@ async fn delete_slot(
461473 "only the slot's teacher or a manager/admin can delete it",
462474 ));
463475 }
464- slot.delete(&st.db).await?;
476+ service::appointment_slot::delete(&st.db, slot).await?;
465477 Ok(StatusCode::NO_CONTENT)
466478 }
467479
@@ -491,7 +503,7 @@ async fn delete_slot_series(
491503 let series = SlotSeries::from_key(&series);
492504 // Every occurrence of one publish carries the same teacher, so the first
493505 // row answers the ownership question for all of them.
494- let slot = AppointmentSlot::list_for_series(&series, &st.db)
506+ let slot = service::appointment_slot::list_for_series(&st.db, &series)
495507 .await?
496508 .into_iter()
497509 .next()
@@ -501,7 +513,7 @@ async fn delete_slot_series(
501513 "only the slot's teacher or a manager/admin can delete it",
502514 ));
503515 }
504- AppointmentSlot::delete_series(&series, &st.db).await?;
516+ service::appointment_slot::delete_series(&st.db, &series).await?;
505517 Ok(StatusCode::NO_CONTENT)
506518 }
507519
@@ -541,7 +553,7 @@ async fn book(
541553 ));
542554 }
543555 let slot_id = AppointmentSlotId::from_key(&req.slot);
544- let slot = AppointmentSlot::read(&slot_id, &st.db)
556+ let slot = service::appointment_slot::read(&st.db, &slot_id)
545557 .await?
546558 .ok_or(AppError::NotFound)?;
547559 // The slot row is not the grant: a teacher demoted since publishing keeps
@@ -555,8 +567,7 @@ async fn book(
555567 ));
556568 }
557569 let reason = AppointmentReason::try_new(&req.reason)?;
558- let appointment =
559- service::appointment::book(&st.db, &slot_id, user.get_id(), reason).await?;
570+ let appointment = service::appointment::book(&st.db, &slot_id, user.get_id(), reason).await?;
560571 Ok((
561572 StatusCode::CREATED,
562573 one_appointment(appointment, &st.db).await?,
@@ -867,7 +878,9 @@ async fn ensure_requester(
867878 user: &User,
868879 db: &Database,
869880 ) -> Result<Appointment, AppError> {
870- let appointment = service::appointment::read(db, id).await?.ok_or(AppError::NotFound)?;
881+ let appointment = service::appointment::read(db, id)
882+ .await?
883+ .ok_or(AppError::NotFound)?;
871884 if appointment.get_requester() != user.get_id() {
872885 return Err(AppError::Forbidden(
873886 "only the requester can answer a counter-proposal",
@@ -902,12 +915,12 @@ mod tests {
902915 async fn demoted_slot_owner_loses_management() {
903916 let db = init_mem().await.unwrap();
904917 let owner = user("ogretmen", Role::Teacher, &db).await;
905- let slot = AppointmentSlot::create(
918+ let slot = service::appointment_slot::create(
919+ &db,
906920 owner.get_id(),
907921 Timestamp::from_millis(1_000),
908922 Timestamp::from_millis(2_000),
909923 None,
910- &db,
911924 )
912925 .await
913926 .unwrap();