fix(db): prevent double-booking a slot via unique active_slot_key (H2)

A non-unique index on (doctor_id, slot_start) plus a count-then-insert check
left a TOCTOU race: two concurrent requests could both pass isSlotTaken and
both insert. wrapInTransaction alone doesn't stop the phantom under InnoDB
REPEATABLE-READ.

Add a nullable, unique active_slot_key on Appointment = "doctorId:slotStart"
while the booking occupies the slot (pending/confirmed — in lockstep with
isSlotTaken); NULL once expired/completed/no_show/cancelled (NULLs don't collide
in a MySQL unique index, so released slots rebook freely). bookAtomically now:
catches the unique violation -> SlotTakenException, and expires lapsed pendings
in-transaction so the ~1-min window before the expiry cron doesn't wrongly block
rebooking. All three booking paths (online / my / admin) routed through it.

Migration backfills one row per (doctor, slot) — the latest id — so the index
builds even on dirty historical data without destructively cancelling bookings.
(Backfill surfaced a real pre-existing double-booked slot in dev data.)

Regression: tests/Appointment/SlotUniquenessTest. Adjusted the expiry-service
test fixture to use distinct slots (one live booking per slot is now enforced).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
hamed
2026-06-28 19:04:54 +03:30
co-authored by Claude Opus 4.8
parent c084571bf0
commit aa87b4a9cb
10 changed files with 343 additions and 38 deletions
+6 -15
View File
@@ -3,6 +3,7 @@
namespace App\Admin\Controller;
use App\Appointment\Entity\Appointment;
use App\Appointment\Repository\SlotTakenException;
use App\Auth\Entity\User;
use App\Shared\Service\InputValidator;
use App\Location\Entity\City;
@@ -805,26 +806,16 @@ class AdminApiController extends BaseController
$this->em->persist($patient);
}
$conflict = $this->em->createQueryBuilder()
->select('COUNT(a.id)')
->from(Appointment::class, 'a')
->where('a.doctor = :doctor')
->andWhere('a.slotStart < :end AND a.slotEnd > :start')
->andWhere("a.status NOT IN ('cancelled_by_doctor','cancelled_by_user','cancelled_by_admin','auto_cancel_unpaid')")
->setParameter('doctor', $doctor)
->setParameter('start', $slotStart)
->setParameter('end', $slotEnd)
->getQuery()->getSingleScalarResult();
if ($conflict > 0) return $this->error('SLOT_TAKEN', 'این نوبت قبلاً رزرو شده است', 409);
$appointment = new Appointment($doctor, $patient, $slotStart, $slotEnd);
if (!empty($data['note'])) $appointment->setNote($data['note']);
$locationId = $this->slotCalculator->resolveSlotLocationId($doctor, $slotStart);
if ($locationId !== null) $appointment->setAddressId($locationId);
$this->em->persist($appointment);
$this->em->flush();
try {
$this->em->getRepository(Appointment::class)->bookAtomically($appointment);
} catch (SlotTakenException) {
return $this->error('SLOT_TAKEN', 'این نوبت قبلاً رزرو شده است', 409);
}
return $this->success([
'uuid' => $appointment->getUuid(),