This commit is contained in:
dahyeon committed 2026-04-26 03:33:24 -07:00
1 parent 6d62de4ec4
commit 285f72b3ee
16 files changed
+2095 -136

No files matched your search

@@ -1,9 +1,11 @@
import { Module } from '@nestjs/common';
import { RiotModule } from '../riot/riot.module';
import { AuctionGateway } from './auction.gateway';
import { AuctionController } from './auction.controller';
import { AuctionService } from './auction.service';
@Module({
imports: [RiotModule],
controllers: [AuctionController],
providers: [AuctionService, AuctionGateway],
exports: [AuctionService],
@@ -12,6 +12,7 @@ import {
Position,
TeamSide,
} from '../global/database/schema';
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
interface StartAuctionParams {
matchId: mongoose.Types.ObjectId;
@@ -35,12 +36,16 @@ interface MarkSoldParams {
@Injectable()
export class AuctionService {
constructor(private readonly connectionService: ConnectionService) {}
constructor(
private readonly connectionService: ConnectionService,
private readonly enrichmentService: RiotAccountEnrichmentService,
) {}
public async start(params: StartAuctionParams): Promise<AuctionDocument> {
const MatchModel = await this.connectionService.getModel('match');
const UserModel = await this.connectionService.getModel('user');
const AuctionModel = await this.connectionService.getModel('auction');
const CommunityModel = await this.connectionService.getModel('community');
const match = await MatchModel.findById(params.matchId);
if (!match) throw new NotFoundException('Match not found.');
@@ -66,16 +71,48 @@ export class AuctionService {
);
}
const nonCaptainPuuids = new Set<string>();
const playerUsers = await UserModel.find({
const basePlayerUsers = await UserModel.find({
_id: {
$in: match.participants
.filter((p) => !captainUserIds.some((cid) => cid.equals(p.userId)))
.map((p) => p.userId),
},
});
const community = await CommunityModel.findById(match.communityId)
.select({ riotPlatform: 1, riotRegion: 1 })
.lean()
.exec();
const platform = community?.riotPlatform ?? 'kr';
const region = community?.riotRegion ?? 'asia';
const enrichTargets = basePlayerUsers
.map((user) => ({
userId: user._id,
puuid: (user.riotAccounts.find((account) => account.isPrimary) ?? user.riotAccounts[0])
?.puuid,
}))
.filter((target): target is { userId: mongoose.Types.ObjectId; puuid: string } =>
typeof target.puuid === 'string' && target.puuid.length > 0,
);
await runWithConcurrency(enrichTargets, 3, async (target) => {
await this.enrichmentService.enrichRiotAccount({
userId: target.userId,
puuid: target.puuid,
options: {
force: false,
platform,
region,
},
});
});
const playerUsers = await UserModel.find({
_id: { $in: basePlayerUsers.map((user) => user._id) },
});
const userById = new Map(playerUsers.map((u) => [u._id.toString(), u]));
const nonCaptainPuuids = new Set<string>();
const order: AuctionPlayerSnapshot[] = [];
for (const participant of match.participants) {
if (captainUserIds.some((cid) => cid.equals(participant.userId))) {
@@ -290,3 +327,22 @@ export class AuctionService {
return Math.max(5, remainingSeconds);
}
}
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.allSettled(runners);
}
+72 -7
View File
@@ -8,6 +8,15 @@ import { ModelDefinition } from './types';
export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
export const POSITIONS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY';
export const RIOT_LANES: RiotLane[] = [
'TOP',
'JUNGLE',
'MIDDLE',
'BOTTOM',
'UTILITY',
];
export type MatchStatus =
| 'recruiting'
| 'team-built'
@@ -112,7 +121,7 @@ export interface ChampionMasteryEntry {
nextSeasonMilestone?: Record<string, unknown>;
}
export interface RiotRecentStatsSummary {
export interface RiotLaneStats {
games: number;
wins: number;
losses: number;
@@ -120,9 +129,34 @@ export interface RiotRecentStatsSummary {
avgDeaths: number;
avgAssists: number;
avgCs: number;
mostPlayedChampionIds: string[];
// 필드 추가가 잦을 수 있어 확장용 추가 메트릭 영역 허용
extras?: Record<string, unknown>;
avgCsPerMin: number;
mostPlayedChampionIds: number[];
}
export interface RiotRecentStatsSummary {
overall: RiotLaneStats;
byLane: Partial<Record<RiotLane, RiotLaneStats>>;
}
export function createEmptyRiotLaneStats(): RiotLaneStats {
return {
games: 0,
wins: 0,
losses: 0,
avgKills: 0,
avgDeaths: 0,
avgAssists: 0,
avgCs: 0,
avgCsPerMin: 0,
mostPlayedChampionIds: [],
};
}
export function createEmptyRiotRecentStatsSummary(): RiotRecentStatsSummary {
return {
overall: createEmptyRiotLaneStats(),
byLane: {},
};
}
export interface RiotAccount extends MongooseTimestamps {
@@ -177,6 +211,7 @@ export interface Community extends MongooseTimestamps {
dakaoProjectId?: mongoose.Types.ObjectId;
riotPlatform?: RiotPlatformRoute;
riotRegion?: RiotRegionalRoute;
seasonStartedAt?: Date;
}
export type CommunityDocument = HydratedDocument<Community>;
@@ -370,7 +405,7 @@ const ChampionMasteryEntrySubSchema = new Schema<ChampionMasteryEntry>(
{ _id: false },
);
const RiotRecentStatsSummarySubSchema = new Schema<RiotRecentStatsSummary>(
const RiotLaneStatsSubSchema = new Schema<RiotLaneStats>(
{
games: { type: Number, required: true, default: 0 },
wins: { type: Number, required: true, default: 0 },
@@ -379,8 +414,37 @@ const RiotRecentStatsSummarySubSchema = new Schema<RiotRecentStatsSummary>(
avgDeaths: { type: Number, required: true, default: 0 },
avgAssists: { type: Number, required: true, default: 0 },
avgCs: { type: Number, required: true, default: 0 },
mostPlayedChampionIds: { type: [String], required: true, default: [] },
extras: { type: Schema.Types.Mixed, required: false, default: {} },
avgCsPerMin: { type: Number, required: true, default: 0 },
mostPlayedChampionIds: { type: [Number], required: true, default: [] },
},
{ _id: false },
);
const RiotRecentStatsByLaneSubSchema = new Schema<
Partial<Record<RiotLane, RiotLaneStats>>
>(
{
TOP: { type: RiotLaneStatsSubSchema, required: false },
JUNGLE: { type: RiotLaneStatsSubSchema, required: false },
MIDDLE: { type: RiotLaneStatsSubSchema, required: false },
BOTTOM: { type: RiotLaneStatsSubSchema, required: false },
UTILITY: { type: RiotLaneStatsSubSchema, required: false },
},
{ _id: false },
);
const RiotRecentStatsSummarySubSchema = new Schema<RiotRecentStatsSummary>(
{
overall: {
type: RiotLaneStatsSubSchema,
required: true,
default: createEmptyRiotLaneStats,
},
byLane: {
type: RiotRecentStatsByLaneSubSchema,
required: true,
default: () => ({}),
},
},
{ _id: false },
);
@@ -453,6 +517,7 @@ export const CommunitySchema = new Schema<Community>(
dakaoProjectId: { type: Schema.Types.ObjectId },
riotPlatform: { type: String },
riotRegion: { type: String },
seasonStartedAt: { type: Date },
},
{
timestamps: true,
@@ -1,10 +1,16 @@
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 {
@@ -12,6 +18,10 @@ interface FakeAccount {
profileIconId: number;
revisionDate: number;
summonerLevel: number;
matchIds: string[];
matchIdsFetchedAt?: Date;
recentStatsSummary?: RiotRecentStatsSummary;
recentStatsFetchedAt?: Date;
tiers: Array<{
leagueId: string;
queueType: string;
@@ -49,6 +59,7 @@ function makeAccount(overrides: Partial<FakeAccount> = {}): FakeAccount {
profileIconId: 0,
revisionDate: 0,
summonerLevel: 0,
matchIds: [],
tiers: [],
tierHistory: [],
championMasteries: [],
@@ -73,13 +84,34 @@ function makeService(overrides?: {
summoner?: Partial<RiotSummonerService>;
league?: Partial<RiotLeagueService>;
mastery?: Partial<RiotChampionMasteryService>;
recentMatches?: Partial<RiotRecentMatchesService>;
recentStats?: Partial<RiotRecentStatsService>;
}) {
const user = overrides?.user;
const findById = jest.fn().mockReturnValue({
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().mockResolvedValue({ findById }),
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 = {
@@ -98,6 +130,17 @@ function makeService(overrides?: {
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,
@@ -105,6 +148,8 @@ function makeService(overrides?: {
summonerService,
leagueService,
masteryService,
recentMatchesService,
recentStatsService,
);
return {
service,
@@ -113,6 +158,8 @@ function makeService(overrides?: {
summonerService,
leagueService,
masteryService,
recentMatchesService,
recentStatsService,
};
}
@@ -124,13 +171,21 @@ describe('RiotAccountEnrichmentService', () => {
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 } =
const {
service,
summonerService,
leagueService,
masteryService,
recentMatchesService,
recentStatsService,
} =
makeService({
user,
summoner: {
@@ -165,6 +220,29 @@ describe('RiotAccountEnrichmentService', () => {
},
]),
} 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({
@@ -176,8 +254,23 @@ describe('RiotAccountEnrichmentService', () => {
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',
@@ -216,6 +309,12 @@ describe('RiotAccountEnrichmentService', () => {
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 () => {
@@ -238,6 +337,8 @@ describe('RiotAccountEnrichmentService', () => {
},
],
championMasteriesFetchedAt: recent,
recentStatsFetchedAt: recent,
recentStatsSummary: createEmptyRiotRecentStatsSummary(),
});
const user = makeUser(account);
const summoner = jest.fn();
@@ -262,6 +363,7 @@ describe('RiotAccountEnrichmentService', () => {
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();
@@ -292,6 +394,7 @@ describe('RiotAccountEnrichmentService', () => {
expect(result.summoner).toBe('failed');
expect(result.league).toBe('updated');
expect(result.masteries).toBe('updated');
expect(result.recentMatches).toBe('updated');
expect(user.save).toHaveBeenCalled();
});
@@ -5,16 +5,21 @@ import {
ChampionMasteryEntry,
RiotAccount,
TierInfo,
UserDocument,
} 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,
@@ -27,6 +32,7 @@ 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;
@@ -35,12 +41,14 @@ export interface EnrichOptions {
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;
}
@@ -55,6 +63,8 @@ export class RiotAccountEnrichmentService {
private readonly summonerService: RiotSummonerService,
private readonly leagueService: RiotLeagueService,
private readonly masteryService: RiotChampionMasteryService,
private readonly recentMatchesService: RiotRecentMatchesService,
private readonly recentStatsService: RiotRecentStatsService,
) {}
public async enrichRiotAccount(params: {
@@ -85,6 +95,7 @@ export class RiotAccountEnrichmentService {
summoner: 'failed',
league: 'failed',
masteries: 'failed',
recentMatches: 'failed',
account: null,
};
}
@@ -94,19 +105,35 @@ export class RiotAccountEnrichmentService {
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 ?? DEFAULT_PLATFORM;
const region = opts.region ?? DEFAULT_REGION;
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 ||
@@ -120,20 +147,34 @@ export class RiotAccountEnrichmentService {
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] = await Promise.all([
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);
@@ -144,11 +185,23 @@ export class RiotAccountEnrichmentService {
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'
masteryOutcome.status === 'updated' ||
recentMatchesOutcome.status === 'updated'
) {
await user.save();
}
@@ -157,6 +210,7 @@ export class RiotAccountEnrichmentService {
summoner: summonerOutcome.status,
league: leagueOutcome.status,
masteries: masteryOutcome.status,
recentMatches: recentMatchesOutcome.status,
account,
};
}
@@ -248,6 +302,48 @@ export class RiotAccountEnrichmentService {
}
}
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;
@@ -317,6 +413,18 @@ export class RiotAccountEnrichmentService {
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;
@@ -0,0 +1,107 @@
import { Injectable, Logger } from '@nestjs/common';
import type { RiotPlatformRoute, RiotRegionalRoute } from './riot.types';
import { GarnetService } from '../global/garnet/garnet.service';
const APP_LIMITS = [
{ windowMs: 1_000, max: 20 },
{ windowMs: 120_000, max: 100 },
] as const;
const ACQUIRE_SCRIPT = `
local now = tonumber(ARGV[1])
local member = ARGV[2]
local maxWait = 0
for i = 1, #KEYS do
local argIndex = 3 + ((i - 1) * 2)
local windowMs = tonumber(ARGV[argIndex])
local limit = tonumber(ARGV[argIndex + 1])
local key = KEYS[i]
redis.call('ZREMRANGEBYSCORE', key, '-inf', now - windowMs)
local count = redis.call('ZCARD', key)
if count >= limit then
local oldest = redis.call('ZRANGE', key, 0, 0, 'WITHSCORES')
local waitMs = windowMs
if oldest[2] then
waitMs = windowMs - (now - tonumber(oldest[2])) + 1
end
if waitMs > maxWait then
maxWait = waitMs
end
end
end
if maxWait > 0 then
return maxWait
end
for i = 1, #KEYS do
local argIndex = 3 + ((i - 1) * 2)
local windowMs = tonumber(ARGV[argIndex])
local key = KEYS[i]
redis.call('ZADD', key, now, member)
redis.call('PEXPIRE', key, windowMs)
end
return 0
`;
@Injectable()
export class RiotRateLimiterService {
private readonly logger = new Logger(RiotRateLimiterService.name);
constructor(private readonly garnet: GarnetService) {}
public async acquire(
route: RiotRegionalRoute | RiotPlatformRoute,
): Promise<void> {
for (;;) {
const now = Date.now();
const waitMs = await this.checkAndAdd(route, now);
if (waitMs <= 0) return;
if (waitMs >= 100) {
this.logger.warn(
`Riot API throttle waiting ${waitMs}ms for route=${route}.`,
);
}
await sleep(waitMs);
}
}
private async checkAndAdd(
route: RiotRegionalRoute | RiotPlatformRoute,
now: number,
): Promise<number> {
const client = this.garnet.raw();
const keys = APP_LIMITS.map(
(limit) => `riot:rl:${route}:${limit.windowMs}`,
);
const member = `${process.pid}:${now}:${Math.random().toString(36).slice(2)}`;
const argumentsList = [
String(now),
member,
...APP_LIMITS.flatMap((limit) => [
String(limit.windowMs),
String(limit.max),
]),
];
const response = await client.sendCommand([
'EVAL',
ACQUIRE_SCRIPT,
String(keys.length),
...keys,
...argumentsList,
]);
const waitMs = Number(response ?? 0);
if (!Number.isFinite(waitMs) || waitMs < 0) return 0;
return waitMs;
}
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
@@ -0,0 +1,144 @@
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) => {
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();
});
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 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;
}
@@ -7,6 +7,7 @@ import {
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',
@@ -51,7 +52,10 @@ export class RiotApiError extends Error {
export class RiotClientService {
private readonly logger = new Logger(RiotClientService.name);
constructor(private readonly secretService: SecretService) {}
constructor(
private readonly secretService: SecretService,
private readonly rateLimiter: RiotRateLimiterService,
) {}
public async get<T>(
path: string,
@@ -60,31 +64,9 @@ export class RiotClientService {
): 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';
const response = await fetch(url, {
method: 'GET',
headers: {
Accept: 'application/json',
'X-Riot-Token': apiKey,
},
signal: options.signal,
});
if (!response.ok) {
throw await this.createApiError(response, url);
}
if (response.status === 204) {
return undefined as T;
}
const payload = (await response.json()) as unknown;
if (parser) {
return parser(payload);
}
return payload as T;
return this.fetchWithRetry(url, apiKey, options.signal, parser, routeKey);
}
private buildUrl(path: string, options: RiotRequestOptions): string {
@@ -137,4 +119,60 @@ export class RiotClientService {
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 &&
error.retryAfterSeconds !== undefined
) {
await sleep(error.retryAfterSeconds * 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));
}
+9
View File
@@ -8,6 +8,9 @@ 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';
@@ -15,9 +18,12 @@ import { RiotWebhookController } from './riot-webhook.controller';
imports: [SecretModule],
controllers: [RiotWebhookController, RiotDdragonController],
providers: [
RiotRateLimiterService,
RiotClientService,
RiotAccountService,
RiotMatchService,
RiotRecentMatchesService,
RiotRecentStatsService,
RiotSummonerService,
RiotLeagueService,
RiotChampionMasteryService,
@@ -25,9 +31,12 @@ import { RiotWebhookController } from './riot-webhook.controller';
RiotDdragonService,
],
exports: [
RiotRateLimiterService,
RiotClientService,
RiotAccountService,
RiotMatchService,
RiotRecentMatchesService,
RiotRecentStatsService,
RiotSummonerService,
RiotLeagueService,
RiotChampionMasteryService,