import { ConflictException, Logger } from '@nestjs/common'; import { randomUUID } from 'crypto'; import { AuctionRedisService } from './redis/auction-redis.service'; export class AuctionLifecycleBusyError extends ConflictException { constructor() { super({ code: 'AUCTION_LIFECYCLE_BUSY', message: '다른 경매 작업을 처리 중입니다. 잠시 후 다시 시도해 주세요.', }); } } /** Serializes startup, cancellation, undo and Match side effects across nodes. */ export class AuctionLifecycleLock { private readonly logger = new Logger(AuctionLifecycleLock.name); constructor(private readonly redis: AuctionRedisService) {} async run(matchId: string, operation: () => Promise): Promise { // Kept outside runtime cleanup: cancelling an auction must not release a // lock still held by its cancellation/recovery operation. const key = `auction:${matchId}:lifecycleMutationLock`; const token = randomUUID(); if (!(await this.redis.acquireTokenLock(key, token, 30_000))) { throw new AuctionLifecycleBusyError(); } let renewal: Promise | undefined; let ownershipError: Error | undefined; const timer = setInterval(() => { if (renewal) return; renewal = this.redis .raw() .sendCommand([ 'SET', key, token, 'IFEQ', token, 'PX', '30000', ]) .then((result) => { if (result !== 'OK') throw new Error('Auction lifecycle lock ownership was lost.'); }) .catch((error: unknown) => { ownershipError = error instanceof Error ? error : new Error(String(error)); }) .finally(() => { renewal = undefined; }); }, 10_000); timer.unref?.(); try { const result = await operation(); clearInterval(timer); await renewal; if (ownershipError) throw ownershipError; return result; } finally { clearInterval(timer); await renewal; await this.redis.releaseTokenLock(key, token).catch((error: unknown) => { this.logger.warn( `Auction lifecycle lock release failed: ${String(error)}`, ); }); } } }