🚫 reject overlapping availability slots at publish time
Browse files at this commit45d6fea68ee0d90942a1c23506f5a74fafcbf358Parent: a962778- fix
- 🚫 reject overlapping availability slots at publish time
2 changed files +161 -6
- src/domain/appointment_slot.rs +146 -0
- tests/integration.rs +15 -6
src/domain/appointment_slot.rsmodified+146 -0
| @@ -215,6 +215,31 @@ impl AppointmentSlot { | |||
| 215 | created.ok_or_else(|| AppError::Internal("failed to create appointment slot".into())) | 215 | created.ok_or_else(|| AppError::Internal("failed to create appointment slot".into())) |
| 216 | } | 216 | } |
| 217 | 217 | ||
| 218 | + /// Does the teacher already have a published slot whose window collides with | ||
| 219 | + /// `[starts_at, ends_at)`? Half-open, so a slot ending exactly where the new | ||
| 220 | + /// one starts is *not* a conflict — that is how a teacher's hour is carved | ||
| 221 | + /// into back-to-back slots. Caller must hold [`APPOINTMENT_LOCK`] for the | ||
| 222 | + /// answer to still be true by the time the insert lands. | ||
| 223 | + async fn conflicts_existing( | ||
| 224 | + teacher: &UserId, | ||
| 225 | + starts_at: Timestamp, | ||
| 226 | + ends_at: Timestamp, | ||
| 227 | + db: &Database, | ||
| 228 | + ) -> Result<bool, AppError> { | ||
| 229 | + let mut result = db | ||
| 230 | + .query( | ||
| 231 | + "SELECT VALUE id FROM appointment_slot \ | ||
| 232 | + WHERE teacher = $teacher AND starts_at < $ends AND ends_at > $starts \ | ||
| 233 | + LIMIT 1", | ||
| 234 | + ) | ||
| 235 | + .bind(("teacher", teacher.record())) | ||
| 236 | + .bind(("starts", starts_at.as_millis())) | ||
| 237 | + .bind(("ends", ends_at.as_millis())) | ||
| 238 | + .await? | ||
| 239 | + .check()?; | ||
| 240 | + Ok(!result.take::<Vec<RecordId>>(0)?.is_empty()) | ||
| 241 | + } | ||
| 242 | + | ||
| 218 | /// Publish one slot. | 243 | /// Publish one slot. |
| 219 | pub async fn create( | 244 | pub async fn create( |
| 220 | teacher: &UserId, | 245 | teacher: &UserId, |
| @@ -224,6 +249,14 @@ impl AppointmentSlot { | |||
| 224 | db: &Database, | 249 | db: &Database, |
| 225 | ) -> Result<AppointmentSlot, AppError> { | 250 | ) -> Result<AppointmentSlot, AppError> { |
| 226 | Self::check_window(starts_at, ends_at)?; | 251 | Self::check_window(starts_at, ends_at)?; |
| 252 | + // Check-then-insert under the lock so a concurrent publish or booking | ||
| 253 | + // can't slip a colliding window in between. | ||
| 254 | + let _guard = APPOINTMENT_LOCK.lock().await; | ||
| 255 | + if Self::conflicts_existing(teacher, starts_at, ends_at, db).await? { | ||
| 256 | + return Err(AppError::ConflictOwned( | ||
| 257 | + "this time overlaps a slot you have already published".into(), | ||
| 258 | + )); | ||
| 259 | + } | ||
| 227 | Self::insert( | 260 | Self::insert( |
| 228 | AppointmentSlot { | 261 | AppointmentSlot { |
| 229 | id: AppointmentSlotId::generate(), | 262 | id: AppointmentSlotId::generate(), |
| @@ -252,6 +285,28 @@ impl AppointmentSlot { | |||
| 252 | db: &Database, | 285 | db: &Database, |
| 253 | ) -> Result<Vec<AppointmentSlot>, AppError> { | 286 | ) -> Result<Vec<AppointmentSlot>, AppError> { |
| 254 | let windows = Self::weekly_windows(starts_at, ends_at, until)?; | 287 | let windows = Self::weekly_windows(starts_at, ends_at, until)?; |
| 288 | + // Validate the whole batch before writing a single row: all-or-nothing, | ||
| 289 | + // so a mid-series collision never leaves stray weeks behind. Held under | ||
| 290 | + // the lock from first check through last insert, matching `create`. | ||
| 291 | + let _guard = APPOINTMENT_LOCK.lock().await; | ||
| 292 | + for (i, &(w_start, w_end)) in windows.iter().enumerate() { | ||
| 293 | + // (a) against slots already in the database, and | ||
| 294 | + if Self::conflicts_existing(teacher, w_start, w_end, db).await? { | ||
| 295 | + return Err(AppError::ConflictOwned( | ||
| 296 | + "a repeated slot overlaps one you have already published".into(), | ||
| 297 | + )); | ||
| 298 | + } | ||
| 299 | + // (b) against every earlier occurrence in this same batch — catches | ||
| 300 | + // a duration longer than the weekly step overlapping itself. | ||
| 301 | + if windows[..i] | ||
| 302 | + .iter() | ||
| 303 | + .any(|&(o_start, o_end)| Appointment::overlaps(w_start, w_end, o_start, o_end)) | ||
| 304 | + { | ||
| 305 | + return Err(AppError::ConflictOwned( | ||
| 306 | + "the repeated slots overlap each other".into(), | ||
| 307 | + )); | ||
| 308 | + } | ||
| 309 | + } | ||
| 255 | let series = SlotSeries::generate(); | 310 | let series = SlotSeries::generate(); |
| 256 | let now = Timestamp::now(); | 311 | let now = Timestamp::now(); |
| 257 | let mut slots = Vec::with_capacity(windows.len()); | 312 | let mut slots = Vec::with_capacity(windows.len()); |
| @@ -510,4 +565,95 @@ mod tests { | |||
| 510 | .unwrap(); | 565 | .unwrap(); |
| 511 | assert_eq!(listed.len(), 5); | 566 | assert_eq!(listed.len(), 5); |
| 512 | } | 567 | } |
| 568 | + | ||
| 569 | + #[tokio::test] | ||
| 570 | + async fn overlapping_publish_is_refused_but_touching_is_allowed() { | ||
| 571 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 572 | + let teacher = UserId::from_key("t1"); | ||
| 573 | + AppointmentSlot::create(&teacher, at(1_000), at(2_000), None, &db) | ||
| 574 | + .await | ||
| 575 | + .unwrap(); | ||
| 576 | + | ||
| 577 | + // Overlaps the existing [1000,2000) → 409. | ||
| 578 | + assert!(matches!( | ||
| 579 | + AppointmentSlot::create(&teacher, at(1_500), at(2_500), None, &db).await, | ||
| 580 | + Err(AppError::ConflictOwned(_)) | ||
| 581 | + )); | ||
| 582 | + // Touching at the boundary (ends where the next starts) → allowed. | ||
| 583 | + assert!(AppointmentSlot::create(&teacher, at(2_000), at(3_000), None, &db) | ||
| 584 | + .await | ||
| 585 | + .is_ok()); | ||
| 586 | + assert!(AppointmentSlot::create(&teacher, at(0), at(1_000), None, &db) | ||
| 587 | + .await | ||
| 588 | + .is_ok()); | ||
| 589 | + // A different teacher sharing the same window is fine. | ||
| 590 | + let other = UserId::from_key("t2"); | ||
| 591 | + assert!(AppointmentSlot::create(&other, at(1_000), at(2_000), None, &db) | ||
| 592 | + .await | ||
| 593 | + .is_ok()); | ||
| 594 | + } | ||
| 595 | + | ||
| 596 | + #[tokio::test] | ||
| 597 | + async fn weekly_publish_overlapping_an_existing_slot_writes_nothing() { | ||
| 598 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 599 | + let teacher = UserId::from_key("t1"); | ||
| 600 | + // A lone slot on the third week of the coming series. | ||
| 601 | + AppointmentSlot::create( | ||
| 602 | + &teacher, | ||
| 603 | + at(1_000 + 2 * MILLIS_PER_WEEK), | ||
| 604 | + at(2_000 + 2 * MILLIS_PER_WEEK), | ||
| 605 | + None, | ||
| 606 | + &db, | ||
| 607 | + ) | ||
| 608 | + .await | ||
| 609 | + .unwrap(); | ||
| 610 | + | ||
| 611 | + let before = AppointmentSlot::list_for_teacher(&teacher, &db) | ||
| 612 | + .await | ||
| 613 | + .unwrap() | ||
| 614 | + .len(); | ||
| 615 | + assert!(matches!( | ||
| 616 | + AppointmentSlot::publish_weekly( | ||
| 617 | + &teacher, | ||
| 618 | + at(1_000), | ||
| 619 | + at(2_000), | ||
| 620 | + None, | ||
| 621 | + at(1_000 + 4 * MILLIS_PER_WEEK), | ||
| 622 | + &db, | ||
| 623 | + ) | ||
| 624 | + .await, | ||
| 625 | + Err(AppError::ConflictOwned(_)) | ||
| 626 | + )); | ||
| 627 | + // All-or-nothing: not one occurrence of the rejected series was written. | ||
| 628 | + assert_eq!( | ||
| 629 | + AppointmentSlot::list_for_teacher(&teacher, &db) | ||
| 630 | + .await | ||
| 631 | + .unwrap() | ||
| 632 | + .len(), | ||
| 633 | + before | ||
| 634 | + ); | ||
| 635 | + } | ||
| 636 | + | ||
| 637 | + #[tokio::test] | ||
| 638 | + async fn weekly_publish_that_self_overlaps_is_refused() { | ||
| 639 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 640 | + let teacher = UserId::from_key("t1"); | ||
| 641 | + // A window longer than the weekly step collides with the next week. | ||
| 642 | + assert!(matches!( | ||
| 643 | + AppointmentSlot::publish_weekly( | ||
| 644 | + &teacher, | ||
| 645 | + at(0), | ||
| 646 | + at(MILLIS_PER_WEEK + 1), | ||
| 647 | + None, | ||
| 648 | + at(MILLIS_PER_WEEK), | ||
| 649 | + &db, | ||
| 650 | + ) | ||
| 651 | + .await, | ||
| 652 | + Err(AppError::ConflictOwned(_)) | ||
| 653 | + )); | ||
| 654 | + assert!(AppointmentSlot::list_for_teacher(&teacher, &db) | ||
| 655 | + .await | ||
| 656 | + .unwrap() | ||
| 657 | + .is_empty()); | ||
| 658 | + } | ||
| 513 | } | 659 | } |
tests/integration.rsmodified+15 -6
| @@ -15576,10 +15576,11 @@ async fn approval_refuses_a_teacher_double_booking() { | |||
| 15576 | let ayse = login(&app, "ayse").await; | 15576 | let ayse = login(&app, "ayse").await; |
| 15577 | let now = Timestamp::now().as_millis(); | 15577 | let now = Timestamp::now().as_millis(); |
| 15578 | 15578 | ||
| 15579 | - // Two overlapping windows on the same calendar, one requester each: the | 15579 | + // A teacher can no longer publish two colliding slots, so the collision is |
| 15580 | - // request is fine (a wish), the second approval is not. | 15580 | + // reached the only way left: two non-overlapping slots, then a reschedule |
| 15581 | + // proposal that drags the second onto the first's just-approved window. | ||
| 15581 | let first = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; | 15582 | let first = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; |
| 15582 | - let second = publish_slot(&app, &ali, now + HOUR_MS + 600_000, now + 3 * HOUR_MS).await; | 15583 | + let second = publish_slot(&app, &ali, now + 3 * HOUR_MS, now + 4 * HOUR_MS).await; |
| 15583 | let one = book_ok(&app, &veli, &first).await; | 15584 | let one = book_ok(&app, &veli, &first).await; |
| 15584 | let two = book_ok(&app, &ayse, &second).await; | 15585 | let two = book_ok(&app, &ayse, &second).await; |
| 15585 | 15586 | ||
| @@ -15587,7 +15588,12 @@ async fn approval_refuses_a_teacher_double_booking() { | |||
| 15587 | decide(&app, &ali, &one, "approve").await.status, | 15588 | decide(&app, &ali, &one, "approve").await.status, |
| 15588 | StatusCode::OK | 15589 | StatusCode::OK |
| 15589 | ); | 15590 | ); |
| 15590 | - let res = decide(&app, &ali, &two, "approve").await; | 15591 | + // Teacher counter-proposes a window overlapping the just-approved meeting; |
| 15592 | + // accepting it is approval at the proposed time, and that collision is what | ||
| 15593 | + // must be refused. | ||
| 15594 | + let res = propose(&app, &ali, &two, now + HOUR_MS + 600_000, now + 2 * HOUR_MS + 600_000).await; | ||
| 15595 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 15596 | + let res = decide(&app, &ayse, &two, "reschedule/accept").await; | ||
| 15591 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); | 15597 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 15592 | // Refused, not half-applied: it is still pending and still decidable. | 15598 | // Refused, not half-applied: it is still pending and still decidable. |
| 15593 | let res = decide(&app, &ali, &two, "reject").await; | 15599 | let res = decide(&app, &ali, &two, "reject").await; |
| @@ -15616,8 +15622,11 @@ async fn approval_refuses_a_requester_double_booking() { | |||
| 15616 | let res = decide(&app, &mert, &two, "approve").await; | 15622 | let res = decide(&app, &mert, &two, "approve").await; |
| 15617 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); | 15623 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 15618 | 15624 | ||
| 15619 | - // Booking a fresh overlap once one is committed is refused up front. | 15625 | + // Booking a fresh overlap once one is committed is refused up front. The |
| 15620 | - let third = publish_slot(&app, &mert, now + HOUR_MS, now + 2 * HOUR_MS).await; | 15626 | + // slot comes from a third teacher: mert's calendar already holds `second`, |
| 15627 | + // which a same-teacher slot at this window would now overlap at publish. | ||
| 15628 | + let ahmet = login_as(&app, &db, "ahmet", "teacher").await; | ||
| 15629 | + let third = publish_slot(&app, &ahmet, now + HOUR_MS, now + 2 * HOUR_MS).await; | ||
| 15621 | let res = book_slot(&app, &veli, &third).await; | 15630 | let res = book_slot(&app, &veli, &third).await; |
| 15622 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); | 15631 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 15623 | } | 15632 | } |