Compare commits

..
41 Commits
Author SHA1 Message Date
dahyeon 2379051196 . 2026-05-02 02:59:33 -07:00
dahyeon b152a5b0fa . 2026-04-28 09:15:38 -07:00
dahyeon 221a4f2097 . 2026-04-28 09:07:19 -07:00
dahyeon a076bca587 . 2026-04-28 08:38:47 -07:00
dahyeon 4475a2d86b . 2026-04-27 19:56:10 -07:00
dahyeon 1fd37f992b . 2026-04-27 19:48:42 -07:00
dahyeon b38cc03a71 . 2026-04-27 19:35:29 -07:00
dahyeon 6609098037 . 2026-04-27 19:31:31 -07:00
dahyeon 4dba82ca03 . 2026-04-27 19:23:26 -07:00
dahyeon 1bbfc901e8 . 2026-04-27 18:55:04 -07:00
dahyeon 2250b6072e . 2026-04-27 15:00:25 -07:00
dahyeon c5d296d403 . 2026-04-27 14:24:43 -07:00
dahyeon c00545f281 . 2026-04-27 14:04:04 -07:00
dahyeon 7a43a667f1 . 2026-04-27 13:16:17 -07:00
dahyeon 8b8dec4c44 . 2026-04-26 06:48:32 -07:00
dahyeon ca56af79e5 . 2026-04-26 06:39:00 -07:00
dahyeon 60928bc165 . 2026-04-26 05:38:58 -07:00
dahyeon dfcfe9e4ad . 2026-04-26 04:55:25 -07:00
dahyeon ec2315cc3d . 2026-04-26 04:41:07 -07:00
dahyeon 8369fbead7 . 2026-04-26 04:18:05 -07:00
dahyeon 4bad21c2d8 . 2026-04-26 03:42:45 -07:00
dahyeon 285f72b3ee . 2026-04-26 03:33:24 -07:00
dahyeon 6d62de4ec4 . 2026-04-26 01:42:59 -07:00
dahyeon c82bf55fe9 . 2026-04-26 01:37:12 -07:00
dahyeon 2472f865ad . 2026-04-26 01:22:38 -07:00
dahyeon 905bbcc6dd . 2026-04-25 16:27:25 -07:00
dahyeon 90a7cf6a7e . 2026-04-25 16:13:45 -07:00
dahyeon d1f7b0c916 . 2026-04-25 14:53:56 -07:00
dahyeon d0ae8ffb0e . 2026-04-25 12:54:57 -07:00
dahyeon b7127b59af . 2026-04-25 12:43:12 -07:00
dahyeon f7ee34da4f . 2026-04-25 11:49:21 -07:00
dahyeon 5af2c80cd1 . 2026-04-24 23:18:56 -07:00
dahyeon 30dfb7ce58 . 2026-04-24 13:40:39 -07:00
dahyeon a197185ad0 feat(api): implement Riot tournament webhook endpoint
Adds a controller to capture and log incoming webhook notifications from Riot Games. Enables raw body parsing at the application level to facilitate payload processing and future signature verification.
2026-04-15 21:27:59 +09:00
dahyeon 35b7db5344 feat(api): implement tournament and auction system models
Introduces new database models and service integrations for managing tournament-related data including users, matches, and auction processes. Updates NATS connection to remove unused TLS configuration.
2026-04-15 17:23:54 +09:00
dahyeon 909845a1df feat(web): implement main pages and auction system
- Set up React Router with routes for Home, Match Detail, and Auction pages
- Integrate Tailwind CSS and daisyUI for application styling
- Implement match management UI components using mock data
- Add auction team-building simulation logic and associated types
- Update project configuration to support the new UI framework
2026-04-15 02:06:42 +09:00
dahyeon 7f0f78b4a1 feat(api): implement Riot Match Service
feat(api): integrate RiotModule and ConfigModule
2026-04-15 02:06:42 +09:00
dahyeon 342bc2565e feat(api): implement Riot Account Service 2026-04-15 02:06:42 +09:00
dahyeon 3ceb654374 feat(api): Implement Riot API client service
feat(riot): create Riot module for service registration
2026-04-15 02:06:42 +09:00
dahyeon b4d0fef5fb feat(api): Add Riot API types for account and match 2026-04-15 02:06:42 +09:00
dahyeon e3da5d83b6 initial commit 2026-04-11 11:44:55 -07:00
441 changed files with 16539 additions and 96407 deletions

No files matched your search

