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

+673
View File
@@ -0,0 +1,673 @@
# 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 매핑
```ts
// 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',
};
```
#### 새 데이터 구조
```ts
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 추가
```ts
// 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 캐시로 분리 검토.
#### 호출 패턴
```ts
// 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 (동일)
```
호출 시 의사코드:
```ts
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` 신규:
```ts
@Injectable()
export class RiotRateLimiterService {
constructor(private readonly garnet: GarnetService) {}
public async acquire(region: RiotRegionalRoute | RiotPlatformRoute): Promise<void>;
// 옵션: per-method 한도 추가 시 추가 인자
}
```
설정 상수(코드 상수, 환경변수화 안 함):
```ts
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`
```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)
```ts
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` 에:
```ts
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)` 으로 동시성 제한:
```ts
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
```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)` 헬퍼:
```ts
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 0~4 → 03시~07시 매핑).
- 안전 마진: 각 슬롯 종료 ≤ 다음 슬롯 시작 (1시간 안에 처리 끝나야). 활성 사용자 100명 / 5슬롯 = 20명/슬롯, throttle 100req/120s 안에서 충분.
- 슬롯별 Garnet 락 키 분리: `riot:cron:nightly-prefetch:slot-<idx>` (NX EX 50m). 다중 인스턴스 leader election + 슬롯 간 독립 실행.
```ts
@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 상수 박기).
#### 더 안전한 변형 (권장)
```ts
@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` 추가)
@@ -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,
+60 -4
View File
@@ -12,6 +12,7 @@ import type {
MatchTeam,
Position,
PositionPreference,
RiotLane,
RiotRecentStatsSummary,
TierInfo,
} from './modules/global/database/schema';
@@ -82,7 +83,7 @@ type SeedPlayer = {
losses: number;
};
masteries: SeedChampionMastery[];
recentStatsSummary: RiotRecentStatsSummary;
recentStatsSummary: SeedRecentStatsSummary;
};
type SeedChampionMastery = {
@@ -92,6 +93,18 @@ type SeedChampionMastery = {
points: number;
};
type SeedRecentStatsSummary = {
games: number;
wins: number;
losses: number;
avgKills: number;
avgDeaths: number;
avgAssists: number;
avgCs: number;
avgCsPerMin?: number;
mostPlayedChampionIds: string[];
};
const DEV_COMMUNITY_NAME = '[DEV] Lolympus Test Community';
const DEV_COMMUNITY_DESCRIPTION =
'Frontend/Backend 통합 검증용으로 생성된 개발 커뮤니티입니다.';
@@ -129,6 +142,14 @@ const CHAMPION_IDS: Record<string, number> = {
Zeri: 221,
};
const POSITION_TO_RIOT_LANE: Record<Position, RiotLane> = {
TOP: 'TOP',
JGL: 'JUNGLE',
MID: 'MIDDLE',
ADC: 'BOTTOM',
SUP: 'UTILITY',
};
const PLAYER_SEEDS: SeedPlayer[] = [
{
key: 'priri',
@@ -635,7 +656,10 @@ function createRiotAccount(player: SeedPlayer) {
tiers,
tierHistory: [],
matchIds: [],
recentStatsSummary: player.recentStatsSummary,
recentStatsSummary: createRecentStatsSummary(
player.recentStatsSummary,
player.main,
),
recentStatsFetchedAt: NOW,
championMasteries: createChampionMasteries(puuid, player.masteries),
championMasteriesFetchedAt: NOW,
@@ -663,7 +687,8 @@ function createStaffRiotAccount(
tiers: [createTier(puuid, 'RANKED_SOLO_5x5', 'GOLD', 'I', 75, 24, 19)],
tierHistory: [],
matchIds: [],
recentStatsSummary: {
recentStatsSummary: createRecentStatsSummary(
{
games: 12,
wins: 7,
losses: 5,
@@ -672,7 +697,9 @@ function createStaffRiotAccount(
avgAssists: 7.4,
avgCs: 167,
mostPlayedChampionIds: ['Orianna', 'JarvanIV'],
},
},
'MID',
),
recentStatsFetchedAt: NOW,
championMasteries: createChampionMasteries(puuid, [
{
@@ -708,6 +735,35 @@ function createChampionMasteries(
}));
}
function createRecentStatsSummary(
input: SeedRecentStatsSummary,
mainPosition: Position,
): RiotRecentStatsSummary {
const lane = POSITION_TO_RIOT_LANE[mainPosition];
const championIds = input.mostPlayedChampionIds.map(
(championId) => CHAMPION_IDS[championId] ?? 0,
);
const laneStats = {
games: input.games,
wins: input.wins,
losses: input.losses,
avgKills: input.avgKills,
avgDeaths: input.avgDeaths,
avgAssists: input.avgAssists,
avgCs: input.avgCs,
avgCsPerMin:
input.avgCsPerMin ?? Math.round((input.avgCs / 28) * 10) / 10,
mostPlayedChampionIds: championIds,
};
return {
overall: laneStats,
byLane: {
[lane]: laneStats,
},
};
}
function toMatchParticipant(user: {
_id: mongoose.Types.ObjectId;
riotAccounts: Array<{
+69 -32
View File
@@ -5,9 +5,12 @@ import type {
ApiMatch,
ApiMatchParticipant,
ApiPositionPreference,
ApiRiotLaneStats,
ApiRiotRecentStatsSummary,
ApiTierInfo,
MatchStatus,
Position,
RiotLane,
TeamSide,
} from './types';
import { POSITION_ORDER, sideLabel } from '../lib/league';
@@ -63,15 +66,10 @@ export interface AuctionPlayerView extends ParticipantView {
points: number;
}[];
recentStats: {
games: number;
wins: number;
losses: number;
kda: {
kills: number;
deaths: number;
assists: number;
};
avgCs: number;
overall: ApiRiotLaneStats;
byLane: Partial<Record<RiotLane, ApiRiotLaneStats>>;
primary: ApiRiotLaneStats | null;
primarySource: 'lane' | 'overall' | 'none';
};
}
@@ -126,6 +124,37 @@ const TIER_NAMES: Record<string, string> = {
CHALLENGER: '챌린저',
};
const POSITION_TO_RIOT_LANE: Record<Position, RiotLane> = {
TOP: 'TOP',
JGL: 'JUNGLE',
MID: 'MIDDLE',
ADC: 'BOTTOM',
SUP: 'UTILITY',
};
function createEmptyLaneStats(): ApiRiotLaneStats {
return {
games: 0,
wins: 0,
losses: 0,
avgKills: 0,
avgDeaths: 0,
avgAssists: 0,
avgCs: 0,
avgCsPerMin: 0,
mostPlayedChampionIds: [],
};
}
function createEmptyRecentStatsView(): AuctionPlayerView['recentStats'] {
return {
overall: createEmptyLaneStats(),
byLane: {},
primary: null,
primarySource: 'none',
};
}
function sortPreferredPositions(preferredPositions: ApiPositionPreference[]) {
return [...preferredPositions].sort((left, right) => left.priority - right.priority);
}
@@ -163,6 +192,8 @@ function mapAuctionPlayerToView(
const { mainPosition, subPosition } = resolveMainAndSubPosition(
player.preferredPositions,
);
const summary = player.recentStatsSummary;
const primary = pickPrimary(summary, mainPosition);
return {
id: player.userId,
@@ -179,15 +210,10 @@ function mapAuctionPlayerToView(
points: mastery.championPoints,
})),
recentStats: {
games: player.recentStatsSummary?.games ?? 0,
wins: player.recentStatsSummary?.wins ?? 0,
losses: player.recentStatsSummary?.losses ?? 0,
kda: {
kills: player.recentStatsSummary?.avgKills ?? 0,
deaths: player.recentStatsSummary?.avgDeaths ?? 0,
assists: player.recentStatsSummary?.avgAssists ?? 0,
},
avgCs: Math.round(player.recentStatsSummary?.avgCs ?? 0),
overall: summary?.overall ?? createEmptyLaneStats(),
byLane: summary?.byLane ?? {},
primary: primary.stats,
primarySource: primary.source,
},
};
}
@@ -224,24 +250,12 @@ function mapAuctionTeamToView(
? {
...participant,
masteries: [],
recentStats: {
games: 0,
wins: 0,
losses: 0,
kda: { kills: 0, deaths: 0, assists: 0 },
avgCs: 0,
},
recentStats: createEmptyRecentStatsView(),
}
: {
...createFallbackParticipant(member.userId),
masteries: [],
recentStats: {
games: 0,
wins: 0,
losses: 0,
kda: { kills: 0, deaths: 0, assists: 0 },
avgCs: 0,
},
recentStats: createEmptyRecentStatsView(),
});
return {
@@ -274,6 +288,29 @@ export function formatKoreanDate(dateLike: string | Date) {
};
}
function pickPrimary(
summary: ApiRiotRecentStatsSummary | undefined,
mainPosition: Position,
): {
stats: ApiRiotLaneStats | null;
source: 'lane' | 'overall' | 'none';
} {
if (!summary) {
return { stats: null, source: 'none' };
}
const laneStats = summary.byLane[POSITION_TO_RIOT_LANE[mainPosition]];
if (laneStats && laneStats.games > 0) {
return { stats: laneStats, source: 'lane' };
}
if (summary.overall.games > 0) {
return { stats: summary.overall, source: 'overall' };
}
return { stats: null, source: 'none' };
}
export function selectPrimaryTier(tiers: ApiTierInfo[]) {
return tiers.find((tier) => tier.queueType === 'RANKED_SOLO_5x5') ?? tiers[0];
}
+9 -3
View File
@@ -1,4 +1,5 @@
export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY';
export type TeamSide = 'blue' | 'red';
export type MatchStatus =
| 'recruiting'
@@ -43,7 +44,7 @@ export interface ApiChampionMasteryEntry {
nextSeasonMilestone?: Record<string, unknown>;
}
export interface ApiRiotRecentStatsSummary {
export interface ApiRiotLaneStats {
games: number;
wins: number;
losses: number;
@@ -51,8 +52,13 @@ export interface ApiRiotRecentStatsSummary {
avgDeaths: number;
avgAssists: number;
avgCs: number;
mostPlayedChampionIds: string[];
extras?: Record<string, unknown>;
avgCsPerMin: number;
mostPlayedChampionIds: number[];
}
export interface ApiRiotRecentStatsSummary {
overall: ApiRiotLaneStats;
byLane: Partial<Record<RiotLane, ApiRiotLaneStats>>;
}
export interface ApiRiotAccount {
+132 -53
View File
@@ -20,12 +20,21 @@ import {
profileIconUrl,
} from '../lib/ddragon';
import { positionIcon, positionLabel } from '../lib/league';
import type { Position } from '../api/types';
import type { ApiRiotLaneStats, Position } from '../api/types';
function formatPoints(value: number) {
return value.toLocaleString();
}
const LANE_ROWS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
const POSITION_TO_RIOT_LANE = {
TOP: 'TOP',
JGL: 'JUNGLE',
MID: 'MIDDLE',
ADC: 'BOTTOM',
SUP: 'UTILITY',
} as const;
function PosBadge({ pos }: { pos: Position }) {
return (
<span className="inline-flex items-center gap-1.5 text-[11px] font-medium px-1.5 py-0.5 border border-primary/20 text-primary bg-primary/5">
@@ -49,6 +58,127 @@ function TimerBar({ timer, maxTimer }: { timer: number; maxTimer: number }) {
);
}
function getWinRate(stats: ApiRiotLaneStats) {
return stats.games > 0 ? Math.round((stats.wins / stats.games) * 100) : 0;
}
function getWinRateClass(winRate: number) {
if (winRate >= 55) return 'text-blue-400';
if (winRate >= 50) return 'text-base-content';
return 'text-red-400';
}
function formatKdaRatio(stats: ApiRiotLaneStats) {
if (stats.avgDeaths === 0) return 'Perfect';
return ((stats.avgKills + stats.avgAssists) / stats.avgDeaths).toFixed(2);
}
function RecentSoloStats({
player,
}: {
player: NonNullable<AuctionStateView['currentPlayer']>;
}) {
const primaryStats = player.recentStats.primary;
if (!primaryStats) {
return (
<div className="p-4">
<h4 className="text-[10px] font-bold uppercase tracking-wider text-base-content/30 mb-2.5">
최근 솔로랭크
</h4>
<div className="rounded border border-dashed border-base-content/10 px-3 py-6 text-center text-[11px] text-base-content/25">
최근 솔로랭크 기록이 없습니다
</div>
</div>
);
}
const primaryWinRate = getWinRate(primaryStats);
const primaryKdaRatio = formatKdaRatio(primaryStats);
return (
<div className="p-4">
<div className="flex items-start justify-between gap-3 mb-3">
<div>
<h4 className="text-[10px] font-bold uppercase tracking-wider text-base-content/30">
최근 솔로랭크
</h4>
<div className="mt-1 flex items-center gap-2">
<span className="text-[12px] font-semibold text-base-content">
{positionLabel[player.mainPosition]}
</span>
{player.recentStats.primarySource === 'overall' ? (
<span className="text-[10px] text-base-content/35">
전체 기준
</span>
) : null}
</div>
</div>
<div
className={`text-sm font-bold tabular-nums ${getWinRateClass(primaryWinRate)}`}
>
{primaryWinRate}%
</div>
</div>
<div className="space-y-2">
<div className="flex items-baseline justify-between">
<span className="text-[11px] text-base-content/40">전적</span>
<span className="text-[12px] text-base-content/60 tabular-nums">
<span className="text-blue-400">{primaryStats.wins}W</span>{' '}
<span className="text-red-400">{primaryStats.losses}L</span>
</span>
</div>
<div className="flex items-baseline justify-between">
<span className="text-[11px] text-base-content/40">KDA</span>
<span className="text-[12px] text-base-content/60 tabular-nums">
{primaryStats.avgKills}/{primaryStats.avgDeaths}/{primaryStats.avgAssists}
<span
className={`ml-1 font-bold ${Number(primaryKdaRatio) >= 3 ? 'text-emerald-400' : 'text-base-content/50'}`}
>
({primaryKdaRatio})
</span>
</span>
</div>
<div className="flex items-baseline justify-between">
<span className="text-[11px] text-base-content/40">분당 CS</span>
<span className="text-[12px] text-base-content/60 tabular-nums">
{primaryStats.avgCsPerMin}
</span>
</div>
</div>
<div className="mt-4 border-t border-base-content/8 pt-3 space-y-1.5">
{LANE_ROWS.map((position) => {
const laneStats =
player.recentStats.byLane[POSITION_TO_RIOT_LANE[position]];
const isMainLane = position === player.mainPosition;
return (
<div
key={position}
className={`flex items-center justify-between gap-3 text-[11px] ${isMainLane ? 'font-semibold text-base-content' : 'text-base-content/65'}`}
>
<span className={isMainLane ? 'text-base-content' : 'text-base-content/35'}>
{positionLabel[position]}
</span>
{laneStats && laneStats.games > 0 ? (
<span className="tabular-nums text-right">
{laneStats.wins}W {laneStats.losses}L · {laneStats.avgKills}/
{laneStats.avgDeaths}/{laneStats.avgAssists} ·{' '}
{laneStats.avgCsPerMin} CS/min
</span>
) : (
<span className="text-base-content/20">—</span>
)}
</div>
);
})}
</div>
</div>
);
}
function TeamPanel({
team,
isActive,
@@ -140,18 +270,6 @@ function PlayerSpotlight({
const player = state.currentPlayer;
if (!player) return null;
const winRate =
player.recentStats.games > 0
? Math.round((player.recentStats.wins / player.recentStats.games) * 100)
: 0;
const kdaRatio =
player.recentStats.kda.deaths > 0
? (
(player.recentStats.kda.kills + player.recentStats.kda.assists) /
player.recentStats.kda.deaths
).toFixed(2)
: 'Perfect';
return (
<div className="border border-base-content/10 bg-base-100">
<div className="p-5 border-b border-base-content/8">
@@ -233,46 +351,7 @@ function PlayerSpotlight({
</div>
</div>
<div className="p-4">
<h4 className="text-[10px] font-bold uppercase tracking-wider text-base-content/30 mb-2.5">
최근 솔로랭크
</h4>
<div className="space-y-2">
<div className="flex items-baseline justify-between">
<span className="text-[11px] text-base-content/40">승률</span>
<span
className={`text-sm font-bold tabular-nums ${winRate >= 55 ? 'text-blue-400' : winRate >= 50 ? 'text-base-content' : 'text-red-400'}`}
>
{winRate}%
</span>
</div>
<div className="flex items-baseline justify-between">
<span className="text-[11px] text-base-content/40">전적</span>
<span className="text-[12px] text-base-content/60 tabular-nums">
<span className="text-blue-400">{player.recentStats.wins}W</span>{' '}
<span className="text-red-400">{player.recentStats.losses}L</span>
</span>
</div>
<div className="flex items-baseline justify-between">
<span className="text-[11px] text-base-content/40">KDA</span>
<span className="text-[12px] text-base-content/60 tabular-nums">
{player.recentStats.kda.kills}/{player.recentStats.kda.deaths}/
{player.recentStats.kda.assists}
<span
className={`ml-1 font-bold ${Number(kdaRatio) >= 3 ? 'text-emerald-400' : 'text-base-content/50'}`}
>
({kdaRatio})
</span>
</span>
</div>
<div className="flex items-baseline justify-between">
<span className="text-[11px] text-base-content/40">평균 CS</span>
<span className="text-[12px] text-base-content/60 tabular-nums">
{player.recentStats.avgCs}
</span>
</div>
</div>
</div>
<RecentSoloStats player={player} />
</div>
{(state.phase === 'bidding' || state.phase === 'sold') && (