# 토너먼트 결과 수집 (우회) 플랜 > **대상**: codex 가 이어서 작업 가능한 수준의 실행 플랜 > **레포**: `/Users/dahyeon/source/lolympus-tournament-support` (pnpm workspace) > **작성 기준**: 2026-04-27 > **선행 작업**: > - `Tournament-Code-플랜.md` (코드 풀, `Match.tournamentCodeIds[]`, `Match.teamBuiltAt`, `TournamentCode.riotMatchId` 자리) > - `Riot-소환사전적-플랜.md` (Redis Stream 작업 큐 + leader election + throttle + ETA) > - `Riot-최근경기-플랜.md` (RiotRateLimiterService, RiotMatch 영구 저장) --- ## 1. Context 토너먼트 API 사용 권한이 없어 게임 종료 webhook 을 받을 수 없습니다. 우회로 다음을 구현합니다. 1. 매치가 `team-built` 으로 전환되면 결과 수집 작업이 큐에 enqueue. 2. **`match-v5 by-puuid?type=tourney&startTime=teamBuiltAt`** 폴링. 3. 응답 `info.tournamentCode` 를 우리 `TournamentCode.code` 와 매칭. 4. 매칭된 match-v5 의 **승팀/스코어/MVP 후보 / riotMatchIds** 를 우리 `Match.result` 로 변환. 5. 모든 게임 슬롯이 `used` 가 되면 `Match.status = 'finished'` 자동 전환. 본 plan 은 "선행 plan 의 §6 자리만 마련" 부분을 실제 모듈로 구현합니다. --- ## 2. 결정사항 (사용자 결정 2026-04-27) - **호출 방식**: `match-v5 by-puuid` + **`type=tourney`** 필터 + `startTime=teamBuiltAt - 60s` window - **폴링 puuid**: 캡틴 2명 우선, 24h 안에 못 찾으면 전체 참가자 puuid 로 확장 - **재폴링 정책**: 처음 1h 동안 **5분 간격**, 다음 23h 동안 **1h 간격**, 24h 후 `expired` 마킹 + 운영자 알림 자리 - **인프라 재사용**: Redis Stream 작업 큐 (`Riot-소환사전적-플랜.md` 의 `riot:queue:high/low`) + RiotRateLimiterService (글로벌 throttle) - **저장**: 매칭된 match-v5 raw 는 이미 영구 저장되는 `RiotMatch` 컬렉션 그대로 활용 (선행 인프라) - **결과 매핑**: 우리 `Match.teams[].members[].userId` ↔ match-v5 `info.participants[].puuid` ↔ `User.riotAccounts[].puuid` 로 양 팀 결정 --- ## 3. 데이터 모델 보강 ### 3.1 Match.result 확장 ```ts // schema.ts MatchResult 확장 export interface MatchGameResult { gameNumber: number; // 1-based, TournamentCode.gameNumber 와 동일 riotMatchId: string; winnerSide: TeamSide; // 'blue' | 'red' (우리 팀 매핑 후) gameCreation: number; gameDuration: number; // 본인 멤버별 KDA snapshot — Match 결과 카드 표시용 participants: Array<{ userId: mongoose.Types.ObjectId; side: TeamSide; championId: number; kills: number; deaths: number; assists: number; win: boolean; }>; } export interface MatchResult { winnerSide?: TeamSide; // 시리즈 최종 승팀 (BO3: 2승 한 팀). 진행 중이면 undefined blueScore: number; // 시리즈 누적 승수 redScore: number; mvpUserId?: mongoose.Types.ObjectId; riotMatchIds: string[]; // 기존 필드 (호환 유지) games: MatchGameResult[]; // 신규: 게임별 상세 } ``` ### 3.2 TournamentCode.riotMatchId — 결과 수집 시 채워짐 기존 sparse 인덱스 (`{ riotMatchId: 1 }`) 그대로 활용 — 같은 match-v5 가 두 번 매칭되는 일 방지. ### 3.3 신규: TournamentResultPollState (선택) 폴링 진척 상태 추적용 별도 컬렉션 또는 `Match.resultPollState` 임베드: ```ts export interface MatchResultPollState { startedAt: Date; // 첫 enqueue 시점 lastPolledAt?: Date; lastPollOutcome?: 'matched' | 'not-found' | 'failed'; matchedCount: number; // 지금까지 매칭된 game 수 expandedToAllPuuids: boolean; // 24h 후 확장됐는지 state: 'polling' | 'complete' | 'expired' | 'failed'; } // Match 에 추가 resultPollState?: MatchResultPollState; ``` → 별도 컬렉션 보다 임베드가 join 0회로 단순. `Match` 안에 둬도 1개 도큐먼트당 작은 크기. --- ## 4. 작업 큐 통합 ### 4.1 신규 stream/job 타입 선행 plan 의 작업 큐 (`riot:queue:high`, `riot:queue:low`) 그대로 사용. 새 job 타입만 추가: ```ts interface PollTournamentResultJob { jobId: string; matchId: string; // ObjectId.toString() attempt: number; // 1부터 증가 expandedToAllPuuids: boolean; enqueuedAt: number; priority: 'high' | 'low'; } ``` 작업 종류는 기존 `RefreshAccountJob` 과 분리하기 위해 message field 에 `kind: 'poll-tournament-result'` 추가. worker 가 kind 별 dispatch. ### 4.2 enqueue 트리거 | 시점 | 호출 위치 | priority | |---|---|---| | `team-built` 전환 직후 | `auction.service.ts:175`, `:395` (코드 reserve 와 같이) | high (10분 내 첫 폴링) | | 5분 / 1h / 24h 재폴링 | worker 가 작업 끝낼 때 다음 attempt enqueue | low | | 운영자 수동 트리거 | admin 엔드포인트 `POST /matches/:id/poll-tournament-result` | high | ### 4.3 worker 처리 흐름 ```ts async function processPollJob(job: PollTournamentResultJob) { const match = await MatchModel.findById(job.matchId); if (!match || match.status === 'finished') return; // 이미 끝남 const codes = await TournamentCodeModel.find({ matchId: match._id }).sort({ gameNumber: 1 }); const unmatched = codes.filter((c) => c.state === 'reserved' && !c.riotMatchId); if (unmatched.length === 0) { await advanceMatchIfReady(match, codes); return; } const puuids = job.expandedToAllPuuids ? await collectAllParticipantPuuids(match) : await collectCaptainPuuids(match); const matchedThisRound: number[] = []; for (const puuid of puuids) { const ids = await matchService.getMatchIdsByPuuid(puuid, { type: 'tourney', startTime: Math.floor((match.teamBuiltAt!.getTime() - 60_000) / 1000), endTime: Math.floor(Date.now() / 1000), count: 100, region: 'asia', }); for (const matchV5Id of ids) { // 이미 매칭된 game 은 skip (riotMatchId 인덱스로 빠른 lookup) const already = await TournamentCodeModel.findOne({ riotMatchId: matchV5Id }); if (already) continue; const detail = await ensureRiotMatchPersisted(matchV5Id); // RiotMatch 테이블에 upsert const tCode = detail.info.tournamentCode; if (!tCode) continue; const code = unmatched.find((c) => c.code === tCode); if (!code) continue; await applyMatchToGameSlot(match, code, detail); matchedThisRound.push(code.gameNumber!); } } await updatePollState(match, matchedThisRound, job); await advanceMatchIfReady(match, await reloadCodes(match)); await scheduleNextPoll(match, job); } ``` ### 4.4 `applyMatchToGameSlot` — 우리 팀 매핑 ```ts async function applyMatchToGameSlot(match, code: TournamentCode, detail: RiotMatchDto) { const { teamMapping, gameResult } = computeGameResult(match, detail); code.state = 'used'; code.usedAt = new Date(detail.info.gameCreation); code.riotMatchId = detail.metadata.matchId; await code.save(); match.result = match.result ?? { blueScore: 0, redScore: 0, riotMatchIds: [], games: [] }; match.result.games.push(gameResult); match.result.riotMatchIds = [ ...new Set([...match.result.riotMatchIds, detail.metadata.matchId]), ]; if (gameResult.winnerSide === 'blue') match.result.blueScore += 1; else match.result.redScore += 1; await match.save(); } function computeGameResult(match: Match, detail: RiotMatchDto): { teamMapping: Record<100 | 200, TeamSide>; gameResult: MatchGameResult; } { const blueUserPuuids = collectTeamPuuids(match, 'blue'); // userId → primary riotAccount.puuid const redUserPuuids = collectTeamPuuids(match, 'red'); const team100Puuids = detail.info.participants.filter((p) => p.teamId === 100).map((p) => p.puuid); const team200Puuids = detail.info.participants.filter((p) => p.teamId === 200).map((p) => p.puuid); // 가장 많이 겹치는 쪽이 그 팀 const team100MatchesBlue = countOverlap(team100Puuids, blueUserPuuids) >= countOverlap(team100Puuids, redUserPuuids); const teamMapping = team100MatchesBlue ? { 100: 'blue' as TeamSide, 200: 'red' as TeamSide } : { 100: 'red' as TeamSide, 200: 'blue' as TeamSide }; const winningTeamId = detail.info.teams.find((t) => t.win)!.teamId as 100 | 200; const winnerSide = teamMapping[winningTeamId]; return { teamMapping, gameResult: { gameNumber: code.gameNumber!, riotMatchId: detail.metadata.matchId, winnerSide, gameCreation: detail.info.gameCreation, gameDuration: detail.info.gameDuration, participants: detail.info.participants .map((p) => { const userId = lookupUserIdByPuuid(match, p.puuid); if (!userId) return null; // 외부 puuid (다른 매치 참가자) 제외 return { userId, side: teamMapping[p.teamId as 100 | 200], championId: p.championId, kills: p.kills, deaths: p.deaths, assists: p.assists, win: p.win, }; }) .filter((p): p is NonNullable => p !== null), }, }; } ``` > 팀 매핑 시 우리 멤버가 1명도 안 겹치면 (잘못된 매칭) → game slot 적용 skip + 운영자 알림 자리. 정상 케이스에선 5명 모두 일치. ### 4.5 `advanceMatchIfReady` — finished 자동 전환 ```ts async function advanceMatchIfReady(match: Match, codes: TournamentCode[]) { if (codes.length < match.gameCount) return; if (!codes.every((c) => c.state === 'used' && c.riotMatchId)) return; match.status = 'finished'; // 시리즈 최종 승팀 = 우세 점수 if (match.result) { match.result.winnerSide = match.result.blueScore > match.result.redScore ? 'blue' : match.result.redScore > match.result.blueScore ? 'red' : undefined; } match.resultPollState = { ...match.resultPollState, state: 'complete' } as any; await match.save(); } ``` `mvpUserId` 자동 산정은 본 plan 범위 외 (Phase 후속). 현재는 운영자 수동 입력 가능 자리만 둠. ### 4.6 `scheduleNextPoll` — 재시도 cadence ```ts function nextPollDelayMs(attempt: number, startedAt: Date): number | null { const elapsedMs = Date.now() - startedAt.getTime(); if (elapsedMs > 24 * 3600_000) return null; // 24h 후 종료 if (elapsedMs <= 1 * 3600_000) return 5 * 60_000; // 1h 동안 5분 간격 return 60 * 60_000; // 그 후 1h 간격 } async function scheduleNextPoll(match: Match, job: PollTournamentResultJob) { const delay = nextPollDelayMs(job.attempt, match.resultPollState!.startedAt); if (delay === null) { await markExpired(match); return; } await jobQueue.enqueue({ kind: 'poll-tournament-result', matchId: match._id.toString(), attempt: job.attempt + 1, expandedToAllPuuids: shouldExpand(job, match), priority: 'low', deferUntil: Date.now() + delay, // §4.7 참고 }); } ``` `shouldExpand`: `elapsedMs > 1h && matchedCount === 0` 또는 `elapsedMs > 24h - 1h` 시점부터 모든 puuid 사용. ### 4.7 deferUntil — 지연 enqueue Redis Stream 자체는 schedule 미지원. 대안: - (a) **Garnet ZSET** `riot:queue:scheduled` — score=실행시각ms. 별도 cron `@Interval(5_000)` 가 `ZRANGEBYSCORE 0 now` 항목을 꺼내 stream 으로 옮김. - (b) NATS JetStream `expires`/`headers.Nats-Delay` — JetStream 활성화 부담. → (a) 채택. 작은 헬퍼 `RiotJobScheduler.scheduleAt(deferUntilMs, payload)` 한 곳에서 관리. ### 4.8 만료 마킹 + 운영자 알림 자리 ```ts async function markExpired(match: Match) { match.resultPollState = { ...match.resultPollState, state: 'expired' } as any; await match.save(); // 알림 자리 — Phase 후속에서 dakao bot publish this.logger.warn(`Tournament result polling expired for match ${match._id}`); } ``` --- ## 5. 변경 사항 (파일 단위) ### 5.1 백엔드 ``` apps/api/src/modules/tournament-result/ tournament-result.module.ts tournament-result.service.ts # processPollJob / applyMatchToGameSlot / advanceMatchIfReady tournament-result.worker.ts # 작업 큐 dispatch (kind=poll-tournament-result) tournament-result.controller.ts # POST /matches/:id/poll-tournament-result (admin 수동) tournament-result.types.ts team-mapping.util.ts # collectTeamPuuids / countOverlap / lookupUserIdByPuuid game-result.util.ts # computeGameResult ``` `riot-job-queue.service.ts` (선행 plan): - `enqueue(payload, deferUntil?)` 시그니처에 `deferUntil` 옵션 추가 - worker 의 dispatch 에 `kind === 'poll-tournament-result'` 분기 추가 `auction.service.ts`: - `team-built` 전환 + `reserveForMatch` 직후 → `tournamentResultService.scheduleInitialPoll(match)` 호출 `match.service.ts` 의 `serializeMatch`: - `result.games[]` 응답에 포함 (gameNumber 정렬) ### 5.2 인덱스 보강 `RiotMatch` 컬렉션 인덱스 추가 (선행 plan 에 없으면): - `{ 'raw.info.tournamentCode': 1 }` sparse — match-v5 의 tournamentCode 로 reverse lookup 가능 (디버깅/admin) ### 5.3 프런트 #### MatchDetailPage 결과 표시 `apps/web/src/pages/MatchDetailPage.tsx`: - 기존 `match.result` 단일 score 표시 → `result.games[]` 게임별 표시: ``` 1경기 블루 ⓦ KR_xxxxx 28:14 2경기 레드 ⓦ KR_xxxxx 31:02 3경기 대기 중 최종 블루 2 - 1 레드 ``` - `match.status === 'in-progress'` 인 동안 부분 결과 점진 표시. - `result.games[].participants[]` 로 멤버별 KDA 표시 가능. #### types.ts ```ts export interface ApiMatchGameResult { gameNumber: number; riotMatchId: string; winnerSide: TeamSide; gameCreation: number; gameDuration: number; participants: Array<{ userId: string; side: TeamSide; championId: number; kills: number; deaths: number; assists: number; win: boolean; }>; } export interface ApiMatchResult { winnerSide?: TeamSide; blueScore: number; redScore: number; mvpUserId?: string; riotMatchIds: string[]; games: ApiMatchGameResult[]; } ``` #### admin 수동 트리거 버튼 매치 상세에 admin 만 보이는 "결과 다시 수집" 버튼 — `POST /matches/:id/poll-tournament-result` 호출 → 토스트 "수집 작업이 큐에 등록되었어요". --- ## 6. 단위 테스트 - `team-mapping.util.spec.ts` - 5명 모두 일치 → 정확한 매핑 - 4 vs 1 일치 → 다수쪽 매핑 - 0 일치 → null 반환 (skip) - `game-result.util.spec.ts` - winnerSide 정확 - participants 외부 puuid 제외 - `tournament-result.service.spec.ts` - 첫 폴링: 캡틴 puuid 만 사용 - 1h 경과 + 매치 0건 → expandedToAllPuuids=true - 24h 후 → markExpired - 모든 game slot used → match.status=finished, winnerSide 우세 계산 - 부분 매칭 (3경기 중 1경기만) → match.status 그대로 유지, result.games 1개 - `riot-job-scheduler.spec.ts` (deferUntil ZSET) - scheduleAt 후 cron 이 정확한 시점에 stream 으로 옮김 --- ## 7. Rollout 1. (PR-1) `Match.result.games[]` schema 확장 + `Match.resultPollState` 임베드 + 마이그레이션 (옛 result 호환 유지) 2. (PR-2) `RiotJobScheduler` (deferUntil ZSET + cron) — 다른 모듈도 재사용 가능 3. (PR-3) `tournament-result.service` (processPollJob / applyMatchToGameSlot / scheduleNextPoll) + 단위 테스트 4. (PR-4) worker dispatch 에 `kind=poll-tournament-result` 추가 5. (PR-5) auction.service `team-built` 전환 직후 `scheduleInitialPoll` 호출 6. (PR-6) admin 수동 트리거 엔드포인트 + 권한 가드 7. (PR-7) 매치 상세 결과 표시 (게임별 row + 시리즈 점수) 8. (PR-8) 운영 모니터링 (폴링 attempt / 매칭 성공률 / expired 카운트) 9. (Phase 후속) MVP 자동 산정 / dakao 알림 / mvpUserId 운영자 수동 입력 UI --- ## 8. 추가 고려사항 ### 확정 (사용자 결정 2026-04-27) - **`type=tourney` 필터** 사용 (`Tournament-Code-플랜.md` §6 결정) - **재폴링**: 5분(1h) → 1h(23h) → 24h 후 expired - **puuid 확장**: 24h 안 못 찾으면 캡틴 → 전체 참가자 - **finished 전환**: 모든 슬롯 used + riotMatchId 채워짐 - **결과 표시**: in-progress 부터 부분 게임 결과 점진 표시 ### 권장 (운영 후 확인) 1. **잘못된 코드 매칭 방어** — `applyMatchToGameSlot` 직전에 `team100/200` 우리 멤버 합집합 ≥ 6명 이면 정상, 미만이면 skip + 운영자 알림. (예: 운영자가 코드를 외부에 유출 → 다른 사람들이 사용한 게임이 우리 매치로 잘못 들어오는 케이스) 2. **`teamBuiltAt` 누락 가드** — 옛 매치 마이그레이션 시 `teamBuiltAt` 없을 수 있음. `null` 이면 폴링 skip + admin 페이지 경고. 3. **재폴링 cadence 초기 burst** — 5분 간격은 12회/h × Match-V5 list 1 + detail N = 매치당 최악 60+ calls/h. 글로벌 throttle 통과는 되지만 큰 매치 동시 진행 시 high stream 점유. low priority 로 enqueue 가 안전. 4. **gameNumber 순서 보존** — 운영자가 1경기/2경기/3경기 코드를 순서대로 발급한 가정. 만약 사용자가 2경기 코드를 먼저 게임에 입력하면 `gameNumber` 와 실제 플레이 순서가 어긋남. `gameCreation` 기준으로 후처리 정렬 필요할 수도. 일단 운영 흐름 가정 유지. 5. **시리즈 동점 판정** — gameCount=3 인데 1-1-pending 상황에서 마지막 매치가 expired 되면 winnerSide 미정. 운영자 수동 종료 자리 필요. 6. **부분 finished UI 처리** — `result.games.length < gameCount` 인 동안 "남은 경기 N개" 표시. 모두 done 되면 시리즈 결과 카드. 7. **외부 사용자에게 노출되는 raw match-v5 id** — `result.riotMatchIds` 가 외부에 노출되는데 puuid 같은 민감 정보는 응답 매핑 단에서 자동 제외 (이미 우리 userId 만 남기는 구조). 8. **Phase 후속 MVP 산정** — 라인별 KDA z-score / damage share / vision score 가중 — 평점 산식과 같은 로직 재사용 가능 (`Riot-소환사전적-플랜.md` §2.7.B.1). 9. **Replays / 랭크/AI 매치 false positive** — `type=tourney` 가 토너먼트 코드 매치만 반환하므로 false positive 거의 없음. 추가로 `info.tournamentCode` 정확 매칭이라 2중 가드. ### 추후 (Phase 후속) - MVP 자동 산정 - dakao bot / discord 알림 (시리즈 종료 시) - 운영자 수동 결과 입력 UI (폴링 expired / 잘못된 매칭 정정용) - 결과 통계 대시보드 (우리 커뮤니티의 시즌 W-L, 멤버 KDA 누적) --- ## 9. Done 정의 - `Match.result.games[]` + `Match.resultPollState` schema 추가 - `team-built` 전환 시 `scheduleInitialPoll` 호출 → 작업 큐 high 에 첫 enqueue - worker 가 `match-v5 by-puuid?type=tourney&startTime=teamBuiltAt-60` 호출 - `info.tournamentCode` 와 우리 코드 매칭 → 해당 `TournamentCode.state='used'`, `riotMatchId` 저장 - 우리 팀(blue/red) 매핑 정확 (5명 일치 케이스 테스트) - 부분 결과 표시: `in-progress` 동안 매칭된 game 만큼 result.games[] 채워지고 UI 점진 표시 - 모든 슬롯 used → `Match.status='finished'`, `result.winnerSide` 자동 산정 - 24h 안 못 찾으면 `resultPollState.state='expired'` + 로그 경고 - admin 수동 재시도 엔드포인트 동작 - `RiotJobScheduler` (deferUntil ZSET) 동작 — 5분/1h 후 정확히 enqueue - 단위 테스트 통과 (team-mapping / game-result / cadence / 부분 매칭) - Riot 429 0건 (글로벌 throttle 통과)