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

@@ -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<void> {
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<void> {
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<void> {
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<MatchDocument['result']>['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}`;
}