Files
lolympus-tournament-support/Riot-최근경기-플랜.md
T
2026-04-26 03:33:24 -07:00

31 KiB
Raw Blame History

Riot 최근 솔로랭크 통계 통합 플랜

대상: codex가 이어서 진행 가능한 수준의 실행 플랜 레포: /Users/dahyeon/source/lolympus-tournament-support (pnpm workspace) 작성 기준: 2026-04-26 선행 작업: Riot-캐싱-Phase2-플랜.md, Riot-DDragon Manifest 도입(RiotDdragonService + Garnet 캐시) 완료


1. Context

AuctionPage.tsx 의 "최근 솔로랭크" 카드(승률/전적/KDA/평균 CS)가 현재 모두 0/NaN 으로 표시됩니다. 백엔드는 이미 RiotAccount.recentStatsSummary 필드를 노출하고 있고 mapper도 이를 전달하지만, 이 필드를 채우는 enrichment 단계가 비어 있습니다.

이번 작업은 다음을 추가합니다.

  1. Match-V5 by-puuid (queue=420) 으로 솔로랭크 matchId 목록 동기화
  2. Match-V5 detail 호출 → RiotMatch 컬렉션에 raw 보관 (이미 schema 존재)
  3. 사용자별 RiotAccount.recentStatsSummary 재계산 + recentStatsFetchedAt 갱신
  4. enrichment 트리거(수동 / 신규 등록 / 경매 직전) 와 TTL/Garnet dedup 적용
  5. 클라가 0/NaN 대신 실제 값을 표시하도록 mapper 점검

이미 다음이 갖춰져 있어 추가 인프라가 거의 필요 없습니다.

  • RiotMatchService.getMatchIdsByPuuid({queue, count, ...}) (riot-match.service.ts)
  • RiotMatchService.getMatch(matchId) 가 RiotMatchDto 파싱까지 포함
  • RiotMatch 컬렉션(riot_match) + participantPuuids 인덱스(schema.ts:573)
  • RiotAccount.matchIds, matchIdsFetchedAt, recentStatsSummary, recentStatsFetchedAt 필드(schema.ts:128-148)
  • GarnetService (in-flight dedup / TTL 락 용도)

2. 결정된 설계 사항

2.1 큐 정책

  • 1차 대상은 솔로랭크(queueId=420) 만.
  • 자유랭크(440)/노말은 추후 Phase 확장. 코드는 queueId 를 인자로 받는 형태로 짜되 호출부는 420 고정.

2.2 "최근" 의 정의

  • 최근 20경기 고정 윈도우 (사용자 결정). 상수 RIOT_RECENT_MATCH_LIMIT = 20 으로 service 모듈에 정의, 환경변수화 하지 않음.
  • 시즌 경계 보정은 하지 않음. mostPlayedChampionIds 가 시즌 패치에 따라 의미가 흔들릴 수 있다는 한계를 README/주석에 명시.

2.3 캐시 / TTL

  • RiotAccount.recentStatsFetchedAt 기반 staleness 검사. TTL 기본 6h (mastery와 동일).
  • enrichment 진행 중 동일 (userId, puuid) 키 중복 호출 방지: 메모리 + Garnet NX 락.
    • 메모리 dedup: RiotAccountEnrichmentService.inFlight 패턴 그대로 확장
    • Garnet 락: riot:enrich:matches:<puuid> 키 + setStringIfAbsent(..., 60) (다중 인스턴스 안전망)
  • ddragon manifest 패턴(Riot-DDragon)과 동일하게 in-flight 후 TTL 캐시 갱신 → 다음 호출은 즉시 fresh 반환.

2.4 RiotMatch 저장 정책

  • RiotMatch.matchId 기준 upsert. 이미 존재하면 API 재호출하지 않음 (다른 사용자가 이미 가져왔을 가능성).
  • participantPuuids 인덱스 활용 → 한 puuid 의 최근 N경기를 DB에서 즉시 조회 가능.
  • Riot raw 응답은 raw 필드(Mixed) 에 통째로 저장. 핵심 메타(gameCreation, gameDuration, gameVersion, queueId) 는 top-level 으로 복제(필터/정렬용).
  • 페이로드 크기 우려: 한 경기 ≈ 30~80KB. 활성 사용자 100명 × 20경기 = 최대 2k 도큐먼트 ≈ 100MB 미만, 같은 매치 dedup 으로 실제는 더 작음.
  • TTL/prune 없음 (사용자 결정). 무한 누적 정책. 추후 컬렉션 비대화 시 별도 prune job 검토.

2.5 통계 계산 규칙 (라인별 분리)

