feat: support double-elimination series games

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

No files matched your search

@@ -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 },
@@ -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<TournamentCode>,
session: mongoose.ClientSession,
): Promise<MatchDocument> {
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<TournamentCodeDocument[]>(
@@ -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<TournamentCodeSlotView, 'code' | 'expiresAt' | 'state' | 'riotMatchId'> {
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[] {
@@ -24,6 +24,9 @@ export interface BulkUploadTournamentCodesResponse {
export interface TournamentCodeSlotView {
gameNumber: number;
seriesGameNumber?: number;
seriesGameCount?: number;
seriesRequiredWins?: number;
bracketMatchId?: string;
bracketSide?: string;
roundNumber?: number;