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,19 @@
import { Type } from 'class-transformer';
import { IsDate, IsString, MaxLength, MinLength } from 'class-validator';
export class CollectTournamentResultWindowDto {
@IsDate()
@Type(() => Date)
startTime!: Date;
@IsDate()
@Type(() => Date)
endTime!: Date;
}
export class CollectTournamentResultRiotMatchDto {
@IsString()
@MinLength(1)
@MaxLength(96)
riotMatchId!: string;
}
@@ -0,0 +1,156 @@
import mongoose from 'mongoose';
import type { MatchDocument } from '../global/database/schema';
import type { RiotMatchDto } from '../riot/riot.types';
import { computeGameResult, type MatchPuuidLookup } from './team-mapping.util';
function makeMatch(): {
match: MatchDocument;
lookup: MatchPuuidLookup;
blueUserIds: mongoose.Types.ObjectId[];
redUserIds: mongoose.Types.ObjectId[];
} {
const blueUserIds = Array.from({ length: 5 }, () => new mongoose.Types.ObjectId());
const redUserIds = Array.from({ length: 5 }, () => new mongoose.Types.ObjectId());
const puuidByUserId = new Map<string, string>();
const userIdByPuuid = new Map<string, mongoose.Types.ObjectId>();
for (const [index, userId] of [...blueUserIds, ...redUserIds].entries()) {
const puuid = `puuid-${index}`;
puuidByUserId.set(userId.toString(), puuid);
userIdByPuuid.set(puuid, userId);
}
const match = {
teams: [
{
teamIndex: 1,
name: '1팀',
members: blueUserIds.map((userId) => ({
userId,
assignedPosition: 'MID',
})),
},
{
teamIndex: 2,
name: '2팀',
members: redUserIds.map((userId) => ({
userId,
assignedPosition: 'MID',
})),
},
],
participants: [...blueUserIds, ...redUserIds].map((userId, index) => ({
userId,
puuid: `puuid-${index}`,
preferredPositions: [],
joinedAt: new Date(),
})),
} as unknown as MatchDocument;
return { match, lookup: { puuidByUserId, userIdByPuuid }, blueUserIds, redUserIds };
}
function makeRiotMatch(params: {
team100Puuids: string[];
team200Puuids: string[];
winningTeamId: 100 | 200;
}): RiotMatchDto {
const participants = [
...params.team100Puuids.map((puuid, index) => ({
puuid,
participantId: index + 1,
teamId: 100,
championId: 10 + index,
kills: index,
deaths: 1,
assists: 2,
win: params.winningTeamId === 100,
})),
...params.team200Puuids.map((puuid, index) => ({
puuid,
participantId: index + 6,
teamId: 200,
championId: 20 + index,
kills: index,
deaths: 2,
assists: 3,
win: params.winningTeamId === 200,
})),
];
return {
metadata: {
dataVersion: '2',
matchId: 'KR_1',
participants: participants.map((participant) => participant.puuid),
},
info: {
gameCreation: 1,
gameDuration: 1800,
participants,
teams: [
{ teamId: 100, win: params.winningTeamId === 100 },
{ teamId: 200, win: params.winningTeamId === 200 },
],
},
} as unknown as RiotMatchDto;
}
describe('computeGameResult', () => {
it('maps Riot teams to local blue/red by overlap', () => {
const { match, lookup } = makeMatch();
const detail = makeRiotMatch({
team100Puuids: ['puuid-0', 'puuid-1', 'puuid-2', 'puuid-3', 'puuid-4'],
team200Puuids: ['puuid-5', 'puuid-6', 'puuid-7', 'puuid-8', 'puuid-9'],
winningTeamId: 100,
});
const result = computeGameResult({ match, lookup, detail, gameNumber: 1 });
expect(result).toMatchObject({
gameNumber: 1,
riotMatchId: 'KR_1',
winnerSide: 'blue',
blueTeamIndex: 1,
redTeamIndex: 2,
winnerTeamIndex: 1,
gameDuration: 1800,
});
expect(result?.participants).toHaveLength(10);
expect(result?.participants[0]).toMatchObject({
teamIndex: 1,
side: 'blue',
});
});
it('handles reversed Riot side assignment', () => {
const { match, lookup } = makeMatch();
const detail = makeRiotMatch({
team100Puuids: ['puuid-5', 'puuid-6', 'puuid-7', 'puuid-8', 'puuid-9'],
team200Puuids: ['puuid-0', 'puuid-1', 'puuid-2', 'puuid-3', 'puuid-4'],
winningTeamId: 100,
});
const result = computeGameResult({ match, lookup, detail, gameNumber: 2 });
expect(result).toMatchObject({
blueTeamIndex: 2,
redTeamIndex: 1,
winnerSide: 'blue',
winnerTeamIndex: 2,
});
});
it('rejects matches with too little overlap', () => {
const { match, lookup } = makeMatch();
const detail = makeRiotMatch({
team100Puuids: ['other-1', 'other-2', 'other-3', 'other-4', 'other-5'],
team200Puuids: ['other-6', 'other-7', 'other-8', 'other-9', 'other-10'],
winningTeamId: 100,
});
const result = computeGameResult({ match, lookup, detail, gameNumber: 3 });
expect(result).toBeNull();
});
});
@@ -0,0 +1,140 @@
import mongoose from 'mongoose';
import type { MatchDocument, MatchGameResult, TeamSide } from '../global/database/schema';
import type { RiotMatchDto } from '../riot/riot.types';
const RIOT_BLUE_TEAM_ID = 100;
const RIOT_RED_TEAM_ID = 200;
const MINIMUM_TRUSTED_OVERLAP = 6;
export interface MatchPuuidLookup {
puuidByUserId: Map<string, string>;
userIdByPuuid: Map<string, mongoose.Types.ObjectId>;
}
export function collectCaptainUserIds(match: MatchDocument): mongoose.Types.ObjectId[] {
return match.teams
.map((team) => team.captainUserId)
.filter((userId): userId is mongoose.Types.ObjectId => Boolean(userId));
}
export function collectMatchUserIds(match: MatchDocument): mongoose.Types.ObjectId[] {
const ids = new Map<string, mongoose.Types.ObjectId>();
for (const participant of match.participants) {
ids.set(participant.userId.toString(), participant.userId);
}
for (const team of match.teams) {
if (team.captainUserId) ids.set(team.captainUserId.toString(), team.captainUserId);
for (const member of team.members) {
ids.set(member.userId.toString(), member.userId);
}
}
return [...ids.values()];
}
export function collectTeamPuuids(
match: MatchDocument,
teamIndex: number,
lookup: MatchPuuidLookup,
): string[] {
const team = match.teams.find((item) => item.teamIndex === teamIndex);
if (!team) return [];
const userIds = [
...(team.captainUserId ? [team.captainUserId] : []),
...team.members.map((member) => member.userId),
];
return userIds
.map((userId) => lookup.puuidByUserId.get(userId.toString()))
.filter((puuid): puuid is string => Boolean(puuid));
}
export function computeGameResult(params: {
match: MatchDocument;
detail: RiotMatchDto;
gameNumber: number;
lookup: MatchPuuidLookup;
teamAIndex?: number;
teamBIndex?: number;
}): MatchGameResult | null {
const {
match,
detail,
gameNumber,
lookup,
teamAIndex = 1,
teamBIndex = 2,
} = params;
const teamAPuuids = collectTeamPuuids(match, teamAIndex, lookup);
const teamBPuuids = collectTeamPuuids(match, teamBIndex, lookup);
const team100Puuids = detail.info.participants
.filter((participant) => participant.teamId === RIOT_BLUE_TEAM_ID)
.map((participant) => participant.puuid);
const team200Puuids = detail.info.participants
.filter((participant) => participant.teamId === RIOT_RED_TEAM_ID)
.map((participant) => participant.puuid);
const normalOverlap =
countOverlap(team100Puuids, teamAPuuids) +
countOverlap(team200Puuids, teamBPuuids);
const reversedOverlap =
countOverlap(team100Puuids, teamBPuuids) +
countOverlap(team200Puuids, teamAPuuids);
const blueTeamIndex = normalOverlap >= reversedOverlap ? teamAIndex : teamBIndex;
const redTeamIndex = normalOverlap >= reversedOverlap ? teamBIndex : teamAIndex;
const teamIndexByRiotTeamId: Record<number, number> = {
[RIOT_BLUE_TEAM_ID]: blueTeamIndex,
[RIOT_RED_TEAM_ID]: redTeamIndex,
};
const sideByRiotTeamId: Record<number, TeamSide> = {
[RIOT_BLUE_TEAM_ID]: 'blue',
[RIOT_RED_TEAM_ID]: 'red',
};
if (Math.max(normalOverlap, reversedOverlap) < MINIMUM_TRUSTED_OVERLAP) {
return null;
}
const winningTeam = detail.info.teams.find((team) => team.win);
if (!winningTeam) return null;
const winnerSide = sideByRiotTeamId[winningTeam.teamId];
if (!winnerSide) return null;
const winnerTeamIndex = teamIndexByRiotTeamId[winningTeam.teamId];
if (!winnerTeamIndex) return null;
const participants = detail.info.participants
.map((participant) => {
const userId = lookup.userIdByPuuid.get(participant.puuid);
const side = sideByRiotTeamId[participant.teamId];
const teamIndex = teamIndexByRiotTeamId[participant.teamId];
if (!userId || !side || !teamIndex) return null;
return {
userId,
teamIndex,
side,
championId: participant.championId,
kills: participant.kills,
deaths: participant.deaths,
assists: participant.assists,
win: participant.win,
};
})
.filter((participant): participant is NonNullable<typeof participant> =>
Boolean(participant),
);
return {
gameNumber,
riotMatchId: detail.metadata.matchId,
blueTeamIndex,
redTeamIndex,
winnerTeamIndex,
winnerSide,
gameCreation: detail.info.gameCreation,
gameDuration: detail.info.gameDuration,
participants,
};
}
export function countOverlap(left: string[], right: string[]): number {
const rightSet = new Set(right);
return left.filter((item) => rightSet.has(item)).length;
}
@@ -0,0 +1,81 @@
import {
BadRequestException,
Body,
Controller,
Param,
Post,
UseGuards,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { CurrentUser } from '../auth/current-user.decorator';
import { Roles } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import type { UserDocument } from '../global/database/schema';
import {
CollectTournamentResultRiotMatchDto,
CollectTournamentResultWindowDto,
} from './dto/manual-result-collection.dto';
import { TournamentResultService } from './tournament-result.service';
@Controller('communities/:communityId/matches/:matchId/poll-tournament-result')
@Roles('owner', 'admin')
@UseGuards(RolesGuard)
export class TournamentResultController {
constructor(
private readonly tournamentResultService: TournamentResultService,
) {}
@Post()
public async poll(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) {
if (!currentUser.communityId.equals(communityId)) {
throw new BadRequestException('Different community.');
}
return this.tournamentResultService.scheduleManualPoll({
matchId,
communityId,
});
}
@Post('collect-by-window')
public async collectByWindow(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: CollectTournamentResultWindowDto,
) {
if (!currentUser.communityId.equals(communityId)) {
throw new BadRequestException('Different community.');
}
return this.tournamentResultService.collectManualByWindow({
matchId,
communityId,
startTime: body.startTime,
endTime: body.endTime,
});
}
@Post('collect-by-riot-match')
public async collectByRiotMatch(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: CollectTournamentResultRiotMatchDto,
) {
if (!currentUser.communityId.equals(communityId)) {
throw new BadRequestException('Different community.');
}
return this.tournamentResultService.collectManualByRiotMatch({
matchId,
communityId,
riotMatchId: body.riotMatchId,
});
}
}
@@ -0,0 +1,14 @@
import { forwardRef, Module } from '@nestjs/common';
import { CommunityStatsModule } from '../community-stats/community-stats.module';
import { RiotJobQueueModule } from '../riot-job-queue/riot-job-queue.module';
import { RiotModule } from '../riot/riot.module';
import { TournamentResultController } from './tournament-result.controller';
import { TournamentResultService } from './tournament-result.service';
@Module({
imports: [RiotModule, CommunityStatsModule, forwardRef(() => RiotJobQueueModule)],
controllers: [TournamentResultController],
providers: [TournamentResultService],
exports: [TournamentResultService],
})
export class TournamentResultModule {}
@@ -0,0 +1,263 @@
import mongoose from 'mongoose';
import type { MatchDocument } from '../global/database/schema';
import type { RiotMatchDto } from '../riot/riot.types';
import { TournamentResultService } from './tournament-result.service';
type TournamentResultServiceInternals = TournamentResultService & {
resolveRequiredGameSlots(match: MatchDocument): number;
resolveSeriesRefForGameNumber(
match: MatchDocument,
gameNumber: number,
): { teamAIndex: number; teamBIndex: number };
};
function createService() {
return new TournamentResultService(
{} as never,
{} as never,
{} as never,
{} as never,
{} as never,
) as unknown as TournamentResultServiceInternals;
}
interface MatchOverrides {
gameCount?: number;
gameMode?: 'pair' | 'bracket' | 'round-robin';
participants?: Array<{ excluded?: boolean }>;
teams?: Array<{ teamIndex: number }>;
gameSchedule?: Array<{
gameNumber: number;
teamAIndex: number;
teamBIndex: number;
}>;
}
function createMatch(overrides: MatchOverrides): MatchDocument {
return {
gameCount: 1,
gameMode: 'pair',
participants: [],
teams: [],
gameSchedule: [],
...overrides,
} as unknown as MatchDocument;
}
describe('TournamentResultService round-robin scheduling', () => {
it('calculates required slots for round-robin polling', () => {
const service = createService();
const match = createMatch({
gameMode: 'round-robin',
gameCount: 1,
teams: Array.from({ length: 6 }, (_, index) => ({
teamIndex: index + 1,
})),
});
expect(service.resolveRequiredGameSlots(match)).toBe(15);
});
it('uses persisted round-robin schedule when mapping a game number', () => {
const service = createService();
const match = createMatch({
gameMode: 'round-robin',
gameSchedule: [
{ gameNumber: 1, teamAIndex: 3, teamBIndex: 6 },
{ gameNumber: 2, teamAIndex: 1, teamBIndex: 5 },
],
});
expect(service.resolveSeriesRefForGameNumber(match, 2)).toEqual({
teamAIndex: 1,
teamBIndex: 5,
});
});
it('keeps pair game number mapping unchanged', () => {
const service = createService();
const match = createMatch({ gameCount: 3 });
expect(service.resolveSeriesRefForGameNumber(match, 4)).toEqual({
teamAIndex: 3,
teamBIndex: 4,
});
});
});
describe('TournamentResultService manual result collection', () => {
function createManualFixture() {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const users = Array.from({ length: 10 }, (_, index) => ({
userId: new mongoose.Types.ObjectId(),
puuid: `puuid-${index + 1}`,
}));
const match = {
_id: matchId,
communityId,
gameCount: 1,
gameMode: 'pair',
teamBuiltAt: new Date('2026-05-03T10:00:00.000Z'),
status: 'team-built',
tournamentCodeIds: [],
gameSchedule: [],
participants: users.map((user) => ({
userId: user.userId,
puuid: user.puuid,
excluded: false,
})),
teams: [
{
teamIndex: 1,
members: users.slice(0, 5).map((user) => ({ userId: user.userId })),
},
{
teamIndex: 2,
members: users.slice(5).map((user) => ({ userId: user.userId })),
},
],
save: jest.fn().mockResolvedValue(undefined),
} as unknown as MatchDocument & {
save: jest.Mock;
result?: MatchDocument['result'];
};
const detail = {
metadata: {
matchId: 'KR_1234567890',
participants: users.map((user) => user.puuid),
},
info: {
gameCreation: Date.parse('2026-05-03T10:30:00.000Z'),
gameDuration: 1800,
participants: users.map((user, index) => ({
puuid: user.puuid,
teamId: index < 5 ? 100 : 200,
championId: 1,
kills: 1,
deaths: 1,
assists: 1,
win: index < 5,
})),
teams: [
{ teamId: 100, win: true },
{ teamId: 200, win: false },
],
},
} as unknown as RiotMatchDto;
const communityFindById = jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ riotRegion: 'asia' }),
}),
}),
});
const riotMatchFindOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(null),
});
const riotMatchUpdateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(undefined),
});
const tournamentCodeUpdateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(undefined),
});
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') {
return { findById: jest.fn().mockResolvedValue(match) };
}
if (name === 'community') {
return { findById: communityFindById };
}
if (name === 'riotMatch') {
return {
findOne: riotMatchFindOne,
updateOne: riotMatchUpdateOne,
};
}
if (name === 'tournamentCode') {
return { updateOne: tournamentCodeUpdateOne };
}
return {};
}),
};
const riotMatchService = {
getMatchIdsByPuuid: jest.fn().mockResolvedValue(['KR_1234567890']),
getMatch: jest.fn().mockResolvedValue(detail),
};
const service = new TournamentResultService(
connectionService as never,
riotMatchService as never,
{} as never,
{ invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never,
{ buildAndUpsert: jest.fn().mockResolvedValue(undefined) } as never,
);
return {
service,
match,
communityId,
matchId,
riotMatchService,
tournamentCodeUpdateOne,
};
}
it('collects by time window without setting Riot match type', async () => {
const { service, match, communityId, matchId, riotMatchService } =
createManualFixture();
const result = await service.collectManualByWindow({
matchId,
communityId,
startTime: new Date('2026-05-03T10:00:00.000Z'),
endTime: new Date('2026-05-03T11:00:00.000Z'),
});
expect(result).toMatchObject({
scanned: 1,
matched: 1,
gameNumbers: [1],
riotMatchIds: ['KR_1234567890'],
});
expect(riotMatchService.getMatchIdsByPuuid).toHaveBeenCalledWith(
'puuid-1',
expect.not.objectContaining({ type: expect.anything() }),
);
expect(match.result?.games).toHaveLength(1);
expect(match.status).toBe('finished');
});
it('collects directly by Riot match id', async () => {
const {
service,
match,
communityId,
matchId,
riotMatchService,
tournamentCodeUpdateOne,
} = createManualFixture();
const result = await service.collectManualByRiotMatch({
matchId,
communityId,
riotMatchId: ' KR_1234567890 ',
});
expect(result.matched).toBe(1);
expect(riotMatchService.getMatchIdsByPuuid).not.toHaveBeenCalled();
expect(riotMatchService.getMatch).toHaveBeenCalledWith('KR_1234567890', {
region: 'asia',
});
expect(tournamentCodeUpdateOne).toHaveBeenCalledWith(
expect.objectContaining({
matchId,
gameNumber: 1,
}),
expect.objectContaining({
$set: expect.objectContaining({ riotMatchId: 'KR_1234567890' }),
}),
);
expect(match.result?.games[0].winnerTeamIndex).toBe(1);
});
});
@@ -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,
);
}
@@ -0,0 +1,39 @@
import type { TeamSide } from '../global/database/schema';
import type { RiotJobPriority } from '../riot-job-queue/riot-job-queue.types';
export interface PollTournamentResultJob {
kind: 'poll-tournament-result';
jobId: string;
matchId: string;
attempt: number;
expandedToAllPuuids: boolean;
enqueuedAt: number;
priority: RiotJobPriority;
}
export interface EnqueueTournamentResultPollResult {
jobId: string;
matchId: string;
priority: RiotJobPriority;
attempt: number;
expandedToAllPuuids: boolean;
}
export interface ManualTournamentResultCollectResponse {
scanned: number;
matched: number;
skipped: number;
riotMatchIds: string[];
gameNumbers: number[];
}
export interface ComputedGameParticipant {
userId: string;
teamIndex: number;
side: TeamSide;
championId: number;
kills: number;
deaths: number;
assists: number;
win: boolean;
}