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.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.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; +}