From a47391e885a6f4c387ef897b1ad948e0f7e65e3b 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: Mon, 13 Apr 2026 10:30:00 +0900 Subject: [PATCH] feat(api): integrate Riot account services --- .../riot-account-enrichment.service.spec.ts | 494 ++++++++++++++++++ .../riot/riot-account-enrichment.service.ts | 437 ++++++++++++++++ .../src/modules/riot/riot-account.service.ts | 128 +++++ .../riot/riot-champion-mastery.service.ts | 129 +++++ .../modules/riot/riot-ddragon.controller.ts | 19 + .../src/modules/riot/riot-ddragon.service.ts | 142 +++++ .../src/modules/riot/riot-league.service.ts | 79 +++ .../src/modules/riot/riot-queue.constants.ts | 88 ++++ .../modules/riot/riot-rate-limiter.service.ts | 107 ++++ .../src/modules/riot/riot-summoner.service.ts | 60 +++ .../src/modules/riot/riot.client.service.ts | 177 +++++++ apps/api/src/modules/riot/riot.module.ts | 47 ++ apps/api/src/modules/riot/riot.types.ts | 251 +++++++++ 13 files changed, 2158 insertions(+) create mode 100644 apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts create mode 100644 apps/api/src/modules/riot/riot-account-enrichment.service.ts create mode 100644 apps/api/src/modules/riot/riot-account.service.ts create mode 100644 apps/api/src/modules/riot/riot-champion-mastery.service.ts create mode 100644 apps/api/src/modules/riot/riot-ddragon.controller.ts create mode 100644 apps/api/src/modules/riot/riot-ddragon.service.ts create mode 100644 apps/api/src/modules/riot/riot-league.service.ts create mode 100644 apps/api/src/modules/riot/riot-queue.constants.ts create mode 100644 apps/api/src/modules/riot/riot-rate-limiter.service.ts create mode 100644 apps/api/src/modules/riot/riot-summoner.service.ts create mode 100644 apps/api/src/modules/riot/riot.client.service.ts create mode 100644 apps/api/src/modules/riot/riot.module.ts create mode 100644 apps/api/src/modules/riot/riot.types.ts diff --git a/apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts b/apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts new file mode 100644 index 00000000..7dc5035e --- /dev/null +++ b/apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts @@ -0,0 +1,494 @@ +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import { + createEmptyRiotRecentStatsSummary, + type RiotRecentStatsSummary, +} from '../global/database/schema'; +import { RiotAccountEnrichmentService } from './riot-account-enrichment.service'; +import { RiotAccountService } from './riot-account.service'; +import { RiotChampionMasteryService } from './riot-champion-mastery.service'; +import { RiotApiError } from './riot.client.service'; +import { RiotLeagueService } from './riot-league.service'; +import { RiotRecentMatchesService } from './riot-recent-matches.service'; +import { RiotRecentStatsService } from './riot-recent-stats.service'; +import { RiotSummonerService } from './riot-summoner.service'; + +interface FakeAccount { + puuid: string; + profileIconId: number; + revisionDate: number; + summonerLevel: number; + matchIds: string[]; + matchIdsFetchedAt?: Date; + recentStatsSummary?: RiotRecentStatsSummary; + recentStatsFetchedAt?: Date; + tiers: Array<{ + leagueId: string; + queueType: string; + tier: string; + rank: string; + puuid: string; + leaguePoints: number; + wins: number; + losses: number; + fetchedAt: Date; + }>; + tierHistory: Array<{ + queueType: string; + tier: string; + rank?: string; + leaguePoints?: number; + wins?: number; + losses?: number; + recordedAt: Date; + }>; + championMasteries: Array<{ + puuid: string; + championId: number; + championLevel: number; + championPoints: number; + }>; + championMasteriesFetchedAt?: Date; + championRecords: Record; + championRecordsFetchedAt?: Date; +} + +function makeAccount(overrides: Partial = {}): FakeAccount { + return { + puuid: 'puuid-1', + profileIconId: 0, + revisionDate: 0, + summonerLevel: 0, + matchIds: [], + tiers: [], + tierHistory: [], + championMasteries: [], + championRecords: {}, + ...overrides, + }; +} + +function makeUser(account: FakeAccount) { + const _id = new mongoose.Types.ObjectId(); + const save = jest.fn().mockResolvedValue(undefined); + return { + _id, + riotAccounts: [account], + save, + }; +} + +function makeService(overrides?: { + user?: any; + account?: Partial; + summoner?: Partial; + league?: Partial; + mastery?: Partial; + recentMatches?: Partial; + recentStats?: Partial; +}) { + const user = overrides?.user; + const userFindById = jest.fn().mockReturnValue({ + exec: () => Promise.resolve(user ?? null), + }); + const communityFindById = jest.fn().mockReturnValue({ + select: () => ({ + lean: () => ({ + exec: () => + Promise.resolve({ + riotPlatform: 'kr', + riotRegion: 'asia', + }), + }), + }), + }); + const connectionService = { + getModel: jest.fn().mockImplementation(async (modelName: string) => { + if (modelName === 'user') { + return { findById: userFindById }; + } + if (modelName === 'community') { + return { findById: communityFindById }; + } + throw new Error(`Unexpected model: ${modelName}`); + }), + } as unknown as ConnectionService; + + const summonerService = { + getByPuuid: jest.fn(), + ...overrides?.summoner, + } as unknown as RiotSummonerService; + const accountService = { + getRegionByPuuid: jest.fn(), + ...overrides?.account, + } as unknown as RiotAccountService; + const leagueService = { + getEntriesByPuuid: jest.fn(), + ...overrides?.league, + } as unknown as RiotLeagueService; + const masteryService = { + getTopByPuuid: jest.fn(), + ...overrides?.mastery, + } as unknown as RiotChampionMasteryService; + const recentMatchesService = { + syncRecentMatches: jest.fn().mockResolvedValue([]), + loadFromDb: jest.fn().mockResolvedValue([]), + ...overrides?.recentMatches, + } as unknown as RiotRecentMatchesService; + const recentStatsService = { + computeSummary: jest + .fn() + .mockReturnValue(createEmptyRiotRecentStatsSummary()), + ...overrides?.recentStats, + } as unknown as RiotRecentStatsService; + + const service = new RiotAccountEnrichmentService( + connectionService, + accountService, + summonerService, + leagueService, + masteryService, + recentMatchesService, + recentStatsService, + ); + return { + service, + user, + accountService, + summonerService, + leagueService, + masteryService, + recentMatchesService, + recentStatsService, + }; +} + +describe('RiotAccountEnrichmentService', () => { + it('returns failed for unknown user', async () => { + const { service } = makeService(); + const result = await service.enrichRiotAccount({ + userId: new mongoose.Types.ObjectId(), + puuid: 'puuid-1', + }); + expect(result.summoner).toBe('failed'); + expect(result.recentMatches).toBe('failed'); + expect(result.account).toBeNull(); + }); + + it('fills summoner / league / mastery on first attach (force)', async () => { + const account = makeAccount(); + const user = makeUser(account); + const { + service, + summonerService, + leagueService, + masteryService, + recentMatchesService, + recentStatsService, + } = + makeService({ + user, + summoner: { + getByPuuid: jest.fn().mockResolvedValue({ + puuid: 'puuid-1', + profileIconId: 588, + revisionDate: 1776977597000, + summonerLevel: 529, + }), + } as Partial, + league: { + getEntriesByPuuid: jest.fn().mockResolvedValue([ + { + leagueId: 'L1', + queueType: 'RANKED_SOLO_5x5', + tier: 'EMERALD', + rank: 'I', + puuid: 'puuid-1', + leaguePoints: 75, + wins: 160, + losses: 148, + }, + ]), + } as Partial, + mastery: { + getTopByPuuid: jest.fn().mockResolvedValue([ + { + puuid: 'puuid-1', + championId: 7, + championLevel: 70, + championPoints: 742560, + }, + ]), + } as Partial, + recentMatches: { + syncRecentMatches: jest.fn().mockResolvedValue([]), + loadFromDb: jest.fn().mockResolvedValue([ + { matchId: 'KR_1', raw: {} }, + { matchId: 'KR_2', raw: {} }, + ]), + } as Partial, + recentStats: { + computeSummary: jest.fn().mockReturnValue({ + overall: { + games: 2, + wins: 1, + losses: 1, + avgKills: 5.5, + avgDeaths: 2.5, + avgAssists: 7, + avgCs: 175, + avgCsPerMin: 6.4, + mostPlayedChampionIds: [7, 103], + }, + byLane: {}, + }), + } as Partial, + }); + + const result = await service.enrichRiotAccount({ + userId: user._id, + puuid: 'puuid-1', + options: { force: true }, + }); + + expect(result.summoner).toBe('updated'); + expect(result.league).toBe('updated'); + expect(result.masteries).toBe('updated'); + expect(result.recentMatches).toBe('updated'); + expect(account.profileIconId).toBe(588); + expect(account.summonerLevel).toBe(529); + expect(account.matchIds).toEqual(['KR_1', 'KR_2']); + expect(account.recentStatsSummary).toMatchObject({ + overall: { + games: 2, + wins: 1, + losses: 1, + avgKills: 5.5, + avgDeaths: 2.5, + avgAssists: 7, + avgCs: 175, + avgCsPerMin: 6.4, + mostPlayedChampionIds: [7, 103], + }, + }); + expect(account.tiers).toHaveLength(1); + expect(account.tiers[0]).toMatchObject({ + leagueId: 'L1', + queueType: 'RANKED_SOLO_5x5', + tier: 'EMERALD', + rank: 'I', + puuid: 'puuid-1', + leaguePoints: 75, + }); + expect(account.tierHistory).toHaveLength(1); + expect(account.tierHistory[0]).toMatchObject({ + queueType: 'RANKED_SOLO_5x5', + tier: 'EMERALD', + rank: 'I', + leaguePoints: 75, + wins: 160, + losses: 148, + }); + expect(account.championMasteries).toEqual([ + { + puuid: 'puuid-1', + championId: 7, + championLevel: 70, + championPoints: 742560, + }, + ]); + expect(account.championRecords).toEqual({}); + expect(user.save).toHaveBeenCalledTimes(1); + expect(summonerService.getByPuuid).toHaveBeenCalledWith('puuid-1', { + platform: 'kr', + }); + expect(leagueService.getEntriesByPuuid).toHaveBeenCalledWith('puuid-1', { + platform: 'kr', + }); + expect(masteryService.getTopByPuuid).toHaveBeenCalledWith('puuid-1', { + platform: 'kr', + count: 10, + }); + expect(recentMatchesService.syncRecentMatches).toHaveBeenCalledWith({ + puuid: 'puuid-1', + region: 'asia', + limit: 20, + }); + expect(recentStatsService.computeSummary).toHaveBeenCalled(); + }); + + it('skips fresh data when within TTL and not forced', async () => { + const recent = new Date(Date.now() - 60_000); + const account = makeAccount({ + profileIconId: 1, + revisionDate: Date.now() - 60_000, + summonerLevel: 100, + tiers: [ + { + leagueId: 'L1', + queueType: 'RANKED_SOLO_5x5', + tier: 'GOLD', + rank: 'II', + puuid: 'puuid-1', + leaguePoints: 1, + wins: 1, + losses: 1, + fetchedAt: recent, + }, + ], + championMasteriesFetchedAt: recent, + recentStatsFetchedAt: recent, + recentStatsSummary: createEmptyRiotRecentStatsSummary(), + }); + const user = makeUser(account); + const summoner = jest.fn(); + const league = jest.fn(); + const mastery = jest.fn(); + const { service } = makeService({ + user, + summoner: { getByPuuid: summoner } as Partial, + league: { + getEntriesByPuuid: league, + } as Partial, + mastery: { + getTopByPuuid: mastery, + } as Partial, + }); + + const result = await service.enrichRiotAccount({ + userId: user._id, + puuid: 'puuid-1', + }); + + expect(result.summoner).toBe('fresh'); + expect(result.league).toBe('fresh'); + expect(result.masteries).toBe('fresh'); + expect(result.recentMatches).toBe('fresh'); + expect(summoner).not.toHaveBeenCalled(); + expect(league).not.toHaveBeenCalled(); + expect(mastery).not.toHaveBeenCalled(); + expect(user.save).not.toHaveBeenCalled(); + }); + + it('records failed for individual failing fetches but updates the rest', async () => { + const account = makeAccount(); + const user = makeUser(account); + const { service } = makeService({ + user, + summoner: { + getByPuuid: jest.fn().mockRejectedValue(new Error('boom')), + } as Partial, + league: { + getEntriesByPuuid: jest.fn().mockResolvedValue([]), + } as Partial, + mastery: { + getTopByPuuid: jest.fn().mockResolvedValue([]), + } as Partial, + }); + + const result = await service.enrichRiotAccount({ + userId: user._id, + puuid: 'puuid-1', + options: { force: true }, + }); + expect(result.summoner).toBe('failed'); + expect(result.league).toBe('updated'); + expect(result.masteries).toBe('updated'); + expect(result.recentMatches).toBe('updated'); + expect(user.save).toHaveBeenCalled(); + }); + + it('retries summoner lookup with region/by-puuid platform on 404', async () => { + const account = makeAccount(); + const user = makeUser(account); + const summoner = jest + .fn() + .mockRejectedValueOnce(new RiotApiError('not found', 404, 'url')) + .mockResolvedValueOnce({ + puuid: 'puuid-1', + profileIconId: 100, + revisionDate: 1776977597000, + summonerLevel: 30, + }); + const region = jest.fn().mockResolvedValue({ + puuid: 'puuid-1', + game: 'lol', + region: 'jp1', + }); + const league = jest.fn().mockResolvedValue([]); + const mastery = jest.fn().mockResolvedValue([]); + const { service } = makeService({ + user, + account: { getRegionByPuuid: region } as Partial, + summoner: { getByPuuid: summoner } as Partial, + league: { + getEntriesByPuuid: league, + } as Partial, + mastery: { + getTopByPuuid: mastery, + } as Partial, + }); + + const result = await service.enrichRiotAccount({ + userId: user._id, + puuid: 'puuid-1', + options: { force: true, platform: 'kr' }, + }); + + expect(result.summoner).toBe('updated'); + expect(region).toHaveBeenCalledWith('puuid-1', { region: 'asia' }); + expect(summoner).toHaveBeenNthCalledWith(1, 'puuid-1', { + platform: 'kr', + }); + expect(summoner).toHaveBeenNthCalledWith(2, 'puuid-1', { + platform: 'jp1', + }); + expect(league).toHaveBeenCalledWith('puuid-1', { platform: 'jp1' }); + expect(mastery).toHaveBeenCalledWith('puuid-1', { + platform: 'jp1', + count: 10, + }); + }); + + it('deduplicates concurrent enrichment for the same user and puuid', async () => { + const account = makeAccount(); + const user = makeUser(account); + let resolveSummoner: (value: unknown) => void; + const summonerPromise = new Promise((resolve) => { + resolveSummoner = resolve; + }); + const summoner = jest.fn().mockReturnValue(summonerPromise); + const { service } = makeService({ + user, + summoner: { getByPuuid: summoner } as Partial, + league: { + getEntriesByPuuid: jest.fn().mockResolvedValue([]), + } as Partial, + mastery: { + getTopByPuuid: jest.fn().mockResolvedValue([]), + } as Partial, + }); + + const first = service.enrichRiotAccount({ + userId: user._id, + puuid: 'puuid-1', + options: { force: true }, + }); + const second = service.enrichRiotAccount({ + userId: user._id, + puuid: 'puuid-1', + options: { force: true }, + }); + + resolveSummoner!({ + puuid: 'puuid-1', + profileIconId: 100, + revisionDate: 1776977597000, + summonerLevel: 30, + }); + await Promise.all([first, second]); + + expect(summoner).toHaveBeenCalledTimes(1); + expect(user.save).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/api/src/modules/riot/riot-account-enrichment.service.ts b/apps/api/src/modules/riot/riot-account-enrichment.service.ts new file mode 100644 index 00000000..85079ad1 --- /dev/null +++ b/apps/api/src/modules/riot/riot-account-enrichment.service.ts @@ -0,0 +1,437 @@ +import { Injectable, Logger } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import { + ChampionMasteryEntry, + RiotAccount, + TierInfo, +} from '../global/database/schema'; +import { RiotAccountService } from './riot-account.service'; +import { RiotChampionMasteryService } from './riot-champion-mastery.service'; +import { RiotApiError } from './riot.client.service'; +import { RiotLeagueService } from './riot-league.service'; +import { + RIOT_RECENT_MATCH_LIMIT, + RiotRecentMatchesService, +} from './riot-recent-matches.service'; +import { RiotRecentStatsService } from './riot-recent-stats.service'; +import { RiotSummonerService } from './riot-summoner.service'; +import { + RiotChampionMasteryDto, + RiotLeagueEntryDto, + RiotMatchDto, + RiotPlatformRoute, + RiotRegionalRoute, + RiotSummonerDto, +} from './riot.types'; + +const DEFAULT_PLATFORM: RiotPlatformRoute = 'kr'; +const DEFAULT_REGION: RiotRegionalRoute = 'asia'; +const MASTERY_LIMIT = 10; + +const DEFAULT_SUMMONER_TTL_MS = 24 * 60 * 60 * 1000; // 24h +const DEFAULT_LEAGUE_TTL_MS = 60 * 60 * 1000; // 1h +const DEFAULT_MASTERY_TTL_MS = 6 * 60 * 60 * 1000; // 6h +const DEFAULT_RECENT_MATCHES_TTL_MS = 6 * 60 * 60 * 1000; // 6h + +export interface EnrichOptions { + platform?: RiotPlatformRoute; + region?: RiotRegionalRoute; + force?: boolean; + summonerTtlMs?: number; + leagueTtlMs?: number; + masteryTtlMs?: number; + recentMatchesTtlMs?: number; +} + +export interface EnrichResult { + summoner: 'updated' | 'fresh' | 'failed'; + league: 'updated' | 'fresh' | 'failed'; + masteries: 'updated' | 'fresh' | 'failed'; + recentMatches: 'updated' | 'fresh' | 'failed'; + account: RiotAccount | null; +} + +@Injectable() +export class RiotAccountEnrichmentService { + private readonly logger = new Logger(RiotAccountEnrichmentService.name); + private readonly inFlight = new Map>(); + + constructor( + private readonly connectionService: ConnectionService, + private readonly accountService: RiotAccountService, + private readonly summonerService: RiotSummonerService, + private readonly leagueService: RiotLeagueService, + private readonly masteryService: RiotChampionMasteryService, + private readonly recentMatchesService: RiotRecentMatchesService, + private readonly recentStatsService: RiotRecentStatsService, + ) {} + + public async enrichRiotAccount(params: { + userId: mongoose.Types.ObjectId; + puuid: string; + options?: EnrichOptions; + }): Promise { + const key = `${params.userId.toString()}:${params.puuid}`; + const existing = this.inFlight.get(key); + if (existing) return existing; + + const promise = this.doEnrichRiotAccount(params).finally(() => { + this.inFlight.delete(key); + }); + this.inFlight.set(key, promise); + return promise; + } + + private async doEnrichRiotAccount(params: { + userId: mongoose.Types.ObjectId; + puuid: string; + options?: EnrichOptions; + }): Promise { + const UserModel = await this.connectionService.getModel('user'); + const user = await UserModel.findById(params.userId).exec(); + if (!user) { + return { + summoner: 'failed', + league: 'failed', + masteries: 'failed', + recentMatches: 'failed', + account: null, + }; + } + const account = user.riotAccounts.find((a) => a.puuid === params.puuid); + if (!account) { + return { + summoner: 'failed', + league: 'failed', + masteries: 'failed', + recentMatches: 'failed', + account: null, + }; + } + + const CommunityModel = await this.connectionService.getModel('community'); + const community = await CommunityModel.findById(user.communityId) + .select({ riotPlatform: 1, riotRegion: 1, seasonStartedAt: 1 }) + .lean() + .exec(); + + const opts = params.options ?? {}; + const platform = opts.platform ?? community?.riotPlatform ?? DEFAULT_PLATFORM; + const region = opts.region ?? community?.riotRegion ?? DEFAULT_REGION; + const now = Date.now(); + + const summonerTtl = opts.summonerTtlMs ?? DEFAULT_SUMMONER_TTL_MS; + const leagueTtl = opts.leagueTtlMs ?? DEFAULT_LEAGUE_TTL_MS; + const masteryTtl = opts.masteryTtlMs ?? DEFAULT_MASTERY_TTL_MS; + const recentMatchesTtl = + opts.recentMatchesTtlMs ?? DEFAULT_RECENT_MATCHES_TTL_MS; + const force = opts.force === true; + const seasonStartedAt = community?.seasonStartedAt + ? new Date(community.seasonStartedAt) + : undefined; + const seasonInvalidatesRecentStats = + seasonStartedAt !== undefined && + (!account.recentStatsFetchedAt || + account.recentStatsFetchedAt.getTime() < seasonStartedAt.getTime()); + + const summonerStale = + force || + account.revisionDate === 0 || + now - account.revisionDate > summonerTtl; + const leagueStale = + force || + account.tiers.length === 0 || + this.tiersOldestAt(account.tiers) < now - leagueTtl; + const masteryStale = + force || + !account.championMasteriesFetchedAt || + now - account.championMasteriesFetchedAt.getTime() > masteryTtl; + const recentMatchesStale = + force || + seasonInvalidatesRecentStats || + !account.recentStatsFetchedAt || + !account.recentStatsSummary || + now - account.recentStatsFetchedAt.getTime() > recentMatchesTtl; + + const summonerOutcome = summonerStale + ? await this.fetchSummonerSafe(params.puuid, platform, region) + : { status: 'fresh' as const, dto: null, platform }; + const effectivePlatform = summonerOutcome.platform ?? platform; + + const [leagueOutcome, masteryOutcome, recentMatchesOutcome] = + await Promise.all([ + leagueStale + ? this.fetchLeagueSafe(params.puuid, effectivePlatform) + : Promise.resolve({ status: 'fresh' as const, dto: null }), + masteryStale + ? this.fetchMasteriesSafe(params.puuid, effectivePlatform) + : Promise.resolve({ status: 'fresh' as const, dto: null }), + recentMatchesStale + ? this.fetchRecentMatchesSafe(params.puuid, region, seasonStartedAt) + : Promise.resolve({ + status: 'fresh' as const, + summary: null, + matchIds: null, + }), + ]); + + if (summonerOutcome.status === 'updated' && summonerOutcome.dto) { + this.applySummoner(account, summonerOutcome.dto); + } + if (leagueOutcome.status === 'updated' && leagueOutcome.dto) { + this.applyLeagueEntries(account, leagueOutcome.dto); + } + if (masteryOutcome.status === 'updated' && masteryOutcome.dto) { + this.applyMasteries(account, masteryOutcome.dto); + } + if ( + recentMatchesOutcome.status === 'updated' && + recentMatchesOutcome.summary && + recentMatchesOutcome.matchIds + ) { + this.applyRecentMatches( + account, + recentMatchesOutcome.summary, + recentMatchesOutcome.matchIds, + ); + } + + if ( + summonerOutcome.status === 'updated' || + leagueOutcome.status === 'updated' || + masteryOutcome.status === 'updated' || + recentMatchesOutcome.status === 'updated' + ) { + await user.save(); + } + + return { + summoner: summonerOutcome.status, + league: leagueOutcome.status, + masteries: masteryOutcome.status, + recentMatches: recentMatchesOutcome.status, + account, + }; + } + + private async fetchSummonerSafe( + puuid: string, + platform: RiotPlatformRoute, + region: RiotRegionalRoute, + ): Promise< + | { status: 'updated'; dto: RiotSummonerDto; platform: RiotPlatformRoute } + | { status: 'failed'; dto: null; platform: RiotPlatformRoute } + > { + try { + const dto = await this.summonerService.getByPuuid(puuid, { platform }); + return { status: 'updated', dto, platform }; + } catch (err) { + if (err instanceof RiotApiError && err.status === 404) { + try { + const regionDto = await this.accountService.getRegionByPuuid(puuid, { + region, + }); + if (regionDto.region !== platform) { + this.logger.warn( + `Summoner platform corrected for ${puuid}: ${platform} -> ${regionDto.region}`, + ); + } + const dto = await this.summonerService.getByPuuid(puuid, { + platform: regionDto.region, + }); + return { status: 'updated', dto, platform: regionDto.region }; + } catch (fallbackErr) { + this.logger.warn( + `Summoner fallback fetch failed for ${puuid}: ${ + (fallbackErr as Error)?.message ?? fallbackErr + }`, + ); + return { status: 'failed', dto: null, platform }; + } + } + this.logger.warn( + `Summoner fetch failed for ${puuid}: ${(err as Error)?.message ?? err}`, + ); + return { status: 'failed', dto: null, platform }; + } + } + + private async fetchLeagueSafe( + puuid: string, + platform: RiotPlatformRoute, + ): Promise< + | { status: 'updated'; dto: RiotLeagueEntryDto[] } + | { status: 'failed'; dto: null } + > { + try { + const dto = await this.leagueService.getEntriesByPuuid(puuid, { + platform, + }); + return { status: 'updated', dto }; + } catch (err) { + this.logger.warn( + `League entries fetch failed for ${puuid}: ${ + (err as Error)?.message ?? err + }`, + ); + return { status: 'failed', dto: null }; + } + } + + private async fetchMasteriesSafe( + puuid: string, + platform: RiotPlatformRoute, + ): Promise< + | { status: 'updated'; dto: RiotChampionMasteryDto[] } + | { status: 'failed'; dto: null } + > { + try { + const dto = await this.masteryService.getTopByPuuid(puuid, { + platform, + count: MASTERY_LIMIT, + }); + return { status: 'updated', dto }; + } catch (err) { + this.logger.warn( + `Champion masteries fetch failed for ${puuid}: ${ + (err as Error)?.message ?? err + }`, + ); + return { status: 'failed', dto: null }; + } + } + + private async fetchRecentMatchesSafe( + puuid: string, + region: RiotRegionalRoute, + seasonStartedAt?: Date, + ): Promise< + | { + status: 'updated'; + summary: RiotAccount['recentStatsSummary']; + matchIds: string[]; + } + | { status: 'failed'; summary: null; matchIds: null } + > { + try { + await this.recentMatchesService.syncRecentMatches({ + puuid, + region, + limit: RIOT_RECENT_MATCH_LIMIT, + }); + const matches = await this.recentMatchesService.loadFromDb({ + puuid, + limit: RIOT_RECENT_MATCH_LIMIT, + }); + const summary = this.recentStatsService.computeSummary( + matches.map((match) => match.raw as unknown as RiotMatchDto), + puuid, + { seasonStartedAt }, + ); + return { + status: 'updated', + summary, + matchIds: matches.map((match) => match.matchId), + }; + } catch (err) { + this.logger.warn( + `Recent matches fetch failed for ${puuid}: ${ + (err as Error)?.message ?? err + }`, + ); + return { status: 'failed', summary: null, matchIds: null }; + } + } + + private applySummoner(account: RiotAccount, dto: RiotSummonerDto): void { + account.profileIconId = dto.profileIconId; + account.revisionDate = dto.revisionDate; + account.summonerLevel = dto.summonerLevel; + } + + private applyLeagueEntries( + account: RiotAccount, + entries: RiotLeagueEntryDto[], + ): void { + const fetchedAt = new Date(); + this.appendTierHistoryIfChanged(account, entries, fetchedAt); + const next: TierInfo[] = entries.map((e) => ({ + leagueId: e.leagueId, + queueType: e.queueType, + tier: e.tier, + rank: e.rank, + puuid: e.puuid, + leaguePoints: e.leaguePoints, + wins: e.wins, + losses: e.losses, + veteran: e.veteran, + inactive: e.inactive, + freshBlood: e.freshBlood, + hotStreak: e.hotStreak, + miniSeries: e.miniSeries, + fetchedAt, + })); + account.tiers = next; + } + + private appendTierHistoryIfChanged( + account: RiotAccount, + entries: RiotLeagueEntryDto[], + recordedAt: Date, + ): void { + for (const entry of entries) { + const last = [...account.tierHistory] + .reverse() + .find((history) => history.queueType === entry.queueType); + const changed = + !last || + last.tier !== entry.tier || + (last.rank ?? '') !== (entry.rank ?? ''); + if (!changed) continue; + + account.tierHistory.push({ + queueType: entry.queueType, + tier: entry.tier, + rank: entry.rank, + leaguePoints: entry.leaguePoints, + wins: entry.wins, + losses: entry.losses, + recordedAt, + }); + } + } + + private applyMasteries( + account: RiotAccount, + masteries: RiotChampionMasteryDto[], + ): void { + const summary: ChampionMasteryEntry[] = masteries + .slice(0, MASTERY_LIMIT) + .map((m) => ({ ...m })); + account.championMasteries = summary; + account.championMasteriesFetchedAt = new Date(); + } + + private applyRecentMatches( + account: RiotAccount, + summary: NonNullable, + matchIds: string[], + ): void { + const fetchedAt = new Date(); + account.recentStatsSummary = summary; + account.recentStatsFetchedAt = fetchedAt; + account.matchIds = matchIds; + account.matchIdsFetchedAt = fetchedAt; + } + + private tiersOldestAt(tiers: TierInfo[]): number { + if (tiers.length === 0) return 0; + let oldest = Infinity; + for (const t of tiers) { + const at = t.fetchedAt instanceof Date ? t.fetchedAt.getTime() : 0; + if (at < oldest) oldest = at; + } + return oldest === Infinity ? 0 : oldest; + } +} diff --git a/apps/api/src/modules/riot/riot-account.service.ts b/apps/api/src/modules/riot/riot-account.service.ts new file mode 100644 index 00000000..58970308 --- /dev/null +++ b/apps/api/src/modules/riot/riot-account.service.ts @@ -0,0 +1,128 @@ +import { Injectable } from '@nestjs/common'; +import { RiotClientService } from './riot.client.service'; +import { + RIOT_PLATFORM_ROUTES, + RiotAccountDto, + RiotAccountLookupOptions, + RiotAccountRegionDto, +} from './riot.types'; + +@Injectable() +export class RiotAccountService { + constructor(private readonly riotClientService: RiotClientService) {} + + public async getByRiotId( + gameName: string, + tagLine: string, + options: RiotAccountLookupOptions = {}, + ): Promise { + return this.riotClientService.get( + `/riot/account/v1/accounts/by-riot-id/${encodeURIComponent(gameName)}/${encodeURIComponent(tagLine)}`, + { + region: options.region, + signal: options.signal, + }, + parseRiotAccountDto, + ); + } + + public async getByPuuid( + puuid: string, + options: RiotAccountLookupOptions = {}, + ): Promise { + return this.riotClientService.get( + `/riot/account/v1/accounts/by-puuid/${encodeURIComponent(puuid)}`, + { + region: options.region, + signal: options.signal, + }, + parseRiotAccountDto, + ); + } + + public async getRegionByPuuid( + puuid: string, + options: RiotAccountLookupOptions = {}, + ): Promise { + return this.riotClientService.get( + `/riot/account/v1/region/by-game/lol/by-puuid/${encodeURIComponent(puuid)}`, + { + region: options.region ?? 'asia', + signal: options.signal, + }, + parseRiotAccountRegionDto, + ); + } +} + +function parseRiotAccountDto(value: unknown): RiotAccountDto { + if (!isRecord(value)) { + throw new TypeError('Riot account response must be an object.'); + } + + const puuid = value.puuid; + const gameName = value.gameName; + const tagLine = value.tagLine; + + if (!isNonEmptyString(puuid)) { + throw new TypeError('Riot account response is missing a valid puuid.'); + } + + if (!isOptionalString(gameName)) { + throw new TypeError('Riot account response has an invalid gameName.'); + } + + if (!isOptionalString(tagLine)) { + throw new TypeError('Riot account response has an invalid tagLine.'); + } + + return { + puuid, + gameName: gameName ?? null, + tagLine: tagLine ?? null, + }; +} + +function parseRiotAccountRegionDto(value: unknown): RiotAccountRegionDto { + if (!isRecord(value)) { + throw new TypeError('Riot account region response must be an object.'); + } + + const puuid = value.puuid; + const game = value.game; + const region = value.region; + + if (!isNonEmptyString(puuid)) { + throw new TypeError( + 'Riot account region response is missing a valid puuid.', + ); + } + if (!isNonEmptyString(game)) { + throw new TypeError( + 'Riot account region response is missing a valid game.', + ); + } + const platformRegion = region as (typeof RIOT_PLATFORM_ROUTES)[number]; + if ( + !isNonEmptyString(region) || + !RIOT_PLATFORM_ROUTES.includes(platformRegion) + ) { + throw new TypeError( + 'Riot account region response is missing a valid region.', + ); + } + + return { puuid, game, region: platformRegion }; +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} + +function isNonEmptyString(value: unknown): value is string { + return typeof value === 'string' && value.length > 0; +} + +function isOptionalString(value: unknown): value is string | undefined { + return value === undefined || typeof value === 'string'; +} diff --git a/apps/api/src/modules/riot/riot-champion-mastery.service.ts b/apps/api/src/modules/riot/riot-champion-mastery.service.ts new file mode 100644 index 00000000..abfc58c2 --- /dev/null +++ b/apps/api/src/modules/riot/riot-champion-mastery.service.ts @@ -0,0 +1,129 @@ +import { Injectable } from '@nestjs/common'; +import { RiotClientService } from './riot.client.service'; +import { + RiotChampionMasteryDto, + RiotPlatformLookupOptions, +} from './riot.types'; + +interface MasteriesByPuuidOptions extends RiotPlatformLookupOptions { + count?: number; +} + +const DEFAULT_TOP_MASTERY_COUNT = 10; +const MAX_TOP_MASTERY_COUNT = 10; + +@Injectable() +export class RiotChampionMasteryService { + constructor(private readonly riotClientService: RiotClientService) {} + + public async getByPuuid( + puuid: string, + options: RiotPlatformLookupOptions = {}, + ): Promise { + return this.riotClientService.get( + `/lol/champion-mastery/v4/champion-masteries/by-puuid/${encodeURIComponent(puuid)}`, + { + platform: options.platform ?? 'kr', + signal: options.signal, + }, + parseMasteries, + ); + } + + public async getTopByPuuid( + puuid: string, + options: MasteriesByPuuidOptions = {}, + ): Promise { + const count = options.count ?? DEFAULT_TOP_MASTERY_COUNT; + if ( + !Number.isInteger(count) || + count <= 0 || + count > MAX_TOP_MASTERY_COUNT + ) { + throw new RangeError('count must be an integer between 1 and 10.'); + } + return this.riotClientService.get( + `/lol/champion-mastery/v4/champion-masteries/by-puuid/${encodeURIComponent(puuid)}/top`, + { + platform: options.platform ?? 'kr', + signal: options.signal, + query: { count }, + }, + parseMasteries, + ); + } +} + +function parseMasteries(value: unknown): RiotChampionMasteryDto[] { + if (!Array.isArray(value)) { + throw new TypeError('Champion masteries response must be an array.'); + } + return value.map((entry, index) => parseEntry(entry, index)); +} + +function parseEntry(value: unknown, index: number): RiotChampionMasteryDto { + if (!isRecord(value)) { + throw new TypeError(`championMasteries[${index}] must be an object.`); + } + const puuid = value.puuid; + const championId = value.championId; + const championLevel = value.championLevel; + const championPoints = value.championPoints; + if (typeof puuid !== 'string') { + throw new TypeError(`championMasteries[${index}].puuid must be a string.`); + } + if (typeof championId !== 'number' || !Number.isFinite(championId)) { + throw new TypeError( + `championMasteries[${index}].championId must be a number.`, + ); + } + if (typeof championLevel !== 'number' || !Number.isFinite(championLevel)) { + throw new TypeError( + `championMasteries[${index}].championLevel must be a number.`, + ); + } + if (typeof championPoints !== 'number' || !Number.isFinite(championPoints)) { + throw new TypeError( + `championMasteries[${index}].championPoints must be a number.`, + ); + } + return { + ...value, + puuid, + championId, + championLevel, + championPoints, + lastPlayTime: + typeof value.lastPlayTime === 'number' ? value.lastPlayTime : undefined, + championPointsSinceLastLevel: + typeof value.championPointsSinceLastLevel === 'number' + ? value.championPointsSinceLastLevel + : undefined, + championPointsUntilNextLevel: + typeof value.championPointsUntilNextLevel === 'number' + ? value.championPointsUntilNextLevel + : undefined, + markRequiredForNextLevel: + typeof value.markRequiredForNextLevel === 'number' + ? value.markRequiredForNextLevel + : undefined, + tokensEarned: + typeof value.tokensEarned === 'number' ? value.tokensEarned : undefined, + championSeasonMilestone: + typeof value.championSeasonMilestone === 'number' + ? value.championSeasonMilestone + : undefined, + milestoneGrades: Array.isArray(value.milestoneGrades) + ? (value.milestoneGrades as unknown[]).filter( + (v): v is string => typeof v === 'string', + ) + : undefined, + nextSeasonMilestone: isRecord(value.nextSeasonMilestone) + ? value.nextSeasonMilestone + : undefined, + }; +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} diff --git a/apps/api/src/modules/riot/riot-ddragon.controller.ts b/apps/api/src/modules/riot/riot-ddragon.controller.ts new file mode 100644 index 00000000..4dbd58a0 --- /dev/null +++ b/apps/api/src/modules/riot/riot-ddragon.controller.ts @@ -0,0 +1,19 @@ +import { Controller, Get, Query } from '@nestjs/common'; +import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; +import { + RiotDdragonService, + type DdragonManifest, +} from './riot-ddragon.service'; + +@Controller('riot/ddragon') +export class RiotDdragonController { + constructor(private readonly ddragonService: RiotDdragonService) {} + + @Get('manifest') + @AllowPublicAccess() + public async getManifest( + @Query('locale') locale?: string, + ): Promise { + return this.ddragonService.getManifest(locale ?? 'ko_KR'); + } +} diff --git a/apps/api/src/modules/riot/riot-ddragon.service.ts b/apps/api/src/modules/riot/riot-ddragon.service.ts new file mode 100644 index 00000000..218e87ca --- /dev/null +++ b/apps/api/src/modules/riot/riot-ddragon.service.ts @@ -0,0 +1,142 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { GarnetService } from '../global/garnet/garnet.service'; + +const DDRAGON_BASE = 'https://ddragon.leagueoflegends.com'; +const DDRAGON_CDN = `${DDRAGON_BASE}/cdn`; +const DEFAULT_LOCALE = 'ko_KR'; +const CACHE_TTL_SECONDS = 24 * 60 * 60; +const CACHE_VERSION = 'v2'; +const FETCH_TIMEOUT_MS = 10_000; + +export interface DdragonChampionEntry { + key: string; + name: string; +} + +export interface DdragonManifest { + version: string; + cdn: string; + locale: string; + champions: Record; + fetchedAt: string; +} + +interface ChampionDataEntry { + key: string; + id: string; + name: string; +} + +interface ChampionDataResponse { + data: Record; +} + +@Injectable() +export class RiotDdragonService { + private readonly logger = new Logger(RiotDdragonService.name); + private inflight = new Map>(); + + constructor(private readonly garnetService: GarnetService) {} + + public async getManifest(locale: string = DEFAULT_LOCALE): Promise { + const normalizedLocale = normalizeLocale(locale); + const cacheKey = manifestCacheKey(normalizedLocale); + + const cached = await this.garnetService.getJson(cacheKey); + if (cached) return cached; + + const pending = this.inflight.get(cacheKey); + if (pending) return pending; + + const promise = this.buildManifest(normalizedLocale) + .then(async (manifest) => { + await this.garnetService.setJson(cacheKey, manifest, CACHE_TTL_SECONDS); + return manifest; + }) + .finally(() => { + this.inflight.delete(cacheKey); + }); + + this.inflight.set(cacheKey, promise); + return promise; + } + + private async buildManifest(locale: string): Promise { + const version = await this.fetchLatestVersion(); + const champions = await this.fetchChampionMap(version, locale); + return { + version, + cdn: DDRAGON_CDN, + locale, + champions, + fetchedAt: new Date().toISOString(), + }; + } + + private async fetchLatestVersion(): Promise { + const versions = await this.fetchJson(`${DDRAGON_BASE}/api/versions.json`); + if (!Array.isArray(versions) || typeof versions[0] !== 'string') { + throw new Error('ddragon versions.json response is malformed.'); + } + return versions[0]; + } + + private async fetchChampionMap( + version: string, + locale: string, + ): Promise> { + const url = `${DDRAGON_CDN}/${version}/data/${locale}/champion.json`; + const payload = await this.fetchJson(url); + if (!payload || typeof payload !== 'object' || !payload.data) { + throw new Error(`ddragon champion.json response is malformed (${url}).`); + } + + const map: Record = {}; + for (const entry of Object.values(payload.data)) { + if (entry?.key && entry.id) { + map[entry.key] = { + key: entry.id, + name: typeof entry.name === 'string' ? entry.name : entry.id, + }; + } + } + return map; + } + + private async fetchJson(url: string): Promise { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS); + try { + const response = await fetch(url, { + method: 'GET', + headers: { Accept: 'application/json' }, + signal: controller.signal, + }); + if (!response.ok) { + throw new Error( + `ddragon request failed (${response.status}): ${url}`, + ); + } + return (await response.json()) as T; + } catch (err) { + this.logger.error( + `ddragon fetch error for ${url}: ${(err as Error)?.message ?? err}`, + ); + throw err; + } finally { + clearTimeout(timeout); + } + } +} + +function normalizeLocale(locale: string): string { + const trimmed = locale.trim(); + if (!/^[a-zA-Z]{2}_[a-zA-Z]{2}$/.test(trimmed)) { + return DEFAULT_LOCALE; + } + return `${trimmed.slice(0, 2).toLowerCase()}_${trimmed.slice(3).toUpperCase()}`; +} + +function manifestCacheKey(locale: string): string { + return `ddragon:manifest:${CACHE_VERSION}:${locale}`; +} diff --git a/apps/api/src/modules/riot/riot-league.service.ts b/apps/api/src/modules/riot/riot-league.service.ts new file mode 100644 index 00000000..a8c4614c --- /dev/null +++ b/apps/api/src/modules/riot/riot-league.service.ts @@ -0,0 +1,79 @@ +import { Injectable } from '@nestjs/common'; +import { RiotClientService } from './riot.client.service'; +import { + RiotLeagueEntryDto, + RiotPlatformLookupOptions, +} from './riot.types'; + +@Injectable() +export class RiotLeagueService { + constructor(private readonly riotClientService: RiotClientService) {} + + public async getEntriesByPuuid( + puuid: string, + options: RiotPlatformLookupOptions = {}, + ): Promise { + return this.riotClientService.get( + `/lol/league/v4/entries/by-puuid/${encodeURIComponent(puuid)}`, + { + platform: options.platform ?? 'kr', + signal: options.signal, + }, + parseLeagueEntries, + ); + } +} + +function parseLeagueEntries(value: unknown): RiotLeagueEntryDto[] { + if (!Array.isArray(value)) { + throw new TypeError('League entries response must be an array.'); + } + return value.map((entry, index) => parseEntry(entry, index)); +} + +function parseEntry(value: unknown, index: number): RiotLeagueEntryDto { + if (!isRecord(value)) { + throw new TypeError(`leagueEntries[${index}] must be an object.`); + } + return { + leagueId: requireString(value.leagueId, `leagueEntries[${index}].leagueId`), + queueType: requireString( + value.queueType, + `leagueEntries[${index}].queueType`, + ), + tier: requireString(value.tier, `leagueEntries[${index}].tier`), + rank: requireString(value.rank, `leagueEntries[${index}].rank`), + puuid: requireString(value.puuid, `leagueEntries[${index}].puuid`), + leaguePoints: requireNumber( + value.leaguePoints, + `leagueEntries[${index}].leaguePoints`, + ), + wins: requireNumber(value.wins, `leagueEntries[${index}].wins`), + losses: requireNumber(value.losses, `leagueEntries[${index}].losses`), + veteran: typeof value.veteran === 'boolean' ? value.veteran : undefined, + inactive: typeof value.inactive === 'boolean' ? value.inactive : undefined, + freshBlood: + typeof value.freshBlood === 'boolean' ? value.freshBlood : undefined, + hotStreak: + typeof value.hotStreak === 'boolean' ? value.hotStreak : undefined, + miniSeries: isRecord(value.miniSeries) ? value.miniSeries : undefined, + }; +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} + +function requireString(value: unknown, path: string): string { + if (typeof value !== 'string' || value.length === 0) { + throw new TypeError(`${path} must be a non-empty string.`); + } + return value; +} + +function requireNumber(value: unknown, path: string): number { + if (typeof value !== 'number' || !Number.isFinite(value)) { + throw new TypeError(`${path} must be a finite number.`); + } + return value; +} diff --git a/apps/api/src/modules/riot/riot-queue.constants.ts b/apps/api/src/modules/riot/riot-queue.constants.ts new file mode 100644 index 00000000..70b3ae05 --- /dev/null +++ b/apps/api/src/modules/riot/riot-queue.constants.ts @@ -0,0 +1,88 @@ +export type RiotQueueGroup = + | 'all' + | 'summoners-rift' + | 'aram' + | 'urf' + | 'arena'; + +export type RiotRankFilter = 'all' | 'solo' | 'flex' | 'normal'; + +export interface RiotQueueGroupConfig { + label: string; + queues: Record; +} + +export const RIOT_QUEUE_GROUPS: Record = { + all: { + label: '전체', + queues: { + all: [400, 420, 430, 440, 450, 900, 1900, 1700, 1710], + solo: [420], + flex: [440], + normal: [400, 430, 450, 900, 1900, 1700, 1710], + }, + }, + 'summoners-rift': { + label: '소환사의 협곡', + queues: { + all: [400, 420, 430, 440], + solo: [420], + flex: [440], + normal: [400, 430], + }, + }, + aram: { + label: '칼바람 나락', + queues: { + all: [450], + solo: [], + flex: [], + normal: [450], + }, + }, + urf: { + label: '우르프', + queues: { + all: [900, 1900], + solo: [], + flex: [], + normal: [900, 1900], + }, + }, + arena: { + label: '아레나', + queues: { + all: [1700, 1710], + solo: [], + flex: [], + normal: [1700, 1710], + }, + }, +}; + +export const RIOT_QUEUE_LABELS: Record = { + 400: '일반 교차 선택', + 420: '솔로 랭크', + 430: '일반 비공개 선택', + 440: '자유 랭크', + 450: '칼바람 나락', + 900: '우르프', + 1700: '아레나', + 1710: '아레나', + 1900: '우르프', +}; + +export function resolveRiotQueueIds( + queueGroup: RiotQueueGroup, + rank: RiotRankFilter, +): number[] { + return RIOT_QUEUE_GROUPS[queueGroup].queues[rank]; +} + +export function isRiotQueueGroup(value: string): value is RiotQueueGroup { + return value in RIOT_QUEUE_GROUPS; +} + +export function isRiotRankFilter(value: string): value is RiotRankFilter { + return value === 'all' || value === 'solo' || value === 'flex' || value === 'normal'; +} diff --git a/apps/api/src/modules/riot/riot-rate-limiter.service.ts b/apps/api/src/modules/riot/riot-rate-limiter.service.ts new file mode 100644 index 00000000..d25a5b59 --- /dev/null +++ b/apps/api/src/modules/riot/riot-rate-limiter.service.ts @@ -0,0 +1,107 @@ +import { Injectable, Logger } from '@nestjs/common'; +import type { RiotPlatformRoute, RiotRegionalRoute } from './riot.types'; +import { GarnetService } from '../global/garnet/garnet.service'; + +const APP_LIMITS = [ + { windowMs: 1_000, max: 15 }, + { windowMs: 120_000, max: 90 }, +] as const; + +const ACQUIRE_SCRIPT = ` +local now = tonumber(ARGV[1]) +local member = ARGV[2] +local maxWait = 0 + +for i = 1, #KEYS do + local argIndex = 3 + ((i - 1) * 2) + local windowMs = tonumber(ARGV[argIndex]) + local limit = tonumber(ARGV[argIndex + 1]) + local key = KEYS[i] + + redis.call('ZREMRANGEBYSCORE', key, '-inf', now - windowMs) + local count = redis.call('ZCARD', key) + if count >= limit then + local oldest = redis.call('ZRANGE', key, 0, 0, 'WITHSCORES') + local waitMs = windowMs + if oldest[2] then + waitMs = windowMs - (now - tonumber(oldest[2])) + 1 + end + if waitMs > maxWait then + maxWait = waitMs + end + end +end + +if maxWait > 0 then + return maxWait +end + +for i = 1, #KEYS do + local argIndex = 3 + ((i - 1) * 2) + local windowMs = tonumber(ARGV[argIndex]) + local key = KEYS[i] + redis.call('ZADD', key, now, member) + redis.call('PEXPIRE', key, windowMs) +end + +return 0 +`; + +@Injectable() +export class RiotRateLimiterService { + private readonly logger = new Logger(RiotRateLimiterService.name); + + constructor(private readonly garnet: GarnetService) {} + + public async acquire( + route: RiotRegionalRoute | RiotPlatformRoute, + ): Promise { + for (;;) { + const now = Date.now(); + const waitMs = await this.checkAndAdd(route, now); + if (waitMs <= 0) return; + + if (waitMs >= 100) { + this.logger.warn( + `Riot API throttle waiting ${waitMs}ms for route=${route}.`, + ); + } + await sleep(waitMs); + } + } + + private async checkAndAdd( + route: RiotRegionalRoute | RiotPlatformRoute, + now: number, + ): Promise { + const client = this.garnet.raw(); + const keys = APP_LIMITS.map( + (limit) => `riot:rl:${route}:${limit.windowMs}`, + ); + const member = `${process.pid}:${now}:${Math.random().toString(36).slice(2)}`; + const argumentsList = [ + String(now), + member, + ...APP_LIMITS.flatMap((limit) => [ + String(limit.windowMs), + String(limit.max), + ]), + ]; + + const response = await client.sendCommand([ + 'EVAL', + ACQUIRE_SCRIPT, + String(keys.length), + ...keys, + ...argumentsList, + ]); + + const waitMs = Number(response ?? 0); + if (!Number.isFinite(waitMs) || waitMs < 0) return 0; + return waitMs; + } +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/apps/api/src/modules/riot/riot-summoner.service.ts b/apps/api/src/modules/riot/riot-summoner.service.ts new file mode 100644 index 00000000..30248294 --- /dev/null +++ b/apps/api/src/modules/riot/riot-summoner.service.ts @@ -0,0 +1,60 @@ +import { Injectable } from '@nestjs/common'; +import { RiotClientService } from './riot.client.service'; +import { + RiotPlatformLookupOptions, + RiotSummonerDto, +} from './riot.types'; + +@Injectable() +export class RiotSummonerService { + constructor(private readonly riotClientService: RiotClientService) {} + + public async getByPuuid( + puuid: string, + options: RiotPlatformLookupOptions = {}, + ): Promise { + return this.riotClientService.get( + `/lol/summoner/v4/summoners/by-puuid/${encodeURIComponent(puuid)}`, + { + platform: options.platform ?? 'kr', + signal: options.signal, + }, + parseSummoner, + ); + } +} + +function parseSummoner(value: unknown): RiotSummonerDto { + if (!isRecord(value)) { + throw new TypeError('Riot summoner response must be an object.'); + } + const puuid = value.puuid; + const profileIconId = value.profileIconId; + const revisionDate = value.revisionDate; + const summonerLevel = value.summonerLevel; + if (typeof puuid !== 'string' || puuid.length === 0) { + throw new TypeError('Summoner.puuid must be a non-empty string.'); + } + if (typeof profileIconId !== 'number') { + throw new TypeError('Summoner.profileIconId must be a number.'); + } + if (typeof revisionDate !== 'number') { + throw new TypeError('Summoner.revisionDate must be a number.'); + } + if (typeof summonerLevel !== 'number') { + throw new TypeError('Summoner.summonerLevel must be a number.'); + } + return { + puuid, + profileIconId, + revisionDate, + summonerLevel, + id: typeof value.id === 'string' ? value.id : undefined, + accountId: + typeof value.accountId === 'string' ? value.accountId : undefined, + }; +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} diff --git a/apps/api/src/modules/riot/riot.client.service.ts b/apps/api/src/modules/riot/riot.client.service.ts new file mode 100644 index 00000000..9c8e3225 --- /dev/null +++ b/apps/api/src/modules/riot/riot.client.service.ts @@ -0,0 +1,177 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { SecretService } from '../global/secret/secret.service'; +import { + RiotApiErrorBody, + RiotPlatformRoute, + RiotRegionalRoute, + RiotRequestOptions, + RiotResponseParser, +} from './riot.types'; +import { RiotRateLimiterService } from './riot-rate-limiter.service'; + +const RIOT_REGION_BASE_URLS: Record = { + americas: 'https://americas.api.riotgames.com', + asia: 'https://asia.api.riotgames.com', + europe: 'https://europe.api.riotgames.com', + sea: 'https://sea.api.riotgames.com', +}; + +const RIOT_PLATFORM_BASE_URLS: Record = { + br1: 'https://br1.api.riotgames.com', + eun1: 'https://eun1.api.riotgames.com', + euw1: 'https://euw1.api.riotgames.com', + jp1: 'https://jp1.api.riotgames.com', + kr: 'https://kr.api.riotgames.com', + la1: 'https://la1.api.riotgames.com', + la2: 'https://la2.api.riotgames.com', + me1: 'https://me1.api.riotgames.com', + na1: 'https://na1.api.riotgames.com', + oc1: 'https://oc1.api.riotgames.com', + ph2: 'https://ph2.api.riotgames.com', + ru: 'https://ru.api.riotgames.com', + sg2: 'https://sg2.api.riotgames.com', + th2: 'https://th2.api.riotgames.com', + tr1: 'https://tr1.api.riotgames.com', + tw2: 'https://tw2.api.riotgames.com', + vn2: 'https://vn2.api.riotgames.com', +}; + +export class RiotApiError extends Error { + constructor( + message: string, + public readonly status: number, + public readonly url: string, + public readonly body?: RiotApiErrorBody, + public readonly retryAfterSeconds?: number, + ) { + super(message); + } +} + +@Injectable() +export class RiotClientService { + private readonly logger = new Logger(RiotClientService.name); + + constructor( + private readonly secretService: SecretService, + private readonly rateLimiter: RiotRateLimiterService, + ) {} + + public async get( + path: string, + options: RiotRequestOptions = {}, + parser?: RiotResponseParser, + ): Promise { + const apiKey = await this.secretService.get('RIOT_API_KEY'); + const url = this.buildUrl(path, options); + const routeKey = options.platform ?? options.region ?? 'asia'; + + return this.fetchWithRetry(url, apiKey, options.signal, parser, routeKey); + } + + private buildUrl(path: string, options: RiotRequestOptions): string { + const baseUrl = options.platform + ? RIOT_PLATFORM_BASE_URLS[options.platform] + : RIOT_REGION_BASE_URLS[options.region ?? 'asia']; + const normalizedPath = path.startsWith('/') ? path : `/${path}`; + const url = new URL(`${baseUrl}${normalizedPath}`); + + if (options.query) { + for (const [key, value] of Object.entries(options.query)) { + if (value === undefined) { + continue; + } + + url.searchParams.set(key, String(value)); + } + } + + return url.toString(); + } + + private async createApiError( + response: Response, + url: string, + ): Promise { + let body: RiotApiErrorBody | undefined; + + try { + body = (await response.json()) as RiotApiErrorBody; + } catch { + body = undefined; + } + + const message = + body?.status?.message ?? + `Riot API request failed with status ${response.status}`; + const retryAfterHeader = response.headers.get('Retry-After'); + const retryAfterSeconds = retryAfterHeader + ? Number(retryAfterHeader) + : undefined; + + this.logger.warn(`${message} (${response.status}) ${url}`); + + return new RiotApiError( + message, + response.status, + url, + body, + Number.isFinite(retryAfterSeconds) ? retryAfterSeconds : undefined, + ); + } + + private async fetchWithRetry( + url: string, + apiKey: string, + signal: AbortSignal | undefined, + parser: RiotResponseParser | undefined, + routeKey: RiotRegionalRoute | RiotPlatformRoute, + attempt = 0, + ): Promise { + await this.rateLimiter.acquire(routeKey); + + const response = await fetch(url, { + method: 'GET', + headers: { + Accept: 'application/json', + 'X-Riot-Token': apiKey, + }, + signal, + }); + + const appRateLimitCount = response.headers.get('X-App-Rate-Limit-Count'); + if (appRateLimitCount && Math.random() < 0.05) { + this.logger.debug(`Riot rate usage ${routeKey}: ${appRateLimitCount}`); + } + + if (!response.ok) { + const error = await this.createApiError(response, url); + if ( + error.status === 429 && + attempt === 0 + ) { + await sleep((error.retryAfterSeconds ?? 1) * 1000); + return this.fetchWithRetry( + url, + apiKey, + signal, + parser, + routeKey, + attempt + 1, + ); + } + throw error; + } + + if (response.status === 204) { + return undefined as T; + } + + const payload = (await response.json()) as unknown; + return parser ? parser(payload) : (payload as T); + } +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/apps/api/src/modules/riot/riot.module.ts b/apps/api/src/modules/riot/riot.module.ts new file mode 100644 index 00000000..0989de8d --- /dev/null +++ b/apps/api/src/modules/riot/riot.module.ts @@ -0,0 +1,47 @@ +import { Module } from '@nestjs/common'; +import { SecretModule } from '../global/secret/secret.module'; +import { RiotAccountEnrichmentService } from './riot-account-enrichment.service'; +import { RiotAccountService } from './riot-account.service'; +import { RiotChampionMasteryService } from './riot-champion-mastery.service'; +import { RiotClientService } from './riot.client.service'; +import { RiotDdragonController } from './riot-ddragon.controller'; +import { RiotDdragonService } from './riot-ddragon.service'; +import { RiotLeagueService } from './riot-league.service'; +import { RiotMatchService } from './riot-match.service'; +import { RiotRateLimiterService } from './riot-rate-limiter.service'; +import { RiotRecentMatchesService } from './riot-recent-matches.service'; +import { RiotRecentStatsService } from './riot-recent-stats.service'; +import { RiotSummonerService } from './riot-summoner.service'; +import { RiotWebhookController } from './riot-webhook.controller'; + +@Module({ + imports: [SecretModule], + controllers: [RiotWebhookController, RiotDdragonController], + providers: [ + RiotRateLimiterService, + RiotClientService, + RiotAccountService, + RiotMatchService, + RiotRecentMatchesService, + RiotRecentStatsService, + RiotSummonerService, + RiotLeagueService, + RiotChampionMasteryService, + RiotAccountEnrichmentService, + RiotDdragonService, + ], + exports: [ + RiotRateLimiterService, + RiotClientService, + RiotAccountService, + RiotMatchService, + RiotRecentMatchesService, + RiotRecentStatsService, + RiotSummonerService, + RiotLeagueService, + RiotChampionMasteryService, + RiotAccountEnrichmentService, + RiotDdragonService, + ], +}) +export class RiotModule {} diff --git a/apps/api/src/modules/riot/riot.types.ts b/apps/api/src/modules/riot/riot.types.ts new file mode 100644 index 00000000..dd7df8d1 --- /dev/null +++ b/apps/api/src/modules/riot/riot.types.ts @@ -0,0 +1,251 @@ +export const RIOT_REGIONAL_ROUTES = [ + 'americas', + 'asia', + 'europe', + 'sea', +] as const; +export type RiotRegionalRoute = (typeof RIOT_REGIONAL_ROUTES)[number]; + +export const RIOT_PLATFORM_ROUTES = [ + 'br1', + 'eun1', + 'euw1', + 'jp1', + 'kr', + 'la1', + 'la2', + 'me1', + 'na1', + 'oc1', + 'ph2', + 'ru', + 'sg2', + 'th2', + 'tr1', + 'tw2', + 'vn2', +] as const; +export type RiotPlatformRoute = (typeof RIOT_PLATFORM_ROUTES)[number]; +export type RiotMatchType = 'ranked' | 'normal' | 'tourney' | 'tutorial'; + +export interface RiotAccountRegionDto { + puuid: string; + game: string; + region: RiotPlatformRoute; +} + +export interface RiotAccountApiResponse { + puuid: string; + gameName?: string; + tagLine?: string; +} + +export interface RiotAccountDto { + puuid: string; + gameName: string | null; + tagLine: string | null; +} + +export interface RiotRequestOptions { + region?: RiotRegionalRoute; + platform?: RiotPlatformRoute; + query?: Record; + signal?: AbortSignal; +} + +export type RiotResponseParser = (value: unknown) => T; + +export interface RiotApiErrorBody { + status?: { + message?: string; + status_code?: number; + }; +} + +export interface RiotAccountLookupOptions { + region?: RiotRegionalRoute; + signal?: AbortSignal; +} + +export interface RiotMatchLookupOptions { + region?: RiotRegionalRoute; + signal?: AbortSignal; +} + +export interface RiotPlatformLookupOptions { + platform?: RiotPlatformRoute; + signal?: AbortSignal; +} + +// Summoner-V4 by-puuid 응답 (간소화 — 실제 응답에 id 가 빠질 수 있어 optional 처리) +export interface RiotSummonerDto { + puuid: string; + profileIconId: number; + revisionDate: number; + summonerLevel: number; + id?: string; + accountId?: string; +} + +// League-V4 entries by-puuid 응답 +export interface RiotLeagueEntryDto { + leagueId: string; + queueType: string; + tier: string; + rank: string; + puuid: string; + leaguePoints: number; + wins: number; + losses: number; + veteran?: boolean; + inactive?: boolean; + freshBlood?: boolean; + hotStreak?: boolean; + miniSeries?: Record; +} + +// Champion-Mastery-V4 by-puuid 응답 +export interface RiotChampionMasteryDto extends Record { + puuid: string; + championId: number; + championLevel: number; + championPoints: number; + lastPlayTime?: number; + championPointsSinceLastLevel?: number; + championPointsUntilNextLevel?: number; + markRequiredForNextLevel?: number; + tokensEarned?: number; + championSeasonMilestone?: number; + milestoneGrades?: string[]; + nextSeasonMilestone?: Record; +} + +export interface RiotMatchIdsLookupOptions extends RiotMatchLookupOptions { + start?: number; + count?: number; + queue?: number; + type?: RiotMatchType; + startTime?: number; + endTime?: number; +} + +export interface RiotMatchDto { + metadata: RiotMatchMetadataDto; + info: RiotMatchInfoDto; +} + +export interface RiotMatchMetadataDto { + dataVersion: string; + matchId: string; + participants: string[]; +} + +export interface RiotMatchInfoDto extends Record { + endOfGameResult?: string; + gameCreation: number; + gameDuration: number; + gameEndTimestamp?: number; + gameId: number; + gameMode: string; + gameName: string; + gameStartTimestamp: number; + gameType: string; + gameVersion: string; + mapId: number; + participants: RiotMatchParticipantDto[]; + platformId: string; + queueId: number; + teams: RiotMatchTeamDto[]; + tournamentCode?: string; +} + +export interface RiotMatchParticipantDto extends Record { + assists: number; + champExperience: number; + champLevel: number; + championId: number; + championName: string; + deaths: number; + goldEarned: number; + goldSpent: number; + individualPosition: string; + item0: number; + item1: number; + item2: number; + item3: number; + item4: number; + item5: number; + item6: number; + kills: number; + neutralMinionsKilled: number; + participantId: number; + perks: RiotMatchPerksDto; + puuid: string; + riotIdGameName?: string; + riotIdTagLine?: string; + summoner1Id: number; + summoner2Id: number; + summonerId: string; + summonerLevel: number; + summonerName: string; + teamId: number; + teamPosition: string; + timePlayed: number; + totalDamageDealtToChampions: number; + totalDamageTaken: number; + totalMinionsKilled: number; + visionScore: number; + wardsKilled: number; + wardsPlaced: number; + win: boolean; +} + +export interface RiotMatchPerksDto { + statPerks: RiotMatchStatPerksDto; + styles: RiotMatchPerkStyleDto[]; +} + +export interface RiotMatchStatPerksDto { + defense: number; + flex: number; + offense: number; +} + +export interface RiotMatchPerkStyleDto { + description: string; + selections: RiotMatchPerkStyleSelectionDto[]; + style: number; +} + +export interface RiotMatchPerkStyleSelectionDto { + perk: number; + var1: number; + var2: number; + var3: number; +} + +export interface RiotMatchTeamDto extends Record { + bans: RiotMatchBanDto[]; + objectives: RiotMatchObjectivesDto; + teamId: number; + win: boolean; +} + +export interface RiotMatchBanDto { + championId: number; + pickTurn: number; +} + +export interface RiotMatchObjectivesDto { + baron: RiotMatchObjectiveDto; + champion: RiotMatchObjectiveDto; + dragon: RiotMatchObjectiveDto; + inhibitor: RiotMatchObjectiveDto; + riftHerald: RiotMatchObjectiveDto; + tower: RiotMatchObjectiveDto; +} + +export interface RiotMatchObjectiveDto { + first: boolean; + kills: number; +}