feat: support double-elimination series games
This commit is contained in:
1 parent
2ee8c3807b
commit
e188828423
16 files changed
+1176
-234
No files matched your search
+335
@@ -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);
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user