From fab16b7c75e45e1f8f551637f0fdc4672d517295 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=B0=95=EB=8B=A4=ED=98=84=20=28Dahyeon=20Park=29?= Date: Tue, 14 Apr 2026 10:30:00 +0900 Subject: [PATCH] feat(api): add Riot match refresh workflows --- .../riot-job-queue.controller.ts | 24 + .../riot-job-queue/riot-job-queue.module.ts | 16 + .../riot-job-queue/riot-job-queue.service.ts | 482 ++++++++++++++ .../riot-job-queue/riot-job-queue.types.ts | 88 +++ .../riot-job-queue/riot-job-worker.service.ts | 227 +++++++ .../riot-job-queue/riot-refresh.gateway.ts | 78 +++ .../modules/riot/riot-match.service.spec.ts | 109 +++ .../src/modules/riot/riot-match.service.ts | 630 ++++++++++++++++++ .../riot/riot-recent-matches.service.ts | 153 +++++ .../riot/riot-recent-stats.service.spec.ts | 304 +++++++++ .../modules/riot/riot-recent-stats.service.ts | 172 +++++ .../riot/riot-webhook.controller.spec.ts | 60 ++ .../modules/riot/riot-webhook.controller.ts | 49 ++ 13 files changed, 2392 insertions(+) create mode 100644 apps/api/src/modules/riot-job-queue/riot-job-queue.controller.ts create mode 100644 apps/api/src/modules/riot-job-queue/riot-job-queue.module.ts create mode 100644 apps/api/src/modules/riot-job-queue/riot-job-queue.service.ts create mode 100644 apps/api/src/modules/riot-job-queue/riot-job-queue.types.ts create mode 100644 apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts create mode 100644 apps/api/src/modules/riot-job-queue/riot-refresh.gateway.ts create mode 100644 apps/api/src/modules/riot/riot-match.service.spec.ts create mode 100644 apps/api/src/modules/riot/riot-match.service.ts create mode 100644 apps/api/src/modules/riot/riot-recent-matches.service.ts create mode 100644 apps/api/src/modules/riot/riot-recent-stats.service.spec.ts create mode 100644 apps/api/src/modules/riot/riot-recent-stats.service.ts create mode 100644 apps/api/src/modules/riot/riot-webhook.controller.spec.ts create mode 100644 apps/api/src/modules/riot/riot-webhook.controller.ts diff --git a/apps/api/src/modules/riot-job-queue/riot-job-queue.controller.ts b/apps/api/src/modules/riot-job-queue/riot-job-queue.controller.ts new file mode 100644 index 00000000..3caa1162 --- /dev/null +++ b/apps/api/src/modules/riot-job-queue/riot-job-queue.controller.ts @@ -0,0 +1,24 @@ +import { Controller, Get, NotFoundException, Param } from '@nestjs/common'; +import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; +import { RiotJobQueueService } from './riot-job-queue.service'; + +@Controller('riot/jobs') +export class RiotJobQueueController { + constructor(private readonly jobQueueService: RiotJobQueueService) {} + + @Get('parents/:parentJobId') + @AllowPublicAccess() + public async getParent(@Param('parentJobId') parentJobId: string) { + const status = await this.jobQueueService.getParentStatus(parentJobId); + if (!status) throw new NotFoundException('Riot parent job not found.'); + return status; + } + + @Get(':jobId') + @AllowPublicAccess() + public async getJob(@Param('jobId') jobId: string) { + const status = await this.jobQueueService.getStatus(jobId); + if (!status) throw new NotFoundException('Riot job not found.'); + return status; + } +} diff --git a/apps/api/src/modules/riot-job-queue/riot-job-queue.module.ts b/apps/api/src/modules/riot-job-queue/riot-job-queue.module.ts new file mode 100644 index 00000000..1bfcae9d --- /dev/null +++ b/apps/api/src/modules/riot-job-queue/riot-job-queue.module.ts @@ -0,0 +1,16 @@ +import { forwardRef, Module } from '@nestjs/common'; +import { LegacyImportModule } from '../legacy-import/legacy-import.module'; +import { RiotModule } from '../riot/riot.module'; +import { TournamentResultModule } from '../tournament-result/tournament-result.module'; +import { RiotJobQueueController } from './riot-job-queue.controller'; +import { RiotJobQueueService } from './riot-job-queue.service'; +import { RiotJobWorkerService } from './riot-job-worker.service'; +import { RiotRefreshGateway } from './riot-refresh.gateway'; + +@Module({ + imports: [RiotModule, LegacyImportModule, forwardRef(() => TournamentResultModule)], + controllers: [RiotJobQueueController], + providers: [RiotJobQueueService, RiotJobWorkerService, RiotRefreshGateway], + exports: [RiotJobQueueService], +}) +export class RiotJobQueueModule {} diff --git a/apps/api/src/modules/riot-job-queue/riot-job-queue.service.ts b/apps/api/src/modules/riot-job-queue/riot-job-queue.service.ts new file mode 100644 index 00000000..ecacef15 --- /dev/null +++ b/apps/api/src/modules/riot-job-queue/riot-job-queue.service.ts @@ -0,0 +1,482 @@ +import { + BadRequestException, + HttpException, + HttpStatus, + Injectable, + NotFoundException, +} from '@nestjs/common'; +import { randomUUID } from 'crypto'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import type { + CommunityDocument, + RiotAccount, + UserDocument, +} from '../global/database/schema'; +import { GarnetService } from '../global/garnet/garnet.service'; +import { + isRiotQueueGroup, + resolveRiotQueueIds, + type RiotQueueGroup, +} from '../riot/riot-queue.constants'; +import { + EnqueueRefreshResult, + RIOT_JOB_AVG_SECONDS, + RIOT_JOB_DEDUP_TTL_SECONDS, + RIOT_JOB_HIGH_COOLDOWN_SECONDS, + RIOT_JOB_HIGH_STREAM, + RIOT_JOB_LOW_COOLDOWN_SECONDS, + RIOT_JOB_LOW_STREAM, + RIOT_JOB_SCHEDULED_ZSET, + RIOT_JOB_STATUS_TTL_SECONDS, + RiotJobPriority, + RiotJobState, + RiotJobStatus, + RiotParentJobStatus, + RiotRefreshEvent, + RiotRefreshSubJob, +} from './riot-job-queue.types'; +import type { + EnqueueTournamentResultPollResult, + PollTournamentResultJob, +} from '../tournament-result/tournament-result.types'; + +interface RefreshContext { + community: CommunityDocument; + user: UserDocument; + account: RiotAccount; +} + +@Injectable() +export class RiotJobQueueService { + constructor( + private readonly connectionService: ConnectionService, + private readonly garnetService: GarnetService, + ) {} + + public async enqueueRefresh(params: { + communityId: mongoose.Types.ObjectId; + userId: mongoose.Types.ObjectId; + queueGroups: string[]; + priority: RiotJobPriority; + requestedBy?: string; + }): Promise { + const context = await this.resolveContext(params); + const queueGroups = this.normalizeQueueGroups(params.queueGroups); + const stream = this.resolveStream(params.priority); + const streamLength = await this.garnetService.streamLength(stream); + const dedupKeys = queueGroups.map((queueGroup) => + this.dedupKey(context.account.puuid, queueGroup), + ); + const existingJobIds = await Promise.all( + dedupKeys.map((key) => this.garnetService.getString(key)), + ); + const needsNewJob = existingJobIds.some((jobId) => !jobId); + + if (params.priority === 'high' && needsNewJob) { + this.assertHighQueueAccepting(streamLength); + this.assertRefreshBudget(context.account.lastRefreshRequestedAt, 'high'); + } + if (params.priority === 'low' && needsNewJob) { + this.assertRefreshBudget(context.account.lastRefreshRequestedAt, 'low'); + } + + const parentJobId = randomUUID(); + const subJobs: EnqueueRefreshResult['subJobs'] = []; + + for (let index = 0; index < queueGroups.length; index += 1) { + const queueGroup = queueGroups[index]; + const existingJobId = existingJobIds[index]; + const queuePosition = streamLength + subJobs.length + 1; + + if (existingJobId) { + const existingStatus = await this.getStatus(existingJobId); + subJobs.push({ + jobId: existingJobId, + queueGroup, + alreadyQueued: true, + etaSeconds: existingStatus?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS, + queuePosition: existingStatus?.queuePosition ?? queuePosition, + }); + continue; + } + + const job: RiotRefreshSubJob = { + jobId: randomUUID(), + parentJobId, + userId: context.user._id.toString(), + puuid: context.account.puuid, + region: context.community.riotRegion ?? 'asia', + platform: context.community.riotPlatform ?? 'kr', + queueGroup, + queueIds: resolveRiotQueueIds(queueGroup, 'all'), + requestedAt: Date.now(), + requestedBy: params.requestedBy, + priority: params.priority, + }; + const acquired = await this.garnetService.setStringIfAbsent( + dedupKeys[index], + job.jobId, + RIOT_JOB_DEDUP_TTL_SECONDS, + ); + if (!acquired) { + const jobId = await this.garnetService.getString(dedupKeys[index]); + if (!jobId) continue; + const status = await this.getStatus(jobId); + subJobs.push({ + jobId, + queueGroup, + alreadyQueued: true, + etaSeconds: status?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS, + queuePosition: status?.queuePosition ?? queuePosition, + }); + continue; + } + + const status: RiotJobStatus = { + jobId: job.jobId, + parentJobId, + state: 'queued', + priority: params.priority, + queueGroup, + queueIds: job.queueIds, + puuid: job.puuid, + userId: job.userId, + enqueuedAt: new Date(job.requestedAt).toISOString(), + etaSeconds: queuePosition * RIOT_JOB_AVG_SECONDS, + queuePosition, + }; + + await Promise.all([ + this.setStatus(status), + this.garnetService.appendStream( + stream, + { job: JSON.stringify(job) }, + { maxLen: 10_000 }, + ), + ]); + subJobs.push({ + jobId: job.jobId, + queueGroup, + alreadyQueued: false, + etaSeconds: status.etaSeconds, + queuePosition, + }); + } + + await this.setParent(parentJobId, subJobs.map((job) => job.jobId)); + if (params.priority === 'high' && needsNewJob) { + await this.markRefreshRequested(context.user._id, context.account.puuid); + } + + return { + parentJobId, + subJobs, + totalEtaSeconds: subJobs.reduce((sum, job) => sum + job.etaSeconds, 0), + }; + } + + public async enqueueTournamentResultPoll(params: { + matchId: string; + attempt: number; + expandedToAllPuuids: boolean; + priority: RiotJobPriority; + deferUntilMs?: number; + }): Promise { + const job: PollTournamentResultJob = { + kind: 'poll-tournament-result', + jobId: randomUUID(), + matchId: params.matchId, + attempt: params.attempt, + expandedToAllPuuids: params.expandedToAllPuuids, + enqueuedAt: Date.now(), + priority: params.priority, + }; + + if (params.deferUntilMs && params.deferUntilMs > Date.now()) { + await this.scheduleJob(job, params.deferUntilMs); + } else { + await this.appendJob(job); + } + + return { + jobId: job.jobId, + matchId: job.matchId, + priority: job.priority, + attempt: job.attempt, + expandedToAllPuuids: job.expandedToAllPuuids, + }; + } + + public async promoteDueScheduledJobs(limit = 100): Promise { + const client = this.garnetService.raw(); + const raw = (await client.sendCommand([ + 'ZRANGEBYSCORE', + RIOT_JOB_SCHEDULED_ZSET, + '-inf', + String(Date.now()), + 'LIMIT', + '0', + String(limit), + ])) as string[] | null; + const entries = raw ?? []; + let promoted = 0; + + for (const entry of entries) { + const removed = (await client.sendCommand([ + 'ZREM', + RIOT_JOB_SCHEDULED_ZSET, + entry, + ])) as number; + if (removed !== 1) continue; + const job = this.parseScheduledJob(entry); + if (!job) continue; + await this.appendJob(job); + promoted += 1; + } + + return promoted; + } + + public async getStatus(jobId: string): Promise { + return this.garnetService.getJson(this.statusKey(jobId)); + } + + public async getParentStatus( + parentJobId: string, + ): Promise { + const jobIds = await this.garnetService.getJson( + this.parentKey(parentJobId), + ); + if (!jobIds) return null; + + const subJobs = ( + await Promise.all(jobIds.map((jobId) => this.getStatus(jobId))) + ).filter((status): status is RiotJobStatus => Boolean(status)); + const done = subJobs.filter((job) => + job.state === 'completed' || job.state === 'failed', + ).length; + const state = this.resolveParentState(subJobs); + + return { + parentJobId, + state, + done, + total: subJobs.length, + etaSeconds: subJobs + .filter((job) => job.state === 'queued' || job.state === 'processing') + .reduce((sum, job) => sum + job.etaSeconds, 0), + subJobs, + }; + } + + public async markProcessing(job: RiotRefreshSubJob): Promise { + const status = await this.requireStatus(job.jobId); + const next: RiotJobStatus = { + ...status, + state: 'processing', + startedAt: new Date().toISOString(), + etaSeconds: RIOT_JOB_AVG_SECONDS, + queuePosition: 0, + }; + await this.setStatus(next); + return next; + } + + public async markCompleted( + job: RiotRefreshSubJob, + ): Promise { + const status = await this.requireStatus(job.jobId); + const next: RiotJobStatus = { + ...status, + state: 'completed', + finishedAt: new Date().toISOString(), + etaSeconds: 0, + queuePosition: 0, + }; + await Promise.all([ + this.setStatus(next), + this.garnetService.delete(this.dedupKey(job.puuid, job.queueGroup)), + ]); + return this.toEvent(next); + } + + public async markFailed( + job: RiotRefreshSubJob, + error: unknown, + ): Promise { + const message = error instanceof Error ? error.message : String(error); + const status = await this.requireStatus(job.jobId); + const next: RiotJobStatus = { + ...status, + state: 'failed', + finishedAt: new Date().toISOString(), + error: message, + etaSeconds: 0, + queuePosition: 0, + }; + await Promise.all([ + this.setStatus(next), + this.garnetService.delete(this.dedupKey(job.puuid, job.queueGroup)), + ]); + return this.toEvent(next); + } + + private async resolveContext(params: { + communityId: mongoose.Types.ObjectId; + userId: mongoose.Types.ObjectId; + }): Promise { + const UserModel = await this.connectionService.getModel('user'); + const CommunityModel = await this.connectionService.getModel('community'); + const [user, community] = await Promise.all([ + UserModel.findById(params.userId).exec(), + CommunityModel.findById(params.communityId).exec(), + ]); + if (!community) throw new NotFoundException('Community not found.'); + if (!user || !user.communityId.equals(params.communityId)) { + throw new NotFoundException('User not found.'); + } + + const account = + user.riotAccounts.find((riotAccount) => riotAccount.isPrimary) ?? + user.riotAccounts[0]; + if (!account) throw new NotFoundException('Riot account not found.'); + return { community, user, account }; + } + + private normalizeQueueGroups(queueGroups: string[]): RiotQueueGroup[] { + const values = queueGroups.length > 0 ? queueGroups : ['summoners-rift']; + const unique = [...new Set(values)]; + if (!unique.every(isRiotQueueGroup)) { + throw new BadRequestException('Invalid queueGroups.'); + } + return unique; + } + + private assertHighQueueAccepting(streamLength: number): void { + if (streamLength <= 50) return; + throw new HttpException( + { + reason: 'queue-full', + retryAfterSeconds: RIOT_JOB_AVG_SECONDS * streamLength, + }, + HttpStatus.TOO_MANY_REQUESTS, + ); + } + + private assertRefreshBudget( + lastRequestedAt: Date | undefined, + priority: RiotJobPriority, + ): void { + if (!lastRequestedAt) return; + const cooldownSeconds = + priority === 'high' + ? RIOT_JOB_HIGH_COOLDOWN_SECONDS + : RIOT_JOB_LOW_COOLDOWN_SECONDS; + const elapsedSeconds = (Date.now() - lastRequestedAt.getTime()) / 1000; + if (elapsedSeconds >= cooldownSeconds) return; + throw new HttpException( + { + reason: 'cooldown', + retryAfterSeconds: Math.ceil(cooldownSeconds - elapsedSeconds), + }, + HttpStatus.TOO_MANY_REQUESTS, + ); + } + + private async markRefreshRequested( + userId: mongoose.Types.ObjectId, + puuid: string, + ): Promise { + const UserModel = await this.connectionService.getModel('user'); + await UserModel.updateOne( + { _id: userId, 'riotAccounts.puuid': puuid }, + { $set: { 'riotAccounts.$.lastRefreshRequestedAt': new Date() } }, + ).exec(); + } + + private resolveStream(priority: RiotJobPriority): string { + return priority === 'high' ? RIOT_JOB_HIGH_STREAM : RIOT_JOB_LOW_STREAM; + } + + private async appendJob(job: RiotRefreshSubJob | PollTournamentResultJob) { + await this.garnetService.appendStream( + this.resolveStream(job.priority), + { job: JSON.stringify(job) }, + { maxLen: 10_000 }, + ); + } + + private async scheduleJob( + job: PollTournamentResultJob, + deferUntilMs: number, + ): Promise { + await this.garnetService.raw().sendCommand([ + 'ZADD', + RIOT_JOB_SCHEDULED_ZSET, + String(deferUntilMs), + JSON.stringify(job), + ]); + } + + private parseScheduledJob(value: string): PollTournamentResultJob | null { + try { + const parsed = JSON.parse(value) as PollTournamentResultJob; + return parsed.kind === 'poll-tournament-result' ? parsed : null; + } catch { + return null; + } + } + + private resolveParentState(subJobs: RiotJobStatus[]): RiotJobState { + if (subJobs.some((job) => job.state === 'processing')) return 'processing'; + if (subJobs.some((job) => job.state === 'queued')) return 'queued'; + if (subJobs.some((job) => job.state === 'failed')) return 'failed'; + return 'completed'; + } + + private async requireStatus(jobId: string): Promise { + const status = await this.getStatus(jobId); + if (!status) throw new Error(`Missing riot job status: ${jobId}`); + return status; + } + + private async setStatus(status: RiotJobStatus): Promise { + await this.garnetService.setJson( + this.statusKey(status.jobId), + status, + RIOT_JOB_STATUS_TTL_SECONDS, + ); + } + + private async setParent(parentJobId: string, jobIds: string[]): Promise { + await this.garnetService.setJson( + this.parentKey(parentJobId), + jobIds, + RIOT_JOB_STATUS_TTL_SECONDS, + ); + } + + private toEvent(status: RiotJobStatus): RiotRefreshEvent { + return { + parentJobId: status.parentJobId, + jobId: status.jobId, + queueGroup: status.queueGroup, + puuid: status.puuid, + state: status.state, + error: status.error, + }; + } + + private statusKey(jobId: string): string { + return `riot:job:status:${jobId}`; + } + + private parentKey(parentJobId: string): string { + return `riot:job:parent:${parentJobId}`; + } + + private dedupKey(puuid: string, queueGroup: RiotQueueGroup): string { + return `riot:job:dedup:${puuid}:${queueGroup}`; + } +} diff --git a/apps/api/src/modules/riot-job-queue/riot-job-queue.types.ts b/apps/api/src/modules/riot-job-queue/riot-job-queue.types.ts new file mode 100644 index 00000000..45968dd0 --- /dev/null +++ b/apps/api/src/modules/riot-job-queue/riot-job-queue.types.ts @@ -0,0 +1,88 @@ +import type { + RiotPlatformRoute, + RiotRegionalRoute, +} from '../riot/riot.types'; +import type { RiotQueueGroup } from '../riot/riot-queue.constants'; +import type { PollTournamentResultJob } from '../tournament-result/tournament-result.types'; +import type { LegacyImportMemberJob } from '../legacy-import/legacy-import.types'; + +export const RIOT_JOB_HIGH_STREAM = 'riot:queue:high'; +export const RIOT_JOB_LOW_STREAM = 'riot:queue:low'; +export const RIOT_JOB_SCHEDULED_ZSET = 'riot:queue:scheduled'; +export const RIOT_JOB_GROUP = 'riot-refresh-worker'; +export const RIOT_JOB_STATUS_TTL_SECONDS = 24 * 60 * 60; +export const RIOT_JOB_DEDUP_TTL_SECONDS = 5 * 60; +export const RIOT_JOB_HIGH_COOLDOWN_SECONDS = 5 * 60; +export const RIOT_JOB_LOW_COOLDOWN_SECONDS = 60 * 60; +export const RIOT_JOB_AVG_SECONDS = 20; + +export type RiotJobPriority = 'high' | 'low'; +export type RiotJobState = 'queued' | 'processing' | 'completed' | 'failed'; + +export interface RiotRefreshSubJob { + kind?: 'refresh-account'; + jobId: string; + parentJobId: string; + userId: string; + puuid: string; + region: RiotRegionalRoute; + platform: RiotPlatformRoute; + queueGroup: RiotQueueGroup; + queueIds: number[]; + requestedAt: number; + requestedBy?: string; + priority: RiotJobPriority; +} + +export type RiotJobPayload = + | RiotRefreshSubJob + | PollTournamentResultJob + | LegacyImportMemberJob; + +export interface RiotJobStatus { + jobId: string; + parentJobId: string; + state: RiotJobState; + priority: RiotJobPriority; + queueGroup: RiotQueueGroup; + queueIds: number[]; + puuid: string; + userId: string; + enqueuedAt: string; + startedAt?: string; + finishedAt?: string; + error?: string; + etaSeconds: number; + queuePosition: number; + alreadyQueued?: boolean; +} + +export interface RiotParentJobStatus { + parentJobId: string; + state: RiotJobState; + done: number; + total: number; + etaSeconds: number; + subJobs: RiotJobStatus[]; +} + +export interface RiotRefreshEvent { + parentJobId: string; + jobId: string; + queueGroup: RiotQueueGroup; + puuid: string; + state: RiotJobState; + error?: string; +} + +export interface EnqueueRefreshResult { + parentJobId: string; + subJobs: Array<{ + jobId: string; + queueGroup: RiotQueueGroup; + alreadyQueued: boolean; + etaSeconds: number; + queuePosition: number; + }>; + totalEtaSeconds: number; +} diff --git a/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts b/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts new file mode 100644 index 00000000..a543d8cb --- /dev/null +++ b/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts @@ -0,0 +1,227 @@ +import { + Injectable, + Logger, + OnModuleDestroy, + OnModuleInit, +} from '@nestjs/common'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import { GarnetService, StreamEntry } from '../global/garnet/garnet.service'; +import { LegacyImportService } from '../legacy-import/legacy-import.service'; +import type { LegacyImportMemberJob } from '../legacy-import/legacy-import.types'; +import { RiotRecentMatchesService } from '../riot/riot-recent-matches.service'; +import { + RIOT_JOB_GROUP, + RIOT_JOB_HIGH_STREAM, + RIOT_JOB_LOW_STREAM, + RiotJobPayload, + RiotRefreshSubJob, +} from './riot-job-queue.types'; +import { RiotJobQueueService } from './riot-job-queue.service'; +import { RiotRefreshGateway } from './riot-refresh.gateway'; +import { TournamentResultService } from '../tournament-result/tournament-result.service'; +import type { PollTournamentResultJob } from '../tournament-result/tournament-result.types'; + +const LEADER_KEY = 'riot:worker:leader'; +const LEADER_TTL_SECONDS = 60; + +@Injectable() +export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy { + private readonly logger = new Logger(RiotJobWorkerService.name); + private readonly consumer = `${process.pid}:${Math.random().toString(36).slice(2)}`; + private stopped = false; + + constructor( + private readonly garnetService: GarnetService, + private readonly jobQueueService: RiotJobQueueService, + private readonly recentMatchesService: RiotRecentMatchesService, + private readonly connectionService: ConnectionService, + private readonly refreshGateway: RiotRefreshGateway, + private readonly tournamentResultService: TournamentResultService, + private readonly legacyImportService: LegacyImportService, + ) {} + + public async onModuleInit() { + await this.ensureConsumerGroups(); + void this.loop(); + } + + public onModuleDestroy() { + this.stopped = true; + } + + private async loop(): Promise { + while (!this.stopped) { + try { + const isLeader = await this.tryBecomeLeader(); + if (!isLeader) { + await this.sleep(1_000); + continue; + } + + await this.jobQueueService.promoteDueScheduledJobs(); + const entry = + (await this.readOne(RIOT_JOB_HIGH_STREAM, 100)) ?? + (await this.readOne(RIOT_JOB_LOW_STREAM, 1_000)); + if (!entry) continue; + + await this.processEntry(entry.stream, entry.message); + } catch (error) { + this.logger.warn( + `Riot job worker loop failed: ${ + error instanceof Error ? error.message : error + }`, + ); + await this.sleep(1_000); + } + } + } + + private async processEntry(stream: string, entry: StreamEntry): Promise { + const job = this.parseJob(entry); + if (!job) { + await this.garnetService.acknowledgeStream(stream, RIOT_JOB_GROUP, entry.id); + return; + } + + try { + if (this.isTournamentResultJob(job)) { + await this.tournamentResultService.processPollJob(job); + return; + } + if (this.isLegacyImportJob(job)) { + await this.legacyImportService.processMemberJob(job); + return; + } + + await this.jobQueueService.markProcessing(job); + for (const queueId of job.queueIds) { + await this.recentMatchesService.ensureFreshForQueue({ + puuid: job.puuid, + region: job.region, + queueId, + }); + } + await this.markUserFetchedAt(job); + const event = await this.jobQueueService.markCompleted(job); + this.refreshGateway.broadcastRefreshEvent(event); + } catch (error) { + if (this.isTournamentResultJob(job)) { + this.logger.warn( + `Tournament result poll job failed ${job.jobId}: ${ + error instanceof Error ? error.message : error + }`, + ); + return; + } + if (this.isLegacyImportJob(job)) { + this.logger.warn( + `Legacy import member job failed ${job.jobId}: ${ + error instanceof Error ? error.message : error + }`, + ); + return; + } + + const event = await this.jobQueueService.markFailed(job, error); + this.refreshGateway.broadcastRefreshEvent(event); + this.logger.warn( + `Riot refresh job failed ${job.jobId}: ${ + error instanceof Error ? error.message : error + }`, + ); + } finally { + await this.garnetService.acknowledgeStream(stream, RIOT_JOB_GROUP, entry.id); + } + } + + private async markUserFetchedAt(job: RiotRefreshSubJob): Promise { + const UserModel = await this.connectionService.getModel('user'); + const now = new Date(); + const $set: Record = { + 'riotAccounts.$.matchIdsFetchedAt': now, + }; + for (const queueId of job.queueIds) { + $set[`riotAccounts.$.matchIdsByQueueFetchedAt.${queueId}`] = now; + } + await UserModel.updateOne( + { + _id: new mongoose.Types.ObjectId(job.userId), + 'riotAccounts.puuid': job.puuid, + }, + { $set }, + ).exec(); + } + + private parseJob(entry: StreamEntry): RiotJobPayload | null { + const raw = entry.message.job; + if (!raw) return null; + try { + return JSON.parse(raw) as RiotJobPayload; + } catch { + return null; + } + } + + private isTournamentResultJob( + job: RiotJobPayload, + ): job is PollTournamentResultJob { + return job.kind === 'poll-tournament-result'; + } + + private isLegacyImportJob( + job: RiotJobPayload, + ): job is LegacyImportMemberJob { + return job.kind === 'legacy-import-member'; + } + + private async readOne( + stream: string, + blockMs: number, + ): Promise<{ stream: string; message: StreamEntry } | null> { + const result = await this.garnetService.readGroup( + stream, + RIOT_JOB_GROUP, + this.consumer, + '>', + { count: 1, blockMs }, + ); + const message = result?.[0]?.messages[0]; + return message ? { stream, message } : null; + } + + private async ensureConsumerGroups(): Promise { + await Promise.all( + [RIOT_JOB_HIGH_STREAM, RIOT_JOB_LOW_STREAM].map(async (stream) => { + try { + await this.garnetService.createConsumerGroup(stream, RIOT_JOB_GROUP); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + if (!message.includes('BUSYGROUP')) throw error; + } + }), + ); + } + + private async tryBecomeLeader(): Promise { + const current = await this.garnetService.getString(LEADER_KEY); + if (current === this.consumer) { + await this.garnetService.setString( + LEADER_KEY, + this.consumer, + LEADER_TTL_SECONDS, + ); + return true; + } + if (current) return false; + return this.garnetService.setStringIfAbsent( + LEADER_KEY, + this.consumer, + LEADER_TTL_SECONDS, + ); + } + + private sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); + } +} diff --git a/apps/api/src/modules/riot-job-queue/riot-refresh.gateway.ts b/apps/api/src/modules/riot-job-queue/riot-refresh.gateway.ts new file mode 100644 index 00000000..477fd717 --- /dev/null +++ b/apps/api/src/modules/riot-job-queue/riot-refresh.gateway.ts @@ -0,0 +1,78 @@ +import { Logger } from '@nestjs/common'; +import { + ConnectedSocket, + MessageBody, + SubscribeMessage, + WebSocketGateway, + WebSocketServer, +} from '@nestjs/websockets'; +import type { Namespace, Socket } from 'socket.io'; +import type { RiotRefreshEvent } from './riot-job-queue.types'; + +interface SubscribePayload { + puuid?: string; + parentJobId?: string; +} + +const MAX_ROOMS_PER_SOCKET = 5; + +@WebSocketGateway({ + namespace: '/riot-refresh', + cors: { + origin: true, + credentials: true, + allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'], + }, +}) +export class RiotRefreshGateway { + @WebSocketServer() + private server!: Namespace; + + private readonly logger = new Logger(RiotRefreshGateway.name); + + @SubscribeMessage('subscribe') + public async handleSubscribe( + @ConnectedSocket() socket: Socket, + @MessageBody() payload: SubscribePayload, + ) { + const rooms = this.resolveRooms(payload); + if (rooms.length === 0) { + socket.emit('error', { message: 'Invalid riot refresh subscription.' }); + return; + } + + const currentRooms = [...socket.rooms].filter((room) => room !== socket.id); + if (currentRooms.length + rooms.length > MAX_ROOMS_PER_SOCKET) { + socket.emit('error', { message: 'Too many riot refresh subscriptions.' }); + return; + } + + await Promise.all(rooms.map((room) => socket.join(room))); + socket.emit('subscribed', { rooms }); + } + + public broadcastRefreshEvent(event: RiotRefreshEvent): void { + const rooms = [ + `puuid:${event.puuid}`, + `parent:${event.parentJobId}`, + `job:${event.jobId}`, + ]; + this.logger.debug( + `Broadcast riot refresh ${event.state}: ${event.jobId} (${event.queueGroup})`, + ); + for (const room of rooms) { + this.server.to(room).emit('riot-refresh', event); + } + } + + private resolveRooms(payload: SubscribePayload): string[] { + const rooms: string[] = []; + if (typeof payload?.puuid === 'string' && payload.puuid.trim()) { + rooms.push(`puuid:${payload.puuid.trim()}`); + } + if (typeof payload?.parentJobId === 'string' && payload.parentJobId.trim()) { + rooms.push(`parent:${payload.parentJobId.trim()}`); + } + return rooms; + } +} diff --git a/apps/api/src/modules/riot/riot-match.service.spec.ts b/apps/api/src/modules/riot/riot-match.service.spec.ts new file mode 100644 index 00000000..6aef710b --- /dev/null +++ b/apps/api/src/modules/riot/riot-match.service.spec.ts @@ -0,0 +1,109 @@ +import { RiotClientService } from './riot.client.service'; +import { RiotMatchService } from './riot-match.service'; +import type { RiotResponseParser } from './riot.types'; + +function createMatchPayload() { + const participant = { + assists: 7, + champExperience: 12000, + champLevel: 16, + championId: 103, + championName: 'Ahri', + deaths: 2, + goldEarned: 12000, + goldSpent: 11000, + individualPosition: '', + item0: 0, + item1: 0, + item2: 0, + item3: 0, + item4: 0, + item5: 0, + item6: 0, + kills: 8, + neutralMinionsKilled: 12, + participantId: 1, + perks: { + statPerks: { defense: 0, flex: 0, offense: 0 }, + styles: [], + }, + puuid: 'puuid-1', + riotIdGameName: '테스터', + riotIdTagLine: 'KR1', + summoner1Id: 4, + summoner2Id: 14, + summonerId: 'summoner-id-1', + summonerLevel: 100, + summonerName: '', + teamId: 100, + teamPosition: '', + timePlayed: 1800, + totalDamageDealtToChampions: 22000, + totalDamageTaken: 11000, + totalMinionsKilled: 180, + visionScore: 20, + wardsKilled: 2, + wardsPlaced: 10, + win: true, + }; + + return { + metadata: { + dataVersion: '2', + matchId: 'KR_8188913502', + participants: ['puuid-1'], + }, + info: { + gameCreation: 1777000000000, + gameDuration: 1800, + gameEndTimestamp: 1777001800000, + gameId: 8188913502, + gameMode: 'CLASSIC', + gameName: 'teambuilder-match-8188913502', + gameStartTimestamp: 1777000000000, + gameType: 'MATCHED_GAME', + gameVersion: '15.8.1', + mapId: 11, + participants: [participant], + platformId: 'KR', + queueId: 420, + teams: [ + { + bans: [], + objectives: { + baron: { first: false, kills: 0 }, + champion: { first: true, kills: 25 }, + dragon: { first: true, kills: 3 }, + inhibitor: { first: false, kills: 1 }, + riftHerald: { first: true, kills: 1 }, + tower: { first: true, kills: 8 }, + }, + teamId: 100, + win: true, + }, + ], + }, + }; +} + +describe('RiotMatchService', () => { + it('accepts empty Riot display fields in match participants', async () => { + const payload = createMatchPayload(); + const riotClientService = { + get: jest.fn( + async ( + _path: string, + _options: unknown, + parser?: RiotResponseParser, + ) => (parser ? parser(payload) : (payload as T)), + ), + } as unknown as RiotClientService; + const service = new RiotMatchService(riotClientService); + + const match = await service.getMatch('KR_8188913502', { region: 'asia' }); + + expect(match.info.participants[0].summonerName).toBe(''); + expect(match.info.participants[0].teamPosition).toBe(''); + expect(match.info.participants[0].individualPosition).toBe(''); + }); +}); diff --git a/apps/api/src/modules/riot/riot-match.service.ts b/apps/api/src/modules/riot/riot-match.service.ts new file mode 100644 index 00000000..33aaeb86 --- /dev/null +++ b/apps/api/src/modules/riot/riot-match.service.ts @@ -0,0 +1,630 @@ +import { Injectable } from '@nestjs/common'; +import { RiotClientService } from './riot.client.service'; +import { + RiotMatchBanDto, + RiotMatchDto, + RiotMatchIdsLookupOptions, + RiotMatchInfoDto, + RiotMatchLookupOptions, + RiotMatchMetadataDto, + RiotMatchObjectiveDto, + RiotMatchObjectivesDto, + RiotMatchParticipantDto, + RiotMatchPerksDto, + RiotMatchPerkStyleDto, + RiotMatchPerkStyleSelectionDto, + RiotMatchStatPerksDto, + RiotMatchTeamDto, + RiotMatchType, +} from './riot.types'; + +const RIOT_MATCH_TYPES: RiotMatchType[] = [ + 'ranked', + 'normal', + 'tourney', + 'tutorial', +]; + +@Injectable() +export class RiotMatchService { + constructor(private readonly riotClientService: RiotClientService) {} + + public async getMatchIdsByPuuid( + puuid: string, + options: RiotMatchIdsLookupOptions = {}, + ): Promise { + validateMatchIdsLookupOptions(options); + + return this.riotClientService.get( + `/lol/match/v5/matches/by-puuid/${encodeURIComponent(puuid)}/ids`, + { + region: options.region, + signal: options.signal, + query: { + start: options.start, + count: options.count, + queue: options.queue, + type: options.type, + startTime: options.startTime, + endTime: options.endTime, + }, + }, + parseMatchIdsResponse, + ); + } + + public async getMatch( + matchId: string, + options: RiotMatchLookupOptions = {}, + ): Promise { + return this.riotClientService.get( + `/lol/match/v5/matches/${encodeURIComponent(matchId)}`, + { + region: options.region, + signal: options.signal, + }, + parseMatchResponse, + ); + } +} + +function validateMatchIdsLookupOptions( + options: RiotMatchIdsLookupOptions, +): void { + assertOptionalNonNegativeInteger(options.start, 'start'); + assertOptionalRange(options.count, 'count', 0, 100); + assertOptionalNonNegativeInteger(options.queue, 'queue'); + assertOptionalNonNegativeInteger(options.startTime, 'startTime'); + assertOptionalNonNegativeInteger(options.endTime, 'endTime'); + + if (options.type !== undefined && !RIOT_MATCH_TYPES.includes(options.type)) { + throw new RangeError( + `type must be one of: ${RIOT_MATCH_TYPES.join(', ')}`, + ); + } + + if ( + options.startTime !== undefined && + options.endTime !== undefined && + options.startTime > options.endTime + ) { + throw new RangeError('startTime must be less than or equal to endTime.'); + } +} + +function parseMatchIdsResponse(value: unknown): string[] { + if (!Array.isArray(value)) { + throw new TypeError('Riot match ids response must be an array.'); + } + + if (!value.every(isNonEmptyString)) { + throw new TypeError('Riot match ids response must contain only strings.'); + } + + return value; +} + +function parseMatchResponse(value: unknown): RiotMatchDto { + if (!isRecord(value)) { + throw new TypeError('Riot match response must be an object.'); + } + + return { + metadata: parseMatchMetadata(value.metadata), + info: parseMatchInfo(value.info), + }; +} + +function parseMatchMetadata(value: unknown): RiotMatchMetadataDto { + if (!isRecord(value)) { + throw new TypeError('Riot match metadata must be an object.'); + } + + const dataVersion = value.dataVersion; + const matchId = value.matchId; + const participants = value.participants; + + if (!isNonEmptyString(dataVersion)) { + throw new TypeError('Riot match metadata.dataVersion must be a string.'); + } + + if (!isNonEmptyString(matchId)) { + throw new TypeError('Riot match metadata.matchId must be a string.'); + } + + if (!Array.isArray(participants) || !participants.every(isNonEmptyString)) { + throw new TypeError( + 'Riot match metadata.participants must be an array of strings.', + ); + } + + return { + dataVersion, + matchId, + participants, + }; +} + +function parseMatchInfo(value: unknown): RiotMatchInfoDto { + if (!isRecord(value)) { + throw new TypeError('Riot match info must be an object.'); + } + + const participants = value.participants; + const teams = value.teams; + + if (!Array.isArray(participants)) { + throw new TypeError('Riot match info.participants must be an array.'); + } + + if (!Array.isArray(teams)) { + throw new TypeError('Riot match info.teams must be an array.'); + } + + const gameCreation = requireNumber(value.gameCreation, 'info.gameCreation'); + const gameDuration = requireNumber(value.gameDuration, 'info.gameDuration'); + const gameId = requireNumber(value.gameId, 'info.gameId'); + const gameMode = requireString(value.gameMode, 'info.gameMode'); + const gameName = requireString(value.gameName, 'info.gameName'); + const gameStartTimestamp = requireNumber( + value.gameStartTimestamp, + 'info.gameStartTimestamp', + ); + const gameType = requireString(value.gameType, 'info.gameType'); + const gameVersion = requireString(value.gameVersion, 'info.gameVersion'); + const mapId = requireNumber(value.mapId, 'info.mapId'); + const platformId = requireString(value.platformId, 'info.platformId'); + const queueId = requireNumber(value.queueId, 'info.queueId'); + const gameEndTimestamp = optionalNumber( + value.gameEndTimestamp, + 'info.gameEndTimestamp', + ); + const tournamentCode = optionalString( + value.tournamentCode, + 'info.tournamentCode', + ); + const endOfGameResult = optionalString( + value.endOfGameResult, + 'info.endOfGameResult', + ); + + return { + ...value, + endOfGameResult, + gameCreation, + gameDuration, + gameEndTimestamp, + gameId, + gameMode, + gameName, + gameStartTimestamp, + gameType, + gameVersion, + mapId, + participants: participants.map((participant, index) => + parseParticipant(participant, index), + ), + platformId, + queueId, + teams: teams.map((team, index) => parseTeam(team, index)), + tournamentCode, + }; +} + +function parseParticipant( + value: unknown, + index: number, +): RiotMatchParticipantDto { + if (!isRecord(value)) { + throw new TypeError(`participants[${index}] must be an object.`); + } + + return { + ...value, + assists: requireNumber(value.assists, `participants[${index}].assists`), + champExperience: requireNumber( + value.champExperience, + `participants[${index}].champExperience`, + ), + champLevel: requireNumber( + value.champLevel, + `participants[${index}].champLevel`, + ), + championId: requireNumber( + value.championId, + `participants[${index}].championId`, + ), + championName: requireString( + value.championName, + `participants[${index}].championName`, + ), + deaths: requireNumber(value.deaths, `participants[${index}].deaths`), + goldEarned: requireNumber( + value.goldEarned, + `participants[${index}].goldEarned`, + ), + goldSpent: requireNumber( + value.goldSpent, + `participants[${index}].goldSpent`, + ), + individualPosition: requireStringAllowEmpty( + value.individualPosition, + `participants[${index}].individualPosition`, + ), + item0: requireNumber(value.item0, `participants[${index}].item0`), + item1: requireNumber(value.item1, `participants[${index}].item1`), + item2: requireNumber(value.item2, `participants[${index}].item2`), + item3: requireNumber(value.item3, `participants[${index}].item3`), + item4: requireNumber(value.item4, `participants[${index}].item4`), + item5: requireNumber(value.item5, `participants[${index}].item5`), + item6: requireNumber(value.item6, `participants[${index}].item6`), + kills: requireNumber(value.kills, `participants[${index}].kills`), + neutralMinionsKilled: requireNumber( + value.neutralMinionsKilled, + `participants[${index}].neutralMinionsKilled`, + ), + participantId: requireNumber( + value.participantId, + `participants[${index}].participantId`, + ), + perks: parsePerks(value.perks, index), + puuid: requireString(value.puuid, `participants[${index}].puuid`), + riotIdGameName: optionalString( + value.riotIdGameName, + `participants[${index}].riotIdGameName`, + ), + riotIdTagLine: optionalString( + value.riotIdTagLine, + `participants[${index}].riotIdTagLine`, + ), + summoner1Id: requireNumber( + value.summoner1Id, + `participants[${index}].summoner1Id`, + ), + summoner2Id: requireNumber( + value.summoner2Id, + `participants[${index}].summoner2Id`, + ), + summonerId: requireString( + value.summonerId, + `participants[${index}].summonerId`, + ), + summonerLevel: requireNumber( + value.summonerLevel, + `participants[${index}].summonerLevel`, + ), + summonerName: requireStringAllowEmpty( + value.summonerName, + `participants[${index}].summonerName`, + ), + teamId: requireNumber(value.teamId, `participants[${index}].teamId`), + teamPosition: requireStringAllowEmpty( + value.teamPosition, + `participants[${index}].teamPosition`, + ), + timePlayed: requireNumber( + value.timePlayed, + `participants[${index}].timePlayed`, + ), + totalDamageDealtToChampions: requireNumber( + value.totalDamageDealtToChampions, + `participants[${index}].totalDamageDealtToChampions`, + ), + totalDamageTaken: requireNumber( + value.totalDamageTaken, + `participants[${index}].totalDamageTaken`, + ), + totalMinionsKilled: requireNumber( + value.totalMinionsKilled, + `participants[${index}].totalMinionsKilled`, + ), + visionScore: requireNumber( + value.visionScore, + `participants[${index}].visionScore`, + ), + wardsKilled: requireNumber( + value.wardsKilled, + `participants[${index}].wardsKilled`, + ), + wardsPlaced: requireNumber( + value.wardsPlaced, + `participants[${index}].wardsPlaced`, + ), + win: requireBoolean(value.win, `participants[${index}].win`), + }; +} + +function parsePerks(value: unknown, participantIndex: number): RiotMatchPerksDto { + if (!isRecord(value)) { + throw new TypeError( + `participants[${participantIndex}].perks must be an object.`, + ); + } + + const styles = value.styles; + if (!Array.isArray(styles)) { + throw new TypeError( + `participants[${participantIndex}].perks.styles must be an array.`, + ); + } + + return { + statPerks: parseStatPerks(value.statPerks, participantIndex), + styles: styles.map((style, styleIndex) => + parsePerkStyle(style, participantIndex, styleIndex), + ), + }; +} + +function parseStatPerks( + value: unknown, + participantIndex: number, +): RiotMatchStatPerksDto { + if (!isRecord(value)) { + throw new TypeError( + `participants[${participantIndex}].perks.statPerks must be an object.`, + ); + } + + return { + defense: requireNumber( + value.defense, + `participants[${participantIndex}].perks.statPerks.defense`, + ), + flex: requireNumber( + value.flex, + `participants[${participantIndex}].perks.statPerks.flex`, + ), + offense: requireNumber( + value.offense, + `participants[${participantIndex}].perks.statPerks.offense`, + ), + }; +} + +function parsePerkStyle( + value: unknown, + participantIndex: number, + styleIndex: number, +): RiotMatchPerkStyleDto { + if (!isRecord(value)) { + throw new TypeError( + `participants[${participantIndex}].perks.styles[${styleIndex}] must be an object.`, + ); + } + + const selections = value.selections; + if (!Array.isArray(selections)) { + throw new TypeError( + `participants[${participantIndex}].perks.styles[${styleIndex}].selections must be an array.`, + ); + } + + return { + description: requireString( + value.description, + `participants[${participantIndex}].perks.styles[${styleIndex}].description`, + ), + selections: selections.map((selection, selectionIndex) => + parsePerkSelection( + selection, + participantIndex, + styleIndex, + selectionIndex, + ), + ), + style: requireNumber( + value.style, + `participants[${participantIndex}].perks.styles[${styleIndex}].style`, + ), + }; +} + +function parsePerkSelection( + value: unknown, + participantIndex: number, + styleIndex: number, + selectionIndex: number, +): RiotMatchPerkStyleSelectionDto { + if (!isRecord(value)) { + throw new TypeError( + `participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}] must be an object.`, + ); + } + + return { + perk: requireNumber( + value.perk, + `participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}].perk`, + ), + var1: requireNumber( + value.var1, + `participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}].var1`, + ), + var2: requireNumber( + value.var2, + `participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}].var2`, + ), + var3: requireNumber( + value.var3, + `participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}].var3`, + ), + }; +} + +function parseTeam(value: unknown, index: number): RiotMatchTeamDto { + if (!isRecord(value)) { + throw new TypeError(`teams[${index}] must be an object.`); + } + + const bans = value.bans; + if (!Array.isArray(bans)) { + throw new TypeError(`teams[${index}].bans must be an array.`); + } + + return { + ...value, + bans: bans.map((ban, banIndex) => parseBan(ban, index, banIndex)), + objectives: parseObjectives(value.objectives, index), + teamId: requireNumber(value.teamId, `teams[${index}].teamId`), + win: requireBoolean(value.win, `teams[${index}].win`), + }; +} + +function parseBan( + value: unknown, + teamIndex: number, + banIndex: number, +): RiotMatchBanDto { + if (!isRecord(value)) { + throw new TypeError(`teams[${teamIndex}].bans[${banIndex}] must be an object.`); + } + + return { + championId: requireNumber( + value.championId, + `teams[${teamIndex}].bans[${banIndex}].championId`, + ), + pickTurn: requireNumber( + value.pickTurn, + `teams[${teamIndex}].bans[${banIndex}].pickTurn`, + ), + }; +} + +function parseObjectives( + value: unknown, + teamIndex: number, +): RiotMatchObjectivesDto { + if (!isRecord(value)) { + throw new TypeError(`teams[${teamIndex}].objectives must be an object.`); + } + + return { + baron: parseObjective(value.baron, teamIndex, 'baron'), + champion: parseObjective(value.champion, teamIndex, 'champion'), + dragon: parseObjective(value.dragon, teamIndex, 'dragon'), + inhibitor: parseObjective(value.inhibitor, teamIndex, 'inhibitor'), + riftHerald: parseObjective(value.riftHerald, teamIndex, 'riftHerald'), + tower: parseObjective(value.tower, teamIndex, 'tower'), + }; +} + +function parseObjective( + value: unknown, + teamIndex: number, + key: keyof RiotMatchObjectivesDto, +): RiotMatchObjectiveDto { + if (!isRecord(value)) { + throw new TypeError(`teams[${teamIndex}].objectives.${key} must be an object.`); + } + + return { + first: requireBoolean( + value.first, + `teams[${teamIndex}].objectives.${key}.first`, + ), + kills: requireNumber( + value.kills, + `teams[${teamIndex}].objectives.${key}.kills`, + ), + }; +} + +function requireString(value: unknown, path: string): string { + if (!isNonEmptyString(value)) { + throw new TypeError(`${path} must be a non-empty string.`); + } + + return value; +} + +function requireStringAllowEmpty(value: unknown, path: string): string { + if (typeof value !== 'string') { + throw new TypeError(`${path} must be a string.`); + } + + return value; +} + +function optionalString(value: unknown, path: string): string | undefined { + if (value === undefined || value === null) { + return undefined; + } + + if (typeof value !== 'string') { + throw new TypeError(`${path} must be a string when present.`); + } + + return value; +} + +function requireNumber(value: unknown, path: string): number { + if (!isFiniteNumber(value)) { + throw new TypeError(`${path} must be a finite number.`); + } + + return value; +} + +function optionalNumber(value: unknown, path: string): number | undefined { + if (value === undefined || value === null) { + return undefined; + } + + if (!isFiniteNumber(value)) { + throw new TypeError(`${path} must be a finite number when present.`); + } + + return value; +} + +function requireBoolean(value: unknown, path: string): boolean { + if (typeof value !== 'boolean') { + throw new TypeError(`${path} must be a boolean.`); + } + + return value; +} + +function assertOptionalNonNegativeInteger( + value: number | undefined, + fieldName: string, +): void { + if (value === undefined) { + return; + } + + if (!Number.isInteger(value) || value < 0) { + throw new RangeError(`${fieldName} must be a non-negative integer.`); + } +} + +function assertOptionalRange( + value: number | undefined, + fieldName: string, + min: number, + max: number, +): void { + if (value === undefined) { + return; + } + + if (!Number.isInteger(value) || value < min || value > max) { + throw new RangeError( + `${fieldName} must be an integer between ${min} and ${max}.`, + ); + } +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} + +function isFiniteNumber(value: unknown): value is number { + return typeof value === 'number' && Number.isFinite(value); +} + +function isNonEmptyString(value: unknown): value is string { + return typeof value === 'string' && value.length > 0; +} diff --git a/apps/api/src/modules/riot/riot-recent-matches.service.ts b/apps/api/src/modules/riot/riot-recent-matches.service.ts new file mode 100644 index 00000000..964dd688 --- /dev/null +++ b/apps/api/src/modules/riot/riot-recent-matches.service.ts @@ -0,0 +1,153 @@ +import { Injectable, Logger } from '@nestjs/common'; +import type { + RiotMatchDocument, + RiotMatch as StoredRiotMatch, +} from '../global/database/schema'; +import { ConnectionService } from '../global/database/connection.service'; +import { GarnetService } from '../global/garnet/garnet.service'; +import type { RiotRegionalRoute } from './riot.types'; +import { RiotMatchService } from './riot-match.service'; + +export const RIOT_RECENT_MATCH_LIMIT = 20; +export const RIOT_SOLO_QUEUE_ID = 420; + +const MATCH_ENRICHMENT_LOCK_TTL_SECONDS = 60; +const MATCH_DETAIL_CONCURRENCY = 2; +const DEFAULT_REGION: RiotRegionalRoute = 'asia'; + +@Injectable() +export class RiotRecentMatchesService { + private readonly logger = new Logger(RiotRecentMatchesService.name); + + constructor( + private readonly connectionService: ConnectionService, + private readonly matchService: RiotMatchService, + private readonly garnetService: GarnetService, + ) {} + + public async syncRecentMatches(params: { + puuid: string; + region?: RiotRegionalRoute; + limit?: number; + queueId?: number; + }): Promise { + const region = params.region ?? DEFAULT_REGION; + const limit = params.limit ?? RIOT_RECENT_MATCH_LIMIT; + const queueId = params.queueId ?? RIOT_SOLO_QUEUE_ID; + const lockKey = `riot:enrich:matches:${params.puuid}`; + const lockValue = `${process.pid}:${Date.now()}`; + + const acquired = await this.garnetService.setStringIfAbsent( + lockKey, + lockValue, + MATCH_ENRICHMENT_LOCK_TTL_SECONDS, + ); + if (!acquired) { + return this.loadFromDb({ puuid: params.puuid, limit, queueId }); + } + + try { + const matchIds = await this.matchService.getMatchIdsByPuuid(params.puuid, { + region, + queue: queueId, + count: limit, + }); + if (matchIds.length === 0) { + return this.loadFromDb({ puuid: params.puuid, limit, queueId }); + } + + const RiotMatchModel = await this.connectionService.getModel('riotMatch'); + const existingMatches = await RiotMatchModel.find({ + matchId: { $in: matchIds }, + }) + .select({ matchId: 1 }) + .lean() + .exec(); + const existingMatchIds = new Set(existingMatches.map((match) => match.matchId)); + const missingMatchIds = matchIds.filter((matchId) => !existingMatchIds.has(matchId)); + + await runWithConcurrency(missingMatchIds, MATCH_DETAIL_CONCURRENCY, async (matchId) => { + const dto = await this.matchService.getMatch(matchId, { region }); + if (dto.info.queueId !== queueId) { + this.logger.warn( + `Skipping unexpected queue ${dto.info.queueId} for ${matchId} while syncing ${params.puuid}.`, + ); + return; + } + + 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 this.loadFromDb({ puuid: params.puuid, limit, queueId }); + } finally { + await this.garnetService.delete(lockKey).catch((error: unknown) => { + this.logger.warn( + `Failed to release recent matches lock for ${params.puuid}: ${ + (error as Error)?.message ?? error + }`, + ); + }); + } + } + + public async ensureFreshForQueue(params: { + puuid: string; + region?: RiotRegionalRoute; + queueId: number; + limit?: number; + }): Promise { + return this.syncRecentMatches(params); + } + + public async loadFromDb(params: { + puuid: string; + limit?: number; + queueId?: number; + }): Promise { + const limit = params.limit ?? RIOT_RECENT_MATCH_LIMIT; + const queueId = params.queueId ?? RIOT_SOLO_QUEUE_ID; + const RiotMatchModel = await this.connectionService.getModel('riotMatch'); + + return RiotMatchModel.find({ + participantPuuids: params.puuid, + queueId, + }) + .sort({ gameCreation: -1 }) + .limit(limit) + .exec(); + } +} + +async function runWithConcurrency( + items: T[], + concurrency: number, + worker: (item: T) => Promise, +): Promise { + if (items.length === 0) return; + + const queue = [...items]; + const runners = Array.from({ length: Math.min(concurrency, queue.length) }, async () => { + while (queue.length > 0) { + const item = queue.shift(); + if (item === undefined) return; + await worker(item); + } + }); + + await Promise.all(runners); +} diff --git a/apps/api/src/modules/riot/riot-recent-stats.service.spec.ts b/apps/api/src/modules/riot/riot-recent-stats.service.spec.ts new file mode 100644 index 00000000..326f1166 --- /dev/null +++ b/apps/api/src/modules/riot/riot-recent-stats.service.spec.ts @@ -0,0 +1,304 @@ +import { RiotRecentStatsService } from './riot-recent-stats.service'; +import type { RiotMatchDto } from './riot.types'; + +function makeMatch(params: { + matchId: string; + gameCreation: number; + gameDuration: number; + puuid: string; + championId: number; + kills: number; + deaths: number; + assists: number; + cs: number; + neutralCs?: number; + win?: boolean; + teamPosition?: string; + individualPosition?: string; +}): RiotMatchDto { + return { + metadata: { + dataVersion: '2', + matchId: params.matchId, + participants: [params.puuid, 'other-1'], + }, + info: { + gameCreation: params.gameCreation, + gameDuration: params.gameDuration, + gameId: 1, + gameMode: 'CLASSIC', + gameName: 'teambuilder-match-1', + gameStartTimestamp: params.gameCreation, + gameType: 'MATCHED_GAME', + gameVersion: '15.8.1', + mapId: 11, + platformId: 'KR', + queueId: 420, + participants: [ + { + assists: params.assists, + champExperience: 10000, + champLevel: 16, + championId: params.championId, + championName: `Champion-${params.championId}`, + deaths: params.deaths, + goldEarned: 12000, + goldSpent: 11000, + individualPosition: params.individualPosition ?? '', + item0: 0, + item1: 0, + item2: 0, + item3: 0, + item4: 0, + item5: 0, + item6: 0, + kills: params.kills, + neutralMinionsKilled: params.neutralCs ?? 0, + participantId: 1, + perks: { + statPerks: { defense: 0, flex: 0, offense: 0 }, + styles: [], + }, + puuid: params.puuid, + riotIdGameName: 'tester', + riotIdTagLine: 'KR1', + summoner1Id: 4, + summoner2Id: 14, + summonerId: 'summoner-1', + summonerLevel: 100, + summonerName: 'tester', + teamId: 100, + teamPosition: params.teamPosition ?? '', + timePlayed: params.gameDuration, + totalDamageDealtToChampions: 10000, + totalDamageTaken: 5000, + totalMinionsKilled: params.cs, + visionScore: 20, + wardsKilled: 2, + wardsPlaced: 10, + win: params.win ?? true, + }, + { + assists: 1, + champExperience: 9000, + champLevel: 15, + championId: 1, + championName: 'Other', + deaths: 5, + goldEarned: 10000, + goldSpent: 9000, + individualPosition: 'TOP', + item0: 0, + item1: 0, + item2: 0, + item3: 0, + item4: 0, + item5: 0, + item6: 0, + kills: 3, + neutralMinionsKilled: 0, + participantId: 2, + perks: { + statPerks: { defense: 0, flex: 0, offense: 0 }, + styles: [], + }, + puuid: 'other-1', + riotIdGameName: 'other', + riotIdTagLine: 'KR1', + summoner1Id: 4, + summoner2Id: 14, + summonerId: 'summoner-2', + summonerLevel: 90, + summonerName: 'other', + teamId: 100, + teamPosition: 'TOP', + timePlayed: params.gameDuration, + totalDamageDealtToChampions: 8000, + totalDamageTaken: 7000, + totalMinionsKilled: 180, + visionScore: 10, + wardsKilled: 1, + wardsPlaced: 5, + win: false, + }, + ], + teams: [ + { + bans: [], + objectives: { + baron: { first: false, kills: 0 }, + champion: { first: false, kills: 0 }, + dragon: { first: false, kills: 0 }, + inhibitor: { first: false, kills: 0 }, + riftHerald: { first: false, kills: 0 }, + tower: { first: false, kills: 0 }, + }, + teamId: 100, + win: params.win ?? true, + }, + { + bans: [], + objectives: { + baron: { first: false, kills: 0 }, + champion: { first: false, kills: 0 }, + dragon: { first: false, kills: 0 }, + inhibitor: { first: false, kills: 0 }, + riftHerald: { first: false, kills: 0 }, + tower: { first: false, kills: 0 }, + }, + teamId: 200, + win: !(params.win ?? true), + }, + ], + }, + }; +} + +describe('RiotRecentStatsService', () => { + const service = new RiotRecentStatsService(); + + it('computes overall and lane summaries for recent solo queue matches', () => { + const matches = [ + makeMatch({ + matchId: 'KR_1', + gameCreation: 1_000, + gameDuration: 1800, + puuid: 'puuid-1', + championId: 103, + kills: 8, + deaths: 2, + assists: 6, + cs: 180, + win: true, + teamPosition: 'MIDDLE', + }), + makeMatch({ + matchId: 'KR_2', + gameCreation: 2_000, + gameDuration: 1500, + puuid: 'puuid-1', + championId: 103, + kills: 4, + deaths: 1, + assists: 8, + cs: 150, + neutralCs: 20, + win: false, + teamPosition: 'MIDDLE', + }), + makeMatch({ + matchId: 'KR_3', + gameCreation: 3_000, + gameDuration: 1800, + puuid: 'puuid-1', + championId: 22, + kills: 10, + deaths: 0, + assists: 5, + cs: 210, + win: true, + teamPosition: '', + individualPosition: 'BOTTOM', + }), + ]; + + const summary = service.computeSummary(matches, 'puuid-1'); + + expect(summary.overall).toEqual({ + games: 3, + wins: 2, + losses: 1, + avgKills: 7.3, + avgDeaths: 1, + avgAssists: 6.3, + avgCs: 186.7, + avgCsPerMin: 6.6, + mostPlayedChampionIds: [103, 22], + }); + expect(summary.byLane.MIDDLE).toEqual({ + games: 2, + wins: 1, + losses: 1, + avgKills: 6, + avgDeaths: 1.5, + avgAssists: 7, + avgCs: 175, + avgCsPerMin: 6.4, + mostPlayedChampionIds: [103], + }); + expect(summary.byLane.BOTTOM).toEqual({ + games: 1, + wins: 1, + losses: 0, + avgKills: 10, + avgDeaths: 0, + avgAssists: 5, + avgCs: 210, + avgCsPerMin: 7, + mostPlayedChampionIds: [22], + }); + }); + + it('skips invalid lane positions from byLane while keeping overall stats', () => { + const summary = service.computeSummary( + [ + makeMatch({ + matchId: 'KR_4', + gameCreation: 4_000, + gameDuration: 1800, + puuid: 'puuid-1', + championId: 61, + kills: 6, + deaths: 3, + assists: 9, + cs: 190, + win: true, + teamPosition: 'Invalid', + individualPosition: '', + }), + ], + 'puuid-1', + ); + + expect(summary.overall.games).toBe(1); + expect(summary.byLane).toEqual({}); + }); + + it('filters out matches before seasonStartedAt', () => { + const summary = service.computeSummary( + [ + makeMatch({ + matchId: 'KR_5', + gameCreation: 1_000, + gameDuration: 1800, + puuid: 'puuid-1', + championId: 61, + kills: 6, + deaths: 3, + assists: 9, + cs: 190, + win: true, + teamPosition: 'MIDDLE', + }), + makeMatch({ + matchId: 'KR_6', + gameCreation: 10_000, + gameDuration: 1800, + puuid: 'puuid-1', + championId: 134, + kills: 9, + deaths: 2, + assists: 7, + cs: 205, + win: true, + teamPosition: 'MIDDLE', + }), + ], + 'puuid-1', + { seasonStartedAt: new Date(5_000) }, + ); + + expect(summary.overall.games).toBe(1); + expect(summary.overall.mostPlayedChampionIds).toEqual([134]); + }); +}); diff --git a/apps/api/src/modules/riot/riot-recent-stats.service.ts b/apps/api/src/modules/riot/riot-recent-stats.service.ts new file mode 100644 index 00000000..62886925 --- /dev/null +++ b/apps/api/src/modules/riot/riot-recent-stats.service.ts @@ -0,0 +1,172 @@ +import { Injectable } from '@nestjs/common'; +import { + createEmptyRiotLaneStats, + createEmptyRiotRecentStatsSummary, + RIOT_LANES, + type RiotLane, + type RiotLaneStats, + type RiotRecentStatsSummary, +} from '../global/database/schema'; +import type { RiotMatchDto, RiotMatchParticipantDto } from './riot.types'; + +interface Aggregate { + games: number; + wins: number; + losses: number; + kills: number; + deaths: number; + assists: number; + cs: number; + csPerMin: number; + championCounts: Map; + lastPlayedAtByChampion: Map; +} + +interface ComputeSummaryOptions { + seasonStartedAt?: Date; +} + +@Injectable() +export class RiotRecentStatsService { + public computeSummary( + matches: RiotMatchDto[], + puuid: string, + options: ComputeSummaryOptions = {}, + ): RiotRecentStatsSummary { + const filteredMatches = this.filterMatchesBySeason(matches, options); + if (filteredMatches.length === 0) { + return createEmptyRiotRecentStatsSummary(); + } + + const overall = createAggregate(); + const laneAggregates = new Map( + RIOT_LANES.map((lane) => [lane, createAggregate()]), + ); + + for (const match of filteredMatches) { + const participant = match.info.participants.find((entry) => entry.puuid === puuid); + if (!participant) continue; + + accumulateAggregate(overall, participant, match.info.gameCreation, match.info.gameDuration); + + const lane = resolveLane(participant); + if (!lane) continue; + + const aggregate = laneAggregates.get(lane); + if (!aggregate) continue; + accumulateAggregate(aggregate, participant, match.info.gameCreation, match.info.gameDuration); + } + + if (overall.games === 0) { + return createEmptyRiotRecentStatsSummary(); + } + + const byLane: Partial> = {}; + for (const lane of RIOT_LANES) { + const aggregate = laneAggregates.get(lane); + if (!aggregate || aggregate.games === 0) continue; + byLane[lane] = finalizeAggregate(aggregate); + } + + return { + overall: finalizeAggregate(overall), + byLane, + }; + } + + private filterMatchesBySeason( + matches: RiotMatchDto[], + options: ComputeSummaryOptions, + ): RiotMatchDto[] { + const startedAt = options.seasonStartedAt?.getTime(); + if (!startedAt) return matches; + return matches.filter((match) => match.info.gameCreation >= startedAt); + } +} + +function createAggregate(): Aggregate { + return { + games: 0, + wins: 0, + losses: 0, + kills: 0, + deaths: 0, + assists: 0, + cs: 0, + csPerMin: 0, + championCounts: new Map(), + lastPlayedAtByChampion: new Map(), + }; +} + +function accumulateAggregate( + aggregate: Aggregate, + participant: RiotMatchParticipantDto, + gameCreation: number, + gameDurationSeconds: number, +): void { + aggregate.games += 1; + aggregate.wins += participant.win ? 1 : 0; + aggregate.losses += participant.win ? 0 : 1; + aggregate.kills += participant.kills; + aggregate.deaths += participant.deaths; + aggregate.assists += participant.assists; + + const cs = participant.totalMinionsKilled + participant.neutralMinionsKilled; + aggregate.cs += cs; + if (gameDurationSeconds > 0) { + aggregate.csPerMin += cs / (gameDurationSeconds / 60); + } + + aggregate.championCounts.set( + participant.championId, + (aggregate.championCounts.get(participant.championId) ?? 0) + 1, + ); + aggregate.lastPlayedAtByChampion.set(participant.championId, gameCreation); +} + +function finalizeAggregate(aggregate: Aggregate): RiotLaneStats { + if (aggregate.games === 0) { + return createEmptyRiotLaneStats(); + } + + const mostPlayedChampionIds = [...aggregate.championCounts.entries()] + .sort((left, right) => { + if (right[1] !== left[1]) return right[1] - left[1]; + const rightLastPlayed = aggregate.lastPlayedAtByChampion.get(right[0]) ?? 0; + const leftLastPlayed = aggregate.lastPlayedAtByChampion.get(left[0]) ?? 0; + if (rightLastPlayed !== leftLastPlayed) { + return rightLastPlayed - leftLastPlayed; + } + return left[0] - right[0]; + }) + .slice(0, 3) + .map(([championId]) => championId); + + return { + games: aggregate.games, + wins: aggregate.wins, + losses: aggregate.losses, + avgKills: roundToOneDecimal(aggregate.kills / aggregate.games), + avgDeaths: roundToOneDecimal(aggregate.deaths / aggregate.games), + avgAssists: roundToOneDecimal(aggregate.assists / aggregate.games), + avgCs: roundToOneDecimal(aggregate.cs / aggregate.games), + avgCsPerMin: roundToOneDecimal(aggregate.csPerMin / aggregate.games), + mostPlayedChampionIds, + }; +} + +function resolveLane(participant: RiotMatchParticipantDto): RiotLane | null { + const candidates = [participant.teamPosition, participant.individualPosition]; + for (const candidate of candidates) { + if (!candidate) continue; + if (RIOT_LANES.includes(candidate as RiotLane)) { + return candidate as RiotLane; + } + } + return null; +} + +function roundToOneDecimal(value: number): number { + return Math.round(value * 10) / 10; +} diff --git a/apps/api/src/modules/riot/riot-webhook.controller.spec.ts b/apps/api/src/modules/riot/riot-webhook.controller.spec.ts new file mode 100644 index 00000000..78bbd913 --- /dev/null +++ b/apps/api/src/modules/riot/riot-webhook.controller.spec.ts @@ -0,0 +1,60 @@ +import type { Request } from 'express'; +import { RiotWebhookController } from './riot-webhook.controller'; + +type RiotWebhookRequest = Request & { + rawBody?: Buffer; +}; + +describe('RiotWebhookController', () => { + let controller: RiotWebhookController; + + beforeEach(() => { + controller = new RiotWebhookController(); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('logs the incoming webhook payload and returns an acknowledgement', () => { + const logSpy = jest.spyOn(console, 'log').mockImplementation(() => undefined); + const dirSpy = jest.spyOn(console, 'dir').mockImplementation(() => undefined); + const request = { + method: 'POST', + originalUrl: '/riot/webhooks/tournament', + protocol: 'https', + hostname: 'example.test', + ip: '127.0.0.1', + ips: ['127.0.0.1'], + headers: { + 'content-type': 'application/json', + }, + query: { + shard: 'kr', + }, + params: {}, + body: { + eventType: 'MATCH_FINISHED', + }, + rawBody: Buffer.from('{"eventType":"MATCH_FINISHED"}', 'utf8'), + } as unknown as RiotWebhookRequest; + + const response = controller.captureTournamentWebhook(request); + + expect(response.ok).toBe(true); + expect(response.message).toBe('Riot webhook received.'); + expect(response.receivedAt).toEqual(expect.any(String)); + expect(logSpy).toHaveBeenCalledTimes(2); + expect(dirSpy).toHaveBeenCalledWith( + expect.objectContaining({ + method: 'POST', + url: '/riot/webhooks/tournament', + body: { + eventType: 'MATCH_FINISHED', + }, + rawBodyText: '{"eventType":"MATCH_FINISHED"}', + }), + { depth: null }, + ); + }); +}); diff --git a/apps/api/src/modules/riot/riot-webhook.controller.ts b/apps/api/src/modules/riot/riot-webhook.controller.ts new file mode 100644 index 00000000..689b2b2e --- /dev/null +++ b/apps/api/src/modules/riot/riot-webhook.controller.ts @@ -0,0 +1,49 @@ +import { + All, + Controller, + HttpCode, + HttpStatus, + Req, +} from '@nestjs/common'; +import type { Request } from 'express'; +import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; + +type RiotWebhookRequest = Request & { + rawBody?: Buffer; +}; + +@Controller('riot') +export class RiotWebhookController { + @All('webhooks/tournament') + @AllowPublicAccess() + @HttpCode(HttpStatus.OK) + public captureTournamentWebhook(@Req() req: RiotWebhookRequest) { + const receivedAt = new Date().toISOString(); + const rawBodyText = req.rawBody?.toString('utf8') ?? null; + const logPayload = { + receivedAt, + method: req.method, + url: req.originalUrl, + protocol: req.protocol, + hostname: req.hostname, + ip: req.ip, + ips: req.ips, + headers: req.headers, + query: req.query, + params: req.params, + body: req.body, + rawBodyLength: req.rawBody?.length ?? null, + rawBodyText, + }; + + console.log('\n[RIOT TOURNAMENT WEBHOOK] Incoming request'); + console.dir(logPayload, { depth: null }); + console.log('[RIOT TOURNAMENT WEBHOOK] End request log\n'); + + return { + ok: true, + message: 'Riot webhook received.', + receivedAt, + }; + } +}