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..704550e9 --- /dev/null +++ b/apps/api/src/modules/riot/riot-recent-matches.service.ts @@ -0,0 +1,161 @@ +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) => { + try { + 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(); + } catch (error: unknown) { + this.logger.warn( + `Skipping Riot match ${matchId} while syncing ${params.puuid}: ${ + error instanceof Error ? error.message : error + }`, + ); + } + }); + + 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); +}