1058 lines
32 KiB
TypeScript
1058 lines
32 KiB
TypeScript
import {
|
|
BadRequestException,
|
|
ConflictException,
|
|
Injectable,
|
|
InternalServerErrorException,
|
|
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;
|
|
|
|
@Injectable()
|
|
export class TournamentCodeService {
|
|
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' && code.state !== 'reserved') {
|
|
throw new BadRequestException(
|
|
'Only released or reserved tournament codes can be restored.',
|
|
);
|
|
}
|
|
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 replaceForMatchGame(params: {
|
|
communityId: mongoose.Types.ObjectId;
|
|
matchId: mongoose.Types.ObjectId;
|
|
gameNumber: number;
|
|
}): Promise<TournamentCodeSlotView> {
|
|
return this.withLockedMatchTransaction(params.matchId, (session) =>
|
|
this.replaceForMatchGameInTransaction(params, session),
|
|
);
|
|
}
|
|
|
|
private async replaceForMatchGameInTransaction(
|
|
params: {
|
|
communityId: mongoose.Types.ObjectId;
|
|
matchId: mongoose.Types.ObjectId;
|
|
gameNumber: number;
|
|
},
|
|
session: mongoose.ClientSession,
|
|
): Promise<TournamentCodeSlotView> {
|
|
const MatchModel = await this.connectionService.getModel('match');
|
|
const TournamentCodeModel =
|
|
await this.connectionService.getModel('tournamentCode');
|
|
const match = await this.execQuery<MatchDocument | null>(
|
|
this.withQuerySession(
|
|
MatchModel.findOne({
|
|
_id: params.matchId,
|
|
communityId: params.communityId,
|
|
}),
|
|
session,
|
|
),
|
|
);
|
|
if (!match) throw new NotFoundException('Match not found.');
|
|
if (match.status !== 'team-built' && match.status !== 'in-progress') {
|
|
throw new BadRequestException(
|
|
'Tournament codes can only be replaced while the match is ready or in progress.',
|
|
);
|
|
}
|
|
|
|
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
|
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
|
|
this.ensureGameSchedule(match);
|
|
const doubleEliminationSlot =
|
|
(match.gameMode ?? 'pair') === 'double-elimination'
|
|
? this.resolveDoubleEliminationGameSlotByGameNumber(
|
|
match,
|
|
params.gameNumber,
|
|
)
|
|
: undefined;
|
|
|
|
const requiredSlots = this.resolveRequiredSlots(match);
|
|
if (
|
|
!Number.isInteger(params.gameNumber) ||
|
|
params.gameNumber < 1 ||
|
|
params.gameNumber > requiredSlots
|
|
) {
|
|
throw new BadRequestException('Invalid tournament code game number.');
|
|
}
|
|
if (
|
|
(match.result?.games ?? []).some(
|
|
(game) => game.gameNumber === params.gameNumber,
|
|
)
|
|
) {
|
|
throw new BadRequestException(
|
|
'This game already has a collected result and cannot be replaced.',
|
|
);
|
|
}
|
|
|
|
const currentCode = await this.execQuery<TournamentCodeDocument | null>(
|
|
this.withQuerySession(
|
|
TournamentCodeModel.findOne({
|
|
_id: { $in: match.tournamentCodeIds },
|
|
matchId: match._id,
|
|
...(doubleEliminationSlot
|
|
? {
|
|
gameNumber: params.gameNumber,
|
|
bracketMatchId:
|
|
doubleEliminationSlot.bracketMatch.bracketMatchId,
|
|
}
|
|
: { gameNumber: params.gameNumber }),
|
|
}),
|
|
session,
|
|
),
|
|
);
|
|
if (!currentCode) {
|
|
throw new NotFoundException('Assigned tournament code not found.');
|
|
}
|
|
if (currentCode.state === 'used' || currentCode.riotMatchId) {
|
|
throw new BadRequestException(
|
|
'Used tournament codes cannot be replaced.',
|
|
);
|
|
}
|
|
|
|
const expiresAfter = new Date(
|
|
Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS,
|
|
);
|
|
await this.execQuery(
|
|
this.withQuerySession(
|
|
TournamentCodeModel.updateOne(
|
|
{ _id: currentCode._id },
|
|
{
|
|
$set: { state: 'released', releasedAt: new Date() },
|
|
$unset: {
|
|
matchId: 1,
|
|
gameNumber: 1,
|
|
bracketMatchId: 1,
|
|
reservedAt: 1,
|
|
riotMatchId: 1,
|
|
},
|
|
},
|
|
),
|
|
session,
|
|
),
|
|
);
|
|
|
|
const replacement = await TournamentCodeModel.findOneAndUpdate(
|
|
{
|
|
state: 'available',
|
|
region: DEFAULT_REGION,
|
|
mapType: 'SUMMONERS_RIFT',
|
|
teamSize: 5,
|
|
expiresAt: { $gt: expiresAfter },
|
|
},
|
|
{
|
|
$set: {
|
|
state: 'reserved',
|
|
matchId: match._id,
|
|
gameNumber: params.gameNumber,
|
|
...(doubleEliminationSlot
|
|
? {
|
|
bracketMatchId:
|
|
doubleEliminationSlot.bracketMatch.bracketMatchId,
|
|
}
|
|
: {}),
|
|
reservedAt: new Date(),
|
|
},
|
|
$unset: { releasedAt: 1 },
|
|
},
|
|
{ sort: { expiresAt: 1 }, returnDocument: 'after', session },
|
|
).exec();
|
|
if (!replacement) {
|
|
throw new BadRequestException(
|
|
'No available tournament code to replace with.',
|
|
);
|
|
}
|
|
|
|
match.tournamentCodeIds = this.replaceTournamentCodeId(
|
|
match.tournamentCodeIds,
|
|
currentCode._id,
|
|
replacement._id,
|
|
);
|
|
await match.save({ session });
|
|
|
|
return {
|
|
gameNumber: params.gameNumber,
|
|
...(doubleEliminationSlot
|
|
? this.toDoubleEliminationSlotBase(doubleEliminationSlot)
|
|
: {}),
|
|
roundNumber: this.resolveRoundNumberForGameNumber(
|
|
match,
|
|
params.gameNumber,
|
|
),
|
|
...this.resolveSeriesRefForGameNumber(match, params.gameNumber),
|
|
code: replacement.code,
|
|
expiresAt: replacement.expiresAt.toISOString(),
|
|
state: replacement.state,
|
|
riotMatchId: replacement.riotMatchId ?? null,
|
|
};
|
|
}
|
|
|
|
public async releaseFromMatch(
|
|
matchOrId: MatchDocument | mongoose.Types.ObjectId,
|
|
): Promise<void> {
|
|
const matchId = this.resolveMatchId(matchOrId);
|
|
await this.withLockedMatchTransaction(matchId, (session) =>
|
|
this.releaseFromMatchInTransaction(matchId, session),
|
|
);
|
|
}
|
|
|
|
private async releaseFromMatchInTransaction(
|
|
matchId: mongoose.Types.ObjectId,
|
|
session: mongoose.ClientSession,
|
|
): Promise<void> {
|
|
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) 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<number> {
|
|
const TournamentCodeModel =
|
|
await this.connectionService.getModel('tournamentCode');
|
|
const result = await TournamentCodeModel.updateMany(
|
|
{
|
|
state: { $in: ['available', 'reserved', 'released'] },
|
|
expiresAt: { $lte: new Date() },
|
|
},
|
|
{ $set: { state: 'expired' } },
|
|
).exec();
|
|
return result.modifiedCount;
|
|
}
|
|
|
|
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: string[] };
|
|
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')
|
|
.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 replaceTournamentCodeId(
|
|
currentIds: mongoose.Types.ObjectId[],
|
|
oldId: mongoose.Types.ObjectId,
|
|
newId: mongoose.Types.ObjectId,
|
|
): mongoose.Types.ObjectId[] {
|
|
let replaced = false;
|
|
const next = currentIds.map((id) => {
|
|
if (id.toString() !== oldId.toString()) return id;
|
|
replaced = true;
|
|
return newId;
|
|
});
|
|
if (!replaced) next.push(newId);
|
|
return next;
|
|
}
|
|
|
|
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 shuffledTeamIndexes = this.shuffleTeamIndexes(teamIndexes);
|
|
match.doubleElimination = buildDoubleEliminationBracket(
|
|
shuffledTeamIndexes,
|
|
{
|
|
resetFinalEnabled: match.doubleElimination?.resetFinalEnabled ?? false,
|
|
winnerBracketGameCount:
|
|
match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT,
|
|
},
|
|
);
|
|
match.markModified?.('doubleElimination');
|
|
}
|
|
|
|
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,
|
|
});
|
|
}
|
|
}
|