diff --git a/apps/api/src/modules/global/database/migrations/repair-double-elimination-series-rules.spec.ts b/apps/api/src/modules/global/database/migrations/repair-double-elimination-series-rules.spec.ts new file mode 100644 index 00000000..c9111b13 --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/repair-double-elimination-series-rules.spec.ts @@ -0,0 +1,94 @@ +import mongoose from 'mongoose'; +import { buildRepairPlan } from './repair-double-elimination-series-rules'; +import type { MatchDocument, TournamentCodeDocument } from '../schema'; + +function createMatch(overrides: Partial): MatchDocument { + return { + _id: new mongoose.Types.ObjectId(), + gameCount: 3, + tournamentCodeIds: [], + doubleElimination: { + teamCount: 8, + resetFinalEnabled: false, + resetFinalCreated: false, + seeds: [], + bracketMatches: [], + placements: {}, + events: [], + }, + ...overrides, + } as unknown as MatchDocument; +} + +function createCode( + overrides: Partial, +): TournamentCodeDocument { + return { + _id: new mongoose.Types.ObjectId(), + code: 'CODE', + state: 'reserved', + ...overrides, + } as unknown as TournamentCodeDocument; +} + +describe('repair-double-elimination-series-rules buildRepairPlan', () => { + it('plans missing ready series slots even when result games already exist', () => { + const match = createMatch({ + result: { + riotMatchIds: ['KR_1'], + games: [ + { + gameNumber: 1, + bracketMatchId: 'WB_R2_M1', + }, + ], + seriesResults: [], + }, + doubleElimination: { + teamCount: 8, + resetFinalEnabled: false, + resetFinalCreated: false, + seeds: [], + bracketMatches: [ + { + bracketMatchId: 'WB_R2_M1', + gameNumber: 1, + gameCount: 3, + requiredWins: 2, + bracketSide: 'winner', + roundNumber: 2, + matchNumber: 1, + state: 'ready', + teamAIndex: 4, + teamBIndex: 6, + }, + ], + placements: {}, + events: [], + }, + }); + const existingFirstSetCode = createCode({ + bracketMatchId: 'WB_R2_M1', + gameNumber: 1, + }); + + const plan = buildRepairPlan(match, [existingFirstSetCode], 3); + + expect(plan.ruleRepairSkippedReason).toBe('result-games-exist'); + expect(plan.codeUpdates).toEqual([]); + expect(plan.missingReadySlots).toEqual([ + { + bracketMatchId: 'WB_R2_M1', + gameNumber: 2, + seriesGameNumber: 2, + seriesGameCount: 3, + }, + { + bracketMatchId: 'WB_R2_M1', + gameNumber: 3, + seriesGameNumber: 3, + seriesGameCount: 3, + }, + ]); + }); +}); diff --git a/apps/api/src/modules/global/database/migrations/repair-double-elimination-series-rules.ts b/apps/api/src/modules/global/database/migrations/repair-double-elimination-series-rules.ts index 47dad4e2..15f163b9 100644 --- a/apps/api/src/modules/global/database/migrations/repair-double-elimination-series-rules.ts +++ b/apps/api/src/modules/global/database/migrations/repair-double-elimination-series-rules.ts @@ -9,6 +9,7 @@ import { buildDoubleEliminationGameSlots, type DoubleEliminationBracketMatch, } from '../../../double-elimination/double-elimination.util'; +import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../../../tournament-code/tournament-code.constants'; import { ConnectionService } from '../connection.service'; import type { MatchDocument, TournamentCodeDocument } from '../schema'; import { SecretModule } from '../../secret/secret.module'; @@ -28,12 +29,21 @@ interface CodeUpdatePlan { nextGameNumber: number; } +interface MissingReadySlotPlan { + bracketMatchId: string; + gameNumber: number; + seriesGameNumber: number; + seriesGameCount: number; +} + interface MatchRepairPlan { codeUpdates: CodeUpdatePlan[]; currentGameCount: number; matchId: mongoose.Types.ObjectId; + missingReadySlots: MissingReadySlotPlan[]; nextGameCount: number; nextBracketMatches: DoubleEliminationBracketMatch[]; + ruleRepairSkippedReason?: string; skippedReason?: string; } @@ -173,27 +183,82 @@ function requiredWinsFor(gameCount: number): number { return Math.floor(gameCount / 2) + 1; } -function buildRepairPlan( +function codeSlotKey( + bracketMatchId: string | undefined, + gameNumber: number | undefined, +): string | undefined { + if (!bracketMatchId || typeof gameNumber !== 'number') return undefined; + return `${bracketMatchId}:${gameNumber}`; +} + +function buildActiveCodeSlotKeys( + codes: TournamentCodeDocument[], + codeUpdates: CodeUpdatePlan[] = [], +): Set { + const updateByCodeId = new Map( + codeUpdates.map((update) => [update.codeId.toString(), update]), + ); + const activeSlotKeys = new Set(); + + for (const code of codes) { + if (code.state !== 'reserved' && code.state !== 'used') continue; + const update = updateByCodeId.get(code._id.toString()); + const key = codeSlotKey( + update?.bracketMatchId ?? code.bracketMatchId, + update?.nextGameNumber ?? code.gameNumber, + ); + if (key) activeSlotKeys.add(key); + } + + return activeSlotKeys; +} + +function buildMissingReadySlots( + bracketMatches: DoubleEliminationBracketMatch[], + codes: TournamentCodeDocument[], + codeUpdates: CodeUpdatePlan[] = [], +): MissingReadySlotPlan[] { + const activeSlotKeys = buildActiveCodeSlotKeys(codes, codeUpdates); + + return buildDoubleEliminationGameSlots(bracketMatches) + .filter((slot) => slot.bracketMatch.state === 'ready') + .filter( + (slot) => + !activeSlotKeys.has( + `${slot.bracketMatch.bracketMatchId}:${slot.gameNumber}`, + ), + ) + .map((slot) => ({ + bracketMatchId: slot.bracketMatch.bracketMatchId, + gameNumber: slot.gameNumber, + seriesGameNumber: slot.seriesGameNumber, + seriesGameCount: slot.seriesGameCount, + })); +} + +export function buildRepairPlan( match: MatchDocument, codes: TournamentCodeDocument[], winnerGameCount: number, ): MatchRepairPlan { const currentGameCount = match.gameCount; const resultGames = match.result?.games ?? []; + const currentBracketMatches = [ + ...(match.doubleElimination?.bracketMatches ?? []), + ]; if (resultGames.length > 0) { return { codeUpdates: [], currentGameCount, matchId: match._id, - nextBracketMatches: [...(match.doubleElimination?.bracketMatches ?? [])], + missingReadySlots: buildMissingReadySlots(currentBracketMatches, codes), + nextBracketMatches: currentBracketMatches, nextGameCount: currentGameCount, - skippedReason: 'result-games-exist', + ruleRepairSkippedReason: 'result-games-exist', }; } - const nextBracketMatches = ( - match.doubleElimination?.bracketMatches ?? [] - ).map((bracketMatch) => { + const nextBracketMatches = currentBracketMatches.map((bracketMatch) => { const gameCount = bracketMatch.bracketSide === 'winner' ? winnerGameCount : 1; return { @@ -222,11 +287,17 @@ function buildRepairPlan( } satisfies CodeUpdatePlan; }) .filter((entry): entry is CodeUpdatePlan => Boolean(entry)); + const missingReadySlots = buildMissingReadySlots( + nextBracketMatches, + codes, + codeUpdates, + ); return { codeUpdates, currentGameCount, matchId: match._id, + missingReadySlots, nextGameCount: Math.max(currentGameCount ?? 1, winnerGameCount), nextBracketMatches, }; @@ -238,15 +309,26 @@ function printPlan(plan: MatchRepairPlan) { console.log(` skipped=${plan.skippedReason}`); return; } - console.log(` gameCount: ${plan.currentGameCount} -> ${plan.nextGameCount}`); + if (plan.ruleRepairSkippedReason) { + console.log(` ruleRepairSkipped=${plan.ruleRepairSkippedReason}`); + } else { + console.log( + ` gameCount: ${plan.currentGameCount} -> ${plan.nextGameCount}`, + ); + } console.log( - ` bracketMatches=${plan.nextBracketMatches.length} codeUpdates=${plan.codeUpdates.length}`, + ` bracketMatches=${plan.nextBracketMatches.length} codeUpdates=${plan.codeUpdates.length} missingReadySlots=${plan.missingReadySlots.length}`, ); for (const update of plan.codeUpdates) { console.log( ` code ${update.code} ${update.bracketMatchId}: ${update.currentGameNumber ?? 'unset'} -> ${update.nextGameNumber}`, ); } + for (const slot of plan.missingReadySlots) { + console.log( + ` missing ${slot.bracketMatchId}: game ${slot.gameNumber} (${slot.seriesGameNumber}/${slot.seriesGameCount})`, + ); + } } async function applyPlan( @@ -259,21 +341,74 @@ async function applyPlan( for (const update of plan.codeUpdates) { await TournamentCodeModel.updateOne( { _id: update.codeId }, - { $set: { gameNumber: update.nextGameNumber } }, + { + $set: { + gameNumber: update.nextGameNumber, + bracketMatchId: update.bracketMatchId, + }, + }, { session }, ).exec(); } - match.gameCount = plan.nextGameCount; - if (match.doubleElimination) { - match.doubleElimination.bracketMatches = plan.nextBracketMatches; - match.markModified('doubleElimination'); + const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS); + const reservedIds: mongoose.Types.ObjectId[] = []; + for (const slot of plan.missingReadySlots) { + const existingSlotCode = await TournamentCodeModel.exists({ + matchId: match._id, + gameNumber: slot.gameNumber, + bracketMatchId: slot.bracketMatchId, + state: { $in: ['reserved', 'used'] }, + }) + .session(session) + .exec(); + if (existingSlotCode) continue; + + const code = await TournamentCodeModel.findOneAndUpdate( + { + state: 'available', + region: 'kr', + mapType: 'SUMMONERS_RIFT', + teamSize: 5, + expiresAt: { $gt: expiresAfter }, + }, + { + $set: { + state: 'reserved', + matchId: match._id, + gameNumber: slot.gameNumber, + bracketMatchId: slot.bracketMatchId, + reservedAt: new Date(), + }, + $unset: { releasedAt: 1 }, + }, + { sort: { expiresAt: 1 }, returnDocument: 'after', session }, + ).exec(); + if (!code) break; + reservedIds.push(code._id); + } + + if (reservedIds.length > 0) { + match.tournamentCodeIds = match.tournamentCodeIds ?? []; + match.tournamentCodeIds.push(...reservedIds); + } + + if (!plan.ruleRepairSkippedReason) { + match.gameCount = plan.nextGameCount; + if (match.doubleElimination) { + match.doubleElimination.bracketMatches = plan.nextBracketMatches; + match.markModified('doubleElimination'); + } + } + + if (reservedIds.length > 0 || !plan.ruleRepairSkippedReason) { + await match.save({ session }); } - await match.save({ session }); } async function main() { const options = parseArgs(process.argv.slice(2)); process.env.NODE_ENV = options.nodeEnv; + process.env.SECRET_SOURCE = process.env.SECRET_SOURCE || 'infisical'; await loadMachineEnvFile(); const app = await NestFactory.createApplicationContext(RepairModule, {