23 KiB
Riot 캐싱 Phase 2 플랜
대상: codex가 이어서 진행 가능한 수준의 실행 플랜 레포:
/Users/dahyeon/source/lolympus-tournament-support(pnpm workspace) 작성 기준: 2026-04-25 선행 작업: dakao NATS 통합, RiotAccountEnrichmentService(force=true 동기 호출, summoner/league/mastery v4) 1차 구현 완료
1. Context
dakao 카카오톡 명령(!내전 신청 ...) 이 들어오면 라이엇 ID를 검증·등록하고, 동시에 summoner v4 / league v4 / champion-mastery v4 데이터를 가져와 User.riotAccounts[*] 임베딩에 캐싱하는 1차 구현이 끝난 상태입니다.
이 플랜은 그 위에 다음을 더합니다.
- community별 default platform 지정 + region/by-puuid 기반 자동 보정
- champion-mastery top 10 으로 좁히고 스키마를 Riot DTO 그대로
- league 변동 시 tierHistory 자동 누적
- 사용자 수동 갱신 엔드포인트 + 한가한 시간대 스케줄러
- 신선도 표시(API 응답에
*FetchedAt노출) - 무거운 필드(
championRecords,tiers)는 list/find 쿼리에서 projection 으로 잘라내기 - 동일 puuid 동시 enrichment dedup
- v4 서비스 응답 파서 단위 테스트
비목표:
- Rate limit 글로벌 throttle (token bucket / Redis) — Phase 3
- OpenSearch / Slack 운영 알림 — Phase 3
- 백오피스 UI — 별도 트랙
2. 결정된 설계 사항
2.1 Riot Schema 우선 (Data Dragon 호환)
기존 ChampionMasteryEntry, TierInfo, TierHistoryEntry 를 Riot v4 응답 그대로 매칭하도록 재정의합니다.
현재 (수정 전)
export interface ChampionMasteryEntry {
championId: string; // ← Riot 은 number
championName?: string; // ← Riot 응답에 없음
level: number; // ← championLevel
points: number; // ← championPoints
}
export interface TierInfo {
queueType: string;
tier: string;
rank: string;
leaguePoints: number;
wins: number;
losses: number;
fetchedAt: Date;
}
목표 (수정 후)
// Riot Champion-Mastery-V4 DTO 그대로
export interface ChampionMasteryEntry {
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>;
}
// Riot League-V4 entries DTO + 우리 측 fetchedAt
export interface TierInfo {
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>;
fetchedAt: Date;
}
// 시점별 tier 스냅샷
export interface TierHistoryEntry {
queueType: string;
tier: string;
rank?: string;
leaguePoints?: number;
wins?: number;
losses?: number;
recordedAt: Date;
// 시즌 단위 통계 / peak (옵션)
season?: string;
peakTier?: string;
peakRank?: string;
}
championRecords 는 챔피언별 집계 데이터(향후 매치 분석) 용으로 유지하되, mastery 원본은 더 이상 championRecords 에 중복 저장하지 않습니다. mastery 자체가 이제 Riot DTO 형태이기 때문입니다.
기존 schema 의 RiotAccount.championRecords 와 RiotAccount.championRecordsFetchedAt 는 그대로 둡니다 (다른 용도).
2.2 community 별 default platform
export interface Community extends MongooseTimestamps {
// ...
riotPlatform?: RiotPlatformRoute; // default 'kr'
riotRegion?: RiotRegionalRoute; // default 'asia'
}
- platform 기본
kr, region 기본asia는 코드 상 fallback. 명시 지정 시 community 설정값 우선. - enrichment / lookup 시 community 의 platform 을 사용.
- 추가로 puuid 만 있는 상황(예: 다른 community 매치 import)에서는 region/by-puuid 로 platform 보정.
2.3 region/by-puuid 자동 보정
GET https://{regional}.api.riotgames.com/riot/account/v1/region/by-game/lol/by-puuid/{puuid}→{ puuid, game, region }
- 응답의
region이 platform 코드 (kr,na1, …) - 사용 시점: community 의 platform 과 puuid 의 실제 platform 이 다른지 의심될 때 (예: 처음 등록 시, summoner v4 404 발생 시)
- 새 서비스:
RiotAccountService.getRegionByPuuid(puuid, options) - enrichment fallback 정책: summoner v4 가 404 면 region/by-puuid 호출해서 platform 보정 후 한 번 더 시도, 그래도 실패면 failed 처리
2.4 mastery top 10
- 엔드포인트 변경:
/lol/champion-mastery/v4/champion-masteries/by-puuid/{puuid}/top?count=10 - 저장 상한 10.
MASTERY_LIMIT = 10. RiotChampionMasteryService.getTopByPuuid(puuid, { platform, count })신규 메서드. 기존getByPuuid는 leftover/내부용으로 유지하거나 삭제 (사용처 확인 후 결정).
2.5 tierHistory 누적 규칙
- enrichment 가 league entries 를 갱신할 때, queueType 별로 가장 최근 history entry 와 비교하여 다음 중 하나라도 다르면 history 에 push:
tier,rankleaguePoints변화 (옵션 — 너무 잦으면 noise. 1차에선 tier/rank 변화만 추적)
- 1차 결정: tier 또는 rank 가 변하면 push. lp 변화는 history 에 안 남김.
- 신규 등록 시(history 비어있음)는 첫 league fetch 결과를 그대로 history 에 1건 push.
recordedAt = new Date().- queueType 외 다른 분류는 도입하지 않음. season 추적은 별도 작업.
2.6 신선도 노출 (*FetchedAt)
API 응답(GET /users/:id, /me, /communities/:id/matches/:id 등)에 RiotAccount 가 포함될 때 다음 필드를 함께 노출:
tiers[*].fetchedAtchampionMasteriesFetchedAtrevisionDate(summoner)championRecordsFetchedAt
스키마 상 이미 존재하므로 변경 불필요. 단, list 쿼리에서는 무거운 raw 필드(championRecords, championMasteries[*].milestoneGrades 등) 는 projection 으로 제외. (2.8 참조)
2.7 수동 갱신 + 스케줄러
HTTP 엔드포인트
POST /users/me/riot-accounts/:puuid/refresh
Body: { force?: boolean, platform?: RiotPlatformRoute }
Auth: 본인 또는 admin
Response: EnrichResult
- 본인 또는 community admin 이상만 허용.
force = true면 TTL 무시.- platform 지정 시 community default 무시.
스케줄러
- NestJS
@nestjs/schedule(cron) 도입. - 작업명:
RiotAccountRefreshScheduler - 실행 주기: 매일 KST 04:00 ~ 06:00 사이에 chunked 실행
- 대상 선정:
tiers[*].fetchedAt가 24h 초과 또는 비어있는 RiotAccount- 한 batch 당 최대 200건, batch 간 5초 간격
- enrichment 호출 시
force = false(TTL 기반) - per-batch try/catch + 실패 카운터 로그
@Cron('0 4 * * *')단일 트리거로 시작 → 추후 batch 분산은 Phase 3 에서 보강
2.8 list/find projection 정책
apps/api/src/modules/global/database/projection.ts 신설하여 공통 projection 상수를 모음.
// 매치 리스트, /me 등에서 RiotAccount 의 무거운 필드를 잘라낸다
export const RIOT_ACCOUNT_LIGHT_PROJECTION = {
'riotAccounts.championRecords': 0,
'riotAccounts.championRecordsFetchedAt': 0,
// championMasteries 자체는 살리되 milestoneGrades 등 무거운 nested 는 protected list 에서만 fetch
} as const;
- 적용 대상:
MatchService.list,UserController.list,MatchController.listMatches등 - 단건 조회(
getById,/me) 는 풀 데이터 포함
2.9 동일 puuid 동시 enrichment dedup
채택 방식: in-memory Map<puuid, Promise<EnrichResult>> (단일 인스턴스 dedup)
private inFlight = new Map<string, Promise<EnrichResult>>();
public enrichRiotAccount(params): Promise<EnrichResult> {
const key = params.puuid;
const existing = this.inFlight.get(key);
if (existing) return existing;
const promise = this.doEnrich(params).finally(() => {
this.inFlight.delete(key);
});
this.inFlight.set(key, promise);
return promise;
}
이유:
- 카카오 신청 빈도가 낮아 분산 락까지 필요 없음.
- 동일 인스턴스 내 race(동시 신청)만 막아도 90%의 중복 호출 절감.
- 멀티 인스턴스 환경 dedup 은 Phase 3 (Redis SET NX) 에서.
대안 비교 (참고)
| 방식 | 장점 | 단점 |
|---|---|---|
| in-memory Map | 의존성 없음, 빠름 | 멀티 인스턴스 미지원 |
Mongo findOneAndUpdate 락 |
의존성 없음, 분산 가능 | 실패 시 락 만료 처리 복잡, 추가 필드 필요 |
| Redis SET NX EX | 분산 / TTL 자연스러움 | Redis 인프라 필요 |
2.10 v4 파서 단위 테스트
riot-summoner.service.spec.tsriot-league.service.spec.tsriot-champion-mastery.service.spec.ts
각각 정상 응답 / 누락 필드 거부 / 빈 배열 / 타입 불일치 거부 케이스.
3. 실행 단계 (codex 진행 순서)
작업 단위는 PR 단위로 쪼갤 수 있도록 분리되어 있습니다. 단계 간 의존성이 있는 부분은 명시.
Step 1. 스키마 재정의 (TierInfo / ChampionMasteryEntry / TierHistoryEntry)
파일: apps/api/src/modules/global/database/schema.ts
TierInfo,TierHistoryEntry,ChampionMasteryEntry인터페이스 위 2.1 정의로 교체.TierInfoSubSchema,TierHistoryEntrySubSchema,ChampionMasteryEntrySubSchema도 동일하게 갱신.championId:Number로 변경championLevel,championPoints: 새 필드명milestoneGrades:[String](defaultundefined)nextSeasonMilestone:Schema.Types.MixedTierInfo에leagueId,puuid,veteran,inactive,freshBlood,hotStreak,miniSeries(Mixed)추가TierHistoryEntry에recordedAt: { type: Date, required: true },leaguePoints/wins/lossesoptional
Community에riotPlatform,riotRegion추가:
riotPlatform: { type: String },
riotRegion: { type: String },
MatchParticipantSubSchema.tier는 새TierInfo모양을 자동으로 따라감 — 추가 변경 없음.
Risk: 기존 데이터가 있다면 마이그레이션 필요. 현재 dev 환경 seed 만 사용한다면 seed 재실행으로 충분. apps/api/src/seed.ts 도 새 필드명에 맞춰 갱신.
테스트: 타입체크 통과 확인.
Step 2. RiotChampionMasteryService → top 엔드포인트로 변경
파일: apps/api/src/modules/riot/riot-champion-mastery.service.ts
- 메서드 시그니처 변경 또는 신규:
public async getTopByPuuid(
puuid: string,
options: { platform?: RiotPlatformRoute; count?: number; signal?: AbortSignal } = {},
): Promise<RiotChampionMasteryDto[]>
엔드포인트: /lol/champion-mastery/v4/champion-masteries/by-puuid/{puuid}/top
query: count (default 10, max 10)
- 기존
getByPuuid사용처 grep 후 모두getTopByPuuid로 교체. riot-account-enrichment.service.ts에서MASTERY_LIMIT = 10으로 변경.
Step 3. region/by-puuid 서비스 + 자동 보정
파일: apps/api/src/modules/riot/riot-account.service.ts
public async getRegionByPuuid(
puuid: string,
options: RiotAccountLookupOptions = {},
): Promise<{ puuid: string; game: string; region: RiotPlatformRoute }> {
return this.riotClientService.get(
`/riot/account/v1/region/by-game/lol/by-puuid/${encodeURIComponent(puuid)}`,
{ region: options.region ?? 'asia', signal: options.signal },
parseRegionByPuuid,
);
}
riot.types.ts 에 응답 타입 추가:
export interface RiotAccountRegionDto {
puuid: string;
game: 'lol' | string;
region: RiotPlatformRoute;
}
enrichment 보정 로직:
RiotAccountEnrichmentService.fetchSummonerSafe 에서 RiotApiError && status === 404 발생 시:
getRegionByPuuid호출- 받은 platform 으로 다시 summoner 호출
- 그래도 실패면
failed처리 - 새 platform 이 community default 와 다르면 로그(
logger.warn) — 향후 schema 에 puuid 별 platform 저장 여부는 별도 결정
Step 4. enrichment dedup + force/TTL 흐름 정리
파일: apps/api/src/modules/riot/riot-account-enrichment.service.ts
- 클래스에
private inFlight = new Map<string, Promise<EnrichResult>>()추가. enrichRiotAccount진입부에서 dedup 체크. key 는${userId}:${puuid}(user 다른데 puuid 같은 케이스도 있으니 user 포함이 안전).applyMasteries에서championRecords채우는 코드 제거 (2.1 결정).applyLeagueEntries호출 직전tierHistory갱신 헬퍼 호출:
private appendTierHistoryIfChanged(
account: RiotAccount,
entries: RiotLeagueEntryDto[],
): void {
const now = new Date();
for (const e of entries) {
const last = [...account.tierHistory]
.reverse()
.find((h) => h.queueType === e.queueType);
const changed =
!last ||
last.tier !== e.tier ||
(last.rank ?? '') !== (e.rank ?? '');
if (changed) {
account.tierHistory.push({
queueType: e.queueType,
tier: e.tier,
rank: e.rank,
leaguePoints: e.leaguePoints,
wins: e.wins,
losses: e.losses,
recordedAt: now,
});
}
}
}
- 위 헬퍼는
applyLeagueEntries가 처음 호출되더라도 빈 history → 첫 entry push 가 자연스럽게 일어남.
Step 5. community.platform 사용 + DakaoUserService 연결
파일:
apps/api/src/modules/dakao/dakao-user.service.tsapps/api/src/modules/dakao/handlers/match-join.handler.ts(필요 시)
resolveRiotAccount가 community 를 한 번 조회해서riotPlatform,riotRegion을 옵션으로 enrichment / Riot lookup 에 전달.RiotAccountService.getByRiotId에region옵션 전달 (community.riotRegion 우선, fallbackasia).- enrichment 호출에도
platform: community.riotPlatform ?? 'kr'.
const community = await CommunityModel.findById(context.communityId)
.select({ riotPlatform: 1, riotRegion: 1 })
.lean()
.exec();
const platform = (community?.riotPlatform as RiotPlatformRoute) ?? 'kr';
const region = (community?.riotRegion as RiotRegionalRoute) ?? 'asia';
Step 6. 수동 갱신 엔드포인트
신규 파일: apps/api/src/modules/user/user.controller.ts (이미 존재) 에 라우트 추가, 또는 riot-account.controller.ts 신설.
- 기존
user.module.ts/user.controller.ts구조 확인 (현재user/user.controller.ts,user/user.module.ts존재). - 라우트:
@Post('me/riot-accounts/:puuid/refresh')
async refreshMyRiotAccount(
@CurrentUser() me: UserDocument,
@Param('puuid') puuid: string,
@Body() body: { force?: boolean; platform?: RiotPlatformRoute },
): Promise<EnrichResult> {
if (!me) throw new UnauthorizedException();
const owns = me.riotAccounts.some((a) => a.puuid === puuid);
if (!owns) throw new ForbiddenException();
return this.enrichmentService.enrichRiotAccount({
userId: me._id,
puuid,
options: { force: body.force === true, platform: body.platform },
});
}
UserModule.imports에RiotModule추가 (이미 RiotModule 이RiotAccountEnrichmentServiceexport 함).- DTO:
class-validator기반RefreshRiotAccountDto.
Step 7. 스케줄러
의존성: pnpm --filter api add @nestjs/schedule
신규 파일: apps/api/src/modules/riot/riot-account-refresh.scheduler.ts
@Injectable()
export class RiotAccountRefreshScheduler {
private readonly logger = new Logger(RiotAccountRefreshScheduler.name);
constructor(
private readonly connectionService: ConnectionService,
private readonly enrichment: RiotAccountEnrichmentService,
) {}
@Cron('0 4 * * *', { timeZone: 'Asia/Seoul' })
async refreshStaleAccounts() {
const UserModel = await this.connectionService.getModel('user');
const cursor = UserModel.find({
'riotAccounts.0': { $exists: true },
})
.select({ _id: 1, riotAccounts: 1, communityId: 1 })
.cursor();
let processed = 0;
for await (const user of cursor) {
for (const acc of user.riotAccounts) {
try {
await this.enrichment.enrichRiotAccount({
userId: user._id,
puuid: acc.puuid,
options: { force: false },
});
processed += 1;
if (processed % 50 === 0) {
await sleep(5000);
}
} catch (err) {
this.logger.warn(`refresh failed: ${(err as Error)?.message ?? err}`);
}
}
}
this.logger.log(`Scheduler done: processed=${processed}`);
}
}
function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
RiotModule.providers 에 추가, app.module.ts 에 ScheduleModule.forRoot() 추가.
Step 8. projection 적용
신규 파일: apps/api/src/modules/global/database/projections.ts
export const USER_LIGHT_PROJECTION = {
'riotAccounts.championRecords': 0,
'riotAccounts.championRecordsFetchedAt': 0,
} as const;
적용 지점:
MatchService.list— 매치 자체에는 RiotAccount 가 없지만 향후 populate 시 사용- 신규
UserService.list또는findByCommunity류 — projection 적용 /me핸들러 — full 데이터 유지/users/:id단건 조회 — full 데이터 유지
대부분의 riotAccounts.* 가 무거워지는 시점이 mastery top 10 + tierHistory 누적이므로, 우선 list 쿼리에만 적용.
Step 9. v4 파서 단위 테스트
신규 파일:
apps/api/src/modules/riot/riot-summoner.service.spec.tsapps/api/src/modules/riot/riot-league.service.spec.tsapps/api/src/modules/riot/riot-champion-mastery.service.spec.ts
각 서비스에 RiotClientService mock 주입, 정상/누락 필드/배열 비정상 케이스 검증. enrichment 의 적용 단계는 기존 riot-account-enrichment.service.spec.ts 에서 이미 커버 중이므로, Step 1 변경에 따라 기존 spec 의 응답 fixture 도 새 필드명으로 갱신 필요.
Step 10. 회귀 테스트 / 정리
npx tsc --noEmit통과npx jest전체 PASS- seed 재실행으로 새 스키마 정상 작동 확인
- dakao 시나리오 수동 검증:
- 신규 카카오 사용자가
!내전 신청 ...으로 등록될 때 summoner v4 가 한 번 호출되고, 응답 후 user 문서에tiers,championMasteries(10건),tierHistory(1건) 가 채워지는지 확인 - 같은 사용자가 즉시 재신청하면 enrichment 가 dedup 으로 단일 호출에 합쳐지는지 로그로 확인
- 한 시즌 후 tier 가 변경된 상태에서 enrichment 가 호출되면
tierHistory에 새 entry 가 push 되는지 단위 테스트
- 신규 카카오 사용자가
4. 변경/추가 파일 목록
신규
apps/api/src/modules/global/database/projections.tsapps/api/src/modules/riot/riot-account-refresh.scheduler.tsapps/api/src/modules/riot/riot-summoner.service.spec.tsapps/api/src/modules/riot/riot-league.service.spec.tsapps/api/src/modules/riot/riot-champion-mastery.service.spec.ts- (옵션)
apps/api/src/modules/user/dto/refresh-riot-account.dto.ts
수정
apps/api/src/modules/global/database/schema.ts— TierInfo / TierHistoryEntry / ChampionMasteryEntry / Community 재정의apps/api/src/modules/riot/riot.types.ts— DTO 타입, RiotAccountRegionDto 추가apps/api/src/modules/riot/riot-account.service.ts—getRegionByPuuid추가apps/api/src/modules/riot/riot-champion-mastery.service.ts—getTopByPuuid로 교체apps/api/src/modules/riot/riot-account-enrichment.service.ts— 새 스키마 적용, dedup, tierHistory 누적, 404 보정apps/api/src/modules/riot/riot.module.ts— Scheduler / region service provider 등록apps/api/src/modules/dakao/dakao-user.service.ts— community platform/region 사용apps/api/src/modules/user/user.controller.ts(또는 신설) —/me/riot-accounts/:puuid/refreshapps/api/src/modules/user/user.module.ts— RiotModule importapps/api/src/modules/match/match.service.ts— list 쿼리 projectionapps/api/src/app.module.ts—ScheduleModule.forRoot()apps/api/src/seed.ts— 새 mastery / tier 필드명에 맞춰 seed 데이터 수정apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts— fixture 갱신
의존성
pnpm --filter api add @nestjs/schedule
5. 검증 체크리스트
pnpm --filter api exec tsc --noEmit통과pnpm --filter api exec jest전체 PASS- seed 재실행 후 user 문서 정상 (
db.user.findOne()으로 새 필드 확인) - dakao
!내전 신청 <id> <기존_등록_riot_id> 미드,탑→ enrichment 캐시 hit, Riot API 호출 0회 - dakao
!내전 신청 <id> <신규_riot_id> 미드,탑→ summoner v4 1회, league v4 1회, mastery top v4 1회 호출, user 문서에 tiers/masteries/tierHistory 채워짐 POST /users/me/riot-accounts/:puuid/refresh { force: true }→ enrichment 수동 강제 갱신 동작- cron 시뮬레이션 (
@Cron수동 트리거 또는node -e로 메서드 직접 호출) → 200건 이상 처리되어도 OOM/timeout 없이 완료 - match list API 응답 사이즈 → projection 적용으로 기존 대비 30%+ 감소 (실측)
- 동시 동일 puuid enrichment 두 번 호출 → in-flight Map 으로 1회로 합쳐짐 (단위 테스트)
6. Phase 3 으로 미루는 것 (참고)
- 분산 dedup (Redis SET NX EX 또는 mongo 락)
- Token bucket / Riot API rate limit 글로벌 throttle
- OpenSearch 인덱싱 (RiotAccount, Match 변화 로그)
- Slack 알림 (enrichment 실패 임계 초과, scheduler 실패)
- puuid 별 last-known platform 캐싱 (Step 3 의 보정 결과를 RiotAccount 에 영구 저장)
- 시즌 종료 시 tierHistory 의
season필드 자동 채움 + peakTier 계산 - 백오피스 UI — community.riotPlatform 설정 / 수동 갱신 트리거 / 신선도 리포트
- NATS 기반 enrichment 분산 (현재 dakao 외 트리거가 없으므로 보류)
7. 운영 노트
- Riot personal API key 는 개당 100req / 2분 / IP 한도. mastery + summoner + league 가 1 user attach 당 3회. dakao 첫 신청이 폭주해도 분당 ~30명 미만이면 무탈.
- 스케줄러는 5초 간격 batch 50건 → 10분에 6000건. 대부분의 community 규모에서 충분.
- region/by-puuid 보정은 community 의 platform 이 잘못 설정된 케이스에서 운영자가 즉시 알 수 있도록
logger.warn만 남김. Phase 3 에서 알림 채널로 승격. championRecords와championRecordsFetchedAt은 비워두는 채로 schema 만 유지. mastery 와는 다른 용도(향후 매치 분석 집계)이므로 충돌 없음.