Files
lolympus-tournament-support/apps/api/src/modules/auction/auction-lifecycle-lock.ts
T
dahyeon f649490cd2 fix(auction): harden lifecycle and durable bid storage
Serialize lifecycle changes and make cancellation, deadlines, and match side effects recoverable and idempotent.

Archive accepted bids durably, quarantine invalid payloads, and preserve compatibility with empty round IDs. Synchronize HTTP polling and socket state with scoped resync events.

Add cancellation cleanup index migration and regression coverage. Validated with 744 API tests, 65 Redis integration tests, and 28 Mongo integration tests.
2026-11-09 23:24:11 +09:00

73 lines
2.2 KiB
TypeScript

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<T>(matchId: string, operation: () => Promise<T>): Promise<T> {
// 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<void> | undefined;
let ownershipError: Error | undefined;
const timer = setInterval(() => {
if (renewal) return;
renewal = this.redis
.raw()
.sendCommand<string | null>([
'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)}`,
);
});
}
}
}