🚫 make a weekly slot publish atomic, and stop holding the lock 52x
Browse files at this commit5e0218698e46533cbf5dba4b1f09cf1eb26fe3ebParent: f62fb74- fix
- 🚫 make a weekly slot publish atomic, and stop holding the lock 52x
2 changed files +127 -23
- src/domain/appointment.rs +6 -2
- src/domain/appointment_slot.rs +121 -21
src/domain/appointment.rsmodified+6 -2
| @@ -473,8 +473,12 @@ impl Appointment { | |||
| 473 | Self::save(appointment, db).await | 473 | Self::save(appointment, db).await |
| 474 | } | 474 | } |
| 475 | 475 | ||
| 476 | - /// Call the meeting off. Legal from either side and from either live | 476 | + /// Call the meeting off. Legal from either live state, so an approved |
| 477 | - /// state, so an approved meeting can still be dropped; the slot frees up. | 477 | + /// meeting can still be dropped; the slot frees up. The web layer opens |
| 478 | + /// this to the **requester only** — a teacher's way out is `reject` while | ||
| 479 | + /// the booking is pending, or `reschedule` (back to `pending`) then | ||
| 480 | + /// `reject` for an approved one — and `decline_reschedule`, the other | ||
| 481 | + /// caller, is the requester's too. | ||
| 478 | /// | 482 | /// |
| 479 | /// Refused (409) once the *effective* window has opened — a meeting that | 483 | /// Refused (409) once the *effective* window has opened — a meeting that |
| 480 | /// began is history, not a plan. The guard lives here rather than in the | 484 | /// began is history, not a plan. The guard lives here rather than in the |
src/domain/appointment_slot.rsmodified+121 -21
| @@ -225,6 +225,36 @@ impl AppointmentSlot { | |||
| 225 | Ok(!result.take::<Vec<RecordId>>(0)?.is_empty()) | 225 | Ok(!result.take::<Vec<RecordId>>(0)?.is_empty()) |
| 226 | } | 226 | } |
| 227 | 227 | ||
| 228 | + /// Every window this teacher already published that intersects the envelope | ||
| 229 | + /// `[from, to)`. One read for a whole batch: a stored row that overlaps *any* | ||
| 230 | + /// window in the batch necessarily overlaps the envelope spanning them all, | ||
| 231 | + /// so filtering the envelope and comparing in memory is exactly the | ||
| 232 | + /// per-window [`conflicts_existing`](Self::conflicts_existing) check, | ||
| 233 | + /// hoisted out of the loop — which is what keeps [`APPOINTMENT_LOCK`] down | ||
| 234 | + /// to two round trips instead of one per occurrence. | ||
| 235 | + async fn windows_in_span( | ||
| 236 | + teacher: &UserId, | ||
| 237 | + from: Timestamp, | ||
| 238 | + to: Timestamp, | ||
| 239 | + db: &Database, | ||
| 240 | + ) -> Result<Vec<(Timestamp, Timestamp)>, AppError> { | ||
| 241 | + let mut result = db | ||
| 242 | + .query( | ||
| 243 | + "SELECT * FROM appointment_slot \ | ||
| 244 | + WHERE teacher = $teacher AND starts_at < $to AND ends_at > $from", | ||
| 245 | + ) | ||
| 246 | + .bind(("teacher", teacher.record())) | ||
| 247 | + .bind(("from", from.as_millis())) | ||
| 248 | + .bind(("to", to.as_millis())) | ||
| 249 | + .await? | ||
| 250 | + .check()?; | ||
| 251 | + Ok(result | ||
| 252 | + .take::<Vec<AppointmentSlot>>(0)? | ||
| 253 | + .into_iter() | ||
| 254 | + .map(|slot| (slot.starts_at, slot.ends_at)) | ||
| 255 | + .collect()) | ||
| 256 | + } | ||
| 257 | + | ||
| 228 | /// Publish one slot. | 258 | /// Publish one slot. |
| 229 | pub async fn create( | 259 | pub async fn create( |
| 230 | teacher: &UserId, | 260 | teacher: &UserId, |
| @@ -272,11 +302,17 @@ impl AppointmentSlot { | |||
| 272 | let windows = Self::weekly_windows(starts_at, ends_at, until)?; | 302 | let windows = Self::weekly_windows(starts_at, ends_at, until)?; |
| 273 | // Validate the whole batch before writing a single row: all-or-nothing, | 303 | // Validate the whole batch before writing a single row: all-or-nothing, |
| 274 | // so a mid-series collision never leaves stray weeks behind. Held under | 304 | // so a mid-series collision never leaves stray weeks behind. Held under |
| 275 | - // the lock from first check through last insert, matching `create`. | 305 | + // the lock from the check through the write, matching `create`. |
| 276 | let _guard = APPOINTMENT_LOCK.lock().await; | 306 | let _guard = APPOINTMENT_LOCK.lock().await; |
| 307 | + // (a) against the slots already in the database. `weekly_windows` walks | ||
| 308 | + // forward, so the first and last occurrence bound every one of them. | ||
| 309 | + let (first, last) = (windows[0], windows[windows.len() - 1]); | ||
| 310 | + let published = Self::windows_in_span(teacher, first.0, last.1, db).await?; | ||
| 277 | for (i, &(w_start, w_end)) in windows.iter().enumerate() { | 311 | for (i, &(w_start, w_end)) in windows.iter().enumerate() { |
| 278 | - // (a) against slots already in the database, and | 312 | + if published |
| 279 | - if Self::conflicts_existing(teacher, w_start, w_end, db).await? { | 313 | + .iter() |
| 314 | + .any(|&(p_start, p_end)| Appointment::overlaps(w_start, w_end, p_start, p_end)) | ||
| 315 | + { | ||
| 280 | return Err(AppError::ConflictOwned( | 316 | return Err(AppError::ConflictOwned( |
| 281 | "a repeated slot overlaps one you have already published".into(), | 317 | "a repeated slot overlaps one you have already published".into(), |
| 282 | )); | 318 | )); |
| @@ -294,25 +330,45 @@ impl AppointmentSlot { | |||
| 294 | } | 330 | } |
| 295 | let series = SlotSeries::generate(); | 331 | let series = SlotSeries::generate(); |
| 296 | let now = Timestamp::now(); | 332 | let now = Timestamp::now(); |
| 297 | - let mut slots = Vec::with_capacity(windows.len()); | 333 | + let rows: Vec<AppointmentSlot> = windows |
| 298 | - for (starts_at, ends_at) in windows { | 334 | + .iter() |
| 299 | - slots.push( | 335 | + .map(|&(starts_at, ends_at)| AppointmentSlot { |
| 300 | - Self::insert( | 336 | + id: AppointmentSlotId::generate(), |
| 301 | - AppointmentSlot { | 337 | + teacher: teacher.clone(), |
| 302 | - id: AppointmentSlotId::generate(), | 338 | + starts_at, |
| 303 | - teacher: teacher.clone(), | 339 | + ends_at, |
| 304 | - starts_at, | 340 | + note: note.clone(), |
| 305 | - ends_at, | 341 | + series: Some(series.clone()), |
| 306 | - note: note.clone(), | 342 | + created_at: now, |
| 307 | - series: Some(series.clone()), | 343 | + }) |
| 308 | - created_at: now, | 344 | + .collect(); |
| 309 | - }, | 345 | + // One statement, therefore one transaction: SurrealDB rolls the whole |
| 310 | - db, | 346 | + // `INSERT` back on any error. The row-by-row loop this replaces did not |
| 311 | - ) | 347 | + // — a database error at week 7 of 10 answered 500 with six stray weeks |
| 312 | - .await?, | 348 | + // already published, a half-series nobody asked for. It is also a single |
| 313 | - ); | 349 | + // round trip, so the lock is now held for two queries whatever the |
| 350 | + // occurrence count, instead of 1 + N (up to 52) sequential ones. | ||
| 351 | + // | ||
| 352 | + // No `BEGIN`/`COMMIT` wrapper: those consume result slots in this | ||
| 353 | + // version, and a lone statement is already atomic — the explicit form | ||
| 354 | + // would buy nothing but an off-by-one waiting to happen. | ||
| 355 | + let mut result = db | ||
| 356 | + .query("INSERT INTO appointment_slot $rows") | ||
| 357 | + .bind(("rows", rows)) | ||
| 358 | + .await? | ||
| 359 | + .check()?; | ||
| 360 | + let mut created = result.take::<Vec<AppointmentSlot>>(0)?; | ||
| 361 | + if created.len() != windows.len() { | ||
| 362 | + return Err(AppError::Internal(format!( | ||
| 363 | + "published {} of {} appointment slots", | ||
| 364 | + created.len(), | ||
| 365 | + windows.len() | ||
| 366 | + ))); | ||
| 314 | } | 367 | } |
| 315 | - Ok(slots) | 368 | + // `INSERT` makes no promise about the order it echoes rows back in, and |
| 369 | + // the response is rendered as the published calendar. | ||
| 370 | + created.sort_by_key(|slot| slot.starts_at.as_millis()); | ||
| 371 | + Ok(created) | ||
| 316 | } | 372 | } |
| 317 | 373 | ||
| 318 | pub async fn read( | 374 | pub async fn read( |
| @@ -625,6 +681,50 @@ mod tests { | |||
| 625 | ); | 681 | ); |
| 626 | } | 682 | } |
| 627 | 683 | ||
| 684 | + /// The existing-slot check is one envelope-wide read instead of a query per | ||
| 685 | + /// occurrence, so the edges of that envelope are what could go wrong: a | ||
| 686 | + /// clash on the *last* week must still be caught, and a slot merely touching | ||
| 687 | + /// the batch's boundaries must still be allowed. | ||
| 688 | + #[tokio::test] | ||
| 689 | + async fn the_batch_wide_conflict_read_still_sees_the_last_week_and_lets_touching_through() { | ||
| 690 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 691 | + let teacher = UserId::from_key("t1"); | ||
| 692 | + let last = 1_000 + 4 * MILLIS_PER_WEEK; | ||
| 693 | + // Touching both ends of the envelope: ends where the first occurrence | ||
| 694 | + // starts, and starts where the last one ends. | ||
| 695 | + AppointmentSlot::create(&teacher, at(0), at(1_000), None, &db) | ||
| 696 | + .await | ||
| 697 | + .unwrap(); | ||
| 698 | + AppointmentSlot::create(&teacher, at(last + 1_000), at(last + 2_000), None, &db) | ||
| 699 | + .await | ||
| 700 | + .unwrap(); | ||
| 701 | + assert_eq!( | ||
| 702 | + AppointmentSlot::publish_weekly(&teacher, at(1_000), at(2_000), None, at(last), &db) | ||
| 703 | + .await | ||
| 704 | + .unwrap() | ||
| 705 | + .len(), | ||
| 706 | + 5 | ||
| 707 | + ); | ||
| 708 | + | ||
| 709 | + // One millisecond into the last occurrence → the whole publish is 409. | ||
| 710 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 711 | + AppointmentSlot::create(&teacher, at(last + 999), at(last + 3_000), None, &db) | ||
| 712 | + .await | ||
| 713 | + .unwrap(); | ||
| 714 | + assert!(matches!( | ||
| 715 | + AppointmentSlot::publish_weekly(&teacher, at(1_000), at(2_000), None, at(last), &db) | ||
| 716 | + .await, | ||
| 717 | + Err(AppError::ConflictOwned(_)) | ||
| 718 | + )); | ||
| 719 | + assert_eq!( | ||
| 720 | + AppointmentSlot::list_for_teacher(&teacher, &db) | ||
| 721 | + .await | ||
| 722 | + .unwrap() | ||
| 723 | + .len(), | ||
| 724 | + 1 | ||
| 725 | + ); | ||
| 726 | + } | ||
| 727 | + | ||
| 628 | #[tokio::test] | 728 | #[tokio::test] |
| 629 | async fn weekly_publish_that_self_overlaps_is_refused() { | 729 | async fn weekly_publish_that_self_overlaps_is_refused() { |
| 630 | let db = crate::database::init_mem().await.unwrap(); | 730 | let db = crate::database::init_mem().await.unwrap(); |