Compare commits

...
3 Commits
7 changed files with 125 additions and 28 deletions

No files matched your search

+2 -2
View File
@@ -27,8 +27,8 @@
## Riot Background Refresh ## Riot Background Refresh
Set `RIOT_BG_REFRESH_ENABLED=true` to refresh stale Riot accounts automatically Stale Riot accounts refresh automatically between KST 03:00 and 10:00.
between KST 03:00 and 10:00. The scheduler picks active users whose The scheduler picks active users whose
`lastRefreshRequestedAt` is older than 6 hours, oldest first, and uses a `lastRefreshRequestedAt` is older than 6 hours, oldest first, and uses a
background-only Riot token bucket capped at roughly 40% of the app rate limit. background-only Riot token bucket capped at roughly 40% of the app rate limit.
@@ -1,4 +1,3 @@
import { ConfigService } from '@nestjs/config';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { GarnetService } from '../global/garnet/garnet.service'; import { GarnetService } from '../global/garnet/garnet.service';
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service'; import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
@@ -30,7 +29,7 @@ function candidate(puuid: string): StaleAccountCandidate {
}; };
} }
function makeScheduler(enabled = true) { function makeScheduler() {
const rawClient = { const rawClient = {
sendCommand: jest.fn().mockResolvedValue(1), sendCommand: jest.fn().mockResolvedValue(1),
}; };
@@ -51,16 +50,11 @@ function makeScheduler(enabled = true) {
const staleAccountRepository = { const staleAccountRepository = {
findStaleAccounts: jest.fn().mockResolvedValue([]), findStaleAccounts: jest.fn().mockResolvedValue([]),
} as unknown as jest.Mocked<StaleAccountRepository>; } as unknown as jest.Mocked<StaleAccountRepository>;
const config = {
get: jest.fn().mockReturnValue(enabled ? 'true' : 'false'),
} as unknown as ConfigService;
const scheduler = new BackgroundRefreshScheduler( const scheduler = new BackgroundRefreshScheduler(
garnet, garnet,
rateLimiter, rateLimiter,
enrichmentService, enrichmentService,
staleAccountRepository, staleAccountRepository,
config,
) as SchedulerInternals; ) as SchedulerInternals;
return { return {
@@ -79,14 +73,15 @@ describe('BackgroundRefreshScheduler', () => {
jest.restoreAllMocks(); jest.restoreAllMocks();
}); });
it('does not schedule ticks when disabled', () => { it('schedules ticks without requiring RIOT_BG_REFRESH_ENABLED', () => {
jest.useFakeTimers(); jest.useFakeTimers();
const setIntervalSpy = jest.spyOn(global, 'setInterval'); const setIntervalSpy = jest.spyOn(global, 'setInterval');
const { scheduler } = makeScheduler(false); const { scheduler } = makeScheduler();
scheduler.onModuleInit(); scheduler.onModuleInit();
expect(setIntervalSpy).not.toHaveBeenCalled(); expect(setIntervalSpy).toHaveBeenCalledTimes(2);
scheduler.onModuleDestroy();
}); });
it('does not query stale accounts outside the KST window', async () => { it('does not query stale accounts outside the KST window', async () => {
@@ -4,7 +4,6 @@ import {
OnModuleDestroy, OnModuleDestroy,
OnModuleInit, OnModuleInit,
} from '@nestjs/common'; } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { import {
type EnrichResult, type EnrichResult,
RiotAccountEnrichmentService, RiotAccountEnrichmentService,
@@ -34,26 +33,15 @@ export class BackgroundRefreshScheduler
private leaderRenewTimer?: NodeJS.Timeout; private leaderRenewTimer?: NodeJS.Timeout;
private tickInProgress = false; private tickInProgress = false;
private readonly consumer = `${process.pid}:${Math.random().toString(36).slice(2)}`; private readonly consumer = `${process.pid}:${Math.random().toString(36).slice(2)}`;
private readonly enabled: boolean;
constructor( constructor(
private readonly garnet: GarnetService, private readonly garnet: GarnetService,
private readonly rateLimiter: RiotRateLimiterService, private readonly rateLimiter: RiotRateLimiterService,
private readonly enrichmentService: RiotAccountEnrichmentService, private readonly enrichmentService: RiotAccountEnrichmentService,
private readonly staleAccountRepository: StaleAccountRepository, private readonly staleAccountRepository: StaleAccountRepository,
config: ConfigService, ) {}
) {
this.enabled = config.get<string>('RIOT_BG_REFRESH_ENABLED') === 'true';
}
public onModuleInit(): void { public onModuleInit(): void {
if (!this.enabled) {
this.logger.log(
'Background Riot refresh is disabled (RIOT_BG_REFRESH_ENABLED).',
);
return;
}
this.tickTimer = setInterval(() => void this.safeTick(), TICK_INTERVAL_MS); this.tickTimer = setInterval(() => void this.safeTick(), TICK_INTERVAL_MS);
this.leaderRenewTimer = setInterval( this.leaderRenewTimer = setInterval(
() => void this.renewLeaderIfHeld(), () => void this.renewLeaderIfHeld(),
@@ -0,0 +1,47 @@
import { RiotClientService } from './riot.client.service';
import { RiotLeagueService } from './riot-league.service';
import type { RiotLeagueEntryDto, RiotResponseParser } from './riot.types';
describe('RiotLeagueService', () => {
it('accepts Riot league entries without optional leagueId', async () => {
const client = {
get: jest.fn(
async <T>(
_path: string,
_options: unknown,
parser?: RiotResponseParser<T>,
) =>
parser
? parser([
{
queueType: 'RANKED_SOLO_5x5',
tier: 'EMERALD',
rank: 'I',
puuid: 'puuid-1',
leaguePoints: 75,
wins: 160,
losses: 148,
},
])
: ([] as T),
),
} as unknown as RiotClientService;
const service = new RiotLeagueService(client);
const result = await service.getEntriesByPuuid('puuid-1', {
platform: 'kr',
});
expect(result).toEqual<RiotLeagueEntryDto[]>([
{
queueType: 'RANKED_SOLO_5x5',
tier: 'EMERALD',
rank: 'I',
puuid: 'puuid-1',
leaguePoints: 75,
wins: 160,
losses: 148,
},
]);
});
});
@@ -36,7 +36,10 @@ function parseEntry(value: unknown, index: number): RiotLeagueEntryDto {
throw new TypeError(`leagueEntries[${index}] must be an object.`); throw new TypeError(`leagueEntries[${index}] must be an object.`);
} }
return { return {
leagueId: requireString(value.leagueId, `leagueEntries[${index}].leagueId`), leagueId: optionalString(
value.leagueId,
`leagueEntries[${index}].leagueId`,
),
queueType: requireString( queueType: requireString(
value.queueType, value.queueType,
`leagueEntries[${index}].queueType`, `leagueEntries[${index}].queueType`,
@@ -71,6 +74,11 @@ function requireString(value: unknown, path: string): string {
return value; return value;
} }
function optionalString(value: unknown, path: string): string | undefined {
if (value === undefined || value === null) return undefined;
return requireString(value, path);
}
function requireNumber(value: unknown, path: string): number { function requireNumber(value: unknown, path: string): number {
if (typeof value !== 'number' || !Number.isFinite(value)) { if (typeof value !== 'number' || !Number.isFinite(value)) {
throw new TypeError(`${path} must be a finite number.`); throw new TypeError(`${path} must be a finite number.`);
+1 -1
View File
@@ -89,7 +89,7 @@ export interface RiotSummonerDto {
// League-V4 entries by-puuid 응답 // League-V4 entries by-puuid 응답
export interface RiotLeagueEntryDto { export interface RiotLeagueEntryDto {
leagueId: string; leagueId?: string;
queueType: string; queueType: string;
tier: string; tier: string;
rank: string; rank: string;
+60 -1
View File
@@ -1,10 +1,69 @@
import { defineConfig } from "vite"; import { defineConfig } from "vite";
import react from "@vitejs/plugin-react"; import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite"; import tailwindcss from "@tailwindcss/vite";
import { createRequire } from "node:module";
import fs from "node:fs";
import path from "node:path";
const ES_TOOLKIT_COMPAT_RE = /^es-toolkit\/compat\/[A-Za-z0-9_$]+$/;
const VIRTUAL_ES_TOOLKIT_COMPAT_PREFIX = "\0es-toolkit-compat-esm:";
function esToolkitCompatEsm() {
return {
name: "es-toolkit-compat-esm",
enforce: "pre" as const,
resolveId(source: string, importer?: string) {
if (!importer || !ES_TOOLKIT_COMPAT_RE.test(source)) {
return null;
}
const requireFromImporter = createRequire(importer);
const wrapperPath = requireFromImporter.resolve(source);
const wrapperSource = fs.readFileSync(wrapperPath, "utf8");
const wrapperMatch = wrapperSource.match(
/require\(['"](\.\.\/dist\/compat\/[^'"]+)\.js['"]\)\.([A-Za-z0-9_$]+)/,
);
if (!wrapperMatch) {
return null;
}
const [, esmPathWithoutExtension, exportName] = wrapperMatch;
const esmPath = path.resolve(
path.dirname(wrapperPath),
`${esmPathWithoutExtension}.mjs`,
);
return `${VIRTUAL_ES_TOOLKIT_COMPAT_PREFIX}${encodeURIComponent(
exportName,
)}:${encodeURIComponent(esmPath)}`;
},
load(id: string) {
if (!id.startsWith(VIRTUAL_ES_TOOLKIT_COMPAT_PREFIX)) {
return null;
}
const [encodedExportName, encodedEsmPath] = id
.slice(VIRTUAL_ES_TOOLKIT_COMPAT_PREFIX.length)
.split(":");
const exportName = decodeURIComponent(encodedExportName);
const esmPath = decodeURIComponent(encodedEsmPath);
return `export { ${exportName} as default, ${exportName} } from ${JSON.stringify(
esmPath,
)};`;
},
};
}
// https://vite.dev/config/ // https://vite.dev/config/
export default defineConfig({ export default defineConfig({
plugins: [react(), tailwindcss()], plugins: [esToolkitCompatEsm(), react(), tailwindcss()],
optimizeDeps: {
rolldownOptions: {
plugins: [esToolkitCompatEsm()],
},
},
server: { server: {
host: "0.0.0.0", host: "0.0.0.0",
allowedHosts: ["126.dahyeon.us"], allowedHosts: ["126.dahyeon.us"],