feat(api): collect tournament results

This commit is contained in:
dahyeon committed 2026-04-29 00:44:00 +09:00
1 parent 45c7fe34ca
commit 57e3c68ea8
8 files changed
+1645

No files matched your search

@@ -0,0 +1,933 @@
import {
BadRequestException,
Injectable,
Logger,
NotFoundException,
} from '@nestjs/common';
import mongoose from 'mongoose';
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,
RiotMatch as StoredRiotMatch,
TournamentCodeDocument,
} from '../global/database/schema';
import { RiotJobQueueService } from '../riot-job-queue/riot-job-queue.service';
import type { RiotJobPriority } from '../riot-job-queue/riot-job-queue.types';
import { RiotMatchService } from '../riot/riot-match.service';
import type { RiotMatchDto, RiotRegionalRoute } from '../riot/riot.types';
import {
resolveRoundRobinTeamCount,
roundRobinPairCount,
roundRobinPairs,
} from '../tournament-code/round-robin.util';
import {
collectCaptainUserIds,
collectMatchUserIds,
computeGameResult,
type MatchPuuidLookup,
} from './team-mapping.util';
import type {
EnqueueTournamentResultPollResult,
ManualTournamentResultCollectResponse,
PollTournamentResultJob,
} from './tournament-result.types';
const FIRST_HOUR_POLL_DELAY_MS = 5 * 60_000;
const LATER_POLL_DELAY_MS = 60 * 60_000;
const POLL_EXPIRY_MS = 24 * 60 * 60_000;
const EXPAND_AFTER_MS = 60 * 60_000;
const TOURNAMENT_LOOKUP_START_MARGIN_SECONDS = 60;
interface ManualGameAssignment {
gameNumber: number;
teamAIndex: number;
teamBIndex: number;
}
@Injectable()
export class TournamentResultService {
private readonly logger = new Logger(TournamentResultService.name);
constructor(
private readonly connectionService: ConnectionService,
private readonly riotMatchService: RiotMatchService,
private readonly riotJobQueueService: RiotJobQueueService,
private readonly communityStatsService: CommunityStatsService,
private readonly matchStatsService: MatchStatsService,
) {}
public async scheduleInitialPoll(
matchOrId: MatchDocument | mongoose.Types.ObjectId,
priority: RiotJobPriority = 'high',
): Promise<EnqueueTournamentResultPollResult | null> {
const match = await this.loadMatch(matchOrId);
if (match.status === 'finished') return null;
if (!this.isReadyToPoll(match)) return null;
match.resultPollState = {
startedAt: match.resultPollState?.startedAt ?? new Date(),
lastPolledAt: match.resultPollState?.lastPolledAt,
lastPollOutcome: match.resultPollState?.lastPollOutcome,
matchedCount: match.result?.games?.length ?? 0,
expandedToAllPuuids: false,
state: 'polling',
};
await match.save();
return this.riotJobQueueService.enqueueTournamentResultPoll({
matchId: match._id.toString(),
attempt: 1,
expandedToAllPuuids: false,
priority,
});
}
public async scheduleManualPoll(params: {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
}): Promise<EnqueueTournamentResultPollResult> {
const match = await this.loadMatch(params.matchId);
if (!match.communityId.equals(params.communityId)) {
throw new BadRequestException('Match does not belong to this community.');
}
if (!this.isReadyToPoll(match)) {
throw new BadRequestException(
'Match needs built teams, teamBuiltAt, and tournament codes before polling.',
);
}
const result = await this.scheduleInitialPoll(match, 'high');
if (!result) {
throw new BadRequestException(
'Tournament result polling is not available.',
);
}
return result;
}
public async collectManualByWindow(params: {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
startTime: Date;
endTime: Date;
}): Promise<ManualTournamentResultCollectResponse> {
const match = await this.loadMatch(params.matchId);
this.assertManualCollectionAllowed(match, params.communityId);
if (params.startTime.getTime() > params.endTime.getTime()) {
throw new BadRequestException(
'startTime must be less than or equal to endTime.',
);
}
const region = await this.resolveRiotRegion(match);
const lookup = await this.buildPuuidLookup(match);
const puuids = this.collectPollingPuuids(
collectMatchUserIds(match),
lookup,
);
const startTime = Math.floor(params.startTime.getTime() / 1000);
const endTime = Math.floor(params.endTime.getTime() / 1000);
const riotMatchIds = new Set<string>();
for (const puuid of puuids) {
try {
const ids = await this.riotMatchService.getMatchIdsByPuuid(puuid, {
region,
startTime,
endTime,
count: 100,
});
ids.forEach((id) => riotMatchIds.add(id));
} catch (error) {
this.logger.warn(
`Manual result match id lookup failed for ${puuid}: ${
error instanceof Error ? error.message : error
}`,
);
}
}
const details = await this.loadRiotMatchDetails(
[...riotMatchIds],
region,
'Manual result detail fetch failed',
);
return this.applyManualRiotMatches(match, details, lookup);
}
public async collectManualByRiotMatch(params: {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
riotMatchId: string;
}): Promise<ManualTournamentResultCollectResponse> {
const match = await this.loadMatch(params.matchId);
this.assertManualCollectionAllowed(match, params.communityId);
const normalizedRiotMatchId = params.riotMatchId.trim();
if (!normalizedRiotMatchId) {
throw new BadRequestException('riotMatchId is required.');
}
const region = await this.resolveRiotRegion(match);
const lookup = await this.buildPuuidLookup(match);
const detail = await this.ensureRiotMatchPersisted(
normalizedRiotMatchId,
region,
);
return this.applyManualRiotMatches(match, [detail], lookup);
}
public async cancelPolling(
matchOrId: MatchDocument | mongoose.Types.ObjectId,
): Promise<void> {
const match = await this.loadMatch(matchOrId);
match.resultPollState = undefined;
await match.save();
}
public async processPollJob(job: PollTournamentResultJob): Promise<void> {
const MatchModel = await this.connectionService.getModel('match');
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const CommunityModel = await this.connectionService.getModel('community');
const match = await MatchModel.findById(job.matchId);
if (!match || match.status === 'finished') return;
if (!this.isReadyToPoll(match)) {
await this.updatePollState(match, 'failed', job.expandedToAllPuuids);
return;
}
const codes = await TournamentCodeModel.find({ matchId: match._id })
.sort({ gameNumber: 1 })
.exec();
const unmatched = codes.filter(
(code) => code.state === 'reserved' && !code.riotMatchId,
);
if (unmatched.length === 0) {
await this.advanceMatchIfReady(match, codes);
return;
}
const community = await CommunityModel.findById(match.communityId)
.select({ riotRegion: 1 })
.lean()
.exec();
const region = community?.riotRegion ?? 'asia';
const lookup = await this.buildPuuidLookup(match);
const puuids = job.expandedToAllPuuids
? this.collectPollingPuuids(collectMatchUserIds(match), lookup)
: this.collectPollingPuuids(collectCaptainUserIds(match), lookup);
const matchedGameNumbers = new Set<number>();
const checkedRiotMatchIds = new Set<string>();
const unmatchedByCode = new Map(unmatched.map((code) => [code.code, code]));
for (const puuid of puuids) {
let ids: string[];
try {
ids = await this.riotMatchService.getMatchIdsByPuuid(puuid, {
region,
type: 'tourney',
startTime: this.resolveStartTime(match),
endTime: Math.floor(Date.now() / 1000),
count: 100,
});
} catch (error) {
this.logger.warn(
`Tournament result match id lookup failed for ${puuid}: ${
error instanceof Error ? error.message : error
}`,
);
continue;
}
for (const riotMatchId of ids) {
if (checkedRiotMatchIds.has(riotMatchId)) continue;
checkedRiotMatchIds.add(riotMatchId);
const alreadyMatched = await TournamentCodeModel.exists({
riotMatchId,
});
if (alreadyMatched) continue;
let detail: RiotMatchDto;
try {
detail = await this.ensureRiotMatchPersisted(riotMatchId, region);
} catch (error) {
this.logger.warn(
`Tournament result detail fetch failed for ${riotMatchId}: ${
error instanceof Error ? error.message : error
}`,
);
continue;
}
const tournamentCode = detail.info.tournamentCode?.trim().toUpperCase();
if (!tournamentCode) continue;
const code = unmatchedByCode.get(tournamentCode);
if (!code) continue;
const applied = await this.applyMatchToGameSlot({
match,
code,
detail,
lookup,
});
if (applied) {
matchedGameNumbers.add(code.gameNumber ?? 0);
unmatchedByCode.delete(tournamentCode);
}
}
}
const reloadedCodes = await TournamentCodeModel.find({ matchId: match._id })
.sort({ gameNumber: 1 })
.exec();
const outcome = matchedGameNumbers.size > 0 ? 'matched' : 'not-found';
await this.updatePollState(match, outcome, job.expandedToAllPuuids);
const completed = await this.advanceMatchIfReady(match, reloadedCodes);
if (!completed) {
await this.scheduleNextPoll(match, job);
}
}
private async applyMatchToGameSlot(params: {
match: MatchDocument;
code: TournamentCodeDocument;
detail: RiotMatchDto;
lookup: MatchPuuidLookup;
}): Promise<boolean> {
const { match, code, detail, lookup } = params;
if (code.state !== 'reserved' || code.riotMatchId) return false;
if (!code.gameNumber) return false;
const gameResult = computeGameResult({
match,
detail,
gameNumber: code.gameNumber,
lookup,
...this.resolveSeriesRefForGameNumber(match, code.gameNumber),
});
if (!gameResult) {
this.logger.warn(
`Skipped tournament result ${detail.metadata.matchId}; team mapping was not trusted for match ${match._id.toString()}.`,
);
return false;
}
code.state = 'used';
code.usedAt = new Date(
detail.info.gameEndTimestamp ?? detail.info.gameCreation,
);
code.riotMatchId = detail.metadata.matchId;
await code.save();
this.upsertGameResult(match, gameResult);
if (match.status === 'team-built') {
match.status = 'in-progress';
}
await match.save();
await this.rebuildMatchStatsSafe(match);
return true;
}
private async applyManualRiotMatches(
match: MatchDocument,
details: RiotMatchDto[],
lookup: MatchPuuidLookup,
): Promise<ManualTournamentResultCollectResponse> {
const sortedDetails = [...details].sort(
(left, right) => left.info.gameCreation - right.info.gameCreation,
);
const appliedRiotMatchIds: string[] = [];
const appliedGameNumbers: number[] = [];
let skipped = 0;
for (const detail of sortedDetails) {
if (this.hasResultForRiotMatch(match, detail.metadata.matchId)) {
skipped += 1;
continue;
}
const gameResult = this.computeManualGameResult(match, detail, lookup);
if (!gameResult) {
skipped += 1;
continue;
}
this.upsertGameResult(match, gameResult);
await this.markTournamentCodeUsedForManualResult(
match,
gameResult,
detail,
);
appliedRiotMatchIds.push(detail.metadata.matchId);
appliedGameNumbers.push(gameResult.gameNumber);
}
if (appliedRiotMatchIds.length > 0 && match.status === 'team-built') {
match.status = 'in-progress';
}
this.updateManualCollectionState(match, appliedRiotMatchIds.length);
await match.save();
if (appliedRiotMatchIds.length > 0) {
await this.rebuildMatchStatsSafe(match);
}
if (this.hasAllRequiredGameResults(match)) {
await this.finishMatchFromManualResults(match);
}
return {
scanned: sortedDetails.length,
matched: appliedRiotMatchIds.length,
skipped,
riotMatchIds: appliedRiotMatchIds,
gameNumbers: appliedGameNumbers,
};
}
private async advanceMatchIfReady(
match: MatchDocument,
codes: TournamentCodeDocument[],
): Promise<boolean> {
if (codes.length < this.resolveRequiredGameSlots(match)) return false;
if (!codes.every((code) => code.state === 'used' && code.riotMatchId)) {
return false;
}
match.status = 'finished';
if (match.result) {
match.result.winnerTeamIndex = this.resolveMatchWinnerTeamIndex(
match.result.seriesResults ?? [],
);
}
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;
}
private async scheduleNextPoll(
match: MatchDocument,
job: PollTournamentResultJob,
): Promise<void> {
const pollState = match.resultPollState;
const startedAt = pollState?.startedAt ?? new Date();
const elapsedMs = Date.now() - startedAt.getTime();
const delayMs = this.nextPollDelayMs(elapsedMs);
if (delayMs === null) {
match.resultPollState = {
startedAt,
lastPolledAt: pollState?.lastPolledAt,
lastPollOutcome: pollState?.lastPollOutcome,
matchedCount: match.result?.games?.length ?? 0,
expandedToAllPuuids:
pollState?.expandedToAllPuuids ?? job.expandedToAllPuuids,
state: 'expired',
};
await match.save();
this.logger.warn(
`Tournament result polling expired for match ${match._id.toString()}.`,
);
return;
}
const expandedToAllPuuids =
job.expandedToAllPuuids ||
(elapsedMs >= EXPAND_AFTER_MS &&
(match.result?.games?.length ?? 0) === 0);
await this.riotJobQueueService.enqueueTournamentResultPoll({
matchId: match._id.toString(),
attempt: job.attempt + 1,
expandedToAllPuuids,
priority: 'low',
deferUntilMs: Date.now() + delayMs,
});
}
private async ensureRiotMatchPersisted(
riotMatchId: string,
region: RiotRegionalRoute,
): Promise<RiotMatchDto> {
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const stored = await RiotMatchModel.findOne({
matchId: riotMatchId,
}).exec();
if (isRiotMatchDto(stored?.raw)) return stored.raw;
const dto = await this.riotMatchService.getMatch(riotMatchId, { region });
const payload: Partial<StoredRiotMatch> = {
matchId: dto.metadata.matchId,
gameCreation: dto.info.gameCreation,
gameDuration: dto.info.gameDuration,
gameVersion: dto.info.gameVersion,
queueId: dto.info.queueId,
participantPuuids: dto.metadata.participants,
raw: dto as unknown as Record<string, unknown>,
fetchedAt: new Date(),
};
await RiotMatchModel.updateOne(
{ matchId: dto.metadata.matchId },
{ $setOnInsert: payload },
{ upsert: true },
).exec();
return dto;
}
private async loadRiotMatchDetails(
riotMatchIds: string[],
region: RiotRegionalRoute,
logPrefix: string,
): Promise<RiotMatchDto[]> {
const details: RiotMatchDto[] = [];
const checked = new Set<string>();
for (const riotMatchId of riotMatchIds) {
if (checked.has(riotMatchId)) continue;
checked.add(riotMatchId);
try {
details.push(await this.ensureRiotMatchPersisted(riotMatchId, region));
} catch (error) {
this.logger.warn(
`${logPrefix} ${riotMatchId}: ${
error instanceof Error ? error.message : error
}`,
);
}
}
return details;
}
private async buildPuuidLookup(
match: MatchDocument,
): Promise<MatchPuuidLookup> {
const puuidByUserId = new Map<string, string>();
const userIdByPuuid = new Map<string, mongoose.Types.ObjectId>();
for (const participant of match.participants) {
if (!participant.puuid) continue;
const userId = participant.userId.toString();
puuidByUserId.set(userId, participant.puuid);
userIdByPuuid.set(participant.puuid, participant.userId);
}
const missingUserIds = collectMatchUserIds(match).filter(
(userId) => !puuidByUserId.has(userId.toString()),
);
if (missingUserIds.length > 0) {
const UserModel = await this.connectionService.getModel('user');
const users = await UserModel.find({ _id: { $in: missingUserIds } })
.select({ riotAccounts: 1 })
.exec();
for (const user of users) {
const primary =
user.riotAccounts.find((account) => account.isPrimary) ??
user.riotAccounts[0];
if (!primary) continue;
puuidByUserId.set(user._id.toString(), primary.puuid);
userIdByPuuid.set(primary.puuid, user._id);
}
}
return { puuidByUserId, userIdByPuuid };
}
private collectPollingPuuids(
userIds: mongoose.Types.ObjectId[],
lookup: MatchPuuidLookup,
): string[] {
return [
...new Set(
userIds
.map((userId) => lookup.puuidByUserId.get(userId.toString()))
.filter((puuid): puuid is string => Boolean(puuid)),
),
];
}
private upsertGameResult(
match: MatchDocument,
gameResult: MatchGameResult,
): void {
const currentGames = match.result?.games ?? [];
const games = [
...currentGames.filter(
(game) =>
game.gameNumber !== gameResult.gameNumber &&
game.riotMatchId !== gameResult.riotMatchId,
),
gameResult,
].sort((left, right) => left.gameNumber - right.gameNumber);
const seriesResults = this.buildSeriesResults(games);
match.result = {
winnerTeamIndex: this.resolveMatchWinnerTeamIndex(seriesResults),
mvpUserId: match.result?.mvpUserId,
riotMatchIds: [...new Set(games.map((game) => game.riotMatchId))],
games,
seriesResults,
};
}
private computeManualGameResult(
match: MatchDocument,
detail: RiotMatchDto,
lookup: MatchPuuidLookup,
): MatchGameResult | null {
for (const assignment of this.resolveOpenManualGameAssignments(match)) {
const gameResult = computeGameResult({
match,
detail,
gameNumber: assignment.gameNumber,
lookup,
teamAIndex: assignment.teamAIndex,
teamBIndex: assignment.teamBIndex,
});
if (gameResult) return gameResult;
}
return null;
}
private resolveOpenManualGameAssignments(
match: MatchDocument,
): ManualGameAssignment[] {
const usedGameNumbers = new Set(
(match.result?.games ?? []).map((game) => game.gameNumber),
);
const assignments: ManualGameAssignment[] = [];
const requiredSlots = this.resolveRequiredGameSlots(match);
for (let gameNumber = 1; gameNumber <= requiredSlots; gameNumber += 1) {
if (usedGameNumbers.has(gameNumber)) continue;
assignments.push({
gameNumber,
...this.resolveSeriesRefForGameNumber(match, gameNumber),
});
}
return assignments;
}
private hasResultForRiotMatch(
match: MatchDocument,
riotMatchId: string,
): boolean {
return Boolean(
match.result?.games?.some((game) => game.riotMatchId === riotMatchId),
);
}
private hasAllRequiredGameResults(match: MatchDocument): boolean {
const requiredSlots = this.resolveRequiredGameSlots(match);
if (requiredSlots <= 0) return false;
const resultGameNumbers = new Set(
(match.result?.games ?? []).map((game) => game.gameNumber),
);
for (let gameNumber = 1; gameNumber <= requiredSlots; gameNumber += 1) {
if (!resultGameNumbers.has(gameNumber)) return false;
}
return true;
}
private updateManualCollectionState(
match: MatchDocument,
matchedCount: number,
): void {
match.resultPollState = {
startedAt: match.resultPollState?.startedAt ?? new Date(),
lastPolledAt: new Date(),
lastPollOutcome: matchedCount > 0 ? 'matched' : 'not-found',
matchedCount: match.result?.games?.length ?? 0,
expandedToAllPuuids: true,
state: 'polling',
};
}
private async finishMatchFromManualResults(
match: MatchDocument,
): Promise<void> {
match.status = 'finished';
if (match.result) {
match.result.winnerTeamIndex = this.resolveMatchWinnerTeamIndex(
match.result.seriesResults ?? [],
);
}
match.resultPollState = {
startedAt: match.resultPollState?.startedAt ?? new Date(),
lastPolledAt: new Date(),
lastPollOutcome: 'matched',
matchedCount: match.result?.games?.length ?? 0,
expandedToAllPuuids: true,
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
}`,
);
});
}
private async rebuildMatchStatsSafe(match: MatchDocument): Promise<void> {
try {
await this.matchStatsService.buildAndUpsert(match._id);
} catch (error) {
this.logger.warn(
`Failed to rebuild match stats for ${match._id.toString()}: ${
error instanceof Error ? error.message : error
}`,
);
}
}
private async markTournamentCodeUsedForManualResult(
match: MatchDocument,
gameResult: MatchGameResult,
detail: RiotMatchDto,
): Promise<void> {
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
await TournamentCodeModel.updateOne(
{
matchId: match._id,
gameNumber: gameResult.gameNumber,
state: { $in: ['reserved', 'released'] },
},
{
$set: {
state: 'used',
usedAt: new Date(
detail.info.gameEndTimestamp ?? detail.info.gameCreation,
),
riotMatchId: detail.metadata.matchId,
},
},
).exec();
}
private buildSeriesResults(
games: MatchGameResult[],
): NonNullable<MatchDocument['result']>['seriesResults'] {
const bySeries = new Map<
string,
{
teamAIndex: number;
teamBIndex: number;
teamAWins: number;
teamBWins: number;
winnerTeamIndex?: number;
}
>();
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 current = bySeries.get(key) ?? {
teamAIndex,
teamBIndex,
teamAWins: 0,
teamBWins: 0,
};
if (game.winnerTeamIndex === teamAIndex) current.teamAWins += 1;
if (game.winnerTeamIndex === teamBIndex) current.teamBWins += 1;
current.winnerTeamIndex =
current.teamAWins > current.teamBWins
? teamAIndex
: current.teamBWins > current.teamAWins
? teamBIndex
: undefined;
bySeries.set(key, current);
}
return [...bySeries.values()].sort(
(left, right) =>
left.teamAIndex - right.teamAIndex ||
left.teamBIndex - right.teamBIndex,
);
}
private resolveSeriesRefForGameNumber(
match: MatchDocument,
gameNumber: number,
): { teamAIndex: number; teamBIndex: number } {
const gameMode = match.gameMode ?? 'pair';
if (gameMode === 'round-robin') {
const persisted = match.gameSchedule?.find(
(entry) => entry.gameNumber === gameNumber,
);
if (persisted) {
return {
teamAIndex: persisted.teamAIndex,
teamBIndex: persisted.teamBIndex,
};
}
const perSeries = match.gameCount || 1;
const pairIndex = Math.max(0, Math.ceil(gameNumber / perSeries) - 1);
return (
roundRobinPairs(resolveRoundRobinTeamCount(match))[pairIndex] ?? {
teamAIndex: 1,
teamBIndex: 2,
}
);
}
const perSeries = match.gameCount || 1;
const seriesIndex = Math.max(1, Math.ceil(gameNumber / perSeries));
return {
teamAIndex: (seriesIndex - 1) * 2 + 1,
teamBIndex: (seriesIndex - 1) * 2 + 2,
};
}
private resolveRequiredGameSlots(match: MatchDocument): number {
const gameMode = match.gameMode ?? 'pair';
if (gameMode === 'round-robin') {
const teamCount = resolveRoundRobinTeamCount(match);
return roundRobinPairCount(teamCount) * (match.gameCount || 1);
}
const activeParticipantCount = match.participants.filter(
(participant) => !participant.excluded,
).length;
const participantSeriesCount = Math.floor(activeParticipantCount / 10);
const teamSeriesCount = Math.ceil(match.teams.length / 2);
const seriesCount = Math.max(1, participantSeriesCount, teamSeriesCount);
return seriesCount * (match.gameCount || 1);
}
private resolveMatchWinnerTeamIndex(
seriesResults: NonNullable<MatchDocument['result']>['seriesResults'],
): number | undefined {
const winsByTeam = new Map<number, number>();
for (const series of seriesResults ?? []) {
if (!series.winnerTeamIndex) continue;
winsByTeam.set(
series.winnerTeamIndex,
(winsByTeam.get(series.winnerTeamIndex) ?? 0) + 1,
);
}
const sorted = [...winsByTeam.entries()].sort(
(left, right) => right[1] - left[1],
);
if (sorted.length === 0) return undefined;
if (sorted.length > 1 && sorted[0][1] === sorted[1][1]) return undefined;
return sorted[0][0];
}
private async updatePollState(
match: MatchDocument,
outcome: 'matched' | 'not-found' | 'failed',
expandedToAllPuuids: boolean,
): Promise<void> {
match.resultPollState = {
startedAt: match.resultPollState?.startedAt ?? new Date(),
lastPolledAt: new Date(),
lastPollOutcome: outcome,
matchedCount: match.result?.games?.length ?? 0,
expandedToAllPuuids,
state: outcome === 'failed' ? 'failed' : 'polling',
};
await match.save();
}
private nextPollDelayMs(elapsedMs: number): number | null {
if (elapsedMs >= POLL_EXPIRY_MS) return null;
if (elapsedMs <= EXPAND_AFTER_MS) return FIRST_HOUR_POLL_DELAY_MS;
return LATER_POLL_DELAY_MS;
}
private resolveStartTime(match: MatchDocument): number {
return Math.max(
0,
Math.floor(match.teamBuiltAt!.getTime() / 1000) -
TOURNAMENT_LOOKUP_START_MARGIN_SECONDS,
);
}
private isReadyToPoll(match: MatchDocument): boolean {
return Boolean(
match.teamBuiltAt &&
match.tournamentCodeIds.length > 0 &&
match.teams.length >= 2 &&
match.teams.every((team) => team.members.length > 0),
);
}
private assertManualCollectionAllowed(
match: MatchDocument,
communityId: mongoose.Types.ObjectId,
): void {
if (!match.communityId.equals(communityId)) {
throw new BadRequestException('Match does not belong to this community.');
}
if (!this.hasBuiltTeams(match)) {
throw new BadRequestException(
'Match needs built teams before manual result collection.',
);
}
}
private hasBuiltTeams(match: MatchDocument): boolean {
return Boolean(
match.teamBuiltAt &&
match.teams.length >= 2 &&
match.teams.every((team) => team.members.length > 0),
);
}
private async resolveRiotRegion(
match: MatchDocument,
): Promise<RiotRegionalRoute> {
const CommunityModel = await this.connectionService.getModel('community');
const community = await CommunityModel.findById(match.communityId)
.select({ riotRegion: 1 })
.lean()
.exec();
return community?.riotRegion ?? 'asia';
}
private async loadMatch(
matchOrId: MatchDocument | mongoose.Types.ObjectId,
): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match');
const match =
matchOrId instanceof mongoose.Types.ObjectId
? await MatchModel.findById(matchOrId)
: await MatchModel.findById(matchOrId._id);
if (!match) throw new NotFoundException('Match not found.');
return match;
}
}
function isRiotMatchDto(value: unknown): value is RiotMatchDto {
return Boolean(
value &&
typeof value === 'object' &&
'metadata' in value &&
'info' in value,
);
}