From 2250b6072edd06af0194a858350bfa79d53ef41e Mon Sep 17 00:00:00 2001 From: dahyeon Date: Mon, 27 Apr 2026 15:00:25 -0700 Subject: [PATCH] . --- Tournament-Result-수집-플랜.md | 470 ++++++++++++++++++ apps/api/src/app.module.ts | 2 + .../api/src/modules/auction/auction.module.ts | 3 +- .../modules/auction/auction.service.spec.ts | 11 + .../src/modules/auction/auction.service.ts | 6 + .../api/src/modules/global/database/schema.ts | 100 +++- apps/api/src/modules/match/match.service.ts | 7 + .../riot-job-queue/riot-job-queue.module.ts | 5 +- .../riot-job-queue/riot-job-queue.service.ts | 96 ++++ .../riot-job-queue/riot-job-queue.types.ts | 5 + .../riot-job-queue/riot-job-worker.service.ts | 29 +- .../team-mapping.util.spec.ts | 144 ++++++ .../tournament-result/team-mapping.util.ts | 118 +++++ .../tournament-result.controller.ts | 39 ++ .../tournament-result.module.ts | 13 + .../tournament-result.service.ts | 453 +++++++++++++++++ .../tournament-result.types.ts | 30 ++ apps/web/src/api/hooks.ts | 15 + apps/web/src/api/mappers.ts | 31 +- apps/web/src/api/types.ts | 22 +- apps/web/src/pages/HomePage.tsx | 2 +- apps/web/src/pages/MatchDetailPage.tsx | 160 ++++-- 22 files changed, 1719 insertions(+), 42 deletions(-) create mode 100644 Tournament-Result-수집-플랜.md create mode 100644 apps/api/src/modules/tournament-result/team-mapping.util.spec.ts create mode 100644 apps/api/src/modules/tournament-result/team-mapping.util.ts create mode 100644 apps/api/src/modules/tournament-result/tournament-result.controller.ts create mode 100644 apps/api/src/modules/tournament-result/tournament-result.module.ts create mode 100644 apps/api/src/modules/tournament-result/tournament-result.service.ts create mode 100644 apps/api/src/modules/tournament-result/tournament-result.types.ts diff --git a/Tournament-Result-수집-플랜.md b/Tournament-Result-수집-플랜.md new file mode 100644 index 00000000..6c111273 --- /dev/null +++ b/Tournament-Result-수집-플랜.md @@ -0,0 +1,470 @@ +# 토너먼트 결과 수집 (우회) 플랜 + +> **대상**: 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 통과) diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts index 2b2fc17e..9e5770a7 100644 --- a/apps/api/src/app.module.ts +++ b/apps/api/src/app.module.ts @@ -11,6 +11,7 @@ import { MatchHistoryModule } from './modules/match-history/match-history.module import { MatchModule } from './modules/match/match.module'; import { RiotModule } from './modules/riot/riot.module'; import { TournamentCodeModule } from './modules/tournament-code/tournament-code.module'; +import { TournamentResultModule } from './modules/tournament-result/tournament-result.module'; import { UserModule } from './modules/user/user.module'; @Module({ @@ -26,6 +27,7 @@ import { UserModule } from './modules/user/user.module'; MatchModule, MatchHistoryModule, TournamentCodeModule, + TournamentResultModule, AuctionModule, UserModule, DakaoModule, diff --git a/apps/api/src/modules/auction/auction.module.ts b/apps/api/src/modules/auction/auction.module.ts index d440e927..fbbb1ccd 100644 --- a/apps/api/src/modules/auction/auction.module.ts +++ b/apps/api/src/modules/auction/auction.module.ts @@ -1,12 +1,13 @@ import { Module } from '@nestjs/common'; import { RiotModule } from '../riot/riot.module'; import { TournamentCodeModule } from '../tournament-code/tournament-code.module'; +import { TournamentResultModule } from '../tournament-result/tournament-result.module'; import { AuctionGateway } from './auction.gateway'; import { AuctionController } from './auction.controller'; import { AuctionService } from './auction.service'; @Module({ - imports: [RiotModule, TournamentCodeModule], + imports: [RiotModule, TournamentCodeModule, TournamentResultModule], controllers: [AuctionController], providers: [AuctionService, AuctionGateway], exports: [AuctionService], diff --git a/apps/api/src/modules/auction/auction.service.spec.ts b/apps/api/src/modules/auction/auction.service.spec.ts index 4770a993..bf1be579 100644 --- a/apps/api/src/modules/auction/auction.service.spec.ts +++ b/apps/api/src/modules/auction/auction.service.spec.ts @@ -10,13 +10,24 @@ describe('AuctionService', () => { const enrichmentService = { enrichRiotAccount: jest.fn(), }; + const tournamentCodeService = { + reserveForMatch: jest.fn().mockResolvedValue(undefined), + releaseFromMatch: jest.fn().mockResolvedValue(undefined), + }; + const tournamentResultService = { + scheduleInitialPoll: jest.fn().mockResolvedValue(null), + }; return { service: new AuctionService( connectionService as never, enrichmentService as never, + tournamentCodeService as never, + tournamentResultService as never, ), connectionService, + tournamentCodeService, + tournamentResultService, }; } diff --git a/apps/api/src/modules/auction/auction.service.ts b/apps/api/src/modules/auction/auction.service.ts index e46d90dc..b940e7b9 100644 --- a/apps/api/src/modules/auction/auction.service.ts +++ b/apps/api/src/modules/auction/auction.service.ts @@ -16,6 +16,7 @@ import { } from '../global/database/schema'; import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service'; import { TournamentCodeService } from '../tournament-code/tournament-code.service'; +import { TournamentResultService } from '../tournament-result/tournament-result.service'; const AUCTION_MAX_TEAM_SIZE = 5; @@ -45,6 +46,7 @@ export class AuctionService { private readonly connectionService: ConnectionService, private readonly enrichmentService: RiotAccountEnrichmentService, private readonly tournamentCodeService: TournamentCodeService, + private readonly tournamentResultService: TournamentResultService, ) {} public async start(params: StartAuctionParams): Promise { @@ -178,6 +180,7 @@ export class AuctionService { match.teamBuiltAt = match.teamBuiltAt ?? new Date(); await match.save(); await this.tournamentCodeService.reserveForMatch(match); + await this.tournamentResultService.scheduleInitialPoll(match); return auction; } @@ -321,6 +324,8 @@ export class AuctionService { match.teams = []; match.tournamentCodeIds = []; match.teamBuiltAt = undefined; + match.result = undefined; + match.resultPollState = undefined; await match.save({ session }); } await session.commitTransaction(); @@ -403,6 +408,7 @@ export class AuctionService { match.teamBuiltAt = match.teamBuiltAt ?? new Date(); await match.save(); await this.tournamentCodeService.reserveForMatch(match); + await this.tournamentResultService.scheduleInitialPoll(match); } private resolveTeamName(side: TeamSide): string { diff --git a/apps/api/src/modules/global/database/schema.ts b/apps/api/src/modules/global/database/schema.ts index 22e30430..93cc4667 100644 --- a/apps/api/src/modules/global/database/schema.ts +++ b/apps/api/src/modules/global/database/schema.ts @@ -57,6 +57,15 @@ export const TOURNAMENT_SPECTATOR_TYPES: TournamentSpectatorType[] = [ 'ALL', ]; +export type MatchResultPollOutcome = 'matched' | 'not-found' | 'failed'; +export type MatchResultPollStateValue = 'polling' | 'complete' | 'expired' | 'failed'; +export const MATCH_RESULT_POLL_STATES: MatchResultPollStateValue[] = [ + 'polling', + 'complete', + 'expired', + 'failed', +]; + export interface PositionPreference { position: Position; priority: number; // 1 = 최우선, 숫자가 작을수록 높은 우선순위 @@ -315,12 +324,41 @@ export interface MatchTeam { members: MatchTeamMember[]; } -export interface MatchResult { +export interface MatchGameResultParticipant { + userId: mongoose.Types.ObjectId; + side: TeamSide; + championId: number; + kills: number; + deaths: number; + assists: number; + win: boolean; +} + +export interface MatchGameResult { + gameNumber: number; + riotMatchId: string; winnerSide: TeamSide; + gameCreation: number; + gameDuration: number; + participants: MatchGameResultParticipant[]; +} + +export interface MatchResult { + winnerSide?: TeamSide; blueScore: number; redScore: number; mvpUserId?: mongoose.Types.ObjectId; riotMatchIds: string[]; // 내전에서 플레이된 Riot matchId들 + games: MatchGameResult[]; +} + +export interface MatchResultPollState { + startedAt: Date; + lastPolledAt?: Date; + lastPollOutcome?: MatchResultPollOutcome; + matchedCount: number; + expandedToAllPuuids: boolean; + state: MatchResultPollStateValue; } export interface MatchScheduleItem { @@ -343,6 +381,7 @@ export interface Match extends MongooseTimestamps { participants: MatchParticipant[]; teams: MatchTeam[]; result?: MatchResult; + resultPollState?: MatchResultPollState; prizes: string[]; notices: string[]; schedule: MatchScheduleItem[]; @@ -714,6 +753,7 @@ export const RiotMatchSchema = new Schema( RiotMatchSchema.index({ participantPuuids: 1, gameCreation: -1 }); RiotMatchSchema.index({ participantPuuids: 1, queueId: 1, gameCreation: -1 }); +RiotMatchSchema.index({ 'raw.info.tournamentCode': 1 }, { sparse: true }); export const TournamentCodeSchema = new Schema( { @@ -805,13 +845,65 @@ const MatchTeamSubSchema = new Schema( { _id: false }, ); +const MatchGameResultParticipantSubSchema = + new Schema( + { + userId: { type: Schema.Types.ObjectId, ref: 'user', required: true }, + side: { type: String, enum: TEAM_SIDES, required: true }, + championId: { type: Number, required: true }, + kills: { type: Number, required: true, default: 0 }, + deaths: { type: Number, required: true, default: 0 }, + assists: { type: Number, required: true, default: 0 }, + win: { type: Boolean, required: true, default: false }, + }, + { _id: false }, + ); + +const MatchGameResultSubSchema = new Schema( + { + gameNumber: { type: Number, required: true }, + riotMatchId: { type: String, required: true }, + winnerSide: { type: String, enum: TEAM_SIDES, required: true }, + gameCreation: { type: Number, required: true }, + gameDuration: { type: Number, required: true }, + participants: { + type: [MatchGameResultParticipantSubSchema], + required: true, + default: [], + }, + }, + { _id: false }, +); + const MatchResultSubSchema = new Schema( { - winnerSide: { type: String, enum: TEAM_SIDES, required: true }, + winnerSide: { type: String, enum: TEAM_SIDES, required: false }, blueScore: { type: Number, required: true, default: 0 }, redScore: { type: Number, required: true, default: 0 }, mvpUserId: { type: Schema.Types.ObjectId, ref: 'user' }, riotMatchIds: { type: [String], required: true, default: [] }, + games: { type: [MatchGameResultSubSchema], required: true, default: [] }, + }, + { _id: false }, +); + +const MatchResultPollStateSubSchema = new Schema( + { + startedAt: { type: Date, required: true }, + lastPolledAt: { type: Date }, + lastPollOutcome: { + type: String, + enum: ['matched', 'not-found', 'failed'], + required: false, + }, + matchedCount: { type: Number, required: true, default: 0 }, + expandedToAllPuuids: { type: Boolean, required: true, default: false }, + state: { + type: String, + enum: MATCH_RESULT_POLL_STATES, + required: true, + default: 'polling', + }, }, { _id: false }, ); @@ -864,6 +956,10 @@ export const MatchSchema = new Schema( }, teams: { type: [MatchTeamSubSchema], required: true, default: [] }, result: { type: MatchResultSubSchema, required: false }, + resultPollState: { + type: MatchResultPollStateSubSchema, + required: false, + }, prizes: { type: [String], required: true, default: [] }, notices: { type: [String], required: true, default: [] }, schedule: { diff --git a/apps/api/src/modules/match/match.service.ts b/apps/api/src/modules/match/match.service.ts index 4283d82b..87d9e2c1 100644 --- a/apps/api/src/modules/match/match.service.ts +++ b/apps/api/src/modules/match/match.service.ts @@ -92,6 +92,11 @@ export class MatchService { public async serialize(match: MatchDocument) { const obj = match.toObject(); + if (obj.result?.games) { + obj.result.games = [...obj.result.games].sort( + (left, right) => left.gameNumber - right.gameNumber, + ); + } return { ...obj, gameCount: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT, @@ -116,6 +121,8 @@ export class MatchService { await this.tournamentCodeService.releaseFromMatch(match); match.tournamentCodeIds = []; match.teamBuiltAt = undefined; + match.result = undefined; + match.resultPollState = undefined; } await match.save(); return match; diff --git a/apps/api/src/modules/riot-job-queue/riot-job-queue.module.ts b/apps/api/src/modules/riot-job-queue/riot-job-queue.module.ts index 049f9112..a11974bd 100644 --- a/apps/api/src/modules/riot-job-queue/riot-job-queue.module.ts +++ b/apps/api/src/modules/riot-job-queue/riot-job-queue.module.ts @@ -1,12 +1,13 @@ -import { Module } from '@nestjs/common'; +import { forwardRef, Module } from '@nestjs/common'; import { RiotModule } from '../riot/riot.module'; +import { TournamentResultModule } from '../tournament-result/tournament-result.module'; import { RiotJobQueueController } from './riot-job-queue.controller'; import { RiotJobQueueService } from './riot-job-queue.service'; import { RiotJobWorkerService } from './riot-job-worker.service'; import { RiotRefreshGateway } from './riot-refresh.gateway'; @Module({ - imports: [RiotModule], + imports: [RiotModule, forwardRef(() => TournamentResultModule)], controllers: [RiotJobQueueController], providers: [RiotJobQueueService, RiotJobWorkerService, RiotRefreshGateway], exports: [RiotJobQueueService], diff --git a/apps/api/src/modules/riot-job-queue/riot-job-queue.service.ts b/apps/api/src/modules/riot-job-queue/riot-job-queue.service.ts index e4476d04..ecacef15 100644 --- a/apps/api/src/modules/riot-job-queue/riot-job-queue.service.ts +++ b/apps/api/src/modules/riot-job-queue/riot-job-queue.service.ts @@ -27,6 +27,7 @@ import { RIOT_JOB_HIGH_STREAM, RIOT_JOB_LOW_COOLDOWN_SECONDS, RIOT_JOB_LOW_STREAM, + RIOT_JOB_SCHEDULED_ZSET, RIOT_JOB_STATUS_TTL_SECONDS, RiotJobPriority, RiotJobState, @@ -35,6 +36,10 @@ import { RiotRefreshEvent, RiotRefreshSubJob, } from './riot-job-queue.types'; +import type { + EnqueueTournamentResultPollResult, + PollTournamentResultJob, +} from '../tournament-result/tournament-result.types'; interface RefreshContext { community: CommunityDocument; @@ -171,6 +176,68 @@ export class RiotJobQueueService { }; } + public async enqueueTournamentResultPoll(params: { + matchId: string; + attempt: number; + expandedToAllPuuids: boolean; + priority: RiotJobPriority; + deferUntilMs?: number; + }): Promise { + const job: PollTournamentResultJob = { + kind: 'poll-tournament-result', + jobId: randomUUID(), + matchId: params.matchId, + attempt: params.attempt, + expandedToAllPuuids: params.expandedToAllPuuids, + enqueuedAt: Date.now(), + priority: params.priority, + }; + + if (params.deferUntilMs && params.deferUntilMs > Date.now()) { + await this.scheduleJob(job, params.deferUntilMs); + } else { + await this.appendJob(job); + } + + return { + jobId: job.jobId, + matchId: job.matchId, + priority: job.priority, + attempt: job.attempt, + expandedToAllPuuids: job.expandedToAllPuuids, + }; + } + + public async promoteDueScheduledJobs(limit = 100): Promise { + const client = this.garnetService.raw(); + const raw = (await client.sendCommand([ + 'ZRANGEBYSCORE', + RIOT_JOB_SCHEDULED_ZSET, + '-inf', + String(Date.now()), + 'LIMIT', + '0', + String(limit), + ])) as string[] | null; + const entries = raw ?? []; + let promoted = 0; + + for (const entry of entries) { + const removed = (await client.sendCommand([ + 'ZREM', + RIOT_JOB_SCHEDULED_ZSET, + entry, + ])) as number; + if (removed !== 1) continue; + const job = this.parseScheduledJob(entry); + if (!job) continue; + await this.appendJob(job); + promoted += 1; + } + + return promoted; + } + public async getStatus(jobId: string): Promise { return this.garnetService.getJson(this.statusKey(jobId)); } @@ -332,6 +399,35 @@ export class RiotJobQueueService { return priority === 'high' ? RIOT_JOB_HIGH_STREAM : RIOT_JOB_LOW_STREAM; } + private async appendJob(job: RiotRefreshSubJob | PollTournamentResultJob) { + await this.garnetService.appendStream( + this.resolveStream(job.priority), + { job: JSON.stringify(job) }, + { maxLen: 10_000 }, + ); + } + + private async scheduleJob( + job: PollTournamentResultJob, + deferUntilMs: number, + ): Promise { + await this.garnetService.raw().sendCommand([ + 'ZADD', + RIOT_JOB_SCHEDULED_ZSET, + String(deferUntilMs), + JSON.stringify(job), + ]); + } + + private parseScheduledJob(value: string): PollTournamentResultJob | null { + try { + const parsed = JSON.parse(value) as PollTournamentResultJob; + return parsed.kind === 'poll-tournament-result' ? parsed : null; + } catch { + return null; + } + } + private resolveParentState(subJobs: RiotJobStatus[]): RiotJobState { if (subJobs.some((job) => job.state === 'processing')) return 'processing'; if (subJobs.some((job) => job.state === 'queued')) return 'queued'; diff --git a/apps/api/src/modules/riot-job-queue/riot-job-queue.types.ts b/apps/api/src/modules/riot-job-queue/riot-job-queue.types.ts index f9367055..b644aaa0 100644 --- a/apps/api/src/modules/riot-job-queue/riot-job-queue.types.ts +++ b/apps/api/src/modules/riot-job-queue/riot-job-queue.types.ts @@ -3,9 +3,11 @@ import type { RiotRegionalRoute, } from '../riot/riot.types'; import type { RiotQueueGroup } from '../riot/riot-queue.constants'; +import type { PollTournamentResultJob } from '../tournament-result/tournament-result.types'; export const RIOT_JOB_HIGH_STREAM = 'riot:queue:high'; export const RIOT_JOB_LOW_STREAM = 'riot:queue:low'; +export const RIOT_JOB_SCHEDULED_ZSET = 'riot:queue:scheduled'; export const RIOT_JOB_GROUP = 'riot-refresh-worker'; export const RIOT_JOB_STATUS_TTL_SECONDS = 24 * 60 * 60; export const RIOT_JOB_DEDUP_TTL_SECONDS = 5 * 60; @@ -17,6 +19,7 @@ export type RiotJobPriority = 'high' | 'low'; export type RiotJobState = 'queued' | 'processing' | 'completed' | 'failed'; export interface RiotRefreshSubJob { + kind?: 'refresh-account'; jobId: string; parentJobId: string; userId: string; @@ -30,6 +33,8 @@ export interface RiotRefreshSubJob { priority: RiotJobPriority; } +export type RiotJobPayload = RiotRefreshSubJob | PollTournamentResultJob; + export interface RiotJobStatus { jobId: string; parentJobId: string; diff --git a/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts b/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts index f6b429f5..e24a8e55 100644 --- a/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts +++ b/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts @@ -12,10 +12,13 @@ import { RIOT_JOB_GROUP, RIOT_JOB_HIGH_STREAM, RIOT_JOB_LOW_STREAM, + RiotJobPayload, RiotRefreshSubJob, } from './riot-job-queue.types'; import { RiotJobQueueService } from './riot-job-queue.service'; import { RiotRefreshGateway } from './riot-refresh.gateway'; +import { TournamentResultService } from '../tournament-result/tournament-result.service'; +import type { PollTournamentResultJob } from '../tournament-result/tournament-result.types'; const LEADER_KEY = 'riot:worker:leader'; const LEADER_TTL_SECONDS = 60; @@ -32,6 +35,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy { private readonly recentMatchesService: RiotRecentMatchesService, private readonly connectionService: ConnectionService, private readonly refreshGateway: RiotRefreshGateway, + private readonly tournamentResultService: TournamentResultService, ) {} public async onModuleInit() { @@ -52,6 +56,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy { continue; } + await this.jobQueueService.promoteDueScheduledJobs(); const entry = (await this.readOne(RIOT_JOB_HIGH_STREAM, 100)) ?? (await this.readOne(RIOT_JOB_LOW_STREAM, 1_000)); @@ -77,6 +82,11 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy { } try { + if (this.isTournamentResultJob(job)) { + await this.tournamentResultService.processPollJob(job); + return; + } + await this.jobQueueService.markProcessing(job); for (const queueId of job.queueIds) { await this.recentMatchesService.ensureFreshForQueue({ @@ -89,6 +99,15 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy { const event = await this.jobQueueService.markCompleted(job); this.refreshGateway.broadcastRefreshEvent(event); } catch (error) { + if (this.isTournamentResultJob(job)) { + this.logger.warn( + `Tournament result poll job failed ${job.jobId}: ${ + error instanceof Error ? error.message : error + }`, + ); + return; + } + const event = await this.jobQueueService.markFailed(job, error); this.refreshGateway.broadcastRefreshEvent(event); this.logger.warn( @@ -119,16 +138,22 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy { ).exec(); } - private parseJob(entry: StreamEntry): RiotRefreshSubJob | null { + private parseJob(entry: StreamEntry): RiotJobPayload | null { const raw = entry.message.job; if (!raw) return null; try { - return JSON.parse(raw) as RiotRefreshSubJob; + return JSON.parse(raw) as RiotJobPayload; } catch { return null; } } + private isTournamentResultJob( + job: RiotJobPayload, + ): job is PollTournamentResultJob { + return job.kind === 'poll-tournament-result'; + } + private async readOne( stream: string, blockMs: number, diff --git a/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts b/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts new file mode 100644 index 00000000..a0e72be8 --- /dev/null +++ b/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts @@ -0,0 +1,144 @@ +import mongoose from 'mongoose'; +import type { MatchDocument } from '../global/database/schema'; +import type { RiotMatchDto } from '../riot/riot.types'; +import { computeGameResult, type MatchPuuidLookup } from './team-mapping.util'; + +function makeMatch(): { + match: MatchDocument; + lookup: MatchPuuidLookup; + blueUserIds: mongoose.Types.ObjectId[]; + redUserIds: mongoose.Types.ObjectId[]; +} { + const blueUserIds = Array.from({ length: 5 }, () => new mongoose.Types.ObjectId()); + const redUserIds = Array.from({ length: 5 }, () => new mongoose.Types.ObjectId()); + const puuidByUserId = new Map(); + const userIdByPuuid = new Map(); + + for (const [index, userId] of [...blueUserIds, ...redUserIds].entries()) { + const puuid = `puuid-${index}`; + puuidByUserId.set(userId.toString(), puuid); + userIdByPuuid.set(puuid, userId); + } + + const match = { + teams: [ + { + side: 'blue', + name: '블루팀', + members: blueUserIds.map((userId) => ({ + userId, + assignedPosition: 'MID', + })), + }, + { + side: 'red', + name: '레드팀', + members: redUserIds.map((userId) => ({ + userId, + assignedPosition: 'MID', + })), + }, + ], + participants: [...blueUserIds, ...redUserIds].map((userId, index) => ({ + userId, + puuid: `puuid-${index}`, + preferredPositions: [], + joinedAt: new Date(), + })), + } as unknown as MatchDocument; + + return { match, lookup: { puuidByUserId, userIdByPuuid }, blueUserIds, redUserIds }; +} + +function makeRiotMatch(params: { + team100Puuids: string[]; + team200Puuids: string[]; + winningTeamId: 100 | 200; +}): RiotMatchDto { + const participants = [ + ...params.team100Puuids.map((puuid, index) => ({ + puuid, + participantId: index + 1, + teamId: 100, + championId: 10 + index, + kills: index, + deaths: 1, + assists: 2, + win: params.winningTeamId === 100, + })), + ...params.team200Puuids.map((puuid, index) => ({ + puuid, + participantId: index + 6, + teamId: 200, + championId: 20 + index, + kills: index, + deaths: 2, + assists: 3, + win: params.winningTeamId === 200, + })), + ]; + + return { + metadata: { + dataVersion: '2', + matchId: 'KR_1', + participants: participants.map((participant) => participant.puuid), + }, + info: { + gameCreation: 1, + gameDuration: 1800, + participants, + teams: [ + { teamId: 100, win: params.winningTeamId === 100 }, + { teamId: 200, win: params.winningTeamId === 200 }, + ], + }, + } as unknown as RiotMatchDto; +} + +describe('computeGameResult', () => { + it('maps Riot teams to local blue/red by overlap', () => { + const { match, lookup } = makeMatch(); + const detail = makeRiotMatch({ + team100Puuids: ['puuid-0', 'puuid-1', 'puuid-2', 'puuid-3', 'puuid-4'], + team200Puuids: ['puuid-5', 'puuid-6', 'puuid-7', 'puuid-8', 'puuid-9'], + winningTeamId: 100, + }); + + const result = computeGameResult({ match, lookup, detail, gameNumber: 1 }); + + expect(result).toMatchObject({ + gameNumber: 1, + riotMatchId: 'KR_1', + winnerSide: 'blue', + gameDuration: 1800, + }); + expect(result?.participants).toHaveLength(10); + }); + + it('handles reversed Riot side assignment', () => { + const { match, lookup } = makeMatch(); + const detail = makeRiotMatch({ + team100Puuids: ['puuid-5', 'puuid-6', 'puuid-7', 'puuid-8', 'puuid-9'], + team200Puuids: ['puuid-0', 'puuid-1', 'puuid-2', 'puuid-3', 'puuid-4'], + winningTeamId: 100, + }); + + const result = computeGameResult({ match, lookup, detail, gameNumber: 2 }); + + expect(result?.winnerSide).toBe('red'); + }); + + it('rejects matches with too little overlap', () => { + const { match, lookup } = makeMatch(); + const detail = makeRiotMatch({ + team100Puuids: ['other-1', 'other-2', 'other-3', 'other-4', 'other-5'], + team200Puuids: ['other-6', 'other-7', 'other-8', 'other-9', 'other-10'], + winningTeamId: 100, + }); + + const result = computeGameResult({ match, lookup, detail, gameNumber: 3 }); + + expect(result).toBeNull(); + }); +}); diff --git a/apps/api/src/modules/tournament-result/team-mapping.util.ts b/apps/api/src/modules/tournament-result/team-mapping.util.ts new file mode 100644 index 00000000..a617b78f --- /dev/null +++ b/apps/api/src/modules/tournament-result/team-mapping.util.ts @@ -0,0 +1,118 @@ +import mongoose from 'mongoose'; +import type { + MatchDocument, + MatchGameResult, + TeamSide, +} from '../global/database/schema'; +import type { RiotMatchDto } from '../riot/riot.types'; + +const RIOT_BLUE_TEAM_ID = 100; +const RIOT_RED_TEAM_ID = 200; +const MINIMUM_TRUSTED_OVERLAP = 6; + +export interface MatchPuuidLookup { + puuidByUserId: Map; + userIdByPuuid: Map; +} + +export function collectCaptainUserIds(match: MatchDocument): mongoose.Types.ObjectId[] { + return match.teams + .map((team) => team.captainUserId) + .filter((userId): userId is mongoose.Types.ObjectId => Boolean(userId)); +} + +export function collectMatchUserIds(match: MatchDocument): mongoose.Types.ObjectId[] { + const ids = new Map(); + for (const participant of match.participants) { + ids.set(participant.userId.toString(), participant.userId); + } + for (const team of match.teams) { + if (team.captainUserId) ids.set(team.captainUserId.toString(), team.captainUserId); + for (const member of team.members) { + ids.set(member.userId.toString(), member.userId); + } + } + return [...ids.values()]; +} + +export function collectTeamPuuids( + match: MatchDocument, + side: TeamSide, + lookup: MatchPuuidLookup, +): string[] { + const team = match.teams.find((item) => item.side === side); + if (!team) return []; + return team.members + .map((member) => lookup.puuidByUserId.get(member.userId.toString())) + .filter((puuid): puuid is string => Boolean(puuid)); +} + +export function computeGameResult(params: { + match: MatchDocument; + detail: RiotMatchDto; + gameNumber: number; + lookup: MatchPuuidLookup; +}): MatchGameResult | null { + const { match, detail, gameNumber, lookup } = params; + const ourBluePuuids = collectTeamPuuids(match, 'blue', lookup); + const ourRedPuuids = collectTeamPuuids(match, 'red', lookup); + const team100Puuids = detail.info.participants + .filter((participant) => participant.teamId === RIOT_BLUE_TEAM_ID) + .map((participant) => participant.puuid); + const team200Puuids = detail.info.participants + .filter((participant) => participant.teamId === RIOT_RED_TEAM_ID) + .map((participant) => participant.puuid); + + const normalOverlap = + countOverlap(team100Puuids, ourBluePuuids) + + countOverlap(team200Puuids, ourRedPuuids); + const reversedOverlap = + countOverlap(team100Puuids, ourRedPuuids) + + countOverlap(team200Puuids, ourBluePuuids); + const teamMapping: Record = + normalOverlap >= reversedOverlap + ? { [RIOT_BLUE_TEAM_ID]: 'blue', [RIOT_RED_TEAM_ID]: 'red' } + : { [RIOT_BLUE_TEAM_ID]: 'red', [RIOT_RED_TEAM_ID]: 'blue' }; + + if (Math.max(normalOverlap, reversedOverlap) < MINIMUM_TRUSTED_OVERLAP) { + return null; + } + + const winningTeam = detail.info.teams.find((team) => team.win); + if (!winningTeam) return null; + const winnerSide = teamMapping[winningTeam.teamId]; + if (!winnerSide) return null; + + const participants = detail.info.participants + .map((participant) => { + const userId = lookup.userIdByPuuid.get(participant.puuid); + const side = teamMapping[participant.teamId]; + if (!userId || !side) return null; + return { + userId, + side, + championId: participant.championId, + kills: participant.kills, + deaths: participant.deaths, + assists: participant.assists, + win: participant.win, + }; + }) + .filter((participant): participant is NonNullable => + Boolean(participant), + ); + + return { + gameNumber, + riotMatchId: detail.metadata.matchId, + winnerSide, + gameCreation: detail.info.gameCreation, + gameDuration: detail.info.gameDuration, + participants, + }; +} + +export function countOverlap(left: string[], right: string[]): number { + const rightSet = new Set(right); + return left.filter((item) => rightSet.has(item)).length; +} diff --git a/apps/api/src/modules/tournament-result/tournament-result.controller.ts b/apps/api/src/modules/tournament-result/tournament-result.controller.ts new file mode 100644 index 00000000..9f9e627e --- /dev/null +++ b/apps/api/src/modules/tournament-result/tournament-result.controller.ts @@ -0,0 +1,39 @@ +import { + BadRequestException, + Controller, + Param, + Post, + UseGuards, +} from '@nestjs/common'; +import mongoose from 'mongoose'; +import { CurrentUser } from '../auth/current-user.decorator'; +import { Roles } from '../auth/roles.decorator'; +import { RolesGuard } from '../auth/roles.guard'; +import { ParseObjectIdPipe } from '../common/parse-object-id.pipe'; +import type { UserDocument } from '../global/database/schema'; +import { TournamentResultService } from './tournament-result.service'; + +@Controller('communities/:communityId/matches/:matchId/poll-tournament-result') +@Roles('owner', 'admin') +@UseGuards(RolesGuard) +export class TournamentResultController { + constructor( + private readonly tournamentResultService: TournamentResultService, + ) {} + + @Post() + public async poll( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + ) { + if (!currentUser.communityId.equals(communityId)) { + throw new BadRequestException('Different community.'); + } + return this.tournamentResultService.scheduleManualPoll({ + matchId, + communityId, + }); + } +} diff --git a/apps/api/src/modules/tournament-result/tournament-result.module.ts b/apps/api/src/modules/tournament-result/tournament-result.module.ts new file mode 100644 index 00000000..bec4bd6b --- /dev/null +++ b/apps/api/src/modules/tournament-result/tournament-result.module.ts @@ -0,0 +1,13 @@ +import { forwardRef, Module } from '@nestjs/common'; +import { RiotJobQueueModule } from '../riot-job-queue/riot-job-queue.module'; +import { RiotModule } from '../riot/riot.module'; +import { TournamentResultController } from './tournament-result.controller'; +import { TournamentResultService } from './tournament-result.service'; + +@Module({ + imports: [RiotModule, forwardRef(() => RiotJobQueueModule)], + controllers: [TournamentResultController], + providers: [TournamentResultService], + exports: [TournamentResultService], +}) +export class TournamentResultModule {} diff --git a/apps/api/src/modules/tournament-result/tournament-result.service.ts b/apps/api/src/modules/tournament-result/tournament-result.service.ts new file mode 100644 index 00000000..5ee2a15f --- /dev/null +++ b/apps/api/src/modules/tournament-result/tournament-result.service.ts @@ -0,0 +1,453 @@ +import { + BadRequestException, + Injectable, + Logger, + NotFoundException, +} from '@nestjs/common'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import type { + MatchDocument, + MatchGameResult, + RiotMatch as StoredRiotMatch, + TournamentCodeDocument, +} from '../global/database/schema'; +import { RiotJobQueueService } from '../riot-job-queue/riot-job-queue.service'; +import type { RiotJobPriority } from '../riot-job-queue/riot-job-queue.types'; +import { RiotMatchService } from '../riot/riot-match.service'; +import type { RiotMatchDto, RiotRegionalRoute } from '../riot/riot.types'; +import { + collectCaptainUserIds, + collectMatchUserIds, + computeGameResult, + type MatchPuuidLookup, +} from './team-mapping.util'; +import type { + EnqueueTournamentResultPollResult, + PollTournamentResultJob, +} from './tournament-result.types'; + +const FIRST_HOUR_POLL_DELAY_MS = 5 * 60_000; +const LATER_POLL_DELAY_MS = 60 * 60_000; +const POLL_EXPIRY_MS = 24 * 60 * 60_000; +const EXPAND_AFTER_MS = 60 * 60_000; +const TOURNAMENT_LOOKUP_START_MARGIN_SECONDS = 60; + +@Injectable() +export class TournamentResultService { + private readonly logger = new Logger(TournamentResultService.name); + + constructor( + private readonly connectionService: ConnectionService, + private readonly riotMatchService: RiotMatchService, + private readonly riotJobQueueService: RiotJobQueueService, + ) {} + + public async scheduleInitialPoll( + matchOrId: MatchDocument | mongoose.Types.ObjectId, + priority: RiotJobPriority = 'high', + ): Promise { + const match = await this.loadMatch(matchOrId); + if (match.status === 'finished') return null; + if (!this.isReadyToPoll(match)) return null; + + match.resultPollState = { + startedAt: match.resultPollState?.startedAt ?? new Date(), + lastPolledAt: match.resultPollState?.lastPolledAt, + lastPollOutcome: match.resultPollState?.lastPollOutcome, + matchedCount: match.result?.games?.length ?? 0, + expandedToAllPuuids: false, + state: 'polling', + }; + await match.save(); + + return this.riotJobQueueService.enqueueTournamentResultPoll({ + matchId: match._id.toString(), + attempt: 1, + expandedToAllPuuids: false, + priority, + }); + } + + public async scheduleManualPoll(params: { + matchId: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + }): Promise { + const match = await this.loadMatch(params.matchId); + if (!match.communityId.equals(params.communityId)) { + throw new BadRequestException('Match does not belong to this community.'); + } + if (!this.isReadyToPoll(match)) { + throw new BadRequestException( + 'Match needs built teams, teamBuiltAt, and tournament codes before polling.', + ); + } + const result = await this.scheduleInitialPoll(match, 'high'); + if (!result) { + throw new BadRequestException('Tournament result polling is not available.'); + } + return result; + } + + public async processPollJob(job: PollTournamentResultJob): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const CommunityModel = await this.connectionService.getModel('community'); + const match = await MatchModel.findById(job.matchId); + if (!match || match.status === 'finished') return; + if (!this.isReadyToPoll(match)) { + await this.updatePollState(match, 'failed', job.expandedToAllPuuids); + return; + } + + const codes = await TournamentCodeModel.find({ matchId: match._id }) + .sort({ gameNumber: 1 }) + .exec(); + const unmatched = codes.filter( + (code) => code.state === 'reserved' && !code.riotMatchId, + ); + if (unmatched.length === 0) { + await this.advanceMatchIfReady(match, codes); + return; + } + + const community = await CommunityModel.findById(match.communityId) + .select({ riotRegion: 1 }) + .lean() + .exec(); + const region = community?.riotRegion ?? 'asia'; + const lookup = await this.buildPuuidLookup(match); + const puuids = job.expandedToAllPuuids + ? this.collectPollingPuuids(collectMatchUserIds(match), lookup) + : this.collectPollingPuuids(collectCaptainUserIds(match), lookup); + + const matchedGameNumbers = new Set(); + const checkedRiotMatchIds = new Set(); + const unmatchedByCode = new Map(unmatched.map((code) => [code.code, code])); + + for (const puuid of puuids) { + let ids: string[]; + try { + ids = await this.riotMatchService.getMatchIdsByPuuid(puuid, { + region, + type: 'tourney', + startTime: this.resolveStartTime(match), + endTime: Math.floor(Date.now() / 1000), + count: 100, + }); + } catch (error) { + this.logger.warn( + `Tournament result match id lookup failed for ${puuid}: ${ + error instanceof Error ? error.message : error + }`, + ); + continue; + } + + for (const riotMatchId of ids) { + if (checkedRiotMatchIds.has(riotMatchId)) continue; + checkedRiotMatchIds.add(riotMatchId); + + const alreadyMatched = await TournamentCodeModel.exists({ riotMatchId }); + if (alreadyMatched) continue; + + let detail: RiotMatchDto; + try { + detail = await this.ensureRiotMatchPersisted(riotMatchId, region); + } catch (error) { + this.logger.warn( + `Tournament result detail fetch failed for ${riotMatchId}: ${ + error instanceof Error ? error.message : error + }`, + ); + continue; + } + const tournamentCode = detail.info.tournamentCode?.trim().toUpperCase(); + if (!tournamentCode) continue; + + const code = unmatchedByCode.get(tournamentCode); + if (!code) continue; + + const applied = await this.applyMatchToGameSlot({ + match, + code, + detail, + lookup, + }); + if (applied) { + matchedGameNumbers.add(code.gameNumber ?? 0); + unmatchedByCode.delete(tournamentCode); + } + } + } + + const reloadedCodes = await TournamentCodeModel.find({ matchId: match._id }) + .sort({ gameNumber: 1 }) + .exec(); + const outcome = matchedGameNumbers.size > 0 ? 'matched' : 'not-found'; + await this.updatePollState(match, outcome, job.expandedToAllPuuids); + const completed = await this.advanceMatchIfReady(match, reloadedCodes); + if (!completed) { + await this.scheduleNextPoll(match, job); + } + } + + private async applyMatchToGameSlot(params: { + match: MatchDocument; + code: TournamentCodeDocument; + detail: RiotMatchDto; + lookup: MatchPuuidLookup; + }): Promise { + const { match, code, detail, lookup } = params; + if (code.state !== 'reserved' || code.riotMatchId) return false; + if (!code.gameNumber) return false; + + const gameResult = computeGameResult({ + match, + detail, + gameNumber: code.gameNumber, + lookup, + }); + if (!gameResult) { + this.logger.warn( + `Skipped tournament result ${detail.metadata.matchId}; team mapping was not trusted for match ${match._id.toString()}.`, + ); + return false; + } + + code.state = 'used'; + code.usedAt = new Date(detail.info.gameEndTimestamp ?? detail.info.gameCreation); + code.riotMatchId = detail.metadata.matchId; + await code.save(); + + this.upsertGameResult(match, gameResult); + if (match.status === 'team-built') { + match.status = 'in-progress'; + } + await match.save(); + return true; + } + + private async advanceMatchIfReady( + match: MatchDocument, + codes: TournamentCodeDocument[], + ): Promise { + if (codes.length < match.gameCount) return false; + if (!codes.every((code) => code.state === 'used' && code.riotMatchId)) { + return false; + } + + 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 = { + startedAt: match.resultPollState?.startedAt ?? new Date(), + lastPolledAt: match.resultPollState?.lastPolledAt, + lastPollOutcome: match.resultPollState?.lastPollOutcome, + matchedCount: match.result?.games?.length ?? 0, + expandedToAllPuuids: match.resultPollState?.expandedToAllPuuids ?? false, + state: 'complete', + }; + await match.save(); + return true; + } + + private async scheduleNextPoll( + match: MatchDocument, + job: PollTournamentResultJob, + ): Promise { + const pollState = match.resultPollState; + const startedAt = pollState?.startedAt ?? new Date(); + const elapsedMs = Date.now() - startedAt.getTime(); + const delayMs = this.nextPollDelayMs(elapsedMs); + if (delayMs === null) { + match.resultPollState = { + startedAt, + lastPolledAt: pollState?.lastPolledAt, + lastPollOutcome: pollState?.lastPollOutcome, + matchedCount: match.result?.games?.length ?? 0, + expandedToAllPuuids: pollState?.expandedToAllPuuids ?? job.expandedToAllPuuids, + state: 'expired', + }; + await match.save(); + this.logger.warn( + `Tournament result polling expired for match ${match._id.toString()}.`, + ); + return; + } + + const expandedToAllPuuids = + job.expandedToAllPuuids || + (elapsedMs >= EXPAND_AFTER_MS && (match.result?.games?.length ?? 0) === 0); + await this.riotJobQueueService.enqueueTournamentResultPoll({ + matchId: match._id.toString(), + attempt: job.attempt + 1, + expandedToAllPuuids, + priority: 'low', + deferUntilMs: Date.now() + delayMs, + }); + } + + private async ensureRiotMatchPersisted( + riotMatchId: string, + region: RiotRegionalRoute, + ): Promise { + const RiotMatchModel = await this.connectionService.getModel('riotMatch'); + const stored = await RiotMatchModel.findOne({ matchId: riotMatchId }).exec(); + if (isRiotMatchDto(stored?.raw)) return stored.raw; + + const dto = await this.riotMatchService.getMatch(riotMatchId, { region }); + const payload: Partial = { + 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, + fetchedAt: new Date(), + }; + await RiotMatchModel.updateOne( + { matchId: dto.metadata.matchId }, + { $setOnInsert: payload }, + { upsert: true }, + ).exec(); + return dto; + } + + private async buildPuuidLookup(match: MatchDocument): Promise { + const puuidByUserId = new Map(); + const userIdByPuuid = new Map(); + + for (const participant of match.participants) { + if (!participant.puuid) continue; + const userId = participant.userId.toString(); + puuidByUserId.set(userId, participant.puuid); + userIdByPuuid.set(participant.puuid, participant.userId); + } + + const missingUserIds = collectMatchUserIds(match).filter( + (userId) => !puuidByUserId.has(userId.toString()), + ); + if (missingUserIds.length > 0) { + const UserModel = await this.connectionService.getModel('user'); + const users = await UserModel.find({ _id: { $in: missingUserIds } }) + .select({ riotAccounts: 1 }) + .exec(); + for (const user of users) { + const primary = + user.riotAccounts.find((account) => account.isPrimary) ?? + user.riotAccounts[0]; + if (!primary) continue; + puuidByUserId.set(user._id.toString(), primary.puuid); + userIdByPuuid.set(primary.puuid, user._id); + } + } + + return { puuidByUserId, userIdByPuuid }; + } + + private collectPollingPuuids( + userIds: mongoose.Types.ObjectId[], + lookup: MatchPuuidLookup, + ): string[] { + return [ + ...new Set( + userIds + .map((userId) => lookup.puuidByUserId.get(userId.toString())) + .filter((puuid): puuid is string => Boolean(puuid)), + ), + ]; + } + + private upsertGameResult( + match: MatchDocument, + gameResult: MatchGameResult, + ): void { + const currentGames = match.result?.games ?? []; + const games = [ + ...currentGames.filter( + (game) => + game.gameNumber !== gameResult.gameNumber && + game.riotMatchId !== gameResult.riotMatchId, + ), + gameResult, + ].sort((left, right) => left.gameNumber - right.gameNumber); + + match.result = { + winnerSide: match.result?.winnerSide, + blueScore: games.filter((game) => game.winnerSide === 'blue').length, + redScore: games.filter((game) => game.winnerSide === 'red').length, + mvpUserId: match.result?.mvpUserId, + riotMatchIds: [...new Set(games.map((game) => game.riotMatchId))], + games, + }; + } + + private async updatePollState( + match: MatchDocument, + outcome: 'matched' | 'not-found' | 'failed', + expandedToAllPuuids: boolean, + ): Promise { + match.resultPollState = { + startedAt: match.resultPollState?.startedAt ?? new Date(), + lastPolledAt: new Date(), + lastPollOutcome: outcome, + matchedCount: match.result?.games?.length ?? 0, + expandedToAllPuuids, + state: outcome === 'failed' ? 'failed' : 'polling', + }; + await match.save(); + } + + private nextPollDelayMs(elapsedMs: number): number | null { + if (elapsedMs >= POLL_EXPIRY_MS) return null; + if (elapsedMs <= EXPAND_AFTER_MS) return FIRST_HOUR_POLL_DELAY_MS; + return LATER_POLL_DELAY_MS; + } + + private resolveStartTime(match: MatchDocument): number { + return Math.max( + 0, + Math.floor(match.teamBuiltAt!.getTime() / 1000) - + TOURNAMENT_LOOKUP_START_MARGIN_SECONDS, + ); + } + + private isReadyToPoll(match: MatchDocument): boolean { + return Boolean( + match.teamBuiltAt && + match.tournamentCodeIds.length > 0 && + match.teams.length >= 2 && + match.teams.every((team) => team.members.length > 0), + ); + } + + private async loadMatch( + matchOrId: MatchDocument | mongoose.Types.ObjectId, + ): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const match = + matchOrId instanceof mongoose.Types.ObjectId + ? await MatchModel.findById(matchOrId) + : await MatchModel.findById(matchOrId._id); + if (!match) throw new NotFoundException('Match not found.'); + return match; + } +} + +function isRiotMatchDto(value: unknown): value is RiotMatchDto { + return Boolean( + value && + typeof value === 'object' && + 'metadata' in value && + 'info' in value, + ); +} diff --git a/apps/api/src/modules/tournament-result/tournament-result.types.ts b/apps/api/src/modules/tournament-result/tournament-result.types.ts new file mode 100644 index 00000000..25e265b7 --- /dev/null +++ b/apps/api/src/modules/tournament-result/tournament-result.types.ts @@ -0,0 +1,30 @@ +import type { TeamSide } from '../global/database/schema'; +import type { RiotJobPriority } from '../riot-job-queue/riot-job-queue.types'; + +export interface PollTournamentResultJob { + kind: 'poll-tournament-result'; + jobId: string; + matchId: string; + attempt: number; + expandedToAllPuuids: boolean; + enqueuedAt: number; + priority: RiotJobPriority; +} + +export interface EnqueueTournamentResultPollResult { + jobId: string; + matchId: string; + priority: RiotJobPriority; + attempt: number; + expandedToAllPuuids: boolean; +} + +export interface ComputedGameParticipant { + userId: string; + side: TeamSide; + championId: number; + kills: number; + deaths: number; + assists: number; + win: boolean; +} diff --git a/apps/web/src/api/hooks.ts b/apps/web/src/api/hooks.ts index 838d82d0..b84c4e4e 100644 --- a/apps/web/src/api/hooks.ts +++ b/apps/web/src/api/hooks.ts @@ -334,6 +334,21 @@ export function useDeleteTournamentCode(communityId = DEFAULT_COMMUNITY_ID) { }); } +export function usePollTournamentResult(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: (matchId: string) => + apiFetch<{ + jobId: string; + matchId: string; + priority: 'high' | 'low'; + attempt: number; + expandedToAllPuuids: boolean; + }>(`/communities/${communityId}/matches/${matchId}/poll-tournament-result`, { + method: 'POST', + }), + }); +} + export function useMe() { const authUserId = useAuthUserId(); const { accounts, inProgress, instance } = useMsal(); diff --git a/apps/web/src/api/mappers.ts b/apps/web/src/api/mappers.ts index 09f87377..9ea5036b 100644 --- a/apps/web/src/api/mappers.ts +++ b/apps/web/src/api/mappers.ts @@ -53,9 +53,27 @@ export interface MatchDetailView { participants: ParticipantView[]; teams: TeamView[]; result?: { - winner: string; + winner?: string; + winnerSide?: TeamSide; blueScore: number; redScore: number; + riotMatchIds: string[]; + games: Array<{ + 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; + }>; + }>; }; prizes: string[]; notices: string[]; @@ -392,7 +410,7 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView { }), })); - const winnerTeam = match.result + const winnerTeam = match.result?.winnerSide ? teams.find((team) => team.side === match.result?.winnerSide) : undefined; @@ -412,9 +430,16 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView { teams, result: match.result ? { - winner: winnerTeam?.name ?? sideLabel(match.result.winnerSide), + winner: match.result.winnerSide + ? winnerTeam?.name ?? sideLabel(match.result.winnerSide) + : undefined, + winnerSide: match.result.winnerSide, blueScore: match.result.blueScore, redScore: match.result.redScore, + riotMatchIds: match.result.riotMatchIds, + games: [...(match.result.games ?? [])].sort( + (left, right) => left.gameNumber - right.gameNumber, + ), } : undefined, prizes: match.prizes, diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index aa461060..47986dbf 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -146,12 +146,32 @@ export interface ApiMatchTeam { members: ApiMatchTeamMember[]; } -export interface ApiMatchResult { +export interface ApiMatchGameResultParticipant { + userId: string; + side: TeamSide; + championId: number; + kills: number; + deaths: number; + assists: number; + win: boolean; +} + +export interface ApiMatchGameResult { + gameNumber: number; + riotMatchId: string; winnerSide: TeamSide; + gameCreation: number; + gameDuration: number; + participants: ApiMatchGameResultParticipant[]; +} + +export interface ApiMatchResult { + winnerSide?: TeamSide; blueScore: number; redScore: number; mvpUserId?: string; riotMatchIds: string[]; + games: ApiMatchGameResult[]; } export interface ApiMatchScheduleItem { diff --git a/apps/web/src/pages/HomePage.tsx b/apps/web/src/pages/HomePage.tsx index 25538298..cec7e7cf 100644 --- a/apps/web/src/pages/HomePage.tsx +++ b/apps/web/src/pages/HomePage.tsx @@ -208,7 +208,7 @@ export default function HomePage() { {match.participants.length}명 - {match.result ? `${match.result.winner} 승리` : '-'} + {match.result?.winner ? `${match.result.winner} 승리` : '-'} )) diff --git a/apps/web/src/pages/MatchDetailPage.tsx b/apps/web/src/pages/MatchDetailPage.tsx index aa303d1f..4cb92c48 100644 --- a/apps/web/src/pages/MatchDetailPage.tsx +++ b/apps/web/src/pages/MatchDetailPage.tsx @@ -6,6 +6,7 @@ import { useDdragonManifest, useMatch, useMe, + usePollTournamentResult, useTournamentCodeStats, } from '../api/hooks'; import { @@ -396,6 +397,97 @@ function PoolStatsHint({ enabled }: { enabled: boolean }) { ); } +function formatGameDuration(seconds: number) { + const minutes = Math.floor(seconds / 60); + const rest = seconds % 60; + return `${minutes}:${String(rest).padStart(2, '0')}`; +} + +function resultSideLabel(side: 'blue' | 'red') { + return side === 'blue' ? '블루팀' : '레드팀'; +} + +function resultSideClass(side: 'blue' | 'red') { + return side === 'blue' ? 'text-blue-400' : 'text-red-400'; +} + +function MatchResultPanel({ match }: { match: MatchDetailView }) { + if (!match.result) return null; + + const gamesByNumber = new Map( + match.result.games.map((game) => [game.gameNumber, game]), + ); + const gameNumbers = Array.from( + { length: match.gameCount }, + (_, index) => index + 1, + ); + + return ( +
+
+
+
+ {match.result.blueScore} +
+
+ 블루팀 +
+
+
+ VS +
+
+
+ {match.result.redScore} +
+
+ 레드팀 +
+
+
+
+ {match.result.winner + ? `${match.result.winner} 승리` + : `결과 수집 중 · ${match.result.games.length}/${match.gameCount}경기`} +
+
+ {gameNumbers.map((gameNumber) => { + const game = gamesByNumber.get(gameNumber); + return ( +
+ + {gameNumber}경기 + + {game ? ( +
+ + {resultSideLabel(game.winnerSide)} 승 + + + {game.riotMatchId} + +
+ ) : ( + 대기 중 + )} + + {game ? formatGameDuration(game.gameDuration) : '-'} + +
+ ); + })} +
+
+ ); +} + export default function MatchDetailPage() { const { id } = useParams(); const navigate = useNavigate(); @@ -411,6 +503,9 @@ export default function MatchDetailPage() { const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID); const [blueCaptainUserId, setBlueCaptainUserId] = useState(''); const [redCaptainUserId, setRedCaptainUserId] = useState(''); + const pollTournamentResultMutation = usePollTournamentResult( + DEFAULT_COMMUNITY_ID, + ); const joinMatchMutation = useMutation({ mutationFn: () => @@ -461,6 +556,17 @@ export default function MatchDetailPage() { }, }); + function handlePollTournamentResult() { + if (!id) return; + pollTournamentResultMutation.mutate(id, { + onSuccess: async () => { + await queryClient.invalidateQueries({ + queryKey: ['match', DEFAULT_COMMUNITY_ID, id ?? null], + }); + }, + }); + } + useEffect(() => { const participants = matchQuery.data?.participants ?? []; if (!blueCaptainUserId && participants[0]) { @@ -578,39 +684,14 @@ export default function MatchDetailPage() { )} - {match.status === 'finished' && match.result && ( -
-
-
-
- {match.result.blueScore} -
-
- 블루팀 -
-
-
- VS -
-
-
- {match.result.redScore} -
-
- 레드팀 -
-
-
-
- {match.result.winner} 승리 -
+ {pollTournamentResultMutation.error instanceof Error && ( +
+ {pollTournamentResultMutation.error.message}
)} + +
{match.status === 'recruiting' ? ( @@ -747,6 +828,25 @@ export default function MatchDetailPage() { )} + {canManageAuction && + (match.status === 'team-built' || match.status === 'in-progress') && ( + +

+ Riot match-v5에서 토너먼트 코드가 붙은 경기를 다시 찾습니다. +

+ +
+ )} + {match.prizes.length > 0 && (