사용자 결정 2026-04-26: 탑/정글/미드/바텀/서폿 라인별로 데이터 구분 필요.

라인 식별

  • Match-V5 participant 의 teamPosition 필드 (TOP | JUNGLE | MIDDLE | BOTTOM | UTILITY) 사용.
  • 빈 문자열인 경우 individualPosition 으로 fallback.
  • 둘 다 비어있거나 Invalid 면 통계에서 제외 (집계 카운트 안 함).

우리 측 enum 매핑

// schema 신규
export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY';

const POSITION_TO_LANE: Record<Position, RiotLane> = {
  TOP: 'TOP',
  JGL: 'JUNGLE',
  MID: 'MIDDLE',
  ADC: 'BOTTOM',
  SUP: 'UTILITY',
};

새 데이터 구조

export interface RiotLaneStats {
  games: number;
  wins: number;
  losses: number;
  avgKills: number;        // 소수 1자리
  avgDeaths: number;
  avgAssists: number;
  avgCs: number;           // (totalMinionsKilled + neutralMinionsKilled) / games
  avgCsPerMin: number;     // 분당 CS — 라인 비교용 (서폿 비교 한계 보정)
  mostPlayedChampionIds: number[]; // 상위 3, Riot DTO 와 동일 number
}

export interface RiotRecentStatsSummary {
  overall: RiotLaneStats;
  byLane: Partial<Record<RiotLane, RiotLaneStats>>; // 게임이 1회 이상 있는 라인만 entry
  // 기존 flat 필드들은 schema 마이그레이션을 통해 제거. § 2.5.1 참고.
}

mostPlayedChampionIds 는 number[] (Riot DTO 와 동일). 클라는 ddragon manifest 로 표시명 풀이. § 2.5.3 참고.

2.5.3 championId 타입 통일 (전체 number)

기존 정합성 깨진 곳: RiotRecentStatsSummary.mostPlayedChampionIds: string[] (schema.ts:123) — Phase2 에서 mastery 는 number 로 바꿨는데 이 한 줄만 string 으로 잔존. Riot 모든 응답이 number 이므로 number 로 통일.

영향 받는 위치:

  • apps/api/src/modules/global/database/schema.ts:123 — string[] → number[]
  • apps/api/src/modules/riot/riot.types.ts — RiotRecentStatsSummary 동일 변경
  • apps/web/src/api/types.ts — ApiRiotRecentStatsSummary.mostPlayedChampionIds, 그리고 §3.7 신규 ApiRiotLaneStats 도 처음부터 number[]
  • apps/web/src/lib/ddragon.ts — 이미 string | number 둘 다 받게 만들어둠. 변경 불필요.

기존 DB 도큐먼트에 string[] 으로 저장된 게 있을 가능성: enrichment 한 번 돌면 새 구조로 통째 교체되므로 자동 정리. 별도 마이그레이션 스크립트 불필요.

2.5.1 schema 마이그레이션 메모

  • 기존 RiotRecentStatsSummary (flat) 는 사용처가 mapper 한 곳뿐 (mappers.ts:184~).
  • DB 에 이미 저장된 도큐먼트는 옛 형태일 수 있으나 enrichment 가 한 번 돌면 자동 덮어씀.
  • 안전한 전환: enrichment service 가 응답 직전 항상 새 구조로 만들어 account.recentStatsSummary = newSummary 통째 교체. partial merge 안 함.
  • 별도 마이그레이션 스크립트 불필요 (TTL 6h 안에 자연 갱신).

2.5.4 시즌 경계 — 자동 리셋

LoL 시즌(splits/sets) 시작 시점에는 누적 통계의 의미가 변하므로 자동 리셋 필요. Riot 이 명시적 "season started at" API 를 제공하지 않으므로 community 단위 수동 설정 + 자동 필터링 의 하이브리드.

Schema 추가

// schema.ts Community
seasonStartedAt?: Date; // 운영자/admin 이 시즌 시작 시점 등록

동작

  1. enrichment 진입 시 community.seasonStartedAt 조회.
  2. account.recentStatsFetchedAt < community.seasonStartedAt 이면 force=true 로 진행 (TTL 무시).
  3. computeSummary 가 매치 필터링: match.info.gameCreation >= seasonStartedAt.getTime() 인 것만 사용.
  4. account.matchIds 도 시즌 경계 이전 것은 통계에서 제외 (DB 자체에서는 제거 안 함 — 무한 저장 정책).

Trigger

  • 운영자가 새 시즌 시작 시 community 의 seasonStartedAt 을 수동 갱신 → 다음 enrichment 부터 자동 적용.
  • 야간 prefetch 가 다음 사이클에 일괄 갱신.

