feat: add double elimination match mode
This commit is contained in:
1 parent
b9aaf55193
commit
e12f182e7f
19 files changed
+3415
-58
No files matched your search
@@ -5,12 +5,16 @@ import {
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import {
|
||||
completeDoubleEliminationBracketMatch,
|
||||
} from '../double-elimination/double-elimination.util';
|
||||
import { MatchStatsService } from '../community-stats/match-stats.service';
|
||||
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type {
|
||||
MatchDocument,
|
||||
MatchGameResult,
|
||||
MatchSeriesResult,
|
||||
RiotMatch as StoredRiotMatch,
|
||||
TournamentCodeDocument,
|
||||
} from '../global/database/schema';
|
||||
@@ -22,6 +26,7 @@ import {
|
||||
roundRobinGameSchedule,
|
||||
resolveRoundRobinTeamCount,
|
||||
} from '../tournament-code/round-robin.util';
|
||||
import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../tournament-code/tournament-code.constants';
|
||||
import {
|
||||
collectCaptainAndLimitedTeamMemberUserIds,
|
||||
collectCaptainUserIds,
|
||||
@@ -44,6 +49,7 @@ const TOURNAMENT_LOOKUP_START_MARGIN_SECONDS = 60;
|
||||
|
||||
interface ManualGameAssignment {
|
||||
gameNumber: number;
|
||||
bracketMatchId?: string;
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
}
|
||||
@@ -207,7 +213,11 @@ export class TournamentResultService {
|
||||
(code) => code.state === 'reserved' && !code.riotMatchId,
|
||||
);
|
||||
if (unmatched.length === 0) {
|
||||
await this.advanceMatchIfReady(match, codes);
|
||||
const completed = await this.advanceMatchIfReady(match, codes);
|
||||
if (!completed) {
|
||||
await this.reserveReadyDoubleEliminationCodes(match);
|
||||
await this.scheduleNextPoll(match, job);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -324,6 +334,7 @@ export class TournamentResultService {
|
||||
return false;
|
||||
}
|
||||
|
||||
gameResult.bracketMatchId = code.bracketMatchId;
|
||||
code.state = 'used';
|
||||
code.usedAt = new Date(
|
||||
detail.info.gameEndTimestamp ?? detail.info.gameCreation,
|
||||
@@ -332,10 +343,12 @@ export class TournamentResultService {
|
||||
await code.save();
|
||||
|
||||
this.upsertGameResult(match, gameResult);
|
||||
this.advanceDoubleEliminationIfNeeded(match, gameResult, 'riot-result');
|
||||
if (match.status === 'team-built') {
|
||||
match.status = 'in-progress';
|
||||
}
|
||||
await match.save();
|
||||
await this.reserveReadyDoubleEliminationCodes(match);
|
||||
await this.rebuildMatchStatsSafe(match);
|
||||
return true;
|
||||
}
|
||||
@@ -365,6 +378,7 @@ export class TournamentResultService {
|
||||
}
|
||||
|
||||
this.upsertGameResult(match, gameResult);
|
||||
this.advanceDoubleEliminationIfNeeded(match, gameResult, 'riot-result');
|
||||
await this.markTournamentCodeUsedForManualResult(
|
||||
match,
|
||||
gameResult,
|
||||
@@ -379,6 +393,9 @@ export class TournamentResultService {
|
||||
}
|
||||
this.updateManualCollectionState(match, appliedRiotMatchIds.length);
|
||||
await match.save();
|
||||
if (appliedRiotMatchIds.length > 0) {
|
||||
await this.reserveReadyDoubleEliminationCodes(match);
|
||||
}
|
||||
if (appliedRiotMatchIds.length > 0) {
|
||||
await this.rebuildMatchStatsSafe(match);
|
||||
}
|
||||
@@ -399,6 +416,36 @@ export class TournamentResultService {
|
||||
match: MatchDocument,
|
||||
codes: TournamentCodeDocument[],
|
||||
): Promise<boolean> {
|
||||
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
||||
if (!this.isDoubleEliminationComplete(match)) return false;
|
||||
match.status = 'finished';
|
||||
if (match.result) {
|
||||
match.result.winnerTeamIndex =
|
||||
match.doubleElimination?.placements.firstTeamIndex;
|
||||
}
|
||||
match.resultPollState = {
|
||||
startedAt: match.resultPollState?.startedAt ?? new Date(),
|
||||
lastPolledAt: match.resultPollState?.lastPolledAt,
|
||||
lastPollOutcome: match.resultPollState?.lastPollOutcome,
|
||||
matchedCount: match.result?.games?.length ?? 0,
|
||||
expandedToAllPuuids:
|
||||
match.resultPollState?.expandedToAllPuuids ?? false,
|
||||
state: 'complete',
|
||||
};
|
||||
await match.save();
|
||||
await this.rebuildMatchStatsSafe(match);
|
||||
void this.communityStatsService
|
||||
.invalidateCommunity(match.communityId)
|
||||
.catch((error) => {
|
||||
this.logger.warn(
|
||||
`Failed to invalidate community stats cache for ${match.communityId.toString()}: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
if (codes.length < this.resolveRequiredGameSlots(match)) return false;
|
||||
if (!codes.every((code) => code.state === 'used' && code.riotMatchId)) {
|
||||
return false;
|
||||
@@ -585,7 +632,10 @@ export class TournamentResultService {
|
||||
const seriesResults = this.buildSeriesResults(games);
|
||||
|
||||
match.result = {
|
||||
winnerTeamIndex: this.resolveMatchWinnerTeamIndex(seriesResults),
|
||||
winnerTeamIndex:
|
||||
(match.gameMode ?? 'pair') === 'double-elimination'
|
||||
? match.doubleElimination?.placements.firstTeamIndex
|
||||
: this.resolveMatchWinnerTeamIndex(seriesResults),
|
||||
mvpUserId: match.result?.mvpUserId,
|
||||
riotMatchIds: [...new Set(games.map((game) => game.riotMatchId))],
|
||||
games,
|
||||
@@ -607,7 +657,10 @@ export class TournamentResultService {
|
||||
teamAIndex: assignment.teamAIndex,
|
||||
teamBIndex: assignment.teamBIndex,
|
||||
});
|
||||
if (gameResult) return gameResult;
|
||||
if (gameResult) {
|
||||
gameResult.bracketMatchId = assignment.bracketMatchId;
|
||||
return gameResult;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -618,7 +671,26 @@ 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 ?? []) {
|
||||
if (bracketMatch.state !== 'ready') continue;
|
||||
if (usedBracketMatchIds.has(bracketMatch.bracketMatchId)) continue;
|
||||
if (!bracketMatch.teamAIndex || !bracketMatch.teamBIndex) continue;
|
||||
assignments.push({
|
||||
gameNumber: bracketMatch.gameNumber,
|
||||
bracketMatchId: bracketMatch.bracketMatchId,
|
||||
teamAIndex: bracketMatch.teamAIndex,
|
||||
teamBIndex: bracketMatch.teamBIndex,
|
||||
});
|
||||
}
|
||||
return assignments;
|
||||
}
|
||||
const requiredSlots = this.resolveRequiredGameSlots(match);
|
||||
|
||||
for (let gameNumber = 1; gameNumber <= requiredSlots; gameNumber += 1) {
|
||||
@@ -641,6 +713,9 @@ export class TournamentResultService {
|
||||
}
|
||||
|
||||
private hasAllRequiredGameResults(match: MatchDocument): boolean {
|
||||
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
||||
return this.isDoubleEliminationComplete(match);
|
||||
}
|
||||
const requiredSlots = this.resolveRequiredGameSlots(match);
|
||||
if (requiredSlots <= 0) return false;
|
||||
const resultGameNumbers = new Set(
|
||||
@@ -671,9 +746,10 @@ export class TournamentResultService {
|
||||
): Promise<void> {
|
||||
match.status = 'finished';
|
||||
if (match.result) {
|
||||
match.result.winnerTeamIndex = this.resolveMatchWinnerTeamIndex(
|
||||
match.result.seriesResults ?? [],
|
||||
);
|
||||
match.result.winnerTeamIndex =
|
||||
(match.gameMode ?? 'pair') === 'double-elimination'
|
||||
? match.doubleElimination?.placements.firstTeamIndex
|
||||
: this.resolveMatchWinnerTeamIndex(match.result.seriesResults ?? []);
|
||||
}
|
||||
match.resultPollState = {
|
||||
startedAt: match.resultPollState?.startedAt ?? new Date(),
|
||||
@@ -708,6 +784,97 @@ export class TournamentResultService {
|
||||
}
|
||||
}
|
||||
|
||||
private advanceDoubleEliminationIfNeeded(
|
||||
match: MatchDocument,
|
||||
gameResult: MatchGameResult,
|
||||
completedBy: 'riot-result' | 'walkover',
|
||||
): void {
|
||||
if ((match.gameMode ?? 'pair') !== 'double-elimination') return;
|
||||
if (!match.doubleElimination || !gameResult.bracketMatchId) return;
|
||||
match.doubleElimination = completeDoubleEliminationBracketMatch(
|
||||
match.doubleElimination,
|
||||
{
|
||||
bracketMatchId: gameResult.bracketMatchId,
|
||||
winnerTeamIndex: gameResult.winnerTeamIndex,
|
||||
completedBy,
|
||||
completedAt: new Date(gameResult.gameCreation),
|
||||
},
|
||||
);
|
||||
if (match.result && this.isDoubleEliminationComplete(match)) {
|
||||
match.result.winnerTeamIndex =
|
||||
match.doubleElimination!.placements.firstTeamIndex;
|
||||
}
|
||||
match.markModified?.('doubleElimination');
|
||||
}
|
||||
|
||||
private isDoubleEliminationComplete(match: MatchDocument): boolean {
|
||||
const placements = match.doubleElimination?.placements;
|
||||
return Boolean(
|
||||
placements?.firstTeamIndex &&
|
||||
placements.secondTeamIndex &&
|
||||
placements.thirdTeamIndex,
|
||||
);
|
||||
}
|
||||
|
||||
private async reserveReadyDoubleEliminationCodes(
|
||||
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 TournamentCodeModel =
|
||||
await this.connectionService.getModel('tournamentCode');
|
||||
const existingCodes =
|
||||
match.tournamentCodeIds.length > 0
|
||||
? await TournamentCodeModel.find({
|
||||
_id: { $in: match.tournamentCodeIds },
|
||||
}).exec()
|
||||
: [];
|
||||
const existingByBracketMatchId = new Map(
|
||||
existingCodes
|
||||
.filter(
|
||||
(code) =>
|
||||
code.bracketMatchId &&
|
||||
(code.state === 'reserved' || code.state === 'used'),
|
||||
)
|
||||
.map((code) => [code.bracketMatchId as string, code]),
|
||||
);
|
||||
const reservedIds: mongoose.Types.ObjectId[] = [];
|
||||
const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS);
|
||||
|
||||
for (const bracketMatch of readyBracketMatches) {
|
||||
if (existingByBracketMatchId.has(bracketMatch.bracketMatchId)) continue;
|
||||
const code = await TournamentCodeModel.findOneAndUpdate(
|
||||
{
|
||||
state: 'available',
|
||||
region: 'kr',
|
||||
mapType: 'SUMMONERS_RIFT',
|
||||
teamSize: 5,
|
||||
expiresAt: { $gt: expiresAfter },
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
state: 'reserved',
|
||||
matchId: match._id,
|
||||
gameNumber: bracketMatch.gameNumber,
|
||||
bracketMatchId: bracketMatch.bracketMatchId,
|
||||
reservedAt: new Date(),
|
||||
},
|
||||
$unset: { releasedAt: 1 },
|
||||
},
|
||||
{ sort: { expiresAt: 1 }, returnDocument: 'after' },
|
||||
).exec();
|
||||
if (!code) break;
|
||||
reservedIds.push(code._id);
|
||||
}
|
||||
|
||||
if (reservedIds.length === 0) return;
|
||||
match.tournamentCodeIds.push(...reservedIds);
|
||||
await match.save();
|
||||
}
|
||||
|
||||
private async markTournamentCodeUsedForManualResult(
|
||||
match: MatchDocument,
|
||||
gameResult: MatchGameResult,
|
||||
@@ -718,7 +885,9 @@ export class TournamentResultService {
|
||||
await TournamentCodeModel.updateOne(
|
||||
{
|
||||
matchId: match._id,
|
||||
gameNumber: gameResult.gameNumber,
|
||||
...(gameResult.bracketMatchId
|
||||
? { bracketMatchId: gameResult.bracketMatchId }
|
||||
: { gameNumber: gameResult.gameNumber }),
|
||||
state: { $in: ['reserved', 'released'] },
|
||||
},
|
||||
{
|
||||
@@ -728,6 +897,9 @@ export class TournamentResultService {
|
||||
detail.info.gameEndTimestamp ?? detail.info.gameCreation,
|
||||
),
|
||||
riotMatchId: detail.metadata.matchId,
|
||||
...(gameResult.bracketMatchId
|
||||
? { bracketMatchId: gameResult.bracketMatchId }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
).exec();
|
||||
@@ -736,22 +908,14 @@ export class TournamentResultService {
|
||||
private buildSeriesResults(
|
||||
games: MatchGameResult[],
|
||||
): NonNullable<MatchDocument['result']>['seriesResults'] {
|
||||
const bySeries = new Map<
|
||||
string,
|
||||
{
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
teamAWins: number;
|
||||
teamBWins: number;
|
||||
winnerTeamIndex?: number;
|
||||
}
|
||||
>();
|
||||
const bySeries = new Map<string, MatchSeriesResult>();
|
||||
|
||||
for (const game of games) {
|
||||
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
|
||||
const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex);
|
||||
const key = `${teamAIndex}:${teamBIndex}`;
|
||||
const key = game.bracketMatchId ?? `${teamAIndex}:${teamBIndex}`;
|
||||
const current = bySeries.get(key) ?? {
|
||||
bracketMatchId: game.bracketMatchId,
|
||||
teamAIndex,
|
||||
teamBIndex,
|
||||
teamAWins: 0,
|
||||
@@ -770,6 +934,9 @@ export class TournamentResultService {
|
||||
|
||||
return [...bySeries.values()].sort(
|
||||
(left, right) =>
|
||||
(left.bracketMatchId ?? '').localeCompare(
|
||||
right.bracketMatchId ?? '',
|
||||
) ||
|
||||
left.teamAIndex - right.teamAIndex ||
|
||||
left.teamBIndex - right.teamBIndex,
|
||||
);
|
||||
@@ -781,6 +948,21 @@ export class TournamentResultService {
|
||||
): { teamAIndex: number; teamBIndex: number } {
|
||||
const gameMode = match.gameMode ?? 'pair';
|
||||
|
||||
if (gameMode === 'double-elimination') {
|
||||
const bracketMatch = match.doubleElimination?.bracketMatches.find(
|
||||
(entry) => entry.gameNumber === gameNumber,
|
||||
);
|
||||
return bracketMatch
|
||||
? {
|
||||
teamAIndex: bracketMatch.teamAIndex ?? 1,
|
||||
teamBIndex: bracketMatch.teamBIndex ?? 2,
|
||||
}
|
||||
: {
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 2,
|
||||
};
|
||||
}
|
||||
|
||||
if (gameMode === 'round-robin') {
|
||||
const persisted = match.gameSchedule?.find(
|
||||
(entry) => entry.gameNumber === gameNumber,
|
||||
@@ -816,6 +998,9 @@ export class TournamentResultService {
|
||||
|
||||
private resolveRequiredGameSlots(match: MatchDocument): number {
|
||||
const gameMode = match.gameMode ?? 'pair';
|
||||
if (gameMode === 'double-elimination') {
|
||||
return match.doubleElimination?.bracketMatches.length ?? 0;
|
||||
}
|
||||
if (gameMode === 'round-robin') {
|
||||
if ((match.gameSchedule?.length ?? 0) > 0) {
|
||||
return match.gameSchedule.length;
|
||||
|
||||
Reference in new issue
Block a user