From 45d6fea68ee0d90942a1c23506f5a74fafcbf358 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 24 Jul 2026 19:51:33 +0300 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=9A=AB=20reject=20overlapping=20av?= =?UTF-8?q?ailability=20slots=20at=20publish=20time=20-=20add=20Appointmen?= =?UTF-8?q?tSlot::conflicts=5Fexisting:=20per-teacher=20half-open=20=20=20?= =?UTF-8?q?[start,end)=20overlap=20query=20against=20existing=20appointmen?= =?UTF-8?q?t=5Fslot=20rows=20-=20create()=20+=20publish=5Fweekly()=20run?= =?UTF-8?q?=20the=20check=20under=20APPOINTMENT=5FLOCK=20so=20=20=20check?= =?UTF-8?q?=E2=86=92insert=20is=20atomic=20vs=20concurrent=20publishes/boo?= =?UTF-8?q?kings=20(409=20on=20hit)=20-=20weekly=20publish=20is=20all-or-n?= =?UTF-8?q?othing:=20every=20occurrence=20validated=20against=20=20=20exis?= =?UTF-8?q?ting=20slots=20and=20pairwise=20in-batch=20before=20any=20row?= =?UTF-8?q?=20is=20written=20-=20boundary-touching=20slots=20still=20allow?= =?UTF-8?q?ed;=20guard=20is=20per-teacher=20only=20-=20tests:=20overlap?= =?UTF-8?q?=E2=86=92409,=20touching=20allowed,=20weekly=20rejection=20writ?= =?UTF-8?q?es=20nothing,=20=20=20self-overlap=20rejected;=20reworked=20two?= =?UTF-8?q?=20integration=20setups=20that=20relied=20on=20=20=20now-illega?= =?UTF-8?q?l=20colliding=20same-teacher=20slots?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/domain/appointment_slot.rs | 146 +++++++++++++++++++++++++++++++++ tests/integration.rs | 21 +++-- 2 files changed, 161 insertions(+), 6 deletions(-) diff --git a/src/domain/appointment_slot.rs b/src/domain/appointment_slot.rs index 086277a..65d31f6 100644 --- a/src/domain/appointment_slot.rs +++ b/src/domain/appointment_slot.rs @@ -215,6 +215,31 @@ impl AppointmentSlot { created.ok_or_else(|| AppError::Internal("failed to create appointment slot".into())) } + /// 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 [`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()) + } + /// Publish one slot. pub async fn create( teacher: &UserId, @@ -224,6 +249,14 @@ impl AppointmentSlot { 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( AppointmentSlot { id: AppointmentSlotId::generate(), @@ -252,6 +285,28 @@ impl AppointmentSlot { 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 first check through last insert, matching `create`. + let _guard = APPOINTMENT_LOCK.lock().await; + for (i, &(w_start, w_end)) in windows.iter().enumerate() { + // (a) against slots already in the database, and + if Self::conflicts_existing(teacher, w_start, w_end, db).await? { + 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 mut slots = Vec::with_capacity(windows.len()); @@ -510,4 +565,95 @@ mod tests { .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 + ); + } + + #[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/tests/integration.rs b/tests/integration.rs index 47632c9..985ed80 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -15576,10 +15576,11 @@ async fn approval_refuses_a_teacher_double_booking() { let ayse = login(&app, "ayse").await; let now = Timestamp::now().as_millis(); - // Two overlapping windows on the same calendar, one requester each: the - // request is fine (a wish), the second approval is not. + // A teacher can no longer publish two colliding slots, so the collision is + // reached the only way left: two non-overlapping slots, then a reschedule + // proposal that drags the second onto the first's just-approved window. let first = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; - let second = publish_slot(&app, &ali, now + HOUR_MS + 600_000, now + 3 * HOUR_MS).await; + let second = publish_slot(&app, &ali, now + 3 * HOUR_MS, now + 4 * HOUR_MS).await; let one = book_ok(&app, &veli, &first).await; let two = book_ok(&app, &ayse, &second).await; @@ -15587,7 +15588,12 @@ async fn approval_refuses_a_teacher_double_booking() { decide(&app, &ali, &one, "approve").await.status, StatusCode::OK ); - let res = decide(&app, &ali, &two, "approve").await; + // Teacher counter-proposes a window overlapping the just-approved meeting; + // accepting it is approval at the proposed time, and that collision is what + // must be refused. + let res = propose(&app, &ali, &two, now + HOUR_MS + 600_000, now + 2 * HOUR_MS + 600_000).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = decide(&app, &ayse, &two, "reschedule/accept").await; assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); // Refused, not half-applied: it is still pending and still decidable. let res = decide(&app, &ali, &two, "reject").await; @@ -15616,8 +15622,11 @@ async fn approval_refuses_a_requester_double_booking() { let res = decide(&app, &mert, &two, "approve").await; assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); - // Booking a fresh overlap once one is committed is refused up front. - let third = publish_slot(&app, &mert, now + HOUR_MS, now + 2 * HOUR_MS).await; + // Booking a fresh overlap once one is committed is refused up front. The + // slot comes from a third teacher: mert's calendar already holds `second`, + // which a same-teacher slot at this window would now overlap at publish. + let ahmet = login_as(&app, &db, "ahmet", "teacher").await; + let third = publish_slot(&app, &ahmet, now + HOUR_MS, now + 2 * HOUR_MS).await; let res = book_slot(&app, &veli, &third).await; assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); }