# Legacy 내전 데이터 백필 (Import) 플랜 > **대상**: codex 가 이어서 작업 가능한 수준의 실행 플랜 > **레포**: `/Users/dahyeon/source/lolympus-tournament-support` (pnpm workspace) > **작성 기준**: 2026-04-27 > **선행 작업**: > - `Riot-최근경기-플랜.md` (RiotRateLimiterService, RiotMatch 영구 저장) > - `Riot-소환사전적-플랜.md` (Redis Stream 작업 큐, leader election, ETA, deferUntil) > - `Tournament-Result-수집-플랜.md` (Match.result.games 매핑 로직, team-mapping 유틸, advanceMatchIfReady) > - `커뮤니티-내전-전적.md` / `stateful-stirring-moler.md` (커뮤니티 통계 페이지 — 본 plan 의 결과 데이터 소비처) --- ## 1. Context 본 시스템 도입 이전에 진행된 내전 매치는 우리 DB 에 없습니다. 그러나 Riot 은 `match-v5` raw 매치 데이터를 ~2년간 보관하므로, **커뮤니티 멤버 puuid 로 `type=tourney` 매치를 검색**해 backfill 할 수 있습니다. 목표: - **2024-05-01 부터** 모든 커뮤니티 멤버의 토너먼트 코드 매치를 import 해 우리 `Match` 도큐먼트로 변환 - 임계값 휴리스틱은 사용하지 않음 — **검색된 모든 매치 import** (외부 토너먼트가 섞여도 OK) - 추후 admin UI 에서 운영자가 잘못 들어온 매치를 직접 삭제 (사후 cleanup 정책) - 1 match-v5 = 1 Match 도큐먼트 (시리즈 묶음 X) - 야간/유휴 시간대 권장 선행 인프라가 갖춘 부분: - `RiotMatchService.getMatchIdsByPuuid({type: 'tourney', startTime, ...})` 가 이미 동작 - `RiotMatch.raw` 영구 저장 + `participantPuuids` 인덱스 - Redis Stream 작업 큐 (`riot:queue:high/low`) + RiotRateLimiterService 글로벌 throttle - `Tournament-Result-수집-플랜.md` 의 `team-mapping.util.ts` (puuid 합집합 다수결 → blue/red 매핑) 그대로 재사용 --- ## 2. 결정사항 (사용자 결정 2026-04-27) - **검색 시작일**: 2024-05-01 (UTC) - **검색 종료일**: 멤버별 `isActivated=false` 면 `user.updatedAt`, 활성이면 현재 - **멤버별 startTime override**: `max(2024-05-01, user.createdAt)` 자동 채움. 운영자가 admin UI 에서 멤버별 수정 가능 - **임계값 필터 사용 X**: 검색된 모든 `type=tourney` 매치 import (외부 토너먼트도 포함) - **시리즈 묶음 X**: 1 match-v5 = 1 Match 도큐먼트, `gameCount=1` - **사후 cleanup**: admin UI 에서 legacy 매치 목록 보고 단일/bulk 삭제 가능 - **idempotent**: 같은 `riotMatchId` 두 번 import 안 됨 - **부하**: 야간 batch 권장. 운영자가 명시적으로 트리거 --- ## 3. 데이터 모델 보강 ### 3.1 Match 확장 (legacy 추적) ```ts // schema.ts Match 추가 legacyImported?: boolean; // true 면 본 import 로 들어온 매치 legacyImportSource?: { importedAt: Date; importedBy: mongoose.Types.ObjectId; // 트리거한 admin userId triggeringPuuid: string; // 어떤 멤버 검색으로 처음 발견됐는지 audit jobId?: string; }; // MatchSchema legacyImported: { type: Boolean, default: false, index: true }, legacyImportSource: { importedAt: { type: Date }, importedBy: { type: Schema.Types.ObjectId, ref: 'user' }, triggeringPuuid: { type: String }, jobId: { type: String }, } ``` ### 3.2 RiotMatch unique 검사 이미 `RiotMatch.matchId` 가 unique 인덱스 (선행 plan 가정). 신규 import 시 이미 있으면 detail 재호출 skip. ### 3.3 Match `riotMatchId` 단위 unique 같은 match-v5 가 두 Match 도큐먼트로 들어오는 사고 방지: - Mongo aggregation 단계에서 `result.games[].riotMatchId` 가 이미 다른 Match 에 존재하면 skip - 또는 신규 sparse 인덱스: `Match.result.games.riotMatchId` (배열 인덱스, sparse) ```ts MatchSchema.index({ 'result.games.riotMatchId': 1 }, { sparse: true, unique: false }); ``` - unique 는 배열 element 단위로 보장하기 어려우니 application 레벨 검사 권장 ### 3.4 신규 컬렉션 — `LegacyImportJob` (운영 추적) ```ts export interface LegacyImportJob { jobId: string; communityId: mongoose.Types.ObjectId; triggeredBy: mongoose.Types.ObjectId; startedAt: Date; completedAt?: Date; state: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled'; // 입력 파라미터 windowStart: Date; // 기본 2024-05-01 windowEnd: Date; memberOverrides: Array<{ // 운영자가 수정한 멤버별 윈도우 userId: mongoose.Types.ObjectId; puuid: string; startTime: Date; endTime: Date; }>; // 진행 상황 totalMembers: number; processedMembers: number; totalDiscoveredMatchIds: number; // dedup 후 totalImportedMatches: number; totalSkippedDuplicate: number; totalErrors: number; errors?: Array<{ puuid?: string; matchId?: string; reason: string; at: Date }>; } ``` 운영 가시성: admin UI 에서 import job 진행률 표시 + 실패 매치 재시도. --- ## 4. Import 흐름 ### 4.1 트리거 ``` admin UI → POST /communities/:cid/legacy-import body: { windowStart?: '2024-05-01T00:00:00Z', windowEnd?: ISO, memberOverrides?: [{ userId, startTime, endTime }, ...] } 응답: { jobId, totalMembers, etaSeconds } ``` `@Roles('owner', 'admin')` 가드. 동시 동일 community 에 대한 job 1개로 제한 (Garnet `legacy-import:lock:` NX EX 6h). ### 4.2 sub-job 분할 선행 plan 의 작업 큐 패턴 그대로: - parent job: `LegacyImportJob` 생성 - 멤버별 sub-job N개 enqueue → `riot:queue:low` (priority low — 사용자 갱신/prefetch 보다 뒤) - payload: ```ts { kind: 'legacy-import-member', parentJobId, communityId, userId, puuid, startTime, // epoch seconds endTime, triggeredBy, } ``` ### 4.3 worker — 멤버 1명 처리 ```ts async function processLegacyImportMember(job: LegacyImportMemberJob) { let start = 0; const collectedMatchIds = new Set(); // 1. type=tourney list 페이지네이션 (count=100, region 'asia') while (true) { const ids = await matchService.getMatchIdsByPuuid(job.puuid, { type: 'tourney', startTime: Math.floor(job.startTime.getTime() / 1000), endTime: Math.floor(job.endTime.getTime() / 1000), start, count: 100, region: 'asia', }); ids.forEach((id) => collectedMatchIds.add(id)); if (ids.length < 100) break; start += 100; // throttle 통과 — 별도 sleep 불필요 } // 2. 각 matchId detail + Match 변환 for (const matchV5Id of collectedMatchIds) { await importSingleMatch(matchV5Id, { communityId: job.communityId, triggeringPuuid: job.puuid, importedBy: job.triggeredBy, parentJobId: job.parentJobId, }); } await updateLegacyImportJobProgress(job.parentJobId, { processedMembers: 1, discovered: collectedMatchIds.size, }); } async function importSingleMatch(matchV5Id: string, ctx) { // dedup: 이미 우리 Match 에 있는지 const existing = await MatchModel.findOne({ 'result.games.riotMatchId': matchV5Id }); if (existing) { await incrementCounter('totalSkippedDuplicate'); return; } // RiotMatch raw 페치 (이미 있으면 cache hit) const detail = await ensureRiotMatchPersisted(matchV5Id); if (!detail.info.tournamentCode) return; // 안전: tourney 인데 코드 없는 비정상 케이스 skip // 우리 멤버 매핑 const community = await CommunityModel.findById(ctx.communityId); const userByPuuid = await buildUserByPuuidMap(ctx.communityId); const teams100Puuids = detail.info.participants.filter((p) => p.teamId === 100).map((p) => p.puuid); const teams200Puuids = detail.info.participants.filter((p) => p.teamId === 200).map((p) => p.puuid); const team100MembersInOurs = teams100Puuids.filter((p) => userByPuuid.has(p)).length; const team200MembersInOurs = teams200Puuids.filter((p) => userByPuuid.has(p)).length; // 외부 매치(우리 멤버 0명) 는 import 하지 않음 — 검색 결과에 잘못 들어온 케이스 가드 if (team100MembersInOurs + team200MembersInOurs === 0) return; // teamId → blue/red: 우리 멤버 더 많은 쪽이 blue (관습), 동수면 100=blue const team100IsBlue = team100MembersInOurs >= team200MembersInOurs; // Match 도큐먼트 생성 const match = await MatchModel.create({ communityId: ctx.communityId, title: `[Legacy] ${formatDate(detail.info.gameCreation)}`, description: 'Legacy import (자동 생성)', mapId: detail.info.mapId ?? 11, status: 'finished', scheduledAt: new Date(detail.info.gameCreation), teamBuiltAt: new Date(detail.info.gameCreation), maxParticipants: 10, gameCount: 1, tournamentCodeIds: [], // legacy 라 우리 풀 코드 없음 participants: buildParticipantsSnapshot(detail, userByPuuid), teams: buildTeams(detail, userByPuuid, team100IsBlue), result: { blueScore: 0, redScore: 0, games: [ buildGameResult(detail, userByPuuid, team100IsBlue, 1), ], riotMatchIds: [matchV5Id], }, legacyImported: true, legacyImportSource: { importedAt: new Date(), importedBy: ctx.importedBy, triggeringPuuid: ctx.triggeringPuuid, jobId: ctx.parentJobId, }, }); // result.winnerSide / blueScore / redScore 산정 const winnerSide = match.result!.games[0].winnerSide; match.result!.blueScore = winnerSide === 'blue' ? 1 : 0; match.result!.redScore = winnerSide === 'red' ? 1 : 0; match.result!.winnerSide = winnerSide; await match.save(); await incrementCounter('totalImportedMatches'); } ``` 핵심 헬퍼: - `ensureRiotMatchPersisted(matchV5Id)`: RiotMatch 컬렉션에 upsert. 이미 있으면 그대로 반환 (Riot API 호출 0회). - `buildUserByPuuidMap(communityId)`: 커뮤니티 멤버 puuid → User 역인덱스 (in-memory cache, job 단위). - `buildGameResult(detail, userByPuuid, team100IsBlue, gameNumber)`: 선행 plan `Tournament-Result-수집-플랜.md` `§4.4 computeGameResult` 함수 그대로 재사용. team mapping 만 override. ### 4.4 동시성 / dedup - **멤버 sub-job 간 동시성**: 두 멤버가 같은 매치에 있으면 두 worker 가 같은 matchV5Id 를 동시에 처리하려고 함. `importSingleMatch` 진입 시 Garnet `legacy-import:match:` NX EX 60s 락. 이미 잡혔으면 skip. - **재실행**: 같은 jobId 재실행 시 이미 처리된 멤버는 `LegacyImportJob.processedMembers` 기준 skip. ### 4.5 진행률 / ETA - worker 가 sub-job 끝낼 때마다 `LegacyImportJob.processedMembers++` - ETA: `(totalMembers - processedMembers) × avgMemberSeconds` - avgMemberSeconds 기본 60 (멤버당 list 1~3 페이지 + detail 10~50건 가정), 실제 처리 시간으로 EWMA 갱신 - admin UI 가 5초 polling 으로 진행률 표시 ### 4.6 cancel - `POST /legacy-import-jobs/:jobId/cancel` (admin) - `LegacyImportJob.state='cancelled'` 마킹 → worker 가 sub-job pickup 직후 state 확인 → cancelled 면 즉시 ack 후 skip --- ## 5. Admin UI ### 5.1 신규 페이지 `apps/web/src/pages/admin/LegacyImportPage.tsx` - 라우트: `/admin/communities/:cid/legacy-import` - `@Roles('owner', 'admin')` 가드 (useMe + role 분기) #### 화면 구성 ``` ┌────────────────────────────────────────────┐ │ Legacy 내전 백필 │ ├────────────────────────────────────────────┤ │ 검색 윈도우 │ │ 시작일 [2024-05-01 ▾] 종료일 [지금 ▾] │ ├────────────────────────────────────────────┤ │ 멤버별 윈도우 (자동 채움 + 수정 가능) │ │ ┌──────────┬─────────────┬──────────┐ │ │ │ 멤버명 │ 시작일 │ 종료일 │ │ │ │ 홍길동 │ 2024-05-01 │ 지금 │ │ │ │ 이순신 │ 2024-08-15 │ 2025-12-31│ │ │ └──────────┴─────────────┴──────────┘ │ ├────────────────────────────────────────────┤ │ [백필 시작] (확인 모달 → 예상 ETA 표시) │ ├────────────────────────────────────────────┤ │ 진행 중인 작업 │ │ - jobId xxx: 23/100 멤버 처리 중... │ │ 발견 매치 142개 / import 89개 / 중복 53 │ ├────────────────────────────────────────────┤ │ 과거 작업 (최근 10개) │ │ - jobId yyy: 완료, 100/100, import 412 │ └────────────────────────────────────────────┘ ``` ### 5.2 신규 페이지 — Legacy 매치 cleanup `apps/web/src/pages/admin/LegacyMatchesPage.tsx` - 라우트: `/admin/communities/:cid/legacy-matches` - legacy 매치 목록 (`legacyImported=true` 필터) — 시간순 / 멤버 인원수 정렬 - 각 row: 매치 ID / 시간 / 우리 멤버 N명 / 외부 puuid 수 / 챔피언 미니 + **삭제 버튼** - bulk select + 일괄 삭제 - 확인 모달 ("이 매치는 영구 삭제됩니다. RiotMatch raw 는 유지됩니다.") ### 5.3 신규 엔드포인트 | Method | Path | 권한 | 용도 | |---|---|---|---| | POST | `/communities/:cid/legacy-import` | `owner/admin` | import 트리거 | | GET | `/communities/:cid/legacy-import-jobs` | `owner/admin` | job 목록 | | GET | `/communities/:cid/legacy-import-jobs/:jobId` | `owner/admin` | job 상세 | | POST | `/communities/:cid/legacy-import-jobs/:jobId/cancel` | `owner/admin` | 취소 | | GET | `/communities/:cid/legacy-matches` | `owner/admin` | legacy 매치 목록 (페이지네이션) | | DELETE | `/matches/:id` | `owner/admin` | 단일 매치 삭제 (legacy 외 일반 매치도 가능) | | POST | `/communities/:cid/legacy-matches/bulk-delete` | `owner/admin` | bulk 삭제 | `Match` 삭제 시 부수 효과: - `tournamentCodeIds` 가 비어있으므로 풀 release 불필요 - `MatchHistoryCache` invalidate (`riot:communitystats:*::*` prefix scan delete) — `community-stats.service` 의 invalidate 헬퍼 재사용 --- ## 6. 변경 사항 (파일 단위) ### 6.1 백엔드 ``` apps/api/src/modules/legacy-import/ legacy-import.module.ts legacy-import.service.ts # enqueue + status + cancel legacy-import.worker.ts # 작업 큐 dispatch (kind=legacy-import-member) legacy-import.controller.ts legacy-import.types.ts match-builder.util.ts # buildParticipantsSnapshot / buildTeams / buildGameResult ``` 수정: - `apps/api/src/modules/global/database/schema.ts` — `Match.legacyImported`, `Match.legacyImportSource`, 신규 인덱스, `LegacyImportJob` 컬렉션 등록 - `apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts` — `kind === 'legacy-import-member'` dispatch 추가 - `apps/api/src/modules/match/match.service.ts` — `delete(matchId)` 메서드 + community-stats invalidate 호출 - `apps/api/src/modules/match/match.controller.ts` — `DELETE /matches/:id` 엔드포인트 - `apps/api/src/app.module.ts` — `LegacyImportModule` import ### 6.2 프런트 ``` apps/web/src/pages/admin/LegacyImportPage.tsx apps/web/src/pages/admin/LegacyMatchesPage.tsx apps/web/src/components/admin/legacy/ MemberWindowTable.tsx # 멤버별 윈도우 수정 폼 LegacyImportJobProgress.tsx LegacyMatchListRow.tsx ``` 수정: - `apps/web/src/App.tsx` — 2 신규 admin 라우트 - `apps/web/src/api/hooks.ts` — `useLegacyImportTrigger / useLegacyImportJobs / useLegacyMatches / useDeleteMatch` - `apps/web/src/api/types.ts` — 응답 타입 --- ## 7. 단위 테스트 - `legacy-import.service.spec.ts` - parent job 생성 + 멤버별 sub-job N개 enqueue - 동일 cid 동시 트리거 시 두 번째 거부 (Garnet 락) - cancel 호출 시 state='cancelled', worker 가 다음 pickup 시 skip - `legacy-import.worker.spec.ts` - `importSingleMatch`: 이미 있는 riotMatchId → totalSkippedDuplicate++ - 외부 매치 (우리 멤버 0명) → import 안 됨 + 에러 카운트 X - 우리 멤버 1명만 + 외부 9명 → 정상 import (휴리스틱 X 라 통과) - team mapping: team100 우리 3명 vs team200 우리 0명 → team100=blue - `match-builder.util.spec.ts` - `buildGameResult` (Tournament-Result `computeGameResult` 재사용 검증) - `buildTeams`: 우리 멤버 puuid → userId 매핑, 외부 puuid 는 teams 에서 제외 - `match.service.spec.ts` - `delete(matchId)`: 매치 삭제 + cache invalidate 호출 확인 --- ## 8. Rollout 1. (PR-1) `Match` 스키마 확장 (legacy 필드 + 인덱스) + `LegacyImportJob` 컬렉션 + 모델 등록 2. (PR-2) `match-builder.util.ts` (선행 plan `computeGameResult` 재사용 wrapping) + 단위 테스트 3. (PR-3) `LegacyImportService.enqueue / cancel / status` + parent job + sub-job 분할 4. (PR-4) `LegacyImportWorker` (worker dispatch + `importSingleMatch`) + 단위 테스트 5. (PR-5) `DELETE /matches/:id` 엔드포인트 + community-stats cache invalidate 통합 6. (PR-6) admin 트리거 페이지 (`LegacyImportPage`) — 윈도우 폼 + ETA 표시 + 진행률 polling 7. (PR-7) admin cleanup 페이지 (`LegacyMatchesPage`) — 매치 목록 + bulk 삭제 8. (PR-8) 운영 모니터링 (job 진행률 / 멤버당 처리 시간 / 외부 매치 비율 로그) 9. (Phase 후속) 자동 주기 재실행 (월 1회 등) — 1차에선 manual only --- ## 9. 추가 고려사항 ### 확정 (사용자 결정 2026-04-27) - **검색 시작일 2024-05-01**, 종료일 멤버 활성/비활성 따라 자동 - **멤버별 startTime override**: admin UI 에서 자동 채움 + 수정 가능 - **임계값 필터 X**: 검색된 모든 매치 import (외부 매치도 포함) - **시리즈 묶음 X**: 1 match-v5 = 1 Match, gameCount=1 - **사후 cleanup**: admin UI 에서 단일/bulk 삭제 - **idempotent**: 같은 riotMatchId 두 번 import 안 됨 ### 권장 (운영 후 확인) 1. **외부 매치 비율 로그** — `team100MembersInOurs + team200MembersInOurs` 별 분포를 import job 끝에 통계로 남기기. 운영자가 cleanup 우선순위 잡기 좋음. 2. **백필 매치의 title 컨벤션** — `[Legacy] 2024-08-15` 형식. 운영자가 cleanup 페이지에서 한눈에 식별. 3. **DELETE /matches/:id 가드** — `legacyImported=true` 외 일반 매치 삭제는 무서운 작업. 일반 매치 삭제 시 추가 확인 모달 또는 별도 엔드포인트로 분리. 4. **백필 매치의 participants snapshot** — `Match.participants[]` 는 보통 매치 신청 단계에서 채워지지만, legacy 라 신청 흐름이 없음. detail.info.participants 에서 우리 멤버만 추출해 채움. preferredPositions / tier 는 비움 (필수 아님 가정). 5. **mapId 결정** — `detail.info.mapId` 가 11(소협) 외 다른 값일 수 있음. 그대로 저장. 통계 페이지에서 mapId 필터로 분리 가능. 6. **시간대 권장** — admin UI 에 "야간 배치 권장" 안내 + 큐가 비어있는 시간대 표시 (Phase 후속). 7. **에러 매치 격리** — `LegacyImportJob.errors[]` 에 puuid+matchId+reason 보관. admin UI 에서 재시도 버튼. 8. **선행 plan 의 결과 수집 워커와의 충돌** — legacy import 가 만든 Match 는 `tournamentCodeIds=[]` 라 결과 수집 워커 (`maybeAdvanceMatch`) 가 트리거되지 않음. 자연 분리. ### 추후 (Phase 후속) - 자동 주기 재실행 (월 1회 cron) - 외부 매치 자동 분류 / 분리 (예: 멤버 ≥ 4명 = 우리 내전, < 4명 = 외부) 옵션 — UI 토글 - legacy 매치도 stateful-stirring-moler.md 의 community 통계 페이지에 자동 포함됨 (별도 분기 필요 없음 — `result.games[]` 형태가 같음) --- ## 10. Done 정의 - `Match.legacyImported` + `Match.legacyImportSource` + `LegacyImportJob` 컬렉션 + 인덱스 추가 - admin 이 `LegacyImportPage` 에서 윈도우/멤버 override 입력 후 트리거 → ETA 토스트 + 진행률 polling - worker 가 멤버별 `type=tourney` list + detail 페치 → Match 도큐먼트 생성, `result.games[0]` 채워짐 - 같은 매치 두 번 import 안 됨 (Garnet 락 + Match application 검사) - 우리 멤버 0명 매치는 자동 skip (외부 매치 가드) - import job 진행률 / 발견 / import / 중복 / 에러 카운트 정확 - admin 이 `LegacyMatchesPage` 에서 잘못된 매치 단일/bulk 삭제 가능, 삭제 시 community-stats 캐시 invalidate - 동일 cid 에 대한 동시 import 트리거 거부 (Garnet 락) - cancel 동작 - Riot 429 0건 (글로벌 throttle 통과) - 단위 테스트 통과 - legacy 매치가 `stateful-stirring-moler.md` 의 community 통계 페이지에 자동 포함됨