Files
lolympus-tournament-support/apps/api/src/modules/tournament-code/tournament-code.service.ts
T

1066 lines
34 KiB
TypeScript

import {
BadRequestException,
ConflictException,
Injectable,
InternalServerErrorException,
Logger,
NotFoundException,
} from '@nestjs/common';
import { randomUUID } from 'crypto';
import mongoose from 'mongoose';
import {
buildDoubleEliminationGameSlots,
buildDoubleEliminationBracket,
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 {
MatchGameAssignment,
MatchDocument,
TournamentCode,
TournamentCodeDocument,
TournamentCodeState,
TournamentSpectatorType,
} from '../global/database/schema';
import {
DEFAULT_TOURNAMENT_GAME_COUNT,
TOURNAMENT_CODE_EXPIRING_SOON_MS,
TOURNAMENT_CODE_EXPIRY_MARGIN_MS,
TOURNAMENT_CODE_PATTERN,
} from './tournament-code.constants';
import type {
BulkUploadTournamentCodesResponse,
TournamentCodeSlotView,
TournamentCodeUploadItem,
} from './tournament-code.types';
import {
roundRobinGameSchedule,
resolveRoundRobinTeamCount,
} from './round-robin.util';
const DEFAULT_REGION = 'kr';
const DEFAULT_SPECTATOR_TYPE: TournamentSpectatorType = 'ALL';
const TOURNAMENT_CODE_MATCH_LOCK_TTL_MS = 30_000;
const TOURNAMENT_CODE_TRANSACTION_ATTEMPTS = 3;
export interface TournamentCodeExpirationResult {
expiredCount: number;
failedCount: number;
affectedMatchIds: mongoose.Types.ObjectId[];
}
@Injectable()
export class TournamentCodeService {
private readonly logger = new Logger(TournamentCodeService.name);
constructor(
private readonly connectionService: ConnectionService,
private readonly auctionRedisService: AuctionRedisService,
) {}
public async bulkUpload(params: {
communityId?: mongoose.Types.ObjectId;
uploadedBy: mongoose.Types.ObjectId;
codes: TournamentCodeUploadItem[];
}): Promise<BulkUploadTournamentCodesResponse> {
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const invalid: BulkUploadTournamentCodesResponse['invalid'] = [];
const duplicates: string[] = [];
const valid: Array<
Omit<TournamentCode, 'createdAt' | 'updatedAt'> & {
uploadedBy: mongoose.Types.ObjectId;
}
> = [];
const seen = new Set<string>();
for (const item of params.codes) {
const code = this.normalizeCode(item.code);
if (!code) {
invalid.push({ code: item.code ?? '', reason: 'empty-code' });
continue;
}
if (!TOURNAMENT_CODE_PATTERN.test(code)) {
invalid.push({ code, reason: 'invalid-format' });
continue;
}
if (seen.has(code)) {
duplicates.push(code);
continue;
}
seen.add(code);
const expiresAt = new Date(item.expiresAt);
if (Number.isNaN(expiresAt.getTime())) {
invalid.push({ code, reason: 'invalid-expiresAt' });
continue;
}
if (expiresAt <= new Date()) {
invalid.push({ code, reason: 'expired-expiresAt' });
continue;
}
valid.push({
code,
region: DEFAULT_REGION,
mapType: 'SUMMONERS_RIFT',
teamSize: 5,
spectatorType: item.spectatorType ?? DEFAULT_SPECTATOR_TYPE,
metadata: item.metadata,
expiresAt,
state: 'available',
uploadedBy: params.uploadedBy,
uploadedAt: new Date(),
source: item.source,
notes: item.notes,
});
}
if (valid.length === 0) {
return { inserted: 0, duplicates, invalid };
}
const existing = await TournamentCodeModel.find({
code: { $in: valid.map((item) => item.code) },
})
.select({ code: 1 })
.lean()
.exec();
const existingCodes = new Set(existing.map((item) => item.code));
duplicates.push(...existing.map((item) => item.code));
const insertable = valid.filter((item) => !existingCodes.has(item.code));
if (insertable.length > 0) {
await TournamentCodeModel.insertMany(insertable, { ordered: false });
}
await this.attachPendingMatches(params.communityId);
return {
inserted: insertable.length,
duplicates: [...new Set(duplicates)],
invalid,
};
}
public async countUsableAvailable(): Promise<number> {
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
return TournamentCodeModel.countDocuments({
state: 'available',
expiresAt: {
$gt: new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS),
},
}).exec();
}
public async list(params: {
state?: TournamentCodeState;
limit?: number;
}): Promise<TournamentCodeDocument[]> {
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const filter: { state?: TournamentCodeState } = {};
if (params.state) filter.state = params.state;
return TournamentCodeModel.find(filter)
.sort({ expiresAt: 1, uploadedAt: -1 })
.limit(Math.min(params.limit ?? 100, 300))
.exec();
}
public async stats(): Promise<{
byState: Record<TournamentCodeState, number>;
expiringSoon: number;
available: number;
}> {
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const states: TournamentCodeState[] = [
'available',
'reserved',
'used',
'expired',
'released',
];
const counts = await TournamentCodeModel.aggregate<{
_id: TournamentCodeState;
count: number;
}>([{ $group: { _id: '$state', count: { $sum: 1 } } }]).exec();
const byState = Object.fromEntries(
states.map((state) => [state, 0]),
) as Record<TournamentCodeState, number>;
for (const entry of counts) byState[entry._id] = entry.count;
const expiringSoon = await TournamentCodeModel.countDocuments({
state: 'available',
expiresAt: {
$gt: new Date(),
$lte: new Date(Date.now() + TOURNAMENT_CODE_EXPIRING_SOON_MS),
},
});
return { byState, expiringSoon, available: byState.available };
}
public async discardAvailable(id: mongoose.Types.ObjectId): Promise<void> {
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const result = await TournamentCodeModel.deleteOne({
_id: id,
state: 'available',
}).exec();
if (result.deletedCount === 0) {
throw new BadRequestException(
'Only available tournament codes can be deleted.',
);
}
}
public async restoreToAvailable(
id: mongoose.Types.ObjectId,
): Promise<TournamentCodeDocument> {
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const MatchModel = await this.connectionService.getModel('match');
const code = await TournamentCodeModel.findById(id);
if (!code) throw new NotFoundException('Tournament code not found.');
if (code.state !== 'released') {
throw new BadRequestException(
'Only released tournament codes can be restored. Active Competition assignments must be reversed through Competition commands.',
);
}
const previousMatchId = code.matchId;
code.state = 'available';
code.matchId = undefined;
code.gameNumber = undefined;
code.reservedAt = undefined;
code.releasedAt = undefined;
await code.save();
if (previousMatchId) {
await MatchModel.updateOne(
{ _id: previousMatchId },
{ $pull: { tournamentCodeIds: code._id } },
).exec();
await this.attachPendingMatches();
}
return code;
}
public async reserveForMatch(
matchOrId: MatchDocument | mongoose.Types.ObjectId,
): Promise<MatchDocument> {
const matchId = this.resolveMatchId(matchOrId);
return this.withLockedMatchTransaction(matchId, (session) =>
this.reserveForMatchInTransaction(matchId, session),
);
}
private async reserveForMatchInTransaction(
matchId: mongoose.Types.ObjectId,
session: mongoose.ClientSession,
): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match');
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const match = await this.execQuery<MatchDocument | null>(
this.withQuerySession(MatchModel.findById(matchId), session),
);
if (!match) throw new NotFoundException('Match not found.');
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
this.ensureGameSchedule(match);
if ((match.gameMode ?? 'pair') === 'double-elimination') {
return this.reserveForDoubleEliminationMatch(
match,
TournamentCodeModel,
session,
);
}
const shouldSaveMetadata =
this.isMatchModified(match, 'gameCount') ||
this.isMatchModified(match, 'gameSchedule');
const requiredSlots = this.resolveRequiredSlots(match);
const need = requiredSlots - match.tournamentCodeIds.length;
if (need <= 0) {
if (shouldSaveMetadata) await match.save();
return match;
}
const reservedIds: mongoose.Types.ObjectId[] = [];
const startGameNumber = match.tournamentCodeIds.length + 1;
const expiresAfter = new Date(
Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS,
);
for (let index = 0; index < need; index += 1) {
const code = await TournamentCodeModel.findOneAndUpdate(
{
state: 'available',
region: DEFAULT_REGION,
mapType: 'SUMMONERS_RIFT',
teamSize: 5,
expiresAt: { $gt: expiresAfter },
},
{
$set: {
state: 'reserved',
matchId: match._id,
gameNumber: startGameNumber + index,
reservedAt: new Date(),
},
$unset: { releasedAt: 1 },
},
{ sort: { expiresAt: 1 }, returnDocument: 'after', session },
).exec();
if (!code) break;
reservedIds.push(code._id);
}
if (reservedIds.length > 0) {
match.tournamentCodeIds.push(...reservedIds);
}
if (reservedIds.length > 0 || shouldSaveMetadata) {
await match.save({ session });
}
return match;
}
public async releaseFromMatch(
matchOrId: MatchDocument | mongoose.Types.ObjectId,
session?: mongoose.ClientSession,
): Promise<void> {
const matchId = this.resolveMatchId(matchOrId);
// Auction cancellation owns the surrounding transaction. Committing a
// separate release would survive its rollback and conflict with Match.save.
if (session) return this.releaseFromMatchInTransaction(matchOrId, session);
await this.withLockedMatchTransaction(matchId, (session) =>
this.releaseFromMatchInTransaction(matchId, session),
);
}
private async releaseFromMatchInTransaction(
matchOrId: MatchDocument | mongoose.Types.ObjectId,
session: mongoose.ClientSession,
): Promise<void> {
const MatchModel = await this.connectionService.getModel('match');
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
// Preserve the caller's document and __v when participating in its session.
const match =
matchOrId instanceof mongoose.Types.ObjectId
? await this.execQuery<MatchDocument | null>(
this.withQuerySession(MatchModel.findById(matchOrId), session),
)
: matchOrId;
if (!match) return;
if (match.tournamentCodeIds.length === 0) return;
await this.execQuery(
this.withQuerySession(
TournamentCodeModel.updateMany(
{ _id: { $in: match.tournamentCodeIds }, state: 'reserved' },
{
$set: { state: 'released', releasedAt: new Date() },
$unset: {
matchId: 1,
gameNumber: 1,
bracketMatchId: 1,
reservedAt: 1,
},
},
),
session,
),
);
match.tournamentCodeIds = [];
await match.save({ session });
}
public async markExpired(): Promise<TournamentCodeExpirationResult> {
const [TournamentCodeModel, AssignmentModel, CompetitionModel, MatchModel] =
await Promise.all([
this.connectionService.getModel('tournamentCode'),
this.connectionService.getModel('tournamentCodeAssignment'),
this.connectionService.getModel('competition'),
this.connectionService.getModel('match'),
]);
const expiredAt = new Date();
const candidates = await TournamentCodeModel.find({
state: { $in: ['available', 'reserved', 'released'] },
expiresAt: { $lte: expiredAt },
})
.select({ _id: 1 })
.lean()
.exec();
const affectedMatchIds = new Map<string, mongoose.Types.ObjectId>();
let expiredCount = 0;
let failedCount = 0;
for (const candidate of candidates) {
try {
const expired = await this.runTransactionWithRetry(async (session) => {
const code = await TournamentCodeModel.findOne(
{
_id: candidate._id,
expiresAt: { $lte: expiredAt },
state: { $in: ['available', 'reserved', 'released'] },
},
null,
{ session },
)
.lean()
.exec();
if (!code) return null;
const activeAssignments = await AssignmentModel.find({
tournamentCodeId: code._id,
state: { $in: ['reserved', 'used'] },
})
.session(session)
.limit(2)
.lean()
.exec();
if (activeAssignments.length > 1) {
throw new Error(
`Tournament Code ${code._id.toString()} has multiple active Competition assignments.`,
);
}
const assignment = activeAssignments[0];
if (assignment?.state === 'used') {
throw new Error(
`Tournament Code ${code._id.toString()} has a used Competition assignment and cannot expire as reserved.`,
);
}
if (assignment) {
if (!code.matchId) {
throw new Error(
`Tournament Code ${code._id.toString()} has an active Competition assignment without a Match binding.`,
);
}
const competition = await CompetitionModel.findById(
assignment.competitionId,
)
.session(session)
.select({ matchId: 1 })
.lean()
.exec();
if (
!competition ||
competition.matchId.toString() !== code.matchId.toString()
) {
throw new Error(
`Tournament Code ${code._id.toString()} Competition ownership does not match its Match binding.`,
);
}
}
const expiredCode = await TournamentCodeModel.findOneAndUpdate(
{
_id: code._id,
expiresAt: { $lte: expiredAt },
state: code.state,
},
{
$set: { state: 'expired' },
$unset: {
bracketMatchId: 1,
gameNumber: 1,
matchId: 1,
reservedAt: 1,
},
},
{ returnDocument: 'before', session },
).exec();
if (!expiredCode) return null;
if (assignment) {
const assignmentResult = await AssignmentModel.updateOne(
{ _id: assignment._id, state: 'reserved' },
{ $set: { releasedAt: expiredAt, state: 'released' } },
{ session },
).exec();
if (assignmentResult.modifiedCount !== 1) {
throw new Error(
`Tournament Code ${code._id.toString()} assignment did not transition to released.`,
);
}
}
if (code.matchId) {
const matchResult = await MatchModel.updateOne(
{ _id: code.matchId },
{ $pull: { tournamentCodeIds: code._id } },
{ session },
).exec();
if (
assignment &&
(matchResult.matchedCount !== 1 ||
matchResult.modifiedCount !== 1)
) {
throw new Error(
`Tournament Code ${code._id.toString()} Match binding did not transition atomically.`,
);
}
}
return code;
});
if (!expired) continue;
expiredCount += 1;
if (expired.matchId) {
affectedMatchIds.set(expired.matchId.toString(), expired.matchId);
}
} catch (error) {
failedCount += 1;
this.logger.error(
`Failed to expire Tournament Code ${candidate._id.toString()}; candidate was left unchanged: ${
error instanceof Error ? error.message : String(error)
}`,
);
}
}
return {
expiredCount,
failedCount,
affectedMatchIds: [...affectedMatchIds.values()],
};
}
public async attachPendingMatches(
communityId?: mongoose.Types.ObjectId,
): Promise<number> {
const matches = await this.attachPendingMatchDocuments(communityId);
return matches.length;
}
public async attachPendingMatchDocuments(
communityId?: mongoose.Types.ObjectId,
): Promise<MatchDocument[]> {
const MatchModel = await this.connectionService.getModel('match');
const filter: {
status: { $in: MatchDocument['status'][] };
communityId?: mongoose.Types.ObjectId;
} = {
status: { $in: ['team-built', 'in-progress'] },
};
if (communityId) filter.communityId = communityId;
const matches = await MatchModel.find(filter).exec();
const touched: MatchDocument[] = [];
for (const match of matches) {
if (!this.hasBuiltTeams(match)) continue;
if (
(match.tournamentCodeIds?.length ?? 0) >=
this.resolveRequiredSlots(match)
) {
continue;
}
const before = match.tournamentCodeIds?.length ?? 0;
const updatedMatch = await this.reserveForMatch(match);
const after = updatedMatch.tournamentCodeIds?.length ?? 0;
if (after > before) touched.push(updatedMatch);
}
return touched;
}
private hasBuiltTeams(match: MatchDocument): boolean {
return Boolean(
match.teams.length >= 2 &&
match.teams.every((team) => team.members.length > 0),
);
}
public async buildSlots(
match: MatchDocument,
): Promise<TournamentCodeSlotView[]> {
if ((match.gameMode ?? 'pair') === 'double-elimination') {
return this.buildDoubleEliminationSlots(match);
}
if (
(match.gameMode ?? 'pair') === 'round-robin' &&
(match.gameSchedule?.length ?? 0) === 0 &&
(match.tournamentCodeIds?.length ?? 0) === 0
) {
return [];
}
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const gameCount = this.resolveRequiredSlots(match);
const ids = match.tournamentCodeIds ?? [];
const codes =
ids.length > 0
? await TournamentCodeModel.find({ _id: { $in: ids } }).exec()
: [];
const byGameNumber = new Map(
codes
.filter(
(code) =>
typeof code.gameNumber === 'number' &&
(code.state === 'reserved' || code.state === 'used'),
)
.map((code) => [code.gameNumber as number, code]),
);
return Array.from({ length: gameCount }, (_, index) => {
const gameNumber = index + 1;
const code = byGameNumber.get(gameNumber);
if (!code) {
const seriesRef = this.resolveSeriesRefForGameNumber(match, gameNumber);
return {
gameNumber,
roundNumber: this.resolveRoundNumberForGameNumber(match, gameNumber),
...seriesRef,
code: null,
expiresAt: null,
state: 'pending',
riotMatchId: null,
};
}
return {
gameNumber,
roundNumber: this.resolveRoundNumberForGameNumber(match, gameNumber),
...this.resolveSeriesRefForGameNumber(match, gameNumber),
code: code.code,
expiresAt: code.expiresAt.toISOString(),
state: code.state,
riotMatchId: code.riotMatchId ?? null,
};
});
}
private normalizeCode(code: string | undefined): string {
return (code ?? '').trim();
}
private resolveMatchId(
matchOrId: MatchDocument | mongoose.Types.ObjectId,
): mongoose.Types.ObjectId {
return matchOrId instanceof mongoose.Types.ObjectId
? matchOrId
: matchOrId._id;
}
private async withLockedMatchTransaction<T>(
matchId: mongoose.Types.ObjectId,
operation: (session: mongoose.ClientSession) => Promise<T>,
): Promise<T> {
const lockKey = this.matchCodeLockKey(matchId);
const token = randomUUID();
const acquired = await this.auctionRedisService.acquireTokenLock(
lockKey,
token,
TOURNAMENT_CODE_MATCH_LOCK_TTL_MS,
);
if (!acquired) {
throw new ConflictException(
'Tournament code operation is already running for this match.',
);
}
try {
return await this.runTransactionWithRetry(operation);
} finally {
await this.auctionRedisService.releaseTokenLock(lockKey, token);
}
}
private async runTransactionWithRetry<T>(
operation: (session: mongoose.ClientSession) => Promise<T>,
): Promise<T> {
let lastError: unknown;
for (
let attempt = 1;
attempt <= TOURNAMENT_CODE_TRANSACTION_ATTEMPTS;
attempt += 1
) {
const session = await this.connectionService.createSession();
if (!session) {
throw new InternalServerErrorException('Failed to start DB session.');
}
try {
session.startTransaction();
const result = await operation(session);
await session.commitTransaction();
return result;
} catch (error) {
lastError = error;
await session.abortTransaction().catch(() => undefined);
if (
attempt >= TOURNAMENT_CODE_TRANSACTION_ATTEMPTS ||
!this.isRetryableTransactionError(error)
) {
throw error;
}
} finally {
await session.endSession().catch(() => undefined);
}
}
throw lastError;
}
private isRetryableTransactionError(error: unknown): boolean {
const candidate = error as {
code?: number;
codeName?: string;
hasErrorLabel?: (label: string) => boolean;
};
return Boolean(
candidate?.hasErrorLabel?.('TransientTransactionError') ||
candidate?.hasErrorLabel?.('UnknownTransactionCommitResult') ||
candidate?.code === 112 ||
candidate?.codeName === 'WriteConflict',
);
}
private matchCodeLockKey(matchId: mongoose.Types.ObjectId): string {
return `tournament-code:match:${matchId.toString()}:lock`;
}
private withQuerySession<T>(query: T, session: mongoose.ClientSession): T {
const maybeQuery = query as {
session?: (session: mongoose.ClientSession) => T;
};
if (maybeQuery && typeof maybeQuery.session === 'function') {
return maybeQuery.session(session);
}
return query;
}
private async execQuery<T = unknown>(query: unknown): Promise<T> {
const maybeQuery = query as { exec?: () => Promise<T> };
if (maybeQuery && typeof maybeQuery.exec === 'function') {
return maybeQuery.exec();
}
return query as Promise<T>;
}
private async reserveForDoubleEliminationMatch(
match: MatchDocument,
TournamentCodeModel: mongoose.Model<TournamentCode>,
session: mongoose.ClientSession,
): Promise<MatchDocument> {
const readySlots = buildDoubleEliminationGameSlots(
match.doubleElimination?.bracketMatches ?? [],
).filter((slot) => slot.bracketMatch.state === 'ready');
const existingCodes =
match.tournamentCodeIds.length > 0
? await this.execQuery<TournamentCodeDocument[]>(
this.withQuerySession(
TournamentCodeModel.find({
_id: { $in: match.tournamentCodeIds },
}),
session,
),
)
: [];
const byGameNumber = new Map(
existingCodes
.filter(
(code) =>
typeof code.gameNumber === 'number' &&
(code.state === 'reserved' || code.state === 'used'),
)
.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 slot of readySlots) {
if (byGameNumber.has(slot.gameNumber)) continue;
const code = await TournamentCodeModel.findOneAndUpdate(
{
state: 'available',
region: DEFAULT_REGION,
mapType: 'SUMMONERS_RIFT',
teamSize: 5,
expiresAt: { $gt: expiresAfter },
},
{
$set: {
state: 'reserved',
matchId: match._id,
gameNumber: slot.gameNumber,
bracketMatchId: slot.bracketMatch.bracketMatchId,
reservedAt: new Date(),
},
$unset: { releasedAt: 1 },
},
{ sort: { expiresAt: 1 }, returnDocument: 'after', session },
).exec();
if (!code) break;
reservedIds.push(code._id);
byGameNumber.set(slot.gameNumber, code);
}
if (reservedIds.length > 0) {
match.tournamentCodeIds.push(...reservedIds);
}
if (
reservedIds.length > 0 ||
this.isMatchModified(match, 'doubleElimination')
) {
await match.save({ session });
}
return match;
}
private async buildDoubleEliminationSlots(
match: MatchDocument,
): Promise<TournamentCodeSlotView[]> {
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 ?? [];
const codes =
ids.length > 0
? await TournamentCodeModel.find({ _id: { $in: ids } }).exec()
: [];
const byGameNumber = new Map(
codes
.filter(
(code) =>
typeof code.gameNumber === 'number' &&
code.state !== 'released' &&
code.state !== 'voided',
)
.map((code) => [code.gameNumber as number, code]),
);
return slots.map((slot) => {
const code = byGameNumber.get(slot.gameNumber);
return {
...this.toDoubleEliminationSlotBase(slot),
code: code?.code ?? null,
expiresAt: code?.expiresAt.toISOString() ?? null,
state: code?.state ?? 'pending',
riotMatchId: code?.riotMatchId ?? null,
};
});
}
private toDoubleEliminationSlotBase(
slot: DoubleEliminationGameSlot,
): Omit<
TournamentCodeSlotView,
'code' | 'expiresAt' | 'state' | 'riotMatchId'
> {
const bracketMatch = slot.bracketMatch;
return {
gameNumber: slot.gameNumber,
seriesGameNumber: slot.seriesGameNumber,
seriesGameCount: slot.seriesGameCount,
seriesRequiredWins: slot.seriesRequiredWins,
bracketMatchId: bracketMatch.bracketMatchId,
bracketSide: bracketMatch.bracketSide,
roundNumber: bracketMatch.roundNumber,
matchNumber: bracketMatch.matchNumber,
teamAIndex: bracketMatch.teamAIndex,
teamBIndex: bracketMatch.teamBIndex,
};
}
private resolveRequiredSlots(match: MatchDocument): number {
const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
const gameMode = match.gameMode ?? 'pair';
if (gameMode === 'double-elimination') {
return buildDoubleEliminationGameSlots(
match.doubleElimination?.bracketMatches ?? [],
).length;
}
if (gameMode === 'round-robin') {
if ((match.gameSchedule?.length ?? 0) > 0) {
return match.gameSchedule.length;
}
return this.buildRoundRobinGameSchedule(match).length;
}
const teamCount = (match.teams ?? []).length;
const activeParticipantCount = (match.participants ?? []).filter(
(participant) => !participant.excluded,
).length;
const participantSeriesCount = Math.floor(activeParticipantCount / 10);
const teamSeriesCount = Math.ceil(teamCount / 2);
const seriesCount = Math.max(1, teamSeriesCount, participantSeriesCount);
return seriesCount * gameCount;
}
private resolveSeriesRefForGameNumber(
match: MatchDocument,
gameNumber: number,
): { teamAIndex: number; teamBIndex: number } {
const gameMode = match.gameMode ?? 'pair';
if (gameMode === 'double-elimination') {
const slot = this.resolveDoubleEliminationGameSlotByGameNumber(
match,
gameNumber,
);
return {
teamAIndex: slot?.bracketMatch.teamAIndex ?? 1,
teamBIndex: slot?.bracketMatch.teamBIndex ?? 2,
};
}
if (gameMode === 'round-robin') {
const persisted = match.gameSchedule?.find(
(entry) => entry.gameNumber === gameNumber,
);
if (persisted) {
return {
teamAIndex: persisted.teamAIndex,
teamBIndex: persisted.teamBIndex,
};
}
const fallback = this.buildRoundRobinGameSchedule(match).find(
(entry) => entry.gameNumber === gameNumber,
);
return fallback
? {
teamAIndex: fallback.teamAIndex,
teamBIndex: fallback.teamBIndex,
}
: {
teamAIndex: 1,
teamBIndex: 2,
};
}
const perSeries = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
const seriesIndex = Math.max(1, Math.ceil(gameNumber / perSeries));
return {
teamAIndex: (seriesIndex - 1) * 2 + 1,
teamBIndex: (seriesIndex - 1) * 2 + 2,
};
}
private ensureGameSchedule(match: MatchDocument): void {
if ((match.gameMode ?? 'pair') === 'double-elimination') {
this.ensureDoubleEliminationBracket(match);
return;
}
if ((match.gameMode ?? 'pair') !== 'round-robin') return;
if ((match.gameSchedule?.length ?? 0) > 0) return;
const teamCount = resolveRoundRobinTeamCount(match);
if (teamCount < 2) return;
match.gameSchedule = this.buildRoundRobinGameSchedule(match);
}
private ensureDoubleEliminationBracket(match: MatchDocument): void {
if ((match.doubleElimination?.bracketMatches.length ?? 0) > 0) return;
const teamIndexes = [...(match.teams ?? [])]
.map((team) => team.teamIndex)
.sort((left, right) => left - right);
if (teamIndexes.length !== 4 && teamIndexes.length !== 8) return;
const seededTeamIndexes = this.configuredDoubleEliminationSeedOrder(
match,
teamIndexes,
);
const shuffledTeamIndexes =
seededTeamIndexes ?? this.shuffleTeamIndexes(teamIndexes);
match.doubleElimination = buildDoubleEliminationBracket(
shuffledTeamIndexes,
{
resetFinalEnabled: match.doubleElimination?.resetFinalEnabled ?? false,
grandFinalGameCount: match.doubleElimination?.grandFinalGameCount,
winnerBracketGameCount:
match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT,
},
);
match.markModified?.('doubleElimination');
}
private configuredDoubleEliminationSeedOrder(
match: MatchDocument,
teamIndexes: number[],
): number[] | undefined {
const seeds = match.doubleElimination?.seeds ?? [];
if (seeds.length !== teamIndexes.length) return undefined;
const validTeamIndexes = new Set(teamIndexes);
const seedNumbers = new Set<number>();
const seededTeamIndexes = new Set<number>();
for (const seed of seeds) {
if (
!Number.isInteger(seed.seedNumber) ||
seed.seedNumber < 1 ||
seed.seedNumber > teamIndexes.length ||
seedNumbers.has(seed.seedNumber) ||
!validTeamIndexes.has(seed.teamIndex) ||
seededTeamIndexes.has(seed.teamIndex)
) {
return undefined;
}
seedNumbers.add(seed.seedNumber);
seededTeamIndexes.add(seed.teamIndex);
}
return [...seeds]
.sort((left, right) => left.seedNumber - right.seedNumber)
.map(({ teamIndex }) => teamIndex);
}
private resolveDoubleEliminationGameSlotByGameNumber(
match: MatchDocument,
gameNumber: number,
): DoubleEliminationGameSlot | undefined {
return buildDoubleEliminationGameSlots(
match.doubleElimination?.bracketMatches ?? [],
).find((slot) => slot.gameNumber === gameNumber);
}
private shuffleTeamIndexes(teamIndexes: number[]): number[] {
const shuffled = [...teamIndexes];
for (let index = shuffled.length - 1; index > 0; index -= 1) {
const swapIndex = Math.floor(Math.random() * (index + 1));
[shuffled[index], shuffled[swapIndex]] = [
shuffled[swapIndex],
shuffled[index],
];
}
return shuffled;
}
private isMatchModified(match: MatchDocument, path: string): boolean {
return typeof match.isModified === 'function' && match.isModified(path);
}
private resolveRoundNumberForGameNumber(
match: MatchDocument,
gameNumber: number,
): number | undefined {
if ((match.gameMode ?? 'pair') !== 'round-robin') return undefined;
const persisted = match.gameSchedule?.find(
(entry) => entry.gameNumber === gameNumber,
);
if (persisted) return persisted.roundNumber;
return this.buildRoundRobinGameSchedule(match).find(
(entry) => entry.gameNumber === gameNumber,
)?.roundNumber;
}
private buildRoundRobinGameSchedule(
match: MatchDocument,
shuffleTeams = false,
): MatchGameAssignment[] {
return roundRobinGameSchedule(resolveRoundRobinTeamCount(match), {
gamesPerPair: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT,
maxRounds: match.roundRobinMaxRounds,
shuffleTeams,
});
}
}