This commit is contained in:
dahyeon committed 2026-04-26 01:22:38 -07:00
1 parent 905bbcc6dd
commit 2472f865ad
14 files changed
+825 -18

No files matched your search

@@ -0,0 +1 @@
export const GARNET_CLIENT = Symbol('GARNET_CLIENT');
@@ -0,0 +1,57 @@
import { Logger, Module } from '@nestjs/common';
import { createClient } from 'redis';
import { SecretModule } from '../secret/secret.module';
import { SecretService } from '../secret/secret.service';
import { GARNET_CLIENT } from './garnet.constants';
import { GarnetService, type GarnetRedisClient } from './garnet.service';
function normalizeGarnetUrl(endpoint: string): string {
const trimmed = endpoint.trim();
if (!trimmed) {
throw new Error('GARNET_ENDPOINT cannot be empty');
}
if (/^redis(s)?:\/\//iu.test(trimmed)) {
return trimmed;
}
return `redis://${trimmed}`;
}
@Module({
imports: [SecretModule],
providers: [
{
provide: GARNET_CLIENT,
inject: [SecretService],
useFactory: async (
secretService: SecretService,
): Promise<GarnetRedisClient> => {
await secretService.ready();
const [endpoint, username, password] = await Promise.all([
secretService.get<string>('GARNET_ENDPOINT'),
secretService.get<string>('GARNET_USERID'),
secretService.get<string>('GARNET_PASSWORD'),
]);
const logger = new Logger('GarnetClient');
const client = createClient({
url: normalizeGarnetUrl(endpoint),
username,
password,
});
client.on('error', (error) => {
logger.error(`Garnet client error: ${error?.message ?? error}`);
});
await client.connect();
logger.log('Garnet connected');
return client;
},
},
GarnetService,
],
exports: [GarnetService, GARNET_CLIENT],
})
export class GarnetModule {}
@@ -0,0 +1,90 @@
import {
Inject,
Injectable,
Logger,
OnModuleDestroy,
} from '@nestjs/common';
import type { createClient } from 'redis';
import { GARNET_CLIENT } from './garnet.constants';
export type GarnetRedisClient = ReturnType<typeof createClient>;
@Injectable()
export class GarnetService implements OnModuleDestroy {
private readonly logger = new Logger(GarnetService.name);
constructor(
@Inject(GARNET_CLIENT) private readonly client: GarnetRedisClient,
) {}
async onModuleDestroy() {
try {
await this.client.quit();
} catch {
this.client.destroy();
}
}
public raw(): GarnetRedisClient {
return this.client;
}
public async getJson<T>(key: string): Promise<T | null> {
const raw = await this.client.get(key);
if (!raw) return null;
try {
return JSON.parse(raw) as T;
} catch (err) {
this.logger.warn(
`Failed to JSON.parse cached value for key="${key}": ${
(err as Error)?.message ?? err
}`,
);
return null;
}
}
public async setJson(
key: string,
value: unknown,
ttlSeconds?: number,
): Promise<void> {
const serialized = JSON.stringify(value);
if (ttlSeconds && ttlSeconds > 0) {
await this.client.set(key, serialized, { EX: ttlSeconds });
return;
}
await this.client.set(key, serialized);
}
public async getString(key: string): Promise<string | null> {
return this.client.get(key);
}
public async setString(
key: string,
value: string,
ttlSeconds?: number,
): Promise<void> {
if (ttlSeconds && ttlSeconds > 0) {
await this.client.set(key, value, { EX: ttlSeconds });
return;
}
await this.client.set(key, value);
}
public async setStringIfAbsent(
key: string,
value: string,
ttlSeconds?: number,
): Promise<boolean> {
const options: { EX?: number; NX: true } = { NX: true };
if (ttlSeconds && ttlSeconds > 0) options.EX = ttlSeconds;
const result = await this.client.set(key, value, options);
return result === 'OK';
}
public async delete(key: string): Promise<number> {
return this.client.del(key);
}
}
+3 -4
View File
@@ -1,14 +1,13 @@
import { Module, Global } from '@nestjs/common';
import { SecretModule } from './secret/secret.module';
// import { DatabaseModule } from './database/database.module';
import { NatsModule } from './nats/nats.module';
import { DatabaseModule } from './database/database.module';
// import { DatabaseModule } from './database/database.module';
import { GarnetModule } from './garnet/garnet.module';
@Global()
@Module({
imports: [SecretModule, NatsModule, DatabaseModule],
imports: [SecretModule, NatsModule, DatabaseModule, GarnetModule],
providers: [],
exports: [SecretModule, NatsModule, DatabaseModule],
exports: [SecretModule, NatsModule, DatabaseModule, GarnetModule],
})
export class GlobalModule {}
@@ -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,132 @@
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 FETCH_TIMEOUT_MS = 10_000;
export interface DdragonManifest {
version: string;
cdn: string;
locale: string;
champions: Record<string, string>;
fetchedAt: string;
}
interface ChampionDataEntry {
key: string;
id: string;
}
interface ChampionDataResponse {
data: Record<string, ChampionDataEntry>;
}
@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 = await this.fetchChampionMap(version, locale);
return {
version,
cdn: DDRAGON_CDN,
locale,
champions,
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, string>> {
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, string> = {};
for (const entry of Object.values(payload.data)) {
if (entry?.key && entry.id) {
map[entry.key] = entry.id;
}
}
return map;
}
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 manifestCacheKey(locale: string): string {
return `ddragon:manifest:${locale}`;
}
+5 -1
View File
@@ -4,6 +4,8 @@ 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 { RiotSummonerService } from './riot-summoner.service';
@@ -11,7 +13,7 @@ import { RiotWebhookController } from './riot-webhook.controller';
@Module({
imports: [SecretModule],
controllers: [RiotWebhookController],
controllers: [RiotWebhookController, RiotDdragonController],
providers: [
RiotClientService,
RiotAccountService,
@@ -20,6 +22,7 @@ import { RiotWebhookController } from './riot-webhook.controller';
RiotLeagueService,
RiotChampionMasteryService,
RiotAccountEnrichmentService,
RiotDdragonService,
],
exports: [
RiotClientService,
@@ -29,6 +32,7 @@ import { RiotWebhookController } from './riot-webhook.controller';
RiotLeagueService,
RiotChampionMasteryService,
RiotAccountEnrichmentService,
RiotDdragonService,
],
})
export class RiotModule {}