refactor: take the three risky rows back to the plan, without the bugs they invited
All three were deviations I had argued for. Reversing them as asked, each in the shape the plan wanted and with the failure it would otherwise cause closed. consume now catches the unique-constraint violation, as specified, instead of relying only on a read-before-insert. The read stays for the ordinary path, but it never closed the race — only the unique key does. What made the catch dangerous is that Doctrine closes the EntityManager on a constraint violation and the rest of the request dies with it, so the catch resets the registry. Without that, "already consumed" would surface as an unrelated 500. A test inserts the ledger row from a second connection and then asks the service to consume: it returns true, the manager is still open, and exactly one session is taken. Cancellation is one transaction now: status, capacity release, credit refund, penalty and the timeline row commit together. An appointment marked cancelled whose capacity was never released is the worst of both — the patient has no appointment and nobody can take the slot. Notification stays outside the commit, because an SMS cannot be rolled back and must not sit inside something that can. A test with an SMS provider that always throws proves the cancellation still commits. The ledger's running balance is computed in the UI from the rows on screen. The server still sends its own and remains the reference; the point of computing it here is that the column now reflects the rows the user is actually looking at, so a truncated list shows up as a mismatch rather than as a number nobody can check. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -447,6 +447,80 @@ class CancellationTest extends ApiTestCase
|
||||
self::assertSame(200, $this->responseCode());
|
||||
}
|
||||
|
||||
/**
|
||||
* ⭐ شکست اطلاعرسانی نباید لغو را برگرداند.
|
||||
*
|
||||
* حالا که همهٔ نوشتنها در یک تراکنشاند، این سؤال جدی است: اگر پیامک **داخل** آن
|
||||
* بلوک بود، یک خطای سرویس پیامک ظرفیت آزادشده را پس میگرفت و بیمار هم نوبت
|
||||
* نداشت هم وقتش را. اطلاعرسانی عمداً بعد از commit است و این تست همان را پین
|
||||
* میکند: با یک notifier که همیشه میترکد، لغو باز هم کامل انجام میشود.
|
||||
*/
|
||||
public function testAFailingNotifierDoesNotUndoTheCancellation(): void
|
||||
{
|
||||
[$user, $section, , $doctor, $patient] = $this->clinicWithPatient();
|
||||
$clinicId = (int) $patient->getEntityId();
|
||||
$service = $this->service($section);
|
||||
|
||||
$appointment = $this->appointment($doctor, $patient, $service, $clinicId, 48, 4_000_000, 4_000_000);
|
||||
$uuid = $appointment->getUuid();
|
||||
|
||||
// برای اینکه اطلاعرسانی واقعاً به بیمار برسد، باید کسی در لیست انتظار باشد.
|
||||
$waiting = $this->createUser(['ROLE_USER']);
|
||||
$record = new PatientRecord('clinic', $clinicId, $waiting, 'clinic', $clinicId);
|
||||
$this->em->persist($record);
|
||||
$this->em->flush();
|
||||
|
||||
$entry = new \App\Waitlist\Entity\WaitlistEntry(
|
||||
$record,
|
||||
$this->em->getRepository(ServiceItem::class)->find($service->getId()),
|
||||
$appointment->getSlotStart() - 86400,
|
||||
$appointment->getSlotStart() + 86400,
|
||||
);
|
||||
$this->em->persist($entry);
|
||||
$this->em->flush();
|
||||
|
||||
// سرویس پیامکی که همیشه میترکد — همان چیزی که در تولید یک قطعی است.
|
||||
static::getContainer()->set(
|
||||
\App\Sms\Service\SmsService::class,
|
||||
new class extends \App\Sms\Service\SmsService {
|
||||
public function __construct() {}
|
||||
|
||||
public function dispatchAsync(
|
||||
string $mobile,
|
||||
string $message,
|
||||
string $provider = 'kavenegar',
|
||||
?string $templateUuid = null,
|
||||
array $templateVars = [],
|
||||
?string $templateCode = null,
|
||||
string $tag = \App\Sms\Entity\SmsLog::TAG_GLOBAL,
|
||||
): void {
|
||||
throw new \RuntimeException('sms provider down');
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
$threw = false;
|
||||
|
||||
try {
|
||||
static::getContainer()->get(\App\Cancellation\Service\CancellationService::class)
|
||||
->cancel($appointment, Appointment::STATUS_CANCELLED_BY_USER, $user);
|
||||
} catch (\RuntimeException) {
|
||||
$threw = true;
|
||||
}
|
||||
|
||||
self::assertTrue($threw, 'خطای اطلاعرسانی بالا میآید — پنهانش نمیکنیم');
|
||||
|
||||
// ولی خودِ لغو commit شده است.
|
||||
$this->em->clear();
|
||||
$reloaded = $this->em->getRepository(Appointment::class)->findOneBy(['uuid' => $uuid]);
|
||||
|
||||
self::assertSame(
|
||||
Appointment::STATUS_CANCELLED_BY_USER,
|
||||
$reloaded->getStatus(),
|
||||
'لغو نباید گروگان سرویس پیامک بماند',
|
||||
);
|
||||
}
|
||||
|
||||
public function testAnotherClinicCannotPreviewTheCancellation(): void
|
||||
{
|
||||
[$owner, $section, $address, $doctor, $patient] = $this->clinicWithPatient();
|
||||
|
||||
@@ -254,6 +254,53 @@ class PackageLedgerTest extends ApiTestCase
|
||||
self::assertSame(5, $this->ledgerService()->balance($entity), 'جلسه پس گرفته شد');
|
||||
}
|
||||
|
||||
/**
|
||||
* ⭐ رقابت واقعی: ردیف `consume` از یک اتصال دیگر درج میشود و بعد سرویس تلاش
|
||||
* میکند همان را بنویسد.
|
||||
*
|
||||
* بررسی پیش از درج این پنجره را نمیبندد؛ فقط کلید یکتا میبندد. و چون Doctrine روی
|
||||
* نقض کلید `EntityManager` را میبندد، بدون بازنشانیِ رجیستری این حالت به یک ۵۰۰
|
||||
* بیربط تبدیل میشد — نه یک «قبلاً مصرف شده».
|
||||
*/
|
||||
public function testAConcurrentConsumeIsAbsorbedWithoutBurningTheRequest(): void
|
||||
{
|
||||
[$user, $section, $address, $doctor, $patient] = $this->clinicWithPatient();
|
||||
$service = $this->service($section, 'لیزر');
|
||||
|
||||
$sold = $this->sell($user, $patient, $this->definePackage($user, $service)['uuid']);
|
||||
$appointment = $this->reload($this->appointment($doctor, $patient, $service, (int) $address->getClinicId()));
|
||||
|
||||
$package = static::getContainer()->get(PatientPackageRepository::class)->findByUuid($sold['uuid']);
|
||||
|
||||
// اتصال جدا = «درخواست دیگر». ردیف مصرف را پشت سرِ سرویس درج میکند.
|
||||
$other = \Doctrine\DBAL\DriverManager::getConnection($this->em->getConnection()->getParams());
|
||||
|
||||
try {
|
||||
$other->insert('session_credit_ledger', [
|
||||
'patient_package_id' => $package->getId(),
|
||||
'appointment_id' => $appointment->getId(),
|
||||
'kind' => 'consume',
|
||||
'delta' => -1,
|
||||
'created_at' => time(),
|
||||
'entity_type' => $package->getEntityType(),
|
||||
'entity_id' => $package->getEntityId(),
|
||||
'uuid' => \Symfony\Component\Uid\Uuid::v4()->toRfc4122(),
|
||||
]);
|
||||
} finally {
|
||||
$other->close();
|
||||
}
|
||||
|
||||
// سرویس همان مصرف را دوباره تلاش میکند: باید `true` بدهد، نه خطا.
|
||||
self::assertTrue($this->consumption()->consumeFor($this->reload($appointment)));
|
||||
|
||||
// و مهمتر: مدیر هنوز زنده است و کارِ بعدی همین request انجام میشود.
|
||||
$em = static::getContainer()->get(\Doctrine\ORM\EntityManagerInterface::class);
|
||||
self::assertTrue($em->isOpen(), 'EntityManager نباید بعد از نقض کلید بسته بماند');
|
||||
|
||||
$fresh = $em->getRepository(\App\Package\Entity\PatientPackage::class)->findOneBy(['uuid' => $sold['uuid']]);
|
||||
self::assertSame(5, $this->ledgerService()->balance($fresh), 'فقط یک جلسه خورده شود');
|
||||
}
|
||||
|
||||
/** `confirm` idempotent است؛ اجرای دومش نباید جلسهٔ دوم بخورد. */
|
||||
public function testConsumingTwiceForTheSameAppointmentTakesOnlyOneSession(): void
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user