Phase 후속 (자동화 검토)

  • Riot patch notes RSS 또는 ddragon versions.json 의 major bump 감지로 자동 갱신 — 본 플랜 범위 외.

2.5.5 다국가 region 지원 (구조)

현재 enrichment 가 region: 'asia', platform: 'kr' 하드코딩. 이미 Community.riotPlatform, Community.riotRegion 필드는 schema 에 존재하지만 enrichment 호출부에서 사용 안 함.

변경

  1. 호출자 책임 모델: enrichRiotAccount 의 EnrichOptions.platform/region 으로 community 값을 명시 전달.
  2. enrichment 트리거 지점 (auction.service, dakao-user.service, prefetch.scheduler) 에서 community 조회 후 platform/region 을 옵션에 주입.
  3. fallback 기본값은 kr / asia 유지 (community 미지정 시).
  4. Throttle 분리: §2.7 의 sliding-window 키가 이미 region 별로 분리됨 (riot:rl:<region>:1s) — 추가 변경 없음.
  5. DDragon 영향: realms/<region>.json 별 자체 dd 버전이 다를 수 있음. 현재 RiotDdragonService 는 글로벌 versions[0] 사용 중 — 한국 클라이언트 dd 버전이 글로벌과 차이 거의 없어 OK. 다른 region 추가 시 region 별 manifest 캐시로 분리 검토.

호출 패턴

// auction.service.ts:start
const community = await CommunityModel.findById(params.communityId);
const platform = community?.riotPlatform ?? 'kr';
const region = community?.riotRegion ?? 'asia';

const limit = pLimit(3);
await Promise.allSettled(
  order.map(p => limit(() => this.enrichmentService.enrichRiotAccount({
    userId: p.userId,
    puuid: p.puuid,
    options: { platform, region, force: false },
  }))),
);

prefetch.scheduler 는 사용자별 community 를 cursor 단계에서 함께 로드 (또는 community → user 양방향 join).

2.5.2 0-state UX (사용자 결정: 적당히 제안)

상황 표시
overall.games === 0 (enrichment 실패 또는 신규 사용자) "최근 솔로랭크 기록이 없습니다" placeholder
주 라인(mainPosition) 게임 ≥ 1 헤더에 주 라인 통계 강조 표시
주 라인 게임 = 0, 다른 라인 있음 헤더에 overall 통계 + "주 라인 기록 없음 / 전체 기준" 보조 라벨
라인별 미니 row 게임 ≥ 1 라인은 W-L · KDA · CS/min, 0 게임 라인은 회색 dash

2.6 트리거 시점

시점 호출 방식 force
신규 RiotAccount 등록 (dakao 명령) 동기 enrich 호출 true
사용자 수동 갱신 (Phase2 엔드포인트 추가됨) 동기 호출 true
경매 start 직전 참가자 puuid 일괄 enrich (p-limit 적용, §2.7 throttle 참조) false
야간 스케줄러 (Phase 2 후속) force=false 로 stale 만 갱신 false

→ 본 플랜에서는 트리거 4개 지점만 호출 추가. 스케줄러는 Phase 2 트랙에서 처리.

2.7 Rate Limit / Throttle (개인키 가정)

전제: 개인 API 키 — Riot 공식 한도 20 req / 1s + 100 req / 120s (앱 단위, region 별).

A. 사전 차단 — RiotClientService 통합 throttle

모든 Riot 호출이 RiotClientService.get() 을 통과하므로 여기에 한 곳에서 게이트를 건다. Garnet 기반 sliding-window 로 다중 인스턴스 안전성 확보.

키 구조:

riot:rl:<region>:1s    -- ZSET (score=timestampMs, member=uuid)
riot:rl:<region>:120s  -- ZSET (동일)

호출 시 의사코드:

async function acquire(region: string): Promise<void> {
  const now = Date.now();
  for (;;) {
    const wait = await checkAndAdd(region, now); // Lua script 추천
    if (wait === 0) return;
    await sleep(wait);
  }
}

checkAndAdd 는 Lua script 1회 호출(원자성):

  1. ZREMRANGEBYSCORE key 0 (now - windowMs) 로 윈도우 밖 제거
  2. ZCARD key 로 현재 카운트
  3. 한도 초과 시 ZRANGE key 0 0 WITHSCORES 로 가장 오래된 항목의 만료 시각 → 대기 시간 반환
  4. 가능하면 ZADD key now uuid + EXPIRE key windowMs 후 0 반환

