Compare commits

..
Author SHA1 Message Date
dahyeon 8d741ef9a7 test(auction): add two-node Docker failure integration suite
Exercise Nginx routing, Mongo transaction ordering, history backfills, Undo, Pub/Sub TCP loss, safety polling, resync, and reconnection. Keep fixtures and results isolated from production and git.
2026-11-12 01:49:35 +09:00
dahyeon 23a0a3f8dd perf(auction): reduce polling with verified socket recovery
Keep fixed 30-second safety polling with separate recovery polling, confirm persistent heartbeat gaps, and refresh shared history after durable writes.
2026-11-12 01:49:27 +09:00
dahyeon e349684523 feat: expand auction emoji reactions to sixteen 2026-11-11 22:42:18 +09:00
dahyeon 9d7c888b0a fix: migrate deprecated APIs and patch vulnerable dependencies
Use current Mongoose, NATS, React, and ESLint APIs. Upgrade Vite and other affected dependencies, restrict the compatibility plugin to resolved module IDs, and keep qs unchanged.
2026-11-11 22:41:42 +09:00
dahyeon 5882585f69 fix: upgrade mongoose to 9.11.4 and align community model type 2026-11-11 20:26:38 +09:00
dahyeon 2d8027cb16 fix: preserve literal types for mongoose queries and seed data 2026-11-11 20:21:51 +09:00
dahyeon fbf22284e8 fix: use explicit match id in temporary match seed 2026-11-11 20:18:14 +09:00
dahyeon 6efbd50db7 fix: update dependencies to resolve critical audit findings 2026-11-11 20:15:51 +09:00
dahyeon 3f68997b9a style: format community stats service tests 2026-11-11 20:10:47 +09:00
dahyeon be4de61bb7 feat: enhance auction interactions and player statistics UI 2026-11-11 20:06:22 +09:00
dahyeonandClaude Fable 5.2 6c582ba3cf feat(web): use a pixel-art medal for recent match winners
Swap the lucide trophy in the home recent results for a hand-drawn
pixel medal, keep the two alternative trophy drafts as assets, and
tune the gold text tokens to match.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 13:48:48 +09:00
dahyeonandClaude Fable 5.2 9064340584 refactor(web): restyle home schedule and results as divided lists
Replace the panel cards on the home page with section lists separated
by horizontal rules, sharing one schedule row layout. Remove the
obsolete home history test and record the design QA notes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 13:48:41 +09:00
dahyeon cc358697d4 fix(web): consolidate player search in stats page 2026-11-11 02:10:37 +09:00
dahyeon f6686bbf17 fix(api): resolve formatting and iterator lint errors 2026-11-11 02:06:40 +09:00
dahyeon 0d7617e2d2 feat: connect tournament views to APIs and recover archived stats
Remove development previews and complete hall of fame, match history, official results, and multi-kill API integration.

Fix active match pagination and team-ready controls, preserve basic scoreboards, and recover statistics when Riot archives arrive.

Use bounded in-process cache invalidation retries and add the Riot match lookup index migration with regression coverage.
2026-11-11 02:00:35 +09:00
dahyeon 20e1e6ec04 feat(web): show winning teams in recent match results 2026-11-10 23:05:59 +09:00
dahyeon 664af15255 feat: refresh the home page and separate match event types
Add an inhouse hero, Hall of Fame, rankings, and event-specific schedules. Carry the event type through the API and admin tools, and improve results and player history displays.
2026-11-10 22:13:55 +09:00
dahyeon 7e0cd7cb19 fix: keep best-of-three grand finals open for results
Allow a separate grand final format and repair prematurely completed finals without dropping accepted games. Replay the correction record alongside subsequent results.
2026-11-10 18:49:26 +09:00
dahyeon 38a89b5374 feat: improve tournament workflows and prune outdated docs 2026-11-10 15:31:19 +09:00
dahyeon da7b502936 feat(web): refresh the app with Astryx and coral branding 2026-11-10 13:35:11 +09:00
dahyeon f649490cd2 fix(auction): harden lifecycle and durable bid storage
Serialize lifecycle changes and make cancellation, deadlines, and match side effects recoverable and idempotent.

Archive accepted bids durably, quarantine invalid payloads, and preserve compatibility with empty round IDs. Synchronize HTTP polling and socket state with scoped resync events.

Add cancellation cleanup index migration and regression coverage. Validated with 744 API tests, 65 Redis integration tests, and 28 Mongo integration tests.
2026-11-09 23:24:11 +09:00
dahyeon f2eec479d9 fix(api): correct champion history and deduplicate stats builds
Apply participant and champion filters before pagination and exclude timeline payloads. Route result statistics through the durable outbox, reuse current fragments, and serialize projection effects without spending retries on contention.

Validated with 716 API tests, 32 isolated Redis integration tests, API typecheck and build, and lint on changed files.
2026-11-09 18:40:51 +09:00
dahyeon ef141a13d0 fix(web): align staging redirect and release identifiers 2026-11-09 18:04:16 +09:00
dahyeon f622ee5b1f chore: remove legacy agent and skill configuration 2026-11-09 18:04:02 +09:00
dahyeon 4b8ccf0077 fix: harden result polling and Redis 8.10 operations
Preserve tournament result jobs through lock contention and transient failures,
atomically schedule retries before acknowledgement, and publish initial polls
after releasing the preparation lock.

Fix Redis connection blocking, durability Hash cleanup, duplicate auction
request ordering, and scheduled-job promotion. Use native Redis 8.10 stream,
lock, counter, and field-expiring cache operations with invalidation fencing.

Repair 90 test type errors and add a repeatable API typecheck command.

Validation: 704 API tests, 129 web tests, 31 real Redis integration tests,
3 dependency checks, workspace type checks and builds, and changed-file lint.
2026-11-09 17:33:13 +09:00
dahyeon 0c4c4239ec fix(redis): share Garnet endpoint and update database versions 2026-11-09 16:30:12 +09:00
dahyeon 9117c9c0a4 fix(deps): resolve production high and critical vulnerabilities
Pin vulnerable transitive dependencies to patched releases and replace Infisical SDK bootstrap calls with a compatible HTTP client. Add dependency-security and secret-loading regression coverage.
2026-11-07 20:21:54 +09:00
dahyeon 5bc748dc4d fix(auction): prevent skipped players and incomplete completion 2026-11-05 23:14:14 +09:00
dahyeon de84ad5309 Merge pull request 'fix(dakao): clarify command usage messages' (#15) from release/88 into main
Reviewed-on: #15
2026-09-26 15:37:04 +00:00
dahyeon f223157542 fix(dakao): clarify command usage messages 2026-09-26 08:36:27 -07:00
dahyeon cd1525c87a Merge pull request 'chore: remove bundled skills directory' (#14) from release/88 into main
Reviewed-on: #14
2026-09-19 11:25:40 +00:00
dahyeon 337970a12b chore: remove bundled skills directory 2026-09-19 20:22:13 +09:00
dahyeon 58e24ccd75 Merge pull request 'fix(deps): patch Socket.IO parser, nanoid and multer vulnerabilities' (#13) from release/88 into main
Reviewed-on: #13
2026-09-19 10:51:05 +00:00
dahyeon 827fc5b6b4 fix(deps): patch Socket.IO parser, nanoid and multer vulnerabilities 2026-09-19 19:50:46 +09:00
dahyeon 384d460ad6 Merge pull request 'feat(dakao): transfer existing users to new KakaoTalk IDs' (#12) from release/88 into main
Reviewed-on: #12
2026-09-19 10:44:08 +00:00
dahyeon 71085d0ac4 feat(dakao): transfer existing users to new KakaoTalk IDs 2026-09-19 19:40:35 +09:00
dahyeon 904f1fc4a4 Merge pull request 'refactor(web): hide history connection status' (#11) from agent/hide-history-realtime-status into main
Reviewed-on: #11
2026-07-25 18:07:21 +00:00
dahyeon f526257d9c refactor(web): hide history connection status 2026-07-25 11:06:28 -07:00
dahyeon 34a47c053e Merge pull request 'feat(api): refresh Riot ID during background updates' (#10) from agent/refresh-riot-id-by-puuid into main
Reviewed-on: #10
2026-07-25 16:13:18 +00:00
dahyeon e3f39fd8b8 feat(api): refresh Riot ID during background updates 2026-07-25 09:08:29 -07:00
dahyeon 4385ba7b8b Merge pull request 'feat(api): refresh Riot ID by PUUID' (#9) from agent/refresh-riot-id-by-puuid into main
Reviewed-on: #9
2026-07-25 15:38:33 +00:00
dahyeon 9cd5850d43 feat(api): refresh Riot ID by PUUID 2026-07-25 08:37:42 -07:00
dahyeon 79534cf43c Merge pull request 'refactor(web): remove redundant history result column' (#8) from agent/remove-history-result-column into main
Reviewed-on: #8
2026-07-25 14:38:57 +00:00
dahyeon 03be85d07b refactor(web): remove redundant history result column 2026-07-25 07:37:32 -07:00
dahyeon d269bdd92b Merge pull request 'chore(deps): resolve high audit findings' (#7) from release/87 into main
Reviewed-on: #7
2026-07-25 08:52:22 +00:00
dahyeon 2bac89d3dc chore(deps): resolve high audit findings
Upgrade direct dependencies and pin patched transitive versions so the high-severity pnpm audit gate passes. Document the dev-only brace-expansion exception and the separate Mongoose type-migration follow-up.
2026-07-25 01:51:00 -07:00
dahyeon 760da1cbea Merge pull request 'fix(dakao): hide started matches from schedule' (#6) from release/87 into main
Reviewed-on: #6
2026-07-25 08:07:42 +00:00
dahyeon ca786fd80a fix(dakao): hide started matches from schedule 2026-07-25 01:01:57 -07:00
dahyeon ac0d2b53f0 Merge pull request 'fix(web): satisfy React hook lint rules' (#5) from release/87 into main
Reviewed-on: #5
2026-07-25 06:40:40 +00:00
dahyeon a4215f86fb fix(web): satisfy React hook lint rules 2026-07-24 22:36:53 -07:00
dahyeon a24726d7da Merge pull request 'fix(api): eliminate unsafe lint warnings' (#4) from release/87 into main
Reviewed-on: #4
2026-07-25 05:23:15 +00:00
dahyeon bb68be14fa fix(api): eliminate unsafe lint warnings 2026-07-24 22:16:53 -07:00
dahyeon 9e2f2c61e7 Merge pull request 'release/87' (#3) from release/87 into main
Reviewed-on: #3
2026-07-25 04:59:34 +00:00
dahyeon fd1fa2366c fix(api): resolve lint errors 2026-07-24 21:52:35 -07:00
dahyeon 96fede9fe5 style(api): apply prettier formatting 2026-07-24 21:42:28 -07:00
dahyeon 80fef25af3 chore: upgrade runtime to Node.js 26 2026-07-18 05:21:49 +00:00
dahyeon 1f75c6318a Merge pull request 'release/86' (#2) from release/86 into main
Reviewed-on: #2
2026-07-15 08:56:05 +00:00
dahyeon 8ec9edc35f feat(web): align double-elimination winner connector rails 2026-07-15 01:41:52 -07:00
dahyeon 61f1db0e6a fix(web): align bracket score-card row geometry 2026-07-15 01:06:26 -07:00
dahyeon c9140b8622 feat: unify competition schedule and results 2026-07-15 01:01:49 -07:00
dahyeon 4e10998794 chore: add macOS Playwright MCP config 2026-07-15 00:18:28 -07:00
dahyeon b115072005 feat: polish double-elimination bracket navigation
Highlight connected routes, add readable round labels and accessible path descriptions, widen routing gaps, and centralize brand colors for winner progression.
2026-07-13 23:17:19 -07:00
dahyeon 03e88a03bc feat: improve series score card presentation
Show outcome-aware labels and scores, prioritize readable match names, and provide complete accessible summaries for bracket cards.
2026-07-13 23:16:43 -07:00
dahyeon 43c25c05cd feat(web): improve competition result history
Prioritize match outcomes, distinguish adjudicated results, and preserve detail context when navigating back.
2026-07-13 23:04:56 -07:00
dahyeon dc77b37494 feat(web): align team match names with bracket 2026-07-13 22:41:16 -07:00
dahyeon bb32c26694 feat(web): redesign team progress experience 2026-07-13 21:40:01 -07:00
dahyeon 81b951889f test(web): specify team progress presentation 2026-07-13 21:16:23 -07:00
dahyeon 96bae0ce28 feat(web): add match detail tabs 2026-07-14 03:22:33 +00:00
dahyeon a88562b208 fix: stabilize competition results flow 2026-07-13 13:55:08 +00:00
dahyeon 3bd3120eb1 feat: link competition games to detail analysis
Route each result-history Game by its global display number and preserve the Competition return target. Refuse stale detail fallbacks so a missing requested Game cannot silently show another Game.
2026-07-13 10:41:44 +00:00
dahyeon 3c60081ece feat: add competition series result history 2026-07-13 09:39:26 +00:00
dahyeon aa675199af feat: enrich internal match game analysis 2026-07-13 09:35:25 +00:00
dahyeon 9f698a8fec test: define competition series history 2026-07-13 09:22:12 +00:00
dahyeon 075fb52848 feat: render double-elimination bracket 2026-07-13 08:37:52 +00:00
dahyeon 738d274095 fix: include contracts workspace in api image 2026-07-13 05:52:59 +00:00
dahyeon ef47de7e4f fix: recover legacy tournament code transitions 2026-07-13 05:34:12 +00:00
dahyeon 489d040d8f fix: normalize reused tournament code lifecycle 2026-07-13 04:52:29 +00:00
dahyeon 6b1c450752 fix: harden competition migration recovery 2026-07-13 04:33:35 +00:00
dahyeon bbcb2f43dc test: harden competition migration assertions 2026-07-13 03:59:52 +00:00
dahyeon a307780752 fix: preserve legacy competition slot identity 2026-07-13 03:56:22 +00:00
dahyeon c2f89f9cb2 feat: preserve explicit round robin pairings 2026-07-13 03:50:32 +00:00
dahyeon 640e593676 docs: specify legacy slot migration rules 2026-07-13 03:41:39 +00:00
dahyeon ee96f8d48b fix: normalize missing legacy match game mode 2026-07-13 03:13:28 +00:00
dahyeon 683d602d63 fix: close competition cutover integrity gaps 2026-07-12 21:22:22 +00:00
dahyeon 7ea2002975 refactor: harden competition persistence type boundaries 2026-07-12 20:18:48 +00:00
dahyeon ec92494211 style: normalize competition contract endings 2026-07-12 20:13:28 +00:00
dahyeon 6bddb666fc refactor: cut web results over to competition projections 2026-07-12 20:11:24 +00:00
dahyeon 7db97c540b refactor: import historical results as competition facts 2026-07-12 20:08:29 +00:00
dahyeon 6aa2cb9009 fix: reject ambiguous Riot winner evidence 2026-07-12 20:08:12 +00:00
dahyeon 575cd911cb refactor: remove live legacy bracket mode 2026-07-12 20:05:25 +00:00
dahyeon 78a2c7cf0d fix: reject unfinishable first-to rules 2026-07-12 20:01:22 +00:00
dahyeon 0c2c7b59fc test: cover full double elimination projection 2026-07-12 19:59:57 +00:00
dahyeon 5049220e03 feat: deliver competition projection outbox effects 2026-07-12 19:57:47 +00:00
dahyeon ab9c48b1e6 refactor: cut tournament results over to competition facts 2026-07-12 19:53:04 +00:00
dahyeon 2958106e42 refactor: remove legacy match result writers 2026-07-12 19:47:53 +00:00
dahyeon ce07bfa0c8 fix: make competition reversals replayable 2026-07-12 19:47:34 +00:00
dahyeon 4d6fa2625e fix: guard competition stats rebuild revisions 2026-07-12 19:40:29 +00:00
dahyeon ee4c3eeb27 feat: add resumable competition migration runner 2026-07-12 19:34:52 +00:00
dahyeon 55e5b8df70 feat: expose revision-safe competition API 2026-07-12 19:34:15 +00:00
dahyeon f3286e7fd1 feat: preserve normalized accepted game facts 2026-07-12 19:32:19 +00:00
dahyeon e6e434d13f refactor: rebuild stats from competition revision 2026-07-12 19:28:04 +00:00
dahyeon 28e9ac1529 refactor: whitelist public match responses 2026-07-12 19:28:04 +00:00
dahyeon 874d785381 feat: plan deterministic competition migration 2026-07-12 19:08:38 +00:00
dahyeon 0c31a78df0 feat: execute competition result commands atomically 2026-07-12 19:08:18 +00:00
dahyeon 3b274b4ec2 feat: bootstrap competition aggregates from built teams 2026-07-12 19:08:10 +00:00
dahyeon 59b9ef79e5 feat: plan strict and cascade result reversals 2026-07-12 19:08:04 +00:00
dahyeon 5d4fe443d0 feat: project competition results by team identity 2026-07-12 19:01:22 +00:00
dahyeon 39112ff7ff build: wire shared competition contracts 2026-07-12 18:53:59 +00:00
dahyeon 2135af7107 feat: add competition persistence schemas 2026-07-12 18:49:37 +00:00
dahyeon 05a83db886 feat: define competition domain contracts 2026-07-12 18:44:26 +00:00
dahyeon f4ba3d524f docs: specify competition result domain 2026-07-12 18:36:38 +00:00
dahyeon 3a76fd8c88 chore: update api container runtime 2026-07-10 08:44:55 -07:00
dahyeon 3357d4c9c8 fix: repair double-elimination tournament codes 2026-07-10 08:44:42 -07:00
dahyeon 2d1c33f1e9 fix: hide bracket completion badges 2026-07-07 18:21:59 -07:00
dahyeon 03358cab4f fix: clone hydrated double-elimination brackets 2026-07-07 18:06:16 -07:00
dahyeon e188828423 feat: support double-elimination series games 2026-07-07 17:34:59 -07:00
dahyeon 2ee8c3807b perf: aggregate champion stats in MongoDB 2026-06-28 01:10:37 -07:00
dahyeon 88de2148ae feat: add API performance observability reporting 2026-06-28 00:40:05 -07:00
dahyeon 871a5fe78a chore: restore api test baseline and logging 2026-06-27 14:19:00 -07:00
dahyeon 60a006008a fix: harden multi-instance scheduler and worker execution 2026-06-27 13:19:43 -07:00
dahyeon df7dcd3a9c Harden match and tournament code concurrency 2026-06-27 12:28:05 -07:00
dahyeon 292e37aaac feat: add spell and rune tooltips 2026-06-26 23:29:47 -07:00
dahyeon 4906f665fd feat: polish match history UI 2026-06-26 23:10:42 -07:00
dahyeon 68afaf0cb8 feat: add item tooltips to match history 2026-06-26 23:07:06 -07:00
dahyeon 38c2d1f1b4 fix: disable automatic mongoose index creation 2026-06-26 10:49:38 -07:00
dahyeon 4ab5722759 chore: identify api mongo connections 2026-06-26 09:56:58 -07:00
dahyeon 51ea9c42d3 feat: route internal match game details by community 2026-06-26 09:41:04 -07:00
dahyeon d6e0bbf0e8 perf: optimize user internal history reads 2026-06-26 05:56:04 -07:00
dahyeon e80313e459 fix: refine double elimination bracket UI 2026-06-26 05:42:12 -07:00
dahyeon 9decc6866f fix: hide tournament code state from bracket 2026-06-26 05:09:16 -07:00
dahyeon e12f182e7f feat: add double elimination match mode 2026-06-26 05:00:08 -07:00
dahyeon b9aaf55193 perf: cache auction history summaries 2026-06-26 04:56:59 -07:00
dahyeon 8567948084 fix: recover stale auction durability history 2026-06-26 04:02:11 -07:00
dahyeon 37f1f4225d fix: prevent auction snapshot mutation 2026-06-26 03:12:13 -07:00
dahyeon 6dbc643c44 chore: add api new relic observability 2026-06-26 01:22:55 -07:00
dahyeon d2fc126fed chore: reflect observability updates in release 83 2026-06-25 23:57:51 -07:00
dahyeon ab721873f3 fix: prevent empty-team auction completion state 2026-06-25 05:26:09 -07:00
dahyeon 2984bd1604 fix: resume tournament result polling after delayed codes 2026-06-25 04:58:10 -07:00
dahyeon e50a683336 feat: enhance auction internal profile 2026-06-24 02:47:10 -07:00
dahyeon 9c69e35cfa fix: smooth auction timer bar 2026-06-23 22:48:41 -07:00
dahyeonandClaude Opus 4.8 55b80e62cd fix: recover auction client from rejected transitions
거부(특히 낙관적 동시성 CONFLICT)를 받은 클라가 낡은 상태에 멈춰 후속
액션을 반복 거부받던 문제를 해결한다.

- 서버: 거부 ack에 설명적 거부코드(auctionRejectionReason)와 resync 권장
  여부, 그리고 resync 권장 거부에 한해 최신 권위 state를 동봉한다. 구조 전환
  거부는 내부 code(CONFLICT 등)를 구조화해 던져 매핑 가능하게 한다.
- 클라: 거부 시 동봉된 state로 즉시 rebaseline(없으면 join으로 재요청)하고,
  "낡은 화면" 거부면 구조 액션을 1회 자동 재시도한다. 거부 문구를 거부코드
  기반 한국어로 매핑한다(error 이벤트 채널 포함).

신규 auction-rejection 모듈로 짧은 내부 코드를 맥락이 담긴 설명적 코드로
변환한다.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 13:26:45 -07:00
dahyeonandClaude Opus 4.8 09d304d782 fix: pass event bus to deadline scheduler in rehearsal script
직전 커밋에서 AuctionDeadlineScheduler 생성자에 추가한 AuctionEventBusService
인자를 rehearsal 스크립트의 직접 생성부에도 반영해 빌드를 복구한다.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 11:54:38 -07:00
dahyeonandClaude Opus 4.8 46c8007e94 fix: broadcast auction state immediately on auto expiry
자동 만료(EXPIRE_PREPARE → completePreparedExpiry)는 게이트웨이를 거치지
않아 만료 확정 결과를 클라이언트에 즉시 알리는 동기 broadcast가 없었다.
그 결과 클라는 입찰 라운드 revision에 멈춰, 0초 근처 입찰 직후 "다음" 등
후속 액션에서 stale 관측값으로 CONFLICT를 반복했다.

AuctionDeadlineScheduler에 AuctionEventBusService를 주입해 만료 확정 직후
최신 state를 1차 broadcast한다. durability worker의 방송은 Mongo 성공 +
~1초 tick에 묶인 크래시 복구 백업임을 주석으로 명확히 했다.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 11:49:48 -07:00
dahyeon b367328df0 Improve auction realtime bid responsiveness 2026-06-23 09:46:38 -07:00
dahyeon c6f5a7077f fix: clear auction cache after cancellation 2026-06-23 03:43:12 -07:00
dahyeon 7c372f0392 fix: fully cancel redis auctions 2026-06-23 03:34:45 -07:00
dahyeon e8bb20d988 feat: redesign auction engine with redis sot 2026-06-23 03:16:04 -07:00
dahyeon 737702d78c chore: point dev web api to shared host 2026-06-22 12:16:28 -07:00
dahyeon 98c2323ff2 fix: sync auction timer with server time 2026-06-22 12:16:18 -07:00
dahyeon d2fe4604dd fix: show solo queue tier graph in auction 2026-06-22 05:07:28 -07:00
dahyeon b0dc857463 fix: reserve auction points for remaining slots 2026-06-22 04:37:06 -07:00
dahyeon bac29ac933 feat: auto provision tournament codes 2026-06-20 02:29:30 -07:00
dahyeon 65bc214fb2 feat: add finished match detail tabs 2026-06-20 01:19:39 -07:00
dahyeon 0434a5db66 feat: refine match game detail ux 2026-06-20 01:04:03 -07:00
dahyeon 747adfcb11 feat: improve match game detail ux 2026-06-19 16:57:28 -07:00
dahyeon 7b5604873e feat: add match game detail analytics 2026-06-20 07:26:20 +09:00
dahyeon c6da2013bd feat: add team page tournament code replacement 2026-06-19 04:01:22 -07:00
dahyeon b9881fcb6f fix: allow public tournament code replacement 2026-06-19 03:56:44 -07:00
dahyeon 303886ed53 feat: allow tournament code replacement 2026-06-19 03:43:53 -07:00
dahyeon 1272c81fa9 chore: add round-robin match repair script 2026-06-19 02:33:18 -07:00
dahyeon ade5735dc2 refactor: remove legacy round-robin repair 2026-06-19 01:36:34 -07:00
dahyeon 7399968fe8 fix: repair legacy round-robin schedules 2026-06-19 01:31:27 -07:00
dahyeon 658592973e feat: add limited round-robin scheduling 2026-06-19 01:13:50 -07:00
dahyeon 24983aeb09 feat: allow admins to add match participants 2026-06-16 06:39:50 -07:00
dahyeon 8aff1be225 fix: align home page loading states 2026-06-09 19:13:34 -07:00
dahyeon c155f26272 Merge pull request 'Release 77' (#1) from release/77 into main
Reviewed-on: #1
2026-06-09 13:36:48 +00:00
dahyeon bb336391ff docs: make readme demo loop 2026-06-09 06:28:15 -07:00
dahyeon 3f4ddead72 docs: update release readme media 2026-06-09 06:25:41 -07:00
dahyeon 168e0eca66 docs: refresh readme for release 77 2026-06-09 06:17:45 -07:00
dahyeon e7eaa4f67d fix(web): stack mobile tier badges 2026-06-09 04:51:37 -07:00
dahyeon ad9bf93b52 fix(web): increase light mode text contrast 2026-06-09 04:48:18 -07:00
dahyeon 774707de65 fix(web): enlarge desktop position text 2026-06-09 04:03:00 -07:00
dahyeon e28a2646bf fix(web): add slight tier badge spacing 2026-06-09 04:01:37 -07:00
dahyeon 2916333d71 fix(web): align tier queue columns 2026-06-09 03:59:53 -07:00
dahyeon d3d5f2b348 fix(web): prevent logout button overflow 2026-06-09 03:54:11 -07:00
dahyeon 4657cd453c fix(web): scale match participant icons with text 2026-06-09 03:38:13 -07:00
dahyeon 577ce45b64 fix(web): align header and match badges with brand styling 2026-06-09 03:37:11 -07:00
dahyeon ee3e5935d6 fix(web): stabilize recruiting mobile participant list 2026-06-09 03:17:49 -07:00
dahyeon 5ba68ea134 fix(web): improve compact UI readability 2026-06-09 03:12:00 -07:00
dahyeon 12869a7e9e fix(web): stabilize participant filter table 2026-06-08 23:10:39 -07:00
dahyeon d10e2ab011 fix(web): keep history table shell during loading 2026-06-08 22:48:16 -07:00
dahyeon 170e42098a fix(web): stabilize history table columns 2026-06-08 22:32:22 -07:00
dahyeon fe7a482969 fix(web): localize history pagination loading 2026-06-08 22:24:20 -07:00
dahyeon aa07ec0304 feat(api): add dakao schedule links 2026-06-08 21:44:28 -07:00
dahyeon cd5a82aa93 fix(web): refine mobile history cards 2026-06-08 05:39:22 -07:00
dahyeon 7a62e52d60 fix(web): improve mobile team layout 2026-06-08 05:24:14 -07:00
dahyeon 6fc58fec1d feat(web): add legal footer 2026-06-08 04:50:29 -07:00
dahyeon f586542dc3 fix(web): split home matches by schedule 2026-06-08 04:44:12 -07:00
dahyeon 6697cd8ea1 feat(api): add dakao primary account command 2026-06-08 03:29:55 -07:00
dahyeon c435e8a6a5 fix(web): stabilize match tier queue alignment 2026-06-08 02:32:11 -07:00
dahyeon 15ae680ec7 fix(web): bind dark utilities to theme toggle 2026-06-08 02:25:59 -07:00
dahyeon bdea0287a5 refactor(web): centralize rank badge display 2026-06-08 02:20:34 -07:00
dahyeon b56728f843 fix(web): align match team table columns 2026-06-08 02:07:56 -07:00
dahyeon 7f2b34fd4b fix(web): stabilize layout when scrollbar changes 2026-06-08 02:02:03 -07:00
dahyeon 146349beb8 fix(web): tone down login link 2026-06-08 01:49:20 -07:00
dahyeon 326e0c66b6 feat(web): add persistent theme toggle 2026-06-08 01:46:59 -07:00
dahyeon edfb960e97 fix(web): highlight shared current peak tier 2026-06-08 01:41:23 -07:00
dahyeon b2d438785b fix(web): pad compact tier chart domain 2026-06-08 01:34:09 -07:00
dahyeon b6dad78d02 fix(web): add adaptive compact tier guides 2026-06-08 01:28:10 -07:00
dahyeon 42d4854f9c fix(web): center compact tier chart labels 2026-06-08 01:15:55 -07:00
dahyeon e9081d77c9 fix(web): keep auction tier labels inside chart 2026-06-08 01:07:39 -07:00
dahyeon 181beb85e5 refactor(web): simplify auction tier chart 2026-06-08 01:02:52 -07:00
dahyeon ebca348723 feat: show tier history in auction spotlight 2026-06-08 00:34:04 -07:00
dahyeon de8bc87940 fix: unify riot refresh rate gating 2026-06-07 11:11:12 -07:00
dahyeon 25f3ccad57 fix: delete acknowledged riot job stream entries 2026-06-07 10:13:29 -07:00
dahyeon 55ab5b27dc chore: update Cloudflare Pages deploy branch handling 2026-06-07 09:54:10 -07:00
dahyeon 1c0af891fa feat: run Riot background refresh by default 2026-06-07 09:51:51 -07:00
dahyeon 528744ebf6 fix: accept Riot league entries without leagueId 2026-06-07 09:51:37 -07:00
dahyeon bd52160d91 fix(web): resolve recharts vite interop 2026-06-07 09:01:02 -07:00
dahyeon c3a3eb46dd feat(web): add tier history chart 2026-06-07 08:11:43 -07:00
dahyeon be5383a2e9 fix(riot): persist refreshed tier state 2026-06-07 07:59:11 -07:00
dahyeon ef693fcf4a feat(auction): cancel active auction 2026-06-07 07:44:59 -07:00
dahyeon 8a9dd37755 chore(release): bump build number to 68 2026-06-07 07:44:32 -07:00
dahyeon 5ad0f8a1c2 feat: add auction chat 2026-06-07 07:20:35 -07:00
dahyeon c4f19d256d fix: refresh riot tiers from history jobs 2026-06-07 07:16:31 -07:00
dahyeon ad84bf1f89 feat(web): show participant position counts 2026-06-07 07:07:48 -07:00
dahyeon b711c63dcd fix(api): keep zero-bid auction passes open 2026-06-07 07:01:01 -07:00
dahyeon 6a192276e8 feat(admin): manage match participants 2026-06-07 06:51:35 -07:00
dahyeon 994a9fcad0 feat(web): filter match participants 2026-06-07 06:28:11 -07:00
dahyeon 2dae3c7cae chore(web): add start scripts for modes 2026-06-07 06:27:51 -07:00
dahyeon a896342429 chore(web): limit upcoming match cards 2026-06-07 06:03:30 -07:00
dahyeon 7b636ee793 fix: preserve dakao result subjects on outbox retry 2026-06-07 05:57:44 -07:00
dahyeon e63fba0286 feat: include dakao send result subjects 2026-06-07 05:30:53 -07:00
dahyeon 245a096606 chore(web): hide api live indicator 2026-06-07 05:00:20 -07:00
dahyeon 6e0afe84cd chore(deploy): add build number release flow 2026-06-07 04:54:08 -07:00
dahyeon 6accb4b166 chore(api): allow pages dev cors origins 2026-06-07 01:26:07 -07:00
dahyeon f3d05004ce chore(env): update staging api origin 2026-06-07 01:24:21 -07:00
dahyeon eadae789c8 chore(env): rename test environment to staging 2026-06-07 01:01:13 -07:00
dahyeon d0d578b2b0 feat(dakao): add jetstream outbox delivery flow 2026-06-07 00:35:18 -07:00
dahyeon 4ab3c3a135 chore(auction): remove unused chat panel prop 2026-06-06 21:58:19 -07:00
dahyeon 251eb6deb9 fix(api): send bearer tokens for authenticated requests 2026-06-06 21:57:52 -07:00
dahyeon b7886589cb chore(docker): let runtime set node env 2026-06-06 21:57:07 -07:00
dahyeon 33abda997f Default secrets to environment source 2026-06-06 13:12:48 -07:00
dahyeonandClaude Opus 4.7 85ba8044da feat(web): add pool sidebar and chat skeleton to auction page
Surface the remaining player pool (waiting + passed) on a left sidebar
so captains can see who still needs a team without revealing the auction
order — entries are sorted by summoner name. Reserve a right sidebar
for the upcoming chat integration.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-30 03:53:24 -07:00
dahyeon e306d696a9 feat: randomize auction player order 2026-05-30 03:15:01 -07:00
dahyeon da5f542292 feat: add agent skill workflows 2026-05-30 18:45:09 +09:00
dahyeon f62e0db849 docs: update project README 2026-05-13 14:12:35 +09:00
dahyeon 3176db8c48 docs: add project README 2026-05-13 13:51:05 +09:00
dahyeon 7620b1677a chore(repo): ignore local artifacts 2026-05-08 02:42:00 +09:00
dahyeon 1d7fdc9622 chore(app): wire remaining modules 2026-05-05 23:19:00 +09:00
dahyeon 9c05850cba chore(api): add data migrations 2026-05-02 22:23:00 +09:00
dahyeon b5aa58dde8 feat(api): handle Dakao match commands 2026-04-29 03:02:00 +09:00
dahyeon 3b2ac601a0 feat(api): handle Dakao registrations 2026-04-29 01:35:00 +09:00
dahyeon 404f7713b9 feat(api): parse Dakao commands 2026-04-28 23:58:00 +09:00
dahyeon ba3894cba2 feat(api): add Dakao integration 2026-04-28 22:37:00 +09:00
dahyeon 9ebdc9b61f feat(web): add team progress page 2026-04-27 02:51:00 +09:00
dahyeon 5fda22c36a feat(web): add match admin page 2026-04-27 01:26:00 +09:00
dahyeon 1e304f48e5 feat(web): add legacy import admin 2026-04-26 23:44:00 +09:00
dahyeon ad3c37c48c feat(api): add legacy import service 2026-04-26 22:16:00 +09:00
dahyeon f266d1de83 feat(web): add community stats pages 2026-04-25 01:38:00 +09:00
dahyeon 956e45ee59 feat(api): add match stats fragments 2026-04-24 23:53:00 +09:00
dahyeon b3b59d37fc feat(api): add community stats API 2026-04-24 22:28:00 +09:00
dahyeon fc81beec45 feat(api): add match history endpoints 2026-04-23 01:07:00 +09:00
dahyeon 3447162aa5 feat(api): collect tournament results 2026-04-22 23:48:00 +09:00
dahyeon 06c190a41f feat(api): add tournament result mapping 2026-04-22 22:21:00 +09:00
dahyeon 862d662a51 feat(web): add tournament code admin 2026-04-21 01:34:00 +09:00
dahyeon 95c8ed3c8b feat(api): add tournament code pool 2026-04-20 23:59:00 +09:00
dahyeon 6bad4861e6 feat(api): add tournament code helpers 2026-04-20 22:42:00 +09:00
dahyeon 422472a641 feat(web): add user history page 2026-04-19 03:10:00 +09:00
dahyeon 7e78b1f92d feat(api): add background refresh 2026-04-19 01:29:00 +09:00
dahyeon 4bc2df7bcc feat(api): add Riot refresh queue 2026-04-18 23:57:00 +09:00
dahyeon c212505ffe feat(api): add recent stats summaries 2026-04-18 22:24:00 +09:00
dahyeon 9ac777b5a4 feat(api): add recent match sync 2026-04-17 01:46:00 +09:00
dahyeon c07b040467 feat(api): add Riot rate limiter 2026-04-17 00:14:00 +09:00
dahyeon 78a8f136d0 feat(web): add auction page 2026-04-16 22:33:00 +09:00
dahyeon 3c8dce1e9b feat(api): add auction gateway 2026-04-15 02:18:00 +09:00
dahyeon b12f44424e feat(api): add auction service 2026-04-15 00:51:00 +09:00
dahyeon b4be06ae83 feat(web): add match detail page 2026-04-14 23:28:00 +09:00
dahyeon 041b1fc8b9 feat(web): add API hooks and mappers 2026-04-14 22:09:00 +09:00
dahyeon 87447a4f09 feat(api): add match management 2026-04-13 02:40:00 +09:00
dahyeon 6cd213a462 feat(api): add community endpoints 2026-04-13 01:12:00 +09:00
dahyeon caf517123b feat(api): add user profile endpoints 2026-04-12 23:46:00 +09:00
dahyeon d4b790fd86 feat(api): add auth guards 2026-04-12 22:17:00 +09:00
dahyeon 3a86676a12 feat(web): add auth and home pages 2026-04-11 02:31:00 +09:00
dahyeon 9fbb11c634 feat(web): add app shell 2026-04-11 00:58:00 +09:00
dahyeon 39f3221640 feat(web): add client utilities 2026-04-10 23:39:00 +09:00
dahyeon a796620b7f feat(web): add static assets 2026-04-10 22:26:00 +09:00
dahyeon 3a3e7938f5 feat(web): configure Vite app 2026-04-09 03:08:00 +09:00
dahyeon 9f6974c577 feat(api): add Riot webhook 2026-04-09 01:24:00 +09:00
dahyeon d6f52a8b15 feat(api): enrich Riot accounts 2026-04-08 23:55:00 +09:00
dahyeon 463c839782 feat(api): add Riot match and ddragon services 2026-04-08 22:41:00 +09:00
dahyeon 5361dc8adb feat(api): add Riot account services 2026-04-07 02:36:00 +09:00
dahyeon 54db90b0df feat(api): add Riot client types 2026-04-07 01:09:00 +09:00
dahyeon 2e311d9cbf feat(api): add shared infrastructure 2026-04-06 23:48:00 +09:00
dahyeon f24674b12c feat(api): add database schema 2026-04-06 22:34:00 +09:00
dahyeon 714349d519 feat(api): add database connection 2026-04-05 03:12:00 +09:00
dahyeon 7cde555bef feat(api): add app bootstrap 2026-04-05 01:43:00 +09:00
dahyeon a7820444fc chore(api): configure Nest app 2026-04-05 00:21:00 +09:00
dahyeon fa13bc48d4 chore(repo): add runtime config 2026-04-04 23:06:00 +09:00
dahyeon 6f891c36af chore(repo): set workspace baseline 2026-04-04 22:18:00 +09:00
660 changed files with 119504 additions and 30115 deletions

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
{
"version": "0.0.1",
"configurations": [
{
"name": "web-staging",
"runtimeExecutable": "pnpm",
"runtimeArgs": ["--filter", "web", "start:staging"],
"port": 5173
}
]
}
+4
View File
@@ -0,0 +1,4 @@
[mcp_servers.playwright_macos]
url = "http://100.96.0.26:8931/mcp"
tool_timeout_sec = 120
startup_timeout_sec = 30
+14 -4
View File
@@ -1,5 +1,5 @@
bin/
lib/
/lib/
dist/
node_modules/
.pnpm-store/
@@ -19,8 +19,18 @@ website/LICENSE
*.log
!.claude/settings.json
*.temp.MD
*.md
*.md
!README.md
!design-qa.md
!docs/specs/home-banner-production.md
!docs/specs/match-status-and-result-presentation.md
!docs/specs/information-visible-ui.md
!docs/ux-audit-2026-11-10/06-ui-improvement-review.md
!docs/ux-audit-2026-11-10/07-visual-design-review.md
/tmp/
/user-game-history/
/*.txt
/*.png
+1
View File
@@ -0,0 +1 @@
26
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 383 KiB

+1
View File
@@ -0,0 +1 @@
83
-43
View File
@@ -1,43 +0,0 @@
# Cloudflare Pages 배포
## 최초 1회 준비
```bash
pnpm --filter web pages:login
pnpm --filter web exec wrangler pages project create lolympus --production-branch main
```
프로젝트명을 바꾸려면 배포 시 `CF_PAGES_PROJECT_NAME` 환경변수로 지정한다.
## 환경 파일
Vite는 빌드 시점에 환경변수를 번들에 포함한다.
```bash
cp apps/web/.env.test.example apps/web/.env.test
cp apps/web/.env.production.example apps/web/.env.production
```
각 파일에서 API URL, community ID, MSAL 설정을 실제 값으로 채운다.
## 배포
```bash
pnpm deploy:web:test
pnpm deploy:web:prod
```
- `test`: `vite build --mode test` 후 Cloudflare Pages `test` preview branch로 배포
- `prod`: `vite build --mode production` 후 Cloudflare Pages production으로 배포
기본 Cloudflare Pages project name은 `lolympus`다.
```bash
CF_PAGES_PROJECT_NAME=lolympus-web pnpm deploy:web:prod
CF_PAGES_TEST_BRANCH=staging pnpm deploy:web:test
```
## SPA / 캐시
- `apps/web/public/_redirects`: React Router 경로 새로고침을 `/index.html`로 fallback
- `apps/web/public/_headers`: fingerprinted `/assets/*`는 1년 immutable 캐시, `index.html`은 no-cache
-481
View File
@@ -1,481 +0,0 @@
# Dakao NATS Command API
dakao는 NATS를 통해 외부 시스템으로부터 command를 받아 LOCO 세션에 반영할 수 있다.
현재 구현 기준으로 지원하는 command는 아래 2종이다.
- `chat.send-text`
기존 API. `text`와 `extra`를 그대로 받아 전송한다.
점진적으로 deprecated 예정.
- `chat.send-message`
신규 권장 API. `segments` 기반으로 텍스트, 멘션, 카카오톡 이모티콘을 조합해서 전송한다.
builder를 거치면서 semantic validation까지 수행한다.
## 개요
### 기본 subject
| 용도 | 기본 subject | 비고 |
| ------------------ | ------------------------------------ | --------------- |
| 레거시 텍스트 전송 | `dakao.command.chat.send-text.v1` | deprecated 예정 |
| 신규 메시지 전송 | `dakao.command.chat.send-message.v1` | 권장 |
### 관련 환경변수
| 키 | 의미 |
| ---------------------------------------------- | ------------------------------- |
| `DAKAO_NATS_COMMANDS_ENABLED` | `1`이면 command consumer 활성화 |
| `DAKAO_NATS_COMMAND_CHAT_SEND_TEXT_SUBJECT` | 레거시 subject override |
| `DAKAO_NATS_COMMAND_CHAT_SEND_MESSAGE_SUBJECT` | 신규 subject override |
### 전송 포맷
- NATS payload는 JSON object여야 한다.
- 내부 구현은 `JSON.stringify(...)`로 publish하고, subscribe 시 `JSON.parse(...)`로 역직렬화한다.
- 응답은 NATS의 transport-level reply가 아니라, command object 내부의 `replySubject` 필드를 사용해 별도 publish된다.
### subject와 `type`의 관계
운영 규약상 아래처럼 맞춰서 보내는 것을 권장한다.
- `dakao.command.chat.send-text.v1` 에는 `type: "chat.send-text"`
- `dakao.command.chat.send-message.v1` 에는 `type: "chat.send-message"`
현재 구현은 두 subject를 모두 구독한 뒤 `type`으로 실제 처리를 분기한다.
즉 subject와 type이 어긋나도 처리될 수 있지만, 운영 혼선을 막기 위해 반드시 맞춰서 보내는 것을 권장한다.
## 공통 Envelope
모든 command는 아래 envelope를 사용한다.
```json
{
"schema": "dakao.command.v1",
"id": "cmd-001",
"type": "chat.send-message",
"source": "my-service",
"correlationId": "trace-001",
"replySubject": "dakao.result.my-service",
"payload": {}
}
```
### 공통 필드
| 필드 | 타입 | 필수 | 설명 |
| --------------- | ------ | ---- | -------------------------------- |
| `schema` | string | Y | 현재는 반드시 `dakao.command.v1` |
| `id` | string | Y | command 고유 ID |
| `type` | string | Y | command 종류 |
| `source` | string | Y | producer 식별자 |
| `correlationId` | string | N | 추적용 상관관계 ID |
| `replySubject` | string | N | 결과를 publish할 subject |
| `payload` | object | Y | command 본문 |
### 공통 검증
- 문자열 필드인 `id`, `type`, `source`, `correlationId`, `replySubject`는 trim 후 빈 문자열이면 거부된다.
- 최상위 object와 payload는 정의되지 않은 필드를 허용하지 않는다.
- `replySubject`가 없으면 처리 결과는 publish되지 않는다.
## Command: `chat.send-text`
### 상태
- 레거시 API
- 기존 producer 호환성을 위해 유지 중
- `text`와 `extra`를 그대로 전달하므로, 멘션/이모티콘 semantic validation은 수행하지 않는다
### 권장 subject
```text
dakao.command.chat.send-text.v1
```
### Payload
```json
{
"chatroomId": "123456789012345678",
"text": "hello",
"attachment": {
"example": true
},
"extra": "{}"
}
```
| 필드 | 타입 | 필수 | 설명 |
| ------------ | ---------------- | ---- | ------------------------------------------------------- |
| `chatroomId` | string | Y | 채팅방 ID. 실운영에서는 decimal string 사용 권장 |
| `text` | string | Y | 보낼 메시지 본문 |
| `attachment` | string or object | N | 첨부 payload. object면 전송 직전에 JSON string으로 변환 |
| `extra` | string | N | LOCO `WRITE.extra` raw 값 |
### 동작
- 내부적으로 `client.sendMessage(chatroomId, text, { attachment, extra })` 로 전송한다.
- `extra`를 생략하면 최종 LOCO 전송 시 기본값 `"{}"` 가 사용된다.
- 이 API는 `extra` 구조를 검증하지 않는다.
### 예시
```json
{
"schema": "dakao.command.v1",
"id": "cmd-text-001",
"type": "chat.send-text",
"source": "admin-panel",
"replySubject": "dakao.result.admin-panel",
"payload": {
"chatroomId": "123456789012345678",
"text": "plain text message",
"extra": "{}"
}
}
```
## Command: `chat.send-message`
### 상태
- 신규 권장 API
- 텍스트, 멘션, 카카오톡 이모티콘을 조합해서 전송할 수 있다
- `buildLocoMessage(...)` 를 통해 최종 `text`와 `extra`를 생성한다
- Joi schema validation 이후 builder semantic validation이 한 번 더 수행된다
### 권장 subject
```text
dakao.command.chat.send-message.v1
```
### Payload
```json
{
"chatroomId": "123456789012345678",
"segments": [
{ "kind": "text", "text": "안녕하세요 " },
{
"kind": "mention",
"userId": "6215844374579825921",
"displayText": "날으는꼴뚜기/95/여/D"
},
{ "kind": "text", "text": " " },
{ "kind": "emoticon", "id": "1200281_004", "altText": "플라워" }
],
"attachment": {
"example": true
},
"type": 1,
"noSeen": false,
"scope": 1,
"silence": false
}
```
| 필드 | 타입 | 필수 | 설명 |
| ------------ | ---------------- | ---- | ------------------------------------------------------- |
| `chatroomId` | string | Y | 채팅방 ID. 실운영에서는 decimal string 사용 권장 |
| `segments` | array | Y | 메시지 세그먼트 배열. 최소 1개 이상 |
| `attachment` | string or object | N | 첨부 payload. object면 전송 직전에 JSON string으로 변환 |
| `type` | integer | N | LOCO `WRITE.type`. 기본값 `1` |
| `noSeen` | boolean | N | LOCO `WRITE.noSeen`. 기본값 `false` |
| `scope` | integer | N | LOCO `WRITE.scope`. 기본값 `1` |
| `silence` | boolean | N | LOCO `WRITE.silence`. 기본값 `false` |
### Segment 종류
#### `text`
```json
{ "kind": "text", "text": "안녕하세요 " }
```
| 필드 | 타입 | 필수 | 설명 |
| ------ | ------ | ---- | -------------------------------------- |
| `kind` | string | Y | 반드시 `text` |
| `text` | string | Y | 일반 텍스트. 빈 문자열은 허용되지 않음 |
#### `mention`
```json
{
"kind": "mention",
"userId": "6215844374579825921",
"displayText": "날으는꼴뚜기/95/여/D"
}
```
| 필드 | 타입 | 필수 | 설명 |
| ------------- | ------ | ---- | --------------------------------------------------------- |
| `kind` | string | Y | 반드시 `mention` |
| `userId` | string | Y | 양의 정수 문자열 권장. int64 손실 방지를 위해 문자열 사용 |
| `displayText` | string | Y | 화면에 표시될 이름. builder가 앞의 `@`를 자동 정리 |
멘션은 최종 메시지에서 아래처럼 렌더링된다.
```text
@{displayText}
```
예를 들어 `displayText: "홍길동"` 이면 `@홍길동` 으로 전송된다.
`displayText`를 `@홍길동`처럼 보내도 builder가 앞의 `@` 하나를 제거한 뒤 다시 렌더링한다.
#### `emoticon`
```json
{
"kind": "emoticon",
"id": "1200281_004",
"altText": "플라워"
}
```
| 필드 | 타입 | 필수 | 설명 |
| --------- | ------ | ---- | --------------------------------------- |
| `kind` | string | Y | 반드시 `emoticon` |
| `id` | string | Y | 카카오톡 이모티콘 item ID |
| `altText` | string | Y | 대체 텍스트. builder가 괄호를 자동 정리 |
이모티콘은 최종 메시지에서 아래처럼 렌더링된다.
```text
({altText})
```
예를 들어 `altText: "플라워"` 이면 `(플라워)` 로 전송된다.
`altText`를 `(플라워)`처럼 보내도 builder가 바깥 괄호를 제거한 뒤 다시 렌더링한다.
### Builder semantic validation
`chat.send-message`는 schema validation 외에 아래 규칙도 검사한다.
#### 공통
- 최종적으로 만들어진 메시지 전체 텍스트는 비어 있으면 안 된다
- `segments`가 모두 비어 있거나 렌더링 결과가 빈 문자열이면 거부된다
#### mention 규칙
- `userId`는 양의 정수여야 한다
- producer에서는 숫자 대신 문자열 사용을 권장한다
- `displayText`는 비어 있으면 안 된다
- 같은 `userId`를 여러 번 멘션하면 `extra.mentions[].at` 배열로 합쳐진다
- 같은 `userId`를 서로 다른 길이의 `displayText`로 섞어 보내면 거부된다
#### emoticon 규칙
- `id`는 trim 후 비어 있으면 안 된다
- `altText`는 trim 후 비어 있으면 안 된다
- `altText` 내부에는 `@`, `(`, `)` 문자가 들어가면 안 된다
- 같은 `(id, 렌더링 길이)` 조합의 이모티콘은 `extra.emojis.items[].at` 배열로 합쳐진다
#### `extra` 생성 규칙
producer가 `extra`를 직접 만들지 않는다.
builder가 최종 텍스트를 기준으로 아래 구조를 자동 생성한다.
```json
{
"mentions": [
{
"user_id": 6215844374579825921,
"at": [1],
"len": 13
}
],
"emojis": {
"total_item": 1,
"total_len": 5,
"items": [
{
"id": "1200281_004",
"len": 5,
"at": [1]
}
]
}
}
```
주의:
- `mentions[].at` 는 메시지 안의 `@` anchor 순번이다
- `emojis.items[].at` 는 메시지 안의 `(` anchor 순번이다
- `len` 은 렌더링된 문자열 길이 기준이다
- `total_item` 은 이모티콘 총 출현 횟수다
- `total_len` 은 각 이모티콘 렌더링 길이의 합이다
### 예시: 추천 전송
```json
{
"schema": "dakao.command.v1",
"id": "cmd-msg-001",
"type": "chat.send-message",
"source": "admin-panel",
"correlationId": "trace-20260417-001",
"replySubject": "dakao.result.admin-panel",
"payload": {
"chatroomId": "123456789012345678",
"segments": [
{ "kind": "text", "text": "😄 " },
{
"kind": "mention",
"userId": "6215844374579825921",
"displayText": "날으는꼴뚜기/95/여/D"
},
{ "kind": "text", "text": " " },
{ "kind": "emoticon", "id": "1200281_004", "altText": "플라워" },
{ "kind": "emoticon", "id": "1200281_003", "altText": "네잎클로버" }
],
"type": 1,
"noSeen": false,
"scope": 1,
"silence": false
}
}
```
위 payload는 내부적으로 대략 아래 LOCO 메시지로 변환된다.
```json
{
"text": "😄 @날으는꼴뚜기/95/여/D (플라워)(네잎클로버)",
"extra": "{\"mentions\":[{\"user_id\":6215844374579825921,\"at\":[1],\"len\":13}],\"emojis\":{\"total_item\":2,\"total_len\":12,\"items\":[{\"id\":\"1200281_004\",\"len\":5,\"at\":[1]},{\"id\":\"1200281_003\",\"len\":7,\"at\":[2]}]}}"
}
```
## Result API
응답이 필요한 경우 producer는 command에 `replySubject`를 포함해야 한다.
consumer는 처리 후 `replySubject`로 결과 object를 publish한다.
### 공통 Result envelope
```json
{
"schema": "dakao.result.v1",
"id": "cmd-msg-001",
"type": "chat.send-message",
"status": "succeeded",
"handledAt": "2026-04-17T12:34:56.789Z",
"correlationId": "trace-20260417-001",
"result": {}
}
```
### 공통 필드
| 필드 | 타입 | 설명 |
| --------------- | ------ | --------------------------------------- |
| `schema` | string | 현재는 반드시 `dakao.result.v1` |
| `id` | string | 원본 command ID |
| `type` | string | 원본 command type |
| `status` | string | `succeeded` 또는 `failed` |
| `handledAt` | string | ISO-8601 timestamp |
| `correlationId` | string | 원본 correlationId가 있으면 그대로 전달 |
| `result` | object | 성공 시 포함 |
| `error` | object | 실패 시 포함 |
### Success result
`chat.send-text`와 `chat.send-message`의 성공 응답 구조는 동일하다.
```json
{
"schema": "dakao.result.v1",
"id": "cmd-msg-001",
"type": "chat.send-message",
"status": "succeeded",
"handledAt": "2026-04-17T12:34:56.789Z",
"correlationId": "trace-20260417-001",
"result": {
"chatroomId": "123456789012345678",
"messageLength": 31,
"hasAttachment": true
}
}
```
| 필드 | 타입 | 설명 |
| --------------- | ------- | ---------------------------- |
| `chatroomId` | string | 대상 채팅방 ID |
| `messageLength` | number | 실제 전송된 최종 메시지 길이 |
| `hasAttachment` | boolean | attachment가 있으면 포함 |
### Failure result
```json
{
"schema": "dakao.result.v1",
"id": "cmd-msg-001",
"type": "chat.send-message",
"status": "failed",
"handledAt": "2026-04-17T12:34:56.789Z",
"correlationId": "trace-20260417-001",
"error": {
"code": "invalid_command",
"message": "emoticon.altText must not contain '@', '(' or ')': \"(bad@text)\"",
"retryable": false
}
}
```
| 필드 | 타입 | 설명 |
| ----------- | ------- | ------------------------------- |
| `code` | string | 오류 코드 |
| `message` | string | 사람이 읽을 수 있는 오류 메시지 |
| `retryable` | boolean | 재시도 권장 여부 |
### 현재 사용되는 오류 코드
| 코드 | retryable | 의미 |
| -------------------------- | --------- | ----------------------------------------------- |
| `invalid_command` | `false` | envelope/payload/schema/builder validation 실패 |
| `command_execution_failed` | `true` | LOCO 전송 등 실행 단계 실패 |
## 응답 publish 조건
아래 조건이 모두 충족될 때만 실패 응답을 publish할 수 있다.
- `replySubject` 존재
- `id` 존재
- `type` 존재
따라서 malformed payload를 보내더라도 `replySubject`가 없으면 실패 응답은 발행되지 않는다.
producer가 처리 결과를 반드시 받아야 한다면 `replySubject`를 항상 넣는 것을 권장한다.
## 운영 권장사항
### 새 producer는 `chat.send-message`만 사용
권장 이유:
- 멘션과 이모티콘을 구조적으로 표현할 수 있다
- `extra`를 producer가 직접 조립하지 않아도 된다
- semantic validation이 추가로 수행된다
- 향후 레거시 `chat.send-text` 제거 시 마이그레이션 부담이 적다
### `chatroomId`와 `userId`는 문자열 사용
- `userId`는 int64 범위일 수 있으므로 JSON number 대신 string 사용을 권장한다
- `chatroomId`도 실운영에서는 decimal string으로 통일하는 것이 안전하다
### `replySubject`는 항상 지정
- 성공/실패를 추적하려면 `replySubject`를 항상 넣는 것이 좋다
- `correlationId`도 함께 넣어두면 producer 로그와 결과 로그를 쉽게 연결할 수 있다
### `send-text` 사용 시 주의
- `extra` 구조를 잘못 만들면 consumer 단계에서는 걸러지지 않는다
- 멘션, 유니코드 이모지, 카카오톡 이모티콘 혼합 메시지는 `send-message` 사용을 권장한다
## 요약
- 레거시: `dakao.command.chat.send-text.v1` + `type: "chat.send-text"`
- 권장: `dakao.command.chat.send-message.v1` + `type: "chat.send-message"`
- 결과 스키마는 공통으로 `dakao.result.v1`
- 신규 API는 `segments`를 받아 builder 기반으로 `text`와 `extra`를 안전하게 생성한다
+19 -7
View File
@@ -1,11 +1,11 @@
# syntax=docker/dockerfile:1.7
FROM node:24-bookworm-slim AS pnpm-base
FROM node:26-bookworm-slim AS pnpm-base
ENV PNPM_HOME=/pnpm
ENV PATH="${PNPM_HOME}:${PATH}"
RUN corepack enable
RUN npm install --global pnpm@10.4.1
WORKDIR /app
@@ -14,36 +14,48 @@ FROM pnpm-base AS deps
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY apps/api/package.json apps/api/package.json
COPY apps/web/package.json apps/web/package.json
COPY packages/contracts/package.json packages/contracts/package.json
RUN pnpm install --frozen-lockfile --filter api... --filter lolympus-tournament-support
FROM deps AS build
COPY packages/contracts packages/contracts
COPY apps/api apps/api
RUN pnpm --filter api build
RUN pnpm --filter api... build
FROM pnpm-base AS prod-deps
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY apps/api/package.json apps/api/package.json
COPY apps/web/package.json apps/web/package.json
COPY packages/contracts/package.json packages/contracts/package.json
RUN pnpm install --prod --frozen-lockfile --filter api... --filter lolympus-tournament-support
FROM gcr.io/distroless/nodejs24-debian13:nonroot AS runtime
FROM gcr.io/distroless/nodejs26-debian13:nonroot AS runtime
WORKDIR /app
ENV NODE_ENV=prod
# ENV NODE_ENV=prod
COPY --from=prod-deps --chown=nonroot:nonroot /app/package.json ./package.json
COPY --from=prod-deps --chown=nonroot:nonroot /app/node_modules ./node_modules
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/package.json ./apps/api/package.json
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/node_modules ./apps/api/node_modules
COPY --from=build --chown=nonroot:nonroot /app/packages/contracts/package.json ./packages/contracts/package.json
COPY --from=build --chown=nonroot:nonroot /app/packages/contracts/dist ./packages/contracts/dist
COPY --chown=nonroot:nonroot apps/api/newrelic.cjs ./apps/api/newrelic.cjs
COPY --from=build --chown=nonroot:nonroot /app/apps/api/dist ./apps/api/dist
COPY --chown=nonroot:nonroot apps/project.env ./project.env
EXPOSE 10712
EXPOSE 3000
CMD ["apps/api/dist/main.js"]
ENV NEW_RELIC_HOME=/app/apps/api \
NEW_RELIC_APP_NAME=lolympus \
NEW_RELIC_AI_MONITORING_ENABLED=true \
NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED=100000 \
NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED=10000
CMD ["--import", "/app/apps/api/node_modules/newrelic/esm-loader.mjs", "-r", "/app/apps/api/node_modules/newrelic", "apps/api/dist/main.js"]
-433
View File
@@ -1,433 +0,0 @@
# Frontend ↔ Backend 통합 플랜 (Lolympus Tournament Support)
> **대상**: codex에 이어서 작업 가능한 수준의 실행 플랜
> **레포**: `/Users/dahyeon/source/lolympus-tournament-support` (pnpm workspace)
> **작성 기준**: 2026-04-24
---
## 1. Context
`apps/web`(React 19 + Vite + React Router 7)은 현재 `src/mock.ts`와 `src/auction-mock.ts`의 하드코딩된 더미 데이터로만 화면을 그립니다. 경매 페이지는 `setInterval` 기반 클라이언트 사이드 시뮬레이터(`createMockAuction()`)로 동작합니다.
`apps/api`(NestJS 11 + Mongoose 9)는 Community/User/Match/Auction 스키마와 CRUD 엔드포인트, RBAC 가드(`@Roles`), 글로벌 `ValidationPipe`, `X-Auth-User-Id` 헤더 기반 임시 인증까지 구축되어 있습니다. 하지만 **경매 실시간 푸시(WebSocket) 미구현, CORS 미설정, `MatchParticipant` 스냅샷에 티어 정보 없음, `/me` 같은 편의 엔드포인트 없음**이 통합의 걸림돌입니다.
### 이번 작업의 목표
1. 경매 페이지가 서버 주도 타이머·상태로 10명 관전 + 2명 입찰을 실시간 동기화하도록 **WebSocket 게이트웨이**를 API에 추가
2. 프론트엔드의 모든 mock import를 제거하고 **API 클라이언트 + React Query + Socket.IO 클라이언트**로 교체
3. 초기 MVP는 **단일 기본 커뮤니티** 전제 (env `VITE_DEFAULT_COMMUNITY_ID`)
4. **로그인 UI는 이번 범위에서 제외**. admin 기능은 개발자용 "User ID 수동 입력" 위젯으로 임시 처리
5. `MatchParticipant` 스냅샷에 `tier` 필드 추가 (참여 시점의 primary RiotAccount tier를 복사)
### 비목표 (이번 작업에 포함하지 않음)
- 카카오/디스코드 OAuth 로그인 플로우
- 다중 커뮤니티 전환 UI
- Riot API 실시간 동기화 UI (기존 `RiotAccountService`는 그대로 둠)
- 매치 결과 기록 UI (`MatchResult`)
- 포스트-경매 Riot 토너먼트 코드 발급
---
## 2. 현재 상태 정리 (실사 결과)
### 2.1 백엔드에 이미 있는 것
| 영역 | 파일 | 상태 |
| ----------------------------------------------- | ------------------------------------------------ | ----------- |
| Community CRUD + owner 트랜잭션 | `apps/api/src/modules/community/*` | ✅ |
| Match CRUD + 참여(join) | `apps/api/src/modules/match/*` | ✅ |
| Auction 시작/입찰/낙찰/다음/리셋 | `apps/api/src/modules/auction/*` | ✅ (HTTP만) |
| 스키마 (Community/User/Match/Auction/RiotMatch) | `apps/api/src/modules/global/database/schema.ts` | ✅ |
| `@Roles` + `RolesGuard` + `CurrentUser` | `apps/api/src/modules/auth/*` | ✅ |
| 글로벌 `ValidationPipe` | `apps/api/src/main.ts` | ✅ |
### 2.2 백엔드에 없는 것 (이번에 추가)
1. **CORS** — Vite dev는 `http://localhost:5173`, API는 `http://localhost:3000`. `app.enableCors()` 필요
2. **WebSocket (Socket.IO) 게이트웨이** — auction 상태 푸시 + 클라이언트 입찰 수신
3. **서버 주도 타이머** — 현재 auction 문서에 `maxTimerSeconds`만 있음. 입찰 시 갱신되는 `currentDeadline: Date` 필드 + 만료 자동 `markSold` 스케줄러 필요
4. **`MatchParticipant.tier`** — 참여 시 primary RiotAccount의 primary queue tier(solo 5x5)를 snapshot으로 복사
5. **`GET /me`** — 현재 `X-Auth-User-Id` 헤더의 User 반환 (헤더 없으면 `null`). 프론트에서 admin 기능 가시성 판단용
6. **`GET /communities/:communityId`** — 프론트 헤더에 커뮤니티 이름 표시용
7. `mapId: number` → 프론트 라벨 매핑 유틸(프론트 쪽). 백엔드는 그대로
### 2.3 프론트엔드에 없는 것 (이번에 추가)
1. API 클라이언트 (`src/lib/api.ts`) — fetch 래퍼, `X-Auth-User-Id` 주입
2. `@tanstack/react-query` + `QueryClientProvider`
3. `socket.io-client` + `useAuctionSocket` 훅
4. `src/config.ts` — `VITE_API_BASE_URL`, `VITE_DEFAULT_COMMUNITY_ID`, localStorage `X-Auth-User-Id` 관리
5. 백엔드 스키마에 대응하는 **프론트 타입** (`src/api/types.ts`)
6. 백엔드 `Match`/`Auction` → 프론트 `MatchDetail`/`AuctionState` **매핑 함수** (`src/api/mappers.ts`)
7. 개발자용 "User ID 주입" 토글 UI (admin 기능 테스트용, 프로덕션 빌드에선 숨김)
### 2.4 데이터 모델 차이 요약
| 프론트 모델 | 백엔드 모델 | 매핑 전략 |
| --------------------------------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------ |
| `MatchDetail.date`/`time` (한국어 string) | `Match.scheduledAt: Date` | 프론트에서 `Intl.DateTimeFormat('ko-KR')`로 포맷 |
| `MatchDetail.map: string` ("소환사의 협곡") | `Match.mapId: number` (11) | 프론트 `mapIdToLabel` 유틸 |
| `Participant.tier: {previousSeason, current, peak}` | 추가 필요: `MatchParticipant.tier` 스냅샷 | 백엔드에 필드 추가 후 프론트가 그대로 읽음 (프론트 `TierInfo`는 백엔드 원본 형태로 리팩터) |
| `Team.participants[].assignedPosition` | `MatchTeam.members[].assignedPosition` | 프론트가 `match.participants`와 `match.teams`를 조합해서 표시 |
| `AuctionPlayer.tier` (단일) | `AuctionPlayerSnapshot.tiers: TierInfo[]` | 프론트에서 `queueType === 'RANKED_SOLO_5x5'` 필터 후 대표 선택 |
| `AuctionPlayer.masteries[].championName` | `ChampionMasteryEntry.championName` (optional) | 프론트가 fallback 처리 |
| `AuctionState.timer` (초, 카운트다운) | 서버 `currentDeadline: Date` | 프론트가 `deadline - now`로 매 틱 계산 |
---
## 3. 실행 계획
> 단계는 독립적이지 않고 순차 진행 권장. Phase 0 → 1 → 2 → 3 순서.
### Phase 0 — 백엔드 선행 보강 (`apps/api`)
#### 0.1 CORS 활성화
**파일**: `apps/api/src/main.ts`
```ts
app.enableCors({
origin: process.env.WEB_ORIGIN?.split(",") ?? ["http://localhost:5173"],
credentials: true,
allowedHeaders: ["Content-Type", "X-Auth-User-Id"],
});
```
프로덕션용 origin은 `project.env`의 `WEB_ORIGIN`으로 주입.
#### 0.2 `MatchParticipant.tier` 스냅샷 필드 추가
**파일**: `apps/api/src/modules/global/database/schema.ts`
- `MatchParticipant` interface + sub-schema에 `tier?: TierInfo` 추가 (optional — Riot 계정이 없는 유저도 참여 가능해야 하면)
- `MatchService.join()` (`apps/api/src/modules/match/match.service.ts` 라인 93~)에서 `primaryRiot.tiers.find(t => t.queueType === 'RANKED_SOLO_5x5') ?? primaryRiot.tiers[0]`를 복사
- 기존 데이터 마이그레이션 없이 optional이라 호환성 유지
#### 0.3 `/me` + `/communities/:id` 편의 엔드포인트
**신규 파일**: `apps/api/src/modules/user/user.controller.ts`, `user.module.ts`
```ts
@Controller("me")
class MeController {
@Get()
me(@CurrentUser() user: UserDocument | undefined) {
return user ? { user } : { user: null };
}
}
```
**Community 쪽** (`community.controller.ts`):
```ts
@Get(':communityId')
async getCommunity(@Param('communityId', ParseObjectIdPipe) id) {
return this.communityService.getById(id); // 서비스에 메서드 추가
}
```
#### 0.4 Auction WebSocket 게이트웨이 (핵심)
**의존성 설치**: `pnpm --filter api add @nestjs/websockets @nestjs/platform-socket.io socket.io`
**신규 파일**: `apps/api/src/modules/auction/auction.gateway.ts`
네임스페이스·룸 구조:
- 네임스페이스: `/auction`
- 룸 이름: `matchId` 문자열
이벤트 스펙:
| 방향 | 이벤트 | payload |
| --- | --- | --- |
| server→client | `state` | `AuctionDocument` (직렬화) |
| server→client | `tick` | `{ deadline: string, serverTime: string }` |
| server→client | `error` | `{ message: string }` |
| client→server | `join` | `{ matchId: string }` |
| client→server | `bid` | `{ side, amount, bidderUserId? }` |
| client→server | `open-bidding` | `{}` |
| client→server | `sold` | `{ assignedPosition? }` |
| client→server | `next` | `{}` |
구현 포인트:
- `handleConnection`/`handleDisconnect`에서 Socket.IO의 rooms 표준 사용
- 클라이언트 `join` 시 해당 matchId 룸에 입장 + 현재 `state` 푸시
- 입찰/낙찰/다음 이벤트는 **기존 `AuctionService` 메서드 재사용**. 결과 상태를 해당 룸에 브로드캐스트
- `AuctionService`가 phase 전이 시마다 `deadline: Date` 계산해서 Auction 문서에 저장 (`AuctionSchema`에 `currentDeadline?: Date` 추가)
- 타이머 만료 자동 처리는 **Phase 0에선 생략**하고, 클라이언트가 deadline 지나면 "시간 종료" 표시만. 자동 `markSold`는 후속 작업 (`SchedulerRegistry` + `setTimeout` 필요). 트러스트 전제라 팀장이 수동 sold 하면 충분.
**AuthMiddleware는 socket.io 연결에 적용되지 않음**: 게이트웨이 자체에서 `@ConnectedSocket()`의 handshake headers 또는 auth payload에서 `x-auth-user-id`를 읽어 옵션으로 취급. 권한 필요한 이벤트(`open-bidding`, `sold`, `next`)는 일단 무검증 유지 (트러스트 전제). `bid`만 payload의 `bidderUserId`를 검증해서 해당 팀의 `captainUserId`와 일치하는지 정도 체크하면 고의 방해 방지 최소선은 만족.
#### 0.5 `AuctionSchema.currentDeadline` 추가
**파일**: `apps/api/src/modules/global/database/schema.ts`
- interface `Auction`에 `currentDeadline?: Date`
- Schema 필드 추가
- `AuctionService.openBidding()`과 `placeBid()`에서 `new Date(Date.now() + auction.maxTimerSeconds * 1000)`로 갱신
- `placeBid` 시엔 `Math.max(5, remainingSeconds)` 보장 (기존 프론트 mock 로직과 동일: 최소 5초)
- `markSold` / `next` 시엔 `undefined`로 리셋
#### 0.6 AppModule 등록
**파일**: `apps/api/src/app.module.ts`
- `UserModule` import
- `AuctionModule`에서 게이트웨이 providers 등록 (`AuctionGateway` + `AuctionService`는 그대로)
#### 0.7 검증 (Phase 0 종료 시)
```bash
cd apps/api
./node_modules/.bin/tsc --noEmit
pnpm start:dev
```
- `curl -H "X-Auth-User-Id: <id>" http://localhost:3000/me`로 `/me` 확인
- socket.io 클라이언트(또는 `wscat`)로 `ws://localhost:3000/auction` 연결 + `join` 이벤트 → `state` 수신 확인
---
### Phase 1 — 프론트엔드 인프라 구축 (`apps/web`)
#### 1.1 의존성 설치
```bash
pnpm --filter web add @tanstack/react-query socket.io-client
pnpm --filter web add -D @tanstack/react-query-devtools
```
#### 1.2 환경 변수
**신규 파일**: `apps/web/.env.development` (기존 있으면 추가)
```
VITE_API_BASE_URL=http://localhost:3000
VITE_DEFAULT_COMMUNITY_ID=<Phase 3에서 생성한 커뮤니티 _id>
```
**신규 파일**: `apps/web/src/config.ts`
- `API_BASE_URL`, `DEFAULT_COMMUNITY_ID` export
- `getAuthUserId()` / `setAuthUserId(id | null)` (localStorage `lolympus.authUserId`)
#### 1.3 API 클라이언트
**신규 파일**: `apps/web/src/lib/api.ts`
- `apiFetch<T>(path, init?)`: 베이스 URL 붙이고, `X-Auth-User-Id` 자동 주입, JSON 파싱, 4xx/5xx는 `ApiError` throw
- 응답 타입은 제네릭
#### 1.4 타입 정의 (백엔드 미러)
**신규 파일**: `apps/web/src/api/types.ts`
- `Position`, `TeamSide`, `MatchStatus`, `AuctionPhase` 같은 유니온은 복붙
- `TierInfo`, `ChampionMasteryEntry`, `RiotRecentStatsSummary` 등 sub-type
- `ApiCommunity`, `ApiUser`, `ApiMatch`, `ApiAuction` — 응답 형태 그대로
- `_id: string` (ObjectId 직렬화), `createdAt/updatedAt: string` (ISO)
> 타입 중복은 MVP에선 감수. 나중에 `packages/shared-types` 생성 고려.
#### 1.5 매핑 레이어
**신규 파일**: `apps/web/src/api/mappers.ts`
- `mapApiMatchToMatchDetail(match: ApiMatch): MatchDetail`
- `mapApiAuctionToAuctionState(auction: ApiAuction, serverNow?: Date): AuctionState`
- `mapIdToLabel(mapId: number): string` — `11 → '소환사의 협곡'`, `12 → '칼바람 나락'`, ...
- `formatKoreanDate(date: Date): { date, time }`
- `selectPrimaryTier(tiers: TierInfo[]): TierInfo | undefined`
> 기존 `apps/web/src/mock.ts`의 `MatchDetail`/`Participant` 타입은 유지한 채로 매퍼가 채움. 이후 Phase 2에서 점진 삭제.
#### 1.6 React Query 설정
**파일 수정**: `apps/web/src/main.tsx`
- `QueryClientProvider`로 감싸기
- staleTime 10s, cacheTime 5min 기본값
#### 1.7 Socket 훅
**신규 파일**: `apps/web/src/api/useAuctionSocket.ts`
- `useAuctionSocket(matchId: string)` 훅
- 내부: `useEffect`로 `io(API_BASE_URL + '/auction', { auth: { 'x-auth-user-id': getAuthUserId() } })`
- `join` emit 후 `state`/`tick`/`error` 이벤트 구독
- state는 `useState`로 저장, 반환: `{ state, placeBid, openBidding, markSold, next, connectionStatus }`
#### 1.8 개발자용 User 주입 위젯
**신규 파일**: `apps/web/src/components/DevAuthSwitcher.tsx`
- 우하단 플로팅 패널. input + "Set"/"Clear" 버튼. localStorage 값 표시
- `import.meta.env.DEV`일 때만 렌더
---
### Phase 2 — 페이지 교체 (`apps/web`)
#### 2.1 HomePage
**파일**: `apps/web/src/pages/HomePage.tsx`
- mock import 제거
- `useQuery(['matches', communityId, 'upcoming'])` → `GET /communities/:id/matches?status=recruiting&limit=20`
- `useQuery(['matches', communityId, 'finished'])` → `GET /communities/:id/matches?status=finished&limit=10`
- "다음 내전"은 upcoming의 첫 요소
- 각 카드는 `mapApiMatchToMatchDetail`의 축약 버전으로
#### 2.2 MatchDetailPage
**파일**: `apps/web/src/pages/MatchDetailPage.tsx`
- `useQuery(['match', matchId])` → `GET /communities/:id/matches/:matchId`
- `mapApiMatchToMatchDetail()` 적용
- 참가자 티어는 `participant.tier` 직접 사용 (백엔드 snapshot)
- "경매 시작" 버튼은 `/me` 결과의 role이 admin/owner일 때만 보여주기 (admin 전용)
#### 2.3 AuctionPage
**파일**: `apps/web/src/pages/AuctionPage.tsx`
- `createMockAuction` import 제거
- 초기 상태: `useQuery(['auction', matchId])` → `GET /communities/:id/matches/:matchId/auction`
- 이후: `useAuctionSocket(matchId)`로 실시간 갱신
- 타이머: `state.currentDeadline`과 `Date.now()` 차이로 클라이언트 카운트다운
- "입찰" 버튼: `placeBid({side, amount})` 호출 (내부적으로 socket emit)
- "공개"/"낙찰"/"다음" 버튼(팀장용): socket emit — 페이지에 세 버튼 노출 (트러스트 전제)
- **localStorage에 자기가 어느 팀장인지 저장하는 토글** 추가 (dev 편의)
#### 2.4 mock 파일 제거
- `apps/web/src/mock.ts` — Position/TierInfo/Participant 같은 타입만 `src/api/types.ts`로 흡수 후 삭제
- `apps/web/src/auction-mock.ts` — 전부 삭제
- `apps/web/src/auction-types.ts` — 프론트 전용 파생 타입만 남기고 백엔드 응답 타입은 `api/types.ts`로
---
### Phase 3 — E2E 검증 및 시드
#### 3.1 시드 데이터 생성 스크립트
**신규 파일**: `apps/api/src/seed.ts` (또는 ad-hoc)
- `CommunityService.createCommunityWithOwner({ name: 'Dev Community', owner: { kakaoTalkNickname: 'DevOwner' } })`
- 참가자 유저 10명 생성 (Riot 계정 더미 + tiers 채움 — 기존 mock 데이터를 DB로 이식)
- 매치 3개 (recruiting 1, team-built 1, finished 1)
- 반환된 `communityId`를 `.env.development`에 복사
실행:
```bash
pnpm --filter api exec ts-node src/seed.ts
```
#### 3.2 통합 smoke test
1. `pnpm --filter api start:dev`
2. `pnpm --filter web dev`
3. 브라우저에서 `http://localhost:5173`:
- HomePage에 시드 매치 3개 표시되는지
- MatchDetailPage에서 참가자 티어 정보 렌더링되는지
- DevAuthSwitcher로 owner User ID 주입 → 경매 시작 버튼 보이는지
- AuctionPage 두 탭 열어서 한쪽 입찰 시 다른 쪽 실시간 반영되는지
4. `tsc --noEmit`과 `pnpm --filter web build` 무오류 확인
---
## 4. 파일별 수정/신규 체크리스트
### `apps/api` 수정
- [ ] `src/main.ts` — CORS
- [ ] `src/modules/global/database/schema.ts` — `MatchParticipant.tier?`, `Auction.currentDeadline?`
- [ ] `src/modules/match/match.service.ts::join` — tier 스냅샷 복사
- [ ] `src/modules/auction/auction.service.ts` — `openBidding`/`placeBid`에서 `currentDeadline` 갱신, `markSold`/`next`에서 리셋
- [ ] `src/modules/community/community.controller.ts` + `community.service.ts` — `getById` + `GET /communities/:id`
- [ ] `src/app.module.ts` — `UserModule`, `AuctionGateway` provider 등록
### `apps/api` 신규
- [ ] `src/modules/user/user.module.ts`
- [ ] `src/modules/user/user.controller.ts` (`GET /me`)
- [ ] `src/modules/auction/auction.gateway.ts`
- [ ] `src/seed.ts` (선택)
### `apps/web` 수정
- [ ] `src/main.tsx` — `QueryClientProvider`
- [ ] `src/App.tsx` — DevAuthSwitcher 마운트
- [ ] `src/pages/HomePage.tsx` — react-query 연동
- [ ] `src/pages/MatchDetailPage.tsx` — react-query 연동
- [ ] `src/pages/AuctionPage.tsx` — socket 훅 연동
### `apps/web` 신규
- [ ] `.env.development`
- [ ] `src/config.ts`
- [ ] `src/lib/api.ts`
- [ ] `src/api/types.ts`
- [ ] `src/api/mappers.ts`
- [ ] `src/api/useAuctionSocket.ts`
- [ ] `src/api/hooks.ts` (선택 — `useMatches`, `useMatch`, `useAuction`, `useMe`)
- [ ] `src/components/DevAuthSwitcher.tsx`
### `apps/web` 삭제
- [ ] `src/mock.ts` (타입은 `src/api/types.ts`로 흡수 후)
- [ ] `src/auction-mock.ts`
---
## 5. 재사용할 기존 유틸
| 용도 | 위치 | 재사용 포인트 |
| ---------------------- | ----------------------------------------------------------------------------- | --------------------------------------------------- |
| ObjectId 파라미터 파싱 | `apps/api/src/modules/common/parse-object-id.pipe.ts` | 새 엔드포인트(`getCommunity`, `me`)에도 적용 |
| 트랜잭션 세션 생성 | `apps/api/src/modules/global/database/connection.service.ts::createSession` | `AuctionGateway`에서 원자적 상태 전이가 필요한 경우 |
| `@CurrentUser()` | `apps/api/src/modules/auth/current-user.decorator.ts` | `/me`에서 그대로 사용 |
| Role 매핑 | `apps/api/src/modules/auth/permissions.ts::roleHasPermission` | 프론트에 권한 표시 JSON 내려줄 때 참고 |
| 포지션 라벨/아이콘 | `apps/web/src/assets/position/*` + `mock.ts`의 `positionLabel`/`positionIcon` | `src/api/mappers.ts`로 이동 |
---
## 6. 위험 요소 & 주의사항
1. **Socket.IO 인증 미적용**: MVP에선 WebSocket 연결에 인증을 강제하지 않음. 고의 방해 시나리오 대비는 `bid` 이벤트의 `bidderUserId`가 해당 팀 `captainUserId`와 일치하는지만 체크. 프로덕션 전환 전에 JWT 핸드셰이크로 교체.
2. **타이머 만료 자동 sold 미구현**: 팀장이 수동으로 "낙찰" 누르는 흐름. 이게 불편하면 후속 작업으로 `SchedulerRegistry` 타이머 추가.
3. **Mongoose `HydratedDocument` 직렬화**: `JSON.stringify`는 `toJSON`을 거치지만 `_id`가 ObjectId 객체로 나올 수 있음. 엔드포인트에서 `.lean()` 또는 `toObject({ versionKey: false })` 적용 고려 — 또는 프론트에서 `String(_id)` 처리.
4. **프론트 타입 중복**: `apps/web/src/api/types.ts`가 백엔드 스키마와 갈라질 수 있음. Phase 3 이후 `packages/shared-types` 워크스페이스로 승격 권장.
5. **시드 데이터의 communityId 동기화**: `.env.development`에 하드코딩되므로 재시드 시 값 바뀜. `seed.ts` 마지막에 `.env.development`를 갱신하도록 하면 편함.
6. **`forbidNonWhitelisted: true`**: DTO에 없는 필드는 400. 프론트 요청 페이로드 구성 시 주의.
7. **Riot 계정 없는 유저 참여**: `MatchService.join`은 현재 `primaryRiot` 없어도 `undefined`로 저장. `tier` 필드도 optional로 유지해야 기존 흐름 유지.
---
## 7. 검증 체크리스트 (최종)
- [ ] `pnpm --filter api run build` 무오류
- [ ] `pnpm --filter web run build` 무오류
- [ ] `curl -i http://localhost:3000/me` → `{user: null}`, 헤더 넣으면 user 객체
- [ ] `curl http://localhost:3000/communities/<id>/matches` → 시드 매치 목록
- [ ] 브라우저 HomePage 렌더 OK
- [ ] MatchDetailPage에 티어 표시 OK
- [ ] AuctionPage 두 탭 open → 한쪽 bid 하면 다른 쪽 `state` 이벤트로 즉시 갱신
- [ ] DevAuthSwitcher로 owner ID 주입 시에만 "경매 시작" 버튼 노출
- [ ] 비 admin 상태에선 admin 엔드포인트 호출 시 401/403 응답이 UI에 에러 토스트로 노출
---
## 8. 작업 순서 (codex 핸드오프용)
1. **Phase 0** (백엔드 보강) — 스키마 변경 → 서비스 갱신 → 게이트웨이 → CORS/ME. 빌드 확인.
2. **Phase 1** (프론트 인프라) — deps 설치 → config/api/types/mappers → QueryClientProvider.
3. **Phase 3의 3.1 시드** 먼저 돌려서 `communityId` 확보 → `.env.development` 업데이트.
4. **Phase 2** (페이지 교체) — HomePage → MatchDetailPage → AuctionPage 순서.
5. **Phase 3의 3.2** E2E 스모크 테스트.
각 Phase 종료마다 `tsc --noEmit`으로 타입 검증, 필요시 `pnpm lint` 실행.
+480
View File
@@ -0,0 +1,480 @@
GNU LIBRARY GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1991 Free Software Foundation, Inc.
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the library GPL. It is
numbered 2 because it goes with version 2 of the ordinary GPL.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Library General Public License, applies to some
specially designated Free Software Foundation software, and to any
other libraries whose authors decide to use it. You can use it for
your libraries, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if
you distribute copies of the library, or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link a program with the library, you must provide
complete object files to the recipients so that they can relink them
with the library, after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
Our method of protecting your rights has two steps: (1) copyright
the library, and (2) offer you this license which gives you legal
permission to copy, distribute and/or modify the library.
Also, for each distributor's protection, we want to make certain
that everyone understands that there is no warranty for this free
library. If the library is modified by someone else and passed on, we
want its recipients to know that what they have is not the original
version, so that any problems introduced by others will not reflect on
the original authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that companies distributing free
software will individually obtain patent licenses, thus in effect
transforming the program into proprietary software. To prevent this,
we have made it clear that any patent must be licensed for everyone's
free use or not licensed at all.
Most GNU software, including some libraries, is covered by the ordinary
GNU General Public License, which was designed for utility programs. This
license, the GNU Library General Public License, applies to certain
designated libraries. This license is quite different from the ordinary
one; be sure to read it in full, and don't assume that anything in it is
the same as in the ordinary license.
The reason we have a separate public license for some libraries is that
they blur the distinction we usually make between modifying or adding to a
program and simply using it. Linking a program with a library, without
changing the library, is in some sense simply using the library, and is
analogous to running a utility program or application program. However, in
a textual and legal sense, the linked executable is a combined work, a
derivative of the original library, and the ordinary General Public License
treats it as such.
Because of this blurred distinction, using the ordinary General
Public License for libraries did not effectively promote software
sharing, because most developers did not use the libraries. We
concluded that weaker conditions might promote sharing better.
However, unrestricted linking of non-free programs would deprive the
users of those programs of all benefit from the free status of the
libraries themselves. This Library General Public License is intended to
permit developers of non-free programs to use free libraries, while
preserving your freedom as a user of such programs to change the free
libraries that are incorporated in them. (We have not seen how to achieve
this as regards changes in header files, but we have achieved it as regards
changes in the actual functions of the Library.) The hope is that this
will lead to faster development of free libraries.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, while the latter only
works together with the library.
Note that it is possible for a library to be covered by the ordinary
General Public License rather than by this special one.
GNU LIBRARY GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library which
contains a notice placed by the copyright holder or other authorized
party saying it may be distributed under the terms of this Library
General Public License (also called "this License"). Each licensee is
addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also compile or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
c) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
d) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the source code distributed need not include anything that is normally
distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Library General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Moe Ghoul>, 1 April 1990
Moe Ghoul, President of Vice
That's all there is to it!
-465
View File
@@ -1,465 +0,0 @@
# 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:<cid>` 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<string>();
// 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:<matchV5Id>` 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:*:<cid>:*` 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 통계 페이지에 자동 포함됨
+195
View File
@@ -0,0 +1,195 @@
# LOLYMPUS
LOLYMPUS는 리그 오브 레전드 커뮤니티의 여러 이벤트 중 내전(사용자 설정 게임)을 운영할 때 필요한 일정 관리, 참여자 모집, 팀 빌딩, 토너먼트 코드 배정, 경기 진행, 실시간 라이브 방송(추후 지원 예정), 결과 수집, 전적 확인을 한곳에서 처리하기 위한 웹 애플리케이션입니다.
<p align="center">
<video
src="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/84/docs/screenshots/lolympus-demo.mp4"
poster="docs/screenshots/lolympus-auction.png"
width="960"
autoplay="autoplay"
muted="muted"
loop="loop"
playsinline="playsinline"
controls
>
<a href="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/84/docs/screenshots/lolympus-demo.mp4">3초 간격 데모 영상 보기</a>
</video>
</p>
<p align="center">
<a href="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/84/docs/screenshots/lolympus-demo.mp4">3초 간격 데모 영상 보기</a>
</p>
## 배포 주소
| Environment | Version | URL |
| ----------- | ------- | -------------------------------------- |
| Production | v84 | <https://lolympus.dahyeon.us/> |
| Staging | v84 | <https://release-84.lolympus.pages.dev/> |
## 개요
내전 운영은 사람을 모으는 것에서 끝나지 않습니다. 참가자의 티어와 포지션을 확인하고, 팀장을 정하고, 팀을 나누고, 경기마다 토너먼트 코드를 전달하고, 끝난 뒤 결과와 전적까지 정리해야 합니다.
LOLYMPUS는 이 반복 작업을 줄이는 데 초점을 맞췄습니다. 운영자는 전체 진행 상황을 한눈에 보고, 참가자는 카카오톡 연동을 통해 쉽게 일정 확인/참가 신청하고 본인이 속한 팀과 다음 경기 정보를 빠르게 확인할 수 있습니다.
## 워크플로우
1. **내전 개설과 모집**
내전 일정, 진행 방식, 정원, 공지사항을 등록하고 참가 신청 현황을 확인합니다.
2. **참가자 정보 확인**
Riot 계정 기반으로 소환사명, 태그, 프로필 아이콘, 솔로랭크/자유랭크 티어, 선호 포지션을 보여줍니다.
3. **팀 빌딩과 경매**
팀장을 기준으로 팀을 구성하거나, 경매 방식으로 참가자를 배정합니다. 현재 입찰가, 팀별 포인트, 낙찰 기록을 함께 관리합니다.
4. **팀별 진행 페이지**
각 팀은 예정 경기, 상대 팀, 라인업, 토너먼트 코드를 한 화면에서 확인하고 복사할 수 있습니다.
5. **더블 엘리미네이션 운영**
4팀/8팀 더블 엘리미네이션 대진표를 생성하고, 시드 교체, 부전승, 제한적 결과 취소, 그랜드 파이널 리셋을 관리합니다.
6. **결과 수집과 통계**
Riot Match-V5 데이터를 이용해 경기 결과를 수집하고, 소환사별 전적과 커뮤니티 리더보드를 제공합니다.
## 스크린샷
상단의 경매 화면은 LOLYMPUS가 단순 참가자 목록을 넘어서 실제 팀빌딩 운영까지 다루는 대표 화면입니다. 3초 간격 데모 영상은 README 렌더러가 video 태그를 지원하면 자동/반복 재생되고, 세부 화면은 아래 PNG 원본을 기준으로 볼 수 있습니다.
| 경매 팀빌딩 |
| ----------------------------------------------------------------------------------------------------------------------------------------- |
| <a href="docs/screenshots/lolympus-demo.mp4"><img src="docs/screenshots/lolympus-auction.png" alt="LOLYMPUS 경매 팀빌딩" width="840"></a> |
| 내전 목록 | 모집 상세 |
| ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| <img src="docs/screenshots/lolympus-match-list.png" alt="LOLYMPUS 내전 목록" width="420"> | <img src="docs/screenshots/lolympus-match-recruiting.png" alt="LOLYMPUS 모집 상세" width="420"> |
| 단판 경기 결과 | 개인 전적 |
| ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------- |
| <img src="docs/screenshots/lolympus-match-result(pair).png" alt="LOLYMPUS 단판 경기 결과" width="420"> | <img src="docs/screenshots/lolympus-player-stats.png" alt="LOLYMPUS 소환사 전적" width="420"> |
| 경기 상세 |
| ------------------------------------------------------------------------------------------- |
| <img src="docs/screenshots/lolympus-match-detail.png" alt="LOLYMPUS 경기 상세" width="840"> |
## 기능
- 내전 생성, 수정, 모집 상태 변경, 참가자 목록 확인
- 카카오톡 명령어를 통한 일정 조회, 내전 참가, 취소, 계정 등록 등 기능 제공
- Riot 계정 기반 참가자 프로필, 티어, 포지션 확인
- 팀장 지정, 포지션 기반 팀 구성, 다팀 내전 지원
- 팀장 경매 방식의 참가자 낙찰과 입찰 기록 관리
- 4팀/8팀 더블 엘리미네이션 대진표, 시드 관리, 부전승, 제한적 취소, 그랜드 파이널 리셋 지원
- 경기별 토너먼트 코드 배정과 팀별 복사 UI
- 팀별 경기 일정, 상대 팀, 라인업, 결과 확인
- Riot Match-V5 기반 결과 수집, 개인 전적, 리더보드 제공
- Dakao/NATS 기반 커뮤니티 명령 연동
## 기술 스택
- React
- Vite
- TypeScript
- TanStack Query
- NestJS
- MongoDB 8.3
- Redis 8.10 (일반 캐시/스트림과 경매 실시간 상태 공유)
- NATS
- Riot API
- pnpm workspace
- Kubernetes
- ArgoCD
## 디렉터리 구조
```text
apps/
api/ NestJS API server
web/ React + Vite client
docs/
screenshots/ README and project screenshots
scripts/ deployment and maintenance scripts
```
## 사전 요구사항
- Node.js 24 이상
- pnpm 10.4.1 (`packageManager` 기준, `corepack enable`로 활성화 권장)
- MongoDB 8.3, Redis 8.10, NATS 실행 환경
일반 캐시/스트림, 경매 실시간 상태, WebSocket Pub/Sub는 `GARNET_ENDPOINT`로 지정한 하나의 Redis 인스턴스를 공유합니다. 값은 `host:port`, `redis://...`, `rediss://...` 형식을 지원합니다. 인증이 필요하면 기존 `GARNET_USERID`(또는 `GARNET_USERNAME`)와 `GARNET_PASSWORD`를 설정합니다. `REDIS_*`, `AUCTION_REDIS_*`, `GARNET_URL` 연결 설정은 사용하지 않습니다. 경매 점검 스크립트도 같은 설정을 사용합니다.
## 실행 방법
```bash
pnpm install
pnpm start:api:dev
pnpm start:web:dev
```
웹 앱은 기본적으로 `apps/web/.env.development` 값을 사용합니다. API 환경값은 `apps/project.env`와 실행 환경의 시크릿 설정을 함께 확인합니다.
### Redis 변경 검증
Redis 8.10.x의 `XREADGROUP CLAIM`, `XACKDEL ACKED`, `DELEX`, `SET IFEQ`, `INCREX`, `HSETEX`를 사용합니다. 스트림의 대기 읽기는 별도 연결에서 실행하며, 처리되지 않은 작업은 길이 제한을 초과해도 보존합니다.
```bash
pnpm --filter api test -- --runInBand
pnpm --filter api typecheck
pnpm --filter api test:redis
pnpm --filter api build
```
`test:redis`는 PATH의 `redis-server` 또는 `REDIS_TEST_SERVER`에 지정한 실행 파일로 Redis 8.10.x를 직접 실행합니다. 임의의 로컬 포트와 일회용 암호를 사용하고, 저장을 비활성화하며, 종료 후 프로세스와 임시 디렉터리를 정리합니다. 애플리케이션 Redis 연결 설정은 사용하지 않습니다. Windows에서는 PowerShell에서 `$env:REDIS_TEST_SERVER = 'C:\tools\redis\redis-server.exe'`처럼 지정할 수 있습니다.
커뮤니티 통계 캐시는 `riot:communitystats:v2:{communityId}:scope` Hash를 사용합니다. 항목별 TTL은 일반 5분, 완성된 상세 24시간, 미완성 상세 60초입니다. 이전 String 캐시는 기존 TTL로 만료되며 새 캐시는 첫 조회에 생성됩니다. 구버전과 신버전은 무효화 대상이 다르므로 배포와 롤백 모두 API 인스턴스를 같은 버전으로 함께 전환해야 합니다.
스트림이 계속 커지면 소비자 그룹별 미처리 항목을 확인합니다. 사용이 중단된 그룹도 미처리 항목을 계속 보존할 수 있습니다.
### API New Relic APM
API 서버는 `newrelic` Node.js agent를 앱 코드보다 먼저 preload합니다. Docker 런타임과 `pnpm start:api:*` 스크립트 모두 `NEW_RELIC_HOME`을 API 패키지로 지정해 `apps/api/newrelic.cjs` 설정을 읽습니다.
Kubernetes에서는 Infisical이 `NEW_RELIC_LICENSE_KEY`를 프로세스 시작 전에 환경변수로 주입해야 합니다. 저장소에는 라이선스 키를 두지 않습니다.
비밀이 아닌 기본값은 Dockerfile과 `apps/api/newrelic.cjs`에 정의되어 있으며 필요하면 런타임 환경변수로 덮어쓸 수 있습니다.
```bash
NEW_RELIC_APP_NAME=lolympus
NEW_RELIC_AI_MONITORING_ENABLED=true
NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED=100000
NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED=10000
```
New Relic Node agent의 정수 환경변수는 `100k` 같은 축약형 대신 `100000`처럼 숫자 문자열을 사용합니다.
### API 성능 리포트 운영
API 성능 계측은 기본 비활성화이며 필요할 때 `API_PERF_OBSERVABILITY_ENABLED=true`로 켭니다. 전체 API route 목록은 `pnpm --filter api perf:routes`, 성능 리포트는 `pnpm --filter api perf:report`로 생성합니다. New Relic Transaction 실측 duration, New Relic custom event, local NDJSON 파일을 데이터 소스로 사용할 수 있습니다.
운영 절차와 해석 기준은 `docs/operations/api-performance-runbook.md`를 참고합니다.
카카오톡 기반 명령어 기능은 Dakao(커스텀 카카오톡 게이트웨이) 연동이 필요합니다. Dakao가 실행 중이 아니거나 NATS를 통해 API 서버와 연결되어 있지 않으면 일정 조회, 내전 참가, 참가 취소, 계정 등록 같은 카카오톡 명령어는 사용할 수 없습니다.
카카오톡 방을 옮긴 뒤에는 새 방에서 `!내전 데이터이관 예전 닉네임`을 실행합니다. 같은 커뮤니티에서 Riot 계정이 등록된 기존 사용자의 카카오톡 ID만 바뀝니다. 기존 사용자 ID, 권한, 참가 기록은 유지됩니다. 닉네임이 중복되거나 새 ID가 이미 다른 사용자에 연결돼 있으면 운영자가 확인합니다. 계정 소유권 확인은 운영 절차에서 담당합니다.
## 커맨드
| Command | Description |
| --------------------------------- | -------------------------------- |
| `pnpm start:web:dev` | 웹 앱 개발 서버 실행 |
| `pnpm start:api:dev` | API 서버 dev 환경 실행 |
| `pnpm --filter api test` | API 테스트 실행 |
| `pnpm --filter api typecheck` | 테스트를 포함한 API 타입 검사 |
| `pnpm --filter api test:redis` | 격리된 Redis 8.10 통합 테스트 실행 |
| `pnpm --filter api perf:routes` | API 성능 리포트 대상 route 출력 |
| `pnpm --filter api perf:report` | API 성능 리포트 생성 |
| `pnpm --filter web build:staging` | 웹 staging 빌드 검증 |
| `pnpm deploy:web:staging` | Cloudflare Pages staging 배포 |
| `pnpm deploy:web:prod` | Cloudflare Pages production 배포 |
## 라이선스
This project is licensed under the GNU Library General Public License v2.0. See [LICENSE](LICENSE) for details.
-628
View File
@@ -1,628 +0,0 @@
# 소환사 전적 페이지 플랜
> **대상**: codex 가 이어서 작업 가능한 수준의 실행 플랜
> **레포**: `/Users/dahyeon/source/lolympus-tournament-support` (pnpm workspace)
> **작성 기준**: 2026-04-26
> **선행 작업**: `Riot-최근경기-플랜.md` (Throttle / RecentMatches / Scheduler / 시즌·region 인프라) 가 깔려 있어야 함.
> **참고 이미지**: `user-game-history/statistics.png`, `123123.png` (poro.gg 스타일 매치 카드)
---
## 1. Context
`AuctionPage.tsx`, `MatchDetailPage.tsx` 에서 소환사 프로필 클릭 → 신규 **개인 전적 페이지** 로 이동.
핵심 정책 (사용자 결정 2026-04-26):
1. **서버 가진 데이터만 표시.** 페이지 진입 시 Riot API 호출 0회. 야간 prefetch + 명시적 "갱신" 버튼 만 enrichment 트리거.
2. 즉각 갱신은 **전역 Riot API 작업 큐** 에 enqueue → consumer 가 throttle 통과시키며 직렬 처리. UI 는 "예상 ~초 후 갱신" 피드백.
3. 시즌 history 는 추후 구현. 다만 **schema/응답에 seasonId 자리** 미리 마련.
표시 항목:
- **챔피언 통계** (`statistics.png`): 큐 탭 / 랭크 필터 / 시즌 필터 / 정렬 가능 표
- **최근 전적** (`123123.png`, poro.gg 스타일): win/lose 좌측 라벨 · 챔프+룬+소주 · KDA · CS · KP% · 양 팀 5명 미니 · 펼치기 시 상세
---
## 2. 설계
### 2.1 라우팅 / 트리거
- 신규 라우트: `/users/:userId/history`
- query param: `?queue=summoners-rift&rank=solo&season=current`
- 클릭 트리거: AuctionPage TeamPanel 멤버 row, PlayerSpotlight 헤더, MatchDetailPage ParticipantRow — **소환사명+아이콘 묶음만** Link (행 전체 X — 입찰 버튼 충돌)
- ACL 없음 (외부 공유 OK — 선행 결정)
### 2.2 큐 매핑
```ts
// apps/web/src/lib/riot-queue.ts (신규) + apps/api/src/modules/riot/riot-queue.constants.ts (신규)
export const RIOT_QUEUE_GROUPS = {
'summoners-rift': {
label: '소환사의 협곡',
queues: { all: [400, 420, 430, 440], solo: [420], flex: [440], normal: [400, 430] },
},
'aram': { label: '칼바람 나락', queues: { all: [450], solo: [], flex: [], normal: [450] } },
'urf': { label: '우르프', queues: { all: [900, 1900], solo: [], flex: [], normal: [900, 1900] } },
'arena': { label: '아레나', queues: { all: [1700, 1710], solo: [], flex: [], normal: [1700, 1710] } },
} as const;
```
`랭크 전체 = solo ∪ flex`. `일반 = 400/430`. queueId 는 [queues.json](https://static.developer.riotgames.com/docs/lol/queues.json) 1차 기준 — §6.B 검증.
### 2.3 enrichment 정책 — server-only + on-demand 큐잉
페이지 진입 시 **API 호출 0**. 다음 두 경로로만 데이터가 채워짐:
| 경로 | 트리거 | 우선순위 |
|---|---|---|
| 야간 prefetch (선행 plan §3.8) | 03~07시 KST | low |
| 사용자 "갱신" 버튼 | 명시적 클릭 | high |
| 신규 RiotAccount 등록 | dakao 명령 | high (동기 — 큐 우회) |
→ **서버 데이터만** 보여줌. 큐 미사용 데이터(예: 첫 방문 사용자, 한 번도 prefetch 안 된 큐) 는 빈 상태 placeholder + "갱신" 버튼 강조.
#### schema 확장
```ts
// RiotAccount 에 추가
matchIdsByQueueFetchedAt?: Map<number, Date>; // 큐별 마지막 list 페치 시각
lastRefreshRequestedAt?: Date; // refresh budget 추적
```
### 2.4 전역 Riot API 작업 큐 (핵심)
#### 왜 Redis Stream (Garnet)
NATS JetStream 과 비교 검토 결과 **Redis Stream 채택**:
| 항목 | Redis Stream (Garnet) | NATS JetStream |
|---|---|---|
| 추가 셋업 | **0** (이미 사용 중) | stream/consumer 활성화 필요 |
| 클라이언트 코드 | `garnet.ts` 의 `xAdd/xReadGroup/xAck/xPending/xClaim` wrapping 재사용 | 신규 작성 |
| ack / redelivery | PEL + `xClaim` 기본 | 기본 |
| consumer group | 지원 | 지원 |
| 운영 부담 | Redis 모니터링만 | NATS + JetStream 둘 다 |
→ 단일 작업 종류 + 우선순위 2단계 + dedup 워크로드에 Redis Stream 충분. 우리 `GarnetClient` 의 stream 메서드 그대로 활용.
#### 스트림 구조
```
stream: riot:queue:high # 사용자 갱신 요청
stream: riot:queue:low # 야간 prefetch
consumer group: riot-refresh-worker (양 stream 공통)
```
- **우선순위 = stream 분리**. worker 한 사이클에서 high `xReadGroup` 먼저 → 비면 low `xReadGroup` (BLOCK 1s).
- **단일 active worker 인스턴스**. rate limit 자체가 글로벌 직렬화라 분산해도 의미 없음. Garnet `setStringIfAbsent('riot:worker:leader', ..., 60s)` 로 leader election, leader 만 loop. lease 갱신은 worker tick 마다.
- **PEL/xClaim 으로 crash recovery**: leader 가 죽으면 30분 idle 후 새 leader 가 PEL 메시지 claim → 재처리.
#### 작업 단위 — sub-job 분할 (큐 그룹별 1 job)
사용자가 `queueGroup='all'` 같은 다중 큐를 요청해도 **백엔드가 큐 그룹 단위로 sub-job 으로 쪼개 enqueue**. 이유:
- 한 사용자 갱신이 큐를 길게 점유하지 않음 → fairness 향상
- 큐 그룹 1개 끝나는 즉시 부분 결과 표시 가능 (소협 끝 → 소협 데이터부터 보임)
- ETA 표시가 자연스러움 ("소협 12초 / 칼바람 8초 / ... 합 36초")
```ts
interface RefreshSubJob {
jobId: string; // uuid
parentJobId?: string; // 그룹 묶음 식별 (UI 진행률 합산용)
userId: string;
puuid: string;
region: RiotRegionalRoute;
platform: RiotPlatformRoute;
queueGroup: keyof typeof RIOT_QUEUE_GROUPS; // 'summoners-rift' 등
queueIds: number[]; // 그룹 내 모든 큐
requestedAt: number;
requestedBy?: string;
priority: 'high' | 'low';
}
```
dedup 키:
- `riot:job:dedup:<puuid>:<queueGroup>` NX EX 5분
- 이미 있으면 기존 jobId 반환, 새 enqueue 안 함
#### 신규 모듈
```
apps/api/src/modules/riot-job-queue/
riot-job-queue.module.ts
riot-job-queue.service.ts # enqueue / dedup / status / ETA / parent 그룹
riot-job-worker.service.ts # leader election + xReadGroup loop
riot-job-queue.types.ts
riot-job-queue.controller.ts # GET /riot/jobs/:jobId, /riot/jobs/stats
```
`RiotJobQueueService.enqueueRefresh(params: { puuid, userId, queueGroups: string[], priority, ... }): Promise<EnqueueResult>`
- 입력 큐 그룹별 sub-job 생성
- 각 sub-job dedup → 기존 또는 신규 publish (`xAdd`)
- 응답:
```ts
interface EnqueueResult {
parentJobId: string;
subJobs: { jobId: string; queueGroup: string; alreadyQueued: boolean; etaSeconds: number; queuePosition: number }[];
totalEtaSeconds: number;
}
```
`RiotJobQueueService.getStatus(jobId): Promise<JobStatus>`
- Garnet `riot:job:status:<jobId>` (state, enqueuedAt, startedAt, finishedAt, error, etaSeconds)
`RiotJobQueueService.getParentStatus(parentJobId): Promise<ParentStatus>`
- 모든 sub-job 합쳐서 진행률 (`done / total`) + 남은 ETA 계산
`RiotJobWorkerService`:
- leader 만 동작. follower 는 lease 만 polling.
- pseudo:
```ts
while (alive) {
const msg = await garnet.readGroup('riot:queue:high', GROUP, consumer, '>', { count: 1, blockMs: 100 });
const target = msg ?? await garnet.readGroup('riot:queue:low', GROUP, consumer, '>', { count: 1, blockMs: 1000 });
if (!target) continue;
await processSubJob(target); // ensureFreshForQueue + 그룹 페치 dedup
await garnet.acknowledgeStream(stream, GROUP, target.id);
await refreshLeaderLease();
}
```
- 작업 시작 → 끝 까지 RiotClientService 가 throttle 통과. 별도 sleep 없음.
- 완료/실패 시 status 업데이트 + Garnet pub `riot:refresh:events` 채널 publish → socket.io 게이트가 broadcast (§2.5.2 참고).
- EWMA 로 평균 작업 시간 갱신 (key: `riot:job:avg-seconds`).
#### 운영자 controls
- `GET /riot/jobs/stats` — high/low 큐 길이, 평균 처리 시간, 최근 실패율, 현재 leader instance id
- `POST /riot/jobs/drain` (admin) — 큐 비우기
### 2.5 UX 피드백 — 채택 정책 (사용자 결정)
세 가지 권장안 모두 채택: **(1) Stale-while-revalidate + (2) Refresh broadcast + (3) 그룹 페치 dedup**.
#### 2.5.1 Stale-while-revalidate
- 페이지 진입 시 서버 데이터 **즉시 표시** (Riot API 호출 0).
- 동시에 백그라운드로 `enqueueRefresh({puuid, queueGroups: [현재 탭], priority: 'low', requestedBy: 'page-view'})` 자동 호출 — refresh budget 통과 시에만.
- 사용자가 "갱신" 버튼을 누르면 동일 enqueue 를 `priority: 'high'` 로 재발행 (dedup 으로 중복 방지, 단 priority 격상).
- 결과 도착 시 broadcast 로 자동 reload (§2.5.2).
→ 사용자가 갱신을 의식하지 않아도 자연 신선화. 명시적 클릭은 "지금 당장 + high 우선순위" 의미.
#### 2.5.2 Refresh broadcast (socket.io)
- 기존 `useAuctionSocket` 패턴 재활용. 신규 namespace `/riot-refresh` 또는 같은 socket 의 `riot-refresh` event.
- 클라가 페이지 진입 시 `subscribe('puuid:<puuid>')` join.
- worker 가 sub-job 완료 시 `emit('riot-refresh', { parentJobId, jobId, queueGroup, puuid, state })` broadcast.
- 같은 puuid 페이지를 보는 **모든 클라**가 React Query invalidate → 자동 reload.
- per-queue-group 단위 invalidate 라 부분 결과 점진 표시 가능 (소협 끝 → 소협 표/카드만 reload).
#### 2.5.3 그룹 페치 dedup
- worker 가 sub-job (puuid, queueGroup) 처리 시:
1. `RiotRecentMatchesService.ensureFreshForQueue` 가 큐별 list call (그룹 N큐 면 N call)
2. **detail call 은 그룹 내 모든 큐의 matchId 합집합에서 RiotMatch 미존재분만** 페치 — 큐 사이 중복 매치 dedup
3. 같은 puuid 의 이미 처리된 sub-job(같은 parentJobId) 이 동일 detail 을 가져왔으면 skip
- 4개 그룹 동시 갱신 시 detail 호출량 ~30% 감소 추정.
#### 2.5.4 "갱신" 클릭 흐름
```
[갱신 버튼] 클릭
│
├─→ POST /communities/:cid/users/:uid/refresh
│ body: { queueGroups: ['summoners-rift', ...], priority: 'high' }
│ resp: { parentJobId, subJobs: [{jobId, queueGroup, etaSeconds, queuePosition, alreadyQueued}], totalEtaSeconds }
│
├─→ 즉시 토스트: "갱신을 요청했어요. 약 36초 후 반영됩니다 (대기열 4번째)"
│ - alreadyQueued 면 "이미 요청 중입니다 (남은 시간 ~)"
│
├─→ socket.io 'riot-refresh' subscribe (parentJobId/puuid 필터)
│ - sub-job 완료 도착마다 해당 큐 그룹 React Query invalidate
│
└─→ 모든 sub-job 완료 시 토스트 "갱신 완료"
실패 시 토스트: "갱신 실패: <reason>. 잠시 후 다시 시도해 주세요."
```
#### 2.5.5 Refresh budget — 폭주 방지
- 사용자당 **5분에 1회** (`RiotAccount.lastRefreshRequestedAt` 검사). 단, page-view 로 자동 enqueue 된 low priority 는 별도 카운터 (사용자당 1시간 1회).
- 글로벌 high 큐 길이가 50 초과면 새 high enqueue 거부 (`429 { reason: 'queue-full', retryAfterSeconds }`)
- IP 단위 rate limit 은 Phase 후속.
#### 2.5.6 빈 데이터 placeholder
- 챔피언 통계 0 행: "아직 수집된 매치가 없습니다. [갱신 요청] 을 눌러 가져오세요." (Stale-while-revalidate 가 이미 백그라운드로 fetch 중이면 "갱신 중..." 으로 자동 변경)
- 최근 전적 0 건: 동일.
- 마지막 갱신 시각 항상 표시: "마지막 업데이트: 3시간 전"
### 2.6 시즌 정책 (history 추후 구현, 설계 고려)
#### 현재
- `Community.seasonStartedAt: Date?` (선행 plan) — 단일 시즌 경계.
#### 미래 호환 schema 자리 (지금 추가)
```ts
// schema.ts Community
seasons?: Array<{
id: string; // ex: '2026-split-1'
label: string; // ex: '2026 시즌'
startedAt: Date;
endedAt?: Date;
}>;
// 'current' 시즌 = endedAt 없는 마지막 entry
```
본 plan 1차에서는 `seasons` 미사용, 응답에 `seasonId: 'current' | string` 만 노출. 추후 history 도입 시 dropdown 만 채우면 됨.
#### API 응답에 미리 자리 잡기
```ts
interface ChampionStatsResponse {
// ...
season: { id: string; label: string; startedAt: string | null; endedAt: string | null };
}
```
→ 클라 dropdown 이 `[{id: 'current', label: '현재 시즌'}]` 한 개만 받지만 구조는 list. 추후 backend 가 history 풀 때 client 코드 무수정.
### 2.7 백엔드 aggregate API
#### A. 챔피언 통계
```
GET /communities/:cid/users/:uid/champion-stats
?queueGroup=summoners-rift
&rank=solo|flex|all|normal
&seasonId=current (현재 'current' 만)
```
응답:
```ts
interface ChampionStatsResponse {
queueIds: number[];
season: { id: 'current' | string; label: string; startedAt: string | null; endedAt: string | null };
lastFetchedAt: string | null; // 큐별 fetchedAt 중 가장 오래된 값
champions: ChampionStatsRow[];
totals: ChampionStatsRow;
}
interface ChampionStatsRow {
championId: number;
games: number; wins: number; losses: number; winRate: number;
avgKills: number; avgDeaths: number; avgAssists: number; kda: number;
totalKills: number; totalDeaths: number; totalAssists: number;
doubleKills: number; tripleKills: number; quadraKills: number; pentaKills: number;
avgCs: number; avgCsPerMin: number;
}
```
집계: MongoDB aggregation pipeline. `$match: {participantPuuids, queueId: {$in}, gameCreation: {$gte: seasonStartedAt}}` → `$project participant slice` → `$group by championId`.
캐시: Garnet `riot:champstats:<puuid>:<queueGroup>:<rank>:<seasonId>` TTL 1h.
#### B. 최근 전적 (페이지네이션) — poro.gg 카드
`poro.gg-html.txt` 분석 기준 카드 항목:
- 좌측 라벨: `승리 / 패배 / 다시 둠(remake)` + 큐 종류 ("자유 랭크") + 날짜 ("4월 19일") + 게임 시간 ("28:52")
- 챔피언 아이콘(52px) + 챔피언 레벨 + 룬 키스톤 + 부 룬 스타일 + 소환사 주문 2개
- KDA 큰 숫자 ("4 / 14 / 6") + **평점** ("0.71 평점")
- 우측 통계 컬럼: **킬 관여 %** + **CS** (분당 CS 병기) + **시야점수** + (제어와드 / 와드 설치 / 와드 파괴 아이콘 + 숫자)
- 아이템 6칸 + 트링킷 1칸
- **자주 함께한 챔피언 / 자주 함께한 소환사** 2열 (각 5명, 미니 챔피언 14px + 소환사명)
- 우측 토글 버튼 "매치 상세 정보 열기"
```
GET /communities/:cid/users/:uid/recent-matches
?queueGroup=summoners-rift
&rank=all
&championId=84 (선택, 챔피언 검색 필터)
&limit=10
&cursor=<gameCreation>
```
응답:
```ts
interface RecentMatchesResponse {
matches: RecentMatchView[];
nextCursor: number | null;
lastFetchedAt: string | null;
season: { id: string; label: string; startedAt: string | null; endedAt: string | null };
}
interface RecentMatchView {
matchId: string;
queueId: number;
queueLabel: string; // '자유 랭크' 등
gameCreation: number;
gameDuration: number; // 초
win: boolean;
remake: boolean; // gameEndedInEarlySurrender 또는 duration < 240s
// 본인 participant
championId: number;
championLevel: number;
teamPosition: string; // 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY' | ''
kills: number; deaths: number; assists: number;
kda: number; // (k+a)/d, deaths=0 이면 (k+a)
rating: number; // 평점 — § 2.7.B.1 산식
totalCs: number; // totalMinionsKilled + neutralMinionsKilled
csPerMin: number;
killParticipation: number; // 0~100, 본인 (k+a) / 팀 총킬
visionScore: number;
controlWardsBought: number; // visionWardsBoughtInGame
wardsPlaced: number;
wardsKilled: number;
damageDealtToChampions: number;
damageTaken: number;
goldEarned: number;
items: number[]; // 6칸 (item0~5)
trinket: number; // item6
summonerSpells: [number, number]; // summoner1Id, summoner2Id
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
// 양 팀 5명씩 미니 (poro.gg 우측 두 컬럼)
teams: Array<{
side: 100 | 200;
win: boolean;
objectives?: { baron?: number; dragon?: number; tower?: number };
participants: Array<{
puuid: string;
gameName: string;
tagLine: string;
championId: number;
teamPosition: string;
kills: number; deaths: number; assists: number;
}>;
}>;
}
```
##### 2.7.B.1 평점 (rating) 산식
poro.gg/op.gg 의 정확한 산식은 비공개. 1차 근사:
```
rating = 0.4 * normalize(kda) // KDA 기여
+ 0.2 * normalize(killParticipation)
+ 0.2 * normalize(csPerMin)
+ 0.1 * normalize(damageShare) // damage / 팀 총damage
+ 0.1 * normalize(visionScore) // jungle/support 가중
```
- normalize 는 라인별 평균 대비 z-score → 0~10 사이 클램프
- "Perfect" = deaths === 0 일 때 최대값 표시 (poro.gg 동일)
- 정확한 산식은 Phase 후속에서 운영자 캘리브레이션
#### B'. 최근 N게임 요약 박스 (poro.gg 헤더)
이미지 상단의 "최근 20게임 전적 요약" 박스 응답:
```
GET /communities/:cid/users/:uid/recent-summary
?queueGroup=summoners-rift
&rank=all
&championId=84 (선택, 검색 필터와 연동)
&limit=20 (기본 20)
```
```ts
interface RecentSummaryResponse {
windowSize: number; // 실제 사용된 매치 수 (≤ limit)
winRate: number; wins: number; losses: number;
streak: { type: 'win' | 'loss'; count: number }; // "2 연패"
kda: number; // 총합 기준
avgKills: number; avgDeaths: number; avgAssists: number;
bestRating: { rating: number | 'Perfect'; kills: number; deaths: number; assists: number; matchId: string };
positionRates: Partial<Record<RiotLane, number>>; // "비드 100%" 등 라인별 픽률
topChampions: Array<{ // 자주 플레이하는 챔프 상위 3
championId: number;
games: number;
winRate: number; // %
pickRate: number; // 본 큐 그룹 내 비율 %
avgRating: number;
}>;
lastFetchedAt: string | null;
}
```
서버 aggregate. Garnet 캐시 1h TTL. 키: `riot:recentsummary:<puuid>:<queueGroup>:<rank>:<championId|none>:<limit>`.
#### C. 갱신 요청
```
POST /communities/:cid/users/:uid/refresh
body: { queueGroups: string[], priority: 'high' | 'low' }
응답: EnqueueResult (§2.4)
또는 429 { reason: 'cooldown' | 'queue-full', retryAfterSeconds }
```
#### D. 작업 상태
```
GET /riot/jobs/:jobId
응답: { state: 'queued' | 'processing' | 'completed' | 'failed',
etaSeconds: number, enqueuedAt, startedAt, finishedAt, error? }
```
### 2.8 인덱스 보강
`RiotMatch` schema 에 추가:
- `{ participantPuuids: 1, queueId: 1, gameCreation: -1 }` (queue 필터 + 정렬)
---
## 3. 변경 사항 (파일 단위)
### 3.1 백엔드 신규
```
apps/api/src/modules/riot/riot-queue.constants.ts
apps/api/src/modules/riot-job-queue/
riot-job-queue.module.ts
riot-job-queue.service.ts
riot-job-worker.service.ts
riot-job-queue.types.ts
riot-job-queue.controller.ts # GET /riot/jobs/:jobId, /riot/jobs/stats
apps/api/src/modules/match-history/
match-history.module.ts
match-history.controller.ts # champion-stats, recent-matches, refresh
match-history.service.ts
match-history-cache.service.ts
match-history.types.ts
```
### 3.2 백엔드 수정
- `schema.ts`:
- `RiotAccount.matchIdsByQueueFetchedAt: Map<number, Date>`
- `RiotAccount.lastRefreshRequestedAt: Date`
- `Community.seasons` (자리만)
- `RiotMatch` 신규 인덱스
- `riot-recent-matches.service.ts`:
- `ensureFreshForQueue({puuid, queueId, ttlMs, limit})` — worker 가 호출
- `RiotJobWorkerService` 가 `RiotRecentMatchesService.ensureFreshForQueue` 직접 호출
- `app.module.ts`: `RiotJobQueueModule`, `MatchHistoryModule` import
### 3.3 프런트 신규
```
apps/web/src/lib/riot-queue.ts
apps/web/src/pages/UserHistoryPage.tsx
apps/web/src/components/history/
UserHistoryHeader.tsx # 프로필 + 마지막 갱신 + 갱신 버튼
QueueTabs.tsx # 전체/솔로/자유/일반/칼바람/우르프/아레나
RankFilter.tsx
SeasonSelector.tsx # 'current' 1개만 — 미래 list 호환
ChampionSearchFilter.tsx # 챔피언 검색 (한글 초성/별명 매칭) — 클라사이드 + ddragon manifest
RecentSummaryBox.tsx # "최근 20게임 전적 요약" (승률/KDA/최고평점/포지션픽률/자주픽챔)
ChampionStatsTable.tsx # 정렬 가능
RecentMatchesList.tsx # useInfiniteQuery
RecentMatchCard.tsx # poro.gg 스타일 (요약/펼치기)
RecentMatchDetail.tsx # 펼친 상세 (양 팀 5명 풀 정보)
RefreshButton.tsx # ETA 토스트 + socket invalidate
EmptyState.tsx
```
> 챔피언 검색: 한글/영문/초성/별명 매칭(가렌, ㄱㄹ, garen 등). ddragon manifest 의 `name` + 별명 사전(별도 정적 파일 `apps/web/src/lib/champion-aliases.ts`)으로 클라사이드 필터. 백엔드는 `championId` 만 받음.
### 3.4 프런트 수정
- `App.tsx`: `<Route path="/users/:userId/history" element={<UserHistoryPage />} />`
- `api/hooks.ts`: `useChampionStats`, `useRecentMatches` (`useInfiniteQuery`), `useRefreshAccount`, `useJobStatus`
- `api/types.ts`: 응답 타입들
- `AuctionPage.tsx`, `MatchDetailPage.tsx`: 소환사명+아이콘 묶음을 `<Link>`
### 3.5 socket.io 통합
기존 `useAuctionSocket` 패턴 재활용. 신규 namespace `/riot-refresh` 권장 (auction socket 분리):
- 클라가 페이지 진입 시 `socket.emit('subscribe', { puuid })`
- worker 가 sub-job 완료 시 `gateway.to(`puuid:${puuid}`).emit('riot-refresh', { parentJobId, jobId, queueGroup, state })`
- 클라가 메시지 수신 시 해당 큐 그룹 React Query (`['champion-stats', puuid, queueGroup, ...]`, `['recent-matches', ...]`, `['recent-summary', ...]`) invalidate
- 같은 puuid 페이지를 보는 모든 클라가 동시에 새로고침됨 (broadcast 효과)
---
## 4. 단위 테스트
- `riot-job-queue.service.spec.ts`
- dedup: 같은 (puuid, queueIds) enqueue 시 동일 jobId 반환
- ETA 계산: 큐 길이 × avg → seconds
- refresh budget: 5분 안 재요청 시 429
- `riot-job-worker.service.spec.ts`
- high subject 우선 처리, high 비면 low fetch
- throttle wait 시 작업 그대로 진행
- `match-history.service.spec.ts`
- queueGroup → queueIds 매핑
- aggregate 결과 sums/avgs 정확
- season 필터 적용 (gameCreation < startedAt 제외)
- cursor 페이지네이션 nextCursor 정확
- `match-history-cache.service.spec.ts`
- 같은 키 두 번째 호출 aggregate 0회
- 프런트
- `RefreshButton` 토스트 ETA 문구
- `ChampionStatsTable` 정렬 토글
- `RecentMatchCard` win/lose 색상, remake 표시
---
## 5. Rollout
1. (PR-1) `riot-queue.constants.ts` + schema 확장 (`matchIdsByQueueFetchedAt`, `lastRefreshRequestedAt`, `Community.seasons` 자리, RiotMatch 인덱스 보강) + `ensureFreshForQueue`
2. (PR-2) `RiotJobQueueModule` (Redis Stream consumer + leader election + dedup + sub-job 분할 + status) + 테스트
3. (PR-3) `MatchHistoryModule` champion-stats + recent-summary + Garnet 캐시
4. (PR-4) recent-matches + cursor 페이지네이션 + 평점 산식
5. (PR-5) refresh 엔드포인트 + budget + socket `/riot-refresh` namespace
6. (PR-6) 그룹 페치 dedup 로직 (worker 내부)
7. (PR-7) 프런트 라우트 + `UserHistoryPage` 골격 + `QueueTabs` + `RankFilter` + `SeasonSelector`
8. (PR-8) `RecentSummaryBox` + `ChampionStatsTable` (정렬)
9. (PR-9) `RecentMatchCard` (poro.gg 스타일) + `RecentMatchDetail` 펼치기
10. (PR-10) `ChampionSearchFilter` (별명 사전 + 초성 매칭)
11. (PR-11) `RefreshButton` + Stale-while-revalidate 자동 enqueue + ETA 토스트 + socket invalidate
12. (PR-12) AuctionPage / MatchDetailPage 클릭 트리거
13. (PR-13) 운영 모니터링 (큐 길이 / aggregate 응답 시간 / Garnet hit / leader 상태)
---
## 6. 추가 고려사항
### 확정 (사용자 결정 2026-04-26)
- **서버 데이터만 표시**: 페이지 진입 시 Riot API 호출 0회
- **전역 작업 큐**: **Redis Stream (Garnet)** — high/low stream 분리 + dedup + leader election + PEL/xClaim 재처리
- **작업 단위**: queueGroup 단위 sub-job 분할 (한 사용자가 큐 길게 점유 X)
- **UX 정책**: (1) Stale-while-revalidate + (2) Refresh broadcast + (3) 그룹 페치 dedup 모두 채택
- **Refresh budget**: 5분당 1회 high, 1시간당 1회 low(자동)
- **카드 스타일**: poro.gg (`poro.gg-html.txt` 분석 기준 — 평점/킬관여/시야/와드/자주함께한 챔피언·소환사 포함)
- **챔피언 검색 필터**: 클라사이드 (한글/영문/초성/별명)
- **시즌 history**: 본 plan 1차 미구현, schema/응답에 자리만 마련
### 미결 (가벼운 확인 권장)
#### A. 평점 산식 캘리브레이션
§2.7.B.1 의 1차 근사 가중치는 추측. 실제 사용자 데이터로 분포 확인 후 조정 필요. 운영 후 Phase 후속에서 처리.
#### B. 큐 매핑 검증
`RIOT_QUEUE_GROUPS` 의 큐 id 는 [queues.json](https://static.developer.riotgames.com/docs/lol/queues.json) 1차 추정. 운영 사용자 데이터로 검증 필요.
#### C. Refresh 폭주 시나리오
큐가 길 때 "현재 갱신 요청이 많습니다 (대기 12분)" 표시 + 야간 prefetch 안내. 너무 길면 갱신 자체를 비활성화.
#### D. socket.io 가드
`/riot-refresh` namespace 가 외부 공개라 puuid subscribe 가 무제한이면 broadcast 비대화 가능. 동일 socket 당 max subscribe 수 제한 (예: 5) 추가 권장.
### 추후 (Phase 후속)
- 시즌 history 본격 도입 (`Community.seasons` 활용 + dropdown)
- 평점 산식 캘리브레이션
- IP 단위 rate limit
- admin 페이지 (큐 모니터링 / drain)
- aggregation 결과 mat-view (큐가 매우 길어질 때)
---
## 7. Done 정의
- AuctionPage 멤버 / PlayerSpotlight, MatchDetailPage 참가자 소환사명 클릭 → `/users/:userId/history` 이동
- 페이지에 큐 7탭(전체/솔로/자유/일반/칼바람/우르프/아레나) + 챔피언 검색 + 시즌 dropdown(현재 1개) + 최근 N게임 요약 박스 + 챔피언 통계 표 + 최근 전적 무한 스크롤(poro.gg 카드)
- 페이지 진입 시 **Riot API 호출 0회** (서버 로그로 확인)
- 페이지 진입 시 자동 백그라운드 enqueue (low priority) — 1시간 budget 안에서만
- "갱신" 클릭 시 ETA 토스트 ("약 ~초 후 반영, 대기열 N번째") + sub-job 완료 도착마다 해당 큐 그룹 React Query invalidate (점진 표시)
- 같은 puuid 페이지 보는 다른 클라도 socket broadcast 로 자동 reload
- 같은 사용자 5분 안 high 재요청 시 429 cooldown
- Redis Stream worker 1 인스턴스만 active (leader election 동작), 큐 길이/처리 시간 로그
- 그룹 페치 dedup: 4개 큐 그룹 동시 갱신 시 detail 호출 중복 0건 (로그 metric)
- 챔피언 통계 컬럼 정렬 토글 (게임수 / 승률 / KDA / CS)
- 챔피언 검색 input 에 "ㄱㄹ" 입력 시 가렌·갈리오·갱플랭크 등 hits
- 같은 (puuid, 큐, 랭크, 시즌) 1h 안 재요청 시 aggregation 0회 (Garnet hit)
- `Community.seasons` schema 자리 추가 (1차 empty, 응답 `season.id = 'current'` 고정)
- 단위 테스트 통과 (sub-job 분할 / leader election / 그룹 페치 dedup / 평점 산식 / 챔피언 검색 매칭)
-673
View File
@@ -1,673 +0,0 @@
# Riot 최근 솔로랭크 통계 통합 플랜
> **대상**: codex가 이어서 진행 가능한 수준의 실행 플랜
> **레포**: `/Users/dahyeon/source/lolympus-tournament-support` (pnpm workspace)
> **작성 기준**: 2026-04-26
> **선행 작업**: Riot-캐싱-Phase2-플랜.md, Riot-DDragon Manifest 도입(`RiotDdragonService` + Garnet 캐시) 완료
---
## 1. Context
`AuctionPage.tsx` 의 "최근 솔로랭크" 카드(승률/전적/KDA/평균 CS)가 현재 모두 `0`/`NaN` 으로 표시됩니다. 백엔드는 이미 `RiotAccount.recentStatsSummary` 필드를 노출하고 있고 mapper도 이를 전달하지만, **이 필드를 채우는 enrichment 단계가 비어 있습니다.**
이번 작업은 다음을 추가합니다.
1. **Match-V5 by-puuid (queue=420)** 으로 솔로랭크 matchId 목록 동기화
2. **Match-V5 detail** 호출 → `RiotMatch` 컬렉션에 raw 보관 (이미 schema 존재)
3. 사용자별 `RiotAccount.recentStatsSummary` 재계산 + `recentStatsFetchedAt` 갱신
4. enrichment 트리거(수동 / 신규 등록 / 경매 직전) 와 TTL/Garnet dedup 적용
5. 클라가 0/NaN 대신 실제 값을 표시하도록 mapper 점검
이미 다음이 갖춰져 있어 추가 인프라가 거의 필요 없습니다.
- `RiotMatchService.getMatchIdsByPuuid({queue, count, ...})` (`riot-match.service.ts`)
- `RiotMatchService.getMatch(matchId)` 가 `RiotMatchDto` 파싱까지 포함
- `RiotMatch` 컬렉션(`riot_match`) + `participantPuuids` 인덱스(`schema.ts:573`)
- `RiotAccount.matchIds`, `matchIdsFetchedAt`, `recentStatsSummary`, `recentStatsFetchedAt` 필드(`schema.ts:128-148`)
- `GarnetService` (in-flight dedup / TTL 락 용도)
---
## 2. 결정된 설계 사항
### 2.1 큐 정책
- **1차 대상은 솔로랭크(`queueId=420`) 만**.
- 자유랭크(`440`)/노말은 추후 Phase 확장. 코드는 `queueId` 를 인자로 받는 형태로 짜되 호출부는 420 고정.
### 2.2 "최근" 의 정의
- **최근 20경기** 고정 윈도우 (사용자 결정). 상수 `RIOT_RECENT_MATCH_LIMIT = 20` 으로 service 모듈에 정의, 환경변수화 하지 않음.
- 시즌 경계 보정은 하지 않음. `mostPlayedChampionIds` 가 시즌 패치에 따라 의미가 흔들릴 수 있다는 한계를 README/주석에 명시.
### 2.3 캐시 / TTL
- `RiotAccount.recentStatsFetchedAt` 기반 staleness 검사. TTL 기본 **6h** (mastery와 동일).
- enrichment 진행 중 동일 (userId, puuid) 키 중복 호출 방지: 메모리 + Garnet **NX 락**.
- 메모리 dedup: `RiotAccountEnrichmentService.inFlight` 패턴 그대로 확장
- Garnet 락: `riot:enrich:matches:<puuid>` 키 + `setStringIfAbsent(..., 60)` (다중 인스턴스 안전망)
- ddragon manifest 패턴(`Riot-DDragon`)과 동일하게 in-flight 후 **TTL 캐시 갱신** → 다음 호출은 즉시 fresh 반환.
### 2.4 RiotMatch 저장 정책
- `RiotMatch.matchId` 기준 upsert. **이미 존재하면 API 재호출하지 않음** (다른 사용자가 이미 가져왔을 가능성).
- `participantPuuids` 인덱스 활용 → 한 puuid 의 최근 N경기를 DB에서 즉시 조회 가능.
- Riot raw 응답은 `raw` 필드(Mixed) 에 통째로 저장. 핵심 메타(`gameCreation`, `gameDuration`, `gameVersion`, `queueId`) 는 top-level 으로 복제(필터/정렬용).
- 페이로드 크기 우려: 한 경기 ≈ 30~80KB. 활성 사용자 100명 × 20경기 = 최대 2k 도큐먼트 ≈ 100MB 미만, 같은 매치 dedup 으로 실제는 더 작음.
- **TTL/prune 없음 (사용자 결정).** 무한 누적 정책. 추후 컬렉션 비대화 시 별도 prune job 검토.
### 2.5 통계 계산 규칙 (라인별 분리)
**사용자 결정 2026-04-26**: 탑/정글/미드/바텀/서폿 라인별로 데이터 구분 필요.
#### 라인 식별
- Match-V5 participant 의 `teamPosition` 필드 (`TOP` | `JUNGLE` | `MIDDLE` | `BOTTOM` | `UTILITY`) 사용.
- 빈 문자열인 경우 `individualPosition` 으로 fallback.
- 둘 다 비어있거나 `Invalid` 면 통계에서 제외 (집계 카운트 안 함).
#### 우리 측 enum 매핑
```ts
// schema 신규
export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY';
const POSITION_TO_LANE: Record<Position, RiotLane> = {
TOP: 'TOP',
JGL: 'JUNGLE',
MID: 'MIDDLE',
ADC: 'BOTTOM',
SUP: 'UTILITY',
};
```
#### 새 데이터 구조
```ts
export interface RiotLaneStats {
games: number;
wins: number;
losses: number;
avgKills: number; // 소수 1자리
avgDeaths: number;
avgAssists: number;
avgCs: number; // (totalMinionsKilled + neutralMinionsKilled) / games
avgCsPerMin: number; // 분당 CS — 라인 비교용 (서폿 비교 한계 보정)
mostPlayedChampionIds: number[]; // 상위 3, Riot DTO 와 동일 number
}
export interface RiotRecentStatsSummary {
overall: RiotLaneStats;
byLane: Partial<Record<RiotLane, RiotLaneStats>>; // 게임이 1회 이상 있는 라인만 entry
// 기존 flat 필드들은 schema 마이그레이션을 통해 제거. § 2.5.1 참고.
}
```
`mostPlayedChampionIds` 는 **`number[]`** (Riot DTO 와 동일). 클라는 ddragon manifest 로 표시명 풀이. § 2.5.3 참고.
### 2.5.3 championId 타입 통일 (전체 number)
기존 정합성 깨진 곳: `RiotRecentStatsSummary.mostPlayedChampionIds: string[]` (`schema.ts:123`) — Phase2 에서 mastery 는 number 로 바꿨는데 이 한 줄만 string 으로 잔존. Riot 모든 응답이 number 이므로 **number 로 통일**.
영향 받는 위치:
- `apps/api/src/modules/global/database/schema.ts:123` — `string[]` → `number[]`
- `apps/api/src/modules/riot/riot.types.ts` — `RiotRecentStatsSummary` 동일 변경
- `apps/web/src/api/types.ts` — `ApiRiotRecentStatsSummary.mostPlayedChampionIds`, 그리고 §3.7 신규 `ApiRiotLaneStats` 도 처음부터 `number[]`
- `apps/web/src/lib/ddragon.ts` — 이미 `string | number` 둘 다 받게 만들어둠. 변경 불필요.
기존 DB 도큐먼트에 `string[]` 으로 저장된 게 있을 가능성: enrichment 한 번 돌면 새 구조로 통째 교체되므로 자동 정리. 별도 마이그레이션 스크립트 불필요.
#### 2.5.1 schema 마이그레이션 메모
- 기존 `RiotRecentStatsSummary` (flat) 는 사용처가 mapper 한 곳뿐 (`mappers.ts:184~`).
- DB 에 이미 저장된 도큐먼트는 옛 형태일 수 있으나 enrichment 가 한 번 돌면 자동 덮어씀.
- 안전한 전환: enrichment service 가 응답 직전 항상 새 구조로 만들어 `account.recentStatsSummary = newSummary` 통째 교체. partial merge 안 함.
- 별도 마이그레이션 스크립트 불필요 (TTL 6h 안에 자연 갱신).
### 2.5.4 시즌 경계 — 자동 리셋
LoL 시즌(splits/sets) 시작 시점에는 누적 통계의 의미가 변하므로 자동 리셋 필요. Riot 이 명시적 "season started at" API 를 제공하지 않으므로 **community 단위 수동 설정 + 자동 필터링** 의 하이브리드.
#### Schema 추가
```ts
// schema.ts Community
seasonStartedAt?: Date; // 운영자/admin 이 시즌 시작 시점 등록
```
#### 동작
1. enrichment 진입 시 `community.seasonStartedAt` 조회.
2. `account.recentStatsFetchedAt < community.seasonStartedAt` 이면 **force=true** 로 진행 (TTL 무시).
3. `computeSummary` 가 매치 필터링: `match.info.gameCreation >= seasonStartedAt.getTime()` 인 것만 사용.
4. `account.matchIds` 도 시즌 경계 이전 것은 통계에서 제외 (DB 자체에서는 제거 안 함 — 무한 저장 정책).
#### Trigger
- 운영자가 새 시즌 시작 시 community 의 `seasonStartedAt` 을 수동 갱신 → 다음 enrichment 부터 자동 적용.
- 야간 prefetch 가 다음 사이클에 일괄 갱신.
#### Phase 후속 (자동화 검토)
- Riot patch notes RSS 또는 ddragon `versions.json` 의 major bump 감지로 자동 갱신 — 본 플랜 범위 외.
### 2.5.5 다국가 region 지원 (구조)
현재 enrichment 가 `region: 'asia'`, `platform: 'kr'` 하드코딩. 이미 `Community.riotPlatform`, `Community.riotRegion` 필드는 schema 에 존재하지만 enrichment 호출부에서 사용 안 함.
#### 변경
1. **호출자 책임 모델**: `enrichRiotAccount` 의 `EnrichOptions.platform/region` 으로 community 값을 명시 전달.
2. enrichment 트리거 지점 (`auction.service`, `dakao-user.service`, `prefetch.scheduler`) 에서 community 조회 후 platform/region 을 옵션에 주입.
3. fallback 기본값은 `kr` / `asia` 유지 (community 미지정 시).
4. **Throttle 분리**: §2.7 의 sliding-window 키가 이미 region 별로 분리됨 (`riot:rl:<region>:1s`) — 추가 변경 없음.
5. **DDragon 영향**: `realms/<region>.json` 별 자체 dd 버전이 다를 수 있음. 현재 `RiotDdragonService` 는 글로벌 versions[0] 사용 중 — 한국 클라이언트 dd 버전이 글로벌과 차이 거의 없어 OK. 다른 region 추가 시 region 별 manifest 캐시로 분리 검토.
#### 호출 패턴
```ts
// auction.service.ts:start
const community = await CommunityModel.findById(params.communityId);
const platform = community?.riotPlatform ?? 'kr';
const region = community?.riotRegion ?? 'asia';
const limit = pLimit(3);
await Promise.allSettled(
order.map(p => limit(() => this.enrichmentService.enrichRiotAccount({
userId: p.userId,
puuid: p.puuid,
options: { platform, region, force: false },
}))),
);
```
`prefetch.scheduler` 는 사용자별 community 를 cursor 단계에서 함께 로드 (또는 community → user 양방향 join).
### 2.5.2 0-state UX (사용자 결정: 적당히 제안)
| 상황 | 표시 |
|---|---|
| `overall.games === 0` (enrichment 실패 또는 신규 사용자) | "최근 솔로랭크 기록이 없습니다" placeholder |
| 주 라인(`mainPosition`) 게임 ≥ 1 | 헤더에 주 라인 통계 강조 표시 |
| 주 라인 게임 = 0, 다른 라인 있음 | 헤더에 `overall` 통계 + "주 라인 기록 없음 / 전체 기준" 보조 라벨 |
| 라인별 미니 row | 게임 ≥ 1 라인은 W-L · KDA · CS/min, 0 게임 라인은 회색 dash |
### 2.6 트리거 시점
| 시점 | 호출 방식 | force |
|---|---|---|
| 신규 RiotAccount 등록 (dakao 명령) | 동기 enrich 호출 | true |
| 사용자 수동 갱신 (Phase2 엔드포인트 추가됨) | 동기 호출 | true |
| 경매 `start` 직전 | 참가자 puuid 일괄 enrich (`p-limit` 적용, §2.7 throttle 참조) | false |
| 야간 스케줄러 (Phase 2 후속) | force=false 로 stale 만 갱신 | false |
→ 본 플랜에서는 **트리거 4개 지점만 호출 추가**. 스케줄러는 Phase 2 트랙에서 처리.
### 2.7 Rate Limit / Throttle (개인키 가정)
**전제**: 개인 API 키 — Riot 공식 한도 `20 req / 1s` + `100 req / 120s` (앱 단위, region 별).
#### A. 사전 차단 — `RiotClientService` 통합 throttle
모든 Riot 호출이 `RiotClientService.get()` 을 통과하므로 여기에 한 곳에서 게이트를 건다. **Garnet 기반 sliding-window** 로 다중 인스턴스 안전성 확보.
키 구조:
```
riot:rl:<region>:1s -- ZSET (score=timestampMs, member=uuid)
riot:rl:<region>:120s -- ZSET (동일)
```
호출 시 의사코드:
```ts
async function acquire(region: string): Promise<void> {
const now = Date.now();
for (;;) {
const wait = await checkAndAdd(region, now); // Lua script 추천
if (wait === 0) return;
await sleep(wait);
}
}
```
`checkAndAdd` 는 **Lua script 1회 호출**(원자성):
1. `ZREMRANGEBYSCORE key 0 (now - windowMs)` 로 윈도우 밖 제거
2. `ZCARD key` 로 현재 카운트
3. 한도 초과 시 `ZRANGE key 0 0 WITHSCORES` 로 가장 오래된 항목의 만료 시각 → 대기 시간 반환
4. 가능하면 `ZADD key now uuid` + `EXPIRE key windowMs` 후 0 반환
두 윈도우(1s/120s) 모두 통과해야 진행. 하나라도 막히면 더 큰 wait 반환.
`apps/api/src/modules/riot/riot-rate-limiter.service.ts` 신규:
```ts
@Injectable()
export class RiotRateLimiterService {
constructor(private readonly garnet: GarnetService) {}
public async acquire(region: RiotRegionalRoute | RiotPlatformRoute): Promise<void>;
// 옵션: per-method 한도 추가 시 추가 인자
}
```
설정 상수(코드 상수, 환경변수화 안 함):
```ts
const APP_LIMITS = [
{ windowMs: 1_000, max: 20 },
{ windowMs: 120_000, max: 100 },
];
```
> 안전 마진을 위해 max 를 **18 / 95** 로 살짝 낮추는 옵션을 코드 주석으로 남김 — 다른 클라이언트(예: 로컬 개발기)와 키를 공유할 때 충돌 방지.
#### B. 사후 처리 — 429 backoff
`RiotClientService.get()` 응답이 429 일 때:
1. 기존 `Retry-After` 캡처 로직(`riot.client.service.ts:125`) 활용
2. `Retry-After` 만큼 대기 후 **최대 1회 재시도**
3. 재시도도 429 면 `RiotApiError` throw (현재 동작 유지)
#### C. 클라이언트단 동시성 제한
Auction `start` 트리거에서 5명 동시 enrichment × (1 list + 최대 20 detail) = burst 가 가장 큼. 사전 차단만으로도 Riot 한도는 지켜지지만, 처리 시간이 길어지므로 **fairness 를 위한 동시성 한도** 도 추가:
- `p-limit` 의존성 추가 (`pnpm --filter api add p-limit`)
- enrichment service 내부에서 `recentMatches` 페치 시 detail 호출을 `pLimit(2)` 로 직렬화
- auction.service 트리거에서도 사용자별 enrichment 자체에 `pLimit(3)` 적용
#### D. 메서드 한도(Method Rate Limit)
Match-V5 `getMatch` 는 `2000 req / 10s` 라 앱 한도가 먼저 걸린다 — **본 플랜에서는 method 한도는 별도 추적 안 함**. 추후 다른 method 추가 시 `RiotRateLimiterService` 가 method 단위 카운터도 받도록 확장.
#### E. 운영 가시성
- `RiotRateLimiterService.acquire()` 가 100ms 이상 대기하면 `logger.warn` (throttle 발생 추적)
- 응답 헤더 `X-App-Rate-Limit-Count` 를 매 호출마다 디버그 로그(샘플링) → 실제 사용량 vs 우리 카운터 drift 확인
---
## 3. 변경 사항 (파일 단위)
### 3.1 신규: `apps/api/src/modules/riot/riot-recent-matches.service.ts`
```ts
@Injectable()
export class RiotRecentMatchesService {
constructor(
private readonly connectionService: ConnectionService,
private readonly matchService: RiotMatchService,
private readonly garnetService: GarnetService,
) {}
/** queue=420 기준 최근 N matchId 동기화 + raw 저장. 새로 가져온 RiotMatch 도큐먼트들 반환 */
public async syncRecentMatches(params: {
puuid: string;
region?: RiotRegionalRoute;
limit?: number; // 기본 20
queueId?: number; // 기본 420
}): Promise<RiotMatchDocument[]>;
/** DB 에서 puuid 기준 최근 N matchInfo 조회 (API 호출 없음) */
public async loadFromDb(params: {
puuid: string;
limit?: number;
queueId?: number;
}): Promise<RiotMatchDocument[]>;
}
```
핵심 로직:
1. `getMatchIdsByPuuid({queue, count, region: 'asia'})`
2. 받은 ids 를 `riot_match.find({matchId: {$in: ids}}, {matchId: 1})` 로 존재 여부 조회
3. 없는 것만 `getMatch(matchId)` → upsert (`updateOne({matchId}, {$setOnInsert: {...}}, {upsert: true})`)
4. Garnet 락: `riot:enrich:matches:<puuid>` NX EX 60. 락 획득 실패 시 즉시 return DB 캐시.
5. queueId 필터: list API 의 `queue` 파라미터로 한 번 거르고, detail 응답의 `info.queueId` 로 한 번 더 검증.
### 3.2 신규: `RiotRecentStatsService` (또는 위 service에 합쳐도 OK)
```ts
public computeSummary(matches: RiotMatchDto[], puuid: string): RiotRecentStatsSummary;
```
- 순수 함수. 단위 테스트 추가(`*.spec.ts`).
- 입력 매치에서 `info.participants.find(p => p.puuid === puuid)` 로 본인 participant 찾기.
- 라인 결정: `teamPosition || individualPosition`. 빈 값이면 `byLane` 집계에서 제외하되 `overall` 에는 포함.
- 0경기 입력 시 `overall` 은 모든 수치 0 으로 채운 객체, `byLane` 은 빈 객체 `{}`. 클라 NaN 회피.
- `avgCsPerMin = ((totalMinionsKilled + neutralMinionsKilled) / (gameDuration / 60))` 의 평균. `gameDuration` 은 초 단위.
### 3.3 `riot-account-enrichment.service.ts` 확장
`EnrichOptions` 에 `recentMatchesTtlMs` (기본 6h) 추가.
`EnrichResult` 에 `recentMatches: 'updated' | 'fresh' | 'failed'` 추가.
`doEnrichRiotAccount` 에:
```ts
const recentMatchesStale =
force ||
!account.recentStatsFetchedAt ||
now - account.recentStatsFetchedAt.getTime() > recentMatchesTtl;
const recentOutcome = recentMatchesStale
? await this.fetchRecentMatchesSafe(params.puuid, region)
: { status: 'fresh' as const, summary: null };
if (recentOutcome.status === 'updated' && recentOutcome.summary) {
account.recentStatsSummary = recentOutcome.summary;
account.recentStatsFetchedAt = new Date();
account.matchIds = recentOutcome.matchIds;
account.matchIdsFetchedAt = new Date();
}
```
`fetchRecentMatchesSafe`:
1. `recentMatchesService.syncRecentMatches({puuid, region})`
2. `recentMatchesService.loadFromDb({puuid, limit: 20, queueId: 420})`
3. `computeSummary(matches, puuid)`
4. 실패 시 `failed` 반환 (기존 patterns와 동일).
### 3.4 `riot.module.ts`
`RiotRecentMatchesService`, `RiotRateLimiterService` 를 providers/exports 에 추가. `GarnetModule` 은 `@Global` 이라 별도 import 불필요.
### 3.4.1 `riot.client.service.ts` 변경
- 생성자에 `RiotRateLimiterService` 주입.
- `get()` 진입 시 `await this.rateLimiter.acquire(options.platform ?? options.region ?? 'asia')`.
- 응답이 429 일 때 `Retry-After` 캡처 후 `await sleep(retryAfterMs)` → 한 번 재시도. 재시도도 429 면 throw.
- (기존 동작과의 차이: throttle/재시도 추가, 그 외 인터페이스 동일.)
### 3.5 트리거 지점
- `apps/api/src/modules/dakao/dakao-user.service.ts`: 신규 RiotAccount 등록 직후 `enrichRiotAccount({force: true})` 호출 흐름이 이미 있는지 확인하고 동일 흐름 유지(별도 호출 추가 불필요).
- `apps/api/src/modules/auction/auction.service.ts:start`: order 구성 직후, 참가자 puuid 들에 대해 `p-limit(3)` 으로 동시성 제한:
```ts
const limit = pLimit(3);
await Promise.allSettled(
order.map(p => limit(() => this.enrichmentService.enrichRiotAccount({
userId: p.userId, puuid: p.puuid, options: {force: false}
}))),
);
```
이미 fresh 면 즉시 return 이라 비용 거의 없음. throttle 은 `RiotClientService` 단에서 추가로 보호.
### 3.6 수동 갱신 엔드포인트
Phase 2 플랜의 `POST /me/riot-accounts/:puuid/refresh` 가 추가되면 동일 enrichment 가 호출되므로, **본 플랜에서 별도 엔드포인트는 만들지 않고** Phase 2 와 합류.
### 3.7 클라 — 변경 큼
#### types.ts
```ts
export interface ApiRiotLaneStats {
games: number;
wins: number;
losses: number;
avgKills: number;
avgDeaths: number;
avgAssists: number;
avgCs: number;
avgCsPerMin: number;
mostPlayedChampionIds: string[];
}
export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY';
export interface ApiRiotRecentStatsSummary {
overall: ApiRiotLaneStats;
byLane: Partial<Record<RiotLane, ApiRiotLaneStats>>;
}
```
기존 flat 필드는 제거. 클라는 enrichment 한 번 돌고 난 새 구조 가정.
#### mappers.ts
`AuctionPlayerView.recentStats` 를 새 구조로 정렬. 추가로 `pickPrimary(stats, mainPosition)` 헬퍼:
```ts
const POSITION_TO_LANE: Record<Position, RiotLane> = {
TOP: 'TOP', JGL: 'JUNGLE', MID: 'MIDDLE', ADC: 'BOTTOM', SUP: 'UTILITY',
};
function pickPrimary(summary, mainPosition) {
const lane = POSITION_TO_LANE[mainPosition];
const lanePrimary = summary.byLane[lane];
if (lanePrimary && lanePrimary.games > 0) return { stats: lanePrimary, source: 'lane' };
if (summary.overall.games > 0) return { stats: summary.overall, source: 'overall' };
return { stats: null, source: 'none' };
}
```
#### AuctionPage.tsx — "최근 솔로랭크" 카드 재설계
```
┌ 최근 솔로랭크 ─ 미드 ───────┐ ← 헤더에 표시 기준 라인
│ 승률 56% · 28W 22L │
│ KDA 7.1/3.4/8.2 (4.50) │
│ 분당 CS 7.2 │
├──────────────────────────── │
│ 탑 2W 1L · 5.0/3.3/4.7 │ ← byLane 미니 row
│ 정글 — │ ← 0 게임 dash
│ 미드 25W 19L · 7.1/3.4/8.2 │ ← 강조
│ 바텀 — │
│ 서폿 1W 2L · 1.0/4.0/15.7 │
└─────────────────────────────┘
```
- 헤더: `pickPrimary` 결과의 `stats` + `source === 'overall'` 이면 "(전체 기준)" 보조 라벨.
- 미니 row: 5개 라인 고정 순서 (TOP/JGL/MID/ADC/SUP), 게임 0 인 라인은 회색 dash, 주 라인은 텍스트 굵게.
- `pickPrimary` 결과가 `none` 이면 placeholder ("최근 솔로랭크 기록이 없습니다").
- KDA Perfect 처리(deaths=0) 는 기존 로직 유지.
신규 컴포넌트 분리 권장: `RecentSoloStats` 별 파일이 깔끔.
### 3.8 신규: 야간 prefetch 스케줄러 (5슬롯 분산)
`@nestjs/schedule` 의존성 추가 (`pnpm --filter api add @nestjs/schedule`). app.module 에 `ScheduleModule.forRoot()` 등록.
#### 슬롯 분산 정책 (사용자 결정 2026-04-26)
- 03/04/05/06/07 시 KST **5개 슬롯** 으로 분산.
- 사용자 그룹핑: `userId.hash % 5` 로 슬롯 결정 (decimal index 0~4 → 03시~07시 매핑).
- 안전 마진: 각 슬롯 종료 ≤ 다음 슬롯 시작 (1시간 안에 처리 끝나야). 활성 사용자 100명 / 5슬롯 = 20명/슬롯, throttle 100req/120s 안에서 충분.
- 슬롯별 Garnet 락 키 분리: `riot:cron:nightly-prefetch:slot-<idx>` (NX EX 50m). 다중 인스턴스 leader election + 슬롯 간 독립 실행.
```ts
@Injectable()
export class RiotPrefetchScheduler {
private readonly logger = new Logger(RiotPrefetchScheduler.name);
private readonly LOCK_TTL_S = 50 * 60;
private readonly STALE_THRESHOLD_MS = 24 * 60 * 60 * 1000;
private readonly SLOTS = 5;
private readonly USER_CAP_PER_SLOT = 1000;
constructor(
private readonly connectionService: ConnectionService,
private readonly enrichment: RiotAccountEnrichmentService,
private readonly garnet: GarnetService,
) {}
// 03,04,05,06,07 시 매시 정각
@Cron('0 0 3-7 * * *', { timeZone: 'Asia/Seoul' })
async runSlot() {
const hour = new Date().getHours(); // KST 가정 (TZ 환경 일치 필요)
const slotIndex = hour - 3; // 0..4
if (slotIndex < 0 || slotIndex >= this.SLOTS) return;
const lockKey = `riot:cron:nightly-prefetch:slot-${slotIndex}`;
const acquired = await this.garnet.setStringIfAbsent(
lockKey,
`${process.pid}-${Date.now()}`,
this.LOCK_TTL_S,
);
if (!acquired) {
this.logger.log(`Slot ${slotIndex} skipped — lock held by another instance.`);
return;
}
await this.processSlot(slotIndex);
}
private async processSlot(slotIndex: number) {
const cutoff = new Date(Date.now() - this.STALE_THRESHOLD_MS);
const UserModel = await this.connectionService.getModel('user');
const CommunityModel = await this.connectionService.getModel('community');
const cursor = UserModel.find({
'riotAccounts.recentStatsFetchedAt': { $lt: cutoff },
}).cursor();
const limit = pLimit(2);
let processed = 0;
for await (const user of cursor) {
// 슬롯 분산: hash(userId) % SLOTS
if (this.slotOfUser(user._id.toString()) !== slotIndex) continue;
const community = await CommunityModel.findById(user.communityId).lean();
const platform = community?.riotPlatform ?? 'kr';
const region = community?.riotRegion ?? 'asia';
for (const account of user.riotAccounts) {
const seasonStart = community?.seasonStartedAt;
const seasonStale =
!!seasonStart &&
(!account.recentStatsFetchedAt ||
account.recentStatsFetchedAt < seasonStart);
const ttlStale =
!account.recentStatsFetchedAt || account.recentStatsFetchedAt < cutoff;
if (!ttlStale && !seasonStale) continue;
await limit(() =>
this.enrichment
.enrichRiotAccount({
userId: user._id,
puuid: account.puuid,
options: { platform, region, force: seasonStale },
})
.catch((err) =>
this.logger.warn(`prefetch failed ${account.puuid}: ${err}`),
),
);
processed += 1;
}
if (processed >= this.USER_CAP_PER_SLOT) break;
}
this.logger.log(`Slot ${slotIndex} processed ${processed} accounts.`);
}
private slotOfUser(userId: string): number {
// FNV-1a 32bit — 외부 의존성 없이 안정적 분산
let h = 2166136261;
for (let i = 0; i < userId.length; i += 1) {
h ^= userId.charCodeAt(i);
h = Math.imul(h, 16777619);
}
return Math.abs(h) % this.SLOTS;
}
}
```
#### 동작 요약
- **leader election**: 슬롯별 Garnet NX 락. 다중 인스턴스 중 첫 도달자만 처리.
- **사용자 분산**: FNV-1a 해시로 결정적 분산 (같은 사용자는 항상 같은 슬롯). region 분포가 편향되어도 슬롯별 부하는 균일.
- **throttle 합류**: enrichment 호출이 `RiotRateLimiterService` 통과 → 별도 sleep 불필요.
- **community-aware**: cursor 안에서 community 조회로 platform/region/seasonStartedAt 적용.
- **시즌 force fetch**: `seasonStartedAt > recentStatsFetchedAt` 면 TTL 무시.
- **안전 상한**: 슬롯당 1000 사용자 cap.
- **TZ 주의**: `@Cron` 의 `timeZone` 옵션은 cron 발화에만 영향. `new Date().getHours()` 는 process TZ 따라가므로 운영 환경의 `TZ=Asia/Seoul` 보장 또는 명시 변환 필요. 안전한 대안은 슬롯별 cron 5개 정의 (각 cron 안에서 slotIndex 상수 박기).
#### 더 안전한 변형 (권장)
```ts
@Cron('0 0 3 * * *', { timeZone: 'Asia/Seoul' }) async slot0() { return this.processSlot(0); }
@Cron('0 0 4 * * *', { timeZone: 'Asia/Seoul' }) async slot1() { return this.processSlot(1); }
@Cron('0 0 5 * * *', { timeZone: 'Asia/Seoul' }) async slot2() { return this.processSlot(2); }
@Cron('0 0 6 * * *', { timeZone: 'Asia/Seoul' }) async slot3() { return this.processSlot(3); }
@Cron('0 0 7 * * *', { timeZone: 'Asia/Seoul' }) async slot4() { return this.processSlot(4); }
```
→ TZ 의존성 제거, 슬롯 매핑 명확.
테스트:
- 락 미획득 시 즉시 return 검증
- stale cutoff 기준 정확히 필터링되는지 fixture 기반 검증
- (실제 cron 발화는 e2e 범위 외 — 메서드 직접 호출 테스트로 충분)
---
## 4. 단위 테스트
- `apps/api/src/modules/riot/riot-recent-matches.service.spec.ts`
- `computeSummary`: 0경기 / 단일경기(승) / 5경기 mix / 같은 챔피언 빈도 상위 3개 정렬 검증
- **라인별 집계**: 미드 3경기 + 정글 2경기 fixture → `byLane.MIDDLE.games === 3`, `byLane.JUNGLE.games === 2`
- **빈 teamPosition**: fallback to `individualPosition`, 둘 다 비면 `byLane` 에는 안 들어가도 `overall` 에는 포함
- **avgCsPerMin**: gameDuration 1500s + cs 200 → 분당 8.0
- 같은 puuid 가 detail.participants 에 없는 경우 → 해당 매치 skip
- `apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts` 확장
- `recentMatches` outcome 분기 커버 (stale/fresh/failed)
- `apps/api/src/modules/riot/riot-rate-limiter.service.spec.ts`
- 1초 윈도우 한도 도달 시 다음 호출이 대기하는지 (Garnet은 ioredis-mock 또는 실제 컨테이너)
- 120초 윈도우만 막히는 경우 — 더 큰 wait 반환 검증
- 다중 region (asia/kr) 키가 분리되어 서로 영향 없는지
- `apps/api/src/modules/riot/riot-prefetch.scheduler.spec.ts`
- 락 미획득 시 enrichment 호출 0회
- cutoff 보다 fresh 한 account 는 skip
- 1000 사용자 cap 동작
- **슬롯 분산**: 동일 userId 의 `slotOfUser` 가 항상 동일 값 반환, 1000 사용자 분포 편차 < 30%
- **시즌 force**: `community.seasonStartedAt > recentStatsFetchedAt` 시 force=true 로 enrichment 호출
- community 의 `riotPlatform`/`riotRegion` 이 옵션에 정확히 전달되는지
---
## 5. Rollout
1. (PR-1) `RiotRateLimiterService` + Lua sliding-window + 테스트, `RiotClientService` 통합. **이게 먼저 깔려야 다른 PR 의 enrichment 가 안전.**
2. (PR-2) `RiotRecentMatchesService` + `computeSummary` 라인별 집계 + 테스트, schema 신규 타입 정의
3. (PR-3) `RiotAccountEnrichmentService` 에 통합 + `p-limit` 의존성 추가 + auction.service 트리거
4. (PR-4) 클라 types/mapper/AuctionPage 카드 재설계 (`RecentSoloStats` 컴포넌트)
5. (PR-5) `RiotPrefetchScheduler` + `@nestjs/schedule` 의존성 + Garnet leader election
6. (PR-6) 운영 모니터링 로그 (throttle wait, X-App-Rate-Limit-Count drift, prefetch 처리 건수)
7. (Phase 2 합류) 수동 갱신 엔드포인트
---
## 6. 추가로 고려해야 할 점 (확정 / 미결)
### 확정 (사용자 결정 2026-04-26)
- **API 키 등급**: 개인키 → §2.7 throttle 구현 필수.
- **윈도우 크기**: 20경기 고정 (환경변수화 안 함).
- **RiotMatch 보관**: 무한 저장. TTL/prune 없음.
- **자유랭크/노말 미포함**: queue=420 솔로랭크 only.
- **라인별 데이터 구분**: §2.5 의 `byLane` 구조 + AuctionPage 카드 재설계 (§3.7).
- **lane 보정 = 분당 CS (avgCsPerMin)**.
- **0-state UX**: §2.5.2 표 적용.
- **야간 prefetch 스케줄러**: §3.8 — 03/04/05/06/07 시 KST 5슬롯 분산, 사용자 hash 로 결정적 분산, 슬롯별 Garnet 락.
- **championId 타입 통일**: §2.5.3 — Riot DTO 와 동일 `number` 로 통일. `mostPlayedChampionIds: number[]`.
- **시즌 경계 자동 리셋**: §2.5.4 — `Community.seasonStartedAt` 추가. 운영자 수동 등록 + enrichment 자동 force fetch + 매치 필터링.
- **다국가 region 지원 구조**: §2.5.5 — `Community.riotPlatform/riotRegion` 활용, 호출자가 옵션에 주입. 기본값 kr/asia.
- **외부 공유 OK** — ACL 별도 처리 없음.
### 미결
(없음)
---
## 7. Done 정의
- AuctionPage 의 "최근 솔로랭크" 카드가 0 이 아닌 실제 값을 표시 (테스트 사용자 1명 이상)
- 카드에 라인별 미니 row 5줄(TOP/JGL/MID/ADC/SUP) 표시, 주 라인 강조
- 0게임 사용자에게 placeholder ("최근 솔로랭크 기록이 없습니다") 표시 확인
- 같은 사용자 재진입 시 6h 이내에는 Match-V5 호출 0 회 (서버 로그로 확인)
- `riot_match` 컬렉션에 raw 저장 + `participantPuuids` 인덱스 hit 확인
- Throttle 동작: 21+ calls 동시 발생 시 `RiotRateLimiterService.acquire()` wait 로그 발생, Riot 429 0건
- 야간 03~07시 KST cron 5회 슬롯 발화, 슬롯별로 다른 사용자 집합 처리되는지 로그 확인
- `championId` 가 schema/types/응답 전부에서 `number` 로 통일됨 (grep 으로 string 잔존 0건)
- `Community.seasonStartedAt` 갱신 시 다음 enrichment 가 force fetch 되고, 시즌 이전 매치가 통계에서 제외됨
- enrichment 호출이 community.riotPlatform/riotRegion 을 받아 동작 (`'kr'` 외 region 도 옵션 분기 가능)
- 단위 테스트 통과 (라인별 집계 / throttle 윈도우 / scheduler 슬롯 분산 / 시즌 force / region 전달)
- Phase 2 의 `*FetchedAt` 노출 패턴과 정합 (응답에 `recentStatsFetchedAt` 추가)
-586
View File
@@ -1,586 +0,0 @@
# Riot 캐싱 Phase 2 플랜
> **대상**: codex가 이어서 진행 가능한 수준의 실행 플랜
> **레포**: `/Users/dahyeon/source/lolympus-tournament-support` (pnpm workspace)
> **작성 기준**: 2026-04-25
> **선행 작업**: dakao NATS 통합, RiotAccountEnrichmentService(force=true 동기 호출, summoner/league/mastery v4) 1차 구현 완료
---
## 1. Context
dakao 카카오톡 명령(`!내전 신청 ...`) 이 들어오면 라이엇 ID를 검증·등록하고, 동시에 summoner v4 / league v4 / champion-mastery v4 데이터를 가져와 `User.riotAccounts[*]` 임베딩에 캐싱하는 1차 구현이 끝난 상태입니다.
이 플랜은 그 위에 다음을 더합니다.
1. **community별 default platform 지정** + region/by-puuid 기반 자동 보정
2. **champion-mastery top 10** 으로 좁히고 스키마를 Riot DTO 그대로
3. **league 변동 시 tierHistory 자동 누적**
4. **사용자 수동 갱신 엔드포인트 + 한가한 시간대 스케줄러**
5. **신선도 표시(API 응답에 `*FetchedAt` 노출)**
6. **무거운 필드(`championRecords`, `tiers`)는 list/find 쿼리에서 projection 으로 잘라내기**
7. **동일 puuid 동시 enrichment dedup**
8. **v4 서비스 응답 파서 단위 테스트**
비목표:
- Rate limit 글로벌 throttle (token bucket / Redis) — Phase 3
- OpenSearch / Slack 운영 알림 — Phase 3
- 백오피스 UI — 별도 트랙
---
## 2. 결정된 설계 사항
### 2.1 Riot Schema 우선 (Data Dragon 호환)
기존 `ChampionMasteryEntry`, `TierInfo`, `TierHistoryEntry` 를 Riot v4 응답 그대로 매칭하도록 재정의합니다.
**현재 (수정 전)**
```ts
export interface ChampionMasteryEntry {
championId: string; // ← Riot 은 number
championName?: string; // ← Riot 응답에 없음
level: number; // ← championLevel
points: number; // ← championPoints
}
export interface TierInfo {
queueType: string;
tier: string;
rank: string;
leaguePoints: number;
wins: number;
losses: number;
fetchedAt: Date;
}
```
**목표 (수정 후)**
```ts
// Riot Champion-Mastery-V4 DTO 그대로
export interface ChampionMasteryEntry {
puuid: string;
championId: number;
championLevel: number;
championPoints: number;
lastPlayTime?: number;
championPointsSinceLastLevel?: number;
championPointsUntilNextLevel?: number;
markRequiredForNextLevel?: number;
tokensEarned?: number;
championSeasonMilestone?: number;
milestoneGrades?: string[];
nextSeasonMilestone?: Record<string, unknown>;
}
// Riot League-V4 entries DTO + 우리 측 fetchedAt
export interface TierInfo {
leagueId: string;
queueType: string;
tier: string;
rank: string;
puuid: string;
leaguePoints: number;
wins: number;
losses: number;
veteran?: boolean;
inactive?: boolean;
freshBlood?: boolean;
hotStreak?: boolean;
miniSeries?: Record<string, unknown>;
fetchedAt: Date;
}
// 시점별 tier 스냅샷
export interface TierHistoryEntry {
queueType: string;
tier: string;
rank?: string;
leaguePoints?: number;
wins?: number;
losses?: number;
recordedAt: Date;
// 시즌 단위 통계 / peak (옵션)
season?: string;
peakTier?: string;
peakRank?: string;
}
```
`championRecords` 는 챔피언별 *집계 데이터(향후 매치 분석)* 용으로 유지하되, **mastery 원본은 더 이상 `championRecords` 에 중복 저장하지 않습니다.** mastery 자체가 이제 Riot DTO 형태이기 때문입니다.
기존 schema 의 `RiotAccount.championRecords` 와 `RiotAccount.championRecordsFetchedAt` 는 그대로 둡니다 (다른 용도).
### 2.2 community 별 default platform
```ts
export interface Community extends MongooseTimestamps {
// ...
riotPlatform?: RiotPlatformRoute; // default 'kr'
riotRegion?: RiotRegionalRoute; // default 'asia'
}
```
- platform 기본 `kr`, region 기본 `asia` 는 코드 상 fallback. 명시 지정 시 community 설정값 우선.
- enrichment / lookup 시 community 의 platform 을 사용.
- 추가로 puuid 만 있는 상황(예: 다른 community 매치 import)에서는 region/by-puuid 로 platform 보정.
### 2.3 region/by-puuid 자동 보정
> `GET https://{regional}.api.riotgames.com/riot/account/v1/region/by-game/lol/by-puuid/{puuid}` → `{ puuid, game, region }`
- 응답의 `region` 이 platform 코드 (`kr`, `na1`, …)
- 사용 시점: community 의 platform 과 puuid 의 실제 platform 이 다른지 의심될 때 (예: 처음 등록 시, summoner v4 404 발생 시)
- 새 서비스: `RiotAccountService.getRegionByPuuid(puuid, options)`
- enrichment fallback 정책: summoner v4 가 404 면 region/by-puuid 호출해서 platform 보정 후 한 번 더 시도, 그래도 실패면 failed 처리
### 2.4 mastery top 10
- 엔드포인트 변경: `/lol/champion-mastery/v4/champion-masteries/by-puuid/{puuid}/top?count=10`
- 저장 상한 10. `MASTERY_LIMIT = 10`.
- `RiotChampionMasteryService.getTopByPuuid(puuid, { platform, count })` 신규 메서드. 기존 `getByPuuid` 는 leftover/내부용으로 유지하거나 삭제 (사용처 확인 후 결정).
### 2.5 tierHistory 누적 규칙
- enrichment 가 league entries 를 갱신할 때, **queueType 별로 가장 최근 history entry 와 비교**하여 다음 중 하나라도 다르면 history 에 push:
- `tier`, `rank`
- `leaguePoints` 변화 (옵션 — 너무 잦으면 noise. 1차에선 tier/rank 변화만 추적)
- 1차 결정: **tier 또는 rank 가 변하면 push**. lp 변화는 history 에 안 남김.
- 신규 등록 시(history 비어있음)는 첫 league fetch 결과를 그대로 history 에 1건 push.
- `recordedAt = new Date()`.
- queueType 외 다른 분류는 도입하지 않음. season 추적은 별도 작업.
### 2.6 신선도 노출 (`*FetchedAt`)
API 응답(`GET /users/:id`, `/me`, `/communities/:id/matches/:id` 등)에 RiotAccount 가 포함될 때 다음 필드를 함께 노출:
- `tiers[*].fetchedAt`
- `championMasteriesFetchedAt`
- `revisionDate` (summoner)
- `championRecordsFetchedAt`
스키마 상 이미 존재하므로 변경 불필요. 단, **list 쿼리에서는 무거운 raw 필드(`championRecords`, `championMasteries[*].milestoneGrades` 등) 는 projection 으로 제외**. (2.8 참조)
### 2.7 수동 갱신 + 스케줄러
**HTTP 엔드포인트**
```
POST /users/me/riot-accounts/:puuid/refresh
Body: { force?: boolean, platform?: RiotPlatformRoute }
Auth: 본인 또는 admin
Response: EnrichResult
```
- 본인 또는 community admin 이상만 허용.
- `force = true` 면 TTL 무시.
- platform 지정 시 community default 무시.
**스케줄러**
- NestJS `@nestjs/schedule` (cron) 도입.
- 작업명: `RiotAccountRefreshScheduler`
- 실행 주기: 매일 KST 04:00 ~ 06:00 사이에 chunked 실행
- 대상 선정:
- `tiers[*].fetchedAt` 가 24h 초과 또는 비어있는 RiotAccount
- 한 batch 당 최대 200건, batch 간 5초 간격
- enrichment 호출 시 `force = false` (TTL 기반)
- per-batch try/catch + 실패 카운터 로그
- `@Cron('0 4 * * *')` 단일 트리거로 시작 → 추후 batch 분산은 Phase 3 에서 보강
### 2.8 list/find projection 정책
`apps/api/src/modules/global/database/projection.ts` 신설하여 공통 projection 상수를 모음.
```ts
// 매치 리스트, /me 등에서 RiotAccount 의 무거운 필드를 잘라낸다
export const RIOT_ACCOUNT_LIGHT_PROJECTION = {
'riotAccounts.championRecords': 0,
'riotAccounts.championRecordsFetchedAt': 0,
// championMasteries 자체는 살리되 milestoneGrades 등 무거운 nested 는 protected list 에서만 fetch
} as const;
```
- 적용 대상: `MatchService.list`, `UserController.list`, `MatchController.listMatches` 등
- 단건 조회(`getById`, `/me`) 는 풀 데이터 포함
### 2.9 동일 puuid 동시 enrichment dedup
**채택 방식**: in-memory `Map<puuid, Promise<EnrichResult>>` (단일 인스턴스 dedup)
```ts
private inFlight = new Map<string, Promise<EnrichResult>>();
public enrichRiotAccount(params): Promise<EnrichResult> {
const key = params.puuid;
const existing = this.inFlight.get(key);
if (existing) return existing;
const promise = this.doEnrich(params).finally(() => {
this.inFlight.delete(key);
});
this.inFlight.set(key, promise);
return promise;
}
```
이유:
- 카카오 신청 빈도가 낮아 분산 락까지 필요 없음.
- 동일 인스턴스 내 race(동시 신청)만 막아도 90%의 중복 호출 절감.
- 멀티 인스턴스 환경 dedup 은 Phase 3 (Redis SET NX) 에서.
**대안 비교 (참고)**
| 방식 | 장점 | 단점 |
| --- | --- | --- |
| in-memory Map | 의존성 없음, 빠름 | 멀티 인스턴스 미지원 |
| Mongo `findOneAndUpdate` 락 | 의존성 없음, 분산 가능 | 실패 시 락 만료 처리 복잡, 추가 필드 필요 |
| Redis SET NX EX | 분산 / TTL 자연스러움 | Redis 인프라 필요 |
### 2.10 v4 파서 단위 테스트
- `riot-summoner.service.spec.ts`
- `riot-league.service.spec.ts`
- `riot-champion-mastery.service.spec.ts`
각각 정상 응답 / 누락 필드 거부 / 빈 배열 / 타입 불일치 거부 케이스.
---
## 3. 실행 단계 (codex 진행 순서)
작업 단위는 PR 단위로 쪼갤 수 있도록 분리되어 있습니다. 단계 간 의존성이 있는 부분은 명시.
### Step 1. 스키마 재정의 (TierInfo / ChampionMasteryEntry / TierHistoryEntry)
**파일**: `apps/api/src/modules/global/database/schema.ts`
1. `TierInfo`, `TierHistoryEntry`, `ChampionMasteryEntry` 인터페이스 위 2.1 정의로 교체.
2. `TierInfoSubSchema`, `TierHistoryEntrySubSchema`, `ChampionMasteryEntrySubSchema` 도 동일하게 갱신.
- `championId`: `Number` 로 변경
- `championLevel`, `championPoints`: 새 필드명
- `milestoneGrades`: `[String]` (default `undefined`)
- `nextSeasonMilestone`: `Schema.Types.Mixed`
- `TierInfo` 에 `leagueId`, `puuid`, `veteran`, `inactive`, `freshBlood`, `hotStreak`, `miniSeries(Mixed)` 추가
- `TierHistoryEntry` 에 `recordedAt: { type: Date, required: true }`, `leaguePoints/wins/losses` optional
3. `Community` 에 `riotPlatform`, `riotRegion` 추가:
```ts
riotPlatform: { type: String },
riotRegion: { type: String },
```
4. `MatchParticipantSubSchema.tier` 는 새 `TierInfo` 모양을 자동으로 따라감 — 추가 변경 없음.
**Risk**: 기존 데이터가 있다면 마이그레이션 필요. 현재 dev 환경 seed 만 사용한다면 seed 재실행으로 충분. `apps/api/src/seed.ts` 도 새 필드명에 맞춰 갱신.
**테스트**: 타입체크 통과 확인.
### Step 2. RiotChampionMasteryService → top 엔드포인트로 변경
**파일**: `apps/api/src/modules/riot/riot-champion-mastery.service.ts`
1. 메서드 시그니처 변경 또는 신규:
```ts
public async getTopByPuuid(
puuid: string,
options: { platform?: RiotPlatformRoute; count?: number; signal?: AbortSignal } = {},
): Promise<RiotChampionMasteryDto[]>
```
엔드포인트: `/lol/champion-mastery/v4/champion-masteries/by-puuid/{puuid}/top`
query: `count` (default 10, max 10)
2. 기존 `getByPuuid` 사용처 grep 후 모두 `getTopByPuuid` 로 교체.
3. `riot-account-enrichment.service.ts` 에서 `MASTERY_LIMIT = 10` 으로 변경.
### Step 3. region/by-puuid 서비스 + 자동 보정
**파일**: `apps/api/src/modules/riot/riot-account.service.ts`
```ts
public async getRegionByPuuid(
puuid: string,
options: RiotAccountLookupOptions = {},
): Promise<{ puuid: string; game: string; region: RiotPlatformRoute }> {
return this.riotClientService.get(
`/riot/account/v1/region/by-game/lol/by-puuid/${encodeURIComponent(puuid)}`,
{ region: options.region ?? 'asia', signal: options.signal },
parseRegionByPuuid,
);
}
```
`riot.types.ts` 에 응답 타입 추가:
```ts
export interface RiotAccountRegionDto {
puuid: string;
game: 'lol' | string;
region: RiotPlatformRoute;
}
```
**enrichment 보정 로직**:
`RiotAccountEnrichmentService.fetchSummonerSafe` 에서 `RiotApiError && status === 404` 발생 시:
1. `getRegionByPuuid` 호출
2. 받은 platform 으로 다시 summoner 호출
3. 그래도 실패면 `failed` 처리
4. 새 platform 이 community default 와 다르면 로그(`logger.warn`) — 향후 schema 에 puuid 별 platform 저장 여부는 별도 결정
### Step 4. enrichment dedup + force/TTL 흐름 정리
**파일**: `apps/api/src/modules/riot/riot-account-enrichment.service.ts`
1. 클래스에 `private inFlight = new Map<string, Promise<EnrichResult>>()` 추가.
2. `enrichRiotAccount` 진입부에서 dedup 체크. key 는 `${userId}:${puuid}` (user 다른데 puuid 같은 케이스도 있으니 user 포함이 안전).
3. `applyMasteries` 에서 `championRecords` 채우는 코드 제거 (2.1 결정).
4. `applyLeagueEntries` 호출 직전 `tierHistory` 갱신 헬퍼 호출:
```ts
private appendTierHistoryIfChanged(
account: RiotAccount,
entries: RiotLeagueEntryDto[],
): void {
const now = new Date();
for (const e of entries) {
const last = [...account.tierHistory]
.reverse()
.find((h) => h.queueType === e.queueType);
const changed =
!last ||
last.tier !== e.tier ||
(last.rank ?? '') !== (e.rank ?? '');
if (changed) {
account.tierHistory.push({
queueType: e.queueType,
tier: e.tier,
rank: e.rank,
leaguePoints: e.leaguePoints,
wins: e.wins,
losses: e.losses,
recordedAt: now,
});
}
}
}
```
5. 위 헬퍼는 `applyLeagueEntries` 가 처음 호출되더라도 빈 history → 첫 entry push 가 자연스럽게 일어남.
### Step 5. community.platform 사용 + DakaoUserService 연결
**파일**:
- `apps/api/src/modules/dakao/dakao-user.service.ts`
- `apps/api/src/modules/dakao/handlers/match-join.handler.ts` (필요 시)
1. `resolveRiotAccount` 가 community 를 한 번 조회해서 `riotPlatform`, `riotRegion` 을 옵션으로 enrichment / Riot lookup 에 전달.
2. `RiotAccountService.getByRiotId` 에 `region` 옵션 전달 (community.riotRegion 우선, fallback `asia`).
3. enrichment 호출에도 `platform: community.riotPlatform ?? 'kr'`.
```ts
const community = await CommunityModel.findById(context.communityId)
.select({ riotPlatform: 1, riotRegion: 1 })
.lean()
.exec();
const platform = (community?.riotPlatform as RiotPlatformRoute) ?? 'kr';
const region = (community?.riotRegion as RiotRegionalRoute) ?? 'asia';
```
### Step 6. 수동 갱신 엔드포인트
**신규 파일**: `apps/api/src/modules/user/user.controller.ts` (이미 존재) 에 라우트 추가, 또는 `riot-account.controller.ts` 신설.
- 기존 `user.module.ts` / `user.controller.ts` 구조 확인 (현재 `user/user.controller.ts`, `user/user.module.ts` 존재).
- 라우트:
```ts
@Post('me/riot-accounts/:puuid/refresh')
async refreshMyRiotAccount(
@CurrentUser() me: UserDocument,
@Param('puuid') puuid: string,
@Body() body: { force?: boolean; platform?: RiotPlatformRoute },
): Promise<EnrichResult> {
if (!me) throw new UnauthorizedException();
const owns = me.riotAccounts.some((a) => a.puuid === puuid);
if (!owns) throw new ForbiddenException();
return this.enrichmentService.enrichRiotAccount({
userId: me._id,
puuid,
options: { force: body.force === true, platform: body.platform },
});
}
```
- `UserModule.imports` 에 `RiotModule` 추가 (이미 RiotModule 이 `RiotAccountEnrichmentService` export 함).
- DTO: `class-validator` 기반 `RefreshRiotAccountDto`.
### Step 7. 스케줄러
**의존성**: `pnpm --filter api add @nestjs/schedule`
**신규 파일**: `apps/api/src/modules/riot/riot-account-refresh.scheduler.ts`
```ts
@Injectable()
export class RiotAccountRefreshScheduler {
private readonly logger = new Logger(RiotAccountRefreshScheduler.name);
constructor(
private readonly connectionService: ConnectionService,
private readonly enrichment: RiotAccountEnrichmentService,
) {}
@Cron('0 4 * * *', { timeZone: 'Asia/Seoul' })
async refreshStaleAccounts() {
const UserModel = await this.connectionService.getModel('user');
const cursor = UserModel.find({
'riotAccounts.0': { $exists: true },
})
.select({ _id: 1, riotAccounts: 1, communityId: 1 })
.cursor();
let processed = 0;
for await (const user of cursor) {
for (const acc of user.riotAccounts) {
try {
await this.enrichment.enrichRiotAccount({
userId: user._id,
puuid: acc.puuid,
options: { force: false },
});
processed += 1;
if (processed % 50 === 0) {
await sleep(5000);
}
} catch (err) {
this.logger.warn(`refresh failed: ${(err as Error)?.message ?? err}`);
}
}
}
this.logger.log(`Scheduler done: processed=${processed}`);
}
}
function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
```
`RiotModule.providers` 에 추가, `app.module.ts` 에 `ScheduleModule.forRoot()` 추가.
### Step 8. projection 적용
**신규 파일**: `apps/api/src/modules/global/database/projections.ts`
```ts
export const USER_LIGHT_PROJECTION = {
'riotAccounts.championRecords': 0,
'riotAccounts.championRecordsFetchedAt': 0,
} as const;
```
**적용 지점**:
- `MatchService.list` — 매치 자체에는 RiotAccount 가 없지만 향후 populate 시 사용
- 신규 `UserService.list` 또는 `findByCommunity` 류 — projection 적용
- `/me` 핸들러 — full 데이터 유지
- `/users/:id` 단건 조회 — full 데이터 유지
대부분의 `riotAccounts.*` 가 무거워지는 시점이 mastery top 10 + tierHistory 누적이므로, 우선 list 쿼리에만 적용.
### Step 9. v4 파서 단위 테스트
**신규 파일**:
- `apps/api/src/modules/riot/riot-summoner.service.spec.ts`
- `apps/api/src/modules/riot/riot-league.service.spec.ts`
- `apps/api/src/modules/riot/riot-champion-mastery.service.spec.ts`
각 서비스에 RiotClientService mock 주입, 정상/누락 필드/배열 비정상 케이스 검증. enrichment 의 적용 단계는 기존 `riot-account-enrichment.service.spec.ts` 에서 이미 커버 중이므로, **Step 1 변경에 따라 기존 spec 의 응답 fixture 도 새 필드명으로 갱신** 필요.
### Step 10. 회귀 테스트 / 정리
1. `npx tsc --noEmit` 통과
2. `npx jest` 전체 PASS
3. seed 재실행으로 새 스키마 정상 작동 확인
4. dakao 시나리오 수동 검증:
- 신규 카카오 사용자가 `!내전 신청 ...` 으로 등록될 때 summoner v4 가 한 번 호출되고, 응답 후 user 문서에 `tiers`, `championMasteries`(10건), `tierHistory`(1건) 가 채워지는지 확인
- 같은 사용자가 즉시 재신청하면 enrichment 가 dedup 으로 단일 호출에 합쳐지는지 로그로 확인
- 한 시즌 후 tier 가 변경된 상태에서 enrichment 가 호출되면 `tierHistory` 에 새 entry 가 push 되는지 단위 테스트
---
## 4. 변경/추가 파일 목록
### 신규
- `apps/api/src/modules/global/database/projections.ts`
- `apps/api/src/modules/riot/riot-account-refresh.scheduler.ts`
- `apps/api/src/modules/riot/riot-summoner.service.spec.ts`
- `apps/api/src/modules/riot/riot-league.service.spec.ts`
- `apps/api/src/modules/riot/riot-champion-mastery.service.spec.ts`
- (옵션) `apps/api/src/modules/user/dto/refresh-riot-account.dto.ts`
### 수정
- `apps/api/src/modules/global/database/schema.ts` — TierInfo / TierHistoryEntry / ChampionMasteryEntry / Community 재정의
- `apps/api/src/modules/riot/riot.types.ts` — DTO 타입, RiotAccountRegionDto 추가
- `apps/api/src/modules/riot/riot-account.service.ts` — `getRegionByPuuid` 추가
- `apps/api/src/modules/riot/riot-champion-mastery.service.ts` — `getTopByPuuid` 로 교체
- `apps/api/src/modules/riot/riot-account-enrichment.service.ts` — 새 스키마 적용, dedup, tierHistory 누적, 404 보정
- `apps/api/src/modules/riot/riot.module.ts` — Scheduler / region service provider 등록
- `apps/api/src/modules/dakao/dakao-user.service.ts` — community platform/region 사용
- `apps/api/src/modules/user/user.controller.ts` (또는 신설) — `/me/riot-accounts/:puuid/refresh`
- `apps/api/src/modules/user/user.module.ts` — RiotModule import
- `apps/api/src/modules/match/match.service.ts` — list 쿼리 projection
- `apps/api/src/app.module.ts` — `ScheduleModule.forRoot()`
- `apps/api/src/seed.ts` — 새 mastery / tier 필드명에 맞춰 seed 데이터 수정
- `apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts` — fixture 갱신
### 의존성
- `pnpm --filter api add @nestjs/schedule`
---
## 5. 검증 체크리스트
- [ ] `pnpm --filter api exec tsc --noEmit` 통과
- [ ] `pnpm --filter api exec jest` 전체 PASS
- [ ] seed 재실행 후 user 문서 정상 (`db.user.findOne()` 으로 새 필드 확인)
- [ ] dakao `!내전 신청 <id> <기존_등록_riot_id> 미드,탑` → enrichment 캐시 hit, Riot API 호출 0회
- [ ] dakao `!내전 신청 <id> <신규_riot_id> 미드,탑` → summoner v4 1회, league v4 1회, mastery top v4 1회 호출, user 문서에 tiers/masteries/tierHistory 채워짐
- [ ] `POST /users/me/riot-accounts/:puuid/refresh { force: true }` → enrichment 수동 강제 갱신 동작
- [ ] cron 시뮬레이션 (`@Cron` 수동 트리거 또는 `node -e` 로 메서드 직접 호출) → 200건 이상 처리되어도 OOM/timeout 없이 완료
- [ ] match list API 응답 사이즈 → projection 적용으로 기존 대비 30%+ 감소 (실측)
- [ ] 동시 동일 puuid enrichment 두 번 호출 → in-flight Map 으로 1회로 합쳐짐 (단위 테스트)
---
## 6. Phase 3 으로 미루는 것 (참고)
- **분산 dedup** (Redis SET NX EX 또는 mongo 락)
- **Token bucket / Riot API rate limit** 글로벌 throttle
- **OpenSearch 인덱싱** (RiotAccount, Match 변화 로그)
- **Slack 알림** (enrichment 실패 임계 초과, scheduler 실패)
- **puuid 별 last-known platform 캐싱** (Step 3 의 보정 결과를 RiotAccount 에 영구 저장)
- **시즌 종료 시 tierHistory 의 `season` 필드 자동 채움** + peakTier 계산
- **백오피스 UI** — community.riotPlatform 설정 / 수동 갱신 트리거 / 신선도 리포트
- **NATS 기반 enrichment 분산** (현재 dakao 외 트리거가 없으므로 보류)
---
## 7. 운영 노트
- Riot personal API key 는 **개당 100req / 2분 / IP** 한도. mastery + summoner + league 가 1 user attach 당 3회. dakao 첫 신청이 폭주해도 분당 ~30명 미만이면 무탈.
- 스케줄러는 5초 간격 batch 50건 → 10분에 6000건. 대부분의 community 규모에서 충분.
- region/by-puuid 보정은 community 의 platform 이 잘못 설정된 케이스에서 운영자가 즉시 알 수 있도록 `logger.warn` 만 남김. Phase 3 에서 알림 채널로 승격.
- `championRecords` 와 `championRecordsFetchedAt` 은 비워두는 채로 schema 만 유지. mastery 와는 다른 용도(향후 매치 분석 집계)이므로 충돌 없음.
-572
View File
@@ -1,572 +0,0 @@
# 토너먼트 코드 풀 / 표시 플랜
> **대상**: codex 가 이어서 작업 가능한 수준의 실행 플랜
> **레포**: `/Users/dahyeon/source/lolympus-tournament-support` (pnpm workspace)
> **작성 기준**: 2026-04-27
---
## 1. Context
내전이 `team-built` 상태가 되면 5명씩 게임에 입장할 수 있도록 **토너먼트 코드** 1개를 매치에 발급해 표시해야 합니다.
**제약** — Riot Tournament-Stub-V5 사용 권한 없음. 우회:
1. 외부 서비스(별도 운영) 가 토너먼트 코드를 미리 수십~수백 개 생성.
2. 운영자가 그 코드를 우리 Admin UI 에 **수동 업로드** → 풀에 적재.
3. 매치가 `team-built` 으로 전환되는 순간 풀에서 atomic pop → 매치에 attach.
4. (Phase 후속) 게임 끝난 후 `match-v5` detail 의 `info.tournamentCode` 필드로 우리 코드와 매칭해 매치 결과 수집.
본 plan 은 1~3 까지. 4 는 §5.E 에 자리만.
---
## 2. 결정사항 (사용자 결정 2026-04-27)
- **적재**: 운영자 수동 업로드 → Admin UI 필수
- **카테고리**: 5v5 소환사 협곡 단일 (`mapType=SUMMONERS_RIFT`, `teamSize=5`)
- **화이트리스트**: 사용 안 함 (`allowedSummonerIds` 미지정)
- **만료**: `expiresAt` 보관 + pop 쿼리에 검사 (24h 안전 마진)
- **Tournament API**: 사용 불가. 단순 표시만.
- **결과 수집**: Phase 후속 — 일반 match-v5 응답의 `info.tournamentCode` 매칭으로 우회
- **잔여 알림**: 미구현. 운영자 수동 확인.
- **권한**: 코드 자체는 누구나 볼 수 있음. **풀 잔여 통계는 admin 만**.
- **풀 비었을 때**: placeholder 표시 + 운영자가 채우면 자동 attach
- **데이터 모델**: 별도 `TournamentCode` 컬렉션 + **`Match.tournamentCodeIds[]` 1:N join**
- **다게임 구조**: 한 내전 = N 경기 (1경기/2경기/3경기 …). `team-built` 진입 시 N개 코드 atomic 발급
- **표시 범위**: `team-built` + `in-progress` 모두 표시. `finished` 에서만 SideCard 숨김
- **코드 형식 검증**: 정규식 통과한 코드만 적재 (`/^[A-Z0-9-]{8,}$/i` 1차)
- **bulk 업로드 2모드**: 간단(textarea CSV) + 확장(JSON 붙여넣기)
---
## 3. 데이터 모델
### 3.1 TournamentCode (신규 컬렉션)
```ts
// apps/api/src/modules/global/database/schema.ts
export type TournamentCodeState =
| 'available' // 풀에 대기 중
| 'reserved' // 매치에 할당됨, 아직 게임 시작 전
| 'used' // 게임 시작/종료 — 회수 불가
| 'expired' // expiresAt 경과 (cron 으로 마킹)
| 'released'; // 매치 취소로 풀 복귀 (재할당 가능)
export interface TournamentCode extends MongooseTimestamps {
code: string; // unique, Riot 형식 (정규식 검증)
region: RiotPlatformRoute; // 기본 'kr'
mapType: 'SUMMONERS_RIFT';
teamSize: number; // 5 고정
spectatorType: 'NONE' | 'LOBBYONLY' | 'ALL';
metadata?: Record<string, unknown>; // 외부 서비스에서 받은 부가 정보
expiresAt: Date; // 운영자 입력 필수
state: TournamentCodeState;
// 할당 추적
matchId?: mongoose.Types.ObjectId; // reserved/used 시 채워짐
gameNumber?: number; // 1-based, 한 매치 안에서 몇 번째 경기인지
reservedAt?: Date;
usedAt?: Date; // 게임 시작 webhook 또는 결과 수집 시
releasedAt?: Date;
riotMatchId?: string; // 결과 수집 시 매칭된 match-v5 id (Phase 후속)
// 운영 추적
uploadedBy: mongoose.Types.ObjectId; // userId
uploadedAt: Date;
source?: string; // 외부 서비스 식별자 (옵션)
notes?: string;
}
export const TournamentCodeSchema = new Schema<TournamentCode>(
{ /* ... */ },
{ timestamps: true, collection: 'tournament_code' },
);
TournamentCodeSchema.index({ code: 1 }, { unique: true });
TournamentCodeSchema.index({ state: 1, expiresAt: 1 }); // pop 쿼리
TournamentCodeSchema.index({ matchId: 1, gameNumber: 1 }); // join lookup + 정렬
TournamentCodeSchema.index({ state: 1, uploadedAt: -1 }); // admin 목록
TournamentCodeSchema.index({ riotMatchId: 1 }, { sparse: true }); // 결과 수집 reverse lookup
```
> 모델 등록: `connection.service.ts` 의 `getModel<'tournamentCode'>` 추가.
#### 3.1.1 코드 형식 정규식 검증
`/^[A-Z0-9-]{8,}$/i` (영숫자 + 하이픈, 최소 8자). bulk 업로드/수동 추가 시 통과 못 한 코드는 응답의 `invalid` 배열에 포함, DB 적재 X. 정규식은 `tournament-code.constants.ts` 에 상수로 분리.
### 3.2 Match 확장
```ts
// schema.ts Match 추가
gameCount: number; // 한 내전의 경기 수 (default 3, community 설정에서 snapshot)
tournamentCodeIds: mongoose.Types.ObjectId[]; // gameNumber 순서 보장 (length ≤ gameCount)
// MatchSchema
gameCount: { type: Number, required: true, default: 3 },
tournamentCodeIds: {
type: [{ type: Schema.Types.ObjectId, ref: 'tournamentCode' }],
default: [],
}
```
#### 3.2.1 Community 확장 (게임 수 기본값)
```ts
// Community
matchGameCount?: number; // default 3, 매치 생성 시 snapshot
```
매치 생성 시 `match.gameCount = community.matchGameCount ?? 3`. 매치별 override 도 매치 생성 폼에서 가능.
#### 3.2.2 API 응답 구조
```ts
// /matches/:id 응답
{
...match,
tournamentCodes: [
{ gameNumber: 1, code: 'KR-...', expiresAt: '...', state: 'reserved', riotMatchId: null },
{ gameNumber: 2, code: 'KR-...', expiresAt: '...', state: 'reserved', riotMatchId: null },
{ gameNumber: 3, code: null, expiresAt: null, state: 'pending', riotMatchId: null }, // 풀 부족분
],
}
```
`gameCount` 만큼 슬롯이 항상 차 있음. 풀 부족 시 코드 자리는 `code: null, state: 'pending'` placeholder. 추후 풀 보충 시 자동 attach.
---
## 4. Lifecycle / 트리거 지점
```
upload (admin) atomic pop game start (Phase 후속)
│ │ │
[available] ─────→ [reserved] ───────────────→ [used]
│
│ match cancel / re-recruit
└──────────→ [released] ──→ [available] (재할당 가능)
[any state] ──── expiresAt < now ────→ [expired] (cron daily)
```
### 4.1 reserve (`team-built` 전환) — N개 atomic 발급
- `auction.service.ts:175` (마지막 멤버 배정), `:395` (admin 강제 전환) 두 곳에서 `match.status = 'team-built'` 직후 호출.
```ts
// TournamentCodeService.reserveForMatch(match): 부족분만 보충하는 idempotent 함수
const need = match.gameCount - match.tournamentCodeIds.length;
if (need <= 0) return;
const startGameNumber = match.tournamentCodeIds.length + 1;
const reservedIds: mongoose.Types.ObjectId[] = [];
for (let i = 0; i < need; i++) {
const code = await TournamentCodeModel.findOneAndUpdate(
{
state: 'available',
region: 'kr',
mapType: 'SUMMONERS_RIFT',
teamSize: 5,
expiresAt: { $gt: new Date(Date.now() + 24 * 60 * 60 * 1000) }, // 24h 안전 마진
},
{
$set: {
state: 'reserved',
matchId: match._id,
gameNumber: startGameNumber + i,
reservedAt: new Date(),
},
},
{ sort: { expiresAt: 1 }, new: true }, // 만료 임박순 소비
);
if (!code) break; // 풀 고갈 — 부분 발급으로 종료
reservedIds.push(code._id);
}
if (reservedIds.length > 0) {
match.tournamentCodeIds.push(...reservedIds);
await match.save();
}
```
- 각 호출이 atomic findOneAndUpdate → 두 매치가 같은 코드 받지 않음.
- 부족분만 채우는 idempotent 라 `pendingMatches` cron 에서 재호출해도 안전.
### 4.2 release (`team-built` → `recruiting` 회귀)
- `auction.service.ts:314-315` 의 회귀 흐름에서 호출.
- match cancel/삭제 시에도 호출.
```ts
// TournamentCodeService.releaseFromMatch(match)
await TournamentCodeModel.updateMany(
{ _id: { $in: match.tournamentCodeIds }, state: 'reserved' },
{ $set: { state: 'released', releasedAt: new Date() }, $unset: { matchId: 1, gameNumber: 1 } },
);
match.tournamentCodeIds = [];
await match.save();
```
`used` 상태(이미 게임 시작) 코드는 release 대상에서 제외. `released` 는 admin UI 환원 버튼에서만 `available` 로 돌아옴 (audit 보존).
### 4.3 expired 마킹 (cron)
```ts
@Cron('0 0 * * * *', { timeZone: 'Asia/Seoul' }) // 매시 정각
async markExpired() {
await TournamentCodeModel.updateMany(
{ state: { $in: ['available', 'reserved', 'released'] }, expiresAt: { $lte: new Date() } },
{ $set: { state: 'expired' } },
);
}
```
`reserved` 였는데 만료되면 → `expired`. 매치 표시는 "코드 만료됨" placeholder. (희박한 케이스 — 운영자가 매치 시작 직전 코드 안 채웠을 때만)
### 4.4 placeholder 자동 채우기 (풀 부족분 보충)
- `team-built` / `in-progress` 인 매치 중 `tournamentCodeIds.length < gameCount` 인 매치 검색 → `reserveForMatch` 재호출 (부족분만 채움).
- **트리거 두 곳**:
1. **admin 업로드 controller 안에서 직접 실행** — 즉시성 보장
2. **cron `@Cron('*/30 * * * * *')`** — 안전망 (30초 간격)
```ts
// TournamentCodeScheduler.attachPending
const pendingMatches = await MatchModel.find({
status: { $in: ['team-built', 'in-progress'] },
$expr: { $lt: [{ $size: '$tournamentCodeIds' }, '$gameCount'] },
});
for (const match of pendingMatches) await codeService.reserveForMatch(match);
```
---
## 5. 변경 사항
### 5.1 백엔드
#### 신규 모듈 `apps/api/src/modules/tournament-code/`
```
tournament-code.module.ts
tournament-code.service.ts # reserveForMatch / releaseFromMatch / markExpired / bulkUpload / list / delete
tournament-code.controller.ts # admin endpoints
tournament-code.scheduler.ts # 만료 cron + 자동 attach cron
tournament-code.types.ts
```
#### 엔드포인트
| Method | Path | 권한 | 용도 |
|---|---|---|---|
| POST | `/communities/:cid/tournament-codes` | `@Roles('owner','admin')` | bulk 업로드 |
| GET | `/communities/:cid/tournament-codes` | `@Roles('owner','admin')` | 목록 (state/expiresAt 필터) |
| GET | `/communities/:cid/tournament-codes/stats` | `@Roles('owner','admin')` | 풀 잔여 통계 (state 별 카운트 + 만료 임박 카운트) |
| DELETE | `/communities/:cid/tournament-codes/:id` | `@Roles('owner','admin')` | 폐기 (state=available 만) |
| POST | `/communities/:cid/tournament-codes/:id/release` | `@Roles('owner','admin')` | reserved/released → available 수동 환원 |
bulk 업로드 body:
```ts
interface BulkUploadRequest {
codes: Array<{
code: string; // 공백 trim
expiresAt: string; // ISO
spectatorType?: 'NONE' | 'LOBBYONLY' | 'ALL'; // 기본 'ALL'
metadata?: Record<string, unknown>;
source?: string;
notes?: string;
}>;
}
```
응답:
```ts
interface BulkUploadResponse {
inserted: number;
duplicates: string[]; // 이미 존재하는 code (skipped)
invalid: Array<{ code: string; reason: string }>;
}
```
#### 매치 응답에 join
`match.service.ts` 의 `serializeMatch` (또는 mapper) 에서 `tournamentCodeIds` 를 `populate` 또는 `$lookup` 으로 풀어 `gameNumber` 정렬 + 부족분은 placeholder 슬롯으로 채워서 응답:
```ts
function buildTournamentCodeSlots(
match: Match,
codes: TournamentCode[],
): TournamentCodeSlotView[] {
const byNumber = new Map(codes.map((c) => [c.gameNumber!, c]));
return Array.from({ length: match.gameCount }, (_, i) => {
const gameNumber = i + 1;
const code = byNumber.get(gameNumber);
return code
? {
gameNumber,
code: code.code,
expiresAt: code.expiresAt.toISOString(),
state: code.state, // 'reserved' | 'used' | 'expired'
riotMatchId: code.riotMatchId ?? null,
}
: { gameNumber, code: null, expiresAt: null, state: 'pending', riotMatchId: null };
});
}
```
#### auction.service 통합
- `:175`, `:395` 직후 `tournamentCodeService.reserveForMatch(match)` 호출.
- `:314-315` 직전 `tournamentCodeService.releaseFromMatch(match)` 호출.
### 5.2 프런트
#### 매치 상세 우측 SideCard 추가
`apps/web/src/pages/MatchDetailPage.tsx` `611~654` 일정/상품/안내사항 SideCard 들 아래에:
```tsx
{match.status !== 'finished' &&
(match.status === 'team-built' || match.status === 'in-progress') && (
<SideCard title="토너먼트 코드">
<TournamentCodeList slots={match.tournamentCodes} />
{isAdmin && <PoolStatsHint />} {/* §8.5 운영자에게만 잔여 표시 */}
</SideCard>
)}
```
`TournamentCodeList` 컴포넌트 — 1경기 / 2경기 / 3경기 식 row:
```tsx
function TournamentCodeList({ slots }: { slots: TournamentCodeSlotView[] }) {
return (
<div className="space-y-2">
{slots.map((slot) => (
<TournamentCodeRow key={slot.gameNumber} slot={slot} />
))}
</div>
);
}
function TournamentCodeRow({ slot }: { slot: TournamentCodeSlotView }) {
return (
<div className="flex items-center gap-2">
<span className="text-[11px] font-bold text-base-content/40 w-12 shrink-0">
{slot.gameNumber}경기
</span>
{slot.code ? (
<TournamentCodeDisplay slot={slot} />
) : (
<span className="text-[11px] text-base-content/30">발급 대기 중…</span>
)}
</div>
);
}
```
`TournamentCodeDisplay`:
- 모노스페이스 코드 + 카피 버튼 (clipboard) + 카피 토스트 ("복사했어요. 게임 클라이언트의 토너먼트 코드 입력란에 붙여 넣으세요")
- 만료 시각 ("만료: 4월 30일 18:00")
- 만료 24h 이내면 amber 경고
- `state === 'expired'` → "코드 만료. 운영자에게 문의해 주세요."
- `state === 'used'` → 회색 + "사용됨" 라벨 (다음 경기 코드만 강조)
- `riotMatchId` 있으면 hover 시 매치 ID 툴팁 (Phase 후속 결과 수집 후)
#### types.ts
```ts
export type TournamentCodeSlotState = 'reserved' | 'used' | 'expired' | 'pending';
export interface TournamentCodeSlotView {
gameNumber: number;
code: string | null;
expiresAt: string | null;
state: TournamentCodeSlotState;
riotMatchId: string | null;
}
export interface ApiMatch {
// ...
gameCount: number;
tournamentCodes: TournamentCodeSlotView[]; // 항상 length === gameCount
}
```
#### Admin 페이지 신규
`apps/web/src/pages/admin/TournamentCodesPage.tsx`:
- 라우트: `/admin/communities/:cid/tournament-codes`
- 권한 가드: `useMe` 의 `currentUser.role === 'owner' | 'admin'` 아니면 redirect
- 섹션:
1. **잔여 현황 카드**: state 별 카운트 (available / reserved / used / expired) + 만료 임박 7일 이내 카운트
2. **bulk 업로드 — 2모드 탭**:
- **간단**: textarea, 줄당 `code,expiresAt(ISO)` (CSV 1줄). 예: `KR-ABCD-1234,2026-05-30T18:00:00Z`
- **확장**: JSON 붙여넣기 (`{spectatorType, metadata, source, notes}` 추가 가능)
- 정규식 통과한 코드만 적재, invalid/duplicate 결과 응답 표시
3. **목록 테이블**: state 필터 / expiresAt 정렬 / 매치 ID 링크 (`gameNumber` 함께) / 폐기·환원 버튼
- 폴링: React Query `refetchInterval: 30s`
#### SideCard 안의 운영자 잔여 안내 (§8.5)
`PoolStatsHint` 컴포넌트:
- `useMe` 로 admin/owner 판별
- 별도 호출 `GET /communities/:cid/tournament-codes/stats` (다음 §)
- 표시: "풀 잔여 12개 (만료 임박 3개)" — 5개 미만이면 빨강
- admin 페이지로 가는 inline link
#### 매치 상세 클릭 트리거 — 변경 없음
기본 `MatchDetailPage` 안에서 자동 표시. 외부 공유 OK 정책 그대로.
### 5.3 매치 cancel/삭제 시 release
- `match.service.ts` 의 매치 삭제/취소 흐름에 `releaseFromMatch` 호출.
- match status 가 `team-built` → `in-progress` 로 전환되면 **코드 자체는 그대로 reserved 유지**. 게임이 끝나는 시점(Phase 후속 결과 수집)에 `reserved → used` 전환.
- `in-progress` 상태에서도 SideCard 표시 유지 (다음 경기 코드 보여주기 위함).
---
## 6. 결과 수집 우회 (Phase 후속 — 본 plan 자리만)
토너먼트 API 못 쓰니까 게임이 끝났는지 알 방법이 없습니다. **`match-v5 by-puuid` 의 `type=tourney` 필터** 를 활용해 호출량/정확도를 끌어올리는 우회 흐름:
### 6.1 호출 패턴 — `type=tourney` + `startTime` window
```
GET /lol/match/v5/matches/by-puuid/{puuid}/ids
?type=tourney
&startTime={teamBuiltAtEpochSeconds - 60} // 안전 마진 60초
&endTime={now}
&start=0
&count=100
```
- `type=tourney` 로 **토너먼트 코드로 만들어진 매치만** 필터 → 일반/랭크 매치 제외, payload·detail call 모두 절감.
- `startTime` = 매치가 `team-built` 으로 전환된 epoch seconds (안전 마진 60초). `Match.teamBuiltAt: Date` 신규 필드 필요.
- `endTime` = 폴링 시점.
- `start/count` 페이지네이션은 1차 100 으로 충분 (BO3/BO5 라도 한 매치는 최대 5게임).
- `RiotMatchService.getMatchIdsByPuuid` 가 이미 `type: 'tourney'` 를 지원함 (`riot.types.ts:29`, `riot-match.service.ts:21~26`) — 신규 클라이언트 코드 불필요.
### 6.2 매핑 흐름
1. 매치가 `team-built` 으로 전환되는 시점에 `Match.teamBuiltAt = now` snapshot.
2. **결과 수집 작업 큐** (선행 plan 의 Riot 작업 큐 high stream 재사용) 에 `riot.tournament-result.poll.match` job enqueue. payload: `{matchId, puuids: [캡틴 2명], teamBuiltAtEpoch}`.
3. worker:
```ts
for (const puuid of puuids) {
const ids = await matchService.getMatchIdsByPuuid(puuid, {
type: 'tourney',
startTime: teamBuiltAtEpoch - 60,
count: 100,
region: 'asia',
});
for (const matchV5Id of ids) {
const detail = await matchService.getMatch(matchV5Id);
const tCode = detail.info.tournamentCode;
if (!tCode) continue;
const code = await TournamentCodeModel.findOneAndUpdate(
{ code: tCode, matchId: match._id, state: 'reserved' },
{ $set: { state: 'used', usedAt: new Date(detail.info.gameCreation), riotMatchId: matchV5Id } },
{ new: true },
);
if (code) await maybeAdvanceMatch(match); // 모든 슬롯 used 면 finished 전환
}
}
```
4. **재폴링 정책**: 결과를 모두 못 찾았으면 5분 후 재 enqueue (예: 첫 polling 후 1시간 동안 5분 간격 재시도, 그 후 1시간 간격으로 24시간까지). 24h 내 못 찾으면 `state = 'expired'` 마킹 + 운영자 알림 자리.
5. **dedup**: 매치당 jobId 단일 (`riot:tourney-poll:dedup:<matchId>` Garnet NX). 한 매치는 한 polling 체인.
### 6.3 finished 전환
```ts
async function maybeAdvanceMatch(match: Match) {
const codes = await TournamentCodeModel.find({ matchId: match._id }).sort({ gameNumber: 1 });
if (codes.length < match.gameCount) return;
if (!codes.every((c) => c.state === 'used' && c.riotMatchId)) return;
match.status = 'finished';
match.result = match.result ?? defaultResult();
match.result.riotMatchIds = codes.map((c) => c.riotMatchId!);
// 승패/스코어는 별도 결과 집계 단계 (이번 PR 범위 외)
await match.save();
}
```
### 6.4 본 plan 에서 미리 준비할 것
- `Match.teamBuiltAt: Date` 필드 추가 (PR-1 에서 같이) — 결과 수집 시 `startTime` 으로 사용.
- `TournamentCode.riotMatchId` 필드 + sparse 인덱스 (이미 §3.1).
- `gameNumber` 로 어느 경기 결과인지 매핑 가능 (운영자가 코드를 1경기/2경기 순서대로 발급한 가정).
- `RiotMatchService.getMatchIdsByPuuid` 의 `type: 'tourney'` 지원 확인 완료.
### 6.5 폴링 대상 puuid 선택
- 기본: **양 팀 캡틴 puuid 2명만** 폴링 → 최소 호출.
- 캡틴이 게임에 입장 안 한 케이스 (드물지만 가능) 대비: 24h 안에 결과 못 찾으면 **모든 참가자 puuid** (10명) 로 확장 retry.
- 한 매치당 최악 호출량: 2 puuid × 100ids list + 매치당 detail call 5게임 = ~12 calls. 매치 1개 finished 까지 ≤ 24h.
### 6.6 결과 수집 모듈 자체는 별도 PR (`Tournament-Result-수집-플랜.md` 후속).
---
## 7. Rollout
1. (PR-1) `TournamentCode` 컬렉션 + Match `gameCount`/`tournamentCodeIds[]`/`teamBuiltAt` + Community `matchGameCount` + 모델 등록 + 인덱스 (riotMatchId sparse 포함)
2. (PR-2) `TournamentCodeService.reserveForMatch (idempotent N개 발급) / releaseFromMatch / bulkUpload (정규식 검증) / list / stats` + 단위 테스트 (atomic pop concurrency, 부분 발급, 정규식 reject)
3. (PR-3) auction.service 통합 (reserve/release 두 트리거) + 매치 생성 시 `gameCount` snapshot + `team-built` 전환 시 `teamBuiltAt` snapshot
4. (PR-4) 매치 응답에 `tournamentCodes[]` slot 빌더 + types 확장 (gameCount + slot view)
5. (PR-5) `TournamentCodeScheduler` (만료 cron 매시 + 부족분 자동 attach cron 30초)
6. (PR-6) 매치 상세 SideCard — `TournamentCodeList` (1경기/2경기/3경기 row) + 카피 토스트 + 만료 경고. status guard: `team-built` ∪ `in-progress`
7. (PR-7) Admin 페이지 `TournamentCodesPage` — 잔여 현황 + 2모드 bulk 업로드 + 목록 + 환원/폐기
8. (PR-8) SideCard `PoolStatsHint` (admin/owner 만 표시, /stats 엔드포인트 호출)
9. (PR-9) 매치 cancel/삭제 흐름에 release 통합
10. (Phase 후속) 결과 수집 폴링 모듈 (`info.tournamentCode` 매칭)
---
## 8. 추가 고려사항
### 확정 (사용자 결정 2026-04-27)
본 plan §2 의 모든 결정사항. 추가 항목:
1. **정규식 검증** (`/^[A-Z0-9-]{8,}$/i`) — bulk 업로드 시 invalid 응답에 포함, DB 적재 X.
2. **만료 안전 마진 24h** — pop 쿼리에 `expiresAt > now + 24h`. admin 페이지에서 임박 코드 amber 표시.
3. **bulk 업로드 2모드** — 간단(textarea CSV) + 확장(JSON 붙여넣기).
4. **표시 범위**: `team-built` + `in-progress` 모두 표시 (1경기/2경기/3경기 식). `finished` 에서만 사라짐.
5. **풀 잔여 통계**: admin/owner 에게만 SideCard 안에 inline 표시 + admin 페이지 카드.
6. **자동 attach 트리거**: admin 업로드 controller 안 + cron 30초 둘 다.
7. **재할당 audit**: `released → available` 은 admin 환원 버튼만. 자동 환원 cron 두지 않음.
8. **카피 토스트**: 코드 카피 시 "복사했어요. 게임 클라이언트의 토너먼트 코드 입력란에 붙여 넣으세요".
### 추후 (Phase 후속)
- 결과 수집 폴링 모듈 (§6) — `info.tournamentCode` 매칭으로 `riotMatchId` 채움 + `state=used`
- 잔여 알림 (dakao bot 또는 discord webhook)
- 풀 자동 보충 (외부 서비스 webhook / API key 인증)
- 토너먼트 API 권한 받으면 본 plan 의 풀 메커니즘은 그대로 두고 코드 생성 자동화만 추가
---
## 9. Done 정의
- `TournamentCode` 컬렉션 생성 + 인덱스 5개 등록 (riotMatchId sparse 포함)
- `Match.gameCount` + `Match.tournamentCodeIds[]` 추가, `Community.matchGameCount` 자리
- 운영자가 admin 페이지에서 2모드 (CSV/JSON) bulk 업로드, 정규식 통과한 코드만 적재
- 매치가 `team-built` 으로 전환 → 매치에 `gameCount` 만큼 코드 atomic N개 발급 (만료 임박순, gameNumber 1..N), 동시 두 매치 같은 코드 받지 않음
- 풀 부족 시 부분 발급 → 부족 슬롯은 `state: 'pending'` placeholder 로 응답
- `team-built` → `recruiting` 회귀 시 reserved 코드 모두 release → admin 환원 버튼으로 available 로 복귀
- MatchDetailPage 우측 SideCard 에 `team-built` ∪ `in-progress` 일 때 1경기/2경기/3경기 row 표시. `finished` 에서 사라짐
- admin/owner 에게는 SideCard 안에 풀 잔여 inline 표시 ("풀 잔여 12개 (만료 임박 3개)")
- 풀이 비었던 슬롯은 admin 이 새 코드 업로드하면 30초 안에 자동 attach
- 만료 임박 24h 이내 코드는 pop 쿼리에서 제외, admin 페이지 amber
- 만료된 코드는 매시 cron 으로 state=expired 마킹
- 매치 응답 (`/matches/:id`) 에 `tournamentCodes: TournamentCodeSlotView[]` (length === gameCount) 포함
- `match-v5` 응답의 `info.tournamentCode` 파싱이 이미 가능함을 확인 + `TournamentCode.riotMatchId` 필드/인덱스 자리 마련 + `Match.teamBuiltAt` 자리 마련 (Phase 후속 결과 수집의 `startTime` 으로 사용)
- `RiotMatchService.getMatchIdsByPuuid` 가 `type: 'tourney'` 지원 확인됨 (Phase 후속에서 그대로 호출)
- 단위 테스트 통과 (atomic N개 pop / 부분 발급 / 정규식 reject / 만료 필터 / release / bulk 중복 skip)
-470
View File
@@ -1,470 +0,0 @@
# 토너먼트 결과 수집 (우회) 플랜
> **대상**: 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<typeof p> => 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 통과)
+101 -2
View File
@@ -27,8 +27,8 @@
## Riot Background Refresh
Set `RIOT_BG_REFRESH_ENABLED=true` to refresh stale Riot accounts automatically
between KST 03:00 and 10:00. The scheduler picks active users whose
Stale Riot accounts refresh automatically between KST 03:00 and 10:00.
The scheduler picks active users whose
`lastRefreshRequestedAt` is older than 6 hours, oldest first, and uses a
background-only Riot token bucket capped at roughly 40% of the app rate limit.
@@ -62,6 +62,105 @@ $ pnpm run test:e2e
# test coverage
$ pnpm run test:cov
# auction cancellation/undo transactions against a real local MongoDB replica set
$ pnpm run test:mongodb
```
`test:mongodb` requires `mongod` on PATH, or `MONGODB_TEST_SERVER` set to its
executable path. The runner starts an isolated replica set on a random loopback
port, uses a temporary database directory, and removes it after the tests. It
does not use the application's database connection settings.
## Temporary auction role selection
Until captain accounts are issued, bids use the team selected in the auction UI.
By default, both WebSocket and HTTP bids accept guests and signed-in users without
checking whether the user is that team's captain. Team existence, bid amounts,
remaining points, roster limits, deadlines and round consistency are still checked.
Bid history continues to identify the selected team's captain, so it is not proof
of the account that submitted a bid in this temporary mode.
After issuing accounts, set `AUCTION_REQUIRE_CAPTAIN_AUTH=true` in the API
environment (or `project.env`) and restart the API to require a signed-in captain
for the selected team on all bid paths. Unset or `false` keeps temporary mode.
## Auction durability
Accepted Redis bids now enter `auction:bidArchivePayloads` and
`auction:bidArchiveQueue` atomically with the bid. The durability scheduler saves
them to `auctionBidRecords` using deterministic IDs before removing queue entries.
Recent state snapshots remain capped at 1000 bids; the archive is not capped and
retains accepted bids across undo/cancellation for audit. These records begin with
this deployment; bids already discarded by an older version cannot be recovered.
`GET /communities/:communityId/matches/:matchId/auction/bids/history` pages through
the current lifecycle's persisted archive using `afterRevision` and `limit` (1–200).
Persistence is asynchronous, so an empty last page may gain entries afterward.
Invalid archive entries are moved atomically to `auction:bidArchiveDeadLetterQueue`
and `auction:bidArchiveDeadLetterPayloads`. The payload stores the original text
(or `null` for a missing payload), error, ID, and quarantine time. Monitor these
keys and review quarantined data before repairing/requeuing it; it is not retried
automatically or expired. Other bids continue to persist. Mongo write failures
leave valid entries in the pending queue for idempotent retries.
Older in-flight rounds can produce `bidRoundId: ''`; the archive treats this as
an absent optional round ID. Empty player IDs and other invalid field types
remain validation errors.
Cancellation commits its completion marker and pending cleanup fields in Match.
The scheduler retries cleanup after restarts, with a delay capped at 60 seconds.
Reset notifications include the lifecycle to protect a newly started auction.
Dead-letter status notifications use `auction:deadLetterStatusQueue`; failures to
persist or mirror the terminal status are retried without rerunning the side effect.
Older side-effect dead letters are also reconciled automatically.
Before deploying the cleanup worker, create its partial Match index using the
additive, repeatable migration below. Schema declarations alone do not create
indexes when `MONGODB_AUTO_INDEX` is disabled (the default). Choose the target
environment explicitly; dry-run does not create indexes or modify documents.
```bash
pnpm --filter api auction:indexes -- --env staging --dry-run
pnpm --filter api auction:indexes -- --env staging --apply
# Use --env prod for production.
```
The index is `{ auctionCancellationCleanupRetryAt: 1 }`, restricted to
`{ auctionCancellationCleanupPending: true }`. The worker only reads due pending
entries; it no longer scans legacy cancellation markers without a pending flag.
## Riot archive recovery
Newly saved or repaired Riot match data refreshes affected internal match
statistics at the same Competition revision. Existing archives and duplicate
imports do not trigger recovery. Recovery failures are logged and do not block
result collection or match refresh. Only communities with recovered statistics
have their caches invalidated, once per recovery batch; one failed rebuild does
not prevent other successful rebuilds from being reflected. Detail
requests also check for newly archived data when a cached game is missing raw
data. An absent archive does not trigger a rebuild or a Riot match fetch. If a
detail rebuild makes no progress, the process waits 60 seconds before retrying
that source revision and does not invalidate the community cache.
Recovery cache invalidations first try Redis with a one-second command timeout.
On failure they return immediately and schedule up to three in-process retries,
waiting 1, 5, then 30 seconds between attempts. A community has one retry budget;
additional immediate failures do not reset it, and a successful current request
cancels the pending retry. Timers are unreferenced and cleared on shutdown.
Retries are not persisted or resumed after a restart. Detail requests detect
newly archived raw data even behind a stale cache, and other response caches
expire after five minutes. A detail response whose immediate invalidation fails
is returned without being cached. No Mongo invalidation collection or periodic
queue scan is used.
Before deploying this recovery path, add its Riot ID lookup index. The migration
defaults to dry-run and leaves other indexes and game records unchanged.
```bash
pnpm --filter api stats:indexes -- --env staging --dry-run
pnpm --filter api stats:indexes -- --env staging --apply
# Use --env prod for production.
```
## Deployment
+24 -2
View File
@@ -1,10 +1,11 @@
// @ts-check
import eslint from '@eslint/js';
import { defineConfig } from 'eslint/config';
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
import globals from 'globals';
import tseslint from 'typescript-eslint';
export default tseslint.config(
export default defineConfig(
{
ignores: ['eslint.config.mjs'],
},
@@ -29,7 +30,28 @@ export default tseslint.config(
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-floating-promises': 'warn',
'@typescript-eslint/no-unsafe-argument': 'warn',
"prettier/prettier": ["error", { endOfLine: "auto" }],
'prettier/prettier': ['error', { endOfLine: 'auto' }],
},
},
{
files: ['**/*.spec.ts', 'test/**/*.ts'],
rules: {
'@typescript-eslint/no-unsafe-assignment': 'off',
'@typescript-eslint/no-unsafe-call': 'off',
'@typescript-eslint/no-unsafe-member-access': 'off',
'@typescript-eslint/no-unsafe-return': 'off',
'@typescript-eslint/no-this-alias': 'off',
'@typescript-eslint/require-await': 'off',
'@typescript-eslint/unbound-method': 'off',
},
},
{
files: ['src/modules/global/database/migrations/**/*.ts'],
rules: {
'@typescript-eslint/no-unsafe-assignment': 'off',
'@typescript-eslint/no-unsafe-call': 'off',
'@typescript-eslint/no-unsafe-member-access': 'off',
'@typescript-eslint/no-unsafe-return': 'off',
},
},
);
+69
View File
@@ -0,0 +1,69 @@
'use strict';
function readBoolean(name, defaultValue) {
const value = process.env[name];
if (value == null || value === '') return defaultValue;
return !['0', 'false', 'f', 'no', 'n', 'disabled'].includes(
value.toLowerCase(),
);
}
function readInteger(name, defaultValue) {
const rawValue = process.env[name]?.trim();
if (!rawValue) return defaultValue;
if (/^\d+$/.test(rawValue)) {
return Number.parseInt(rawValue, 10);
}
process.env[name] = String(defaultValue);
return defaultValue;
}
const hasLicenseKey = Boolean(process.env.NEW_RELIC_LICENSE_KEY);
exports.config = {
app_name: [process.env.NEW_RELIC_APP_NAME || 'lolympus'],
license_key: process.env.NEW_RELIC_LICENSE_KEY || '',
agent_enabled: readBoolean('NEW_RELIC_ENABLED', hasLicenseKey),
distributed_tracing: {
enabled: true,
},
ai_monitoring: {
enabled: readBoolean('NEW_RELIC_AI_MONITORING_ENABLED', true),
},
custom_insights_events: {
max_samples_stored: readInteger(
'NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED',
100000,
),
},
span_events: {
max_samples_stored: readInteger(
'NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED',
10000,
),
},
logging: {
level: process.env.NEW_RELIC_LOG_LEVEL || 'info',
},
instrumentation: {
timers: {
enabled: false,
},
},
allow_all_headers: false,
attributes: {
exclude: [
'request.headers.cookie',
'request.headers.authorization',
'request.headers.proxyAuthorization',
'request.headers.setCookie*',
'response.headers.cookie',
'response.headers.authorization',
'response.headers.proxyAuthorization',
'response.headers.setCookie*',
],
},
};
+28 -16
View File
@@ -8,35 +8,48 @@
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"competition:migrate": "ts-node src/modules/global/database/migrations/run-competition-domain.ts",
"competition:repair-grand-final": "ts-node src/modules/global/database/migrations/repair-grand-final-bo3.ts",
"auction:indexes": "ts-node src/modules/global/database/migrations/run-auction-cancellation-index.ts",
"stats:indexes": "ts-node src/modules/global/database/migrations/run-match-stats-raw-index.ts",
"seed:dev": "ts-node src/seed.ts",
"seed:dakao-participant": "ts-node src/seed-dakao-participant.ts",
"start:dev": "node -e \"process.env.NODE_ENV='dev'; require('./dist/main.js')\"",
"start:test": "node -e \"process.env.NODE_ENV='test'; require('./dist/main.js')\"",
"start:prod": "node -e \"process.env.NODE_ENV='prod'; require('./dist/main.js')\"",
"start:dev": "NODE_ENV=dev NEW_RELIC_HOME=. node --import newrelic/esm-loader.mjs -r newrelic dist/main.js",
"start:staging": "NODE_ENV=staging NEW_RELIC_HOME=. node --import newrelic/esm-loader.mjs -r newrelic dist/main.js",
"start:prod": "NODE_ENV=prod NEW_RELIC_HOME=. node --import newrelic/esm-loader.mjs -r newrelic dist/main.js",
"pm2:dev": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:dev",
"pm2:test": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:test",
"pm2:staging": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:staging",
"pm2:prod": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:prod",
"perf:report": "ts-node src/scripts/api-performance-report.ts",
"perf:routes": "ts-node src/scripts/api-performance-report.ts --routes-only",
"start:debug": "nest start --debug --watch",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"typecheck": "tsc --noEmit --incremental false",
"test:redis": "node test/run-redis-tests.mjs",
"test:mongodb": "node test/run-mongo-tests.mjs",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/common": "^11.0.1",
"@lolympus/contracts": "workspace:*",
"@nats-io/jetstream": "^3.4.0",
"@nats-io/transport-node": "^3.4.0",
"@nestjs/common": "^11.1.28",
"@nestjs/config": "^4.0.4",
"@nestjs/core": "^11.0.1",
"@nestjs/platform-express": "^11.0.1",
"@nestjs/platform-socket.io": "^11.1.19",
"@nestjs/swagger": "^11.2.7",
"@nestjs/websockets": "^11.1.19",
"@nestjs/core": "^11.1.28",
"@nestjs/platform-express": "^11.1.28",
"@nestjs/platform-socket.io": "^11.1.28",
"@nestjs/swagger": "^11.4.8",
"@nestjs/websockets": "^11.1.28",
"@socket.io/redis-adapter": "^8.3.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.15.1",
"jose": "^6.2.2",
"mongoose": "^9.4.1",
"nats": "^2.29.3",
"mongoose": "9.12.1",
"newrelic": "^14.3.3",
"redis": "^5.12.1",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
@@ -44,16 +57,15 @@
"temporal-polyfill": "^0.3.2"
},
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
"@eslint/js": "^9.18.0",
"@eslint/js": "^10.0.1",
"@nestjs/cli": "^11.0.0",
"@nestjs/schematics": "^11.0.0",
"@nestjs/testing": "^11.0.1",
"@types/express": "^5.0.0",
"@types/jest": "^30.0.0",
"@types/node": "^24.0.0",
"@types/node": "^26.1.1",
"@types/supertest": "^7.0.0",
"eslint": "^9.18.0",
"eslint": "^10.14.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.2.2",
"globals": "^17.0.0",
+11 -1
View File
@@ -1,11 +1,14 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ApiPerformanceInterceptor } from './modules/global/observability/api-performance.interceptor';
import { AuctionModule } from './modules/auction/auction.module';
import { AuthModule } from './modules/auth/auth.module';
import { CommunityModule } from './modules/community/community.module';
import { CommunityStatsModule } from './modules/community-stats/community-stats.module';
import { CompetitionModule } from './modules/competition/competition.module';
import { DakaoModule } from './modules/dakao/dakao.module';
import { GlobalModule } from './modules/global/global.module';
import { LegacyImportModule } from './modules/legacy-import/legacy-import.module';
@@ -29,6 +32,7 @@ import { UserModule } from './modules/user/user.module';
BackgroundRefreshModule,
CommunityModule,
CommunityStatsModule,
CompetitionModule,
MatchModule,
MatchHistoryModule,
LegacyImportModule,
@@ -39,6 +43,12 @@ import { UserModule } from './modules/user/user.module';
DakaoModule,
],
controllers: [AppController],
providers: [AppService],
providers: [
AppService,
{
provide: APP_INTERCEPTOR,
useClass: ApiPerformanceInterceptor,
},
],
})
export class AppModule {}
+67
View File
@@ -0,0 +1,67 @@
import {
createCorsOrigin,
isAllowedCorsOrigin,
resolveWebOrigins,
} from './cors-origin';
describe('CORS origin resolution', () => {
it('allows Cloudflare Pages preview origins in dev and staging', () => {
const origin = 'https://807e0ea6.lolympus.pages.dev';
expect(isAllowedCorsOrigin(origin, 'dev')).toBe(true);
expect(isAllowedCorsOrigin(origin, 'staging')).toBe(true);
});
it('does not allow Cloudflare Pages preview origins in prod', () => {
expect(
isAllowedCorsOrigin('https://807e0ea6.lolympus.pages.dev', 'prod'),
).toBe(false);
});
it('rejects similar but unsafe Pages origins', () => {
expect(
isAllowedCorsOrigin('http://807e0ea6.lolympus.pages.dev', 'staging'),
).toBe(false);
expect(isAllowedCorsOrigin('https://lolympus.pages.dev', 'staging')).toBe(
false,
);
expect(
isAllowedCorsOrigin('https://a.b.lolympus.pages.dev', 'staging'),
).toBe(false);
expect(
isAllowedCorsOrigin(
'https://807e0ea6.lolympus.pages.dev.evil.com',
'staging',
),
).toBe(false);
});
it('keeps configured web origins allowed', () => {
expect(
isAllowedCorsOrigin('https://example.com', 'prod', [
'https://example.com',
]),
).toBe(true);
});
it('falls back to default web origins when WEB_ORIGIN is empty', () => {
expect(resolveWebOrigins('')).toContain('http://localhost:5173');
});
it('creates a Nest CORS callback from the same rules', (done) => {
const corsOrigin = createCorsOrigin('staging');
expect(corsOrigin).not.toBe(true);
if (corsOrigin === true) return;
corsOrigin('https://807e0ea6.lolympus.pages.dev', (error, allow) => {
expect(error).toBeNull();
expect(allow).toBe(true);
done();
});
});
it('keeps dev CORS permissive for local development', () => {
expect(createCorsOrigin('dev')).toBe(true);
});
});
+101
View File
@@ -0,0 +1,101 @@
import type { CustomOrigin } from '@nestjs/common/interfaces/external/cors-options.interface';
const DEFAULT_WEB_ORIGINS = [
'http://localhost:5173',
'http://126.dahyeon.us:5173',
'https://lolympus.dahyeon.us',
];
const PAGES_DEV_ORIGIN_HOST_PATTERN =
/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.lolympus\.pages\.dev$/i;
const PAGES_DEV_CORS_ENVIRONMENTS = new Set(['dev', 'staging']);
function parseOrigin(origin: string, allowPath: boolean): URL | null {
const trimmedOrigin = origin.trim();
if (trimmedOrigin.length === 0) return null;
try {
const url = new URL(trimmedOrigin);
if (
!allowPath &&
(url.pathname !== '/' || url.search !== '' || url.hash !== '')
) {
return null;
}
return url;
} catch {
return null;
}
}
function normalizeOrigin(origin: string, allowPath = false): string | null {
const url = parseOrigin(origin, allowPath);
if (!url) return null;
return `${url.protocol}//${url.host}`;
}
export function resolveWebOrigins(
webOrigin = process.env.WEB_ORIGIN,
): string[] {
const configuredOrigins = webOrigin
?.split(',')
.map((origin) => normalizeOrigin(origin, true))
.filter((origin): origin is string => origin !== null);
if (configuredOrigins && configuredOrigins.length > 0) {
return configuredOrigins;
}
return [...DEFAULT_WEB_ORIGINS];
}
export function isLolympusPagesDevOrigin(origin: string): boolean {
const url = parseOrigin(origin, false);
if (!url) return false;
return (
url.protocol === 'https:' &&
url.port === '' &&
PAGES_DEV_ORIGIN_HOST_PATTERN.test(url.hostname)
);
}
export function isAllowedCorsOrigin(
requestOrigin: string | undefined,
nodeEnv = process.env.NODE_ENV,
webOrigins = resolveWebOrigins(),
): boolean {
if (!requestOrigin) return false;
const normalizedRequestOrigin = normalizeOrigin(requestOrigin);
if (!normalizedRequestOrigin) return false;
const normalizedWebOrigins = webOrigins
.map((origin) => normalizeOrigin(origin, true))
.filter((origin): origin is string => origin !== null);
if (normalizedWebOrigins.includes(normalizedRequestOrigin)) {
return true;
}
return (
PAGES_DEV_CORS_ENVIRONMENTS.has(nodeEnv ?? '') &&
isLolympusPagesDevOrigin(requestOrigin)
);
}
export function createCorsOrigin(
nodeEnv = process.env.NODE_ENV,
webOrigin = process.env.WEB_ORIGIN,
): true | CustomOrigin {
if (nodeEnv === 'dev') return true;
const webOrigins = resolveWebOrigins(webOrigin);
return (requestOrigin, callback) => {
callback(null, isAllowedCorsOrigin(requestOrigin, nodeEnv, webOrigins));
};
}
+17 -11
View File
@@ -1,25 +1,31 @@
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { createCorsOrigin } from './cors-origin';
import { RedisIoAdapter } from './redis-io.adapter';
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
rawBody: true,
});
const isDev = process.env.NODE_ENV === 'dev';
const webOrigins = process.env.WEB_ORIGIN?.split(',').map((origin) =>
origin.trim(),
) ?? [
'http://localhost:5173',
'http://126.dahyeon.us:5173',
'https://lolympus.dahyeon.us',
];
const nodeEnv = process.env.NODE_ENV;
const isDev = nodeEnv === 'dev';
const redisIoAdapter = new RedisIoAdapter(app);
await redisIoAdapter.connectToRedis();
app.useWebSocketAdapter(redisIoAdapter);
app.enableCors({
origin: isDev ? true : webOrigins,
origin: createCorsOrigin(nodeEnv),
credentials: true,
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
allowedHeaders: [
'Authorization',
'Content-Type',
'X-Auth-User-Id',
'If-Match',
'Idempotency-Key',
],
exposedHeaders: ['ETag'],
});
app.useGlobalPipes(
new ValidationPipe({
@@ -31,4 +37,4 @@ async function bootstrap() {
);
await app.listen(isDev ? 3000 : 10712);
}
bootstrap();
void bootstrap();
@@ -0,0 +1,82 @@
import mongoose from 'mongoose';
import { AuctionBidArchiveService } from './auction-bid-archive.service';
const matchId = new mongoose.Types.ObjectId().toString();
function bid(overrides: Record<string, unknown> = {}) {
return {
_id: `${matchId}:life:${String(1).padStart(16, '0')}`,
matchId,
auctionLifecycleId: 'life',
revision: 1,
bidRequestId: 'bid-1',
bidderUserId: new mongoose.Types.ObjectId().toString(),
playerUserId: new mongoose.Types.ObjectId().toString(),
bidderTeamIndex: 1,
bidPointAmount: 10,
bidPlacedAtTimestampMS: 1_700_000_000_000,
...overrides,
};
}
function fixture(payload: Record<string, unknown>) {
const raw = JSON.stringify(payload);
const commands: string[][] = [];
const sendCommand = jest.fn(async (command: string[]) => {
commands.push(command);
if (command[0] === 'ZRANGE') return [payload._id];
if (command[0] === 'HMGET') return [raw];
return 1;
});
const bulkWrite = jest.fn(async (operations: unknown[]) => ({
matchedCount: 0,
upsertedCount: operations.length,
}));
const service = new AuctionBidArchiveService(
{ getModel: async () => ({ bulkWrite }) } as never,
{ raw: () => ({ sendCommand }) } as never,
);
return { service, bulkWrite, commands };
}
function savedEvent(bulkWrite: jest.Mock) {
const [[operations]] = bulkWrite.mock.calls as unknown as [
[
Array<{
updateOne: { update: { $setOnInsert: Record<string, unknown> } };
}>,
],
];
return operations[0].updateOne.update.$setOnInsert;
}
function quarantined(commands: string[][]) {
return commands.some(
(command) =>
command[0] === 'EVAL' &&
command[1].includes("redis.call('ZADD', KEYS[4]"),
);
}
it('archives a pre-upgrade bid with an empty round ID without the field', async () => {
const f = fixture(bid({ bidRoundId: '' }));
await expect(f.service.persistPendingBids()).resolves.toBe(1);
expect(quarantined(f.commands)).toBe(false);
expect(savedEvent(f.bulkWrite)).not.toHaveProperty('bidRoundId');
});
it('keeps a non-empty round ID on the archived bid', async () => {
const f = fixture(bid({ bidRoundId: 'round-1' }));
await expect(f.service.persistPendingBids()).resolves.toBe(1);
expect(savedEvent(f.bulkWrite)).toMatchObject({ bidRoundId: 'round-1' });
});
it.each([' ', null, 1])(
'still quarantines an invalid round ID %j',
async (bidRoundId) => {
const f = fixture(bid({ bidRoundId }));
await expect(f.service.persistPendingBids()).resolves.toBe(0);
expect(f.bulkWrite).not.toHaveBeenCalled();
expect(quarantined(f.commands)).toBe(true);
},
);
@@ -0,0 +1,242 @@
import {
BadRequestException,
Injectable,
Logger,
NotFoundException,
} from '@nestjs/common';
import mongoose from 'mongoose';
import type { AuctionBidRecord } from '../global/database/schema';
import { ConnectionService } from '../global/database/connection.service';
import { AuctionRedisService } from './redis/auction-redis.service';
import {
AUCTION_BID_ARCHIVE_PAYLOADS_KEY,
AUCTION_BID_ARCHIVE_QUEUE_KEY,
AUCTION_BID_ARCHIVE_DEAD_LETTER_QUEUE_KEY,
AUCTION_BID_ARCHIVE_DEAD_LETTER_PAYLOADS_KEY,
} from './redis/auction-redis.keys';
// Compare the payload as well as the ID: a concurrent repair must not be moved
// or acknowledged by a worker that read an older value.
const QUARANTINE_BID_ARCHIVE_SCRIPT = `
local moved = 0
for i = 2, #ARGV, 4 do
local current = redis.call('HGET', KEYS[1], ARGV[i])
local matches = (ARGV[i+1] == '0' and current == false) or (ARGV[i+1] == '1' and current == ARGV[i+2])
if matches and redis.call('ZSCORE', KEYS[2], ARGV[i]) then
redis.call('HSET', KEYS[3], ARGV[i], ARGV[i+3])
redis.call('ZADD', KEYS[4], ARGV[1], ARGV[i])
redis.call('HDEL', KEYS[1], ARGV[i])
redis.call('ZREM', KEYS[2], ARGV[i])
moved = moved + 1
end
end
return moved
`;
@Injectable()
export class AuctionBidArchiveService {
private readonly logger = new Logger(AuctionBidArchiveService.name);
constructor(
private readonly database: ConnectionService,
private readonly redis: AuctionRedisService,
) {}
public async persistPendingBids(limit = 200): Promise<number> {
const client = this.redis.raw();
const reply = await client.sendCommand([
'ZRANGE',
AUCTION_BID_ARCHIVE_QUEUE_KEY,
'0',
String(limit - 1),
]);
const ids = Array.isArray(reply) ? reply.map(String) : [];
if (!ids.length) return 0;
const values = await client.sendCommand<Array<string | null>>([
'HMGET',
AUCTION_BID_ARCHIVE_PAYLOADS_KEY,
...ids,
]);
const valid: Array<{ event: AuctionBidRecord; raw: string }> = [];
const invalid: Array<{ id: string; raw: string | null; error: string }> =
[];
for (let index = 0; index < ids.length; index++) {
const raw = values[index] ?? null;
try {
valid.push({ event: parseBidArchiveEvent(ids[index], raw), raw: raw! });
} catch (error) {
invalid.push({
id: ids[index],
raw,
error: String(error).slice(0, 2000),
});
}
}
if (invalid.length) {
const now = Date.now();
const moved = await client.sendCommand<number>([
'EVAL',
QUARANTINE_BID_ARCHIVE_SCRIPT,
'4',
AUCTION_BID_ARCHIVE_PAYLOADS_KEY,
AUCTION_BID_ARCHIVE_QUEUE_KEY,
AUCTION_BID_ARCHIVE_DEAD_LETTER_PAYLOADS_KEY,
AUCTION_BID_ARCHIVE_DEAD_LETTER_QUEUE_KEY,
String(now),
...invalid.flatMap(({ id, raw, error }) => [
id,
raw === null ? '0' : '1',
raw ?? '',
JSON.stringify({
id,
rawPayload: raw,
error,
quarantinedAtTimestampMS: now,
}),
]),
]);
if (moved > 0)
this.logger.warn(`Quarantined ${moved} invalid bid archive events.`);
}
if (valid.length) {
const model = await this.database.getModel('auctionBidRecord');
// The deterministic _id is the dedupe key, including after a crash between
// Mongo acknowledgement and Redis cleanup. Never trim unpersisted events.
const result = await model.bulkWrite(
valid.map(({ event }) => ({
updateOne: {
filter: { _id: event._id },
update: { $setOnInsert: event },
upsert: true,
},
})),
{ ordered: false, throwOnValidationError: true },
);
// A partial/ambiguous write leaves valid entries queued. Replaying the
// upserts is safe; assuming that a resolved bulkWrite saved all is not.
if (result.matchedCount + result.upsertedCount !== valid.length) {
throw new Error(
'Bid archive batch was not fully acknowledged by MongoDB.',
);
}
await client.sendCommand([
'EVAL',
"for i = 1, #ARGV, 2 do if redis.call('HGET', KEYS[1], ARGV[i]) == ARGV[i+1] then redis.call('HDEL', KEYS[1], ARGV[i]); redis.call('ZREM', KEYS[2], ARGV[i]) end end return 1",
'2',
AUCTION_BID_ARCHIVE_PAYLOADS_KEY,
AUCTION_BID_ARCHIVE_QUEUE_KEY,
...valid.flatMap(({ event, raw }) => [event._id, raw]),
]);
}
return valid.length;
}
public async list(
matchId: mongoose.Types.ObjectId,
afterRevision = -1,
limit = 100,
) {
if (
!Number.isSafeInteger(afterRevision) ||
afterRevision < -1 ||
!Number.isSafeInteger(limit) ||
limit < 1 ||
limit > 200
) {
throw new BadRequestException('Invalid bid history cursor or limit.');
}
const AuctionModel = await this.database.getModel('auction');
const auction = await AuctionModel.findOne({ matchId })
.select({ auctionLifecycleId: 1 })
.lean()
.exec();
if (!auction) throw new NotFoundException('Auction not found.');
const prefix = `${matchId.toString()}:${auction.auctionLifecycleId}:`;
const model = await this.database.getModel('auctionBidRecord');
// The built-in _id index supports ordered pagination without an additional
// production index or an unbounded array inside an Auction document.
const items = await model
.find({
_id: {
$gt:
afterRevision < 0
? prefix
: prefix + String(afterRevision).padStart(16, '0'),
$lt: prefix + '\uffff',
},
})
.sort({ _id: 1 })
.limit(limit + 1)
.lean()
.exec();
const hasMore = items.length > limit;
if (hasMore) items.pop();
return {
items,
hasMore,
nextRevision: items.at(-1)?.revision ?? afterRevision,
};
}
}
function parseBidArchiveEvent(
id: string,
raw: string | null,
): AuctionBidRecord {
if (raw === null) throw new Error('Missing bid archive payload.');
const value: unknown = JSON.parse(raw);
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new Error('Bid archive payload must be an object.');
}
const event = value as Record<string, unknown>;
const string = (field: string): string => {
const value = event[field];
if (typeof value !== 'string' || !value.trim()) {
throw new Error(`Invalid bid archive ${field}.`);
}
return value;
};
const integer = (field: string, minimum = 0): number => {
const value = event[field];
if (
typeof value !== 'number' ||
!Number.isSafeInteger(value) ||
value < minimum
) {
throw new Error(`Invalid bid archive ${field}.`);
}
return value;
};
const objectId = (field: string): mongoose.Types.ObjectId => {
const value = string(field);
if (!mongoose.isObjectIdOrHexString(value)) {
throw new Error(`Invalid bid archive ${field}.`);
}
return new mongoose.Types.ObjectId(value);
};
const matchId = objectId('matchId');
const auctionLifecycleId = string('auctionLifecycleId');
const revision = integer('revision');
const expectedId = `${matchId.toString()}:${auctionLifecycleId}:${String(revision).padStart(16, '0')}`;
if (event._id !== id || id !== expectedId) {
throw new Error('Bid archive identity does not match its payload.');
}
return {
_id: id,
matchId,
auctionLifecycleId,
revision,
bidRequestId: string('bidRequestId'),
bidderUserId: objectId('bidderUserId'),
bidderTeamIndex: integer('bidderTeamIndex', 1),
bidPointAmount: integer('bidPointAmount'),
bidPlacedAtTimestampMS: integer('bidPlacedAtTimestampMS'),
...(event.playerUserId !== undefined
? { playerUserId: objectId('playerUserId') }
: {}),
// Pre-upgrade rounds have no Redis round ID; the bid Lua records ''.
...(event.bidRoundId !== undefined && event.bidRoundId !== ''
? { bidRoundId: string('bidRoundId') }
: {}),
};
}
@@ -0,0 +1,9 @@
/**
* 계정 지급 전에는 화면에서 선택한 팀으로 입찰하는 임시 운영 모드가 기본이다.
* 계정 지급 후 AUCTION_REQUIRE_CAPTAIN_AUTH=true로 로그인·팀장 검증을 복구한다.
*/
export function isAuctionCaptainAuthRequired(): boolean {
return (
process.env.AUCTION_REQUIRE_CAPTAIN_AUTH?.trim().toLowerCase() === 'true'
);
}
@@ -0,0 +1,154 @@
import { NotFoundException } from '@nestjs/common';
import mongoose from 'mongoose';
import { AuctionService } from './auction.service';
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
function sessionQuery<T>(value: T) {
return { session: async () => value };
}
function fixture(options: {
auction: Record<string, unknown> | null;
match: Record<string, unknown>;
failRedisCleanup?: boolean;
}) {
const session = {
startTransaction: jest.fn(),
commitTransaction: jest.fn().mockResolvedValue(undefined),
abortTransaction: jest.fn().mockResolvedValue(undefined),
endSession: jest.fn().mockResolvedValue(undefined),
};
const deleteMany = jest.fn(() => sessionQuery(undefined));
const models: Record<string, unknown> = {
auction: { findOne: () => sessionQuery(options.auction) },
auctionHistory: { deleteMany },
auctionSideEffectApplication: { deleteMany },
match: { findById: () => sessionQuery(options.match) },
};
const redisCommands: string[][] = [];
const sendCommand = jest.fn(async (command: string[]) => {
redisCommands.push(command);
if (command[0] === 'EVAL' && options.failRedisCleanup)
throw new Error('redis unavailable');
return command[0] === 'SCAN' ? ['0', []] : 1;
});
const service = new AuctionService(
{
getModel: async (name: string) => models[name],
createSession: async () => session,
} as never,
{} as never,
{ releaseFromMatch: jest.fn().mockResolvedValue(undefined) } as never,
{ cancelPolling: jest.fn().mockResolvedValue(undefined) } as never,
{
acquireTokenLock: async () => true,
releaseTokenLock: async () => true,
raw: () => ({ sendCommand }),
} as never,
{} as never,
{} as never,
);
return { service, session, redisCommands };
}
function liveMatch(): Record<string, unknown> {
return {
communityId,
status: 'team-built',
teams: [],
tournamentCodeIds: [],
gameSchedule: [],
participants: [],
save: jest.fn().mockResolvedValue(undefined),
};
}
function redisAuction() {
return {
_id: new mongoose.Types.ObjectId(),
auctionEngineVersion: 'redis-v1',
auctionLifecycleId: 'life',
deleteOne: jest.fn().mockResolvedValue(undefined),
};
}
it('records the cancelled lifecycle and still succeeds when Redis cleanup fails', async () => {
const match = liveMatch();
const f = fixture({
auction: redisAuction(),
match,
failRedisCleanup: true,
});
await expect(
f.service.reset({
matchId,
communityId,
clientObservedAuctionLifecycleId: 'life',
}),
).resolves.toBeUndefined();
expect(f.session.commitTransaction).toHaveBeenCalledTimes(1);
expect(match.lastCancelledAuctionLifecycleId).toBe('life');
expect(match.status).toBe('recruiting');
});
it('answers a retransmitted cancellation and durably schedules Redis cleanup', async () => {
const match = { ...liveMatch(), lastCancelledAuctionLifecycleId: 'life' };
const f = fixture({ auction: null, match });
await expect(
f.service.reset({
matchId,
communityId,
clientObservedAuctionLifecycleId: 'life',
}),
).resolves.toBeUndefined();
expect(match).toMatchObject({
auctionCancellationCleanupPending: true,
auctionCancellationCleanupRetryAt: expect.any(Date),
});
expect(f.redisCommands).toEqual([]);
});
it('preserves a committed cancellation even if its lock renewal fails before returning', async () => {
jest.useFakeTimers();
try {
const match = liveMatch();
const f = fixture({ auction: redisAuction(), match });
f.session.commitTransaction.mockImplementation(async () => {
await jest.advanceTimersByTimeAsync(10000);
});
await expect(
f.service.reset({
matchId,
communityId,
clientObservedAuctionLifecycleId: 'life',
}),
).resolves.toBeUndefined();
expect(match.auctionCancellationCleanupPending).toBe(true);
expect(f.session.commitTransaction).toHaveBeenCalledTimes(1);
} finally {
jest.useRealTimers();
}
});
it('keeps 404 for a missing auction that was not cancelled with this lifecycle', async () => {
for (const [observed, recorded] of [
['other', 'life'],
[undefined, 'life'],
['life', undefined],
] as const) {
const f = fixture({
auction: null,
match: { ...liveMatch(), lastCancelledAuctionLifecycleId: recorded },
});
await expect(
f.service.reset({
matchId,
communityId,
clientObservedAuctionLifecycleId: observed,
}),
).rejects.toBeInstanceOf(NotFoundException);
expect(f.session.abortTransaction).toHaveBeenCalled();
}
});
@@ -0,0 +1,156 @@
import mongoose from 'mongoose';
import { BadRequestException } from '@nestjs/common';
jest.mock('../auth/jwt.service', () => ({ JwtService: class JwtService {} }));
import { AuctionGateway } from './auction.gateway';
function setup() {
const appendChatMessage = jest.fn();
const gateway = new AuctionGateway(
{ appendChatMessage } as never,
{} as never,
{} as never,
{} as never,
{} as never,
{} as never,
{} as never,
);
const broadcast = jest.fn();
const to = jest.fn().mockReturnValue({ emit: broadcast });
(gateway as unknown as { server: unknown }).server = {
to,
};
const socket = {
data: {
matchId: new mongoose.Types.ObjectId().toString(),
user: {
_id: new mongoose.Types.ObjectId(),
role: 'admin',
riotAccounts: [],
kakaoTalkNickname: '운영자',
},
},
emit: jest.fn(),
};
return { gateway, appendChatMessage, broadcast, socket, to };
}
describe('Auction chat delivery', () => {
const payload = {
message: '준비해 주세요',
clientMessageId: '0589e8a4-bccd-4ccd-a3ae-28f117401e79',
};
it('acknowledges only after saving and assigns the operator role from the socket user', async () => {
const { gateway, appendChatMessage, broadcast, socket } = setup();
const message = { id: 'saved', ...payload, sentAt: new Date() };
let finish!: (result: unknown) => void;
appendChatMessage.mockReturnValue(
new Promise((resolve) => {
finish = resolve;
}),
);
const ack = jest.fn();
const pending = gateway.handleChatMessage(socket as never, payload, ack);
expect(ack).not.toHaveBeenCalled();
expect(broadcast).not.toHaveBeenCalled();
finish({ message, created: true });
await pending;
expect(appendChatMessage).toHaveBeenCalledWith(
expect.objectContaining({
clientMessageId: payload.clientMessageId,
senderRole: 'operator',
displayName: '운영자',
}),
);
expect(ack).toHaveBeenCalledWith({
ok: true,
message: expect.objectContaining({ id: 'saved' }),
});
expect(broadcast).toHaveBeenCalledTimes(1);
});
it('acknowledges a retry without broadcasting a duplicate', async () => {
const { gateway, appendChatMessage, broadcast, socket } = setup();
appendChatMessage.mockResolvedValue({
message: { id: 'saved' },
created: false,
});
const ack = jest.fn();
await gateway.handleChatMessage(socket as never, payload, ack);
expect(ack).toHaveBeenCalledWith({ ok: true, message: { id: 'saved' } });
expect(broadcast).not.toHaveBeenCalled();
});
it('returns rejection to the requesting composer without reporting success', async () => {
const { gateway, appendChatMessage, broadcast, socket } = setup();
appendChatMessage.mockRejectedValue(
new BadRequestException('Chat message is required.'),
);
const ack = jest.fn();
await gateway.handleChatMessage(socket as never, payload, ack);
expect(ack).toHaveBeenCalledWith(
expect.objectContaining({
ok: false,
message: 'Chat message is required.',
}),
);
expect(broadcast).not.toHaveBeenCalled();
});
});
describe('Auction live reactions', () => {
it('broadcasts to the joined room with the server-resolved name, without saving a chat message', () => {
const { gateway, appendChatMessage, broadcast, socket, to } = setup();
const ack = jest.fn();
gateway.handleChatReaction(socket as never, { kind: 'clap' }, ack);
expect(to).toHaveBeenCalledWith(socket.data.matchId);
expect(broadcast).toHaveBeenCalledWith(
'chat-reaction',
expect.objectContaining({
id: expect.any(String),
kind: 'clap',
displayName: '운영자',
userId: socket.data.user._id.toString(),
}),
);
expect(ack).toHaveBeenCalledWith({
ok: true,
reaction: broadcast.mock.calls[0][1],
});
expect(appendChatMessage).not.toHaveBeenCalled();
});
it('rejects unjoined clients and arbitrary reaction values', () => {
const { gateway, broadcast, socket } = setup();
const ack = jest.fn();
gateway.handleChatReaction({ data: {} } as never, { kind: 'heart' }, ack);
expect(ack).toHaveBeenLastCalledWith({ ok: false, code: 'NOT_JOINED' });
for (const kind of ['__proto__', 'not-supported', 1, null]) {
gateway.handleChatReaction(socket as never, { kind }, ack);
expect(ack).toHaveBeenLastCalledWith({
ok: false,
code: 'INVALID_REACTION',
});
}
expect(broadcast).not.toHaveBeenCalled();
});
it('throttles bursts, then accepts the next reaction after the interval', () => {
const { gateway, broadcast, socket } = setup();
const clock = jest.spyOn(Date, 'now').mockReturnValue(1000);
const ack = jest.fn();
try {
gateway.handleChatReaction(socket as never, { kind: 'heart' }, ack);
gateway.handleChatReaction(socket as never, { kind: 'heart' }, ack);
expect(ack).toHaveBeenLastCalledWith({
ok: false,
code: 'REACTION_RATE_LIMITED',
});
expect(broadcast).toHaveBeenCalledTimes(1);
clock.mockReturnValue(1400);
gateway.handleChatReaction(socket as never, { kind: 'celebrate' }, ack);
expect(broadcast).toHaveBeenCalledTimes(2);
} finally {
clock.mockRestore();
}
});
});
@@ -0,0 +1,607 @@
import mongoose from 'mongoose';
import { AuctionService } from './auction.service';
import {
AuctionDurabilityScheduler,
buildAuctionProjectionGuardedUpdate,
type AuctionDurabilityPayload,
} from './auction-durability.scheduler';
import { AuctionDeadlineScheduler } from './auction-deadline.scheduler';
import { AuctionLifecycleLock } from './auction-lifecycle-lock';
const query = <T>(value: T) => ({
select() {
return this;
},
session() {
return this;
},
lean() {
return this;
},
exec: async () => value,
});
const session = () => ({
startTransaction: jest.fn(),
commitTransaction: jest.fn(),
abortTransaction: jest.fn(),
endSession: jest.fn(),
});
const state = {
auctionLifecycleId: 'life',
revision: 12,
phase: 'presenting',
currentAuctionHistorySequence: 7,
currentAuctionPlayerOrderIndex: 0,
currentAuctionRound: 1,
auctionTeams: [],
auctionPlayerOrder: [],
passedAuctionPlayerQueue: [],
currentHighestBidPointAmount: 0,
currentHighestBidderTeamIndex: -1,
auctionCompletedAtTimestampMS: 0,
currentBidRoundDeadlineTimestampMS: 0,
};
beforeEach(() => {
jest
.spyOn(AuctionLifecycleLock.prototype, 'run')
.mockImplementation(async (_id, work) => work());
});
afterEach(() => jest.restoreAllMocks());
function matches(
document: Record<string, unknown>,
filter: Record<string, unknown>,
): boolean {
return Object.entries(filter).every(([key, value]) => {
if (key === '$or')
return (value as Record<string, unknown>[]).some((alternative) =>
matches(document, alternative),
);
if (value && typeof value === 'object') {
return Object.entries(value).every(([operator, limit]) => {
if (operator === '$exists')
return (document[key] !== undefined) === limit;
if (operator === '$lt') return Number(document[key]) < Number(limit);
if (operator === '$lte') return Number(document[key]) <= Number(limit);
return false;
});
}
return document[key] === value;
});
}
function update(
document: Record<string, unknown>,
mutation: Record<string, Record<string, unknown>>,
) {
Object.assign(document, mutation.$set);
for (const [key, amount] of Object.entries(mutation.$inc ?? {}))
document[key] = Number(document[key] ?? 0) + Number(amount);
for (const key of Object.keys(mutation.$unset ?? {})) delete document[key];
}
function sideEffectFixture(withReader = false) {
const projection: Record<string, unknown> = {
_id: 'auction',
auctionLifecycleId: 'life',
revision: 9,
matchSideEffectRevision: 0,
};
const application: Record<string, unknown> = {};
const payload: AuctionDurabilityPayload = {
auctionId: 'auction',
matchId: 'match',
auctionLifecycleId: 'life',
auctionStateTransitionId: 'complete',
auctionActionType: 'complete',
auctionHistorySequence: 10,
revision: 10,
snapshotBefore: {},
historyMutation: { type: 'append' },
matchSideEffectMutation: { type: 'syncMatchTeamsAfterComplete' },
afterAuctionMongoProjection: {
auctionLifecycleId: 'life',
revision: 10,
phase: 'complete',
matchSideEffectRevision: 1,
matchSideEffectStatus: 'pending',
matchSideEffectTransitionId: 'complete',
auctionTeams: [{ teamIndex: 1, captainUserId: 'captain', members: [] }],
},
};
const AuctionModel = {
findById: () => query({ ...projection }),
updateOne: (
filter: Record<string, unknown>,
mutation: Record<string, Record<string, unknown>>,
) => {
const matchedCount = Number(matches(projection, filter));
if (matchedCount) update(projection, mutation);
return query({ matchedCount });
},
findOneAndUpdate: (
filter: Record<string, unknown>,
mutation: Record<string, Record<string, unknown>>,
) => {
if (!matches(projection, filter)) return query(null);
update(projection, mutation);
return query({ ...projection });
},
};
const ApplicationModel = {
findOne: () => query({ ...application }),
updateOne: (
filter: Record<string, unknown>,
mutation: Record<string, Record<string, unknown>>,
) => {
if (mutation.$setOnInsert) {
if (!application.state)
Object.assign(application, mutation.$setOnInsert);
return query({ matchedCount: 1 });
}
const matchedCount = Number(matches(application, filter));
if (matchedCount) update(application, mutation);
return query({ matchedCount });
},
};
const match = {
participants: [],
teams: [],
save: jest.fn().mockResolvedValue(undefined),
};
const historyFindOne = jest.fn().mockReturnValue(query(null));
const historyUpdateOne = jest
.fn()
.mockReturnValue(query({ matchedCount: 1 }));
const models: Record<string, unknown> = {
auction: AuctionModel,
auctionHistory: {
findOne: historyFindOne,
updateOne: historyUpdateOne,
},
auctionSideEffectApplication: ApplicationModel,
match: {
findById: () => ({ ...query(match), session: async () => match }),
},
};
const reserveForMatch = jest
.fn()
.mockRejectedValueOnce(new Error('temporary reservation error'))
.mockResolvedValue(match);
const scheduleInitialPoll = jest.fn().mockResolvedValue(undefined);
const releaseFromMatch = jest.fn().mockResolvedValue(undefined);
const cancelPolling = jest.fn().mockResolvedValue(undefined);
let queued = true;
const sendCommand = jest.fn(async (command: string[]) => {
if (command[0] === 'ZRANGEBYSCORE') return queued ? ['payload'] : [];
if (command[0] === 'HGETALL')
return { payloadJson: JSON.stringify(payload) };
if (command[0] === 'DEL') queued = false;
if (command[0] === 'HINCRBY') return 1;
return 1;
});
const scheduler = new AuctionDurabilityScheduler(
{
getModel: async (name: string) => models[name],
createSession: async () => session(),
} as never,
{
getCurrentRedisTimestampMS: async () => 10000,
raw: () => ({ sendCommand }),
} as never,
{ reserveForMatch, releaseFromMatch } as never,
{ scheduleInitialPoll, cancelPolling } as never,
undefined,
undefined,
withReader
? ({
readAuctionStateView: async () => ({
auctionLifecycleId: 'life',
phase: payload.afterAuctionMongoProjection.phase,
matchSideEffectTransitionId: 'complete',
}),
} as never)
: undefined,
);
return {
scheduler,
payload,
projection,
application,
reserveForMatch,
scheduleInitialPoll,
sendCommand,
match,
historyFindOne,
historyUpdateOne,
releaseFromMatch,
cancelPolling,
};
}
it('retries failed completion work with the current generation and only then deletes the payload', async () => {
const f = sideEffectFixture();
expect(await f.scheduler.processDueDurabilityPayloads(20)).toMatchObject({
failed: 1,
});
expect(f.projection.matchSideEffectStatus).toBe('failed');
expect(await f.scheduler.processDueDurabilityPayloads(20)).toMatchObject({
applied: 1,
});
expect(f.reserveForMatch).toHaveBeenCalledTimes(2);
expect(f.scheduleInitialPoll).toHaveBeenCalledTimes(1);
expect(f.application.state).toBe('completed');
expect(f.projection.matchSideEffectStatus).toBe('completed');
expect(f.projection.matchSideEffectRevision).toBe(5);
expect(f.sendCommand).toHaveBeenCalledWith(['DEL', 'payload']);
});
it('keeps an outbox payload while another worker owns its side-effect lease', async () => {
const f = sideEffectFixture();
Object.assign(f.application, {
auctionId: 'auction',
auctionStateTransitionId: 'complete',
sideEffectType: 'syncMatchTeamsAfterComplete',
state: 'processing',
processingOwnerToken: 'other',
processingLeaseExpiresAtTimestampMS: 50000,
});
expect(await f.scheduler.processDueDurabilityPayloads(20)).toEqual({
applied: 0,
failed: 0,
skipped: 1,
});
expect(f.sendCommand).not.toHaveBeenCalledWith(['DEL', 'payload']);
expect(
f.sendCommand.mock.calls.some(([command]) => command[0] === 'HINCRBY'),
).toBe(false);
expect(f.reserveForMatch).not.toHaveBeenCalled();
});
it('recovers side effects when a later ordinary projection was persisted first', async () => {
const f = sideEffectFixture(true);
f.reserveForMatch.mockReset().mockResolvedValue(undefined);
Object.assign(f.projection, { revision: 12 });
await f.scheduler.applyDurabilityPayload(f.payload);
expect(f.reserveForMatch).toHaveBeenCalledTimes(1);
expect(f.projection.revision).toBe(12);
expect(f.projection.matchSideEffectTransitionId).toBe('complete');
expect(f.projection.matchSideEffectStatus).toBe('completed');
});
it('still cleans up completed Match state when a second undo invalidates the first undo history', async () => {
const f = sideEffectFixture(true);
Object.assign(f.projection, { revision: 12 });
Object.assign(f.payload, {
matchSideEffectMutation: { type: 'undoCompletedAuctionSideEffects' },
});
f.payload.afterAuctionMongoProjection.phase = 'presenting';
Object.assign(f.match, {
teams: [{ teamIndex: 1 }],
teamBuiltAt: new Date(),
tournamentCodeIds: ['code'],
gameSchedule: [{}],
});
f.historyFindOne.mockReturnValue(
query({
sequence: 12,
historyMutation: {
type: 'deleteAfterSequenceAndAppendUndo',
targetHistorySequence: 2,
},
}),
);
await f.scheduler.applyDurabilityPayload(f.payload);
expect(f.historyUpdateOne).not.toHaveBeenCalled();
expect(f.releaseFromMatch).toHaveBeenCalledTimes(1);
expect(f.cancelPolling).toHaveBeenCalledTimes(1);
expect(f.match).toMatchObject({
teams: [],
teamBuiltAt: undefined,
tournamentCodeIds: [],
gameSchedule: [],
});
expect(f.projection.matchSideEffectStatus).toBe('completed');
});
it('does not let a superseded side effect overwrite the newer generation', async () => {
const f = sideEffectFixture();
Object.assign(f.projection, {
revision: 12,
matchSideEffectTransitionId: 'undo',
matchSideEffectRevision: 6,
});
await f.scheduler.applyDurabilityPayload(f.payload);
expect(f.reserveForMatch).not.toHaveBeenCalled();
expect(f.projection.matchSideEffectTransitionId).toBe('undo');
});
it('removes obsolete projection fields both from Mongo updates and subsequent undo snapshots', () => {
const service = new AuctionService(
{} as never,
{} as never,
{} as never,
{} as never,
{} as never,
{} as never,
{} as never,
);
const internal = service as unknown as {
buildAuctionMongoProjectionFromState(
auction: unknown,
state: Record<string, unknown>,
): Record<string, unknown>;
buildAuctionSnapshotFromRedisState(
auction: unknown,
state: Record<string, unknown>,
): Record<string, unknown>;
};
const old = {
_id: new mongoose.Types.ObjectId(),
matchId: new mongoose.Types.ObjectId(),
completedAt: new Date(),
auctionCompletedAtTimestampMS: 100,
currentHighestBidderTeamIndex: 2,
currentBidderTeamIndex: 2,
};
const projection = internal.buildAuctionMongoProjectionFromState(old, state);
const mutation = buildAuctionProjectionGuardedUpdate({
auctionId: old._id,
auctionLifecycleId: 'life',
revision: 12,
afterAuctionMongoProjection: projection,
} as AuctionDurabilityPayload).update;
const stored = { ...old } as Record<string, unknown>;
update(stored, mutation);
const snapshot = internal.buildAuctionSnapshotFromRedisState(old, state);
for (const record of [stored, snapshot]) {
expect(record).not.toHaveProperty('completedAt');
expect(record).not.toHaveProperty('currentHighestBidderTeamIndex');
expect(record.phase).toBe('presenting');
}
});
it('applies delayed undo history cleanup without deleting newer branch entries or rolling back projection', async () => {
const deleteMany = jest.fn().mockReturnValue(query({}));
const updateOne = jest.fn().mockReturnValue(query({}));
const projectionUpdate = jest.fn();
const models: Record<string, unknown> = {
auction: {
findById: () => query({ auctionLifecycleId: 'life', revision: 12 }),
updateOne: projectionUpdate,
},
auctionHistory: { findOne: () => query(null), deleteMany, updateOne },
auctionSideEffectApplication: {},
};
const scheduler = new AuctionDurabilityScheduler(
{
getModel: async (name: string) => models[name],
createSession: async () => null,
} as never,
{} as never,
);
await scheduler.applyDurabilityPayload({
auctionId: 'auction',
matchId: 'match',
auctionStateTransitionId: 'undo',
auctionLifecycleId: 'life',
revision: 11,
auctionHistorySequence: 9,
auctionActionType: 'undo',
historyMutation: {
type: 'deleteAfterSequenceAndAppendUndo',
targetHistorySequence: 3,
},
matchSideEffectMutation: { type: 'none' },
afterAuctionMongoProjection: {},
snapshotBefore: {},
} as AuctionDurabilityPayload);
expect(deleteMany).toHaveBeenCalledWith(
{ auctionId: 'auction', sequence: { $gt: 3, $lt: 9 } },
{ session: null },
);
expect(updateOne).toHaveBeenCalledTimes(1);
expect(projectionUpdate).not.toHaveBeenCalled();
});
it('rejects a cancellation from a prior lifecycle before deleting anything', async () => {
const matchId = new mongoose.Types.ObjectId(),
communityId = new mongoose.Types.ObjectId();
const deleteOne = jest.fn();
const service = new AuctionService(
{
createSession: async () => session(),
getModel: async () => ({
findOne: () => ({
session: async () => ({
auctionEngineVersion: 'redis-v1',
auctionLifecycleId: 'new-life',
deleteOne,
}),
}),
}),
} as never,
{} as never,
{} as never,
{} as never,
{} as never,
{} as never,
{} as never,
);
await expect(
service.reset({
matchId,
communityId,
clientObservedAuctionLifecycleId: 'old-life',
}),
).rejects.toThrow('lifecycle has changed');
expect(deleteOne).not.toHaveBeenCalled();
});
it('resumes startup after Mongo creation instead of returning an unfinished auction', async () => {
const matchId = new mongoose.Types.ObjectId(),
communityId = new mongoose.Types.ObjectId();
const captain = new mongoose.Types.ObjectId(),
player = new mongoose.Types.ObjectId(),
lateJoiner = new mongoose.Types.ObjectId();
const auction = {
_id: new mongoose.Types.ObjectId(),
matchId,
auctionLifecycleId: 'life',
revision: 1,
phase: 'presenting',
startupCompleted: false,
startAuctionRequestId: 'same-request',
teams: [{ captainUserId: captain, members: [], teamIndex: 1 }],
order: [{ userId: player }],
};
const match = {
communityId,
status: 'recruiting',
participants: [captain, player, lateJoiner].map((userId) => ({
userId,
excluded: false,
})),
save: jest.fn(),
};
const updateOne = jest.fn();
const historyUpdate = jest.fn();
const models: Record<string, unknown> = {
auction: { findOne: async () => auction, updateOne },
match: { findById: async () => match },
auctionHistory: { updateOne: historyUpdate },
};
const hydrateState = jest.fn().mockResolvedValue({ hydrated: true });
const service = new AuctionService(
{ getModel: async (name: string) => models[name] } as never,
{} as never,
{} as never,
{} as never,
{} as never,
{ hydrateState } as never,
{} as never,
);
await service.start({
matchId,
communityId,
startAuctionRequestId: 'same-request',
} as never);
expect(hydrateState).toHaveBeenCalledTimes(1);
expect(historyUpdate).toHaveBeenCalledTimes(1);
expect(match.save).toHaveBeenCalledTimes(1);
expect(match.status).toBe('team-built');
expect(auction.startupCompleted).toBe(true);
expect(match.participants.map((entry) => entry.excluded)).toEqual([
false,
false,
true,
]);
});
it('does not open bidding until interrupted startup has been completed', async () => {
const service = new AuctionService(
{
getModel: async () => ({
findOne: async () => ({
auctionEngineVersion: 'redis-v1',
startupCompleted: false,
}),
}),
} as never,
{} as never,
{} as never,
{} as never,
{} as never,
{} as never,
{} as never,
);
await expect(
service.openBidding(new mongoose.Types.ObjectId()),
).rejects.toThrow('startup is not complete');
});
it('uses Redis completion state to schedule cleanup despite a delayed Mongo projection', async () => {
const matchId = new mongoose.Types.ObjectId(),
communityId = new mongoose.Types.ObjectId();
const auction = {
_id: new mongoose.Types.ObjectId(),
matchId,
auctionEngineVersion: 'redis-v1',
auctionLifecycleId: 'life',
phase: 'sold',
revision: 9,
};
const snapshot = { ...state, phase: 'bidding', revision: 5 };
const models: Record<string, unknown> = {
auction: { findOne: () => ({ session: async () => auction }) },
match: { findById: () => ({ session: async () => ({ communityId }) }) },
auctionHistory: { findOne: () => query({ snapshotBefore: snapshot }) },
};
const applyTransition = jest.fn().mockResolvedValue({ ok: true });
const commands = {
reserveActionRequest: async () => ({
reserved: true,
actionRequestScopeKey: 'scope',
auctionStateTransitionId: 'undo',
observedProcessingLeaseVersion: 1,
}),
applyTransition,
};
const service = new AuctionService(
{
getModel: async (name: string) => models[name],
createSession: async () => session(),
} as never,
{} as never,
{} as never,
{} as never,
{} as never,
commands as never,
{
readAuctionStateView: async () => ({
...state,
phase: 'complete',
revision: 10,
}),
} as never,
);
await service.undoTo({ matchId, communityId, sequence: 2 });
const input = applyTransition.mock.calls[0][1] as {
durabilityPayloadJson: string;
};
expect(JSON.parse(input.durabilityPayloadJson)).toMatchObject({
matchSideEffectMutation: { type: 'undoCompletedAuctionSideEffects' },
});
});
it.each(['deadline', 'durability'])(
'continues %s ticks when lock release fails',
async (kind) => {
const redis = {
acquireTokenLock: jest.fn().mockResolvedValue(true),
releaseTokenLock: jest
.fn()
.mockRejectedValue(new Error('redis disconnected')),
};
const scheduler =
kind === 'deadline'
? new AuctionDeadlineScheduler(
redis as never,
{} as never,
{} as never,
{} as never,
)
: new AuctionDurabilityScheduler({} as never, redis as never);
const work = jest.fn().mockResolvedValue({});
Object.assign(
scheduler,
kind === 'deadline'
? { processDueBidRoundDeadlines: work }
: { processDueDurabilityPayloads: work },
);
const internal = scheduler as unknown as { safeTick(): Promise<void> };
await internal.safeTick();
await internal.safeTick();
expect(work).toHaveBeenCalledTimes(2);
},
);
@@ -0,0 +1,223 @@
import { AuctionRedisService } from './redis/auction-redis.service';
import { AuctionDeadlineScheduler } from './auction-deadline.scheduler';
import { AuctionRedisCommandService } from './redis/auction-redis-command.service';
import { AuctionService } from './auction.service';
import { AuctionEventBusService } from './auction-event-bus.service';
function makeScheduler(params: {
dueReply?: unknown;
leaderLockAcquired?: boolean;
expireReply?: unknown;
completedState?: unknown;
currentRedisTimestampMS?: number;
}) {
const sendCommand = jest.fn().mockResolvedValue(params.dueReply ?? []);
const redis = {
acquireTokenLock: jest
.fn()
.mockResolvedValue(params.leaderLockAcquired ?? true),
getCurrentRedisTimestampMS: jest
.fn()
.mockResolvedValue(params.currentRedisTimestampMS ?? 1000),
releaseTokenLock: jest.fn().mockResolvedValue(true),
raw: jest.fn().mockReturnValue({ sendCommand }),
} as unknown as jest.Mocked<AuctionRedisService>;
const redisCommand = {
expirePrepare: jest.fn().mockResolvedValue(
params.expireReply ?? {
auctionStateTransitionId: 'expire-1',
bidRoundExpiryDecision: 'passed',
currentServerTimestampMS: 1000,
ok: true,
revision: 2,
},
),
} as unknown as jest.Mocked<AuctionRedisCommandService>;
const auctionService = {
completePreparedExpiry: jest
.fn()
.mockResolvedValue(params.completedState ?? { phase: 'passed' }),
} as unknown as jest.Mocked<AuctionService>;
const eventBus = {
broadcastState: jest.fn(),
} as unknown as jest.Mocked<AuctionEventBusService>;
return {
auctionService,
eventBus,
redis,
redisCommand,
scheduler: new AuctionDeadlineScheduler(
redis,
redisCommand,
auctionService,
eventBus,
),
sendCommand,
};
}
describe('AuctionDeadlineScheduler', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('starts and clears the deadline tick timer', () => {
const setIntervalSpy = jest.spyOn(global, 'setInterval');
const clearIntervalSpy = jest.spyOn(global, 'clearInterval');
const { scheduler } = makeScheduler({});
scheduler.onModuleInit();
scheduler.onModuleDestroy();
expect(setIntervalSpy).toHaveBeenCalledWith(expect.any(Function), 1000);
expect(clearIntervalSpy).toHaveBeenCalledTimes(1);
});
it('processes a deadline tick only while holding the Redis leader lock', async () => {
const { redis, scheduler } = makeScheduler({});
const processDueBidRoundDeadlinesSpy = jest
.spyOn(scheduler, 'processDueBidRoundDeadlines')
.mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 });
await (
scheduler as unknown as { safeTick: () => Promise<void> }
).safeTick();
const leaderLockToken = redis.acquireTokenLock.mock.calls[0]?.[1];
expect(redis.acquireTokenLock).toHaveBeenCalledWith(
'auction:bidRoundDeadlineScheduler:leader',
expect.any(String),
2500,
);
expect(processDueBidRoundDeadlinesSpy).toHaveBeenCalledWith(20);
expect(redis.releaseTokenLock).toHaveBeenCalledWith(
'auction:bidRoundDeadlineScheduler:leader',
leaderLockToken,
);
});
it('skips deadline tick work when another instance holds the leader lock', async () => {
const { redis, scheduler } = makeScheduler({ leaderLockAcquired: false });
const processDueBidRoundDeadlinesSpy = jest
.spyOn(scheduler, 'processDueBidRoundDeadlines')
.mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 });
await (
scheduler as unknown as { safeTick: () => Promise<void> }
).safeTick();
expect(processDueBidRoundDeadlinesSpy).not.toHaveBeenCalled();
expect(redis.releaseTokenLock).not.toHaveBeenCalled();
});
it('reads due match ids from the Redis deadline queue with a batch limit', async () => {
const { redis, scheduler } = makeScheduler({
dueReply: ['match-1', 'match-2'],
});
await expect(scheduler.readDueMatchIds(1_000, 2)).resolves.toEqual([
'match-1',
'match-2',
]);
expect(redis.raw().sendCommand).toHaveBeenCalledWith([
'ZRANGEBYSCORE',
'auction:bidRoundDeadlineQueue',
'-inf',
'1000',
'LIMIT',
'0',
'2',
]);
});
it('prepares and completes due auction deadlines', async () => {
const matchId = '665f2f01f1f1f1f1f1f1f1f1';
const completedState = { phase: 'passed', revision: 3 };
const { auctionService, eventBus, redisCommand, scheduler } = makeScheduler(
{
dueReply: [matchId],
completedState,
},
);
await expect(scheduler.processDueBidRoundDeadlines(10)).resolves.toEqual({
completed: 1,
prepared: 1,
skipped: 0,
});
expect(redisCommand.expirePrepare).toHaveBeenCalledWith(
matchId,
expect.objectContaining({
bidRoundExpiryRetryDelayMS: 3000,
matchId,
}),
);
expect(auctionService.completePreparedExpiry).toHaveBeenCalledTimes(1);
// 만료 확정 결과는 즉시 1차 broadcast돼야 한다(클라가 입찰 라운드에 멈춰
// 후속 액션에서 CONFLICT가 반복되는 것을 막는 핵심 동작).
expect(eventBus.broadcastState).toHaveBeenCalledWith(
matchId,
completedState,
);
});
it('skips noop expiry preparations', async () => {
const { auctionService, eventBus, scheduler } = makeScheduler({
dueReply: ['665f2f01f1f1f1f1f1f1f1f1'],
expireReply: {
code: 'NOT_DUE',
currentServerTimestampMS: 1000,
noop: true,
},
});
await expect(scheduler.processDueBidRoundDeadlines(10)).resolves.toEqual({
completed: 0,
prepared: 0,
skipped: 1,
});
expect(auctionService.completePreparedExpiry).not.toHaveBeenCalled();
expect(eventBus.broadcastState).not.toHaveBeenCalled();
});
it('removes invalid deadline queue members', async () => {
const { scheduler, sendCommand } = makeScheduler({
dueReply: ['not-a-match-id'],
});
await expect(scheduler.processDueBidRoundDeadlines(10)).resolves.toEqual({
completed: 0,
prepared: 0,
skipped: 1,
});
expect(sendCommand).toHaveBeenLastCalledWith([
'ZREM',
'auction:bidRoundDeadlineQueue',
'not-a-match-id',
]);
});
it('continues processing later deadline items after one item fails', async () => {
const matchIds = ['665f2f01f1f1f1f1f1f1f1f1', '665f2f02f1f1f1f1f1f1f1f1'];
const { auctionService, redisCommand, scheduler } = makeScheduler({
dueReply: matchIds,
});
redisCommand.expirePrepare
.mockRejectedValueOnce(new Error('temporary redis error'))
.mockResolvedValueOnce({
auctionStateTransitionId: 'expire-2',
bidRoundExpiryDecision: 'passed',
currentServerTimestampMS: 1000,
ok: true,
revision: 3,
});
await expect(scheduler.processDueBidRoundDeadlines(10)).resolves.toEqual({
completed: 1,
prepared: 1,
skipped: 1,
});
expect(redisCommand.expirePrepare).toHaveBeenCalledTimes(2);
expect(auctionService.completePreparedExpiry).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,192 @@
import {
Injectable,
Logger,
OnModuleDestroy,
OnModuleInit,
} from '@nestjs/common';
import { randomUUID } from 'crypto';
import mongoose from 'mongoose';
import { AuctionService } from './auction.service';
import { AuctionEventBusService } from './auction-event-bus.service';
import { AuctionRedisCommandService } from './redis/auction-redis-command.service';
import { AuctionRedisService } from './redis/auction-redis.service';
const BID_ROUND_DEADLINE_QUEUE_KEY = 'auction:bidRoundDeadlineQueue';
const BID_ROUND_EXPIRY_RETRY_DELAY_MS = 3000;
const BID_ROUND_DEADLINE_TICK_INTERVAL_MS = 1000;
const BID_ROUND_DEADLINE_BATCH_LIMIT = 20;
const BID_ROUND_DEADLINE_LEADER_LOCK_KEY =
'auction:bidRoundDeadlineScheduler:leader';
const BID_ROUND_DEADLINE_LEADER_LOCK_TTL_MS = 2500;
/**
* 입찰 라운드 마감(deadline)을 감시해 자동으로 만료시키는 단일 리더 스위퍼.
*
* 만료는 2단계로 처리한다(정확히-1회 + 노드 크래시 복구를 위해):
* 1) EXPIRE_PREPARE Lua: `bidding → expiring`으로 flip하고 만료 결정/컨텍스트를
* `liveAuctionState`에 고정 + deadline ZSET에 재시도 점수 재등록.
* 2) `completePreparedExpiry`: 고정된 컨텍스트로 APPLY_TRANSITION을 돌려
* `sold`/`passed`로 확정하고 Mongo durability outbox를 enqueue.
*
* 중요(브로드캐스트 책임):
* - 관리자 수동 전환(sold/next 등)은 게이트웨이가 응답 직후 동기로 `state`를
* broadcast하지만, 자동 만료는 게이트웨이를 거치지 않는다.
* - 따라서 만료 확정 결과를 클라이언트에 즉시 알리는 1차 전달 책임은 이 스위퍼에
* 있다. 여기서 broadcast하지 않으면 클라는 입찰 라운드 revision에 멈춰 있다가
* "다음" 등 후속 액션에서 stale 관측값으로 CONFLICT를 반복하게 된다.
* - `AuctionDurabilityScheduler`의 broadcast는 Mongo 영속화 성공에 묶인 ~1초 주기의
* "노드 크래시 복구용 백업"이지 1차 전달 경로가 아니다(중복 emit돼도 클라
* revision 가드로 무해).
*
* 멀티 인스턴스: 리더 락을 잡은 한 인스턴스만 만료를 처리/방송하고, socket.io Redis
* adapter가 전 인스턴스 소켓으로 fanout한다.
*/
@Injectable()
export class AuctionDeadlineScheduler implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(AuctionDeadlineScheduler.name);
private tickTimer?: NodeJS.Timeout;
private tickInProgress = false;
constructor(
private readonly auctionRedisService: AuctionRedisService,
private readonly auctionRedisCommandService: AuctionRedisCommandService,
private readonly auctionService: AuctionService,
// 만료 확정 결과를 클라이언트에 즉시 알리기 위한 1차 broadcast 채널.
private readonly auctionEventBusService: AuctionEventBusService,
) {}
public onModuleInit(): void {
this.tickTimer = setInterval(
() => void this.safeTick(),
BID_ROUND_DEADLINE_TICK_INTERVAL_MS,
);
this.tickTimer.unref?.();
}
public onModuleDestroy(): void {
if (this.tickTimer) clearInterval(this.tickTimer);
}
private async safeTick(): Promise<void> {
if (this.tickInProgress) return;
this.tickInProgress = true;
const leaderLockToken = randomUUID();
let leaderLockAcquired = false;
try {
leaderLockAcquired = await this.auctionRedisService.acquireTokenLock(
BID_ROUND_DEADLINE_LEADER_LOCK_KEY,
leaderLockToken,
BID_ROUND_DEADLINE_LEADER_LOCK_TTL_MS,
);
if (!leaderLockAcquired) return;
await this.processDueBidRoundDeadlines(BID_ROUND_DEADLINE_BATCH_LIMIT);
} catch (error) {
this.logger.warn(
`Auction deadline tick failed: ${
error instanceof Error ? error.message : error
}`,
);
} finally {
if (leaderLockAcquired) {
await this.auctionRedisService
.releaseTokenLock(BID_ROUND_DEADLINE_LEADER_LOCK_KEY, leaderLockToken)
.catch((error: unknown) => {
this.logger.warn(
`Auction deadline lock release failed: ${String(error)}`,
);
});
}
this.tickInProgress = false;
}
}
public async readDueMatchIds(
currentRedisTimestampMS: number,
batchLimit: number,
): Promise<string[]> {
const reply = await this.auctionRedisService
.raw()
.sendCommand([
'ZRANGEBYSCORE',
BID_ROUND_DEADLINE_QUEUE_KEY,
'-inf',
String(currentRedisTimestampMS),
'LIMIT',
'0',
String(batchLimit),
]);
return Array.isArray(reply) ? reply.map(String) : [];
}
public async processDueBidRoundDeadlines(batchLimit: number): Promise<{
completed: number;
prepared: number;
skipped: number;
}> {
const currentRedisTimestampMS =
await this.auctionRedisService.getCurrentRedisTimestampMS();
const matchIds = await this.readDueMatchIds(
currentRedisTimestampMS,
batchLimit,
);
let prepared = 0;
let completed = 0;
let skipped = 0;
for (const matchId of matchIds) {
if (!mongoose.isValidObjectId(matchId)) {
skipped += 1;
await this.removeBidRoundDeadlineQueueEntry(matchId);
continue;
}
try {
// 1단계: 만료 결정/컨텍스트 고정(bidding → expiring). 아직 마감 전이거나
// 이미 다른 phase면 noop으로 빠진다(stale ZSET 엔트리는 Lua가 정리).
const result = await this.auctionRedisCommandService.expirePrepare(
matchId,
{
auctionStateTransitionId: `expire:${matchId}:${randomUUID()}`,
bidRoundExpiryRetryDelayMS: BID_ROUND_EXPIRY_RETRY_DELAY_MS,
matchId,
},
);
if ('noop' in result) {
skipped += 1;
continue;
}
prepared += 1;
// 2단계: 고정된 컨텍스트로 sold/passed 확정. 재진입(다른 인스턴스/다음 틱)해도
// appliedAuctionStateTransitionIds dedupe로 정확히-1회만 반영된다.
const completedState = await this.auctionService.completePreparedExpiry(
new mongoose.Types.ObjectId(matchId),
);
if (completedState) {
completed += 1;
// 1차 전달: 만료 확정 즉시 최신 state를 방송한다. 이게 없으면 클라가
// 입찰 라운드에 멈춰 후속 액션에서 CONFLICT가 반복된다(durability
// worker 백업 방송은 Mongo 성공 + ~1초 tick에 묶여 1차 전달로 부적합).
// 이미 처리된 전환은 completePreparedExpiry가 null을 반환하므로 중복
// 방송되지 않고, 혹시 겹쳐도 클라 revision 가드로 무해하다.
this.auctionEventBusService.broadcastState(matchId, completedState);
}
} catch (error) {
skipped += 1;
this.logger.warn(
`Auction deadline item failed for ${matchId}: ${
error instanceof Error ? error.message : error
}`,
);
}
}
return { completed, prepared, skipped };
}
private async removeBidRoundDeadlineQueueEntry(
matchId: string,
): Promise<void> {
await this.auctionRedisService
.raw()
.sendCommand(['ZREM', BID_ROUND_DEADLINE_QUEUE_KEY, matchId]);
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,38 @@
import { Injectable } from '@nestjs/common';
import type { Namespace } from 'socket.io';
import type { AuctionHistoryUpdatedEvent } from '@lolympus/contracts';
import type { AuctionStateResponse } from './auction.service';
import type { MatchSideEffectDelta } from './auction-side-effect.service';
import { serializeRealtimeAuction } from './auction-realtime-serializer';
@Injectable()
export class AuctionEventBusService {
private auctionNamespace?: Namespace;
public attachAuctionNamespace(namespace: Namespace): void {
this.auctionNamespace = namespace;
}
public broadcastMatchSideEffect(
matchId: string,
delta: MatchSideEffectDelta,
): void {
this.auctionNamespace?.to(matchId).emit('match-side-effect', delta);
}
public broadcastState(matchId: string, state: AuctionStateResponse): void {
this.auctionNamespace
?.to(matchId)
.emit('state', serializeRealtimeAuction(state));
}
public broadcastHistoryUpdated(event: AuctionHistoryUpdatedEvent): void {
this.auctionNamespace?.to(event.matchId).emit('history-updated', event);
}
public broadcastReset(matchId: string, auctionLifecycleId: string): void {
this.auctionNamespace
?.to(matchId)
.emit('reset', { matchId, auctionLifecycleId });
}
}
@@ -0,0 +1,32 @@
import { AuctionLifecycleLock } from './auction-lifecycle-lock';
afterEach(() => jest.useRealTimers());
it('renews ownership and handles renewal/release failures without unhandled rejection', async () => {
jest.useFakeTimers();
const sendCommand = jest
.fn()
.mockRejectedValue(new Error('redis disconnected'));
const releaseTokenLock = jest
.fn()
.mockRejectedValue(new Error('release failed'));
const lock = new AuctionLifecycleLock({
acquireTokenLock: jest.fn().mockResolvedValue(true),
releaseTokenLock,
raw: () => ({ sendCommand }),
} as never);
const result = lock.run('match', async () => {
await jest.advanceTimersByTimeAsync(10000);
});
await expect(result).rejects.toThrow('redis disconnected');
expect(releaseTokenLock).toHaveBeenCalledTimes(1);
expect(jest.getTimerCount()).toBe(0);
});
it('preserves an operation result if only lock release fails', async () => {
const lock = new AuctionLifecycleLock({
acquireTokenLock: jest.fn().mockResolvedValue(true),
releaseTokenLock: jest.fn().mockRejectedValue(new Error('release failed')),
} as never);
await expect(lock.run('match', async () => 42)).resolves.toBe(42);
});
@@ -0,0 +1,72 @@
import { ConflictException, Logger } from '@nestjs/common';
import { randomUUID } from 'crypto';
import { AuctionRedisService } from './redis/auction-redis.service';
export class AuctionLifecycleBusyError extends ConflictException {
constructor() {
super({
code: 'AUCTION_LIFECYCLE_BUSY',
message: '다른 경매 작업을 처리 중입니다. 잠시 후 다시 시도해 주세요.',
});
}
}
/** Serializes startup, cancellation, undo and Match side effects across nodes. */
export class AuctionLifecycleLock {
private readonly logger = new Logger(AuctionLifecycleLock.name);
constructor(private readonly redis: AuctionRedisService) {}
async run<T>(matchId: string, operation: () => Promise<T>): Promise<T> {
// Kept outside runtime cleanup: cancelling an auction must not release a
// lock still held by its cancellation/recovery operation.
const key = `auction:${matchId}:lifecycleMutationLock`;
const token = randomUUID();
if (!(await this.redis.acquireTokenLock(key, token, 30_000))) {
throw new AuctionLifecycleBusyError();
}
let renewal: Promise<void> | undefined;
let ownershipError: Error | undefined;
const timer = setInterval(() => {
if (renewal) return;
renewal = this.redis
.raw()
.sendCommand<string | null>([
'SET',
key,
token,
'IFEQ',
token,
'PX',
'30000',
])
.then((result) => {
if (result !== 'OK')
throw new Error('Auction lifecycle lock ownership was lost.');
})
.catch((error: unknown) => {
ownershipError =
error instanceof Error ? error : new Error(String(error));
})
.finally(() => {
renewal = undefined;
});
}, 10_000);
timer.unref?.();
try {
const result = await operation();
clearInterval(timer);
await renewal;
if (ownershipError) throw ownershipError;
return result;
} finally {
clearInterval(timer);
await renewal;
await this.redis.releaseTokenLock(key, token).catch((error: unknown) => {
this.logger.warn(
`Auction lifecycle lock release failed: ${String(error)}`,
);
});
}
}
}
@@ -0,0 +1,20 @@
/** Missing optional fields in a complete projection mean deletion, not retention. */
export const AUCTION_OPTIONAL_PROJECTION_FIELDS = [
'completedAt',
'auctionCompletedAtTimestampMS',
'currentBidderTeamIndex',
'currentHighestBidderTeamIndex',
'currentDeadline',
'currentBidRoundDeadlineTimestampMS',
'currentBidRoundId',
] as const;
export function buildAuctionProjectionUnset(
projection: Record<string, unknown>,
) {
return Object.fromEntries(
AUCTION_OPTIONAL_PROJECTION_FIELDS.filter(
(field) => projection[field] === undefined,
).map((field) => [field, '']),
);
}
@@ -0,0 +1,101 @@
import type { AuctionStateResponse } from './auction.service';
export function serializeRealtimeAuction(auction: AuctionStateResponse) {
const serialized = JSON.parse(JSON.stringify(auction)) as Record<
string,
unknown
>;
const auctionPlayerOrder = getRecordArray(
serialized.auctionPlayerOrder ?? serialized.order,
);
const currentAuctionPlayerOrderIndex = Number(
serialized.currentAuctionPlayerOrderIndex ?? serialized.currentIndex ?? 0,
);
const currentBidRoundPlayerUserId =
typeof serialized.currentBidRoundPlayerUserId === 'string'
? serialized.currentBidRoundPlayerUserId
: getStringField(
auctionPlayerOrder[currentAuctionPlayerOrderIndex],
'userId',
);
if (Array.isArray(serialized.auctionPlayerOrder)) {
serialized.auctionPlayerOrder = auctionPlayerOrder.map((player) =>
serializeRealtimeAuctionPlayer(player, currentBidRoundPlayerUserId),
);
} else if (Array.isArray(serialized.order)) {
serialized.order = auctionPlayerOrder.map((player) =>
serializeRealtimeAuctionPlayer(player, currentBidRoundPlayerUserId),
);
}
const passedAuctionPlayerQueue = getRecordArray(
serialized.passedAuctionPlayerQueue ?? serialized.passedQueue,
);
if (Array.isArray(serialized.passedAuctionPlayerQueue)) {
serialized.passedAuctionPlayerQueue = passedAuctionPlayerQueue.map(
(player) =>
serializeRealtimeAuctionPlayer(player, currentBidRoundPlayerUserId),
);
} else if (Array.isArray(serialized.passedQueue)) {
serialized.passedQueue = passedAuctionPlayerQueue.map((player) =>
serializeRealtimeAuctionPlayer(player, currentBidRoundPlayerUserId),
);
}
if ('auctionPlayerOrder' in serialized) delete serialized.order;
if ('auctionTeams' in serialized) delete serialized.teams;
if ('passedAuctionPlayerQueue' in serialized) delete serialized.passedQueue;
if ('auctionBidHistory' in serialized) delete serialized.bids;
if ('maximumBidRoundDurationSeconds' in serialized) {
delete serialized.maxTimerSeconds;
}
if ('bidRoundExtensionSeconds' in serialized) {
delete serialized.bidExtensionSeconds;
}
if ('initialTeamBidPointAmount' in serialized) {
delete serialized.initialPoints;
}
if ('topTierAuctionPriorityThreshold' in serialized) {
delete serialized.topTierThreshold;
}
if ('manualTopTierAuctionPriorityUserIds' in serialized) {
delete serialized.manualTopTierUserIds;
}
return serialized;
}
function serializeRealtimeAuctionPlayer(
player: Record<string, unknown>,
currentBidRoundPlayerUserId?: string,
) {
if (getStringField(player, 'userId') === currentBidRoundPlayerUserId) {
return player;
}
const lightweightPlayer = { ...player };
delete lightweightPlayer.masteries;
delete lightweightPlayer.puuid;
delete lightweightPlayer.recentStatsSummary;
delete lightweightPlayer.tierHistory;
return lightweightPlayer;
}
function getRecordArray(value: unknown): Array<Record<string, unknown>> {
return Array.isArray(value)
? value.filter(
(item): item is Record<string, unknown> =>
typeof item === 'object' && item !== null,
)
: [];
}
function getStringField(
value: Record<string, unknown> | undefined,
fieldName: string,
): string | undefined {
const fieldValue = value?.[fieldName];
return typeof fieldValue === 'string' ? fieldValue : undefined;
}
@@ -0,0 +1,99 @@
import {
AUCTION_REJECTION_REASON,
isAuctionResyncRecommended,
resolveAuctionRejectionReason,
} from './auction-rejection';
describe('resolveAuctionRejectionReason', () => {
it('distinguishes an outdated client from a stale round and does not suggest a state-only resync', () => {
const reason = resolveAuctionRejectionReason('BID_CLIENT_UPDATE_REQUIRED');
expect(reason).toBe('BID_REJECTED_BECAUSE_CLIENT_UPDATE_REQUIRED');
expect(isAuctionResyncRecommended(reason)).toBe(false);
});
it('reports roster validation failures without recommending a retry', () => {
const reason = resolveAuctionRejectionReason(
'AUCTION_ROSTER_INVALID',
'Auction roster validation failed.',
);
expect(reason).toBe('AUCTION_TRANSITION_REJECTED_BECAUSE_ROSTER_INVALID');
expect(isAuctionResyncRecommended(reason)).toBe(false);
});
it('maps the internal CONFLICT code to the descriptive transition reason', () => {
expect(resolveAuctionRejectionReason('CONFLICT')).toBe(
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_LIVE_STATE_CHANGED_BEFORE_APPLY,
);
});
it('maps internal bid codes to descriptive bid reasons', () => {
expect(resolveAuctionRejectionReason('EXPIRED')).toBe(
AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_BID_ROUND_DEADLINE_PASSED,
);
expect(resolveAuctionRejectionReason('TOO_LOW')).toBe(
AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_AMOUNT_NOT_HIGHER_THAN_CURRENT_HIGHEST,
);
});
it('maps known BadRequest messages without a structured code', () => {
expect(
resolveAuctionRejectionReason(
undefined,
'Cannot advance from current phase.',
),
).toBe(
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE,
);
});
it('falls back via the message when the code carries the full sentence', () => {
// 구조 전환 경로는 code 자리에 message 문장이 들어올 수 있다.
expect(
resolveAuctionRejectionReason('Auction is not in bidding phase.'),
).toBe(
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE,
);
});
it('treats internal coordination codes as retryable', () => {
expect(resolveAuctionRejectionReason('ACTION_REQUEST_LEASE_EXPIRED')).toBe(
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_REQUEST_COORDINATION_RETRYABLE,
);
expect(resolveAuctionRejectionReason('INVALID_DEADLINE_MODE')).toBe(
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_REQUEST_COORDINATION_RETRYABLE,
);
});
it('falls back to the unrecognized reason for unknown input', () => {
expect(resolveAuctionRejectionReason('SOMETHING_NEW', 'weird')).toBe(
AUCTION_REJECTION_REASON.AUCTION_REQUEST_REJECTED_FOR_UNRECOGNIZED_REASON,
);
});
});
describe('isAuctionResyncRecommended', () => {
it('recommends resync for stale-view rejections', () => {
expect(
isAuctionResyncRecommended(
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_LIVE_STATE_CHANGED_BEFORE_APPLY,
),
).toBe(true);
expect(
isAuctionResyncRecommended(
AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_BID_ROUND_DEADLINE_PASSED,
),
).toBe(true);
});
it('does not recommend resync for genuine constraint rejections', () => {
expect(
isAuctionResyncRecommended(
AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_TEAM_ROSTER_FULL,
),
).toBe(false);
expect(
isAuctionResyncRecommended(
AUCTION_REJECTION_REASON.AUCTION_REQUEST_REJECTED_FOR_UNRECOGNIZED_REASON,
),
).toBe(false);
});
});
@@ -0,0 +1,179 @@
/**
* 경매 거부(rejection)를 클라이언트에 알릴 때 쓰는 "설명적 거부코드" 체계.
*
* 배경:
* - 내부 Lua/서비스는 `CONFLICT`, `EXPIRED`, `TOO_LOW` 같은 짧은 코드를 쓴다.
* 이 코드들은 구현 디테일이고, 그대로 클라/운영자에게 노출하면 "무엇이 왜
* 거부됐는지"를 알기 어렵다(특히 `CONFLICT`는 원인이 광범위하다).
* - 그래서 ack의 `code`/`message`는 그대로 두되(진단/하위호환), 별도로
* `auctionRejectionReason`이라는 **맥락을 코드 이름에 담은 안정적 식별자**를
* 함께 내려준다. 클라는 이 reason을 사람이 읽는 문구로 매핑한다(프론트 사전).
*
* 명명 규칙:
* - 다소 길어지더라도 "무엇이(BID/AUCTION_TRANSITION) + 왜(BECAUSE_...)"를
* 이름만으로 알 수 있게 풀어쓴다.
*
* resync 권장 여부:
* - `AUCTION_RESYNC_RECOMMENDED_REASONS`에 속한 reason은 "클라가 본 상태가 이미
* 바뀌었다(낙관적 동시성 충돌/만료/단계 전이)"는 신호다. 이 경우 클라는 최신
* state로 rebaseline한다. 구조 액션 재시도는 원래 대상과 단계가 같을 때만 허용한다.
* - 반대로 정원 초과/포인트 부족처럼 "상태를 새로고침해도 결과가 같은" 거부는
* resync 권장 대상이 아니다(재시도해도 또 거부됨).
*/
export const AUCTION_REJECTION_REASON = {
// === 구조 전환(낙찰/유찰/다음/입찰오픈) ===
/** 내가 본 revision/phase/선수가 commit 직전 이미 바뀜(낙관적 동시성 충돌, 내부 `CONFLICT`). */
AUCTION_TRANSITION_REJECTED_BECAUSE_LIVE_STATE_CHANGED_BEFORE_APPLY:
'AUCTION_TRANSITION_REJECTED_BECAUSE_LIVE_STATE_CHANGED_BEFORE_APPLY',
/** 입찰 단계가 아닌데 입찰 단계 전환을 시도함(이미 sold/passed/presenting 등). */
AUCTION_TRANSITION_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE:
'AUCTION_TRANSITION_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE',
/** 낙찰 또는 유찰이 확정되지 않아 다음 선수로 진행할 수 없음. */
AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE:
'AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE',
/** 원 참가자 명단과 실제 팀 배정이 일치하지 않아 완료할 수 없음. */
AUCTION_TRANSITION_REJECTED_BECAUSE_ROSTER_INVALID:
'AUCTION_TRANSITION_REJECTED_BECAUSE_ROSTER_INVALID',
/** 낙찰 처리할 유효한 최고 입찰이 없음(만료 처리로 이미 정리됐을 수 있음). */
AUCTION_TRANSITION_REJECTED_BECAUSE_NO_WINNING_BID_TO_MARK_SOLD:
'AUCTION_TRANSITION_REJECTED_BECAUSE_NO_WINNING_BID_TO_MARK_SOLD',
/** 진행 중인 입찰이 있는 선수를 유찰 처리하려 함. */
AUCTION_TRANSITION_REJECTED_BECAUSE_ACTIVE_BID_PRESENT:
'AUCTION_TRANSITION_REJECTED_BECAUSE_ACTIVE_BID_PRESENT',
/** 전환 요청 조정(예약/리스/멱등) 단계의 일시적 거부 — 최신 상태로 재시도하면 보통 해소됨. */
AUCTION_TRANSITION_REJECTED_BECAUSE_REQUEST_COORDINATION_RETRYABLE:
'AUCTION_TRANSITION_REJECTED_BECAUSE_REQUEST_COORDINATION_RETRYABLE',
// === 입찰(bid) ===
BID_REJECTED_BECAUSE_CLIENT_UPDATE_REQUIRED:
'BID_REJECTED_BECAUSE_CLIENT_UPDATE_REQUIRED',
/** 입찰 라운드가 이미 다음 선수/다음 라운드로 넘어감(내부 `STALE_BID_ROUND`). */
BID_REJECTED_BECAUSE_BID_ROUND_ALREADY_ADVANCED:
'BID_REJECTED_BECAUSE_BID_ROUND_ALREADY_ADVANCED',
/** 입찰 라운드 마감 시각이 이미 지남(내부 `EXPIRED`). */
BID_REJECTED_BECAUSE_BID_ROUND_DEADLINE_PASSED:
'BID_REJECTED_BECAUSE_BID_ROUND_DEADLINE_PASSED',
/** 경매가 입찰 단계가 아님(내부 `PHASE`). */
BID_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE:
'BID_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE',
/** 입찰 금액이 현재 최고가보다 높지 않음(내부 `TOO_LOW`). */
BID_REJECTED_BECAUSE_AMOUNT_NOT_HIGHER_THAN_CURRENT_HIGHEST:
'BID_REJECTED_BECAUSE_AMOUNT_NOT_HIGHER_THAN_CURRENT_HIGHEST',
/** 팀 정원이 이미 가득 참(내부 `FULL`). */
BID_REJECTED_BECAUSE_TEAM_ROSTER_FULL:
'BID_REJECTED_BECAUSE_TEAM_ROSTER_FULL',
/** 남은 슬롯 최소 확보분을 고려하면 포인트가 부족함(내부 `INSUFFICIENT`). */
BID_REJECTED_BECAUSE_INSUFFICIENT_REMAINING_POINTS_FOR_SLOTS:
'BID_REJECTED_BECAUSE_INSUFFICIENT_REMAINING_POINTS_FOR_SLOTS',
/** 알 수 없는 팀 인덱스(내부 `UNKNOWN_TEAM`). */
BID_REJECTED_BECAUSE_UNKNOWN_TEAM: 'BID_REJECTED_BECAUSE_UNKNOWN_TEAM',
/** 같은 요청 id에 다른 내용이 온 멱등성 충돌(내부 `DUPLICATE_REQUEST_CONFLICT`). */
BID_REJECTED_BECAUSE_DUPLICATE_REQUEST_PAYLOAD_CONFLICT:
'BID_REJECTED_BECAUSE_DUPLICATE_REQUEST_PAYLOAD_CONFLICT',
/** 짧은 시간에 너무 많은 입찰 요청(게이트웨이 rate limit). */
BID_REJECTED_BECAUSE_RATE_LIMITED: 'BID_REJECTED_BECAUSE_RATE_LIMITED',
// === 공통/그 외 ===
/** 실시간 상태를 아직 사용할 수 없음(재접속/재조회 필요). */
AUCTION_REQUEST_REJECTED_BECAUSE_REALTIME_STATE_UNAVAILABLE:
'AUCTION_REQUEST_REJECTED_BECAUSE_REALTIME_STATE_UNAVAILABLE',
/** 위 어디에도 해당하지 않는 미분류 거부(원문 message로 안내). */
AUCTION_REQUEST_REJECTED_FOR_UNRECOGNIZED_REASON:
'AUCTION_REQUEST_REJECTED_FOR_UNRECOGNIZED_REASON',
} as const;
export type AuctionRejectionReason =
(typeof AUCTION_REJECTION_REASON)[keyof typeof AUCTION_REJECTION_REASON];
/** 내부 짧은 코드 → 설명적 reason. */
const INTERNAL_CODE_TO_REASON: Record<string, AuctionRejectionReason> = {
BID_CLIENT_UPDATE_REQUIRED:
AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_CLIENT_UPDATE_REQUIRED,
AUCTION_ROSTER_INVALID:
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_ROSTER_INVALID,
CONFLICT:
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_LIVE_STATE_CHANGED_BEFORE_APPLY,
STALE_BID_ROUND:
AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_BID_ROUND_ALREADY_ADVANCED,
EXPIRED:
AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_BID_ROUND_DEADLINE_PASSED,
PHASE:
AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE,
TOO_LOW:
AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_AMOUNT_NOT_HIGHER_THAN_CURRENT_HIGHEST,
FULL: AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_TEAM_ROSTER_FULL,
INSUFFICIENT:
AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_INSUFFICIENT_REMAINING_POINTS_FOR_SLOTS,
UNKNOWN_TEAM: AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_UNKNOWN_TEAM,
DUPLICATE_REQUEST_CONFLICT:
AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_DUPLICATE_REQUEST_PAYLOAD_CONFLICT,
BID_RATE_LIMITED: AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_RATE_LIMITED,
};
/** 구조화된 code 없이 message만 던지는 BadRequest(구조 전환 검증 등) → 설명적 reason. */
const MESSAGE_TO_REASON: Record<string, AuctionRejectionReason> = {
'Auction is not in bidding phase.':
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE,
'Cannot advance from current phase.':
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE,
'No bid to mark sold.':
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_NO_WINNING_BID_TO_MARK_SOLD,
'Cannot pass a player with an active bid.':
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_ACTIVE_BID_PRESENT,
'Auction realtime state is not available.':
AUCTION_REJECTION_REASON.AUCTION_REQUEST_REJECTED_BECAUSE_REALTIME_STATE_UNAVAILABLE,
};
/**
* resync(최신 state로 rebaseline 후 재시도)가 권장되는 reason 집합.
* "내가 본 상태가 낡았을 뿐, 다시 보면 가능할 수 있는" 거부들이다.
*/
export const AUCTION_RESYNC_RECOMMENDED_REASONS: ReadonlySet<AuctionRejectionReason> =
new Set<AuctionRejectionReason>([
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_LIVE_STATE_CHANGED_BEFORE_APPLY,
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE,
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE,
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_NO_WINNING_BID_TO_MARK_SOLD,
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_ACTIVE_BID_PRESENT,
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_REQUEST_COORDINATION_RETRYABLE,
AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_BID_ROUND_ALREADY_ADVANCED,
AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_BID_ROUND_DEADLINE_PASSED,
AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE,
AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_AMOUNT_NOT_HIGHER_THAN_CURRENT_HIGHEST,
AUCTION_REJECTION_REASON.AUCTION_REQUEST_REJECTED_BECAUSE_REALTIME_STATE_UNAVAILABLE,
]);
/**
* 내부 거부 code(짧은 코드) 또는 BadRequest message로부터 설명적 reason을 해석한다.
* 둘 다 모르면 미분류 reason으로 떨어뜨린다(원문 message는 ack에 그대로 남는다).
*/
export function resolveAuctionRejectionReason(
internalCode?: string,
message?: string,
): AuctionRejectionReason {
if (internalCode && INTERNAL_CODE_TO_REASON[internalCode]) {
return INTERNAL_CODE_TO_REASON[internalCode];
}
if (message && MESSAGE_TO_REASON[message]) {
return MESSAGE_TO_REASON[message];
}
// 구조 전환 경로는 code 자리에 message 문장이 들어올 수 있어 한 번 더 확인한다.
if (internalCode && MESSAGE_TO_REASON[internalCode]) {
return MESSAGE_TO_REASON[internalCode];
}
if (
internalCode &&
(internalCode.startsWith('ACTION_REQUEST_') ||
internalCode.startsWith('INVALID_'))
) {
return AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_REQUEST_COORDINATION_RETRYABLE;
}
return AUCTION_REJECTION_REASON.AUCTION_REQUEST_REJECTED_FOR_UNRECOGNIZED_REASON;
}
export function isAuctionResyncRecommended(
reason: AuctionRejectionReason,
): boolean {
return AUCTION_RESYNC_RECOMMENDED_REASONS.has(reason);
}
@@ -0,0 +1,102 @@
import {
AuctionSideEffectService,
buildMatchSideEffectDelta,
buildSideEffectApplicationIdentity,
buildSideEffectLeaseAcquireUpdate,
canAcquireSideEffectLease,
} from './auction-side-effect.service';
describe('auction side effect helpers', () => {
it('builds idempotency identity from transition and side effect type', () => {
expect(
buildSideEffectApplicationIdentity({
auctionId: 'auction-1',
auctionStateTransitionId: 'transition-1',
sideEffectType: 'syncMatchTeams',
}),
).toEqual({
auctionId: 'auction-1',
auctionStateTransitionId: 'transition-1',
sideEffectType: 'syncMatchTeams',
});
});
it('allows lease acquisition for pending, failed, or stale processing items only', () => {
expect(canAcquireSideEffectLease({ state: 'pending' }, 1000)).toBe(true);
expect(canAcquireSideEffectLease({ state: 'failed' }, 1000)).toBe(true);
expect(
canAcquireSideEffectLease(
{ processingLeaseExpiresAtTimestampMS: 999, state: 'processing' },
1000,
),
).toBe(true);
expect(
canAcquireSideEffectLease(
{ processingLeaseExpiresAtTimestampMS: 1001, state: 'processing' },
1000,
),
).toBe(false);
expect(canAcquireSideEffectLease({ state: 'completed' }, 1000)).toBe(false);
});
it('builds lease acquire update with Redis TIME timestamps', () => {
expect(
buildSideEffectLeaseAcquireUpdate({
currentRedisTimestampMS: 1000,
leaseDurationMS: 5000,
ownerToken: 'worker-1',
}),
).toEqual({
$inc: { attempts: 1 },
$set: {
processingLeaseExpiresAtTimestampMS: 6000,
processingOwnerToken: 'worker-1',
processingStartedAtTimestampMS: 1000,
state: 'processing',
},
});
});
it('builds side-effect socket delta independently from auction revision', () => {
expect(
buildMatchSideEffectDelta({
auctionLifecycleId: 'life-1',
currentServerTimestampMS: 1000,
matchSideEffectRevision: 3,
matchSideEffectStatus: 'completed',
}),
).toEqual({
auctionLifecycleId: 'life-1',
currentServerTimestampMS: 1000,
matchSideEffectRevision: 3,
matchSideEffectStatus: 'completed',
});
});
it('mirrors side-effect status into Redis live state with lifecycle and revision guard', async () => {
const sendCommand = jest.fn().mockResolvedValue(1);
const service = new AuctionSideEffectService({
raw: jest.fn().mockReturnValue({ sendCommand }),
} as never);
await expect(
service.mirrorMatchSideEffectStatus({
auctionLifecycleId: 'life-1',
matchId: 'match-1',
matchSideEffectRevision: 2,
matchSideEffectStatus: 'completed',
}),
).resolves.toBe(true);
expect(sendCommand).toHaveBeenCalledWith([
'EVAL',
expect.stringContaining('auctionLifecycleId'),
'1',
'auction:match-1:liveAuctionState',
'life-1',
'2',
'completed',
'',
]);
});
});
@@ -0,0 +1,119 @@
import { Injectable } from '@nestjs/common';
import type {
AuctionMatchSideEffectStatus,
AuctionSideEffectApplicationState,
} from '../global/database/schema';
import { buildAuctionRedisKeys } from './redis/auction-redis.keys';
import { AuctionRedisService } from './redis/auction-redis.service';
export interface SideEffectApplicationIdentity {
auctionId: unknown;
auctionStateTransitionId: string;
sideEffectType: string;
}
export interface SideEffectLeaseState {
processingLeaseExpiresAtTimestampMS?: number;
state: AuctionSideEffectApplicationState;
}
export interface BuildSideEffectLeaseAcquireUpdateParams {
currentRedisTimestampMS: number;
leaseDurationMS: number;
ownerToken: string;
}
export interface MatchSideEffectDelta {
auctionLifecycleId: string;
auctionStateTransitionId?: string;
currentServerTimestampMS: number;
matchSideEffectRevision: number;
matchSideEffectStatus: AuctionMatchSideEffectStatus;
}
@Injectable()
export class AuctionSideEffectService {
constructor(private readonly auctionRedisService: AuctionRedisService) {}
public async mirrorMatchSideEffectStatus(params: {
auctionLifecycleId: string;
auctionStateTransitionId?: string;
matchId: string;
matchSideEffectRevision: number;
matchSideEffectStatus: AuctionMatchSideEffectStatus;
}): Promise<boolean> {
const keys = buildAuctionRedisKeys(params.matchId);
const result = await this.auctionRedisService
.raw()
.sendCommand([
'EVAL',
[
"if redis.call('HGET', KEYS[1], 'auctionLifecycleId') ~= ARGV[1] then return 0 end",
"local generation = redis.call('HGET', KEYS[1], 'matchSideEffectTransitionId')",
"if ARGV[4] ~= '' and generation and generation ~= ARGV[4] then return 0 end",
"local currentRevision = tonumber(redis.call('HGET', KEYS[1], 'matchSideEffectRevision') or '-1')",
'local nextRevision = tonumber(ARGV[2])',
'if currentRevision >= nextRevision then return 0 end',
"redis.call('HSET', KEYS[1], 'matchSideEffectRevision', ARGV[2], 'matchSideEffectStatus', ARGV[3])",
'return 1',
].join('\n'),
'1',
keys.liveStateKey,
params.auctionLifecycleId,
String(params.matchSideEffectRevision),
params.matchSideEffectStatus,
params.auctionStateTransitionId ?? '',
]);
return Number(result) === 1;
}
}
export function buildSideEffectApplicationIdentity(
params: SideEffectApplicationIdentity,
): SideEffectApplicationIdentity {
return {
auctionId: params.auctionId,
auctionStateTransitionId: params.auctionStateTransitionId,
sideEffectType: params.sideEffectType,
};
}
export function canAcquireSideEffectLease(
state: SideEffectLeaseState,
currentRedisTimestampMS: number,
): boolean {
if (state.state === 'pending' || state.state === 'failed') return true;
if (state.state !== 'processing') return false;
return (
(state.processingLeaseExpiresAtTimestampMS ?? 0) <= currentRedisTimestampMS
);
}
export function buildSideEffectLeaseAcquireUpdate(
params: BuildSideEffectLeaseAcquireUpdateParams,
) {
return {
$inc: { attempts: 1 },
$set: {
processingLeaseExpiresAtTimestampMS:
params.currentRedisTimestampMS + params.leaseDurationMS,
processingOwnerToken: params.ownerToken,
processingStartedAtTimestampMS: params.currentRedisTimestampMS,
state: 'processing',
},
};
}
export function buildMatchSideEffectDelta(
params: MatchSideEffectDelta,
): MatchSideEffectDelta {
return {
auctionLifecycleId: params.auctionLifecycleId,
...(params.auctionStateTransitionId
? { auctionStateTransitionId: params.auctionStateTransitionId }
: {}),
currentServerTimestampMS: params.currentServerTimestampMS,
matchSideEffectRevision: params.matchSideEffectRevision,
matchSideEffectStatus: params.matchSideEffectStatus,
};
}
@@ -0,0 +1,101 @@
import 'reflect-metadata';
import mongoose from 'mongoose';
import { GUARDS_METADATA } from '@nestjs/common/constants';
import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from '../auth/allow-public-access.decorator';
import type { UserDocument } from '../global/database/schema';
jest.mock('../auth/jwt.service', () => ({
JwtService: class JwtService {},
}));
import { AuctionController } from './auction.controller';
describe('AuctionController bid authentication', () => {
beforeEach(() => {
jest.replaceProperty(process, 'env', { ...process.env });
delete process.env.AUCTION_REQUIRE_CAPTAIN_AUTH;
});
afterEach(() => jest.restoreAllMocks());
it('allows HTTP guests to reach the configurable bid checks', () => {
const handler = AuctionController.prototype.placeBid;
expect(
Reflect.getMetadata(METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, handler),
).toBe(true);
expect(Reflect.getMetadata(GUARDS_METADATA, handler)).toBeUndefined();
});
it.each([undefined, 'false', 'true'])(
'handles HTTP guests with captain auth=%s',
async (auth) => {
if (auth !== undefined) process.env.AUCTION_REQUIRE_CAPTAIN_AUTH = auth;
const placeBid = jest.fn().mockResolvedValue({ revision: 2 });
const controller = new AuctionController(
{ placeBid } as never,
{} as never,
{} as never,
);
const matchId = new mongoose.Types.ObjectId();
const result = controller.placeBid(
undefined,
new mongoose.Types.ObjectId(),
matchId,
{
bidderTeamIndex: 2,
bidPointAmount: 20,
},
);
if (auth === 'true') {
await expect(result).rejects.toThrow(
'팀장 계정으로 로그인해야 입찰할 수 있습니다.',
);
expect(placeBid).not.toHaveBeenCalled();
} else {
await expect(result).resolves.toEqual({ revision: 2 });
expect(placeBid).toHaveBeenCalledWith(
expect.objectContaining({
matchId,
teamIndex: 2,
amount: 20,
bidderUserId: undefined,
}),
);
}
},
);
it('passes the signed-in user to service checks and restores community validation in strict mode', async () => {
const placeBid = jest.fn().mockResolvedValue({ revision: 2 });
const controller = new AuctionController(
{ placeBid } as never,
{} as never,
{} as never,
);
const user = {
_id: new mongoose.Types.ObjectId(),
communityId: new mongoose.Types.ObjectId(),
} as UserDocument;
const matchId = new mongoose.Types.ObjectId();
const body = { bidderTeamIndex: 2, bidPointAmount: 20 };
await controller.placeBid(
user,
new mongoose.Types.ObjectId(),
matchId,
body,
);
expect(placeBid).toHaveBeenLastCalledWith(
expect.objectContaining({ bidderUserId: user._id }),
);
process.env.AUCTION_REQUIRE_CAPTAIN_AUTH = 'true';
await expect(
controller.placeBid(user, new mongoose.Types.ObjectId(), matchId, body),
).rejects.toThrow('Different community.');
expect(placeBid).toHaveBeenCalledTimes(1);
await expect(
controller.placeBid(user, user.communityId, matchId, body),
).resolves.toEqual({ revision: 2 });
expect(placeBid).toHaveBeenCalledTimes(2);
});
});
@@ -3,12 +3,14 @@ import {
Body,
Controller,
Delete,
ForbiddenException,
Get,
HttpCode,
HttpStatus,
Param,
Post,
UseGuards,
Query,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
@@ -18,9 +20,15 @@ import { RolesGuard } from '../auth/roles.guard';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import type { UserDocument } from '../global/database/schema';
import { AuctionService } from './auction.service';
import { isAuctionCaptainAuthRequired } from './auction-bid-auth';
import { AuctionGateway } from './auction.gateway';
import { AuctionBidArchiveService } from './auction-bid-archive.service';
import {
NextAuctionDto,
OpenBiddingDto,
PassedAuctionDto,
PlaceBidDto,
ResetAuctionDto,
SoldDto,
StartAuctionDto,
UndoAuctionDto,
@@ -31,6 +39,7 @@ export class AuctionController {
constructor(
private readonly auctionService: AuctionService,
private readonly auctionGateway: AuctionGateway,
private readonly auctionBidArchiveService: AuctionBidArchiveService,
) {}
@Post()
@@ -47,18 +56,21 @@ export class AuctionController {
return this.auctionService.start({
matchId,
communityId,
startAuctionRequestId: body.startAuctionRequestId,
actorUserId: currentUser._id,
captains: body.captains.map((c) => ({
teamIndex: c.teamIndex,
userId: new mongoose.Types.ObjectId(c.userId),
initialPoints: c.initialPoints,
initialTeamBidPointAmount: c.initialTeamBidPointAmount,
})),
initialPoints: body.initialPoints ?? 1000,
maxTimerSeconds: body.maxTimerSeconds ?? 30,
bidExtensionSeconds: body.bidExtensionSeconds ?? 5,
topTierThreshold: body.topTierThreshold ?? 'NONE',
manualTopTierUserIds: (body.manualTopTierUserIds ?? []).map(
(userId) => new mongoose.Types.ObjectId(userId),
),
initialTeamBidPointAmount: body.initialTeamBidPointAmount ?? 1000,
maximumBidRoundDurationSeconds: body.maximumBidRoundDurationSeconds ?? 30,
bidRoundExtensionSeconds: body.bidRoundExtensionSeconds ?? 5,
topTierAuctionPriorityThreshold:
body.topTierAuctionPriorityThreshold ?? 'NONE',
manualTopTierAuctionPriorityUserIds: (
body.manualTopTierAuctionPriorityUserIds ?? []
).map((userId) => new mongoose.Types.ObjectId(userId)),
});
}
@@ -67,17 +79,32 @@ export class AuctionController {
public async getAuction(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) {
return this.auctionService.getByMatchId(matchId);
return this.auctionService.getStateByMatchId(matchId);
}
// 공개 입찰 기록 조회.
@Get('bids/history')
@AllowPublicAccess()
public async getBidHistory(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Query('afterRevision') afterRevision?: string,
@Query('limit') limit?: string,
) {
return this.auctionBidArchiveService.list(
matchId,
afterRevision === undefined ? -1 : Number(afterRevision),
limit === undefined ? 100 : Number(limit),
);
}
// 공개 — 팀장 2명만 쓸 엔드포인트(트러스트 기반, 10명 동시 관전).
@Post('open-bidding')
@AllowPublicAccess()
@HttpCode(HttpStatus.OK)
public async openBidding(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: OpenBiddingDto = {},
) {
return this.auctionService.openBidding(matchId);
return this.auctionService.openBidding(matchId, body);
}
@Post('bids')
@@ -85,14 +112,29 @@ export class AuctionController {
@HttpCode(HttpStatus.OK)
public async placeBid(
@CurrentUser() currentUser: UserDocument | undefined,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: PlaceBidDto,
) {
if (isAuctionCaptainAuthRequired()) {
if (!currentUser) {
throw new ForbiddenException(
'팀장 계정으로 로그인해야 입찰할 수 있습니다.',
);
}
this.assertSameCommunity(currentUser, communityId);
}
return this.auctionService.placeBid({
matchId,
teamIndex: body.teamIndex,
amount: body.amount,
bidderUserId: this.resolveBidder(currentUser, body.bidderUserId),
bidderUserId: currentUser?._id,
teamIndex: body.bidderTeamIndex,
amount: body.bidPointAmount,
bidRequestId: body.bidRequestId,
clientObservedBidRoundId: body.clientObservedBidRoundId,
clientObservedAuctionLifecycleId: body.clientObservedAuctionLifecycleId,
clientObservedCurrentBidRoundPlayerUserId:
body.clientObservedCurrentBidRoundPlayerUserId,
});
}
@@ -106,16 +148,35 @@ export class AuctionController {
return this.auctionService.markSold({
matchId,
assignedPosition: body.assignedPosition,
auctionActionRequestId: body.auctionActionRequestId,
clientObservedAuctionLifecycleId: body.clientObservedAuctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex:
body.clientObservedCurrentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId:
body.clientObservedCurrentBidRoundPlayerUserId,
clientObservedPhase: body.clientObservedPhase,
clientObservedRevision: body.clientObservedRevision,
});
}
@Post('passed')
@AllowPublicAccess()
@HttpCode(HttpStatus.OK)
public async markPassed(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: PassedAuctionDto = {},
) {
return this.auctionService.markPassed(matchId, body);
}
@Post('next')
@AllowPublicAccess()
@HttpCode(HttpStatus.OK)
public async next(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: NextAuctionDto = {},
) {
return this.auctionService.next(matchId);
return this.auctionService.next(matchId, body);
}
@Get('history')
@@ -147,6 +208,14 @@ export class AuctionController {
matchId,
communityId,
sequence: body.sequence,
auctionActionRequestId: body.auctionActionRequestId,
clientObservedAuctionLifecycleId: body.clientObservedAuctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex:
body.clientObservedCurrentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId:
body.clientObservedCurrentBidRoundPlayerUserId,
clientObservedPhase: body.clientObservedPhase,
clientObservedRevision: body.clientObservedRevision,
});
this.auctionGateway.broadcastState(matchId.toString(), auction);
return auction;
@@ -161,21 +230,25 @@ export class AuctionController {
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: ResetAuctionDto = {},
) {
this.assertSameCommunity(currentUser, communityId);
await this.auctionService.reset({ matchId, communityId });
}
private resolveBidder(
currentUser: UserDocument | undefined,
bodyBidder?: string,
): mongoose.Types.ObjectId | undefined {
if (currentUser) return currentUser._id;
if (!bodyBidder) return undefined;
if (!mongoose.isValidObjectId(bodyBidder)) {
throw new BadRequestException('Invalid bidderUserId.');
}
return new mongoose.Types.ObjectId(bodyBidder);
await this.auctionService.reset({
matchId,
communityId,
auctionActionRequestId: body.auctionActionRequestId,
clientObservedAuctionLifecycleId: body.clientObservedAuctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex:
body.clientObservedCurrentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId:
body.clientObservedCurrentBidRoundPlayerUserId,
clientObservedPhase: body.clientObservedPhase,
clientObservedRevision: body.clientObservedRevision,
});
this.auctionGateway.broadcastReset(
matchId.toString(),
body.clientObservedAuctionLifecycleId,
);
}
private assertSameCommunity(
@@ -0,0 +1,525 @@
import mongoose from 'mongoose';
import { ServiceUnavailableException } from '@nestjs/common';
jest.mock('../auth/jwt.service', () => ({
JwtService: class JwtService {},
}));
import { AuctionGateway } from './auction.gateway';
describe('AuctionGateway', () => {
beforeEach(() => {
jest.replaceProperty(process, 'env', { ...process.env });
delete process.env.AUCTION_REQUIRE_CAPTAIN_AUTH;
});
afterEach(() => {
jest.restoreAllMocks();
});
it('signals pending initial state so the client can retry privately after recovery', async () => {
const matchId = new mongoose.Types.ObjectId().toString();
const gateway = new AuctionGateway(
{
getByMatchId: async () => ({}),
getStateByMatchId: async () => {
throw new ServiceUnavailableException({
code: 'AUCTION_STATE_RECOVERING',
message: 'recovering',
});
},
} as never,
{} as never,
{} as never,
{} as never,
{} as never,
{} as never,
{} as never,
);
const socket = { data: { matchId }, join: jest.fn(), emit: jest.fn() };
const ack = jest.fn();
await gateway.handleJoin(socket as never, { matchId }, ack);
expect(ack).toHaveBeenCalledWith(
expect.objectContaining({ ok: false, code: 'AUCTION_STATE_RECOVERING' }),
);
expect(socket.emit).toHaveBeenCalledTimes(1);
expect(socket.emit).toHaveBeenCalledWith('state-pending', {
retryAfterMS: 500,
});
});
it('sends join and resync snapshots only to the requesting socket and coalesces in-flight resyncs', async () => {
const matchId = new mongoose.Types.ObjectId().toString();
const getStateByMatchId = jest.fn().mockResolvedValue({ revision: 3 });
const gateway = new AuctionGateway(
{
getByMatchId: async () => ({ chatMessages: [] }),
getStateByMatchId,
} as never,
{} as never,
{} as never,
{} as never,
{} as never,
{} as never,
{} as never,
);
const broadcast = jest.fn();
(gateway as unknown as { server: unknown }).server = {
to: () => ({ emit: broadcast }),
};
const socket = { data: { matchId }, join: jest.fn(), emit: jest.fn() };
await gateway.handleJoin(socket as never, { matchId });
expect(socket.emit).toHaveBeenCalledWith('state', { revision: 3 });
expect(broadcast).not.toHaveBeenCalled();
let finish!: (value: unknown) => void;
getStateByMatchId.mockImplementationOnce(
() =>
new Promise((resolve) => {
finish = resolve;
}),
);
const ack = jest.fn(),
busyAck = jest.fn();
const pending = gateway.handleResync(socket as never, {}, ack);
await gateway.handleResync(socket as never, {}, busyAck);
expect(busyAck).toHaveBeenCalledWith(
expect.objectContaining({ code: 'RESYNC_BUSY' }),
);
finish({ revision: 4 });
await pending;
expect(ack).toHaveBeenCalledWith({ ok: true, state: { revision: 4 } });
expect(getStateByMatchId).toHaveBeenCalledTimes(2);
expect(broadcast).not.toHaveBeenCalled();
});
const bidderUserId = new mongoose.Types.ObjectId();
function createGateway(params?: {
getCurrentRedisTimestampMS?: jest.Mock;
placeBidDelta?: jest.Mock;
getRealtimeIdentity?: jest.Mock;
}) {
const auctionService = {
placeBidDelta: params?.placeBidDelta ?? jest.fn(),
getRealtimeIdentity:
params?.getRealtimeIdentity ?? jest.fn().mockResolvedValue(null),
};
const auctionRedisService = {
getCurrentRedisTimestampMS:
params?.getCurrentRedisTimestampMS ??
jest.fn().mockResolvedValue(1780000000000),
};
const gateway = new AuctionGateway(
auctionService as never,
{ resolveDevUserById: jest.fn() } as never,
{ verify: jest.fn() } as never,
{ findOrCreateByOid: jest.fn() } as never,
{ getModel: jest.fn() } as never,
{ attachAuctionNamespace: jest.fn() } as never,
auctionRedisService as never,
);
const emit = jest.fn();
const to = jest.fn().mockReturnValue({ emit });
(gateway as unknown as { server: { to: jest.Mock } }).server = { to };
return {
auctionService,
emit,
gateway,
auctionRedisService,
to,
};
}
it('requires an authenticated user when captain authentication is enabled', async () => {
process.env.AUCTION_REQUIRE_CAPTAIN_AUTH = 'true';
const matchId = new mongoose.Types.ObjectId().toString();
const { gateway, auctionService } = createGateway();
const ack = jest.fn();
await gateway.handleBid(
{ data: { matchId }, emit: jest.fn() } as never,
{ bidderTeamIndex: 1, bidPointAmount: 100 },
ack,
);
expect(auctionService.placeBidDelta).not.toHaveBeenCalled();
expect(ack).toHaveBeenCalledWith(
expect.objectContaining({ rejected: true }),
);
});
it.each([undefined, bidderUserId])(
'accepts the selected team in temporary mode for user %s',
async (userId) => {
const matchId = new mongoose.Types.ObjectId().toString();
const placeBidDelta = jest.fn().mockResolvedValue({
auctionBidHistoryEntry: {
bidderTeamIndex: 2,
bidderUserId: new mongoose.Types.ObjectId().toString(),
bidPointAmount: 120,
bidPlacedAtTimestampMS: 1780000000000,
},
currentHighestBidderTeamIndex: 2,
currentHighestBidPointAmount: 120,
currentServerTimestampMS: 1780000000000,
revision: 9,
});
const { gateway, emit } = createGateway({ placeBidDelta });
const ack = jest.fn();
await gateway.handleBid(
{
data: { matchId, user: userId ? { _id: userId } : undefined },
emit: jest.fn(),
} as never,
{ bidderTeamIndex: 2, bidPointAmount: 120 },
ack,
);
expect(placeBidDelta).toHaveBeenCalledWith(
expect.objectContaining({
teamIndex: 2,
amount: 120,
bidderUserId: userId,
}),
);
expect(ack).toHaveBeenCalledWith(expect.objectContaining({ ok: true }));
expect(emit).toHaveBeenCalledWith(
'bid',
expect.objectContaining({ currentHighestBidderTeamIndex: 2 }),
);
},
);
it('broadcasts a bid delta and acknowledges the matching bid request', async () => {
const matchId = new mongoose.Types.ObjectId().toString();
const auctionBidHistoryEntry = {
bidderTeamIndex: 2,
bidderUserId: 'captain-2',
bidPlacedAtTimestampMS: 1780000000000,
bidPointAmount: 120,
};
const placeBidDelta = jest.fn().mockResolvedValue({
auctionBidHistoryEntry,
auctionLifecycleId: 'life-1',
currentBidRoundDeadlineTimestampMS: 1780000030000,
currentHighestBidderTeamIndex: 2,
currentHighestBidPointAmount: 120,
currentServerTimestampMS: 1780000000000,
revision: 9,
});
const { emit, gateway, to } = createGateway({ placeBidDelta });
const ack = jest.fn();
await gateway.handleBid(
{
data: { matchId, user: { _id: bidderUserId } },
emit: jest.fn(),
} as never,
{
bidPointAmount: 120,
bidderTeamIndex: 2,
bidRequestId: 'bid-1',
clientObservedAuctionLifecycleId: 'life-1',
clientObservedCurrentBidRoundPlayerUserId: 'player-1',
},
ack,
);
expect(placeBidDelta).toHaveBeenCalledWith({
amount: 120,
bidRequestId: 'bid-1',
bidderUserId,
clientObservedAuctionLifecycleId: 'life-1',
clientObservedCurrentBidRoundPlayerUserId: 'player-1',
matchId: new mongoose.Types.ObjectId(matchId),
teamIndex: 2,
});
expect(to).toHaveBeenCalledWith(matchId);
expect(emit).toHaveBeenCalledWith('bid', {
auctionBidHistoryEntry,
auctionLifecycleId: 'life-1',
bidRequestId: 'bid-1',
currentBidRoundDeadlineTimestampMS: 1780000030000,
currentHighestBidderTeamIndex: 2,
currentHighestBidPointAmount: 120,
currentServerTimestampMS: 1780000000000,
revision: 9,
});
expect(ack).toHaveBeenCalledWith(
expect.objectContaining({
bidDelta: {
auctionBidHistoryEntry,
auctionLifecycleId: 'life-1',
bidRequestId: 'bid-1',
currentBidRoundDeadlineTimestampMS: 1780000030000,
currentHighestBidderTeamIndex: 2,
currentHighestBidPointAmount: 120,
currentServerTimestampMS: 1780000000000,
revision: 9,
},
bidRequestId: 'bid-1',
bidServerTiming: expect.objectContaining({
gatewayTotalDurationMS: expect.any(Number),
}),
ok: true,
}),
);
});
it('generates one bid request id when the client omits it', async () => {
const matchId = new mongoose.Types.ObjectId().toString();
const placeBidDelta = jest.fn().mockResolvedValue({
auctionBidHistoryEntry: {
bidderTeamIndex: 1,
bidPointAmount: 50,
},
auctionLifecycleId: 'life-1',
currentHighestBidderTeamIndex: 1,
currentHighestBidPointAmount: 50,
revision: 3,
});
const { emit, gateway } = createGateway({ placeBidDelta });
const ack = jest.fn();
await gateway.handleBid(
{
data: { matchId, user: { _id: bidderUserId } },
emit: jest.fn(),
} as never,
{
bidPointAmount: 50,
bidderTeamIndex: 1,
},
ack,
);
const generatedBidRequestId = placeBidDelta.mock.calls[0][0].bidRequestId;
expect(generatedBidRequestId).toEqual(expect.any(String));
expect(generatedBidRequestId).not.toHaveLength(0);
expect(emit).toHaveBeenCalledWith(
'bid',
expect.objectContaining({
bidRequestId: generatedBidRequestId,
}),
);
expect(ack).toHaveBeenCalledWith(
expect.objectContaining({
bidRequestId: generatedBidRequestId,
ok: true,
}),
);
});
it('acknowledges bid failures with the request id used for the attempt', async () => {
const matchId = new mongoose.Types.ObjectId().toString();
const placeBidDelta = jest.fn().mockRejectedValue({
getResponse: () => ({
bidDiagnostics: {
currentBidRoundDeadlineTimestampMS: 1780000002500,
currentServerTimestampMS: 1780000003000,
},
bidServerTiming: {
redisBidCommandDurationMS: 2,
redisBidContextReadDurationMS: 1,
serviceTotalDurationMS: 4,
},
code: 'EXPIRED',
message: 'Bid deadline has already expired.',
}),
});
const socketEmit = jest.fn();
const { gateway } = createGateway({ placeBidDelta });
const ack = jest.fn();
await gateway.handleBid(
{
data: { matchId, user: { _id: bidderUserId } },
emit: socketEmit,
} as never,
{
bidPointAmount: 50,
bidderTeamIndex: 1,
bidRequestId: 'bid-1',
},
ack,
);
expect(socketEmit).toHaveBeenCalledWith('error', {
message: 'Bid deadline has already expired.',
});
expect(ack).toHaveBeenCalledWith(
expect.objectContaining({
bidDiagnostics: {
currentBidRoundDeadlineTimestampMS: 1780000002500,
currentServerTimestampMS: 1780000003000,
},
bidRequestId: 'bid-1',
bidServerTiming: expect.objectContaining({
gatewayTotalDurationMS: expect.any(Number),
redisBidCommandDurationMS: 2,
redisBidContextReadDurationMS: 1,
serviceTotalDurationMS: 4,
}),
code: 'EXPIRED',
message: 'Bid deadline has already expired.',
rejected: true,
}),
);
});
it('acknowledges time sync with Redis server time', async () => {
const getCurrentRedisTimestampMS = jest
.fn()
.mockResolvedValue(1780000001234);
const { gateway } = createGateway({ getCurrentRedisTimestampMS });
const ack = jest.fn();
await gateway.handleTimeSync(
{
clientSentAtTimestampMS: 1780000000000,
sequence: 7,
},
ack,
);
expect(getCurrentRedisTimestampMS).toHaveBeenCalledTimes(1);
expect(ack).toHaveBeenCalledWith(
expect.objectContaining({
clientSentAtTimestampMS: 1780000000000,
currentServerTimestampMS: 1780000001234,
ok: true,
sequence: 7,
}),
);
});
it('adds lightweight auction identity to heartbeats for the joined match', async () => {
const matchId = new mongoose.Types.ObjectId().toString();
const identity = {
auctionLifecycleId: 'life-1',
revision: 11,
matchSideEffectRevision: 3,
};
const getRealtimeIdentity = jest.fn().mockResolvedValue(identity);
const { gateway } = createGateway({ getRealtimeIdentity });
const ack = jest.fn();
await gateway.handleTimeSync({ sequence: 1 }, ack, {
data: { matchId },
} as never);
expect(getRealtimeIdentity).toHaveBeenCalledWith(matchId);
expect(ack).toHaveBeenCalledWith(
expect.objectContaining({ ok: true, auctionState: identity }),
);
});
it('continues clock sync when the optional auction identity read fails', async () => {
const matchId = new mongoose.Types.ObjectId().toString();
const { gateway } = createGateway({
getRealtimeIdentity: jest
.fn()
.mockRejectedValue(new Error('identity unavailable')),
});
const ack = jest.fn();
await gateway.handleTimeSync({ sequence: 2 }, ack, {
data: { matchId },
} as never);
expect(ack).toHaveBeenCalledWith(
expect.objectContaining({
ok: true,
sequence: 2,
currentServerTimestampMS: 1780000000000,
auctionStateUnavailable: true,
}),
);
});
it('rate limits excessive bid requests from the same socket', async () => {
jest.spyOn(Date, 'now').mockReturnValue(1780000000000);
const matchId = new mongoose.Types.ObjectId().toString();
const placeBidDelta = jest.fn().mockResolvedValue({
auctionBidHistoryEntry: {
bidderTeamIndex: 1,
bidPointAmount: 50,
},
currentHighestBidderTeamIndex: 1,
currentHighestBidPointAmount: 50,
revision: 3,
});
const socketEmit = jest.fn();
const socket = {
data: { matchId, user: { _id: bidderUserId } },
emit: socketEmit,
};
const { gateway } = createGateway({ placeBidDelta });
const acknowledgements: Array<Record<string, unknown>> = [];
for (let index = 0; index < 9; index += 1) {
await gateway.handleBid(
socket as never,
{
bidPointAmount: 50,
bidderTeamIndex: 1,
bidRequestId: `bid-${index}`,
},
(response) => acknowledgements.push(response),
);
}
expect(placeBidDelta).toHaveBeenCalledTimes(8);
expect(socketEmit).toHaveBeenCalledWith('error', {
message: '입찰 요청이 너무 많습니다. 잠시 후 다시 시도해주세요.',
});
expect(acknowledgements[8]).toEqual({
bidRequestId: 'bid-8',
code: 'BID_RATE_LIMITED',
message: '입찰 요청이 너무 많습니다. 잠시 후 다시 시도해주세요.',
rejected: true,
});
});
it('allows bid requests again after the rate limit window resets', async () => {
const nowSpy = jest.spyOn(Date, 'now');
nowSpy.mockReturnValue(1780000000000);
const matchId = new mongoose.Types.ObjectId().toString();
const placeBidDelta = jest.fn().mockResolvedValue({
auctionBidHistoryEntry: {
bidderTeamIndex: 1,
bidPointAmount: 50,
},
currentHighestBidderTeamIndex: 1,
currentHighestBidPointAmount: 50,
revision: 3,
});
const socket = {
data: { matchId, user: { _id: bidderUserId } },
emit: jest.fn(),
};
const { gateway } = createGateway({ placeBidDelta });
for (let index = 0; index < 8; index += 1) {
await gateway.handleBid(
socket as never,
{
bidPointAmount: 50,
bidderTeamIndex: 1,
bidRequestId: `bid-${index}`,
},
jest.fn(),
);
}
nowSpy.mockReturnValue(1780000001000);
await gateway.handleBid(
socket as never,
{
bidPointAmount: 50,
bidderTeamIndex: 1,
bidRequestId: 'bid-reset',
},
jest.fn(),
);
expect(placeBidDelta).toHaveBeenCalledTimes(9);
});
});
File diff suppressed because it is too large. Load diff
+21 -2
View File
@@ -4,12 +4,31 @@ 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 { AuctionDeadlineScheduler } from './auction-deadline.scheduler';
import { AuctionDurabilityScheduler } from './auction-durability.scheduler';
import { AuctionEventBusService } from './auction-event-bus.service';
import { AuctionRedisModule } from './redis/auction-redis.module';
import { AuctionSideEffectService } from './auction-side-effect.service';
import { AuctionService } from './auction.service';
import { AuctionBidArchiveService } from './auction-bid-archive.service';
@Module({
imports: [RiotModule, TournamentCodeModule, TournamentResultModule],
imports: [
RiotModule,
TournamentCodeModule,
TournamentResultModule,
AuctionRedisModule,
],
controllers: [AuctionController],
providers: [AuctionService, AuctionGateway],
providers: [
AuctionService,
AuctionBidArchiveService,
AuctionGateway,
AuctionEventBusService,
AuctionDeadlineScheduler,
AuctionDurabilityScheduler,
AuctionSideEffectService,
],
exports: [AuctionService],
})
export class AuctionModule {}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+68 -17
View File
@@ -7,6 +7,8 @@ import {
IsInt,
IsMongoId,
IsOptional,
IsString,
IsUUID,
Max,
Min,
ValidateNested,
@@ -28,10 +30,13 @@ class CaptainAssignmentDto {
@IsInt()
@Min(100)
@Max(100000)
initialPoints?: number;
initialTeamBidPointAmount?: number;
}
export class StartAuctionDto {
@IsUUID()
startAuctionRequestId!: string;
@IsArray()
@ArrayMinSize(2)
@ArrayMaxSize(16)
@@ -43,50 +48,96 @@ export class StartAuctionDto {
@IsInt()
@Min(100)
@Max(100000)
initialPoints?: number;
initialTeamBidPointAmount?: number;
@IsOptional()
@IsEnum(AUCTION_TOP_TIER_THRESHOLDS)
topTierThreshold?: AuctionTopTierThreshold;
topTierAuctionPriorityThreshold?: AuctionTopTierThreshold;
@IsOptional()
@IsArray()
@ArrayMaxSize(100)
@IsMongoId({ each: true })
manualTopTierUserIds?: string[];
manualTopTierAuctionPriorityUserIds?: string[];
@IsOptional()
@IsInt()
@Min(5)
maxTimerSeconds?: number;
maximumBidRoundDurationSeconds?: number;
@IsOptional()
@IsInt()
@Min(0)
bidExtensionSeconds?: number;
bidRoundExtensionSeconds?: number;
}
export class PlaceBidDto {
@IsInt()
@Min(1)
teamIndex!: number;
@IsInt()
@Min(1)
amount!: number;
@IsOptional()
@IsString()
clientObservedBidRoundId?: string;
@IsOptional()
@IsMongoId()
bidderUserId?: string;
@IsUUID()
bidRequestId?: string;
@IsInt()
@Min(1)
bidderTeamIndex!: number;
@IsInt()
@Min(1)
bidPointAmount!: number;
@IsOptional()
clientObservedAuctionLifecycleId?: string;
@IsOptional()
clientObservedCurrentBidRoundPlayerUserId?: string;
}
export class SoldDto {
export class AuctionActionRequestDto {
@IsOptional()
@IsUUID()
auctionActionRequestId?: string;
@IsOptional()
@IsString()
clientObservedAuctionLifecycleId?: string;
@IsOptional()
@IsInt()
@Min(0)
clientObservedRevision?: number;
@IsOptional()
@IsString()
clientObservedPhase?: string;
@IsOptional()
@IsString()
clientObservedCurrentBidRoundPlayerUserId?: string;
@IsOptional()
@IsInt()
@Min(0)
clientObservedCurrentAuctionPlayerOrderIndex?: number;
}
export class SoldDto extends AuctionActionRequestDto {
@IsOptional()
@IsEnum(['TOP', 'JGL', 'MID', 'ADC', 'SUP'])
assignedPosition?: 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
}
export class UndoAuctionDto {
export class OpenBiddingDto extends AuctionActionRequestDto {}
export class NextAuctionDto extends AuctionActionRequestDto {}
export class PassedAuctionDto extends AuctionActionRequestDto {}
export class ResetAuctionDto extends AuctionActionRequestDto {}
export class UndoAuctionDto extends AuctionActionRequestDto {
@IsInt()
@Min(1)
sequence!: number;
@@ -0,0 +1,395 @@
import { AuctionRedisService } from './auction-redis.service';
import { AuctionRedisCommandService } from './auction-redis-command.service';
import { AUCTION_APPLY_TRANSITION_SCRIPT } from './auction-redis.apply-transition';
import { AUCTION_BID_SCRIPT } from './auction-redis.bid';
import { AUCTION_EXPIRE_PREPARE_SCRIPT } from './auction-redis.expire-prepare';
import { AUCTION_RESERVE_ACTION_REQUEST_SCRIPT } from './auction-redis.reserve-action';
import { AUCTION_HYDRATE_STATE_SCRIPT } from './auction-redis.state';
function makeService(reply: unknown) {
const auctionRedisService = {
evalScript: jest.fn().mockResolvedValue(reply),
} as unknown as jest.Mocked<AuctionRedisService>;
return {
auctionRedisService,
service: new AuctionRedisCommandService(auctionRedisService),
};
}
describe('AuctionRedisCommandService', () => {
it('executes BID script and parses successful reply', async () => {
const { service, auctionRedisService } = makeService([
'OK',
'bid-1',
'9',
'1000',
'120',
'2',
'31000',
'{"bidPointAmount":120}',
]);
await expect(
service.placeBid('match-1', {
bidderTeamIndex: 2,
bidPointAmount: 120,
bidRequestId: 'bid-1',
bidderUserId: 'captain-2',
clientObservedAuctionLifecycleId: 'life-1',
clientObservedCurrentBidRoundPlayerUserId: 'player-1',
maximumAuctionTeamMemberCount: 5,
maximumStoredAuctionBidHistoryCount: 200,
maximumStoredBidRequestResultCount: 100,
matchId: 'match-1',
minimumBidPointReservePerRemainingAuctionTeamMemberSlot: 10,
minimumBidRequestResultReplayWindowMS: 60_000,
}),
).resolves.toEqual({
auctionBidHistoryEntry: { bidPointAmount: 120 },
bidRequestId: 'bid-1',
currentHighestBidderTeamIndex: 2,
currentHighestBidPointAmount: 120,
currentBidRoundDeadlineTimestampMS: 31_000,
currentServerTimestampMS: 1_000,
ok: true,
revision: 9,
});
expect(auctionRedisService.evalScript).toHaveBeenCalledWith(
AUCTION_BID_SCRIPT,
expect.arrayContaining(['auction:match-1:liveAuctionState']),
expect.arrayContaining(['match-1', '2', '120']),
);
});
it('parses BID rejected reply', async () => {
const { service } = makeService([
'REJECTED',
'TOO_LOW',
'bid-1',
'1000',
'31000',
]);
await expect(
service.placeBid('match-1', {
bidderTeamIndex: 2,
bidPointAmount: 120,
bidRequestId: 'bid-1',
bidderUserId: 'captain-2',
clientObservedAuctionLifecycleId: 'life-1',
clientObservedCurrentBidRoundPlayerUserId: 'player-1',
maximumAuctionTeamMemberCount: 5,
maximumStoredAuctionBidHistoryCount: 200,
maximumStoredBidRequestResultCount: 100,
matchId: 'match-1',
minimumBidPointReservePerRemainingAuctionTeamMemberSlot: 10,
minimumBidRequestResultReplayWindowMS: 60_000,
}),
).resolves.toEqual({
bidRequestId: 'bid-1',
code: 'TOO_LOW',
currentBidRoundDeadlineTimestampMS: 31_000,
currentServerTimestampMS: 1000,
rejected: true,
});
});
it('executes reserve action request and parses lease metadata', async () => {
const { service, auctionRedisService } = makeService([
'RESERVED',
'life-1:request-1',
'transition-1',
'',
'2',
'1',
'1000',
]);
await expect(
service.reserveActionRequest('match-1', {
auctionActionRequestId: 'request-1',
auctionActionType: 'sold',
auctionStateTransitionId: 'transition-1',
clientObservedAuctionLifecycleId: 'life-1',
clientObservedPhase: 'bidding',
clientObservedRevision: 8,
leaseDurationMS: 10_000,
maximumStoredAuctionActionRequestResultCount: 100,
minimumAuctionActionRequestResultReplayWindowMS: 60_000,
processingOwnerToken: 'owner-1',
}),
).resolves.toEqual({
actionRequestScopeKey: 'life-1:request-1',
auctionStateTransitionId: 'transition-1',
currentServerTimestampMS: 1000,
newAuctionLifecycleId: '',
observedProcessingLeaseVersion: 2,
reserved: true,
wasLeaseExpired: true,
});
expect(auctionRedisService.evalScript).toHaveBeenCalledWith(
AUCTION_RESERVE_ACTION_REQUEST_SCRIPT,
expect.arrayContaining(['auction:match-1:auctionActionRequestResults']),
expect.arrayContaining(['life-1', 'request-1', 'sold']),
);
});
it('parses reserve action request replay refetch metadata', async () => {
const { service } = makeService([
'REPLAY',
'applied',
'life-1:request-1',
'11',
'',
'transition-1',
'',
'2',
'3000',
'',
'1',
]);
await expect(
service.reserveActionRequest('match-1', {
auctionActionRequestId: 'request-1',
auctionActionType: 'sold',
auctionStateTransitionId: 'transition-1',
clientObservedAuctionLifecycleId: 'life-1',
clientObservedPhase: 'bidding',
clientObservedRevision: 8,
leaseDurationMS: 10_000,
maximumStoredAuctionActionRequestResultCount: 100,
minimumAuctionActionRequestResultReplayWindowMS: 60_000,
processingOwnerToken: 'owner-1',
}),
).resolves.toEqual({
actionRequestScopeKey: 'life-1:request-1',
currentServerTimestampMS: 3000,
isReplay: true,
requiresRefetch: true,
replayStatus: 'applied',
revision: 11,
});
});
it('executes apply transition and parses successful reply', async () => {
const { service, auctionRedisService } = makeService([
'OK',
'transition-1',
'11',
'2000',
]);
await expect(
service.applyTransition('match-1', {
afterAuctionStructureStateJson: '{"auctionTeams":[]}',
auctionHistorySequence: 5,
auctionLifecycleId: 'life-1',
auctionStateTransitionId: 'transition-1',
broadcastStateRevision: 11,
deadline: { mode: 'remove' },
durabilityPayloadJson: '{"auctionStateTransitionId":"transition-1"}',
expectedPhase: 'bidding',
expectedRevision: 10,
liveStatePatch: { phase: 'sold' },
matchId: 'match-1',
shouldBroadcastState: true,
}),
).resolves.toEqual({
auctionStateTransitionId: 'transition-1',
currentServerTimestampMS: 2000,
ok: true,
revision: 11,
});
expect(auctionRedisService.evalScript).toHaveBeenCalledWith(
AUCTION_APPLY_TRANSITION_SCRIPT,
expect.arrayContaining(['auction:match-1:liveAuctionState']),
expect.arrayContaining(['match-1', 'life-1', 'transition-1']),
);
});
it('parses apply transition replay and rejected replies', async () => {
await expect(
makeService([
'REPLAY',
'APPLIED',
'transition-1',
'2100',
]).service.applyTransition('match-1', {
afterAuctionStructureStateJson: '{}',
auctionHistorySequence: 5,
auctionLifecycleId: 'life-1',
auctionStateTransitionId: 'transition-1',
broadcastStateRevision: 11,
deadline: { mode: 'none' },
durabilityPayloadJson: '{}',
expectedPhase: 'sold',
expectedRevision: 10,
liveStatePatch: {},
matchId: 'match-1',
shouldBroadcastState: false,
}),
).resolves.toEqual({
auctionStateTransitionId: 'transition-1',
currentServerTimestampMS: 2100,
isReplay: true,
replayStatus: 'APPLIED',
});
await expect(
makeService([
'REJECTED',
'CONFLICT',
'transition-1',
'2200',
]).service.applyTransition('match-1', {
afterAuctionStructureStateJson: '{}',
auctionHistorySequence: 5,
auctionLifecycleId: 'life-1',
auctionStateTransitionId: 'transition-1',
broadcastStateRevision: 11,
deadline: { mode: 'none' },
durabilityPayloadJson: '{}',
expectedPhase: 'sold',
expectedRevision: 10,
liveStatePatch: {},
matchId: 'match-1',
shouldBroadcastState: false,
}),
).resolves.toEqual({
auctionStateTransitionId: 'transition-1',
code: 'CONFLICT',
currentServerTimestampMS: 2200,
rejected: true,
});
});
it('executes expire prepare and parses expiry decisions', async () => {
const { service, auctionRedisService } = makeService([
'OK',
'sold',
'expire-1',
'12',
'3000',
]);
await expect(
service.expirePrepare('match-1', {
auctionStateTransitionId: 'expire-1',
bidRoundExpiryRetryDelayMS: 3000,
matchId: 'match-1',
}),
).resolves.toEqual({
auctionStateTransitionId: 'expire-1',
bidRoundExpiryDecision: 'sold',
currentServerTimestampMS: 3000,
isReplay: undefined,
ok: true,
revision: 12,
});
expect(auctionRedisService.evalScript).toHaveBeenCalledWith(
AUCTION_EXPIRE_PREPARE_SCRIPT,
expect.arrayContaining(['auction:match-1:liveAuctionState']),
expect.arrayContaining(['match-1', 'expire-1']),
);
});
it('parses expire prepare replay and noop replies', async () => {
await expect(
makeService([
'REPLAY',
'passed',
'expire-1',
'12',
'3100',
]).service.expirePrepare('match-1', {
auctionStateTransitionId: 'expire-1',
bidRoundExpiryRetryDelayMS: 3000,
matchId: 'match-1',
}),
).resolves.toMatchObject({
auctionStateTransitionId: 'expire-1',
bidRoundExpiryDecision: 'passed',
currentServerTimestampMS: 3100,
isReplay: true,
ok: true,
revision: 12,
});
await expect(
makeService(['NOOP', 'NOT_DUE', '3200']).service.expirePrepare(
'match-1',
{
auctionStateTransitionId: 'expire-1',
bidRoundExpiryRetryDelayMS: 3000,
matchId: 'match-1',
},
),
).resolves.toEqual({
code: 'NOT_DUE',
currentServerTimestampMS: 3200,
noop: true,
});
});
it('executes hydrate state and parses hydrate/noop replies', async () => {
const { service, auctionRedisService } = makeService(['OK', '7', '4000']);
await expect(
service.hydrateState('match-1', {
auctionHistorySequence: 3,
auctionLifecycleId: 'life-1',
maximumBidRoundDurationSeconds: 30,
matchId: 'match-1',
phase: 'presenting',
revision: 6,
structureStateJson: '{"auctionTeams":[]}',
}),
).resolves.toEqual({
currentServerTimestampMS: 4000,
hydrated: true,
revision: 7,
});
expect(auctionRedisService.evalScript).toHaveBeenCalledWith(
AUCTION_HYDRATE_STATE_SCRIPT,
expect.arrayContaining(['auction:match-1:liveAuctionState']),
expect.arrayContaining(['match-1', 'life-1', '6']),
);
await expect(
makeService(['NOOP', '8', '4100']).service.hydrateState('match-1', {
auctionHistorySequence: 3,
auctionLifecycleId: 'life-1',
maximumBidRoundDurationSeconds: 30,
matchId: 'match-1',
phase: 'presenting',
revision: 6,
structureStateJson: '{}',
}),
).resolves.toEqual({
currentServerTimestampMS: 4100,
noop: true,
revision: 8,
});
await expect(
makeService([
'REJECTED',
'INVALID_PATCH_ARITY',
'4200',
]).service.hydrateState('match-1', {
auctionHistorySequence: 3,
auctionLifecycleId: 'life-1',
maximumBidRoundDurationSeconds: 30,
matchId: 'match-1',
phase: 'presenting',
revision: 6,
structureStateJson: '{}',
}),
).resolves.toEqual({
code: 'INVALID_PATCH_ARITY',
currentServerTimestampMS: 4200,
rejected: true,
});
});
});
@@ -0,0 +1,384 @@
import { Injectable } from '@nestjs/common';
import {
type AuctionApplyTransitionScriptInput,
buildAuctionApplyTransitionScriptInvocation,
} from './auction-redis.apply-transition';
import {
type AuctionBidScriptInput,
buildAuctionBidScriptInvocation,
} from './auction-redis.bid';
import {
type AuctionExpirePrepareScriptInput,
buildAuctionExpirePrepareScriptInvocation,
} from './auction-redis.expire-prepare';
import { buildAuctionRedisKeys } from './auction-redis.keys';
import { AuctionRedisService } from './auction-redis.service';
import {
type AuctionReserveActionRequestScriptInput,
buildAuctionReserveActionRequestScriptInvocation,
} from './auction-redis.reserve-action';
import {
type HydrateAuctionStateScriptInput,
buildHydrateAuctionStateScriptInvocation,
} from './auction-redis.state';
export type AuctionBidCommandResult =
| {
auctionBidHistoryEntry: Record<string, unknown>;
bidRequestId: string;
currentBidRoundDeadlineTimestampMS: number;
currentHighestBidderTeamIndex: number;
currentHighestBidPointAmount: number;
currentServerTimestampMS: number;
isReplay?: boolean;
ok: true;
revision: number;
}
| {
bidRequestId: string;
code: string;
currentBidRoundDeadlineTimestampMS?: number;
currentServerTimestampMS: number;
isReplay?: boolean;
rejected: true;
};
export type AuctionReserveActionRequestCommandResult =
| {
actionRequestScopeKey: string;
auctionStateTransitionId: string;
currentServerTimestampMS: number;
newAuctionLifecycleId: string;
observedProcessingLeaseVersion: number;
reserved: true;
wasLeaseExpired: boolean;
}
| {
actionRequestScopeKey: string;
code: string;
currentServerTimestampMS: number;
rejected: true;
}
| {
actionRequestScopeKey: string;
currentServerTimestampMS: number;
isReplay: true;
requiresRefetch?: boolean;
replayStatus: string;
responseJson?: string;
revision?: number;
};
export type AuctionApplyTransitionCommandResult =
| {
auctionStateTransitionId: string;
currentServerTimestampMS: number;
ok: true;
revision: number;
}
| {
auctionStateTransitionId: string;
currentServerTimestampMS: number;
isReplay: true;
replayStatus: string;
}
| {
auctionStateTransitionId: string;
code: string;
currentServerTimestampMS: number;
rejected: true;
};
export type AuctionExpirePrepareCommandResult =
| {
auctionStateTransitionId: string;
bidRoundExpiryDecision: 'passed' | 'sold';
currentServerTimestampMS: number;
isReplay?: boolean;
ok: true;
revision: number;
}
| {
code: string;
currentServerTimestampMS: number;
noop: true;
};
export type AuctionHydrateStateCommandResult =
| {
currentServerTimestampMS: number;
hydrated: true;
revision: number;
}
| {
currentServerTimestampMS: number;
noop: true;
revision: number;
}
| {
code: string;
currentServerTimestampMS: number;
rejected: true;
};
@Injectable()
export class AuctionRedisCommandService {
constructor(private readonly auctionRedisService: AuctionRedisService) {}
public async placeBid(
matchId: string,
input: AuctionBidScriptInput,
): Promise<AuctionBidCommandResult> {
const invocation = buildAuctionBidScriptInvocation(
buildAuctionRedisKeys(matchId),
input,
);
const reply = await this.auctionRedisService.evalScript<unknown[]>(
invocation.script,
invocation.keys,
invocation.values,
);
return parseBidCommandReply(reply);
}
public async reserveActionRequest(
matchId: string,
input: AuctionReserveActionRequestScriptInput,
): Promise<AuctionReserveActionRequestCommandResult> {
const invocation = buildAuctionReserveActionRequestScriptInvocation(
buildAuctionRedisKeys(matchId),
input,
);
const reply = await this.auctionRedisService.evalScript<unknown[]>(
invocation.script,
invocation.keys,
invocation.values,
);
return parseReserveActionRequestReply(reply);
}
public async applyTransition(
matchId: string,
input: AuctionApplyTransitionScriptInput,
): Promise<AuctionApplyTransitionCommandResult> {
const invocation = buildAuctionApplyTransitionScriptInvocation(
buildAuctionRedisKeys(matchId),
input,
);
const reply = await this.auctionRedisService.evalScript<unknown[]>(
invocation.script,
invocation.keys,
invocation.values,
);
return parseApplyTransitionReply(reply);
}
public async expirePrepare(
matchId: string,
input: AuctionExpirePrepareScriptInput,
): Promise<AuctionExpirePrepareCommandResult> {
const invocation = buildAuctionExpirePrepareScriptInvocation(
buildAuctionRedisKeys(matchId),
input,
);
const reply = await this.auctionRedisService.evalScript<unknown[]>(
invocation.script,
invocation.keys,
invocation.values,
);
return parseExpirePrepareReply(reply);
}
public async hydrateState(
matchId: string,
input: HydrateAuctionStateScriptInput,
): Promise<AuctionHydrateStateCommandResult> {
const invocation = buildHydrateAuctionStateScriptInvocation(
buildAuctionRedisKeys(matchId),
input,
);
const reply = await this.auctionRedisService.evalScript<unknown[]>(
invocation.script,
invocation.keys,
invocation.values,
);
return parseHydrateStateReply(reply);
}
}
function parseBidCommandReply(reply: unknown[]): AuctionBidCommandResult {
const values = reply.map(String);
const kind = values[0];
if (kind === 'OK') {
return {
auctionBidHistoryEntry: JSON.parse(values[7] || '{}') as Record<
string,
unknown
>,
bidRequestId: values[1],
currentBidRoundDeadlineTimestampMS: numberValue(values[6]),
currentHighestBidderTeamIndex: numberValue(values[5]),
currentHighestBidPointAmount: numberValue(values[4]),
currentServerTimestampMS: numberValue(values[3]),
ok: true,
revision: numberValue(values[2]),
};
}
if (kind === 'REPLAY') {
const status = values[1];
if (status === 'ok') {
return {
auctionBidHistoryEntry: JSON.parse(values[8] || '{}') as Record<
string,
unknown
>,
bidRequestId: values[2],
currentBidRoundDeadlineTimestampMS: numberValue(values[7]),
currentHighestBidderTeamIndex: numberValue(values[6]),
currentHighestBidPointAmount: numberValue(values[5]),
currentServerTimestampMS: numberValue(values[9]),
isReplay: true,
ok: true,
revision: numberValue(values[3]),
};
}
return {
bidRequestId: values[2],
code: values[4] || status,
currentBidRoundDeadlineTimestampMS: optionalNumberValue(values[7]),
currentServerTimestampMS: numberValue(values[9]),
isReplay: true,
rejected: true,
};
}
return {
bidRequestId: values[2] ?? '',
code: values[1] ?? 'UNKNOWN',
currentBidRoundDeadlineTimestampMS: optionalNumberValue(values[4]),
currentServerTimestampMS: numberValue(values[3]),
rejected: true,
};
}
function parseReserveActionRequestReply(
reply: unknown[],
): AuctionReserveActionRequestCommandResult {
const values = reply.map(String);
const kind = values[0];
if (kind === 'RESERVED') {
return {
actionRequestScopeKey: values[1],
auctionStateTransitionId: values[2],
currentServerTimestampMS: numberValue(values[6]),
newAuctionLifecycleId: values[3],
observedProcessingLeaseVersion: numberValue(values[4]),
reserved: true,
wasLeaseExpired: values[5] === '1',
};
}
if (kind === 'REPLAY') {
return {
actionRequestScopeKey: values[2],
currentServerTimestampMS: numberValue(values[8]),
isReplay: true,
requiresRefetch: values[10] === '1' || undefined,
replayStatus: values[1],
responseJson: values[9] || undefined,
revision: values[3] ? numberValue(values[3]) : undefined,
};
}
return {
actionRequestScopeKey: values[2] ?? '',
code: values[1] ?? 'UNKNOWN',
currentServerTimestampMS: numberValue(values[3]),
rejected: true,
};
}
function parseApplyTransitionReply(
reply: unknown[],
): AuctionApplyTransitionCommandResult {
const values = reply.map(String);
const kind = values[0];
if (kind === 'OK') {
return {
auctionStateTransitionId: values[1],
currentServerTimestampMS: numberValue(values[3]),
ok: true,
revision: numberValue(values[2]),
};
}
if (kind === 'REPLAY') {
return {
auctionStateTransitionId: values[2],
currentServerTimestampMS: numberValue(values[3]),
isReplay: true,
replayStatus: values[1],
};
}
return {
auctionStateTransitionId: values[2] ?? '',
code: values[1] ?? 'UNKNOWN',
currentServerTimestampMS: numberValue(values[3]),
rejected: true,
};
}
function parseExpirePrepareReply(
reply: unknown[],
): AuctionExpirePrepareCommandResult {
const values = reply.map(String);
const kind = values[0];
if (kind === 'OK' || kind === 'REPLAY') {
return {
auctionStateTransitionId: values[2],
bidRoundExpiryDecision:
values[1] === 'sold' || values[1] === 'passed' ? values[1] : 'passed',
currentServerTimestampMS: numberValue(values[4]),
isReplay: kind === 'REPLAY' || undefined,
ok: true,
revision: numberValue(values[3]),
};
}
return {
code: values[1] ?? 'UNKNOWN',
currentServerTimestampMS: numberValue(values[2]),
noop: true,
};
}
function parseHydrateStateReply(
reply: unknown[],
): AuctionHydrateStateCommandResult {
const values = reply.map(String);
if (values[0] === 'OK') {
return {
currentServerTimestampMS: numberValue(values[2]),
hydrated: true,
revision: numberValue(values[1]),
};
}
if (values[0] === 'REJECTED') {
return {
code: values[1] ?? 'UNKNOWN',
currentServerTimestampMS: numberValue(values[2]),
rejected: true,
};
}
return {
currentServerTimestampMS: numberValue(values[2]),
noop: true,
revision: numberValue(values[1]),
};
}
function numberValue(value: string | undefined): number {
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : 0;
}
function optionalNumberValue(value: string | undefined): number | undefined {
if (value === undefined || value === '') return undefined;
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : undefined;
}
@@ -0,0 +1,153 @@
import mongoose from 'mongoose';
import {
buildAuctionRedisLiveStatePatchFromStructure,
buildAuctionRedisStructureState,
convertLegacyAuctionTeamsToRedisTeams,
} from './auction-redis-projection';
describe('auction redis projection helpers', () => {
it('converts legacy auction team fields to redis-v1 names', () => {
const captainUserId = new mongoose.Types.ObjectId();
const memberUserId = new mongoose.Types.ObjectId();
expect(
convertLegacyAuctionTeamsToRedisTeams([
{
teamIndex: 1,
captainUserId,
points: 970,
members: [
{
userId: memberUserId,
assignedPosition: 'ADC',
cost: 30,
},
],
},
]),
).toEqual([
{
teamIndex: 1,
captainUserId,
remainingBidPointAmount: 970,
members: [
{
userId: memberUserId,
assignedPosition: 'ADC',
memberAcquisitionBidPointAmount: 30,
},
],
},
]);
});
it('builds the redis structure state with only structure/config fields', () => {
const captainUserId = new mongoose.Types.ObjectId();
const playerUserId = new mongoose.Types.ObjectId();
expect(
buildAuctionRedisStructureState({
auctionPlayerOrder: [
{
userId: playerUserId,
puuid: 'puuid',
gameName: 'Player',
tagLine: 'KR1',
profileIconId: 1,
preferredPositions: [{ position: 'MID', priority: 1 }],
tiers: [],
tierHistory: [],
masteries: [],
passCount: 0,
},
],
auctionTeams: [
{
teamIndex: 1,
captainUserId,
remainingBidPointAmount: 1000,
members: [],
},
],
bidRoundExtensionSeconds: 5,
currentAuctionPlayerOrderIndex: 0,
currentAuctionRound: 1,
initialTeamBidPointAmount: 1000,
manualTopTierAuctionPriorityUserIds: [],
maximumBidRoundDurationSeconds: 30,
passedAuctionPlayerQueue: [],
topTierAuctionPriorityThreshold: 'NONE',
}),
).toMatchObject({
auctionPlayerOrder: [expect.objectContaining({ userId: playerUserId })],
auctionTeams: [
expect.objectContaining({
captainUserId,
remainingBidPointAmount: 1000,
teamIndex: 1,
}),
],
bidRoundExtensionSeconds: 5,
currentAuctionPlayerOrderIndex: 0,
currentAuctionRound: 1,
initialTeamBidPointAmount: 1000,
maximumBidRoundDurationSeconds: 30,
passedAuctionPlayerQueue: [],
topTierAuctionPriorityThreshold: 'NONE',
});
});
it('builds live state patch required by BID Lua', () => {
const captainUserId = new mongoose.Types.ObjectId();
const playerUserId = new mongoose.Types.ObjectId();
expect(
buildAuctionRedisLiveStatePatchFromStructure({
auctionPlayerOrder: [
{
userId: playerUserId,
puuid: 'puuid',
gameName: 'Player',
tagLine: 'KR1',
profileIconId: 1,
preferredPositions: [{ position: 'MID', priority: 1 }],
tiers: [],
tierHistory: [],
masteries: [],
passCount: 0,
},
],
auctionTeams: [
{
teamIndex: 2,
captainUserId,
remainingBidPointAmount: 970,
members: [
{
userId: new mongoose.Types.ObjectId(),
assignedPosition: 'ADC',
memberAcquisitionBidPointAmount: 30,
},
],
},
],
bidRoundExtensionSeconds: 5,
currentAuctionPlayerOrderIndex: 0,
currentAuctionRound: 1,
initialTeamBidPointAmount: 1000,
manualTopTierAuctionPriorityUserIds: [],
maximumBidRoundDurationSeconds: 30,
passedAuctionPlayerQueue: [],
topTierAuctionPriorityThreshold: 'NONE',
}),
).toEqual({
bidRoundExtensionSeconds: 5,
currentAuctionPlayerOrderIndex: 0,
currentBidRoundPlayerUserId: playerUserId.toString(),
maximumBidRoundDurationSeconds: 30,
'team:2:assignedAuctionTeamMemberCount': 2,
'team:2:captainUserId': captainUserId.toString(),
'team:2:remainingBidPointAmount': 970,
});
});
});
@@ -0,0 +1,96 @@
import type {
AuctionPlayerSnapshot,
AuctionTeam,
AuctionTopTierThreshold,
RedisAuctionTeam,
} from '../../global/database/schema';
import type mongoose from 'mongoose';
export interface AuctionRedisStructureStateInput {
auctionPlayerOrder: AuctionPlayerSnapshot[];
auctionTeams: RedisAuctionTeam[];
bidRoundExtensionSeconds: number;
currentAuctionPlayerOrderIndex: number;
currentAuctionRound: number;
initialTeamBidPointAmount: number;
manualTopTierAuctionPriorityUserIds: mongoose.Types.ObjectId[];
maximumBidRoundDurationSeconds: number;
passedAuctionPlayerQueue: AuctionPlayerSnapshot[];
topTierAuctionPriorityThreshold: AuctionTopTierThreshold;
}
export function convertLegacyAuctionTeamsToRedisTeams(
teams: AuctionTeam[],
): RedisAuctionTeam[] {
return teams.map((team) => ({
teamIndex: team.teamIndex,
captainUserId: team.captainUserId,
remainingBidPointAmount: team.points,
members: team.members.map((member) => ({
userId: member.userId,
assignedPosition: member.assignedPosition,
memberAcquisitionBidPointAmount: member.cost,
})),
}));
}
export function buildAuctionRedisStructureState(
input: AuctionRedisStructureStateInput,
): Record<string, unknown> {
return {
auctionPlayerOrder: input.auctionPlayerOrder,
auctionTeams: input.auctionTeams,
bidRoundExtensionSeconds: input.bidRoundExtensionSeconds,
currentAuctionPlayerOrderIndex: input.currentAuctionPlayerOrderIndex,
currentAuctionRound: input.currentAuctionRound,
initialTeamBidPointAmount: input.initialTeamBidPointAmount,
manualTopTierAuctionPriorityUserIds:
input.manualTopTierAuctionPriorityUserIds,
maximumBidRoundDurationSeconds: input.maximumBidRoundDurationSeconds,
passedAuctionPlayerQueue: input.passedAuctionPlayerQueue,
topTierAuctionPriorityThreshold: input.topTierAuctionPriorityThreshold,
};
}
export function buildAuctionRedisLiveStatePatchFromStructure(
input: AuctionRedisStructureStateInput,
): Record<string, string | number> {
const patch: Record<string, string | number> = {
bidRoundExtensionSeconds: input.bidRoundExtensionSeconds,
currentAuctionPlayerOrderIndex: input.currentAuctionPlayerOrderIndex,
maximumBidRoundDurationSeconds: input.maximumBidRoundDurationSeconds,
};
const currentPlayer =
input.auctionPlayerOrder[input.currentAuctionPlayerOrderIndex];
if (currentPlayer) {
patch.currentBidRoundPlayerUserId = currentPlayer.userId.toString();
}
for (const team of input.auctionTeams) {
patch[`team:${team.teamIndex}:captainUserId`] =
team.captainUserId.toString();
patch[`team:${team.teamIndex}:remainingBidPointAmount`] =
team.remainingBidPointAmount;
patch[`team:${team.teamIndex}:assignedAuctionTeamMemberCount`] =
countAuctionTeamMembersIncludingCaptain(team);
}
return patch;
}
export function stringifyAuctionRedisStructureState(
input: AuctionRedisStructureStateInput,
): string {
return JSON.stringify(buildAuctionRedisStructureState(input));
}
function countAuctionTeamMembersIncludingCaptain(
team: RedisAuctionTeam,
): number {
const userIds = new Set<string>([team.captainUserId.toString()]);
for (const member of team.members) {
userIds.add(member.userId.toString());
}
return userIds.size;
}
@@ -0,0 +1,213 @@
import { AuctionRedisService } from './auction-redis.service';
import { AuctionRedisStateReaderService } from './auction-redis-state-reader.service';
function makeService(
commandReplies: unknown[],
currentServerTimestampMS = 1000,
) {
const sendCommand = jest
.fn()
.mockImplementation((command: string[]) =>
Promise.resolve(
command[0] === 'EVAL'
? [currentServerTimestampMS, ...commandReplies.splice(0, 3)]
: commandReplies.shift(),
),
);
const auctionRedisService = {
getCurrentRedisTimestampMS: jest
.fn()
.mockResolvedValue(currentServerTimestampMS),
raw: jest.fn().mockReturnValue({ sendCommand }),
} as unknown as jest.Mocked<AuctionRedisService>;
return {
auctionRedisService,
sendCommand,
service: new AuctionRedisStateReaderService(auctionRedisService),
};
}
describe('AuctionRedisStateReaderService', () => {
it('reads live state identity', async () => {
const { service, sendCommand } = makeService([
['life-1', '7', '3', 'transition-1'],
]);
await expect(service.readLiveStateIdentity('match-1')).resolves.toEqual({
auctionLifecycleId: 'life-1',
revision: 7,
matchSideEffectRevision: 3,
matchSideEffectTransitionId: 'transition-1',
});
expect(sendCommand).toHaveBeenCalledWith([
'HMGET',
'auction:match-1:liveAuctionState',
'auctionLifecycleId',
'revision',
'matchSideEffectRevision',
'matchSideEffectTransitionId',
]);
});
it('returns null when live state identity is missing', async () => {
const { service } = makeService([[null, null]]);
await expect(service.readLiveStateIdentity('match-1')).resolves.toBeNull();
});
it('reads bid context from the live state hot path fields', async () => {
const { service, sendCommand } = makeService([
['bidding', 'life-1', 'player-1', 'captain-2'],
]);
await expect(service.readBidContext('match-1', 2)).resolves.toEqual({
auctionLifecycleId: 'life-1',
bidderTeamCaptainUserId: 'captain-2',
currentBidRoundPlayerUserId: 'player-1',
phase: 'bidding',
});
expect(sendCommand).toHaveBeenCalledTimes(1);
expect(sendCommand).toHaveBeenCalledWith([
'HMGET',
'auction:match-1:liveAuctionState',
'phase',
'auctionLifecycleId',
'currentBidRoundPlayerUserId',
'team:2:captainUserId',
]);
});
it('falls back to structure state when bid context has no live captain field', async () => {
const { service, sendCommand } = makeService([
['bidding', 'life-1', 'player-1', null],
'{"auctionTeams":[{"teamIndex":2,"captainUserId":"captain-2"}]}',
]);
await expect(service.readBidContext('match-1', 2)).resolves.toEqual({
auctionLifecycleId: 'life-1',
bidderTeamCaptainUserId: 'captain-2',
currentBidRoundPlayerUserId: 'player-1',
phase: 'bidding',
});
expect(sendCommand).toHaveBeenNthCalledWith(2, [
'GET',
'auction:match-1:auctionStructureState',
]);
});
it('assembles a public auction view from Redis state', async () => {
const { service, sendCommand } = makeService([
[
'auctionLifecycleId',
'life-1',
'phase',
'expiring',
'revision',
'8',
'currentHighestBidPointAmount',
'100',
'currentHighestBidderTeamIndex',
'2',
'team:2:remainingBidPointAmount',
'900',
'bidRoundExpiryDecision',
'sold',
],
'{"auctionTeams":[{"teamIndex":1}]}',
['{"bidPointAmount":100,"bidderTeamIndex":2}'],
]);
const view = await service.readAuctionStateView('match-1', {
shouldForceAuctionStateResync: true,
});
expect(view).toMatchObject({
auctionBidHistory: [{ bidPointAmount: 100, bidderTeamIndex: 2 }],
auctionEngineVersion: 'redis-v1',
auctionLifecycleId: 'life-1',
matchId: 'match-1',
auctionTeams: [{ teamIndex: 1 }],
canPlaceBidInCurrentBidRound: false,
currentHighestBidderTeamIndex: 2,
currentHighestBidPointAmount: 100,
currentServerTimestampMS: 1000,
isAuctionStateTransitionInProgress: true,
phase: 'bidding',
revision: 8,
shouldForceAuctionStateResync: true,
});
expect(view).not.toHaveProperty('team:2:remainingBidPointAmount');
expect(view).not.toHaveProperty('bidRoundExpiryDecision');
expect(sendCommand).toHaveBeenCalledTimes(1);
expect(sendCommand).toHaveBeenCalledWith([
'EVAL',
expect.stringContaining("redis.call('TIME')"),
'3',
'auction:match-1:liveAuctionState',
'auction:match-1:auctionStructureState',
'auction:match-1:auctionBidHistory',
]);
});
it('assembles state when HGETALL returns an object', async () => {
const { service } = makeService([
{
auctionLifecycleId: 'life-1',
phase: 'presenting',
revision: '3',
},
'{"auctionTeams":[]}',
[],
]);
await expect(
service.readAuctionStateView('match-1'),
).resolves.toMatchObject({
auctionLifecycleId: 'life-1',
auctionTeams: [],
phase: 'presenting',
revision: 3,
});
});
it('can expose internal live fields for server-side expiry completion', async () => {
const { service } = makeService([
{
auctionLifecycleId: 'life-1',
bidRoundExpiryDecision: 'sold',
phase: 'expiring',
revision: '4',
'team:1:remainingBidPointAmount': '900',
},
'{"auctionTeams":[]}',
[],
]);
await expect(
service.readAuctionStateView('match-1', {
includeInternalLiveStateFields: true,
}),
).resolves.toMatchObject({
bidRoundExpiryDecision: 'sold',
redisInternalPhase: 'expiring',
'team:1:remainingBidPointAmount': '900',
});
});
it('returns null when live or structure state is absent', async () => {
await expect(
makeService([[], '{"auctionTeams":[]}', []]).service.readAuctionStateView(
'match-1',
),
).resolves.toBeNull();
await expect(
makeService([
{ auctionLifecycleId: 'life-1', phase: 'presenting', revision: '1' },
null,
[],
]).service.readAuctionStateView('match-1'),
).resolves.toBeNull();
});
});
@@ -0,0 +1,245 @@
import { Injectable } from '@nestjs/common';
import type { AuctionStateIdentity } from '@lolympus/contracts';
import { buildAuctionRedisKeys } from './auction-redis.keys';
import { AuctionRedisService } from './auction-redis.service';
import { assembleAuctionViewFromRedisState } from './auction-redis.state';
const NUMERIC_LIVE_STATE_FIELDS = new Set([
'bidRoundExpiryPlayerOrderIndex',
'bidRoundExpiryRevision',
'bidRoundExpiryWinningBidPointAmount',
'bidRoundExpiryWinningBidderTeamIndex',
'currentAuctionHistorySequence',
'currentAuctionPlayerOrderIndex',
'currentBidRoundDeadlineTimestampMS',
'currentHighestBidPointAmount',
'currentHighestBidderTeamIndex',
'matchSideEffectRevision',
'revision',
]);
export type AuctionRedisLiveStateIdentity = AuctionStateIdentity;
export interface AuctionRedisBidContext {
auctionLifecycleId: string;
bidderTeamCaptainUserId?: string;
currentBidRoundPlayerUserId?: string;
phase: string;
}
export interface AuctionRedisStateViewReadOptions {
includeInternalLiveStateFields?: boolean;
shouldForceAuctionStateResync?: boolean;
}
@Injectable()
export class AuctionRedisStateReaderService {
constructor(private readonly auctionRedisService: AuctionRedisService) {}
public async readLiveStateIdentity(
matchId: string,
): Promise<AuctionRedisLiveStateIdentity | null> {
const keys = buildAuctionRedisKeys(matchId);
const reply = await this.auctionRedisService
.raw()
.sendCommand([
'HMGET',
keys.liveStateKey,
'auctionLifecycleId',
'revision',
'matchSideEffectRevision',
'matchSideEffectTransitionId',
]);
if (!Array.isArray(reply)) return null;
const auctionLifecycleId =
typeof reply[0] === 'string' && reply[0] ? reply[0] : undefined;
const revision =
typeof reply[1] === 'string' || typeof reply[1] === 'number'
? Number(reply[1])
: Number.NaN;
if (!auctionLifecycleId && !Number.isFinite(revision)) return null;
return {
auctionLifecycleId,
revision: Number.isFinite(revision) ? revision : undefined,
matchSideEffectRevision:
reply[2] !== null && Number.isFinite(Number(reply[2]))
? Number(reply[2])
: undefined,
matchSideEffectTransitionId:
typeof reply[3] === 'string' && reply[3] ? reply[3] : undefined,
};
}
public async readBidContext(
matchId: string,
bidderTeamIndex: number,
): Promise<AuctionRedisBidContext | null> {
const keys = buildAuctionRedisKeys(matchId);
const bidderTeamCaptainUserIdField = `team:${bidderTeamIndex}:captainUserId`;
const liveReply = await this.auctionRedisService
.raw()
.sendCommand([
'HMGET',
keys.liveStateKey,
'phase',
'auctionLifecycleId',
'currentBidRoundPlayerUserId',
bidderTeamCaptainUserIdField,
]);
if (!Array.isArray(liveReply)) return null;
const phase = stringValue(liveReply[0]);
const auctionLifecycleId = stringValue(liveReply[1]);
const currentBidRoundPlayerUserId = stringValue(liveReply[2]);
const liveCaptainUserId = stringValue(liveReply[3]);
if (!phase || !auctionLifecycleId) return null;
return {
auctionLifecycleId,
bidderTeamCaptainUserId:
liveCaptainUserId ??
(await this.readBidderTeamCaptainUserIdFromStructure(
keys.structureStateKey,
bidderTeamIndex,
)),
currentBidRoundPlayerUserId,
phase,
};
}
public async readAuctionStateView(
matchId: string,
options: AuctionRedisStateViewReadOptions = {},
): Promise<Record<string, unknown> | null> {
const keys = buildAuctionRedisKeys(matchId);
const [
currentServerTimestampMS,
liveReply,
structureStateJson,
bidEntries,
] = await this.auctionRedisService
.raw()
.sendCommand<
unknown[]
>(['EVAL', ["local now = redis.call('TIME')", 'local timestamp = tonumber(now[1]) * 1000 + math.floor(tonumber(now[2]) / 1000)', "return {tostring(timestamp), redis.call('HGETALL', KEYS[1]), redis.call('GET', KEYS[2]), redis.call('LRANGE', KEYS[3], 0, -1)}"].join('\n'), '3', keys.liveStateKey, keys.structureStateKey, keys.bidHistoryKey]);
const liveState = parseHashReply(liveReply, {
includeInternalLiveStateFields:
options.includeInternalLiveStateFields ?? false,
});
if (!liveState) return null;
if (
typeof liveState.auctionLifecycleId !== 'string' ||
typeof liveState.phase !== 'string' ||
typeof liveState.revision !== 'number'
) {
return null;
}
if (typeof structureStateJson !== 'string' || !structureStateJson) {
return null;
}
const view = assembleAuctionViewFromRedisState({
auctionBidHistoryEntries: Array.isArray(bidEntries)
? bidEntries.map(String)
: [],
currentServerTimestampMS: Number(currentServerTimestampMS),
liveState: liveState as Record<string, unknown> & {
auctionLifecycleId: string;
phase: string;
revision: number;
},
shouldForceAuctionStateResync: options.shouldForceAuctionStateResync,
structureState: parseJsonRecord(structureStateJson),
});
view.matchId = matchId;
view.auctionEngineVersion = 'redis-v1';
if (options.includeInternalLiveStateFields) {
view.redisInternalPhase = liveState.phase;
}
return view;
}
private async readBidderTeamCaptainUserIdFromStructure(
structureStateKey: string,
bidderTeamIndex: number,
): Promise<string | undefined> {
const structureStateJson = await this.auctionRedisService
.raw()
.sendCommand(['GET', structureStateKey]);
if (typeof structureStateJson !== 'string' || !structureStateJson) {
return undefined;
}
const structureState = parseJsonRecord(structureStateJson);
const auctionTeams: unknown[] = Array.isArray(structureState.auctionTeams)
? (structureState.auctionTeams as unknown[])
: [];
const bidderTeam = auctionTeams.find((entry) => {
if (!entry || typeof entry !== 'object') return false;
return (
Number((entry as Record<string, unknown>).teamIndex) === bidderTeamIndex
);
});
if (!bidderTeam || typeof bidderTeam !== 'object') return undefined;
return stringValue((bidderTeam as Record<string, unknown>).captainUserId);
}
}
function stringValue(value: unknown): string | undefined {
return typeof value === 'string' && value ? value : undefined;
}
function parseJsonRecord(json: string): Record<string, unknown> {
const value: unknown = JSON.parse(json);
return typeof value === 'object' && value !== null
? (value as Record<string, unknown>)
: {};
}
function parseHashReply(
reply: unknown,
options: { includeInternalLiveStateFields?: boolean } = {},
): Record<string, unknown> | null {
if (!reply) return null;
if (Array.isArray(reply)) {
if (reply.length === 0) return null;
const entries: [string, unknown][] = [];
for (let index = 0; index < reply.length; index += 2) {
entries.push([String(reply[index]), reply[index + 1]]);
}
return parseHashEntries(entries, options);
}
if (typeof reply === 'object') {
const entries = Object.entries(reply as Record<string, unknown>);
if (entries.length === 0) return null;
return parseHashEntries(entries, options);
}
return null;
}
function parseHashEntries(
entries: [string, unknown][],
options: { includeInternalLiveStateFields?: boolean } = {},
): Record<string, unknown> {
const result: Record<string, unknown> = {};
for (const [field, rawValue] of entries) {
if (
!options.includeInternalLiveStateFields &&
isInternalLiveStateField(field)
) {
continue;
}
const value = String(rawValue);
if (NUMERIC_LIVE_STATE_FIELDS.has(field)) {
const parsed = Number(value);
result[field] = Number.isFinite(parsed) ? parsed : 0;
continue;
}
result[field] = value;
}
return result;
}
function isInternalLiveStateField(field: string): boolean {
return field.startsWith('team:') || field.startsWith('bidRoundExpiry');
}
@@ -0,0 +1,112 @@
import { buildAuctionRedisKeys } from './auction-redis.keys';
import {
AUCTION_APPLY_TRANSITION_SCRIPT,
buildAuctionApplyTransitionScriptInvocation,
} from './auction-redis.apply-transition';
describe('auction apply transition redis script contract', () => {
it('builds APPLY_TRANSITION keys and values in a stable order', () => {
const keys = buildAuctionRedisKeys('match-1');
const invocation = buildAuctionApplyTransitionScriptInvocation(keys, {
actionRequest: {
observedProcessingLeaseVersion: 3,
processingOwnerToken: 'owner-1',
scopeKey: 'life-1:request-1',
},
afterAuctionStructureStateJson: '{"auctionTeams":[]}',
auctionHistorySequence: 4,
auctionLifecycleId: 'life-1',
auctionStateTransitionId: 'transition-1',
broadcastStateRevision: 9,
deadline: { durationSeconds: 30, mode: 'set-relative' },
durabilityPayloadJson: '{"revision":9}',
expectedCurrentAuctionPlayerOrderIndex: 2,
expectedCurrentBidRoundPlayerUserId: 'player-1',
expectedAuctionHistorySequence: 3,
expectedPhase: 'bidding',
expectedRevision: 8,
liveStatePatch: {
currentAuctionHistorySequence: 4,
phase: 'sold',
},
matchId: 'match-1',
shouldBroadcastState: true,
});
expect(invocation.script).toBe(AUCTION_APPLY_TRANSITION_SCRIPT);
expect(invocation.keys).toEqual([
'auction:match-1:liveAuctionState',
'auction:match-1:auctionStructureState',
'auction:match-1:appliedAuctionStateTransitionIds',
'auction:match-1:durability:transition-1',
'auction:auctionDurabilityRetryQueue',
'auction:match-1:auctionActionRequestResults',
'auction:match-1:auctionActionRequestResultOrder',
'auction:match-1:auctionBidHistory',
'auction:match-1:bidRequestResults',
'auction:match-1:bidRequestResultOrder',
'auction:bidRoundDeadlineQueue',
'auction:match-1:rejectedBidRequestResultOrder',
]);
expect(invocation.values.slice(0, 19)).toEqual([
'match-1',
'life-1',
'transition-1',
'8',
'3',
'bidding',
'player-1',
'2',
'{"auctionTeams":[]}',
'4',
'{"revision":9}',
'1',
'9',
'set-relative',
'30',
'0',
'life-1:request-1',
'owner-1',
'3',
]);
expect(invocation.values.slice(19)).toEqual([
'2',
'currentAuctionHistorySequence',
'4',
'phase',
'sold',
]);
});
it('keeps critical atomicity guards in Lua', () => {
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain("redis.call('TIME')");
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain(
'ACTION_REQUEST_LEASE_VERSION_MISMATCH',
);
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain(
'ACTION_REQUEST_TRANSITION_MISMATCH',
);
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain(
'INVALID_PATCH_ARITY',
);
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain(
'shouldBroadcastState',
);
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain("redis.call('SADD'");
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain(
"redis.call('HINCRBY'",
);
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain(
'currentAuctionHistorySequence',
);
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain(
'storeValidatedActionRequestRejection',
);
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain(
"actionRequestPrefix .. 'status'",
);
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain(
"actionRequestPrefix .. 'requiresRefetch'",
);
});
});
@@ -0,0 +1,340 @@
import type { AuctionRedisKeys } from './auction-redis.keys';
import { defineAuctionRedisScript } from './auction-redis.scripts';
export type ApplyTransitionDeadlineInput =
| { mode: 'none' }
| { mode: 'remove' }
| { durationSeconds: number; mode: 'set-relative' };
export interface ApplyTransitionActionRequestInput {
observedProcessingLeaseVersion: number;
processingOwnerToken: string;
scopeKey: string;
}
export interface AuctionApplyTransitionScriptInput {
actionRequest?: ApplyTransitionActionRequestInput;
afterAuctionStructureStateJson: string;
auctionHistorySequence: number;
auctionLifecycleId: string;
auctionStateTransitionId: string;
broadcastStateRevision: number;
deadline: ApplyTransitionDeadlineInput;
durabilityPayloadJson: string;
expectedCurrentAuctionPlayerOrderIndex?: number;
expectedCurrentBidRoundPlayerUserId?: string;
expectedAuctionHistorySequence?: number;
expectedPhase: string;
expectedRevision: number;
liveStatePatch: Record<string, string | number | boolean | null | undefined>;
matchId: string;
shouldBroadcastState: boolean;
shouldResetBidRuntime?: boolean;
}
export interface AuctionApplyTransitionScriptInvocation {
keys: string[];
script: typeof AUCTION_APPLY_TRANSITION_SCRIPT;
values: string[];
}
function stringifyRedisValue(value: string | number | boolean | null): string {
if (typeof value === 'boolean') return value ? '1' : '0';
if (value === null) return '';
return String(value);
}
function flattenLiveStatePatch(
liveStatePatch: AuctionApplyTransitionScriptInput['liveStatePatch'],
): string[] {
return Object.entries(liveStatePatch)
.filter(([, value]) => value !== undefined)
.sort(([a], [b]) => a.localeCompare(b))
.flatMap(([key, value]) => [
key,
stringifyRedisValue(value as string | number | boolean | null),
]);
}
export function buildAuctionApplyTransitionScriptInvocation(
keys: AuctionRedisKeys,
input: AuctionApplyTransitionScriptInput,
): AuctionApplyTransitionScriptInvocation {
const liveStatePatchPairs = flattenLiveStatePatch(input.liveStatePatch);
const deadlineDurationSeconds =
input.deadline.mode === 'set-relative'
? String(input.deadline.durationSeconds)
: '0';
return {
keys: [
keys.liveStateKey,
keys.structureStateKey,
keys.appliedTransitionIdsKey,
keys.durabilityPayloadKey(input.auctionStateTransitionId),
keys.durabilityRetryQueueKey,
keys.actionRequestResultsKey,
keys.actionRequestResultOrderKey,
keys.bidHistoryKey,
keys.bidRequestResultsKey,
keys.bidRequestResultOrderKey,
keys.deadlineQueueKey,
keys.rejectedBidRequestResultOrderKey,
],
script: AUCTION_APPLY_TRANSITION_SCRIPT,
values: [
input.matchId,
input.auctionLifecycleId,
input.auctionStateTransitionId,
String(input.expectedRevision),
String(
input.expectedAuctionHistorySequence ??
input.auctionHistorySequence - 1,
),
input.expectedPhase,
input.expectedCurrentBidRoundPlayerUserId ?? '',
input.expectedCurrentAuctionPlayerOrderIndex === undefined
? ''
: String(input.expectedCurrentAuctionPlayerOrderIndex),
input.afterAuctionStructureStateJson,
String(input.auctionHistorySequence),
input.durabilityPayloadJson,
input.shouldBroadcastState ? '1' : '0',
String(input.broadcastStateRevision),
input.deadline.mode,
deadlineDurationSeconds,
input.shouldResetBidRuntime ? '1' : '0',
input.actionRequest?.scopeKey ?? '',
input.actionRequest?.processingOwnerToken ?? '',
input.actionRequest?.observedProcessingLeaseVersion === undefined
? ''
: String(input.actionRequest.observedProcessingLeaseVersion),
String(liveStatePatchPairs.length / 2),
...liveStatePatchPairs,
],
};
}
export const AUCTION_APPLY_TRANSITION_SCRIPT = defineAuctionRedisScript(
'auction.applyTransition',
`
local liveAuctionStateKey = KEYS[1]
local auctionStructureStateKey = KEYS[2]
local appliedAuctionStateTransitionIdsKey = KEYS[3]
local durabilityPayloadKey = KEYS[4]
local durabilityRetryQueueKey = KEYS[5]
local auctionActionRequestResultsKey = KEYS[6]
local auctionActionRequestResultOrderKey = KEYS[7]
local auctionBidHistoryKey = KEYS[8]
local bidRequestResultsKey = KEYS[9]
local bidRequestResultOrderKey = KEYS[10]
local bidRoundDeadlineQueueKey = KEYS[11]
local rejectedBidRequestResultOrderKey = KEYS[12]
local matchId = ARGV[1]
local auctionLifecycleId = ARGV[2]
local auctionStateTransitionId = ARGV[3]
local expectedRevision = tonumber(ARGV[4])
local expectedAuctionHistorySequence = tonumber(ARGV[5])
local expectedPhase = ARGV[6]
local expectedCurrentBidRoundPlayerUserId = ARGV[7]
local expectedCurrentAuctionPlayerOrderIndex = ARGV[8]
local afterAuctionStructureStateJson = ARGV[9]
local auctionHistorySequence = tonumber(ARGV[10])
local durabilityPayloadJson = ARGV[11]
local shouldBroadcastState = ARGV[12]
local broadcastStateRevision = tonumber(ARGV[13])
local deadlineMode = ARGV[14]
local deadlineDurationSeconds = tonumber(ARGV[15])
local shouldResetBidRuntime = ARGV[16]
local actionRequestScopeKey = ARGV[17]
local processingOwnerToken = ARGV[18]
local observedProcessingLeaseVersion = ARGV[19]
local liveStatePatchPairCount = tonumber(ARGV[20])
local redisTime = redis.call('TIME')
local currentRedisTimestampMS = (tonumber(redisTime[1]) * 1000) + math.floor(tonumber(redisTime[2]) / 1000)
local validatedActionRequestScopeKey = ''
local function storeValidatedActionRequestRejection(code)
if validatedActionRequestScopeKey == '' then
return
end
local actionRequestPrefix = validatedActionRequestScopeKey .. ':'
redis.call(
'HSET',
auctionActionRequestResultsKey,
actionRequestPrefix .. 'status',
'rejected',
actionRequestPrefix .. 'rejectCode',
code,
actionRequestPrefix .. 'requiresRefetch',
'1',
actionRequestPrefix .. 'responseServerTimestampMS',
tostring(currentRedisTimestampMS)
)
end
local function reject(code)
storeValidatedActionRequestRejection(code)
return {'REJECTED', code, auctionStateTransitionId, tostring(currentRedisTimestampMS)}
end
if not liveStatePatchPairCount then
return reject('INVALID_PATCH_ARITY')
end
if #ARGV ~= 20 + (liveStatePatchPairCount * 2) then
return reject('INVALID_PATCH_ARITY')
end
if not durabilityPayloadJson or durabilityPayloadJson == '' then
return reject('MISSING_DURABILITY_PAYLOAD')
end
if shouldBroadcastState ~= '0' and shouldBroadcastState ~= '1' then
return reject('INVALID_SHOULD_BROADCAST_STATE')
end
if shouldBroadcastState == '1' and not broadcastStateRevision then
return reject('INVALID_BROADCAST_STATE_REVISION')
end
if deadlineMode ~= 'none' and deadlineMode ~= 'remove' and deadlineMode ~= 'set-relative' then
return reject('INVALID_DEADLINE_MODE')
end
if deadlineMode == 'set-relative' and (not deadlineDurationSeconds or deadlineDurationSeconds <= 0) then
return reject('INVALID_DEADLINE_DURATION')
end
if actionRequestScopeKey ~= '' then
local actionRequestPrefix = actionRequestScopeKey .. ':'
local storedTransitionId = redis.call('HGET', auctionActionRequestResultsKey, actionRequestPrefix .. 'auctionStateTransitionId')
if not storedTransitionId then
return reject('ACTION_REQUEST_NOT_RESERVED')
end
if storedTransitionId ~= auctionStateTransitionId then
return reject('ACTION_REQUEST_TRANSITION_MISMATCH')
end
local storedOwnerToken = redis.call('HGET', auctionActionRequestResultsKey, actionRequestPrefix .. 'processingOwnerToken')
local leaseExpiresAtTimestampMS = tonumber(redis.call('HGET', auctionActionRequestResultsKey, actionRequestPrefix .. 'processingLeaseExpiresAtTimestampMS') or '0')
if leaseExpiresAtTimestampMS <= currentRedisTimestampMS then
return reject('ACTION_REQUEST_LEASE_EXPIRED')
end
if storedOwnerToken ~= processingOwnerToken then
return reject('ACTION_REQUEST_IN_PROGRESS')
end
local storedLeaseVersion = redis.call('HGET', auctionActionRequestResultsKey, actionRequestPrefix .. 'processingLeaseVersion') or ''
if storedLeaseVersion ~= observedProcessingLeaseVersion then
return reject('ACTION_REQUEST_LEASE_VERSION_MISMATCH')
end
validatedActionRequestScopeKey = actionRequestScopeKey
end
local currentRevision = tonumber(redis.call('HGET', liveAuctionStateKey, 'revision') or '-1')
if currentRevision ~= expectedRevision then
return reject('CONFLICT')
end
local currentAuctionHistorySequence = tonumber(redis.call('HGET', liveAuctionStateKey, 'currentAuctionHistorySequence') or '-1')
if currentAuctionHistorySequence ~= expectedAuctionHistorySequence then
return reject('CONFLICT')
end
if redis.call('HGET', liveAuctionStateKey, 'auctionLifecycleId') ~= auctionLifecycleId then
return reject('CONFLICT')
end
if redis.call('HGET', liveAuctionStateKey, 'phase') ~= expectedPhase then
return reject('CONFLICT')
end
if expectedCurrentBidRoundPlayerUserId ~= '' and redis.call('HGET', liveAuctionStateKey, 'currentBidRoundPlayerUserId') ~= expectedCurrentBidRoundPlayerUserId then
return reject('CONFLICT')
end
if expectedCurrentAuctionPlayerOrderIndex ~= '' and redis.call('HGET', liveAuctionStateKey, 'currentAuctionPlayerOrderIndex') ~= expectedCurrentAuctionPlayerOrderIndex then
return reject('CONFLICT')
end
local transitionDedupeMember = auctionLifecycleId .. ':' .. auctionStateTransitionId
if redis.call('SISMEMBER', appliedAuctionStateTransitionIdsKey, transitionDedupeMember) == 1 then
return {'REPLAY', 'APPLIED', auctionStateTransitionId, tostring(currentRedisTimestampMS)}
end
local newRevision = redis.call('HINCRBY', liveAuctionStateKey, 'revision', 1)
redis.call('SET', auctionStructureStateKey, afterAuctionStructureStateJson)
local hsetArgs = {
liveAuctionStateKey,
'auctionLifecycleId',
auctionLifecycleId,
'currentAuctionHistorySequence',
tostring(auctionHistorySequence),
'lastAppliedAuctionStateTransitionId',
auctionStateTransitionId
}
local patchIndex = 21
for i = 1, liveStatePatchPairCount do
table.insert(hsetArgs, ARGV[patchIndex])
table.insert(hsetArgs, ARGV[patchIndex + 1])
patchIndex = patchIndex + 2
end
redis.call('HSET', unpack(hsetArgs))
local committedBidRoundDeadlineTimestampMS = ''
if deadlineMode == 'set-relative' then
local currentBidRoundDeadlineTimestampMS = currentRedisTimestampMS + (deadlineDurationSeconds * 1000)
committedBidRoundDeadlineTimestampMS = tostring(currentBidRoundDeadlineTimestampMS)
redis.call('HSET', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS', tostring(currentBidRoundDeadlineTimestampMS))
redis.call('HSET', liveAuctionStateKey, 'currentBidRoundId', auctionStateTransitionId)
redis.call('ZADD', bidRoundDeadlineQueueKey, currentBidRoundDeadlineTimestampMS, matchId)
elseif deadlineMode == 'remove' then
redis.call('ZREM', bidRoundDeadlineQueueKey, matchId)
redis.call('HDEL', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS')
end
-- A resumed auction must not disappear when its former completion TTL elapses.
if redis.call('HGET', liveAuctionStateKey, 'phase') ~= 'complete' then
for _, index in ipairs({1, 2, 3, 6, 7, 8, 9, 10, 12}) do
redis.call('PERSIST', KEYS[index])
end
end
if shouldResetBidRuntime == '1' then
redis.call('DEL', auctionBidHistoryKey, bidRequestResultsKey, bidRequestResultOrderKey, rejectedBidRequestResultOrderKey)
end
redis.call('SADD', appliedAuctionStateTransitionIdsKey, transitionDedupeMember)
redis.call(
'HSET',
durabilityPayloadKey,
'payloadJson',
durabilityPayloadJson,
'committedBidRoundDeadlineTimestampMS',
committedBidRoundDeadlineTimestampMS,
'preparedAtRedisTimestampMS',
tostring(currentRedisTimestampMS),
'committedAtRedisTimestampMS',
tostring(currentRedisTimestampMS),
'auctionLifecycleId',
auctionLifecycleId,
'revision',
tostring(newRevision),
'shouldBroadcastState',
shouldBroadcastState,
'broadcastStateRevision',
tostring(broadcastStateRevision)
)
redis.call('ZADD', durabilityRetryQueueKey, currentRedisTimestampMS, durabilityPayloadKey)
if actionRequestScopeKey ~= '' then
local actionRequestPrefix = actionRequestScopeKey .. ':'
redis.call(
'HSET',
auctionActionRequestResultsKey,
actionRequestPrefix .. 'status',
'applied',
actionRequestPrefix .. 'revision',
tostring(newRevision),
actionRequestPrefix .. 'requiresRefetch',
'1',
actionRequestPrefix .. 'responseServerTimestampMS',
tostring(currentRedisTimestampMS)
)
-- The reservation already inserted this request into the order list.
end
return {'OK', auctionStateTransitionId, tostring(newRevision), tostring(currentRedisTimestampMS)}
`,
);
@@ -0,0 +1,74 @@
import { buildAuctionRedisKeys } from './auction-redis.keys';
import {
AUCTION_BID_SCRIPT,
buildAuctionBidScriptInvocation,
buildBidRequestPayloadFingerprint,
} from './auction-redis.bid';
describe('auction bid redis script contract', () => {
it('builds the BID script KEYS and ARGV in the documented order', () => {
const keys = buildAuctionRedisKeys('match-1');
const invocation = buildAuctionBidScriptInvocation(keys, {
bidderTeamIndex: 2,
bidPointAmount: 120,
bidRequestId: 'bid-1',
bidderUserId: 'captain-2',
clientObservedAuctionLifecycleId: 'life-1',
clientObservedCurrentBidRoundPlayerUserId: 'player-1',
maximumAuctionTeamMemberCount: 5,
maximumStoredAuctionBidHistoryCount: 200,
maximumStoredBidRequestResultCount: 100,
matchId: 'match-1',
minimumBidPointReservePerRemainingAuctionTeamMemberSlot: 10,
minimumBidRequestResultReplayWindowMS: 60_000,
});
expect(invocation.script).toBe(AUCTION_BID_SCRIPT);
expect(invocation.keys).toEqual([
'auction:match-1:liveAuctionState',
'auction:match-1:auctionBidHistory',
'auction:match-1:bidRequestResults',
'auction:match-1:bidRequestResultOrder',
'auction:bidRoundDeadlineQueue',
'auction:match-1:rejectedBidRequestResultOrder',
'auction:bidArchiveQueue',
'auction:bidArchivePayloads',
]);
expect(invocation.values).toEqual([
'match-1',
'2',
'120',
'5',
'10',
'bid-1',
'captain-2',
'life-1',
'player-1',
'match-1|life-1|player-1|2|120',
'100',
'60000',
'200',
'',
]);
});
it('keeps bid fingerprints stable and timestamp-free', () => {
expect(
buildBidRequestPayloadFingerprint({
bidderTeamIndex: 2,
bidPointAmount: 120,
clientObservedAuctionLifecycleId: 'life-1',
clientObservedCurrentBidRoundPlayerUserId: 'player-1',
matchId: 'match-1',
}),
).toBe('match-1|life-1|player-1|2|120');
});
it('uses Redis TIME and scalar hash fields rather than JSON parsing', () => {
expect(AUCTION_BID_SCRIPT.lua).toContain("redis.call('TIME')");
expect(AUCTION_BID_SCRIPT.lua).toContain("redis.call('HINCRBY'");
expect(AUCTION_BID_SCRIPT.lua).toContain('BID_REQUEST_RESULT_LIMIT');
expect(AUCTION_BID_SCRIPT.lua).toContain('currentHighestBidPointAmount');
expect(AUCTION_BID_SCRIPT.lua).not.toContain('cjson.decode');
});
});
@@ -0,0 +1,371 @@
import type { AuctionRedisKeys } from './auction-redis.keys';
import {
AUCTION_BID_ARCHIVE_QUEUE_KEY,
AUCTION_BID_ARCHIVE_PAYLOADS_KEY,
} from './auction-redis.keys';
import { defineAuctionRedisScript } from './auction-redis.scripts';
export interface AuctionBidScriptInput {
bidderTeamIndex: number;
bidPointAmount: number;
bidRequestId: string;
bidderUserId: string;
clientObservedAuctionLifecycleId: string;
clientObservedCurrentBidRoundPlayerUserId: string;
clientObservedBidRoundId?: string;
maximumAuctionTeamMemberCount: number;
maximumStoredAuctionBidHistoryCount: number;
maximumStoredBidRequestResultCount: number;
matchId: string;
minimumBidPointReservePerRemainingAuctionTeamMemberSlot: number;
minimumBidRequestResultReplayWindowMS: number;
}
export interface AuctionBidScriptInvocation {
keys: string[];
script: typeof AUCTION_BID_SCRIPT;
values: string[];
}
const BID_RESULT_HASH_SUFFIXES = [
'fingerprint',
'status',
'revision',
'rejectCode',
'currentHighestBidPointAmount',
'currentHighestBidderTeamIndex',
'currentBidRoundDeadlineTimestampMS',
'auctionBidHistoryEntryJson',
'responseServerTimestampMS',
'createdAtTimestampMS',
] as const;
export function buildBidRequestPayloadFingerprint(params: {
bidderTeamIndex: number;
bidPointAmount: number;
clientObservedAuctionLifecycleId: string;
clientObservedCurrentBidRoundPlayerUserId: string;
clientObservedBidRoundId?: string;
matchId: string;
}): string {
const parts = [
params.matchId,
params.clientObservedAuctionLifecycleId,
params.clientObservedCurrentBidRoundPlayerUserId,
params.bidderTeamIndex,
params.bidPointAmount,
];
if (params.clientObservedBidRoundId)
parts.push(params.clientObservedBidRoundId);
return parts.join('|');
}
export function buildAuctionBidScriptInvocation(
keys: AuctionRedisKeys,
input: AuctionBidScriptInput,
): AuctionBidScriptInvocation {
return {
keys: [
keys.liveStateKey,
keys.bidHistoryKey,
keys.bidRequestResultsKey,
keys.bidRequestResultOrderKey,
keys.deadlineQueueKey,
keys.rejectedBidRequestResultOrderKey,
AUCTION_BID_ARCHIVE_QUEUE_KEY,
AUCTION_BID_ARCHIVE_PAYLOADS_KEY,
],
script: AUCTION_BID_SCRIPT,
values: [
input.matchId,
String(input.bidderTeamIndex),
String(input.bidPointAmount),
String(input.maximumAuctionTeamMemberCount),
String(input.minimumBidPointReservePerRemainingAuctionTeamMemberSlot),
input.bidRequestId,
input.bidderUserId,
input.clientObservedAuctionLifecycleId,
input.clientObservedCurrentBidRoundPlayerUserId,
buildBidRequestPayloadFingerprint(input),
String(input.maximumStoredBidRequestResultCount),
String(input.minimumBidRequestResultReplayWindowMS),
String(input.maximumStoredAuctionBidHistoryCount),
input.clientObservedBidRoundId ?? '',
],
};
}
export const AUCTION_BID_SCRIPT = defineAuctionRedisScript(
'auction.bid',
`
local liveAuctionStateKey = KEYS[1]
local auctionBidHistoryKey = KEYS[2]
local bidRequestResultsKey = KEYS[3]
local bidRequestResultOrderKey = KEYS[4]
local bidRoundDeadlineQueueKey = KEYS[5]
local rejectedBidRequestResultOrderKey = KEYS[6]
local bidArchiveQueueKey = KEYS[7]
local bidArchivePayloadsKey = KEYS[8]
local matchId = ARGV[1]
local bidderTeamIndex = ARGV[2]
local bidPointAmount = tonumber(ARGV[3])
local maximumAuctionTeamMemberCount = tonumber(ARGV[4])
local minimumBidPointReservePerRemainingAuctionTeamMemberSlot = tonumber(ARGV[5])
local bidRequestId = ARGV[6]
local bidderUserId = ARGV[7]
local clientObservedAuctionLifecycleId = ARGV[8]
local clientObservedCurrentBidRoundPlayerUserId = ARGV[9]
local bidRequestPayloadFingerprint = ARGV[10]
local maximumStoredBidRequestResultCount = tonumber(ARGV[11])
local minimumBidRequestResultReplayWindowMS = tonumber(ARGV[12])
local maximumStoredAuctionBidHistoryCount = tonumber(ARGV[13])
local clientObservedBidRoundId = ARGV[14] or ''
local redisTime = redis.call('TIME')
local currentRedisTimestampMS = (tonumber(redisTime[1]) * 1000) + math.floor(tonumber(redisTime[2]) / 1000)
local function requestField(suffix)
return bidRequestId .. ':' .. suffix
end
local function hdelBidRequest(requestId)
redis.call(
'HDEL',
bidRequestResultsKey,
requestId .. ':fingerprint',
requestId .. ':status',
requestId .. ':revision',
requestId .. ':rejectCode',
requestId .. ':currentHighestBidPointAmount',
requestId .. ':currentHighestBidderTeamIndex',
requestId .. ':currentBidRoundDeadlineTimestampMS',
requestId .. ':auctionBidHistoryEntryJson',
requestId .. ':responseServerTimestampMS',
requestId .. ':createdAtTimestampMS'
)
end
local function trimOldBidRequestResults()
while redis.call('LLEN', bidRequestResultOrderKey) >= maximumStoredBidRequestResultCount do
local oldestBidRequestId = redis.call('LINDEX', bidRequestResultOrderKey, 0)
if not oldestBidRequestId then
return
end
local createdAtTimestampMS = tonumber(redis.call('HGET', bidRequestResultsKey, oldestBidRequestId .. ':createdAtTimestampMS') or '0')
if createdAtTimestampMS > currentRedisTimestampMS - minimumBidRequestResultReplayWindowMS then
return
end
redis.call('LPOP', bidRequestResultOrderKey)
hdelBidRequest(oldestBidRequestId)
end
end
local function replayExistingRequest()
local status = redis.call('HGET', bidRequestResultsKey, requestField('status')) or ''
return {
'REPLAY',
status,
bidRequestId,
redis.call('HGET', bidRequestResultsKey, requestField('revision')) or '',
redis.call('HGET', bidRequestResultsKey, requestField('rejectCode')) or '',
redis.call('HGET', bidRequestResultsKey, requestField('currentHighestBidPointAmount')) or '',
redis.call('HGET', bidRequestResultsKey, requestField('currentHighestBidderTeamIndex')) or '',
redis.call('HGET', bidRequestResultsKey, requestField('currentBidRoundDeadlineTimestampMS')) or '',
redis.call('HGET', bidRequestResultsKey, requestField('auctionBidHistoryEntryJson')) or '',
redis.call('HGET', bidRequestResultsKey, requestField('responseServerTimestampMS')) or tostring(currentRedisTimestampMS)
}
end
local existingFingerprint = redis.call('HGET', bidRequestResultsKey, requestField('fingerprint'))
if existingFingerprint then
if existingFingerprint ~= bidRequestPayloadFingerprint then
return {'REJECTED', 'DUPLICATE_REQUEST_CONFLICT', bidRequestId, tostring(currentRedisTimestampMS)}
end
return replayExistingRequest()
end
-- Upgrade the old shared queue once, preserving every accepted replay record.
if redis.call('HSETNX', bidRequestResultsKey, '_acceptedOnlyOrderV1', '1') == 1 then
for _, oldRequestId in ipairs(redis.call('LRANGE', bidRequestResultOrderKey, 0, -1)) do
if redis.call('HGET', bidRequestResultsKey, oldRequestId .. ':status') == 'rejected' then
redis.call('LREM', bidRequestResultOrderKey, 0, oldRequestId)
hdelBidRequest(oldRequestId)
end
end
end
local function storeRejectedRequest(rejectCode)
-- Rejections have their own bounded retention. They must never consume the
-- protected replay capacity of accepted bids.
while redis.call('LLEN', rejectedBidRequestResultOrderKey) >= maximumStoredBidRequestResultCount do
local oldest = redis.call('LPOP', rejectedBidRequestResultOrderKey)
if oldest then hdelBidRequest(oldest) end
end
local rejectedCurrentBidRoundDeadlineTimestampMS = redis.call('HGET', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS') or ''
redis.call(
'HSET',
bidRequestResultsKey,
requestField('fingerprint'),
bidRequestPayloadFingerprint,
requestField('status'),
'rejected',
requestField('rejectCode'),
rejectCode,
requestField('currentBidRoundDeadlineTimestampMS'),
rejectedCurrentBidRoundDeadlineTimestampMS,
requestField('responseServerTimestampMS'),
tostring(currentRedisTimestampMS),
requestField('createdAtTimestampMS'),
tostring(currentRedisTimestampMS)
)
redis.call('RPUSH', rejectedBidRequestResultOrderKey, bidRequestId)
return {'REJECTED', rejectCode, bidRequestId, tostring(currentRedisTimestampMS), rejectedCurrentBidRoundDeadlineTimestampMS}
end
local phase = redis.call('HGET', liveAuctionStateKey, 'phase')
if phase ~= 'bidding' then
return storeRejectedRequest('PHASE')
end
local auctionLifecycleId = redis.call('HGET', liveAuctionStateKey, 'auctionLifecycleId')
local currentBidRoundPlayerUserId = redis.call('HGET', liveAuctionStateKey, 'currentBidRoundPlayerUserId')
local currentBidRoundId = redis.call('HGET', liveAuctionStateKey, 'currentBidRoundId') or ''
if currentBidRoundId ~= '' and clientObservedBidRoundId == '' then
return storeRejectedRequest('BID_CLIENT_UPDATE_REQUIRED')
end
if auctionLifecycleId ~= clientObservedAuctionLifecycleId or currentBidRoundPlayerUserId ~= clientObservedCurrentBidRoundPlayerUserId then
return storeRejectedRequest('STALE_BID_ROUND')
end
if currentBidRoundId ~= clientObservedBidRoundId then
return storeRejectedRequest('STALE_BID_ROUND')
end
local currentBidRoundDeadlineTimestampMS = tonumber(redis.call('HGET', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS') or '0')
if currentBidRoundDeadlineTimestampMS <= currentRedisTimestampMS then
return storeRejectedRequest('EXPIRED')
end
local currentHighestBidPointAmount = tonumber(redis.call('HGET', liveAuctionStateKey, 'currentHighestBidPointAmount') or '0')
if bidPointAmount <= currentHighestBidPointAmount then
return storeRejectedRequest('TOO_LOW')
end
local remainingBidPointAmountField = 'team:' .. bidderTeamIndex .. ':remainingBidPointAmount'
local assignedAuctionTeamMemberCountField = 'team:' .. bidderTeamIndex .. ':assignedAuctionTeamMemberCount'
local remainingBidPointAmountRaw = redis.call('HGET', liveAuctionStateKey, remainingBidPointAmountField)
if not remainingBidPointAmountRaw then
return storeRejectedRequest('UNKNOWN_TEAM')
end
local assignedAuctionTeamMemberCount = tonumber(redis.call('HGET', liveAuctionStateKey, assignedAuctionTeamMemberCountField) or '0')
if assignedAuctionTeamMemberCount >= maximumAuctionTeamMemberCount then
return storeRejectedRequest('FULL')
end
local remainingBidPointAmount = tonumber(remainingBidPointAmountRaw)
local remainingSlotsAfterBid = maximumAuctionTeamMemberCount - assignedAuctionTeamMemberCount - 1
local requiredReserveAfterBid = remainingSlotsAfterBid * minimumBidPointReservePerRemainingAuctionTeamMemberSlot
if bidPointAmount + requiredReserveAfterBid > remainingBidPointAmount then
return storeRejectedRequest('INSUFFICIENT')
end
trimOldBidRequestResults()
if redis.call('LLEN', bidRequestResultOrderKey) >= maximumStoredBidRequestResultCount then
return {'REJECTED', 'BID_REQUEST_RESULT_LIMIT', bidRequestId, tostring(currentRedisTimestampMS)}
end
local maximumBidRoundDurationSeconds = tonumber(redis.call('HGET', liveAuctionStateKey, 'maximumBidRoundDurationSeconds') or '0')
local bidRoundExtensionSeconds = tonumber(redis.call('HGET', liveAuctionStateKey, 'bidRoundExtensionSeconds') or '0')
local remainingBidRoundTimeMS = currentBidRoundDeadlineTimestampMS - currentRedisTimestampMS
local nextRemainingBidRoundTimeMS = remainingBidRoundTimeMS
local bidRoundExtensionMS = bidRoundExtensionSeconds * 1000
local maximumBidRoundDurationMS = maximumBidRoundDurationSeconds * 1000
if nextRemainingBidRoundTimeMS < bidRoundExtensionMS then
nextRemainingBidRoundTimeMS = bidRoundExtensionMS
end
if nextRemainingBidRoundTimeMS > maximumBidRoundDurationMS then
nextRemainingBidRoundTimeMS = maximumBidRoundDurationMS
end
local nextBidRoundDeadlineTimestampMS = currentRedisTimestampMS + nextRemainingBidRoundTimeMS
local revision = redis.call('HINCRBY', liveAuctionStateKey, 'revision', 1)
local auctionBidHistoryEntryJson = cjson.encode({
bidRequestId = bidRequestId,
revision = revision,
bidderTeamIndex = tonumber(bidderTeamIndex),
bidPointAmount = bidPointAmount,
bidderUserId = bidderUserId,
playerUserId = currentBidRoundPlayerUserId,
bidRoundId = currentBidRoundId,
bidPlacedAtTimestampMS = currentRedisTimestampMS
})
-- Accepted replay returns above this point. Persist every accepted event before
-- trimming the recent view; the durable archive worker removes only saved events.
local archiveId = matchId .. ':' .. auctionLifecycleId .. ':' .. string.format('%016d', revision)
redis.call('HSET', bidArchivePayloadsKey, archiveId, cjson.encode({
_id = archiveId,
matchId = matchId,
auctionLifecycleId = auctionLifecycleId,
revision = revision,
bidRequestId = bidRequestId,
bidderTeamIndex = tonumber(bidderTeamIndex),
bidPointAmount = bidPointAmount,
bidderUserId = bidderUserId,
playerUserId = currentBidRoundPlayerUserId,
bidRoundId = currentBidRoundId,
bidPlacedAtTimestampMS = currentRedisTimestampMS
}))
redis.call('ZADD', bidArchiveQueueKey, currentRedisTimestampMS, archiveId)
redis.call('RPUSH', auctionBidHistoryKey, auctionBidHistoryEntryJson)
redis.call('LTRIM', auctionBidHistoryKey, -maximumStoredAuctionBidHistoryCount, -1)
redis.call(
'HSET',
liveAuctionStateKey,
'currentHighestBidPointAmount',
tostring(bidPointAmount),
'currentHighestBidderTeamIndex',
bidderTeamIndex,
'currentBidRoundDeadlineTimestampMS',
tostring(nextBidRoundDeadlineTimestampMS)
)
redis.call('ZADD', bidRoundDeadlineQueueKey, nextBidRoundDeadlineTimestampMS, matchId)
redis.call(
'HSET',
bidRequestResultsKey,
requestField('fingerprint'),
bidRequestPayloadFingerprint,
requestField('status'),
'ok',
requestField('revision'),
tostring(revision),
requestField('currentHighestBidPointAmount'),
tostring(bidPointAmount),
requestField('currentHighestBidderTeamIndex'),
bidderTeamIndex,
requestField('currentBidRoundDeadlineTimestampMS'),
tostring(nextBidRoundDeadlineTimestampMS),
requestField('auctionBidHistoryEntryJson'),
auctionBidHistoryEntryJson,
requestField('responseServerTimestampMS'),
tostring(currentRedisTimestampMS),
requestField('createdAtTimestampMS'),
tostring(currentRedisTimestampMS)
)
redis.call('RPUSH', bidRequestResultOrderKey, bidRequestId)
return {
'OK',
bidRequestId,
tostring(revision),
tostring(currentRedisTimestampMS),
tostring(bidPointAmount),
bidderTeamIndex,
tostring(nextBidRoundDeadlineTimestampMS),
auctionBidHistoryEntryJson
}
`,
);
export const BID_RESULT_HASH_FIELD_SUFFIXES = BID_RESULT_HASH_SUFFIXES;
@@ -0,0 +1,27 @@
import { defineAuctionRedisScript } from './auction-redis.scripts';
// Compare the lifecycle and remove the payload and its indexes atomically.
export const AUCTION_CLEANUP_DURABILITY_SCRIPT = defineAuctionRedisScript(
'auction.cleanupDurability',
`
local deleted = 0
for i = 3, #KEYS do
local key = KEYS[i]
local keyType = redis.call('TYPE', key).ok
local matches = ARGV[1] == ''
if not matches and keyType == 'hash' then
matches = redis.call('HGET', key, 'auctionLifecycleId') == ARGV[1]
elseif not matches and keyType == 'string' then
-- Retain compatibility with payloads written before the Hash format.
local ok, payload = pcall(cjson.decode, redis.call('GET', key))
matches = ok and type(payload) == 'table' and payload.auctionLifecycleId == ARGV[1]
end
if matches then
redis.call('ZREM', KEYS[1], key)
redis.call('ZREM', KEYS[2], key)
deleted = deleted + redis.call('UNLINK', key)
end
end
return deleted
`,
);
@@ -0,0 +1 @@
export const AUCTION_REDIS_CLIENT = Symbol('AUCTION_REDIS_CLIENT');
@@ -0,0 +1,38 @@
import { buildAuctionRedisKeys } from './auction-redis.keys';
import {
AUCTION_EXPIRE_PREPARE_SCRIPT,
buildAuctionExpirePrepareScriptInvocation,
} from './auction-redis.expire-prepare';
describe('auction expire prepare redis script contract', () => {
it('builds EXPIRE_PREPARE keys and values', () => {
const invocation = buildAuctionExpirePrepareScriptInvocation(
buildAuctionRedisKeys('match-1'),
{
auctionStateTransitionId: 'expire-1',
bidRoundExpiryRetryDelayMS: 3_000,
matchId: 'match-1',
},
);
expect(invocation.script).toBe(AUCTION_EXPIRE_PREPARE_SCRIPT);
expect(invocation.keys).toEqual([
'auction:match-1:liveAuctionState',
'auction:bidRoundDeadlineQueue',
]);
expect(invocation.values).toEqual(['match-1', 'expire-1', '3000']);
});
it('freezes expiry context with Redis TIME and expiring phase', () => {
expect(AUCTION_EXPIRE_PREPARE_SCRIPT.lua).toContain("redis.call('TIME')");
expect(AUCTION_EXPIRE_PREPARE_SCRIPT.lua).toContain("'phase'");
expect(AUCTION_EXPIRE_PREPARE_SCRIPT.lua).toContain("'expiring'");
expect(AUCTION_EXPIRE_PREPARE_SCRIPT.lua).toContain(
'bidRoundExpiryRevision',
);
expect(AUCTION_EXPIRE_PREPARE_SCRIPT.lua).toContain(
'bidRoundExpiryWinningBidderTeamIndex',
);
expect(AUCTION_EXPIRE_PREPARE_SCRIPT.lua).toContain("'ZADD'");
});
});
@@ -0,0 +1,107 @@
import type { AuctionRedisKeys } from './auction-redis.keys';
import { defineAuctionRedisScript } from './auction-redis.scripts';
export interface AuctionExpirePrepareScriptInput {
auctionStateTransitionId: string;
bidRoundExpiryRetryDelayMS: number;
matchId: string;
}
export interface AuctionExpirePrepareScriptInvocation {
keys: string[];
script: typeof AUCTION_EXPIRE_PREPARE_SCRIPT;
values: string[];
}
export function buildAuctionExpirePrepareScriptInvocation(
keys: AuctionRedisKeys,
input: AuctionExpirePrepareScriptInput,
): AuctionExpirePrepareScriptInvocation {
return {
keys: [keys.liveStateKey, keys.deadlineQueueKey],
script: AUCTION_EXPIRE_PREPARE_SCRIPT,
values: [
input.matchId,
input.auctionStateTransitionId,
String(input.bidRoundExpiryRetryDelayMS),
],
};
}
export const AUCTION_EXPIRE_PREPARE_SCRIPT = defineAuctionRedisScript(
'auction.expirePrepare',
`
local liveAuctionStateKey = KEYS[1]
local bidRoundDeadlineQueueKey = KEYS[2]
local matchId = ARGV[1]
local auctionStateTransitionId = ARGV[2]
local bidRoundExpiryRetryDelayMS = tonumber(ARGV[3])
local redisTime = redis.call('TIME')
local currentRedisTimestampMS = (tonumber(redisTime[1]) * 1000) + math.floor(tonumber(redisTime[2]) / 1000)
local phase = redis.call('HGET', liveAuctionStateKey, 'phase')
if phase == 'expiring' then
return {
'REPLAY',
redis.call('HGET', liveAuctionStateKey, 'bidRoundExpiryDecision') or '',
redis.call('HGET', liveAuctionStateKey, 'bidRoundExpiryAuctionStateTransitionId') or '',
redis.call('HGET', liveAuctionStateKey, 'bidRoundExpiryRevision') or '',
tostring(currentRedisTimestampMS)
}
end
if phase ~= 'bidding' then
redis.call('ZREM', bidRoundDeadlineQueueKey, matchId)
return {'NOOP', 'PHASE', tostring(currentRedisTimestampMS)}
end
local currentBidRoundDeadlineTimestampMS = tonumber(redis.call('HGET', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS') or '0')
if currentBidRoundDeadlineTimestampMS > currentRedisTimestampMS then
return {'NOOP', 'NOT_DUE', tostring(currentRedisTimestampMS)}
end
local currentHighestBidPointAmount = tonumber(redis.call('HGET', liveAuctionStateKey, 'currentHighestBidPointAmount') or '0')
local currentHighestBidderTeamIndex = redis.call('HGET', liveAuctionStateKey, 'currentHighestBidderTeamIndex') or '-1'
local bidRoundExpiryDecision = 'passed'
if currentHighestBidPointAmount > 0 then
bidRoundExpiryDecision = 'sold'
end
local revision = redis.call('HINCRBY', liveAuctionStateKey, 'revision', 1)
redis.call(
'HSET',
liveAuctionStateKey,
'phase',
'expiring',
'bidRoundExpiryDecision',
bidRoundExpiryDecision,
'bidRoundExpiryAuctionStateTransitionId',
auctionStateTransitionId,
'bidRoundExpiryPlayerUserId',
redis.call('HGET', liveAuctionStateKey, 'currentBidRoundPlayerUserId') or '',
'bidRoundExpiryPlayerOrderIndex',
redis.call('HGET', liveAuctionStateKey, 'currentAuctionPlayerOrderIndex') or '',
'bidRoundExpiryWinningBidPointAmount',
tostring(currentHighestBidPointAmount),
'bidRoundExpiryWinningBidderTeamIndex',
currentHighestBidderTeamIndex,
'bidRoundExpiryRevision',
tostring(revision)
)
redis.call(
'ZADD',
bidRoundDeadlineQueueKey,
currentRedisTimestampMS + bidRoundExpiryRetryDelayMS,
matchId
)
return {
'OK',
bidRoundExpiryDecision,
auctionStateTransitionId,
tostring(revision),
tostring(currentRedisTimestampMS)
}
`,
);
@@ -0,0 +1,31 @@
import { buildAuctionRedisKeys } from './auction-redis.keys';
describe('auction redis keys', () => {
it('builds lifecycle-safe key names from match id', () => {
expect(buildAuctionRedisKeys('match-1')).toMatchObject({
actionRequestResultOrderKey:
'auction:match-1:auctionActionRequestResultOrder',
actionRequestResultsKey: 'auction:match-1:auctionActionRequestResults',
appliedTransitionIdsKey:
'auction:match-1:appliedAuctionStateTransitionIds',
bidHistoryKey: 'auction:match-1:auctionBidHistory',
bidRequestResultOrderKey: 'auction:match-1:bidRequestResultOrder',
bidRequestResultsKey: 'auction:match-1:bidRequestResults',
deadlineQueueKey: 'auction:bidRoundDeadlineQueue',
durabilityDeadLetterQueueKey: 'auction:auctionDurabilityDeadLetterQueue',
durabilityPayloadKeyPrefix: 'auction:match-1:durability:',
durabilityRetryQueueKey: 'auction:auctionDurabilityRetryQueue',
liveStateKey: 'auction:match-1:liveAuctionState',
rehydrateLockKey: 'auction:match-1:rehydrateLock',
stateTransitionLockKey: 'auction:match-1:auctionStateTransitionLock',
structureStateKey: 'auction:match-1:auctionStructureState',
});
});
it('builds transition durability payload keys', () => {
const keys = buildAuctionRedisKeys('match-1');
expect(keys.durabilityPayloadKey('transition-1')).toBe(
'auction:match-1:durability:transition-1',
);
});
});
@@ -0,0 +1,57 @@
export const AUCTION_BID_ROUND_DEADLINE_QUEUE_KEY =
'auction:bidRoundDeadlineQueue';
export const AUCTION_DURABILITY_RETRY_QUEUE_KEY =
'auction:auctionDurabilityRetryQueue';
export const AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY =
'auction:auctionDurabilityDeadLetterQueue';
export const AUCTION_DEAD_LETTER_STATUS_QUEUE_KEY =
'auction:deadLetterStatusQueue';
export const AUCTION_BID_ARCHIVE_QUEUE_KEY = 'auction:bidArchiveQueue';
export const AUCTION_BID_ARCHIVE_PAYLOADS_KEY = 'auction:bidArchivePayloads';
export const AUCTION_BID_ARCHIVE_DEAD_LETTER_QUEUE_KEY =
'auction:bidArchiveDeadLetterQueue';
export const AUCTION_BID_ARCHIVE_DEAD_LETTER_PAYLOADS_KEY =
'auction:bidArchiveDeadLetterPayloads';
export interface AuctionRedisKeys {
actionRequestResultOrderKey: string;
actionRequestResultsKey: string;
appliedTransitionIdsKey: string;
bidHistoryKey: string;
bidRequestResultOrderKey: string;
bidRequestResultsKey: string;
rejectedBidRequestResultOrderKey: string;
deadlineQueueKey: string;
durabilityDeadLetterQueueKey: string;
durabilityPayloadKey: (auctionStateTransitionId: string) => string;
durabilityPayloadKeyPrefix: string;
durabilityRetryQueueKey: string;
liveStateKey: string;
rehydrateLockKey: string;
stateTransitionLockKey: string;
structureStateKey: string;
}
export function buildAuctionRedisKeys(matchId: string): AuctionRedisKeys {
const prefix = `auction:${matchId}`;
const durabilityPayloadKeyPrefix = `${prefix}:durability:`;
return {
actionRequestResultOrderKey: `${prefix}:auctionActionRequestResultOrder`,
actionRequestResultsKey: `${prefix}:auctionActionRequestResults`,
appliedTransitionIdsKey: `${prefix}:appliedAuctionStateTransitionIds`,
bidHistoryKey: `${prefix}:auctionBidHistory`,
bidRequestResultOrderKey: `${prefix}:bidRequestResultOrder`,
bidRequestResultsKey: `${prefix}:bidRequestResults`,
rejectedBidRequestResultOrderKey: `${prefix}:rejectedBidRequestResultOrder`,
deadlineQueueKey: AUCTION_BID_ROUND_DEADLINE_QUEUE_KEY,
durabilityDeadLetterQueueKey: AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY,
durabilityPayloadKey: (auctionStateTransitionId: string) =>
`${durabilityPayloadKeyPrefix}${auctionStateTransitionId}`,
durabilityPayloadKeyPrefix,
durabilityRetryQueueKey: AUCTION_DURABILITY_RETRY_QUEUE_KEY,
liveStateKey: `${prefix}:liveAuctionState`,
rehydrateLockKey: `${prefix}:rehydrateLock`,
stateTransitionLockKey: `${prefix}:auctionStateTransitionLock`,
structureStateKey: `${prefix}:auctionStructureState`,
};
}
@@ -0,0 +1,52 @@
import { Logger, Module } from '@nestjs/common';
import { createClient } from 'redis';
import { SecretModule } from '../../global/secret/secret.module';
import { SecretService } from '../../global/secret/secret.service';
import { loadRedisClientOptions } from '../../global/redis/redis.config';
import { AUCTION_REDIS_CLIENT } from './auction-redis.constants';
import {
AuctionRedisService,
type AuctionRedisClient,
} from './auction-redis.service';
import { AuctionRedisCommandService } from './auction-redis-command.service';
import { AuctionRedisStateReaderService } from './auction-redis-state-reader.service';
@Module({
imports: [SecretModule],
providers: [
{
provide: AUCTION_REDIS_CLIENT,
inject: [SecretService],
useFactory: async (
secretService: SecretService,
): Promise<AuctionRedisClient> => {
const logger = new Logger('AuctionRedisClient');
const client = createClient(
await loadRedisClientOptions(secretService),
);
client.on('error', (error: unknown) => {
logger.error(
`Auction Redis client error: ${
error instanceof Error ? error.message : String(error)
}`,
);
});
await client.connect();
logger.log('Auction Redis connected');
return client;
},
},
AuctionRedisService,
AuctionRedisCommandService,
AuctionRedisStateReaderService,
],
exports: [
AuctionRedisService,
AuctionRedisCommandService,
AuctionRedisStateReaderService,
AUCTION_REDIS_CLIENT,
],
})
export class AuctionRedisModule {}
@@ -0,0 +1,77 @@
import { buildAuctionRedisKeys } from './auction-redis.keys';
import {
AUCTION_RESERVE_ACTION_REQUEST_SCRIPT,
buildActionRequestPayloadFingerprint,
buildAuctionReserveActionRequestScriptInvocation,
} from './auction-redis.reserve-action';
describe('auction reserve action request redis script contract', () => {
it('builds RESERVE_AUCTION_ACTION_REQUEST keys and values', () => {
const invocation = buildAuctionReserveActionRequestScriptInvocation(
buildAuctionRedisKeys('match-1'),
{
auctionActionRequestId: 'request-1',
auctionActionType: 'sold',
auctionStateTransitionId: 'transition-1',
clientObservedAuctionLifecycleId: 'life-1',
clientObservedPhase: 'bidding',
clientObservedRevision: 8,
leaseDurationMS: 10_000,
maximumStoredAuctionActionRequestResultCount: 100,
minimumAuctionActionRequestResultReplayWindowMS: 60_000,
newAuctionLifecycleId: undefined,
processingOwnerToken: 'owner-1',
},
);
expect(invocation.script).toBe(AUCTION_RESERVE_ACTION_REQUEST_SCRIPT);
expect(invocation.keys).toEqual([
'auction:match-1:auctionActionRequestResults',
'auction:match-1:auctionActionRequestResultOrder',
]);
expect(invocation.values).toEqual([
'life-1',
'request-1',
'sold',
'transition-1',
'',
'owner-1',
'10000',
'100',
'60000',
'life-1|request-1|sold|8|bidding||',
]);
});
it('builds stable action request fingerprints', () => {
expect(
buildActionRequestPayloadFingerprint({
auctionActionRequestId: 'request-1',
auctionActionType: 'next',
clientObservedAuctionLifecycleId: 'life-1',
clientObservedCurrentAuctionPlayerOrderIndex: 3,
clientObservedCurrentBidRoundPlayerUserId: 'player-1',
clientObservedPhase: 'sold',
clientObservedRevision: 9,
}),
).toBe('life-1|request-1|next|9|sold|player-1|3');
});
it('keeps lease version and replay guards in Lua', () => {
expect(AUCTION_RESERVE_ACTION_REQUEST_SCRIPT.lua).toContain(
"redis.call('TIME')",
);
expect(AUCTION_RESERVE_ACTION_REQUEST_SCRIPT.lua).toContain(
'processingLeaseVersion',
);
expect(AUCTION_RESERVE_ACTION_REQUEST_SCRIPT.lua).toContain(
'ACTION_REQUEST_IN_PROGRESS',
);
expect(AUCTION_RESERVE_ACTION_REQUEST_SCRIPT.lua).toContain(
'ACTION_REQUEST_RESULT_LIMIT',
);
expect(AUCTION_RESERVE_ACTION_REQUEST_SCRIPT.lua).toContain(
'DUPLICATE_ACTION_REQUEST_CONFLICT',
);
});
});
@@ -0,0 +1,233 @@
import type { AuctionRedisKeys } from './auction-redis.keys';
import { defineAuctionRedisScript } from './auction-redis.scripts';
export interface AuctionReserveActionRequestScriptInput {
auctionActionRequestId: string;
auctionActionType: string;
auctionStateTransitionId: string;
clientObservedAuctionLifecycleId: string;
clientObservedCurrentAuctionPlayerOrderIndex?: number;
clientObservedCurrentBidRoundPlayerUserId?: string;
clientObservedPhase: string;
clientObservedRevision: number;
leaseDurationMS: number;
maximumStoredAuctionActionRequestResultCount: number;
minimumAuctionActionRequestResultReplayWindowMS: number;
newAuctionLifecycleId?: string;
processingOwnerToken: string;
}
export interface AuctionReserveActionRequestScriptInvocation {
keys: string[];
script: typeof AUCTION_RESERVE_ACTION_REQUEST_SCRIPT;
values: string[];
}
export function buildActionRequestPayloadFingerprint(params: {
auctionActionRequestId: string;
auctionActionType: string;
clientObservedAuctionLifecycleId: string;
clientObservedCurrentAuctionPlayerOrderIndex?: number;
clientObservedCurrentBidRoundPlayerUserId?: string;
clientObservedPhase: string;
clientObservedRevision: number;
}): string {
return [
params.clientObservedAuctionLifecycleId,
params.auctionActionRequestId,
params.auctionActionType,
params.clientObservedRevision,
params.clientObservedPhase,
params.clientObservedCurrentBidRoundPlayerUserId ?? '',
params.clientObservedCurrentAuctionPlayerOrderIndex ?? '',
].join('|');
}
export function buildAuctionReserveActionRequestScriptInvocation(
keys: AuctionRedisKeys,
input: AuctionReserveActionRequestScriptInput,
): AuctionReserveActionRequestScriptInvocation {
return {
keys: [keys.actionRequestResultsKey, keys.actionRequestResultOrderKey],
script: AUCTION_RESERVE_ACTION_REQUEST_SCRIPT,
values: [
input.clientObservedAuctionLifecycleId,
input.auctionActionRequestId,
input.auctionActionType,
input.auctionStateTransitionId,
input.newAuctionLifecycleId ?? '',
input.processingOwnerToken,
String(input.leaseDurationMS),
String(input.maximumStoredAuctionActionRequestResultCount),
String(input.minimumAuctionActionRequestResultReplayWindowMS),
buildActionRequestPayloadFingerprint(input),
],
};
}
export const AUCTION_RESERVE_ACTION_REQUEST_SCRIPT = defineAuctionRedisScript(
'auction.reserveActionRequest',
`
local auctionActionRequestResultsKey = KEYS[1]
local auctionActionRequestResultOrderKey = KEYS[2]
local clientObservedAuctionLifecycleId = ARGV[1]
local auctionActionRequestId = ARGV[2]
local auctionActionType = ARGV[3]
local auctionStateTransitionId = ARGV[4]
local newAuctionLifecycleId = ARGV[5]
local processingOwnerToken = ARGV[6]
local leaseDurationMS = tonumber(ARGV[7])
local maximumStoredAuctionActionRequestResultCount = tonumber(ARGV[8])
local minimumAuctionActionRequestResultReplayWindowMS = tonumber(ARGV[9])
local actionRequestPayloadFingerprint = ARGV[10]
local redisTime = redis.call('TIME')
local currentRedisTimestampMS = (tonumber(redisTime[1]) * 1000) + math.floor(tonumber(redisTime[2]) / 1000)
local actionRequestScopeKey = clientObservedAuctionLifecycleId .. ':' .. auctionActionRequestId
local function requestField(suffix)
return actionRequestScopeKey .. ':' .. suffix
end
local function hdelActionRequest(scopeKey)
redis.call(
'HDEL',
auctionActionRequestResultsKey,
scopeKey .. ':fingerprint',
scopeKey .. ':status',
scopeKey .. ':revision',
scopeKey .. ':rejectCode',
scopeKey .. ':auctionActionType',
scopeKey .. ':auctionStateTransitionId',
scopeKey .. ':newAuctionLifecycleId',
scopeKey .. ':processingOwnerToken',
scopeKey .. ':processingLeaseExpiresAtTimestampMS',
scopeKey .. ':processingLeaseVersion',
scopeKey .. ':responseServerTimestampMS',
scopeKey .. ':responseJson',
scopeKey .. ':requiresRefetch',
scopeKey .. ':createdAtTimestampMS'
)
end
local function trimOldActionRequestResults()
while redis.call('LLEN', auctionActionRequestResultOrderKey) >= maximumStoredAuctionActionRequestResultCount do
local oldestActionRequestScopeKey = redis.call('LINDEX', auctionActionRequestResultOrderKey, 0)
if not oldestActionRequestScopeKey then
return
end
local createdAtTimestampMS = tonumber(redis.call('HGET', auctionActionRequestResultsKey, oldestActionRequestScopeKey .. ':createdAtTimestampMS') or '0')
if createdAtTimestampMS > currentRedisTimestampMS - minimumAuctionActionRequestResultReplayWindowMS then
return
end
redis.call('LPOP', auctionActionRequestResultOrderKey)
hdelActionRequest(oldestActionRequestScopeKey)
end
end
local existingFingerprint = redis.call('HGET', auctionActionRequestResultsKey, requestField('fingerprint'))
if existingFingerprint then
if existingFingerprint ~= actionRequestPayloadFingerprint then
return {'REJECTED', 'DUPLICATE_ACTION_REQUEST_CONFLICT', actionRequestScopeKey, tostring(currentRedisTimestampMS)}
end
local status = redis.call('HGET', auctionActionRequestResultsKey, requestField('status')) or ''
if status == 'applied' or status == 'rejected' then
return {
'REPLAY',
status,
actionRequestScopeKey,
redis.call('HGET', auctionActionRequestResultsKey, requestField('revision')) or '',
redis.call('HGET', auctionActionRequestResultsKey, requestField('rejectCode')) or '',
redis.call('HGET', auctionActionRequestResultsKey, requestField('auctionStateTransitionId')) or '',
redis.call('HGET', auctionActionRequestResultsKey, requestField('newAuctionLifecycleId')) or '',
redis.call('HGET', auctionActionRequestResultsKey, requestField('processingLeaseVersion')) or '',
redis.call('HGET', auctionActionRequestResultsKey, requestField('responseServerTimestampMS')) or tostring(currentRedisTimestampMS),
redis.call('HGET', auctionActionRequestResultsKey, requestField('responseJson')) or '',
redis.call('HGET', auctionActionRequestResultsKey, requestField('requiresRefetch')) or ''
}
end
local leaseExpiresAtTimestampMS = tonumber(redis.call('HGET', auctionActionRequestResultsKey, requestField('processingLeaseExpiresAtTimestampMS')) or '0')
local storedOwnerToken = redis.call('HGET', auctionActionRequestResultsKey, requestField('processingOwnerToken')) or ''
local storedLeaseVersion = tonumber(redis.call('HGET', auctionActionRequestResultsKey, requestField('processingLeaseVersion')) or '1')
if leaseExpiresAtTimestampMS > currentRedisTimestampMS and storedOwnerToken ~= processingOwnerToken then
return {'REJECTED', 'ACTION_REQUEST_IN_PROGRESS', actionRequestScopeKey, tostring(currentRedisTimestampMS)}
end
local nextLeaseVersion = storedLeaseVersion
local wasLeaseExpired = '0'
if leaseExpiresAtTimestampMS <= currentRedisTimestampMS then
nextLeaseVersion = storedLeaseVersion + 1
wasLeaseExpired = '1'
end
redis.call(
'HSET',
auctionActionRequestResultsKey,
requestField('status'),
'processing',
requestField('processingOwnerToken'),
processingOwnerToken,
requestField('processingLeaseExpiresAtTimestampMS'),
tostring(currentRedisTimestampMS + leaseDurationMS),
requestField('processingLeaseVersion'),
tostring(nextLeaseVersion),
requestField('responseServerTimestampMS'),
tostring(currentRedisTimestampMS)
)
return {
'RESERVED',
actionRequestScopeKey,
redis.call('HGET', auctionActionRequestResultsKey, requestField('auctionStateTransitionId')) or auctionStateTransitionId,
redis.call('HGET', auctionActionRequestResultsKey, requestField('newAuctionLifecycleId')) or '',
tostring(nextLeaseVersion),
wasLeaseExpired,
tostring(currentRedisTimestampMS)
}
end
trimOldActionRequestResults()
if redis.call('LLEN', auctionActionRequestResultOrderKey) >= maximumStoredAuctionActionRequestResultCount then
return {'REJECTED', 'ACTION_REQUEST_RESULT_LIMIT', actionRequestScopeKey, tostring(currentRedisTimestampMS)}
end
redis.call(
'HSET',
auctionActionRequestResultsKey,
requestField('fingerprint'),
actionRequestPayloadFingerprint,
requestField('status'),
'processing',
requestField('auctionActionType'),
auctionActionType,
requestField('auctionStateTransitionId'),
auctionStateTransitionId,
requestField('newAuctionLifecycleId'),
newAuctionLifecycleId,
requestField('processingOwnerToken'),
processingOwnerToken,
requestField('processingLeaseExpiresAtTimestampMS'),
tostring(currentRedisTimestampMS + leaseDurationMS),
requestField('processingLeaseVersion'),
'1',
requestField('responseServerTimestampMS'),
tostring(currentRedisTimestampMS),
requestField('createdAtTimestampMS'),
tostring(currentRedisTimestampMS)
)
redis.call('RPUSH', auctionActionRequestResultOrderKey, actionRequestScopeKey)
return {
'RESERVED',
actionRequestScopeKey,
auctionStateTransitionId,
newAuctionLifecycleId,
'1',
'0',
tostring(currentRedisTimestampMS)
}
`,
);
@@ -0,0 +1,14 @@
import { createHash } from 'crypto';
import { defineAuctionRedisScript } from './auction-redis.scripts';
describe('auction redis scripts', () => {
it('stores normalized Lua and its SHA1', () => {
const script = defineAuctionRedisScript('test', 'return 1\n');
expect(script).toEqual({
lua: 'return 1\n',
name: 'test',
sha: createHash('sha1').update('return 1\n').digest('hex'),
});
});
});
@@ -0,0 +1,18 @@
import { createHash } from 'crypto';
export interface AuctionRedisScriptDefinition {
lua: string;
name: string;
sha: string;
}
export function defineAuctionRedisScript(
name: string,
lua: string,
): AuctionRedisScriptDefinition {
return {
lua,
name,
sha: createHash('sha1').update(lua).digest('hex'),
};
}
@@ -0,0 +1,66 @@
import {
AuctionRedisNoscriptError,
AuctionRedisService,
} from './auction-redis.service';
function makeService(sendCommand: jest.Mock) {
const client = {
destroy: jest.fn(),
quit: jest.fn().mockResolvedValue(undefined),
sendCommand,
};
return new AuctionRedisService(client as never);
}
describe('AuctionRedisService', () => {
it('uses Redis TIME as the timestamp source', async () => {
const service = makeService(
jest.fn().mockResolvedValue(['1781700000', '123000']),
);
await expect(service.getCurrentRedisTimestampMS()).resolves.toBe(
1_781_700_000_123,
);
});
it('loads and retries a script once when EVALSHA returns NOSCRIPT', async () => {
const sendCommand = jest
.fn()
.mockRejectedValueOnce(new AuctionRedisNoscriptError())
.mockResolvedValueOnce('sha-from-redis')
.mockResolvedValueOnce(['ok']);
const service = makeService(sendCommand);
await expect(
service.evalShaWithReload({
keys: ['auction:state:1'],
script: 'return 1',
scriptSha: 'old-sha',
values: ['v1'],
}),
).resolves.toEqual(['ok']);
expect(sendCommand.mock.calls).toEqual([
[['EVALSHA', 'old-sha', '1', 'auction:state:1', 'v1']],
[['SCRIPT', 'LOAD', 'return 1']],
[['EVALSHA', 'sha-from-redis', '1', 'auction:state:1', 'v1']],
]);
});
it('does not reload scripts for non-NOSCRIPT errors', async () => {
const error = new Error('OOM command not allowed');
const sendCommand = jest.fn().mockRejectedValue(error);
const service = makeService(sendCommand);
await expect(
service.evalShaWithReload({
keys: [],
script: 'return 1',
scriptSha: 'sha',
values: [],
}),
).rejects.toBe(error);
expect(sendCommand).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,135 @@
import { Inject, Injectable, OnModuleDestroy } from '@nestjs/common';
import type { createClient } from 'redis';
import { AUCTION_REDIS_CLIENT } from './auction-redis.constants';
import type { AuctionRedisScriptDefinition } from './auction-redis.scripts';
export type AuctionRedisClient = ReturnType<typeof createClient>;
export interface EvalShaWithReloadParams {
keys: string[];
script: string;
scriptSha: string;
values: string[];
}
export class AuctionRedisNoscriptError extends Error {
constructor(message = 'NOSCRIPT No matching script. Please use EVAL.') {
super(message);
this.name = 'AuctionRedisNoscriptError';
}
}
function isNoscriptError(error: unknown): boolean {
if (error instanceof AuctionRedisNoscriptError) return true;
const message =
error instanceof Error
? error.message
: typeof error === 'string'
? error
: '';
return /\bNOSCRIPT\b/iu.test(message);
}
function buildEvalShaCommand(
scriptSha: string,
keys: string[],
values: string[],
): string[] {
return ['EVALSHA', scriptSha, String(keys.length), ...keys, ...values];
}
function parseRedisTimeReply(reply: unknown): number {
if (Array.isArray(reply) && reply.length >= 2) {
const seconds = Number(reply[0]);
const microseconds = Number(reply[1]);
if (Number.isFinite(seconds) && Number.isFinite(microseconds)) {
return seconds * 1000 + Math.floor(microseconds / 1000);
}
}
throw new Error(`Unexpected Redis TIME reply: ${JSON.stringify(reply)}`);
}
@Injectable()
export class AuctionRedisService implements OnModuleDestroy {
constructor(
@Inject(AUCTION_REDIS_CLIENT)
private readonly client: AuctionRedisClient,
) {}
async onModuleDestroy() {
try {
await this.client.quit();
} catch {
this.client.destroy();
}
}
public raw(): AuctionRedisClient {
return this.client;
}
public async getCurrentRedisTimestampMS(): Promise<number> {
const reply = await this.client.sendCommand(['TIME']);
return parseRedisTimeReply(reply);
}
public async evalShaWithReload<T = unknown>(
params: EvalShaWithReloadParams,
): Promise<T> {
try {
return (await this.client.sendCommand(
buildEvalShaCommand(params.scriptSha, params.keys, params.values),
)) as T;
} catch (error) {
if (!isNoscriptError(error)) throw error;
}
const loadedShaReply = await this.client.sendCommand([
'SCRIPT',
'LOAD',
params.script,
]);
if (typeof loadedShaReply !== 'string') {
throw new Error('Redis SCRIPT LOAD returned a non-string SHA.');
}
const loadedSha = loadedShaReply;
return (await this.client.sendCommand(
buildEvalShaCommand(loadedSha, params.keys, params.values),
)) as T;
}
public async evalScript<T = unknown>(
script: AuctionRedisScriptDefinition,
keys: string[],
values: string[],
): Promise<T> {
return this.evalShaWithReload<T>({
keys,
script: script.lua,
scriptSha: script.sha,
values,
});
}
public async acquireTokenLock(
key: string,
token: string,
ttlMS: number,
): Promise<boolean> {
const result = await this.client.sendCommand<string | null>([
'SET',
key,
token,
'PX',
String(ttlMS),
'NX',
]);
return result === 'OK';
}
public async releaseTokenLock(key: string, token: string): Promise<boolean> {
const result = await this.client.sendCommand(['DELEX', key, 'IFEQ', token]);
return Number(result) === 1;
}
}
@@ -0,0 +1,109 @@
import { buildAuctionRedisKeys } from './auction-redis.keys';
import {
AUCTION_HYDRATE_STATE_SCRIPT,
assembleAuctionViewFromRedisState,
buildHydrateAuctionStateScriptInvocation,
shouldHydrateRedisAuctionState,
} from './auction-redis.state';
describe('auction redis state assembly', () => {
it.each([
{
expected: true,
live: null,
mongo: { auctionLifecycleId: 'life-1', revision: 1 },
},
{
expected: true,
live: { auctionLifecycleId: 'life-1', revision: 1 },
mongo: { auctionLifecycleId: 'life-1', revision: 2 },
},
{
expected: true,
live: { auctionLifecycleId: 'old-life', revision: 2 },
mongo: { auctionLifecycleId: 'new-life', revision: 2 },
},
{
expected: true,
live: { auctionLifecycleId: 'redis-life', revision: 3 },
mongo: { auctionLifecycleId: 'mongo-life', revision: 2 },
},
])('decides rehydrate need: %#', ({ live, mongo, expected }) => {
expect(shouldHydrateRedisAuctionState({ live, mongo })).toBe(expected);
});
it('assembles public view and maps internal expiring phase to bidding', () => {
expect(
assembleAuctionViewFromRedisState({
auctionBidHistoryEntries: ['{"bidPointAmount":100}'],
currentServerTimestampMS: 1_000,
liveState: {
auctionLifecycleId: 'life-1',
currentBidRoundPlayerUserId: 'player-1',
phase: 'expiring',
revision: 3,
},
shouldForceAuctionStateResync: true,
structureState: {
auctionTeams: [],
},
}),
).toMatchObject({
auctionBidHistory: [{ bidPointAmount: 100 }],
auctionLifecycleId: 'life-1',
canPlaceBidInCurrentBidRound: false,
currentBidRoundPlayerUserId: 'player-1',
currentServerTimestampMS: 1000,
isAuctionStateTransitionInProgress: true,
phase: 'bidding',
revision: 3,
shouldForceAuctionStateResync: true,
});
});
it('builds HYDRATE invocation and keeps CAS conditions in Lua', () => {
const invocation = buildHydrateAuctionStateScriptInvocation(
buildAuctionRedisKeys('match-1'),
{
auctionHistorySequence: 4,
auctionLifecycleId: 'life-1',
liveStatePatch: {
'team:1:assignedAuctionTeamMemberCount': 1,
'team:1:remainingBidPointAmount': 1000,
},
maximumBidRoundDurationSeconds: 30,
matchId: 'match-1',
phase: 'bidding',
revision: 7,
structureStateJson: '{"auctionTeams":[]}',
},
);
expect(invocation.script).toBe(AUCTION_HYDRATE_STATE_SCRIPT);
expect(invocation.keys).toEqual([
'auction:match-1:liveAuctionState',
'auction:match-1:auctionStructureState',
'auction:bidRoundDeadlineQueue',
]);
expect(invocation.values).toEqual([
'match-1',
'life-1',
'7',
'bidding',
'4',
'30',
'{"auctionTeams":[]}',
'2',
'team:1:assignedAuctionTeamMemberCount',
'1',
'team:1:remainingBidPointAmount',
'1000',
]);
expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain("redis.call('TIME')");
expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain('INVALID_PATCH_ARITY');
expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain(
'mongoRevision > redisRevision',
);
expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain("redis.call('ZADD'");
});
});
@@ -0,0 +1,194 @@
import type { AuctionRedisKeys } from './auction-redis.keys';
import { defineAuctionRedisScript } from './auction-redis.scripts';
export interface AuctionRedisRevisionIdentity {
auctionLifecycleId?: string;
revision?: number;
}
export interface ShouldHydrateRedisAuctionStateParams {
live: AuctionRedisRevisionIdentity | null;
mongo: Required<AuctionRedisRevisionIdentity>;
}
export interface AssembleAuctionViewParams {
auctionBidHistoryEntries: string[];
currentServerTimestampMS: number;
liveState: Record<string, unknown> & {
auctionLifecycleId: string;
phase: string;
revision: number;
};
shouldForceAuctionStateResync?: boolean;
structureState: Record<string, unknown>;
}
export interface HydrateAuctionStateScriptInput {
auctionHistorySequence: number;
auctionLifecycleId: string;
liveStatePatch?: Record<string, string | number | boolean | null | undefined>;
maximumBidRoundDurationSeconds: number;
matchId: string;
phase: string;
revision: number;
structureStateJson: string;
}
export interface HydrateAuctionStateScriptInvocation {
keys: string[];
script: typeof AUCTION_HYDRATE_STATE_SCRIPT;
values: string[];
}
function stringifyRedisValue(value: string | number | boolean | null): string {
if (typeof value === 'boolean') return value ? '1' : '0';
if (value === null) return '';
return String(value);
}
function flattenLiveStatePatch(
liveStatePatch: HydrateAuctionStateScriptInput['liveStatePatch'],
): string[] {
return Object.entries(liveStatePatch ?? {})
.filter(([, value]) => value !== undefined)
.sort(([a], [b]) => a.localeCompare(b))
.flatMap(([key, value]) => [
key,
stringifyRedisValue(value as string | number | boolean | null),
]);
}
export function shouldHydrateRedisAuctionState(
params: ShouldHydrateRedisAuctionStateParams,
): boolean {
if (!params.live) return true;
if (params.mongo.auctionLifecycleId !== params.live.auctionLifecycleId)
return true;
const redisRevision = params.live.revision ?? -1;
const mongoRevision = params.mongo.revision;
return mongoRevision > redisRevision;
}
export function assembleAuctionViewFromRedisState(
params: AssembleAuctionViewParams,
): Record<string, unknown> {
const isExpiring = params.liveState.phase === 'expiring';
return {
...params.structureState,
...params.liveState,
auctionBidHistory: params.auctionBidHistoryEntries.map(parseJsonValue),
canPlaceBidInCurrentBidRound: !isExpiring,
currentServerTimestampMS: params.currentServerTimestampMS,
isAuctionStateTransitionInProgress: isExpiring,
phase: isExpiring ? 'bidding' : params.liveState.phase,
shouldForceAuctionStateResync:
params.shouldForceAuctionStateResync || undefined,
};
}
function parseJsonValue(json: string): unknown {
const value: unknown = JSON.parse(json);
return value;
}
export function buildHydrateAuctionStateScriptInvocation(
keys: AuctionRedisKeys,
input: HydrateAuctionStateScriptInput,
): HydrateAuctionStateScriptInvocation {
const liveStatePatchPairs = flattenLiveStatePatch(input.liveStatePatch);
return {
keys: [keys.liveStateKey, keys.structureStateKey, keys.deadlineQueueKey],
script: AUCTION_HYDRATE_STATE_SCRIPT,
values: [
input.matchId,
input.auctionLifecycleId,
String(input.revision),
input.phase,
String(input.auctionHistorySequence),
String(input.maximumBidRoundDurationSeconds),
input.structureStateJson,
String(liveStatePatchPairs.length / 2),
...liveStatePatchPairs,
],
};
}
export const AUCTION_HYDRATE_STATE_SCRIPT = defineAuctionRedisScript(
'auction.hydrateState',
`
local liveAuctionStateKey = KEYS[1]
local auctionStructureStateKey = KEYS[2]
local bidRoundDeadlineQueueKey = KEYS[3]
local matchId = ARGV[1]
local mongoAuctionLifecycleId = ARGV[2]
local mongoRevision = tonumber(ARGV[3])
local phase = ARGV[4]
local auctionHistorySequence = ARGV[5]
local maximumBidRoundDurationSeconds = tonumber(ARGV[6])
local structureStateJson = ARGV[7]
local liveStatePatchPairCount = tonumber(ARGV[8])
local redisTime = redis.call('TIME')
local currentRedisTimestampMS = (tonumber(redisTime[1]) * 1000) + math.floor(tonumber(redisTime[2]) / 1000)
local redisRevision = tonumber(redis.call('HGET', liveAuctionStateKey, 'revision') or '-1')
local redisAuctionLifecycleId = redis.call('HGET', liveAuctionStateKey, 'auctionLifecycleId')
if not liveStatePatchPairCount or #ARGV ~= 8 + (liveStatePatchPairCount * 2) then
return {'REJECTED', 'INVALID_PATCH_ARITY', tostring(currentRedisTimestampMS)}
end
-- A lifecycle replacement requires Mongo authority and an explicit cleanup
-- under the lifecycle lock. Revision numbers from different runs are unrelated.
if redisAuctionLifecycleId and redisAuctionLifecycleId ~= mongoAuctionLifecycleId then
return {'REJECTED', 'LIFECYCLE_CONFLICT', tostring(currentRedisTimestampMS)}
end
local shouldHydrate = false
if redisRevision < 0 then
shouldHydrate = true
elseif mongoRevision > redisRevision then
shouldHydrate = true
end
if not shouldHydrate then
return {'NOOP', tostring(redisRevision), tostring(currentRedisTimestampMS)}
end
local hydratedRevision = mongoRevision + 1
redis.call('SET', auctionStructureStateKey, structureStateJson)
local hsetArgs = {
liveAuctionStateKey,
'auctionLifecycleId',
mongoAuctionLifecycleId,
'revision',
tostring(hydratedRevision),
'phase',
phase,
'currentAuctionHistorySequence',
auctionHistorySequence,
'currentHighestBidPointAmount',
'0',
'currentHighestBidderTeamIndex',
'-1'
}
local patchIndex = 9
for i = 1, liveStatePatchPairCount do
table.insert(hsetArgs, ARGV[patchIndex])
table.insert(hsetArgs, ARGV[patchIndex + 1])
patchIndex = patchIndex + 2
end
redis.call('HSET', unpack(hsetArgs))
if phase == 'bidding' then
local currentBidRoundDeadlineTimestampMS = currentRedisTimestampMS + (maximumBidRoundDurationSeconds * 1000)
redis.call('HSET', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS', tostring(currentBidRoundDeadlineTimestampMS))
redis.call('ZADD', bidRoundDeadlineQueueKey, currentBidRoundDeadlineTimestampMS, matchId)
else
redis.call('ZREM', bidRoundDeadlineQueueKey, matchId)
redis.call('HDEL', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS')
end
return {'OK', tostring(hydratedRevision), tostring(currentRedisTimestampMS)}
`,
);
+1 -4
View File
@@ -1,8 +1,5 @@
import type { JWTHeaderParameters, JWTPayload } from 'jose';
import type {
IdentityDocument,
UserDocument,
} from '../global/database/schema';
import type { IdentityDocument, UserDocument } from '../global/database/schema';
import type { IdentityProviderName } from './jwt.service';
declare module 'express' {
+1 -4
View File
@@ -2,10 +2,7 @@ import { Injectable } from '@nestjs/common';
import type { Request } from 'express';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import {
IdentityDocument,
UserDocument,
} from '../global/database/schema';
import { IdentityDocument, UserDocument } from '../global/database/schema';
import { SecretService } from '../global/secret/secret.service';
import './auth-request';
+4 -4
View File
@@ -26,8 +26,7 @@ export class JwtAuthGuard implements CanActivate {
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
[context.getHandler(), context.getClass()],
);
const authz = request.headers?.authorization;
const authzHeader = Array.isArray(authz) ? authz[0] : authz;
const authzHeader = request.get('authorization');
if (!authzHeader) {
const fallback =
@@ -74,7 +73,7 @@ export class JwtAuthGuard implements CanActivate {
private pickIdPFromToken(token: string): IdentityProviderName {
try {
const { iss } = decodeJwt(token) as { iss?: string };
const { iss } = decodeJwt(token);
if (!iss) {
throw new Error('Token has no issuer (iss) claim');
}
@@ -84,7 +83,8 @@ export class JwtAuthGuard implements CanActivate {
}
throw new Error(`Unknown issuer: ${iss}`);
} catch (err) {
const message = err instanceof Error ? err.message : 'Unable to decode token';
const message =
err instanceof Error ? err.message : 'Unable to decode token';
throw new UnauthorizedException(message);
}
}
+32 -9
View File
@@ -35,11 +35,13 @@ export class JwtService {
throw new Error('Empty token');
}
if (identityProvider !== 'MICROSOFT_ENTRAID') {
throw new Error(`Identity provider not configured: ${identityProvider}`);
const provider =
identityProvider === 'MICROSOFT_ENTRAID'
? await this.getEntraConfig()
: undefined;
if (!provider) {
throw new Error('Identity provider not configured.');
}
const provider = await this.getEntraConfig();
const result = await jwtVerify(token, provider.jwks, {
issuer: provider.issuer,
audience: provider.audience,
@@ -48,14 +50,22 @@ export class JwtService {
});
const { payload, protectedHeader } = result;
if (!provider.allowedAlgs.includes(protectedHeader.alg as string)) {
if (!provider.allowedAlgs.includes(protectedHeader.alg)) {
throw new Error(`Unexpected alg: ${protectedHeader.alg}`);
}
if (payload.ver && payload.ver !== '2.0') {
throw new Error(`Unsupported Entra token version: ${payload.ver}`);
if (
payload.ver !== undefined &&
(typeof payload.ver !== 'string' || payload.ver !== '2.0')
) {
throw new Error(
`Unsupported Entra token version: ${formatClaimValue(payload.ver)}`,
);
}
if (payload.tid && payload.tid !== provider.tenantId) {
throw new Error(`Unexpected tenant: ${payload.tid}`);
if (
payload.tid !== undefined &&
(typeof payload.tid !== 'string' || payload.tid !== provider.tenantId)
) {
throw new Error(`Unexpected tenant: ${formatClaimValue(payload.tid)}`);
}
return result;
@@ -98,3 +108,16 @@ export class JwtService {
return this.entraConfig;
}
}
function formatClaimValue(value: unknown): string {
if (
typeof value === 'string' ||
typeof value === 'number' ||
typeof value === 'boolean' ||
typeof value === 'bigint'
) {
return String(value);
}
if (value === null) return 'null';
return JSON.stringify(value) ?? typeof value;
}
+2 -2
View File
@@ -7,7 +7,7 @@ import {
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import type { Request } from 'express';
import { CommunityRole, UserDocument } from '../global/database/schema';
import type { CommunityRole } from '../global/database/schema';
import { ROLES_KEY } from './roles.decorator';
import './auth-request';
@@ -23,7 +23,7 @@ export class RolesGuard implements CanActivate {
if (!requiredRoles || requiredRoles.length === 0) return true;
const req = context.switchToHttp().getRequest<Request>();
const user = req.user as UserDocument | undefined;
const user = req.user;
if (!user && req.identity) {
throw new ForbiddenException('No membership in this community.');
}
@@ -4,6 +4,7 @@ import { ConnectionService } from '../global/database/connection.service';
import { IdentityDocument, UserDocument } from '../global/database/schema';
import { UserResolverGuard } from './user-resolver.guard';
import './auth-request';
import type { Request } from 'express';
function createContext(request: Record<string, unknown>): ExecutionContext {
return {
@@ -24,7 +25,7 @@ describe('UserResolverGuard', () => {
const connectionService = {
getModel: jest.fn().mockResolvedValue({ findOne }),
} as unknown as ConnectionService;
const request = {
const request: Pick<Request, 'params' | 'identity' | 'user'> = {
params: { communityId: communityId.toString() },
identity: { _id: identityId } as IdentityDocument,
};
@@ -7,9 +7,10 @@ import {
import mongoose from 'mongoose';
@Injectable()
export class ParseObjectIdPipe
implements PipeTransform<string, mongoose.Types.ObjectId>
{
export class ParseObjectIdPipe implements PipeTransform<
string,
mongoose.Types.ObjectId
> {
public transform(
value: string,
metadata: ArgumentMetadata,
@@ -0,0 +1,198 @@
import { Logger } from '@nestjs/common';
import { CommunityStatsCacheService } from './community-stats-cache.service';
describe('Community stats cache invalidation retries', () => {
let service: CommunityStatsCacheService;
let invalidate: jest.SpyInstance<Promise<number>, [string, number?]>;
beforeEach(() => {
jest.useFakeTimers();
jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
service = new CommunityStatsCacheService({} as never);
invalidate = jest
.spyOn(service, 'invalidateCommunity')
.mockRejectedValue(new Error('Redis down'));
});
afterEach(() => {
service.onModuleDestroy();
jest.restoreAllMocks();
jest.useRealTimers();
});
it('returns true even when successful invalidation deletes no cache entries', async () => {
invalidate.mockResolvedValue(0);
expect(await service.invalidateCommunityWithRetry('community')).toBe(true);
expect(invalidate).toHaveBeenCalledWith('community', 1_000);
expect(jest.getTimerCount()).toBe(0);
});
it('returns false immediately, then retries at most three times with increasing delays', async () => {
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
expect(invalidate).toHaveBeenCalledTimes(1);
for (const [index, delay] of [1_000, 5_000, 30_000].entries()) {
await jest.advanceTimersByTimeAsync(delay - 1);
expect(invalidate).toHaveBeenCalledTimes(index + 1);
await jest.advanceTimersByTimeAsync(1);
expect(invalidate).toHaveBeenCalledTimes(index + 2);
}
expect(jest.getTimerCount()).toBe(0);
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(4);
expect(Logger.prototype.warn).toHaveBeenCalledWith(
expect.stringContaining('retries exhausted for community'),
);
});
it('does not reset the scheduled delay or remaining budget after another immediate failure', async () => {
await service.invalidateCommunityWithRetry('community');
await jest.advanceTimersByTimeAsync(1_000);
expect(invalidate).toHaveBeenCalledTimes(2);
await jest.advanceTimersByTimeAsync(2_000);
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
expect(jest.getTimerCount()).toBe(1);
await jest.advanceTimersByTimeAsync(2_999);
expect(invalidate).toHaveBeenCalledTimes(3);
await jest.advanceTimersByTimeAsync(1);
expect(invalidate).toHaveBeenCalledTimes(4);
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
await jest.advanceTimersByTimeAsync(30_000);
expect(invalidate).toHaveBeenCalledTimes(6);
expect(jest.getTimerCount()).toBe(0);
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(6);
});
it.each(['immediate', 'background'] as const)(
'cancels remaining retries after a successful %s attempt',
async (attempt) => {
await service.invalidateCommunityWithRetry('community');
invalidate.mockResolvedValue(0);
if (attempt === 'immediate') {
expect(await service.invalidateCommunityWithRetry('community')).toBe(
true,
);
} else {
await jest.advanceTimersByTimeAsync(1_000);
}
expect(jest.getTimerCount()).toBe(0);
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(2);
},
);
it('unrefs every retry timer so it does not keep the process alive', async () => {
const setTimeoutSpy = jest.spyOn(global, 'setTimeout');
await service.invalidateCommunityWithRetry('community');
for (const delay of [1_000, 5_000, 30_000]) {
const timer = setTimeoutSpy.mock.results.at(-1)!.value as NodeJS.Timeout;
expect(timer.hasRef()).toBe(false);
await jest.advanceTimersByTimeAsync(delay);
}
});
it('keeps different communities independent when one continues to fail', async () => {
await service.invalidateCommunityWithRetry('first');
await service.invalidateCommunityWithRetry('second');
invalidate.mockImplementation(async (id) => {
if (id === 'first') throw new Error('still unavailable');
return 1;
});
await jest.advanceTimersByTimeAsync(36_000);
expect(invalidate.mock.calls.filter(([id]) => id === 'first')).toHaveLength(
4,
);
expect(
invalidate.mock.calls.filter(([id]) => id === 'second'),
).toHaveLength(2);
expect(jest.getTimerCount()).toBe(0);
});
it('clears scheduled retries on shutdown', async () => {
await service.invalidateCommunityWithRetry('community');
service.onModuleDestroy();
expect(jest.getTimerCount()).toBe(0);
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(1);
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
expect(invalidate).toHaveBeenCalledTimes(1);
});
it.each(['shutdown', 'immediate success'] as const)(
'does not reschedule an in-flight retry after %s',
async (finish) => {
await service.invalidateCommunityWithRetry('community');
const pending = deferred();
invalidate.mockImplementationOnce(() => pending.promise);
await jest.advanceTimersByTimeAsync(1_000);
expect(invalidate).toHaveBeenCalledTimes(2);
if (finish === 'shutdown') {
service.onModuleDestroy();
} else {
invalidate.mockResolvedValueOnce(1);
expect(await service.invalidateCommunityWithRetry('community')).toBe(
true,
);
}
pending.reject(new Error('late failure'));
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(finish === 'shutdown' ? 2 : 3);
expect(jest.getTimerCount()).toBe(0);
},
);
it('does not cancel a newer failed request when an older immediate attempt succeeds late', async () => {
const pending = deferred();
invalidate.mockImplementationOnce(() => pending.promise);
const first = service.invalidateCommunityWithRetry('community');
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
pending.resolve(1);
expect(await first).toBe(true);
expect(jest.getTimerCount()).toBe(1);
invalidate.mockResolvedValue(1);
await jest.advanceTimersByTimeAsync(1_000);
expect(invalidate).toHaveBeenCalledTimes(3);
expect(jest.getTimerCount()).toBe(0);
});
it('preserves the retry budget when an immediate request fails during an in-flight retry', async () => {
await service.invalidateCommunityWithRetry('community');
const pending = deferred();
invalidate.mockImplementationOnce(() => pending.promise);
await jest.advanceTimersByTimeAsync(1_000);
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
await jest.advanceTimersByTimeAsync(5_000);
expect(invalidate).toHaveBeenCalledTimes(3);
pending.resolve(1);
await jest.advanceTimersByTimeAsync(5_000);
expect(invalidate).toHaveBeenCalledTimes(4);
await jest.advanceTimersByTimeAsync(30_000);
expect(invalidate).toHaveBeenCalledTimes(5);
expect(jest.getTimerCount()).toBe(0);
});
it('does not restart an exhausted budget when an older immediate request fails late', async () => {
await service.invalidateCommunityWithRetry('community');
await jest.advanceTimersByTimeAsync(6_000);
const pending = deferred();
invalidate.mockImplementationOnce(() => pending.promise);
const immediate = service.invalidateCommunityWithRetry('community');
await jest.advanceTimersByTimeAsync(30_000);
expect(invalidate).toHaveBeenCalledTimes(5);
pending.reject(new Error('late failure'));
expect(await immediate).toBe(false);
expect(jest.getTimerCount()).toBe(0);
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(5);
});
});
function deferred() {
let resolve!: (value: number) => void;
let reject!: (reason: Error) => void;
const promise = new Promise<number>((done, fail) => {
resolve = done;
reject = fail;
});
return { promise, resolve, reject };
}
@@ -1,57 +1,246 @@
import { Injectable, Logger } from '@nestjs/common';
import { GarnetService } from '../global/garnet/garnet.service';
import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
import { randomUUID } from 'crypto';
import { RedisService } from '../global/redis/redis.service';
const COMMUNITY_STATS_TTL_SECONDS = 5 * 60;
const COMMUNITY_STATS_DETAIL_TTL_SECONDS = 24 * 60 * 60;
const INVALIDATION_RETRY_DELAYS_MS = [1_000, 5_000, 30_000] as const;
interface InvalidationRetry {
attempts: number;
requestVersion: number;
timer?: NodeJS.Timeout;
}
const CACHE_SCOPES = [
'matches',
'leaderboard',
'teamInsights',
'matchDetail',
'userInternal',
] as const;
type CacheScope = (typeof CACHE_SCOPES)[number];
@Injectable()
export class CommunityStatsCacheService {
private readonly logger = new Logger(CommunityStatsCacheService.name);
function communityPrefix(communityId: string): string {
return `riot:communitystats:v2:{${communityId}}`;
}
constructor(private readonly garnetService: GarnetService) {}
export class CommunityStatsCacheKey {
public readonly generationKey: string;
public readonly hashKey: string;
public generation?: string;
public get<T>(key: string): Promise<T | null> {
return this.garnetService.getJson<T>(key);
constructor(
communityId: string,
scope: CacheScope,
public readonly field: string,
) {
const prefix = communityPrefix(communityId);
this.generationKey = `${prefix}:generation`;
this.hashKey = `${prefix}:${scope}`;
}
public set(
key: string,
public get identity(): string {
return JSON.stringify([this.hashKey, this.generation, this.field]);
}
}
const READ_CACHE_SCRIPT = `
local generation = redis.call('GET', KEYS[1])
if not generation then
generation = ARGV[1]
redis.call('SET', KEYS[1], generation)
end
return {generation, redis.call('HGET', KEYS[2], ARGV[2])}
`;
const WRITE_CACHE_SCRIPT = `
if redis.call('GET', KEYS[1]) ~= ARGV[1] then return 0 end
redis.call('HSETEX', KEYS[2], 'EX', ARGV[4], 'FIELDS', 1, ARGV[2], ARGV[3])
return 1
`;
const INVALIDATE_CACHE_SCRIPT = `
-- A fill started before invalidation cannot publish into the new generation.
redis.call('SET', KEYS[1], ARGV[1])
local deleted = 0
for i = 2, #KEYS do
deleted = deleted + redis.call('HLEN', KEYS[i])
redis.call('UNLINK', KEYS[i])
end
return deleted
`;
@Injectable()
export class CommunityStatsCacheService implements OnModuleDestroy {
private readonly logger = new Logger(CommunityStatsCacheService.name);
private readonly invalidationRetries = new Map<string, InvalidationRetry>();
private destroyed = false;
constructor(private readonly redisService: RedisService) {}
public onModuleDestroy(): void {
this.destroyed = true;
for (const pending of this.invalidationRetries.values()) {
if (pending.timer) clearTimeout(pending.timer);
}
this.invalidationRetries.clear();
}
// Only the immediate attempt determines whether the caller may cache its response.
public async invalidateCommunityWithRetry(
communityId: string,
): Promise<boolean> {
if (this.destroyed) return false;
const pending = this.invalidationRetries.get(communityId) ?? {
attempts: 0,
requestVersion: 0,
};
this.invalidationRetries.set(communityId, pending);
const version = ++pending.requestVersion;
const succeeded = await this.tryInvalidateCommunity(communityId);
if (succeeded && pending.requestVersion === version) {
this.clearInvalidationRetry(communityId, pending);
} else if (!succeeded) {
// An existing retry keeps its remaining budget, including while in flight.
this.scheduleInvalidationRetry(communityId, pending);
}
return succeeded;
}
private scheduleInvalidationRetry(
communityId: string,
pending: InvalidationRetry,
): void {
if (
this.destroyed ||
this.invalidationRetries.get(communityId) !== pending ||
pending.timer
)
return;
const delay = INVALIDATION_RETRY_DELAYS_MS[pending.attempts];
if (delay === undefined) {
this.clearInvalidationRetry(communityId, pending);
this.logger.warn(
`Stats cache invalidation retries exhausted for ${communityId}; detail recovery and cache expiry will refresh stale responses.`,
);
return;
}
pending.attempts += 1;
pending.timer = setTimeout(
() => void this.retryInvalidation(communityId, pending),
delay,
);
pending.timer.unref();
}
private async retryInvalidation(
communityId: string,
pending: InvalidationRetry,
): Promise<void> {
const version = pending.requestVersion;
const succeeded = await this.tryInvalidateCommunity(communityId);
if (this.invalidationRetries.get(communityId) !== pending) return;
pending.timer = undefined;
// An older completion must not cancel a newer request's retry.
if (succeeded && pending.requestVersion === version) {
this.clearInvalidationRetry(communityId, pending);
} else {
this.scheduleInvalidationRetry(communityId, pending);
}
}
private clearInvalidationRetry(
communityId: string,
pending: InvalidationRetry,
): void {
if (this.invalidationRetries.get(communityId) !== pending) return;
if (pending.timer) clearTimeout(pending.timer);
this.invalidationRetries.delete(communityId);
}
private async tryInvalidateCommunity(communityId: string): Promise<boolean> {
try {
await this.invalidateCommunity(communityId, 1_000);
return true;
} catch (error) {
this.logger.warn(
`Stats cache invalidation failed for ${communityId}: ${String(error)}`,
);
return false;
}
}
public async get<T>(key: CommunityStatsCacheKey): Promise<T | null> {
const reply = await this.redisService
.raw()
.sendCommand<
[string, string | null]
>(['EVAL', READ_CACHE_SCRIPT, '2', key.generationKey, key.hashKey, randomUUID(), key.field]);
key.generation = reply[0];
if (!reply[1]) return null;
try {
return JSON.parse(reply[1]) as T;
} catch {
this.logger.warn(
`Failed to parse community stats cache field in ${key.hashKey}.`,
);
return null;
}
}
public async set(
key: CommunityStatsCacheKey,
value: unknown,
ttlSeconds = COMMUNITY_STATS_TTL_SECONDS,
): Promise<void> {
return this.garnetService.setJson(key, value, ttlSeconds);
if (!key.generation)
throw new Error(
'Read the cache generation before starting a cache fill.',
);
if (!Number.isInteger(ttlSeconds) || ttlSeconds <= 0)
throw new Error('Cache TTL must be a positive integer.');
await this.redisService
.raw()
.sendCommand([
'EVAL',
WRITE_CACHE_SCRIPT,
'2',
key.generationKey,
key.hashKey,
key.generation,
key.field,
JSON.stringify(value),
String(ttlSeconds),
]);
}
public setDetail(key: string, value: unknown): Promise<void> {
public setDetail(key: CommunityStatsCacheKey, value: unknown): Promise<void> {
return this.set(key, value, COMMUNITY_STATS_DETAIL_TTL_SECONDS);
}
public async invalidateCommunity(communityId: string): Promise<number> {
const prefix = `riot:communitystats:`;
const match = `${prefix}*${communityId}*`;
const client = this.garnetService.raw();
let cursor = '0';
let deleted = 0;
do {
const reply = (await client.sendCommand([
'SCAN',
cursor,
'MATCH',
match,
'COUNT',
'100',
])) as [string, string[]];
cursor = reply[0];
const keys = reply[1] ?? [];
if (keys.length > 0) {
deleted += await client.del(keys);
}
} while (cursor !== '0');
public async invalidateCommunity(
communityId: string,
timeoutMs?: number,
): Promise<number> {
const prefix = communityPrefix(communityId);
const deleted = Number(
await this.redisService
.raw()
.sendCommand(
[
'EVAL',
INVALIDATE_CACHE_SCRIPT,
String(CACHE_SCOPES.length + 1),
`${prefix}:generation`,
...CACHE_SCOPES.map((scope) => `${prefix}:${scope}`),
randomUUID(),
],
timeoutMs === undefined ? undefined : { timeout: timeoutMs },
),
);
if (deleted > 0) {
this.logger.debug(
`Invalidated ${deleted} community stats cache keys for ${communityId}.`,
`Invalidated ${deleted} community stats cache entries for ${communityId}.`,
);
}
return deleted;
@@ -0,0 +1,321 @@
import mongoose from 'mongoose';
import { CommunityStatsService } from './community-stats.service';
import { CommunityStatsCacheKey } from './community-stats-cache.service';
import type { InternalMatchDetailResponse } from './community-stats.types';
describe('Community stats raw archive recovery', () => {
it.each([true, false])(
'recovers a cached missing game even if invalidation needs retry (%s)',
async (invalidationSucceeds) => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
let archived = false;
let enriched = false;
let generation = 'before';
let cached: InternalMatchDetailResponse | null = null;
const exists = jest.fn(() => query(archived ? { _id: 'archive' } : null));
const buildAndUpsert = jest.fn(async () => {
enriched = true;
});
const invalidateCommunity = jest.fn(async () => {
if (!invalidationSucceeds) return false;
cached = null;
generation = 'after';
return true;
});
const setDetail = jest.fn(
async (
key: CommunityStatsCacheKey,
value: InternalMatchDetailResponse,
) => {
expect(key.generation).toBe(generation);
cached = value;
},
);
const service = new CommunityStatsService(
{ getModel: async () => ({ exists }) } as never,
{
get: async (key: CommunityStatsCacheKey) => {
key.generation = generation;
return cached;
},
setDetail,
invalidateCommunityWithRetry: invalidateCommunity,
} as never,
{} as never,
{ buildAndUpsert } as never,
);
const internals = service as unknown as {
getDetailRevision: () => Promise<string>;
buildBaseDataset: () => Promise<unknown>;
matchDetailInFlight: Map<string, unknown>;
};
jest
.spyOn(internals, 'getDetailRevision')
.mockResolvedValue('same-revision');
jest
.spyOn(internals, 'buildBaseDataset')
.mockImplementation(async () => ({
matches: [{ matchId: matchId.toString() }],
detailsByMatchId: new Map([
[
matchId.toString(),
[
{
gameNumber: 1,
riotMatchId: 'KR_1',
rawAvailable: enriched,
timelineLoaded: enriched,
teams: [],
},
],
],
]),
competition: {
projection: {
games: [
{
id: 'official-game',
displayNumber: 1,
evidence: { type: 'riot', riotMatchId: 'KR_1' },
},
],
},
},
}));
const missing = await service.getMatchDetail({ communityId, matchId });
expect(missing.games[0].analysisAvailability).toBe('missing');
expect(await service.getMatchDetail({ communityId, matchId })).toBe(
missing,
);
expect(buildAndUpsert).not.toHaveBeenCalled();
archived = true;
const recovered = await service.getMatchDetail({ communityId, matchId });
expect(recovered.games[0]).toMatchObject({
gameId: 'official-game',
analysisAvailability: 'available',
riotMatchId: 'KR_1',
});
expect(buildAndUpsert).toHaveBeenCalledWith(matchId, {
includeTimeline: true,
});
expect(invalidateCommunity).toHaveBeenCalledWith(communityId.toString());
expect(internals.matchDetailInFlight.size).toBe(0);
expect(setDetail).toHaveBeenCalledTimes(invalidationSucceeds ? 2 : 1);
expect(await service.getMatchDetail({ communityId, matchId })).toEqual(
recovered,
);
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
},
);
it('rebuilds only affected missing fragments and invalidates every affected community after the writes', async () => {
const first = new mongoose.Types.ObjectId();
const second = new mongoose.Types.ObjectId();
const fragments = [
{
matchId: new mongoose.Types.ObjectId(),
communityId: first,
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: false }],
},
{
matchId: new mongoose.Types.ObjectId(),
communityId: first,
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: true }],
},
{
matchId: new mongoose.Types.ObjectId(),
communityId: second,
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: false }],
},
];
const order: string[] = [];
const buildAndUpsert = jest.fn(async () => {
order.push('build');
});
const invalidateCommunity = jest.fn(async () => {
order.push('invalidate');
return true;
});
const findByRiotMatchIds = jest.fn().mockResolvedValue(fragments);
const service = new CommunityStatsService(
{
getModel: async () => ({ find: () => query([{ matchId: 'KR_1' }]) }),
} as never,
{ invalidateCommunityWithRetry: invalidateCommunity } as never,
{
findByRiotMatchIds,
findByMatch: async () => ({
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: true }],
}),
} as never,
{ buildAndUpsert } as never,
);
await service.refreshForRiotMatches(['KR_1', 'KR_1', 'KR_ABSENT']);
expect(findByRiotMatchIds).toHaveBeenCalledWith(['KR_1']);
expect(buildAndUpsert.mock.calls).toEqual([
[fragments[0].matchId],
[fragments[2].matchId],
]);
expect(invalidateCommunity.mock.calls).toEqual([
[first.toString()],
[second.toString()],
]);
expect(order).toEqual(['build', 'build', 'invalidate', 'invalidate']);
});
it('does not invalidate already enriched games or builds that make no progress', async () => {
const game = { riotMatchId: 'KR_1', rawAvailable: false };
const fragment = {
matchId: new mongoose.Types.ObjectId(),
communityId: new mongoose.Types.ObjectId(),
gameDetails: [game],
};
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
const invalidateCommunity = jest.fn();
const service = new CommunityStatsService(
{
getModel: async () => ({ find: () => query([{ matchId: 'KR_1' }]) }),
} as never,
{ invalidateCommunityWithRetry: invalidateCommunity } as never,
{
findByRiotMatchIds: async () => [fragment],
findByMatch: async () => fragment,
} as never,
{ buildAndUpsert } as never,
);
await service.refreshForRiotMatches(['KR_1']);
game.rawAvailable = true;
await service.refreshForRiotMatches(['KR_1']);
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
expect(invalidateCommunity).not.toHaveBeenCalled();
});
it('does not rebuild when raw is still absent', async () => {
const findByRiotMatchIds = jest.fn();
const buildAndUpsert = jest.fn();
const service = new CommunityStatsService(
{ getModel: async () => ({ find: () => query([]) }) } as never,
{} as never,
{ findByRiotMatchIds } as never,
{ buildAndUpsert } as never,
);
await service.refreshForRiotMatches(['KR_1']);
expect(findByRiotMatchIds).not.toHaveBeenCalled();
expect(buildAndUpsert).not.toHaveBeenCalled();
});
it('invalidates successful communities once even when another game fails mid-batch', async () => {
const communities = Array.from(
{ length: 4 },
() => new mongoose.Types.ObjectId(),
);
const fragments = [0, 1, 0, 2, 3].map((community, index) => ({
matchId: new mongoose.Types.ObjectId(),
communityId: communities[community],
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: index === 4 }],
}));
const buildAndUpsert = jest.fn(async (matchId: mongoose.Types.ObjectId) => {
const fragment = fragments.find((item) => item.matchId === matchId)!;
if (fragment === fragments[1]) throw new Error('one build fails');
fragment.gameDetails[0].rawAvailable = true;
});
const invalidate = jest.fn().mockResolvedValue(true);
const service = new CommunityStatsService(
{
getModel: async () => ({ find: () => query([{ matchId: 'KR_1' }]) }),
} as never,
{ invalidateCommunityWithRetry: invalidate } as never,
{
findByRiotMatchIds: async () => fragments,
findByMatch: async (id: mongoose.Types.ObjectId) =>
fragments.find((item) => item.matchId === id),
} as never,
{ buildAndUpsert } as never,
);
await service.refreshForRiotMatches(['KR_1']);
expect(buildAndUpsert).toHaveBeenCalledTimes(4);
expect(invalidate.mock.calls).toEqual([
[communities[0].toString()],
[communities[2].toString()],
]);
});
it('backs off raw recovery that makes no progress and does not invalidate the community', async () => {
let now = 1000;
const clock = jest.spyOn(Date, 'now').mockImplementation(() => now);
try {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
let cached: InternalMatchDetailResponse | null = null;
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
const invalidate = jest.fn();
const service = new CommunityStatsService(
{
getModel: async () => ({ exists: () => query({ _id: 'archive' }) }),
} as never,
{
get: async () => cached,
setDetail: async (
_key: unknown,
value: InternalMatchDetailResponse,
) => {
cached = value;
},
invalidateCommunityWithRetry: invalidate,
} as never,
{} as never,
{ buildAndUpsert } as never,
);
const internals = service as unknown as {
getDetailRevision: () => Promise<string>;
buildBaseDataset: () => Promise<unknown>;
};
jest
.spyOn(internals, 'getDetailRevision')
.mockResolvedValue('same-revision');
jest.spyOn(internals, 'buildBaseDataset').mockResolvedValue({
matches: [{ matchId: matchId.toString() }],
detailsByMatchId: new Map([
[
matchId.toString(),
[
{
gameNumber: 1,
riotMatchId: 'KR_1',
rawAvailable: false,
timelineLoaded: false,
teams: [],
},
],
],
]),
});
await service.getMatchDetail({ communityId, matchId });
await service.getMatchDetail({ communityId, matchId });
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
now += 60_000;
await service.getMatchDetail({ communityId, matchId });
expect(buildAndUpsert).toHaveBeenCalledTimes(2);
expect(invalidate).not.toHaveBeenCalled();
} finally {
clock.mockRestore();
}
});
});
function query<T>(value: T) {
return {
select() {
return this;
},
lean() {
return this;
},
exec: async () => value,
};
}
@@ -1,4 +1,10 @@
import { Controller, Get, Param, Query } from '@nestjs/common';
import {
BadRequestException,
Controller,
Get,
Param,
Query,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
@@ -9,6 +15,15 @@ import type { CommunityStatsFilters } from './community-stats.types';
export class CommunityStatsController {
constructor(private readonly communityStatsService: CommunityStatsService) {}
@Get('internal-stats/seasons')
@AllowPublicAccess()
public getSeasons(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
) {
return this.communityStatsService.getSeasons(communityId);
}
@Get('internal-stats/matches')
@AllowPublicAccess()
public getMatches(
@@ -20,10 +35,44 @@ export class CommunityStatsController {
@Query('championId') championId?: string,
@Query('cursor') cursor?: string,
@Query('limit') limit?: string,
@Query('q') query?: string,
@Query('format') format?: string,
@Query('playerId') playerId?: string,
@Query('cursorMatchId') cursorMatchId?: string,
) {
if (format !== undefined && format !== 'pair' && format !== 'tournament') {
throw new BadRequestException('Invalid format.');
}
if (playerId !== undefined && !mongoose.isObjectIdOrHexString(playerId)) {
throw new BadRequestException('Invalid playerId.');
}
if (
cursorMatchId !== undefined &&
(!mongoose.isObjectIdOrHexString(cursorMatchId) ||
this.toNumber(cursor) === undefined)
) {
throw new BadRequestException('Invalid cursor.');
}
if (
cursor !== undefined &&
Number.isNaN(new Date(this.toNumber(cursor) ?? NaN).getTime())
) {
throw new BadRequestException('Invalid cursor.');
}
return this.communityStatsService.getMatches({
communityId,
filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }),
filters: this.toFilters({
seasonId,
from,
to,
championId,
cursor,
limit,
query,
format,
playerId,
cursorMatchId,
}),
});
}
@@ -36,10 +85,12 @@ export class CommunityStatsController {
@Query('from') from?: string,
@Query('to') to?: string,
@Query('championId') championId?: string,
@Query('q') query?: string,
@Query('lane') lane?: string,
) {
return this.communityStatsService.getLeaderboard({
communityId,
filters: this.toFilters({ seasonId, from, to, championId }),
filters: this.toFilters({ seasonId, from, to, championId, query, lane }),
});
}
@@ -81,11 +132,24 @@ export class CommunityStatsController {
@Query('championId') championId?: string,
@Query('cursor') cursor?: string,
@Query('limit') limit?: string,
@Query('lane') lane?: string,
@Query('includePositionCounts') includePositionCounts?: string,
) {
return this.communityStatsService.getUserInternalHistory({
communityId,
userId,
filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }),
filters: {
...this.toFilters({
seasonId,
from,
to,
championId,
cursor,
limit,
lane,
}),
includePositionCounts: includePositionCounts === 'true',
},
});
}
@@ -96,7 +160,24 @@ export class CommunityStatsController {
championId?: string;
cursor?: string;
limit?: string;
query?: string;
format?: CommunityStatsFilters['format'];
playerId?: string;
cursorMatchId?: string;
lane?: string;
}): CommunityStatsFilters {
if (
params.lane !== undefined &&
!['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'].includes(params.lane)
) {
throw new BadRequestException('Invalid lane.');
}
if (
params.query !== undefined &&
(typeof params.query !== 'string' || params.query.length > 100)
) {
throw new BadRequestException('Invalid search query.');
}
return {
seasonId: params.seasonId,
from: params.from,
@@ -104,6 +185,11 @@ export class CommunityStatsController {
championId: this.toNumber(params.championId),
cursor: this.toNumber(params.cursor),
limit: this.toNumber(params.limit),
query: params.query?.trim(),
format: params.format,
playerId: params.playerId,
cursorMatchId: params.cursorMatchId,
lane: params.lane as CommunityStatsFilters['lane'],
};
}
@@ -1,4 +1,5 @@
import { Module } from '@nestjs/common';
import { forwardRef, Module } from '@nestjs/common';
import { RiotModule } from '../riot/riot.module';
import { CommunityStatsCacheService } from './community-stats-cache.service';
import { CommunityStatsController } from './community-stats.controller';
import { CommunityStatsService } from './community-stats.service';
@@ -7,6 +8,7 @@ import { MatchStatsRepository } from './match-stats.repository';
import { MatchStatsService } from './match-stats.service';
@Module({
imports: [forwardRef(() => RiotModule)],
controllers: [CommunityStatsController],
providers: [
CommunityStatsService,
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,18 +1,45 @@
import type { RiotLane, TeamSide } from '../global/database/schema';
import type { RecentMatchView, HistorySeasonDto } from '../match-history/match-history.types';
import type {
GameAnalysisAvailability,
GameId,
GameSlotId,
InternalMatchCompetition,
InternalMatchResultPresentation,
SeriesId,
SeriesProjection,
} from '@lolympus/contracts';
import type {
MatchStatsParticipantCheckpoints,
MatchStatsItemBuildEvent,
MatchStatsRunePerks,
MatchStatsSkillBuildEvent,
MatchStatsTimelineEvent,
RiotLane,
TeamSide,
} from '../global/database/schema';
import type {
RecentMatchView,
HistorySeasonDto,
} from '../match-history/match-history.types';
export interface CommunityStatsFilters {
includePositionCounts?: boolean;
seasonId?: string;
from?: string;
to?: string;
championId?: number;
cursor?: number;
limit?: number;
query?: string;
format?: 'pair' | 'tournament';
playerId?: string;
cursorMatchId?: string;
lane?: RiotLane;
}
export interface InternalMatchListResponse {
matches: InternalMatchCardView[];
nextCursor: number | null;
nextCursorMatchId?: string;
season: HistorySeasonDto;
}
@@ -23,6 +50,9 @@ export interface InternalMatchCardView {
status: 'finished' | 'in-progress';
gameCount: number;
winnerTeamIndex?: number;
resultPresentation?: InternalMatchResultPresentation;
/** Official series only. Historical opponent pairs are not inferred rounds. */
series?: SeriesProjection[];
seriesResults: Array<{
teamAIndex: number;
teamBIndex: number;
@@ -32,6 +62,9 @@ export interface InternalMatchCardView {
}>;
games: Array<{
gameNumber: number;
seriesId?: string;
ordinal?: number;
analysisAvailability?: GameAnalysisAvailability | 'pending';
riotMatchId: string | null;
blueTeamIndex: number;
redTeamIndex: number;
@@ -41,6 +74,7 @@ export interface InternalMatchCardView {
}>;
teams: Array<{
teamIndex: number;
teamId?: string;
name: string;
members: Array<{
userId: string;
@@ -52,12 +86,15 @@ export interface InternalMatchCardView {
export interface LeaderboardResponse {
rows: LeaderboardRow[];
lane?: RiotLane;
season: HistorySeasonDto;
matchedUserIds?: string[];
}
export interface LeaderboardRow {
userId: string;
summonerName: string;
tagLine?: string;
profileIconId: number;
games: number;
wins: number;
@@ -72,7 +109,9 @@ export interface LeaderboardRow {
avgCsPerMin: number;
avgDamageShare: number;
avgVisionScore: number;
byLane: Partial<Record<RiotLane, { games: number; wins: number; kda: number }>>;
byLane: Partial<
Record<RiotLane, { games: number; wins: number; kda: number }>
>;
topChampions: Array<{ championId: number; games: number; winRate: number }>;
}
@@ -82,16 +121,25 @@ export interface LeaderHighlight {
summonerName: string;
championId?: number;
matchId?: string;
internalMatchId?: string;
gameNumber?: number;
isSingleGame: boolean;
}
export interface TeamInsightsResponse {
season: HistorySeasonDto;
totals: {
matches: number;
games: number;
analyzedGames: number;
players: number;
};
sideWinRate: {
blue: number;
red: number;
bluePicks: number;
redPicks: number;
confirmed: { sampleSize: number; blue: number; red: number };
};
topKda: LeaderHighlight | null;
mostKills: LeaderHighlight | null;
@@ -103,23 +151,57 @@ export interface TeamInsightsResponse {
export interface InternalMatchDetailResponse {
match: InternalMatchCardView;
competition?: InternalMatchCompetition;
games: Array<{
gameNumber: number;
gameId?: GameId;
analysisAvailability?: GameAnalysisAvailability;
gameSlotId?: GameSlotId;
seriesId?: SeriesId;
ordinal?: number;
riotMatchId: string;
gameCreation: number;
gameDuration: number;
gameVersion?: string;
timeline: Array<{
timestamp: number;
blue: { gold: number; xp: number };
red: { gold: number; xp: number };
goldDiff: number;
xpDiff: number;
}>;
objectiveEvents: Array<{
timestamp: number;
side: TeamSide;
type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub';
monsterSubType?: string;
}>;
timelineEvents: MatchStatsTimelineEvent[];
teams: Array<{
teamIndex: number;
side: TeamSide;
win: boolean;
objectives: { baron: number; dragon: number; tower: number };
objectives: {
tower: number;
dragon: number;
inhibitor: number;
baron: number;
riftHerald: number;
voidGrub: number;
elderDragon: number;
};
bans: Array<{ championId: number; pickTurn: number }>;
participants: Array<{
participantId?: number;
checkpoints?: MatchStatsParticipantCheckpoints;
userId: string | null;
summonerName: string;
tagLine: string;
teamIndex: number;
side: TeamSide;
teamPosition: string;
championId: number;
championLevel: number;
kills: number;
deaths: number;
assists: number;
@@ -128,13 +210,21 @@ export interface InternalMatchDetailResponse {
gold: number;
gpm: number;
damageDealtToChampions: number;
damageTaken: number;
damageShare: number;
killParticipation: number;
visionScore: number;
wardsPlaced: number;
wardsKilled: number;
controlWardsBought: number;
firstBloodKill: boolean;
firstBloodAssist: boolean;
items: number[];
trinket: number;
summonerSpells: [number, number];
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
perks: MatchStatsRunePerks;
itemBuild: MatchStatsItemBuildEvent[];
skillBuild: MatchStatsSkillBuildEvent[];
win: boolean;
}>;
}>;
@@ -142,7 +232,9 @@ export interface InternalMatchDetailResponse {
}
export interface UserInternalHistoryResponse {
positionCounts?: Record<string, number>;
season: HistorySeasonDto;
playerStats?: LeaderboardRow | null;
championStats: LeaderboardChampionStats;
summary: {
windowSize: number;
@@ -0,0 +1,378 @@
import { BadRequestException } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import request from 'supertest';
import type { Server } from 'node:http';
import mongoose from 'mongoose';
import { CommunityStatsService } from './community-stats.service';
import { CommunityStatsController } from './community-stats.controller';
import { ConnectionService } from '../global/database/connection.service';
import { CommunityStatsCacheService } from './community-stats-cache.service';
import { MatchStatsRepository } from './match-stats.repository';
import { MatchStatsService } from './match-stats.service';
import {
MATCH_STATS_BUILDER_VERSION,
type InternalRecord,
} from './match-stats.types';
import { presentStatsCard, statsDate } from './internal-stats-presentation';
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
const start = Date.parse('2026-06-18T12:00:00Z');
function record(
gameNumber: number,
values: Partial<InternalRecord> = {},
): InternalRecord {
return {
matchId: matchId.toString(),
title: '여름 내전',
scheduledAt: new Date(start),
gameNumber,
riotMatchId: `KR_${gameNumber}`,
gameCreation: start + gameNumber * 1800000,
gameDuration: 1800,
userId: userId.toString(),
summonerName: '선수',
tagLine: 'KR1',
profileIconId: 1,
teamIndex: 1,
side: 'blue',
championId: 1,
teamPosition: 'TOP',
kills: 8,
deaths: 2,
assists: 4,
win: true,
cs: 240,
csPerMin: 8,
gold: 12000,
gpm: 400,
killParticipation: 60,
damageShare: 30,
visionScore: 12,
damageDealtToChampions: 18000,
...values,
} as InternalRecord;
}
function fixture() {
const records = [
record(1),
record(2, {
teamPosition: 'JUNGLE',
championId: 2,
kills: 2,
deaths: 4,
assists: 6,
win: false,
csPerMin: 4,
gpm: 300,
killParticipation: 40,
}),
record(3, { kills: 99 }),
record(3, { userId: new mongoose.Types.ObjectId().toString() }),
];
const fragment = {
matchId,
builderVersion: MATCH_STATS_BUILDER_VERSION,
records,
gameDetails: [1, 2, 3].map((gameNumber) => ({
gameNumber,
gameCreation: start + gameNumber * 1800000,
winnerSide: gameNumber === 2 ? 'red' : 'blue',
rawAvailable: gameNumber !== 3,
})),
};
const cache = new Map<string, unknown>();
const repository = {
findSeasonStats: jest.fn().mockResolvedValue([fragment]),
findUserRecordFragments: jest.fn().mockResolvedValue([fragment]),
findDetailsByMatches: jest.fn().mockResolvedValue([]),
};
const service = new CommunityStatsService(
{
getModel: async () => ({
findById: () => ({
exec: async () => ({
seasons: [
{
id: 'june',
label: '6월',
startedAt: new Date('2026-06-01T00:00:00+09:00'),
endedAt: new Date('2026-06-30T23:59:59.999+09:00'),
},
],
}),
}),
}),
} as unknown as ConnectionService,
{
get: async (key: unknown) => cache.get(JSON.stringify(key)),
set: async (key: unknown, value: unknown) => {
cache.set(JSON.stringify(key), value);
},
} as unknown as CommunityStatsCacheService,
repository as unknown as MatchStatsRepository,
{} as MatchStatsService,
);
jest
.spyOn(
service as unknown as { repairCommunityFragments: () => Promise<number> },
'repairCommunityFragments',
)
.mockResolvedValue(0);
return { service, repository };
}
describe('internal stats API contract', () => {
it('serves the scoped player and leaderboard contracts through the HTTP routes', async () => {
const { service } = fixture();
const module = await Test.createTestingModule({
controllers: [CommunityStatsController],
providers: [{ provide: CommunityStatsService, useValue: service }],
}).compile();
const app = module.createNestApplication();
await app.init();
const server: Server = app.getHttpServer();
try {
const base = `/communities/${communityId.toString()}`;
const leaderboard = await request(server)
.get(`${base}/internal-stats/leaderboard?seasonId=all&lane=TOP`)
.expect(200);
expect(leaderboard.body).toMatchObject({
lane: 'TOP',
rows: [{ games: 1, kda: 6 }],
});
const player = await request(server)
.get(
`${base}/users/${userId.toString()}/internal-history?seasonId=all&lane=JUNGLE`,
)
.expect(200);
expect(player.body).toMatchObject({
playerStats: { games: 1, kda: 2 },
matches: [{ gameNumber: 2 }],
});
await request(server)
.get(`${base}/internal-stats/leaderboard?lane=invalid`)
.expect(400);
await request(server)
.get(`${base}/internal-stats/leaderboard?from=2026-02-30`)
.expect(400);
await request(server)
.get('/communities/invalid/internal-stats/leaderboard')
.expect(400);
} finally {
await app.close();
}
});
it('searches escaped text across title, team and player without losing date or cursor constraints', async () => {
const chain = {
select: jest.fn().mockReturnThis(),
sort: jest.fn().mockReturnThis(),
limit: jest.fn().mockReturnThis(),
lean: jest.fn().mockReturnThis(),
exec: jest.fn().mockResolvedValue([]),
};
const find = jest.fn().mockReturnValue(chain);
const repository = new MatchStatsRepository({
getModel: async () => ({ find }),
} as unknown as ConnectionService);
await repository.findMatchPage({
communityId,
query: '팀.*',
from: start,
cursor: start + 1000,
cursorMatchId: matchId.toString(),
limit: 4,
});
expect(find).toHaveBeenCalledWith(
expect.objectContaining({
communityId,
$and: expect.arrayContaining([
{
$or: [
'matchCard.title',
'matchCard.teams.name',
'matchCard.teams.members.summonerName',
].map((field) => ({
[field]: { $regex: '팀\\.\\*', $options: 'i' },
})),
},
]),
}),
);
expect(chain.limit).toHaveBeenCalledWith(4);
expect(chain.select).toHaveBeenCalledWith(
expect.objectContaining({ 'gameDetails.rawAvailable': 1 }),
);
});
it('recalculates every metric per lane, isolates cached scopes and excludes missing raw data', async () => {
const { service } = fixture();
const all = await service.getLeaderboard({
communityId,
filters: { seasonId: 'all' },
});
const top = await service.getLeaderboard({
communityId,
filters: { seasonId: 'all', lane: 'TOP' },
});
const jungle = await service.getLeaderboard({
communityId,
filters: { seasonId: 'all', lane: 'JUNGLE' },
});
expect(all.rows).toHaveLength(1);
expect(all.rows[0]).toMatchObject({
games: 2,
totalKills: 10,
winRate: 50,
avgGoldPerMin: 350,
avgCsPerMin: 6,
avgKillParticipation: 50,
});
expect(top).toMatchObject({
lane: 'TOP',
rows: [
{
games: 1,
kda: 6,
winRate: 100,
avgGoldPerMin: 400,
avgCsPerMin: 8,
avgKillParticipation: 60,
},
],
});
expect(jungle).toMatchObject({
lane: 'JUNGLE',
rows: [{ games: 1, kda: 2, winRate: 0, avgGoldPerMin: 300 }],
});
expect(
await service.getLeaderboard({
communityId,
filters: { seasonId: 'all' },
}),
).toEqual(all);
const insight = await service.getTeamInsights({
communityId,
filters: { seasonId: 'all' },
});
expect(insight.totals).toEqual({
matches: 1,
games: 3,
analyzedGames: 2,
players: 2,
});
expect(insight.topTeamGpm).toMatchObject({
internalMatchId: matchId.toString(),
gameNumber: 1,
metric: 400,
});
});
it('keeps player summary and matches in the same scope while retaining champion choices', async () => {
const { service } = fixture();
const history = await service.getUserInternalHistory({
communityId,
userId,
filters: { seasonId: 'all', championId: 1 },
});
expect(history.playerStats).toMatchObject({ games: 1, kda: 6 });
expect(history.matches).toHaveLength(1);
expect(history.matches[0]).toMatchObject({
internalMatchId: matchId.toString(),
internalMatchTitle: '여름 내전',
gameNumber: 1,
});
expect(history.championStats.champions).toHaveLength(2);
});
it('intersects custom dates with the season and accepts inclusive KST calendar dates', async () => {
const { service, repository } = fixture();
await service.getLeaderboard({
communityId,
filters: { seasonId: 'june', from: '2026-05-01', to: '2026-07-31' },
});
expect(repository.findSeasonStats).toHaveBeenCalledWith({
communityId,
from: Date.parse('2026-05-31T15:00:00Z'),
to: Date.parse('2026-06-30T14:59:59.999Z'),
});
expect(statsDate('2026-06-18', false)?.toISOString()).toBe(
'2026-06-17T15:00:00.000Z',
);
expect(statsDate('2026-06-18', true)?.toISOString()).toBe(
'2026-06-18T14:59:59.999Z',
);
await expect(
service.getLeaderboard({ communityId, filters: { from: '2026-02-30' } }),
).rejects.toBeInstanceOf(BadRequestException);
await expect(
service.getLeaderboard({
communityId,
filters: { from: '2026-06-20', to: '2026-06-19' },
}),
).rejects.toBeInstanceOf(BadRequestException);
});
it('rejects unsupported lanes at the HTTP controller boundary', () => {
const controller = new CommunityStatsController(
{} as CommunityStatsService,
);
expect(() =>
(
controller as unknown as {
toFilters: (params: { lane: string }) => unknown;
}
).toFilters({ lane: 'SUPPORT' }),
).toThrow(BadRequestException);
});
it('uses official evidence to distinguish rematches and does not invent round identities', () => {
type Card = Parameters<typeof presentStatsCard>[0];
type Competition = NonNullable<Parameters<typeof presentStatsCard>[1]>;
const card = {
games: [
{ gameNumber: 1, riotMatchId: 'KR_1' },
{ gameNumber: 2, riotMatchId: 'KR_2' },
{ gameNumber: 3, riotMatchId: 'old' },
],
teams: [{ teamIndex: 1 }],
} as Card;
const competition = {
teams: [{ displayOrder: 1, teamId: 'a' }],
projection: {
games: [
{
displayNumber: 1,
ordinal: 1,
seriesId: 'upper',
evidence: { type: 'riot', riotMatchId: 'KR_1' },
},
{
displayNumber: 2,
ordinal: 1,
seriesId: 'final',
evidence: { type: 'riot', riotMatchId: 'KR_2' },
},
{
displayNumber: 3,
ordinal: 2,
seriesId: 'final',
evidence: { type: 'riot', riotMatchId: 'replacement' },
},
],
series: [
{ seriesId: 'upper' },
{ seriesId: 'final' },
{ seriesId: 'other', status: 'scheduled' },
],
},
} as unknown as Competition;
const result = presentStatsCard(card, competition);
expect(result.games.map((game) => game.seriesId)).toEqual([
'upper',
'final',
undefined,
]);
expect(result.series?.map((series) => series.seriesId)).toEqual([
'upper',
'final',
]);
expect(result.teams[0].teamId).toBe('a');
});
});
@@ -0,0 +1,59 @@
import type { InternalMatchCompetition } from '@lolympus/contracts';
import type { InternalMatchCardView } from './community-stats.types';
/** Attach official identities without merging rematches between the same teams. */
export function presentStatsCard(
card: InternalMatchCardView,
competition?: Pick<InternalMatchCompetition, 'teams' | 'projection'>,
): InternalMatchCardView {
if (!competition) return card;
const officialGames = competition.projection.games ?? [];
const games = card.games.map((game) => {
const official = officialGames.find(
(candidate) =>
candidate.displayNumber === game.gameNumber &&
(candidate.evidence.type === 'riot'
? candidate.evidence.riotMatchId
: candidate.evidence.legacyReference) === game.riotMatchId,
);
return official
? { ...game, seriesId: official.seriesId, ordinal: official.ordinal }
: game;
});
const visible = new Set(games.map((game) => game.seriesId));
return {
...card,
games,
teams: card.teams?.map((team) => ({
...team,
teamId: competition.teams.find((t) => t.displayOrder === team.teamIndex)
?.teamId,
})),
series: (competition.projection.series ?? []).filter(
(series) =>
visible.has(series.seriesId) ||
(series.status === 'completed' && series.outcome.type !== 'played'),
),
};
}
/** Date-only inputs are inclusive Korean calendar days; ISO timestamps remain supported. */
export function statsDate(
value: string | undefined,
end: boolean,
): Date | null {
if (!value) return null;
if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
const date = new Date(
`${value}T${end ? '23:59:59.999' : '00:00:00.000'}+09:00`,
);
const midnight = new Date(`${value}T00:00:00.000Z`);
if (
!Number.isFinite(midnight.getTime()) ||
midnight.toISOString().slice(0, 10) !== value
)
return new Date(NaN);
return date;
}
return new Date(value);
}
@@ -1,5 +1,6 @@
import mongoose from 'mongoose';
import type { MatchDocument } from '../global/database/schema';
import type { RiotMatchDto, RiotMatchTimelineDto } from '../riot/riot.types';
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
function makeMatch(): MatchDocument {
@@ -95,4 +96,726 @@ describe('MatchStatsFragmentBuilder', () => {
});
expect(fragment.gameDetails[0].teams[0].participants).toHaveLength(1);
});
it('builds rich set detail from raw Riot match data', () => {
const builder = new MatchStatsFragmentBuilder();
const match = makeMatch();
const redUserId = new mongoose.Types.ObjectId();
match.participants.push({
userId: redUserId,
puuid: 'puuid-2',
gameName: 'Opponent',
profileIconId: 8,
preferredPositions: [],
joinedAt: new Date('2026-05-03T00:00:00.000Z'),
});
match.teams[1].members.push({ userId: redUserId, assignedPosition: 'TOP' });
match.result?.games[0].participants.push({
userId: redUserId,
teamIndex: 2,
side: 'red',
championId: 24,
kills: 1,
deaths: 3,
assists: 0,
win: false,
});
const raw = {
metadata: {
dataVersion: '2',
matchId: 'KR_1',
participants: ['puuid-1'],
},
info: {
gameCreation: 1_000,
gameDuration: 1_800,
gameId: 1,
gameMode: 'CLASSIC',
gameName: 'teambuilder-match-1',
gameStartTimestamp: 1_000,
gameType: 'CUSTOM_GAME',
gameVersion: '16.11.1.1234',
mapId: 11,
participants: [
{
assists: 7,
champExperience: 15_000,
champLevel: 15,
championId: 266,
championName: 'Aatrox',
deaths: 1,
firstBloodAssist: false,
firstBloodKill: true,
goldEarned: 12_345,
goldSpent: 11_000,
individualPosition: 'TOP',
item0: 1054,
item1: 3071,
item2: 0,
item3: 0,
item4: 0,
item5: 0,
item6: 3340,
kills: 5,
neutralMinionsKilled: 8,
participantId: 1,
perks: {
statPerks: { defense: 5001, flex: 5008, offense: 5005 },
styles: [
{
description: 'primaryStyle',
style: 8000,
selections: [
{ perk: 8010, var1: 0, var2: 0, var3: 0 },
{ perk: 9111, var1: 0, var2: 0, var3: 0 },
{ perk: 9105, var1: 0, var2: 0, var3: 0 },
{ perk: 8299, var1: 0, var2: 0, var3: 0 },
],
},
{
description: 'subStyle',
style: 8400,
selections: [
{ perk: 8444, var1: 0, var2: 0, var3: 0 },
{ perk: 8451, var1: 0, var2: 0, var3: 0 },
],
},
],
},
puuid: 'puuid-1',
riotIdGameName: 'Player',
riotIdTagLine: 'KR1',
summoner1Id: 4,
summoner2Id: 12,
summonerId: 'summoner-1',
summonerLevel: 100,
summonerName: 'Player',
teamId: 100,
teamPosition: 'TOP',
timePlayed: 1_800,
totalDamageDealtToChampions: 18_765,
totalDamageTaken: 24_321,
totalMinionsKilled: 220,
visionScore: 18,
visionWardsBoughtInGame: 2,
wardsKilled: 3,
wardsPlaced: 11,
win: true,
},
],
platformId: 'KR',
queueId: 0,
teams: [
{
bans: [
{ championId: 14, pickTurn: 1 },
{ championId: 43, pickTurn: 2 },
],
objectives: {
baron: { first: true, kills: 1 },
champion: { first: true, kills: 5 },
dragon: { first: true, kills: 2 },
horde: { first: false, kills: 3 },
inhibitor: { first: false, kills: 0 },
riftHerald: { first: false, kills: 0 },
tower: { first: true, kills: 7 },
},
teamId: 100,
win: true,
},
],
},
};
raw.info.participants.push(
{
...raw.info.participants[0],
assists: 0,
championId: 24,
championName: 'Jax',
deaths: 3,
kills: 1,
participantId: 2,
puuid: 'puuid-2',
riotIdGameName: 'Opponent',
summonerId: 'summoner-2',
summonerName: 'Opponent',
teamId: 200,
win: false,
},
{
...raw.info.participants[0],
assists: 2,
championId: 64,
championName: 'LeeSin',
deaths: 0,
kills: 1,
participantId: 3,
puuid: 'puuid-3',
riotIdGameName: 'Jungler',
summonerId: 'summoner-3',
summonerName: 'Jungler',
teamId: 100,
},
);
raw.info.teams.push({
bans: [],
objectives: {
baron: { first: false, kills: 0 },
champion: { first: false, kills: 3 },
dragon: { first: false, kills: 0 },
horde: { first: false, kills: 0 },
inhibitor: { first: false, kills: 0 },
riftHerald: { first: false, kills: 0 },
tower: { first: false, kills: 0 },
},
teamId: 200,
win: false,
});
const timeline: RiotMatchTimelineDto = {
metadata: {
dataVersion: '2',
matchId: 'KR_1',
participants: ['puuid-1'],
},
info: {
frameInterval: 60_000,
frames: [
{
timestamp: 0,
events: [],
participantFrames: {
'1': {
participantId: 1,
totalGold: 500,
xp: 0,
minionsKilled: 0,
jungleMinionsKilled: 0,
},
'2': {
participantId: 2,
totalGold: 500,
xp: 0,
minionsKilled: 0,
jungleMinionsKilled: 0,
},
},
},
{
timestamp: 60_000,
events: [
{
type: 'ITEM_PURCHASED',
timestamp: 10_000,
participantId: 1,
itemId: 1054,
},
{
type: 'SKILL_LEVEL_UP',
timestamp: 11_000,
participantId: 1,
skillSlot: 1,
levelUpType: 'NORMAL',
},
{
type: 'ITEM_DESTROYED',
timestamp: 12_000,
participantId: 1,
itemId: 2003,
},
{
type: 'ITEM_UNDO',
timestamp: 13_000,
participantId: 1,
beforeId: 1054,
afterId: 3071,
},
{
type: 'ELITE_MONSTER_KILL',
timestamp: 20_000,
killerTeamId: 100,
monsterType: 'DRAGON',
monsterSubType: 'FIRE_DRAGON',
},
{
type: 'ELITE_MONSTER_KILL',
timestamp: 30_000,
killerTeamId: 100,
monsterType: 'DRAGON',
monsterSubType: 'ELDER_DRAGON',
},
{
type: 'ELITE_MONSTER_KILL',
timestamp: 40_000,
killerId: 1,
monsterType: 'HORDE',
},
{
type: 'SKILL_LEVEL_UP',
timestamp: 45_000,
participantId: 1,
skillSlot: 3,
levelUpType: 'NORMAL',
},
{
type: 'ELITE_MONSTER_KILL',
timestamp: 50_000,
killerTeamId: 100,
monsterType: 'BARON_NASHOR',
},
{
type: 'ELITE_MONSTER_KILL',
timestamp: 55_000,
killerTeamId: 100,
monsterType: 'RIFTHERALD',
},
],
participantFrames: {
'1': {
participantId: 1,
totalGold: 1_150,
xp: 550,
minionsKilled: 5,
jungleMinionsKilled: 1,
},
'2': {
participantId: 2,
totalGold: 1_050,
xp: 500,
minionsKilled: 4,
jungleMinionsKilled: 0,
},
},
},
{
timestamp: 540_000,
events: [
{
type: 'CHAMPION_KILL',
timestamp: 300_000,
killerId: 1,
victimId: 2,
assistingParticipantIds: [3],
},
{
type: 'CHAMPION_KILL',
timestamp: 400_000,
killerId: 0,
victimId: 1,
},
{
type: 'BUILDING_KILL',
timestamp: 450_000,
killerId: 0,
teamId: 200,
buildingType: 'TOWER_BUILDING',
towerType: 'OUTER_TURRET',
},
{
type: 'BUILDING_KILL',
timestamp: 450_000,
killerId: 1,
teamId: 200,
buildingType: 'INHIBITOR_BUILDING',
},
{
type: 'CHAMPION_KILL',
timestamp: 500_000,
killerId: 3,
victimId: 2,
assistingParticipantIds: [1],
},
],
participantFrames: {
'1': {
participantId: 1,
totalGold: 4_900,
xp: 3_900,
minionsKilled: 72,
jungleMinionsKilled: 8,
},
'2': {
participantId: 2,
totalGold: 4_300,
xp: 3_500,
minionsKilled: 68,
jungleMinionsKilled: 2,
},
},
},
{
timestamp: 590_000,
events: [],
participantFrames: {
'1': {
participantId: 1,
totalGold: 5_200,
xp: 4_200,
minionsKilled: 80,
jungleMinionsKilled: 10,
},
},
},
{
timestamp: 900_000,
events: [
{
type: 'CHAMPION_KILL',
timestamp: 900_000,
killerId: 1,
victimId: 2,
assistingParticipantIds: [3],
},
],
participantFrames: {
'1': {
participantId: 1,
totalGold: 8_100,
xp: 7_300,
minionsKilled: 130,
jungleMinionsKilled: 15,
},
'2': {
participantId: 2,
totalGold: 6_700,
xp: 6_100,
minionsKilled: 115,
jungleMinionsKilled: 5,
},
},
},
{
timestamp: 1_800_000,
events: [],
participantFrames: {
'1': {
participantId: 1,
totalGold: 12_500,
xp: 14_000,
minionsKilled: 205,
jungleMinionsKilled: 23,
},
'2': {
participantId: 2,
totalGold: 10_200,
xp: 12_700,
minionsKilled: 190,
jungleMinionsKilled: 10,
},
},
},
],
},
};
const fragment = builder.buildFragment({
match,
rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]),
timelineByRiotMatchId: new Map([['KR_1', timeline]]),
});
expect(fragment.gameDetails[0]).toMatchObject({
gameVersion: '16.11.1.1234',
objectiveEvents: [
{
timestamp: 20,
side: 'blue',
type: 'dragon',
monsterSubType: 'FIRE_DRAGON',
},
{
timestamp: 30,
side: 'blue',
type: 'elderDragon',
monsterSubType: 'ELDER_DRAGON',
},
{ timestamp: 40, side: 'blue', type: 'voidGrub' },
{ timestamp: 50, side: 'blue', type: 'baron' },
{ timestamp: 55, side: 'blue', type: 'riftHerald' },
],
timeline: [
{
timestamp: 0,
blue: { gold: 500, xp: 0 },
red: { gold: 500, xp: 0 },
goldDiff: 0,
xpDiff: 0,
},
{
timestamp: 60,
blue: { gold: 1_150, xp: 550 },
red: { gold: 1_050, xp: 500 },
goldDiff: 100,
xpDiff: 50,
},
{
timestamp: 540,
blue: { gold: 4_900, xp: 3_900 },
red: { gold: 4_300, xp: 3_500 },
goldDiff: 600,
xpDiff: 400,
},
{
timestamp: 590,
blue: { gold: 5_200, xp: 4_200 },
red: { gold: 0, xp: 0 },
goldDiff: 5_200,
xpDiff: 4_200,
},
{
timestamp: 900,
blue: { gold: 8_100, xp: 7_300 },
red: { gold: 6_700, xp: 6_100 },
goldDiff: 1_400,
xpDiff: 1_200,
},
{
timestamp: 1_800,
blue: { gold: 12_500, xp: 14_000 },
red: { gold: 10_200, xp: 12_700 },
goldDiff: 2_300,
xpDiff: 1_300,
},
],
});
expect(fragment.gameDetails[0].timelineEvents).toEqual([
{
timestamp: 20,
side: 'blue',
type: 'dragon',
monsterSubType: 'FIRE_DRAGON',
},
{
timestamp: 30,
side: 'blue',
type: 'elderDragon',
monsterSubType: 'ELDER_DRAGON',
},
{ timestamp: 40, side: 'blue', type: 'voidGrub' },
{ timestamp: 50, side: 'blue', type: 'baron' },
{ timestamp: 55, side: 'blue', type: 'riftHerald' },
{
timestamp: 300,
side: 'blue',
type: 'championKill',
killerParticipantId: 1,
victimParticipantId: 2,
assistingParticipantIds: [3],
},
{
timestamp: 400,
type: 'championKill',
victimParticipantId: 1,
},
{
timestamp: 450,
side: 'blue',
type: 'tower',
towerType: 'OUTER_TURRET',
},
{
timestamp: 450,
side: 'blue',
type: 'inhibitor',
killerParticipantId: 1,
},
{
timestamp: 500,
side: 'blue',
type: 'championKill',
killerParticipantId: 3,
victimParticipantId: 2,
assistingParticipantIds: [1],
},
{
timestamp: 900,
side: 'blue',
type: 'championKill',
killerParticipantId: 1,
victimParticipantId: 2,
assistingParticipantIds: [3],
},
]);
expect(fragment.gameDetails[0].teams[0].bans).toEqual([
{ championId: 14, pickTurn: 1 },
{ championId: 43, pickTurn: 2 },
]);
expect(fragment.gameDetails[0].teams[0].objectives).toMatchObject({
baron: 1,
dragon: 1,
elderDragon: 1,
inhibitor: 0,
riftHerald: 1,
tower: 7,
voidGrub: 1,
});
expect(fragment.records[0]).toMatchObject({
participantId: 1,
checkpoints: {
at10: {
timestamp: 590,
gold: 5_200,
cs: 90,
xp: 4_200,
kills: 1,
deaths: 1,
assists: 1,
},
at15: {
timestamp: 900,
gold: 8_100,
cs: 145,
xp: 7_300,
kills: 2,
deaths: 1,
assists: 1,
},
},
championLevel: 15,
cs: 228,
damageDealtToChampions: 18_765,
damageTaken: 24_321,
firstBloodKill: true,
firstBloodAssist: false,
controlWardsBought: 2,
wardsKilled: 3,
wardsPlaced: 11,
perks: {
primaryStyle: 8000,
subStyle: 8400,
keystone: 8010,
selectedPerkIds: [8010, 9111, 9105, 8299, 8444, 8451],
styles: [
{ styleId: 8000, perkIds: [8010, 9111, 9105, 8299] },
{ styleId: 8400, perkIds: [8444, 8451] },
],
statPerks: { defense: 5001, flex: 5008, offense: 5005 },
},
itemBuild: [
{ timestamp: 10, itemId: 1054, type: 'purchased' },
{ timestamp: 12, itemId: 2003, type: 'destroyed' },
{
timestamp: 13,
itemId: 3071,
type: 'undo',
beforeId: 1054,
afterId: 3071,
},
],
skillBuild: [
{ timestamp: 11, skillSlot: 1, level: 1, levelUpType: 'NORMAL' },
{ timestamp: 45, skillSlot: 3, level: 2, levelUpType: 'NORMAL' },
],
});
expect(fragment.records[1]).toMatchObject({
participantId: 2,
checkpoints: {
at15: {
timestamp: 900,
gold: 6_700,
cs: 120,
xp: 6_100,
kills: 0,
deaths: 3,
assists: 0,
},
},
});
expect(fragment.records[1].checkpoints).not.toHaveProperty('at10');
const timelineWithoutEvents = {
...timeline,
info: {
...timeline.info,
frames: timeline.info.frames.map((frame) => ({
...frame,
events: [],
})),
},
} as RiotMatchTimelineDto;
const objectiveFallback = builder.buildFragment({
match,
rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]),
timelineByRiotMatchId: new Map([['KR_1', timelineWithoutEvents]]),
});
expect(objectiveFallback.gameDetails[0].teams[0].objectives).toMatchObject({
baron: 1,
dragon: 2,
elderDragon: 0,
riftHerald: 0,
voidGrub: 3,
});
const dragonOnlyTimeline = {
...timeline,
info: {
...timeline.info,
frames: timeline.info.frames.map((frame) => ({
...frame,
events: (frame.events ?? []).filter(
(event) =>
event.type !== 'ELITE_MONSTER_KILL' ||
event.monsterType === 'DRAGON',
),
})),
},
} as RiotMatchTimelineDto;
const partialObjectiveFallback = builder.buildFragment({
match,
rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]),
timelineByRiotMatchId: new Map([['KR_1', dragonOnlyTimeline]]),
});
expect(
partialObjectiveFallback.gameDetails[0].teams[0].objectives,
).toMatchObject({
baron: 1,
dragon: 1,
elderDragon: 1,
riftHerald: 0,
voidGrub: 3,
});
const shortMatch = {
...match,
result: {
...match.result!,
games: match.result!.games.map((game) => ({
...game,
gameDuration: 599,
})),
},
} as MatchDocument;
const shortFragment = builder.buildFragment({
match: shortMatch,
rawByRiotMatchId: new Map([
[
'KR_1',
{
...raw,
info: { ...raw.info, gameDuration: 599 },
} as RiotMatchDto,
],
]),
timelineByRiotMatchId: new Map([['KR_1', timeline]]),
});
expect(
shortFragment.records.every((record) => record.checkpoints === undefined),
).toBe(true);
const invalidIntervalTimeline = {
...timeline,
info: { ...timeline.info, frameInterval: Number.NaN },
} as RiotMatchTimelineDto;
const invalidIntervalFragment = builder.buildFragment({
match,
rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]),
timelineByRiotMatchId: new Map([['KR_1', invalidIntervalTimeline]]),
});
expect(invalidIntervalFragment.gameDetails[0].timelineLoaded).toBe(false);
expect(invalidIntervalFragment.gameDetails[0].timeline).toEqual([]);
expect(
invalidIntervalFragment.records.every(
(record) => record.checkpoints === undefined,
),
).toBe(true);
});
});
@@ -1,11 +1,24 @@
import { Injectable } from '@nestjs/common';
import { readMultiKills } from '../riot/riot-multi-kill';
import mongoose from 'mongoose';
import type {
MatchDocument,
MatchGameResultParticipant,
MatchStatsCheckpoint,
MatchStatsItemBuildEvent,
MatchStatsObjectiveEvent,
MatchStatsObjectiveSummary,
MatchStatsParticipantCheckpoints,
MatchStatsSkillBuildEvent,
MatchStatsTimelineEvent,
MatchStatsTimelinePoint,
TeamSide,
} from '../global/database/schema';
import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types';
import type {
RiotMatchDto,
RiotMatchParticipantDto,
RiotMatchTimelineDto,
} from '../riot/riot.types';
import type { InternalMatchCardView } from './community-stats.types';
import type {
InternalGameDetail,
@@ -13,11 +26,22 @@ import type {
MatchStatsFragment,
} from './match-stats.types';
interface ParticipantBuildEvents {
items: MatchStatsItemBuildEvent[];
skills: MatchStatsSkillBuildEvent[];
}
interface TimelineProjection {
objectiveEvents: MatchStatsObjectiveEvent[];
timelineEvents: MatchStatsTimelineEvent[];
}
@Injectable()
export class MatchStatsFragmentBuilder {
public buildFragment(params: {
match: MatchDocument;
rawByRiotMatchId: Map<string, RiotMatchDto>;
timelineByRiotMatchId?: Map<string, RiotMatchTimelineDto>;
}): MatchStatsFragment {
const games = [...(params.match.result?.games ?? [])].sort(
(left, right) => left.gameNumber - right.gameNumber,
@@ -25,8 +49,9 @@ export class MatchStatsFragmentBuilder {
const matchCard = this.toMatchCard(params.match, games);
const gameDetails = games.map((game) => {
const raw = params.rawByRiotMatchId.get(game.riotMatchId);
const timeline = params.timelineByRiotMatchId?.get(game.riotMatchId);
return raw
? this.toGameDetail(params.match, game, raw)
? this.toGameDetail(params.match, game, raw, timeline)
: this.toFallbackGameDetail(params.match, game);
});
const records = gameDetails.flatMap((detail) =>
@@ -106,7 +131,11 @@ export class MatchStatsFragmentBuilder {
match: MatchDocument,
game: NonNullable<MatchDocument['result']>['games'][number],
raw: RiotMatchDto,
timeline?: RiotMatchTimelineDto,
): InternalGameDetail {
const usableTimeline = isUsableTimeline(timeline, raw.info.gameDuration)
? timeline
: undefined;
const puuidByUserId = new Map(
match.participants
.filter((participant) => participant.puuid)
@@ -129,13 +158,35 @@ export class MatchStatsFragmentBuilder {
rawTeamIdBySide.set(participant.side, rawParticipant.teamId);
}
}
const sideByParticipantId = this.toSideByParticipantId(
raw,
rawTeamIdBySide,
);
const { objectiveEvents, timelineEvents } = this.toTimelineEvents(
usableTimeline,
rawTeamIdBySide,
sideByParticipantId,
);
const timelineObjectives = this.toTimelineObjectives(objectiveEvents);
const buildEventsByParticipantId =
this.toBuildEventsByParticipantId(usableTimeline);
const checkpointsByParticipantId = this.toCheckpointsByParticipantId(
usableTimeline,
raw.info.gameDuration,
);
return {
gameNumber: game.gameNumber,
riotMatchId: game.riotMatchId,
gameCreation: game.gameCreation,
gameDuration: game.gameDuration,
gameVersion: raw.info.gameVersion,
winnerSide: game.winnerSide,
timeline: this.toTimeline(raw, rawTeamIdBySide, usableTimeline),
timelineLoaded: Boolean(usableTimeline),
rawAvailable: true,
objectiveEvents,
timelineEvents,
teams: (['blue', 'red'] as TeamSide[]).map((side) => {
const teamIndex =
side === 'blue' ? game.blueTeamIndex : game.redTeamIndex;
@@ -158,25 +209,35 @@ export class MatchStatsFragmentBuilder {
teamIndex,
side,
win: game.winnerSide === side,
objectives: {
baron: rawTeam?.objectives?.baron?.kills ?? 0,
dragon: rawTeam?.objectives?.dragon?.kills ?? 0,
tower: rawTeam?.objectives?.tower?.kills ?? 0,
},
objectives: this.toObjectiveSummary(
rawTeam,
timelineObjectives.get(side),
),
bans: (rawTeam?.bans ?? []).map((ban) => ({
championId: ban.championId,
pickTurn: ban.pickTurn,
})),
participants: game.participants
.filter((participant) => participant.side === side)
.map((participant) =>
this.toRecord({
.map((participant) => {
const rawParticipant = rawByPuuid.get(
puuidByUserId.get(participant.userId.toString()) ?? '',
);
return this.toRecord({
match,
game,
participant,
rawParticipant: rawByPuuid.get(
puuidByUserId.get(participant.userId.toString()) ?? '',
),
rawParticipant,
buildEvents: rawParticipant
? buildEventsByParticipantId.get(rawParticipant.participantId)
: undefined,
checkpoints: rawParticipant
? checkpointsByParticipantId.get(rawParticipant.participantId)
: undefined,
teamKills,
teamDamage,
}),
),
});
}),
};
}),
};
@@ -192,11 +253,17 @@ export class MatchStatsFragmentBuilder {
gameCreation: game.gameCreation,
gameDuration: game.gameDuration,
winnerSide: game.winnerSide,
timeline: [],
timelineLoaded: false,
rawAvailable: false,
objectiveEvents: [],
timelineEvents: [],
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex,
side,
win: game.winnerSide === side,
objectives: { baron: 0, dragon: 0, tower: 0 },
objectives: emptyObjectives(),
bans: [],
participants: game.participants
.filter((participant) => participant.side === side)
.map((participant) =>
@@ -217,11 +284,21 @@ export class MatchStatsFragmentBuilder {
game: NonNullable<MatchDocument['result']>['games'][number];
participant: MatchGameResultParticipant;
rawParticipant?: RiotMatchParticipantDto;
buildEvents?: ParticipantBuildEvents;
checkpoints?: MatchStatsParticipantCheckpoints;
teamKills: number;
teamDamage: number;
}): InternalRecord {
const { match, game, participant, rawParticipant, teamKills, teamDamage } =
params;
const {
match,
game,
participant,
rawParticipant,
buildEvents,
checkpoints,
teamKills,
teamDamage,
} = params;
const snapshot = match.participants.find((item) =>
item.userId.equals(participant.userId),
);
@@ -256,12 +333,15 @@ export class MatchStatsFragmentBuilder {
riotMatchId: game.riotMatchId,
gameCreation: game.gameCreation,
gameDuration: game.gameDuration,
participantId: rawParticipant?.participantId,
checkpoints,
userId: participant.userId.toString(),
summonerName:
snapshot?.gameName ??
rawParticipant?.riotIdGameName ??
rawParticipant?.summonerName ??
'Unknown',
tagLine: snapshot?.tagLine ?? rawParticipant?.riotIdTagLine ?? '',
profileIconId: snapshot?.profileIconId ?? 0,
teamIndex: participant.teamIndex,
side: participant.side,
@@ -272,6 +352,8 @@ export class MatchStatsFragmentBuilder {
rawParticipant?.individualPosition ||
'',
kills: participant.kills,
multiKills: readMultiKills(rawParticipant),
tier: snapshot?.tier,
deaths: participant.deaths,
assists: participant.assists,
win: participant.win,
@@ -290,6 +372,8 @@ export class MatchStatsFragmentBuilder {
),
wardsPlaced: rawParticipant?.wardsPlaced ?? 0,
wardsKilled: rawParticipant?.wardsKilled ?? 0,
firstBloodKill: booleanField(rawParticipant, 'firstBloodKill'),
firstBloodAssist: booleanField(rawParticipant, 'firstBloodAssist'),
items: [
rawParticipant?.item0 ?? 0,
rawParticipant?.item1 ?? 0,
@@ -304,6 +388,8 @@ export class MatchStatsFragmentBuilder {
rawParticipant?.summoner2Id ?? 0,
],
perks: rawParticipant ? this.resolvePerks(rawParticipant) : {},
itemBuild: buildEvents?.items ?? [],
skillBuild: buildEvents?.skills ?? [],
rating,
};
}
@@ -319,6 +405,416 @@ export class MatchStatsFragmentBuilder {
primaryStyle: primary?.style,
subStyle: sub?.style,
keystone: primary?.selections[0]?.perk,
selectedPerkIds: participant.perks.styles.flatMap((style) =>
style.selections.map((selection) => selection.perk),
),
styles: participant.perks.styles.map((style) => ({
styleId: style.style,
perkIds: style.selections.map((selection) => selection.perk),
})),
statPerks: {
offense: participant.perks.statPerks.offense,
flex: participant.perks.statPerks.flex,
defense: participant.perks.statPerks.defense,
},
};
}
private toBuildEventsByParticipantId(
timeline?: RiotMatchTimelineDto,
): Map<number, ParticipantBuildEvents> {
const buildEventsByParticipantId = new Map<
number,
ParticipantBuildEvents
>();
if (!timeline?.info.frames.length) return buildEventsByParticipantId;
const getEvents = (participantId: number): ParticipantBuildEvents => {
const current = buildEventsByParticipantId.get(participantId);
if (current) return current;
const created: ParticipantBuildEvents = { items: [], skills: [] };
buildEventsByParticipantId.set(participantId, created);
return created;
};
for (const frame of timeline.info.frames) {
for (const event of frame.events ?? []) {
const participantId = event.participantId;
if (!participantId) continue;
const timestamp = Math.max(0, Math.round(event.timestamp / 1000));
if (event.type === 'SKILL_LEVEL_UP' && isSkillSlot(event.skillSlot)) {
const skills = getEvents(participantId).skills;
skills.push({
timestamp,
skillSlot: event.skillSlot,
level: skills.length + 1,
levelUpType: event.levelUpType,
});
continue;
}
const itemType = toItemBuildType(event.type);
if (!itemType) continue;
const itemId = event.itemId ?? event.afterId ?? event.beforeId ?? 0;
if (itemId <= 0) continue;
getEvents(participantId).items.push({
timestamp,
itemId,
type: itemType,
beforeId: event.beforeId,
afterId: event.afterId,
});
}
}
for (const events of buildEventsByParticipantId.values()) {
events.items.sort((left, right) => left.timestamp - right.timestamp);
events.skills.sort((left, right) => left.timestamp - right.timestamp);
}
return buildEventsByParticipantId;
}
private toCheckpointsByParticipantId(
timeline: RiotMatchTimelineDto | undefined,
gameDurationSeconds: number,
): Map<number, MatchStatsParticipantCheckpoints> {
const checkpointsByParticipantId = new Map<
number,
MatchStatsParticipantCheckpoints
>();
if (
!timeline?.info.frames.length ||
!Number.isFinite(timeline.info.frameInterval) ||
timeline.info.frameInterval <= 0
) {
return checkpointsByParticipantId;
}
const participantIds = new Set<number>();
const championKillEvents = timeline.info.frames.flatMap((frame) =>
(frame.events ?? []).filter((event) => event.type === 'CHAMPION_KILL'),
);
for (const frame of timeline.info.frames) {
for (const participantFrame of Object.values(frame.participantFrames)) {
participantIds.add(participantFrame.participantId);
}
}
const targets = [
['at10', 600_000],
['at15', 900_000],
] as const;
for (const participantId of participantIds) {
const checkpoints: MatchStatsParticipantCheckpoints = {};
for (const [key, targetTimestamp] of targets) {
if (gameDurationSeconds * 1_000 < targetTimestamp) continue;
const selectedFrame = timeline.info.frames.reduce<
RiotMatchTimelineDto['info']['frames'][number] | undefined
>((latest, frame) => {
if (
frame.timestamp > targetTimestamp ||
!Object.values(frame.participantFrames).some(
(participantFrame) =>
participantFrame.participantId === participantId,
)
) {
return latest;
}
return !latest || frame.timestamp > latest.timestamp ? frame : latest;
}, undefined);
if (
!selectedFrame ||
targetTimestamp - selectedFrame.timestamp >=
timeline.info.frameInterval
) {
continue;
}
const participantFrame = Object.values(
selectedFrame.participantFrames,
).find((frame) => frame.participantId === participantId);
if (
!participantFrame ||
typeof participantFrame.minionsKilled !== 'number' ||
!Number.isFinite(participantFrame.minionsKilled) ||
typeof participantFrame.jungleMinionsKilled !== 'number' ||
!Number.isFinite(participantFrame.jungleMinionsKilled)
) {
continue;
}
const checkpoint: MatchStatsCheckpoint = {
timestamp: Math.max(0, Math.round(selectedFrame.timestamp / 1_000)),
gold: participantFrame.totalGold,
cs:
participantFrame.minionsKilled +
participantFrame.jungleMinionsKilled,
xp: participantFrame.xp,
kills: 0,
deaths: 0,
assists: 0,
};
for (const event of championKillEvents) {
if (event.timestamp > selectedFrame.timestamp) continue;
if (event.killerId === participantId && event.killerId > 0) {
checkpoint.kills += 1;
}
if (event.victimId === participantId) checkpoint.deaths += 1;
if (event.assistingParticipantIds?.includes(participantId)) {
checkpoint.assists += 1;
}
}
checkpoints[key] = checkpoint;
}
if (checkpoints.at10 || checkpoints.at15) {
checkpointsByParticipantId.set(participantId, checkpoints);
}
}
return checkpointsByParticipantId;
}
private toTimeline(
raw: RiotMatchDto,
rawTeamIdBySide: Map<TeamSide, number>,
timeline?: RiotMatchTimelineDto,
): MatchStatsTimelinePoint[] {
if (!timeline?.info.frames.length) return [];
const sideByParticipantId = this.toSideByParticipantId(
raw,
rawTeamIdBySide,
);
const points = timeline.info.frames.map((frame) => {
const point: MatchStatsTimelinePoint = {
timestamp: Math.max(0, Math.round(frame.timestamp / 1000)),
blue: { gold: 0, xp: 0 },
red: { gold: 0, xp: 0 },
goldDiff: 0,
xpDiff: 0,
};
for (const participantFrame of Object.values(frame.participantFrames)) {
const side = sideByParticipantId.get(participantFrame.participantId);
if (!side) continue;
point[side].gold += participantFrame.totalGold;
point[side].xp += participantFrame.xp;
}
point.goldDiff = point.blue.gold - point.red.gold;
point.xpDiff = point.blue.xp - point.red.xp;
return point;
});
return points.filter(
(point, index) =>
index === 0 || point.timestamp !== points[index - 1].timestamp,
);
}
private toSideByParticipantId(
raw: RiotMatchDto,
rawTeamIdBySide: Map<TeamSide, number>,
): Map<number, TeamSide> {
const blueTeamId = rawTeamIdBySide.get('blue') ?? 100;
const redTeamId = rawTeamIdBySide.get('red') ?? 200;
const sideByParticipantId = new Map<number, TeamSide>();
for (const participant of raw.info.participants) {
if (participant.teamId === blueTeamId) {
sideByParticipantId.set(participant.participantId, 'blue');
}
if (participant.teamId === redTeamId) {
sideByParticipantId.set(participant.participantId, 'red');
}
}
return sideByParticipantId;
}
private toTimelineEvents(
timeline: RiotMatchTimelineDto | undefined,
rawTeamIdBySide: Map<TeamSide, number>,
sideByParticipantId: Map<number, TeamSide>,
): TimelineProjection {
if (!timeline?.info.frames.length) {
return { objectiveEvents: [], timelineEvents: [] };
}
const sideByTeamId = new Map<number, TeamSide>();
for (const [side, teamId] of rawTeamIdBySide.entries()) {
sideByTeamId.set(teamId, side);
}
const projected: Array<{
sourceSequence: number;
event: MatchStatsTimelineEvent;
}> = [];
let sourceSequence = 0;
for (const frame of timeline.info.frames) {
for (const event of frame.events ?? []) {
const currentSequence = sourceSequence;
sourceSequence += 1;
const timestamp = Math.max(0, Math.round(event.timestamp / 1000));
if (event.type === 'ELITE_MONSTER_KILL') {
const side =
(typeof event.killerTeamId === 'number'
? sideByTeamId.get(event.killerTeamId)
: undefined) ??
(typeof event.killerId === 'number'
? sideByParticipantId.get(event.killerId)
: undefined);
if (!side) continue;
const objectiveEvent = toObjectiveTimelineEvent({
timestamp,
side,
monsterType: event.monsterType,
monsterSubType: event.monsterSubType,
});
if (objectiveEvent) {
projected.push({
sourceSequence: currentSequence,
event: objectiveEvent,
});
}
continue;
}
if (event.type === 'CHAMPION_KILL') {
const side =
typeof event.killerId === 'number' && event.killerId > 0
? sideByParticipantId.get(event.killerId)
: undefined;
projected.push({
sourceSequence: currentSequence,
event: {
timestamp,
type: 'championKill',
...(side ? { side } : {}),
...(typeof event.killerId === 'number' && event.killerId > 0
? { killerParticipantId: event.killerId }
: {}),
...(typeof event.victimId === 'number' && event.victimId > 0
? { victimParticipantId: event.victimId }
: {}),
...(event.assistingParticipantIds
? { assistingParticipantIds: event.assistingParticipantIds }
: {}),
},
});
continue;
}
if (event.type !== 'BUILDING_KILL') continue;
const destroyedSide =
typeof event.teamId === 'number'
? sideByTeamId.get(event.teamId)
: undefined;
const side =
(typeof event.killerId === 'number' && event.killerId > 0
? sideByParticipantId.get(event.killerId)
: undefined) ??
(destroyedSide ? oppositeSide(destroyedSide) : undefined);
const type =
event.buildingType === 'TOWER_BUILDING'
? 'tower'
: event.buildingType === 'INHIBITOR_BUILDING'
? 'inhibitor'
: undefined;
if (!side || !type) continue;
projected.push({
sourceSequence: currentSequence,
event: {
timestamp,
side,
type,
...(typeof event.killerId === 'number' && event.killerId > 0
? { killerParticipantId: event.killerId }
: {}),
...(type === 'tower' && event.towerType
? { towerType: event.towerType }
: {}),
},
});
}
}
const timelineEvents = projected
.sort(
(left, right) =>
left.event.timestamp - right.event.timestamp ||
left.sourceSequence - right.sourceSequence,
)
.map(({ event }) => event);
return {
timelineEvents,
objectiveEvents: timelineEvents.filter(isObjectiveTimelineEvent),
};
}
private toTimelineObjectives(
objectiveEvents: MatchStatsObjectiveEvent[],
): Map<TeamSide, MatchStatsObjectiveSummary> {
const objectives = new Map<TeamSide, MatchStatsObjectiveSummary>([
['blue', emptyObjectives()],
['red', emptyObjectives()],
]);
for (const event of objectiveEvents) {
const current = objectives.get(event.side) ?? emptyObjectives();
switch (event.type) {
case 'baron':
current.baron += 1;
break;
case 'riftHerald':
current.riftHerald += 1;
break;
case 'voidGrub':
current.voidGrub += 1;
break;
case 'dragon':
current.dragon += 1;
break;
case 'elderDragon':
current.elderDragon += 1;
break;
default:
break;
}
objectives.set(event.side, current);
}
return objectives;
}
private toObjectiveSummary(
rawTeam: RiotMatchDto['info']['teams'][number] | undefined,
timelineObjectives: MatchStatsObjectiveSummary | undefined,
): MatchStatsObjectiveSummary {
const rawObjectives = rawTeam?.objectives;
const timelineDragon = timelineObjectives?.dragon ?? 0;
const timelineElder = timelineObjectives?.elderDragon ?? 0;
const hasProjectedDragon = timelineDragon + timelineElder > 0;
return {
tower: rawObjectives?.tower?.kills ?? 0,
dragon: hasProjectedDragon
? timelineDragon
: (rawObjectives?.dragon?.kills ?? 0),
inhibitor: rawObjectives?.inhibitor?.kills ?? 0,
baron:
(timelineObjectives?.baron ?? 0) > 0
? (timelineObjectives?.baron ?? 0)
: (rawObjectives?.baron?.kills ?? 0),
riftHerald:
(timelineObjectives?.riftHerald ?? 0) > 0
? (timelineObjectives?.riftHerald ?? 0)
: (rawObjectives?.riftHerald?.kills ?? 0),
voidGrub:
(timelineObjectives?.voidGrub ?? 0) > 0
? (timelineObjectives?.voidGrub ?? 0)
: (rawObjectives?.horde?.kills ?? 0),
elderDragon: hasProjectedDragon ? timelineElder : 0,
};
}
@@ -354,6 +850,100 @@ function average(value: number, total: number): number {
return total > 0 ? round(value / total) : 0;
}
function isSkillSlot(value: number | undefined): value is 1 | 2 | 3 | 4 {
return value === 1 || value === 2 || value === 3 || value === 4;
}
function toItemBuildType(
value: string,
): MatchStatsItemBuildEvent['type'] | null {
switch (value) {
case 'ITEM_PURCHASED':
return 'purchased';
case 'ITEM_SOLD':
return 'sold';
case 'ITEM_DESTROYED':
return 'destroyed';
case 'ITEM_UNDO':
return 'undo';
default:
return null;
}
}
function toObjectiveTimelineEvent(params: {
timestamp: number;
side: TeamSide;
monsterType?: string;
monsterSubType?: string;
}): MatchStatsObjectiveEvent | null {
switch (params.monsterType) {
case 'BARON_NASHOR':
return { timestamp: params.timestamp, side: params.side, type: 'baron' };
case 'RIFTHERALD':
return {
timestamp: params.timestamp,
side: params.side,
type: 'riftHerald',
};
case 'HORDE':
return {
timestamp: params.timestamp,
side: params.side,
type: 'voidGrub',
};
case 'DRAGON':
return {
timestamp: params.timestamp,
side: params.side,
type:
params.monsterSubType === 'ELDER_DRAGON' ? 'elderDragon' : 'dragon',
monsterSubType: params.monsterSubType,
};
default:
return null;
}
}
function isObjectiveTimelineEvent(
event: MatchStatsTimelineEvent,
): event is MatchStatsObjectiveEvent {
return (
event.type === 'dragon' ||
event.type === 'elderDragon' ||
event.type === 'baron' ||
event.type === 'riftHerald' ||
event.type === 'voidGrub'
);
}
function oppositeSide(side: TeamSide): TeamSide {
return side === 'blue' ? 'red' : 'blue';
}
function isUsableTimeline(
timeline: RiotMatchTimelineDto | undefined,
gameDurationSeconds: number,
): timeline is RiotMatchTimelineDto {
if (
!timeline ||
!Number.isFinite(timeline.info.frameInterval) ||
timeline.info.frameInterval <= 0 ||
!Array.isArray(timeline.info.frames) ||
timeline.info.frames.length === 0
) {
return false;
}
const finalTimestamp = Math.max(
...timeline.info.frames.map((frame) => frame.timestamp),
);
return (
Number.isFinite(finalTimestamp) &&
Math.abs(gameDurationSeconds * 1_000 - finalTimestamp) <
timeline.info.frameInterval
);
}
function round(value: number): number {
return Math.round(value * 10) / 10;
}
@@ -365,3 +955,22 @@ function numberField(
const value = participant?.[key];
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
}
function booleanField(
participant: RiotMatchParticipantDto | undefined,
key: string,
): boolean {
return participant?.[key] === true;
}
function emptyObjectives(): MatchStatsObjectiveSummary {
return {
tower: 0,
dragon: 0,
inhibitor: 0,
baron: 0,
riftHerald: 0,
voidGrub: 0,
elderDragon: 0,
};
}
@@ -0,0 +1,173 @@
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
import { MatchStatsRepository } from './match-stats.repository';
import { MatchStatsService } from './match-stats.service';
import { MATCH_STATS_BUILDER_VERSION } from './match-stats.types';
describe('MatchStatsService outbox idempotency', () => {
it('reuses the latest stored revision when an older outbox event is delivered', async () => {
const h = createHarness();
h.isCurrent.mockResolvedValue(true);
await h.service.buildAndUpsert(h.matchId, { sourceRevision: 10 });
expect(h.isCurrent).toHaveBeenCalledWith({
matchId: h.matchId,
sourceCompetitionId: h.competitionId,
sourceRevision: 12,
projectorVersion: 3,
builderVersion: MATCH_STATS_BUILDER_VERSION,
});
expect(h.riotFind).not.toHaveBeenCalled();
expect(h.builder.buildFragment).not.toHaveBeenCalled();
expect(h.upsert).not.toHaveBeenCalled();
});
it('builds once across repeated deliveries after the write succeeds', async () => {
const h = createHarness();
h.upsert.mockImplementation(async () => {
h.isCurrent.mockResolvedValue(true);
});
await h.service.buildAndUpsert(h.matchId, { sourceRevision: 12 });
await h.service.buildAndUpsert(h.matchId, { sourceRevision: 12 });
expect(h.riotFind).toHaveBeenCalledTimes(1);
expect(h.builder.buildFragment).toHaveBeenCalledTimes(1);
expect(h.upsert).toHaveBeenCalledTimes(1);
});
it('retries a failed write without treating an attempted build as complete', async () => {
const h = createHarness();
h.upsert.mockRejectedValueOnce(new Error('database unavailable'));
await expect(
h.service.buildAndUpsert(h.matchId, { sourceRevision: 12 }),
).rejects.toThrow('database unavailable');
await h.service.buildAndUpsert(h.matchId, { sourceRevision: 12 });
expect(h.builder.buildFragment).toHaveBeenCalledTimes(2);
expect(h.upsert).toHaveBeenCalledTimes(2);
});
it.each([{}, { sourceRevision: 12, includeTimeline: true }])(
'still performs explicit rebuilds and timeline hydration (%j)',
async (options) => {
const h = createHarness();
h.isCurrent.mockResolvedValue(true);
await h.service.buildAndUpsert(h.matchId, options);
expect(h.isCurrent).not.toHaveBeenCalled();
expect(h.builder.buildFragment).toHaveBeenCalledTimes(1);
expect(h.upsert).toHaveBeenCalledTimes(1);
if ('includeTimeline' in options) {
expect(h.getMatchTimeline).toHaveBeenCalledWith('KR_1', {
region: 'asia',
});
}
},
);
it('deletes reversed zero-game stats even if their versions were current', async () => {
const h = createHarness();
h.competition.projection.games = [];
h.isCurrent.mockResolvedValue(true);
await h.service.buildAndUpsert(h.matchId, { sourceRevision: 12 });
expect(h.isCurrent).not.toHaveBeenCalled();
expect(h.deleteByMatch).toHaveBeenCalledWith(h.matchId, {
sourceCompetitionId: h.competitionId,
sourceRevision: 12,
});
});
});
function createHarness() {
const matchId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const teamAId = new mongoose.Types.ObjectId();
const teamBId = new mongoose.Types.ObjectId();
const match = {
_id: matchId,
communityId: new mongoose.Types.ObjectId(),
status: 'in-progress',
scheduledAt: new Date(),
teams: [],
};
const competition = {
_id: competitionId,
revision: 12,
projectorVersion: 3,
teams: [
{ teamId: teamAId, displayOrder: 1 },
{ teamId: teamBId, displayOrder: 2 },
],
projection: {
phase: 'running',
games: [
{
displayNumber: 1,
evidence: { type: 'riot', riotMatchId: 'KR_1' },
teams: { blue: { teamId: teamAId }, red: { teamId: teamBId } },
winnerTeamId: teamAId,
},
],
},
};
const riotFind = jest.fn(() => query([{ matchId: 'KR_1', raw: {} }]));
const models = {
match: { findById: () => query(match) },
competition: { findOne: () => query(competition) },
riotMatch: { find: riotFind },
community: { findById: () => query({ riotRegion: 'asia' }) },
};
const connection = {
getModel: async (name: keyof typeof models) => models[name],
} as unknown as ConnectionService;
const isCurrent = jest.fn().mockResolvedValue(false);
const upsert = jest.fn().mockResolvedValue(undefined);
const deleteByMatch = jest.fn().mockResolvedValue(undefined);
const repository = {
hasCurrentCompetitionFragment: isCurrent,
upsert,
deleteByMatch,
} as unknown as MatchStatsRepository;
const builder = {
buildFragment: jest.fn().mockReturnValue({
matchCard: {},
records: [],
gameDetails: [],
userIds: [],
championIds: [],
gameCreationMin: 1,
gameCreationMax: 2,
}),
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
const getMatchTimeline = jest.fn().mockResolvedValue(undefined);
const service = new MatchStatsService(connection, repository, builder, {
getMatchTimeline,
} as never);
return {
service,
matchId,
competitionId,
competition,
isCurrent,
upsert,
deleteByMatch,
riotFind,
builder,
getMatchTimeline,
};
}
function query<T>(value: T) {
return {
select: jest.fn().mockReturnThis(),
lean: jest.fn().mockReturnThis(),
exec: async () => value,
};
}
@@ -0,0 +1,245 @@
import { Types } from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type { MatchStats } from '../global/database/schema';
import { MatchStatsRepository } from './match-stats.repository';
describe('MatchStatsRepository', () => {
it.each([null, { _id: new Types.ObjectId() }])(
'checks persisted source identity and every build version without loading payloads (%j)',
async (stored) => {
const exists = jest.fn(() => ({ exec: async () => stored }));
const connection = {
getModel: jest.fn().mockResolvedValue({ exists }),
} as unknown as ConnectionService;
const repository = new MatchStatsRepository(connection);
const source = {
matchId: new Types.ObjectId(),
sourceCompetitionId: new Types.ObjectId(),
sourceRevision: 12,
projectorVersion: 3,
builderVersion: 10,
};
await expect(
repository.hasCurrentCompetitionFragment(source),
).resolves.toBe(Boolean(stored));
expect(exists).toHaveBeenCalledWith({
matchId: source.matchId,
sourceCompetitionId: source.sourceCompetitionId,
sourceRevision: { $gte: 12 },
projectorVersion: { $gte: 3 },
builderVersion: { $gte: 10 },
});
},
);
it('does not let a legacy upsert overwrite a Competition-backed fragment', async () => {
const fragment = {
...statsFragment(12),
sourceCompetitionId: undefined,
sourceRevision: undefined,
projectorVersion: undefined,
};
const updateOne = jest
.fn()
.mockReturnValueOnce({
exec: jest.fn().mockResolvedValue({ matchedCount: 0 }),
})
.mockReturnValueOnce({
exec: jest
.fn()
.mockResolvedValue({ matchedCount: 1, upsertedCount: 0 }),
});
const connection = {
getModel: jest.fn().mockResolvedValue({ updateOne }),
} as unknown as ConnectionService;
const repository = new MatchStatsRepository(connection);
await repository.upsert(fragment);
expect(updateOne).toHaveBeenNthCalledWith(
1,
{
matchId: fragment.matchId,
sourceCompetitionId: { $exists: false },
},
{ $set: fragment },
{ upsert: false },
);
expect(updateOne).toHaveBeenNthCalledWith(
2,
{ matchId: fragment.matchId },
{ $setOnInsert: fragment },
{ upsert: true },
);
});
it('only updates a Competition projection when its revision is not stale', async () => {
const updateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ matchedCount: 1, upsertedCount: 0 }),
});
const connection = {
getModel: jest.fn().mockResolvedValue({ updateOne }),
} as unknown as ConnectionService;
const repository = new MatchStatsRepository(connection);
const fragment = statsFragment(12);
await repository.upsert(fragment);
expect(updateOne).toHaveBeenCalledWith(
{
matchId: fragment.matchId,
$or: [
{ sourceCompetitionId: { $exists: false } },
{ sourceCompetitionId: fragment.sourceCompetitionId },
],
$and: [
{
$or: [
{ sourceRevision: { $exists: false } },
{ sourceRevision: { $lte: 12 } },
],
},
],
},
{ $set: fragment },
{ upsert: false },
);
});
it('converges concurrent initial upserts to the highest Competition revision', async () => {
const older = statsFragment(12);
const newer = {
...statsFragment(13),
matchId: older.matchId,
sourceCompetitionId: older.sourceCompetitionId,
};
let stored: ReturnType<typeof statsFragment> | undefined;
let initialGuardCount = 0;
let releaseInitialGuards!: () => void;
const initialGuardsReady = new Promise<void>((resolve) => {
releaseInitialGuards = resolve;
});
let releaseOlderInsert!: () => void;
const olderInserted = new Promise<void>((resolve) => {
releaseOlderInsert = resolve;
});
const updateOne = jest.fn(
(
_filter: Record<string, unknown>,
update: {
$set?: ReturnType<typeof statsFragment>;
$setOnInsert?: ReturnType<typeof statsFragment>;
},
) => ({
exec: async () => {
const fragment = update.$set ?? update.$setOnInsert!;
if (update.$set && !stored && initialGuardCount < 2) {
initialGuardCount += 1;
if (initialGuardCount === 2) releaseInitialGuards();
await initialGuardsReady;
return { matchedCount: 0, upsertedCount: 0 };
}
if (update.$setOnInsert) {
if (fragment.sourceRevision === 13) await olderInserted;
const existed = stored !== undefined;
if (!stored) stored = fragment;
if (fragment.sourceRevision === 12) releaseOlderInsert();
return {
matchedCount: existed ? 1 : 0,
upsertedCount: existed ? 0 : 1,
};
}
if (
stored &&
stored.sourceCompetitionId?.equals(fragment.sourceCompetitionId) &&
stored.sourceRevision <= fragment.sourceRevision
) {
stored = fragment;
return { matchedCount: 1, upsertedCount: 0 };
}
return { matchedCount: 0, upsertedCount: 0 };
},
}),
);
const connection = {
getModel: jest.fn().mockResolvedValue({ updateOne }),
} as unknown as ConnectionService;
const repository = new MatchStatsRepository(connection);
await Promise.all([repository.upsert(older), repository.upsert(newer)]);
expect(stored?.sourceRevision).toBe(13);
});
it('guards a zero-game delete so an observed revision cannot remove newer stats', async () => {
const matchId = new Types.ObjectId();
const sourceCompetitionId = new Types.ObjectId();
const deleteOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ deletedCount: 0 }),
});
const connection = {
getModel: jest.fn().mockResolvedValue({ deleteOne }),
} as unknown as ConnectionService;
const repository = new MatchStatsRepository(connection);
await repository.deleteByMatch(matchId, {
sourceCompetitionId,
sourceRevision: 12,
});
expect(deleteOne).toHaveBeenCalledWith({
matchId,
$or: [
{ sourceCompetitionId: { $exists: false } },
{
sourceCompetitionId,
$or: [
{ sourceRevision: { $exists: false } },
{ sourceRevision: { $lte: 12 } },
],
},
],
});
});
it('deletes only non-Competition stats during legacy source cleanup', async () => {
const matchId = new Types.ObjectId();
const deleteOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ deletedCount: 0 }),
});
const connection = {
getModel: jest.fn().mockResolvedValue({ deleteOne }),
} as unknown as ConnectionService;
const repository = new MatchStatsRepository(connection);
await repository.deleteLegacyByMatch(matchId);
expect(deleteOne).toHaveBeenCalledWith({
matchId,
sourceCompetitionId: { $exists: false },
});
});
});
function statsFragment(sourceRevision: number) {
return {
matchId: new Types.ObjectId(),
communityId: new Types.ObjectId(),
sourceCompetitionId: new Types.ObjectId(),
sourceRevision,
projectorVersion: 3,
scheduledAt: new Date(),
gameCreationMin: 1,
gameCreationMax: 2,
userIds: [],
championIds: [],
matchCard: {},
records: [],
gameDetails: [],
builtAt: new Date(),
builderVersion: 9,
} satisfies Omit<MatchStats, 'createdAt' | 'updatedAt'>;
}
@@ -3,24 +3,132 @@ import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type { MatchStats, MatchStatsDocument } from '../global/database/schema';
export type MatchStatsUserRecordFragment = Pick<
MatchStats,
'matchId' | 'records' | 'builderVersion'
> & {
gameDetails?: Array<
Pick<MatchStats['gameDetails'][number], 'gameNumber' | 'rawAvailable'>
>;
};
export type MatchStatsDetailFragment = Pick<
MatchStats,
'matchId' | 'gameDetails'
>;
export interface MatchStatsDeleteGuard {
sourceCompetitionId: mongoose.Types.ObjectId;
sourceRevision: number;
}
@Injectable()
export class MatchStatsRepository {
constructor(private readonly connectionService: ConnectionService) {}
public async hasCurrentCompetitionFragment(params: {
matchId: mongoose.Types.ObjectId;
sourceCompetitionId: mongoose.Types.ObjectId;
sourceRevision: number;
projectorVersion: number;
builderVersion: number;
}): Promise<boolean> {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
return Boolean(
await MatchStatsModel.exists({
matchId: params.matchId,
sourceCompetitionId: params.sourceCompetitionId,
sourceRevision: { $gte: params.sourceRevision },
projectorVersion: { $gte: params.projectorVersion },
builderVersion: { $gte: params.builderVersion },
}).exec(),
);
}
public async upsert(
fragment: Omit<MatchStats, 'createdAt' | 'updatedAt'>,
): Promise<void> {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
await MatchStatsModel.updateOne(
{ matchId: fragment.matchId },
if (
!fragment.sourceCompetitionId ||
fragment.sourceRevision === undefined
) {
const updated = await MatchStatsModel.updateOne(
{
matchId: fragment.matchId,
sourceCompetitionId: { $exists: false },
},
{ $set: fragment },
{ upsert: false },
).exec();
if (updated.matchedCount > 0) return;
// A legacy builder must never overwrite a Competition-backed fragment
// that appeared while the legacy source was being read.
try {
await MatchStatsModel.updateOne(
{ matchId: fragment.matchId },
{ $setOnInsert: fragment },
{ upsert: true },
).exec();
} catch (error) {
if (!isDuplicateKeyError(error)) throw error;
}
return;
}
const revisionGuard = competitionRevisionGuard(fragment);
const updated = await MatchStatsModel.updateOne(
revisionGuard,
{ $set: fragment },
{ upsert: true },
{ upsert: false },
).exec();
if (updated.matchedCount > 0) return;
// If no read model exists, insert it. If a newer revision won the race,
// this filter matches it and $setOnInsert intentionally changes nothing.
try {
await MatchStatsModel.updateOne(
{ matchId: fragment.matchId },
{ $setOnInsert: fragment },
{ upsert: true },
).exec();
} catch (error) {
if (!isDuplicateKeyError(error)) throw error;
}
// A lower revision can win the initial insert between the guarded miss and
// the upsert. Re-run the monotonic CAS so every concurrent builder converges
// to the highest source revision; a newer winner simply does not match.
await MatchStatsModel.updateOne(
revisionGuard,
{ $set: fragment },
{ upsert: false },
).exec();
}
public async deleteByMatch(matchId: mongoose.Types.ObjectId): Promise<void> {
public async deleteByMatch(
matchId: mongoose.Types.ObjectId,
guard?: MatchStatsDeleteGuard,
): Promise<void> {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
await MatchStatsModel.deleteOne({ matchId }).exec();
await MatchStatsModel.deleteOne(
guard
? {
matchId,
$or: [
{ sourceCompetitionId: { $exists: false } },
{
sourceCompetitionId: guard.sourceCompetitionId,
$or: [
{ sourceRevision: { $exists: false } },
{ sourceRevision: { $lte: guard.sourceRevision } },
],
},
],
}
: { matchId },
).exec();
}
public async deleteByMatches(
@@ -31,6 +139,16 @@ export class MatchStatsRepository {
await MatchStatsModel.deleteMany({ matchId: { $in: matchIds } }).exec();
}
public async deleteLegacyByMatch(
matchId: mongoose.Types.ObjectId,
): Promise<void> {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
await MatchStatsModel.deleteOne({
matchId,
sourceCompetitionId: { $exists: false },
}).exec();
}
public async findByMatch(
matchId: mongoose.Types.ObjectId,
): Promise<MatchStatsDocument | null> {
@@ -38,6 +156,119 @@ export class MatchStatsRepository {
return MatchStatsModel.findOne({ matchId }).exec();
}
public async findByRiotMatchIds(riotMatchIds: string[]) {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
return MatchStatsModel.find({
'gameDetails.riotMatchId': { $in: riotMatchIds },
})
.select({
matchId: 1,
communityId: 1,
'gameDetails.riotMatchId': 1,
'gameDetails.rawAvailable': 1,
})
.lean()
.exec();
}
public async findMatchPage(params: {
communityId: mongoose.Types.ObjectId;
from?: number;
to?: number;
query?: string;
format?: 'pair' | 'tournament';
playerId?: string;
championId?: number;
cursor?: number;
cursorMatchId?: string;
limit: number;
}) {
const model = await this.connectionService.getModel('matchStats');
const filter: Record<string, unknown> = { communityId: params.communityId };
const conditions: Array<Record<string, unknown>> = [];
const gameCreation = {
...(params.from === undefined ? {} : { $gte: params.from }),
...(params.to === undefined ? {} : { $lte: params.to }),
};
if (Object.keys(gameCreation).length > 0) {
conditions.push({
$or: [
{ gameDetails: { $elemMatch: { gameCreation } } },
{
'gameDetails.0': { $exists: false },
gameCreationMin: gameCreation,
},
],
});
}
if (params.from !== undefined)
filter.gameCreationMax = { $gte: params.from };
if (params.to !== undefined) filter.gameCreationMin = { $lte: params.to };
if (params.championId) {
filter.records = {
$elemMatch: {
championId: params.championId,
...(Object.keys(gameCreation).length > 0 ? { gameCreation } : {}),
},
};
}
if (params.query) {
const search = {
$regex: params.query.replace(/[.*+?^$\x7b\x7d()|[\]\\]/g, '\\$&'),
$options: 'i',
};
conditions.push({
$or: [
{ 'matchCard.title': search },
{ 'matchCard.teams.name': search },
{ 'matchCard.teams.members.summonerName': search },
],
});
}
if (params.format) {
filter['matchCard.teams.1'] = { $exists: true };
filter['matchCard.teams.2'] = { $exists: params.format === 'tournament' };
}
if (params.playerId) {
filter['matchCard.teams.members.userId'] = params.playerId;
}
if (params.cursor !== undefined) {
const cursor = new Date(params.cursor);
if (params.cursorMatchId) {
conditions.push({
$or: [
{ scheduledAt: { $lt: cursor } },
{
scheduledAt: cursor,
matchId: {
$lt: new mongoose.Types.ObjectId(params.cursorMatchId),
},
},
],
});
} else {
filter.scheduledAt = { $lt: cursor };
}
}
if (conditions.length > 0) filter.$and = conditions;
return model
.find(filter)
.select({
matchId: 1,
scheduledAt: 1,
matchCard: 1,
sourceCompetitionId: 1,
sourceRevision: 1,
'gameDetails.gameNumber': 1,
'gameDetails.gameCreation': 1,
'gameDetails.rawAvailable': 1,
})
.sort({ scheduledAt: -1, matchId: -1 })
.limit(params.limit)
.lean()
.exec();
}
public async findByCommunity(params: {
communityId: mongoose.Types.ObjectId;
fromGameCreation?: number;
@@ -61,6 +292,54 @@ export class MatchStatsRepository {
.exec();
}
public async findSeasonStats(params: {
communityId: mongoose.Types.ObjectId;
from?: number;
to?: number;
}) {
const model = await this.connectionService.getModel('matchStats');
return model
.find({
communityId: params.communityId,
...(params.from === undefined
? {}
: { gameCreationMax: { $gte: params.from } }),
...(params.to === undefined
? {}
: { gameCreationMin: { $lte: params.to } }),
})
.select({
_id: 0,
matchId: 1,
scheduledAt: 1,
'records.userId': 1,
'records.summonerName': 1,
'records.tagLine': 1,
'records.profileIconId': 1,
'records.gameCreation': 1,
'records.gameNumber': 1,
'records.matchId': 1,
'records.championId': 1,
'records.teamPosition': 1,
'records.win': 1,
'records.kills': 1,
'records.deaths': 1,
'records.assists': 1,
'records.gpm': 1,
'records.csPerMin': 1,
'records.killParticipation': 1,
'records.visionScore': 1,
'records.damageShare': 1,
'gameDetails.gameCreation': 1,
'gameDetails.gameNumber': 1,
'gameDetails.winnerSide': 1,
'gameDetails.rawAvailable': 1,
})
.sort({ scheduledAt: -1 })
.lean()
.exec();
}
public async findByUser(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
@@ -68,6 +347,60 @@ export class MatchStatsRepository {
toGameCreation?: number;
}): Promise<MatchStatsDocument[]> {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
const filter = this.buildUserFilter(params);
return MatchStatsModel.find(filter).sort({ scheduledAt: -1 }).exec();
}
public async findUserRecordFragments(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
fromGameCreation?: number;
toGameCreation?: number;
limit?: number;
}): Promise<MatchStatsUserRecordFragment[]> {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
const filter = this.buildUserFilter(params);
// User history only needs records for summaries/page selection; gameDetails
// are much larger and are fetched separately for the visible page.
return MatchStatsModel.find(filter)
.sort({ scheduledAt: -1 })
.limit(params.limit ?? 300)
.select({
_id: 0,
matchId: 1,
records: 1,
builderVersion: 1,
'gameDetails.gameNumber': 1,
'gameDetails.rawAvailable': 1,
})
.lean<MatchStatsUserRecordFragment[]>()
.exec();
}
public async findDetailsByMatches(params: {
communityId: mongoose.Types.ObjectId;
matchIds: mongoose.Types.ObjectId[];
}): Promise<MatchStatsDetailFragment[]> {
if (params.matchIds.length === 0) return [];
const MatchStatsModel = await this.connectionService.getModel('matchStats');
return MatchStatsModel.find({
communityId: params.communityId,
matchId: { $in: params.matchIds },
})
.select({ _id: 0, matchId: 1, gameDetails: 1 })
.lean<MatchStatsDetailFragment[]>()
.exec();
}
private buildUserFilter(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
fromGameCreation?: number;
toGameCreation?: number;
}): Record<string, unknown> {
const filter: Record<string, unknown> = {
communityId: params.communityId,
userIds: params.userId,
@@ -78,7 +411,35 @@ export class MatchStatsRepository {
if (params.toGameCreation !== undefined) {
filter.gameCreationMin = { $lte: params.toGameCreation };
}
return MatchStatsModel.find(filter).sort({ scheduledAt: -1 }).exec();
return filter;
}
}
function competitionRevisionGuard(
fragment: Omit<MatchStats, 'createdAt' | 'updatedAt'>,
) {
return {
matchId: fragment.matchId,
$or: [
{ sourceCompetitionId: { $exists: false } },
{ sourceCompetitionId: fragment.sourceCompetitionId },
],
$and: [
{
$or: [
{ sourceRevision: { $exists: false } },
{ sourceRevision: { $lte: fragment.sourceRevision } },
],
},
],
};
}
function isDuplicateKeyError(error: unknown): boolean {
return (
typeof error === 'object' &&
error !== null &&
'code' in error &&
error.code === 11_000
);
}
Loaded 100 of 660 files, more files were not shown because too many files have changed in this diff. Show more