fix: broadcast auction state immediately on auto expiry

자동 만료(EXPIRE_PREPARE → completePreparedExpiry)는 게이트웨이를 거치지
않아 만료 확정 결과를 클라이언트에 즉시 알리는 동기 broadcast가 없었다.
그 결과 클라는 입찰 라운드 revision에 멈춰, 0초 근처 입찰 직후 "다음" 등
후속 액션에서 stale 관측값으로 CONFLICT를 반복했다.

AuctionDeadlineScheduler에 AuctionEventBusService를 주입해 만료 확정 직후
최신 state를 1차 broadcast한다. durability worker의 방송은 Mongo 성공 +
~1초 tick에 묶인 크래시 복구 백업임을 주석으로 명확히 했다.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
dahyeonandClaude Opus 4.8 committed 2026-06-23 11:49:48 -07:00
1 parent b367328df0
commit 46c8007e94
3 files changed
+62 -3

No files matched your search

@@ -2,6 +2,7 @@ import { AuctionRedisService } from './redis/auction-redis.service';
import { AuctionDeadlineScheduler } from './auction-deadline.scheduler'; import { AuctionDeadlineScheduler } from './auction-deadline.scheduler';
import { AuctionRedisCommandService } from './redis/auction-redis-command.service'; import { AuctionRedisCommandService } from './redis/auction-redis-command.service';
import { AuctionService } from './auction.service'; import { AuctionService } from './auction.service';
import { AuctionEventBusService } from './auction-event-bus.service';
function makeScheduler(params: { function makeScheduler(params: {
dueReply?: unknown; dueReply?: unknown;
@@ -37,14 +38,19 @@ function makeScheduler(params: {
.fn() .fn()
.mockResolvedValue(params.completedState ?? { phase: 'passed' }), .mockResolvedValue(params.completedState ?? { phase: 'passed' }),
} as unknown as jest.Mocked<AuctionService>; } as unknown as jest.Mocked<AuctionService>;
const eventBus = {
broadcastState: jest.fn(),
} as unknown as jest.Mocked<AuctionEventBusService>;
return { return {
auctionService, auctionService,
eventBus,
redis, redis,
redisCommand, redisCommand,
scheduler: new AuctionDeadlineScheduler( scheduler: new AuctionDeadlineScheduler(
redis, redis,
redisCommand, redisCommand,
auctionService, auctionService,
eventBus,
), ),
sendCommand, sendCommand,
}; };
@@ -122,8 +128,10 @@ describe('AuctionDeadlineScheduler', () => {
it('prepares and completes due auction deadlines', async () => { it('prepares and completes due auction deadlines', async () => {
const matchId = '665f2f01f1f1f1f1f1f1f1f1'; const matchId = '665f2f01f1f1f1f1f1f1f1f1';
const { auctionService, redisCommand, scheduler } = makeScheduler({ const completedState = { phase: 'passed', revision: 3 };
const { auctionService, eventBus, redisCommand, scheduler } = makeScheduler({
dueReply: [matchId], dueReply: [matchId],
completedState,
}); });
await expect(scheduler.processDueBidRoundDeadlines(10)).resolves.toEqual({ await expect(scheduler.processDueBidRoundDeadlines(10)).resolves.toEqual({
@@ -139,10 +147,13 @@ describe('AuctionDeadlineScheduler', () => {
}), }),
); );
expect(auctionService.completePreparedExpiry).toHaveBeenCalledTimes(1); expect(auctionService.completePreparedExpiry).toHaveBeenCalledTimes(1);
// 만료 확정 결과는 즉시 1차 broadcast돼야 한다(클라가 입찰 라운드에 멈춰
// 후속 액션에서 CONFLICT가 반복되는 것을 막는 핵심 동작).
expect(eventBus.broadcastState).toHaveBeenCalledWith(matchId, completedState);
}); });
it('skips noop expiry preparations', async () => { it('skips noop expiry preparations', async () => {
const { auctionService, scheduler } = makeScheduler({ const { auctionService, eventBus, scheduler } = makeScheduler({
dueReply: ['665f2f01f1f1f1f1f1f1f1f1'], dueReply: ['665f2f01f1f1f1f1f1f1f1f1'],
expireReply: { expireReply: {
code: 'NOT_DUE', code: 'NOT_DUE',
@@ -157,6 +168,7 @@ describe('AuctionDeadlineScheduler', () => {
skipped: 1, skipped: 1,
}); });
expect(auctionService.completePreparedExpiry).not.toHaveBeenCalled(); expect(auctionService.completePreparedExpiry).not.toHaveBeenCalled();
expect(eventBus.broadcastState).not.toHaveBeenCalled();
}); });
it('removes invalid deadline queue members', async () => { it('removes invalid deadline queue members', async () => {
@@ -7,6 +7,7 @@ import {
import { randomUUID } from 'crypto'; import { randomUUID } from 'crypto';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { AuctionService } from './auction.service'; import { AuctionService } from './auction.service';
import { AuctionEventBusService } from './auction-event-bus.service';
import { AuctionRedisCommandService } from './redis/auction-redis-command.service'; import { AuctionRedisCommandService } from './redis/auction-redis-command.service';
import { AuctionRedisService } from './redis/auction-redis.service'; import { AuctionRedisService } from './redis/auction-redis.service';
@@ -18,6 +19,28 @@ const BID_ROUND_DEADLINE_LEADER_LOCK_KEY =
'auction:bidRoundDeadlineScheduler:leader'; 'auction:bidRoundDeadlineScheduler:leader';
const BID_ROUND_DEADLINE_LEADER_LOCK_TTL_MS = 2500; const BID_ROUND_DEADLINE_LEADER_LOCK_TTL_MS = 2500;
/**
* 입찰 라운드 마감(deadline)을 감시해 자동으로 만료시키는 단일 리더 스위퍼.
*
* 만료는 2단계로 처리한다(정확히-1회 + 노드 크래시 복구를 위해):
* 1) EXPIRE_PREPARE Lua: `bidding → expiring`으로 flip하고 만료 결정/컨텍스트를
* `liveAuctionState`에 고정 + deadline ZSET에 재시도 점수 재등록.
* 2) `completePreparedExpiry`: 고정된 컨텍스트로 APPLY_TRANSITION을 돌려
* `sold`/`passed`로 확정하고 Mongo durability outbox를 enqueue.
*
* 중요(브로드캐스트 책임):
* - 관리자 수동 전환(sold/next 등)은 게이트웨이가 응답 직후 동기로 `state`를
* broadcast하지만, 자동 만료는 게이트웨이를 거치지 않는다.
* - 따라서 만료 확정 결과를 클라이언트에 즉시 알리는 1차 전달 책임은 이 스위퍼에
* 있다. 여기서 broadcast하지 않으면 클라는 입찰 라운드 revision에 멈춰 있다가
* "다음" 등 후속 액션에서 stale 관측값으로 CONFLICT를 반복하게 된다.
* - `AuctionDurabilityScheduler`의 broadcast는 Mongo 영속화 성공에 묶인 ~1초 주기의
* "노드 크래시 복구용 백업"이지 1차 전달 경로가 아니다(중복 emit돼도 클라
* revision 가드로 무해).
*
* 멀티 인스턴스: 리더 락을 잡은 한 인스턴스만 만료를 처리/방송하고, socket.io Redis
* adapter가 전 인스턴스 소켓으로 fanout한다.
*/
@Injectable() @Injectable()
export class AuctionDeadlineScheduler implements OnModuleInit, OnModuleDestroy { export class AuctionDeadlineScheduler implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(AuctionDeadlineScheduler.name); private readonly logger = new Logger(AuctionDeadlineScheduler.name);
@@ -28,6 +51,8 @@ export class AuctionDeadlineScheduler implements OnModuleInit, OnModuleDestroy {
private readonly auctionRedisService: AuctionRedisService, private readonly auctionRedisService: AuctionRedisService,
private readonly auctionRedisCommandService: AuctionRedisCommandService, private readonly auctionRedisCommandService: AuctionRedisCommandService,
private readonly auctionService: AuctionService, private readonly auctionService: AuctionService,
// 만료 확정 결과를 클라이언트에 즉시 알리기 위한 1차 broadcast 채널.
private readonly auctionEventBusService: AuctionEventBusService,
) {} ) {}
public onModuleInit(): void { public onModuleInit(): void {
@@ -110,6 +135,8 @@ export class AuctionDeadlineScheduler implements OnModuleInit, OnModuleDestroy {
continue; continue;
} }
try { try {
// 1단계: 만료 결정/컨텍스트 고정(bidding → expiring). 아직 마감 전이거나
// 이미 다른 phase면 noop으로 빠진다(stale ZSET 엔트리는 Lua가 정리).
const result = await this.auctionRedisCommandService.expirePrepare( const result = await this.auctionRedisCommandService.expirePrepare(
matchId, matchId,
{ {
@@ -123,10 +150,20 @@ export class AuctionDeadlineScheduler implements OnModuleInit, OnModuleDestroy {
continue; continue;
} }
prepared += 1; prepared += 1;
// 2단계: 고정된 컨텍스트로 sold/passed 확정. 재진입(다른 인스턴스/다음 틱)해도
// appliedAuctionStateTransitionIds dedupe로 정확히-1회만 반영된다.
const completedState = await this.auctionService.completePreparedExpiry( const completedState = await this.auctionService.completePreparedExpiry(
new mongoose.Types.ObjectId(matchId), new mongoose.Types.ObjectId(matchId),
); );
if (completedState) completed += 1; if (completedState) {
completed += 1;
// 1차 전달: 만료 확정 즉시 최신 state를 방송한다. 이게 없으면 클라가
// 입찰 라운드에 멈춰 후속 액션에서 CONFLICT가 반복된다(durability
// worker 백업 방송은 Mongo 성공 + ~1초 tick에 묶여 1차 전달로 부적합).
// 이미 처리된 전환은 completePreparedExpiry가 null을 반환하므로 중복
// 방송되지 않고, 혹시 겹쳐도 클라 revision 가드로 무해하다.
this.auctionEventBusService.broadcastState(matchId, completedState);
}
} catch (error) { } catch (error) {
skipped += 1; skipped += 1;
this.logger.warn( this.logger.warn(
@@ -278,6 +278,16 @@ export class AuctionDurabilityScheduler
} }
} }
/**
* 노드 크래시 복구용 백업 broadcast(1차 전달 아님).
*
* 정상 경로에서는 요청을 처리한 게이트웨이(수동 전환) 또는
* `AuctionDeadlineScheduler`(자동 만료)가 commit 직후 동기로 `state`를 방송한다.
* 이 메서드는 "방송을 하기로 한 인스턴스가 broadcast 전에 죽은" 경우를 위해
* outbox를 처리하면서 최신 state를 한 번 더 방송하는 안전망이다.
* 이 호출은 위 try 블록의 Mongo 트랜잭션이 성공해야(early return/throw 없이)
* 도달하므로 1차 전달로 의존해서는 안 된다. 중복 방송은 클라 revision 가드로 무해.
*/
private async broadcastLatestRedisAuctionStateIfRequested( private async broadcastLatestRedisAuctionStateIfRequested(
payload: AuctionDurabilityPayload, payload: AuctionDurabilityPayload,
): Promise<void> { ): Promise<void> {