두 윈도우(1s/120s) 모두 통과해야 진행. 하나라도 막히면 더 큰 wait 반환.

apps/api/src/modules/riot/riot-rate-limiter.service.ts 신규:

@Injectable()
export class RiotRateLimiterService {
  constructor(private readonly garnet: GarnetService) {}
  public async acquire(region: RiotRegionalRoute | RiotPlatformRoute): Promise<void>;
  // 옵션: per-method 한도 추가 시 추가 인자
}

설정 상수(코드 상수, 환경변수화 안 함):

const APP_LIMITS = [
  { windowMs: 1_000, max: 20 },
  { windowMs: 120_000, max: 100 },
];

안전 마진을 위해 max 를 18 / 95 로 살짝 낮추는 옵션을 코드 주석으로 남김 — 다른 클라이언트(예: 로컬 개발기)와 키를 공유할 때 충돌 방지.

B. 사후 처리 — 429 backoff

RiotClientService.get() 응답이 429 일 때:

  1. 기존 Retry-After 캡처 로직(riot.client.service.ts:125) 활용
  2. Retry-After 만큼 대기 후 최대 1회 재시도
  3. 재시도도 429 면 RiotApiError throw (현재 동작 유지)

C. 클라이언트단 동시성 제한

Auction start 트리거에서 5명 동시 enrichment × (1 list + 최대 20 detail) = burst 가 가장 큼. 사전 차단만으로도 Riot 한도는 지켜지지만, 처리 시간이 길어지므로 fairness 를 위한 동시성 한도 도 추가:

  • p-limit 의존성 추가 (pnpm --filter api add p-limit)
  • enrichment service 내부에서 recentMatches 페치 시 detail 호출을 pLimit(2) 로 직렬화
  • auction.service 트리거에서도 사용자별 enrichment 자체에 pLimit(3) 적용

D. 메서드 한도(Method Rate Limit)

Match-V5 getMatch 는 2000 req / 10s 라 앱 한도가 먼저 걸린다 — 본 플랜에서는 method 한도는 별도 추적 안 함. 추후 다른 method 추가 시 RiotRateLimiterService 가 method 단위 카운터도 받도록 확장.

E. 운영 가시성

  • RiotRateLimiterService.acquire() 가 100ms 이상 대기하면 logger.warn (throttle 발생 추적)
  • 응답 헤더 X-App-Rate-Limit-Count 를 매 호출마다 디버그 로그(샘플링) → 실제 사용량 vs 우리 카운터 drift 확인

3. 변경 사항 (파일 단위)

3.1 신규: apps/api/src/modules/riot/riot-recent-matches.service.ts

@Injectable()
export class RiotRecentMatchesService {
  constructor(
    private readonly connectionService: ConnectionService,
    private readonly matchService: RiotMatchService,
    private readonly garnetService: GarnetService,
  ) {}

  /** queue=420 기준 최근 N matchId 동기화 + raw 저장. 새로 가져온 RiotMatch 도큐먼트들 반환 */
  public async syncRecentMatches(params: {
    puuid: string;
    region?: RiotRegionalRoute;
    limit?: number;          // 기본 20
    queueId?: number;        // 기본 420
  }): Promise<RiotMatchDocument[]>;

  /** DB 에서 puuid 기준 최근 N matchInfo 조회 (API 호출 없음) */
  public async loadFromDb(params: {
    puuid: string;
    limit?: number;
    queueId?: number;
  }): Promise<RiotMatchDocument[]>;
}

핵심 로직:

  1. getMatchIdsByPuuid({queue, count, region: 'asia'})
  2. 받은 ids 를 riot_match.find({matchId: {$in: ids}}, {matchId: 1}) 로 존재 여부 조회
  3. 없는 것만 getMatch(matchId) → upsert (updateOne({matchId}, {$setOnInsert: {...}}, {upsert: true}))
  4. Garnet 락: riot:enrich:matches:<puuid> NX EX 60. 락 획득 실패 시 즉시 return DB 캐시.
  5. queueId 필터: list API 의 queue 파라미터로 한 번 거르고, detail 응답의 info.queueId 로 한 번 더 검증.

3.2 신규: RiotRecentStatsService (또는 위 service에 합쳐도 OK)

public computeSummary(matches: RiotMatchDto[], puuid: string): RiotRecentStatsSummary;
  • 순수 함수. 단위 테스트 추가(*.spec.ts).
  • 입력 매치에서 info.participants.find(p => p.puuid === puuid) 로 본인 participant 찾기.
  • 라인 결정: teamPosition || individualPosition. 빈 값이면 byLane 집계에서 제외하되 overall 에는 포함.
  • 0경기 입력 시 overall 은 모든 수치 0 으로 채운 객체, byLane 은 빈 객체 {}. 클라 NaN 회피.
  • avgCsPerMin = ((totalMinionsKilled + neutralMinionsKilled) / (gameDuration / 60)) 의 평균. gameDuration 은 초 단위.

