fix issue

This commit is contained in:
Marshal
2026-07-16 00:33:31 +00:00
parent 234a74e812
commit 41fe04652f
51 changed files with 1895 additions and 206 deletions

View File

@@ -769,7 +769,54 @@ export class BookingBatchService implements OnModuleInit {
bookings: Booking[],
scheduleId: string,
): Promise<void> {
for (const b of bookings) await this.reserve(b, scheduleId);
// H8: the capacity check (pickExportSchedule → budget.fits) and the
// reservation writes below are not atomic on their own — two concurrent
// export accepts can each see the same train as fitting and both reserve,
// overshooting the train's capacity. Serialize reservations against this
// schedule: take a pessimistic_write lock on the TrainSchedule row
// (SELECT … FOR UPDATE), then RE-VERIFY budget.fits for these bookings'
// combined need from freshly-committed state INSIDE the lock before the
// reserve writes run. A loser (another accept took the space first) gets a
// ConflictException — the staff accept fails and reverts, exactly as an
// up-front full train does. Covered: the fits-vs-reserve overshoot on the
// export FCFS path; the lock is held for the duration of the reserve writes.
await this.dataSource.transaction(async (manager) => {
const locked = await manager.findOne(TrainSchedule, {
where: { id: scheduleId },
lock: { mode: "pessimistic_write" },
});
if (!locked) {
throw new ConflictException(
"Export train is no longer available for reservation",
);
}
const schedule =
await this.trainSchedulesRepository.findByIdWithFullGraph(scheduleId);
const locomotive = schedule?.trainSet?.locomotive;
if (!schedule || !locomotive) {
throw new ConflictException(
"Export train is no longer available for reservation",
);
}
const wagonDims = await this.loadWagonDims();
const limits = await this.capacityLimits(locomotive);
const budget = await this.remainingBudget(schedule, limits, wagonDims);
const leg = budget.legOf(
bookings[0].originYardId,
bookings[0].destinationYardId,
);
const need =
bookings.length >= 2
? this.combinedNeed(bookings[0], bookings[1], wagonDims)
: this.needFor(bookings[0], wagonDims);
if (!leg || !budget.fits(need, leg)) {
throw new ConflictException(
"Train is full — no export capacity left for this day",
);
}
for (const b of bookings) await this.reserve(b, scheduleId);
});
this.armSettle(scheduleId);
const schedule =
await this.trainSchedulesRepository.findByIdWithFullGraph(scheduleId);