diff --git a/apps/api/src/modules/tournament-code/tournament-code.constants.ts b/apps/api/src/modules/tournament-code/tournament-code.constants.ts new file mode 100644 index 00000000..ee4da598 --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code.constants.ts @@ -0,0 +1,4 @@ +export const TOURNAMENT_CODE_PATTERN = /^[A-Z0-9-]{8,}$/i; +export const TOURNAMENT_CODE_EXPIRY_MARGIN_MS = 24 * 60 * 60 * 1000; +export const TOURNAMENT_CODE_EXPIRING_SOON_MS = 7 * 24 * 60 * 60 * 1000; +export const DEFAULT_TOURNAMENT_GAME_COUNT = 3; diff --git a/apps/api/src/modules/tournament-code/tournament-code.controller.ts b/apps/api/src/modules/tournament-code/tournament-code.controller.ts new file mode 100644 index 00000000..cd28cd47 --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code.controller.ts @@ -0,0 +1,105 @@ +import { + BadRequestException, + Body, + Controller, + Delete, + Get, + HttpCode, + HttpStatus, + Param, + Post, + Query, + 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 { + TournamentCodeState, + UserDocument, +} from '../global/database/schema'; +import { TournamentCodeService } from './tournament-code.service'; +import type { BulkUploadTournamentCodesRequest } from './tournament-code.types'; + +@Controller('communities/:communityId/tournament-codes') +@Roles('owner', 'admin') +@UseGuards(RolesGuard) +export class TournamentCodeController { + constructor(private readonly tournamentCodeService: TournamentCodeService) {} + + @Post() + public async bulkUpload( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Body() body: BulkUploadTournamentCodesRequest, + ) { + this.assertSameCommunity(currentUser, communityId); + return this.tournamentCodeService.bulkUpload({ + communityId, + uploadedBy: currentUser._id, + codes: body.codes ?? [], + }); + } + + @Get() + public async list( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Query('state') state?: TournamentCodeState, + @Query('limit') limit?: string, + ) { + this.assertSameCommunity(currentUser, communityId); + return { + codes: await this.tournamentCodeService.list({ + state, + limit: limit ? Number(limit) : undefined, + }), + }; + } + + @Get('stats') + public async stats( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + ) { + this.assertSameCommunity(currentUser, communityId); + return this.tournamentCodeService.stats(); + } + + @Post(':id/release') + public async restore( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('id', ParseObjectIdPipe) id: mongoose.Types.ObjectId, + ) { + this.assertSameCommunity(currentUser, communityId); + return this.tournamentCodeService.restoreToAvailable(id); + } + + @Delete(':id') + @HttpCode(HttpStatus.NO_CONTENT) + public async discard( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('id', ParseObjectIdPipe) id: mongoose.Types.ObjectId, + ) { + this.assertSameCommunity(currentUser, communityId); + await this.tournamentCodeService.discardAvailable(id); + } + + private assertSameCommunity( + user: UserDocument, + communityId: mongoose.Types.ObjectId, + ): void { + if (!user.communityId.equals(communityId)) { + throw new BadRequestException('Different community.'); + } + } +} diff --git a/apps/api/src/modules/tournament-code/tournament-code.module.ts b/apps/api/src/modules/tournament-code/tournament-code.module.ts new file mode 100644 index 00000000..f41cc726 --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code.module.ts @@ -0,0 +1,11 @@ +import { Module } from '@nestjs/common'; +import { TournamentCodeController } from './tournament-code.controller'; +import { TournamentCodeScheduler } from './tournament-code.scheduler'; +import { TournamentCodeService } from './tournament-code.service'; + +@Module({ + controllers: [TournamentCodeController], + providers: [TournamentCodeService, TournamentCodeScheduler], + exports: [TournamentCodeService], +}) +export class TournamentCodeModule {} diff --git a/apps/api/src/modules/tournament-code/tournament-code.scheduler.ts b/apps/api/src/modules/tournament-code/tournament-code.scheduler.ts new file mode 100644 index 00000000..9f73d297 --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code.scheduler.ts @@ -0,0 +1,57 @@ +import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common'; +import { TournamentCodeService } from './tournament-code.service'; + +@Injectable() +export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy { + private readonly logger = new Logger(TournamentCodeScheduler.name); + private attachTimer?: NodeJS.Timeout; + private expireTimer?: NodeJS.Timeout; + + constructor(private readonly tournamentCodeService: TournamentCodeService) {} + + public onModuleInit() { + this.attachTimer = setInterval(() => { + void this.attachPending(); + }, 30_000); + this.expireTimer = setInterval(() => { + void this.markExpired(); + }, 60 * 60 * 1000); + this.attachTimer.unref?.(); + this.expireTimer.unref?.(); + + void this.attachPending(); + void this.markExpired(); + } + + public onModuleDestroy() { + if (this.attachTimer) clearInterval(this.attachTimer); + if (this.expireTimer) clearInterval(this.expireTimer); + } + + private async attachPending() { + try { + const touched = await this.tournamentCodeService.attachPendingMatches(); + if (touched > 0) { + this.logger.debug(`Attached tournament codes for ${touched} matches.`); + } + } catch (error) { + this.logger.warn( + `Failed to attach pending tournament codes: ${ + error instanceof Error ? error.message : error + }`, + ); + } + } + + private async markExpired() { + try { + await this.tournamentCodeService.markExpired(); + } catch (error) { + this.logger.warn( + `Failed to mark expired tournament codes: ${ + error instanceof Error ? error.message : error + }`, + ); + } + } +} diff --git a/apps/api/src/modules/tournament-code/tournament-code.service.ts b/apps/api/src/modules/tournament-code/tournament-code.service.ts new file mode 100644 index 00000000..c5305abc --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code.service.ts @@ -0,0 +1,365 @@ +import { + BadRequestException, + Injectable, + NotFoundException, +} from '@nestjs/common'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import type { + 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'; + +const DEFAULT_REGION = 'kr'; +const DEFAULT_SPECTATOR_TYPE: TournamentSpectatorType = 'ALL'; + +@Injectable() +export class TournamentCodeService { + constructor(private readonly connectionService: ConnectionService) {} + + public async bulkUpload(params: { + communityId: mongoose.Types.ObjectId; + uploadedBy: mongoose.Types.ObjectId; + codes: TournamentCodeUploadItem[]; + }): Promise { + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const invalid: BulkUploadTournamentCodesResponse['invalid'] = []; + const duplicates: string[] = []; + const valid: Array< + Omit & { + uploadedBy: mongoose.Types.ObjectId; + } + > = []; + const seen = new Set(); + + 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 list(params: { + state?: TournamentCodeState; + limit?: number; + }): Promise { + 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; + 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 { + 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 { + 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 { + const MatchModel = await this.connectionService.getModel('match'); + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const match = + matchOrId instanceof mongoose.Types.ObjectId + ? await MatchModel.findById(matchOrId) + : await MatchModel.findById(matchOrId._id); + if (!match) throw new NotFoundException('Match not found.'); + + match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; + const need = match.gameCount - match.tournamentCodeIds.length; + if (need <= 0) 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' }, + ).exec(); + if (!code) break; + reservedIds.push(code._id); + } + + if (reservedIds.length > 0) { + match.tournamentCodeIds.push(...reservedIds); + await match.save(); + } + return match; + } + + public async releaseFromMatch( + matchOrId: MatchDocument | mongoose.Types.ObjectId, + ): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const match = + matchOrId instanceof mongoose.Types.ObjectId + ? await MatchModel.findById(matchOrId) + : await MatchModel.findById(matchOrId._id); + if (!match) return; + if (match.tournamentCodeIds.length === 0) return; + + await TournamentCodeModel.updateMany( + { _id: { $in: match.tournamentCodeIds }, state: 'reserved' }, + { + $set: { state: 'released', releasedAt: new Date() }, + $unset: { matchId: 1, gameNumber: 1, reservedAt: 1 }, + }, + ).exec(); + + match.tournamentCodeIds = []; + await match.save(); + } + + public async markExpired(): Promise { + 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 { + 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(); + let touched = 0; + for (const match of matches) { + if ((match.tournamentCodeIds?.length ?? 0) >= (match.gameCount || 0)) { + continue; + } + const before = match.tournamentCodeIds?.length ?? 0; + await this.reserveForMatch(match); + const after = match.tournamentCodeIds?.length ?? 0; + if (after > before) touched += 1; + } + return touched; + } + + public async buildSlots(match: MatchDocument): Promise { + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; + 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) { + return { + gameNumber, + code: null, + expiresAt: null, + state: 'pending', + riotMatchId: null, + }; + } + return { + gameNumber, + code: code.code, + expiresAt: code.expiresAt.toISOString(), + state: code.state, + riotMatchId: code.riotMatchId ?? null, + }; + }); + } + + private normalizeCode(code: string | undefined): string { + return (code ?? '').trim().toUpperCase(); + } +} diff --git a/apps/api/src/modules/tournament-code/tournament-code.types.ts b/apps/api/src/modules/tournament-code/tournament-code.types.ts new file mode 100644 index 00000000..c841da3f --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code.types.ts @@ -0,0 +1,31 @@ +import type { + TournamentCodeState, + TournamentSpectatorType, +} from '../global/database/schema'; + +export interface TournamentCodeUploadItem { + code: string; + expiresAt: string; + spectatorType?: TournamentSpectatorType; + metadata?: Record; + source?: string; + notes?: string; +} + +export interface BulkUploadTournamentCodesRequest { + codes: TournamentCodeUploadItem[]; +} + +export interface BulkUploadTournamentCodesResponse { + inserted: number; + duplicates: string[]; + invalid: Array<{ code: string; reason: string }>; +} + +export interface TournamentCodeSlotView { + gameNumber: number; + code: string | null; + expiresAt: string | null; + state: TournamentCodeState | 'pending'; + riotMatchId: string | null; +} diff --git a/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts b/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts new file mode 100644 index 00000000..a0e72be8 --- /dev/null +++ b/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts @@ -0,0 +1,144 @@ +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(); + const userIdByPuuid = new Map(); + + for (const [index, userId] of [...blueUserIds, ...redUserIds].entries()) { + const puuid = `puuid-${index}`; + puuidByUserId.set(userId.toString(), puuid); + userIdByPuuid.set(puuid, userId); + } + + const match = { + teams: [ + { + side: 'blue', + name: '블루팀', + members: blueUserIds.map((userId) => ({ + userId, + assignedPosition: 'MID', + })), + }, + { + side: 'red', + name: '레드팀', + 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', + gameDuration: 1800, + }); + expect(result?.participants).toHaveLength(10); + }); + + 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?.winnerSide).toBe('red'); + }); + + 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(); + }); +}); diff --git a/apps/api/src/modules/tournament-result/team-mapping.util.ts b/apps/api/src/modules/tournament-result/team-mapping.util.ts new file mode 100644 index 00000000..a617b78f --- /dev/null +++ b/apps/api/src/modules/tournament-result/team-mapping.util.ts @@ -0,0 +1,118 @@ +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; + userIdByPuuid: Map; +} + +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(); + 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, + side: TeamSide, + lookup: MatchPuuidLookup, +): string[] { + const team = match.teams.find((item) => item.side === side); + if (!team) return []; + return team.members + .map((member) => lookup.puuidByUserId.get(member.userId.toString())) + .filter((puuid): puuid is string => Boolean(puuid)); +} + +export function computeGameResult(params: { + match: MatchDocument; + detail: RiotMatchDto; + gameNumber: number; + lookup: MatchPuuidLookup; +}): MatchGameResult | null { + const { match, detail, gameNumber, lookup } = params; + const ourBluePuuids = collectTeamPuuids(match, 'blue', lookup); + const ourRedPuuids = collectTeamPuuids(match, 'red', 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, ourBluePuuids) + + countOverlap(team200Puuids, ourRedPuuids); + const reversedOverlap = + countOverlap(team100Puuids, ourRedPuuids) + + countOverlap(team200Puuids, ourBluePuuids); + const teamMapping: Record = + normalOverlap >= reversedOverlap + ? { [RIOT_BLUE_TEAM_ID]: 'blue', [RIOT_RED_TEAM_ID]: 'red' } + : { [RIOT_BLUE_TEAM_ID]: 'red', [RIOT_RED_TEAM_ID]: 'blue' }; + + 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 = teamMapping[winningTeam.teamId]; + if (!winnerSide) return null; + + const participants = detail.info.participants + .map((participant) => { + const userId = lookup.userIdByPuuid.get(participant.puuid); + const side = teamMapping[participant.teamId]; + if (!userId || !side) return null; + return { + userId, + side, + championId: participant.championId, + kills: participant.kills, + deaths: participant.deaths, + assists: participant.assists, + win: participant.win, + }; + }) + .filter((participant): participant is NonNullable => + Boolean(participant), + ); + + return { + gameNumber, + riotMatchId: detail.metadata.matchId, + 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; +} diff --git a/apps/api/src/modules/tournament-result/tournament-result.controller.ts b/apps/api/src/modules/tournament-result/tournament-result.controller.ts new file mode 100644 index 00000000..9f9e627e --- /dev/null +++ b/apps/api/src/modules/tournament-result/tournament-result.controller.ts @@ -0,0 +1,39 @@ +import { + BadRequestException, + 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 { 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, + }); + } +} diff --git a/apps/api/src/modules/tournament-result/tournament-result.module.ts b/apps/api/src/modules/tournament-result/tournament-result.module.ts new file mode 100644 index 00000000..b9281ad0 --- /dev/null +++ b/apps/api/src/modules/tournament-result/tournament-result.module.ts @@ -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 {} diff --git a/apps/api/src/modules/tournament-result/tournament-result.service.ts b/apps/api/src/modules/tournament-result/tournament-result.service.ts new file mode 100644 index 00000000..2ce0be98 --- /dev/null +++ b/apps/api/src/modules/tournament-result/tournament-result.service.ts @@ -0,0 +1,464 @@ +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 { + 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 { + 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 { + 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(); + const checkedRiotMatchIds = new Set(); + 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 { + 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 { + 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 { + 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 { + 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 = { + 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, + fetchedAt: new Date(), + }; + await RiotMatchModel.updateOne( + { matchId: dto.metadata.matchId }, + { $setOnInsert: payload }, + { upsert: true }, + ).exec(); + return dto; + } + + private async buildPuuidLookup(match: MatchDocument): Promise { + const puuidByUserId = new Map(); + const userIdByPuuid = new Map(); + + 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 { + 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 { + 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, + ); +} diff --git a/apps/api/src/modules/tournament-result/tournament-result.types.ts b/apps/api/src/modules/tournament-result/tournament-result.types.ts new file mode 100644 index 00000000..25e265b7 --- /dev/null +++ b/apps/api/src/modules/tournament-result/tournament-result.types.ts @@ -0,0 +1,30 @@ +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 ComputedGameParticipant { + userId: string; + side: TeamSide; + championId: number; + kills: number; + deaths: number; + assists: number; + win: boolean; +}