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.
This commit is contained in:
dahyeon committed 2026-11-09 23:24:11 +09:00
1 parent f2eec479d9
commit f649490cd2
55 files changed
+5374 -522

No files matched your search

@@ -0,0 +1,7 @@
export const AUCTION_CANCELLATION_CLEANUP_INDEX = {
key: { auctionCancellationCleanupRetryAt: 1 as const },
options: {
name: 'auction_cancellation_cleanup_due',
partialFilterExpression: { auctionCancellationCleanupPending: true },
},
};
@@ -0,0 +1,39 @@
import type { mongo } from 'mongoose';
import { AUCTION_CANCELLATION_CLEANUP_INDEX } from '../auction-cancellation-index';
/** Creates only this additive index; never drops or rebuilds other indexes. */
export async function migrateAuctionCancellationIndex(
db: mongo.Db,
{ dryRun = true }: { dryRun?: boolean } = {},
) {
const { key, options } = AUCTION_CANCELLATION_CLEANUP_INDEX;
const collection = db.collection('match');
const indexes = await collection
.listIndexes()
.toArray()
.catch((error: unknown) => {
if (error instanceof Error && 'code' in error && error.code === 26)
return [];
throw error;
});
const existing = indexes.find((index) => index.name === options.name);
if (
existing &&
(JSON.stringify(existing.key) !== JSON.stringify(key) ||
JSON.stringify(existing.partialFilterExpression) !==
JSON.stringify(options.partialFilterExpression) ||
existing.unique === true ||
existing.sparse === true ||
existing.hidden === true)
) {
throw new Error(
`Index ${options.name} already exists with a different definition.`,
);
}
if (!dryRun) await collection.createIndex(key, options);
return {
dryRun,
alreadyPresent: Boolean(existing),
index: { key, ...options },
};
}
@@ -0,0 +1,105 @@
import 'reflect-metadata';
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { readFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import { ConnectionService, resolveMongoDbName } from '../connection.service';
import { SecretModule } from '../../secret/secret.module';
import { migrateAuctionCancellationIndex } from './20261109-auction-cancellation-index';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: [
resolve(__dirname, '../../../../../../project.env'),
resolve(process.cwd(), '../project.env'),
resolve(process.cwd(), 'apps/project.env'),
resolve(process.cwd(), 'project.env'),
],
}),
SecretModule,
],
providers: [ConnectionService],
})
class MigrationModule {}
export function parseAuctionIndexOptions(argv: string[]) {
let dryRun = true;
let help = false;
let nodeEnv = process.env.NODE_ENV ?? 'dev';
for (let index = 0; index < argv.length; index++) {
const argument = argv[index];
if (argument === '--') continue;
if (argument === '--apply') dryRun = false;
else if (argument === '--dry-run') dryRun = true;
else if (argument === '--help' || argument === '-h') help = true;
else if (argument === '--env') nodeEnv = argv[++index] ?? '';
else if (argument.startsWith('--env=')) nodeEnv = argument.slice(6);
else throw new Error(`Unknown argument: ${argument}`);
}
if (!help && !['dev', 'staging', 'prod'].includes(nodeEnv)) {
throw new Error('--env must be dev, staging, or prod.');
}
return { dryRun, help, nodeEnv };
}
async function main(): Promise<void> {
const options = parseAuctionIndexOptions(process.argv.slice(2));
if (options.help) {
console.log(`Usage:
pnpm --filter api auction:indexes -- --env staging --dry-run
pnpm --filter api auction:indexes -- --env prod --apply
Defaults to dry-run. --env accepts dev, staging, or prod (NODE_ENV or dev by default).
Creates the Match cancellation cleanup partial index; does not modify documents.`);
return;
}
// Use the same optional machine environment as the existing migration runners.
const machineHome = process.env.HOME ?? process.env.USERPROFILE;
if (machineHome) {
const contents = await readFile(
resolve(machineHome, 'source/global-env-vars.txt'),
'utf8',
).catch(() => '');
for (const line of contents.split(/\r?\n/)) {
const match = line.trim().match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
if (match) process.env[match[1]] = match[2].replace(/^["']|["']$/g, '');
}
}
process.env.NODE_ENV = options.nodeEnv;
// Even a dry-run with auto-index enabled in the environment must not write.
process.env.MONGODB_AUTO_INDEX = 'false';
const app = await NestFactory.createApplicationContext(MigrationModule, {
logger: ['warn', 'error'],
});
try {
const connection = await app.get(ConnectionService).getConnection();
if (!connection.db) throw new Error('MongoDB connection has no db handle.');
const result = await migrateAuctionCancellationIndex(
connection.db,
options,
);
console.log(
JSON.stringify(
{
env: options.nodeEnv,
db: resolveMongoDbName(options.nodeEnv),
...result,
},
null,
2,
),
);
} finally {
await app.close();
}
}
if (require.main === module) {
void main().catch((error: unknown) => {
console.error(error instanceof Error ? error.message : error);
process.exitCode = 1;
});
}
@@ -12,6 +12,7 @@ import {
competitionModelDefinitions,
} from '../../competition/competition.schema';
import { ModelDefinition } from './types';
import { AUCTION_CANCELLATION_CLEANUP_INDEX } from './auction-cancellation-index';
export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
export const POSITIONS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
@@ -700,6 +701,12 @@ export interface Match extends MongooseTimestamps {
teams: MatchTeam[];
result?: MatchResult;
resultPollState?: MatchResultPollState;
/** 마지막으로 취소된 Redis 경매 lifecycle. 취소 재전송을 멱등 처리한다. */
lastCancelledAuctionLifecycleId?: string;
auctionCancellationCleanupPending?: boolean;
auctionCancellationCleanupRetryAt?: Date;
auctionCancellationCleanupAttempts?: number;
auctionCancellationCleanupError?: string;
doubleElimination?: DoubleEliminationBracket;
legacyImported?: boolean;
legacyImportSource?: {
@@ -804,12 +811,41 @@ export interface AuctionBid {
}
export interface AuctionBidHistoryEntry {
bidRequestId?: string;
revision?: number;
bidRoundId?: string;
playerUserId?: mongoose.Types.ObjectId;
bidderTeamIndex: number;
bidPointAmount: number;
bidderUserId: mongoose.Types.ObjectId;
bidPlacedAtTimestampMS: number;
}
export interface AuctionBidRecord extends AuctionBidHistoryEntry {
_id: string;
matchId: mongoose.Types.ObjectId;
auctionLifecycleId: string;
revision: number;
bidRequestId: string;
}
export const AuctionBidRecordSchema = new Schema<AuctionBidRecord>(
{
_id: { type: String, required: true },
matchId: { type: Schema.Types.ObjectId, required: true },
auctionLifecycleId: { type: String, required: true },
revision: { type: Number, required: true },
bidRequestId: { type: String, required: true },
bidRoundId: { type: String },
playerUserId: { type: Schema.Types.ObjectId },
bidderUserId: { type: Schema.Types.ObjectId, required: true },
bidderTeamIndex: { type: Number, required: true },
bidPointAmount: { type: Number, required: true },
bidPlacedAtTimestampMS: { type: Number, required: true },
},
{ collection: 'auctionBidRecords', versionKey: false },
);
export interface AuctionChatMessage {
id: string;
userId?: mongoose.Types.ObjectId;
@@ -832,6 +868,8 @@ export interface Auction extends MongooseTimestamps {
matchSideEffectStatus: AuctionMatchSideEffectStatus;
matchSideEffectRevision: number;
matchSideEffectError?: string;
matchSideEffectTransitionId?: string;
startupCompleted?: boolean;
teams: AuctionTeam[];
order: AuctionPlayerSnapshot[];
passedQueue: AuctionPlayerSnapshot[];
@@ -858,6 +896,7 @@ export interface Auction extends MongooseTimestamps {
currentHighestBidPointAmount?: number;
currentHighestBidderTeamIndex?: number;
currentBidRoundDeadlineTimestampMS?: number;
currentBidRoundId?: string;
maximumBidRoundDurationSeconds?: number;
bidRoundExtensionSeconds?: number;
initialTeamBidPointAmount?: number;
@@ -1971,6 +2010,11 @@ export const MatchSchema = new Schema<Match>(
type: MatchResultPollStateSubSchema,
required: false,
},
lastCancelledAuctionLifecycleId: { type: String, required: false },
auctionCancellationCleanupPending: { type: Boolean },
auctionCancellationCleanupRetryAt: { type: Date },
auctionCancellationCleanupAttempts: { type: Number },
auctionCancellationCleanupError: { type: String },
doubleElimination: {
type: DoubleEliminationBracketSubSchema,
required: false,
@@ -1995,6 +2039,10 @@ export const MatchSchema = new Schema<Match>(
);
MatchSchema.index({ communityId: 1, scheduledAt: -1 });
MatchSchema.index(
AUCTION_CANCELLATION_CLEANUP_INDEX.key,
AUCTION_CANCELLATION_CLEANUP_INDEX.options,
);
applyCompetitionDomainInvariantIndexes(MatchSchema, 'match');
MatchSchema.index({ communityId: 1, status: 1, scheduledAt: -1 });
MatchSchema.index(
@@ -2174,6 +2222,8 @@ const AuctionBidSubSchema = new Schema<AuctionBid>(
const AuctionBidHistoryEntrySubSchema = new Schema<AuctionBidHistoryEntry>(
{
bidRoundId: { type: String },
playerUserId: { type: Schema.Types.ObjectId, ref: 'user' },
bidderTeamIndex: { type: Number, required: true, min: 1 },
bidPointAmount: { type: Number, required: true },
bidderUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
@@ -2195,6 +2245,9 @@ const AuctionChatMessageSubSchema = new Schema<AuctionChatMessage>(
export const AuctionSchema = new Schema<Auction>(
{
startupCompleted: { type: Boolean },
matchSideEffectTransitionId: { type: String },
currentBidRoundId: { type: String },
matchId: {
type: Schema.Types.ObjectId,
ref: 'match',
@@ -2520,6 +2573,11 @@ export const tournamentModelDefinitions: Array<
},
{ name: 'match', schema: MatchSchema, schemaName: 'match' },
{ name: 'auction', schema: AuctionSchema, schemaName: 'auction' },
{
name: 'auctionBidRecord',
schema: AuctionBidRecordSchema,
schemaName: 'auctionBidRecords',
},
{
name: 'auctionHistory',
schema: AuctionHistoryEntrySchema,
@@ -2553,6 +2611,7 @@ export interface TournamentModelTypes {
legacyImportJob: LegacyImportJob;
match: Match;
auction: Auction;
auctionBidRecord: AuctionBidRecord;
auctionHistory: AuctionHistoryEntry;
auctionSideEffectApplication: AuctionSideEffectApplication;
matchStats: MatchStats;