3.3 riot-account-enrichment.service.ts 확장

EnrichOptions 에 recentMatchesTtlMs (기본 6h) 추가. EnrichResult 에 recentMatches: 'updated' | 'fresh' | 'failed' 추가.

doEnrichRiotAccount 에:

const recentMatchesStale =
  force ||
  !account.recentStatsFetchedAt ||
  now - account.recentStatsFetchedAt.getTime() > recentMatchesTtl;

const recentOutcome = recentMatchesStale
  ? await this.fetchRecentMatchesSafe(params.puuid, region)
  : { status: 'fresh' as const, summary: null };

if (recentOutcome.status === 'updated' && recentOutcome.summary) {
  account.recentStatsSummary = recentOutcome.summary;
  account.recentStatsFetchedAt = new Date();
  account.matchIds = recentOutcome.matchIds;
  account.matchIdsFetchedAt = new Date();
}

fetchRecentMatchesSafe:

  1. recentMatchesService.syncRecentMatches({puuid, region})
  2. recentMatchesService.loadFromDb({puuid, limit: 20, queueId: 420})
  3. computeSummary(matches, puuid)
  4. 실패 시 failed 반환 (기존 patterns와 동일).

3.4 riot.module.ts

RiotRecentMatchesService, RiotRateLimiterService 를 providers/exports 에 추가. GarnetModule 은 @Global 이라 별도 import 불필요.

3.4.1 riot.client.service.ts 변경

  • 생성자에 RiotRateLimiterService 주입.
  • get() 진입 시 await this.rateLimiter.acquire(options.platform ?? options.region ?? 'asia').
  • 응답이 429 일 때 Retry-After 캡처 후 await sleep(retryAfterMs) → 한 번 재시도. 재시도도 429 면 throw.
  • (기존 동작과의 차이: throttle/재시도 추가, 그 외 인터페이스 동일.)

3.5 트리거 지점

  • apps/api/src/modules/dakao/dakao-user.service.ts: 신규 RiotAccount 등록 직후 enrichRiotAccount({force: true}) 호출 흐름이 이미 있는지 확인하고 동일 흐름 유지(별도 호출 추가 불필요).
  • apps/api/src/modules/auction/auction.service.ts:start: order 구성 직후, 참가자 puuid 들에 대해 p-limit(3) 으로 동시성 제한:
    const limit = pLimit(3);
    await Promise.allSettled(
      order.map(p => limit(() => this.enrichmentService.enrichRiotAccount({
        userId: p.userId, puuid: p.puuid, options: {force: false}
      }))),
    );
    
    이미 fresh 면 즉시 return 이라 비용 거의 없음. throttle 은 RiotClientService 단에서 추가로 보호.

3.6 수동 갱신 엔드포인트

Phase 2 플랜의 POST /me/riot-accounts/:puuid/refresh 가 추가되면 동일 enrichment 가 호출되므로, 본 플랜에서 별도 엔드포인트는 만들지 않고 Phase 2 와 합류.

3.7 클라 — 변경 큼

types.ts

export interface ApiRiotLaneStats {
  games: number;
  wins: number;
  losses: number;
  avgKills: number;
  avgDeaths: number;
  avgAssists: number;
  avgCs: number;
  avgCsPerMin: number;
  mostPlayedChampionIds: string[];
}

export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY';

export interface ApiRiotRecentStatsSummary {
  overall: ApiRiotLaneStats;
  byLane: Partial<Record<RiotLane, ApiRiotLaneStats>>;
}

기존 flat 필드는 제거. 클라는 enrichment 한 번 돌고 난 새 구조 가정.

mappers.ts

AuctionPlayerView.recentStats 를 새 구조로 정렬. 추가로 pickPrimary(stats, mainPosition) 헬퍼:

const POSITION_TO_LANE: Record<Position, RiotLane> = {
  TOP: 'TOP', JGL: 'JUNGLE', MID: 'MIDDLE', ADC: 'BOTTOM', SUP: 'UTILITY',
};

function pickPrimary(summary, mainPosition) {
  const lane = POSITION_TO_LANE[mainPosition];
  const lanePrimary = summary.byLane[lane];
  if (lanePrimary && lanePrimary.games > 0) return { stats: lanePrimary, source: 'lane' };
  if (summary.overall.games > 0) return { stats: summary.overall, source: 'overall' };
  return { stats: null, source: 'none' };
}

