feat(api): integrate Riot data

This commit is contained in:
dahyeon committed 2026-04-11 22:47:00 +09:00
1 parent 79d2a46a05
commit afc1355221
21 files changed
+3921

No files matched your search

@@ -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<string, unknown>;
championRecordsFetchedAt?: Date;
}
function makeAccount(overrides: Partial<FakeAccount> = {}): 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<RiotAccountService>;
summoner?: Partial<RiotSummonerService>;
league?: Partial<RiotLeagueService>;
mastery?: Partial<RiotChampionMasteryService>;
recentMatches?: Partial<RiotRecentMatchesService>;
recentStats?: Partial<RiotRecentStatsService>;
}) {
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<RiotSummonerService>,
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<RiotLeagueService>,
mastery: {
getTopByPuuid: jest.fn().mockResolvedValue([
{
puuid: 'puuid-1',
championId: 7,
championLevel: 70,
championPoints: 742560,
},
]),
} as Partial<RiotChampionMasteryService>,
recentMatches: {
syncRecentMatches: jest.fn().mockResolvedValue([]),
loadFromDb: jest.fn().mockResolvedValue([
{ matchId: 'KR_1', raw: {} },
{ matchId: 'KR_2', raw: {} },
]),
} as Partial<RiotRecentMatchesService>,
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<RiotRecentStatsService>,
});
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<RiotSummonerService>,
league: {
getEntriesByPuuid: league,
} as Partial<RiotLeagueService>,
mastery: {
getTopByPuuid: mastery,
} as Partial<RiotChampionMasteryService>,
});
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<RiotSummonerService>,
league: {
getEntriesByPuuid: jest.fn().mockResolvedValue([]),
} as Partial<RiotLeagueService>,
mastery: {
getTopByPuuid: jest.fn().mockResolvedValue([]),
} as Partial<RiotChampionMasteryService>,
});
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<RiotAccountService>,
summoner: { getByPuuid: summoner } as Partial<RiotSummonerService>,
league: {
getEntriesByPuuid: league,
} as Partial<RiotLeagueService>,
mastery: {
getTopByPuuid: mastery,
} as Partial<RiotChampionMasteryService>,
});
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<RiotSummonerService>,
league: {
getEntriesByPuuid: jest.fn().mockResolvedValue([]),
} as Partial<RiotLeagueService>,
mastery: {
getTopByPuuid: jest.fn().mockResolvedValue([]),
} as Partial<RiotChampionMasteryService>,
});
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);
});
});
@@ -0,0 +1,450 @@
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<string, Promise<EnrichResult>>();
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 markRefreshRequested(
userId: mongoose.Types.ObjectId,
puuid: string,
at: Date = new Date(),
): Promise<void> {
const UserModel = await this.connectionService.getModel('user');
await UserModel.updateOne(
{ _id: userId, 'riotAccounts.puuid': puuid },
{ $set: { 'riotAccounts.$.lastRefreshRequestedAt': at } },
).exec();
}
public async enrichRiotAccount(params: {
userId: mongoose.Types.ObjectId;
puuid: string;
options?: EnrichOptions;
}): Promise<EnrichResult> {
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<EnrichResult> {
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<RiotAccount['recentStatsSummary']>,
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;
}
}
@@ -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<RiotAccountDto> {
return this.riotClientService.get<RiotAccountDto>(
`/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<RiotAccountDto> {
return this.riotClientService.get<RiotAccountDto>(
`/riot/account/v1/accounts/by-puuid/${encodeURIComponent(puuid)}`,
{
region: options.region,
signal: options.signal,
},
parseRiotAccountDto,
);
}
public async getRegionByPuuid(
puuid: string,
options: RiotAccountLookupOptions = {},
): Promise<RiotAccountRegionDto> {
return this.riotClientService.get<RiotAccountRegionDto>(
`/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<string, unknown> {
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';
}
@@ -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<RiotChampionMasteryDto[]> {
return this.riotClientService.get<RiotChampionMasteryDto[]>(
`/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<RiotChampionMasteryDto[]> {
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<RiotChampionMasteryDto[]>(
`/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<string, unknown> {
return typeof value === 'object' && value !== null;
}
@@ -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<DdragonManifest> {
return this.ddragonService.getManifest(locale ?? 'ko_KR');
}
}
@@ -0,0 +1,250 @@
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 = 'v3';
const FETCH_TIMEOUT_MS = 10_000;
export interface DdragonChampionEntry {
key: string;
name: string;
}
export interface DdragonSummonerSpellEntry {
key: string;
name: string;
}
export interface DdragonRuneEntry {
id: number;
key: string;
icon: string;
name: string;
}
export interface DdragonRuneStyleEntry extends DdragonRuneEntry {
slots: Array<{ runes: DdragonRuneEntry[] }>;
}
export interface DdragonManifest {
version: string;
cdn: string;
locale: string;
champions: Record<string, DdragonChampionEntry>;
summonerSpells: Record<string, DdragonSummonerSpellEntry>;
runesReforged: DdragonRuneStyleEntry[];
fetchedAt: string;
}
interface ChampionDataEntry {
key: string;
id: string;
name: string;
}
interface ChampionDataResponse {
data: Record<string, ChampionDataEntry>;
}
interface SummonerSpellDataEntry {
key: string;
id: string;
name: string;
}
interface SummonerSpellDataResponse {
data: Record<string, SummonerSpellDataEntry>;
}
interface RuneDataEntry {
id: number;
key: string;
icon: string;
name: string;
}
interface RuneStyleDataEntry extends RuneDataEntry {
slots?: Array<{ runes?: RuneDataEntry[] }>;
}
@Injectable()
export class RiotDdragonService {
private readonly logger = new Logger(RiotDdragonService.name);
private inflight = new Map<string, Promise<DdragonManifest>>();
constructor(private readonly garnetService: GarnetService) {}
public async getManifest(locale: string = DEFAULT_LOCALE): Promise<DdragonManifest> {
const normalizedLocale = normalizeLocale(locale);
const cacheKey = manifestCacheKey(normalizedLocale);
const cached = await this.garnetService.getJson<DdragonManifest>(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<DdragonManifest> {
const version = await this.fetchLatestVersion();
const [champions, summonerSpells, runesReforged] = await Promise.all([
this.fetchChampionMap(version, locale),
this.fetchSummonerSpellMap(version, locale),
this.fetchRuneStyles(version, locale),
]);
return {
version,
cdn: DDRAGON_CDN,
locale,
champions,
summonerSpells,
runesReforged,
fetchedAt: new Date().toISOString(),
};
}
private async fetchLatestVersion(): Promise<string> {
const versions = await this.fetchJson<unknown>(`${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<Record<string, DdragonChampionEntry>> {
const url = `${DDRAGON_CDN}/${version}/data/${locale}/champion.json`;
const payload = await this.fetchJson<ChampionDataResponse>(url);
if (!payload || typeof payload !== 'object' || !payload.data) {
throw new Error(`ddragon champion.json response is malformed (${url}).`);
}
const map: Record<string, DdragonChampionEntry> = {};
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 fetchSummonerSpellMap(
version: string,
locale: string,
): Promise<Record<string, DdragonSummonerSpellEntry>> {
const url = `${DDRAGON_CDN}/${version}/data/${locale}/summoner.json`;
const payload = await this.fetchJson<SummonerSpellDataResponse>(url);
if (!payload || typeof payload !== 'object' || !payload.data) {
throw new Error(`ddragon summoner.json response is malformed (${url}).`);
}
const map: Record<string, DdragonSummonerSpellEntry> = {};
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 fetchRuneStyles(
version: string,
locale: string,
): Promise<DdragonRuneStyleEntry[]> {
const url = `${DDRAGON_CDN}/${version}/data/${locale}/runesReforged.json`;
const payload = await this.fetchJson<unknown>(url);
if (!Array.isArray(payload)) {
throw new Error(`ddragon runesReforged.json response is malformed (${url}).`);
}
return payload
.filter((style): style is RuneStyleDataEntry => isRuneEntry(style))
.map((style) => ({
id: style.id,
key: style.key,
icon: style.icon,
name: style.name,
slots: (style.slots ?? []).map((slot) => ({
runes: (slot.runes ?? [])
.filter((rune): rune is RuneDataEntry => isRuneEntry(rune))
.map((rune) => ({
id: rune.id,
key: rune.key,
icon: rune.icon,
name: rune.name,
})),
})),
}));
}
private async fetchJson<T>(url: string): Promise<T> {
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 isRuneEntry(value: unknown): value is RuneDataEntry {
if (!value || typeof value !== 'object') return false;
const entry = value as Partial<RuneDataEntry>;
return (
typeof entry.id === 'number' &&
typeof entry.key === 'string' &&
typeof entry.icon === 'string' &&
typeof entry.name === 'string'
);
}
function manifestCacheKey(locale: string): string {
return `ddragon:manifest:${CACHE_VERSION}:${locale}`;
}
@@ -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<RiotLeagueEntryDto[]> {
return this.riotClientService.get<RiotLeagueEntryDto[]>(
`/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<string, unknown> {
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;
}
@@ -0,0 +1,109 @@
import { RiotClientService } from './riot.client.service';
import { RiotMatchService } from './riot-match.service';
import type { RiotResponseParser } from './riot.types';
function createMatchPayload() {
const participant = {
assists: 7,
champExperience: 12000,
champLevel: 16,
championId: 103,
championName: 'Ahri',
deaths: 2,
goldEarned: 12000,
goldSpent: 11000,
individualPosition: '',
item0: 0,
item1: 0,
item2: 0,
item3: 0,
item4: 0,
item5: 0,
item6: 0,
kills: 8,
neutralMinionsKilled: 12,
participantId: 1,
perks: {
statPerks: { defense: 0, flex: 0, offense: 0 },
styles: [],
},
puuid: 'puuid-1',
riotIdGameName: '테스터',
riotIdTagLine: 'KR1',
summoner1Id: 4,
summoner2Id: 14,
summonerId: 'summoner-id-1',
summonerLevel: 100,
summonerName: '',
teamId: 100,
teamPosition: '',
timePlayed: 1800,
totalDamageDealtToChampions: 22000,
totalDamageTaken: 11000,
totalMinionsKilled: 180,
visionScore: 20,
wardsKilled: 2,
wardsPlaced: 10,
win: true,
};
return {
metadata: {
dataVersion: '2',
matchId: 'KR_8188913502',
participants: ['puuid-1'],
},
info: {
gameCreation: 1777000000000,
gameDuration: 1800,
gameEndTimestamp: 1777001800000,
gameId: 8188913502,
gameMode: 'CLASSIC',
gameName: 'teambuilder-match-8188913502',
gameStartTimestamp: 1777000000000,
gameType: 'MATCHED_GAME',
gameVersion: '15.8.1',
mapId: 11,
participants: [participant],
platformId: 'KR',
queueId: 420,
teams: [
{
bans: [],
objectives: {
baron: { first: false, kills: 0 },
champion: { first: true, kills: 25 },
dragon: { first: true, kills: 3 },
inhibitor: { first: false, kills: 1 },
riftHerald: { first: true, kills: 1 },
tower: { first: true, kills: 8 },
},
teamId: 100,
win: true,
},
],
},
};
}
describe('RiotMatchService', () => {
it('accepts empty Riot display fields in match participants', async () => {
const payload = createMatchPayload();
const riotClientService = {
get: jest.fn(
async <T>(
_path: string,
_options: unknown,
parser?: RiotResponseParser<T>,
) => (parser ? parser(payload) : (payload as T)),
),
} as unknown as RiotClientService;
const service = new RiotMatchService(riotClientService);
const match = await service.getMatch('KR_8188913502', { region: 'asia' });
expect(match.info.participants[0].summonerName).toBe('');
expect(match.info.participants[0].teamPosition).toBe('');
expect(match.info.participants[0].individualPosition).toBe('');
});
});
@@ -0,0 +1,630 @@
import { Injectable } from '@nestjs/common';
import { RiotClientService } from './riot.client.service';
import {
RiotMatchBanDto,
RiotMatchDto,
RiotMatchIdsLookupOptions,
RiotMatchInfoDto,
RiotMatchLookupOptions,
RiotMatchMetadataDto,
RiotMatchObjectiveDto,
RiotMatchObjectivesDto,
RiotMatchParticipantDto,
RiotMatchPerksDto,
RiotMatchPerkStyleDto,
RiotMatchPerkStyleSelectionDto,
RiotMatchStatPerksDto,
RiotMatchTeamDto,
RiotMatchType,
} from './riot.types';
const RIOT_MATCH_TYPES: RiotMatchType[] = [
'ranked',
'normal',
'tourney',
'tutorial',
];
@Injectable()
export class RiotMatchService {
constructor(private readonly riotClientService: RiotClientService) {}
public async getMatchIdsByPuuid(
puuid: string,
options: RiotMatchIdsLookupOptions = {},
): Promise<string[]> {
validateMatchIdsLookupOptions(options);
return this.riotClientService.get<string[]>(
`/lol/match/v5/matches/by-puuid/${encodeURIComponent(puuid)}/ids`,
{
region: options.region,
signal: options.signal,
query: {
start: options.start,
count: options.count,
queue: options.queue,
type: options.type,
startTime: options.startTime,
endTime: options.endTime,
},
},
parseMatchIdsResponse,
);
}
public async getMatch(
matchId: string,
options: RiotMatchLookupOptions = {},
): Promise<RiotMatchDto> {
return this.riotClientService.get<RiotMatchDto>(
`/lol/match/v5/matches/${encodeURIComponent(matchId)}`,
{
region: options.region,
signal: options.signal,
},
parseMatchResponse,
);
}
}
function validateMatchIdsLookupOptions(
options: RiotMatchIdsLookupOptions,
): void {
assertOptionalNonNegativeInteger(options.start, 'start');
assertOptionalRange(options.count, 'count', 0, 100);
assertOptionalNonNegativeInteger(options.queue, 'queue');
assertOptionalNonNegativeInteger(options.startTime, 'startTime');
assertOptionalNonNegativeInteger(options.endTime, 'endTime');
if (options.type !== undefined && !RIOT_MATCH_TYPES.includes(options.type)) {
throw new RangeError(
`type must be one of: ${RIOT_MATCH_TYPES.join(', ')}`,
);
}
if (
options.startTime !== undefined &&
options.endTime !== undefined &&
options.startTime > options.endTime
) {
throw new RangeError('startTime must be less than or equal to endTime.');
}
}
function parseMatchIdsResponse(value: unknown): string[] {
if (!Array.isArray(value)) {
throw new TypeError('Riot match ids response must be an array.');
}
if (!value.every(isNonEmptyString)) {
throw new TypeError('Riot match ids response must contain only strings.');
}
return value;
}
function parseMatchResponse(value: unknown): RiotMatchDto {
if (!isRecord(value)) {
throw new TypeError('Riot match response must be an object.');
}
return {
metadata: parseMatchMetadata(value.metadata),
info: parseMatchInfo(value.info),
};
}
function parseMatchMetadata(value: unknown): RiotMatchMetadataDto {
if (!isRecord(value)) {
throw new TypeError('Riot match metadata must be an object.');
}
const dataVersion = value.dataVersion;
const matchId = value.matchId;
const participants = value.participants;
if (!isNonEmptyString(dataVersion)) {
throw new TypeError('Riot match metadata.dataVersion must be a string.');
}
if (!isNonEmptyString(matchId)) {
throw new TypeError('Riot match metadata.matchId must be a string.');
}
if (!Array.isArray(participants) || !participants.every(isNonEmptyString)) {
throw new TypeError(
'Riot match metadata.participants must be an array of strings.',
);
}
return {
dataVersion,
matchId,
participants,
};
}
function parseMatchInfo(value: unknown): RiotMatchInfoDto {
if (!isRecord(value)) {
throw new TypeError('Riot match info must be an object.');
}
const participants = value.participants;
const teams = value.teams;
if (!Array.isArray(participants)) {
throw new TypeError('Riot match info.participants must be an array.');
}
if (!Array.isArray(teams)) {
throw new TypeError('Riot match info.teams must be an array.');
}
const gameCreation = requireNumber(value.gameCreation, 'info.gameCreation');
const gameDuration = requireNumber(value.gameDuration, 'info.gameDuration');
const gameId = requireNumber(value.gameId, 'info.gameId');
const gameMode = requireString(value.gameMode, 'info.gameMode');
const gameName = requireString(value.gameName, 'info.gameName');
const gameStartTimestamp = requireNumber(
value.gameStartTimestamp,
'info.gameStartTimestamp',
);
const gameType = requireString(value.gameType, 'info.gameType');
const gameVersion = requireString(value.gameVersion, 'info.gameVersion');
const mapId = requireNumber(value.mapId, 'info.mapId');
const platformId = requireString(value.platformId, 'info.platformId');
const queueId = requireNumber(value.queueId, 'info.queueId');
const gameEndTimestamp = optionalNumber(
value.gameEndTimestamp,
'info.gameEndTimestamp',
);
const tournamentCode = optionalString(
value.tournamentCode,
'info.tournamentCode',
);
const endOfGameResult = optionalString(
value.endOfGameResult,
'info.endOfGameResult',
);
return {
...value,
endOfGameResult,
gameCreation,
gameDuration,
gameEndTimestamp,
gameId,
gameMode,
gameName,
gameStartTimestamp,
gameType,
gameVersion,
mapId,
participants: participants.map((participant, index) =>
parseParticipant(participant, index),
),
platformId,
queueId,
teams: teams.map((team, index) => parseTeam(team, index)),
tournamentCode,
};
}
function parseParticipant(
value: unknown,
index: number,
): RiotMatchParticipantDto {
if (!isRecord(value)) {
throw new TypeError(`participants[${index}] must be an object.`);
}
return {
...value,
assists: requireNumber(value.assists, `participants[${index}].assists`),
champExperience: requireNumber(
value.champExperience,
`participants[${index}].champExperience`,
),
champLevel: requireNumber(
value.champLevel,
`participants[${index}].champLevel`,
),
championId: requireNumber(
value.championId,
`participants[${index}].championId`,
),
championName: requireString(
value.championName,
`participants[${index}].championName`,
),
deaths: requireNumber(value.deaths, `participants[${index}].deaths`),
goldEarned: requireNumber(
value.goldEarned,
`participants[${index}].goldEarned`,
),
goldSpent: requireNumber(
value.goldSpent,
`participants[${index}].goldSpent`,
),
individualPosition: requireStringAllowEmpty(
value.individualPosition,
`participants[${index}].individualPosition`,
),
item0: requireNumber(value.item0, `participants[${index}].item0`),
item1: requireNumber(value.item1, `participants[${index}].item1`),
item2: requireNumber(value.item2, `participants[${index}].item2`),
item3: requireNumber(value.item3, `participants[${index}].item3`),
item4: requireNumber(value.item4, `participants[${index}].item4`),
item5: requireNumber(value.item5, `participants[${index}].item5`),
item6: requireNumber(value.item6, `participants[${index}].item6`),
kills: requireNumber(value.kills, `participants[${index}].kills`),
neutralMinionsKilled: requireNumber(
value.neutralMinionsKilled,
`participants[${index}].neutralMinionsKilled`,
),
participantId: requireNumber(
value.participantId,
`participants[${index}].participantId`,
),
perks: parsePerks(value.perks, index),
puuid: requireString(value.puuid, `participants[${index}].puuid`),
riotIdGameName: optionalString(
value.riotIdGameName,
`participants[${index}].riotIdGameName`,
),
riotIdTagLine: optionalString(
value.riotIdTagLine,
`participants[${index}].riotIdTagLine`,
),
summoner1Id: requireNumber(
value.summoner1Id,
`participants[${index}].summoner1Id`,
),
summoner2Id: requireNumber(
value.summoner2Id,
`participants[${index}].summoner2Id`,
),
summonerId: requireString(
value.summonerId,
`participants[${index}].summonerId`,
),
summonerLevel: requireNumber(
value.summonerLevel,
`participants[${index}].summonerLevel`,
),
summonerName: requireStringAllowEmpty(
value.summonerName,
`participants[${index}].summonerName`,
),
teamId: requireNumber(value.teamId, `participants[${index}].teamId`),
teamPosition: requireStringAllowEmpty(
value.teamPosition,
`participants[${index}].teamPosition`,
),
timePlayed: requireNumber(
value.timePlayed,
`participants[${index}].timePlayed`,
),
totalDamageDealtToChampions: requireNumber(
value.totalDamageDealtToChampions,
`participants[${index}].totalDamageDealtToChampions`,
),
totalDamageTaken: requireNumber(
value.totalDamageTaken,
`participants[${index}].totalDamageTaken`,
),
totalMinionsKilled: requireNumber(
value.totalMinionsKilled,
`participants[${index}].totalMinionsKilled`,
),
visionScore: requireNumber(
value.visionScore,
`participants[${index}].visionScore`,
),
wardsKilled: requireNumber(
value.wardsKilled,
`participants[${index}].wardsKilled`,
),
wardsPlaced: requireNumber(
value.wardsPlaced,
`participants[${index}].wardsPlaced`,
),
win: requireBoolean(value.win, `participants[${index}].win`),
};
}
function parsePerks(value: unknown, participantIndex: number): RiotMatchPerksDto {
if (!isRecord(value)) {
throw new TypeError(
`participants[${participantIndex}].perks must be an object.`,
);
}
const styles = value.styles;
if (!Array.isArray(styles)) {
throw new TypeError(
`participants[${participantIndex}].perks.styles must be an array.`,
);
}
return {
statPerks: parseStatPerks(value.statPerks, participantIndex),
styles: styles.map((style, styleIndex) =>
parsePerkStyle(style, participantIndex, styleIndex),
),
};
}
function parseStatPerks(
value: unknown,
participantIndex: number,
): RiotMatchStatPerksDto {
if (!isRecord(value)) {
throw new TypeError(
`participants[${participantIndex}].perks.statPerks must be an object.`,
);
}
return {
defense: requireNumber(
value.defense,
`participants[${participantIndex}].perks.statPerks.defense`,
),
flex: requireNumber(
value.flex,
`participants[${participantIndex}].perks.statPerks.flex`,
),
offense: requireNumber(
value.offense,
`participants[${participantIndex}].perks.statPerks.offense`,
),
};
}
function parsePerkStyle(
value: unknown,
participantIndex: number,
styleIndex: number,
): RiotMatchPerkStyleDto {
if (!isRecord(value)) {
throw new TypeError(
`participants[${participantIndex}].perks.styles[${styleIndex}] must be an object.`,
);
}
const selections = value.selections;
if (!Array.isArray(selections)) {
throw new TypeError(
`participants[${participantIndex}].perks.styles[${styleIndex}].selections must be an array.`,
);
}
return {
description: requireString(
value.description,
`participants[${participantIndex}].perks.styles[${styleIndex}].description`,
),
selections: selections.map((selection, selectionIndex) =>
parsePerkSelection(
selection,
participantIndex,
styleIndex,
selectionIndex,
),
),
style: requireNumber(
value.style,
`participants[${participantIndex}].perks.styles[${styleIndex}].style`,
),
};
}
function parsePerkSelection(
value: unknown,
participantIndex: number,
styleIndex: number,
selectionIndex: number,
): RiotMatchPerkStyleSelectionDto {
if (!isRecord(value)) {
throw new TypeError(
`participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}] must be an object.`,
);
}
return {
perk: requireNumber(
value.perk,
`participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}].perk`,
),
var1: requireNumber(
value.var1,
`participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}].var1`,
),
var2: requireNumber(
value.var2,
`participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}].var2`,
),
var3: requireNumber(
value.var3,
`participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}].var3`,
),
};
}
function parseTeam(value: unknown, index: number): RiotMatchTeamDto {
if (!isRecord(value)) {
throw new TypeError(`teams[${index}] must be an object.`);
}
const bans = value.bans;
if (!Array.isArray(bans)) {
throw new TypeError(`teams[${index}].bans must be an array.`);
}
return {
...value,
bans: bans.map((ban, banIndex) => parseBan(ban, index, banIndex)),
objectives: parseObjectives(value.objectives, index),
teamId: requireNumber(value.teamId, `teams[${index}].teamId`),
win: requireBoolean(value.win, `teams[${index}].win`),
};
}
function parseBan(
value: unknown,
teamIndex: number,
banIndex: number,
): RiotMatchBanDto {
if (!isRecord(value)) {
throw new TypeError(`teams[${teamIndex}].bans[${banIndex}] must be an object.`);
}
return {
championId: requireNumber(
value.championId,
`teams[${teamIndex}].bans[${banIndex}].championId`,
),
pickTurn: requireNumber(
value.pickTurn,
`teams[${teamIndex}].bans[${banIndex}].pickTurn`,
),
};
}
function parseObjectives(
value: unknown,
teamIndex: number,
): RiotMatchObjectivesDto {
if (!isRecord(value)) {
throw new TypeError(`teams[${teamIndex}].objectives must be an object.`);
}
return {
baron: parseObjective(value.baron, teamIndex, 'baron'),
champion: parseObjective(value.champion, teamIndex, 'champion'),
dragon: parseObjective(value.dragon, teamIndex, 'dragon'),
inhibitor: parseObjective(value.inhibitor, teamIndex, 'inhibitor'),
riftHerald: parseObjective(value.riftHerald, teamIndex, 'riftHerald'),
tower: parseObjective(value.tower, teamIndex, 'tower'),
};
}
function parseObjective(
value: unknown,
teamIndex: number,
key: keyof RiotMatchObjectivesDto,
): RiotMatchObjectiveDto {
if (!isRecord(value)) {
throw new TypeError(`teams[${teamIndex}].objectives.${key} must be an object.`);
}
return {
first: requireBoolean(
value.first,
`teams[${teamIndex}].objectives.${key}.first`,
),
kills: requireNumber(
value.kills,
`teams[${teamIndex}].objectives.${key}.kills`,
),
};
}
function requireString(value: unknown, path: string): string {
if (!isNonEmptyString(value)) {
throw new TypeError(`${path} must be a non-empty string.`);
}
return value;
}
function requireStringAllowEmpty(value: unknown, path: string): string {
if (typeof value !== 'string') {
throw new TypeError(`${path} must be a string.`);
}
return value;
}
function optionalString(value: unknown, path: string): string | undefined {
if (value === undefined || value === null) {
return undefined;
}
if (typeof value !== 'string') {
throw new TypeError(`${path} must be a string when present.`);
}
return value;
}
function requireNumber(value: unknown, path: string): number {
if (!isFiniteNumber(value)) {
throw new TypeError(`${path} must be a finite number.`);
}
return value;
}
function optionalNumber(value: unknown, path: string): number | undefined {
if (value === undefined || value === null) {
return undefined;
}
if (!isFiniteNumber(value)) {
throw new TypeError(`${path} must be a finite number when present.`);
}
return value;
}
function requireBoolean(value: unknown, path: string): boolean {
if (typeof value !== 'boolean') {
throw new TypeError(`${path} must be a boolean.`);
}
return value;
}
function assertOptionalNonNegativeInteger(
value: number | undefined,
fieldName: string,
): void {
if (value === undefined) {
return;
}
if (!Number.isInteger(value) || value < 0) {
throw new RangeError(`${fieldName} must be a non-negative integer.`);
}
}
function assertOptionalRange(
value: number | undefined,
fieldName: string,
min: number,
max: number,
): void {
if (value === undefined) {
return;
}
if (!Number.isInteger(value) || value < min || value > max) {
throw new RangeError(
`${fieldName} must be an integer between ${min} and ${max}.`,
);
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
function isFiniteNumber(value: unknown): value is number {
return typeof value === 'number' && Number.isFinite(value);
}
function isNonEmptyString(value: unknown): value is string {
return typeof value === 'string' && value.length > 0;
}
@@ -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<RiotRankFilter, number[]>;
}
export const RIOT_QUEUE_GROUPS: Record<RiotQueueGroup, RiotQueueGroupConfig> = {
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<number, string> = {
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';
}
@@ -0,0 +1,65 @@
import { GarnetService } from '../global/garnet/garnet.service';
import { RiotRateLimiterService } from './riot-rate-limiter.service';
function makeService(sendCommand = jest.fn().mockResolvedValue(0)) {
const garnet = {
raw: jest.fn().mockReturnValue({ sendCommand }),
} as unknown as GarnetService;
return {
service: new RiotRateLimiterService(garnet),
sendCommand,
};
}
describe('RiotRateLimiterService background limiter', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('uses the background key namespace and passes cost to the Lua script', async () => {
jest.spyOn(Date, 'now').mockReturnValue(1_000);
const { service, sendCommand } = makeService();
await service.acquireBackground(8);
expect(sendCommand).toHaveBeenCalledTimes(1);
const command = sendCommand.mock.calls[0][0] as string[];
expect(command[0]).toBe('EVAL');
expect(command[2]).toBe('2');
expect(command[3]).toBe('riot:bg:rl:1000');
expect(command[4]).toBe('riot:bg:rl:120000');
expect(command[5]).toBe('1000');
expect(command[7]).toBe('8');
});
it('reads cleaned background usage for both windows', async () => {
jest.spyOn(Date, 'now').mockReturnValue(200_000);
const sendCommand = jest
.fn()
.mockImplementation(async (command: string[]) => {
if (command[0] === 'ZREMRANGEBYSCORE') return 0;
if (command[1] === 'riot:bg:rl:1000') return 3;
if (command[1] === 'riot:bg:rl:120000') return 24;
return 0;
});
const { service } = makeService(sendCommand);
await expect(service.getBackgroundUsage()).resolves.toEqual({
used1s: 3,
used2m: 24,
});
expect(sendCommand).toHaveBeenCalledWith([
'ZREMRANGEBYSCORE',
'riot:bg:rl:1000',
'-inf',
'199000',
]);
expect(sendCommand).toHaveBeenCalledWith([
'ZREMRANGEBYSCORE',
'riot:bg:rl:120000',
'-inf',
'80000',
]);
});
});
@@ -0,0 +1,199 @@
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 BACKGROUND_LIMITS = [
{ windowMs: 1_000, max: 6 },
{ windowMs: 120_000, max: 36 },
] as const;
const BACKGROUND_KEY_PREFIX = 'riot:bg:rl';
const ACQUIRE_SCRIPT = `
local now = tonumber(ARGV[1])
local memberBase = ARGV[2]
local cost = tonumber(ARGV[3])
if cost == nil or cost < 1 then
cost = 1
end
local maxWait = 0
local effectiveCosts = {}
for i = 1, #KEYS do
local argIndex = 4 + ((i - 1) * 2)
local windowMs = tonumber(ARGV[argIndex])
local limit = tonumber(ARGV[argIndex + 1])
local key = KEYS[i]
local effectiveCost = cost
if effectiveCost > limit then
effectiveCost = limit
end
effectiveCosts[i] = effectiveCost
redis.call('ZREMRANGEBYSCORE', key, '-inf', now - windowMs)
local count = redis.call('ZCARD', key)
local overflow = count + effectiveCost - limit
if overflow > 0 then
local oldest = redis.call(
'ZRANGE',
key,
overflow - 1,
overflow - 1,
'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 = 4 + ((i - 1) * 2)
local windowMs = tonumber(ARGV[argIndex])
local key = KEYS[i]
local effectiveCost = effectiveCosts[i] or cost
for c = 1, effectiveCost do
redis.call('ZADD', key, now, memberBase .. ':' .. i .. ':' .. c)
end
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<void> {
for (;;) {
const now = Date.now();
const waitMs = await this.checkAndAdd(route, now, 1);
if (waitMs <= 0) return;
if (waitMs >= 100) {
this.logger.warn(
`Riot API throttle waiting ${waitMs}ms for route=${route}.`,
);
}
await sleep(waitMs);
}
}
public async acquireBackground(cost = 1): Promise<void> {
const normalizedCost = normalizeCost(cost);
for (;;) {
const now = Date.now();
const waitMs = await this.checkAndAddBackground(now, normalizedCost);
if (waitMs <= 0) return;
if (waitMs >= 100) {
this.logger.warn(
`Background Riot throttle waiting ${waitMs}ms (cost=${normalizedCost}).`,
);
}
await sleep(waitMs);
}
}
public async getBackgroundUsage(): Promise<{
used1s: number;
used2m: number;
}> {
const client = this.garnet.raw();
const now = Date.now();
const usages = await Promise.all(
BACKGROUND_LIMITS.map(async (limit) => {
const key = `${BACKGROUND_KEY_PREFIX}:${limit.windowMs}`;
await client.sendCommand([
'ZREMRANGEBYSCORE',
key,
'-inf',
String(now - limit.windowMs),
]);
const response = await client.sendCommand(['ZCARD', key]);
const count = Number(response ?? 0);
return Number.isFinite(count) && count > 0 ? count : 0;
}),
);
return {
used1s: usages[0] ?? 0,
used2m: usages[1] ?? 0,
};
}
private async checkAndAdd(
route: RiotRegionalRoute | RiotPlatformRoute,
now: number,
cost: number,
): Promise<number> {
const keys = APP_LIMITS.map(
(limit) => `riot:rl:${route}:${limit.windowMs}`,
);
return this.checkAndAddWithLimits(keys, APP_LIMITS, now, cost);
}
private async checkAndAddBackground(
now: number,
cost: number,
): Promise<number> {
const keys = BACKGROUND_LIMITS.map(
(limit) => `${BACKGROUND_KEY_PREFIX}:${limit.windowMs}`,
);
return this.checkAndAddWithLimits(keys, BACKGROUND_LIMITS, now, cost);
}
private async checkAndAddWithLimits(
keys: string[],
limits: ReadonlyArray<{ windowMs: number; max: number }>,
now: number,
cost: number,
): Promise<number> {
const client = this.garnet.raw();
const member = `${process.pid}:${now}:${Math.random().toString(36).slice(2)}`;
const argumentsList = [
String(now),
member,
String(normalizeCost(cost)),
...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 normalizeCost(cost: number): number {
if (!Number.isFinite(cost)) return 1;
return Math.max(1, Math.floor(cost));
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
@@ -0,0 +1,161 @@
import { Injectable, Logger } from '@nestjs/common';
import type {
RiotMatchDocument,
RiotMatch as StoredRiotMatch,
} from '../global/database/schema';
import { ConnectionService } from '../global/database/connection.service';
import { GarnetService } from '../global/garnet/garnet.service';
import type { RiotRegionalRoute } from './riot.types';
import { RiotMatchService } from './riot-match.service';
export const RIOT_RECENT_MATCH_LIMIT = 20;
export const RIOT_SOLO_QUEUE_ID = 420;
const MATCH_ENRICHMENT_LOCK_TTL_SECONDS = 60;
const MATCH_DETAIL_CONCURRENCY = 2;
const DEFAULT_REGION: RiotRegionalRoute = 'asia';
@Injectable()
export class RiotRecentMatchesService {
private readonly logger = new Logger(RiotRecentMatchesService.name);
constructor(
private readonly connectionService: ConnectionService,
private readonly matchService: RiotMatchService,
private readonly garnetService: GarnetService,
) {}
public async syncRecentMatches(params: {
puuid: string;
region?: RiotRegionalRoute;
limit?: number;
queueId?: number;
}): Promise<RiotMatchDocument[]> {
const region = params.region ?? DEFAULT_REGION;
const limit = params.limit ?? RIOT_RECENT_MATCH_LIMIT;
const queueId = params.queueId ?? RIOT_SOLO_QUEUE_ID;
const lockKey = `riot:enrich:matches:${params.puuid}`;
const lockValue = `${process.pid}:${Date.now()}`;
const acquired = await this.garnetService.setStringIfAbsent(
lockKey,
lockValue,
MATCH_ENRICHMENT_LOCK_TTL_SECONDS,
);
if (!acquired) {
return this.loadFromDb({ puuid: params.puuid, limit, queueId });
}
try {
const matchIds = await this.matchService.getMatchIdsByPuuid(params.puuid, {
region,
queue: queueId,
count: limit,
});
if (matchIds.length === 0) {
return this.loadFromDb({ puuid: params.puuid, limit, queueId });
}
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const existingMatches = await RiotMatchModel.find({
matchId: { $in: matchIds },
})
.select({ matchId: 1 })
.lean()
.exec();
const existingMatchIds = new Set(existingMatches.map((match) => match.matchId));
const missingMatchIds = matchIds.filter((matchId) => !existingMatchIds.has(matchId));
await runWithConcurrency(missingMatchIds, MATCH_DETAIL_CONCURRENCY, async (matchId) => {
try {
const dto = await this.matchService.getMatch(matchId, { region });
if (dto.info.queueId !== queueId) {
this.logger.warn(
`Skipping unexpected queue ${dto.info.queueId} for ${matchId} while syncing ${params.puuid}.`,
);
return;
}
const payload: Partial<StoredRiotMatch> = {
matchId: dto.metadata.matchId,
gameCreation: dto.info.gameCreation,
gameDuration: dto.info.gameDuration,
gameVersion: dto.info.gameVersion,
queueId: dto.info.queueId,
participantPuuids: dto.metadata.participants,
raw: dto as unknown as Record<string, unknown>,
fetchedAt: new Date(),
};
await RiotMatchModel.updateOne(
{ matchId: dto.metadata.matchId },
{ $setOnInsert: payload },
{ upsert: true },
).exec();
} catch (error: unknown) {
this.logger.warn(
`Skipping Riot match ${matchId} while syncing ${params.puuid}: ${
error instanceof Error ? error.message : error
}`,
);
}
});
return this.loadFromDb({ puuid: params.puuid, limit, queueId });
} finally {
await this.garnetService.delete(lockKey).catch((error: unknown) => {
this.logger.warn(
`Failed to release recent matches lock for ${params.puuid}: ${
(error as Error)?.message ?? error
}`,
);
});
}
}
public async ensureFreshForQueue(params: {
puuid: string;
region?: RiotRegionalRoute;
queueId: number;
limit?: number;
}): Promise<RiotMatchDocument[]> {
return this.syncRecentMatches(params);
}
public async loadFromDb(params: {
puuid: string;
limit?: number;
queueId?: number;
}): Promise<RiotMatchDocument[]> {
const limit = params.limit ?? RIOT_RECENT_MATCH_LIMIT;
const queueId = params.queueId ?? RIOT_SOLO_QUEUE_ID;
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
return RiotMatchModel.find({
participantPuuids: params.puuid,
queueId,
})
.sort({ gameCreation: -1 })
.limit(limit)
.exec();
}
}
async function runWithConcurrency<T>(
items: T[],
concurrency: number,
worker: (item: T) => Promise<void>,
): Promise<void> {
if (items.length === 0) return;
const queue = [...items];
const runners = Array.from({ length: Math.min(concurrency, queue.length) }, async () => {
while (queue.length > 0) {
const item = queue.shift();
if (item === undefined) return;
await worker(item);
}
});
await Promise.all(runners);
}
@@ -0,0 +1,304 @@
import { RiotRecentStatsService } from './riot-recent-stats.service';
import type { RiotMatchDto } from './riot.types';
function makeMatch(params: {
matchId: string;
gameCreation: number;
gameDuration: number;
puuid: string;
championId: number;
kills: number;
deaths: number;
assists: number;
cs: number;
neutralCs?: number;
win?: boolean;
teamPosition?: string;
individualPosition?: string;
}): RiotMatchDto {
return {
metadata: {
dataVersion: '2',
matchId: params.matchId,
participants: [params.puuid, 'other-1'],
},
info: {
gameCreation: params.gameCreation,
gameDuration: params.gameDuration,
gameId: 1,
gameMode: 'CLASSIC',
gameName: 'teambuilder-match-1',
gameStartTimestamp: params.gameCreation,
gameType: 'MATCHED_GAME',
gameVersion: '15.8.1',
mapId: 11,
platformId: 'KR',
queueId: 420,
participants: [
{
assists: params.assists,
champExperience: 10000,
champLevel: 16,
championId: params.championId,
championName: `Champion-${params.championId}`,
deaths: params.deaths,
goldEarned: 12000,
goldSpent: 11000,
individualPosition: params.individualPosition ?? '',
item0: 0,
item1: 0,
item2: 0,
item3: 0,
item4: 0,
item5: 0,
item6: 0,
kills: params.kills,
neutralMinionsKilled: params.neutralCs ?? 0,
participantId: 1,
perks: {
statPerks: { defense: 0, flex: 0, offense: 0 },
styles: [],
},
puuid: params.puuid,
riotIdGameName: 'tester',
riotIdTagLine: 'KR1',
summoner1Id: 4,
summoner2Id: 14,
summonerId: 'summoner-1',
summonerLevel: 100,
summonerName: 'tester',
teamId: 100,
teamPosition: params.teamPosition ?? '',
timePlayed: params.gameDuration,
totalDamageDealtToChampions: 10000,
totalDamageTaken: 5000,
totalMinionsKilled: params.cs,
visionScore: 20,
wardsKilled: 2,
wardsPlaced: 10,
win: params.win ?? true,
},
{
assists: 1,
champExperience: 9000,
champLevel: 15,
championId: 1,
championName: 'Other',
deaths: 5,
goldEarned: 10000,
goldSpent: 9000,
individualPosition: 'TOP',
item0: 0,
item1: 0,
item2: 0,
item3: 0,
item4: 0,
item5: 0,
item6: 0,
kills: 3,
neutralMinionsKilled: 0,
participantId: 2,
perks: {
statPerks: { defense: 0, flex: 0, offense: 0 },
styles: [],
},
puuid: 'other-1',
riotIdGameName: 'other',
riotIdTagLine: 'KR1',
summoner1Id: 4,
summoner2Id: 14,
summonerId: 'summoner-2',
summonerLevel: 90,
summonerName: 'other',
teamId: 100,
teamPosition: 'TOP',
timePlayed: params.gameDuration,
totalDamageDealtToChampions: 8000,
totalDamageTaken: 7000,
totalMinionsKilled: 180,
visionScore: 10,
wardsKilled: 1,
wardsPlaced: 5,
win: false,
},
],
teams: [
{
bans: [],
objectives: {
baron: { first: false, kills: 0 },
champion: { first: false, kills: 0 },
dragon: { first: false, kills: 0 },
inhibitor: { first: false, kills: 0 },
riftHerald: { first: false, kills: 0 },
tower: { first: false, kills: 0 },
},
teamId: 100,
win: params.win ?? true,
},
{
bans: [],
objectives: {
baron: { first: false, kills: 0 },
champion: { first: false, kills: 0 },
dragon: { first: false, kills: 0 },
inhibitor: { first: false, kills: 0 },
riftHerald: { first: false, kills: 0 },
tower: { first: false, kills: 0 },
},
teamId: 200,
win: !(params.win ?? true),
},
],
},
};
}
describe('RiotRecentStatsService', () => {
const service = new RiotRecentStatsService();
it('computes overall and lane summaries for recent solo queue matches', () => {
const matches = [
makeMatch({
matchId: 'KR_1',
gameCreation: 1_000,
gameDuration: 1800,
puuid: 'puuid-1',
championId: 103,
kills: 8,
deaths: 2,
assists: 6,
cs: 180,
win: true,
teamPosition: 'MIDDLE',
}),
makeMatch({
matchId: 'KR_2',
gameCreation: 2_000,
gameDuration: 1500,
puuid: 'puuid-1',
championId: 103,
kills: 4,
deaths: 1,
assists: 8,
cs: 150,
neutralCs: 20,
win: false,
teamPosition: 'MIDDLE',
}),
makeMatch({
matchId: 'KR_3',
gameCreation: 3_000,
gameDuration: 1800,
puuid: 'puuid-1',
championId: 22,
kills: 10,
deaths: 0,
assists: 5,
cs: 210,
win: true,
teamPosition: '',
individualPosition: 'BOTTOM',
}),
];
const summary = service.computeSummary(matches, 'puuid-1');
expect(summary.overall).toEqual({
games: 3,
wins: 2,
losses: 1,
avgKills: 7.3,
avgDeaths: 1,
avgAssists: 6.3,
avgCs: 186.7,
avgCsPerMin: 6.6,
mostPlayedChampionIds: [103, 22],
});
expect(summary.byLane.MIDDLE).toEqual({
games: 2,
wins: 1,
losses: 1,
avgKills: 6,
avgDeaths: 1.5,
avgAssists: 7,
avgCs: 175,
avgCsPerMin: 6.4,
mostPlayedChampionIds: [103],
});
expect(summary.byLane.BOTTOM).toEqual({
games: 1,
wins: 1,
losses: 0,
avgKills: 10,
avgDeaths: 0,
avgAssists: 5,
avgCs: 210,
avgCsPerMin: 7,
mostPlayedChampionIds: [22],
});
});
it('skips invalid lane positions from byLane while keeping overall stats', () => {
const summary = service.computeSummary(
[
makeMatch({
matchId: 'KR_4',
gameCreation: 4_000,
gameDuration: 1800,
puuid: 'puuid-1',
championId: 61,
kills: 6,
deaths: 3,
assists: 9,
cs: 190,
win: true,
teamPosition: 'Invalid',
individualPosition: '',
}),
],
'puuid-1',
);
expect(summary.overall.games).toBe(1);
expect(summary.byLane).toEqual({});
});
it('filters out matches before seasonStartedAt', () => {
const summary = service.computeSummary(
[
makeMatch({
matchId: 'KR_5',
gameCreation: 1_000,
gameDuration: 1800,
puuid: 'puuid-1',
championId: 61,
kills: 6,
deaths: 3,
assists: 9,
cs: 190,
win: true,
teamPosition: 'MIDDLE',
}),
makeMatch({
matchId: 'KR_6',
gameCreation: 10_000,
gameDuration: 1800,
puuid: 'puuid-1',
championId: 134,
kills: 9,
deaths: 2,
assists: 7,
cs: 205,
win: true,
teamPosition: 'MIDDLE',
}),
],
'puuid-1',
{ seasonStartedAt: new Date(5_000) },
);
expect(summary.overall.games).toBe(1);
expect(summary.overall.mostPlayedChampionIds).toEqual([134]);
});
});
@@ -0,0 +1,172 @@
import { Injectable } from '@nestjs/common';
import {
createEmptyRiotLaneStats,
createEmptyRiotRecentStatsSummary,
RIOT_LANES,
type RiotLane,
type RiotLaneStats,
type RiotRecentStatsSummary,
} from '../global/database/schema';
import type { RiotMatchDto, RiotMatchParticipantDto } from './riot.types';
interface Aggregate {
games: number;
wins: number;
losses: number;
kills: number;
deaths: number;
assists: number;
cs: number;
csPerMin: number;
championCounts: Map<number, number>;
lastPlayedAtByChampion: Map<number, number>;
}
interface ComputeSummaryOptions {
seasonStartedAt?: Date;
}
@Injectable()
export class RiotRecentStatsService {
public computeSummary(
matches: RiotMatchDto[],
puuid: string,
options: ComputeSummaryOptions = {},
): RiotRecentStatsSummary {
const filteredMatches = this.filterMatchesBySeason(matches, options);
if (filteredMatches.length === 0) {
return createEmptyRiotRecentStatsSummary();
}
const overall = createAggregate();
const laneAggregates = new Map<RiotLane, Aggregate>(
RIOT_LANES.map((lane) => [lane, createAggregate()]),
);
for (const match of filteredMatches) {
const participant = match.info.participants.find((entry) => entry.puuid === puuid);
if (!participant) continue;
accumulateAggregate(overall, participant, match.info.gameCreation, match.info.gameDuration);
const lane = resolveLane(participant);
if (!lane) continue;
const aggregate = laneAggregates.get(lane);
if (!aggregate) continue;
accumulateAggregate(aggregate, participant, match.info.gameCreation, match.info.gameDuration);
}
if (overall.games === 0) {
return createEmptyRiotRecentStatsSummary();
}
const byLane: Partial<Record<RiotLane, RiotLaneStats>> = {};
for (const lane of RIOT_LANES) {
const aggregate = laneAggregates.get(lane);
if (!aggregate || aggregate.games === 0) continue;
byLane[lane] = finalizeAggregate(aggregate);
}
return {
overall: finalizeAggregate(overall),
byLane,
};
}
private filterMatchesBySeason(
matches: RiotMatchDto[],
options: ComputeSummaryOptions,
): RiotMatchDto[] {
const startedAt = options.seasonStartedAt?.getTime();
if (!startedAt) return matches;
return matches.filter((match) => match.info.gameCreation >= startedAt);
}
}
function createAggregate(): Aggregate {
return {
games: 0,
wins: 0,
losses: 0,
kills: 0,
deaths: 0,
assists: 0,
cs: 0,
csPerMin: 0,
championCounts: new Map(),
lastPlayedAtByChampion: new Map(),
};
}
function accumulateAggregate(
aggregate: Aggregate,
participant: RiotMatchParticipantDto,
gameCreation: number,
gameDurationSeconds: number,
): void {
aggregate.games += 1;
aggregate.wins += participant.win ? 1 : 0;
aggregate.losses += participant.win ? 0 : 1;
aggregate.kills += participant.kills;
aggregate.deaths += participant.deaths;
aggregate.assists += participant.assists;
const cs = participant.totalMinionsKilled + participant.neutralMinionsKilled;
aggregate.cs += cs;
if (gameDurationSeconds > 0) {
aggregate.csPerMin += cs / (gameDurationSeconds / 60);
}
aggregate.championCounts.set(
participant.championId,
(aggregate.championCounts.get(participant.championId) ?? 0) + 1,
);
aggregate.lastPlayedAtByChampion.set(participant.championId, gameCreation);
}
function finalizeAggregate(aggregate: Aggregate): RiotLaneStats {
if (aggregate.games === 0) {
return createEmptyRiotLaneStats();
}
const mostPlayedChampionIds = [...aggregate.championCounts.entries()]
.sort((left, right) => {
if (right[1] !== left[1]) return right[1] - left[1];
const rightLastPlayed = aggregate.lastPlayedAtByChampion.get(right[0]) ?? 0;
const leftLastPlayed = aggregate.lastPlayedAtByChampion.get(left[0]) ?? 0;
if (rightLastPlayed !== leftLastPlayed) {
return rightLastPlayed - leftLastPlayed;
}
return left[0] - right[0];
})
.slice(0, 3)
.map(([championId]) => championId);
return {
games: aggregate.games,
wins: aggregate.wins,
losses: aggregate.losses,
avgKills: roundToOneDecimal(aggregate.kills / aggregate.games),
avgDeaths: roundToOneDecimal(aggregate.deaths / aggregate.games),
avgAssists: roundToOneDecimal(aggregate.assists / aggregate.games),
avgCs: roundToOneDecimal(aggregate.cs / aggregate.games),
avgCsPerMin: roundToOneDecimal(aggregate.csPerMin / aggregate.games),
mostPlayedChampionIds,
};
}
function resolveLane(participant: RiotMatchParticipantDto): RiotLane | null {
const candidates = [participant.teamPosition, participant.individualPosition];
for (const candidate of candidates) {
if (!candidate) continue;
if (RIOT_LANES.includes(candidate as RiotLane)) {
return candidate as RiotLane;
}
}
return null;
}
function roundToOneDecimal(value: number): number {
return Math.round(value * 10) / 10;
}
@@ -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<RiotSummonerDto> {
return this.riotClientService.get<RiotSummonerDto>(
`/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<string, unknown> {
return typeof value === 'object' && value !== null;
}
@@ -0,0 +1,60 @@
import type { Request } from 'express';
import { RiotWebhookController } from './riot-webhook.controller';
type RiotWebhookRequest = Request & {
rawBody?: Buffer;
};
describe('RiotWebhookController', () => {
let controller: RiotWebhookController;
beforeEach(() => {
controller = new RiotWebhookController();
});
afterEach(() => {
jest.restoreAllMocks();
});
it('logs the incoming webhook payload and returns an acknowledgement', () => {
const logSpy = jest.spyOn(console, 'log').mockImplementation(() => undefined);
const dirSpy = jest.spyOn(console, 'dir').mockImplementation(() => undefined);
const request = {
method: 'POST',
originalUrl: '/riot/webhooks/tournament',
protocol: 'https',
hostname: 'example.test',
ip: '127.0.0.1',
ips: ['127.0.0.1'],
headers: {
'content-type': 'application/json',
},
query: {
shard: 'kr',
},
params: {},
body: {
eventType: 'MATCH_FINISHED',
},
rawBody: Buffer.from('{"eventType":"MATCH_FINISHED"}', 'utf8'),
} as unknown as RiotWebhookRequest;
const response = controller.captureTournamentWebhook(request);
expect(response.ok).toBe(true);
expect(response.message).toBe('Riot webhook received.');
expect(response.receivedAt).toEqual(expect.any(String));
expect(logSpy).toHaveBeenCalledTimes(2);
expect(dirSpy).toHaveBeenCalledWith(
expect.objectContaining({
method: 'POST',
url: '/riot/webhooks/tournament',
body: {
eventType: 'MATCH_FINISHED',
},
rawBodyText: '{"eventType":"MATCH_FINISHED"}',
}),
{ depth: null },
);
});
});
@@ -0,0 +1,49 @@
import {
All,
Controller,
HttpCode,
HttpStatus,
Req,
} from '@nestjs/common';
import type { Request } from 'express';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
type RiotWebhookRequest = Request & {
rawBody?: Buffer;
};
@Controller('riot')
export class RiotWebhookController {
@All('webhooks/tournament')
@AllowPublicAccess()
@HttpCode(HttpStatus.OK)
public captureTournamentWebhook(@Req() req: RiotWebhookRequest) {
const receivedAt = new Date().toISOString();
const rawBodyText = req.rawBody?.toString('utf8') ?? null;
const logPayload = {
receivedAt,
method: req.method,
url: req.originalUrl,
protocol: req.protocol,
hostname: req.hostname,
ip: req.ip,
ips: req.ips,
headers: req.headers,
query: req.query,
params: req.params,
body: req.body,
rawBodyLength: req.rawBody?.length ?? null,
rawBodyText,
};
console.log('\n[RIOT TOURNAMENT WEBHOOK] Incoming request');
console.dir(logPayload, { depth: null });
console.log('[RIOT TOURNAMENT WEBHOOK] End request log\n');
return {
ok: true,
message: 'Riot webhook received.',
receivedAt,
};
}
}
@@ -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<RiotRegionalRoute, string> = {
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<RiotPlatformRoute, string> = {
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<T>(
path: string,
options: RiotRequestOptions = {},
parser?: RiotResponseParser<T>,
): Promise<T> {
const apiKey = await this.secretService.get<string>('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<RiotApiError> {
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<T>(
url: string,
apiKey: string,
signal: AbortSignal | undefined,
parser: RiotResponseParser<T> | undefined,
routeKey: RiotRegionalRoute | RiotPlatformRoute,
attempt = 0,
): Promise<T> {
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<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
+47
View File
@@ -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 {}
+251
View File
@@ -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<string, string | number | boolean | undefined>;
signal?: AbortSignal;
}
export type RiotResponseParser<T> = (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<string, unknown>;
}
// Champion-Mastery-V4 by-puuid 응답
export interface RiotChampionMasteryDto extends Record<string, unknown> {
puuid: string;
championId: number;
championLevel: number;
championPoints: number;
lastPlayTime?: number;
championPointsSinceLastLevel?: number;
championPointsUntilNextLevel?: number;
markRequiredForNextLevel?: number;
tokensEarned?: number;
championSeasonMilestone?: number;
milestoneGrades?: string[];
nextSeasonMilestone?: Record<string, unknown>;
}
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<string, unknown> {
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<string, unknown> {
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<string, unknown> {
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;
}