From 256d7761317af04cc72b3f7c87d13b3f2355ea8b Mon Sep 17 00:00:00 2001 From: dahyeon Date: Thu, 2 Jul 2026 14:18:26 -0700 Subject: [PATCH] Add Riot API client --- .../src/modules/riot/riot-api.client.spec.ts | 232 +++++++++ apps/api/src/modules/riot/riot-api.client.ts | 464 ++++++++++++++++++ .../modules/riot/riot-rate-limiter.spec.ts | 59 +++ .../api/src/modules/riot/riot-rate-limiter.ts | 111 +++++ apps/api/src/modules/riot/riot.module.ts | 11 + apps/api/src/modules/riot/riot.types.ts | 31 ++ 6 files changed, 908 insertions(+) create mode 100644 apps/api/src/modules/riot/riot-api.client.spec.ts create mode 100644 apps/api/src/modules/riot/riot-api.client.ts create mode 100644 apps/api/src/modules/riot/riot-rate-limiter.spec.ts create mode 100644 apps/api/src/modules/riot/riot-rate-limiter.ts create mode 100644 apps/api/src/modules/riot/riot.module.ts diff --git a/apps/api/src/modules/riot/riot-api.client.spec.ts b/apps/api/src/modules/riot/riot-api.client.spec.ts new file mode 100644 index 0000000..e3a4417 --- /dev/null +++ b/apps/api/src/modules/riot/riot-api.client.spec.ts @@ -0,0 +1,232 @@ +import { SecretService } from '../global/secret/secret.service'; +import { + RiotApiClient, + RiotApiKeyError, + RiotApiTimeoutError, + type RiotApiClientOptions, + RiotNotFoundError, +} from './riot-api.client'; +import { RiotRateLimiter } from './riot-rate-limiter'; + +type FetchMock = jest.Mock, Parameters>; +type SleepMock = jest.Mock, [number]>; + +function jsonResponse(body: unknown, init: ResponseInit = {}): Response { + return new Response(JSON.stringify(body), { + headers: { 'content-type': 'application/json' }, + status: 200, + ...init, + }); +} + +function createFetchMock(): FetchMock { + return jest.fn, Parameters>(); +} + +function createClient( + fetchMock: FetchMock, + options?: { + clientOptions?: Partial; + sleep?: SleepMock; + }, +) { + const getSecret = jest + .fn, [string]>() + .mockResolvedValue('RGAPI-test-key'); + const waitForSlot = jest + .fn, [string]>() + .mockResolvedValue(undefined); + const sleep = + options?.sleep ?? + jest.fn, [number]>().mockResolvedValue(undefined); + const secretService = { + get: getSecret, + } as unknown as SecretService; + const rateLimiter = { + waitForSlot, + } as unknown as RiotRateLimiter; + const clientOptions: RiotApiClientOptions = { + fetchFn: fetchMock, + sleep, + ...options?.clientOptions, + }; + const client = new RiotApiClient(secretService, rateLimiter, clientOptions); + + return { client, getSecret, sleep, waitForSlot }; +} + +describe('RiotApiClient', () => { + it('fetches account data through the regional Riot ID endpoint with an API key header', async () => { + const fetchMock = createFetchMock().mockResolvedValue( + jsonResponse({ + puuid: 'puuid-1', + gameName: 'Hide on bush', + tagLine: 'KR1', + }), + ); + const { client, getSecret, waitForSlot } = createClient(fetchMock); + + await expect( + client.getAccountByRiotId('Hide on bush', 'KR1', 'asia'), + ).resolves.toEqual({ + puuid: 'puuid-1', + gameName: 'Hide on bush', + tagLine: 'KR1', + }); + + expect(getSecret).toHaveBeenCalledWith('RIOT_API_KEY'); + expect(waitForSlot).toHaveBeenCalledWith('asia'); + const [requestUrl, requestInit] = fetchMock.mock.calls[0]; + expect(requestUrl).toBe( + 'https://asia.api.riotgames.com/riot/account/v1/accounts/by-riot-id/Hide%20on%20bush/KR1', + ); + expect(requestInit?.headers).toEqual( + expect.objectContaining({ + 'X-Riot-Token': 'RGAPI-test-key', + }), + ); + }); + + it('fetches platform and regional League endpoints with encoded parameters and query filters', async () => { + const fetchMock = createFetchMock() + .mockResolvedValueOnce( + jsonResponse({ + id: 'summoner-1', + puuid: 'puuid/1', + profileIconId: 7, + summonerLevel: 30, + }), + ) + .mockResolvedValueOnce(jsonResponse(['KR_1', 'KR_2'])); + const { client } = createClient(fetchMock); + + await client.getSummonerByPuuid('puuid/1', 'kr'); + await expect( + client.getMatchIds('puuid/1', { + regionalRoute: 'asia', + queue: 420, + start: 0, + count: 20, + }), + ).resolves.toEqual(['KR_1', 'KR_2']); + + expect(fetchMock).toHaveBeenNthCalledWith( + 1, + 'https://kr.api.riotgames.com/lol/summoner/v4/summoners/by-puuid/puuid%2F1', + expect.any(Object), + ); + expect(fetchMock).toHaveBeenNthCalledWith( + 2, + 'https://asia.api.riotgames.com/lol/match/v5/matches/by-puuid/puuid%2F1/ids?queue=420&start=0&count=20', + expect.any(Object), + ); + }); + + it('honors Retry-After for 429 responses and retries', async () => { + const sleep = jest + .fn, [number]>() + .mockResolvedValue(undefined); + const fetchMock = createFetchMock() + .mockResolvedValueOnce( + jsonResponse( + { status: { message: 'rate limited' } }, + { + status: 429, + headers: { 'retry-after': '2' }, + }, + ), + ) + .mockResolvedValueOnce(jsonResponse(['KR_1'])); + const { client } = createClient(fetchMock, { sleep }); + + await expect(client.getMatchIds('puuid-1')).resolves.toEqual(['KR_1']); + + expect(sleep).toHaveBeenCalledWith(2000); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + it('caps oversized Retry-After waits before retrying', async () => { + const sleep = jest + .fn, [number]>() + .mockResolvedValue(undefined); + const fetchMock = createFetchMock() + .mockResolvedValueOnce( + jsonResponse( + { status: { message: 'rate limited' } }, + { + status: 429, + headers: { 'retry-after': '9999' }, + }, + ), + ) + .mockResolvedValueOnce(jsonResponse(['KR_1'])); + const { client } = createClient(fetchMock, { sleep }); + + await expect(client.getMatchIds('puuid-1')).resolves.toEqual(['KR_1']); + + expect(sleep).toHaveBeenCalledWith(30_000); + }); + + it('fails 401 and 403 responses without retrying or leaking the API key', async () => { + const fetchMock = createFetchMock().mockResolvedValue( + jsonResponse({ status: { message: 'Forbidden' } }, { status: 403 }), + ); + const { client } = createClient(fetchMock); + + await expect(client.getMatch('KR_1')).rejects.toThrow(RiotApiKeyError); + await expect(client.getMatch('KR_1')).rejects.not.toThrow('RGAPI-test-key'); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + it('maps 404 responses to a domain not-found error', async () => { + const fetchMock = createFetchMock().mockResolvedValue( + jsonResponse({ status: { message: 'not found' } }, { status: 404 }), + ); + const { client } = createClient(fetchMock); + + await expect(client.getAccountByRiotId('Missing', 'KR1')).rejects.toThrow( + RiotNotFoundError, + ); + }); + + it('aborts a stalled Riot request with a domain timeout error', async () => { + const fetchMock: FetchMock = jest.fn( + (_input: RequestInfo | URL, init?: RequestInit) => + new Promise((_resolve, reject) => { + init?.signal?.addEventListener('abort', () => { + reject(new DOMException('aborted', 'AbortError')); + }); + }), + ); + const { client } = createClient(fetchMock, { + clientOptions: { requestTimeoutMs: 1 }, + }); + + await expect(client.getMatch('KR_1')).rejects.toThrow(RiotApiTimeoutError); + }); + + it('validates minimal match and timeline response invariants', async () => { + const fetchMock = createFetchMock() + .mockResolvedValueOnce(jsonResponse({ metadata: {}, info: {} })) + .mockResolvedValueOnce(jsonResponse({ metadata: {}, info: {} })); + const { client } = createClient(fetchMock); + + await expect(client.getMatch('KR_1')).resolves.toEqual({ + metadata: {}, + info: {}, + }); + await expect(client.getMatchTimeline('KR_1')).resolves.toEqual({ + metadata: {}, + info: {}, + }); + }); + + it('rejects malformed match payloads before analytics can consume them', async () => { + const fetchMock = createFetchMock().mockResolvedValue(jsonResponse({})); + const { client } = createClient(fetchMock); + + await expect(client.getMatch('KR_1')).rejects.toThrow( + 'Riot match response was missing object field "metadata".', + ); + }); +}); diff --git a/apps/api/src/modules/riot/riot-api.client.ts b/apps/api/src/modules/riot/riot-api.client.ts new file mode 100644 index 0000000..72b8f21 --- /dev/null +++ b/apps/api/src/modules/riot/riot-api.client.ts @@ -0,0 +1,464 @@ +import { Inject, Injectable, Optional } from '@nestjs/common'; +import { SecretService } from '../global/secret/secret.service'; +import { + RIOT_PLATFORM_ROUTES, + RIOT_REGIONAL_ROUTES, + type RiotPlatformRoute, + type RiotRegionalRoute, +} from './riot.types'; +import { RiotRateLimiter } from './riot-rate-limiter'; + +export const RIOT_API_CLIENT_OPTIONS = Symbol('RIOT_API_CLIENT_OPTIONS'); + +type FetchFunction = typeof fetch; + +export interface RiotApiClientOptions { + baseBackoffMs?: number; + maxRetryAfterMs?: number; + fetchFn?: FetchFunction; + requestTimeoutMs?: number; + maxRetries?: number; + sleep?: (durationMs: number) => Promise; +} + +export interface RiotAccountDto { + puuid: string; + gameName: string; + tagLine: string; +} + +export interface RiotSummonerDto { + accountId?: string; + id: string; + profileIconId: number; + puuid: string; + revisionDate?: number; + summonerLevel: number; +} + +export interface RiotLeagueEntryDto { + freshBlood: boolean; + hotStreak: boolean; + inactive: boolean; + leagueId: string; + leaguePoints: number; + losses: number; + queueType: string; + rank: string; + tier: string; + veteran: boolean; + wins: number; +} + +export interface RiotMatchIdsParams { + count?: number; + queue?: number; + regionalRoute?: RiotRegionalRoute; + start?: number; +} + +export class RiotApiError extends Error { + constructor( + message: string, + public readonly statusCode?: number, + public readonly code = 'RIOT_API_ERROR', + ) { + super(message); + this.name = new.target.name; + } +} + +export class RiotApiKeyError extends RiotApiError { + constructor(statusCode: number) { + super( + 'Riot API key is missing, expired, or invalid. Regenerate the key in the Riot Developer Portal and update Infisical RIOT_API_KEY.', + statusCode, + 'RIOT_API_KEY_INVALID', + ); + } +} + +export class RiotNotFoundError extends RiotApiError { + constructor(statusCode: number) { + super('Riot API resource was not found.', statusCode, 'RIOT_NOT_FOUND'); + } +} + +export class RiotApiTimeoutError extends RiotApiError { + constructor() { + super('Riot API request timed out.', undefined, 'RIOT_API_TIMEOUT'); + } +} + +const DEFAULT_MAX_RETRIES = 3; +const DEFAULT_BASE_BACKOFF_MS = 250; +const DEFAULT_MAX_RETRY_AFTER_MS = 30_000; +const DEFAULT_REQUEST_TIMEOUT_MS = 10_000; + +function defaultSleep(durationMs: number): Promise { + return new Promise((resolve) => setTimeout(resolve, durationMs)); +} + +function assertAllowedRoute( + route: RiotPlatformRoute | RiotRegionalRoute, +): void { + if ( + !RIOT_PLATFORM_ROUTES.includes(route as RiotPlatformRoute) && + !RIOT_REGIONAL_ROUTES.includes(route as RiotRegionalRoute) + ) { + throw new RiotApiError('Unsupported Riot routing value.'); + } +} + +function regionalBaseUrl(regionalRoute: RiotRegionalRoute): string { + assertAllowedRoute(regionalRoute); + return `https://${regionalRoute}.api.riotgames.com`; +} + +function platformBaseUrl(platformRoute: RiotPlatformRoute): string { + assertAllowedRoute(platformRoute); + return `https://${platformRoute}.api.riotgames.com`; +} + +function encodePathValue(value: string): string { + return encodeURIComponent(value); +} + +export function parseRetryAfterMs( + retryAfter: string | null, + now = Date.now(), +): number | undefined { + const trimmed = retryAfter?.trim(); + if (!trimmed) return undefined; + + const retryAfterSeconds = Number(trimmed); + if (Number.isFinite(retryAfterSeconds)) { + return Math.max(0, retryAfterSeconds * 1000); + } + + const retryAt = Date.parse(trimmed); + if (Number.isNaN(retryAt)) return undefined; + return Math.max(0, retryAt - now); +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function requireRecord(value: unknown, endpointName: string) { + if (!isRecord(value)) { + throw new RiotApiError( + `Riot ${endpointName} response had an unexpected shape.`, + ); + } + return value; +} + +function requireRecordField( + record: Record, + key: string, + endpointName: string, +): Record { + const value = record[key]; + if (!isRecord(value)) { + throw new RiotApiError( + `Riot ${endpointName} response was missing object field "${key}".`, + ); + } + return value; +} + +function requireString( + record: Record, + key: string, + endpointName: string, +): string { + const value = record[key]; + if (typeof value !== 'string') { + throw new RiotApiError( + `Riot ${endpointName} response was missing string field "${key}".`, + ); + } + return value; +} + +function optionalString(record: Record, key: string) { + const value = record[key]; + return typeof value === 'string' ? value : undefined; +} + +function numberOrFallback( + record: Record, + key: string, + fallback: number, +): number { + const value = record[key]; + return typeof value === 'number' ? value : fallback; +} + +function optionalNumber( + record: Record, + key: string, +): number | undefined { + const value = record[key]; + return typeof value === 'number' ? value : undefined; +} + +function optionalBoolean( + record: Record, + key: string, + fallback: boolean, +) { + const value = record[key]; + return typeof value === 'boolean' ? value : fallback; +} + +@Injectable() +export class RiotApiClient { + private readonly baseBackoffMs: number; + private readonly fetchFn: FetchFunction; + private readonly maxRetryAfterMs: number; + private readonly maxRetries: number; + private readonly requestTimeoutMs: number; + private readonly sleep: (durationMs: number) => Promise; + + constructor( + private readonly secretService: SecretService, + private readonly rateLimiter: RiotRateLimiter, + @Optional() + @Inject(RIOT_API_CLIENT_OPTIONS) + options: RiotApiClientOptions = {}, + ) { + this.baseBackoffMs = options.baseBackoffMs ?? DEFAULT_BASE_BACKOFF_MS; + this.fetchFn = options.fetchFn ?? fetch; + this.maxRetryAfterMs = + options.maxRetryAfterMs ?? DEFAULT_MAX_RETRY_AFTER_MS; + this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES; + this.requestTimeoutMs = + options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS; + this.sleep = options.sleep ?? defaultSleep; + } + + public async getAccountByRiotId( + gameName: string, + tagLine: string, + regionalRoute: RiotRegionalRoute = 'asia', + ): Promise { + const response = await this.requestJson( + regionalRoute, + `${regionalBaseUrl(regionalRoute)}/riot/account/v1/accounts/by-riot-id/${encodePathValue(gameName)}/${encodePathValue(tagLine)}`, + ); + return this.parseAccount(response); + } + + public async getSummonerByPuuid( + puuid: string, + platformRoute: RiotPlatformRoute = 'kr', + ): Promise { + const response = await this.requestJson( + platformRoute, + `${platformBaseUrl(platformRoute)}/lol/summoner/v4/summoners/by-puuid/${encodePathValue(puuid)}`, + ); + return this.parseSummoner(response); + } + + public async getLeagueEntriesByPuuid( + puuid: string, + platformRoute: RiotPlatformRoute = 'kr', + ): Promise { + const response = await this.requestJson( + platformRoute, + `${platformBaseUrl(platformRoute)}/lol/league/v4/entries/by-puuid/${encodePathValue(puuid)}`, + ); + return this.parseLeagueEntries(response); + } + + public async getMatchIds( + puuid: string, + params: RiotMatchIdsParams = {}, + ): Promise { + const regionalRoute = params.regionalRoute ?? 'asia'; + const searchParams = new URLSearchParams(); + if (params.queue !== undefined) + searchParams.set('queue', String(params.queue)); + if (params.start !== undefined) + searchParams.set('start', String(params.start)); + if (params.count !== undefined) + searchParams.set('count', String(params.count)); + + const query = searchParams.size > 0 ? `?${searchParams.toString()}` : ''; + const response = await this.requestJson( + regionalRoute, + `${regionalBaseUrl(regionalRoute)}/lol/match/v5/matches/by-puuid/${encodePathValue(puuid)}/ids${query}`, + ); + return this.parseMatchIds(response); + } + + public async getMatch( + matchId: string, + regionalRoute: RiotRegionalRoute = 'asia', + ): Promise> { + const response = await this.requestJson( + regionalRoute, + `${regionalBaseUrl(regionalRoute)}/lol/match/v5/matches/${encodePathValue(matchId)}`, + ); + return this.parseMatchPayload(response, 'match'); + } + + public async getMatchTimeline( + matchId: string, + regionalRoute: RiotRegionalRoute = 'asia', + ): Promise> { + const response = await this.requestJson( + regionalRoute, + `${regionalBaseUrl(regionalRoute)}/lol/match/v5/matches/${encodePathValue(matchId)}/timeline`, + ); + return this.parseMatchPayload(response, 'match timeline'); + } + + private async requestJson( + routingValue: RiotPlatformRoute | RiotRegionalRoute, + url: string, + ): Promise { + const apiKey = await this.secretService.get('RIOT_API_KEY'); + + for (let attemptIndex = 0; ; attemptIndex += 1) { + await this.rateLimiter.waitForSlot(routingValue); + + const response = await this.fetchWithTimeout(url, apiKey); + + if (response.status === 429 && attemptIndex < this.maxRetries) { + const rawRetryAfterMs = + parseRetryAfterMs(response.headers.get('retry-after')) ?? + this.exponentialBackoffMs(attemptIndex); + const retryAfterMs = Math.min(rawRetryAfterMs, this.maxRetryAfterMs); + await this.sleep(retryAfterMs); + continue; + } + + if (response.status >= 500 && attemptIndex < this.maxRetries) { + await this.sleep(this.exponentialBackoffMs(attemptIndex)); + continue; + } + + if (response.status === 401 || response.status === 403) { + throw new RiotApiKeyError(response.status); + } + if (response.status === 404) { + throw new RiotNotFoundError(response.status); + } + if (!response.ok) { + throw new RiotApiError( + `Riot API request failed with status ${response.status}.`, + response.status, + ); + } + + return response.json(); + } + } + + private exponentialBackoffMs(attemptIndex: number): number { + return this.baseBackoffMs * 2 ** attemptIndex; + } + + private async fetchWithTimeout( + url: string, + apiKey: string, + ): Promise { + const abortController = new AbortController(); + const timeout = setTimeout( + () => abortController.abort(), + this.requestTimeoutMs, + ); + try { + return await this.fetchFn(url, { + headers: { + Accept: 'application/json', + 'X-Riot-Token': apiKey, + }, + signal: abortController.signal, + }); + } catch (error) { + if ( + error instanceof DOMException && + error.name.toLowerCase() === 'aborterror' + ) { + throw new RiotApiTimeoutError(); + } + throw error; + } finally { + clearTimeout(timeout); + } + } + + private parseAccount(value: unknown): RiotAccountDto { + const record = requireRecord(value, 'account'); + return { + puuid: requireString(record, 'puuid', 'account'), + gameName: requireString(record, 'gameName', 'account'), + tagLine: requireString(record, 'tagLine', 'account'), + }; + } + + private parseSummoner(value: unknown): RiotSummonerDto { + const record = requireRecord(value, 'summoner'); + return { + id: requireString(record, 'id', 'summoner'), + accountId: optionalString(record, 'accountId'), + puuid: requireString(record, 'puuid', 'summoner'), + profileIconId: numberOrFallback(record, 'profileIconId', 0), + revisionDate: optionalNumber(record, 'revisionDate'), + summonerLevel: numberOrFallback(record, 'summonerLevel', 0), + }; + } + + private parseLeagueEntries(value: unknown): RiotLeagueEntryDto[] { + if (!Array.isArray(value)) { + throw new RiotApiError( + 'Riot league entries response had an unexpected shape.', + ); + } + + return value.map((entry) => { + const record = requireRecord(entry, 'league entry'); + return { + leagueId: requireString(record, 'leagueId', 'league entry'), + queueType: requireString(record, 'queueType', 'league entry'), + tier: requireString(record, 'tier', 'league entry'), + rank: requireString(record, 'rank', 'league entry'), + leaguePoints: numberOrFallback(record, 'leaguePoints', 0), + wins: numberOrFallback(record, 'wins', 0), + losses: numberOrFallback(record, 'losses', 0), + veteran: optionalBoolean(record, 'veteran', false), + inactive: optionalBoolean(record, 'inactive', false), + freshBlood: optionalBoolean(record, 'freshBlood', false), + hotStreak: optionalBoolean(record, 'hotStreak', false), + }; + }); + } + + private parseMatchIds(value: unknown): string[] { + if (!Array.isArray(value)) { + throw new RiotApiError('Riot match id response had an unexpected shape.'); + } + + const matchIds = value.filter( + (matchId): matchId is string => typeof matchId === 'string', + ); + if (matchIds.length !== value.length) { + throw new RiotApiError('Riot match id response had an unexpected shape.'); + } + return matchIds; + } + + private parseMatchPayload( + value: unknown, + endpointName: string, + ): Record { + const record = requireRecord(value, endpointName); + requireRecordField(record, 'metadata', endpointName); + requireRecordField(record, 'info', endpointName); + return record; + } +} diff --git a/apps/api/src/modules/riot/riot-rate-limiter.spec.ts b/apps/api/src/modules/riot/riot-rate-limiter.spec.ts new file mode 100644 index 0000000..8751889 --- /dev/null +++ b/apps/api/src/modules/riot/riot-rate-limiter.spec.ts @@ -0,0 +1,59 @@ +import { RiotRateLimiter } from './riot-rate-limiter'; + +class ManualClock { + public currentTimeMs = 0; + public sleeps: number[] = []; + + now = () => this.currentTimeMs; + + sleep = (durationMs: number): Promise => { + this.sleeps.push(durationMs); + this.currentTimeMs += durationMs; + return Promise.resolve(); + }; +} + +describe('RiotRateLimiter', () => { + it('waits when the one-second development key window is exhausted', async () => { + const clock = new ManualClock(); + const limiter = new RiotRateLimiter({ clock }); + + for (let index = 0; index < 20; index += 1) { + await limiter.waitForSlot('asia'); + } + await limiter.waitForSlot('asia'); + + expect(clock.sleeps).toEqual([1000]); + }); + + it('tracks windows independently per Riot routing value', async () => { + const clock = new ManualClock(); + const limiter = new RiotRateLimiter({ clock }); + + for (let index = 0; index < 20; index += 1) { + await limiter.waitForSlot('asia'); + } + await limiter.waitForSlot('kr'); + + expect(clock.sleeps).toEqual([]); + }); + + it('waits for the longest exhausted window before recording a new request', async () => { + const clock = new ManualClock(); + const limiter = new RiotRateLimiter({ + clock, + windows: [ + { limit: 2, durationMs: 1000 }, + { limit: 3, durationMs: 5000 }, + ], + }); + + await limiter.waitForSlot('asia'); + await limiter.waitForSlot('asia'); + clock.currentTimeMs = 1000; + await limiter.waitForSlot('asia'); + await limiter.waitForSlot('asia'); + + expect(clock.sleeps).toEqual([4000]); + }); +}); diff --git a/apps/api/src/modules/riot/riot-rate-limiter.ts b/apps/api/src/modules/riot/riot-rate-limiter.ts new file mode 100644 index 0000000..6930622 --- /dev/null +++ b/apps/api/src/modules/riot/riot-rate-limiter.ts @@ -0,0 +1,111 @@ +import { Inject, Injectable, Optional } from '@nestjs/common'; + +export const RIOT_RATE_LIMITER_OPTIONS = Symbol('RIOT_RATE_LIMITER_OPTIONS'); + +export interface RiotRateLimitWindow { + durationMs: number; + limit: number; +} + +export interface RiotRateLimiterClock { + now(): number; + sleep(durationMs: number): Promise; +} + +export interface RiotRateLimiterOptions { + clock?: RiotRateLimiterClock; + windows?: RiotRateLimitWindow[]; +} + +const DEFAULT_RATE_LIMIT_WINDOWS: RiotRateLimitWindow[] = [ + { limit: 20, durationMs: 1000 }, + { limit: 100, durationMs: 120_000 }, +]; + +// Single-process limiter for the MVP worker/API process. If workers split into +// multiple processes or hosts, replace this with Redis-backed coordination. +const DEFAULT_CLOCK: RiotRateLimiterClock = { + now: () => Date.now(), + sleep: (durationMs: number) => + new Promise((resolve) => setTimeout(resolve, durationMs)), +}; + +@Injectable() +export class RiotRateLimiter { + private readonly clock: RiotRateLimiterClock; + private readonly windows: RiotRateLimitWindow[]; + private readonly requestTimestampsByRoutingValue = new Map< + string, + number[] + >(); + + constructor( + @Optional() + @Inject(RIOT_RATE_LIMITER_OPTIONS) + options: RiotRateLimiterOptions = {}, + ) { + this.clock = options.clock ?? DEFAULT_CLOCK; + this.windows = options.windows ?? DEFAULT_RATE_LIMIT_WINDOWS; + } + + public async waitForSlot(routingValue: string): Promise { + const requestTimestamps = + this.requestTimestampsByRoutingValue.get(routingValue) ?? []; + this.requestTimestampsByRoutingValue.set(routingValue, requestTimestamps); + + while (true) { + const now = this.clock.now(); + this.pruneExpiredTimestamps(requestTimestamps, now); + + const waitDurationMs = this.resolveWaitDurationMs(requestTimestamps, now); + if (waitDurationMs <= 0) { + requestTimestamps.push(now); + return; + } + + await this.clock.sleep(waitDurationMs); + } + } + + private pruneExpiredTimestamps( + requestTimestamps: number[], + now: number, + ): void { + const longestWindowDurationMs = Math.max( + ...this.windows.map((window) => window.durationMs), + ); + const firstRetainedIndex = requestTimestamps.findIndex( + (timestamp) => timestamp > now - longestWindowDurationMs, + ); + + if (firstRetainedIndex === -1) { + requestTimestamps.splice(0, requestTimestamps.length); + return; + } + if (firstRetainedIndex > 0) { + requestTimestamps.splice(0, firstRetainedIndex); + } + } + + private resolveWaitDurationMs( + requestTimestamps: number[], + now: number, + ): number { + let waitDurationMs = 0; + + for (const window of this.windows) { + const timestampsInWindow = requestTimestamps.filter( + (timestamp) => timestamp > now - window.durationMs, + ); + if (timestampsInWindow.length < window.limit) continue; + + const oldestTimestamp = timestampsInWindow[0]; + waitDurationMs = Math.max( + waitDurationMs, + oldestTimestamp + window.durationMs - now, + ); + } + + return waitDurationMs; + } +} 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 0000000..4227c1b --- /dev/null +++ b/apps/api/src/modules/riot/riot.module.ts @@ -0,0 +1,11 @@ +import { Module } from '@nestjs/common'; +import { SecretModule } from '../global/secret/secret.module'; +import { RiotApiClient } from './riot-api.client'; +import { RiotRateLimiter } from './riot-rate-limiter'; + +@Module({ + imports: [SecretModule], + providers: [RiotApiClient, RiotRateLimiter], + exports: [RiotApiClient, RiotRateLimiter], +}) +export class RiotModule {} diff --git a/apps/api/src/modules/riot/riot.types.ts b/apps/api/src/modules/riot/riot.types.ts index 6fbc2dd..50a3560 100644 --- a/apps/api/src/modules/riot/riot.types.ts +++ b/apps/api/src/modules/riot/riot.types.ts @@ -17,12 +17,41 @@ export type RiotPlatformRoute = | 'ru' | 'me1' | 'oc1' + | 'ph2' | 'sg2' + | 'th2' | 'tw2' | 'vn2'; export type RiotRegionalRoute = 'americas' | 'asia' | 'europe' | 'sea'; +export const RIOT_PLATFORM_ROUTES: readonly RiotPlatformRoute[] = [ + 'kr', + 'jp1', + 'na1', + 'br1', + 'la1', + 'la2', + 'euw1', + 'eun1', + 'tr1', + 'ru', + 'me1', + 'oc1', + 'ph2', + 'sg2', + 'th2', + 'tw2', + 'vn2', +]; + +export const RIOT_REGIONAL_ROUTES: readonly RiotRegionalRoute[] = [ + 'americas', + 'asia', + 'europe', + 'sea', +]; + export const PLATFORM_TO_REGIONAL_ROUTE: Record< RiotPlatformRoute, RiotRegionalRoute @@ -39,7 +68,9 @@ export const PLATFORM_TO_REGIONAL_ROUTE: Record< ru: 'europe', me1: 'europe', oc1: 'sea', + ph2: 'sea', sg2: 'sea', + th2: 'sea', tw2: 'sea', vn2: 'sea', };