-4
View File
@@ -1,4 +0,0 @@
[mcp_servers.playwright_macos]
url = "http://100.96.0.26:8931/mcp"
tool_timeout_sec = 120
startup_timeout_sec = 30
+2 -13
View File
@@ -1,5 +1,5 @@
bin/
/lib/
lib/
dist/
node_modules/
.pnpm-store/
@@ -23,15 +23,4 @@ website/LICENSE
*.temp.MD
*.md
!README.md
!AGENTS.md
!docs/specs/internal-match-game-analysis.md
!docs/plans/internal-match-game-analysis-p0-p1.md
!agents/**/*.md
!skills/**/*.md
/tmp/
/user-game-history/
/*.txt
/*.png
*.md
-1
View File
@@ -1 +0,0 @@
26
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 383 KiB

-189
View File
@@ -1,189 +0,0 @@
# AGENTS.md
This file provides guidance to AI coding agents (Claude Code, Cursor, Copilot, Antigravity, etc.) when working with code in this repository.
## Repository Overview
A collection of skills for Claude.ai and Claude Code for senior software engineers. Skills are packaged instructions and scripts that extend Claude and your coding agents capabilities.
## OpenCode Integration
OpenCode uses a **skill-driven execution model** powered by the `skill` tool and this repository's `/skills` directory.
### Core Rules
- If a task matches a skill, you MUST invoke it
- Skills are located in `skills/<skill-name>/SKILL.md`
- Never implement directly if a skill applies
- Always follow the skill instructions exactly (do not partially apply them)
### Intent → Skill Mapping
The agent should automatically map user intent to skills:
- Feature / new functionality → `spec-driven-development`, then `incremental-implementation`, `test-driven-development`
- Planning / breakdown → `planning-and-task-breakdown`
- Bug / failure / unexpected behavior → `debugging-and-error-recovery`
- Code review → `code-review-and-quality`
- Refactoring / simplification → `code-simplification`
- API or interface design → `api-and-interface-design`
- UI work → `frontend-ui-engineering`
### Lifecycle Mapping (Implicit Commands)
OpenCode does not support slash commands like `/spec` or `/plan`.
Instead, the agent must internally follow this lifecycle:
- DEFINE → `spec-driven-development`
- PLAN → `planning-and-task-breakdown`
- BUILD → `incremental-implementation` + `test-driven-development`
- VERIFY → `debugging-and-error-recovery`
- REVIEW → `code-review-and-quality`
- SHIP → `shipping-and-launch`
### Execution Model
For every request:
1. Determine if any skill applies (even 1% chance)
2. Invoke the appropriate skill using the `skill` tool
3. Follow the skill workflow strictly
4. Only proceed to implementation after required steps (spec, plan, etc.) are complete
### Anti-Rationalization
The following thoughts are incorrect and must be ignored:
- "This is too small for a skill"
- "I can just quickly implement this"
- "I’ll gather context first"
Correct behavior:
- Always check for and use skills first
This ensures OpenCode behaves similarly to Claude Code with full workflow enforcement.
## Orchestration: Personas, Skills, and Commands
This repo has three composable layers. They have different jobs and should not be confused:
- **Skills** (`skills/<name>/SKILL.md`) — workflows with steps and exit criteria. The *how*. Mandatory hops when an intent matches.
- **Personas** (`agents/<role>.md`) — roles with a perspective and an output format. The *who*.
- **Slash commands** (`.claude/commands/*.md`) — user-facing entry points. The *when*. The orchestration layer.
Composition rule: **the user (or a slash command) is the orchestrator. Personas do not invoke other personas.** A persona may invoke skills.
The only multi-persona orchestration pattern this repo endorses is **parallel fan-out with a merge step** — used by `/ship` to run `code-reviewer`, `security-auditor`, and `test-engineer` concurrently and synthesize their reports. Do not build a "router" persona that decides which other persona to call; that's the job of slash commands and intent mapping.
See [agents/README.md](agents/README.md) for the decision matrix and [references/orchestration-patterns.md](references/orchestration-patterns.md) for the full pattern catalog.
**Claude Code interop:** the personas in `agents/` work as Claude Code subagents (auto-discovered from this plugin's `agents/` directory) and as Agent Teams teammates (referenced by name when spawning). Two platform constraints align with our rules: subagents cannot spawn other subagents, and teams cannot nest. Plugin agents silently ignore the `hooks`, `mcpServers`, and `permissionMode` frontmatter fields.
## Creating a New Skill
### Directory Structure
```
skills/
{skill-name}/ # kebab-case directory name
SKILL.md # Required: skill definition
scripts/ # Required: executable scripts
{script-name}.sh # Bash scripts (preferred)
{skill-name}.zip # Required: packaged for distribution
```
### Naming Conventions
- **Skill directory**: `kebab-case` (e.g. `web-quality`)
- **SKILL.md**: Always uppercase, always this exact filename
- **Scripts**: `kebab-case.sh` (e.g., `deploy.sh`, `fetch-logs.sh`)
- **Zip file**: Must match directory name exactly: `{skill-name}.zip`
### SKILL.md Format
```markdown
---
name: {skill-name}
description: {One sentence describing what the skill does, followed by one or more "Use when" trigger conditions. Include trigger phrases like "Deploy my app" or "Check logs" when helpful.}
---
# {Skill Title}
{Brief overview of what the skill does and why it matters.}
## How It Works
{Numbered list explaining the skill's workflow}
Equivalent headings like `Workflow`, `Core Process`, or `When to Use` are fine when they communicate the same structure clearly.
## Usage (Optional)
Include this section only if the skill ships runnable helpers under `scripts/`. Markdown-only skills can omit both the section and the directory entirely.
```bash
bash /mnt/skills/user/{skill-name}/scripts/{script}.sh [args]
```
**Arguments:**
- `arg1` - Description (defaults to X)
**Examples:**
{Show 2-3 common usage patterns}
## Output
{Show example output users will see}
## Present Results to User
{Template for how Claude should format results when presenting to users}
## Troubleshooting
{Common issues and solutions, especially network/permissions errors}
```
### Best Practices for Context Efficiency
Skills are loaded on-demand — only the skill name and description are loaded at startup. The full `SKILL.md` loads into context only when the agent decides the skill is relevant. To minimize context usage:
- **Keep SKILL.md under 500 lines** — put detailed reference material in separate files
- **Write specific descriptions** — helps the agent know exactly when to activate the skill
- **Use progressive disclosure** — reference supporting files that get read only when needed
- **Prefer scripts over inline code** — script execution doesn't consume context (only output does)
- **File references work one level deep** — link directly from SKILL.md to supporting files
### Script Requirements
- Use `#!/bin/bash` shebang
- Use `set -e` for fail-fast behavior
- Write status messages to stderr: `echo "Message" >&2`
- Write machine-readable output (JSON) to stdout
- Include a cleanup trap for temp files
- Reference the script path as `/mnt/skills/user/{skill-name}/scripts/{script}.sh`
### Creating the Zip Package
After creating or updating a skill:
```bash
cd skills
zip -r {skill-name}.zip {skill-name}/
```
### End-User Installation
Document these two installation methods for users:
**Claude Code:**
```bash
cp -r skills/{skill-name} ~/.claude/skills/
```
**claude.ai:**
Add the skill to project knowledge or paste SKILL.md contents into the conversation.
If the skill requires network access, instruct users to add required domains at `claude.ai/settings/capabilities`.
-1
View File
@@ -1 +0,0 @@
83
+43
View File
@@ -0,0 +1,43 @@
# 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
@@ -0,0 +1,481 @@
# 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`를 안전하게 생성한다
+7 -19
View File
@@ -1,11 +1,11 @@
# syntax=docker/dockerfile:1.7
FROM node:26-bookworm-slim AS pnpm-base
FROM node:24-bookworm-slim AS pnpm-base
ENV PNPM_HOME=/pnpm
ENV PATH="${PNPM_HOME}:${PATH}"
RUN npm install --global pnpm@10.4.1
RUN corepack enable
WORKDIR /app
@@ -14,48 +14,36 @@ 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/nodejs26-debian13:nonroot AS runtime
FROM gcr.io/distroless/nodejs24-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 3000
EXPOSE 10712
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"]
CMD ["apps/api/dist/main.js"]
+433
View File
@@ -0,0 +1,433 @@
# 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
@@ -1,480 +0,0 @@
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
@@ -0,0 +1,465 @@
# 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 통계 페이지에 자동 포함됨
-175
View File
@@ -1,175 +0,0 @@
# 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
- Redis
- Redis 8.4 (경매 실시간 상태 전용)
- 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 7.0, 일반 캐시/스트림용 Redis, 경매 실시간 상태 전용 Redis 8.4, NATS 실행 환경
경매 Redis는 라이브 경매 상태의 source of truth로 사용되므로 일반 캐시/스트림 Redis와 물리적으로 분리해야 합니다. API는 `REDIS_URL`/`REDIS_ENDPOINT`와 별도로 `AUCTION_REDIS_URL`/`AUCTION_REDIS_ENDPOINT`를 읽고, 두 값이 같은 호스트/포트를 가리키면 부팅을 거부합니다.
## 실행 방법
```bash
pnpm install
pnpm start:api:dev
pnpm start:web:dev
```
웹 앱은 기본적으로 `apps/web/.env.development` 값을 사용합니다. API 환경값은 `apps/project.env`와 실행 환경의 시크릿 설정을 함께 확인합니다.
### 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 서버와 연결되어 있지 않으면 일정 조회, 내전 참가, 참가 취소, 계정 등록 같은 카카오톡 명령어는 사용할 수 없습니다.
## 커맨드
| Command | Description |
| --------------------------------- | -------------------------------- |
| `pnpm start:web:dev` | 웹 앱 개발 서버 실행 |
| `pnpm start:api:dev` | API 서버 dev 환경 실행 |
| `pnpm --filter api test` | API 테스트 실행 |
| `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
@@ -0,0 +1,628 @@
# 소환사 전적 페이지 플랜
> **대상**: 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
@@ -0,0 +1,673 @@
# Riot 최근 솔로랭크 통계 통합 플랜
> **대상**: codex가 이어서 진행 가능한 수준의 실행 플랜
> **레포**: `/Users/dahyeon/source/lolympus-tournament-support` (pnpm workspace)
> **작성 기준**: 2026-04-26
> **선행 작업**: Riot-캐싱-Phase2-플랜.md, Riot-DDragon Manifest 도입(`RiotDdragonService` + Garnet 캐시) 완료
---
## 1. Context
`AuctionPage.tsx` 의 "최근 솔로랭크" 카드(승률/전적/KDA/평균 CS)가 현재 모두 `0`/`NaN` 으로 표시됩니다. 백엔드는 이미 `RiotAccount.recentStatsSummary` 필드를 노출하고 있고 mapper도 이를 전달하지만, **이 필드를 채우는 enrichment 단계가 비어 있습니다.**
이번 작업은 다음을 추가합니다.
1. **Match-V5 by-puuid (queue=420)** 으로 솔로랭크 matchId 목록 동기화
2. **Match-V5 detail** 호출 → `RiotMatch` 컬렉션에 raw 보관 (이미 schema 존재)
3. 사용자별 `RiotAccount.recentStatsSummary` 재계산 + `recentStatsFetchedAt` 갱신
4. enrichment 트리거(수동 / 신규 등록 / 경매 직전) 와 TTL/Garnet dedup 적용
5. 클라가 0/NaN 대신 실제 값을 표시하도록 mapper 점검
이미 다음이 갖춰져 있어 추가 인프라가 거의 필요 없습니다.
- `RiotMatchService.getMatchIdsByPuuid({queue, count, ...})` (`riot-match.service.ts`)
- `RiotMatchService.getMatch(matchId)` 가 `RiotMatchDto` 파싱까지 포함
- `RiotMatch` 컬렉션(`riot_match`) + `participantPuuids` 인덱스(`schema.ts:573`)
- `RiotAccount.matchIds`, `matchIdsFetchedAt`, `recentStatsSummary`, `recentStatsFetchedAt` 필드(`schema.ts:128-148`)
- `GarnetService` (in-flight dedup / TTL 락 용도)
---
## 2. 결정된 설계 사항
### 2.1 큐 정책
- **1차 대상은 솔로랭크(`queueId=420`) 만**.
- 자유랭크(`440`)/노말은 추후 Phase 확장. 코드는 `queueId` 를 인자로 받는 형태로 짜되 호출부는 420 고정.
### 2.2 "최근" 의 정의
- **최근 20경기** 고정 윈도우 (사용자 결정). 상수 `RIOT_RECENT_MATCH_LIMIT = 20` 으로 service 모듈에 정의, 환경변수화 하지 않음.
- 시즌 경계 보정은 하지 않음. `mostPlayedChampionIds` 가 시즌 패치에 따라 의미가 흔들릴 수 있다는 한계를 README/주석에 명시.
### 2.3 캐시 / TTL
- `RiotAccount.recentStatsFetchedAt` 기반 staleness 검사. TTL 기본 **6h** (mastery와 동일).
- enrichment 진행 중 동일 (userId, puuid) 키 중복 호출 방지: 메모리 + Garnet **NX 락**.
- 메모리 dedup: `RiotAccountEnrichmentService.inFlight` 패턴 그대로 확장
- Garnet 락: `riot:enrich:matches:<puuid>` 키 + `setStringIfAbsent(..., 60)` (다중 인스턴스 안전망)
- ddragon manifest 패턴(`Riot-DDragon`)과 동일하게 in-flight 후 **TTL 캐시 갱신** → 다음 호출은 즉시 fresh 반환.
### 2.4 RiotMatch 저장 정책
- `RiotMatch.matchId` 기준 upsert. **이미 존재하면 API 재호출하지 않음** (다른 사용자가 이미 가져왔을 가능성).
- `participantPuuids` 인덱스 활용 → 한 puuid 의 최근 N경기를 DB에서 즉시 조회 가능.
- Riot raw 응답은 `raw` 필드(Mixed) 에 통째로 저장. 핵심 메타(`gameCreation`, `gameDuration`, `gameVersion`, `queueId`) 는 top-level 으로 복제(필터/정렬용).
- 페이로드 크기 우려: 한 경기 ≈ 30~80KB. 활성 사용자 100명 × 20경기 = 최대 2k 도큐먼트 ≈ 100MB 미만, 같은 매치 dedup 으로 실제는 더 작음.
- **TTL/prune 없음 (사용자 결정).** 무한 누적 정책. 추후 컬렉션 비대화 시 별도 prune job 검토.
### 2.5 통계 계산 규칙 (라인별 분리)
**사용자 결정 2026-04-26**: 탑/정글/미드/바텀/서폿 라인별로 데이터 구분 필요.
#### 라인 식별
- Match-V5 participant 의 `teamPosition` 필드 (`TOP` | `JUNGLE` | `MIDDLE` | `BOTTOM` | `UTILITY`) 사용.
- 빈 문자열인 경우 `individualPosition` 으로 fallback.
- 둘 다 비어있거나 `Invalid` 면 통계에서 제외 (집계 카운트 안 함).
#### 우리 측 enum 매핑
```ts
// schema 신규
export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY';
const POSITION_TO_LANE: Record<Position, RiotLane> = {
TOP: 'TOP',
JGL: 'JUNGLE',
MID: 'MIDDLE',
ADC: 'BOTTOM',
SUP: 'UTILITY',
};
```
#### 새 데이터 구조
```ts
export interface RiotLaneStats {
games: number;
wins: number;
losses: number;
avgKills: number; // 소수 1자리
avgDeaths: number;
avgAssists: number;
avgCs: number; // (totalMinionsKilled + neutralMinionsKilled) / games
avgCsPerMin: number; // 분당 CS — 라인 비교용 (서폿 비교 한계 보정)
mostPlayedChampionIds: number[]; // 상위 3, Riot DTO 와 동일 number
}
export interface RiotRecentStatsSummary {
overall: RiotLaneStats;
byLane: Partial<Record<RiotLane, RiotLaneStats>>; // 게임이 1회 이상 있는 라인만 entry
// 기존 flat 필드들은 schema 마이그레이션을 통해 제거. § 2.5.1 참고.
}
```
`mostPlayedChampionIds` 는 **`number[]`** (Riot DTO 와 동일). 클라는 ddragon manifest 로 표시명 풀이. § 2.5.3 참고.
### 2.5.3 championId 타입 통일 (전체 number)
기존 정합성 깨진 곳: `RiotRecentStatsSummary.mostPlayedChampionIds: string[]` (`schema.ts:123`) — Phase2 에서 mastery 는 number 로 바꿨는데 이 한 줄만 string 으로 잔존. Riot 모든 응답이 number 이므로 **number 로 통일**.
영향 받는 위치:
- `apps/api/src/modules/global/database/schema.ts:123` — `string[]` → `number[]`
- `apps/api/src/modules/riot/riot.types.ts` — `RiotRecentStatsSummary` 동일 변경
- `apps/web/src/api/types.ts` — `ApiRiotRecentStatsSummary.mostPlayedChampionIds`, 그리고 §3.7 신규 `ApiRiotLaneStats` 도 처음부터 `number[]`
- `apps/web/src/lib/ddragon.ts` — 이미 `string | number` 둘 다 받게 만들어둠. 변경 불필요.
기존 DB 도큐먼트에 `string[]` 으로 저장된 게 있을 가능성: enrichment 한 번 돌면 새 구조로 통째 교체되므로 자동 정리. 별도 마이그레이션 스크립트 불필요.
#### 2.5.1 schema 마이그레이션 메모
- 기존 `RiotRecentStatsSummary` (flat) 는 사용처가 mapper 한 곳뿐 (`mappers.ts:184~`).
- DB 에 이미 저장된 도큐먼트는 옛 형태일 수 있으나 enrichment 가 한 번 돌면 자동 덮어씀.
- 안전한 전환: enrichment service 가 응답 직전 항상 새 구조로 만들어 `account.recentStatsSummary = newSummary` 통째 교체. partial merge 안 함.
- 별도 마이그레이션 스크립트 불필요 (TTL 6h 안에 자연 갱신).
### 2.5.4 시즌 경계 — 자동 리셋
LoL 시즌(splits/sets) 시작 시점에는 누적 통계의 의미가 변하므로 자동 리셋 필요. Riot 이 명시적 "season started at" API 를 제공하지 않으므로 **community 단위 수동 설정 + 자동 필터링** 의 하이브리드.
#### Schema 추가
```ts
// schema.ts Community
seasonStartedAt?: Date; // 운영자/admin 이 시즌 시작 시점 등록
```
#### 동작
1. enrichment 진입 시 `community.seasonStartedAt` 조회.
2. `account.recentStatsFetchedAt < community.seasonStartedAt` 이면 **force=true** 로 진행 (TTL 무시).
3. `computeSummary` 가 매치 필터링: `match.info.gameCreation >= seasonStartedAt.getTime()` 인 것만 사용.
4. `account.matchIds` 도 시즌 경계 이전 것은 통계에서 제외 (DB 자체에서는 제거 안 함 — 무한 저장 정책).
#### Trigger
- 운영자가 새 시즌 시작 시 community 의 `seasonStartedAt` 을 수동 갱신 → 다음 enrichment 부터 자동 적용.
- 야간 prefetch 가 다음 사이클에 일괄 갱신.
#### Phase 후속 (자동화 검토)
- Riot patch notes RSS 또는 ddragon `versions.json` 의 major bump 감지로 자동 갱신 — 본 플랜 범위 외.
### 2.5.5 다국가 region 지원 (구조)
현재 enrichment 가 `region: 'asia'`, `platform: 'kr'` 하드코딩. 이미 `Community.riotPlatform`, `Community.riotRegion` 필드는 schema 에 존재하지만 enrichment 호출부에서 사용 안 함.
#### 변경
1. **호출자 책임 모델**: `enrichRiotAccount` 의 `EnrichOptions.platform/region` 으로 community 값을 명시 전달.
2. enrichment 트리거 지점 (`auction.service`, `dakao-user.service`, `prefetch.scheduler`) 에서 community 조회 후 platform/region 을 옵션에 주입.
3. fallback 기본값은 `kr` / `asia` 유지 (community 미지정 시).
4. **Throttle 분리**: §2.7 의 sliding-window 키가 이미 region 별로 분리됨 (`riot:rl:<region>:1s`) — 추가 변경 없음.
5. **DDragon 영향**: `realms/<region>.json` 별 자체 dd 버전이 다를 수 있음. 현재 `RiotDdragonService` 는 글로벌 versions[0] 사용 중 — 한국 클라이언트 dd 버전이 글로벌과 차이 거의 없어 OK. 다른 region 추가 시 region 별 manifest 캐시로 분리 검토.
#### 호출 패턴
```ts
// auction.service.ts:start
const community = await CommunityModel.findById(params.communityId);
const platform = community?.riotPlatform ?? 'kr';
const region = community?.riotRegion ?? 'asia';
const limit = pLimit(3);
await Promise.allSettled(
order.map(p => limit(() => this.enrichmentService.enrichRiotAccount({
userId: p.userId,
puuid: p.puuid,
options: { platform, region, force: false },
}))),
);
```
`prefetch.scheduler` 는 사용자별 community 를 cursor 단계에서 함께 로드 (또는 community → user 양방향 join).
### 2.5.2 0-state UX (사용자 결정: 적당히 제안)
| 상황 | 표시 |
|---|---|
| `overall.games === 0` (enrichment 실패 또는 신규 사용자) | "최근 솔로랭크 기록이 없습니다" placeholder |
| 주 라인(`mainPosition`) 게임 ≥ 1 | 헤더에 주 라인 통계 강조 표시 |
| 주 라인 게임 = 0, 다른 라인 있음 | 헤더에 `overall` 통계 + "주 라인 기록 없음 / 전체 기준" 보조 라벨 |
| 라인별 미니 row | 게임 ≥ 1 라인은 W-L · KDA · CS/min, 0 게임 라인은 회색 dash |
### 2.6 트리거 시점
| 시점 | 호출 방식 | force |
|---|---|---|
| 신규 RiotAccount 등록 (dakao 명령) | 동기 enrich 호출 | true |
| 사용자 수동 갱신 (Phase2 엔드포인트 추가됨) | 동기 호출 | true |
| 경매 `start` 직전 | 참가자 puuid 일괄 enrich (`p-limit` 적용, §2.7 throttle 참조) | false |
| 야간 스케줄러 (Phase 2 후속) | force=false 로 stale 만 갱신 | false |
→ 본 플랜에서는 **트리거 4개 지점만 호출 추가**. 스케줄러는 Phase 2 트랙에서 처리.
### 2.7 Rate Limit / Throttle (개인키 가정)
**전제**: 개인 API 키 — Riot 공식 한도 `20 req / 1s` + `100 req / 120s` (앱 단위, region 별).
#### A. 사전 차단 — `RiotClientService` 통합 throttle
모든 Riot 호출이 `RiotClientService.get()` 을 통과하므로 여기에 한 곳에서 게이트를 건다. **Garnet 기반 sliding-window** 로 다중 인스턴스 안전성 확보.
키 구조:
```
riot:rl:<region>:1s -- ZSET (score=timestampMs, member=uuid)
riot:rl:<region>:120s -- ZSET (동일)
```
호출 시 의사코드:
```ts
async function acquire(region: string): Promise<void> {
const now = Date.now();
for (;;) {
const wait = await checkAndAdd(region, now); // Lua script 추천
if (wait === 0) return;
await sleep(wait);
}
}
```
`checkAndAdd` 는 **Lua script 1회 호출**(원자성):
1. `ZREMRANGEBYSCORE key 0 (now - windowMs)` 로 윈도우 밖 제거
2. `ZCARD key` 로 현재 카운트
3. 한도 초과 시 `ZRANGE key 0 0 WITHSCORES` 로 가장 오래된 항목의 만료 시각 → 대기 시간 반환
4. 가능하면 `ZADD key now uuid` + `EXPIRE key windowMs` 후 0 반환
두 윈도우(1s/120s) 모두 통과해야 진행. 하나라도 막히면 더 큰 wait 반환.
`apps/api/src/modules/riot/riot-rate-limiter.service.ts` 신규:
```ts
@Injectable()
export class RiotRateLimiterService {
constructor(private readonly garnet: GarnetService) {}
public async acquire(region: RiotRegionalRoute | RiotPlatformRoute): Promise<void>;
// 옵션: per-method 한도 추가 시 추가 인자
}
```
설정 상수(코드 상수, 환경변수화 안 함):
```ts
const APP_LIMITS = [
{ windowMs: 1_000, max: 20 },
{ windowMs: 120_000, max: 100 },
];
```
> 안전 마진을 위해 max 를 **18 / 95** 로 살짝 낮추는 옵션을 코드 주석으로 남김 — 다른 클라이언트(예: 로컬 개발기)와 키를 공유할 때 충돌 방지.
#### B. 사후 처리 — 429 backoff
`RiotClientService.get()` 응답이 429 일 때:
1. 기존 `Retry-After` 캡처 로직(`riot.client.service.ts:125`) 활용
2. `Retry-After` 만큼 대기 후 **최대 1회 재시도**
3. 재시도도 429 면 `RiotApiError` throw (현재 동작 유지)
#### C. 클라이언트단 동시성 제한
Auction `start` 트리거에서 5명 동시 enrichment × (1 list + 최대 20 detail) = burst 가 가장 큼. 사전 차단만으로도 Riot 한도는 지켜지지만, 처리 시간이 길어지므로 **fairness 를 위한 동시성 한도** 도 추가:
- `p-limit` 의존성 추가 (`pnpm --filter api add p-limit`)
- enrichment service 내부에서 `recentMatches` 페치 시 detail 호출을 `pLimit(2)` 로 직렬화
- auction.service 트리거에서도 사용자별 enrichment 자체에 `pLimit(3)` 적용
#### D. 메서드 한도(Method Rate Limit)
Match-V5 `getMatch` 는 `2000 req / 10s` 라 앱 한도가 먼저 걸린다 — **본 플랜에서는 method 한도는 별도 추적 안 함**. 추후 다른 method 추가 시 `RiotRateLimiterService` 가 method 단위 카운터도 받도록 확장.
#### E. 운영 가시성
- `RiotRateLimiterService.acquire()` 가 100ms 이상 대기하면 `logger.warn` (throttle 발생 추적)
- 응답 헤더 `X-App-Rate-Limit-Count` 를 매 호출마다 디버그 로그(샘플링) → 실제 사용량 vs 우리 카운터 drift 확인
---
## 3. 변경 사항 (파일 단위)
### 3.1 신규: `apps/api/src/modules/riot/riot-recent-matches.service.ts`
```ts
@Injectable()
export class RiotRecentMatchesService {
constructor(
private readonly connectionService: ConnectionService,
private readonly matchService: RiotMatchService,
private readonly garnetService: GarnetService,
) {}
/** queue=420 기준 최근 N matchId 동기화 + raw 저장. 새로 가져온 RiotMatch 도큐먼트들 반환 */
public async syncRecentMatches(params: {
puuid: string;
region?: RiotRegionalRoute;
limit?: number; // 기본 20
queueId?: number; // 기본 420
}): Promise<RiotMatchDocument[]>;
/** DB 에서 puuid 기준 최근 N matchInfo 조회 (API 호출 없음) */
public async loadFromDb(params: {
puuid: string;
limit?: number;
queueId?: number;
}): Promise<RiotMatchDocument[]>;
}
```
핵심 로직:
1. `getMatchIdsByPuuid({queue, count, region: 'asia'})`
2. 받은 ids 를 `riot_match.find({matchId: {$in: ids}}, {matchId: 1})` 로 존재 여부 조회
3. 없는 것만 `getMatch(matchId)` → upsert (`updateOne({matchId}, {$setOnInsert: {...}}, {upsert: true})`)
4. Garnet 락: `riot:enrich:matches:<puuid>` NX EX 60. 락 획득 실패 시 즉시 return DB 캐시.
5. queueId 필터: list API 의 `queue` 파라미터로 한 번 거르고, detail 응답의 `info.queueId` 로 한 번 더 검증.
### 3.2 신규: `RiotRecentStatsService` (또는 위 service에 합쳐도 OK)
```ts
public computeSummary(matches: RiotMatchDto[], puuid: string): RiotRecentStatsSummary;
```
- 순수 함수. 단위 테스트 추가(`*.spec.ts`).
- 입력 매치에서 `info.participants.find(p => p.puuid === puuid)` 로 본인 participant 찾기.
- 라인 결정: `teamPosition || individualPosition`. 빈 값이면 `byLane` 집계에서 제외하되 `overall` 에는 포함.
- 0경기 입력 시 `overall` 은 모든 수치 0 으로 채운 객체, `byLane` 은 빈 객체 `{}`. 클라 NaN 회피.
- `avgCsPerMin = ((totalMinionsKilled + neutralMinionsKilled) / (gameDuration / 60))` 의 평균. `gameDuration` 은 초 단위.
### 3.3 `riot-account-enrichment.service.ts` 확장
`EnrichOptions` 에 `recentMatchesTtlMs` (기본 6h) 추가.
`EnrichResult` 에 `recentMatches: 'updated' | 'fresh' | 'failed'` 추가.
`doEnrichRiotAccount` 에:
```ts
const recentMatchesStale =
force ||
!account.recentStatsFetchedAt ||
now - account.recentStatsFetchedAt.getTime() > recentMatchesTtl;
const recentOutcome = recentMatchesStale
? await this.fetchRecentMatchesSafe(params.puuid, region)
: { status: 'fresh' as const, summary: null };
if (recentOutcome.status === 'updated' && recentOutcome.summary) {
account.recentStatsSummary = recentOutcome.summary;
account.recentStatsFetchedAt = new Date();
account.matchIds = recentOutcome.matchIds;
account.matchIdsFetchedAt = new Date();
}
```
`fetchRecentMatchesSafe`:
1. `recentMatchesService.syncRecentMatches({puuid, region})`
2. `recentMatchesService.loadFromDb({puuid, limit: 20, queueId: 420})`
3. `computeSummary(matches, puuid)`
4. 실패 시 `failed` 반환 (기존 patterns와 동일).
### 3.4 `riot.module.ts`
`RiotRecentMatchesService`, `RiotRateLimiterService` 를 providers/exports 에 추가. `GarnetModule` 은 `@Global` 이라 별도 import 불필요.
### 3.4.1 `riot.client.service.ts` 변경
- 생성자에 `RiotRateLimiterService` 주입.
- `get()` 진입 시 `await this.rateLimiter.acquire(options.platform ?? options.region ?? 'asia')`.
- 응답이 429 일 때 `Retry-After` 캡처 후 `await sleep(retryAfterMs)` → 한 번 재시도. 재시도도 429 면 throw.
- (기존 동작과의 차이: throttle/재시도 추가, 그 외 인터페이스 동일.)
### 3.5 트리거 지점
- `apps/api/src/modules/dakao/dakao-user.service.ts`: 신규 RiotAccount 등록 직후 `enrichRiotAccount({force: true})` 호출 흐름이 이미 있는지 확인하고 동일 흐름 유지(별도 호출 추가 불필요).
- `apps/api/src/modules/auction/auction.service.ts:start`: order 구성 직후, 참가자 puuid 들에 대해 `p-limit(3)` 으로 동시성 제한:
```ts
const limit = pLimit(3);
await Promise.allSettled(
order.map(p => limit(() => this.enrichmentService.enrichRiotAccount({
userId: p.userId, puuid: p.puuid, options: {force: false}
}))),
);
```
이미 fresh 면 즉시 return 이라 비용 거의 없음. throttle 은 `RiotClientService` 단에서 추가로 보호.
### 3.6 수동 갱신 엔드포인트
Phase 2 플랜의 `POST /me/riot-accounts/:puuid/refresh` 가 추가되면 동일 enrichment 가 호출되므로, **본 플랜에서 별도 엔드포인트는 만들지 않고** Phase 2 와 합류.
### 3.7 클라 — 변경 큼
#### types.ts
```ts
export interface ApiRiotLaneStats {
games: number;
wins: number;
losses: number;
avgKills: number;
avgDeaths: number;
avgAssists: number;
avgCs: number;
avgCsPerMin: number;
mostPlayedChampionIds: string[];
}
export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY';
export interface ApiRiotRecentStatsSummary {
overall: ApiRiotLaneStats;
byLane: Partial<Record<RiotLane, ApiRiotLaneStats>>;
}
```
기존 flat 필드는 제거. 클라는 enrichment 한 번 돌고 난 새 구조 가정.
#### mappers.ts
`AuctionPlayerView.recentStats` 를 새 구조로 정렬. 추가로 `pickPrimary(stats, mainPosition)` 헬퍼:
```ts
const POSITION_TO_LANE: Record<Position, RiotLane> = {
TOP: 'TOP', JGL: 'JUNGLE', MID: 'MIDDLE', ADC: 'BOTTOM', SUP: 'UTILITY',
};
function pickPrimary(summary, mainPosition) {
const lane = POSITION_TO_LANE[mainPosition];
const lanePrimary = summary.byLane[lane];
if (lanePrimary && lanePrimary.games > 0) return { stats: lanePrimary, source: 'lane' };
if (summary.overall.games > 0) return { stats: summary.overall, source: 'overall' };
return { stats: null, source: 'none' };
}
```
#### AuctionPage.tsx — "최근 솔로랭크" 카드 재설계
```
┌ 최근 솔로랭크 ─ 미드 ───────┐ ← 헤더에 표시 기준 라인
│ 승률 56% · 28W 22L │
│ KDA 7.1/3.4/8.2 (4.50) │
│ 분당 CS 7.2 │
├──────────────────────────── │
│ 탑 2W 1L · 5.0/3.3/4.7 │ ← byLane 미니 row
│ 정글 — │ ← 0 게임 dash
│ 미드 25W 19L · 7.1/3.4/8.2 │ ← 강조
│ 바텀 — │
│ 서폿 1W 2L · 1.0/4.0/15.7 │
└─────────────────────────────┘
```
- 헤더: `pickPrimary` 결과의 `stats` + `source === 'overall'` 이면 "(전체 기준)" 보조 라벨.
- 미니 row: 5개 라인 고정 순서 (TOP/JGL/MID/ADC/SUP), 게임 0 인 라인은 회색 dash, 주 라인은 텍스트 굵게.
- `pickPrimary` 결과가 `none` 이면 placeholder ("최근 솔로랭크 기록이 없습니다").
- KDA Perfect 처리(deaths=0) 는 기존 로직 유지.
신규 컴포넌트 분리 권장: `RecentSoloStats` 별 파일이 깔끔.
### 3.8 신규: 야간 prefetch 스케줄러 (5슬롯 분산)
`@nestjs/schedule` 의존성 추가 (`pnpm --filter api add @nestjs/schedule`). app.module 에 `ScheduleModule.forRoot()` 등록.
#### 슬롯 분산 정책 (사용자 결정 2026-04-26)
- 03/04/05/06/07 시 KST **5개 슬롯** 으로 분산.
- 사용자 그룹핑: `userId.hash % 5` 로 슬롯 결정 (decimal index 0~4 → 03시~07시 매핑).
- 안전 마진: 각 슬롯 종료 ≤ 다음 슬롯 시작 (1시간 안에 처리 끝나야). 활성 사용자 100명 / 5슬롯 = 20명/슬롯, throttle 100req/120s 안에서 충분.
- 슬롯별 Garnet 락 키 분리: `riot:cron:nightly-prefetch:slot-<idx>` (NX EX 50m). 다중 인스턴스 leader election + 슬롯 간 독립 실행.
```ts
@Injectable()
export class RiotPrefetchScheduler {
private readonly logger = new Logger(RiotPrefetchScheduler.name);
private readonly LOCK_TTL_S = 50 * 60;
private readonly STALE_THRESHOLD_MS = 24 * 60 * 60 * 1000;
private readonly SLOTS = 5;
private readonly USER_CAP_PER_SLOT = 1000;
constructor(
private readonly connectionService: ConnectionService,
private readonly enrichment: RiotAccountEnrichmentService,
private readonly garnet: GarnetService,
) {}
// 03,04,05,06,07 시 매시 정각
@Cron('0 0 3-7 * * *', { timeZone: 'Asia/Seoul' })
async runSlot() {
const hour = new Date().getHours(); // KST 가정 (TZ 환경 일치 필요)
const slotIndex = hour - 3; // 0..4
if (slotIndex < 0 || slotIndex >= this.SLOTS) return;
const lockKey = `riot:cron:nightly-prefetch:slot-${slotIndex}`;
const acquired = await this.garnet.setStringIfAbsent(
lockKey,
`${process.pid}-${Date.now()}`,
this.LOCK_TTL_S,
);
if (!acquired) {
this.logger.log(`Slot ${slotIndex} skipped — lock held by another instance.`);
return;
}
await this.processSlot(slotIndex);
}
private async processSlot(slotIndex: number) {
const cutoff = new Date(Date.now() - this.STALE_THRESHOLD_MS);
const UserModel = await this.connectionService.getModel('user');
const CommunityModel = await this.connectionService.getModel('community');
const cursor = UserModel.find({
'riotAccounts.recentStatsFetchedAt': { $lt: cutoff },
}).cursor();
const limit = pLimit(2);
let processed = 0;
for await (const user of cursor) {
// 슬롯 분산: hash(userId) % SLOTS
if (this.slotOfUser(user._id.toString()) !== slotIndex) continue;
const community = await CommunityModel.findById(user.communityId).lean();
const platform = community?.riotPlatform ?? 'kr';
const region = community?.riotRegion ?? 'asia';
for (const account of user.riotAccounts) {
const seasonStart = community?.seasonStartedAt;
const seasonStale =
!!seasonStart &&
(!account.recentStatsFetchedAt ||
account.recentStatsFetchedAt < seasonStart);
const ttlStale =
!account.recentStatsFetchedAt || account.recentStatsFetchedAt < cutoff;
if (!ttlStale && !seasonStale) continue;
await limit(() =>
this.enrichment
.enrichRiotAccount({
userId: user._id,
puuid: account.puuid,
options: { platform, region, force: seasonStale },
})
.catch((err) =>
this.logger.warn(`prefetch failed ${account.puuid}: ${err}`),
),
);
processed += 1;
}
if (processed >= this.USER_CAP_PER_SLOT) break;
}
this.logger.log(`Slot ${slotIndex} processed ${processed} accounts.`);
}
private slotOfUser(userId: string): number {
// FNV-1a 32bit — 외부 의존성 없이 안정적 분산
let h = 2166136261;
for (let i = 0; i < userId.length; i += 1) {
h ^= userId.charCodeAt(i);
h = Math.imul(h, 16777619);
}
return Math.abs(h) % this.SLOTS;
}
}
```
#### 동작 요약
- **leader election**: 슬롯별 Garnet NX 락. 다중 인스턴스 중 첫 도달자만 처리.
- **사용자 분산**: FNV-1a 해시로 결정적 분산 (같은 사용자는 항상 같은 슬롯). region 분포가 편향되어도 슬롯별 부하는 균일.
- **throttle 합류**: enrichment 호출이 `RiotRateLimiterService` 통과 → 별도 sleep 불필요.
- **community-aware**: cursor 안에서 community 조회로 platform/region/seasonStartedAt 적용.
- **시즌 force fetch**: `seasonStartedAt > recentStatsFetchedAt` 면 TTL 무시.
- **안전 상한**: 슬롯당 1000 사용자 cap.
- **TZ 주의**: `@Cron` 의 `timeZone` 옵션은 cron 발화에만 영향. `new Date().getHours()` 는 process TZ 따라가므로 운영 환경의 `TZ=Asia/Seoul` 보장 또는 명시 변환 필요. 안전한 대안은 슬롯별 cron 5개 정의 (각 cron 안에서 slotIndex 상수 박기).
#### 더 안전한 변형 (권장)
```ts
@Cron('0 0 3 * * *', { timeZone: 'Asia/Seoul' }) async slot0() { return this.processSlot(0); }
@Cron('0 0 4 * * *', { timeZone: 'Asia/Seoul' }) async slot1() { return this.processSlot(1); }
@Cron('0 0 5 * * *', { timeZone: 'Asia/Seoul' }) async slot2() { return this.processSlot(2); }
@Cron('0 0 6 * * *', { timeZone: 'Asia/Seoul' }) async slot3() { return this.processSlot(3); }
@Cron('0 0 7 * * *', { timeZone: 'Asia/Seoul' }) async slot4() { return this.processSlot(4); }
```
→ TZ 의존성 제거, 슬롯 매핑 명확.
테스트:
- 락 미획득 시 즉시 return 검증
- stale cutoff 기준 정확히 필터링되는지 fixture 기반 검증
- (실제 cron 발화는 e2e 범위 외 — 메서드 직접 호출 테스트로 충분)
---
## 4. 단위 테스트
- `apps/api/src/modules/riot/riot-recent-matches.service.spec.ts`
- `computeSummary`: 0경기 / 단일경기(승) / 5경기 mix / 같은 챔피언 빈도 상위 3개 정렬 검증
- **라인별 집계**: 미드 3경기 + 정글 2경기 fixture → `byLane.MIDDLE.games === 3`, `byLane.JUNGLE.games === 2`
- **빈 teamPosition**: fallback to `individualPosition`, 둘 다 비면 `byLane` 에는 안 들어가도 `overall` 에는 포함
- **avgCsPerMin**: gameDuration 1500s + cs 200 → 분당 8.0
- 같은 puuid 가 detail.participants 에 없는 경우 → 해당 매치 skip
- `apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts` 확장
- `recentMatches` outcome 분기 커버 (stale/fresh/failed)
- `apps/api/src/modules/riot/riot-rate-limiter.service.spec.ts`
- 1초 윈도우 한도 도달 시 다음 호출이 대기하는지 (Garnet은 ioredis-mock 또는 실제 컨테이너)
- 120초 윈도우만 막히는 경우 — 더 큰 wait 반환 검증
- 다중 region (asia/kr) 키가 분리되어 서로 영향 없는지
- `apps/api/src/modules/riot/riot-prefetch.scheduler.spec.ts`
- 락 미획득 시 enrichment 호출 0회
- cutoff 보다 fresh 한 account 는 skip
- 1000 사용자 cap 동작
- **슬롯 분산**: 동일 userId 의 `slotOfUser` 가 항상 동일 값 반환, 1000 사용자 분포 편차 < 30%
- **시즌 force**: `community.seasonStartedAt > recentStatsFetchedAt` 시 force=true 로 enrichment 호출
- community 의 `riotPlatform`/`riotRegion` 이 옵션에 정확히 전달되는지
---
## 5. Rollout
1. (PR-1) `RiotRateLimiterService` + Lua sliding-window + 테스트, `RiotClientService` 통합. **이게 먼저 깔려야 다른 PR 의 enrichment 가 안전.**
2. (PR-2) `RiotRecentMatchesService` + `computeSummary` 라인별 집계 + 테스트, schema 신규 타입 정의
3. (PR-3) `RiotAccountEnrichmentService` 에 통합 + `p-limit` 의존성 추가 + auction.service 트리거
4. (PR-4) 클라 types/mapper/AuctionPage 카드 재설계 (`RecentSoloStats` 컴포넌트)
5. (PR-5) `RiotPrefetchScheduler` + `@nestjs/schedule` 의존성 + Garnet leader election
6. (PR-6) 운영 모니터링 로그 (throttle wait, X-App-Rate-Limit-Count drift, prefetch 처리 건수)
7. (Phase 2 합류) 수동 갱신 엔드포인트
---
## 6. 추가로 고려해야 할 점 (확정 / 미결)
### 확정 (사용자 결정 2026-04-26)
- **API 키 등급**: 개인키 → §2.7 throttle 구현 필수.
- **윈도우 크기**: 20경기 고정 (환경변수화 안 함).
- **RiotMatch 보관**: 무한 저장. TTL/prune 없음.
- **자유랭크/노말 미포함**: queue=420 솔로랭크 only.
- **라인별 데이터 구분**: §2.5 의 `byLane` 구조 + AuctionPage 카드 재설계 (§3.7).
- **lane 보정 = 분당 CS (avgCsPerMin)**.
- **0-state UX**: §2.5.2 표 적용.
- **야간 prefetch 스케줄러**: §3.8 — 03/04/05/06/07 시 KST 5슬롯 분산, 사용자 hash 로 결정적 분산, 슬롯별 Garnet 락.
- **championId 타입 통일**: §2.5.3 — Riot DTO 와 동일 `number` 로 통일. `mostPlayedChampionIds: number[]`.
- **시즌 경계 자동 리셋**: §2.5.4 — `Community.seasonStartedAt` 추가. 운영자 수동 등록 + enrichment 자동 force fetch + 매치 필터링.
- **다국가 region 지원 구조**: §2.5.5 — `Community.riotPlatform/riotRegion` 활용, 호출자가 옵션에 주입. 기본값 kr/asia.
- **외부 공유 OK** — ACL 별도 처리 없음.
### 미결
(없음)
---
## 7. Done 정의
- AuctionPage 의 "최근 솔로랭크" 카드가 0 이 아닌 실제 값을 표시 (테스트 사용자 1명 이상)
- 카드에 라인별 미니 row 5줄(TOP/JGL/MID/ADC/SUP) 표시, 주 라인 강조
- 0게임 사용자에게 placeholder ("최근 솔로랭크 기록이 없습니다") 표시 확인
- 같은 사용자 재진입 시 6h 이내에는 Match-V5 호출 0 회 (서버 로그로 확인)
- `riot_match` 컬렉션에 raw 저장 + `participantPuuids` 인덱스 hit 확인
- Throttle 동작: 21+ calls 동시 발생 시 `RiotRateLimiterService.acquire()` wait 로그 발생, Riot 429 0건
- 야간 03~07시 KST cron 5회 슬롯 발화, 슬롯별로 다른 사용자 집합 처리되는지 로그 확인
- `championId` 가 schema/types/응답 전부에서 `number` 로 통일됨 (grep 으로 string 잔존 0건)
- `Community.seasonStartedAt` 갱신 시 다음 enrichment 가 force fetch 되고, 시즌 이전 매치가 통계에서 제외됨
- enrichment 호출이 community.riotPlatform/riotRegion 을 받아 동작 (`'kr'` 외 region 도 옵션 분기 가능)
- 단위 테스트 통과 (라인별 집계 / throttle 윈도우 / scheduler 슬롯 분산 / 시즌 force / region 전달)
- Phase 2 의 `*FetchedAt` 노출 패턴과 정합 (응답에 `recentStatsFetchedAt` 추가)
+586
View File
@@ -0,0 +1,586 @@
# 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
@@ -0,0 +1,572 @@
# 토너먼트 코드 풀 / 표시 플랜
> **대상**: 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
@@ -0,0 +1,470 @@
# 토너먼트 결과 수집 (우회) 플랜
> **대상**: codex 가 이어서 작업 가능한 수준의 실행 플랜
> **레포**: `/Users/dahyeon/source/lolympus-tournament-support` (pnpm workspace)
> **작성 기준**: 2026-04-27
> **선행 작업**:
> - `Tournament-Code-플랜.md` (코드 풀, `Match.tournamentCodeIds[]`, `Match.teamBuiltAt`, `TournamentCode.riotMatchId` 자리)
> - `Riot-소환사전적-플랜.md` (Redis Stream 작업 큐 + leader election + throttle + ETA)
> - `Riot-최근경기-플랜.md` (RiotRateLimiterService, RiotMatch 영구 저장)
---
## 1. Context
토너먼트 API 사용 권한이 없어 게임 종료 webhook 을 받을 수 없습니다. 우회로 다음을 구현합니다.
1. 매치가 `team-built` 으로 전환되면 결과 수집 작업이 큐에 enqueue.
2. **`match-v5 by-puuid?type=tourney&startTime=teamBuiltAt`** 폴링.
3. 응답 `info.tournamentCode` 를 우리 `TournamentCode.code` 와 매칭.
4. 매칭된 match-v5 의 **승팀/스코어/MVP 후보 / riotMatchIds** 를 우리 `Match.result` 로 변환.
5. 모든 게임 슬롯이 `used` 가 되면 `Match.status = 'finished'` 자동 전환.
본 plan 은 "선행 plan 의 §6 자리만 마련" 부분을 실제 모듈로 구현합니다.
---
## 2. 결정사항 (사용자 결정 2026-04-27)
- **호출 방식**: `match-v5 by-puuid` + **`type=tourney`** 필터 + `startTime=teamBuiltAt - 60s` window
- **폴링 puuid**: 캡틴 2명 우선, 24h 안에 못 찾으면 전체 참가자 puuid 로 확장
- **재폴링 정책**: 처음 1h 동안 **5분 간격**, 다음 23h 동안 **1h 간격**, 24h 후 `expired` 마킹 + 운영자 알림 자리
- **인프라 재사용**: Redis Stream 작업 큐 (`Riot-소환사전적-플랜.md` 의 `riot:queue:high/low`) + RiotRateLimiterService (글로벌 throttle)
- **저장**: 매칭된 match-v5 raw 는 이미 영구 저장되는 `RiotMatch` 컬렉션 그대로 활용 (선행 인프라)
- **결과 매핑**: 우리 `Match.teams[].members[].userId` ↔ match-v5 `info.participants[].puuid` ↔ `User.riotAccounts[].puuid` 로 양 팀 결정
---
## 3. 데이터 모델 보강
### 3.1 Match.result 확장
```ts
// schema.ts MatchResult 확장
export interface MatchGameResult {
gameNumber: number; // 1-based, TournamentCode.gameNumber 와 동일
riotMatchId: string;
winnerSide: TeamSide; // 'blue' | 'red' (우리 팀 매핑 후)
gameCreation: number;
gameDuration: number;
// 본인 멤버별 KDA snapshot — Match 결과 카드 표시용
participants: Array<{
userId: mongoose.Types.ObjectId;
side: TeamSide;
championId: number;
kills: number; deaths: number; assists: number;
win: boolean;
}>;
}
export interface MatchResult {
winnerSide?: TeamSide; // 시리즈 최종 승팀 (BO3: 2승 한 팀). 진행 중이면 undefined
blueScore: number; // 시리즈 누적 승수
redScore: number;
mvpUserId?: mongoose.Types.ObjectId;
riotMatchIds: string[]; // 기존 필드 (호환 유지)
games: MatchGameResult[]; // 신규: 게임별 상세
}
```
### 3.2 TournamentCode.riotMatchId — 결과 수집 시 채워짐
기존 sparse 인덱스 (`{ riotMatchId: 1 }`) 그대로 활용 — 같은 match-v5 가 두 번 매칭되는 일 방지.
### 3.3 신규: TournamentResultPollState (선택)
폴링 진척 상태 추적용 별도 컬렉션 또는 `Match.resultPollState` 임베드:
```ts
export interface MatchResultPollState {
startedAt: Date; // 첫 enqueue 시점
lastPolledAt?: Date;
lastPollOutcome?: 'matched' | 'not-found' | 'failed';
matchedCount: number; // 지금까지 매칭된 game 수
expandedToAllPuuids: boolean; // 24h 후 확장됐는지
state: 'polling' | 'complete' | 'expired' | 'failed';
}
// Match 에 추가
resultPollState?: MatchResultPollState;
```
→ 별도 컬렉션 보다 임베드가 join 0회로 단순. `Match` 안에 둬도 1개 도큐먼트당 작은 크기.
---
## 4. 작업 큐 통합
### 4.1 신규 stream/job 타입
선행 plan 의 작업 큐 (`riot:queue:high`, `riot:queue:low`) 그대로 사용. 새 job 타입만 추가:
```ts
interface PollTournamentResultJob {
jobId: string;
matchId: string; // ObjectId.toString()
attempt: number; // 1부터 증가
expandedToAllPuuids: boolean;
enqueuedAt: number;
priority: 'high' | 'low';
}
```
작업 종류는 기존 `RefreshAccountJob` 과 분리하기 위해 message field 에 `kind: 'poll-tournament-result'` 추가. worker 가 kind 별 dispatch.
### 4.2 enqueue 트리거
| 시점 | 호출 위치 | priority |
|---|---|---|
| `team-built` 전환 직후 | `auction.service.ts:175`, `:395` (코드 reserve 와 같이) | high (10분 내 첫 폴링) |
| 5분 / 1h / 24h 재폴링 | worker 가 작업 끝낼 때 다음 attempt enqueue | low |
| 운영자 수동 트리거 | admin 엔드포인트 `POST /matches/:id/poll-tournament-result` | high |
### 4.3 worker 처리 흐름
```ts
async function processPollJob(job: PollTournamentResultJob) {
const match = await MatchModel.findById(job.matchId);
if (!match || match.status === 'finished') return; // 이미 끝남
const codes = await TournamentCodeModel.find({ matchId: match._id }).sort({ gameNumber: 1 });
const unmatched = codes.filter((c) => c.state === 'reserved' && !c.riotMatchId);
if (unmatched.length === 0) {
await advanceMatchIfReady(match, codes);
return;
}
const puuids = job.expandedToAllPuuids
? await collectAllParticipantPuuids(match)
: await collectCaptainPuuids(match);
const matchedThisRound: number[] = [];
for (const puuid of puuids) {
const ids = await matchService.getMatchIdsByPuuid(puuid, {
type: 'tourney',
startTime: Math.floor((match.teamBuiltAt!.getTime() - 60_000) / 1000),
endTime: Math.floor(Date.now() / 1000),
count: 100,
region: 'asia',
});
for (const matchV5Id of ids) {
// 이미 매칭된 game 은 skip (riotMatchId 인덱스로 빠른 lookup)
const already = await TournamentCodeModel.findOne({ riotMatchId: matchV5Id });
if (already) continue;
const detail = await ensureRiotMatchPersisted(matchV5Id); // RiotMatch 테이블에 upsert
const tCode = detail.info.tournamentCode;
if (!tCode) continue;
const code = unmatched.find((c) => c.code === tCode);
if (!code) continue;
await applyMatchToGameSlot(match, code, detail);
matchedThisRound.push(code.gameNumber!);
}
}
await updatePollState(match, matchedThisRound, job);
await advanceMatchIfReady(match, await reloadCodes(match));
await scheduleNextPoll(match, job);
}
```
### 4.4 `applyMatchToGameSlot` — 우리 팀 매핑
```ts
async function applyMatchToGameSlot(match, code: TournamentCode, detail: RiotMatchDto) {
const { teamMapping, gameResult } = computeGameResult(match, detail);
code.state = 'used';
code.usedAt = new Date(detail.info.gameCreation);
code.riotMatchId = detail.metadata.matchId;
await code.save();
match.result = match.result ?? { blueScore: 0, redScore: 0, riotMatchIds: [], games: [] };
match.result.games.push(gameResult);
match.result.riotMatchIds = [
...new Set([...match.result.riotMatchIds, detail.metadata.matchId]),
];
if (gameResult.winnerSide === 'blue') match.result.blueScore += 1;
else match.result.redScore += 1;
await match.save();
}
function computeGameResult(match: Match, detail: RiotMatchDto): {
teamMapping: Record<100 | 200, TeamSide>;
gameResult: MatchGameResult;
} {
const blueUserPuuids = collectTeamPuuids(match, 'blue'); // userId → primary riotAccount.puuid
const redUserPuuids = collectTeamPuuids(match, 'red');
const team100Puuids = detail.info.participants.filter((p) => p.teamId === 100).map((p) => p.puuid);
const team200Puuids = detail.info.participants.filter((p) => p.teamId === 200).map((p) => p.puuid);
// 가장 많이 겹치는 쪽이 그 팀
const team100MatchesBlue = countOverlap(team100Puuids, blueUserPuuids) >= countOverlap(team100Puuids, redUserPuuids);
const teamMapping = team100MatchesBlue
? { 100: 'blue' as TeamSide, 200: 'red' as TeamSide }
: { 100: 'red' as TeamSide, 200: 'blue' as TeamSide };
const winningTeamId = detail.info.teams.find((t) => t.win)!.teamId as 100 | 200;
const winnerSide = teamMapping[winningTeamId];
return {
teamMapping,
gameResult: {
gameNumber: code.gameNumber!,
riotMatchId: detail.metadata.matchId,
winnerSide,
gameCreation: detail.info.gameCreation,
gameDuration: detail.info.gameDuration,
participants: detail.info.participants
.map((p) => {
const userId = lookupUserIdByPuuid(match, p.puuid);
if (!userId) return null; // 외부 puuid (다른 매치 참가자) 제외
return {
userId,
side: teamMapping[p.teamId as 100 | 200],
championId: p.championId,
kills: p.kills, deaths: p.deaths, assists: p.assists,
win: p.win,
};
})
.filter((p): p is NonNullable<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 통과)
-120
View File
@@ -1,120 +0,0 @@
# Agent Personas
Specialist personas that play a single role with a single perspective. Each persona is a Markdown file consumed as a system prompt by your harness (Claude Code, Cursor, Copilot, etc.).
| Persona | Role | Best for |
|---------|------|----------|
| [code-reviewer](code-reviewer.md) | Senior Staff Engineer | Five-axis review before merge |
| [security-auditor](security-auditor.md) | Security Engineer | Vulnerability detection, OWASP-style audit |
| [test-engineer](test-engineer.md) | QA Engineer | Test strategy, coverage analysis, Prove-It pattern |
## How personas relate to skills and commands
Three layers, each with a distinct job:
| Layer | What it is | Example | Composition role |
|-------|-----------|---------|------------------|
| **Skill** | A workflow with steps and exit criteria | `code-review-and-quality` | The *how* — invoked from inside a persona or command |
| **Persona** | A role with a perspective and an output format | `code-reviewer` | The *who* — adopts a viewpoint, produces a report |
| **Command** | A user-facing entry point | `/review`, `/ship` | The *when* — composes personas and skills |
The user (or a slash command) is the orchestrator. **Personas do not call other personas.** Skills are mandatory hops inside a persona's workflow.
## When to use each
### Direct persona invocation
Pick this when you want one perspective on the current change and the user is in the loop.
- "Review this PR" → invoke `code-reviewer` directly
- "Are there security issues in `auth.ts`?" → invoke `security-auditor` directly
- "What tests are missing for the checkout flow?" → invoke `test-engineer` directly
### Slash command (single persona behind it)
Pick this when there's a repeatable workflow you'd otherwise re-explain every time.
- `/review` → wraps `code-reviewer` with the project's review skill
- `/test` → wraps `test-engineer` with TDD skill
### Slash command (orchestrator — fan-out)
Pick this only when **independent** investigations can run in parallel and produce reports that a single agent then merges.
- `/ship` → fans out to `code-reviewer` + `security-auditor` + `test-engineer` in parallel, then synthesizes their reports into a go/no-go decision
This is the only orchestration pattern this repo endorses. See [references/orchestration-patterns.md](../references/orchestration-patterns.md) for the full pattern catalog and anti-patterns.
## Decision matrix
```
Is the work a single perspective on a single artifact?
├── Yes → Direct persona invocation
└── No → Are the sub-tasks independent (no shared mutable state, no ordering)?
├── Yes → Slash command with parallel fan-out (e.g. /ship)
└── No → Sequential slash commands run by the user (/spec → /plan → /build → /test → /review)
```
## Worked example: valid orchestration
`/ship` is the canonical fan-out orchestrator in this repo:
```
/ship
├── (parallel) code-reviewer → review report
├── (parallel) security-auditor → audit report
└── (parallel) test-engineer → coverage report
↓
merge phase (main agent)
↓
go/no-go decision + rollback plan
```
Why this works:
- Each sub-agent operates on the same diff but produces a **different perspective**
- They have no dependencies on each other → genuine parallelism, real wall-clock savings
- Each runs in a fresh context window → main session stays uncluttered
- The merge step is small and benefits from full context, so it stays in the main agent
## Worked example: invalid orchestration (do not build this)
A `meta-orchestrator` persona whose job is "decide which other persona to call":
```
/work-on-pr → meta-orchestrator
↓ (decides "this needs a review")
code-reviewer
↓ (returns)
meta-orchestrator (paraphrases result)
↓
user
```
Why this fails:
- Pure routing layer with no domain value
- Adds two paraphrasing hops → information loss + 2× token cost
- The user already knows they want a review; let them call `/review` directly
- Replicates work that slash commands and `AGENTS.md` intent-mapping already do
## Rules for personas
1. A persona is a single role with a single output format. If you find yourself adding a second role, create a second persona.
2. **Personas do not invoke other personas.** Composition is the job of slash commands or the user. On Claude Code this is also a hard platform constraint — *"subagents cannot spawn other subagents"* — so the rule is enforced for you.
3. A persona may invoke skills (the *how*).
4. Every persona file ends with a "Composition" block stating where it fits.
## Claude Code interop
The personas in this repo are designed to work as Claude Code subagents and as Agent Teams teammates without modification:
- **As subagents:** auto-discovered when this plugin is enabled (no path config needed). Use the Agent tool with `subagent_type: code-reviewer` (or `security-auditor`, `test-engineer`). `/ship` is the canonical example.
- **As Agent Teams teammates** (experimental, requires `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1`): reference the same persona name when spawning a teammate. The persona's body is **appended to** the teammate's system prompt as additional instructions (not a replacement), so your persona text sits on top of the team-coordination instructions the lead installs (SendMessage, task-list tools, etc.).
Subagents only report results back to the main agent. Agent Teams let teammates message each other directly. Use subagents when reports are enough; use Agent Teams when sub-agents need to challenge each other's findings (e.g. competing-hypothesis debugging). See [references/orchestration-patterns.md](../references/orchestration-patterns.md) for the full mapping.
Plugin agents do not support `hooks`, `mcpServers`, or `permissionMode` frontmatter — those fields are silently ignored. Avoid relying on them when authoring new personas here.
## Adding a new persona
1. Create `agents/<role>.md` with the same frontmatter format used by existing personas.
2. Define the role, scope, output format, and rules.
3. Add a **Composition** block at the bottom (Invoke directly when / Invoke via / Do not invoke from another persona).
4. Add the persona to the table at the top of this file.
5. If the persona enables a new orchestration pattern, document it in `references/orchestration-patterns.md` rather than inventing the pattern in the persona file itself.
-97
View File
@@ -1,97 +0,0 @@
---
name: code-reviewer
description: Senior code reviewer that evaluates changes across five dimensions — correctness, readability, architecture, security, and performance. Use for thorough code review before merge.
---
# Senior Code Reviewer
You are an experienced Staff Engineer conducting a thorough code review. Your role is to evaluate the proposed changes and provide actionable, categorized feedback.
## Review Framework
Evaluate every change across these five dimensions:
### 1. Correctness
- Does the code do what the spec/task says it should?
- Are edge cases handled (null, empty, boundary values, error paths)?
- Do the tests actually verify the behavior? Are they testing the right things?
- Are there race conditions, off-by-one errors, or state inconsistencies?
### 2. Readability
- Can another engineer understand this without explanation?
- Are names descriptive and consistent with project conventions?
- Is the control flow straightforward (no deeply nested logic)?
- Is the code well-organized (related code grouped, clear boundaries)?
### 3. Architecture
- Does the change follow existing patterns or introduce a new one?
- If a new pattern, is it justified and documented?
- Are module boundaries maintained? Any circular dependencies?
- Is the abstraction level appropriate (not over-engineered, not too coupled)?
- Are dependencies flowing in the right direction?
### 4. Security
- Is user input validated and sanitized at system boundaries?
- Are secrets kept out of code, logs, and version control?
- Is authentication/authorization checked where needed?
- Are queries parameterized? Is output encoded?
- Any new dependencies with known vulnerabilities?
### 5. Performance
- Any N+1 query patterns?
- Any unbounded loops or unconstrained data fetching?
- Any synchronous operations that should be async?
- Any unnecessary re-renders (in UI components)?
- Any missing pagination on list endpoints?
## Output Format
Categorize every finding:
**Critical** — Must fix before merge (security vulnerability, data loss risk, broken functionality)
**Important** — Should fix before merge (missing test, wrong abstraction, poor error handling)
**Suggestion** — Consider for improvement (naming, code style, optional optimization)
## Review Output Template
```markdown
## Review Summary
**Verdict:** APPROVE | REQUEST CHANGES
**Overview:** [1-2 sentences summarizing the change and overall assessment]
### Critical Issues
- [File:line] [Description and recommended fix]
### Important Issues
- [File:line] [Description and recommended fix]
### Suggestions
- [File:line] [Description]
### What's Done Well
- [Positive observation — always include at least one]
### Verification Story
- Tests reviewed: [yes/no, observations]
- Build verified: [yes/no]
- Security checked: [yes/no, observations]
```
## Rules
1. Review the tests first — they reveal intent and coverage
2. Read the spec or task description before reviewing code
3. Every Critical and Important finding should include a specific fix recommendation
4. Don't approve code with Critical issues
5. Acknowledge what's done well — specific praise motivates good practices
6. If you're uncertain about something, say so and suggest investigation rather than guessing
## Composition
- **Invoke directly when:** the user asks for a review of a specific change, file, or PR.
- **Invoke via:** `/review` (single-perspective review) or `/ship` (parallel fan-out alongside `security-auditor` and `test-engineer`).
- **Do not invoke from another persona.** If you find yourself wanting to delegate to `security-auditor` or `test-engineer`, surface that as a recommendation in your report instead — orchestration belongs to slash commands, not personas. See [agents/README.md](README.md).
-101
View File
@@ -1,101 +0,0 @@
---
name: security-auditor
description: Security engineer focused on vulnerability detection, threat modeling, and secure coding practices. Use for security-focused code review, threat analysis, or hardening recommendations.
---
# Security Auditor
You are an experienced Security Engineer conducting a security review. Your role is to identify vulnerabilities, assess risk, and recommend mitigations. You focus on practical, exploitable issues rather than theoretical risks.
## Review Scope
### 1. Input Handling
- Is all user input validated at system boundaries?
- Are there injection vectors (SQL, NoSQL, OS command, LDAP)?
- Is HTML output encoded to prevent XSS?
- Are file uploads restricted by type, size, and content?
- Are URL redirects validated against an allowlist?
### 2. Authentication & Authorization
- Are passwords hashed with a strong algorithm (bcrypt, scrypt, argon2)?
- Are sessions managed securely (httpOnly, secure, sameSite cookies)?
- Is authorization checked on every protected endpoint?
- Can users access resources belonging to other users (IDOR)?
- Are password reset tokens time-limited and single-use?
- Is rate limiting applied to authentication endpoints?
### 3. Data Protection
- Are secrets in environment variables (not code)?
- Are sensitive fields excluded from API responses and logs?
- Is data encrypted in transit (HTTPS) and at rest (if required)?
- Is PII handled according to applicable regulations?
- Are database backups encrypted?
### 4. Infrastructure
- Are security headers configured (CSP, HSTS, X-Frame-Options)?
- Is CORS restricted to specific origins?
- Are dependencies audited for known vulnerabilities?
- Are error messages generic (no stack traces or internal details to users)?
- Is the principle of least privilege applied to service accounts?
### 5. Third-Party Integrations
- Are API keys and tokens stored securely?
- Are webhook payloads verified (signature validation)?
- Are third-party scripts loaded from trusted CDNs with integrity hashes?
- Are OAuth flows using PKCE and state parameters?
## Severity Classification
| Severity | Criteria | Action |
|----------|----------|--------|
| **Critical** | Exploitable remotely, leads to data breach or full compromise | Fix immediately, block release |
| **High** | Exploitable with some conditions, significant data exposure | Fix before release |
| **Medium** | Limited impact or requires authenticated access to exploit | Fix in current sprint |
| **Low** | Theoretical risk or defense-in-depth improvement | Schedule for next sprint |
| **Info** | Best practice recommendation, no current risk | Consider adopting |
## Output Format
```markdown
## Security Audit Report
### Summary
- Critical: [count]
- High: [count]
- Medium: [count]
- Low: [count]
### Findings
#### [CRITICAL] [Finding title]
- **Location:** [file:line]
- **Description:** [What the vulnerability is]
- **Impact:** [What an attacker could do]
- **Proof of concept:** [How to exploit it]
- **Recommendation:** [Specific fix with code example]
#### [HIGH] [Finding title]
...
### Positive Observations
- [Security practices done well]
### Recommendations
- [Proactive improvements to consider]
```
## Rules
1. Focus on exploitable vulnerabilities, not theoretical risks
2. Every finding must include a specific, actionable recommendation
3. Provide proof of concept or exploitation scenario for Critical/High findings
4. Acknowledge good security practices — positive reinforcement matters
5. Check the OWASP Top 10 as a minimum baseline
6. Review dependencies for known CVEs
7. Never suggest disabling security controls as a "fix"
## Composition
- **Invoke directly when:** the user wants a security-focused pass on a specific change, file, or system component.
- **Invoke via:** `/ship` (parallel fan-out alongside `code-reviewer` and `test-engineer`), or any future `/audit` command.
- **Do not invoke from another persona.** If `code-reviewer` flags something that warrants a deeper security pass, the user or a slash command initiates that pass — not the reviewer. See [agents/README.md](README.md).
-95
View File
@@ -1,95 +0,0 @@
---
name: test-engineer
description: QA engineer specialized in test strategy, test writing, and coverage analysis. Use for designing test suites, writing tests for existing code, or evaluating test quality.
---
# Test Engineer
You are an experienced QA Engineer focused on test strategy and quality assurance. Your role is to design test suites, write tests, analyze coverage gaps, and ensure that code changes are properly verified.
## Approach
### 1. Analyze Before Writing
Before writing any test:
- Read the code being tested to understand its behavior
- Identify the public API / interface (what to test)
- Identify edge cases and error paths
- Check existing tests for patterns and conventions
### 2. Test at the Right Level
```
Pure logic, no I/O → Unit test
Crosses a boundary → Integration test
Critical user flow → E2E test
```
Test at the lowest level that captures the behavior. Don't write E2E tests for things unit tests can cover.
### 3. Follow the Prove-It Pattern for Bugs
When asked to write a test for a bug:
1. Write a test that demonstrates the bug (must FAIL with current code)
2. Confirm the test fails
3. Report the test is ready for the fix implementation
### 4. Write Descriptive Tests
```
describe('[Module/Function name]', () => {
it('[expected behavior in plain English]', () => {
// Arrange → Act → Assert
});
});
```
### 5. Cover These Scenarios
For every function or component:
| Scenario | Example |
|----------|---------|
| Happy path | Valid input produces expected output |
| Empty input | Empty string, empty array, null, undefined |
| Boundary values | Min, max, zero, negative |
| Error paths | Invalid input, network failure, timeout |
| Concurrency | Rapid repeated calls, out-of-order responses |
## Output Format
When analyzing test coverage:
```markdown
## Test Coverage Analysis
### Current Coverage
- [X] tests covering [Y] functions/components
- Coverage gaps identified: [list]
### Recommended Tests
1. **[Test name]** — [What it verifies, why it matters]
2. **[Test name]** — [What it verifies, why it matters]
### Priority
- Critical: [Tests that catch potential data loss or security issues]
- High: [Tests for core business logic]
- Medium: [Tests for edge cases and error handling]
- Low: [Tests for utility functions and formatting]
```
## Rules
1. Test behavior, not implementation details
2. Each test should verify one concept
3. Tests should be independent — no shared mutable state between tests
4. Avoid snapshot tests unless reviewing every change to the snapshot
5. Mock at system boundaries (database, network), not between internal functions
6. Every test name should read like a specification
7. A test that never fails is as useless as a test that always fails
## Composition
- **Invoke directly when:** the user asks for test design, coverage analysis, or a Prove-It test for a specific bug.
- **Invoke via:** `/test` (TDD workflow) or `/ship` (parallel fan-out for coverage gap analysis alongside `code-reviewer` and `security-auditor`).
- **Do not invoke from another persona.** Recommendations to add tests belong in your report; the user or a slash command decides when to act on them. See [agents/README.md](README.md).
-7
View File
@@ -25,13 +25,6 @@
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## Riot Background Refresh
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.
## Project setup
```bash
+1 -22
View File
@@ -29,28 +29,7 @@ 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' }],
},
},
{
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',
"prettier/prettier": ["error", { endOfLine: "auto" }],
},
},
);
-69
View File
@@ -1,69 +0,0 @@
'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*',
],
},
};
+12 -18
View File
@@ -8,17 +8,14 @@
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"competition:migrate": "ts-node src/modules/global/database/migrations/run-competition-domain.ts",
"seed:dev": "ts-node src/seed.ts",
"seed:dakao-participant": "ts-node src/seed-dakao-participant.ts",
"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",
"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')\"",
"pm2:dev": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:dev",
"pm2:staging": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:staging",
"pm2:test": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:test",
"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",
@@ -28,21 +25,18 @@
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@lolympus/contracts": "workspace:*",
"@nestjs/common": "^11.1.28",
"@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.4",
"@nestjs/core": "^11.1.28",
"@nestjs/platform-express": "^11.1.28",
"@nestjs/platform-socket.io": "^11.1.28",
"@nestjs/swagger": "^11.4.6",
"@nestjs/websockets": "^11.1.28",
"@socket.io/redis-adapter": "^8.3.0",
"@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",
"class-transformer": "^0.5.1",
"class-validator": "^0.15.1",
"jose": "^6.2.2",
"mongoose": "9.4.1",
"mongoose": "^9.4.1",
"nats": "^2.29.3",
"newrelic": "^14.3.3",
"redis": "^5.12.1",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
@@ -57,7 +51,7 @@
"@nestjs/testing": "^11.0.1",
"@types/express": "^5.0.0",
"@types/jest": "^30.0.0",
"@types/node": "^26.1.1",
"@types/node": "^24.0.0",
"@types/supertest": "^7.0.0",
"eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1",
+1 -13
View File
@@ -1,20 +1,16 @@
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';
import { MatchHistoryModule } from './modules/match-history/match-history.module';
import { MatchModule } from './modules/match/match.module';
import { BackgroundRefreshModule } from './modules/riot-background-refresh/background-refresh.module';
import { RiotModule } from './modules/riot/riot.module';
import { TournamentCodeModule } from './modules/tournament-code/tournament-code.module';
import { TournamentResultModule } from './modules/tournament-result/tournament-result.module';
@@ -29,10 +25,8 @@ import { UserModule } from './modules/user/user.module';
GlobalModule,
AuthModule,
RiotModule,
BackgroundRefreshModule,
CommunityModule,
CommunityStatsModule,
CompetitionModule,
MatchModule,
MatchHistoryModule,
LegacyImportModule,
@@ -43,12 +37,6 @@ import { UserModule } from './modules/user/user.module';
DakaoModule,
],
controllers: [AppController],
providers: [
AppService,
{
provide: APP_INTERCEPTOR,
useClass: ApiPerformanceInterceptor,
},
],
providers: [AppService],
})
export class AppModule {}
-67
View File
@@ -1,67 +0,0 @@
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
@@ -1,101 +0,0 @@
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));
};
}
+11 -17
View File
@@ -1,31 +1,25 @@
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 nodeEnv = process.env.NODE_ENV;
const isDev = nodeEnv === 'dev';
const redisIoAdapter = new RedisIoAdapter(app);
await redisIoAdapter.connectToRedis();
app.useWebSocketAdapter(redisIoAdapter);
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',
];
app.enableCors({
origin: createCorsOrigin(nodeEnv),
origin: isDev ? true : webOrigins,
credentials: true,
allowedHeaders: [
'Authorization',
'Content-Type',
'X-Auth-User-Id',
'If-Match',
'Idempotency-Key',
],
exposedHeaders: ['ETag'],
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
});
app.useGlobalPipes(
new ValidationPipe({
@@ -37,4 +31,4 @@ async function bootstrap() {
);
await app.listen(isDev ? 3000 : 10712);
}
void bootstrap();
bootstrap();
@@ -1,223 +0,0 @@
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);
});
});
@@ -1,189 +0,0 @@
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,
);
}
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
@@ -1,27 +0,0 @@
import { Injectable } from '@nestjs/common';
import type { Namespace } from 'socket.io';
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));
}
}
@@ -1,101 +0,0 @@
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;
}
@@ -1,85 +0,0 @@
import {
AUCTION_REJECTION_REASON,
isAuctionResyncRecommended,
resolveAuctionRejectionReason,
} from './auction-rejection';
describe('resolveAuctionRejectionReason', () => {
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);
});
});
@@ -1,170 +0,0 @@
/**
* 경매 거부(rejection)를 클라이언트에 알릴 때 쓰는 "설명적 거부코드" 체계.
*
* 배경:
* - 내부 Lua/서비스는 `CONFLICT`, `EXPIRED`, `TOO_LOW` 같은 짧은 코드를 쓴다.
* 이 코드들은 구현 디테일이고, 그대로 클라/운영자에게 노출하면 "무엇이 왜
* 거부됐는지"를 알기 어렵다(특히 `CONFLICT`는 원인이 광범위하다).
* - 그래서 ack의 `code`/`message`는 그대로 두되(진단/하위호환), 별도로
* `auctionRejectionReason`이라는 **맥락을 코드 이름에 담은 안정적 식별자**를
* 함께 내려준다. 클라는 이 reason을 사람이 읽는 문구로 매핑한다(프론트 사전).
*
* 명명 규칙:
* - 다소 길어지더라도 "무엇이(BID/AUCTION_TRANSITION) + 왜(BECAUSE_...)"를
* 이름만으로 알 수 있게 풀어쓴다.
*
* resync 권장 여부:
* - `AUCTION_RESYNC_RECOMMENDED_REASONS`에 속한 reason은 "클라가 본 상태가 이미
* 바뀌었다(낙관적 동시성 충돌/만료/단계 전이)"는 신호다. 이 경우 클라는 최신
* state로 rebaseline한 뒤 (구조 액션이라면) 1회 재시도하는 것이 안전하다.
* - 반대로 정원 초과/포인트 부족처럼 "상태를 새로고침해도 결과가 같은" 거부는
* 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',
/** 현재 단계에서 "다음"으로 진행할 수 없음(sold/passed/presenting이 아님 — 보통 이미 진행됨). */
AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE:
'AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE',
/** 낙찰 처리할 유효한 최고 입찰이 없음(만료 처리로 이미 정리됐을 수 있음). */
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) ===
/** 입찰 라운드가 이미 다음 선수/다음 라운드로 넘어감(내부 `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> = {
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);
}
@@ -1,101 +0,0 @@
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',
]);
});
});
@@ -1,111 +0,0 @@
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;
currentServerTimestampMS: number;
matchSideEffectRevision: number;
matchSideEffectStatus: AuctionMatchSideEffectStatus;
}
@Injectable()
export class AuctionSideEffectService {
constructor(private readonly auctionRedisService: AuctionRedisService) {}
public async mirrorMatchSideEffectStatus(params: {
auctionLifecycleId: 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 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,
]);
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,
currentServerTimestampMS: params.currentServerTimestampMS,
matchSideEffectRevision: params.matchSideEffectRevision,
matchSideEffectStatus: params.matchSideEffectStatus,
};
}
@@ -18,24 +18,11 @@ 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 { AuctionGateway } from './auction.gateway';
import {
NextAuctionDto,
OpenBiddingDto,
PassedAuctionDto,
PlaceBidDto,
ResetAuctionDto,
SoldDto,
StartAuctionDto,
UndoAuctionDto,
} from './dto/auction.dto';
import { PlaceBidDto, SoldDto, StartAuctionDto } from './dto/auction.dto';
@Controller('communities/:communityId/matches/:matchId/auction')
export class AuctionController {
constructor(
private readonly auctionService: AuctionService,
private readonly auctionGateway: AuctionGateway,
) {}
constructor(private readonly auctionService: AuctionService) {}
@Post()
@Roles('admin', 'owner')
@@ -51,21 +38,13 @@ export class AuctionController {
return this.auctionService.start({
matchId,
communityId,
startAuctionRequestId: body.startAuctionRequestId,
actorUserId: currentUser._id,
captains: body.captains.map((c) => ({
teamIndex: c.teamIndex,
side: c.side,
groupIndex: c.groupIndex ?? 1,
userId: new mongoose.Types.ObjectId(c.userId),
initialTeamBidPointAmount: c.initialTeamBidPointAmount,
})),
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)),
initialPoints: body.initialPoints ?? 1000,
maxTimerSeconds: body.maxTimerSeconds ?? 30,
});
}
@@ -74,7 +53,7 @@ export class AuctionController {
public async getAuction(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) {
return this.auctionService.getStateByMatchId(matchId);
return this.auctionService.getByMatchId(matchId);
}
// 공개 — 팀장 2명만 쓸 엔드포인트(트러스트 기반, 10명 동시 관전).
@@ -83,26 +62,24 @@ export class AuctionController {
@HttpCode(HttpStatus.OK)
public async openBidding(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: OpenBiddingDto = {},
) {
return this.auctionService.openBidding(matchId, body);
return this.auctionService.openBidding(matchId);
}
@Post('bids')
@AllowPublicAccess()
@HttpCode(HttpStatus.OK)
public async placeBid(
@CurrentUser() currentUser: UserDocument | undefined,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: PlaceBidDto,
) {
return this.auctionService.placeBid({
matchId,
teamIndex: body.bidderTeamIndex,
amount: body.bidPointAmount,
bidRequestId: body.bidRequestId,
clientObservedAuctionLifecycleId: body.clientObservedAuctionLifecycleId,
clientObservedCurrentBidRoundPlayerUserId:
body.clientObservedCurrentBidRoundPlayerUserId,
side: body.side,
groupIndex: body.groupIndex ?? 1,
amount: body.amount,
bidderUserId: this.resolveBidder(currentUser, body.bidderUserId),
});
}
@@ -116,77 +93,16 @@ 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, body);
}
@Get('history')
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
public async listHistory(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) {
this.assertSameCommunity(currentUser, communityId);
return this.auctionService.listHistory({ matchId, communityId });
}
@Post('undo')
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
@HttpCode(HttpStatus.OK)
public async undo(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: UndoAuctionDto,
) {
this.assertSameCommunity(currentUser, communityId);
const auction = await this.auctionService.undoTo({
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;
return this.auctionService.next(matchId);
}
@Delete()
@@ -198,22 +114,21 @@ 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,
auctionActionRequestId: body.auctionActionRequestId,
clientObservedAuctionLifecycleId: body.clientObservedAuctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex:
body.clientObservedCurrentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId:
body.clientObservedCurrentBidRoundPlayerUserId,
clientObservedPhase: body.clientObservedPhase,
clientObservedRevision: body.clientObservedRevision,
});
this.auctionGateway.broadcastReset(matchId.toString());
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);
}
private assertSameCommunity(
@@ -1,319 +0,0 @@
import mongoose from 'mongoose';
jest.mock('../auth/jwt.service', () => ({
JwtService: class JwtService {},
}));
import { AuctionGateway } from './auction.gateway';
describe('AuctionGateway', () => {
function createGateway(params?: {
getCurrentRedisTimestampMS?: jest.Mock;
placeBidDelta?: jest.Mock;
}) {
const auctionService = {
placeBidDelta: params?.placeBidDelta ?? jest.fn(),
};
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('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 }, 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',
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 }, 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 }, 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('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 }, 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 }, 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);
});
});
+107 -601
View File
@@ -1,103 +1,44 @@
import { Logger } from '@nestjs/common';
import { randomUUID } from 'crypto';
import { performance } from 'perf_hooks';
import {
Ack,
ConnectedSocket,
MessageBody,
OnGatewayConnection,
OnGatewayInit,
OnGatewayDisconnect,
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
} from '@nestjs/websockets';
import mongoose from 'mongoose';
import type { JWTPayload } from 'jose';
import type { DefaultEventsMap, Namespace, Socket } from 'socket.io';
import { Namespace, Socket } from 'socket.io';
import { AuthService } from '../auth/auth.service';
import { IdentityService } from '../auth/identity.service';
import { JwtService } from '../auth/jwt.service';
import { ConnectionService } from '../global/database/connection.service';
import type {
AuctionChatMessage,
AuctionDocument,
IdentityDocument,
Position,
TeamSide,
UserDocument,
} from '../global/database/schema';
import { AuctionService } from './auction.service';
import type {
AuctionBidDeltaResponse,
AuctionStateResponse,
} from './auction.service';
import { AuctionEventBusService } from './auction-event-bus.service';
import {
isAuctionResyncRecommended,
resolveAuctionRejectionReason,
} from './auction-rejection';
import type { MatchSideEffectDelta } from './auction-side-effect.service';
import { serializeRealtimeAuction } from './auction-realtime-serializer';
import { AuctionRedisService } from './redis/auction-redis.service';
interface JoinAuctionPayload {
matchId: string;
}
interface BidPayload {
bidderTeamIndex: number;
bidPointAmount: number;
bidRequestId?: string;
clientObservedAuctionLifecycleId?: string;
clientObservedCurrentBidRoundPlayerUserId?: string;
}
interface TimeSyncPayload {
clientSentAtTimestampMS?: number;
sequence?: number;
side: TeamSide;
groupIndex?: number;
amount: number;
bidderUserId?: string;
}
interface SoldPayload {
auctionActionRequestId?: string;
assignedPosition?: Position;
clientObservedAuctionLifecycleId?: string;
clientObservedCurrentAuctionPlayerOrderIndex?: number;
clientObservedCurrentBidRoundPlayerUserId?: string;
clientObservedPhase?: string;
clientObservedRevision?: number;
}
type AuctionActionPayload = Omit<SoldPayload, 'assignedPosition'>;
interface ChatMessagePayload {
message?: string;
displayName?: string;
}
interface BidRateLimitState {
count: number;
windowStartedAtTimestampMS: number;
}
interface AuctionSocketData {
auctionBidRateLimit?: BidRateLimitState;
identity?: IdentityDocument;
matchId?: string;
user?: UserDocument;
}
type AuctionSocket = Socket<
DefaultEventsMap,
DefaultEventsMap,
DefaultEventsMap,
AuctionSocketData
>;
const BID_RATE_LIMIT_WINDOW_MS = 1000;
const BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW = 8;
const BID_RATE_LIMIT_REJECTION_CODE = 'BID_RATE_LIMITED';
const BID_RATE_LIMIT_REJECTION_MESSAGE =
'입찰 요청이 너무 많습니다. 잠시 후 다시 시도해주세요.';
@WebSocketGateway({
namespace: '/auction',
cors: {
@@ -106,11 +47,14 @@ const BID_RATE_LIMIT_REJECTION_MESSAGE =
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
},
})
export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
export class AuctionGateway
implements OnGatewayConnection, OnGatewayDisconnect
{
@WebSocketServer()
private server!: Namespace;
private readonly logger = new Logger(AuctionGateway.name);
private readonly roomTimers = new Map<string, NodeJS.Timeout>();
constructor(
private readonly auctionService: AuctionService,
@@ -118,31 +62,31 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
private readonly jwtService: JwtService,
private readonly identityService: IdentityService,
private readonly connectionService: ConnectionService,
private readonly auctionEventBusService: AuctionEventBusService,
private readonly auctionRedisService: AuctionRedisService,
) {}
public afterInit(server: Namespace): void {
this.auctionEventBusService.attachAuctionNamespace(server);
}
public async handleConnection(socket: AuctionSocket) {
public async handleConnection(socket: Socket) {
try {
await this.authenticateSocket(socket);
this.logger.debug(`Auction client connected: ${socket.id}`);
} catch (err) {
this.logger.warn(
`Auction client authentication failed: ${
err instanceof Error ? err.message : String(err)
err instanceof Error ? err.message : err
}`,
);
socket.disconnect(true);
}
}
public handleDisconnect(socket: Socket) {
const matchId = this.getSocketMatchId(socket);
if (!matchId) return;
this.maybeClearRoomTimer(matchId);
}
@SubscribeMessage('join')
public async handleJoin(
@ConnectedSocket() socket: AuctionSocket,
@ConnectedSocket() socket: Socket,
@MessageBody() payload: JoinAuctionPayload,
) {
if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) {
@@ -158,11 +102,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
const auction = await this.auctionService.getByMatchId(
new mongoose.Types.ObjectId(payload.matchId),
);
const auctionState = await this.auctionService.getStateByMatchId(
new mongoose.Types.ObjectId(payload.matchId),
);
this.emitChatHistory(socket, auction);
this.broadcastState(payload.matchId, auctionState);
this.broadcastState(payload.matchId, auction);
} catch (error) {
this.emitKnownError(socket, error);
}
@@ -170,150 +110,51 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
@SubscribeMessage('bid')
public async handleBid(
@ConnectedSocket() socket: AuctionSocket,
@ConnectedSocket() socket: Socket,
@MessageBody() payload: BidPayload,
@Ack() ack?: (response: Record<string, unknown>) => void,
) {
const gatewayBidStartedAtMS = performance.now();
const matchId = this.requireJoinedMatchId(socket);
if (!matchId) return;
const bidRequestId = payload.bidRequestId ?? randomUUID();
if (!this.consumeBidRateLimit(socket)) {
this.emitError(socket, BID_RATE_LIMIT_REJECTION_MESSAGE);
ack?.({
bidRequestId,
code: BID_RATE_LIMIT_REJECTION_CODE,
message: BID_RATE_LIMIT_REJECTION_MESSAGE,
rejected: true,
});
const bidderUserId = this.resolveBidderUserId(socket, payload?.bidderUserId);
if (payload?.bidderUserId && !bidderUserId) {
this.emitError(socket, 'Invalid bidderUserId.');
return;
}
try {
const bidResult = await this.auctionService.placeBidDelta({
const auction = await this.auctionService.placeBid({
matchId: new mongoose.Types.ObjectId(matchId),
teamIndex: payload.bidderTeamIndex,
amount: payload.bidPointAmount,
bidRequestId,
clientObservedAuctionLifecycleId:
payload.clientObservedAuctionLifecycleId,
clientObservedCurrentBidRoundPlayerUserId:
payload.clientObservedCurrentBidRoundPlayerUserId,
});
const bidDelta = this.isBidDeltaResponse(bidResult)
? {
...bidResult,
bidRequestId: bidResult.bidRequestId ?? bidRequestId,
}
: this.buildBidDeltaFromAuctionState(bidResult, bidRequestId);
const bidServerTiming = this.extractBidServerTiming(bidDelta);
const broadcastBidDelta = this.stripBidServerTiming(bidDelta);
if (broadcastBidDelta) {
this.broadcastBid(matchId, broadcastBidDelta);
} else {
this.broadcastState(matchId, bidResult as AuctionStateResponse);
}
ack?.({
...(bidDelta
? {}
: {
state: this.serializeAuction(bidResult as AuctionStateResponse),
}),
ok: true,
bidRequestId,
bidDelta: broadcastBidDelta,
bidServerTiming: this.buildGatewayBidTiming(
gatewayBidStartedAtMS,
bidServerTiming,
),
side: payload.side,
groupIndex: payload.groupIndex ?? 1,
amount: payload.amount,
bidderUserId,
});
this.broadcastState(matchId, auction);
} catch (error) {
const rejectionAckFields = await this.resolveRejectionAckFields(
matchId,
error,
);
const bidServerTiming = this.extractBidServerTiming(rejectionAckFields);
this.emitError(
socket,
typeof rejectionAckFields.message === 'string'
? rejectionAckFields.message
: '',
);
ack?.({
...rejectionAckFields,
bidRequestId,
bidServerTiming: this.buildGatewayBidTiming(
gatewayBidStartedAtMS,
bidServerTiming,
),
rejected: true,
});
}
}
@SubscribeMessage('time-sync')
public async handleTimeSync(
@MessageBody() payload: TimeSyncPayload,
@Ack() ack?: (response: Record<string, unknown>) => void,
) {
const receivedAtMonotonicMS = performance.now();
try {
const currentServerTimestampMS =
await this.auctionRedisService.getCurrentRedisTimestampMS();
ack?.({
clientSentAtTimestampMS: payload?.clientSentAtTimestampMS,
currentServerTimestampMS,
ok: true,
sequence: payload?.sequence,
serverProcessingDurationMS:
Math.round((performance.now() - receivedAtMonotonicMS) * 10) / 10,
});
} catch (error) {
const errorPayload = this.resolveErrorPayload(error);
ack?.({
...errorPayload,
clientSentAtTimestampMS: payload?.clientSentAtTimestampMS,
rejected: true,
sequence: payload?.sequence,
});
this.emitKnownError(socket, error);
}
}
@SubscribeMessage('open-bidding')
public async handleOpenBidding(
@ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: AuctionActionPayload,
@Ack() ack?: (response: Record<string, unknown>) => void,
) {
public async handleOpenBidding(@ConnectedSocket() socket: Socket) {
const matchId = this.requireJoinedMatchId(socket);
if (!matchId) return;
try {
const auction = await this.auctionService.openBidding(
new mongoose.Types.ObjectId(matchId),
this.toSocketAuctionActionRequest(payload),
);
this.broadcastState(matchId, auction);
ack?.({
auctionActionRequestId: payload?.auctionActionRequestId,
ok: true,
});
} catch (error) {
this.emitKnownError(socket, error);
ack?.({
...(await this.resolveRejectionAckFields(matchId, error)),
auctionActionRequestId: payload?.auctionActionRequestId,
rejected: true,
});
}
}
@SubscribeMessage('sold')
public async handleSold(
@ConnectedSocket() socket: AuctionSocket,
@ConnectedSocket() socket: Socket,
@MessageBody() payload: SoldPayload,
@Ack() ack?: (response: Record<string, unknown>) => void,
) {
const matchId = this.requireJoinedMatchId(socket);
if (!matchId) return;
@@ -322,110 +163,29 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
const auction = await this.auctionService.markSold({
matchId: new mongoose.Types.ObjectId(matchId),
assignedPosition: payload?.assignedPosition,
...this.toSocketAuctionActionRequest(payload),
});
this.broadcastState(matchId, auction);
ack?.({
auctionActionRequestId: payload?.auctionActionRequestId,
ok: true,
});
} catch (error) {
this.emitKnownError(socket, error);
ack?.({
...(await this.resolveRejectionAckFields(matchId, error)),
auctionActionRequestId: payload?.auctionActionRequestId,
rejected: true,
});
}
}
@SubscribeMessage('next')
public async handleNext(
@ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: AuctionActionPayload,
@Ack() ack?: (response: Record<string, unknown>) => void,
) {
public async handleNext(@ConnectedSocket() socket: Socket) {
const matchId = this.requireJoinedMatchId(socket);
if (!matchId) return;
try {
const auction = await this.auctionService.next(
new mongoose.Types.ObjectId(matchId),
this.toSocketAuctionActionRequest(payload),
);
this.broadcastState(matchId, auction);
ack?.({
auctionActionRequestId: payload?.auctionActionRequestId,
ok: true,
});
} catch (error) {
this.emitKnownError(socket, error);
ack?.({
...(await this.resolveRejectionAckFields(matchId, error)),
auctionActionRequestId: payload?.auctionActionRequestId,
rejected: true,
});
}
}
@SubscribeMessage('passed')
public async handlePassed(
@ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: AuctionActionPayload,
@Ack() ack?: (response: Record<string, unknown>) => void,
) {
const matchId = this.requireJoinedMatchId(socket);
if (!matchId) return;
try {
const auction = await this.auctionService.markPassed(
new mongoose.Types.ObjectId(matchId),
this.toSocketAuctionActionRequest(payload),
);
this.broadcastState(matchId, auction);
ack?.({
auctionActionRequestId: payload?.auctionActionRequestId,
ok: true,
});
} catch (error) {
this.emitKnownError(socket, error);
ack?.({
...(await this.resolveRejectionAckFields(matchId, error)),
auctionActionRequestId: payload?.auctionActionRequestId,
rejected: true,
});
}
}
@SubscribeMessage('chat-message')
public async handleChatMessage(
@ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: ChatMessagePayload,
) {
const matchId = this.requireJoinedMatchId(socket);
if (!matchId) return;
if (typeof payload?.message !== 'string') {
this.emitError(socket, 'Chat message is required.');
return;
}
try {
const { message } = await this.auctionService.appendChatMessage({
matchId: new mongoose.Types.ObjectId(matchId),
userId: this.resolveSocketUserId(socket),
displayName: this.resolveChatDisplayName(socket, payload.displayName),
message: payload.message,
});
this.server
.to(matchId)
.emit('chat-message', this.serializeChatMessage(message));
} catch (error) {
this.emitKnownError(socket, error);
}
}
private requireJoinedMatchId(socket: AuctionSocket): string | null {
private requireJoinedMatchId(socket: Socket): string | null {
const matchId = this.getSocketMatchId(socket);
if (!matchId) {
this.emitError(socket, 'Join a match room before sending events.');
@@ -434,91 +194,35 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
return matchId;
}
private consumeBidRateLimit(socket: AuctionSocket): boolean {
const currentTimestampMS = Date.now();
const previousState = socket.data.auctionBidRateLimit;
if (
!previousState ||
currentTimestampMS - previousState.windowStartedAtTimestampMS >=
BID_RATE_LIMIT_WINDOW_MS
) {
socket.data.auctionBidRateLimit = {
count: 1,
windowStartedAtTimestampMS: currentTimestampMS,
};
return true;
private getSocketMatchId(socket: Socket): string | undefined {
return typeof socket.data.matchId === 'string'
? socket.data.matchId
: undefined;
}
private resolveBidderUserId(
socket: Socket,
payloadBidderUserId?: string,
): mongoose.Types.ObjectId | undefined {
const candidate =
payloadBidderUserId ??
(socket.data.user as UserDocument | undefined)?._id.toString() ??
this.readHandshakeUserId(socket);
if (!candidate || !mongoose.isValidObjectId(candidate)) {
return undefined;
}
previousState.count += 1;
socket.data.auctionBidRateLimit = previousState;
return previousState.count <= BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW;
return new mongoose.Types.ObjectId(candidate);
}
private getSocketMatchId(socket: AuctionSocket): string | undefined {
return socket.data.matchId;
}
private toAuctionActionRequest(payload?: AuctionActionPayload) {
return {
auctionActionRequestId: payload?.auctionActionRequestId,
clientObservedAuctionLifecycleId:
payload?.clientObservedAuctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex:
payload?.clientObservedCurrentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId:
payload?.clientObservedCurrentBidRoundPlayerUserId,
clientObservedPhase: payload?.clientObservedPhase,
clientObservedRevision: payload?.clientObservedRevision,
};
}
private toSocketAuctionActionRequest(payload?: AuctionActionPayload) {
return {
...this.toAuctionActionRequest(payload),
shouldBroadcastStateAfterDurability: false,
};
}
private readHandshakeUserId(socket: AuctionSocket): string | undefined {
const handshakeAuth = socket.handshake.auth as Record<string, unknown>;
const authUserId = handshakeAuth['x-auth-user-id'];
private readHandshakeUserId(socket: Socket): string | undefined {
const authUserId = socket.handshake.auth['x-auth-user-id'];
if (typeof authUserId === 'string') return authUserId;
const header = socket.handshake.headers['x-auth-user-id'];
return Array.isArray(header) ? header[0] : header;
}
private resolveSocketUserId(
socket: AuctionSocket,
): mongoose.Types.ObjectId | undefined {
return socket.data.user?._id;
}
private resolveChatDisplayName(
socket: AuctionSocket,
fallbackDisplayName?: string,
): string {
const user = socket.data.user;
const primaryRiotAccount =
user?.riotAccounts.find((entry) => entry.isPrimary) ??
user?.riotAccounts[0];
if (primaryRiotAccount?.gameName) {
return primaryRiotAccount.tagLine
? `${primaryRiotAccount.gameName}#${primaryRiotAccount.tagLine}`
: primaryRiotAccount.gameName;
}
if (user?.kakaoTalkNickname) return user.kakaoTalkNickname;
if (user?.discordNickname) return user.discordNickname;
const identity = socket.data.identity;
if (identity?.displayName) return identity.displayName;
if (identity?.email) return identity.email;
return fallbackDisplayName ?? '관전자';
}
private async authenticateSocket(socket: AuctionSocket): Promise<void> {
private async authenticateSocket(socket: Socket): Promise<void> {
const fallback = await this.authService.resolveDevUserById(
this.readHandshakeUserId(socket),
);
@@ -548,20 +252,14 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
});
}
private readHandshakeToken(socket: AuctionSocket): string | undefined {
const handshakeAuth = socket.handshake.auth as Record<string, unknown>;
const authToken = handshakeAuth.token;
private readHandshakeToken(socket: Socket): string | undefined {
const authToken = socket.handshake.auth.token;
if (typeof authToken === 'string' && authToken.trim()) {
return authToken.trim().replace(/^Bearer\s+/i, '');
}
const header: unknown = socket.handshake.headers.authorization;
const authorization =
typeof header === 'string'
? header
: Array.isArray(header) && typeof header[0] === 'string'
? header[0]
: undefined;
const header = socket.handshake.headers.authorization;
const authorization = Array.isArray(header) ? header[0] : header;
if (authorization?.startsWith('Bearer ')) {
return authorization.slice('Bearer '.length).trim();
}
@@ -569,11 +267,10 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
}
private async resolveSocketUserForMatch(
socket: AuctionSocket,
socket: Socket,
matchId: string,
): Promise<void> {
if (socket.data.user || !socket.data.identity) return;
const identity = socket.data.identity;
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findById(matchId).select({
@@ -582,11 +279,10 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
if (!match) return;
const UserModel = await this.connectionService.getModel('user');
const user = await UserModel.findOne({
socket.data.user = await UserModel.findOne({
communityId: match.communityId,
identityId: identity._id,
identityId: (socket.data.identity as IdentityDocument)._id,
}).exec();
socket.data.user = user ?? undefined;
}
private requireStringClaim(payload: JWTPayload, key: string): string {
@@ -601,250 +297,60 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
return typeof value === 'string' && value.length > 0 ? value : undefined;
}
public broadcastState(matchId: string, auction: AuctionStateResponse) {
this.server.to(matchId).emit('state', serializeRealtimeAuction(auction));
private broadcastState(matchId: string, auction: AuctionDocument) {
this.server.to(matchId).emit('state', this.serializeAuction(auction));
this.syncRoomTimer(matchId, auction);
}
public broadcastBid(matchId: string, delta: Record<string, unknown>) {
this.server.to(matchId).emit('bid', delta);
}
private syncRoomTimer(matchId: string, auction: AuctionDocument) {
this.clearRoomTimer(matchId);
if (!auction.currentDeadline) return;
public broadcastReset(matchId: string) {
this.server.to(matchId).emit('reset', { matchId });
}
public broadcastMatchSideEffect(
matchId: string,
delta: MatchSideEffectDelta,
) {
this.server.to(matchId).emit('match-side-effect', delta);
}
private emitChatHistory(socket: AuctionSocket, auction: AuctionDocument) {
socket.emit('chat-history', {
messages: (auction.chatMessages ?? []).map((message) =>
this.serializeChatMessage(message),
),
const deadline = auction.currentDeadline;
const deadlineIso = deadline.toISOString();
this.server.to(matchId).emit('tick', {
deadline: deadlineIso,
serverTime: new Date().toISOString(),
});
const timer = setInterval(() => {
this.server.to(matchId).emit('tick', {
deadline: deadlineIso,
serverTime: new Date().toISOString(),
});
if (Date.now() >= deadline.getTime()) {
this.clearRoomTimer(matchId);
}
}, 1000);
this.roomTimers.set(matchId, timer);
}
private emitKnownError(socket: AuctionSocket, error: unknown) {
this.emitError(socket, this.resolveErrorPayload(error).message);
private maybeClearRoomTimer(matchId: string) {
const room = this.server.adapter.rooms.get(matchId);
if (room && room.size > 0) return;
this.clearRoomTimer(matchId);
}
private emitError(socket: AuctionSocket, message: string) {
private clearRoomTimer(matchId: string) {
const timer = this.roomTimers.get(matchId);
if (!timer) return;
clearInterval(timer);
this.roomTimers.delete(matchId);
}
private emitKnownError(socket: Socket, error: unknown) {
const message =
error instanceof Error ? error.message : 'Unexpected auction gateway error.';
this.emitError(socket, message);
}
private emitError(socket: Socket, message: string) {
socket.emit('error', { message });
}
private serializeAuction(
auction: AuctionStateResponse,
): Record<string, unknown> {
const serialized: unknown = JSON.parse(JSON.stringify(auction));
return typeof serialized === 'object' && serialized !== null
? (serialized as Record<string, unknown>)
: {};
}
/**
* 거부 ack에 실을 공통 필드를 만든다.
*
* - `code`/`message`: 기존 내부 코드/문구(진단·하위호환).
* - `auctionRejectionReason`: 맥락을 담은 설명적 거부코드(클라가 문구로 매핑).
* - `resyncRecommended`: "내가 본 상태가 낡았다"는 신호면 true.
* - `state`: resync 권장 거부에 한해 최신 권위 state를 동봉해, 클라가 join
* 왕복 없이 즉시 rebaseline하도록 한다(후속 액션의 반복 CONFLICT 차단).
*/
private async resolveRejectionAckFields(
matchId: string,
error: unknown,
): Promise<Record<string, unknown>> {
const errorPayload = this.resolveErrorPayload(error);
const auctionRejectionReason = resolveAuctionRejectionReason(
typeof errorPayload.code === 'string' ? errorPayload.code : undefined,
errorPayload.message,
);
const resyncRecommended = isAuctionResyncRecommended(
auctionRejectionReason,
);
const state = resyncRecommended
? await this.fetchSerializedAuctionState(matchId)
: undefined;
return {
...errorPayload,
auctionRejectionReason,
resyncRecommended,
...(state ? { state } : {}),
};
}
private async fetchSerializedAuctionState(
matchId: string,
): Promise<Record<string, unknown> | undefined> {
try {
const state = await this.auctionService.getStateByMatchId(
new mongoose.Types.ObjectId(matchId),
);
return state ? this.serializeAuction(state) : undefined;
} catch {
return undefined;
}
}
private resolveErrorPayload(error: unknown): Record<string, unknown> & {
message: string;
} {
const response =
typeof (error as { getResponse?: unknown })?.getResponse === 'function'
? (error as { getResponse: () => unknown }).getResponse()
: undefined;
if (typeof response === 'object' && response !== null) {
const record = response as Record<string, unknown>;
const message = Array.isArray(record.message)
? record.message.join(', ')
: typeof record.message === 'string'
? record.message
: error instanceof Error
? error.message
: 'Unexpected auction gateway error.';
return {
...record,
code:
typeof record.code === 'string'
? record.code
: error instanceof Error
? error.message
: 'UNKNOWN',
message,
};
}
return {
code: error instanceof Error ? error.message : 'UNKNOWN',
message:
error instanceof Error
? error.message
: 'Unexpected auction gateway error.',
};
}
private buildGatewayBidTiming(
gatewayBidStartedAtMS: number,
bidServerTiming?: Record<string, unknown>,
): Record<string, unknown> {
return {
...(bidServerTiming ?? {}),
gatewayTotalDurationMS:
Math.round((performance.now() - gatewayBidStartedAtMS) * 10) / 10,
};
}
private extractBidServerTiming(
bidDelta: Record<string, unknown> | null,
): Record<string, unknown> | undefined {
const timing = bidDelta?.bidServerTiming;
return typeof timing === 'object' && timing !== null
? (timing as Record<string, unknown>)
: undefined;
}
private stripBidServerTiming(
bidDelta: Record<string, unknown> | null,
): Record<string, unknown> | null {
if (!bidDelta || !('bidServerTiming' in bidDelta)) return bidDelta;
const publicBidDelta = { ...bidDelta };
delete publicBidDelta.bidServerTiming;
return publicBidDelta;
}
private buildBidDeltaFromAuctionState(
auction: AuctionStateResponse,
bidRequestId?: string,
): Record<string, unknown> | null {
const serialized = this.serializeAuction(auction);
const revision = Number(serialized.revision);
const currentHighestBidPointAmount = Number(
serialized.currentHighestBidPointAmount ?? serialized.currentBid,
);
const currentHighestBidderTeamIndex = Number(
serialized.currentHighestBidderTeamIndex ??
serialized.currentBidderTeamIndex,
);
const currentBidRoundDeadlineTimestampMS = Number(
serialized.currentBidRoundDeadlineTimestampMS ??
(typeof serialized.currentDeadline === 'string'
? Date.parse(serialized.currentDeadline)
: 0),
);
const redisBidHistory: unknown[] = Array.isArray(
serialized.auctionBidHistory,
)
? (serialized.auctionBidHistory as unknown[])
: [];
const legacyBidHistory: unknown[] = Array.isArray(serialized.bids)
? (serialized.bids as unknown[])
: [];
const auctionBidHistoryEntry =
redisBidHistory[redisBidHistory.length - 1] ??
this.convertLegacyBidToRedisBidHistoryEntry(
legacyBidHistory[legacyBidHistory.length - 1],
);
if (
!Number.isFinite(currentHighestBidPointAmount) ||
!Number.isFinite(currentHighestBidderTeamIndex) ||
!auctionBidHistoryEntry
) {
return null;
}
return {
auctionBidHistoryEntry,
auctionLifecycleId: serialized.auctionLifecycleId,
bidRequestId,
currentBidRoundDeadlineTimestampMS: Number.isFinite(
currentBidRoundDeadlineTimestampMS,
)
? currentBidRoundDeadlineTimestampMS
: undefined,
currentHighestBidPointAmount,
currentHighestBidderTeamIndex,
currentServerTimestampMS: serialized.currentServerTimestampMS,
revision: Number.isFinite(revision) ? revision : undefined,
};
}
private isBidDeltaResponse(value: unknown): value is AuctionBidDeltaResponse {
return (
typeof value === 'object' &&
value !== null &&
'auctionBidHistoryEntry' in value &&
'currentHighestBidPointAmount' in value &&
'currentHighestBidderTeamIndex' in value &&
'revision' in value
);
}
private convertLegacyBidToRedisBidHistoryEntry(
bid: unknown,
): Record<string, unknown> | null {
if (!bid || typeof bid !== 'object') return null;
const record = bid as Record<string, unknown>;
return {
bidderTeamIndex: record.teamIndex,
bidPointAmount: record.amount,
bidderUserId: record.bidderUserId,
bidPlacedAtTimestampMS:
typeof record.timestamp === 'string'
? Date.parse(record.timestamp)
: undefined,
};
}
private serializeChatMessage(
message: AuctionChatMessage,
): Record<string, unknown> {
const serialized: unknown = JSON.parse(JSON.stringify(message));
return typeof serialized === 'object' && serialized !== null
? (serialized as Record<string, unknown>)
: {};
private serializeAuction(auction: AuctionDocument) {
return JSON.parse(JSON.stringify(auction));
}
}
+2 -19
View File
@@ -4,29 +4,12 @@ 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';
@Module({
imports: [
RiotModule,
TournamentCodeModule,
TournamentResultModule,
AuctionRedisModule,
],
imports: [RiotModule, TournamentCodeModule, TournamentResultModule],
controllers: [AuctionController],
providers: [
AuctionService,
AuctionGateway,
AuctionEventBusService,
AuctionDeadlineScheduler,
AuctionDurabilityScheduler,
AuctionSideEffectService,
],
providers: [AuctionService, AuctionGateway],
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
+22 -92
View File
@@ -7,36 +7,26 @@ import {
IsInt,
IsMongoId,
IsOptional,
IsString,
IsUUID,
Max,
Min,
ValidateNested,
} from 'class-validator';
import { AUCTION_TOP_TIER_THRESHOLDS } from '../../global/database/schema';
export type AuctionTopTierThreshold =
(typeof AUCTION_TOP_TIER_THRESHOLDS)[number];
import { TEAM_SIDES } from '../../global/database/schema';
import type { TeamSide } from '../../global/database/schema';
class CaptainAssignmentDto {
@IsInt()
@Min(1)
teamIndex!: number;
@IsMongoId()
userId!: string;
@IsEnum(TEAM_SIDES)
side!: TeamSide;
@IsOptional()
@IsInt()
@Min(100)
@Max(100000)
initialTeamBidPointAmount?: number;
@Min(1)
groupIndex?: number;
@IsMongoId()
userId!: string;
}
export class StartAuctionDto {
@IsUUID()
startAuctionRequestId!: string;
@IsArray()
@ArrayMinSize(2)
@ArrayMaxSize(16)
@@ -46,95 +36,35 @@ export class StartAuctionDto {
@IsOptional()
@IsInt()
@Min(100)
@Max(100000)
initialTeamBidPointAmount?: number;
@IsOptional()
@IsEnum(AUCTION_TOP_TIER_THRESHOLDS)
topTierAuctionPriorityThreshold?: AuctionTopTierThreshold;
@IsOptional()
@IsArray()
@ArrayMaxSize(100)
@IsMongoId({ each: true })
manualTopTierAuctionPriorityUserIds?: string[];
@Min(1)
initialPoints?: number;
@IsOptional()
@IsInt()
@Min(5)
maximumBidRoundDurationSeconds?: number;
@IsOptional()
@IsInt()
@Min(0)
bidRoundExtensionSeconds?: number;
maxTimerSeconds?: number;
}
export class PlaceBidDto {
@IsEnum(TEAM_SIDES)
side!: TeamSide;
@IsOptional()
@IsUUID()
bidRequestId?: string;
@IsInt()
@Min(1)
groupIndex?: number;
@IsInt()
@Min(1)
bidderTeamIndex!: number;
@IsInt()
@Min(1)
bidPointAmount!: number;
amount!: number;
@IsOptional()
clientObservedAuctionLifecycleId?: string;
@IsOptional()
clientObservedCurrentBidRoundPlayerUserId?: string;
@IsMongoId()
bidderUserId?: string;
}
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 {
export class SoldDto {
@IsOptional()
@IsEnum(['TOP', 'JGL', 'MID', 'ADC', 'SUP'])
assignedPosition?: 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
}
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;
}
@@ -1,395 +0,0 @@
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,
});
});
});
@@ -1,384 +0,0 @@
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;
}
@@ -1,153 +0,0 @@
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,
});
});
});
@@ -1,96 +0,0 @@
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;
}
@@ -1,204 +0,0 @@
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(() => Promise.resolve(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']]);
await expect(service.readLiveStateIdentity('match-1')).resolves.toEqual({
auctionLifecycleId: 'life-1',
revision: 7,
});
expect(sendCommand).toHaveBeenCalledWith([
'HMGET',
'auction:match-1:liveAuctionState',
'auctionLifecycleId',
'revision',
]);
});
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 }],
auctionLifecycleId: 'life-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).toHaveBeenNthCalledWith(1, [
'HGETALL',
'auction:match-1:liveAuctionState',
]);
expect(sendCommand).toHaveBeenNthCalledWith(2, [
'GET',
'auction:match-1:auctionStructureState',
]);
expect(sendCommand).toHaveBeenNthCalledWith(3, [
'LRANGE',
'auction:match-1:auctionBidHistory',
'0',
'-1',
]);
});
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();
});
});
@@ -1,245 +0,0 @@
import { Injectable } from '@nestjs/common';
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 interface AuctionRedisLiveStateIdentity {
auctionLifecycleId?: string;
revision?: number;
}
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',
]);
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,
};
}
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 Promise.all([
this.auctionRedisService.getCurrentRedisTimestampMS(),
this.auctionRedisService
.raw()
.sendCommand(['HGETALL', keys.liveStateKey]),
this.auctionRedisService
.raw()
.sendCommand(['GET', keys.structureStateKey]),
this.auctionRedisService
.raw()
.sendCommand(['LRANGE', keys.bidHistoryKey, '0', '-1']),
]);
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,
liveState: liveState as Record<string, unknown> & {
auctionLifecycleId: string;
phase: string;
revision: number;
},
shouldForceAuctionStateResync: options.shouldForceAuctionStateResync,
structureState: parseJsonRecord(structureStateJson),
});
view.matchId = matchId;
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');
}
@@ -1,111 +0,0 @@
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',
]);
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'",
);
});
});
@@ -1,325 +0,0 @@
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,
],
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 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))
if deadlineMode == 'set-relative' then
local currentBidRoundDeadlineTimestampMS = currentRedisTimestampMS + (deadlineDurationSeconds * 1000)
redis.call('HSET', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS', tostring(currentBidRoundDeadlineTimestampMS))
redis.call('ZADD', bidRoundDeadlineQueueKey, currentBidRoundDeadlineTimestampMS, matchId)
elseif deadlineMode == 'remove' then
redis.call('ZREM', bidRoundDeadlineQueueKey, matchId)
end
if shouldResetBidRuntime == '1' then
redis.call('DEL', auctionBidHistoryKey, bidRequestResultsKey, bidRequestResultOrderKey)
end
redis.call('SADD', appliedAuctionStateTransitionIdsKey, transitionDedupeMember)
redis.call(
'HSET',
durabilityPayloadKey,
'payloadJson',
durabilityPayloadJson,
'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)
)
redis.call('RPUSH', auctionActionRequestResultOrderKey, actionRequestScopeKey)
end
return {'OK', auctionStateTransitionId, tostring(newRevision), tostring(currentRedisTimestampMS)}
`,
);
@@ -1,70 +0,0 @@
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',
]);
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');
});
});
@@ -1,313 +0,0 @@
import type { AuctionRedisKeys } 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;
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;
matchId: string;
}): string {
return [
params.matchId,
params.clientObservedAuctionLifecycleId,
params.clientObservedCurrentBidRoundPlayerUserId,
params.bidderTeamIndex,
params.bidPointAmount,
].join('|');
}
export function buildAuctionBidScriptInvocation(
keys: AuctionRedisKeys,
input: AuctionBidScriptInput,
): AuctionBidScriptInvocation {
return {
keys: [
keys.liveStateKey,
keys.bidHistoryKey,
keys.bidRequestResultsKey,
keys.bidRequestResultOrderKey,
keys.deadlineQueueKey,
],
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),
],
};
}
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 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 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
trimOldBidRequestResults()
if redis.call('LLEN', bidRequestResultOrderKey) >= maximumStoredBidRequestResultCount then
return {'REJECTED', 'BID_REQUEST_RESULT_LIMIT', bidRequestId, tostring(currentRedisTimestampMS)}
end
local function storeRejectedRequest(rejectCode)
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', bidRequestResultOrderKey, 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')
if auctionLifecycleId ~= clientObservedAuctionLifecycleId or currentBidRoundPlayerUserId ~= clientObservedCurrentBidRoundPlayerUserId 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
if redis.call('LLEN', auctionBidHistoryKey) >= maximumStoredAuctionBidHistoryCount then
return storeRejectedRequest('BID_HISTORY_LIMIT')
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 =
'{"bidderTeamIndex":' .. bidderTeamIndex ..
',"bidPointAmount":' .. tostring(bidPointAmount) ..
',"bidderUserId":"' .. bidderUserId ..
'","bidPlacedAtTimestampMS":' .. tostring(currentRedisTimestampMS) ..
'}'
redis.call('RPUSH', auctionBidHistoryKey, auctionBidHistoryEntryJson)
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;
@@ -1 +0,0 @@
export const AUCTION_REDIS_CLIENT = Symbol('AUCTION_REDIS_CLIENT');
@@ -1,38 +0,0 @@
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'");
});
});
@@ -1,107 +0,0 @@
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)
}
`,
);
@@ -1,31 +0,0 @@
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',
);
});
});
@@ -1,47 +0,0 @@
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 interface AuctionRedisKeys {
actionRequestResultOrderKey: string;
actionRequestResultsKey: string;
appliedTransitionIdsKey: string;
bidHistoryKey: string;
bidRequestResultOrderKey: string;
bidRequestResultsKey: 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`,
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`,
};
}
@@ -1,102 +0,0 @@
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 {
assertDistinctRedisInstances,
resolveRedisClientOptions,
} 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';
async function readFirstSecret(
secretService: SecretService,
keys: string[],
): Promise<string | undefined> {
for (const key of keys) {
const value = await secretService.get<string>(key, '');
const trimmed = value.trim();
if (trimmed) return trimmed;
}
return undefined;
}
@Module({
imports: [SecretModule],
providers: [
{
provide: AUCTION_REDIS_CLIENT,
inject: [SecretService],
useFactory: async (
secretService: SecretService,
): Promise<AuctionRedisClient> => {
await secretService.ready();
const [
redisUrl,
redisEndpoint,
auctionRedisUrl,
auctionRedisEndpoint,
auctionRedisUsername,
auctionRedisPassword,
] = await Promise.all([
readFirstSecret(secretService, ['REDIS_URL', 'GARNET_URL']),
readFirstSecret(secretService, ['REDIS_ENDPOINT', 'GARNET_ENDPOINT']),
readFirstSecret(secretService, ['AUCTION_REDIS_URL']),
readFirstSecret(secretService, ['AUCTION_REDIS_ENDPOINT']),
readFirstSecret(secretService, [
'AUCTION_REDIS_USERNAME',
'AUCTION_REDIS_USERID',
]),
readFirstSecret(secretService, ['AUCTION_REDIS_PASSWORD']),
]);
const redisOptions = resolveRedisClientOptions({
endpoint: redisEndpoint,
endpointEnvName: 'REDIS_ENDPOINT',
url: redisUrl,
urlEnvName: 'REDIS_URL',
});
const auctionRedisOptions = resolveRedisClientOptions({
endpoint: auctionRedisEndpoint,
endpointEnvName: 'AUCTION_REDIS_ENDPOINT',
password: auctionRedisPassword,
url: auctionRedisUrl,
urlEnvName: 'AUCTION_REDIS_URL',
username: auctionRedisUsername,
});
assertDistinctRedisInstances(redisOptions.url, auctionRedisOptions.url);
const logger = new Logger('AuctionRedisClient');
const client = createClient(auctionRedisOptions);
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 {}
@@ -1,77 +0,0 @@
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',
);
});
});
@@ -1,233 +0,0 @@
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)
}
`,
);
@@ -1,14 +0,0 @@
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'),
});
});
});
@@ -1,18 +0,0 @@
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'),
};
}
@@ -1,66 +0,0 @@
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);
});
});
@@ -1,141 +0,0 @@
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([
'EVAL',
'if redis.call("GET", KEYS[1]) == ARGV[1] then return redis.call("DEL", KEYS[1]) else return 0 end',
'1',
key,
token,
]);
return Number(result) === 1;
}
}
@@ -1,109 +0,0 @@
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: false,
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'");
});
});
@@ -1,191 +0,0 @@
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;
const redisRevision = params.live.revision ?? -1;
const mongoRevision = params.mongo.revision;
if (mongoRevision > redisRevision) return true;
return (
mongoRevision === redisRevision &&
params.mongo.auctionLifecycleId !== params.live.auctionLifecycleId
);
}
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
local shouldHydrate = false
if redisRevision < 0 then
shouldHydrate = true
elseif mongoRevision > redisRevision then
shouldHydrate = true
elseif mongoRevision == redisRevision and mongoAuctionLifecycleId ~= redisAuctionLifecycleId 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)
end
return {'OK', tostring(hydratedRevision), tostring(currentRedisTimestampMS)}
`,
);
+4 -1
View File
@@ -1,5 +1,8 @@
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' {
+4 -1
View File
@@ -2,7 +2,10 @@ 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,7 +26,8 @@ export class JwtAuthGuard implements CanActivate {
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
[context.getHandler(), context.getClass()],
);
const authzHeader = request.get('authorization');
const authz = request.headers?.authorization;
const authzHeader = Array.isArray(authz) ? authz[0] : authz;
if (!authzHeader) {
const fallback =
@@ -73,7 +74,7 @@ export class JwtAuthGuard implements CanActivate {
private pickIdPFromToken(token: string): IdentityProviderName {
try {
const { iss } = decodeJwt(token);
const { iss } = decodeJwt(token) as { iss?: string };
if (!iss) {
throw new Error('Token has no issuer (iss) claim');
}
@@ -83,8 +84,7 @@ 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);
}
}
+9 -32
View File
@@ -35,13 +35,11 @@ export class JwtService {
throw new Error('Empty token');
}
const provider =
identityProvider === 'MICROSOFT_ENTRAID'
? await this.getEntraConfig()
: undefined;
if (!provider) {
throw new Error('Identity provider not configured.');
if (identityProvider !== 'MICROSOFT_ENTRAID') {
throw new Error(`Identity provider not configured: ${identityProvider}`);
}
const provider = await this.getEntraConfig();
const result = await jwtVerify(token, provider.jwks, {
issuer: provider.issuer,
audience: provider.audience,
@@ -50,22 +48,14 @@ export class JwtService {
});
const { payload, protectedHeader } = result;
if (!provider.allowedAlgs.includes(protectedHeader.alg)) {
if (!provider.allowedAlgs.includes(protectedHeader.alg as string)) {
throw new Error(`Unexpected alg: ${protectedHeader.alg}`);
}
if (
payload.ver !== undefined &&
(typeof payload.ver !== 'string' || payload.ver !== '2.0')
) {
throw new Error(
`Unsupported Entra token version: ${formatClaimValue(payload.ver)}`,
);
if (payload.ver && payload.ver !== '2.0') {
throw new Error(`Unsupported Entra token version: ${payload.ver}`);
}
if (
payload.tid !== undefined &&
(typeof payload.tid !== 'string' || payload.tid !== provider.tenantId)
) {
throw new Error(`Unexpected tenant: ${formatClaimValue(payload.tid)}`);
if (payload.tid && payload.tid !== provider.tenantId) {
throw new Error(`Unexpected tenant: ${payload.tid}`);
}
return result;
@@ -108,16 +98,3 @@ 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 type { CommunityRole } from '../global/database/schema';
import { CommunityRole, UserDocument } 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;
const user = req.user as UserDocument | undefined;
if (!user && req.identity) {
throw new ForbiddenException('No membership in this community.');
}
@@ -7,10 +7,9 @@ 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,
@@ -1,17 +1,17 @@
import { Injectable, Logger } from '@nestjs/common';
import { RedisService } from '../global/redis/redis.service';
import { GarnetService } from '../global/garnet/garnet.service';
const COMMUNITY_STATS_TTL_SECONDS = 5 * 60;
const COMMUNITY_STATS_TTL_SECONDS = 60 * 60;
const COMMUNITY_STATS_DETAIL_TTL_SECONDS = 24 * 60 * 60;
@Injectable()
export class CommunityStatsCacheService {
private readonly logger = new Logger(CommunityStatsCacheService.name);
constructor(private readonly redisService: RedisService) {}
constructor(private readonly garnetService: GarnetService) {}
public get<T>(key: string): Promise<T | null> {
return this.redisService.getJson<T>(key);
return this.garnetService.getJson<T>(key);
}
public set(
@@ -19,7 +19,7 @@ export class CommunityStatsCacheService {
value: unknown,
ttlSeconds = COMMUNITY_STATS_TTL_SECONDS,
): Promise<void> {
return this.redisService.setJson(key, value, ttlSeconds);
return this.garnetService.setJson(key, value, ttlSeconds);
}
public setDetail(key: string, value: unknown): Promise<void> {
@@ -29,34 +29,21 @@ export class CommunityStatsCacheService {
public async invalidateCommunity(communityId: string): Promise<number> {
const prefix = `riot:communitystats:`;
const match = `${prefix}*${communityId}*`;
const client = this.redisService.raw();
const client = this.garnetService.raw();
let cursor = '0';
let deleted = 0;
do {
const reply = await client.sendCommand([
const reply = (await client.sendCommand([
'SCAN',
cursor,
'MATCH',
match,
'COUNT',
'100',
]);
if (!Array.isArray(reply)) {
throw new Error('Redis SCAN returned an invalid response.');
}
const values = reply as unknown[];
const nextCursor = values[0];
const rawKeys = values[1];
if (typeof nextCursor !== 'string') {
throw new Error('Redis SCAN returned an invalid cursor.');
}
cursor = nextCursor;
const keys = Array.isArray(rawKeys)
? (rawKeys as unknown[]).filter(
(key): key is string => typeof key === 'string',
)
: [];
])) as [string, string[]];
cursor = reply[0];
const keys = reply[1] ?? [];
if (keys.length > 0) {
deleted += await client.del(keys);
}
@@ -23,14 +23,7 @@ export class CommunityStatsController {
) {
return this.communityStatsService.getMatches({
communityId,
filters: this.toFilters({
seasonId,
from,
to,
championId,
cursor,
limit,
}),
filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }),
});
}
@@ -92,14 +85,7 @@ export class CommunityStatsController {
return this.communityStatsService.getUserInternalHistory({
communityId,
userId,
filters: this.toFilters({
seasonId,
from,
to,
championId,
cursor,
limit,
}),
filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }),
});
}
@@ -1,22 +1,11 @@
import { 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';
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
import { MatchStatsRepository } from './match-stats.repository';
import { MatchStatsService } from './match-stats.service';
@Module({
imports: [RiotModule],
controllers: [CommunityStatsController],
providers: [
CommunityStatsService,
CommunityStatsCacheService,
MatchStatsFragmentBuilder,
MatchStatsRepository,
MatchStatsService,
],
exports: [CommunityStatsService, MatchStatsService],
providers: [CommunityStatsService, CommunityStatsCacheService],
exports: [CommunityStatsService],
})
export class CommunityStatsModule {}
@@ -1,702 +0,0 @@
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { CommunityStatsCacheService } from './community-stats-cache.service';
import { CommunityStatsService } from './community-stats.service';
import type {
InternalMatchCardView,
InternalMatchDetailResponse,
} from './community-stats.types';
import { MatchStatsRepository } from './match-stats.repository';
import { MatchStatsService } from './match-stats.service';
import {
MATCH_STATS_BUILDER_VERSION,
type InternalGameDetail,
type InternalRecord,
} from './match-stats.types';
function objectives() {
return {
tower: 1,
dragon: 0,
inhibitor: 0,
baron: 0,
riftHerald: 0,
voidGrub: 0,
elderDragon: 0,
};
}
function record(matchId: mongoose.Types.ObjectId): InternalRecord {
return {
matchId: matchId.toString(),
title: '내전',
scheduledAt: new Date('2026-06-18T12:00:00.000Z'),
gameNumber: 1,
riotMatchId: 'KR_1',
gameCreation: 1_000,
gameDuration: 1_800,
userId: new mongoose.Types.ObjectId().toString(),
summonerName: 'Player',
tagLine: 'KR1',
profileIconId: 1,
teamIndex: 1,
side: 'blue',
championId: 266,
championLevel: 15,
teamPosition: 'TOP',
kills: 5,
deaths: 1,
assists: 7,
win: true,
cs: 200,
csPerMin: 6.7,
gold: 12_000,
gpm: 400,
damageDealtToChampions: 18_000,
damageTaken: 20_000,
damageShare: 30,
killParticipation: 60,
visionScore: 18,
controlWardsBought: 1,
wardsPlaced: 8,
wardsKilled: 2,
firstBloodKill: false,
firstBloodAssist: false,
items: [1054, 3071, 0, 0, 0, 0],
trinket: 3340,
summonerSpells: [4, 12],
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' }],
skillBuild: [{ timestamp: 11, skillSlot: 1, level: 1 }],
rating: 8.5,
};
}
describe('CommunityStatsService', () => {
it('ignores detail caches missing unified events or containing invalid checkpoints', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const match: InternalMatchCardView = {
matchId: matchId.toString(),
title: '내전',
scheduledAt: '2026-06-18T12:00:00.000Z',
status: 'finished',
gameCount: 1,
games: [],
teams: [],
seriesResults: [],
};
const participant = record(matchId);
Object.assign(participant, {
participantId: 1,
checkpoints: {
at10: {
timestamp: 590,
gold: 5_200,
cs: 90,
xp: 4_200,
kills: 1,
deaths: 1,
assists: 1,
},
},
});
const gameDetail: InternalGameDetail = {
gameNumber: 1,
riotMatchId: 'KR_1',
gameCreation: 1_000,
gameDuration: 1_800,
winnerSide: 'blue',
timelineLoaded: true,
timeline: [
{
timestamp: 0,
blue: { gold: 500, xp: 0 },
red: { gold: 500, xp: 0 },
goldDiff: 0,
xpDiff: 0,
},
],
objectiveEvents: [],
teams: [
{
teamIndex: 1,
side: 'blue',
win: true,
objectives: objectives(),
bans: [],
participants: [participant],
},
],
};
Object.assign(gameDetail, {
timelineEvents: [
{
timestamp: 300,
side: 'blue',
type: 'championKill',
killerParticipantId: 1,
victimParticipantId: 2,
assistingParticipantIds: [],
},
],
});
const otherwiseCompleteCachedGame = {
gameNumber: 1,
riotMatchId: 'KR_1',
gameCreation: 1_000,
gameDuration: 1_800,
timeline: [],
objectiveEvents: [],
teams: [
{
teamIndex: 1,
side: 'blue' as const,
win: true,
objectives: objectives(),
bans: [],
participants: [
{
summonerName: 'Cached Player',
tagLine: 'KR1',
itemBuild: [],
skillBuild: [],
},
],
},
],
};
const missingTimelineEventsCache = {
match,
games: [otherwiseCompleteCachedGame],
} as unknown as InternalMatchDetailResponse;
const invalidCheckpointCache = {
match,
games: [
{
...otherwiseCompleteCachedGame,
timelineEvents: [],
teams: otherwiseCompleteCachedGame.teams.map((team) => ({
...team,
participants: team.participants.map((cachedParticipant) => ({
...cachedParticipant,
participantId: 1,
checkpoints: {
at10: {
timestamp: '590',
gold: 5_200,
cs: 90,
xp: 4_200,
kills: 1,
deaths: 1,
assists: 1,
},
},
})),
})),
},
],
} as unknown as InternalMatchDetailResponse;
const setDetail = jest.fn().mockResolvedValue(undefined);
const cacheService = {
get: jest
.fn()
.mockResolvedValueOnce(missingTimelineEventsCache)
.mockResolvedValueOnce(invalidCheckpointCache),
setDetail,
} as unknown as jest.Mocked<CommunityStatsCacheService>;
const matchStatsService = {
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<MatchStatsService>;
const service = new CommunityStatsService(
{} as ConnectionService,
cacheService,
{} as MatchStatsRepository,
matchStatsService,
);
(service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset =
jest.fn().mockResolvedValue({
season: {
id: 'all',
label: '전체',
startTime: null,
endTime: null,
},
matches: [match],
records: [participant],
detailsByMatchId: new Map([[matchId.toString(), [gameDetail]]]),
});
const missingEventsResponse = await service.getMatchDetail({
communityId,
matchId,
});
const invalidCheckpointResponse = await service.getMatchDetail({
communityId,
matchId,
});
expect(missingEventsResponse.games[0].timeline).toHaveLength(1);
expect(invalidCheckpointResponse.games[0].timeline).toHaveLength(1);
expect(invalidCheckpointResponse.games[0]).toMatchObject({
timelineEvents: [
{
timestamp: 300,
side: 'blue',
type: 'championKill',
},
],
});
expect(
invalidCheckpointResponse.games[0].teams[0].participants[0],
).toMatchObject({
participantId: 1,
checkpoints: {
at10: {
timestamp: 590,
gold: 5_200,
cs: 90,
xp: 4_200,
kills: 1,
deaths: 1,
assists: 1,
},
},
itemBuild: [{ timestamp: 10, itemId: 1054, type: 'purchased' }],
perks: {
selectedPerkIds: [8010, 9111, 9105, 8299, 8444, 8451],
},
});
expect(matchStatsService.buildAndUpsert).not.toHaveBeenCalled();
expect(setDetail).toHaveBeenCalledTimes(2);
expect(setDetail).toHaveBeenNthCalledWith(
2,
expect.stringContaining(':r4:'),
invalidCheckpointResponse,
);
});
it('backs off failed timeline hydration and retries after the short cache expires', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const match: InternalMatchCardView = {
matchId: matchId.toString(),
title: '내전',
scheduledAt: '2026-06-18T12:00:00.000Z',
status: 'finished',
gameCount: 1,
games: [],
teams: [],
seriesResults: [],
};
const participant = record(matchId);
const gameDetail: InternalGameDetail = {
gameNumber: 1,
riotMatchId: 'KR_1',
gameCreation: 1_000,
gameDuration: 1_800,
winnerSide: 'blue',
timelineLoaded: false,
timeline: [],
objectiveEvents: [],
timelineEvents: [],
teams: [
{
teamIndex: 1,
side: 'blue',
win: true,
objectives: objectives(),
bans: [],
participants: [participant],
},
],
};
const dataset = (timelineLoaded: boolean) => ({
season: {
id: 'all',
label: '전체',
startTime: null,
endTime: null,
},
matches: [match],
records: [participant],
detailsByMatchId: new Map([
[matchId.toString(), [{ ...gameDetail, timelineLoaded }]],
]),
});
let cachedResponse: InternalMatchDetailResponse | null = null;
const set = jest
.fn()
.mockImplementation(
(_key: string, value: InternalMatchDetailResponse) => {
cachedResponse = value;
return Promise.resolve();
},
);
const setDetail = jest
.fn()
.mockImplementation(
(_key: string, value: InternalMatchDetailResponse) => {
cachedResponse = value;
return Promise.resolve();
},
);
const cacheService = {
get: jest.fn().mockImplementation(() => Promise.resolve(cachedResponse)),
set,
setDetail,
} as unknown as jest.Mocked<CommunityStatsCacheService>;
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
const service = new CommunityStatsService(
{} as ConnectionService,
cacheService,
{} as MatchStatsRepository,
{ buildAndUpsert } as unknown as MatchStatsService,
);
(service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset =
jest
.fn()
.mockResolvedValueOnce(dataset(false))
.mockResolvedValueOnce(dataset(false))
.mockResolvedValueOnce(dataset(false))
.mockResolvedValueOnce(dataset(true));
const fallback = await service.getMatchDetail({ communityId, matchId });
const backedOff = await service.getMatchDetail({ communityId, matchId });
expect(backedOff).toBe(fallback);
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
expect(set).toHaveBeenCalledWith(
expect.stringContaining(':r4:'),
fallback,
60,
);
expect(setDetail).not.toHaveBeenCalled();
cachedResponse = null;
const recovered = await service.getMatchDetail({ communityId, matchId });
expect(buildAndUpsert).toHaveBeenCalledTimes(2);
expect(setDetail).toHaveBeenCalledTimes(1);
expect(setDetail).toHaveBeenCalledWith(
expect.stringContaining(':r4:'),
recovered,
);
});
it('coalesces concurrent internal match detail cache misses', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const match: InternalMatchCardView = {
matchId: matchId.toString(),
title: '내전',
scheduledAt: '2026-06-18T12:00:00.000Z',
status: 'finished',
gameCount: 1,
games: [],
teams: [],
seriesResults: [],
};
const participant = record(matchId);
const dataset = {
season: {
id: 'all',
label: '전체',
startTime: null,
endTime: null,
},
matches: [match],
records: [participant],
detailsByMatchId: new Map([
[
matchId.toString(),
[
{
gameNumber: 1,
riotMatchId: 'KR_1',
gameCreation: 1_000,
gameDuration: 1_800,
winnerSide: 'blue' as const,
timelineLoaded: true,
timeline: [],
objectiveEvents: [],
timelineEvents: [],
teams: [
{
teamIndex: 1,
side: 'blue' as const,
win: true,
objectives: objectives(),
bans: [],
participants: [participant],
},
],
},
],
],
]),
};
let resolveDataset: ((value: typeof dataset) => void) | undefined;
const datasetPromise = new Promise<typeof dataset>((resolve) => {
resolveDataset = resolve;
});
const setDetail = jest.fn().mockResolvedValue(undefined);
const cacheService = {
get: jest.fn().mockResolvedValue(null),
setDetail,
} as unknown as jest.Mocked<CommunityStatsCacheService>;
const service = new CommunityStatsService(
{} as ConnectionService,
cacheService,
{} as MatchStatsRepository,
{} as MatchStatsService,
);
const buildBaseDataset = jest.fn().mockReturnValue(datasetPromise);
(service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset =
buildBaseDataset;
const first = service.getMatchDetail({ communityId, matchId });
const second = service.getMatchDetail({ communityId, matchId });
await Promise.resolve();
resolveDataset?.(dataset);
const [firstResponse, secondResponse] = await Promise.all([first, second]);
expect(firstResponse).toBe(secondResponse);
expect(buildBaseDataset).toHaveBeenCalledTimes(1);
expect(setDetail).toHaveBeenCalledTimes(1);
});
it('includes internal match route fields in user internal history matches', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
const participant = record(matchId);
participant.userId = userId.toString();
participant.gameNumber = 2;
participant.riotMatchId = 'KR_1234';
const cacheService = {
get: jest.fn().mockResolvedValue(null),
set: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<CommunityStatsCacheService>;
const matchStatsRepository = {
findUserRecordFragments: jest
.fn()
.mockResolvedValue([{ matchId, records: [participant] }]),
findDetailsByMatches: jest
.fn()
.mockResolvedValue([{ matchId, gameDetails: [] }]),
} as unknown as jest.Mocked<MatchStatsRepository>;
const service = new CommunityStatsService(
{} as ConnectionService,
cacheService,
matchStatsRepository,
{} as MatchStatsService,
);
(service as unknown as { resolveContext: jest.Mock }).resolveContext = jest
.fn()
.mockResolvedValue({
community: {},
season: {
id: 'all',
label: '전체',
startedAt: null,
endedAt: null,
},
from: null,
to: null,
});
const buildBaseDataset = jest.spyOn(
service as unknown as { buildBaseDataset: jest.Mock },
'buildBaseDataset',
);
const response = await service.getUserInternalHistory({
communityId,
userId,
filters: { limit: 5 },
});
expect(response.matches[0]).toMatchObject({
matchId: 'KR_1234',
internalMatchId: matchId.toString(),
gameNumber: 2,
queueLabel: '내전',
});
expect(matchStatsRepository.findUserRecordFragments).toHaveBeenCalledWith({
communityId,
userId,
fromGameCreation: undefined,
toGameCreation: undefined,
limit: 300,
});
expect(
matchStatsRepository.findDetailsByMatches.mock.calls[0][0].matchIds.map(
(id) => id.toString(),
),
).toEqual([matchId.toString()]);
expect(buildBaseDataset).not.toHaveBeenCalled();
expect(cacheService.set).toHaveBeenCalledWith(
expect.stringContaining(`userInternal:v3:${userId.toString()}`),
response,
);
});
it('coalesces concurrent user internal history cache misses', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
const participant = record(matchId);
participant.userId = userId.toString();
let resolveFragments:
| ((
fragments: Array<{
matchId: mongoose.Types.ObjectId;
records: InternalRecord[];
}>,
) => void)
| undefined;
const fragmentsPromise = new Promise<
Array<{ matchId: mongoose.Types.ObjectId; records: InternalRecord[] }>
>((resolve) => {
resolveFragments = resolve;
});
const cacheService = {
get: jest.fn().mockResolvedValue(null),
set: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<CommunityStatsCacheService>;
const matchStatsRepository = {
findUserRecordFragments: jest.fn().mockReturnValue(fragmentsPromise),
findDetailsByMatches: jest.fn().mockResolvedValue([]),
} as unknown as jest.Mocked<MatchStatsRepository>;
const service = new CommunityStatsService(
{} as ConnectionService,
cacheService,
matchStatsRepository,
{} as MatchStatsService,
);
(service as unknown as { resolveContext: jest.Mock }).resolveContext = jest
.fn()
.mockResolvedValue({
community: {},
season: {
id: 'all',
label: '전체',
startedAt: null,
endedAt: null,
},
from: null,
to: null,
});
const first = service.getUserInternalHistory({
communityId,
userId,
filters: { limit: 5 },
});
const second = service.getUserInternalHistory({
communityId,
userId,
filters: { limit: 5 },
});
await Promise.resolve();
resolveFragments?.([{ matchId, records: [participant] }]);
const [firstResponse, secondResponse] = await Promise.all([first, second]);
expect(firstResponse).toBe(secondResponse);
expect(matchStatsRepository.findUserRecordFragments).toHaveBeenCalledTimes(
1,
);
expect(cacheService.set).toHaveBeenCalledTimes(1);
});
it('self-heals Competition fragments when their source revision is stale', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const matches = [{ _id: matchId, competitionId }];
const MatchModel = {
find: jest.fn().mockReturnValue({
sort: jest.fn().mockReturnValue({
limit: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(matches),
}),
}),
}),
}),
};
const CompetitionModel = {
find: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue([
{
_id: competitionId,
revision: 7,
projectorVersion: 3,
},
]),
}),
}),
}),
};
const connectionService = {
getModel: jest.fn().mockImplementation((name: string) => {
if (name === 'match') return Promise.resolve(MatchModel);
if (name === 'competition') return Promise.resolve(CompetitionModel);
throw new Error(`Unexpected model ${name}`);
}),
} as unknown as ConnectionService;
const matchStatsRepository = {
findByCommunity: jest.fn().mockResolvedValue([
{
matchId,
builderVersion: MATCH_STATS_BUILDER_VERSION,
sourceCompetitionId: competitionId,
sourceRevision: 6,
projectorVersion: 3,
},
]),
} as unknown as jest.Mocked<MatchStatsRepository>;
const matchStatsService = {
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<MatchStatsService>;
const service = new CommunityStatsService(
connectionService,
{} as CommunityStatsCacheService,
matchStatsRepository,
matchStatsService,
);
const rebuilt = await (
service as unknown as {
rebuildMissingOrStaleFragments(
communityId: mongoose.Types.ObjectId,
): Promise<number>;
}
).rebuildMissingOrStaleFragments(communityId);
expect(MatchModel.find).toHaveBeenCalledWith({
communityId,
status: { $in: ['finished', 'in-progress'] },
$or: [
{ competitionId: { $exists: true } },
{ 'result.games.0': { $exists: true } },
],
});
expect(matchStatsService.buildAndUpsert).toHaveBeenCalledWith(matchId);
expect(rebuilt).toBe(1);
});
});
File diff suppressed because it is too large. Load diff
@@ -1,16 +1,5 @@
import type {
MatchStatsParticipantCheckpoints,
MatchStatsItemBuildEvent,
MatchStatsRunePerks,
MatchStatsSkillBuildEvent,
MatchStatsTimelineEvent,
RiotLane,
TeamSide,
} from '../global/database/schema';
import type {
RecentMatchView,
HistorySeasonDto,
} from '../match-history/match-history.types';
import type { RiotLane, TeamSide } from '../global/database/schema';
import type { RecentMatchView, HistorySeasonDto } from '../match-history/match-history.types';
export interface CommunityStatsFilters {
seasonId?: string;
@@ -33,25 +22,17 @@ export interface InternalMatchCardView {
scheduledAt: string;
status: 'finished' | 'in-progress';
gameCount: number;
winnerTeamIndex?: number;
seriesResults: Array<{
teamAIndex: number;
teamBIndex: number;
teamAWins: number;
teamBWins: number;
winnerTeamIndex?: number;
}>;
blueScore: number;
redScore: number;
winnerSide?: TeamSide;
games: Array<{
gameNumber: number;
riotMatchId: string | null;
blueTeamIndex: number;
redTeamIndex: number;
winnerTeamIndex: number | null;
winnerSide: TeamSide | null;
gameDuration: number;
}>;
teams: Array<{
teamIndex: number;
side: TeamSide;
name: string;
members: Array<{
userId: string;
@@ -83,9 +64,7 @@ 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 }>;
}
@@ -121,46 +100,16 @@ export interface InternalMatchDetailResponse {
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: {
tower: number;
dragon: number;
inhibitor: number;
baron: number;
riftHerald: number;
voidGrub: number;
elderDragon: number;
};
bans: Array<{ championId: number; pickTurn: number }>;
objectives: { baron: number; dragon: number; tower: 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;
@@ -169,21 +118,13 @@ 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: MatchStatsRunePerks;
itemBuild: MatchStatsItemBuildEvent[];
skillBuild: MatchStatsSkillBuildEvent[];
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
win: boolean;
}>;
}>;
@@ -1,822 +0,0 @@
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 {
const userId = new mongoose.Types.ObjectId();
return {
_id: new mongoose.Types.ObjectId(),
communityId: new mongoose.Types.ObjectId(),
title: '내전',
scheduledAt: new Date('2026-05-03T00:00:00.000Z'),
status: 'finished',
gameCount: 1,
participants: [
{
userId,
puuid: 'puuid-1',
gameName: 'Player',
profileIconId: 7,
},
],
teams: [
{
teamIndex: 1,
name: 'A',
members: [{ userId, assignedPosition: 'TOP' }],
},
{ teamIndex: 2, name: 'B', members: [] },
],
result: {
winnerTeamIndex: 1,
riotMatchIds: ['KR_1'],
games: [
{
gameNumber: 1,
riotMatchId: 'KR_1',
blueTeamIndex: 1,
redTeamIndex: 2,
winnerTeamIndex: 1,
winnerSide: 'blue',
gameCreation: 1_000,
gameDuration: 1_800,
participants: [
{
userId,
teamIndex: 1,
side: 'blue',
championId: 266,
kills: 5,
deaths: 1,
assists: 7,
win: true,
},
],
},
],
seriesResults: [
{
teamAIndex: 1,
teamBIndex: 2,
teamAWins: 1,
teamBWins: 0,
winnerTeamIndex: 1,
},
],
},
} as unknown as MatchDocument;
}
describe('MatchStatsFragmentBuilder', () => {
it('builds a fallback fragment without raw Riot match data', () => {
const builder = new MatchStatsFragmentBuilder();
const match = makeMatch();
const fragment = builder.buildFragment({
match,
rawByRiotMatchId: new Map(),
});
expect(fragment.matchCard.matchId).toBe(match._id.toString());
expect(fragment.gameCreationMin).toBe(1_000);
expect(fragment.gameCreationMax).toBe(1_000);
expect(fragment.userIds.map((id) => id.toString())).toEqual([
match.participants[0].userId.toString(),
]);
expect(fragment.championIds).toEqual([266]);
expect(fragment.records).toHaveLength(1);
expect(fragment.records[0]).toMatchObject({
summonerName: 'Player',
championId: 266,
kills: 5,
deaths: 1,
assists: 7,
win: true,
});
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,
});
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 = {
metadata: {
dataVersion: '2',
matchId: 'KR_1',
participants: ['puuid-1'],
},
info: {
frameInterval: 60_000,
frames: [
{
timestamp: 0,
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 as RiotMatchTimelineDto],
]),
});
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 as RiotMatchTimelineDto],
]),
});
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,971 +0,0 @@
import { Injectable } from '@nestjs/common';
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,
RiotMatchTimelineDto,
} from '../riot/riot.types';
import type { InternalMatchCardView } from './community-stats.types';
import type {
InternalGameDetail,
InternalRecord,
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,
);
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, timeline)
: this.toFallbackGameDetail(params.match, game);
});
const records = gameDetails.flatMap((detail) =>
detail.teams.flatMap((team) => team.participants),
);
const gameCreations = gameDetails.map((detail) => detail.gameCreation);
return {
matchCard,
records,
gameDetails,
userIds: [
...new Map(
records
.filter((record) => mongoose.isValidObjectId(record.userId))
.map((record) => [
record.userId,
new mongoose.Types.ObjectId(record.userId),
]),
).values(),
],
championIds: [...new Set(records.map((record) => record.championId))],
gameCreationMin:
gameCreations.length > 0
? Math.min(...gameCreations)
: params.match.scheduledAt.getTime(),
gameCreationMax:
gameCreations.length > 0
? Math.max(...gameCreations)
: params.match.scheduledAt.getTime(),
};
}
private toMatchCard(
match: MatchDocument,
games: NonNullable<MatchDocument['result']>['games'],
): InternalMatchCardView {
const participantById = new Map(
match.participants.map((participant) => [
participant.userId.toString(),
participant,
]),
);
return {
matchId: match._id.toString(),
title: match.title,
scheduledAt: match.scheduledAt.toISOString(),
status: match.status === 'finished' ? 'finished' : 'in-progress',
gameCount: match.gameCount,
winnerTeamIndex: match.result?.winnerTeamIndex,
seriesResults: match.result?.seriesResults ?? [],
games: games.map((game) => ({
gameNumber: game.gameNumber,
riotMatchId: game.riotMatchId ?? null,
blueTeamIndex: game.blueTeamIndex,
redTeamIndex: game.redTeamIndex,
winnerTeamIndex: game.winnerTeamIndex ?? null,
winnerSide: game.winnerSide ?? null,
gameDuration: game.gameDuration,
})),
teams: match.teams.map((team) => ({
teamIndex: team.teamIndex,
name: team.name,
members: team.members.map((member) => {
const participant = participantById.get(member.userId.toString());
return {
userId: member.userId.toString(),
summonerName: participant?.gameName ?? 'Unknown',
profileIconId: participant?.profileIconId ?? 0,
};
}),
})),
};
}
private toGameDetail(
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)
.map((participant) => [
participant.userId.toString(),
participant.puuid as string,
]),
);
const rawByPuuid = new Map(
raw.info.participants.map((participant) => [
participant.puuid,
participant,
]),
);
const rawTeamIdBySide = new Map<TeamSide, number>();
for (const participant of game.participants) {
const puuid = puuidByUserId.get(participant.userId.toString());
const rawParticipant = puuid ? rawByPuuid.get(puuid) : undefined;
if (rawParticipant) {
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),
objectiveEvents,
timelineEvents,
teams: (['blue', 'red'] as TeamSide[]).map((side) => {
const teamIndex =
side === 'blue' ? game.blueTeamIndex : game.redTeamIndex;
const rawTeamId = rawTeamIdBySide.get(side);
const rawTeam = raw.info.teams.find(
(team) => team.teamId === rawTeamId,
);
const teamRawParticipants = raw.info.participants.filter(
(participant) => participant.teamId === rawTeamId,
);
const teamKills = teamRawParticipants.reduce(
(sum, participant) => sum + participant.kills,
0,
);
const teamDamage = teamRawParticipants.reduce(
(sum, participant) => sum + participant.totalDamageDealtToChampions,
0,
);
return {
teamIndex,
side,
win: game.winnerSide === side,
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) => {
const rawParticipant = rawByPuuid.get(
puuidByUserId.get(participant.userId.toString()) ?? '',
);
return this.toRecord({
match,
game,
participant,
rawParticipant,
buildEvents: rawParticipant
? buildEventsByParticipantId.get(rawParticipant.participantId)
: undefined,
checkpoints: rawParticipant
? checkpointsByParticipantId.get(rawParticipant.participantId)
: undefined,
teamKills,
teamDamage,
});
}),
};
}),
};
}
private toFallbackGameDetail(
match: MatchDocument,
game: NonNullable<MatchDocument['result']>['games'][number],
): InternalGameDetail {
return {
gameNumber: game.gameNumber,
riotMatchId: game.riotMatchId,
gameCreation: game.gameCreation,
gameDuration: game.gameDuration,
winnerSide: game.winnerSide,
timeline: [],
timelineLoaded: false,
objectiveEvents: [],
timelineEvents: [],
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex,
side,
win: game.winnerSide === side,
objectives: emptyObjectives(),
bans: [],
participants: game.participants
.filter((participant) => participant.side === side)
.map((participant) =>
this.toRecord({
match,
game,
participant,
teamKills: 0,
teamDamage: 0,
}),
),
})),
};
}
private toRecord(params: {
match: MatchDocument;
game: NonNullable<MatchDocument['result']>['games'][number];
participant: MatchGameResultParticipant;
rawParticipant?: RiotMatchParticipantDto;
buildEvents?: ParticipantBuildEvents;
checkpoints?: MatchStatsParticipantCheckpoints;
teamKills: number;
teamDamage: number;
}): InternalRecord {
const {
match,
game,
participant,
rawParticipant,
buildEvents,
checkpoints,
teamKills,
teamDamage,
} = params;
const snapshot = match.participants.find((item) =>
item.userId.equals(participant.userId),
);
const minutes = Math.max(
(rawParticipant?.timePlayed ?? game.gameDuration) / 60,
1,
);
const cs = rawParticipant
? rawParticipant.totalMinionsKilled + rawParticipant.neutralMinionsKilled
: 0;
const damage = rawParticipant?.totalDamageDealtToChampions ?? 0;
const killParticipation = percent(
participant.kills + participant.assists,
teamKills,
);
const damageShare = percent(damage, teamDamage);
const rating = this.resolveRating({
kills: participant.kills,
deaths: participant.deaths,
assists: participant.assists,
killParticipation,
csPerMin: average(cs, minutes),
damageShare,
visionPerMin: average(rawParticipant?.visionScore ?? 0, minutes),
});
return {
matchId: match._id.toString(),
title: match.title,
scheduledAt: match.scheduledAt,
gameNumber: game.gameNumber,
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,
championId: participant.championId,
championLevel: rawParticipant?.champLevel ?? 0,
teamPosition:
rawParticipant?.teamPosition ||
rawParticipant?.individualPosition ||
'',
kills: participant.kills,
deaths: participant.deaths,
assists: participant.assists,
win: participant.win,
cs,
csPerMin: average(cs, minutes),
gold: rawParticipant?.goldEarned ?? 0,
gpm: average(rawParticipant?.goldEarned ?? 0, minutes),
damageDealtToChampions: damage,
damageTaken: rawParticipant?.totalDamageTaken ?? 0,
damageShare,
killParticipation,
visionScore: rawParticipant?.visionScore ?? 0,
controlWardsBought: numberField(
rawParticipant,
'visionWardsBoughtInGame',
),
wardsPlaced: rawParticipant?.wardsPlaced ?? 0,
wardsKilled: rawParticipant?.wardsKilled ?? 0,
firstBloodKill: booleanField(rawParticipant, 'firstBloodKill'),
firstBloodAssist: booleanField(rawParticipant, 'firstBloodAssist'),
items: [
rawParticipant?.item0 ?? 0,
rawParticipant?.item1 ?? 0,
rawParticipant?.item2 ?? 0,
rawParticipant?.item3 ?? 0,
rawParticipant?.item4 ?? 0,
rawParticipant?.item5 ?? 0,
],
trinket: rawParticipant?.item6 ?? 0,
summonerSpells: [
rawParticipant?.summoner1Id ?? 0,
rawParticipant?.summoner2Id ?? 0,
],
perks: rawParticipant ? this.resolvePerks(rawParticipant) : {},
itemBuild: buildEvents?.items ?? [],
skillBuild: buildEvents?.skills ?? [],
rating,
};
}
private resolvePerks(participant: RiotMatchParticipantDto) {
const primary = participant.perks.styles.find(
(style) => style.description === 'primaryStyle',
);
const sub = participant.perks.styles.find(
(style) => style.description === 'subStyle',
);
return {
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,
};
}
private resolveRating(params: {
kills: number;
deaths: number;
assists: number;
killParticipation: number;
csPerMin: number;
damageShare: number;
visionPerMin: number;
}): number {
const kdaScore = kda(params.kills, params.deaths, params.assists);
const score =
Math.min(kdaScore / 6, 1) * 4 +
Math.min(params.killParticipation / 100, 1) * 2 +
Math.min(params.csPerMin / 9, 1) * 2 +
Math.min(params.damageShare / 35, 1) +
Math.min(params.visionPerMin / 2, 1);
return round(score);
}
}
function kda(kills: number, deaths: number, assists: number): number {
return deaths === 0 ? kills + assists : round((kills + assists) / deaths);
}
function percent(value: number, total: number): number {
return total > 0 ? Math.round((value / total) * 100) : 0;
}
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;
}
function numberField(
participant: RiotMatchParticipantDto | undefined,
key: string,
): number {
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,
};
}
@@ -1,216 +0,0 @@
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('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'>;
}
@@ -1,254 +0,0 @@
import { Injectable } from '@nestjs/common';
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'
>;
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 upsert(
fragment: Omit<MatchStats, 'createdAt' | 'updatedAt'>,
): Promise<void> {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
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: 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,
guard?: MatchStatsDeleteGuard,
): Promise<void> {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
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(
matchIds: mongoose.Types.ObjectId[],
): Promise<void> {
if (matchIds.length === 0) return;
const MatchStatsModel = await this.connectionService.getModel('matchStats');
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> {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
return MatchStatsModel.findOne({ matchId }).exec();
}
public async findByCommunity(params: {
communityId: mongoose.Types.ObjectId;
fromGameCreation?: number;
toGameCreation?: number;
limit?: number;
}): Promise<MatchStatsDocument[]> {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
const filter: Record<string, unknown> = {
communityId: params.communityId,
};
if (params.fromGameCreation !== undefined) {
filter.gameCreationMax = { $gte: params.fromGameCreation };
}
if (params.toGameCreation !== undefined) {
filter.gameCreationMin = { $lte: params.toGameCreation };
}
return MatchStatsModel.find(filter)
.sort({ scheduledAt: -1 })
.limit(params.limit ?? 300)
.exec();
}
public async findByUser(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
fromGameCreation?: number;
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 })
.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,
};
if (params.fromGameCreation !== undefined) {
filter.gameCreationMax = { $gte: params.fromGameCreation };
}
if (params.toGameCreation !== undefined) {
filter.gameCreationMin = { $lte: params.toGameCreation };
}
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
);
}
@@ -1,630 +0,0 @@
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', () => {
it('deletes an existing fragment when the match is no longer eligible', async () => {
const matchId = new mongoose.Types.ObjectId();
const findById = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({
_id: matchId,
status: 'recruiting',
result: undefined,
}),
});
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') return { findById };
if (name === 'competition') return { findOne: () => queryResult(null) };
if (name === 'riotMatch') return {};
throw new Error(`Unexpected model: ${name}`);
}),
} as unknown as ConnectionService;
const repository = {
deleteByMatch: jest.fn().mockResolvedValue(undefined),
upsert: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
const service = new MatchStatsService(
connectionService,
repository,
{} as MatchStatsFragmentBuilder,
{ getMatchTimeline: jest.fn() } as never,
);
await service.buildAndUpsert(matchId);
expect(repository.deleteByMatch).toHaveBeenCalledWith(matchId);
expect(repository.upsert).not.toHaveBeenCalled();
});
it('revision-guards deletion when a Competition reversal leaves zero games', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const match = {
_id: matchId,
communityId,
scheduledAt: new Date('2026-07-12T10:00:00.000Z'),
status: 'in-progress',
teams: [],
result: undefined,
};
const competition = {
_id: competitionId,
revision: 12,
projectorVersion: 3,
teams: [],
projection: { phase: 'ready', games: [] },
};
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') {
return { findById: () => queryResult(match, false) };
}
if (name === 'competition') {
return { findOne: () => queryResult(competition) };
}
if (name === 'riotMatch') return {};
throw new Error(`Unexpected model: ${name}`);
}),
} as unknown as ConnectionService;
const repository = {
deleteByMatch: jest.fn().mockResolvedValue(undefined),
upsert: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
const service = new MatchStatsService(
connectionService,
repository,
{} as MatchStatsFragmentBuilder,
{ getMatchTimeline: jest.fn() } as never,
);
await service.buildAndUpsert(matchId, { sourceRevision: 12 });
expect(repository.deleteByMatch).toHaveBeenCalledWith(matchId, {
sourceCompetitionId: competitionId,
sourceRevision: 12,
});
expect(repository.upsert).not.toHaveBeenCalled();
});
it('upserts a fragment for eligible matches', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const scheduledAt = new Date('2026-05-03T00:00:00.000Z');
const match = {
_id: matchId,
communityId,
scheduledAt,
status: 'finished',
result: { games: [{ riotMatchId: 'KR_1' }] },
};
const findById = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(match),
});
const riotFind = jest.fn().mockReturnValue({
lean: () => ({
exec: jest.fn().mockResolvedValue([
{
matchId: 'KR_1',
raw: {},
timeline: {
metadata: {
dataVersion: '2',
matchId: 'KR_1',
participants: [],
},
info: { frameInterval: 60_000, frames: [] },
},
},
]),
}),
});
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') return { findById };
if (name === 'competition') return { findOne: () => queryResult(null) };
if (name === 'riotMatch') return { find: riotFind };
throw new Error(`Unexpected model: ${name}`);
}),
} as unknown as ConnectionService;
const repository = {
upsert: jest.fn().mockResolvedValue(undefined),
deleteByMatch: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
const builder = {
buildFragment: jest.fn().mockReturnValue({
matchCard: { matchId: matchId.toString() },
records: [],
gameDetails: [],
userIds: [],
championIds: [],
gameCreationMin: 1_000,
gameCreationMax: 2_000,
}),
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
const service = new MatchStatsService(
connectionService,
repository,
builder,
{ getMatchTimeline: jest.fn() } as never,
);
await service.buildAndUpsert(matchId);
expect(builder.buildFragment).toHaveBeenCalledWith({
match,
rawByRiotMatchId: expect.any(Map),
timelineByRiotMatchId: expect.any(Map),
});
expect(
builder.buildFragment.mock.calls[0][0].timelineByRiotMatchId,
).toHaveProperty('size', 0);
expect(repository.upsert).toHaveBeenCalledWith(
expect.objectContaining({
matchId,
communityId,
scheduledAt,
gameCreationMin: 1_000,
gameCreationMax: 2_000,
builderVersion: MATCH_STATS_BUILDER_VERSION,
}),
);
});
it('retries unusable timeline caches and stores a later usable fetch', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const match = {
_id: matchId,
communityId,
scheduledAt: new Date('2026-05-03T00:00:00.000Z'),
status: 'finished',
result: { games: [{ riotMatchId: 'KR_1' }] },
};
const emptyTimeline = {
info: { frameInterval: 60_000, frames: [] },
};
const partialTimeline = {
info: {
frameInterval: 60_000,
frames: [{ timestamp: 0, events: [] }],
},
};
const nonPositiveTimeline = {
info: {
frameInterval: 0,
frames: [timelineFrame(120_000)],
},
};
const truncatedTimeline = {
info: {
frameInterval: 60_000,
frames: [timelineFrame()],
},
};
const usableTimeline = {
metadata: {
dataVersion: '2',
matchId: 'KR_1',
participants: ['puuid-1'],
},
info: {
frameInterval: 60_000,
frames: [timelineFrame(120_000)],
},
};
const cachedTimelines = [
emptyTimeline,
partialTimeline,
nonPositiveTimeline,
truncatedTimeline,
];
let buildIndex = 0;
const riotFind = jest.fn().mockImplementation(() => ({
lean: () => ({
exec: jest.fn().mockResolvedValue([
{
matchId: 'KR_1',
raw: { info: { gameDuration: 120 } },
timeline: cachedTimelines[Math.min(buildIndex++, 3)],
},
]),
}),
}));
const updateExec = jest.fn().mockResolvedValue(undefined);
let storedUpdate:
| {
filter: unknown;
update: { $set: { timeline: unknown; timelineFetchedAt: Date } };
}
| undefined;
const updateOne = jest.fn(
(
filter: unknown,
update: { $set: { timeline: unknown; timelineFetchedAt: Date } },
) => {
storedUpdate = { filter, update };
return { exec: updateExec };
},
);
const connectionService = {
getModel: jest.fn().mockImplementation((name: string) => {
if (name === 'match') {
return Promise.resolve({ findById: () => queryResult(match, false) });
}
if (name === 'competition') {
return Promise.resolve({ findOne: () => queryResult(null) });
}
if (name === 'riotMatch') {
return Promise.resolve({ find: riotFind, updateOne });
}
if (name === 'community') {
return Promise.resolve({
findById: () => ({
select: () => queryResult({ riotRegion: 'asia' }),
}),
});
}
return Promise.reject(new Error(`Unexpected model: ${name}`));
}),
} as unknown as ConnectionService;
const repository = {
upsert: jest.fn().mockResolvedValue(undefined),
deleteByMatch: jest.fn(),
deleteLegacyByMatch: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
type BuildParams = Parameters<
MatchStatsFragmentBuilder['buildFragment']
>[0];
const buildCalls: BuildParams[] = [];
const builtFragment = {
matchCard: { matchId: matchId.toString() },
records: [],
gameDetails: [],
userIds: [],
championIds: [],
gameCreationMin: 1_000,
gameCreationMax: 2_000,
} as ReturnType<MatchStatsFragmentBuilder['buildFragment']>;
const buildFragment = jest.fn((params: BuildParams) => {
buildCalls.push(params);
return builtFragment;
});
const builder = {
buildFragment,
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
const getMatchTimeline = jest
.fn()
.mockRejectedValueOnce(new Error('temporary Riot failure'))
.mockRejectedValueOnce(new Error('temporary Riot failure'))
.mockRejectedValueOnce(new Error('temporary Riot failure'))
.mockResolvedValueOnce(usableTimeline);
const service = new MatchStatsService(
connectionService,
repository,
builder,
{ getMatchTimeline } as never,
);
await service.buildAndUpsert(matchId, { includeTimeline: true });
await service.buildAndUpsert(matchId, { includeTimeline: true });
await service.buildAndUpsert(matchId, { includeTimeline: true });
await service.buildAndUpsert(matchId, { includeTimeline: true });
expect(getMatchTimeline).toHaveBeenCalledTimes(4);
expect(buildFragment).toHaveBeenCalledTimes(4);
expect(buildCalls[0].timelineByRiotMatchId).toHaveProperty('size', 0);
expect(buildCalls[1].timelineByRiotMatchId).toHaveProperty('size', 0);
expect(buildCalls[2].timelineByRiotMatchId?.get('KR_1')).toBeUndefined();
expect(buildCalls[3].timelineByRiotMatchId?.get('KR_1')).toBe(
usableTimeline,
);
for (const call of buildCalls) {
expect(call).not.toHaveProperty('timelineLoadAttempted');
}
expect(updateOne).toHaveBeenCalledTimes(1);
expect(storedUpdate?.filter).toEqual({ matchId: 'KR_1' });
expect(storedUpdate?.update.$set.timeline).toBe(usableTimeline);
expect(storedUpdate?.update.$set.timelineFetchedAt).toBeInstanceOf(Date);
expect(updateExec).toHaveBeenCalledTimes(1);
});
it('builds from the Competition projection and records its source revision', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const teamAId = new mongoose.Types.ObjectId();
const teamBId = new mongoose.Types.ObjectId();
const userAId = new mongoose.Types.ObjectId();
const userBId = new mongoose.Types.ObjectId();
const match = {
_id: matchId,
communityId,
scheduledAt: new Date('2026-07-12T10:00:00.000Z'),
status: 'in-progress',
teams: [],
result: { games: [{ riotMatchId: 'KR_LEGACY_MUST_NOT_BE_USED' }] },
};
const competition = {
_id: competitionId,
revision: 12,
projectorVersion: 3,
teams: [
{ teamId: teamAId, legacyTeamIndex: 8, displayOrder: 1 },
{ teamId: teamBId, legacyTeamIndex: 3, displayOrder: 2 },
],
projection: {
phase: 'running',
games: [
{
displayNumber: 4,
evidence: { type: 'riot', riotMatchId: 'KR_COMPETITION' },
teams: {
blue: { teamId: teamAId.toString() },
red: { teamId: teamBId.toString() },
},
winnerTeamId: teamAId.toString(),
startedAt: '2026-07-12T10:00:00.000Z',
durationSeconds: 1800,
participants: [
participant(userAId, teamAId, 'blue', true),
participant(userBId, teamBId, 'red', false),
],
},
],
},
};
const riotFind = jest.fn().mockReturnValue({
lean: () => ({
exec: jest
.fn()
.mockResolvedValue([{ matchId: 'KR_COMPETITION', raw: {} }]),
}),
});
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match')
return { findById: () => queryResult(match, false) };
if (name === 'competition') {
return { findOne: () => queryResult(competition) };
}
if (name === 'riotMatch') return { find: riotFind };
throw new Error(`Unexpected model: ${name}`);
}),
} as unknown as ConnectionService;
const repository = {
upsert: jest.fn().mockResolvedValue(undefined),
deleteByMatch: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
const builder = {
buildFragment: jest.fn().mockReturnValue({
matchCard: {},
records: [],
gameDetails: [],
userIds: [],
championIds: [],
gameCreationMin: 1,
gameCreationMax: 2,
}),
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
const service = new MatchStatsService(
connectionService,
repository,
builder,
{ getMatchTimeline: jest.fn() } as never,
);
await service.buildAndUpsert(matchId, { sourceRevision: 12 });
expect(riotFind).toHaveBeenCalledWith({
matchId: { $in: ['KR_COMPETITION'] },
});
expect(builder.buildFragment).toHaveBeenCalledWith(
expect.objectContaining({
match: expect.objectContaining({
result: expect.objectContaining({
riotMatchIds: ['KR_COMPETITION'],
games: [
expect.objectContaining({
gameNumber: 4,
blueTeamIndex: 8,
redTeamIndex: 3,
winnerTeamIndex: 8,
}),
],
}),
}),
}),
);
expect(repository.upsert).toHaveBeenCalledWith(
expect.objectContaining({
sourceCompetitionId: competitionId,
sourceRevision: 12,
projectorVersion: 3,
}),
);
});
it('removes a fragment written after its Competition Match was deleted', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = 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,
scheduledAt: new Date('2026-07-12T10:00:00.000Z'),
status: 'in-progress',
teams: [],
result: undefined,
};
const competition = {
_id: competitionId,
revision: 12,
projectorVersion: 3,
teams: [
{ teamId: teamAId, legacyTeamIndex: 1, displayOrder: 1 },
{ teamId: teamBId, legacyTeamIndex: 2, displayOrder: 2 },
],
projection: {
phase: 'running',
games: [
{
id: new mongoose.Types.ObjectId(),
displayNumber: 1,
evidence: { type: 'legacy', legacyReference: 'legacy:1' },
teams: {
blue: { teamId: teamAId.toString() },
red: { teamId: teamBId.toString() },
},
winnerTeamId: teamAId.toString(),
},
],
},
};
const findById = jest
.fn()
.mockReturnValueOnce(queryResult(match, false))
.mockReturnValueOnce(queryResult(null, false));
const findCompetition = jest.fn().mockReturnValue(queryResult(competition));
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') return { findById };
if (name === 'competition') return { findOne: findCompetition };
if (name === 'riotMatch') return {};
throw new Error(`Unexpected model: ${name}`);
}),
} as unknown as ConnectionService;
const repository = {
upsert: jest.fn().mockResolvedValue(undefined),
deleteByMatch: jest.fn().mockResolvedValue(undefined),
deleteLegacyByMatch: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
const builder = {
buildFragment: jest.fn().mockReturnValue({
matchCard: {},
records: [],
gameDetails: [],
userIds: [],
championIds: [],
gameCreationMin: 1,
gameCreationMax: 2,
}),
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
const service = new MatchStatsService(
connectionService,
repository,
builder,
{ getMatchTimeline: jest.fn() } as never,
);
await service.buildAndUpsert(matchId, { sourceRevision: 12 });
expect(repository.upsert).toHaveBeenCalled();
expect(repository.deleteByMatch).toHaveBeenCalledWith(matchId, {
sourceCompetitionId: competitionId,
sourceRevision: 12,
});
expect(repository.upsert.mock.invocationCallOrder[0]).toBeLessThan(
repository.deleteByMatch.mock.invocationCallOrder[0],
);
});
it('does not rebuild before the requested Competition revision is visible', async () => {
const matchId = new mongoose.Types.ObjectId();
const riotFind = jest.fn();
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') {
return {
findById: () =>
queryResult(
{
_id: matchId,
status: 'in-progress',
},
false,
),
};
}
if (name === 'competition') {
return {
findOne: () => queryResult({ revision: 11 }),
};
}
if (name === 'riotMatch') return { find: riotFind };
throw new Error(`Unexpected model: ${name}`);
}),
} as unknown as ConnectionService;
const repository = {
upsert: jest.fn(),
deleteByMatch: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
const builder = {
buildFragment: jest.fn(),
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
const service = new MatchStatsService(
connectionService,
repository,
builder,
{ getMatchTimeline: jest.fn() } as never,
);
await service.buildAndUpsert(matchId, { sourceRevision: 12 });
expect(riotFind).not.toHaveBeenCalled();
expect(builder.buildFragment).not.toHaveBeenCalled();
expect(repository.upsert).not.toHaveBeenCalled();
expect(repository.deleteByMatch).not.toHaveBeenCalled();
});
});
function participant(
userId: mongoose.Types.ObjectId,
teamId: mongoose.Types.ObjectId,
side: 'blue' | 'red',
win: boolean,
) {
return {
userId: userId.toString(),
teamId: teamId.toString(),
side,
summonerName: 'player',
tagLine: 'KR1',
championId: 1,
kills: 1,
deaths: 1,
assists: 1,
win,
};
}
function queryResult<T>(value: T, lean = true) {
const query = {
lean: jest.fn(),
exec: jest.fn().mockResolvedValue(value),
};
query.lean.mockReturnValue(query);
return lean ? query : { exec: query.exec };
}
function timelineFrame(timestamp = 0) {
return {
timestamp,
events: [],
participantFrames: {
'1': {
participantId: 1,
totalGold: 500,
xp: 0,
minionsKilled: 0,
jungleMinionsKilled: 0,
},
},
};
}
@@ -1,474 +0,0 @@
import { Injectable, Logger } from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type { MatchDocument } from '../global/database/schema';
import { RiotMatchService } from '../riot/riot-match.service';
import {
RIOT_REGIONAL_ROUTES,
type RiotMatchDto,
type RiotMatchTimelineDto,
type RiotRegionalRoute,
} from '../riot/riot.types';
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
import { MatchStatsRepository } from './match-stats.repository';
import { MATCH_STATS_BUILDER_VERSION } from './match-stats.types';
@Injectable()
export class MatchStatsService {
private readonly logger = new Logger(MatchStatsService.name);
constructor(
private readonly connectionService: ConnectionService,
private readonly repository: MatchStatsRepository,
private readonly builder: MatchStatsFragmentBuilder,
private readonly riotMatchService: RiotMatchService,
) {}
public async buildAndUpsert(
matchId: mongoose.Types.ObjectId,
options: { includeTimeline?: boolean; sourceRevision?: number } = {},
): Promise<void> {
const MatchModel = await this.connectionService.getModel('match');
const CompetitionModel =
await this.connectionService.getModel('competition');
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const match = await MatchModel.findById(matchId).exec();
if (!match) return;
const competition = await CompetitionModel.findOne({ matchId })
.lean()
.exec();
if (
options.sourceRevision !== undefined &&
(!competition || competition.revision < options.sourceRevision)
) {
return;
}
const competitionSource = competition
? competitionStatsSource(match, competition)
: undefined;
const sourceMatch = competitionSource?.match ?? match;
if (!this.isEligible(sourceMatch)) {
if (competitionSource) {
await this.repository.deleteByMatch(matchId, {
sourceCompetitionId: competitionSource.sourceCompetitionId,
sourceRevision: competitionSource.sourceRevision,
});
} else {
await this.repository.deleteByMatch(matchId);
}
return;
}
const riotIds = competitionSource?.riotMatchIds ?? [
...new Set(
(match.result?.games ?? [])
.map((game) => game.riotMatchId)
.filter((riotMatchId): riotMatchId is string => Boolean(riotMatchId)),
),
];
const riotDocs =
riotIds.length > 0
? await RiotMatchModel.find({ matchId: { $in: riotIds } })
.lean()
.exec()
: [];
const rawByRiotMatchId = new Map(
riotDocs.map((doc) => [doc.matchId, doc.raw as unknown as RiotMatchDto]),
);
const timelineByRiotMatchId = new Map<string, RiotMatchTimelineDto>();
for (const doc of riotDocs) {
if (isUsableRiotMatchTimeline(doc.timeline, doc.raw)) {
timelineByRiotMatchId.set(doc.matchId, doc.timeline);
}
}
if (
options.includeTimeline &&
riotDocs.length > 0 &&
timelineByRiotMatchId.size < riotDocs.length
) {
const region = await this.resolveRiotRegion(match.communityId);
for (const doc of riotDocs) {
if (timelineByRiotMatchId.has(doc.matchId)) continue;
try {
const timeline = await this.riotMatchService.getMatchTimeline(
doc.matchId,
{ region },
);
if (!isUsableRiotMatchTimeline(timeline, doc.raw)) {
this.logger.warn(
`Ignored unusable match timeline for ${doc.matchId}.`,
);
continue;
}
await RiotMatchModel.updateOne(
{ matchId: doc.matchId },
{
$set: {
timeline: timeline as unknown as Record<string, unknown>,
timelineFetchedAt: new Date(),
},
},
).exec();
timelineByRiotMatchId.set(doc.matchId, timeline);
} catch (error) {
this.logger.warn(
`Failed to fetch match timeline for ${doc.matchId}: ${
error instanceof Error ? error.message : error
}`,
);
}
}
}
const fragment = this.builder.buildFragment({
match: sourceMatch,
rawByRiotMatchId,
timelineByRiotMatchId,
});
await this.repository.upsert({
matchId: match._id,
communityId: match.communityId,
scheduledAt: match.scheduledAt,
gameCreationMin: fragment.gameCreationMin,
gameCreationMax: fragment.gameCreationMax,
userIds: fragment.userIds,
championIds: fragment.championIds,
matchCard: fragment.matchCard as unknown as Record<string, unknown>,
records: fragment.records,
gameDetails: fragment.gameDetails,
builtAt: new Date(),
builderVersion: MATCH_STATS_BUILDER_VERSION,
...(competitionSource
? {
sourceCompetitionId: competitionSource.sourceCompetitionId,
sourceRevision: competitionSource.sourceRevision,
projectorVersion: competitionSource.projectorVersion,
}
: {}),
});
// Source reads and the read-model write are intentionally separated by
// Riot/timeline work. Revalidate after the write so a concurrent aggregate
// deletion cannot resurrect MatchStats after the delete transaction.
await this.removeFragmentIfSourceChanged(matchId, competitionSource);
}
public async removeByMatch(matchId: mongoose.Types.ObjectId): Promise<void> {
await this.repository.deleteByMatch(matchId);
}
public async removeByMatches(
matchIds: mongoose.Types.ObjectId[],
): Promise<void> {
await this.repository.deleteByMatches(matchIds);
}
public async backfillCommunity(
communityId: mongoose.Types.ObjectId,
): Promise<{ processed: number; failed: number }> {
const MatchModel = await this.connectionService.getModel('match');
const matches = await MatchModel.find({
communityId,
status: { $in: ['finished', 'in-progress'] },
$or: [
{ competitionId: { $exists: true } },
{ 'result.games.0': { $exists: true } },
],
})
.sort({ scheduledAt: -1 })
.select({ _id: 1 })
.exec();
let processed = 0;
let failed = 0;
for (const match of matches) {
try {
await this.buildAndUpsert(match._id);
processed += 1;
} catch {
failed += 1;
}
}
return { processed, failed };
}
private isEligible(match: MatchDocument): boolean {
return (
(match.status === 'finished' || match.status === 'in-progress') &&
Boolean(match.result?.games?.length)
);
}
private async resolveRiotRegion(
communityId: mongoose.Types.ObjectId,
): Promise<RiotRegionalRoute> {
const CommunityModel = await this.connectionService.getModel('community');
const community = await CommunityModel.findById(communityId)
.select({ riotRegion: 1 })
.lean()
.exec();
const region = community?.riotRegion;
return RIOT_REGIONAL_ROUTES.includes(region as RiotRegionalRoute)
? (region as RiotRegionalRoute)
: 'asia';
}
private async removeFragmentIfSourceChanged(
matchId: mongoose.Types.ObjectId,
source:
| {
sourceCompetitionId: mongoose.Types.ObjectId;
sourceRevision: number;
}
| undefined,
): Promise<void> {
const [MatchModel, CompetitionModel] = await Promise.all([
this.connectionService.getModel('match'),
this.connectionService.getModel('competition'),
]);
const [currentMatch, currentCompetition] = await Promise.all([
MatchModel.findById(matchId).exec(),
CompetitionModel.findOne({
matchId,
...(source
? {
_id: source.sourceCompetitionId,
revision: source.sourceRevision,
}
: {}),
})
.lean()
.exec(),
]);
if (source) {
if (!currentMatch || !currentCompetition) {
await this.repository.deleteByMatch(matchId, {
sourceCompetitionId: source.sourceCompetitionId,
sourceRevision: source.sourceRevision,
});
}
return;
}
if (!currentMatch || currentCompetition) {
await this.repository.deleteLegacyByMatch(matchId);
}
}
}
function isUsableRiotMatchTimeline(
value: unknown,
rawMatch: unknown,
): value is RiotMatchTimelineDto {
if (
!isRecord(value) ||
!isRecord(value.info) ||
!isRecord(rawMatch) ||
!isRecord(rawMatch.info)
) {
return false;
}
const frameInterval = finiteNumber(value.info.frameInterval);
const gameDuration = finiteNumber(rawMatch.info.gameDuration);
const frames = value.info.frames;
if (
frameInterval === undefined ||
frameInterval <= 0 ||
gameDuration === undefined ||
gameDuration < 0 ||
!Array.isArray(frames) ||
frames.length === 0 ||
!frames.every(isUsableTimelineFrame)
) {
return false;
}
const lastTimestamp = Math.max(
...frames.map((frame) => (frame as { timestamp: number }).timestamp),
);
return Math.abs(gameDuration * 1_000 - lastTimestamp) < frameInterval;
}
function isUsableTimelineFrame(value: unknown): boolean {
if (
!isRecord(value) ||
finiteNumber(value.timestamp) === undefined ||
!Array.isArray(value.events) ||
!value.events.every(
(event) =>
isRecord(event) &&
typeof event.type === 'string' &&
finiteNumber(event.timestamp) !== undefined,
) ||
!isRecord(value.participantFrames)
) {
return false;
}
const participantFrames = Object.values(value.participantFrames);
return (
participantFrames.length > 0 &&
participantFrames.every(
(participantFrame) =>
isRecord(participantFrame) &&
finiteNumber(participantFrame.participantId) !== undefined &&
finiteNumber(participantFrame.totalGold) !== undefined &&
finiteNumber(participantFrame.xp) !== undefined,
)
);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
function competitionStatsSource(
match: MatchDocument,
competition: {
_id: mongoose.Types.ObjectId;
revision: number;
projectorVersion: number;
teams: unknown[];
projection: Record<string, unknown>;
},
): {
match: MatchDocument;
riotMatchIds: string[];
sourceCompetitionId: mongoose.Types.ObjectId;
sourceRevision: number;
projectorVersion: number;
} {
const teamIndexById = new Map<string, number>();
for (const rawTeam of competition.teams) {
if (!isRecord(rawTeam)) continue;
const teamId = identifier(rawTeam.teamId);
const legacyTeamIndex = finiteNumber(rawTeam.legacyTeamIndex);
const displayOrder = finiteNumber(rawTeam.displayOrder);
if (teamId && (legacyTeamIndex ?? displayOrder)) {
teamIndexById.set(teamId, legacyTeamIndex ?? displayOrder!);
}
}
const rawGames = Array.isArray(competition.projection.games)
? competition.projection.games
: [];
const riotMatchIds = new Set<string>();
const games = rawGames.flatMap((rawGame, gameIndex) => {
if (!isRecord(rawGame)) return [];
const teams = isRecord(rawGame.teams) ? rawGame.teams : undefined;
const blue = teams && isRecord(teams.blue) ? teams.blue : undefined;
const red = teams && isRecord(teams.red) ? teams.red : undefined;
const blueTeamId = identifier(blue?.teamId);
const redTeamId = identifier(red?.teamId);
const winnerTeamId = identifier(rawGame.winnerTeamId);
const blueTeamIndex = blueTeamId
? teamIndexById.get(blueTeamId)
: undefined;
const redTeamIndex = redTeamId ? teamIndexById.get(redTeamId) : undefined;
const winnerTeamIndex = winnerTeamId
? teamIndexById.get(winnerTeamId)
: undefined;
if (!blueTeamIndex || !redTeamIndex || !winnerTeamIndex) return [];
const evidence = isRecord(rawGame.evidence) ? rawGame.evidence : undefined;
const riotMatchId =
evidence?.type === 'riot' && typeof evidence.riotMatchId === 'string'
? evidence.riotMatchId
: typeof evidence?.legacyReference === 'string'
? evidence.legacyReference
: `competition:${identifier(rawGame.id) ?? 'game'}`;
if (evidence?.type === 'riot') riotMatchIds.add(riotMatchId);
const participantValues = Array.isArray(rawGame.participants)
? rawGame.participants
: [];
const participants = participantValues.flatMap((rawParticipant) => {
if (!isRecord(rawParticipant)) return [];
const userId = identifier(rawParticipant.userId);
const teamId = identifier(rawParticipant.teamId);
const teamIndex = teamId ? teamIndexById.get(teamId) : undefined;
const side = rawParticipant.side;
if (
!userId ||
!mongoose.isValidObjectId(userId) ||
!teamIndex ||
(side !== 'blue' && side !== 'red')
) {
return [];
}
return [
{
userId: new mongoose.Types.ObjectId(userId),
teamIndex,
side,
championId: finiteNumber(rawParticipant.championId) ?? 0,
kills: finiteNumber(rawParticipant.kills) ?? 0,
deaths: finiteNumber(rawParticipant.deaths) ?? 0,
assists: finiteNumber(rawParticipant.assists) ?? 0,
win: teamId === winnerTeamId,
},
];
});
const startedAt = dateFromUnknown(rawGame.startedAt);
return [
{
gameNumber: finiteNumber(rawGame.displayNumber) ?? gameIndex + 1,
riotMatchId,
blueTeamIndex,
redTeamIndex,
winnerTeamIndex,
winnerSide:
winnerTeamIndex === blueTeamIndex
? ('blue' as const)
: ('red' as const),
gameCreation: Number.isNaN(startedAt.getTime())
? 0
: startedAt.getTime(),
gameDuration: finiteNumber(rawGame.durationSeconds) ?? 0,
participants,
},
];
});
const base =
typeof match.toObject === 'function' ? match.toObject() : { ...match };
return {
match: {
...base,
status:
competition.projection.phase === 'completed'
? 'finished'
: games.length > 0
? 'in-progress'
: match.status,
result: {
riotMatchIds: games.map(({ riotMatchId }) => riotMatchId),
games,
seriesResults: [],
},
} as unknown as MatchDocument,
riotMatchIds: [...riotMatchIds],
sourceCompetitionId: competition._id,
sourceRevision: competition.revision,
projectorVersion: competition.projectorVersion,
};
}
function identifier(value: unknown): string | undefined {
if (typeof value === 'string' && value.length > 0) return value;
if (value instanceof mongoose.Types.ObjectId) return value.toHexString();
return undefined;
}
function dateFromUnknown(value: unknown): Date {
if (value instanceof Date) return new Date(value.getTime());
if (typeof value === 'string' || typeof value === 'number') {
return new Date(value);
}
return new Date(Number.NaN);
}
function finiteNumber(value: unknown): number | undefined {
return typeof value === 'number' && Number.isFinite(value)
? value
: undefined;
}
@@ -1,20 +0,0 @@
import type {
MatchStatsGameDetail,
MatchStatsRecord,
} from '../global/database/schema';
import type { InternalMatchCardView } from './community-stats.types';
export const MATCH_STATS_BUILDER_VERSION = 10;
export type InternalRecord = MatchStatsRecord;
export type InternalGameDetail = MatchStatsGameDetail;
export interface MatchStatsFragment {
matchCard: InternalMatchCardView;
records: InternalRecord[];
gameDetails: InternalGameDetail[];
userIds: import('mongoose').Types.ObjectId[];
championIds: number[];
gameCreationMin: number;
gameCreationMax: number;
}
@@ -6,7 +6,10 @@ import {
} from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { CommunityDocument, UserDocument } from '../global/database/schema';
import {
CommunityDocument,
UserDocument,
} from '../global/database/schema';
export interface CreateCommunityInput {
name: string;
@@ -1,537 +0,0 @@
import { Types } from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import {
CompetitionBootstrapError,
CompetitionBootstrapService,
type CompetitionBootstrapMatch,
} from './competition-bootstrap.service';
describe('CompetitionBootstrapService', () => {
it('creates a deterministic paired-Series Competition and immutable snapshots', async () => {
const firstHarness = createHarness();
const firstService = new CompetitionBootstrapService(
firstHarness.connectionService as ConnectionService,
);
const match = matchSnapshot({ gameMode: 'pair', teamCount: 2 });
const first = await firstService.bootstrap(match);
const inserted = firstHarness.insertedPayloads[0];
expect(inserted).toMatchObject({
_id: expect.any(Types.ObjectId),
matchId: MATCH_ID,
communityId: COMMUNITY_ID,
schemaVersion: 1,
projectorVersion: 1,
revision: 0,
phase: 'ready',
format: {
type: 'paired-series',
rule: { type: 'fixed-games', gameCount: 3, drawPolicy: 'allow' },
},
});
expect(inserted.teams).toEqual([
expect.objectContaining({
teamId: expect.any(Types.ObjectId),
legacyTeamIndex: 1,
displayOrder: 1,
seedNumber: 1,
name: 'Team 1',
members: [
expect.objectContaining({
userId: USER_IDS[0],
displayName: 'Player 1#KR1',
gameName: 'Player 1',
tagLine: 'KR1',
profileIconId: 101,
assignedPosition: 'TOP',
cost: 10,
}),
],
}),
expect.objectContaining({
teamId: expect.any(Types.ObjectId),
legacyTeamIndex: 2,
displayOrder: 2,
seedNumber: 2,
name: 'Team 2',
}),
]);
expect(inserted.seriesGraph).toHaveLength(1);
expect(inserted.seriesGraph[0]).toMatchObject({
code: 'PAIR_M1',
slots: [
{
position: 'A',
source: {
type: 'team',
teamId: inserted.teams[0].teamId.toString(),
},
},
{
position: 'B',
source: {
type: 'team',
teamId: inserted.teams[1].teamId.toString(),
},
},
],
});
expect(inserted.projection).toMatchObject({
competitionId: inserted._id.toString(),
sourceRevision: 0,
projectorVersion: 1,
formatType: 'paired-series',
phase: 'ready',
});
expect(first._id).toEqual(inserted._id);
const secondHarness = createHarness();
const secondService = new CompetitionBootstrapService(
secondHarness.connectionService as ConnectionService,
);
await secondService.bootstrap({
...match,
teams: [...match.teams].reverse(),
participants: [...match.participants].reverse(),
});
const secondInserted = secondHarness.insertedPayloads[0];
expect(secondInserted._id).toEqual(inserted._id);
expect(secondInserted.teams.map(({ teamId }) => teamId)).toEqual(
inserted.teams.map(({ teamId }) => teamId),
);
expect(secondInserted.seriesGraph).toEqual(inserted.seriesGraph);
});
it('maps round-robin configuration and preserves a limited round count', async () => {
const harness = createHarness();
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
await service.bootstrap(
matchSnapshot({
gameMode: 'round-robin',
teamCount: 4,
gameCount: 2,
roundRobinMaxRounds: 2,
}),
);
expect(harness.insertedPayloads[0]).toMatchObject({
format: {
type: 'round-robin',
rule: { type: 'fixed-games', gameCount: 2, drawPolicy: 'allow' },
maxRounds: 2,
tieBreakers: ['series-wins', 'game-diff', 'head-to-head'],
},
});
expect(harness.insertedPayloads[0].seriesGraph).toHaveLength(4);
});
it('maps double elimination seeds and stage-specific Series rules', async () => {
const harness = createHarness();
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
const match = matchSnapshot({
gameMode: 'double-elimination',
teamCount: 4,
gameCount: 5,
});
match.doubleElimination = {
teamCount: 4,
resetFinalEnabled: true,
seeds: [
{ seedNumber: 1, teamIndex: 3 },
{ seedNumber: 2, teamIndex: 1 },
{ seedNumber: 3, teamIndex: 4 },
{ seedNumber: 4, teamIndex: 2 },
],
};
await service.bootstrap(match);
const inserted = harness.insertedPayloads[0];
expect(inserted.format).toEqual({
type: 'double-elimination',
teamCount: 4,
resetFinalEnabled: true,
rules: {
upper: { type: 'first-to', winsRequired: 3, maxGames: 5 },
lower: { type: 'first-to', winsRequired: 1, maxGames: 1 },
grandFinal: { type: 'first-to', winsRequired: 1, maxGames: 1 },
resetFinal: { type: 'first-to', winsRequired: 1, maxGames: 1 },
},
});
expect(
inserted.teams.map(({ legacyTeamIndex, seedNumber }) => ({
legacyTeamIndex,
seedNumber,
})),
).toEqual([
{ legacyTeamIndex: 1, seedNumber: 2 },
{ legacyTeamIndex: 2, seedNumber: 4 },
{ legacyTeamIndex: 3, seedNumber: 1 },
{ legacyTeamIndex: 4, seedNumber: 3 },
]);
expect(
inserted.seriesGraph.find(({ code }) => code === 'WB_R1_M1').rule,
).toEqual({ type: 'first-to', winsRequired: 3, maxGames: 5 });
expect(
inserted.seriesGraph.find(({ code }) => code?.startsWith('LB_')).rule,
).toEqual({ type: 'first-to', winsRequired: 1, maxGames: 1 });
expect(inserted.seriesGraph.find(({ code }) => code === 'GF').rule).toEqual(
{ type: 'first-to', winsRequired: 1, maxGames: 1 },
);
expect(
inserted.seriesGraph.find(({ code }) => code === 'GF_RESET'),
).toMatchObject({
rule: { type: 'first-to', winsRequired: 1, maxGames: 1 },
activation: { type: 'grand-final-reset-required' },
});
});
it('rejects double elimination until authoritative seeds are persisted', async () => {
const harness = createHarness();
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
await expect(
service.bootstrap(
matchSnapshot({
gameMode: 'double-elimination',
teamCount: 4,
gameCount: 3,
}),
),
).rejects.toMatchObject({
code: 'INVALID_MATCH_TEAM_SNAPSHOT',
httpStatus: 422,
});
expect(harness.connectionService.createSession).not.toHaveBeenCalled();
expect(harness.competitionModel.findOneAndUpdate).not.toHaveBeenCalled();
});
it('rejects incomplete and duplicate team assignments before opening a transaction', async () => {
const cases: Array<[string, (match: CompetitionBootstrapMatch) => void]> = [
[
'the Match lifecycle is still recruiting',
(match) => {
match.status = 'recruiting';
},
],
[
'an active participant is not assigned',
(match) => {
match.teams[1].members = [];
},
],
[
'the same team index is repeated',
(match) => {
match.teams[1].teamIndex = match.teams[0].teamIndex;
},
],
[
'one member is assigned to multiple teams',
(match) => {
match.teams[1].members[0].userId = match.teams[0].members[0].userId;
},
],
[
'a team member has no participant snapshot',
(match) => {
match.teams[1].members[0].userId = new Types.ObjectId();
},
],
];
for (const [label, mutate] of cases) {
const harness = createHarness();
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
const match = matchSnapshot({ gameMode: 'pair', teamCount: 2 });
mutate(match);
await expect(service.bootstrap(match)).rejects.toMatchObject({
name: 'CompetitionBootstrapError',
code: 'INVALID_MATCH_TEAM_SNAPSHOT',
httpStatus: 422,
});
expect(harness.connectionService.createSession).not.toHaveBeenCalled();
expect(harness.competitionModel.findOneAndUpdate).not.toHaveBeenCalled();
expect(label).toBeTruthy();
}
});
it('rejects bracket mode live but explicitly maps it for legacy migration', async () => {
const liveHarness = createHarness();
const liveService = new CompetitionBootstrapService(
liveHarness.connectionService as ConnectionService,
);
const match = matchSnapshot({ gameMode: 'bracket', teamCount: 2 });
await expect(liveService.bootstrap(match)).rejects.toEqual(
expect.objectContaining<Partial<CompetitionBootstrapError>>({
code: 'UNSUPPORTED_LIVE_MATCH_MODE',
httpStatus: 422,
}),
);
const migrationHarness = createHarness();
const migrationService = new CompetitionBootstrapService(
migrationHarness.connectionService as ConnectionService,
);
await migrationService.bootstrap(match, { source: 'legacy-migration' });
expect(migrationHarness.insertedPayloads[0].format.type).toBe(
'paired-series',
);
});
it('upserts once and links only an unlinked or already-linked Match in one transaction', async () => {
const harness = createHarness();
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
const competition = await service.bootstrap(
matchSnapshot({ gameMode: 'pair', teamCount: 2 }),
);
expect(harness.competitionModel.findOneAndUpdate).toHaveBeenCalledWith(
{ matchId: MATCH_ID },
{ $setOnInsert: harness.insertedPayloads[0] },
expect.objectContaining({
upsert: true,
returnDocument: 'after',
setDefaultsOnInsert: true,
session: harness.sessions[0],
}),
);
expect(harness.matchModel.updateOne).toHaveBeenCalledWith(
{
_id: MATCH_ID,
status: 'team-built',
teamBuiltAt: new Date('2026-07-12T00:05:00.000Z'),
$or: [
{ competitionId: { $exists: false } },
{ competitionId: null },
{ competitionId: competition._id },
],
},
{ $set: { competitionId: competition._id } },
{ session: harness.sessions[0] },
);
expect(harness.sessions[0].commitTransaction).toHaveBeenCalledTimes(1);
expect(harness.sessions[0].abortTransaction).not.toHaveBeenCalled();
expect(harness.sessions[0].endSession).toHaveBeenCalledTimes(1);
});
it('reuses an existing Competition without replacing its immutable snapshot', async () => {
const existingId = new Types.ObjectId('64b000000000000000000099');
const existing = {
_id: existingId,
matchId: MATCH_ID,
teams: [{ name: 'Original immutable team snapshot' }],
revision: 4,
};
const harness = createHarness({ existingCompetition: existing });
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
const result = await service.bootstrap(
matchSnapshot({ gameMode: 'pair', teamCount: 2 }),
);
expect(result).toBe(existing);
expect(harness.competitionModel.findOneAndUpdate.mock.calls[0][1]).toEqual({
$setOnInsert: harness.insertedPayloads[0],
});
expect(harness.matchModel.updateOne.mock.calls[0][1]).toEqual({
$set: { competitionId: existingId },
});
});
it('retries a duplicate-key bootstrap race and safely converges on the winner', async () => {
const duplicateKey = Object.assign(new Error('duplicate key'), {
code: 11000,
});
const winner = {
_id: new Types.ObjectId('64b000000000000000000098'),
matchId: MATCH_ID,
revision: 0,
};
const harness = createHarness({
competitionResults: [duplicateKey, winner],
sessionCount: 2,
});
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
const result = await service.bootstrap(
matchSnapshot({ gameMode: 'pair', teamCount: 2 }),
);
expect(result).toBe(winner);
expect(harness.connectionService.createSession).toHaveBeenCalledTimes(2);
expect(harness.sessions[0].abortTransaction).toHaveBeenCalledTimes(1);
expect(harness.sessions[0].commitTransaction).not.toHaveBeenCalled();
expect(harness.sessions[0].endSession).toHaveBeenCalledTimes(1);
expect(harness.sessions[1].commitTransaction).toHaveBeenCalledTimes(1);
expect(harness.matchModel.updateOne).toHaveBeenCalledTimes(1);
});
it('aborts when the Match is already linked to a different Competition', async () => {
const harness = createHarness({ matchUpdateResult: { matchedCount: 0 } });
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
await expect(
service.bootstrap(matchSnapshot({ gameMode: 'pair', teamCount: 2 })),
).rejects.toMatchObject({
code: 'MATCH_COMPETITION_LINK_CONFLICT',
httpStatus: 409,
});
expect(harness.sessions[0].abortTransaction).toHaveBeenCalledTimes(1);
expect(harness.sessions[0].commitTransaction).not.toHaveBeenCalled();
});
});
const MATCH_ID = new Types.ObjectId('64b000000000000000000001');
const COMMUNITY_ID = new Types.ObjectId('64b000000000000000000002');
const USER_IDS = Array.from(
{ length: 8 },
(_, index) =>
new Types.ObjectId(
`64b0000000000000000001${String(index + 1).padStart(2, '0')}`,
),
);
function matchSnapshot(params: {
gameMode: CompetitionBootstrapMatch['gameMode'];
teamCount: number;
gameCount?: number;
roundRobinMaxRounds?: number;
}): CompetitionBootstrapMatch {
const participants = USER_IDS.slice(0, params.teamCount).map(
(userId, index) => ({
userId,
gameName: `Player ${index + 1}`,
tagLine: 'KR1',
profileIconId: 101 + index,
preferredPositions: [],
joinedAt: new Date('2026-07-12T00:00:00.000Z'),
}),
);
return {
_id: MATCH_ID,
communityId: COMMUNITY_ID,
status: 'team-built',
teamBuiltAt: new Date('2026-07-12T00:05:00.000Z'),
gameCount: params.gameCount ?? 3,
gameMode: params.gameMode,
...(params.roundRobinMaxRounds === undefined
? {}
: { roundRobinMaxRounds: params.roundRobinMaxRounds }),
participants,
teams: participants.map((participant, index) => ({
teamIndex: index + 1,
name: `Team ${index + 1}`,
captainUserId: participant.userId,
members: [
{
userId: participant.userId,
assignedPosition: 'TOP',
cost: 10 + index,
},
],
})),
};
}
interface InsertPayload {
_id: Types.ObjectId;
teams: Array<{
teamId: Types.ObjectId;
legacyTeamIndex: number;
seedNumber: number;
}>;
seriesGraph: Array<{ code?: string; rule: unknown }>;
[key: string]: any;
}
function createHarness(
options: {
existingCompetition?: Record<string, unknown>;
competitionResults?: Array<Record<string, unknown> | Error>;
matchUpdateResult?: { matchedCount: number };
sessionCount?: number;
} = {},
) {
const sessions = Array.from(
{ length: options.sessionCount ?? 1 },
createSession,
);
const insertedPayloads: InsertPayload[] = [];
let competitionCall = 0;
const competitionModel = {
findOneAndUpdate: jest.fn(
(_filter: unknown, update: { $setOnInsert: InsertPayload }) => {
insertedPayloads.push(update.$setOnInsert);
const selected = options.competitionResults?.[competitionCall++];
if (selected instanceof Error) return rejectedQuery(selected);
return queryResult(
selected ?? options.existingCompetition ?? update.$setOnInsert,
);
},
),
};
const matchModel = {
updateOne: jest
.fn()
.mockResolvedValue(options.matchUpdateResult ?? { matchedCount: 1 }),
};
const models: Record<string, unknown> = {
competition: competitionModel,
match: matchModel,
};
let sessionIndex = 0;
const connectionService = {
createSession: jest.fn(() => Promise.resolve(sessions[sessionIndex++])),
getModel: jest.fn((name: string) => Promise.resolve(models[name])),
};
return {
sessions,
insertedPayloads,
competitionModel,
matchModel,
connectionService,
};
}
function createSession() {
return {
startTransaction: jest.fn(),
commitTransaction: jest.fn().mockResolvedValue(undefined),
abortTransaction: jest.fn().mockResolvedValue(undefined),
endSession: jest.fn().mockResolvedValue(undefined),
};
}
function queryResult<T>(value: T) {
return { exec: jest.fn().mockResolvedValue(value) };
}
function rejectedQuery(error: Error) {
return { exec: jest.fn().mockRejectedValue(error) };
}
@@ -1,639 +0,0 @@
import { createHash } from 'node:crypto';
import { Injectable } from '@nestjs/common';
import mongoose, { Types } from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type {
MatchGameMode,
MatchParticipant,
MatchStatus,
MatchTeam,
} from '../global/database/schema';
import type {
CompetitionDocument,
CompetitionTeamSnapshot,
} from './competition.schema';
import {
generateSeriesGraph,
type CompetitionGraphFormat,
type CompetitionGraphTeam,
type SeriesDefinition,
} from './domain/series-graph';
import {
projectCompetition,
type CompetitionProjection,
} from './domain/competition-projector';
const COMPETITION_SCHEMA_VERSION = 1;
const COMPETITION_PROJECTOR_VERSION = 1;
const BOOTSTRAP_TRANSACTION_ATTEMPTS = 3;
export interface CompetitionBootstrapMatch {
_id: Types.ObjectId;
communityId: Types.ObjectId;
competitionId?: Types.ObjectId;
status: MatchStatus;
teamBuiltAt: Date;
gameCount: number;
gameMode: MatchGameMode;
roundRobinMaxRounds?: number;
participants: MatchParticipant[];
teams: MatchTeam[];
doubleElimination?: {
teamCount: 4 | 8;
resetFinalEnabled: boolean;
seeds: Array<{ seedNumber: number; teamIndex: number }>;
};
}
export interface CompetitionBootstrapOptions {
/** `bracket` is accepted only by the explicit legacy migration path. */
source?: 'live' | 'legacy-migration';
}
export type CompetitionBootstrapErrorCode =
| 'INVALID_MATCH_TEAM_SNAPSHOT'
| 'INVALID_MATCH_FORMAT'
| 'UNSUPPORTED_LIVE_MATCH_MODE'
| 'COMPETITION_TRANSACTION_UNAVAILABLE'
| 'COMPETITION_BOOTSTRAP_FAILED'
| 'COMPETITION_BOOTSTRAP_RACE'
| 'MATCH_COMPETITION_LINK_CONFLICT';
export class CompetitionBootstrapError extends Error {
constructor(
public readonly code: CompetitionBootstrapErrorCode,
message: string,
public readonly httpStatus: 409 | 422 | 500,
public readonly details?: Readonly<Record<string, unknown>>,
) {
super(message);
this.name = 'CompetitionBootstrapError';
}
}
interface CompetitionInsertPayload {
_id: Types.ObjectId;
matchId: Types.ObjectId;
communityId: Types.ObjectId;
schemaVersion: number;
projectorVersion: number;
revision: number;
phase: CompetitionProjection['phase'];
teams: CompetitionTeamSnapshot[];
format: CompetitionGraphFormat;
seriesGraph: SeriesDefinition[];
projection: CompetitionProjection;
}
/**
* Freezes the recruiting Match into the one-to-one Competition aggregate.
* Retries only repeat deterministic upserts, so duplicate creators and unknown
* commit outcomes converge without replacing an existing immutable snapshot.
*/
@Injectable()
export class CompetitionBootstrapService {
constructor(private readonly connectionService: ConnectionService) {}
public async bootstrap(
match: CompetitionBootstrapMatch,
options: CompetitionBootstrapOptions = {},
): Promise<CompetitionDocument> {
const payload = buildCompetitionInsertPayload(
match,
options.source ?? 'live',
);
const [CompetitionModel, MatchModel] = await Promise.all([
this.connectionService.getModel('competition'),
this.connectionService.getModel('match'),
]);
let lastRetryableError: unknown;
for (
let attempt = 1;
attempt <= BOOTSTRAP_TRANSACTION_ATTEMPTS;
attempt += 1
) {
const session = await this.connectionService.createSession();
if (!session) {
throw new CompetitionBootstrapError(
'COMPETITION_TRANSACTION_UNAVAILABLE',
'A MongoDB transaction is required to bootstrap a Competition.',
500,
);
}
try {
session.startTransaction();
const competition = await CompetitionModel.findOneAndUpdate(
{ matchId: match._id },
{ $setOnInsert: payload },
{
upsert: true,
returnDocument: 'after',
setDefaultsOnInsert: true,
session,
},
).exec();
if (!competition) {
throw new CompetitionBootstrapError(
'COMPETITION_BOOTSTRAP_FAILED',
'Competition upsert returned no document.',
500,
);
}
const linkResult = await MatchModel.updateOne(
{
_id: match._id,
status: match.status,
teamBuiltAt: match.teamBuiltAt,
$or: [
{ competitionId: { $exists: false } },
{ competitionId: null },
{ competitionId: competition._id },
],
},
{ $set: { competitionId: competition._id } },
{ session },
);
if (linkResult.matchedCount !== 1) {
throw new CompetitionBootstrapError(
'MATCH_COMPETITION_LINK_CONFLICT',
'Match is missing or linked to a different Competition.',
409,
{ matchId: match._id.toString() },
);
}
await session.commitTransaction();
return competition;
} catch (error) {
await session.abortTransaction().catch(() => undefined);
if (
attempt < BOOTSTRAP_TRANSACTION_ATTEMPTS &&
isRetryableBootstrapError(error)
) {
lastRetryableError = error;
continue;
}
if (isRetryableBootstrapError(error)) {
throw new CompetitionBootstrapError(
'COMPETITION_BOOTSTRAP_RACE',
'Competition bootstrap did not converge after concurrent writes.',
409,
{ matchId: match._id.toString() },
);
}
throw error;
} finally {
await session.endSession().catch(() => undefined);
}
}
throw new CompetitionBootstrapError(
'COMPETITION_BOOTSTRAP_RACE',
'Competition bootstrap retry budget was exhausted.',
409,
{
matchId: match._id.toString(),
cause:
lastRetryableError instanceof Error
? lastRetryableError.message
: String(lastRetryableError),
},
);
}
}
function buildCompetitionInsertPayload(
match: CompetitionBootstrapMatch,
source: NonNullable<CompetitionBootstrapOptions['source']>,
): CompetitionInsertPayload {
assertObjectId(match._id, 'Match ID');
assertObjectId(match.communityId, 'Community ID');
if (match.status === 'recruiting' || !(match.teamBuiltAt instanceof Date)) {
throw new CompetitionBootstrapError(
'INVALID_MATCH_TEAM_SNAPSHOT',
'Competition bootstrap requires a finalized team-built Match lifecycle.',
422,
);
}
assertPositiveInteger(match.gameCount, 'Match game count');
const competitionId = stableObjectId(match._id, 'competition');
const teams = snapshotTeams(match, competitionId);
const graphTeams = teams.map(
({ teamId, displayOrder, seedNumber }): CompetitionGraphTeam => ({
teamId: teamId.toString(),
displayOrder,
seedNumber,
}),
);
const format = mapMatchFormat(match, teams, source);
let seriesGraph: SeriesDefinition[];
let projection: CompetitionProjection;
try {
seriesGraph = generateSeriesGraph({
competitionId: competitionId.toString(),
teams: graphTeams,
format,
});
projection = projectCompetition({
competitionId: competitionId.toString(),
revision: 0,
projectorVersion: COMPETITION_PROJECTOR_VERSION,
teams: graphTeams,
format,
seriesGraph,
facts: [],
});
} catch (error) {
throw new CompetitionBootstrapError(
'INVALID_MATCH_FORMAT',
error instanceof Error
? error.message
: 'The Match cannot produce a valid Competition graph.',
422,
{
matchId: match._id.toString(),
domainCode: readErrorCode(error),
},
);
}
return {
_id: competitionId,
matchId: match._id,
communityId: match.communityId,
schemaVersion: COMPETITION_SCHEMA_VERSION,
projectorVersion: COMPETITION_PROJECTOR_VERSION,
revision: 0,
phase: projection.phase,
teams,
format,
seriesGraph,
projection,
};
}
function snapshotTeams(
match: CompetitionBootstrapMatch,
competitionId: Types.ObjectId,
): CompetitionTeamSnapshot[] {
if (!Array.isArray(match.teams) || match.teams.length < 2) {
throw invalidTeamSnapshot(
'A Competition requires at least two built teams.',
);
}
if (!Array.isArray(match.participants)) {
throw invalidTeamSnapshot('Match participants are missing.');
}
const participantById = new Map<string, MatchParticipant>();
for (const participant of match.participants) {
const userId = objectIdString(participant?.userId);
if (!userId || participantById.has(userId)) {
throw invalidTeamSnapshot(
'Match participants must have unique ObjectId user identities.',
);
}
participantById.set(userId, participant);
}
const orderedTeams = [...match.teams].sort(
(left, right) => left.teamIndex - right.teamIndex,
);
const teamIndexes = new Set<number>();
const assignedUserIds = new Set<string>();
const memberCounts = new Set<number>();
const snapshots: CompetitionTeamSnapshot[] = [];
for (const [displayIndex, team] of orderedTeams.entries()) {
if (
!Number.isInteger(team.teamIndex) ||
team.teamIndex < 1 ||
teamIndexes.has(team.teamIndex)
) {
throw invalidTeamSnapshot(
'Built teams must have unique positive integer team indexes.',
);
}
teamIndexes.add(team.teamIndex);
if (typeof team.name !== 'string' || team.name.trim().length === 0) {
throw invalidTeamSnapshot('Every built team needs a non-empty name.');
}
if (!Array.isArray(team.members) || team.members.length === 0) {
throw invalidTeamSnapshot('Every built team needs at least one member.');
}
memberCounts.add(team.members.length);
const memberSnapshots = [...team.members]
.sort(compareTeamMembers)
.map((member) => {
const userId = objectIdString(member.userId);
const participant = userId ? participantById.get(userId) : undefined;
if (
!userId ||
!participant ||
participant.excluded === true ||
assignedUserIds.has(userId)
) {
throw invalidTeamSnapshot(
'Every non-excluded participant must be assigned to exactly one team.',
);
}
assignedUserIds.add(userId);
const gameName = nonEmptyString(participant.gameName);
const tagLine = nonEmptyString(participant.tagLine);
return {
userId: member.userId,
displayName: gameName
? tagLine
? `${gameName}#${tagLine}`
: gameName
: userId,
...(gameName ? { gameName } : {}),
...(tagLine ? { tagLine } : {}),
...(participant.profileIconId === undefined
? {}
: { profileIconId: participant.profileIconId }),
assignedPosition: member.assignedPosition,
...(member.cost === undefined ? {} : { cost: member.cost }),
};
});
if (team.captainUserId) {
const captainUserId = team.captainUserId.toString();
if (
!memberSnapshots.some(
({ userId }) => userId.toString() === captainUserId,
)
) {
throw invalidTeamSnapshot('A team captain must belong to that team.');
}
}
snapshots.push({
teamId: stableObjectId(
competitionId,
'team',
`legacy-team-index:${team.teamIndex}`,
),
legacyTeamIndex: team.teamIndex,
displayOrder: displayIndex + 1,
seedNumber: displayIndex + 1,
name: team.name.trim(),
...(team.captainUserId ? { captainUserId: team.captainUserId } : {}),
members: memberSnapshots,
});
}
if (memberCounts.size !== 1) {
throw invalidTeamSnapshot(
'All built teams must have the same member count.',
);
}
const activeParticipantIds = [...participantById]
.filter(([, participant]) => participant.excluded !== true)
.map(([userId]) => userId);
if (
activeParticipantIds.length !== assignedUserIds.size ||
activeParticipantIds.some((userId) => !assignedUserIds.has(userId))
) {
throw invalidTeamSnapshot(
'Every non-excluded participant must be assigned to exactly one team.',
);
}
applySeeds(match, snapshots);
return snapshots;
}
function applySeeds(
match: CompetitionBootstrapMatch,
teams: CompetitionTeamSnapshot[],
): void {
if (match.gameMode !== 'double-elimination') return;
const configuredSeeds = match.doubleElimination?.seeds ?? [];
if (configuredSeeds.length === 0) {
throw invalidTeamSnapshot(
'Double-elimination seeds must be finalized before Competition bootstrap.',
);
}
if (configuredSeeds.length !== teams.length) {
throw invalidTeamSnapshot(
'Double-elimination seeds must include every built team exactly once.',
);
}
const validTeamIndexes = new Set(
teams.map(({ legacyTeamIndex }) => legacyTeamIndex as number),
);
const seedByTeamIndex = new Map<number, number>();
const seedNumbers = new Set<number>();
for (const seed of configuredSeeds) {
if (
!Number.isInteger(seed.seedNumber) ||
seed.seedNumber < 1 ||
seed.seedNumber > teams.length ||
seedNumbers.has(seed.seedNumber) ||
!validTeamIndexes.has(seed.teamIndex) ||
seedByTeamIndex.has(seed.teamIndex)
) {
throw invalidTeamSnapshot(
'Double-elimination seeds must be unique and contiguous.',
);
}
seedNumbers.add(seed.seedNumber);
seedByTeamIndex.set(seed.teamIndex, seed.seedNumber);
}
for (const team of teams) {
team.seedNumber = seedByTeamIndex.get(team.legacyTeamIndex as number)!;
}
}
function mapMatchFormat(
match: CompetitionBootstrapMatch,
teams: CompetitionTeamSnapshot[],
source: NonNullable<CompetitionBootstrapOptions['source']>,
): CompetitionGraphFormat {
switch (match.gameMode) {
case 'pair':
return fixedGameFormat('paired-series', match.gameCount);
case 'bracket':
if (source !== 'legacy-migration') {
throw new CompetitionBootstrapError(
'UNSUPPORTED_LIVE_MATCH_MODE',
'Legacy bracket mode can only be bootstrapped by migration.',
422,
);
}
return fixedGameFormat('paired-series', match.gameCount);
case 'round-robin':
if (
match.roundRobinMaxRounds !== undefined &&
(!Number.isInteger(match.roundRobinMaxRounds) ||
match.roundRobinMaxRounds < 1)
) {
throw new CompetitionBootstrapError(
'INVALID_MATCH_FORMAT',
'Round-robin max rounds must be a positive integer.',
422,
);
}
return {
type: 'round-robin',
rule: fixedGamesRule(match.gameCount),
...(match.roundRobinMaxRounds === undefined
? {}
: { maxRounds: match.roundRobinMaxRounds }),
tieBreakers: ['series-wins', 'game-diff', 'head-to-head'],
};
case 'double-elimination': {
if (teams.length !== 4 && teams.length !== 8) {
throw new CompetitionBootstrapError(
'INVALID_MATCH_FORMAT',
'Double elimination supports only four or eight teams.',
422,
);
}
if (
match.doubleElimination?.teamCount !== undefined &&
match.doubleElimination.teamCount !== teams.length
) {
throw new CompetitionBootstrapError(
'INVALID_MATCH_FORMAT',
'Double-elimination team count does not match the built teams.',
422,
);
}
const bestOfOne = {
type: 'first-to' as const,
winsRequired: 1,
maxGames: 1,
};
return {
type: 'double-elimination',
teamCount: teams.length,
resetFinalEnabled: match.doubleElimination?.resetFinalEnabled ?? false,
rules: {
upper: {
type: 'first-to',
winsRequired: Math.floor(match.gameCount / 2) + 1,
maxGames: match.gameCount,
},
lower: { ...bestOfOne },
grandFinal: { ...bestOfOne },
resetFinal: { ...bestOfOne },
},
};
}
}
}
function fixedGameFormat(
type: 'paired-series',
gameCount: number,
): Extract<CompetitionGraphFormat, { type: 'paired-series' }> {
return { type, rule: fixedGamesRule(gameCount) };
}
function fixedGamesRule(gameCount: number) {
return {
type: 'fixed-games' as const,
gameCount,
drawPolicy: 'allow' as const,
};
}
function stableObjectId(
namespaceId: Types.ObjectId,
entityKind: string,
...logicalKey: string[]
): Types.ObjectId {
const hex = createHash('sha256')
.update(JSON.stringify([namespaceId.toString(), entityKind, ...logicalKey]))
.digest('hex')
.slice(0, 24);
return new Types.ObjectId(hex);
}
function compareTeamMembers(
left: MatchTeam['members'][number],
right: MatchTeam['members'][number],
): number {
const positionOrder = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
return (
positionOrder.indexOf(left.assignedPosition) -
positionOrder.indexOf(right.assignedPosition) ||
left.userId.toString().localeCompare(right.userId.toString())
);
}
function invalidTeamSnapshot(message: string): CompetitionBootstrapError {
return new CompetitionBootstrapError(
'INVALID_MATCH_TEAM_SNAPSHOT',
message,
422,
);
}
function assertPositiveInteger(value: number, label: string): void {
if (!Number.isInteger(value) || value < 1) {
throw new CompetitionBootstrapError(
'INVALID_MATCH_FORMAT',
`${label} must be a positive integer.`,
422,
);
}
}
function assertObjectId(
value: unknown,
label: string,
): asserts value is Types.ObjectId {
if (!(value instanceof mongoose.Types.ObjectId)) {
throw invalidTeamSnapshot(`${label} must be a MongoDB ObjectId.`);
}
}
function objectIdString(value: unknown): string | undefined {
return value instanceof mongoose.Types.ObjectId
? value.toString()
: undefined;
}
function nonEmptyString(value: unknown): string | undefined {
if (typeof value !== 'string') return undefined;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
function readErrorCode(error: unknown): string | undefined {
if (
typeof error === 'object' &&
error !== null &&
'code' in error &&
typeof error.code === 'string'
) {
return error.code;
}
return undefined;
}
function isRetryableBootstrapError(error: unknown): boolean {
const candidate = error as {
code?: number;
codeName?: string;
hasErrorLabel?: (label: string) => boolean;
};
return Boolean(
candidate?.code === 11000 ||
candidate?.code === 112 ||
candidate?.codeName === 'WriteConflict' ||
candidate?.hasErrorLabel?.('TransientTransactionError') ||
candidate?.hasErrorLabel?.('UnknownTransactionCommitResult'),
);
}
@@ -1,787 +0,0 @@
import { Types } from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { CompetitionCommandService } from './competition-command.service';
import { projectCompetition } from './domain/competition-projector';
jest.mock('./domain/competition-projector', () => ({
projectCompetition: jest.fn(),
}));
const mockedProjectCompetition = jest.mocked(projectCompetition);
describe('CompetitionCommandService', () => {
beforeEach(() => {
jest.useFakeTimers().setSystemTime(new Date('2026-07-12T10:00:00.000Z'));
mockedProjectCompetition.mockReset();
mockedProjectCompetition.mockReturnValue(PROJECTION as never);
});
afterEach(() => {
jest.useRealTimers();
});
it('rejects a stale expected revision and aborts without writing', async () => {
const harness = createHarness({ competitionRevision: 8 });
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
await expect(service.acceptGame(acceptGameCommand())).rejects.toMatchObject(
{
code: 'STALE_COMPETITION_REVISION',
httpStatus: 412,
details: { expectedRevision: 7, actualRevision: 8 },
},
);
expect(harness.factModel.insertMany).not.toHaveBeenCalled();
expect(harness.competitionModel.findOneAndUpdate).not.toHaveBeenCalled();
expect(harness.outboxModel.insertMany).not.toHaveBeenCalled();
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).not.toHaveBeenCalled();
expect(harness.session.endSession).toHaveBeenCalledTimes(1);
});
it('uses the expected revision in the persistence CAS and aborts a lost race', async () => {
const harness = createHarness({ casResult: null });
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
await expect(service.acceptGame(acceptGameCommand())).rejects.toMatchObject(
{
code: 'STALE_COMPETITION_REVISION',
httpStatus: 412,
},
);
const [casFilter, casUpdate, casOptions] = harness.competitionModel
.findOneAndUpdate.mock.calls[0] as unknown as [
Record<string, unknown>,
{ $inc: Record<string, unknown>; $set: Record<string, unknown> },
Record<string, unknown>,
];
expect(casFilter).toEqual({ _id: COMPETITION_ID, revision: 7 });
expect(casUpdate).toMatchObject({
$inc: { revision: 1 },
$set: { projection: PROJECTION },
});
expect(casOptions).toMatchObject({
returnDocument: 'after',
session: harness.session,
});
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).not.toHaveBeenCalled();
});
it('replays an exact Idempotency-Key request without appending a second fact', async () => {
const harness = createHarness();
let storedReceipt: Record<string, unknown> | null = null;
harness.outboxModel.findOne.mockImplementation(() =>
queryResult(storedReceipt),
);
harness.outboxModel.insertMany.mockImplementation(
([receipt]: Array<Record<string, unknown>>) => {
storedReceipt = receipt;
return Promise.resolve([receipt]);
},
);
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const command = acceptGameCommand();
const first = await service.acceptGame(command);
const replay = await service.acceptGame(command);
expect(first).toMatchObject({ revision: 8, replayed: false });
expect(replay).toMatchObject({
commandId: first.commandId,
revision: 8,
replayed: true,
});
expect(replay.competition).toEqual(first.competition);
expect(harness.factModel.insertMany).toHaveBeenCalledTimes(1);
expect(harness.competitionModel.findOneAndUpdate).toHaveBeenCalledTimes(1);
expect(harness.outboxModel.insertMany).toHaveBeenCalledTimes(1);
expect(mockedProjectCompetition).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(2);
expect(harness.session.abortTransaction).not.toHaveBeenCalled();
});
it('replays a concurrently committed identical command after a duplicate-key race', async () => {
const harness = createHarness();
let committedReceipt: Record<string, unknown> | null = null;
harness.outboxModel.findOne.mockImplementation(() =>
queryResult(committedReceipt),
);
harness.factModel.insertMany.mockImplementationOnce(
async ([fact]: Array<Record<string, unknown>>) => {
committedReceipt = {
competitionId: COMPETITION_ID,
idempotencyKey: fact.idempotencyKey,
requestHash: fact.requestHash,
commandId: fact.commandId,
revision: fact.revision,
payload: {
projection: PROJECTION,
phase: PROJECTION.phase,
},
};
throw Object.assign(new Error('duplicate command fact'), {
code: 11_000,
});
},
);
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
await expect(
service.acceptGame(acceptGameCommand()),
).resolves.toMatchObject({
revision: 8,
replayed: true,
});
expect(harness.connectionService.createSession).toHaveBeenCalledTimes(2);
expect(harness.factModel.insertMany).toHaveBeenCalledTimes(1);
expect(harness.competitionModel.findOneAndUpdate).not.toHaveBeenCalled();
expect(harness.outboxModel.insertMany).not.toHaveBeenCalled();
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(1);
});
it('rejects the same Idempotency-Key when its payload hash differs', async () => {
const harness = createHarness();
harness.outboxModel.findOne.mockReturnValue(
queryResult({
idempotencyKey: 'riot:KR_7000000001',
requestHash: 'a-different-payload-hash',
commandId: 'cmpcmd_original',
revision: 8,
}),
);
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
await expect(service.acceptGame(acceptGameCommand())).rejects.toMatchObject(
{
code: 'IDEMPOTENCY_KEY_CONFLICT',
httpStatus: 409,
},
);
expect(harness.competitionModel.findById).not.toHaveBeenCalled();
expect(harness.factModel.insertMany).not.toHaveBeenCalled();
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
});
it('atomically accepts a code-backed game, projects it, and enqueues an event', async () => {
const harness = createHarness();
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const command = {
...acceptGameCommand(),
tournamentCode: {
tournamentCodeId: TOURNAMENT_CODE_ID,
riotMatchId: 'KR_7000000001',
},
};
const result = await service.acceptGame(command);
expect(result).toMatchObject({ revision: 8, replayed: false });
expect(harness.session.startTransaction).toHaveBeenCalledTimes(1);
const [insertedFacts, factOptions] = harness.factModel.insertMany.mock
.calls[0] as unknown as [
Array<Record<string, unknown>>,
Record<string, unknown>,
];
expect(insertedFacts).toHaveLength(1);
expect(insertedFacts[0]).toMatchObject({
type: 'game-accepted',
revision: 8,
ordinalWithinRevision: 1,
gameId: GAME_ID,
seriesId: SERIES_ID,
gameSlotId: GAME_SLOT_ID,
startedAt: new Date('2026-07-12T09:30:00.000Z'),
durationSeconds: 1_800,
participants: [
{
userId: USER_ID.toHexString(),
teamId: TEAM_A_ID.toHexString(),
side: 'blue',
},
],
});
expect(factOptions).toEqual({ session: harness.session });
const projectionInput = mockedProjectCompetition.mock.calls[0][0];
const projectedFact = projectionInput.facts[0] as Record<string, unknown>;
const projectedMapping = projectedFact.mapping as Record<string, unknown>;
expect(projectionInput.competitionId).toBe(COMPETITION_ID.toHexString());
expect(projectionInput.revision).toBe(8);
expect(typeof projectedFact.id).toBe('string');
expect(projectedFact).toMatchObject({
type: 'game-accepted',
seriesId: SERIES_ID.toHexString(),
});
expect(projectedMapping.winnerTeamId).toBe(TEAM_A_ID.toHexString());
const [assignmentFilter, assignmentUpdate, assignmentOptions] = harness
.assignmentModel.updateOne.mock.calls[0] as unknown as [
Record<string, unknown>,
{ $set: Record<string, unknown> },
Record<string, unknown>,
];
expect(assignmentFilter).toMatchObject({
competitionId: COMPETITION_ID,
gameSlotId: GAME_SLOT_ID,
tournamentCodeId: TOURNAMENT_CODE_ID,
state: 'reserved',
});
expect(assignmentUpdate.$set.state).toBe('used');
expect(assignmentOptions).toEqual({ session: harness.session });
const [codeFilter, codeUpdate, codeOptions] = harness.tournamentCodeModel
.updateOne.mock.calls[0] as unknown as [
Record<string, unknown>,
{ $set: Record<string, unknown> },
Record<string, unknown>,
];
expect(codeFilter).toEqual({
_id: TOURNAMENT_CODE_ID,
state: 'reserved',
});
expect(codeUpdate.$set.state).toBe('used');
expect(codeOptions).toEqual({ session: harness.session });
const [outboxRecords, outboxOptions] = harness.outboxModel.insertMany.mock
.calls[0] as unknown as [
Array<Record<string, unknown>>,
Record<string, unknown>,
];
expect(outboxRecords).toHaveLength(1);
expect(outboxRecords[0]).toMatchObject({
revision: 8,
type: 'competition.projection-updated',
state: 'pending',
payload: { projection: PROJECTION },
});
expect(outboxOptions).toEqual({ session: harness.session });
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(1);
expect(harness.session.abortTransaction).not.toHaveBeenCalled();
});
it('appends an administrative adjudication through the same command runner', async () => {
const harness = createHarness();
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const result = await service.adjudicateSeries({
competitionId: COMPETITION_ID,
expectedRevision: 7,
idempotencyKey: 'admin:series:walkover:1',
actor: { type: 'user', userId: USER_ID },
seriesId: SERIES_ID,
decision: { type: 'walkover', winnerTeamId: TEAM_B_ID },
reason: 'Opponent did not appear before the deadline.',
});
expect(result).toMatchObject({ revision: 8, replayed: false });
expect(harness.factModel.insertMany).toHaveBeenCalledWith(
[
expect.objectContaining({
type: 'series-adjudicated',
seriesId: SERIES_ID,
decision: { type: 'walkover', winnerTeamId: TEAM_B_ID },
reason: 'Opponent did not appear before the deadline.',
}),
],
{ session: harness.session },
);
expect(harness.assignmentModel.updateOne).not.toHaveBeenCalled();
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(1);
});
it('previews a strict or cascade reversal against the requested revision', async () => {
const reversal = reversalFixture();
const harness = createHarness({
competition: reversal.competition,
facts: reversal.facts,
assignments: reversal.assignments,
});
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const preview = await service.previewSeriesReversal({
competitionId: COMPETITION_ID,
expectedRevision: 7,
seriesId: reversal.parentSeriesId,
mode: 'cascade',
});
expect(preview).toMatchObject({
sourceRevision: 7,
impactHash: expect.stringMatching(/^[a-f0-9]{64}$/),
impact: {
seriesIds: [
reversal.parentSeriesId.toHexString(),
reversal.childSeriesId.toHexString(),
],
factIds: [
reversal.parentFactId.toHexString(),
reversal.childFactId.toHexString(),
],
releasesReservedCodes: 1,
voidsUsedCodes: 1,
},
});
});
it('rejects a reversal preview at a stale revision', async () => {
const reversal = reversalFixture();
const harness = createHarness({ competition: reversal.competition });
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
await expect(
service.previewSeriesReversal({
competitionId: COMPETITION_ID,
expectedRevision: 6,
seriesId: reversal.parentSeriesId,
mode: 'strict',
}),
).rejects.toMatchObject({
code: 'STALE_COMPETITION_REVISION',
httpStatus: 412,
});
});
it('hash-confirms and atomically appends cascade reversal facts', async () => {
const reversal = reversalFixture();
const harness = createHarness({
competition: reversal.competition,
facts: reversal.facts,
assignments: reversal.assignments,
});
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const preview = await service.previewSeriesReversal({
competitionId: COMPETITION_ID,
expectedRevision: 7,
seriesId: reversal.parentSeriesId,
mode: 'cascade',
});
const result = await service.reverseSeries({
competitionId: COMPETITION_ID,
expectedRevision: 7,
idempotencyKey: 'admin:reverse:1',
actor: { type: 'user', userId: USER_ID },
seriesId: reversal.parentSeriesId,
mode: 'cascade',
reason: 'Wrong result ingestion',
impactHash: preview.impactHash,
});
expect(result).toMatchObject({ revision: 8, replayed: false });
expect(harness.factModel.insertMany).toHaveBeenCalledWith(
[
expect.objectContaining({
_id: expect.any(Types.ObjectId),
type: 'game-voided',
gameAcceptedFactId: reversal.parentFactId,
revision: 8,
ordinalWithinRevision: 1,
reason: 'Wrong result ingestion',
}),
expect.objectContaining({
_id: expect.any(Types.ObjectId),
type: 'game-voided',
gameAcceptedFactId: reversal.childFactId,
revision: 8,
ordinalWithinRevision: 2,
}),
],
{ session: harness.session },
);
expect(harness.assignmentModel.updateMany).toHaveBeenCalledWith(
expect.objectContaining({
competitionId: COMPETITION_ID,
gameSlotId: {
$in: expect.arrayContaining([
reversal.parentGameSlotId,
reversal.childGameSlotId,
]),
},
}),
expect.any(Array),
{ session: harness.session },
);
expect(harness.tournamentCodeModel.updateMany).toHaveBeenCalled();
expect(harness.matchModel.updateOne).toHaveBeenCalledWith(
{ _id: reversal.competition.matchId },
{
$pull: {
tournamentCodeIds: {
$in: [reversal.parentCodeId, reversal.childCodeId],
},
},
},
{ session: harness.session },
);
const [, codeReversalPipeline] = harness.tournamentCodeModel.updateMany.mock
.calls[0] as unknown as [
Record<string, unknown>,
Array<Record<string, any>>,
];
expect(codeReversalPipeline[0].$set).toMatchObject({
state: {
$cond: [{ $eq: ['$state', 'reserved'] }, 'released', 'voided'],
},
matchId: {
$cond: [{ $eq: ['$state', 'reserved'] }, '$$REMOVE', '$matchId'],
},
gameNumber: {
$cond: [{ $eq: ['$state', 'reserved'] }, '$$REMOVE', '$gameNumber'],
},
bracketMatchId: {
$cond: [{ $eq: ['$state', 'reserved'] }, '$$REMOVE', '$bracketMatchId'],
},
reservedAt: {
$cond: [{ $eq: ['$state', 'reserved'] }, '$$REMOVE', '$reservedAt'],
},
});
expect(harness.competitionModel.findOneAndUpdate).toHaveBeenCalledWith(
{ _id: COMPETITION_ID, revision: 7 },
expect.objectContaining({ $inc: { revision: 1 } }),
expect.objectContaining({ session: harness.session }),
);
expect(harness.outboxModel.insertMany).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(1);
});
it('retries a cascade reversal after a transient transaction conflict', async () => {
const reversal = reversalFixture();
const harness = createHarness({
competition: reversal.competition,
facts: reversal.facts,
assignments: reversal.assignments,
});
harness.factModel.insertMany
.mockRejectedValueOnce(
Object.assign(new Error('write conflict'), {
code: 112,
codeName: 'WriteConflict',
}),
)
.mockResolvedValueOnce([]);
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const preview = await service.previewSeriesReversal({
competitionId: COMPETITION_ID,
expectedRevision: 7,
seriesId: reversal.parentSeriesId,
mode: 'cascade',
});
await expect(
service.reverseSeries({
competitionId: COMPETITION_ID,
expectedRevision: 7,
idempotencyKey: 'admin:reverse:transient-retry',
actor: { type: 'user', userId: USER_ID },
seriesId: reversal.parentSeriesId,
mode: 'cascade',
reason: 'Wrong result ingestion',
impactHash: preview.impactHash,
}),
).resolves.toMatchObject({ revision: 8, replayed: false });
expect(harness.connectionService.createSession).toHaveBeenCalledTimes(2);
expect(harness.factModel.insertMany).toHaveBeenCalledTimes(2);
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(1);
});
});
const COMPETITION_ID = new Types.ObjectId('64b000000000000000000001');
const SERIES_ID = new Types.ObjectId('64b000000000000000000002');
const GAME_SLOT_ID = new Types.ObjectId('64b000000000000000000003');
const GAME_ID = new Types.ObjectId('64b000000000000000000004');
const TEAM_A_ID = new Types.ObjectId('64b000000000000000000005');
const TEAM_B_ID = new Types.ObjectId('64b000000000000000000006');
const USER_ID = new Types.ObjectId('64b000000000000000000007');
const TOURNAMENT_CODE_ID = new Types.ObjectId('64b000000000000000000008');
const PROJECTION = {
sourceRevision: 8,
projectorVersion: 1,
phase: 'running',
formatType: 'paired-series',
series: [],
games: [],
gameSlots: [],
rounds: [],
connectors: [],
};
function acceptGameCommand() {
return {
competitionId: COMPETITION_ID,
expectedRevision: 7,
idempotencyKey: 'riot:KR_7000000001',
actor: { type: 'system' as const },
occurredAt: new Date('2026-07-12T09:59:00.000Z'),
gameId: GAME_ID,
seriesId: SERIES_ID,
gameSlotId: GAME_SLOT_ID,
ordinal: 1,
evidence: {
type: 'riot' as const,
riotMatchId: 'KR_7000000001',
payloadHash: 'sha256:riot-payload',
},
mapping: {
mappingVersion: 1,
confidence: 1,
blueTeamId: TEAM_A_ID,
redTeamId: TEAM_B_ID,
winnerTeamId: TEAM_A_ID,
participantAssignments: [],
},
startedAt: new Date('2026-07-12T09:30:00.000Z'),
durationSeconds: 1_800,
participants: [
{
userId: USER_ID.toHexString(),
teamId: TEAM_A_ID.toHexString(),
side: 'blue',
},
],
};
}
function createHarness(
options: {
competitionRevision?: number;
casResult?: Record<string, unknown> | null;
competition?: Record<string, unknown>;
facts?: Array<Record<string, unknown>>;
assignments?: Array<Record<string, unknown>>;
} = {},
) {
const session = {
startTransaction: jest.fn(),
commitTransaction: jest.fn().mockResolvedValue(undefined),
abortTransaction: jest.fn().mockResolvedValue(undefined),
endSession: jest.fn().mockResolvedValue(undefined),
};
const competition =
options.competition ??
competitionDocument(options.competitionRevision ?? 7);
const competitionModel = {
findById: jest.fn().mockReturnValue(queryResult(competition)),
findOneAndUpdate: jest
.fn()
.mockReturnValue(
queryResult(
options.casResult === undefined
? competitionDocument(8, PROJECTION)
: options.casResult,
),
),
};
const factModel = {
find: jest.fn().mockReturnValue(queryResult(options.facts ?? [])),
insertMany: jest.fn().mockResolvedValue([]),
};
const outboxModel = {
findOne: jest.fn().mockReturnValue(queryResult(null)),
insertMany: jest.fn().mockResolvedValue([]),
};
const assignmentModel = {
find: jest.fn().mockReturnValue(queryResult(options.assignments ?? [])),
updateOne: jest.fn().mockResolvedValue({ modifiedCount: 1 }),
updateMany: jest.fn().mockResolvedValue({ modifiedCount: 2 }),
};
const tournamentCodeModel = {
updateOne: jest.fn().mockResolvedValue({ modifiedCount: 1 }),
updateMany: jest.fn().mockResolvedValue({ modifiedCount: 2 }),
};
const matchModel = {
updateOne: jest
.fn()
.mockResolvedValue({ matchedCount: 1, modifiedCount: 1 }),
};
const models: Record<string, unknown> = {
competition: competitionModel,
competitionFact: factModel,
competitionOutbox: outboxModel,
tournamentCodeAssignment: assignmentModel,
tournamentCode: tournamentCodeModel,
match: matchModel,
};
const connectionService = {
createSession: jest.fn().mockResolvedValue(session),
getModel: jest.fn((name: string) => Promise.resolve(models[name])),
};
return {
session,
competitionModel,
factModel,
outboxModel,
assignmentModel,
tournamentCodeModel,
matchModel,
connectionService,
};
}
function competitionDocument(revision: number, projection = PROJECTION) {
return {
_id: COMPETITION_ID,
matchId: new Types.ObjectId('64b000000000000000000010'),
communityId: new Types.ObjectId('64b000000000000000000011'),
schemaVersion: 1,
projectorVersion: 1,
revision,
phase: 'running',
teams: [
{ teamId: TEAM_A_ID, displayOrder: 1, seedNumber: 1 },
{ teamId: TEAM_B_ID, displayOrder: 2, seedNumber: 2 },
],
format: {
type: 'paired-series',
rule: { type: 'first-to', winsRequired: 2, maxGames: 3 },
},
seriesGraph: [],
projection,
};
}
function queryResult<T>(value: T) {
const query = {
session: jest.fn(),
sort: jest.fn(),
lean: jest.fn(),
exec: jest.fn().mockResolvedValue(value),
};
query.session.mockReturnValue(query);
query.sort.mockReturnValue(query);
query.lean.mockReturnValue(query);
return query;
}
function reversalFixture() {
const parentSeriesId = new Types.ObjectId('64b000000000000000000021');
const childSeriesId = new Types.ObjectId('64b000000000000000000022');
const parentFactId = new Types.ObjectId('64b000000000000000000023');
const childFactId = new Types.ObjectId('64b000000000000000000024');
const parentGameSlotId = new Types.ObjectId('64b000000000000000000025');
const childGameSlotId = new Types.ObjectId('64b000000000000000000026');
const parentCodeId = new Types.ObjectId('64b000000000000000000027');
const childCodeId = new Types.ObjectId('64b000000000000000000028');
const series = (
id: Types.ObjectId,
sourceA: Record<string, unknown>,
sourceB: Record<string, unknown>,
) => ({
id: id.toHexString(),
stage: { type: 'upper', displayOrder: 1 },
slots: [
{ position: 'A', source: sourceA },
{ position: 'B', source: sourceB },
],
rule: { type: 'first-to', winsRequired: 1, maxGames: 1 },
gameSlots: [],
});
const accepted = (
_id: Types.ObjectId,
seriesId: Types.ObjectId,
gameSlotId: Types.ObjectId,
) => ({
_id,
competitionId: COMPETITION_ID,
type: 'game-accepted',
revision: 1,
ordinalWithinRevision: 1,
commandId: `command-${_id.toHexString()}`,
idempotencyKey: `key-${_id.toHexString()}`,
requestHash: `hash-${_id.toHexString()}`,
schemaVersion: 1,
actor: { type: 'system' },
occurredAt: new Date('2026-07-12T00:00:00.000Z'),
recordedAt: new Date('2026-07-12T00:00:00.000Z'),
gameId: new Types.ObjectId(),
seriesId,
gameSlotId,
ordinal: 1,
evidence: { type: 'legacy', legacyReference: 'legacy' },
mapping: {
blueTeamId: TEAM_A_ID,
redTeamId: TEAM_B_ID,
winnerTeamId: TEAM_A_ID,
},
});
return {
parentSeriesId,
childSeriesId,
parentFactId,
childFactId,
parentGameSlotId,
childGameSlotId,
parentCodeId,
childCodeId,
competition: {
...competitionDocument(7),
seriesGraph: [
series(
parentSeriesId,
{ type: 'team', teamId: TEAM_A_ID.toHexString() },
{ type: 'team', teamId: TEAM_B_ID.toHexString() },
),
series(
childSeriesId,
{
type: 'series-outcome',
seriesId: parentSeriesId.toHexString(),
select: 'winner',
},
{ type: 'team', teamId: TEAM_B_ID.toHexString() },
),
],
},
facts: [
accepted(parentFactId, parentSeriesId, parentGameSlotId),
accepted(childFactId, childSeriesId, childGameSlotId),
],
assignments: [
{
competitionId: COMPETITION_ID,
seriesId: parentSeriesId,
gameSlotId: parentGameSlotId,
tournamentCodeId: parentCodeId,
state: 'used',
},
{
competitionId: COMPETITION_ID,
seriesId: childSeriesId,
gameSlotId: childGameSlotId,
tournamentCodeId: childCodeId,
state: 'reserved',
},
],
};
}
File diff suppressed because it is too large. Load diff
@@ -1,367 +0,0 @@
import {
ConflictException,
ForbiddenException,
NotFoundException,
} from '@nestjs/common';
import { Types } from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { CompetitionQueryService } from './competition-query.service';
describe('CompetitionQueryService', () => {
it('does not let a public read race the team-build bootstrap workflow', async () => {
const harness = createHarness({ competition: null });
const service = createService(harness);
await expect(
service.getCompetition({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
}),
).rejects.toBeInstanceOf(ConflictException);
expect(harness.matchModel.findOne).toHaveBeenCalledWith({
_id: MATCH_ID,
communityId: COMMUNITY_ID,
});
});
it('returns an explicit team view with codes only for the callers team', async () => {
const harness = createHarness();
const service = createService(harness);
const result = await service.getTeamView({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
userId: TEAM_A_USER_ID,
});
expect(result).toMatchObject({
competitionId: COMPETITION_ID.toHexString(),
revision: 4,
teamId: TEAM_A_ID.toHexString(),
activeSeries: [expect.objectContaining({ seriesId: SERIES_ID })],
tournamentCodes: [
{
gameSlotId: GAME_SLOT_ID,
seriesId: SERIES_ID,
ordinal: 1,
displayNumber: 1,
state: 'reserved',
code: 'TEAM-A-SECRET-CODE',
expiresAt: '2026-07-13T00:00:00.000Z',
},
],
});
expect(JSON.stringify(result)).not.toContain('OPPONENT-SECRET-CODE');
expect(harness.tournamentCodeModel.find).toHaveBeenCalledWith({
_id: { $in: [TEAM_A_CODE_ID] },
state: { $in: ['reserved', 'used'] },
});
});
it('resolves a team view from an explicit team id without a caller identity', async () => {
const harness = createHarness();
const service = createService(harness);
const result = await service.getTeamView({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
teamId: TEAM_A_ID,
});
expect(result).toMatchObject({
teamId: TEAM_A_ID.toHexString(),
activeSeries: [expect.objectContaining({ seriesId: SERIES_ID })],
tournamentCodes: [
expect.objectContaining({ code: 'TEAM-A-SECRET-CODE' }),
],
});
expect(JSON.stringify(result)).not.toContain('OPPONENT-SECRET-CODE');
});
it('does not resolve a team view for an unknown team id', async () => {
const service = createService(createHarness());
await expect(
service.getTeamView({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
teamId: new Types.ObjectId('64c000000000000000000098'),
}),
).rejects.toBeInstanceOf(NotFoundException);
});
it('does not reveal a team view to an authenticated non-participant', async () => {
const service = createService(createHarness());
await expect(
service.getTeamView({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
userId: new Types.ObjectId('64c000000000000000000099'),
}),
).rejects.toBeInstanceOf(ForbiddenException);
});
it('does not expose a stale code whose active assignment no longer matches', async () => {
const harness = createHarness();
harness.tournamentCodeModel.find.mockReturnValueOnce(queryResult([]));
const service = createService(harness);
await expect(
service.getTeamView({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
userId: TEAM_A_USER_ID,
}),
).rejects.toBeInstanceOf(ConflictException);
});
it('pages facts in immutable revision order using an opaque cursor', async () => {
const harness = createHarness();
harness.factModel.find.mockReturnValueOnce(
queryResult([
factDocument('64c000000000000000000031', 1, 1),
factDocument('64c000000000000000000032', 2, 1),
factDocument('64c000000000000000000033', 3, 1),
]),
);
const service = createService(harness);
const first = await service.listFacts({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
limit: 2,
});
expect(first.facts).toHaveLength(2);
expect(first.nextCursor).toEqual(expect.any(String));
expect(first.facts[0]).toMatchObject({
id: '64c000000000000000000031',
competitionId: COMPETITION_ID.toHexString(),
type: 'game-accepted',
revision: 1,
});
expect(first.facts[0]).not.toHaveProperty('requestHash');
expect(first.facts[0]).not.toHaveProperty('idempotencyKey');
});
});
const COMMUNITY_ID = new Types.ObjectId('64c000000000000000000001');
const MATCH_ID = new Types.ObjectId('64c000000000000000000002');
const COMPETITION_ID = new Types.ObjectId('64c000000000000000000003');
const TEAM_A_ID = new Types.ObjectId('64c000000000000000000004');
const TEAM_B_ID = new Types.ObjectId('64c000000000000000000005');
const TEAM_A_USER_ID = new Types.ObjectId('64c000000000000000000006');
const TEAM_B_USER_ID = new Types.ObjectId('64c000000000000000000007');
const TEAM_A_CODE_ID = new Types.ObjectId('64c000000000000000000008');
const TEAM_B_CODE_ID = new Types.ObjectId('64c000000000000000000009');
const SERIES_ID = 'series-1';
const GAME_SLOT_ID = 'slot-1';
function createService(harness: ReturnType<typeof createHarness>) {
return new CompetitionQueryService(
harness.connectionService as ConnectionService,
);
}
function createHarness(options: { competition?: unknown } = {}) {
const competition =
options.competition === undefined
? competitionDocument()
: options.competition;
const competitionModel = {
findOne: jest.fn().mockReturnValue(queryResult(competition)),
};
const matchModel = {
findOne: jest.fn().mockReturnValue(
queryResult({
_id: MATCH_ID,
communityId: COMMUNITY_ID,
status: 'team-built',
teams: [{ teamIndex: 1 }, { teamIndex: 2 }],
participants: [],
gameMode: 'pair',
gameCount: 3,
}),
),
};
const assignmentModel = {
find: jest.fn().mockReturnValue(
queryResult([
{
competitionId: COMPETITION_ID,
seriesId: SERIES_ID,
gameSlotId: GAME_SLOT_ID,
tournamentCodeId: TEAM_A_CODE_ID,
state: 'reserved',
},
{
competitionId: COMPETITION_ID,
seriesId: 'series-opponent-only',
gameSlotId: 'slot-opponent-only',
tournamentCodeId: TEAM_B_CODE_ID,
state: 'reserved',
},
]),
),
};
const tournamentCodeModel = {
find: jest.fn().mockReturnValue(
queryResult([
{
_id: TEAM_A_CODE_ID,
code: 'TEAM-A-SECRET-CODE',
state: 'reserved',
matchId: MATCH_ID,
expiresAt: new Date('2026-07-13T00:00:00.000Z'),
},
{
_id: TEAM_B_CODE_ID,
code: 'OPPONENT-SECRET-CODE',
state: 'reserved',
matchId: MATCH_ID,
expiresAt: new Date('2026-07-13T00:00:00.000Z'),
},
]),
),
};
const factModel = {
find: jest.fn().mockReturnValue(queryResult([])),
};
const models: Record<string, unknown> = {
competition: competitionModel,
match: matchModel,
tournamentCodeAssignment: assignmentModel,
tournamentCode: tournamentCodeModel,
competitionFact: factModel,
};
return {
competitionModel,
matchModel,
assignmentModel,
tournamentCodeModel,
factModel,
connectionService: {
getModel: jest.fn((name: string) => Promise.resolve(models[name])),
},
};
}
function competitionDocument() {
return {
_id: COMPETITION_ID,
matchId: MATCH_ID,
communityId: COMMUNITY_ID,
schemaVersion: 1,
projectorVersion: 1,
revision: 4,
phase: 'running',
teams: [
{
teamId: TEAM_A_ID,
displayOrder: 1,
seedNumber: 1,
name: 'Team A',
members: [{ userId: TEAM_A_USER_ID, displayName: 'A' }],
},
{
teamId: TEAM_B_ID,
displayOrder: 2,
seedNumber: 2,
name: 'Team B',
members: [{ userId: TEAM_B_USER_ID, displayName: 'B' }],
},
],
format: {
type: 'paired-series',
rule: { type: 'fixed-games', gameCount: 3, drawPolicy: 'allow' },
},
seriesGraph: [],
projection: {
sourceRevision: 4,
projectorVersion: 1,
phase: 'running',
formatType: 'paired-series',
series: [
{
seriesId: SERIES_ID,
status: 'in-progress',
stage: { type: 'pair', displayOrder: 1 },
rule: { type: 'fixed-games', gameCount: 3, drawPolicy: 'allow' },
entries: [
{ slot: 'A', teamId: TEAM_A_ID.toHexString(), gameWins: 1 },
{ slot: 'B', teamId: TEAM_B_ID.toHexString(), gameWins: 0 },
],
},
{
seriesId: 'series-opponent-only',
status: 'in-progress',
stage: { type: 'pair', displayOrder: 2 },
rule: { type: 'fixed-games', gameCount: 3, drawPolicy: 'allow' },
entries: [
{ slot: 'A', teamId: TEAM_B_ID.toHexString(), gameWins: 0 },
{ slot: 'B', teamId: 'other-team', gameWins: 1 },
],
},
],
games: [],
gameSlots: [
{
id: GAME_SLOT_ID,
seriesId: SERIES_ID,
ordinal: 1,
displayNumber: 1,
status: 'reserved',
entries: [],
},
],
rounds: [],
connectors: [],
},
createdAt: new Date('2026-07-11T00:00:00.000Z'),
updatedAt: new Date('2026-07-12T00:00:00.000Z'),
};
}
function factDocument(id: string, revision: number, ordinal: number) {
return {
_id: new Types.ObjectId(id),
competitionId: COMPETITION_ID,
type: 'game-accepted',
revision,
ordinalWithinRevision: ordinal,
commandId: `command-${revision}`,
idempotencyKey: `secret-${revision}`,
requestHash: `hash-${revision}`,
schemaVersion: 1,
actor: { type: 'system' },
occurredAt: new Date('2026-07-12T00:00:00.000Z'),
recordedAt: new Date('2026-07-12T00:00:01.000Z'),
gameId: new Types.ObjectId('64c000000000000000000041'),
seriesId: new Types.ObjectId('64c000000000000000000042'),
gameSlotId: new Types.ObjectId('64c000000000000000000043'),
ordinal: 1,
evidence: { type: 'legacy', legacyReference: 'legacy-1' },
mapping: {
mappingVersion: 1,
confidence: 1,
blueTeamId: TEAM_A_ID,
redTeamId: TEAM_B_ID,
winnerTeamId: TEAM_A_ID,
},
};
}
function queryResult<T>(value: T) {
const query = {
sort: jest.fn(),
limit: jest.fn(),
lean: jest.fn(),
exec: jest.fn().mockResolvedValue(value),
};
query.sort.mockReturnValue(query);
query.limit.mockReturnValue(query);
query.lean.mockReturnValue(query);
return query;
}
@@ -1,407 +0,0 @@
import type {
CompetitionFactView,
CompetitionFactsResponse,
TeamCompetitionViewResponse,
} from '@lolympus/contracts';
import {
ConflictException,
ForbiddenException,
Injectable,
NotFoundException,
UnprocessableEntityException,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type { Competition, CompetitionFact } from './competition.schema';
type PersistenceId = string | mongoose.Types.ObjectId;
type CompetitionRecord = Competition & { _id: mongoose.Types.ObjectId };
export interface CompetitionScope {
communityId: mongoose.Types.ObjectId;
matchId: mongoose.Types.ObjectId;
}
/**
* A team view is addressed either by the caller's membership (signed-in) or by
* an explicit team id. The explicit form exists so that the team progress page
* stays usable while community members have not all signed in yet.
*/
export type TeamViewScope = CompetitionScope &
(
| { userId: mongoose.Types.ObjectId; teamId?: undefined }
| { teamId: mongoose.Types.ObjectId; userId?: undefined }
);
interface CompetitionProjectionSource {
series?: Array<Record<string, unknown>>;
gameSlots?: Array<Record<string, unknown>>;
}
@Injectable()
export class CompetitionQueryService {
constructor(private readonly connectionService: ConnectionService) {}
/** Resolve the aggregate created by the finalized team-build workflow. */
public async getCompetition(
scope: CompetitionScope,
): Promise<CompetitionRecord> {
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findOne({
_id: scope.matchId,
communityId: scope.communityId,
})
.lean()
.exec();
if (!match) throw new NotFoundException('Match not found.');
if (
match.status === 'recruiting' ||
!Array.isArray(match.teams) ||
match.teams.length < 2
) {
throw new ConflictException(
'Competition is unavailable until team building is complete.',
);
}
const CompetitionModel =
await this.connectionService.getModel('competition');
const existing = await CompetitionModel.findOne({
matchId: scope.matchId,
communityId: scope.communityId,
})
.lean()
.exec();
if (existing) return existing as CompetitionRecord;
throw new ConflictException(
'Competition is still being initialized by the team-build workflow.',
);
}
public async getTeamView(
scope: TeamViewScope,
): Promise<TeamCompetitionViewResponse> {
const competition = (await this.getCompetition(scope)) as Competition & {
_id: PersistenceId;
};
const requestedTeamId = scope.teamId;
const team = requestedTeamId
? competition.teams.find(({ teamId }) => sameId(teamId, requestedTeamId))
: competition.teams.find(({ members }) =>
members.some(({ userId }) => sameId(userId, scope.userId)),
);
if (!team) {
if (requestedTeamId) {
throw new NotFoundException('Competition team not found.');
}
throw new ForbiddenException(
'Only a Competition team member may access the team view.',
);
}
const projection = competition.projection as CompetitionProjectionSource;
const allSeries = Array.isArray(projection.series) ? projection.series : [];
const teamId = idString(team.teamId);
const activeSeries = allSeries.filter(
(series) =>
series.status !== 'completed' &&
series.status !== 'inactive' &&
Array.isArray(series.entries) &&
series.entries.some(
(entry) =>
isRecord(entry) &&
idString(entry.teamId as PersistenceId) === teamId,
),
);
const activeSeriesIds = new Set(
activeSeries.map((series) => idString(series.seriesId as PersistenceId)),
);
const gameSlots = (
Array.isArray(projection.gameSlots) ? projection.gameSlots : []
).filter((slot) =>
activeSeriesIds.has(idString(slot.seriesId as PersistenceId)),
);
const AssignmentModel = await this.connectionService.getModel(
'tournamentCodeAssignment',
);
const queriedAssignments = await AssignmentModel.find({
competitionId: competition._id,
seriesId: { $in: [...activeSeriesIds] },
state: { $in: ['reserved', 'used'] },
})
.lean()
.exec();
// Keep this defensive filter even when the persistence query is mocked or
// changed: an opponent-only assignment must never cross this boundary.
const assignments = queriedAssignments.filter((assignment) =>
activeSeriesIds.has(idString(assignment.seriesId)),
);
const codeIds = assignments.map(({ tournamentCodeId }) => tournamentCodeId);
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const codes = codeIds.length
? await TournamentCodeModel.find({
_id: { $in: codeIds },
state: { $in: ['reserved', 'used'] },
})
.lean()
.exec()
: [];
const codeById = new Map(codes.map((code) => [idString(code._id), code]));
const assignmentBySlot = new Map(
assignments.map((assignment) => [
idString(assignment.gameSlotId),
assignment,
]),
);
return {
competitionId: idString(competition._id) as never,
revision: competition.revision,
phase: competition.phase,
teamId: teamId as never,
activeSeries: toWire(activeSeries) as never,
tournamentCodes: gameSlots.map((slot) => {
const gameSlotId = idString(slot.id as PersistenceId);
const assignment = assignmentBySlot.get(gameSlotId);
const code = assignment
? codeById.get(idString(assignment.tournamentCodeId))
: undefined;
if (
assignment &&
(!code ||
code.state !== assignment.state ||
!code.matchId ||
!sameId(code.matchId, competition.matchId))
) {
throw new ConflictException(
'Tournament Code assignment is inconsistent and cannot be exposed.',
);
}
return {
gameSlotId: gameSlotId as never,
seriesId: idString(slot.seriesId as PersistenceId) as never,
ordinal: numberValue(slot.ordinal),
displayNumber: numberValue(slot.displayNumber),
state:
assignment?.state === 'reserved' || assignment?.state === 'used'
? assignment.state
: 'pending',
code: typeof code?.code === 'string' ? code.code : null,
expiresAt: code?.expiresAt ? isoDate(code.expiresAt) : null,
};
}),
};
}
public async listFacts(
scope: CompetitionScope & { cursor?: string; limit?: number },
): Promise<CompetitionFactsResponse> {
const competition = (await this.getCompetition(scope)) as Competition & {
_id: PersistenceId;
};
const limit = normalizeLimit(scope.limit);
const cursor = scope.cursor ? decodeCursor(scope.cursor) : undefined;
const cursorFilter = cursor
? {
$or: [
{ revision: { $gt: cursor.revision } },
{
revision: cursor.revision,
ordinalWithinRevision: { $gt: cursor.ordinalWithinRevision },
},
{
revision: cursor.revision,
ordinalWithinRevision: cursor.ordinalWithinRevision,
_id: { $gt: new mongoose.Types.ObjectId(cursor.id) },
},
],
}
: {};
const FactModel = await this.connectionService.getModel('competitionFact');
const rows = await FactModel.find({
competitionId: competition._id,
...cursorFilter,
})
.sort({ revision: 1, ordinalWithinRevision: 1, _id: 1 })
.limit(limit + 1)
.lean()
.exec();
const page = rows.slice(0, limit);
const last = page.at(-1);
return {
facts: page.map(presentFact),
nextCursor:
rows.length > limit && last
? encodeCursor({
revision: requiredNumber(last.revision, 'revision'),
ordinalWithinRevision: requiredNumber(
last.ordinalWithinRevision,
'ordinalWithinRevision',
),
id: requiredId(last._id, '_id'),
})
: null,
};
}
}
function presentFact(
source: CompetitionFact & { _id: mongoose.Types.ObjectId },
): CompetitionFactView {
const common = {
id: requiredId(source._id, '_id') as never,
competitionId: requiredId(source.competitionId, 'competitionId') as never,
revision: requiredNumber(source.revision, 'revision'),
ordinalWithinRevision: requiredNumber(
source.ordinalWithinRevision,
'ordinalWithinRevision',
),
commandId: requiredString(source.commandId, 'commandId') as never,
schemaVersion: requiredNumber(source.schemaVersion, 'schemaVersion'),
actor: toWire(source.actor) as never,
occurredAt: isoDate(source.occurredAt),
recordedAt: isoDate(source.recordedAt),
...(typeof source.causationId === 'string' && source.causationId.length > 0
? { causationId: source.causationId }
: {}),
};
switch (source.type) {
case 'game-accepted':
return {
...common,
type: 'game-accepted',
gameId: requiredId(source.gameId, 'gameId') as never,
seriesId: requiredId(source.seriesId, 'seriesId') as never,
gameSlotId: requiredId(source.gameSlotId, 'gameSlotId') as never,
ordinal: requiredNumber(source.ordinal, 'ordinal'),
startedAt: isoDate(source.startedAt ?? source.occurredAt),
durationSeconds: numberValue(source.durationSeconds ?? 0),
participants: toWire(source.participants ?? []) as never,
evidence: toWire(source.evidence) as never,
mapping: toWire(source.mapping) as never,
};
case 'game-voided':
return {
...common,
type: 'game-voided',
gameAcceptedFactId: requiredId(
source.gameAcceptedFactId,
'gameAcceptedFactId',
) as never,
reason: requiredString(source.reason, 'reason'),
};
case 'series-adjudicated':
return {
...common,
type: 'series-adjudicated',
seriesId: requiredId(source.seriesId, 'seriesId') as never,
decision: toWire(source.decision) as never,
reason: requiredString(source.reason, 'reason'),
};
case 'adjudication-reversed':
return {
...common,
type: 'adjudication-reversed',
adjudicationFactId: requiredId(
source.adjudicationFactId,
'adjudicationFactId',
) as never,
reason: requiredString(source.reason, 'reason'),
};
default:
throw new Error('Unsupported Competition fact type.');
}
}
interface FactCursor {
revision: number;
ordinalWithinRevision: number;
id: string;
}
function encodeCursor(cursor: FactCursor): string {
return Buffer.from(JSON.stringify(cursor)).toString('base64url');
}
function decodeCursor(value: string): FactCursor {
try {
const parsed: unknown = JSON.parse(
Buffer.from(value, 'base64url').toString('utf8'),
);
if (
!isRecord(parsed) ||
!Number.isInteger(parsed.revision) ||
!Number.isInteger(parsed.ordinalWithinRevision) ||
typeof parsed.id !== 'string' ||
!mongoose.isValidObjectId(parsed.id)
) {
throw new Error('malformed cursor');
}
return parsed as unknown as FactCursor;
} catch {
throw new UnprocessableEntityException('Invalid facts cursor.');
}
}
function normalizeLimit(value: number | undefined): number {
if (value === undefined) return 50;
if (!Number.isInteger(value) || value < 1 || value > 100) {
throw new UnprocessableEntityException(
'Facts page limit must be an integer from 1 through 100.',
);
}
return value;
}
function sameId(left: PersistenceId, right: PersistenceId): boolean {
return idString(left) === idString(right);
}
function idString(value: PersistenceId): string {
return value instanceof mongoose.Types.ObjectId
? value.toHexString()
: String(value);
}
function isoDate(value: unknown): string {
if (value instanceof Date) return value.toISOString();
if (typeof value === 'string') return value;
throw new Error('Competition fact contains an invalid date.');
}
function numberValue(value: unknown): number {
return typeof value === 'number' ? value : Number(value);
}
function toWire(value: unknown): unknown {
if (value instanceof mongoose.Types.ObjectId) return value.toHexString();
if (value instanceof Date) return value.toISOString();
if (Array.isArray(value)) return value.map(toWire);
if (isRecord(value)) {
return Object.fromEntries(
Object.entries(value).map(([key, child]) => [key, toWire(child)]),
);
}
return value;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function requiredId(value: unknown, field: string): string {
if (value instanceof mongoose.Types.ObjectId) return value.toHexString();
return requiredString(value, field);
}
function requiredString(value: unknown, field: string): string {
if (typeof value === 'string' && value.length > 0) return value;
throw new Error(`Competition fact contains an invalid ${field}.`);
}
function requiredNumber(value: unknown, field: string): number {
if (typeof value === 'number' && Number.isFinite(value)) return value;
throw new Error(`Competition fact contains an invalid ${field}.`);
}
@@ -1,411 +0,0 @@
import { HttpException } from '@nestjs/common';
import { Types } from 'mongoose';
import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from '../auth/allow-public-access.decorator';
import { ROLES_KEY } from '../auth/roles.decorator';
import { CompetitionCommandService } from './competition-command.service';
import { CompetitionController } from './competition.controller';
import { CompetitionQueryService } from './competition-query.service';
describe('CompetitionController', () => {
it('marks the read endpoints public and writes a revision ETag', async () => {
const { controller, queryService } = createHarness();
const response = { setHeader: jest.fn() };
const result = await controller.getDetail(
COMMUNITY_ID,
MATCH_ID,
response as never,
);
for (const method of ['getDetail', 'getTeamView'] as const) {
expect(
Reflect.getMetadata(
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
CompetitionController.prototype[method],
),
).toBe(true);
}
expect(response.setHeader).toHaveBeenCalledWith('ETag', '"7"');
expect(result).toMatchObject({ revision: 7 });
expect(queryService.getCompetition).toHaveBeenCalledWith({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
});
});
it('reads a team view by explicit team id without an authenticated caller', async () => {
const { controller, queryService } = createHarness();
queryService.getTeamView.mockResolvedValue({ revision: 7 });
const response = { setHeader: jest.fn() };
const result = await controller.getTeamView(
undefined,
COMMUNITY_ID,
MATCH_ID,
TEAM_A_ID.toHexString(),
response as never,
);
expect(queryService.getTeamView).toHaveBeenCalledWith({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
teamId: TEAM_A_ID,
});
expect(response.setHeader).toHaveBeenCalledWith('ETag', '"7"');
expect(result).toMatchObject({ revision: 7 });
});
it('falls back to the membership-scoped team view for a signed-in caller', async () => {
const { controller, queryService } = createHarness();
queryService.getTeamView.mockResolvedValue({ revision: 7 });
await controller.getTeamView(adminUser(), COMMUNITY_ID, MATCH_ID);
expect(queryService.getTeamView).toHaveBeenCalledWith({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
userId: ADMIN_ID,
});
});
it('rejects an anonymous team view request that names no team', async () => {
const { controller, queryService } = createHarness();
await expect(
controller.getTeamView(undefined, COMMUNITY_ID, MATCH_ID),
).rejects.toMatchObject({
status: 401,
response: { error: { code: 'COMPETITION_TEAM_UNIDENTIFIED' } },
});
expect(queryService.getTeamView).not.toHaveBeenCalled();
});
it('rejects a malformed team id', async () => {
const { controller, queryService } = createHarness();
await expect(
controller.getTeamView(undefined, COMMUNITY_ID, MATCH_ID, 'not-an-id'),
).rejects.toMatchObject({
status: 422,
response: { error: { code: 'INVALID_COMPETITION_REQUEST' } },
});
expect(queryService.getTeamView).not.toHaveBeenCalled();
});
it('protects audit and mutation endpoints with admin roles', () => {
for (const method of [
'listFacts',
'acceptGame',
'adjudicateSeries',
'previewReversal',
'reverseSeries',
] as const) {
expect(
Reflect.getMetadata(ROLES_KEY, CompetitionController.prototype[method]),
).toEqual(['owner', 'admin']);
}
});
it('requires If-Match and Idempotency-Key for a mutation', async () => {
const { controller } = createHarness();
await expect(
controller.acceptGame(
adminUser(),
COMMUNITY_ID,
MATCH_ID,
undefined,
undefined,
acceptGameBody(),
),
).rejects.toMatchObject({
status: 422,
response: {
error: { code: 'INVALID_COMPETITION_COMMAND_HEADERS' },
},
});
});
it('passes revision, idempotency and the authenticated actor to accept-game', async () => {
const { controller, commandService } = createHarness();
await controller.acceptGame(
adminUser(),
COMMUNITY_ID,
MATCH_ID,
'W/"7"',
'operator:accept:1',
acceptGameBody(),
);
expect(commandService.acceptGame).toHaveBeenCalledWith(
expect.objectContaining({
expectedRevision: 7,
idempotencyKey: 'operator:accept:1',
}),
);
const accepted = commandService.acceptGame.mock.calls[0][0];
expect(accepted.competitionId.toHexString()).toBe(
COMPETITION_ID.toHexString(),
);
expect(accepted.actor.userId.toHexString()).toBe(ADMIN_ID.toHexString());
expect(accepted.gameId.toHexString()).toBe(GAME_ID.toHexString());
expect(accepted.seriesId.toHexString()).toBe(SERIES_ID);
expect(accepted.gameSlotId.toHexString()).toBe(GAME_SLOT_ID.toHexString());
});
it('maps command conflicts to the explicit error envelope', async () => {
const { controller, commandService } = createHarness();
commandService.adjudicateSeries.mockRejectedValue({
code: 'IDEMPOTENCY_KEY_CONFLICT',
message: 'duplicate key with another payload',
httpStatus: 409,
details: { idempotencyKey: 'same-key' },
});
let thrown: unknown;
try {
await controller.adjudicateSeries(
adminUser(),
COMMUNITY_ID,
MATCH_ID,
new Types.ObjectId(SERIES_ID),
'"7"',
'same-key',
{
decision: { type: 'administrative-draw' },
reason: '운영 판단',
},
);
} catch (error) {
thrown = error;
}
expect(thrown).toBeInstanceOf(HttpException);
expect(thrown).toMatchObject({
status: 409,
response: {
error: {
code: 'IDEMPOTENCY_KEY_CONFLICT',
details: { idempotencyKey: 'same-key' },
},
},
});
});
it.each([
{
source: {
code: 'STALE_COMPETITION_REVISION',
message: 'stale',
httpStatus: 412,
},
status: 412,
},
{
source: {
code: 'GAME_TEAM_MISMATCH',
message: 'invalid evidence mapping',
},
status: 422,
},
])('maps $source.code to HTTP $status', async ({ source, status }) => {
const { controller, commandService } = createHarness();
commandService.acceptGame.mockRejectedValue(source);
await expect(
controller.acceptGame(
adminUser(),
COMMUNITY_ID,
MATCH_ID,
'"7"',
`operator:error:${status}`,
acceptGameBody(),
),
).rejects.toMatchObject({
status,
response: { error: { code: source.code } },
});
});
it('returns an explicit 422 envelope for an invalid command body', async () => {
const { controller, commandService } = createHarness();
await expect(
controller.adjudicateSeries(
adminUser(),
COMMUNITY_ID,
MATCH_ID,
new Types.ObjectId(SERIES_ID),
'"7"',
'operator:invalid-body:1',
{
decision: { type: 'walkover' },
reason: '',
},
),
).rejects.toMatchObject({
status: 422,
response: {
error: { code: 'INVALID_COMPETITION_REQUEST' },
},
});
expect(commandService.adjudicateSeries).not.toHaveBeenCalled();
});
it('rejects malformed game evidence before it reaches the ledger', async () => {
const { controller, commandService } = createHarness();
await expect(
controller.acceptGame(
adminUser(),
COMMUNITY_ID,
MATCH_ID,
'"7"',
'operator:bad-evidence:1',
{
...acceptGameBody(),
evidence: { type: 'invented-evidence' },
},
),
).rejects.toMatchObject({
status: 422,
response: {
error: { code: 'INVALID_COMPETITION_REQUEST' },
},
});
expect(commandService.acceptGame).not.toHaveBeenCalled();
});
it('requires the same revision for preview and hash-confirmed reversal', async () => {
const { controller, commandService } = createHarness();
await controller.previewReversal(
adminUser(),
COMMUNITY_ID,
MATCH_ID,
new Types.ObjectId(SERIES_ID),
'"7"',
{ mode: 'cascade', reason: '잘못 수집됨' },
);
await controller.reverseSeries(
adminUser(),
COMMUNITY_ID,
MATCH_ID,
new Types.ObjectId(SERIES_ID),
'"7"',
'operator:reverse:1',
{
mode: 'cascade',
reason: '잘못 수집됨',
impactHash: 'a'.repeat(64),
},
);
expect(commandService.previewSeriesReversal).toHaveBeenCalledWith({
competitionId: COMPETITION_ID,
expectedRevision: 7,
seriesId: new Types.ObjectId(SERIES_ID),
mode: 'cascade',
});
expect(commandService.reverseSeries).toHaveBeenCalledWith(
expect.objectContaining({
competitionId: COMPETITION_ID,
expectedRevision: 7,
idempotencyKey: 'operator:reverse:1',
impactHash: 'a'.repeat(64),
}),
);
});
});
const COMMUNITY_ID = new Types.ObjectId('64d000000000000000000001');
const MATCH_ID = new Types.ObjectId('64d000000000000000000002');
const COMPETITION_ID = new Types.ObjectId('64d000000000000000000003');
const ADMIN_ID = new Types.ObjectId('64d000000000000000000004');
const GAME_ID = new Types.ObjectId('64d000000000000000000005');
const SERIES_ID = '64d000000000000000000006';
const GAME_SLOT_ID = new Types.ObjectId('64d000000000000000000007');
const TEAM_A_ID = new Types.ObjectId('64d000000000000000000008');
const TEAM_B_ID = new Types.ObjectId('64d000000000000000000009');
function createHarness() {
const competition = {
_id: COMPETITION_ID,
matchId: MATCH_ID,
communityId: COMMUNITY_ID,
schemaVersion: 1,
revision: 7,
phase: 'running',
teams: [],
format: {
type: 'paired-series',
rule: { type: 'fixed-games', gameCount: 3, drawPolicy: 'allow' },
},
projection: {
sourceRevision: 7,
projectorVersion: 1,
phase: 'running',
formatType: 'paired-series',
series: [],
games: [],
gameSlots: [],
rounds: [],
connectors: [],
},
createdAt: new Date('2026-07-11T00:00:00.000Z'),
updatedAt: new Date('2026-07-12T00:00:00.000Z'),
};
const queryService = {
getCompetition: jest.fn().mockResolvedValue(competition),
getTeamView: jest.fn(),
listFacts: jest.fn(),
};
const commandService = {
acceptGame: jest.fn().mockResolvedValue({ competition, revision: 8 }),
adjudicateSeries: jest.fn().mockResolvedValue({ competition, revision: 8 }),
previewSeriesReversal: jest.fn().mockResolvedValue({
sourceRevision: 7,
impactHash: 'a'.repeat(64),
impact: {},
}),
reverseSeries: jest.fn().mockResolvedValue({ competition, revision: 8 }),
};
return {
queryService,
commandService,
controller: new CompetitionController(
queryService as unknown as CompetitionQueryService,
commandService as unknown as CompetitionCommandService,
),
};
}
function adminUser() {
return {
_id: ADMIN_ID,
communityId: COMMUNITY_ID,
role: 'admin',
} as never;
}
function acceptGameBody() {
return {
gameId: GAME_ID.toHexString(),
seriesId: SERIES_ID,
gameSlotId: GAME_SLOT_ID.toHexString(),
ordinal: 1,
evidence: {
type: 'riot',
riotMatchId: 'KR_1',
payloadHash: 'sha256:value',
},
mapping: {
mappingVersion: 1,
confidence: 1,
blueTeamId: TEAM_A_ID.toHexString(),
redTeamId: TEAM_B_ID.toHexString(),
winnerTeamId: TEAM_A_ID.toHexString(),
},
};
}
@@ -1,530 +0,0 @@
import type {
CompetitionCommandResponse,
CompetitionDetailResponse,
CompetitionFactsResponse,
SeriesReversalPreviewResponse,
TeamCompetitionViewResponse,
} from '@lolympus/contracts';
import {
Body,
Controller,
Get,
Headers,
HttpException,
Param,
Post,
Query,
Res,
UseGuards,
} from '@nestjs/common';
import type { Response } from 'express';
import mongoose from 'mongoose';
import { plainToInstance } from 'class-transformer';
import { validateSync, type ValidationError } from 'class-validator';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { CurrentUser } from '../auth/current-user.decorator';
import { Roles } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import type { UserDocument } from '../global/database/schema';
import { CompetitionCommandService } from './competition-command.service';
import { presentCompetitionDetail } from './competition.presenter';
import { CompetitionQueryService } from './competition-query.service';
import {
AcceptCompetitionGameDto,
AdjudicateCompetitionSeriesDto,
CompetitionFactsQueryDto,
PreviewCompetitionSeriesReversalDto,
ReverseCompetitionSeriesDto,
} from './dto/competition-command.dto';
@Controller('communities/:communityId/matches/:matchId/competition')
export class CompetitionController {
constructor(
private readonly queryService: CompetitionQueryService,
private readonly commandService: CompetitionCommandService,
) {}
@Get()
@AllowPublicAccess()
public async getDetail(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Res({ passthrough: true }) response: Response,
): Promise<CompetitionDetailResponse> {
return this.translate(async () => {
const competition = await this.queryService.getCompetition({
communityId,
matchId,
});
response.setHeader('ETag', revisionEtag(competition.revision));
return presentCompetitionDetail(competition as never);
});
}
// Temporarily public: community members are not all signed in yet, so the
// team progress page addresses a team through an explicit `teamId` instead of
// the caller's identity. A signed-in caller with no `teamId` keeps the
// membership-scoped behaviour.
@Get('team')
@AllowPublicAccess()
public async getTeamView(
@CurrentUser() currentUser: UserDocument | undefined,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Query('teamId') requestedTeamId?: string,
@Res({ passthrough: true }) response?: Response,
): Promise<TeamCompetitionViewResponse> {
return this.translate(async () => {
const teamId = parseOptionalObjectId(requestedTeamId, 'teamId');
if (!teamId) {
if (!currentUser) {
throw apiHttpError(
401,
'COMPETITION_TEAM_UNIDENTIFIED',
'Sign in or provide a teamId query parameter to read a team view.',
);
}
assertSameCommunity(currentUser, communityId);
}
const result = await this.queryService.getTeamView({
communityId,
matchId,
...(teamId ? { teamId } : { userId: currentUser!._id }),
});
response?.setHeader('ETag', revisionEtag(result.revision));
return result;
});
}
@Get('facts')
@Roles('owner', 'admin')
@UseGuards(RolesGuard)
public async listFacts(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Query() rawQuery: unknown,
): Promise<CompetitionFactsResponse> {
return this.translate(async () => {
assertSameCommunity(currentUser, communityId);
const query = validateDto(CompetitionFactsQueryDto, rawQuery);
return this.queryService.listFacts({
communityId,
matchId,
cursor: query.cursor,
limit: query.limit,
});
});
}
@Post('games/accept')
@Roles('owner', 'admin')
@UseGuards(RolesGuard)
public async acceptGame(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Headers('if-match') ifMatch: string | undefined,
@Headers('idempotency-key') idempotencyKey: string | undefined,
@Body() rawBody: unknown,
): Promise<CompetitionCommandResponse> {
return this.translate(async () => {
assertSameCommunity(currentUser, communityId);
const body = validateDto(AcceptCompetitionGameDto, rawBody);
const expectedRevision = requireCommandHeaders(ifMatch, idempotencyKey);
const competition = await this.queryService.getCompetition({
communityId,
matchId,
});
const result = await this.commandService.acceptGame({
competitionId: competition._id,
expectedRevision,
idempotencyKey: idempotencyKey!,
actor: { type: 'user', userId: currentUser._id },
gameId: new mongoose.Types.ObjectId(body.gameId),
seriesId: new mongoose.Types.ObjectId(body.seriesId),
gameSlotId: new mongoose.Types.ObjectId(body.gameSlotId),
ordinal: body.ordinal,
evidence: { ...body.evidence },
mapping: { ...body.mapping },
...(body.startedAt ? { startedAt: body.startedAt } : {}),
...(body.durationSeconds === undefined
? {}
: { durationSeconds: body.durationSeconds }),
...(body.participants ? { participants: body.participants } : {}),
...(body.tournamentCode
? {
tournamentCode: {
tournamentCodeId: new mongoose.Types.ObjectId(
body.tournamentCode.tournamentCodeId,
),
riotMatchId: body.tournamentCode.riotMatchId,
},
}
: {}),
});
return {
competition: presentCompetitionDetail(result.competition as never),
};
});
}
@Post('series/:seriesId/adjudications')
@Roles('owner', 'admin')
@UseGuards(RolesGuard)
public async adjudicateSeries(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Param('seriesId', ParseObjectIdPipe) seriesId: mongoose.Types.ObjectId,
@Headers('if-match') ifMatch: string | undefined,
@Headers('idempotency-key') idempotencyKey: string | undefined,
@Body() rawBody: unknown,
): Promise<CompetitionCommandResponse> {
return this.translate(async () => {
assertSameCommunity(currentUser, communityId);
const body = validateDto(AdjudicateCompetitionSeriesDto, rawBody);
const expectedRevision = requireCommandHeaders(ifMatch, idempotencyKey);
const competition = await this.queryService.getCompetition({
communityId,
matchId,
});
const decision =
body.decision.type === 'administrative-draw'
? ({ type: 'administrative-draw' } as const)
: {
type: body.decision.type,
winnerTeamId: new mongoose.Types.ObjectId(
body.decision.winnerTeamId!,
),
};
const result = await this.commandService.adjudicateSeries({
competitionId: competition._id,
expectedRevision,
idempotencyKey: idempotencyKey!,
actor: { type: 'user', userId: currentUser._id },
seriesId,
decision,
reason: body.reason,
});
return {
competition: presentCompetitionDetail(result.competition as never),
};
});
}
@Post('series/:seriesId/reversal-preview')
@Roles('owner', 'admin')
@UseGuards(RolesGuard)
public async previewReversal(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Param('seriesId', ParseObjectIdPipe) seriesId: mongoose.Types.ObjectId,
@Headers('if-match') ifMatch: string | undefined,
@Body() rawBody: unknown,
): Promise<SeriesReversalPreviewResponse> {
return this.translate(async () => {
assertSameCommunity(currentUser, communityId);
const body = validateDto(PreviewCompetitionSeriesReversalDto, rawBody);
const expectedRevision = requireRevisionHeader(ifMatch);
const competition = await this.queryService.getCompetition({
communityId,
matchId,
});
return (await this.commandService.previewSeriesReversal({
competitionId: competition._id,
expectedRevision,
seriesId,
mode: body.mode,
})) as SeriesReversalPreviewResponse;
});
}
@Post('series/:seriesId/reverse')
@Roles('owner', 'admin')
@UseGuards(RolesGuard)
public async reverseSeries(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Param('seriesId', ParseObjectIdPipe) seriesId: mongoose.Types.ObjectId,
@Headers('if-match') ifMatch: string | undefined,
@Headers('idempotency-key') idempotencyKey: string | undefined,
@Body() rawBody: unknown,
): Promise<CompetitionCommandResponse> {
return this.translate(async () => {
assertSameCommunity(currentUser, communityId);
const body = validateDto(ReverseCompetitionSeriesDto, rawBody);
const expectedRevision = requireCommandHeaders(ifMatch, idempotencyKey);
const competition = await this.queryService.getCompetition({
communityId,
matchId,
});
const result = await this.commandService.reverseSeries({
competitionId: competition._id,
expectedRevision,
idempotencyKey: idempotencyKey!,
actor: { type: 'user', userId: currentUser._id },
seriesId,
mode: body.mode,
reason: body.reason,
impactHash: body.impactHash,
});
return {
competition: presentCompetitionDetail(result.competition as never),
};
});
}
private async translate<T>(operation: () => Promise<T>): Promise<T> {
try {
return await operation();
} catch (error) {
throw explicitHttpError(error);
}
}
}
function requireCommandHeaders(
ifMatch: string | undefined,
idempotencyKey: string | undefined,
): number {
const revision = parseRevision(ifMatch);
if (
revision === undefined ||
typeof idempotencyKey !== 'string' ||
idempotencyKey.trim().length === 0 ||
idempotencyKey.length > 200
) {
throw apiHttpError(
422,
'INVALID_COMPETITION_COMMAND_HEADERS',
'A numeric If-Match revision and non-empty Idempotency-Key are required.',
);
}
return revision;
}
function parseOptionalObjectId(
value: string | undefined,
field: string,
): mongoose.Types.ObjectId | undefined {
if (value === undefined || value.trim().length === 0) return undefined;
if (!mongoose.isValidObjectId(value)) {
throw apiHttpError(
422,
'INVALID_COMPETITION_REQUEST',
`The ${field} query parameter must be a valid ObjectId.`,
);
}
return new mongoose.Types.ObjectId(value);
}
function requireRevisionHeader(ifMatch: string | undefined): number {
const revision = parseRevision(ifMatch);
if (revision === undefined) {
throw apiHttpError(
422,
'INVALID_COMPETITION_COMMAND_HEADERS',
'A numeric If-Match revision is required.',
);
}
return revision;
}
function parseRevision(value: string | undefined): number | undefined {
if (!value) return undefined;
const match = /^(?:W\/)?"?(\d+)"?$/.exec(value.trim());
if (!match) return undefined;
const revision = Number(match[1]);
return Number.isSafeInteger(revision) ? revision : undefined;
}
function revisionEtag(revision: number): string {
return `"${revision}"`;
}
function assertSameCommunity(
user: UserDocument,
communityId: mongoose.Types.ObjectId,
): void {
if (!user?.communityId?.equals(communityId)) {
throw apiHttpError(
403,
'COMPETITION_COMMUNITY_FORBIDDEN',
'The authenticated user does not belong to this community.',
);
}
}
function explicitHttpError(error: unknown): HttpException {
if (error instanceof HttpException) {
const response = error.getResponse();
if (
typeof response === 'object' &&
response !== null &&
'error' in response
) {
return error;
}
return apiHttpError(
error.getStatus(),
statusCodeName(error.getStatus()),
typeof response === 'string'
? response
: error.message || 'Competition request failed.',
);
}
if (isCodedError(error)) {
return apiHttpError(
error.httpStatus ?? codedErrorStatus(error.code),
error.code,
error.message,
error.details,
);
}
return apiHttpError(
500,
'COMPETITION_INTERNAL_ERROR',
'Competition request failed.',
);
}
function codedErrorStatus(code: string): number {
switch (code) {
case 'REVERSAL_SERIES_NOT_FOUND':
case 'REVERSAL_REASON_REQUIRED':
return 422;
case 'REVERSAL_DESCENDANT_ACTIVITY':
case 'REVERSAL_NO_ACTIVE_RESULT':
case 'REVERSAL_PREVIEW_STALE':
case 'DUPLICATE_FACT_ID':
case 'DUPLICATE_GAME_ID':
case 'DUPLICATE_RIOT_MATCH_ID':
case 'DUPLICATE_GAME_SLOT':
case 'DUPLICATE_GAME_ORDINAL':
case 'DUPLICATE_ADJUDICATION':
case 'FACT_ALREADY_REVERSED':
case 'SERIES_ALREADY_COMPLETED':
case 'WALKOVER_HAS_ACTIVE_GAMES':
return 409;
case 'FACT_REFERENCE_NOT_FOUND':
case 'FACT_TYPE_INVALID':
case 'GAME_SLOT_INVALID':
case 'GAME_ORDINAL_INVALID':
case 'GAME_SERIES_MISMATCH':
case 'GAME_TEAM_MISMATCH':
case 'GAME_WINNER_INVALID':
case 'SERIES_DEFINITION_INVALID':
case 'SERIES_PARTICIPANTS_INVALID':
case 'ADJUDICATION_INVALID':
case 'ADJUDICATION_DRAW_NOT_ALLOWED':
return 422;
default:
return 500;
}
}
function statusCodeName(status: number): string {
switch (status) {
case 403:
return 'COMPETITION_FORBIDDEN';
case 404:
return 'COMPETITION_NOT_FOUND';
case 409:
return 'COMPETITION_CONFLICT';
case 412:
return 'STALE_COMPETITION_REVISION';
case 422:
return 'INVALID_COMPETITION_REQUEST';
default:
return 'COMPETITION_REQUEST_FAILED';
}
}
function apiHttpError(
status: number,
code: string,
message: string,
details?: unknown,
): HttpException {
return new HttpException(
{
error: {
code,
message,
...(details === undefined ? {} : { details }),
},
},
status,
);
}
function isCodedError(error: unknown): error is {
code: string;
message: string;
httpStatus?: number;
details?: unknown;
} {
return (
typeof error === 'object' &&
error !== null &&
typeof (error as { code?: unknown }).code === 'string' &&
typeof (error as { message?: unknown }).message === 'string'
);
}
type DtoConstructor<T extends object> = new () => T;
function validateDto<T extends object>(
constructor: DtoConstructor<T>,
value: unknown,
): T {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
throw apiHttpError(
422,
'INVALID_COMPETITION_REQUEST',
'The Competition request body must be an object.',
);
}
const instance = plainToInstance(constructor, value);
const errors = validateSync(instance, {
whitelist: true,
forbidNonWhitelisted: true,
forbidUnknownValues: true,
});
if (errors.length > 0) {
throw apiHttpError(
422,
'INVALID_COMPETITION_REQUEST',
'The Competition request payload is invalid.',
{ fields: flattenValidationErrors(errors) },
);
}
return instance;
}
function flattenValidationErrors(
errors: readonly ValidationError[],
prefix = '',
): Array<{ field: string; constraints: string[] }> {
return errors.flatMap((error) => {
const field = prefix ? `${prefix}.${error.property}` : error.property;
const current = error.constraints
? [{ field, constraints: Object.values(error.constraints) }]
: [];
return [
...current,
...flattenValidationErrors(error.children ?? [], field),
];
});
}
@@ -1,23 +0,0 @@
export type CompetitionCommandErrorCode =
| 'COMPETITION_NOT_FOUND'
| 'COMPETITION_TRANSACTION_UNAVAILABLE'
| 'IDEMPOTENCY_KEY_CONFLICT'
| 'INVALID_COMPETITION_COMMAND'
| 'STALE_COMPETITION_REVISION'
| 'TOURNAMENT_CODE_ASSIGNMENT_CONFLICT';
/**
* Transport-neutral command failure. Controllers may translate `httpStatus`
* directly while command handlers remain usable by jobs and migrations.
*/
export class CompetitionCommandError extends Error {
constructor(
public readonly code: CompetitionCommandErrorCode,
message: string,
public readonly httpStatus: 404 | 409 | 412 | 422 | 500,
public readonly details?: Readonly<Record<string, unknown>>,
) {
super(message);
this.name = 'CompetitionCommandError';
}
}
Loaded 100 of 441 files, more files were not shown because too many files have changed in this diff. Show more