AuctionPage.tsx — "최근 솔로랭크" 카드 재설계

┌ 최근 솔로랭크 ─ 미드 ───────┐  ← 헤더에 표시 기준 라인
│ 승률 56% · 28W 22L          │
│ KDA 7.1/3.4/8.2 (4.50)      │
│ 분당 CS 7.2                 │
├──────────────────────────── │
│ 탑   2W 1L · 5.0/3.3/4.7    │  ← byLane 미니 row
│ 정글 —                       │  ← 0 게임 dash
│ 미드 25W 19L · 7.1/3.4/8.2  │  ← 강조
│ 바텀 —                       │
│ 서폿 1W 2L · 1.0/4.0/15.7   │
└─────────────────────────────┘
  • 헤더: pickPrimary 결과의 stats + source === 'overall' 이면 "(전체 기준)" 보조 라벨.
  • 미니 row: 5개 라인 고정 순서 (TOP/JGL/MID/ADC/SUP), 게임 0 인 라인은 회색 dash, 주 라인은 텍스트 굵게.
  • pickPrimary 결과가 none 이면 placeholder ("최근 솔로랭크 기록이 없습니다").
  • KDA Perfect 처리(deaths=0) 는 기존 로직 유지.

신규 컴포넌트 분리 권장: RecentSoloStats 별 파일이 깔끔.

3.8 신규: 야간 prefetch 스케줄러 (5슬롯 분산)

@nestjs/schedule 의존성 추가 (pnpm --filter api add @nestjs/schedule). app.module 에 ScheduleModule.forRoot() 등록.

슬롯 분산 정책 (사용자 결정 2026-04-26)

  • 03/04/05/06/07 시 KST 5개 슬롯 으로 분산.
  • 사용자 그룹핑: userId.hash % 5 로 슬롯 결정 (decimal index 04 → 03시07시 매핑).
  • 안전 마진: 각 슬롯 종료 ≤ 다음 슬롯 시작 (1시간 안에 처리 끝나야). 활성 사용자 100명 / 5슬롯 = 20명/슬롯, throttle 100req/120s 안에서 충분.
  • 슬롯별 Garnet 락 키 분리: riot:cron:nightly-prefetch:slot-<idx> (NX EX 50m). 다중 인스턴스 leader election + 슬롯 간 독립 실행.
@Injectable()
export class RiotPrefetchScheduler {
  private readonly logger = new Logger(RiotPrefetchScheduler.name);
  private readonly LOCK_TTL_S = 50 * 60;
  private readonly STALE_THRESHOLD_MS = 24 * 60 * 60 * 1000;
  private readonly SLOTS = 5;
  private readonly USER_CAP_PER_SLOT = 1000;

  constructor(
    private readonly connectionService: ConnectionService,
    private readonly enrichment: RiotAccountEnrichmentService,
    private readonly garnet: GarnetService,
  ) {}

  // 03,04,05,06,07 시 매시 정각
  @Cron('0 0 3-7 * * *', { timeZone: 'Asia/Seoul' })
  async runSlot() {
    const hour = new Date().getHours(); // KST 가정 (TZ 환경 일치 필요)
    const slotIndex = hour - 3; // 0..4
    if (slotIndex < 0 || slotIndex >= this.SLOTS) return;

    const lockKey = `riot:cron:nightly-prefetch:slot-${slotIndex}`;
    const acquired = await this.garnet.setStringIfAbsent(
      lockKey,
      `${process.pid}-${Date.now()}`,
      this.LOCK_TTL_S,
    );
    if (!acquired) {
      this.logger.log(`Slot ${slotIndex} skipped — lock held by another instance.`);
      return;
    }

    await this.processSlot(slotIndex);
  }

