feat: support double-elimination series games

This commit is contained in:
dahyeon committed 2026-07-07 17:34:59 -07:00
1 parent 2ee8c3807b
commit e188828423
16 files changed
+1176 -234

No files matched your search

@@ -347,20 +347,22 @@ describe('migrateTournamentCodeUniqueIndexes', () => {
indexesDropped: 3,
matchesUpdated: 1,
});
expect(collections.tournamentCode.find((code) => code._id === 'code-2')).toMatchObject({
expect(
collections.tournamentCode.find((code) => code._id === 'code-2'),
).toMatchObject({
code: 'B',
releasedAt: now,
state: 'released',
});
expect(collections.tournamentCode.find((code) => code._id === 'code-2')).not.toHaveProperty(
'matchId',
);
expect(collections.tournamentCode.find((code) => code._id === 'code-4')).not.toHaveProperty(
'riotMatchId',
);
expect(collections.tournamentCode.find((code) => code._id === 'code-5')).not.toHaveProperty(
'riotMatchId',
);
expect(
collections.tournamentCode.find((code) => code._id === 'code-2'),
).not.toHaveProperty('matchId');
expect(
collections.tournamentCode.find((code) => code._id === 'code-4'),
).not.toHaveProperty('riotMatchId');
expect(
collections.tournamentCode.find((code) => code._id === 'code-5'),
).not.toHaveProperty('riotMatchId');
expect(collections.match[0].tournamentCodeIds).toEqual(['code-1']);
expect(indexes).toEqual(
expect.arrayContaining([
@@ -375,7 +377,9 @@ describe('migrateTournamentCodeUniqueIndexes', () => {
expect.objectContaining({
key: { matchId: 1, bracketMatchId: 1 },
name: 'matchId_1_bracketMatchId_1',
unique: true,
partialFilterExpression: expect.objectContaining({
state: { $in: ['reserved', 'used'] },
}),
}),
expect.objectContaining({
key: { riotMatchId: 1 },
@@ -421,7 +425,6 @@ describe('migrateTournamentCodeUniqueIndexes', () => {
expect.objectContaining({
key: { matchId: 1, bracketMatchId: 1 },
name: 'matchId_1_bracketMatchId_1',
unique: true,
}),
expect.objectContaining({
key: { riotMatchId: 1 },
@@ -501,6 +504,49 @@ describe('migrateTournamentCodeUniqueIndexes', () => {
expect(JSON.stringify(collections.match)).toBe(beforeMatches);
});
it('allows multiple active codes for the same double-elimination bracket match', async () => {
const { db, collections } = createDb({
codes: [
{
_id: 'code-1',
matchId: 'match-1',
gameNumber: 1,
bracketMatchId: 'WB_R1_M1',
state: 'reserved',
},
{
_id: 'code-2',
matchId: 'match-1',
gameNumber: 2,
bracketMatchId: 'WB_R1_M1',
state: 'reserved',
},
],
matches: [{ _id: 'match-1', tournamentCodeIds: ['code-1', 'code-2'] }],
});
const result = await migrateTournamentCodeUniqueIndexes(db, {
dryRun: false,
createIndexes: false,
});
expect(result.stats).toMatchObject({
duplicateBracketMatchGroups: 0,
duplicateCodesReleased: 0,
duplicateCodesToRelease: 0,
});
expect(collections.tournamentCode).toEqual(
expect.arrayContaining([
expect.objectContaining({ _id: 'code-1', state: 'reserved' }),
expect.objectContaining({ _id: 'code-2', state: 'reserved' }),
]),
);
expect(collections.match[0].tournamentCodeIds).toEqual([
'code-1',
'code-2',
]);
});
it('unsets blank riot match ids without treating them as duplicate releases', async () => {
const { db, collections } = createDb({
codes: [
@@ -151,7 +151,13 @@ export interface TournamentCodeUniqueIndexMigrationResult {
}
export interface TournamentCodeUniqueIndexMigrationProgress {
action?: 'alreadyCorrect' | 'create' | 'created' | 'drop' | 'dropped' | 'list';
action?:
| 'alreadyCorrect'
| 'create'
| 'created'
| 'drop'
| 'dropped'
| 'list';
phase:
| 'scanMatches'
| 'scanTournamentCodes'
@@ -205,7 +211,6 @@ const DESIRED_TOURNAMENT_CODE_INDEXES: DesiredIndex[] = [
key: { matchId: 1, bracketMatchId: 1 },
options: {
name: 'matchId_1_bracketMatchId_1',
unique: true,
partialFilterExpression: {
matchId: { $exists: true },
bracketMatchId: { $exists: true },
@@ -414,7 +419,6 @@ function findDuplicateGroups(
): DuplicateGroup[] {
return [
...duplicateGroupsFor(docs, referencedCodeIds, 'gameNumber'),
...duplicateGroupsFor(docs, referencedCodeIds, 'bracketMatchId'),
...duplicateGroupsFor(docs, referencedCodeIds, 'riotMatchId'),
];
}
@@ -514,7 +518,8 @@ function summarizeCode(doc: TournamentCodeDoc): TournamentCodeDuplicateSummary {
bracketMatchId:
doc.bracketMatchId === undefined ? undefined : String(doc.bracketMatchId),
code: doc.code === undefined ? undefined : String(doc.code),
gameNumber: doc.gameNumber === undefined ? undefined : String(doc.gameNumber),
gameNumber:
doc.gameNumber === undefined ? undefined : String(doc.gameNumber),
id: stringifyId(doc._id) ?? '',
matchId: doc.matchId === undefined ? undefined : stringifyId(doc.matchId),
riotMatchId:
@@ -576,7 +581,9 @@ function compareCodePriority(
const rightDate = latestTimestamp(right);
if (leftDate !== rightDate) return rightDate - leftDate;
return (stringifyId(left._id) ?? '').localeCompare(stringifyId(right._id) ?? '');
return (stringifyId(left._id) ?? '').localeCompare(
stringifyId(right._id) ?? '',
);
}
function stateRank(state: unknown): number {
@@ -715,8 +722,8 @@ function isNamespaceNotFoundError(error: unknown): boolean {
};
return Boolean(
candidate?.code === 26 ||
candidate?.codeName === 'NamespaceNotFound' ||
candidate?.message?.includes('ns does not exist'),
candidate?.codeName === 'NamespaceNotFound' ||
candidate?.message?.includes('ns does not exist'),
);
}
@@ -0,0 +1,335 @@
import 'reflect-metadata';
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import mongoose from 'mongoose';
import { readFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import {
buildDoubleEliminationGameSlots,
type DoubleEliminationBracketMatch,
} from '../../../double-elimination/double-elimination.util';
import { ConnectionService } from '../connection.service';
import type { MatchDocument, TournamentCodeDocument } from '../schema';
import { SecretModule } from '../../secret/secret.module';
interface CliOptions {
dryRun: boolean;
matchId?: mongoose.Types.ObjectId;
nodeEnv: string;
winnerGameCount: number;
}
interface CodeUpdatePlan {
codeId: mongoose.Types.ObjectId;
code: string;
bracketMatchId: string;
currentGameNumber: number | undefined;
nextGameNumber: number;
}
interface MatchRepairPlan {
codeUpdates: CodeUpdatePlan[];
currentGameCount: number;
matchId: mongoose.Types.ObjectId;
nextGameCount: number;
nextBracketMatches: DoubleEliminationBracketMatch[];
skippedReason?: string;
}
@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 RepairModule {}
async function loadMachineEnvFile() {
const homeDir = process.env.HOME ?? process.env.USERPROFILE;
if (!homeDir) return;
const machineEnvFile = resolve(homeDir, 'source/global-env-vars.txt');
try {
const file = await readFile(machineEnvFile, 'utf8');
for (const rawLine of file.split(/\r?\n/)) {
const line = rawLine.trim();
if (!line || line.startsWith('#')) continue;
const matched = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
if (!matched) continue;
const [, key, rawValue] = matched;
process.env[key] = rawValue.replace(/^["']|["']$/g, '');
}
} catch {
// Local machine env is optional for one-off migrations.
}
}
function parseArgs(argv: string[]): CliOptions {
let dryRun = true;
let matchId: mongoose.Types.ObjectId | undefined;
let nodeEnv = process.env.NODE_ENV ?? 'dev';
let winnerGameCount = 3;
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (arg === '--apply') {
dryRun = false;
continue;
}
if (arg === '--dry-run') {
dryRun = true;
continue;
}
if (arg === '--env') {
const value = argv[index + 1];
if (!value) throw new Error('--env requires dev, staging, or prod.');
nodeEnv = value;
index += 1;
continue;
}
if (arg.startsWith('--env=')) {
nodeEnv = arg.slice('--env='.length);
continue;
}
if (arg === '--match-id') {
matchId = parseObjectId(argv[index + 1], '--match-id');
index += 1;
continue;
}
if (arg.startsWith('--match-id=')) {
matchId = parseObjectId(arg.slice('--match-id='.length), '--match-id');
continue;
}
if (arg === '--winner-game-count') {
winnerGameCount = parseOddPositiveInteger(
argv[index + 1],
'--winner-game-count',
);
index += 1;
continue;
}
if (arg.startsWith('--winner-game-count=')) {
winnerGameCount = parseOddPositiveInteger(
arg.slice('--winner-game-count='.length),
'--winner-game-count',
);
continue;
}
if (arg === '--help' || arg === '-h') {
printHelp();
process.exit(0);
}
throw new Error(`Unknown argument: ${arg}`);
}
if (!['dev', 'staging', 'prod'].includes(nodeEnv)) {
throw new Error('--env must be dev, staging, or prod.');
}
return { dryRun, matchId, nodeEnv, winnerGameCount };
}
function parseObjectId(value: string | undefined, label: string) {
if (!value || !mongoose.isValidObjectId(value)) {
throw new Error(`${label} requires a valid ObjectId.`);
}
return new mongoose.Types.ObjectId(value);
}
function parseOddPositiveInteger(value: string | undefined, label: string) {
const parsed = Number(value);
if (!Number.isInteger(parsed) || parsed < 1 || parsed % 2 === 0) {
throw new Error(`${label} requires a positive odd integer.`);
}
return parsed;
}
function printHelp() {
console.log(`Usage:
pnpm --filter api exec ts-node src/modules/global/database/migrations/repair-double-elimination-series-rules.ts --match-id <id> --dry-run
pnpm --filter api exec ts-node src/modules/global/database/migrations/repair-double-elimination-series-rules.ts --match-id <id> --env prod --apply
Options:
--match-id <id> Optional match ObjectId. If omitted, scans all double-elimination matches.
--winner-game-count <n> Winner-bracket series size. Must be odd. Default: 3.
--dry-run Print the repair plan without writing. Default.
--apply Apply match and tournament code updates.
--env <env> dev | staging | prod. Default: NODE_ENV or dev.
`);
}
function requiredWinsFor(gameCount: number): number {
return Math.floor(gameCount / 2) + 1;
}
function buildRepairPlan(
match: MatchDocument,
codes: TournamentCodeDocument[],
winnerGameCount: number,
): MatchRepairPlan {
const currentGameCount = match.gameCount;
const resultGames = match.result?.games ?? [];
if (resultGames.length > 0) {
return {
codeUpdates: [],
currentGameCount,
matchId: match._id,
nextBracketMatches: [...(match.doubleElimination?.bracketMatches ?? [])],
nextGameCount: currentGameCount,
skippedReason: 'result-games-exist',
};
}
const nextBracketMatches = (
match.doubleElimination?.bracketMatches ?? []
).map((bracketMatch) => {
const gameCount =
bracketMatch.bracketSide === 'winner' ? winnerGameCount : 1;
return {
...bracketMatch,
gameCount,
requiredWins: requiredWinsFor(gameCount),
};
});
const firstSlotByBracketMatchId = new Map(
buildDoubleEliminationGameSlots(nextBracketMatches)
.filter((slot) => slot.seriesGameNumber === 1)
.map((slot) => [slot.bracketMatch.bracketMatchId, slot]),
);
const codeUpdates = codes
.filter((code) => code.bracketMatchId)
.map((code) => {
const slot = firstSlotByBracketMatchId.get(code.bracketMatchId!);
if (!slot) return null;
if (code.gameNumber === slot.gameNumber) return null;
return {
codeId: code._id,
code: code.code,
bracketMatchId: code.bracketMatchId!,
currentGameNumber: code.gameNumber,
nextGameNumber: slot.gameNumber,
} satisfies CodeUpdatePlan;
})
.filter((entry): entry is CodeUpdatePlan => Boolean(entry));
return {
codeUpdates,
currentGameCount,
matchId: match._id,
nextGameCount: Math.max(currentGameCount ?? 1, winnerGameCount),
nextBracketMatches,
};
}
function printPlan(plan: MatchRepairPlan) {
console.log(`match=${plan.matchId.toString()}`);
if (plan.skippedReason) {
console.log(` skipped=${plan.skippedReason}`);
return;
}
console.log(` gameCount: ${plan.currentGameCount} -> ${plan.nextGameCount}`);
console.log(
` bracketMatches=${plan.nextBracketMatches.length} codeUpdates=${plan.codeUpdates.length}`,
);
for (const update of plan.codeUpdates) {
console.log(
` code ${update.code} ${update.bracketMatchId}: ${update.currentGameNumber ?? 'unset'} -> ${update.nextGameNumber}`,
);
}
}
async function applyPlan(
match: MatchDocument,
plan: MatchRepairPlan,
TournamentCodeModel: mongoose.Model<any>,
session: mongoose.ClientSession,
) {
if (plan.skippedReason) return;
for (const update of plan.codeUpdates) {
await TournamentCodeModel.updateOne(
{ _id: update.codeId },
{ $set: { gameNumber: update.nextGameNumber } },
{ session },
).exec();
}
match.gameCount = plan.nextGameCount;
if (match.doubleElimination) {
match.doubleElimination.bracketMatches = plan.nextBracketMatches;
match.markModified('doubleElimination');
}
await match.save({ session });
}
async function main() {
const options = parseArgs(process.argv.slice(2));
process.env.NODE_ENV = options.nodeEnv;
await loadMachineEnvFile();
const app = await NestFactory.createApplicationContext(RepairModule, {
logger: ['log', 'warn', 'error'],
});
try {
const connectionService = app.get(ConnectionService);
const MatchModel = await connectionService.getModel('match');
const TournamentCodeModel =
await connectionService.getModel('tournamentCode');
const matches = await MatchModel.find({
gameMode: 'double-elimination',
...(options.matchId ? { _id: options.matchId } : {}),
}).exec();
const plans: Array<{ match: MatchDocument; plan: MatchRepairPlan }> = [];
for (const match of matches) {
const codes = await TournamentCodeModel.find({
_id: { $in: match.tournamentCodeIds ?? [] },
}).exec();
const plan = buildRepairPlan(match, codes, options.winnerGameCount);
plans.push({ match, plan });
printPlan(plan);
}
if (options.dryRun) {
console.log(
'No writes were made. Re-run with --apply to update MongoDB.',
);
return;
}
const session = await (
await connectionService.getConnection()
).startSession();
try {
await session.withTransaction(async () => {
for (const { match, plan } of plans) {
await applyPlan(match, plan, TournamentCodeModel, session);
}
});
} finally {
await session.endSession();
}
console.log(
`Applied ${plans.filter(({ plan }) => !plan.skippedReason).length} match repairs.`,
);
} finally {
await app.close();
}
}
if (require.main === module) {
main().catch((error) => {
console.error(error);
process.exit(1);
});
}
+31 -29
View File
@@ -598,6 +598,8 @@ export interface DoubleEliminationWalkover {
export interface DoubleEliminationBracketMatch {
bracketMatchId: string;
gameNumber: number;
gameCount: number;
requiredWins: number;
bracketSide: DoubleEliminationBracketSide;
roundNumber: number;
matchNumber: number;
@@ -1516,7 +1518,6 @@ TournamentCodeSchema.index(
TournamentCodeSchema.index(
{ matchId: 1, bracketMatchId: 1 },
{
unique: true,
partialFilterExpression: {
matchId: { $exists: true },
bracketMatchId: { $exists: true },
@@ -1679,6 +1680,8 @@ const DoubleEliminationBracketMatchSubSchema =
{
bracketMatchId: { type: String, required: true },
gameNumber: { type: Number, required: true, min: 1 },
gameCount: { type: Number, required: true, min: 1, default: 1 },
requiredWins: { type: Number, required: true, min: 1, default: 1 },
bracketSide: {
type: String,
enum: DOUBLE_ELIMINATION_BRACKET_SIDES,
@@ -1750,35 +1753,34 @@ const DoubleEliminationEventSubSchema = new Schema<DoubleEliminationEvent>(
{ _id: false },
);
const DoubleEliminationBracketSubSchema =
new Schema<DoubleEliminationBracket>(
{
teamCount: { type: Number, enum: [4, 8], required: true },
resetFinalEnabled: { type: Boolean, required: true, default: false },
resetFinalCreated: { type: Boolean, required: true, default: false },
seeds: {
type: [DoubleEliminationSeedSubSchema],
required: true,
default: [],
},
bracketMatches: {
type: [DoubleEliminationBracketMatchSubSchema],
required: true,
default: [],
},
placements: {
type: DoubleEliminationPlacementsSubSchema,
required: true,
default: () => ({}),
},
events: {
type: [DoubleEliminationEventSubSchema],
required: true,
default: [],
},
const DoubleEliminationBracketSubSchema = new Schema<DoubleEliminationBracket>(
{
teamCount: { type: Number, enum: [4, 8], required: true },
resetFinalEnabled: { type: Boolean, required: true, default: false },
resetFinalCreated: { type: Boolean, required: true, default: false },
seeds: {
type: [DoubleEliminationSeedSubSchema],
required: true,
default: [],
},
{ _id: false },
);
bracketMatches: {
type: [DoubleEliminationBracketMatchSubSchema],
required: true,
default: [],
},
placements: {
type: DoubleEliminationPlacementsSubSchema,
required: true,
default: () => ({}),
},
events: {
type: [DoubleEliminationEventSubSchema],
required: true,
default: [],
},
},
{ _id: false },
);
const MatchResultSubSchema = new Schema<MatchResult>(
{