From e1888284232a8fa757f2548929c12f120d3d41ad Mon Sep 17 00:00:00 2001 From: dahyeon Date: Tue, 7 Jul 2026 17:34:59 -0700 Subject: [PATCH] feat: support double-elimination series games --- .../double-elimination.util.spec.ts | 148 ++++++-- .../double-elimination.util.ts | 203 +++++++++-- ...627-tournament-code-unique-indexes.spec.ts | 70 +++- ...20260627-tournament-code-unique-indexes.ts | 21 +- .../repair-double-elimination-series-rules.ts | 335 ++++++++++++++++++ .../api/src/modules/global/database/schema.ts | 60 ++-- .../src/modules/match/match.service.spec.ts | 6 +- apps/api/src/modules/match/match.service.ts | 43 ++- .../tournament-code.service.spec.ts | 69 +++- .../tournament-code.service.ts | 110 +++--- .../tournament-code/tournament-code.types.ts | 3 + .../tournament-result.service.spec.ts | 119 ++++++- .../tournament-result.service.ts | 193 +++++++--- apps/web/src/api/types.ts | 5 + apps/web/src/pages/MatchDetailPage.tsx | 8 + apps/web/src/pages/admin/MatchAdminPage.tsx | 17 +- 16 files changed, 1176 insertions(+), 234 deletions(-) create mode 100644 apps/api/src/modules/global/database/migrations/repair-double-elimination-series-rules.ts diff --git a/apps/api/src/modules/double-elimination/double-elimination.util.spec.ts b/apps/api/src/modules/double-elimination/double-elimination.util.spec.ts index 7284e3cc..93214559 100644 --- a/apps/api/src/modules/double-elimination/double-elimination.util.spec.ts +++ b/apps/api/src/modules/double-elimination/double-elimination.util.spec.ts @@ -1,7 +1,9 @@ import { + buildDoubleEliminationGameSlots, buildDoubleEliminationBracket, cancelDoubleEliminationBracketMatch, completeDoubleEliminationBracketMatch, + resolveDoubleEliminationSeriesWinner, reshuffleDoubleEliminationSeeds, swapDoubleEliminationSeeds, } from './double-elimination.util'; @@ -15,14 +17,111 @@ describe('double-elimination util', () => { expect(bracket.bracketMatches.map((match) => match.bracketMatchId)).toEqual( ['WB_R1_M1', 'WB_R1_M2', 'WB_FINAL', 'LB_R1_M1', 'LB_FINAL', 'GF'], ); - expect(bracket.bracketMatches.find((match) => match.bracketMatchId === 'WB_R1_M1')) - .toMatchObject({ - teamAIndex: 1, - teamBIndex: 4, - winnerAdvancesTo: { bracketMatchId: 'WB_FINAL', position: 'A' }, - loserAdvancesTo: { bracketMatchId: 'LB_R1_M1', position: 'A' }, - state: 'ready', - }); + expect( + bracket.bracketMatches.find( + (match) => match.bracketMatchId === 'WB_R1_M1', + ), + ).toMatchObject({ + teamAIndex: 1, + teamBIndex: 4, + winnerAdvancesTo: { bracketMatchId: 'WB_FINAL', position: 'A' }, + loserAdvancesTo: { bracketMatchId: 'LB_R1_M1', position: 'A' }, + state: 'ready', + }); + }); + + it('assigns extensible series rules to winner-bracket matches', () => { + const bracket = buildDoubleEliminationBracket([1, 2, 3, 4], { + resetFinalEnabled: true, + winnerBracketGameCount: 5, + }); + + expect( + bracket.bracketMatches + .filter((match) => match.bracketSide === 'winner') + .map((match) => ({ + bracketMatchId: match.bracketMatchId, + gameCount: match.gameCount, + requiredWins: match.requiredWins, + })), + ).toEqual([ + { bracketMatchId: 'WB_R1_M1', gameCount: 5, requiredWins: 3 }, + { bracketMatchId: 'WB_R1_M2', gameCount: 5, requiredWins: 3 }, + { bracketMatchId: 'WB_FINAL', gameCount: 5, requiredWins: 3 }, + ]); + expect( + bracket.bracketMatches.find( + (match) => match.bracketMatchId === 'LB_R1_M1', + ), + ).toMatchObject({ gameCount: 1, requiredWins: 1 }); + expect( + bracket.bracketMatches.find((match) => match.bracketMatchId === 'GF'), + ).toMatchObject({ gameCount: 1, requiredWins: 1 }); + }); + + it('expands bracket match series into game slots', () => { + const bracket = buildDoubleEliminationBracket([1, 2, 3, 4], { + resetFinalEnabled: true, + }); + + expect( + buildDoubleEliminationGameSlots(bracket.bracketMatches).slice(0, 7), + ).toEqual([ + expect.objectContaining({ + gameNumber: 1, + seriesGameNumber: 1, + bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M1' }), + }), + expect.objectContaining({ + gameNumber: 2, + seriesGameNumber: 2, + bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M1' }), + }), + expect.objectContaining({ + gameNumber: 3, + seriesGameNumber: 3, + bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M1' }), + }), + expect.objectContaining({ + gameNumber: 4, + seriesGameNumber: 1, + bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M2' }), + }), + expect.objectContaining({ + gameNumber: 5, + seriesGameNumber: 2, + bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M2' }), + }), + expect.objectContaining({ + gameNumber: 6, + seriesGameNumber: 3, + bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M2' }), + }), + expect.objectContaining({ + gameNumber: 7, + seriesGameNumber: 1, + bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_FINAL' }), + }), + ]); + }); + + it('requires the configured number of wins before resolving a series winner', () => { + const bracketMatch = buildDoubleEliminationBracket([1, 2, 3, 4], { + resetFinalEnabled: true, + }).bracketMatches.find((match) => match.bracketMatchId === 'WB_R1_M1'); + + expect( + resolveDoubleEliminationSeriesWinner( + { teamAIndex: 1, teamBIndex: 4, teamAWins: 1, teamBWins: 0 }, + bracketMatch!, + ), + ).toBeUndefined(); + expect( + resolveDoubleEliminationSeriesWinner( + { teamAIndex: 1, teamBIndex: 4, teamAWins: 2, teamBWins: 1 }, + bracketMatch!, + ), + ).toBe(1); }); it('moves winners and losers through a 4-team bracket and records top 3', () => { @@ -43,10 +142,16 @@ describe('double-elimination util', () => { completedAt: new Date('2026-06-01T10:30:00.000Z'), }); - expect(bracket.bracketMatches.find((match) => match.bracketMatchId === 'WB_FINAL')) - .toMatchObject({ teamAIndex: 1, teamBIndex: 2, state: 'ready' }); - expect(bracket.bracketMatches.find((match) => match.bracketMatchId === 'LB_R1_M1')) - .toMatchObject({ teamAIndex: 4, teamBIndex: 3, state: 'ready' }); + expect( + bracket.bracketMatches.find( + (match) => match.bracketMatchId === 'WB_FINAL', + ), + ).toMatchObject({ teamAIndex: 1, teamBIndex: 2, state: 'ready' }); + expect( + bracket.bracketMatches.find( + (match) => match.bracketMatchId === 'LB_R1_M1', + ), + ).toMatchObject({ teamAIndex: 4, teamBIndex: 3, state: 'ready' }); bracket = completeDoubleEliminationBracketMatch(bracket, { bracketMatchId: 'WB_FINAL', @@ -97,14 +202,17 @@ describe('double-elimination util', () => { expect(bracket.resetFinalCreated).toBe(true); expect(bracket.placements).toEqual({ thirdTeamIndex: 3 }); - expect(bracket.bracketMatches.find((match) => match.bracketMatchId === 'GF_RESET')) - .toMatchObject({ - gameNumber: 7, - bracketSide: 'reset-final', - teamAIndex: 1, - teamBIndex: 2, - state: 'ready', - }); + expect( + bracket.bracketMatches.find( + (match) => match.bracketMatchId === 'GF_RESET', + ), + ).toMatchObject({ + gameNumber: 7, + bracketSide: 'reset-final', + teamAIndex: 1, + teamBIndex: 2, + state: 'ready', + }); }); it('rejects completion cancellation when downstream matches are already completed', () => { diff --git a/apps/api/src/modules/double-elimination/double-elimination.util.ts b/apps/api/src/modules/double-elimination/double-elimination.util.ts index 60c0f811..08f3373d 100644 --- a/apps/api/src/modules/double-elimination/double-elimination.util.ts +++ b/apps/api/src/modules/double-elimination/double-elimination.util.ts @@ -43,6 +43,8 @@ export interface DoubleEliminationWalkover { export interface DoubleEliminationBracketMatch { bracketMatchId: string; gameNumber: number; + gameCount: number; + requiredWins: number; bracketSide: DoubleEliminationBracketSide; roundNumber: number; matchNumber: number; @@ -95,6 +97,27 @@ export interface DoubleEliminationBracket { export interface BuildDoubleEliminationBracketOptions { resetFinalEnabled: boolean; + winnerBracketGameCount?: number; +} + +export interface DoubleEliminationSeriesRule { + gameCount: number; + requiredWins: number; +} + +export interface DoubleEliminationGameSlot { + gameNumber: number; + seriesGameNumber: number; + seriesGameCount: number; + seriesRequiredWins: number; + bracketMatch: DoubleEliminationBracketMatch; +} + +export interface DoubleEliminationSeriesScore { + teamAIndex: number; + teamBIndex: number; + teamAWins: number; + teamBWins: number; } export interface CompleteDoubleEliminationBracketMatchParams { @@ -127,8 +150,8 @@ export function buildDoubleEliminationBracket( seeds, bracketMatches: seededTeamIndexes.length === 4 - ? buildFourTeamBracketMatches() - : buildEightTeamBracketMatches(), + ? buildFourTeamBracketMatches(options) + : buildEightTeamBracketMatches(options), placements: {}, events: [ { @@ -142,6 +165,73 @@ export function buildDoubleEliminationBracket( return bracket; } +export function resolveDoubleEliminationSeriesRule( + params: { + bracketSide: DoubleEliminationBracketSide; + bracketMatchId: string; + roundNumber: number; + }, + options: { winnerBracketGameCount?: number } = {}, +): DoubleEliminationSeriesRule { + if (params.bracketSide === 'winner') { + return seriesRule(options.winnerBracketGameCount ?? 3); + } + return seriesRule(1); +} + +export function buildDoubleEliminationGameSlots( + bracketMatches: DoubleEliminationBracketMatch[], +): DoubleEliminationGameSlot[] { + const slots: DoubleEliminationGameSlot[] = []; + let gameNumber = 1; + for (const bracketMatch of bracketMatches) { + const seriesGameCount = normalizeSeriesGameCount(bracketMatch.gameCount); + const seriesRequiredWins = + bracketMatch.requiredWins ?? requiredWinsForGameCount(seriesGameCount); + for ( + let seriesGameNumber = 1; + seriesGameNumber <= seriesGameCount; + seriesGameNumber += 1 + ) { + slots.push({ + gameNumber, + seriesGameNumber, + seriesGameCount, + seriesRequiredWins, + bracketMatch, + }); + gameNumber += 1; + } + } + return slots; +} + +export function resolveDoubleEliminationSeriesWinner( + series: DoubleEliminationSeriesScore | undefined, + bracketMatch: Pick< + DoubleEliminationBracketMatch, + 'requiredWins' | 'teamAIndex' | 'teamBIndex' + >, +): number | undefined { + if (!series) return undefined; + const requiredWins = bracketMatch.requiredWins ?? 1; + if ( + bracketMatch.teamAIndex && + series.teamAWins >= requiredWins && + series.teamAWins > series.teamBWins + ) { + return bracketMatch.teamAIndex; + } + if ( + bracketMatch.teamBIndex && + series.teamBWins >= requiredWins && + series.teamBWins > series.teamAWins + ) { + return bracketMatch.teamBIndex; + } + return undefined; +} + export function reshuffleDoubleEliminationSeeds( bracket: DoubleEliminationBracket, rng: () => number = Math.random, @@ -245,10 +335,13 @@ export function cancelDoubleEliminationBracketMatch( bracketMatch.bracketMatchId, ); const completedDescendant = next.bracketMatches.find( - (match) => descendants.has(match.bracketMatchId) && match.state === 'completed', + (match) => + descendants.has(match.bracketMatchId) && match.state === 'completed', ); if (completedDescendant) { - throw new Error('Cannot cancel because a downstream bracket match is completed.'); + throw new Error( + 'Cannot cancel because a downstream bracket match is completed.', + ); } if (bracketMatch.bracketMatchId === 'GF') { @@ -263,10 +356,20 @@ export function cancelDoubleEliminationBracketMatch( (match) => match.bracketMatchId === descendantId, ); if (!descendant) continue; - if (referencesBracketMatch(descendant.teamASource, bracketMatch.bracketMatchId)) { + if ( + referencesBracketMatch( + descendant.teamASource, + bracketMatch.bracketMatchId, + ) + ) { descendant.teamAIndex = undefined; } - if (referencesBracketMatch(descendant.teamBSource, bracketMatch.bracketMatchId)) { + if ( + referencesBracketMatch( + descendant.teamBSource, + bracketMatch.bracketMatchId, + ) + ) { descendant.teamBIndex = undefined; } descendant.winnerTeamIndex = undefined; @@ -351,9 +454,12 @@ function completeGrandFinal( grandFinal.winnerTeamIndex !== winnerBracketTeamIndex ) { bracket.resetFinalCreated = true; + const resetRule = seriesRule(1); bracket.bracketMatches.push({ bracketMatchId: 'GF_RESET', gameNumber: nextGameNumber(bracket), + gameCount: resetRule.gameCount, + requiredWins: resetRule.requiredWins, bracketSide: 'reset-final', roundNumber: 1, matchNumber: 1, @@ -418,118 +524,122 @@ function applySeedTeams(bracket: DoubleEliminationBracket): void { } } -function buildFourTeamBracketMatches(): DoubleEliminationBracketMatch[] { +function buildFourTeamBracketMatches( + options: BuildDoubleEliminationBracketOptions, +): DoubleEliminationBracketMatch[] { return [ - bracketMatch('WB_R1_M1', 1, 'winner', 1, 1, { + bracketMatch('WB_R1_M1', 1, 'winner', 1, 1, options, { teamASource: seedSource(1), teamBSource: seedSource(4), winnerAdvancesTo: destination('WB_FINAL', 'A'), loserAdvancesTo: destination('LB_R1_M1', 'A'), }), - bracketMatch('WB_R1_M2', 2, 'winner', 1, 2, { + bracketMatch('WB_R1_M2', 2, 'winner', 1, 2, options, { teamASource: seedSource(2), teamBSource: seedSource(3), winnerAdvancesTo: destination('WB_FINAL', 'B'), loserAdvancesTo: destination('LB_R1_M1', 'B'), }), - bracketMatch('WB_FINAL', 3, 'winner', 2, 1, { + bracketMatch('WB_FINAL', 3, 'winner', 2, 1, options, { teamASource: winnerSource('WB_R1_M1'), teamBSource: winnerSource('WB_R1_M2'), winnerAdvancesTo: destination('GF', 'A'), loserAdvancesTo: destination('LB_FINAL', 'B'), }), - bracketMatch('LB_R1_M1', 4, 'loser', 1, 1, { + bracketMatch('LB_R1_M1', 4, 'loser', 1, 1, options, { teamASource: loserSource('WB_R1_M1'), teamBSource: loserSource('WB_R1_M2'), winnerAdvancesTo: destination('LB_FINAL', 'A'), }), - bracketMatch('LB_FINAL', 5, 'loser', 2, 1, { + bracketMatch('LB_FINAL', 5, 'loser', 2, 1, options, { teamASource: winnerSource('LB_R1_M1'), teamBSource: loserSource('WB_FINAL'), winnerAdvancesTo: destination('GF', 'B'), }), - bracketMatch('GF', 6, 'grand-final', 1, 1, { + bracketMatch('GF', 6, 'grand-final', 1, 1, options, { teamASource: winnerSource('WB_FINAL'), teamBSource: winnerSource('LB_FINAL'), }), ]; } -function buildEightTeamBracketMatches(): DoubleEliminationBracketMatch[] { +function buildEightTeamBracketMatches( + options: BuildDoubleEliminationBracketOptions, +): DoubleEliminationBracketMatch[] { return [ - bracketMatch('WB_R1_M1', 1, 'winner', 1, 1, { + bracketMatch('WB_R1_M1', 1, 'winner', 1, 1, options, { teamASource: seedSource(1), teamBSource: seedSource(8), winnerAdvancesTo: destination('WB_R2_M1', 'A'), loserAdvancesTo: destination('LB_R1_M1', 'A'), }), - bracketMatch('WB_R1_M2', 2, 'winner', 1, 2, { + bracketMatch('WB_R1_M2', 2, 'winner', 1, 2, options, { teamASource: seedSource(4), teamBSource: seedSource(5), winnerAdvancesTo: destination('WB_R2_M1', 'B'), loserAdvancesTo: destination('LB_R1_M1', 'B'), }), - bracketMatch('WB_R1_M3', 3, 'winner', 1, 3, { + bracketMatch('WB_R1_M3', 3, 'winner', 1, 3, options, { teamASource: seedSource(2), teamBSource: seedSource(7), winnerAdvancesTo: destination('WB_R2_M2', 'A'), loserAdvancesTo: destination('LB_R1_M2', 'A'), }), - bracketMatch('WB_R1_M4', 4, 'winner', 1, 4, { + bracketMatch('WB_R1_M4', 4, 'winner', 1, 4, options, { teamASource: seedSource(3), teamBSource: seedSource(6), winnerAdvancesTo: destination('WB_R2_M2', 'B'), loserAdvancesTo: destination('LB_R1_M2', 'B'), }), - bracketMatch('WB_R2_M1', 5, 'winner', 2, 1, { + bracketMatch('WB_R2_M1', 5, 'winner', 2, 1, options, { teamASource: winnerSource('WB_R1_M1'), teamBSource: winnerSource('WB_R1_M2'), winnerAdvancesTo: destination('WB_FINAL', 'A'), loserAdvancesTo: destination('LB_R2_M2', 'B'), }), - bracketMatch('WB_R2_M2', 6, 'winner', 2, 2, { + bracketMatch('WB_R2_M2', 6, 'winner', 2, 2, options, { teamASource: winnerSource('WB_R1_M3'), teamBSource: winnerSource('WB_R1_M4'), winnerAdvancesTo: destination('WB_FINAL', 'B'), loserAdvancesTo: destination('LB_R2_M1', 'B'), }), - bracketMatch('WB_FINAL', 7, 'winner', 3, 1, { + bracketMatch('WB_FINAL', 7, 'winner', 3, 1, options, { teamASource: winnerSource('WB_R2_M1'), teamBSource: winnerSource('WB_R2_M2'), winnerAdvancesTo: destination('GF', 'A'), loserAdvancesTo: destination('LB_FINAL', 'B'), }), - bracketMatch('LB_R1_M1', 8, 'loser', 1, 1, { + bracketMatch('LB_R1_M1', 8, 'loser', 1, 1, options, { teamASource: loserSource('WB_R1_M1'), teamBSource: loserSource('WB_R1_M2'), winnerAdvancesTo: destination('LB_R2_M1', 'A'), }), - bracketMatch('LB_R1_M2', 9, 'loser', 1, 2, { + bracketMatch('LB_R1_M2', 9, 'loser', 1, 2, options, { teamASource: loserSource('WB_R1_M3'), teamBSource: loserSource('WB_R1_M4'), winnerAdvancesTo: destination('LB_R2_M2', 'A'), }), - bracketMatch('LB_R2_M1', 10, 'loser', 2, 1, { + bracketMatch('LB_R2_M1', 10, 'loser', 2, 1, options, { teamASource: winnerSource('LB_R1_M1'), teamBSource: loserSource('WB_R2_M2'), winnerAdvancesTo: destination('LB_R3_M1', 'A'), }), - bracketMatch('LB_R2_M2', 11, 'loser', 2, 2, { + bracketMatch('LB_R2_M2', 11, 'loser', 2, 2, options, { teamASource: winnerSource('LB_R1_M2'), teamBSource: loserSource('WB_R2_M1'), winnerAdvancesTo: destination('LB_R3_M1', 'B'), }), - bracketMatch('LB_R3_M1', 12, 'loser', 3, 1, { + bracketMatch('LB_R3_M1', 12, 'loser', 3, 1, options, { teamASource: winnerSource('LB_R2_M1'), teamBSource: winnerSource('LB_R2_M2'), winnerAdvancesTo: destination('LB_FINAL', 'A'), }), - bracketMatch('LB_FINAL', 13, 'loser', 4, 1, { + bracketMatch('LB_FINAL', 13, 'loser', 4, 1, options, { teamASource: winnerSource('LB_R3_M1'), teamBSource: loserSource('WB_FINAL'), winnerAdvancesTo: destination('GF', 'B'), }), - bracketMatch('GF', 14, 'grand-final', 1, 1, { + bracketMatch('GF', 14, 'grand-final', 1, 1, options, { teamASource: winnerSource('WB_FINAL'), teamBSource: winnerSource('LB_FINAL'), }), @@ -542,11 +652,18 @@ function bracketMatch( bracketSide: DoubleEliminationBracketSide, roundNumber: number, matchNumber: number, + options: BuildDoubleEliminationBracketOptions, params: Partial, ): DoubleEliminationBracketMatch { + const rule = resolveDoubleEliminationSeriesRule( + { bracketMatchId, bracketSide, roundNumber }, + options, + ); return { bracketMatchId, gameNumber, + gameCount: params.gameCount ?? rule.gameCount, + requiredWins: params.requiredWins ?? rule.requiredWins, bracketSide, roundNumber, matchNumber, @@ -627,14 +744,35 @@ function assertSeedChangeAllowed(bracket: DoubleEliminationBracket): void { } } -function assertSupportedTeamCount(teamCount: number): asserts teamCount is 4 | 8 { +function assertSupportedTeamCount( + teamCount: number, +): asserts teamCount is 4 | 8 { if (teamCount !== 4 && teamCount !== 8) { throw new Error('Double elimination supports only 4 or 8 teams.'); } } function nextGameNumber(bracket: DoubleEliminationBracket): number { - return Math.max(...bracket.bracketMatches.map((match) => match.gameNumber)) + 1; + return ( + Math.max(...bracket.bracketMatches.map((match) => match.gameNumber)) + 1 + ); +} + +function seriesRule(gameCount: number): DoubleEliminationSeriesRule { + const normalizedGameCount = normalizeSeriesGameCount(gameCount); + return { + gameCount: normalizedGameCount, + requiredWins: requiredWinsForGameCount(normalizedGameCount), + }; +} + +function normalizeSeriesGameCount(gameCount: number | undefined): number { + if (!Number.isInteger(gameCount) || !gameCount || gameCount < 1) return 1; + return gameCount % 2 === 0 ? gameCount + 1 : gameCount; +} + +function requiredWinsForGameCount(gameCount: number): number { + return Math.floor(gameCount / 2) + 1; } function cloneBracket( @@ -660,10 +798,7 @@ function cloneBracket( }; } -function shuffleInPlace( - items: T[], - rng: () => number = Math.random, -): T[] { +function shuffleInPlace(items: T[], rng: () => number = Math.random): T[] { for (let index = items.length - 1; index > 0; index -= 1) { const swapIndex = Math.floor(rng() * (index + 1)); [items[index], items[swapIndex]] = [items[swapIndex], items[index]]; diff --git a/apps/api/src/modules/global/database/migrations/20260627-tournament-code-unique-indexes.spec.ts b/apps/api/src/modules/global/database/migrations/20260627-tournament-code-unique-indexes.spec.ts index 4d2ba885..19473cd7 100644 --- a/apps/api/src/modules/global/database/migrations/20260627-tournament-code-unique-indexes.spec.ts +++ b/apps/api/src/modules/global/database/migrations/20260627-tournament-code-unique-indexes.spec.ts @@ -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: [ diff --git a/apps/api/src/modules/global/database/migrations/20260627-tournament-code-unique-indexes.ts b/apps/api/src/modules/global/database/migrations/20260627-tournament-code-unique-indexes.ts index ecb37865..b8e457af 100644 --- a/apps/api/src/modules/global/database/migrations/20260627-tournament-code-unique-indexes.ts +++ b/apps/api/src/modules/global/database/migrations/20260627-tournament-code-unique-indexes.ts @@ -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'), ); } 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 new file mode 100644 index 00000000..47dad4e2 --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/repair-double-elimination-series-rules.ts @@ -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 --dry-run + pnpm --filter api exec ts-node src/modules/global/database/migrations/repair-double-elimination-series-rules.ts --match-id --env prod --apply + +Options: + --match-id Optional match ObjectId. If omitted, scans all double-elimination matches. + --winner-game-count 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 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, + 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); + }); +} diff --git a/apps/api/src/modules/global/database/schema.ts b/apps/api/src/modules/global/database/schema.ts index c14485ab..2a6169ba 100644 --- a/apps/api/src/modules/global/database/schema.ts +++ b/apps/api/src/modules/global/database/schema.ts @@ -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( { _id: false }, ); -const DoubleEliminationBracketSubSchema = - new Schema( - { - 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( + { + 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( { diff --git a/apps/api/src/modules/match/match.service.spec.ts b/apps/api/src/modules/match/match.service.spec.ts index 6d67d28d..41110da0 100644 --- a/apps/api/src/modules/match/match.service.spec.ts +++ b/apps/api/src/modules/match/match.service.spec.ts @@ -491,7 +491,7 @@ describe('MatchService', () => { expect(createdPayloads[0]).toMatchObject({ communityId, maxParticipants: 20, - gameCount: 1, + gameCount: 5, gameMode: 'double-elimination', roundRobinMaxRounds: undefined, doubleElimination: { @@ -519,7 +519,9 @@ describe('MatchService', () => { gameMode: 'double-elimination', }, }), - ).rejects.toThrow('Double elimination supports only 20 or 40 participants.'); + ).rejects.toThrow( + 'Double elimination supports only 20 or 40 participants.', + ); expect(MatchModel.create).not.toHaveBeenCalled(); }); diff --git a/apps/api/src/modules/match/match.service.ts b/apps/api/src/modules/match/match.service.ts index d139c641..b9e13f13 100644 --- a/apps/api/src/modules/match/match.service.ts +++ b/apps/api/src/modules/match/match.service.ts @@ -34,6 +34,7 @@ const MATCH_SHORT_CODE_GENERATION_ATTEMPTS = 20; const DEFAULT_MATCH_LIST_LIMIT = 50; const MAX_MATCH_LIST_LIMIT = 200; const DOUBLE_ELIMINATION_PARTICIPANT_COUNTS = [20, 40] as const; +const DEFAULT_DOUBLE_ELIMINATION_SERIES_GAME_COUNT = 3; interface DoubleEliminationConfigInput { doubleEliminationResetFinalEnabled?: boolean; @@ -109,21 +110,18 @@ interface DoubleEliminationAdminParams { actorUserId: mongoose.Types.ObjectId; } -interface SwapDoubleEliminationSeedsParams - extends DoubleEliminationAdminParams { +interface SwapDoubleEliminationSeedsParams extends DoubleEliminationAdminParams { leftSeedNumber: number; rightSeedNumber: number; } -interface ApplyDoubleEliminationWalkoverParams - extends DoubleEliminationAdminParams { +interface ApplyDoubleEliminationWalkoverParams extends DoubleEliminationAdminParams { bracketMatchId: string; winnerTeamIndex: number; reason?: string; } -interface CancelDoubleEliminationActionParams - extends DoubleEliminationAdminParams { +interface CancelDoubleEliminationActionParams extends DoubleEliminationAdminParams { bracketMatchId: string; reason?: string; } @@ -529,9 +527,9 @@ export class MatchService { return await this.throwJoinFailure(MatchModel, params.matchId, user); } - private normalizeMatchConfig & DoubleEliminationConfigInput>( - input: T, - ): Partial { + private normalizeMatchConfig< + T extends Partial & DoubleEliminationConfigInput, + >(input: T): Partial { const patch = this.stripMatchConfigInput(input); const gameMode = (patch.gameMode ?? 'pair') as MatchGameMode; const maxParticipants = patch.maxParticipants ?? 10; @@ -550,7 +548,9 @@ export class MatchService { ...patch, gameMode, maxParticipants, - gameCount: 1, + gameCount: this.normalizeDoubleEliminationSeriesGameCount( + patch.gameCount ?? DEFAULT_DOUBLE_ELIMINATION_SERIES_GAME_COUNT, + ), roundRobinMaxRounds: undefined, gameSchedule: [], doubleElimination: { @@ -575,13 +575,20 @@ export class MatchService { }; } - private stripMatchConfigInput & DoubleEliminationConfigInput>( - input: T, - ): Partial { + private stripMatchConfigInput< + T extends Partial & DoubleEliminationConfigInput, + >(input: T): Partial { const { doubleEliminationResetFinalEnabled: _ignored, ...patch } = input; return patch; } + private normalizeDoubleEliminationSeriesGameCount(gameCount: number): number { + if (!Number.isInteger(gameCount) || gameCount < 1) { + return DEFAULT_DOUBLE_ELIMINATION_SERIES_GAME_COUNT; + } + return gameCount % 2 === 0 ? gameCount + 1 : gameCount; + } + private async loadDoubleEliminationMatch(params: { matchId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; @@ -836,7 +843,10 @@ export class MatchService { private async throwJoinFailure( MatchModel: mongoose.Model, matchId: mongoose.Types.ObjectId, - user: { _id: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId }, + user: { + _id: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + }, ): Promise { const match = await MatchModel.findById(matchId); if (!match) throw new NotFoundException('Match not found.'); @@ -864,7 +874,10 @@ export class MatchService { private async throwCancelJoinFailure( MatchModel: mongoose.Model, matchId: mongoose.Types.ObjectId, - user: { _id: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId }, + user: { + _id: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + }, ): Promise { const match = await MatchModel.findById(matchId); if (!match) throw new NotFoundException('Match not found.'); diff --git a/apps/api/src/modules/tournament-code/tournament-code.service.spec.ts b/apps/api/src/modules/tournament-code/tournament-code.service.spec.ts index d7560052..c0ed7fd0 100644 --- a/apps/api/src/modules/tournament-code/tournament-code.service.spec.ts +++ b/apps/api/src/modules/tournament-code/tournament-code.service.spec.ts @@ -4,6 +4,7 @@ import { } from '../global/database/schema'; import mongoose from 'mongoose'; import { TournamentCodeService } from './tournament-code.service'; +import { buildDoubleEliminationBracket } from '../double-elimination/double-elimination.util'; type TournamentCodeServiceInternals = TournamentCodeService & { resolveRequiredSlots(match: MatchDocument): number; @@ -229,6 +230,7 @@ describe('TournamentCodeService round-robin scheduling', () => { const service = createService(); const match = createMatch({ gameMode: 'double-elimination', + gameCount: 3, teams: Array.from({ length: 4 }, (_, index) => ({ teamIndex: index + 1, })), @@ -252,6 +254,70 @@ describe('TournamentCodeService round-robin scheduling', () => { (bracketMatch) => bracketMatch.state === 'ready', ), ).toHaveLength(2); + expect( + match.doubleElimination?.bracketMatches.find( + (bracketMatch) => bracketMatch.bracketMatchId === 'WB_R1_M1', + ), + ).toMatchObject({ gameCount: 3, requiredWins: 2 }); + }); + + it('expands double-elimination winner bracket series into code slots', async () => { + const TournamentCodeModel = { + find: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue([]), + }), + }; + const service = new TournamentCodeService( + { getModel: jest.fn().mockResolvedValue(TournamentCodeModel) } as never, + createAuctionRedisService() as never, + ) as unknown as TournamentCodeServiceInternals; + const match = createMatch({ + gameMode: 'double-elimination', + gameCount: 3, + teams: Array.from({ length: 4 }, (_, index) => ({ + teamIndex: index + 1, + })), + doubleElimination: buildDoubleEliminationBracket([1, 2, 3, 4], { + resetFinalEnabled: true, + }), + }); + + const slots = await service.buildSlots(match); + + expect(slots.slice(0, 6)).toEqual([ + expect.objectContaining({ + gameNumber: 1, + seriesGameNumber: 1, + seriesGameCount: 3, + seriesRequiredWins: 2, + bracketMatchId: 'WB_R1_M1', + }), + expect.objectContaining({ + gameNumber: 2, + seriesGameNumber: 2, + bracketMatchId: 'WB_R1_M1', + }), + expect.objectContaining({ + gameNumber: 3, + seriesGameNumber: 3, + bracketMatchId: 'WB_R1_M1', + }), + expect.objectContaining({ + gameNumber: 4, + seriesGameNumber: 1, + bracketMatchId: 'WB_R1_M2', + }), + expect.objectContaining({ + gameNumber: 5, + seriesGameNumber: 2, + bracketMatchId: 'WB_R1_M2', + }), + expect.objectContaining({ + gameNumber: 6, + seriesGameNumber: 3, + bracketMatchId: 'WB_R1_M2', + }), + ]); }); it('creates a limited round-robin schedule grouped by playable rounds', () => { @@ -374,7 +440,7 @@ describe('TournamentCodeService round-robin scheduling', () => { }); describe('TournamentCodeService bulk upload', () => { - it('defines unique slot and riot match indexes for multi-instance safety', () => { + it('defines slot and riot match indexes for multi-instance safety', () => { const indexes = TournamentCodeSchema.indexes(); expect(indexes).toContainEqual([ @@ -391,7 +457,6 @@ describe('TournamentCodeService bulk upload', () => { expect(indexes).toContainEqual([ { matchId: 1, bracketMatchId: 1 }, expect.objectContaining({ - unique: true, partialFilterExpression: { matchId: { $exists: true }, bracketMatchId: { $exists: true }, diff --git a/apps/api/src/modules/tournament-code/tournament-code.service.ts b/apps/api/src/modules/tournament-code/tournament-code.service.ts index 0ae2e95e..06611779 100644 --- a/apps/api/src/modules/tournament-code/tournament-code.service.ts +++ b/apps/api/src/modules/tournament-code/tournament-code.service.ts @@ -8,13 +8,13 @@ import { import { randomUUID } from 'crypto'; import mongoose from 'mongoose'; import { + buildDoubleEliminationGameSlots, buildDoubleEliminationBracket, - findNextReadyDoubleEliminationBracketMatches, + type DoubleEliminationGameSlot, } from '../double-elimination/double-elimination.util'; import { AuctionRedisService } from '../auction/redis/auction-redis.service'; import { ConnectionService } from '../global/database/connection.service'; import type { - DoubleEliminationBracketMatch, MatchGameAssignment, MatchDocument, TournamentCode, @@ -358,9 +358,9 @@ export class TournamentCodeService { match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; match.tournamentCodeIds = match.tournamentCodeIds ?? []; this.ensureGameSchedule(match); - const doubleEliminationBracketMatch = + const doubleEliminationSlot = (match.gameMode ?? 'pair') === 'double-elimination' - ? this.resolveDoubleEliminationBracketMatchByGameNumber( + ? this.resolveDoubleEliminationGameSlotByGameNumber( match, params.gameNumber, ) @@ -376,11 +376,7 @@ export class TournamentCodeService { } if ( (match.result?.games ?? []).some( - (game) => - game.gameNumber === params.gameNumber || - (doubleEliminationBracketMatch?.bracketMatchId && - game.bracketMatchId === - doubleEliminationBracketMatch.bracketMatchId), + (game) => game.gameNumber === params.gameNumber, ) ) { throw new BadRequestException( @@ -393,8 +389,12 @@ export class TournamentCodeService { TournamentCodeModel.findOne({ _id: { $in: match.tournamentCodeIds }, matchId: match._id, - ...(doubleEliminationBracketMatch - ? { bracketMatchId: doubleEliminationBracketMatch.bracketMatchId } + ...(doubleEliminationSlot + ? { + gameNumber: params.gameNumber, + bracketMatchId: + doubleEliminationSlot.bracketMatch.bracketMatchId, + } : { gameNumber: params.gameNumber }), }), session, @@ -444,9 +444,10 @@ export class TournamentCodeService { state: 'reserved', matchId: match._id, gameNumber: params.gameNumber, - ...(doubleEliminationBracketMatch + ...(doubleEliminationSlot ? { - bracketMatchId: doubleEliminationBracketMatch.bracketMatchId, + bracketMatchId: + doubleEliminationSlot.bracketMatch.bracketMatchId, } : {}), reservedAt: new Date(), @@ -470,8 +471,8 @@ export class TournamentCodeService { return { gameNumber: params.gameNumber, - ...(doubleEliminationBracketMatch - ? this.toDoubleEliminationSlotBase(doubleEliminationBracketMatch) + ...(doubleEliminationSlot + ? this.toDoubleEliminationSlotBase(doubleEliminationSlot) : {}), roundNumber: this.resolveRoundNumberForGameNumber( match, @@ -735,9 +736,9 @@ export class TournamentCodeService { }; return Boolean( candidate?.hasErrorLabel?.('TransientTransactionError') || - candidate?.hasErrorLabel?.('UnknownTransactionCommitResult') || - candidate?.code === 112 || - candidate?.codeName === 'WriteConflict', + candidate?.hasErrorLabel?.('UnknownTransactionCommitResult') || + candidate?.code === 112 || + candidate?.codeName === 'WriteConflict', ); } @@ -768,9 +769,9 @@ export class TournamentCodeService { TournamentCodeModel: mongoose.Model, session: mongoose.ClientSession, ): Promise { - const readyBracketMatches = findNextReadyDoubleEliminationBracketMatches( - match.doubleElimination, - ); + const readySlots = buildDoubleEliminationGameSlots( + match.doubleElimination?.bracketMatches ?? [], + ).filter((slot) => slot.bracketMatch.state === 'ready'); const existingCodes = match.tournamentCodeIds.length > 0 ? await this.execQuery( @@ -782,22 +783,22 @@ export class TournamentCodeService { ), ) : []; - const byBracketMatchId = new Map( + const byGameNumber = new Map( existingCodes .filter( (code) => - code.bracketMatchId && + typeof code.gameNumber === 'number' && (code.state === 'reserved' || code.state === 'used'), ) - .map((code) => [code.bracketMatchId as string, code]), + .map((code) => [code.gameNumber as number, code]), ); const expiresAfter = new Date( Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS, ); const reservedIds: mongoose.Types.ObjectId[] = []; - for (const bracketMatch of readyBracketMatches) { - if (byBracketMatchId.has(bracketMatch.bracketMatchId)) continue; + for (const slot of readySlots) { + if (byGameNumber.has(slot.gameNumber)) continue; const code = await TournamentCodeModel.findOneAndUpdate( { state: 'available', @@ -810,8 +811,8 @@ export class TournamentCodeService { $set: { state: 'reserved', matchId: match._id, - gameNumber: bracketMatch.gameNumber, - bracketMatchId: bracketMatch.bracketMatchId, + gameNumber: slot.gameNumber, + bracketMatchId: slot.bracketMatch.bracketMatchId, reservedAt: new Date(), }, $unset: { releasedAt: 1 }, @@ -820,7 +821,7 @@ export class TournamentCodeService { ).exec(); if (!code) break; reservedIds.push(code._id); - byBracketMatchId.set(bracketMatch.bracketMatchId, code); + byGameNumber.set(slot.gameNumber, code); } if (reservedIds.length > 0) { @@ -841,6 +842,7 @@ export class TournamentCodeService { this.ensureGameSchedule(match); const bracketMatches = match.doubleElimination?.bracketMatches ?? []; if (bracketMatches.length === 0) return []; + const slots = buildDoubleEliminationGameSlots(bracketMatches); const TournamentCodeModel = await this.connectionService.getModel('tournamentCode'); const ids = match.tournamentCodeIds ?? []; @@ -848,21 +850,21 @@ export class TournamentCodeService { ids.length > 0 ? await TournamentCodeModel.find({ _id: { $in: ids } }).exec() : []; - const byBracketMatchId = new Map( + const byGameNumber = new Map( codes .filter( (code) => - code.bracketMatchId && + typeof code.gameNumber === 'number' && code.state !== 'released' && code.state !== 'voided', ) - .map((code) => [code.bracketMatchId as string, code]), + .map((code) => [code.gameNumber as number, code]), ); - return bracketMatches.map((bracketMatch) => { - const code = byBracketMatchId.get(bracketMatch.bracketMatchId); + return slots.map((slot) => { + const code = byGameNumber.get(slot.gameNumber); return { - ...this.toDoubleEliminationSlotBase(bracketMatch), + ...this.toDoubleEliminationSlotBase(slot), code: code?.code ?? null, expiresAt: code?.expiresAt.toISOString() ?? null, state: code?.state ?? 'pending', @@ -872,10 +874,17 @@ export class TournamentCodeService { } private toDoubleEliminationSlotBase( - bracketMatch: DoubleEliminationBracketMatch, - ): Omit { + slot: DoubleEliminationGameSlot, + ): Omit< + TournamentCodeSlotView, + 'code' | 'expiresAt' | 'state' | 'riotMatchId' + > { + const bracketMatch = slot.bracketMatch; return { - gameNumber: bracketMatch.gameNumber, + gameNumber: slot.gameNumber, + seriesGameNumber: slot.seriesGameNumber, + seriesGameCount: slot.seriesGameCount, + seriesRequiredWins: slot.seriesRequiredWins, bracketMatchId: bracketMatch.bracketMatchId, bracketSide: bracketMatch.bracketSide, roundNumber: bracketMatch.roundNumber, @@ -890,7 +899,9 @@ export class TournamentCodeService { const gameMode = match.gameMode ?? 'pair'; if (gameMode === 'double-elimination') { - return match.doubleElimination?.bracketMatches.length ?? 0; + return buildDoubleEliminationGameSlots( + match.doubleElimination?.bracketMatches ?? [], + ).length; } if (gameMode === 'round-robin') { @@ -917,13 +928,13 @@ export class TournamentCodeService { const gameMode = match.gameMode ?? 'pair'; if (gameMode === 'double-elimination') { - const bracketMatch = this.resolveDoubleEliminationBracketMatchByGameNumber( + const slot = this.resolveDoubleEliminationGameSlotByGameNumber( match, gameNumber, ); return { - teamAIndex: bracketMatch?.teamAIndex ?? 1, - teamBIndex: bracketMatch?.teamBIndex ?? 2, + teamAIndex: slot?.bracketMatch.teamAIndex ?? 1, + teamBIndex: slot?.bracketMatch.teamBIndex ?? 2, }; } @@ -984,20 +995,21 @@ export class TournamentCodeService { match.doubleElimination = buildDoubleEliminationBracket( shuffledTeamIndexes, { - resetFinalEnabled: - match.doubleElimination?.resetFinalEnabled ?? false, + resetFinalEnabled: match.doubleElimination?.resetFinalEnabled ?? false, + winnerBracketGameCount: + match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT, }, ); match.markModified?.('doubleElimination'); } - private resolveDoubleEliminationBracketMatchByGameNumber( + private resolveDoubleEliminationGameSlotByGameNumber( match: MatchDocument, gameNumber: number, - ): DoubleEliminationBracketMatch | undefined { - return match.doubleElimination?.bracketMatches.find( - (bracketMatch) => bracketMatch.gameNumber === gameNumber, - ); + ): DoubleEliminationGameSlot | undefined { + return buildDoubleEliminationGameSlots( + match.doubleElimination?.bracketMatches ?? [], + ).find((slot) => slot.gameNumber === gameNumber); } private shuffleTeamIndexes(teamIndexes: number[]): number[] { diff --git a/apps/api/src/modules/tournament-code/tournament-code.types.ts b/apps/api/src/modules/tournament-code/tournament-code.types.ts index 4ac7ea6d..f3b9a59f 100644 --- a/apps/api/src/modules/tournament-code/tournament-code.types.ts +++ b/apps/api/src/modules/tournament-code/tournament-code.types.ts @@ -24,6 +24,9 @@ export interface BulkUploadTournamentCodesResponse { export interface TournamentCodeSlotView { gameNumber: number; + seriesGameNumber?: number; + seriesGameCount?: number; + seriesRequiredWins?: number; bracketMatchId?: string; bracketSide?: string; roundNumber?: number; diff --git a/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts b/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts index 7bebe1f0..733c534f 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts @@ -3,6 +3,7 @@ import type { MatchDocument } from '../global/database/schema'; import { DistributedLockService } from '../global/redis/distributed-lock.service'; import type { RiotMatchDto } from '../riot/riot.types'; import { TournamentResultService } from './tournament-result.service'; +import { buildDoubleEliminationBracket } from '../double-elimination/double-elimination.util'; type TournamentResultServiceInternals = TournamentResultService & { nextPollDelayMs(elapsedMs: number): number | null; @@ -14,6 +15,11 @@ type TournamentResultServiceInternals = TournamentResultService & { buildSeriesResults( games: NonNullable['games'], ): NonNullable['seriesResults']; + advanceDoubleEliminationIfNeeded( + match: MatchDocument, + gameResult: NonNullable['games'][number], + completedBy: 'riot-result' | 'walkover', + ): string | undefined; }; function createService() { @@ -38,23 +44,27 @@ function createDistributedLockService() { options.lockExpirationDurationMilliseconds, }), ), - runWithRenewedLock: jest.fn().mockImplementation(async (options, operation) => - operation({ - lockKey: options.lockKey, - lockOwnershipToken: 'lock-owner', - lockExpirationDurationMilliseconds: - options.lockExpirationDurationMilliseconds, - }), - ), + runWithRenewedLock: jest + .fn() + .mockImplementation(async (options, operation) => + operation({ + lockKey: options.lockKey, + lockOwnershipToken: 'lock-owner', + lockExpirationDurationMilliseconds: + options.lockExpirationDurationMilliseconds, + }), + ), } as unknown as jest.Mocked; } interface MatchOverrides { gameCount?: number; - gameMode?: 'pair' | 'bracket' | 'round-robin'; + gameMode?: 'pair' | 'bracket' | 'round-robin' | 'double-elimination'; roundRobinMaxRounds?: number; participants?: Array<{ excluded?: boolean }>; teams?: Array<{ teamIndex: number }>; + doubleElimination?: MatchDocument['doubleElimination']; + result?: MatchDocument['result']; gameSchedule?: Array<{ gameNumber: number; roundNumber?: number; @@ -70,6 +80,7 @@ function createMatch(overrides: MatchOverrides): MatchDocument { participants: [], teams: [], gameSchedule: [], + result: undefined, ...overrides, } as unknown as MatchDocument; } @@ -177,6 +188,96 @@ describe('TournamentResultService round-robin scheduling', () => { }, ]); }); + + it('maps double-elimination series game numbers to bracket matches', () => { + const service = createService(); + const match = createMatch({ + gameMode: 'double-elimination', + doubleElimination: buildDoubleEliminationBracket([1, 2, 3, 4], { + resetFinalEnabled: true, + }), + }); + + expect(service.resolveRequiredGameSlots(match)).toBe(12); + expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({ + teamAIndex: 1, + teamBIndex: 4, + }); + expect(service.resolveSeriesRefForGameNumber(match, 4)).toEqual({ + teamAIndex: 2, + teamBIndex: 3, + }); + }); + + it('advances double-elimination only after a team reaches required series wins', () => { + const service = createService(); + const game = { + gameNumber: 1, + bracketMatchId: 'WB_R1_M1', + riotMatchId: 'KR_1', + blueTeamIndex: 1, + redTeamIndex: 4, + winnerTeamIndex: 1, + winnerSide: 'blue', + gameCreation: 1, + gameDuration: 1800, + participants: [], + } as NonNullable['games'][number]; + const match = createMatch({ + gameMode: 'double-elimination', + doubleElimination: buildDoubleEliminationBracket([1, 2, 3, 4], { + resetFinalEnabled: true, + }), + result: { + riotMatchIds: ['KR_1'], + games: [game], + seriesResults: [ + { + bracketMatchId: 'WB_R1_M1', + teamAIndex: 1, + teamBIndex: 4, + teamAWins: 1, + teamBWins: 0, + winnerTeamIndex: 1, + }, + ], + }, + } as MatchOverrides); + + expect( + service.advanceDoubleEliminationIfNeeded(match, game, 'riot-result'), + ).toBeUndefined(); + const firstGameBracketMatch = match.doubleElimination?.bracketMatches.find( + (entry) => entry.bracketMatchId === 'WB_R1_M1', + ); + expect(firstGameBracketMatch).toMatchObject({ state: 'ready' }); + expect(firstGameBracketMatch?.winnerTeamIndex).toBeUndefined(); + + match.result!.seriesResults = [ + { + bracketMatchId: 'WB_R1_M1', + teamAIndex: 1, + teamBIndex: 4, + teamAWins: 2, + teamBWins: 0, + winnerTeamIndex: 1, + }, + ]; + + expect( + service.advanceDoubleEliminationIfNeeded(match, game, 'riot-result'), + ).toBe('WB_R1_M1'); + expect( + match.doubleElimination?.bracketMatches.find( + (entry) => entry.bracketMatchId === 'WB_R1_M1', + ), + ).toMatchObject({ state: 'completed', winnerTeamIndex: 1 }); + expect( + match.doubleElimination?.bracketMatches.find( + (entry) => entry.bracketMatchId === 'WB_FINAL', + ), + ).toMatchObject({ teamAIndex: 1 }); + }); }); describe('TournamentResultService tournament code polling', () => { diff --git a/apps/api/src/modules/tournament-result/tournament-result.service.ts b/apps/api/src/modules/tournament-result/tournament-result.service.ts index 789acb1b..59067a14 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.service.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.service.ts @@ -6,7 +6,10 @@ import { } from '@nestjs/common'; import mongoose from 'mongoose'; import { + buildDoubleEliminationGameSlots, completeDoubleEliminationBracketMatch, + resolveDoubleEliminationSeriesWinner, + type DoubleEliminationGameSlot, } from '../double-elimination/double-elimination.util'; import { MatchStatsService } from '../community-stats/match-stats.service'; import { CommunityStatsService } from '../community-stats/community-stats.service'; @@ -220,19 +223,20 @@ export class TournamentResultService { } public async processPollJob(job: PollTournamentResultJob): Promise { - const didProcessPollJob = await this.distributedLockService.runWithRenewedLock( - { - lockKey: this.tournamentResultPollProcessingLockKey(job.matchId), - lockExpirationDurationMilliseconds: - TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_EXPIRATION_DURATION_MILLISECONDS, - lockRenewalIntervalMilliseconds: - TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_RENEWAL_INTERVAL_MILLISECONDS, - }, - async () => { - await this.processPollJobWhileLockOwned(job); - return true; - }, - ); + const didProcessPollJob = + await this.distributedLockService.runWithRenewedLock( + { + lockKey: this.tournamentResultPollProcessingLockKey(job.matchId), + lockExpirationDurationMilliseconds: + TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_EXPIRATION_DURATION_MILLISECONDS, + lockRenewalIntervalMilliseconds: + TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_RENEWAL_INTERVAL_MILLISECONDS, + }, + async () => { + await this.processPollJobWhileLockOwned(job); + return true; + }, + ); if (didProcessPollJob) return; this.logger.debug( @@ -391,7 +395,17 @@ export class TournamentResultService { await code.save(); this.upsertGameResult(match, gameResult); - this.advanceDoubleEliminationIfNeeded(match, gameResult, 'riot-result'); + const completedBracketMatchId = this.advanceDoubleEliminationIfNeeded( + match, + gameResult, + 'riot-result', + ); + if (completedBracketMatchId) { + await this.releaseUnusedReservedDoubleEliminationCodes( + match, + completedBracketMatchId, + ); + } if (match.status === 'team-built') { match.status = 'in-progress'; } @@ -426,7 +440,17 @@ export class TournamentResultService { } this.upsertGameResult(match, gameResult); - this.advanceDoubleEliminationIfNeeded(match, gameResult, 'riot-result'); + const completedBracketMatchId = this.advanceDoubleEliminationIfNeeded( + match, + gameResult, + 'riot-result', + ); + if (completedBracketMatchId) { + await this.releaseUnusedReservedDoubleEliminationCodes( + match, + completedBracketMatchId, + ); + } await this.markTournamentCodeUsedForManualResult( match, gameResult, @@ -719,19 +743,17 @@ export class TournamentResultService { const usedGameNumbers = new Set( (match.result?.games ?? []).map((game) => game.gameNumber), ); - const usedBracketMatchIds = new Set( - (match.result?.games ?? []) - .map((game) => game.bracketMatchId) - .filter((id): id is string => Boolean(id)), - ); const assignments: ManualGameAssignment[] = []; if ((match.gameMode ?? 'pair') === 'double-elimination') { - for (const bracketMatch of match.doubleElimination?.bracketMatches ?? []) { + for (const slot of buildDoubleEliminationGameSlots( + match.doubleElimination?.bracketMatches ?? [], + )) { + const bracketMatch = slot.bracketMatch; if (bracketMatch.state !== 'ready') continue; - if (usedBracketMatchIds.has(bracketMatch.bracketMatchId)) continue; + if (usedGameNumbers.has(slot.gameNumber)) continue; if (!bracketMatch.teamAIndex || !bracketMatch.teamBIndex) continue; assignments.push({ - gameNumber: bracketMatch.gameNumber, + gameNumber: slot.gameNumber, bracketMatchId: bracketMatch.bracketMatchId, teamAIndex: bracketMatch.teamAIndex, teamBIndex: bracketMatch.teamBIndex, @@ -836,14 +858,27 @@ export class TournamentResultService { match: MatchDocument, gameResult: MatchGameResult, completedBy: 'riot-result' | 'walkover', - ): void { - if ((match.gameMode ?? 'pair') !== 'double-elimination') return; - if (!match.doubleElimination || !gameResult.bracketMatchId) return; + ): string | undefined { + if ((match.gameMode ?? 'pair') !== 'double-elimination') return undefined; + if (!match.doubleElimination || !gameResult.bracketMatchId) + return undefined; + const bracketMatch = match.doubleElimination.bracketMatches.find( + (entry) => entry.bracketMatchId === gameResult.bracketMatchId, + ); + if (!bracketMatch || bracketMatch.state !== 'ready') return undefined; + const seriesResult = match.result?.seriesResults?.find( + (entry) => entry.bracketMatchId === gameResult.bracketMatchId, + ); + const winnerTeamIndex = resolveDoubleEliminationSeriesWinner( + seriesResult, + bracketMatch, + ); + if (!winnerTeamIndex) return undefined; match.doubleElimination = completeDoubleEliminationBracketMatch( match.doubleElimination, { bracketMatchId: gameResult.bracketMatchId, - winnerTeamIndex: gameResult.winnerTeamIndex, + winnerTeamIndex, completedBy, completedAt: new Date(gameResult.gameCreation), }, @@ -853,14 +888,15 @@ export class TournamentResultService { match.doubleElimination!.placements.firstTeamIndex; } match.markModified?.('doubleElimination'); + return gameResult.bracketMatchId; } private isDoubleEliminationComplete(match: MatchDocument): boolean { const placements = match.doubleElimination?.placements; return Boolean( placements?.firstTeamIndex && - placements.secondTeamIndex && - placements.thirdTeamIndex, + placements.secondTeamIndex && + placements.thirdTeamIndex, ); } @@ -883,9 +919,10 @@ export class TournamentResultService { match: MatchDocument, ): Promise { if ((match.gameMode ?? 'pair') !== 'double-elimination') return; - const readyBracketMatches = (match.doubleElimination?.bracketMatches ?? []) - .filter((bracketMatch) => bracketMatch.state === 'ready'); - if (readyBracketMatches.length === 0) return; + const readySlots = buildDoubleEliminationGameSlots( + match.doubleElimination?.bracketMatches ?? [], + ).filter((slot) => slot.bracketMatch.state === 'ready'); + if (readySlots.length === 0) return; const MatchModel = await this.connectionService.getModel('match'); const TournamentCodeModel = @@ -896,20 +933,22 @@ export class TournamentResultService { _id: { $in: match.tournamentCodeIds }, }).exec() : []; - const existingByBracketMatchId = new Map( + const existingByGameNumber = new Map( existingCodes .filter( (code) => - code.bracketMatchId && + typeof code.gameNumber === 'number' && (code.state === 'reserved' || code.state === 'used'), ) - .map((code) => [code.bracketMatchId as string, code]), + .map((code) => [code.gameNumber as number, code]), ); const reservedIds: mongoose.Types.ObjectId[] = []; - const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS); + const expiresAfter = new Date( + Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS, + ); - for (const bracketMatch of readyBracketMatches) { - if (existingByBracketMatchId.has(bracketMatch.bracketMatchId)) continue; + for (const slot of readySlots) { + if (existingByGameNumber.has(slot.gameNumber)) continue; const code = await TournamentCodeModel.findOneAndUpdate( { state: 'available', @@ -922,8 +961,8 @@ export class TournamentResultService { $set: { state: 'reserved', matchId: match._id, - gameNumber: bracketMatch.gameNumber, - bracketMatchId: bracketMatch.bracketMatchId, + gameNumber: slot.gameNumber, + bracketMatchId: slot.bracketMatch.bracketMatchId, reservedAt: new Date(), }, $unset: { releasedAt: 1 }, @@ -960,9 +999,10 @@ export class TournamentResultService { await TournamentCodeModel.updateOne( { matchId: match._id, + gameNumber: gameResult.gameNumber, ...(gameResult.bracketMatchId ? { bracketMatchId: gameResult.bracketMatchId } - : { gameNumber: gameResult.gameNumber }), + : {}), state: { $in: ['reserved', 'released'] }, }, { @@ -980,6 +1020,45 @@ export class TournamentResultService { ).exec(); } + private async releaseUnusedReservedDoubleEliminationCodes( + match: MatchDocument, + bracketMatchId: string, + ): Promise { + const ids = match.tournamentCodeIds ?? []; + if (ids.length === 0) return; + const usedGameNumbers = new Set( + (match.result?.games ?? []) + .filter((game) => game.bracketMatchId === bracketMatchId) + .map((game) => game.gameNumber), + ); + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const codes = await TournamentCodeModel.find({ + _id: { $in: ids }, + matchId: match._id, + bracketMatchId, + state: 'reserved', + gameNumber: { $nin: [...usedGameNumbers] }, + }).exec(); + if (codes.length === 0) return; + const releasedIds = codes.map((code) => code._id.toString()); + await TournamentCodeModel.updateMany( + { _id: { $in: codes.map((code) => code._id) } }, + { + $set: { state: 'released', releasedAt: new Date() }, + $unset: { + matchId: 1, + gameNumber: 1, + bracketMatchId: 1, + reservedAt: 1, + }, + }, + ).exec(); + match.tournamentCodeIds = ids.filter( + (id) => !releasedIds.includes(id.toString()), + ); + } + private buildSeriesResults( games: MatchGameResult[], ): NonNullable['seriesResults'] { @@ -1009,9 +1088,7 @@ export class TournamentResultService { return [...bySeries.values()].sort( (left, right) => - (left.bracketMatchId ?? '').localeCompare( - right.bracketMatchId ?? '', - ) || + (left.bracketMatchId ?? '').localeCompare(right.bracketMatchId ?? '') || left.teamAIndex - right.teamAIndex || left.teamBIndex - right.teamBIndex, ); @@ -1024,13 +1101,14 @@ export class TournamentResultService { const gameMode = match.gameMode ?? 'pair'; if (gameMode === 'double-elimination') { - const bracketMatch = match.doubleElimination?.bracketMatches.find( - (entry) => entry.gameNumber === gameNumber, + const slot = this.resolveDoubleEliminationGameSlotByGameNumber( + match, + gameNumber, ); - return bracketMatch + return slot ? { - teamAIndex: bracketMatch.teamAIndex ?? 1, - teamBIndex: bracketMatch.teamBIndex ?? 2, + teamAIndex: slot.bracketMatch.teamAIndex ?? 1, + teamBIndex: slot.bracketMatch.teamBIndex ?? 2, } : { teamAIndex: 1, @@ -1071,10 +1149,21 @@ export class TournamentResultService { }; } + private resolveDoubleEliminationGameSlotByGameNumber( + match: MatchDocument, + gameNumber: number, + ): DoubleEliminationGameSlot | undefined { + return buildDoubleEliminationGameSlots( + match.doubleElimination?.bracketMatches ?? [], + ).find((slot) => slot.gameNumber === gameNumber); + } + private resolveRequiredGameSlots(match: MatchDocument): number { const gameMode = match.gameMode ?? 'pair'; if (gameMode === 'double-elimination') { - return match.doubleElimination?.bracketMatches.length ?? 0; + return buildDoubleEliminationGameSlots( + match.doubleElimination?.bracketMatches ?? [], + ).length; } if (gameMode === 'round-robin') { if ((match.gameSchedule?.length ?? 0) > 0) { @@ -1210,7 +1299,9 @@ export class TournamentResultService { : matchOrId._id.toString(); } - private tournamentResultPollProcessingLockKey(matchIdentifier: string): string { + private tournamentResultPollProcessingLockKey( + matchIdentifier: string, + ): string { return `distributed-lock:tournament-result:process-poll-job:match:${matchIdentifier}`; } diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index bce1341e..b5f72041 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -147,6 +147,9 @@ export type TournamentCodeSlotState = TournamentCodeState | 'pending'; export interface TournamentCodeSlotView { gameNumber: number; + seriesGameNumber?: number; + seriesGameCount?: number; + seriesRequiredWins?: number; bracketMatchId?: string; bracketSide?: string; roundNumber?: number; @@ -257,6 +260,8 @@ export interface ApiDoubleEliminationWalkover { export interface ApiDoubleEliminationBracketMatch { bracketMatchId: string; gameNumber: number; + gameCount: number; + requiredWins: number; bracketSide: 'winner' | 'loser' | 'grand-final' | 'reset-final'; roundNumber: number; matchNumber: number; diff --git a/apps/web/src/pages/MatchDetailPage.tsx b/apps/web/src/pages/MatchDetailPage.tsx index 2da5e909..88ddb1fa 100644 --- a/apps/web/src/pages/MatchDetailPage.tsx +++ b/apps/web/src/pages/MatchDetailPage.tsx @@ -1535,6 +1535,9 @@ function TournamentCodeList({
{slot.gameNumber}경기 + {slot.seriesGameCount && slot.seriesGameCount > 1 + ? ` · ${slot.seriesGameNumber ?? 1}/${slot.seriesGameCount}세트` + : ""} {shouldShowTeamLabel && ( @@ -3007,6 +3010,11 @@ function DoubleEliminationBracketCard({ {bracketMatch.gameNumber}경기 + {bracketMatch.gameCount > 1 && ( + + BO{bracketMatch.gameCount} · {bracketMatch.requiredWins}선승 + + )} {bracketMatch.bracketMatchId} diff --git a/apps/web/src/pages/admin/MatchAdminPage.tsx b/apps/web/src/pages/admin/MatchAdminPage.tsx index 5e9d60bb..af44ea3e 100644 --- a/apps/web/src/pages/admin/MatchAdminPage.tsx +++ b/apps/web/src/pages/admin/MatchAdminPage.tsx @@ -52,6 +52,12 @@ function normalizeRoundRobinMaxRounds( return Math.max(1, Math.min(fullRoundCount, Math.floor(value))); } +function normalizeSeriesGameCount(value: number | undefined) { + if (!value || !Number.isFinite(value) || value < 1) return 3; + const integer = Math.floor(value); + return integer % 2 === 0 ? integer + 1 : integer; +} + function RequiredBadge() { return ( @@ -350,14 +356,15 @@ export default function MatchAdminPage() { setForm((current) => ({ ...current, gameCount: Number(event.target.value) }))} className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm" /> {form.gameMode === 'double-elimination' && ( - 더블 엘리미네이션은 단판으로 진행됩니다. + 승자조는 현재 3판 2선승으로 진행됩니다. 추후 5판 3선승도 같은 + 구조로 지원합니다. )} @@ -377,7 +384,9 @@ export default function MatchAdminPage() { ? 20 : current.maxParticipants, gameCount: - gameMode === 'double-elimination' ? 1 : current.gameCount, + gameMode === 'double-elimination' + ? normalizeSeriesGameCount(current.gameCount) + : current.gameCount, })); }} className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"