import { Injectable, Logger, OnModuleDestroy, OnModuleInit, } from '@nestjs/common'; import { randomUUID } from 'crypto'; import mongoose from 'mongoose'; import { AuctionService } from './auction.service'; import { AuctionEventBusService } from './auction-event-bus.service'; import { AuctionRedisCommandService } from './redis/auction-redis-command.service'; import { AuctionRedisService } from './redis/auction-redis.service'; const BID_ROUND_DEADLINE_QUEUE_KEY = 'auction:bidRoundDeadlineQueue'; const BID_ROUND_EXPIRY_RETRY_DELAY_MS = 3000; const BID_ROUND_DEADLINE_TICK_INTERVAL_MS = 1000; const BID_ROUND_DEADLINE_BATCH_LIMIT = 20; const BID_ROUND_DEADLINE_LEADER_LOCK_KEY = 'auction:bidRoundDeadlineScheduler:leader'; 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() export class AuctionDeadlineScheduler implements OnModuleInit, OnModuleDestroy { private readonly logger = new Logger(AuctionDeadlineScheduler.name); private tickTimer?: NodeJS.Timeout; private tickInProgress = false; constructor( private readonly auctionRedisService: AuctionRedisService, private readonly auctionRedisCommandService: AuctionRedisCommandService, private readonly auctionService: AuctionService, // 만료 확정 결과를 클라이언트에 즉시 알리기 위한 1차 broadcast 채널. private readonly auctionEventBusService: AuctionEventBusService, ) {} public onModuleInit(): void { this.tickTimer = setInterval( () => void this.safeTick(), BID_ROUND_DEADLINE_TICK_INTERVAL_MS, ); this.tickTimer.unref?.(); } public onModuleDestroy(): void { if (this.tickTimer) clearInterval(this.tickTimer); } private async safeTick(): Promise { if (this.tickInProgress) return; this.tickInProgress = true; const leaderLockToken = randomUUID(); let leaderLockAcquired = false; try { leaderLockAcquired = await this.auctionRedisService.acquireTokenLock( BID_ROUND_DEADLINE_LEADER_LOCK_KEY, leaderLockToken, BID_ROUND_DEADLINE_LEADER_LOCK_TTL_MS, ); if (!leaderLockAcquired) return; await this.processDueBidRoundDeadlines(BID_ROUND_DEADLINE_BATCH_LIMIT); } catch (error) { this.logger.warn( `Auction deadline tick failed: ${ error instanceof Error ? error.message : error }`, ); } finally { if (leaderLockAcquired) { await this.auctionRedisService.releaseTokenLock( BID_ROUND_DEADLINE_LEADER_LOCK_KEY, leaderLockToken, ); } this.tickInProgress = false; } } public async readDueMatchIds( currentRedisTimestampMS: number, batchLimit: number, ): Promise { const reply = await this.auctionRedisService.raw().sendCommand([ 'ZRANGEBYSCORE', BID_ROUND_DEADLINE_QUEUE_KEY, '-inf', String(currentRedisTimestampMS), 'LIMIT', '0', String(batchLimit), ]); return Array.isArray(reply) ? reply.map(String) : []; } public async processDueBidRoundDeadlines(batchLimit: number): Promise<{ completed: number; prepared: number; skipped: number; }> { const currentRedisTimestampMS = await this.auctionRedisService.getCurrentRedisTimestampMS(); const matchIds = await this.readDueMatchIds( currentRedisTimestampMS, batchLimit, ); let prepared = 0; let completed = 0; let skipped = 0; for (const matchId of matchIds) { if (!mongoose.isValidObjectId(matchId)) { skipped += 1; await this.removeBidRoundDeadlineQueueEntry(matchId); continue; } try { // 1단계: 만료 결정/컨텍스트 고정(bidding → expiring). 아직 마감 전이거나 // 이미 다른 phase면 noop으로 빠진다(stale ZSET 엔트리는 Lua가 정리). const result = await this.auctionRedisCommandService.expirePrepare( matchId, { auctionStateTransitionId: `expire:${matchId}:${randomUUID()}`, bidRoundExpiryRetryDelayMS: BID_ROUND_EXPIRY_RETRY_DELAY_MS, matchId, }, ); if ('noop' in result) { skipped += 1; continue; } prepared += 1; // 2단계: 고정된 컨텍스트로 sold/passed 확정. 재진입(다른 인스턴스/다음 틱)해도 // appliedAuctionStateTransitionIds dedupe로 정확히-1회만 반영된다. const completedState = await this.auctionService.completePreparedExpiry( new mongoose.Types.ObjectId(matchId), ); if (completedState) { completed += 1; // 1차 전달: 만료 확정 즉시 최신 state를 방송한다. 이게 없으면 클라가 // 입찰 라운드에 멈춰 후속 액션에서 CONFLICT가 반복된다(durability // worker 백업 방송은 Mongo 성공 + ~1초 tick에 묶여 1차 전달로 부적합). // 이미 처리된 전환은 completePreparedExpiry가 null을 반환하므로 중복 // 방송되지 않고, 혹시 겹쳐도 클라 revision 가드로 무해하다. this.auctionEventBusService.broadcastState(matchId, completedState); } } catch (error) { skipped += 1; this.logger.warn( `Auction deadline item failed for ${matchId}: ${ error instanceof Error ? error.message : error }`, ); } } return { completed, prepared, skipped }; } private async removeBidRoundDeadlineQueueEntry(matchId: string): Promise { await this.auctionRedisService.raw().sendCommand([ 'ZREM', BID_ROUND_DEADLINE_QUEUE_KEY, matchId, ]); } }