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

465 lines
15 KiB
TypeScript

import {
BadRequestException,
Injectable,
Logger,
NotFoundException,
} from '@nestjs/common';
import mongoose from 'mongoose';
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 {
collectCaptainUserIds,
collectMatchUserIds,
computeGameResult,
type MatchPuuidLookup,
} from './team-mapping.util';
import type {
EnqueueTournamentResultPollResult,
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;
@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,
) {}
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 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,
});
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();
return true;
}
private async advanceMatchIfReady(
match: MatchDocument,
codes: TournamentCodeDocument[],
): Promise<boolean> {
if (codes.length < match.gameCount) return false;
if (!codes.every((code) => code.state === 'used' && code.riotMatchId)) {
return false;
}
match.status = 'finished';
if (match.result) {
match.result.winnerSide =
match.result.blueScore > match.result.redScore
? 'blue'
: match.result.redScore > match.result.blueScore
? 'red'
: undefined;
}
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();
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 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);
match.result = {
winnerSide: match.result?.winnerSide,
blueScore: games.filter((game) => game.winnerSide === 'blue').length,
redScore: games.filter((game) => game.winnerSide === 'red').length,
mvpUserId: match.result?.mvpUserId,
riotMatchIds: [...new Set(games.map((game) => game.riotMatchId))],
games,
};
}
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 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,
);
}