  private async processSlot(slotIndex: number) {
    const cutoff = new Date(Date.now() - this.STALE_THRESHOLD_MS);
    const UserModel = await this.connectionService.getModel('user');
    const CommunityModel = await this.connectionService.getModel('community');

    const cursor = UserModel.find({
      'riotAccounts.recentStatsFetchedAt': { $lt: cutoff },
    }).cursor();

    const limit = pLimit(2);
    let processed = 0;
    for await (const user of cursor) {
      // 슬롯 분산: hash(userId) % SLOTS
      if (this.slotOfUser(user._id.toString()) !== slotIndex) continue;

      const community = await CommunityModel.findById(user.communityId).lean();
      const platform = community?.riotPlatform ?? 'kr';
      const region = community?.riotRegion ?? 'asia';

      for (const account of user.riotAccounts) {
        const seasonStart = community?.seasonStartedAt;
        const seasonStale =
          !!seasonStart &&
          (!account.recentStatsFetchedAt ||
            account.recentStatsFetchedAt < seasonStart);
        const ttlStale =
          !account.recentStatsFetchedAt || account.recentStatsFetchedAt < cutoff;
        if (!ttlStale && !seasonStale) continue;

        await limit(() =>
          this.enrichment
            .enrichRiotAccount({
              userId: user._id,
              puuid: account.puuid,
              options: { platform, region, force: seasonStale },
            })
            .catch((err) =>
              this.logger.warn(`prefetch failed ${account.puuid}: ${err}`),
            ),
        );
        processed += 1;
      }
      if (processed >= this.USER_CAP_PER_SLOT) break;
    }

    this.logger.log(`Slot ${slotIndex} processed ${processed} accounts.`);
  }

  private slotOfUser(userId: string): number {
    // FNV-1a 32bit — 외부 의존성 없이 안정적 분산
    let h = 2166136261;
    for (let i = 0; i < userId.length; i += 1) {
      h ^= userId.charCodeAt(i);
      h = Math.imul(h, 16777619);
    }
    return Math.abs(h) % this.SLOTS;
  }
}

동작 요약

  • leader election: 슬롯별 Garnet NX 락. 다중 인스턴스 중 첫 도달자만 처리.
  • 사용자 분산: FNV-1a 해시로 결정적 분산 (같은 사용자는 항상 같은 슬롯). region 분포가 편향되어도 슬롯별 부하는 균일.
  • throttle 합류: enrichment 호출이 RiotRateLimiterService 통과 → 별도 sleep 불필요.
  • community-aware: cursor 안에서 community 조회로 platform/region/seasonStartedAt 적용.
  • 시즌 force fetch: seasonStartedAt > recentStatsFetchedAt 면 TTL 무시.
  • 안전 상한: 슬롯당 1000 사용자 cap.
  • TZ 주의: @Cron 의 timeZone 옵션은 cron 발화에만 영향. new Date().getHours() 는 process TZ 따라가므로 운영 환경의 TZ=Asia/Seoul 보장 또는 명시 변환 필요. 안전한 대안은 슬롯별 cron 5개 정의 (각 cron 안에서 slotIndex 상수 박기).

더 안전한 변형 (권장)

@Cron('0 0 3 * * *', { timeZone: 'Asia/Seoul' }) async slot0() { return this.processSlot(0); }
@Cron('0 0 4 * * *', { timeZone: 'Asia/Seoul' }) async slot1() { return this.processSlot(1); }
@Cron('0 0 5 * * *', { timeZone: 'Asia/Seoul' }) async slot2() { return this.processSlot(2); }
@Cron('0 0 6 * * *', { timeZone: 'Asia/Seoul' }) async slot3() { return this.processSlot(3); }
@Cron('0 0 7 * * *', { timeZone: 'Asia/Seoul' }) async slot4() { return this.processSlot(4); }

→ TZ 의존성 제거, 슬롯 매핑 명확.

테스트:

  • 락 미획득 시 즉시 return 검증
  • stale cutoff 기준 정확히 필터링되는지 fixture 기반 검증
  • (실제 cron 발화는 e2e 범위 외 — 메서드 직접 호출 테스트로 충분)

4. 단위 테스트

  • apps/api/src/modules/riot/riot-recent-matches.service.spec.ts
    • computeSummary: 0경기 / 단일경기(승) / 5경기 mix / 같은 챔피언 빈도 상위 3개 정렬 검증
    • 라인별 집계: 미드 3경기 + 정글 2경기 fixture → byLane.MIDDLE.games === 3, byLane.JUNGLE.games === 2
    • 빈 teamPosition: fallback to individualPosition, 둘 다 비면 byLane 에는 안 들어가도 overall 에는 포함
    • avgCsPerMin: gameDuration 1500s + cs 200 → 분당 8.0
    • 같은 puuid 가 detail.participants 에 없는 경우 → 해당 매치 skip
  • apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts 확장
    • recentMatches outcome 분기 커버 (stale/fresh/failed)
  • apps/api/src/modules/riot/riot-rate-limiter.service.spec.ts
    • 1초 윈도우 한도 도달 시 다음 호출이 대기하는지 (Garnet은 ioredis-mock 또는 실제 컨테이너)
    • 120초 윈도우만 막히는 경우 — 더 큰 wait 반환 검증
    • 다중 region (asia/kr) 키가 분리되어 서로 영향 없는지
  • apps/api/src/modules/riot/riot-prefetch.scheduler.spec.ts
    • 락 미획득 시 enrichment 호출 0회
    • cutoff 보다 fresh 한 account 는 skip
    • 1000 사용자 cap 동작
    • 슬롯 분산: 동일 userId 의 slotOfUser 가 항상 동일 값 반환, 1000 사용자 분포 편차 < 30%
    • 시즌 force: community.seasonStartedAt > recentStatsFetchedAt 시 force=true 로 enrichment 호출
    • community 의 riotPlatform/riotRegion 이 옵션에 정확히 전달되는지

5. Rollout

  1. (PR-1) RiotRateLimiterService + Lua sliding-window + 테스트, RiotClientService 통합. 이게 먼저 깔려야 다른 PR 의 enrichment 가 안전.
  2. (PR-2) RiotRecentMatchesService + computeSummary 라인별 집계 + 테스트, schema 신규 타입 정의
  3. (PR-3) RiotAccountEnrichmentService 에 통합 + p-limit 의존성 추가 + auction.service 트리거
  4. (PR-4) 클라 types/mapper/AuctionPage 카드 재설계 (RecentSoloStats 컴포넌트)
  5. (PR-5) RiotPrefetchScheduler + @nestjs/schedule 의존성 + Garnet leader election
  6. (PR-6) 운영 모니터링 로그 (throttle wait, X-App-Rate-Limit-Count drift, prefetch 처리 건수)
  7. (Phase 2 합류) 수동 갱신 엔드포인트

6. 추가로 고려해야 할 점 (확정 / 미결)

확정 (사용자 결정 2026-04-26)

  • API 키 등급: 개인키 → §2.7 throttle 구현 필수.
  • 윈도우 크기: 20경기 고정 (환경변수화 안 함).
  • RiotMatch 보관: 무한 저장. TTL/prune 없음.
  • 자유랭크/노말 미포함: queue=420 솔로랭크 only.
  • 라인별 데이터 구분: §2.5 의 byLane 구조 + AuctionPage 카드 재설계 (§3.7).
  • lane 보정 = 분당 CS (avgCsPerMin).
  • 0-state UX: §2.5.2 표 적용.
  • 야간 prefetch 스케줄러: §3.8 — 03/04/05/06/07 시 KST 5슬롯 분산, 사용자 hash 로 결정적 분산, 슬롯별 Garnet 락.
  • championId 타입 통일: §2.5.3 — Riot DTO 와 동일 number 로 통일. mostPlayedChampionIds: number[].
  • 시즌 경계 자동 리셋: §2.5.4 — Community.seasonStartedAt 추가. 운영자 수동 등록 + enrichment 자동 force fetch + 매치 필터링.
  • 다국가 region 지원 구조: §2.5.5 — Community.riotPlatform/riotRegion 활용, 호출자가 옵션에 주입. 기본값 kr/asia.
  • 외부 공유 OK — ACL 별도 처리 없음.

미결

(없음)


7. Done 정의

  • AuctionPage 의 "최근 솔로랭크" 카드가 0 이 아닌 실제 값을 표시 (테스트 사용자 1명 이상)
  • 카드에 라인별 미니 row 5줄(TOP/JGL/MID/ADC/SUP) 표시, 주 라인 강조
  • 0게임 사용자에게 placeholder ("최근 솔로랭크 기록이 없습니다") 표시 확인
  • 같은 사용자 재진입 시 6h 이내에는 Match-V5 호출 0 회 (서버 로그로 확인)
  • riot_match 컬렉션에 raw 저장 + participantPuuids 인덱스 hit 확인
  • Throttle 동작: 21+ calls 동시 발생 시 RiotRateLimiterService.acquire() wait 로그 발생, Riot 429 0건
  • 야간 03~07시 KST cron 5회 슬롯 발화, 슬롯별로 다른 사용자 집합 처리되는지 로그 확인
  • championId 가 schema/types/응답 전부에서 number 로 통일됨 (grep 으로 string 잔존 0건)
  • Community.seasonStartedAt 갱신 시 다음 enrichment 가 force fetch 되고, 시즌 이전 매치가 통계에서 제외됨
  • enrichment 호출이 community.riotPlatform/riotRegion 을 받아 동작 ('kr' 외 region 도 옵션 분기 가능)
  • 단위 테스트 통과 (라인별 집계 / throttle 윈도우 / scheduler 슬롯 분산 / 시즌 force / region 전달)
  • Phase 2 의 *FetchedAt 노출 패턴과 정합 (응답에 recentStatsFetchedAt 추가)