Compare commits
102
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6697cd8ea1 | ||
|
|
c435e8a6a5 | ||
|
|
15ae680ec7 | ||
|
|
bdea0287a5 | ||
|
|
b56728f843 | ||
|
|
7f2b34fd4b | ||
|
|
146349beb8 | ||
|
|
326e0c66b6 | ||
|
|
edfb960e97 | ||
|
|
b2d438785b | ||
|
|
b6dad78d02 | ||
|
|
42d4854f9c | ||
|
|
e9081d77c9 | ||
|
|
181beb85e5 | ||
|
|
ebca348723 | ||
|
|
de8bc87940 | ||
|
|
25f3ccad57 | ||
|
|
55ab5b27dc | ||
|
|
1c0af891fa | ||
|
|
528744ebf6 | ||
|
|
bd52160d91 | ||
|
|
c3a3eb46dd | ||
|
|
be5383a2e9 | ||
|
|
ef693fcf4a | ||
|
|
8a9dd37755 | ||
|
|
5ad0f8a1c2 | ||
|
|
c4f19d256d | ||
|
|
ad84bf1f89 | ||
|
|
b711c63dcd | ||
|
|
6a192276e8 | ||
|
|
994a9fcad0 | ||
|
|
2dae3c7cae | ||
|
|
a896342429 | ||
|
|
7b636ee793 | ||
|
|
e63fba0286 | ||
|
|
245a096606 | ||
|
|
6e0afe84cd | ||
|
|
6accb4b166 | ||
|
|
f3d05004ce | ||
|
|
eadae789c8 | ||
|
|
d0d578b2b0 | ||
|
|
4ab3c3a135 | ||
|
|
251eb6deb9 | ||
|
|
b7886589cb | ||
|
|
33abda997f | ||
|
|
85ba8044da | ||
|
|
e306d696a9 | ||
|
|
da5f542292 | ||
|
|
f62e0db849 | ||
|
|
3176db8c48 | ||
|
|
7620b1677a | ||
|
|
1d7fdc9622 | ||
|
|
9c05850cba | ||
|
|
b5aa58dde8 | ||
|
|
3b2ac601a0 | ||
|
|
404f7713b9 | ||
|
|
ba3894cba2 | ||
|
|
9ebdc9b61f | ||
|
|
5fda22c36a | ||
|
|
1e304f48e5 | ||
|
|
ad3c37c48c | ||
|
|
f266d1de83 | ||
|
|
956e45ee59 | ||
|
|
b3b59d37fc | ||
|
|
fc81beec45 | ||
|
|
3447162aa5 | ||
|
|
06c190a41f | ||
|
|
862d662a51 | ||
|
|
95c8ed3c8b | ||
|
|
6bad4861e6 | ||
|
|
422472a641 | ||
|
|
7e78b1f92d | ||
|
|
4bc2df7bcc | ||
|
|
c212505ffe | ||
|
|
9ac777b5a4 | ||
|
|
c07b040467 | ||
|
|
78a8f136d0 | ||
|
|
3c8dce1e9b | ||
|
|
b12f44424e | ||
|
|
b4be06ae83 | ||
|
|
041b1fc8b9 | ||
|
|
87447a4f09 | ||
|
|
6cd213a462 | ||
|
|
caf517123b | ||
|
|
d4b790fd86 | ||
|
|
3a86676a12 | ||
|
|
9fbb11c634 | ||
|
|
39f3221640 | ||
|
|
a796620b7f | ||
|
|
3a3e7938f5 | ||
|
|
9f6974c577 | ||
|
|
d6f52a8b15 | ||
|
|
463c839782 | ||
|
|
5361dc8adb | ||
|
|
54db90b0df | ||
|
|
2e311d9cbf | ||
|
|
f24674b12c | ||
|
|
714349d519 | ||
|
|
7cde555bef | ||
|
|
a7820444fc | ||
|
|
fa13bc48d4 | ||
|
|
6f891c36af |
No files matched your search
+12
-8
@@ -1,5 +1,5 @@
|
||||
bin/
|
||||
lib/
|
||||
/lib/
|
||||
dist/
|
||||
node_modules/
|
||||
.pnpm-store/
|
||||
@@ -17,15 +17,19 @@ website/LICENSE
|
||||
!internals/template/*/README.md
|
||||
!internals/template/*/LICENSE
|
||||
|
||||
# Keep planning notes, screenshots, and local scrape/log captures out of Git.
|
||||
*.md
|
||||
*.log
|
||||
/*.png
|
||||
/*.jpg
|
||||
/*.jpeg
|
||||
/*.txt
|
||||
/user-game-history/
|
||||
|
||||
!.claude/settings.json
|
||||
|
||||
*.temp.MD
|
||||
|
||||
*.md
|
||||
!README.md
|
||||
!AGENTS.md
|
||||
!agents/**/*.md
|
||||
!skills/**/*.md
|
||||
/tmp/
|
||||
/user-game-history/
|
||||
/*.txt
|
||||
/*.png
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
# 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`.
|
||||
@@ -0,0 +1 @@
|
||||
68
|
||||
+2
-3
@@ -35,7 +35,7 @@ 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
|
||||
@@ -43,8 +43,7 @@ COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/package.json ./apps/
|
||||
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/node_modules ./apps/api/node_modules
|
||||
COPY --from=build --chown=nonroot:nonroot /app/apps/api/dist ./apps/api/dist
|
||||
COPY --chown=nonroot:nonroot apps/project.env ./project.env
|
||||
COPY --chown=nonroot:nonroot apps/api/docker-entrypoint.js ./apps/api/docker-entrypoint.js
|
||||
|
||||
EXPOSE 10712
|
||||
|
||||
CMD ["apps/api/docker-entrypoint.js"]
|
||||
CMD ["apps/api/dist/main.js"]
|
||||
@@ -0,0 +1,114 @@
|
||||
# LOLYMPUS
|
||||
|
||||

|
||||
|
||||
## Overview
|
||||
|
||||
LOLYMPUS는 리그 오브 레전드 내전을 운영할 때 필요한 것들을 한곳에 모아둔 웹 애플리케이션입니다.
|
||||
|
||||
참가자 모집, 팀 편성, 경매, 토너먼트 코드 배정, 경기 결과 수집, 전적 확인처럼 운영자가 매번 손으로 챙기던 일을 줄이는 데 초점을 맞췄습니다. 처음부터 큰 서비스로 만들었다기보다는, 실제 커뮤니티 내전을 굴리면서 불편했던 부분을 하나씩 붙여가며 만든 프로젝트입니다.
|
||||
|
||||
## Purpose
|
||||
|
||||
내전은 사람만 모이면 끝나는 일이 아니었습니다. 참가자 티어를 확인하고, 포지션을 맞추고, 팀장을 정하고, 경기마다 토너먼트 코드를 나눠주고, 끝난 뒤 결과까지 정리해야 했습니다.
|
||||
|
||||
이 프로젝트는 그 흐름을 최대한 덜 번거롭게 만들기 위해 시작했습니다. 운영자는 전체 진행 상황을 보고, 참가자는 본인이 속한 팀과 다음 경기를 빠르게 확인할 수 있도록 구성했습니다.
|
||||
|
||||
## Screens
|
||||
|
||||
### Match detail
|
||||
|
||||

|
||||
|
||||
### Team progress
|
||||
|
||||

|
||||
|
||||
## Functionalities
|
||||
|
||||
**1. 내전 관리**
|
||||
내전 생성, 수정, 모집 상태 변경, 참가자 목록 확인을 할 수 있습니다.
|
||||
|
||||
**2. 참가자 정보 관리**
|
||||
Riot 계정 정보를 기반으로 소환사명, 태그, 프로필 아이콘, 솔로랭크/자유랭크 티어, 선호 포지션을 보여줍니다.
|
||||
|
||||
**3. 팀 빌딩**
|
||||
팀장을 정하고 포지션을 맞춰 팀을 구성합니다. 여러 팀이 참여하는 내전도 처리할 수 있습니다.
|
||||
|
||||
**4. 경매 진행**
|
||||
팀장 경매 방식으로 참가자를 뽑을 수 있고, 현재 입찰가와 낙찰 기록을 관리합니다.
|
||||
|
||||
**5. 토너먼트 코드 관리**
|
||||
업로드한 토너먼트 코드를 경기별로 배정하고, 팀별 진행 페이지에서 바로 복사할 수 있게 했습니다.
|
||||
|
||||
**6. 팀별 진행 페이지**
|
||||
각 팀이 자기 경기 일정, 상대 팀, 토너먼트 코드, 종료된 경기 결과를 한 화면에서 확인할 수 있습니다.
|
||||
|
||||
**7. 전적 수집과 통계**
|
||||
Riot Match-V5 데이터를 이용해 내전 결과를 수집하고, 개인 전적과 커뮤니티 리더보드를 보여줍니다.
|
||||
|
||||
**8. 커뮤니티 명령 연동**
|
||||
Dakao/NATS 기반 명령을 받아 참가 신청이나 운영 흐름과 연결할 수 있도록 구성했습니다.
|
||||
|
||||
## Used technologies
|
||||
|
||||
- React
|
||||
- Vite
|
||||
- TypeScript
|
||||
- TanStack Query
|
||||
- NestJS
|
||||
- MongoDB
|
||||
- Redis/Garnet
|
||||
- NATS
|
||||
- Riot API
|
||||
- pnpm workspace
|
||||
|
||||
## Project structure
|
||||
|
||||
```text
|
||||
apps/
|
||||
api/ NestJS API server
|
||||
web/ React + Vite client
|
||||
scripts/ deployment and maintenance scripts
|
||||
```
|
||||
|
||||
## How to run
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm start:api:dev
|
||||
pnpm dev:web
|
||||
```
|
||||
|
||||
웹 앱은 기본적으로 `apps/web/.env.development` 값을 사용합니다. API 환경값은 `apps/project.env`와 실행 환경의 시크릿 설정을 같이 확인합니다.
|
||||
|
||||
## Checks
|
||||
|
||||
```bash
|
||||
pnpm --filter api test
|
||||
pnpm --filter web build:staging
|
||||
```
|
||||
|
||||
현재 정리된 기준으로 API 테스트와 웹 테스트 빌드를 통과합니다.
|
||||
|
||||
## Deployment branches
|
||||
|
||||
`main`은 항상 배포 가능한 trunk로 유지하고 dev 배포 기준으로 사용합니다.
|
||||
빌드 번호는 `BUILD_NUMBER` 파일에서 1씩 증가시키며, 현재 시작 번호는 `66`입니다.
|
||||
staging 검증이 필요할 때는 `release/66` 같은 임시 브랜치를 만들고,
|
||||
검증이 끝나면 삭제합니다.
|
||||
|
||||
```bash
|
||||
git push origin main:release/66
|
||||
pnpm deploy:web:staging
|
||||
```
|
||||
|
||||
staging/prod Pages 배포 스크립트는 명시 릴리즈 브랜치 환경변수가 있으면 그
|
||||
값을 사용하고, 없으면 최신 `release/*` 브랜치를 자동으로 선택합니다. 최신
|
||||
기준은 브랜치가 가리키는 커밋 시각이며, 동률이면 브랜치명 내림차순입니다.
|
||||
staging은 선택된 릴리즈 브랜치로 preview 배포를 만들고, prod는 Cloudflare
|
||||
Pages production branch로 업로드해 production 배포를 만듭니다.
|
||||
|
||||
명시 릴리즈 브랜치는 staging은 `CF_PAGES_STAGING_BRANCH`, prod는
|
||||
`CF_PAGES_RELEASE_BRANCH`로 지정합니다. Cloudflare Pages production branch가
|
||||
`main`이 아니면 `CF_PAGES_PRODUCTION_BRANCH`로 지정합니다.
|
||||
@@ -0,0 +1,120 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,97 @@
|
||||
---
|
||||
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).
|
||||
@@ -0,0 +1,101 @@
|
||||
---
|
||||
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).
|
||||
@@ -0,0 +1,95 @@
|
||||
---
|
||||
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).
|
||||
@@ -0,0 +1,105 @@
|
||||
<p align="center">
|
||||
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
|
||||
</p>
|
||||
|
||||
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
||||
[circleci-url]: https://circleci.com/gh/nestjs/nest
|
||||
|
||||
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
|
||||
<p align="center">
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
|
||||
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
|
||||
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
||||
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
||||
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
|
||||
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
|
||||
</p>
|
||||
<!--[](https://opencollective.com/nest#backer)
|
||||
[](https://opencollective.com/nest#sponsor)-->
|
||||
|
||||
## Description
|
||||
|
||||
[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
|
||||
$ pnpm install
|
||||
```
|
||||
|
||||
## Compile and run the project
|
||||
|
||||
```bash
|
||||
# development
|
||||
$ pnpm run start
|
||||
|
||||
# watch mode
|
||||
$ pnpm run start:dev
|
||||
|
||||
# production mode
|
||||
$ pnpm run start:prod
|
||||
```
|
||||
|
||||
## Run tests
|
||||
|
||||
```bash
|
||||
# unit tests
|
||||
$ pnpm run test
|
||||
|
||||
# e2e tests
|
||||
$ pnpm run test:e2e
|
||||
|
||||
# test coverage
|
||||
$ pnpm run test:cov
|
||||
```
|
||||
|
||||
## Deployment
|
||||
|
||||
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
|
||||
|
||||
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
|
||||
|
||||
```bash
|
||||
$ pnpm install -g @nestjs/mau
|
||||
$ mau deploy
|
||||
```
|
||||
|
||||
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
|
||||
|
||||
## Resources
|
||||
|
||||
Check out a few resources that may come in handy when working with NestJS:
|
||||
|
||||
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
|
||||
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
|
||||
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
|
||||
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
|
||||
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
|
||||
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
|
||||
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
|
||||
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
|
||||
|
||||
## Support
|
||||
|
||||
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
|
||||
|
||||
## Stay in touch
|
||||
|
||||
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
|
||||
- Website - [https://nestjs.com](https://nestjs.com/)
|
||||
- Twitter - [@nestframework](https://twitter.com/nestframework)
|
||||
|
||||
## License
|
||||
|
||||
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
|
||||
@@ -1,72 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const MACHINE_ENV_PATHS = [
|
||||
process.env.MachineEnvFile,
|
||||
process.env.MACHINE_ENV_FILE,
|
||||
'/source/global-env-vars.txt',
|
||||
process.env.HOME
|
||||
? path.join(process.env.HOME, 'source/global-env-vars.txt')
|
||||
: '',
|
||||
].filter(Boolean);
|
||||
|
||||
const PROJECT_ENV_PATHS = [
|
||||
'project.env',
|
||||
'/app/project.env',
|
||||
'apps/project.env',
|
||||
];
|
||||
|
||||
function stripQuotes(value) {
|
||||
const trimmed = value.trim();
|
||||
if (
|
||||
(trimmed.startsWith('"') && trimmed.endsWith('"')) ||
|
||||
(trimmed.startsWith("'") && trimmed.endsWith("'"))
|
||||
) {
|
||||
return trimmed.slice(1, -1);
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function loadEnvFile(filePath, options = {}) {
|
||||
const { override = false } = options;
|
||||
const content = fs.readFileSync(filePath, 'utf8');
|
||||
for (const line of content.split(/\r?\n/u)) {
|
||||
if (!line.trim() || /^\s*#/u.test(line)) continue;
|
||||
|
||||
const match = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/u);
|
||||
if (!match) continue;
|
||||
|
||||
if (!override && process.env[match[1]] !== undefined) continue;
|
||||
process.env[match[1]] = stripQuotes(match[2]);
|
||||
}
|
||||
}
|
||||
|
||||
const machineEnvFile = MACHINE_ENV_PATHS.find((candidate) =>
|
||||
fs.existsSync(candidate),
|
||||
);
|
||||
if (machineEnvFile) {
|
||||
loadEnvFile(machineEnvFile, { override: true });
|
||||
}
|
||||
|
||||
for (const projectEnvFile of PROJECT_ENV_PATHS) {
|
||||
if (fs.existsSync(projectEnvFile)) {
|
||||
loadEnvFile(projectEnvFile);
|
||||
}
|
||||
}
|
||||
|
||||
const missing = [
|
||||
'INFISICAL_CLIENT_ID',
|
||||
'INFISICAL_CLIENT_SECRET',
|
||||
'INFISICAL_PROJECT_ID',
|
||||
].filter((key) => !process.env[key]);
|
||||
|
||||
if (missing.length > 0) {
|
||||
console.error(
|
||||
`Missing required environment variables: ${missing.join(', ')}`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
require('./dist/main.js');
|
||||
@@ -10,12 +10,12 @@
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"seed:dev": "ts-node src/seed.ts",
|
||||
"seed:dakao-participant": "ts-node src/seed-dakao-participant.ts",
|
||||
"start:dev": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'dev'); \"./start.ps1\"\"",
|
||||
"start:test": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'test'); \"./start.ps1\"\"",
|
||||
"start:prod": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'prod'); \"./start.ps1\"\"",
|
||||
"pm2:dev": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'dev'); ./start.ps1 -UsePm2\"",
|
||||
"pm2:test": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'test'); ./start.ps1 -UsePm2\"",
|
||||
"pm2:prod": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'prod'); ./start.ps1 -UsePm2\"",
|
||||
"start:dev": "node -e \"process.env.NODE_ENV='dev'; require('./dist/main.js')\"",
|
||||
"start:staging": "node -e \"process.env.NODE_ENV='staging'; 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:prod": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:prod",
|
||||
"start:debug": "nest start --debug --watch",
|
||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||
"test": "jest",
|
||||
|
||||
@@ -11,6 +11,7 @@ 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';
|
||||
@@ -25,6 +26,7 @@ import { UserModule } from './modules/user/user.module';
|
||||
GlobalModule,
|
||||
AuthModule,
|
||||
RiotModule,
|
||||
BackgroundRefreshModule,
|
||||
CommunityModule,
|
||||
CommunityStatsModule,
|
||||
MatchModule,
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import {
|
||||
createCorsOrigin,
|
||||
isAllowedCorsOrigin,
|
||||
resolveWebOrigins,
|
||||
} from './cors-origin';
|
||||
|
||||
describe('CORS origin resolution', () => {
|
||||
it('allows Cloudflare Pages preview origins in dev and staging', () => {
|
||||
const origin = 'https://807e0ea6.lolympus.pages.dev';
|
||||
|
||||
expect(isAllowedCorsOrigin(origin, 'dev')).toBe(true);
|
||||
expect(isAllowedCorsOrigin(origin, 'staging')).toBe(true);
|
||||
});
|
||||
|
||||
it('does not allow Cloudflare Pages preview origins in prod', () => {
|
||||
expect(
|
||||
isAllowedCorsOrigin('https://807e0ea6.lolympus.pages.dev', 'prod'),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects similar but unsafe Pages origins', () => {
|
||||
expect(
|
||||
isAllowedCorsOrigin('http://807e0ea6.lolympus.pages.dev', 'staging'),
|
||||
).toBe(false);
|
||||
expect(isAllowedCorsOrigin('https://lolympus.pages.dev', 'staging')).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
isAllowedCorsOrigin('https://a.b.lolympus.pages.dev', 'staging'),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isAllowedCorsOrigin(
|
||||
'https://807e0ea6.lolympus.pages.dev.evil.com',
|
||||
'staging',
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps configured web origins allowed', () => {
|
||||
expect(
|
||||
isAllowedCorsOrigin('https://example.com', 'prod', [
|
||||
'https://example.com',
|
||||
]),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('falls back to default web origins when WEB_ORIGIN is empty', () => {
|
||||
expect(resolveWebOrigins('')).toContain('http://localhost:5173');
|
||||
});
|
||||
|
||||
it('creates a Nest CORS callback from the same rules', (done) => {
|
||||
const corsOrigin = createCorsOrigin('staging');
|
||||
|
||||
expect(corsOrigin).not.toBe(true);
|
||||
if (corsOrigin === true) return;
|
||||
|
||||
corsOrigin('https://807e0ea6.lolympus.pages.dev', (error, allow) => {
|
||||
expect(error).toBeNull();
|
||||
expect(allow).toBe(true);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps dev CORS permissive for local development', () => {
|
||||
expect(createCorsOrigin('dev')).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import type { CustomOrigin } from '@nestjs/common/interfaces/external/cors-options.interface';
|
||||
|
||||
const DEFAULT_WEB_ORIGINS = [
|
||||
'http://localhost:5173',
|
||||
'http://126.dahyeon.us:5173',
|
||||
'https://lolympus.dahyeon.us',
|
||||
];
|
||||
|
||||
const PAGES_DEV_ORIGIN_HOST_PATTERN =
|
||||
/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.lolympus\.pages\.dev$/i;
|
||||
|
||||
const PAGES_DEV_CORS_ENVIRONMENTS = new Set(['dev', 'staging']);
|
||||
|
||||
function parseOrigin(origin: string, allowPath: boolean): URL | null {
|
||||
const trimmedOrigin = origin.trim();
|
||||
if (trimmedOrigin.length === 0) return null;
|
||||
|
||||
try {
|
||||
const url = new URL(trimmedOrigin);
|
||||
if (
|
||||
!allowPath &&
|
||||
(url.pathname !== '/' || url.search !== '' || url.hash !== '')
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return url;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeOrigin(origin: string, allowPath = false): string | null {
|
||||
const url = parseOrigin(origin, allowPath);
|
||||
if (!url) return null;
|
||||
|
||||
return `${url.protocol}//${url.host}`;
|
||||
}
|
||||
|
||||
export function resolveWebOrigins(
|
||||
webOrigin = process.env.WEB_ORIGIN,
|
||||
): string[] {
|
||||
const configuredOrigins = webOrigin
|
||||
?.split(',')
|
||||
.map((origin) => normalizeOrigin(origin, true))
|
||||
.filter((origin): origin is string => origin !== null);
|
||||
|
||||
if (configuredOrigins && configuredOrigins.length > 0) {
|
||||
return configuredOrigins;
|
||||
}
|
||||
|
||||
return [...DEFAULT_WEB_ORIGINS];
|
||||
}
|
||||
|
||||
export function isLolympusPagesDevOrigin(origin: string): boolean {
|
||||
const url = parseOrigin(origin, false);
|
||||
if (!url) return false;
|
||||
|
||||
return (
|
||||
url.protocol === 'https:' &&
|
||||
url.port === '' &&
|
||||
PAGES_DEV_ORIGIN_HOST_PATTERN.test(url.hostname)
|
||||
);
|
||||
}
|
||||
|
||||
export function isAllowedCorsOrigin(
|
||||
requestOrigin: string | undefined,
|
||||
nodeEnv = process.env.NODE_ENV,
|
||||
webOrigins = resolveWebOrigins(),
|
||||
): boolean {
|
||||
if (!requestOrigin) return false;
|
||||
|
||||
const normalizedRequestOrigin = normalizeOrigin(requestOrigin);
|
||||
if (!normalizedRequestOrigin) return false;
|
||||
|
||||
const normalizedWebOrigins = webOrigins
|
||||
.map((origin) => normalizeOrigin(origin, true))
|
||||
.filter((origin): origin is string => origin !== null);
|
||||
|
||||
if (normalizedWebOrigins.includes(normalizedRequestOrigin)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
PAGES_DEV_CORS_ENVIRONMENTS.has(nodeEnv ?? '') &&
|
||||
isLolympusPagesDevOrigin(requestOrigin)
|
||||
);
|
||||
}
|
||||
|
||||
export function createCorsOrigin(
|
||||
nodeEnv = process.env.NODE_ENV,
|
||||
webOrigin = process.env.WEB_ORIGIN,
|
||||
): true | CustomOrigin {
|
||||
if (nodeEnv === 'dev') return true;
|
||||
|
||||
const webOrigins = resolveWebOrigins(webOrigin);
|
||||
|
||||
return (requestOrigin, callback) => {
|
||||
callback(null, isAllowedCorsOrigin(requestOrigin, nodeEnv, webOrigins));
|
||||
};
|
||||
}
|
||||
+5
-10
@@ -1,23 +1,18 @@
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { AppModule } from './app.module';
|
||||
import { createCorsOrigin } from './cors-origin';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule, {
|
||||
rawBody: true,
|
||||
});
|
||||
|
||||
const isDev = process.env.NODE_ENV === 'dev';
|
||||
const webOrigins = process.env.WEB_ORIGIN?.split(',').map((origin) =>
|
||||
origin.trim(),
|
||||
) ?? [
|
||||
'http://localhost:5173',
|
||||
'http://126.dahyeon.us:5173',
|
||||
'https://lolympus.dahyeon.us',
|
||||
];
|
||||
const nodeEnv = process.env.NODE_ENV;
|
||||
const isDev = nodeEnv === 'dev';
|
||||
|
||||
app.enableCors({
|
||||
origin: isDev ? true : webOrigins,
|
||||
origin: createCorsOrigin(nodeEnv),
|
||||
credentials: true,
|
||||
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
|
||||
});
|
||||
@@ -31,4 +26,4 @@ async function bootstrap() {
|
||||
);
|
||||
await app.listen(isDev ? 3000 : 10712);
|
||||
}
|
||||
bootstrap();
|
||||
void bootstrap();
|
||||
@@ -18,11 +18,20 @@ 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 { PlaceBidDto, SoldDto, StartAuctionDto } from './dto/auction.dto';
|
||||
import { AuctionGateway } from './auction.gateway';
|
||||
import {
|
||||
PlaceBidDto,
|
||||
SoldDto,
|
||||
StartAuctionDto,
|
||||
UndoAuctionDto,
|
||||
} from './dto/auction.dto';
|
||||
|
||||
@Controller('communities/:communityId/matches/:matchId/auction')
|
||||
export class AuctionController {
|
||||
constructor(private readonly auctionService: AuctionService) {}
|
||||
constructor(
|
||||
private readonly auctionService: AuctionService,
|
||||
private readonly auctionGateway: AuctionGateway,
|
||||
) {}
|
||||
|
||||
@Post()
|
||||
@Roles('admin', 'owner')
|
||||
@@ -39,11 +48,17 @@ export class AuctionController {
|
||||
matchId,
|
||||
communityId,
|
||||
captains: body.captains.map((c) => ({
|
||||
side: c.side,
|
||||
teamIndex: c.teamIndex,
|
||||
userId: new mongoose.Types.ObjectId(c.userId),
|
||||
initialPoints: c.initialPoints,
|
||||
})),
|
||||
initialPoints: body.initialPoints ?? 1000,
|
||||
maxTimerSeconds: body.maxTimerSeconds ?? 30,
|
||||
bidExtensionSeconds: body.bidExtensionSeconds ?? 5,
|
||||
topTierThreshold: body.topTierThreshold ?? 'NONE',
|
||||
manualTopTierUserIds: (body.manualTopTierUserIds ?? []).map(
|
||||
(userId) => new mongoose.Types.ObjectId(userId),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -75,7 +90,7 @@ export class AuctionController {
|
||||
) {
|
||||
return this.auctionService.placeBid({
|
||||
matchId,
|
||||
side: body.side,
|
||||
teamIndex: body.teamIndex,
|
||||
amount: body.amount,
|
||||
bidderUserId: this.resolveBidder(currentUser, body.bidderUserId),
|
||||
});
|
||||
@@ -103,6 +118,40 @@ export class AuctionController {
|
||||
return this.auctionService.next(matchId);
|
||||
}
|
||||
|
||||
@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,
|
||||
});
|
||||
this.auctionGateway.broadcastState(matchId.toString(), auction);
|
||||
return auction;
|
||||
}
|
||||
|
||||
@Delete()
|
||||
@Roles('admin', 'owner')
|
||||
@UseGuards(RolesGuard)
|
||||
@@ -115,6 +164,7 @@ export class AuctionController {
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
await this.auctionService.reset({ matchId, communityId });
|
||||
this.auctionGateway.broadcastReset(matchId.toString());
|
||||
}
|
||||
|
||||
private resolveBidder(
|
||||
|
||||
@@ -16,10 +16,10 @@ 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';
|
||||
@@ -29,7 +29,7 @@ interface JoinAuctionPayload {
|
||||
}
|
||||
|
||||
interface BidPayload {
|
||||
side: TeamSide;
|
||||
teamIndex: number;
|
||||
amount: number;
|
||||
bidderUserId?: string;
|
||||
}
|
||||
@@ -38,6 +38,11 @@ interface SoldPayload {
|
||||
assignedPosition?: Position;
|
||||
}
|
||||
|
||||
interface ChatMessagePayload {
|
||||
message?: string;
|
||||
displayName?: string;
|
||||
}
|
||||
|
||||
@WebSocketGateway({
|
||||
namespace: '/auction',
|
||||
cors: {
|
||||
@@ -101,6 +106,7 @@ export class AuctionGateway
|
||||
const auction = await this.auctionService.getByMatchId(
|
||||
new mongoose.Types.ObjectId(payload.matchId),
|
||||
);
|
||||
this.emitChatHistory(socket, auction);
|
||||
this.broadcastState(payload.matchId, auction);
|
||||
} catch (error) {
|
||||
this.emitKnownError(socket, error);
|
||||
@@ -124,7 +130,7 @@ export class AuctionGateway
|
||||
try {
|
||||
const auction = await this.auctionService.placeBid({
|
||||
matchId: new mongoose.Types.ObjectId(matchId),
|
||||
side: payload.side,
|
||||
teamIndex: payload.teamIndex,
|
||||
amount: payload.amount,
|
||||
bidderUserId,
|
||||
});
|
||||
@@ -183,6 +189,34 @@ export class AuctionGateway
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeMessage('chat-message')
|
||||
public async handleChatMessage(
|
||||
@ConnectedSocket() socket: Socket,
|
||||
@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: Socket): string | null {
|
||||
const matchId = this.getSocketMatchId(socket);
|
||||
if (!matchId) {
|
||||
@@ -220,6 +254,36 @@ export class AuctionGateway
|
||||
return Array.isArray(header) ? header[0] : header;
|
||||
}
|
||||
|
||||
private resolveSocketUserId(
|
||||
socket: Socket,
|
||||
): mongoose.Types.ObjectId | undefined {
|
||||
return (socket.data.user as UserDocument | undefined)?._id;
|
||||
}
|
||||
|
||||
private resolveChatDisplayName(
|
||||
socket: Socket,
|
||||
fallbackDisplayName?: string,
|
||||
): string {
|
||||
const user = socket.data.user as UserDocument | undefined;
|
||||
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 as IdentityDocument | undefined;
|
||||
if (identity?.displayName) return identity.displayName;
|
||||
if (identity?.email) return identity.email;
|
||||
|
||||
return fallbackDisplayName ?? '관전자';
|
||||
}
|
||||
|
||||
private async authenticateSocket(socket: Socket): Promise<void> {
|
||||
const fallback = await this.authService.resolveDevUserById(
|
||||
this.readHandshakeUserId(socket),
|
||||
@@ -295,17 +359,34 @@ export class AuctionGateway
|
||||
return typeof value === 'string' && value.length > 0 ? value : undefined;
|
||||
}
|
||||
|
||||
private broadcastState(matchId: string, auction: AuctionDocument) {
|
||||
public broadcastState(matchId: string, auction: AuctionDocument) {
|
||||
this.server.to(matchId).emit('state', this.serializeAuction(auction));
|
||||
this.syncRoomTimer(matchId, auction);
|
||||
}
|
||||
|
||||
public broadcastReset(matchId: string) {
|
||||
this.clearRoomTimer(matchId);
|
||||
this.server.to(matchId).emit('reset', { matchId });
|
||||
}
|
||||
|
||||
private emitChatHistory(socket: Socket, auction: AuctionDocument) {
|
||||
socket.emit('chat-history', {
|
||||
messages: (auction.chatMessages ?? []).map((message) =>
|
||||
this.serializeChatMessage(message),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
private syncRoomTimer(matchId: string, auction: AuctionDocument) {
|
||||
this.clearRoomTimer(matchId);
|
||||
if (!auction.currentDeadline) return;
|
||||
|
||||
const deadline = auction.currentDeadline;
|
||||
const deadlineIso = deadline.toISOString();
|
||||
if (Date.now() >= deadline.getTime()) {
|
||||
void this.handleDeadlineExpiry(matchId);
|
||||
return;
|
||||
}
|
||||
this.server.to(matchId).emit('tick', {
|
||||
deadline: deadlineIso,
|
||||
serverTime: new Date().toISOString(),
|
||||
@@ -319,12 +400,34 @@ export class AuctionGateway
|
||||
|
||||
if (Date.now() >= deadline.getTime()) {
|
||||
this.clearRoomTimer(matchId);
|
||||
void this.handleDeadlineExpiry(matchId);
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
this.roomTimers.set(matchId, timer);
|
||||
}
|
||||
|
||||
private async handleDeadlineExpiry(matchIdStr: string) {
|
||||
const matchId = new mongoose.Types.ObjectId(matchIdStr);
|
||||
const auction = await this.auctionService
|
||||
.getByMatchId(matchId)
|
||||
.catch(() => null);
|
||||
if (!auction || auction.phase !== 'bidding') return;
|
||||
if (!auction.currentDeadline || auction.currentDeadline.getTime() > Date.now()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const nextAuction =
|
||||
auction.currentBid > 0
|
||||
? await this.auctionService.markSold({ matchId })
|
||||
: await this.auctionService.markPassed(matchId);
|
||||
this.broadcastState(matchIdStr, nextAuction);
|
||||
} catch (error) {
|
||||
this.emitKnownErrorToRoom(matchIdStr, error);
|
||||
}
|
||||
}
|
||||
|
||||
private maybeClearRoomTimer(matchId: string) {
|
||||
const room = this.server.adapter.rooms.get(matchId);
|
||||
if (room && room.size > 0) return;
|
||||
@@ -344,6 +447,12 @@ export class AuctionGateway
|
||||
this.emitError(socket, message);
|
||||
}
|
||||
|
||||
private emitKnownErrorToRoom(matchId: string, error: unknown) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : 'Unexpected auction gateway error.';
|
||||
this.server.to(matchId).emit('error', { message });
|
||||
}
|
||||
|
||||
private emitError(socket: Socket, message: string) {
|
||||
socket.emit('error', { message });
|
||||
}
|
||||
@@ -351,4 +460,8 @@ export class AuctionGateway
|
||||
private serializeAuction(auction: AuctionDocument) {
|
||||
return JSON.parse(JSON.stringify(auction));
|
||||
}
|
||||
|
||||
private serializeChatMessage(message: AuctionChatMessage) {
|
||||
return JSON.parse(JSON.stringify(message));
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,27 @@ import { AuctionService } from './auction.service';
|
||||
|
||||
describe('AuctionService', () => {
|
||||
function createService(models: Record<string, unknown>) {
|
||||
const auctionHistoryModel = {
|
||||
findOne: jest.fn().mockReturnValue({
|
||||
sort: jest.fn().mockReturnValue({
|
||||
select: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue(null),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
create: jest.fn().mockResolvedValue(undefined),
|
||||
deleteMany: jest.fn().mockReturnValue({
|
||||
session: jest.fn().mockResolvedValue(undefined),
|
||||
}),
|
||||
};
|
||||
const allModels = {
|
||||
auctionHistory: auctionHistoryModel,
|
||||
...models,
|
||||
};
|
||||
const connectionService = {
|
||||
getModel: jest.fn((name: string) => models[name]),
|
||||
getModel: jest.fn((name: string) => allModels[name]),
|
||||
createSession: jest.fn(),
|
||||
};
|
||||
const enrichmentService = {
|
||||
@@ -16,6 +35,7 @@ describe('AuctionService', () => {
|
||||
};
|
||||
const tournamentResultService = {
|
||||
scheduleInitialPoll: jest.fn().mockResolvedValue(null),
|
||||
cancelPolling: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -28,12 +48,13 @@ describe('AuctionService', () => {
|
||||
connectionService,
|
||||
tournamentCodeService,
|
||||
tournamentResultService,
|
||||
auctionHistoryModel,
|
||||
};
|
||||
}
|
||||
|
||||
function createFullTeam(side: 'blue' | 'red') {
|
||||
function createFullTeam(teamIndex: number) {
|
||||
return {
|
||||
side,
|
||||
teamIndex,
|
||||
captainUserId: new mongoose.Types.ObjectId(),
|
||||
points: 100,
|
||||
members: Array.from({ length: 4 }, () => ({
|
||||
@@ -44,11 +65,381 @@ describe('AuctionService', () => {
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it('starts an auction without reserving tournament codes before teams are complete', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const userIds = Array.from(
|
||||
{ length: 10 },
|
||||
() => new mongoose.Types.ObjectId(),
|
||||
);
|
||||
const participants = userIds.map((userId, index) => ({
|
||||
userId,
|
||||
preferredPositions: [{ position: 'MID', priority: 1 }],
|
||||
joinedAt: new Date(index),
|
||||
excluded: false,
|
||||
}));
|
||||
const match = {
|
||||
_id: matchId,
|
||||
communityId,
|
||||
participants,
|
||||
status: 'recruiting',
|
||||
teamBuiltAt: undefined,
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const users = userIds.slice(2).map((userId, index) => ({
|
||||
_id: userId,
|
||||
riotAccounts: [
|
||||
{
|
||||
puuid: `puuid-${index}`,
|
||||
gameName: `Player${index}`,
|
||||
tagLine: 'KR1',
|
||||
profileIconId: index,
|
||||
tiers: [],
|
||||
championMasteries: [],
|
||||
recentStatsSummary: undefined,
|
||||
lastRefreshRequestedAt: new Date(),
|
||||
isPrimary: true,
|
||||
},
|
||||
],
|
||||
}));
|
||||
const auction = {
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
matchId,
|
||||
toObject: jest.fn().mockReturnValue({ matchId }),
|
||||
};
|
||||
const { service, tournamentCodeService, tournamentResultService } =
|
||||
createService({
|
||||
match: {
|
||||
findById: jest.fn().mockResolvedValue(match),
|
||||
},
|
||||
user: {
|
||||
find: jest.fn().mockResolvedValue(users),
|
||||
},
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(null),
|
||||
create: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
community: {
|
||||
findById: jest.fn().mockReturnValue({
|
||||
select: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({
|
||||
riotPlatform: 'kr',
|
||||
riotRegion: 'asia',
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
await service.start({
|
||||
matchId,
|
||||
communityId,
|
||||
captains: [
|
||||
{ teamIndex: 1, userId: userIds[0] },
|
||||
{ teamIndex: 2, userId: userIds[1] },
|
||||
],
|
||||
initialPoints: 1000,
|
||||
maxTimerSeconds: 30,
|
||||
bidExtensionSeconds: 5,
|
||||
topTierThreshold: 'NONE',
|
||||
manualTopTierUserIds: [],
|
||||
});
|
||||
|
||||
expect(match.status).toBe('team-built');
|
||||
expect(match.teamBuiltAt).toBeInstanceOf(Date);
|
||||
expect(match.save).toHaveBeenCalledTimes(1);
|
||||
expect(tournamentCodeService.reserveForMatch).not.toHaveBeenCalled();
|
||||
expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('appends a chat message and keeps only the latest 200 messages', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
const oldMessages = Array.from({ length: 200 }, (_, index) => ({
|
||||
id: `old-${index}`,
|
||||
displayName: 'Old',
|
||||
message: `old message ${index}`,
|
||||
sentAt: new Date(index),
|
||||
}));
|
||||
const auction = {
|
||||
matchId,
|
||||
chatMessages: oldMessages,
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const { service } = createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
});
|
||||
|
||||
const appended = await service.appendChatMessage({
|
||||
matchId,
|
||||
userId,
|
||||
displayName: ' Captain One ',
|
||||
message: ' 좋은 픽입니다 ',
|
||||
});
|
||||
|
||||
expect(appended.message).toMatchObject({
|
||||
userId,
|
||||
displayName: 'Captain One',
|
||||
message: '좋은 픽입니다',
|
||||
});
|
||||
expect(appended.message.id).toHaveLength(36);
|
||||
expect(appended.message.sentAt).toBeInstanceOf(Date);
|
||||
expect(auction.chatMessages).toHaveLength(200);
|
||||
expect(auction.chatMessages[0].id).toBe('old-1');
|
||||
expect(auction.chatMessages.at(-1)).toBe(appended.message);
|
||||
expect(auction.save).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('rejects blank and overly long chat messages', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const auction = {
|
||||
matchId,
|
||||
chatMessages: [],
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const { service } = createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.appendChatMessage({
|
||||
matchId,
|
||||
displayName: 'Spectator',
|
||||
message: ' ',
|
||||
}),
|
||||
).rejects.toThrow('Chat message is required.');
|
||||
await expect(
|
||||
service.appendChatMessage({
|
||||
matchId,
|
||||
displayName: 'Spectator',
|
||||
message: 'a'.repeat(301),
|
||||
}),
|
||||
).rejects.toThrow('Chat message must be 300 characters or less.');
|
||||
expect(auction.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('randomizes the non-captain player order when starting an auction', async () => {
|
||||
const randomSpy = jest.spyOn(Math, 'random').mockReturnValue(0);
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const userIds = Array.from(
|
||||
{ length: 10 },
|
||||
() => new mongoose.Types.ObjectId(),
|
||||
);
|
||||
const participants = userIds.map((userId, index) => ({
|
||||
userId,
|
||||
preferredPositions: [{ position: 'MID', priority: 1 }],
|
||||
joinedAt: new Date(index),
|
||||
excluded: false,
|
||||
}));
|
||||
const match = {
|
||||
_id: matchId,
|
||||
communityId,
|
||||
participants,
|
||||
status: 'recruiting',
|
||||
teamBuiltAt: undefined,
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const users = userIds.slice(2).map((userId, index) => ({
|
||||
_id: userId,
|
||||
riotAccounts: [
|
||||
{
|
||||
puuid: `puuid-${index}`,
|
||||
gameName: `Player${index}`,
|
||||
tagLine: 'KR1',
|
||||
profileIconId: index,
|
||||
tiers: [],
|
||||
championMasteries: [],
|
||||
recentStatsSummary: undefined,
|
||||
lastRefreshRequestedAt: new Date(),
|
||||
isPrimary: true,
|
||||
},
|
||||
],
|
||||
}));
|
||||
const auctionCreate = jest.fn().mockImplementation(async (payload) => ({
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
matchId,
|
||||
toObject: jest.fn().mockReturnValue({ matchId, ...payload }),
|
||||
}));
|
||||
const { service } = createService({
|
||||
match: {
|
||||
findById: jest.fn().mockResolvedValue(match),
|
||||
},
|
||||
user: {
|
||||
find: jest.fn().mockResolvedValue(users),
|
||||
},
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(null),
|
||||
create: auctionCreate,
|
||||
},
|
||||
community: {
|
||||
findById: jest.fn().mockReturnValue({
|
||||
select: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({
|
||||
riotPlatform: 'kr',
|
||||
riotRegion: 'asia',
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
await service.start({
|
||||
matchId,
|
||||
communityId,
|
||||
captains: [
|
||||
{ teamIndex: 1, userId: userIds[0] },
|
||||
{ teamIndex: 2, userId: userIds[1] },
|
||||
],
|
||||
initialPoints: 1000,
|
||||
maxTimerSeconds: 30,
|
||||
bidExtensionSeconds: 5,
|
||||
topTierThreshold: 'NONE',
|
||||
manualTopTierUserIds: [],
|
||||
});
|
||||
|
||||
const signupOrder = userIds.slice(2).map((userId) => userId.toString());
|
||||
const auctionOrder = auctionCreate.mock.calls[0][0].order.map(
|
||||
(player: { userId: mongoose.Types.ObjectId }) =>
|
||||
player.userId.toString(),
|
||||
);
|
||||
|
||||
expect(auctionOrder).not.toEqual(signupOrder);
|
||||
expect([...auctionOrder].sort()).toEqual([...signupOrder].sort());
|
||||
expect(randomSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('includes tier history in auction player snapshots when starting an auction', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const userIds = Array.from(
|
||||
{ length: 10 },
|
||||
() => new mongoose.Types.ObjectId(),
|
||||
);
|
||||
const participants = userIds.map((userId, index) => ({
|
||||
userId,
|
||||
preferredPositions: [{ position: 'MID', priority: 1 }],
|
||||
joinedAt: new Date(index),
|
||||
excluded: false,
|
||||
}));
|
||||
const match = {
|
||||
_id: matchId,
|
||||
communityId,
|
||||
participants,
|
||||
status: 'recruiting',
|
||||
teamBuiltAt: undefined,
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const tierHistory = [
|
||||
{
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'GOLD',
|
||||
rank: 'II',
|
||||
leaguePoints: 42,
|
||||
wins: 30,
|
||||
losses: 24,
|
||||
recordedAt: new Date('2026-05-01T00:00:00.000Z'),
|
||||
},
|
||||
{
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'PLATINUM',
|
||||
rank: 'IV',
|
||||
leaguePoints: 15,
|
||||
wins: 34,
|
||||
losses: 27,
|
||||
recordedAt: new Date('2026-05-08T00:00:00.000Z'),
|
||||
},
|
||||
];
|
||||
const users = userIds.slice(2).map((userId, index) => ({
|
||||
_id: userId,
|
||||
riotAccounts: [
|
||||
{
|
||||
puuid: `puuid-${index}`,
|
||||
gameName: `Player${index}`,
|
||||
tagLine: 'KR1',
|
||||
profileIconId: index,
|
||||
tiers: [],
|
||||
tierHistory: index === 0 ? tierHistory : [],
|
||||
championMasteries: [],
|
||||
recentStatsSummary: undefined,
|
||||
lastRefreshRequestedAt: new Date(),
|
||||
isPrimary: true,
|
||||
},
|
||||
],
|
||||
}));
|
||||
const auctionCreate = jest.fn().mockImplementation(async (payload) => ({
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
matchId,
|
||||
toObject: jest.fn().mockReturnValue({ matchId, ...payload }),
|
||||
}));
|
||||
const { service } = createService({
|
||||
match: {
|
||||
findById: jest.fn().mockResolvedValue(match),
|
||||
},
|
||||
user: {
|
||||
find: jest.fn().mockResolvedValue(users),
|
||||
},
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(null),
|
||||
create: auctionCreate,
|
||||
},
|
||||
community: {
|
||||
findById: jest.fn().mockReturnValue({
|
||||
select: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({
|
||||
riotPlatform: 'kr',
|
||||
riotRegion: 'asia',
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
await service.start({
|
||||
matchId,
|
||||
communityId,
|
||||
captains: [
|
||||
{ teamIndex: 1, userId: userIds[0] },
|
||||
{ teamIndex: 2, userId: userIds[1] },
|
||||
],
|
||||
initialPoints: 1000,
|
||||
maxTimerSeconds: 30,
|
||||
bidExtensionSeconds: 5,
|
||||
topTierThreshold: 'NONE',
|
||||
manualTopTierUserIds: [],
|
||||
});
|
||||
|
||||
const firstPlayerSnapshot = auctionCreate.mock.calls[0][0].order.find(
|
||||
(player: { userId: mongoose.Types.ObjectId }) =>
|
||||
player.userId.equals(userIds[2]),
|
||||
);
|
||||
|
||||
expect(firstPlayerSnapshot).toMatchObject({
|
||||
userId: userIds[2],
|
||||
tierHistory,
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects bids when the team already has 5 members including captain', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const auction = {
|
||||
phase: 'bidding',
|
||||
teams: [createFullTeam('blue'), createFullTeam('red')],
|
||||
teams: [createFullTeam(1), createFullTeam(2)],
|
||||
currentBid: 10,
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
@@ -61,18 +452,62 @@ describe('AuctionService', () => {
|
||||
await expect(
|
||||
service.placeBid({
|
||||
matchId,
|
||||
side: 'blue',
|
||||
teamIndex: 1,
|
||||
amount: 20,
|
||||
}),
|
||||
).rejects.toThrow('Team already has maximum members.');
|
||||
expect(auction.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('extends a short bid deadline using the configured bid extension seconds', async () => {
|
||||
const now = new Date('2026-05-02T00:00:00.000Z');
|
||||
jest.useFakeTimers().setSystemTime(now);
|
||||
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const captainUserId = new mongoose.Types.ObjectId();
|
||||
const auction = {
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
matchId,
|
||||
phase: 'bidding',
|
||||
teams: [
|
||||
{
|
||||
teamIndex: 1,
|
||||
captainUserId,
|
||||
points: 1000,
|
||||
members: [],
|
||||
},
|
||||
],
|
||||
currentBid: 10,
|
||||
currentDeadline: new Date(now.getTime() + 2000),
|
||||
maxTimerSeconds: 30,
|
||||
bidExtensionSeconds: 12,
|
||||
bids: [],
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }),
|
||||
};
|
||||
const { service } = createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
});
|
||||
|
||||
await service.placeBid({
|
||||
matchId,
|
||||
teamIndex: 1,
|
||||
amount: 20,
|
||||
});
|
||||
|
||||
expect(auction.currentDeadline).toEqual(
|
||||
new Date(now.getTime() + 12000),
|
||||
);
|
||||
expect(auction.save).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('rejects sold confirmation when the winning team is already full', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const auction = {
|
||||
phase: 'bidding',
|
||||
currentBidder: 'blue',
|
||||
currentBidderTeamIndex: 1,
|
||||
currentBid: 20,
|
||||
currentIndex: 0,
|
||||
order: [
|
||||
@@ -81,7 +516,7 @@ describe('AuctionService', () => {
|
||||
preferredPositions: [{ position: 'ADC', priority: 1 }],
|
||||
},
|
||||
],
|
||||
teams: [createFullTeam('blue'), createFullTeam('red')],
|
||||
teams: [createFullTeam(1), createFullTeam(2)],
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const { service } = createService({
|
||||
@@ -96,6 +531,139 @@ describe('AuctionService', () => {
|
||||
expect(auction.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('marks a zero-bid player as passed and queues them for another round', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const playerId = new mongoose.Types.ObjectId();
|
||||
const auction = {
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
matchId,
|
||||
phase: 'bidding',
|
||||
currentBid: 0,
|
||||
currentIndex: 0,
|
||||
auctionRound: 1,
|
||||
order: [
|
||||
{
|
||||
userId: playerId,
|
||||
preferredPositions: [{ position: 'MID', priority: 1 }],
|
||||
passCount: 0,
|
||||
},
|
||||
],
|
||||
passedQueue: [],
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }),
|
||||
};
|
||||
const { service } = createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
});
|
||||
|
||||
await service.markPassed(matchId);
|
||||
|
||||
expect(auction.phase).toBe('passed');
|
||||
expect(auction.order[0].passCount).toBe(1);
|
||||
expect(auction.passedQueue).toHaveLength(1);
|
||||
expect(auction.save).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('queues zero-bid passes after the first auction round', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const playerId = new mongoose.Types.ObjectId();
|
||||
const auction = {
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
matchId,
|
||||
phase: 'bidding',
|
||||
currentBid: 0,
|
||||
currentIndex: 0,
|
||||
auctionRound: 2,
|
||||
order: [
|
||||
{
|
||||
userId: playerId,
|
||||
preferredPositions: [{ position: 'MID', priority: 1 }],
|
||||
passCount: 1,
|
||||
},
|
||||
],
|
||||
passedQueue: [],
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }),
|
||||
};
|
||||
const { service } = createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
});
|
||||
|
||||
await service.markPassed(matchId);
|
||||
|
||||
expect(auction.phase).toBe('passed');
|
||||
expect(auction.order[0].passCount).toBe(2);
|
||||
expect(auction.passedQueue).toHaveLength(1);
|
||||
expect(auction.passedQueue[0]).toMatchObject({
|
||||
userId: playerId.toString(),
|
||||
preferredPositions: [{ position: 'MID', priority: 1 }],
|
||||
passCount: 2,
|
||||
});
|
||||
});
|
||||
|
||||
it('requeues second-pass players instead of force-assigning them', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const captainOneId = new mongoose.Types.ObjectId();
|
||||
const captainTwoId = new mongoose.Types.ObjectId();
|
||||
const passedPlayerId = new mongoose.Types.ObjectId();
|
||||
const passedPlayer = {
|
||||
userId: passedPlayerId,
|
||||
preferredPositions: [{ position: 'SUP', priority: 1 }],
|
||||
passCount: 2,
|
||||
};
|
||||
const auction = {
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
matchId,
|
||||
phase: 'passed',
|
||||
currentIndex: 0,
|
||||
auctionRound: 2,
|
||||
order: [passedPlayer],
|
||||
passedQueue: [passedPlayer],
|
||||
teams: [
|
||||
{
|
||||
teamIndex: 1,
|
||||
captainUserId: captainOneId,
|
||||
points: 10,
|
||||
members: [],
|
||||
},
|
||||
{
|
||||
teamIndex: 2,
|
||||
captainUserId: captainTwoId,
|
||||
points: 50,
|
||||
members: [],
|
||||
},
|
||||
],
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }),
|
||||
};
|
||||
const { service } = createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
});
|
||||
|
||||
await service.next(matchId);
|
||||
|
||||
expect(auction.phase).toBe('presenting');
|
||||
expect(auction.auctionRound).toBe(3);
|
||||
expect(auction.currentIndex).toBe(1);
|
||||
expect(auction.order).toHaveLength(2);
|
||||
expect(auction.order[1]).toMatchObject({
|
||||
userId: passedPlayerId.toString(),
|
||||
preferredPositions: [{ position: 'SUP', priority: 1 }],
|
||||
passCount: 2,
|
||||
});
|
||||
expect(auction.passedQueue).toEqual([]);
|
||||
expect(auction.teams[0].members).toEqual([]);
|
||||
expect(auction.teams[1].members).toEqual([]);
|
||||
expect(auction.teams[0].points).toBe(10);
|
||||
expect(auction.teams[1].points).toBe(50);
|
||||
});
|
||||
|
||||
it('syncs completed auction teams into the match document', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const blueCaptainId = new mongoose.Types.ObjectId();
|
||||
@@ -110,7 +678,7 @@ describe('AuctionService', () => {
|
||||
order: [{ userId: blueMemberId }, { userId: redMemberId }],
|
||||
teams: [
|
||||
{
|
||||
side: 'blue',
|
||||
teamIndex: 1,
|
||||
captainUserId: blueCaptainId,
|
||||
points: 970,
|
||||
members: [
|
||||
@@ -122,7 +690,7 @@ describe('AuctionService', () => {
|
||||
],
|
||||
},
|
||||
{
|
||||
side: 'red',
|
||||
teamIndex: 2,
|
||||
captainUserId: redCaptainId,
|
||||
points: 940,
|
||||
members: [
|
||||
@@ -159,14 +727,15 @@ describe('AuctionService', () => {
|
||||
teams: [],
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const { service } = createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
match: {
|
||||
findById: jest.fn().mockResolvedValue(match),
|
||||
},
|
||||
});
|
||||
const { service, tournamentCodeService, tournamentResultService } =
|
||||
createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
match: {
|
||||
findById: jest.fn().mockResolvedValue(match),
|
||||
},
|
||||
});
|
||||
|
||||
await service.next(matchId);
|
||||
|
||||
@@ -176,8 +745,8 @@ describe('AuctionService', () => {
|
||||
expect(match.save).toHaveBeenCalledTimes(1);
|
||||
expect(match.teams).toEqual([
|
||||
{
|
||||
side: 'blue',
|
||||
name: '블루팀',
|
||||
teamIndex: 1,
|
||||
name: '1팀',
|
||||
captainUserId: blueCaptainId,
|
||||
members: [
|
||||
{
|
||||
@@ -193,8 +762,8 @@ describe('AuctionService', () => {
|
||||
],
|
||||
},
|
||||
{
|
||||
side: 'red',
|
||||
name: '레드팀',
|
||||
teamIndex: 2,
|
||||
name: '2팀',
|
||||
captainUserId: redCaptainId,
|
||||
members: [
|
||||
{
|
||||
@@ -210,6 +779,10 @@ describe('AuctionService', () => {
|
||||
],
|
||||
},
|
||||
]);
|
||||
expect(tournamentCodeService.reserveForMatch).toHaveBeenCalledWith(match);
|
||||
expect(tournamentResultService.scheduleInitialPoll).toHaveBeenCalledWith(
|
||||
match,
|
||||
);
|
||||
});
|
||||
|
||||
it('clears match teams when resetting an auction', async () => {
|
||||
@@ -229,11 +802,14 @@ describe('AuctionService', () => {
|
||||
status: 'team-built',
|
||||
teams: [
|
||||
{
|
||||
side: 'blue',
|
||||
name: '블루팀',
|
||||
teamIndex: 1,
|
||||
name: '1팀',
|
||||
members: [],
|
||||
},
|
||||
],
|
||||
tournamentCodeIds: [new mongoose.Types.ObjectId()],
|
||||
gameSchedule: [{ gameNumber: 1, teamAIndex: 1, teamBIndex: 2 }],
|
||||
participants: [],
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const auctionFindOneQuery = {
|
||||
@@ -256,7 +832,97 @@ describe('AuctionService', () => {
|
||||
|
||||
expect(match.status).toBe('recruiting');
|
||||
expect(match.teams).toEqual([]);
|
||||
expect(match.tournamentCodeIds).toEqual([]);
|
||||
expect(match.gameSchedule).toEqual([]);
|
||||
expect(match.save).toHaveBeenCalledWith({ session });
|
||||
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('undoes to a history snapshot and releases resources when leaving complete', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const auctionId = new mongoose.Types.ObjectId();
|
||||
const session = {
|
||||
startTransaction: jest.fn(),
|
||||
commitTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
endSession: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const auction = {
|
||||
_id: auctionId,
|
||||
matchId,
|
||||
completedAt: new Date(),
|
||||
};
|
||||
const snapshot = {
|
||||
_id: auctionId.toString(),
|
||||
matchId: matchId.toString(),
|
||||
phase: 'bidding',
|
||||
order: [],
|
||||
teams: [],
|
||||
};
|
||||
const restored = { _id: auctionId, phase: 'bidding' };
|
||||
const match = {
|
||||
communityId,
|
||||
status: 'finished',
|
||||
result: { games: [] },
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const auctionFindOneQuery = {
|
||||
session: jest.fn().mockResolvedValue(auction),
|
||||
};
|
||||
const matchFindByIdQuery = {
|
||||
session: jest.fn().mockResolvedValue(match),
|
||||
};
|
||||
const historyFindOneQuery = {
|
||||
session: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({
|
||||
auctionId,
|
||||
matchId,
|
||||
sequence: 3,
|
||||
snapshotBefore: snapshot,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
};
|
||||
const historyDeleteManyQuery = {
|
||||
session: jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue(undefined),
|
||||
}),
|
||||
};
|
||||
const auctionReplaceOne = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue(undefined),
|
||||
});
|
||||
const { service, connectionService, tournamentCodeService, tournamentResultService } =
|
||||
createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockReturnValue(auctionFindOneQuery),
|
||||
replaceOne: auctionReplaceOne,
|
||||
findById: jest.fn().mockResolvedValue(restored),
|
||||
},
|
||||
auctionHistory: {
|
||||
findOne: jest.fn().mockReturnValue(historyFindOneQuery),
|
||||
deleteMany: jest.fn().mockReturnValue(historyDeleteManyQuery),
|
||||
},
|
||||
match: {
|
||||
findById: jest.fn().mockReturnValue(matchFindByIdQuery),
|
||||
},
|
||||
});
|
||||
connectionService.createSession.mockResolvedValue(session);
|
||||
|
||||
await expect(
|
||||
service.undoTo({ matchId, communityId, sequence: 3 }),
|
||||
).resolves.toBe(restored);
|
||||
|
||||
expect(tournamentCodeService.releaseFromMatch).toHaveBeenCalledWith(match);
|
||||
expect(tournamentResultService.cancelPolling).toHaveBeenCalledWith(match);
|
||||
expect(match.status).toBe('team-built');
|
||||
expect(match.result).toBeUndefined();
|
||||
expect(auctionReplaceOne).toHaveBeenCalledWith(
|
||||
{ _id: auctionId },
|
||||
snapshot,
|
||||
{ session },
|
||||
);
|
||||
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -2,35 +2,54 @@ import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
InternalServerErrorException,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'crypto';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import {
|
||||
AuctionActionType,
|
||||
AuctionChatMessage,
|
||||
AuctionDocument,
|
||||
AuctionPlayerSnapshot,
|
||||
AuctionTeam,
|
||||
AuctionTopTierThreshold,
|
||||
MatchParticipant,
|
||||
MatchTeamMember,
|
||||
Position,
|
||||
TeamSide,
|
||||
RiotAccount,
|
||||
} from '../global/database/schema';
|
||||
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
||||
import type { RiotPlatformRoute, RiotRegionalRoute } from '../riot/riot.types';
|
||||
import { TournamentCodeService } from '../tournament-code/tournament-code.service';
|
||||
import { TournamentResultService } from '../tournament-result/tournament-result.service';
|
||||
|
||||
const AUCTION_MAX_TEAM_SIZE = 5;
|
||||
const AUCTION_BACKGROUND_ENRICHMENT_CONCURRENCY = 1;
|
||||
const AUCTION_ENRICHMENT_COOLDOWN_MS = 3 * 60 * 60 * 1000;
|
||||
const AUCTION_CHAT_MAX_MESSAGES = 200;
|
||||
const AUCTION_CHAT_MAX_MESSAGE_LENGTH = 300;
|
||||
const AUCTION_CHAT_MAX_DISPLAY_NAME_LENGTH = 24;
|
||||
|
||||
interface StartAuctionParams {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
captains: { side: TeamSide; userId: mongoose.Types.ObjectId }[];
|
||||
captains: {
|
||||
teamIndex: number;
|
||||
userId: mongoose.Types.ObjectId;
|
||||
initialPoints?: number;
|
||||
}[];
|
||||
initialPoints: number;
|
||||
maxTimerSeconds: number;
|
||||
bidExtensionSeconds: number;
|
||||
topTierThreshold: AuctionTopTierThreshold;
|
||||
manualTopTierUserIds: mongoose.Types.ObjectId[];
|
||||
}
|
||||
|
||||
interface PlaceBidParams {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
side: TeamSide;
|
||||
teamIndex: number;
|
||||
amount: number;
|
||||
bidderUserId?: mongoose.Types.ObjectId;
|
||||
}
|
||||
@@ -40,8 +59,29 @@ interface MarkSoldParams {
|
||||
assignedPosition?: Position;
|
||||
}
|
||||
|
||||
interface AppendChatMessageParams {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
userId?: mongoose.Types.ObjectId;
|
||||
displayName?: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface AuctionHistoryView {
|
||||
sequence: number;
|
||||
action: AuctionActionType;
|
||||
actionLabel: string;
|
||||
takenAt: Date;
|
||||
}
|
||||
|
||||
interface AuctionEnrichmentTarget {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
puuid: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AuctionService {
|
||||
private readonly logger = new Logger(AuctionService.name);
|
||||
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly enrichmentService: RiotAccountEnrichmentService,
|
||||
@@ -66,30 +106,27 @@ export class AuctionService {
|
||||
throw new BadRequestException('Auction already exists for this match.');
|
||||
}
|
||||
|
||||
const captainUserIds = params.captains.map((c) => c.userId);
|
||||
if (captainUserIds[0].equals(captainUserIds[1])) {
|
||||
throw new BadRequestException('Captains must be different users.');
|
||||
const activeParticipants = this.applyAuctionCut(match);
|
||||
const desiredAuctionCount = activeParticipants.length;
|
||||
if (desiredAuctionCount < 10) {
|
||||
throw new BadRequestException('Not enough participants (need at least 10).');
|
||||
}
|
||||
const captainParticipants = match.participants.filter((p) =>
|
||||
captainUserIds.some((cid) => cid.equals(p.userId)),
|
||||
const expectedCaptainCount = desiredAuctionCount / AUCTION_MAX_TEAM_SIZE;
|
||||
if (params.captains.length !== expectedCaptainCount) {
|
||||
throw new BadRequestException(
|
||||
`Expected ${expectedCaptainCount} captains for ${desiredAuctionCount} participants.`,
|
||||
);
|
||||
}
|
||||
this.assertCaptainAssignments(
|
||||
params.captains,
|
||||
activeParticipants,
|
||||
expectedCaptainCount,
|
||||
);
|
||||
if (captainParticipants.length !== 2) {
|
||||
throw new BadRequestException(
|
||||
'Both captains must be participants of the match.',
|
||||
);
|
||||
}
|
||||
if (
|
||||
match.participants.length >
|
||||
params.captains.length * AUCTION_MAX_TEAM_SIZE
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
'Auction supports up to 5 members per team including captains.',
|
||||
);
|
||||
}
|
||||
const captainUserIds = params.captains.map((c) => c.userId);
|
||||
|
||||
const basePlayerUsers = await UserModel.find({
|
||||
_id: {
|
||||
$in: match.participants
|
||||
$in: activeParticipants
|
||||
.filter((p) => !captainUserIds.some((cid) => cid.equals(p.userId)))
|
||||
.map((p) => p.userId),
|
||||
},
|
||||
@@ -101,36 +138,20 @@ export class AuctionService {
|
||||
const platform = community?.riotPlatform ?? 'kr';
|
||||
const region = community?.riotRegion ?? 'asia';
|
||||
|
||||
const enrichTargets = basePlayerUsers
|
||||
.map((user) => ({
|
||||
userId: user._id,
|
||||
puuid: (user.riotAccounts.find((account) => account.isPrimary) ?? user.riotAccounts[0])
|
||||
?.puuid,
|
||||
}))
|
||||
.filter((target): target is { userId: mongoose.Types.ObjectId; puuid: string } =>
|
||||
typeof target.puuid === 'string' && target.puuid.length > 0,
|
||||
);
|
||||
|
||||
await runWithConcurrency(enrichTargets, 3, async (target) => {
|
||||
await this.enrichmentService.enrichRiotAccount({
|
||||
userId: target.userId,
|
||||
puuid: target.puuid,
|
||||
options: {
|
||||
force: false,
|
||||
platform,
|
||||
region,
|
||||
},
|
||||
});
|
||||
const enrichCooldownCutoff = Date.now() - AUCTION_ENRICHMENT_COOLDOWN_MS;
|
||||
const enrichTargets = basePlayerUsers.flatMap((user) => {
|
||||
const account =
|
||||
user.riotAccounts.find((entry) => entry.isPrimary) ?? user.riotAccounts[0];
|
||||
if (!account?.puuid) return [];
|
||||
if (this.wasRecentlyRefreshed(account, enrichCooldownCutoff)) return [];
|
||||
return [{ userId: user._id, puuid: account.puuid }];
|
||||
});
|
||||
|
||||
const playerUsers = await UserModel.find({
|
||||
_id: { $in: basePlayerUsers.map((user) => user._id) },
|
||||
});
|
||||
const userById = new Map(playerUsers.map((u) => [u._id.toString(), u]));
|
||||
const userById = new Map(basePlayerUsers.map((u) => [u._id.toString(), u]));
|
||||
|
||||
const nonCaptainPuuids = new Set<string>();
|
||||
const order: AuctionPlayerSnapshot[] = [];
|
||||
for (const participant of match.participants) {
|
||||
for (const participant of activeParticipants) {
|
||||
if (captainUserIds.some((cid) => cid.equals(participant.userId))) {
|
||||
continue;
|
||||
}
|
||||
@@ -153,34 +174,53 @@ export class AuctionService {
|
||||
profileIconId: primary.profileIconId,
|
||||
preferredPositions: participant.preferredPositions,
|
||||
tiers: primary.tiers,
|
||||
tierHistory: primary.tierHistory ?? [],
|
||||
masteries: primary.championMasteries,
|
||||
recentStatsSummary: primary.recentStatsSummary,
|
||||
passCount: 0,
|
||||
});
|
||||
}
|
||||
const shuffledOrder = this.shuffleAuctionPlayerOrder(order);
|
||||
const prioritizedOrder = this.applyTopTierPriority(
|
||||
shuffledOrder,
|
||||
params.topTierThreshold,
|
||||
params.manualTopTierUserIds,
|
||||
);
|
||||
|
||||
const auction = await AuctionModel.create({
|
||||
matchId: params.matchId,
|
||||
phase: 'presenting',
|
||||
teams: params.captains.map((c) => ({
|
||||
side: c.side,
|
||||
teamIndex: c.teamIndex,
|
||||
captainUserId: c.userId,
|
||||
points: params.initialPoints,
|
||||
points: c.initialPoints ?? params.initialPoints,
|
||||
members: [],
|
||||
})),
|
||||
order,
|
||||
order: prioritizedOrder,
|
||||
passedQueue: [],
|
||||
auctionRound: 1,
|
||||
currentIndex: 0,
|
||||
bids: [],
|
||||
currentBid: 0,
|
||||
maxTimerSeconds: params.maxTimerSeconds,
|
||||
bidExtensionSeconds: params.bidExtensionSeconds,
|
||||
initialPoints: params.initialPoints,
|
||||
topTierThreshold: params.topTierThreshold,
|
||||
manualTopTierUserIds:
|
||||
params.topTierThreshold === 'MANUAL' ? params.manualTopTierUserIds : [],
|
||||
startedAt: new Date(),
|
||||
});
|
||||
await this.recordSnapshot(auction, 'start');
|
||||
|
||||
match.status = 'team-built';
|
||||
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
||||
await match.save();
|
||||
await this.tournamentCodeService.reserveForMatch(match);
|
||||
await this.tournamentResultService.scheduleInitialPoll(match);
|
||||
this.enqueueBackgroundOrderEnrichment({
|
||||
auctionId: auction._id,
|
||||
targets: enrichTargets,
|
||||
platform,
|
||||
region,
|
||||
});
|
||||
|
||||
return auction;
|
||||
}
|
||||
@@ -194,6 +234,60 @@ export class AuctionService {
|
||||
return auction;
|
||||
}
|
||||
|
||||
public async appendChatMessage(params: AppendChatMessageParams): Promise<{
|
||||
auction: AuctionDocument;
|
||||
message: AuctionChatMessage;
|
||||
}> {
|
||||
const auction = await this.getByMatchId(params.matchId);
|
||||
const messageText = this.normalizeChatMessage(params.message);
|
||||
const message: AuctionChatMessage = {
|
||||
id: randomUUID(),
|
||||
userId: params.userId,
|
||||
displayName: this.normalizeChatDisplayName(params.displayName),
|
||||
message: messageText,
|
||||
sentAt: new Date(),
|
||||
};
|
||||
|
||||
auction.chatMessages ??= [];
|
||||
auction.chatMessages.push(message);
|
||||
const overflow = auction.chatMessages.length - AUCTION_CHAT_MAX_MESSAGES;
|
||||
if (overflow > 0) {
|
||||
auction.chatMessages.splice(0, overflow);
|
||||
}
|
||||
|
||||
await auction.save();
|
||||
return { auction, message };
|
||||
}
|
||||
|
||||
public async listHistory(params: {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
}): Promise<AuctionHistoryView[]> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const AuctionHistoryModel =
|
||||
await this.connectionService.getModel('auctionHistory');
|
||||
const match = await MatchModel.findById(params.matchId).select({
|
||||
communityId: 1,
|
||||
});
|
||||
if (!match) throw new NotFoundException('Match not found.');
|
||||
if (!match.communityId.equals(params.communityId)) {
|
||||
throw new BadRequestException('Match does not belong to this community.');
|
||||
}
|
||||
|
||||
const entries = await AuctionHistoryModel.find({ matchId: params.matchId })
|
||||
.sort({ sequence: -1 })
|
||||
.limit(100)
|
||||
.lean()
|
||||
.exec();
|
||||
|
||||
return entries.map((entry) => ({
|
||||
sequence: entry.sequence,
|
||||
action: entry.action,
|
||||
actionLabel: this.formatHistoryActionLabel(entry.action),
|
||||
takenAt: entry.takenAt,
|
||||
}));
|
||||
}
|
||||
|
||||
public async openBidding(
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
): Promise<AuctionDocument> {
|
||||
@@ -201,9 +295,10 @@ export class AuctionService {
|
||||
if (auction.phase !== 'presenting') {
|
||||
throw new BadRequestException('Auction is not in presenting phase.');
|
||||
}
|
||||
await this.recordSnapshot(auction, 'open-bidding');
|
||||
auction.phase = 'bidding';
|
||||
auction.currentBid = 0;
|
||||
auction.currentBidder = undefined;
|
||||
auction.currentBidderTeamIndex = undefined;
|
||||
auction.currentDeadline = this.createDeadline(auction.maxTimerSeconds);
|
||||
await auction.save();
|
||||
return auction;
|
||||
@@ -214,8 +309,8 @@ export class AuctionService {
|
||||
if (auction.phase !== 'bidding') {
|
||||
throw new BadRequestException('Auction is not in bidding phase.');
|
||||
}
|
||||
const team = auction.teams.find((t) => t.side === params.side);
|
||||
if (!team) throw new BadRequestException('Unknown team side.');
|
||||
const team = this.findAuctionTeamByIndex(auction, params.teamIndex);
|
||||
if (!team) throw new BadRequestException('Unknown team.');
|
||||
if (params.amount <= auction.currentBid) {
|
||||
throw new BadRequestException('Bid must exceed current bid.');
|
||||
}
|
||||
@@ -225,13 +320,14 @@ export class AuctionService {
|
||||
this.assertTeamHasSlot(team);
|
||||
// 임시 운영용: 클라이언트에서 선택한 팀장 모드를 신뢰하고 실제 로그인 사용자 검증은 건너뛴다.
|
||||
|
||||
await this.recordSnapshot(auction, 'bid', params.bidderUserId);
|
||||
auction.currentBid = params.amount;
|
||||
auction.currentBidder = params.side;
|
||||
auction.currentBidderTeamIndex = params.teamIndex;
|
||||
auction.currentDeadline = this.createDeadline(
|
||||
this.resolveBidExtensionSeconds(auction),
|
||||
);
|
||||
auction.bids.push({
|
||||
side: params.side,
|
||||
teamIndex: params.teamIndex,
|
||||
amount: params.amount,
|
||||
bidderUserId: team.captainUserId,
|
||||
timestamp: new Date(),
|
||||
@@ -245,16 +341,20 @@ export class AuctionService {
|
||||
if (auction.phase !== 'bidding') {
|
||||
throw new BadRequestException('Auction is not in bidding phase.');
|
||||
}
|
||||
if (!auction.currentBidder || auction.currentBid <= 0) {
|
||||
if (!auction.currentBidderTeamIndex || auction.currentBid <= 0) {
|
||||
throw new BadRequestException('No bid to mark sold.');
|
||||
}
|
||||
const team = auction.teams.find((t) => t.side === auction.currentBidder);
|
||||
const team = this.findAuctionTeamByIndex(
|
||||
auction,
|
||||
auction.currentBidderTeamIndex,
|
||||
);
|
||||
if (!team) throw new BadRequestException('Winning team not found.');
|
||||
this.assertTeamHasSlot(team);
|
||||
|
||||
const current = auction.order[auction.currentIndex];
|
||||
if (!current) throw new BadRequestException('No current player.');
|
||||
|
||||
await this.recordSnapshot(auction, 'sold');
|
||||
const preferredPrimary = current.preferredPositions[0]?.position;
|
||||
team.members.push({
|
||||
userId: current.userId,
|
||||
@@ -268,22 +368,67 @@ export class AuctionService {
|
||||
return auction;
|
||||
}
|
||||
|
||||
public async markPassed(
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
): Promise<AuctionDocument> {
|
||||
const auction = await this.getByMatchId(matchId);
|
||||
if (auction.phase !== 'bidding') {
|
||||
throw new BadRequestException('Auction is not in bidding phase.');
|
||||
}
|
||||
if (auction.currentBid > 0) {
|
||||
throw new BadRequestException('Cannot pass a player with an active bid.');
|
||||
}
|
||||
const current = auction.order[auction.currentIndex];
|
||||
if (!current) throw new BadRequestException('No current player.');
|
||||
|
||||
await this.recordSnapshot(auction, 'passed');
|
||||
current.passCount = (current.passCount ?? 0) + 1;
|
||||
auction.passedQueue ??= [];
|
||||
auction.passedQueue.push(this.cloneAuctionPlayerSnapshot(current));
|
||||
auction.phase = 'passed';
|
||||
auction.currentDeadline = undefined;
|
||||
await auction.save();
|
||||
return auction;
|
||||
}
|
||||
|
||||
public async next(
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
): Promise<AuctionDocument> {
|
||||
const auction = await this.getByMatchId(matchId);
|
||||
if (auction.phase !== 'sold' && auction.phase !== 'presenting') {
|
||||
if (
|
||||
auction.phase !== 'sold' &&
|
||||
auction.phase !== 'presenting' &&
|
||||
auction.phase !== 'passed'
|
||||
) {
|
||||
throw new BadRequestException('Cannot advance from current phase.');
|
||||
}
|
||||
const nextIndex = auction.currentIndex + 1;
|
||||
const completesAuction =
|
||||
nextIndex >= auction.order.length &&
|
||||
(auction.passedQueue?.length ?? 0) === 0;
|
||||
await this.recordSnapshot(auction, completesAuction ? 'complete' : 'next');
|
||||
if (nextIndex >= auction.order.length) {
|
||||
auction.phase = 'complete';
|
||||
auction.completedAt = new Date();
|
||||
if ((auction.passedQueue?.length ?? 0) > 0) {
|
||||
auction.order.push(
|
||||
...auction.passedQueue.map((player) =>
|
||||
this.cloneAuctionPlayerSnapshot(player),
|
||||
),
|
||||
);
|
||||
auction.passedQueue = [];
|
||||
auction.auctionRound = (auction.auctionRound ?? 1) + 1;
|
||||
auction.currentIndex = nextIndex;
|
||||
auction.phase = 'presenting';
|
||||
auction.currentBid = 0;
|
||||
auction.currentBidderTeamIndex = undefined;
|
||||
} else {
|
||||
auction.phase = 'complete';
|
||||
auction.completedAt = new Date();
|
||||
}
|
||||
} else {
|
||||
auction.currentIndex = nextIndex;
|
||||
auction.phase = 'presenting';
|
||||
auction.currentBid = 0;
|
||||
auction.currentBidder = undefined;
|
||||
auction.currentBidderTeamIndex = undefined;
|
||||
}
|
||||
auction.currentDeadline = undefined;
|
||||
await auction.save();
|
||||
@@ -298,6 +443,8 @@ export class AuctionService {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
}): Promise<void> {
|
||||
const AuctionModel = await this.connectionService.getModel('auction');
|
||||
const AuctionHistoryModel =
|
||||
await this.connectionService.getModel('auctionHistory');
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
|
||||
const session = await this.connectionService.createSession();
|
||||
@@ -318,11 +465,18 @@ export class AuctionService {
|
||||
}
|
||||
|
||||
await auction.deleteOne({ session });
|
||||
await AuctionHistoryModel.deleteMany({ auctionId: auction._id }).session(
|
||||
session,
|
||||
);
|
||||
if (match.status === 'team-built') {
|
||||
await this.tournamentCodeService.releaseFromMatch(match);
|
||||
match.status = 'recruiting';
|
||||
match.teams = [];
|
||||
match.tournamentCodeIds = [];
|
||||
match.gameSchedule = [];
|
||||
match.participants.forEach((participant) => {
|
||||
participant.excluded = false;
|
||||
});
|
||||
match.teamBuiltAt = undefined;
|
||||
match.result = undefined;
|
||||
match.resultPollState = undefined;
|
||||
@@ -337,19 +491,316 @@ export class AuctionService {
|
||||
}
|
||||
}
|
||||
|
||||
public async undoTo(params: {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
sequence: number;
|
||||
}): Promise<AuctionDocument> {
|
||||
const AuctionModel = await this.connectionService.getModel('auction');
|
||||
const AuctionHistoryModel =
|
||||
await this.connectionService.getModel('auctionHistory');
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
|
||||
const session = await this.connectionService.createSession();
|
||||
if (!session) {
|
||||
throw new InternalServerErrorException('Failed to start DB session.');
|
||||
}
|
||||
|
||||
try {
|
||||
session.startTransaction();
|
||||
const auction = await AuctionModel.findOne({
|
||||
matchId: params.matchId,
|
||||
}).session(session);
|
||||
if (!auction) throw new NotFoundException('Auction not found.');
|
||||
|
||||
const match = await MatchModel.findById(params.matchId).session(session);
|
||||
if (!match) throw new NotFoundException('Match not found.');
|
||||
if (!match.communityId.equals(params.communityId)) {
|
||||
throw new BadRequestException('Community mismatch.');
|
||||
}
|
||||
|
||||
const history = await AuctionHistoryModel.findOne({
|
||||
auctionId: auction._id,
|
||||
sequence: params.sequence,
|
||||
})
|
||||
.session(session)
|
||||
.lean()
|
||||
.exec();
|
||||
if (!history) throw new NotFoundException('Auction history not found.');
|
||||
|
||||
const snapshot = history.snapshotBefore;
|
||||
if (!snapshot || typeof snapshot !== 'object') {
|
||||
throw new BadRequestException('Auction history snapshot is invalid.');
|
||||
}
|
||||
|
||||
const undoingCompletedAuction =
|
||||
Boolean(auction.completedAt) && !('completedAt' in snapshot);
|
||||
if (undoingCompletedAuction) {
|
||||
await this.tournamentCodeService.releaseFromMatch(match);
|
||||
await this.tournamentResultService.cancelPolling(match);
|
||||
match.status = 'team-built';
|
||||
match.result = undefined;
|
||||
await match.save({ session });
|
||||
}
|
||||
|
||||
await AuctionModel.replaceOne({ _id: auction._id }, snapshot, {
|
||||
session,
|
||||
}).exec();
|
||||
await AuctionHistoryModel.deleteMany({
|
||||
auctionId: auction._id,
|
||||
sequence: { $gt: params.sequence },
|
||||
})
|
||||
.session(session)
|
||||
.exec();
|
||||
|
||||
await session.commitTransaction();
|
||||
const restored = await AuctionModel.findById(auction._id);
|
||||
if (!restored) throw new NotFoundException('Auction not found.');
|
||||
return restored;
|
||||
} catch (err) {
|
||||
await session.abortTransaction();
|
||||
throw err;
|
||||
} finally {
|
||||
await session.endSession();
|
||||
}
|
||||
}
|
||||
|
||||
private applyTopTierPriority(
|
||||
order: AuctionPlayerSnapshot[],
|
||||
threshold: AuctionTopTierThreshold,
|
||||
manualTopTierUserIds: mongoose.Types.ObjectId[],
|
||||
): AuctionPlayerSnapshot[] {
|
||||
if (threshold === 'NONE') return order;
|
||||
if (threshold === 'MANUAL') {
|
||||
const manualIds = new Set(
|
||||
manualTopTierUserIds.map((userId) => userId.toString()),
|
||||
);
|
||||
if (manualIds.size === 0) return order;
|
||||
const selected = order.filter((snap) =>
|
||||
manualIds.has(snap.userId.toString()),
|
||||
);
|
||||
const rest = order.filter(
|
||||
(snap) => !manualIds.has(snap.userId.toString()),
|
||||
);
|
||||
return [...selected, ...rest];
|
||||
}
|
||||
|
||||
const ranks = [
|
||||
'IRON',
|
||||
'BRONZE',
|
||||
'SILVER',
|
||||
'GOLD',
|
||||
'PLATINUM',
|
||||
'EMERALD',
|
||||
'DIAMOND',
|
||||
'MASTER',
|
||||
'GRANDMASTER',
|
||||
'CHALLENGER',
|
||||
];
|
||||
const cutoff = ranks.indexOf(threshold);
|
||||
const score = (snap: AuctionPlayerSnapshot) => {
|
||||
const solo = snap.tiers.find(
|
||||
(tier) => tier.queueType === 'RANKED_SOLO_5x5',
|
||||
);
|
||||
if (!solo) return -1;
|
||||
const tierIdx = ranks.indexOf(solo.tier);
|
||||
if (tierIdx < cutoff) return -1;
|
||||
const rankBonus =
|
||||
({ I: 4, II: 3, III: 2, IV: 1, '': 0 } as Record<string, number>)[
|
||||
solo.rank
|
||||
] ?? 0;
|
||||
return tierIdx * 1000 + rankBonus * 100 + (solo.leaguePoints ?? 0) * 0.001;
|
||||
};
|
||||
|
||||
const top = order
|
||||
.filter((snap) => score(snap) >= 0)
|
||||
.sort((left, right) => score(right) - score(left));
|
||||
const rest = order.filter((snap) => score(snap) < 0);
|
||||
return [...top, ...rest];
|
||||
}
|
||||
|
||||
private shuffleAuctionPlayerOrder(
|
||||
order: AuctionPlayerSnapshot[],
|
||||
): AuctionPlayerSnapshot[] {
|
||||
const shuffled = [...order];
|
||||
for (let index = shuffled.length - 1; index > 0; index -= 1) {
|
||||
const swapIndex = Math.floor(Math.random() * (index + 1));
|
||||
[shuffled[index], shuffled[swapIndex]] = [
|
||||
shuffled[swapIndex],
|
||||
shuffled[index],
|
||||
];
|
||||
}
|
||||
return shuffled;
|
||||
}
|
||||
|
||||
private cloneAuctionPlayerSnapshot(
|
||||
player: AuctionPlayerSnapshot,
|
||||
): AuctionPlayerSnapshot {
|
||||
return JSON.parse(JSON.stringify(player)) as AuctionPlayerSnapshot;
|
||||
}
|
||||
|
||||
private normalizeChatMessage(message: string): string {
|
||||
const normalized = message.trim();
|
||||
if (!normalized) {
|
||||
throw new BadRequestException('Chat message is required.');
|
||||
}
|
||||
if (Array.from(normalized).length > AUCTION_CHAT_MAX_MESSAGE_LENGTH) {
|
||||
throw new BadRequestException(
|
||||
`Chat message must be ${AUCTION_CHAT_MAX_MESSAGE_LENGTH} characters or less.`,
|
||||
);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private normalizeChatDisplayName(displayName: string | undefined): string {
|
||||
const normalized = displayName?.trim() || '관전자';
|
||||
const chars = Array.from(normalized);
|
||||
if (chars.length <= AUCTION_CHAT_MAX_DISPLAY_NAME_LENGTH) {
|
||||
return normalized;
|
||||
}
|
||||
return chars.slice(0, AUCTION_CHAT_MAX_DISPLAY_NAME_LENGTH).join('');
|
||||
}
|
||||
|
||||
private async recordSnapshot(
|
||||
auction: AuctionDocument,
|
||||
action: AuctionActionType,
|
||||
actorUserId?: mongoose.Types.ObjectId,
|
||||
): Promise<void> {
|
||||
const AuctionHistoryModel =
|
||||
await this.connectionService.getModel('auctionHistory');
|
||||
const latest = await AuctionHistoryModel.findOne({ auctionId: auction._id })
|
||||
.sort({ sequence: -1 })
|
||||
.select({ sequence: 1 })
|
||||
.lean()
|
||||
.exec();
|
||||
const snapshotBefore =
|
||||
typeof auction.toObject === 'function'
|
||||
? auction.toObject({ depopulate: true })
|
||||
: auction;
|
||||
|
||||
await AuctionHistoryModel.create({
|
||||
auctionId: auction._id,
|
||||
matchId: auction.matchId,
|
||||
sequence: (latest?.sequence ?? 0) + 1,
|
||||
action,
|
||||
actorUserId,
|
||||
snapshotBefore: JSON.parse(JSON.stringify(snapshotBefore)),
|
||||
takenAt: new Date(),
|
||||
});
|
||||
}
|
||||
|
||||
private formatHistoryActionLabel(action: AuctionActionType): string {
|
||||
switch (action) {
|
||||
case 'start':
|
||||
return '경매 시작';
|
||||
case 'open-bidding':
|
||||
return '입찰 열기';
|
||||
case 'bid':
|
||||
return '입찰';
|
||||
case 'sold':
|
||||
return '낙찰 처리';
|
||||
case 'passed':
|
||||
return '유찰';
|
||||
case 'next':
|
||||
return '다음 선수';
|
||||
case 'complete':
|
||||
return '경매 완료';
|
||||
default:
|
||||
return action;
|
||||
}
|
||||
}
|
||||
|
||||
private applyAuctionCut(match: {
|
||||
participants: MatchParticipant[];
|
||||
}): MatchParticipant[] {
|
||||
const ordered = [...match.participants].sort(
|
||||
(left, right) => left.joinedAt.getTime() - right.joinedAt.getTime(),
|
||||
);
|
||||
const desiredAuctionCount = Math.floor(ordered.length / 10) * 10;
|
||||
const activeIds = new Set(
|
||||
ordered
|
||||
.slice(0, desiredAuctionCount)
|
||||
.map((participant) => participant.userId.toString()),
|
||||
);
|
||||
match.participants.forEach((participant) => {
|
||||
participant.excluded = !activeIds.has(participant.userId.toString());
|
||||
});
|
||||
return ordered.slice(0, desiredAuctionCount);
|
||||
}
|
||||
|
||||
private assertCaptainAssignments(
|
||||
captains: StartAuctionParams['captains'],
|
||||
activeParticipants: Array<{ userId: mongoose.Types.ObjectId }>,
|
||||
expectedCaptainCount: number,
|
||||
): void {
|
||||
const activeUserIds = new Set(
|
||||
activeParticipants.map((participant) => participant.userId.toString()),
|
||||
);
|
||||
const captainUserIds = new Set<string>();
|
||||
const teamIndexes = new Set<number>();
|
||||
|
||||
for (const captain of captains) {
|
||||
const userId = captain.userId.toString();
|
||||
if (!activeUserIds.has(userId)) {
|
||||
throw new BadRequestException(
|
||||
'All captains must be active participants of the match.',
|
||||
);
|
||||
}
|
||||
if (captainUserIds.has(userId)) {
|
||||
throw new BadRequestException('Captains must be different users.');
|
||||
}
|
||||
captainUserIds.add(userId);
|
||||
|
||||
if (
|
||||
!Number.isInteger(captain.teamIndex) ||
|
||||
captain.teamIndex < 1 ||
|
||||
captain.teamIndex > expectedCaptainCount
|
||||
) {
|
||||
throw new BadRequestException('Captain teamIndex is out of range.');
|
||||
}
|
||||
if (teamIndexes.has(captain.teamIndex)) {
|
||||
throw new BadRequestException('Duplicate captain team assignment.');
|
||||
}
|
||||
teamIndexes.add(captain.teamIndex);
|
||||
}
|
||||
|
||||
for (let teamIndex = 1; teamIndex <= expectedCaptainCount; teamIndex += 1) {
|
||||
if (!teamIndexes.has(teamIndex)) {
|
||||
throw new BadRequestException('Each teamIndex needs one captain.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private findAuctionTeamByIndex(
|
||||
auction: AuctionDocument,
|
||||
teamIndex: number,
|
||||
): AuctionTeam | undefined {
|
||||
return auction.teams.find((team) => team.teamIndex === teamIndex);
|
||||
}
|
||||
|
||||
private createDeadline(secondsFromNow: number): Date {
|
||||
return new Date(Date.now() + secondsFromNow * 1000);
|
||||
}
|
||||
|
||||
private resolveBidExtensionSeconds(auction: AuctionDocument): number {
|
||||
const maxTimerSeconds = Math.max(5, auction.maxTimerSeconds ?? 30);
|
||||
const bidExtensionSeconds = Math.max(0, auction.bidExtensionSeconds ?? 5);
|
||||
const minimumRemainingSeconds = Math.min(
|
||||
maxTimerSeconds,
|
||||
bidExtensionSeconds,
|
||||
);
|
||||
|
||||
if (!auction.currentDeadline) {
|
||||
return auction.maxTimerSeconds;
|
||||
return maxTimerSeconds;
|
||||
}
|
||||
|
||||
const remainingSeconds = Math.ceil(
|
||||
(auction.currentDeadline.getTime() - Date.now()) / 1000,
|
||||
);
|
||||
return Math.max(5, remainingSeconds);
|
||||
return Math.min(
|
||||
maxTimerSeconds,
|
||||
Math.max(minimumRemainingSeconds, remainingSeconds),
|
||||
);
|
||||
}
|
||||
|
||||
private assertTeamHasSlot(team: AuctionTeam): void {
|
||||
@@ -398,8 +849,8 @@ export class AuctionService {
|
||||
];
|
||||
|
||||
return {
|
||||
side: team.side,
|
||||
name: this.resolveTeamName(team.side),
|
||||
teamIndex: team.teamIndex,
|
||||
name: this.resolveTeamName(team.teamIndex),
|
||||
captainUserId: team.captainUserId,
|
||||
members,
|
||||
};
|
||||
@@ -411,8 +862,103 @@ export class AuctionService {
|
||||
await this.tournamentResultService.scheduleInitialPoll(match);
|
||||
}
|
||||
|
||||
private resolveTeamName(side: TeamSide): string {
|
||||
return side === 'blue' ? '블루팀' : '레드팀';
|
||||
private enqueueBackgroundOrderEnrichment(params: {
|
||||
auctionId: mongoose.Types.ObjectId;
|
||||
targets: AuctionEnrichmentTarget[];
|
||||
platform: RiotPlatformRoute;
|
||||
region: RiotRegionalRoute;
|
||||
}): void {
|
||||
if (params.targets.length === 0) return;
|
||||
|
||||
// 경매 시작 UX를 막지 않도록 Riot 최신화는 뒤에서 1명씩 천천히 수행한다.
|
||||
void this.refreshOrderSnapshotsFromRiot(params).catch((error: unknown) => {
|
||||
this.logger.warn(
|
||||
`Auction background Riot refresh failed for ${params.auctionId.toString()}: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
private async refreshOrderSnapshotsFromRiot(params: {
|
||||
auctionId: mongoose.Types.ObjectId;
|
||||
targets: AuctionEnrichmentTarget[];
|
||||
platform: RiotPlatformRoute;
|
||||
region: RiotRegionalRoute;
|
||||
}): Promise<void> {
|
||||
const AuctionModel = await this.connectionService.getModel('auction');
|
||||
|
||||
this.logger.debug(
|
||||
`Refreshing Riot snapshots for ${params.targets.length} auction players in background.`,
|
||||
);
|
||||
|
||||
await runWithConcurrency(
|
||||
params.targets,
|
||||
AUCTION_BACKGROUND_ENRICHMENT_CONCURRENCY,
|
||||
async (target) => {
|
||||
try {
|
||||
const result = await this.enrichmentService.enrichRiotAccount({
|
||||
userId: target.userId,
|
||||
puuid: target.puuid,
|
||||
options: {
|
||||
force: false,
|
||||
platform: params.platform,
|
||||
region: params.region,
|
||||
},
|
||||
});
|
||||
const account = result.account;
|
||||
if (!account) return;
|
||||
|
||||
await AuctionModel.updateOne(
|
||||
{
|
||||
_id: params.auctionId,
|
||||
'order.userId': target.userId,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
'order.$.gameName': account.gameName,
|
||||
'order.$.tagLine': account.tagLine,
|
||||
'order.$.profileIconId': account.profileIconId,
|
||||
'order.$.tiers': account.tiers,
|
||||
'order.$.tierHistory': account.tierHistory ?? [],
|
||||
'order.$.masteries': account.championMasteries,
|
||||
'order.$.recentStatsSummary': account.recentStatsSummary,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
},
|
||||
).exec();
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn(
|
||||
`Failed to refresh auction Riot snapshot for ${target.puuid}: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private wasRecentlyRefreshed(account: RiotAccount, cutoff: number): boolean {
|
||||
return this.getLatestRefreshAt(account) >= cutoff;
|
||||
}
|
||||
|
||||
private getLatestRefreshAt(account: RiotAccount): number {
|
||||
const timestamps = [
|
||||
account.lastRefreshRequestedAt,
|
||||
account.recentStatsFetchedAt,
|
||||
account.championMasteriesFetchedAt,
|
||||
account.matchIdsFetchedAt,
|
||||
...account.tiers.map((tier) => tier.fetchedAt),
|
||||
];
|
||||
|
||||
return timestamps.reduce((latest, value) => {
|
||||
const timestamp = value instanceof Date ? value.getTime() : 0;
|
||||
return Math.max(latest, timestamp);
|
||||
}, 0);
|
||||
}
|
||||
|
||||
private resolveTeamName(teamIndex: number): string {
|
||||
return `${teamIndex}팀`;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,42 +7,69 @@ import {
|
||||
IsInt,
|
||||
IsMongoId,
|
||||
IsOptional,
|
||||
Max,
|
||||
Min,
|
||||
ValidateNested,
|
||||
} from 'class-validator';
|
||||
import { TEAM_SIDES } from '../../global/database/schema';
|
||||
import type { TeamSide } from '../../global/database/schema';
|
||||
import { AUCTION_TOP_TIER_THRESHOLDS } from '../../global/database/schema';
|
||||
|
||||
export type AuctionTopTierThreshold =
|
||||
(typeof AUCTION_TOP_TIER_THRESHOLDS)[number];
|
||||
|
||||
class CaptainAssignmentDto {
|
||||
@IsEnum(TEAM_SIDES)
|
||||
side!: TeamSide;
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
teamIndex!: number;
|
||||
|
||||
@IsMongoId()
|
||||
userId!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(100)
|
||||
@Max(100000)
|
||||
initialPoints?: number;
|
||||
}
|
||||
|
||||
export class StartAuctionDto {
|
||||
@IsArray()
|
||||
@ArrayMinSize(2)
|
||||
@ArrayMaxSize(2)
|
||||
@ArrayMaxSize(16)
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => CaptainAssignmentDto)
|
||||
captains!: CaptainAssignmentDto[];
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Min(100)
|
||||
@Max(100000)
|
||||
initialPoints?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(AUCTION_TOP_TIER_THRESHOLDS)
|
||||
topTierThreshold?: AuctionTopTierThreshold;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ArrayMaxSize(100)
|
||||
@IsMongoId({ each: true })
|
||||
manualTopTierUserIds?: string[];
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(5)
|
||||
maxTimerSeconds?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
bidExtensionSeconds?: number;
|
||||
}
|
||||
|
||||
export class PlaceBidDto {
|
||||
@IsEnum(TEAM_SIDES)
|
||||
side!: TeamSide;
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
teamIndex!: number;
|
||||
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@@ -58,3 +85,9 @@ export class SoldDto {
|
||||
@IsEnum(['TOP', 'JGL', 'MID', 'ADC', 'SUP'])
|
||||
assignedPosition?: 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
|
||||
}
|
||||
|
||||
export class UndoAuctionDto {
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
sequence!: number;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { GarnetService } from '../global/garnet/garnet.service';
|
||||
|
||||
const COMMUNITY_STATS_TTL_SECONDS = 60 * 60;
|
||||
const COMMUNITY_STATS_TTL_SECONDS = 5 * 60;
|
||||
const COMMUNITY_STATS_DETAIL_TTL_SECONDS = 24 * 60 * 60;
|
||||
|
||||
@Injectable()
|
||||
|
||||
@@ -2,10 +2,19 @@ import { Module } from '@nestjs/common';
|
||||
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({
|
||||
controllers: [CommunityStatsController],
|
||||
providers: [CommunityStatsService, CommunityStatsCacheService],
|
||||
exports: [CommunityStatsService],
|
||||
providers: [
|
||||
CommunityStatsService,
|
||||
CommunityStatsCacheService,
|
||||
MatchStatsFragmentBuilder,
|
||||
MatchStatsRepository,
|
||||
MatchStatsService,
|
||||
],
|
||||
exports: [CommunityStatsService, MatchStatsService],
|
||||
})
|
||||
export class CommunityStatsModule {}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -22,17 +22,25 @@ export interface InternalMatchCardView {
|
||||
scheduledAt: string;
|
||||
status: 'finished' | 'in-progress';
|
||||
gameCount: number;
|
||||
blueScore: number;
|
||||
redScore: number;
|
||||
winnerSide?: TeamSide;
|
||||
winnerTeamIndex?: number;
|
||||
seriesResults: Array<{
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
teamAWins: number;
|
||||
teamBWins: number;
|
||||
winnerTeamIndex?: number;
|
||||
}>;
|
||||
games: Array<{
|
||||
gameNumber: number;
|
||||
riotMatchId: string | null;
|
||||
blueTeamIndex: number;
|
||||
redTeamIndex: number;
|
||||
winnerTeamIndex: number | null;
|
||||
winnerSide: TeamSide | null;
|
||||
gameDuration: number;
|
||||
}>;
|
||||
teams: Array<{
|
||||
side: TeamSide;
|
||||
teamIndex: number;
|
||||
name: string;
|
||||
members: Array<{
|
||||
userId: string;
|
||||
@@ -101,12 +109,14 @@ export interface InternalMatchDetailResponse {
|
||||
gameCreation: number;
|
||||
gameDuration: number;
|
||||
teams: Array<{
|
||||
teamIndex: number;
|
||||
side: TeamSide;
|
||||
win: boolean;
|
||||
objectives: { baron: number; dragon: number; tower: number };
|
||||
participants: Array<{
|
||||
userId: string | null;
|
||||
summonerName: string;
|
||||
teamIndex: number;
|
||||
side: TeamSide;
|
||||
teamPosition: string;
|
||||
championId: number;
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import mongoose from 'mongoose';
|
||||
import type { MatchDocument } from '../global/database/schema';
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,367 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import type {
|
||||
MatchDocument,
|
||||
MatchGameResultParticipant,
|
||||
TeamSide,
|
||||
} from '../global/database/schema';
|
||||
import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types';
|
||||
import type { InternalMatchCardView } from './community-stats.types';
|
||||
import type {
|
||||
InternalGameDetail,
|
||||
InternalRecord,
|
||||
MatchStatsFragment,
|
||||
} from './match-stats.types';
|
||||
|
||||
@Injectable()
|
||||
export class MatchStatsFragmentBuilder {
|
||||
public buildFragment(params: {
|
||||
match: MatchDocument;
|
||||
rawByRiotMatchId: Map<string, RiotMatchDto>;
|
||||
}): 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);
|
||||
return raw
|
||||
? this.toGameDetail(params.match, game, raw)
|
||||
: 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,
|
||||
): InternalGameDetail {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
gameNumber: game.gameNumber,
|
||||
riotMatchId: game.riotMatchId,
|
||||
gameCreation: game.gameCreation,
|
||||
gameDuration: game.gameDuration,
|
||||
winnerSide: game.winnerSide,
|
||||
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: {
|
||||
baron: rawTeam?.objectives?.baron?.kills ?? 0,
|
||||
dragon: rawTeam?.objectives?.dragon?.kills ?? 0,
|
||||
tower: rawTeam?.objectives?.tower?.kills ?? 0,
|
||||
},
|
||||
participants: game.participants
|
||||
.filter((participant) => participant.side === side)
|
||||
.map((participant) =>
|
||||
this.toRecord({
|
||||
match,
|
||||
game,
|
||||
participant,
|
||||
rawParticipant: rawByPuuid.get(
|
||||
puuidByUserId.get(participant.userId.toString()) ?? '',
|
||||
),
|
||||
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,
|
||||
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
|
||||
teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex,
|
||||
side,
|
||||
win: game.winnerSide === side,
|
||||
objectives: { baron: 0, dragon: 0, tower: 0 },
|
||||
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;
|
||||
teamKills: number;
|
||||
teamDamage: number;
|
||||
}): InternalRecord {
|
||||
const { match, game, participant, rawParticipant, 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,
|
||||
userId: participant.userId.toString(),
|
||||
summonerName:
|
||||
snapshot?.gameName ??
|
||||
rawParticipant?.riotIdGameName ??
|
||||
rawParticipant?.summonerName ??
|
||||
'Unknown',
|
||||
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,
|
||||
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) : {},
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
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 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;
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type { MatchStats, MatchStatsDocument } from '../global/database/schema';
|
||||
|
||||
@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');
|
||||
await MatchStatsModel.updateOne(
|
||||
{ matchId: fragment.matchId },
|
||||
{ $set: fragment },
|
||||
{ upsert: true },
|
||||
).exec();
|
||||
}
|
||||
|
||||
public async deleteByMatch(matchId: mongoose.Types.ObjectId): Promise<void> {
|
||||
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||
await MatchStatsModel.deleteOne({ 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 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: 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 MatchStatsModel.find(filter).sort({ scheduledAt: -1 }).exec();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
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';
|
||||
|
||||
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 === '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,
|
||||
);
|
||||
|
||||
await service.buildAndUpsert(matchId);
|
||||
|
||||
expect(repository.deleteByMatch).toHaveBeenCalledWith(matchId);
|
||||
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: {} }]),
|
||||
}),
|
||||
});
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockImplementation(async (name: string) => {
|
||||
if (name === 'match') return { findById };
|
||||
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,
|
||||
);
|
||||
|
||||
await service.buildAndUpsert(matchId);
|
||||
|
||||
expect(builder.buildFragment).toHaveBeenCalledWith({
|
||||
match,
|
||||
rawByRiotMatchId: expect.any(Map),
|
||||
});
|
||||
expect(repository.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
matchId,
|
||||
communityId,
|
||||
scheduledAt,
|
||||
gameCreationMin: 1_000,
|
||||
gameCreationMax: 2_000,
|
||||
builderVersion: 1,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type { MatchDocument } from '../global/database/schema';
|
||||
import type { RiotMatchDto } 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 {
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly repository: MatchStatsRepository,
|
||||
private readonly builder: MatchStatsFragmentBuilder,
|
||||
) {}
|
||||
|
||||
public async buildAndUpsert(matchId: mongoose.Types.ObjectId): Promise<void> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
||||
const match = await MatchModel.findById(matchId).exec();
|
||||
if (!match) return;
|
||||
if (!this.isEligible(match)) {
|
||||
await this.repository.deleteByMatch(matchId);
|
||||
return;
|
||||
}
|
||||
|
||||
const riotIds = [
|
||||
...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 fragment = this.builder.buildFragment({ match, rawByRiotMatchId });
|
||||
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
||||
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'] },
|
||||
'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)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type {
|
||||
MatchStatsGameDetail,
|
||||
MatchStatsRecord,
|
||||
} from '../global/database/schema';
|
||||
import type { InternalMatchCardView } from './community-stats.types';
|
||||
|
||||
export const MATCH_STATS_BUILDER_VERSION = 1;
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
|
||||
const DEFAULT_LEASE_MS = 5 * 60 * 1000;
|
||||
|
||||
export type DakaoInboxClaimResult =
|
||||
| { status: 'claimed' }
|
||||
| { status: 'duplicate' }
|
||||
| { status: 'inflight' };
|
||||
|
||||
@Injectable()
|
||||
export class DakaoInboxService {
|
||||
constructor(private readonly connectionService: ConnectionService) {}
|
||||
|
||||
public async claim(params: {
|
||||
consumer: string;
|
||||
projectId: string;
|
||||
chatLogLogId: string;
|
||||
leaseMs?: number;
|
||||
}): Promise<DakaoInboxClaimResult> {
|
||||
const Model = await this.connectionService.getModel('dakaoInboundMessage');
|
||||
const now = new Date();
|
||||
const processingExpiresAt = new Date(
|
||||
now.getTime() + (params.leaseMs ?? DEFAULT_LEASE_MS),
|
||||
);
|
||||
|
||||
try {
|
||||
await Model.create({
|
||||
consumer: params.consumer,
|
||||
projectId: params.projectId,
|
||||
chatLogLogId: params.chatLogLogId,
|
||||
state: 'processing',
|
||||
attempts: 1,
|
||||
processingExpiresAt,
|
||||
});
|
||||
return { status: 'claimed' };
|
||||
} catch (err) {
|
||||
if ((err as { code?: number })?.code !== 11000) throw err;
|
||||
}
|
||||
|
||||
const existing = await Model.findOne({
|
||||
consumer: params.consumer,
|
||||
projectId: params.projectId,
|
||||
chatLogLogId: params.chatLogLogId,
|
||||
})
|
||||
.lean()
|
||||
.exec();
|
||||
if (!existing) return { status: 'inflight' };
|
||||
if (existing.state === 'processed') return { status: 'duplicate' };
|
||||
if (
|
||||
existing.state === 'processing' &&
|
||||
existing.processingExpiresAt &&
|
||||
existing.processingExpiresAt > now
|
||||
) {
|
||||
return { status: 'inflight' };
|
||||
}
|
||||
|
||||
const updated = await Model.updateOne(
|
||||
{
|
||||
_id: existing._id,
|
||||
$or: [
|
||||
{ state: 'failed' },
|
||||
{ state: 'processing', processingExpiresAt: { $lte: now } },
|
||||
],
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
state: 'processing',
|
||||
processingExpiresAt,
|
||||
},
|
||||
$inc: { attempts: 1 },
|
||||
},
|
||||
).exec();
|
||||
return updated.modifiedCount > 0
|
||||
? { status: 'claimed' }
|
||||
: { status: 'inflight' };
|
||||
}
|
||||
|
||||
public async markProcessed(params: {
|
||||
consumer: string;
|
||||
projectId: string;
|
||||
chatLogLogId: string;
|
||||
}): Promise<void> {
|
||||
const Model = await this.connectionService.getModel('dakaoInboundMessage');
|
||||
await Model.updateOne(
|
||||
{
|
||||
consumer: params.consumer,
|
||||
projectId: params.projectId,
|
||||
chatLogLogId: params.chatLogLogId,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
state: 'processed',
|
||||
processedAt: new Date(),
|
||||
},
|
||||
$unset: { processingExpiresAt: '', lastError: '' },
|
||||
},
|
||||
).exec();
|
||||
}
|
||||
|
||||
public async markFailed(params: {
|
||||
consumer: string;
|
||||
projectId: string;
|
||||
chatLogLogId: string;
|
||||
error: unknown;
|
||||
}): Promise<void> {
|
||||
const Model = await this.connectionService.getModel('dakaoInboundMessage');
|
||||
await Model.updateOne(
|
||||
{
|
||||
consumer: params.consumer,
|
||||
projectId: params.projectId,
|
||||
chatLogLogId: params.chatLogLogId,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
state: 'failed',
|
||||
lastError: (params.error as Error)?.message ?? String(params.error),
|
||||
},
|
||||
$unset: { processingExpiresAt: '' },
|
||||
},
|
||||
).exec();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { NatsService } from '../global/nats/nats.service';
|
||||
import { resolveDakaoNatsNames } from './dakao.nats-names';
|
||||
|
||||
@Injectable()
|
||||
export class DakaoJetStreamResourceService {
|
||||
private ensurePromise: Promise<void> | null = null;
|
||||
|
||||
constructor(private readonly natsService: NatsService) {}
|
||||
|
||||
public async ensure(): Promise<void> {
|
||||
this.ensurePromise ??= this.ensureInternal();
|
||||
await this.ensurePromise;
|
||||
}
|
||||
|
||||
private async ensureInternal(): Promise<void> {
|
||||
const names = resolveDakaoNatsNames();
|
||||
await this.natsService.ensureJetStreamStream({
|
||||
name: names.streams.botCommand,
|
||||
subjects: [names.subjects.botCommandSubmitted],
|
||||
retention: 'workqueue',
|
||||
replicas: 1,
|
||||
});
|
||||
await this.natsService.ensureJetStreamConsumer({
|
||||
stream: names.streams.botCommand,
|
||||
durable: names.consumers.botCommand,
|
||||
filterSubject: names.subjects.botCommandSubmitted,
|
||||
description: 'LolyMpus Dakao bot command handler',
|
||||
replicas: 1,
|
||||
});
|
||||
|
||||
await this.natsService.ensureJetStreamStream({
|
||||
name: names.streams.sendRequest,
|
||||
subjects: [names.subjects.chatSendMessage],
|
||||
retention: 'workqueue',
|
||||
replicas: 1,
|
||||
});
|
||||
await this.natsService.ensureJetStreamConsumer({
|
||||
stream: names.streams.sendRequest,
|
||||
durable: names.consumers.sendRequest,
|
||||
filterSubject: names.subjects.chatSendMessage,
|
||||
description: 'Dakao send-message worker',
|
||||
replicas: 1,
|
||||
});
|
||||
|
||||
await this.natsService.ensureJetStreamStream({
|
||||
name: names.streams.sendResult,
|
||||
subjects: [
|
||||
names.subjects.chatSendMessageSucceeded,
|
||||
names.subjects.chatSendMessageFailed,
|
||||
],
|
||||
retention: 'limits',
|
||||
maxAgeDays: 30,
|
||||
replicas: 1,
|
||||
});
|
||||
await this.natsService.ensureJetStreamConsumer({
|
||||
stream: names.streams.sendResult,
|
||||
durable: names.consumers.sendResult,
|
||||
filterSubject: `${names.env}.lolympus.dakao.chat.send-message.*.v1`,
|
||||
description: 'LolyMpus Dakao send-message result handler',
|
||||
replicas: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import {
|
||||
Injectable,
|
||||
Logger,
|
||||
OnModuleDestroy,
|
||||
OnModuleInit,
|
||||
} from '@nestjs/common';
|
||||
import { DakaoOutboxService } from './dakao-outbox.service';
|
||||
|
||||
const SWEEP_INTERVAL_MS = 60 * 1000;
|
||||
const STALE_OUTBOX_MS = 5 * 60 * 1000;
|
||||
|
||||
@Injectable()
|
||||
export class DakaoOutboxSweeperService
|
||||
implements OnModuleInit, OnModuleDestroy
|
||||
{
|
||||
private readonly logger = new Logger(DakaoOutboxSweeperService.name);
|
||||
private timer: NodeJS.Timeout | undefined;
|
||||
|
||||
constructor(private readonly outboxService: DakaoOutboxService) {}
|
||||
|
||||
onModuleInit() {
|
||||
this.timer = setInterval(() => {
|
||||
void this.sweep();
|
||||
}, SWEEP_INTERVAL_MS);
|
||||
this.timer.unref();
|
||||
}
|
||||
|
||||
onModuleDestroy() {
|
||||
if (this.timer) clearInterval(this.timer);
|
||||
}
|
||||
|
||||
private async sweep(): Promise<void> {
|
||||
try {
|
||||
const swept = await this.outboxService.sweepStale({
|
||||
staleMs: STALE_OUTBOX_MS,
|
||||
limit: 20,
|
||||
});
|
||||
if (swept > 0) {
|
||||
this.logger.warn(`Re-published ${swept} stale Dakao outbox messages.`);
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.error(
|
||||
`Dakao outbox sweep failed: ${(err as Error)?.stack ?? err}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import { NatsService } from '../global/nats/nats.service';
|
||||
import { DakaoOutboxService } from './dakao-outbox.service';
|
||||
import { DakaoResultSubjects } from './dakao.types';
|
||||
|
||||
function execResult<T>(value: T) {
|
||||
return { exec: jest.fn().mockResolvedValue(value) };
|
||||
}
|
||||
|
||||
function makeService(outboxModel: Record<string, unknown>) {
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockResolvedValue(outboxModel),
|
||||
} as unknown as ConnectionService;
|
||||
const natsService = {
|
||||
publishJetStream: jest.fn().mockResolvedValue(undefined),
|
||||
} as unknown as NatsService;
|
||||
|
||||
return {
|
||||
service: new DakaoOutboxService(connectionService, natsService),
|
||||
connectionService,
|
||||
natsService,
|
||||
};
|
||||
}
|
||||
|
||||
describe('DakaoOutboxService', () => {
|
||||
it('persists result subjects when enqueuing send-message commands', async () => {
|
||||
const outboxModel = {
|
||||
findOneAndUpdate: jest.fn().mockReturnValue(execResult({})),
|
||||
updateOne: jest.fn().mockReturnValue(execResult({})),
|
||||
};
|
||||
const { service, natsService } = makeService(outboxModel);
|
||||
const resultSubjects: DakaoResultSubjects = {
|
||||
succeeded: 'staging.lolympus.dakao.chat.send-message.succeeded.v1',
|
||||
failed: 'staging.lolympus.dakao.chat.send-message.failed.v1',
|
||||
};
|
||||
|
||||
await service.enqueueAndPublish({
|
||||
subject: 'staging.dakao.chat.send-message.v1',
|
||||
eventId: 'lolympus:chat.send-message:chat-log-1',
|
||||
envelope: {
|
||||
schema: 'dakao.command.v1',
|
||||
eventId: 'lolympus:chat.send-message:chat-log-1',
|
||||
type: 'chat.send-message',
|
||||
eventSource: 'lolympus',
|
||||
correlationId: 'chat-log-1',
|
||||
resultSubjects,
|
||||
payload: {
|
||||
chatroomId: '18474390111480678',
|
||||
segments: [{ kind: 'text', text: 'done' }],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(outboxModel.findOneAndUpdate).toHaveBeenCalledWith(
|
||||
{ eventId: 'lolympus:chat.send-message:chat-log-1' },
|
||||
expect.objectContaining({
|
||||
$setOnInsert: expect.objectContaining({ resultSubjects }),
|
||||
}),
|
||||
expect.any(Object),
|
||||
);
|
||||
expect(natsService.publishJetStream).toHaveBeenCalledWith(
|
||||
'staging.dakao.chat.send-message.v1',
|
||||
expect.objectContaining({ resultSubjects }),
|
||||
{ messageId: 'lolympus:chat.send-message:chat-log-1' },
|
||||
);
|
||||
});
|
||||
|
||||
it('restores send-message result subjects when sweeping legacy stale rows', async () => {
|
||||
const previousNodeEnv = process.env.NODE_ENV;
|
||||
process.env.NODE_ENV = 'staging';
|
||||
|
||||
try {
|
||||
const exec = jest.fn().mockResolvedValue([
|
||||
{
|
||||
eventId: 'lolympus:chat.send-message:chat-log-1',
|
||||
type: 'chat.send-message',
|
||||
eventSource: 'lolympus',
|
||||
subject: 'staging.dakao.chat.send-message.v1',
|
||||
correlationId: 'chat-log-1',
|
||||
payload: {
|
||||
chatroomId: '18474390111480678',
|
||||
segments: [{ kind: 'text', text: 'done' }],
|
||||
},
|
||||
},
|
||||
]);
|
||||
const lean = jest.fn().mockReturnValue({ exec });
|
||||
const limit = jest.fn().mockReturnValue({ lean });
|
||||
const sort = jest.fn().mockReturnValue({ limit });
|
||||
const outboxModel = {
|
||||
find: jest.fn().mockReturnValue({ sort }),
|
||||
};
|
||||
const { service } = makeService(outboxModel);
|
||||
const enqueue = jest
|
||||
.spyOn(service, 'enqueueAndPublish')
|
||||
.mockResolvedValue(undefined);
|
||||
|
||||
await expect(service.sweepStale({ staleMs: 1, limit: 1 })).resolves.toBe(
|
||||
1,
|
||||
);
|
||||
|
||||
expect(enqueue).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
envelope: expect.objectContaining({
|
||||
resultSubjects: {
|
||||
succeeded:
|
||||
'staging.lolympus.dakao.chat.send-message.succeeded.v1',
|
||||
failed: 'staging.lolympus.dakao.chat.send-message.failed.v1',
|
||||
},
|
||||
}),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
process.env.NODE_ENV = previousNodeEnv;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,191 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import { NatsService } from '../global/nats/nats.service';
|
||||
import { resolveDakaoNatsNames } from './dakao.nats-names';
|
||||
import {
|
||||
DakaoCommandEnvelope,
|
||||
DakaoResultEnvelope,
|
||||
DakaoResultSubjects,
|
||||
} from './dakao.types';
|
||||
|
||||
const CHAT_SEND_MESSAGE_TYPE = 'chat.send-message';
|
||||
const TERMINAL_STATES = ['sent', 'failed'] as const;
|
||||
|
||||
@Injectable()
|
||||
export class DakaoOutboxService {
|
||||
private readonly logger = new Logger(DakaoOutboxService.name);
|
||||
private readonly chatSendMessageResultSubjects = {
|
||||
succeeded: resolveDakaoNatsNames().subjects.chatSendMessageSucceeded,
|
||||
failed: resolveDakaoNatsNames().subjects.chatSendMessageFailed,
|
||||
};
|
||||
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly natsService: NatsService,
|
||||
) {}
|
||||
|
||||
public async enqueueAndPublish<TPayload>(params: {
|
||||
subject: string;
|
||||
eventId: string;
|
||||
envelope: DakaoCommandEnvelope<TPayload>;
|
||||
}): Promise<void> {
|
||||
const OutboxModel =
|
||||
await this.connectionService.getModel('dakaoOutboxMessage');
|
||||
await OutboxModel.findOneAndUpdate(
|
||||
{ eventId: params.eventId },
|
||||
{
|
||||
$setOnInsert: {
|
||||
eventId: params.eventId,
|
||||
eventSource: params.envelope.eventSource,
|
||||
type: params.envelope.type,
|
||||
subject: params.subject,
|
||||
correlationId: params.envelope.correlationId,
|
||||
resultSubjects: params.envelope.resultSubjects,
|
||||
payload: params.envelope.payload as Record<string, unknown>,
|
||||
state: 'pending',
|
||||
publishAttempts: 0,
|
||||
compensationState: 'none',
|
||||
},
|
||||
},
|
||||
{ upsert: true, returnDocument: 'after', setDefaultsOnInsert: true },
|
||||
).exec();
|
||||
|
||||
try {
|
||||
await this.natsService.publishJetStream(params.subject, params.envelope, {
|
||||
messageId: params.eventId,
|
||||
});
|
||||
await OutboxModel.updateOne(
|
||||
{
|
||||
eventId: params.eventId,
|
||||
state: { $nin: TERMINAL_STATES },
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
state: 'published',
|
||||
publishedAt: new Date(),
|
||||
},
|
||||
$inc: { publishAttempts: 1 },
|
||||
$unset: { lastPublishError: '' },
|
||||
},
|
||||
).exec();
|
||||
} catch (err) {
|
||||
await OutboxModel.updateOne(
|
||||
{
|
||||
eventId: params.eventId,
|
||||
state: { $nin: TERMINAL_STATES },
|
||||
},
|
||||
{
|
||||
$inc: { publishAttempts: 1 },
|
||||
$set: {
|
||||
lastPublishError: (err as Error)?.message ?? String(err),
|
||||
},
|
||||
},
|
||||
).exec();
|
||||
this.logger.error(
|
||||
`Failed to publish Dakao outbox eventId=${params.eventId}: ${
|
||||
(err as Error)?.stack ?? err
|
||||
}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public async applySendResult(params: {
|
||||
subject: string;
|
||||
envelope: DakaoResultEnvelope;
|
||||
}): Promise<{ duplicate: boolean; terminalState?: 'sent' | 'failed' }> {
|
||||
const ResultModel = await this.connectionService.getModel(
|
||||
'dakaoSendResultEvent',
|
||||
);
|
||||
const OutboxModel =
|
||||
await this.connectionService.getModel('dakaoOutboxMessage');
|
||||
|
||||
try {
|
||||
await ResultModel.create({
|
||||
eventId: params.envelope.eventId,
|
||||
requestEventId: params.envelope.requestEventId,
|
||||
eventSource: params.envelope.eventSource,
|
||||
requestEventSource: params.envelope.requestEventSource,
|
||||
type: params.envelope.type,
|
||||
subject: params.subject,
|
||||
status: params.envelope.status,
|
||||
correlationId: params.envelope.correlationId,
|
||||
handledAt: new Date(params.envelope.handledAt),
|
||||
providerMessageId: params.envelope.providerMessageId,
|
||||
error: params.envelope.error,
|
||||
raw: params.envelope as unknown as Record<string, unknown>,
|
||||
});
|
||||
} catch (err) {
|
||||
if ((err as { code?: number })?.code === 11000) {
|
||||
return { duplicate: true };
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
const terminalState =
|
||||
params.envelope.status === 'succeeded' ? 'sent' : 'failed';
|
||||
await OutboxModel.updateOne(
|
||||
{
|
||||
eventId: params.envelope.requestEventId,
|
||||
state: { $nin: TERMINAL_STATES },
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
state: terminalState,
|
||||
terminalAt: new Date(),
|
||||
resultEventId: params.envelope.eventId,
|
||||
terminalError: params.envelope.error,
|
||||
compensationState:
|
||||
params.envelope.status === 'failed' ? 'pending' : 'none',
|
||||
compensationReason: params.envelope.error?.code,
|
||||
},
|
||||
},
|
||||
).exec();
|
||||
|
||||
return { duplicate: false, terminalState };
|
||||
}
|
||||
|
||||
public async sweepStale(params?: {
|
||||
staleMs?: number;
|
||||
limit?: number;
|
||||
}): Promise<number> {
|
||||
const OutboxModel =
|
||||
await this.connectionService.getModel('dakaoOutboxMessage');
|
||||
const staleBefore = new Date(
|
||||
Date.now() - (params?.staleMs ?? 5 * 60 * 1000),
|
||||
);
|
||||
const rows = await OutboxModel.find({
|
||||
state: { $in: ['pending', 'published'] },
|
||||
updatedAt: { $lte: staleBefore },
|
||||
})
|
||||
.sort({ updatedAt: 1 })
|
||||
.limit(params?.limit ?? 20)
|
||||
.lean()
|
||||
.exec();
|
||||
|
||||
for (const row of rows) {
|
||||
await this.enqueueAndPublish({
|
||||
subject: row.subject,
|
||||
eventId: row.eventId,
|
||||
envelope: {
|
||||
schema: 'dakao.command.v1',
|
||||
eventId: row.eventId,
|
||||
type: row.type,
|
||||
eventSource: row.eventSource,
|
||||
correlationId: row.correlationId,
|
||||
resultSubjects:
|
||||
row.resultSubjects ?? this.resolveDefaultResultSubjects(row.type),
|
||||
payload: row.payload,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
}
|
||||
|
||||
private resolveDefaultResultSubjects(
|
||||
type: string,
|
||||
): DakaoResultSubjects | undefined {
|
||||
if (type !== CHAT_SEND_MESSAGE_TYPE) return undefined;
|
||||
return this.chatSendMessageResultSubjects;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
|
||||
import { NatsService } from '../global/nats/nats.service';
|
||||
import { DakaoJetStreamResourceService } from './dakao-jetstream-resource.service';
|
||||
import { resolveDakaoNatsNames } from './dakao.nats-names';
|
||||
import { DakaoOutboxService } from './dakao-outbox.service';
|
||||
import { DakaoResultEnvelope } from './dakao.types';
|
||||
|
||||
@Injectable()
|
||||
export class DakaoSendResultSubscriber implements OnModuleInit {
|
||||
private readonly logger = new Logger(DakaoSendResultSubscriber.name);
|
||||
|
||||
constructor(
|
||||
private readonly natsService: NatsService,
|
||||
private readonly resources: DakaoJetStreamResourceService,
|
||||
private readonly outboxService: DakaoOutboxService,
|
||||
) {}
|
||||
|
||||
async onModuleInit() {
|
||||
await this.resources.ensure();
|
||||
const names = resolveDakaoNatsNames();
|
||||
void this.natsService.consumeJetStream<DakaoResultEnvelope>(
|
||||
{
|
||||
stream: names.streams.sendResult,
|
||||
durable: names.consumers.sendResult,
|
||||
},
|
||||
(event, msg) => this.handleResult(event, msg.subject),
|
||||
);
|
||||
this.logger.log(
|
||||
`Dakao send-result subscriber ready on stream="${names.streams.sendResult}" durable="${names.consumers.sendResult}"`,
|
||||
);
|
||||
}
|
||||
|
||||
private async handleResult(
|
||||
event: DakaoResultEnvelope,
|
||||
subject: string,
|
||||
): Promise<void> {
|
||||
if (!this.validate(event)) {
|
||||
this.logger.warn(`Ignoring invalid Dakao send-result on ${subject}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await this.outboxService.applySendResult({
|
||||
subject,
|
||||
envelope: event,
|
||||
});
|
||||
if (result.duplicate) {
|
||||
this.logger.log(
|
||||
`Duplicate Dakao result ignored eventId=${event.eventId}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.logger.log(
|
||||
`Dakao result applied eventId=${event.eventId} requestEventId=${event.requestEventId} state=${result.terminalState ?? '-'}`,
|
||||
);
|
||||
}
|
||||
|
||||
private validate(event: unknown): event is DakaoResultEnvelope {
|
||||
if (!event || typeof event !== 'object') return false;
|
||||
const e = event as Partial<DakaoResultEnvelope>;
|
||||
if (e.schema !== 'dakao.result.v1') return false;
|
||||
if (typeof e.eventId !== 'string' || e.eventId.length === 0) return false;
|
||||
if (typeof e.requestEventId !== 'string' || e.requestEventId.length === 0) {
|
||||
return false;
|
||||
}
|
||||
if (typeof e.eventSource !== 'string' || e.eventSource.length === 0)
|
||||
return false;
|
||||
if (
|
||||
typeof e.requestEventSource !== 'string' ||
|
||||
e.requestEventSource.length === 0
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (e.status !== 'succeeded' && e.status !== 'failed') return false;
|
||||
if (
|
||||
typeof e.handledAt !== 'string' ||
|
||||
Number.isNaN(Date.parse(e.handledAt))
|
||||
)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { ConnectionService } from '../global/database/connection.service';
|
||||
import { RiotAccount, UserDocument } from '../global/database/schema';
|
||||
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
||||
import { RiotAccountService } from '../riot/riot-account.service';
|
||||
import { DakaoUserError, DakaoUserService } from './dakao-user.service';
|
||||
import { DakaoUserService } from './dakao-user.service';
|
||||
|
||||
const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
|
||||
|
||||
@@ -14,15 +14,26 @@ function makeQuery<T>(value: T) {
|
||||
}
|
||||
|
||||
function makeService(params: {
|
||||
user: Partial<UserDocument>;
|
||||
user: Partial<UserDocument> | null;
|
||||
community?: Record<string, unknown> | null;
|
||||
riotAccountService?: Partial<RiotAccountService>;
|
||||
enrichmentService?: Partial<RiotAccountEnrichmentService>;
|
||||
}) {
|
||||
const findOneAndUpdate = jest
|
||||
.fn()
|
||||
.mockReturnValue(makeQuery(params.user as UserDocument));
|
||||
const findOne = jest.fn().mockReturnValue(makeQuery(params.user));
|
||||
const findById = jest.fn().mockReturnValue({
|
||||
select: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue(makeQuery(params.community ?? {})),
|
||||
}),
|
||||
});
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockResolvedValue({ findOneAndUpdate }),
|
||||
getModel: jest.fn().mockImplementation(async (name: string) => {
|
||||
if (name === 'user') return { findOneAndUpdate, findOne };
|
||||
if (name === 'community') return { findById };
|
||||
throw new Error(`Unexpected model: ${name}`);
|
||||
}),
|
||||
} as unknown as ConnectionService;
|
||||
const riotAccountService = {
|
||||
getByRiotId: jest.fn(),
|
||||
@@ -41,13 +52,15 @@ function makeService(params: {
|
||||
),
|
||||
connectionService,
|
||||
findOneAndUpdate,
|
||||
findOne,
|
||||
findById,
|
||||
riotAccountService,
|
||||
enrichmentService,
|
||||
};
|
||||
}
|
||||
|
||||
describe('DakaoUserService', () => {
|
||||
it('rejects account registration when the user already has a Riot account', async () => {
|
||||
it('registers an additional Riot account when the user already has one', async () => {
|
||||
const save = jest.fn().mockResolvedValue(undefined);
|
||||
const existingAccount = {
|
||||
puuid: 'puuid-1',
|
||||
@@ -66,25 +79,169 @@ describe('DakaoUserService', () => {
|
||||
riotAccounts: [existingAccount],
|
||||
save,
|
||||
} as Partial<UserDocument>,
|
||||
riotAccountService: {
|
||||
getByRiotId: jest.fn().mockResolvedValue({
|
||||
puuid: 'puuid-2',
|
||||
gameName: '새소환사',
|
||||
tagLine: 'KR2',
|
||||
}),
|
||||
},
|
||||
enrichmentService: {
|
||||
enrichRiotAccount: jest.fn().mockResolvedValue({ account: null }),
|
||||
},
|
||||
});
|
||||
|
||||
const result = await service.registerRiotAccount({
|
||||
communityId: objectId('111111111111111111111111'),
|
||||
kakaoTalkId: 'kakao-user-1',
|
||||
kakaoTalkNickname: '프리리',
|
||||
gameName: '새소환사',
|
||||
tagLine: 'KR2',
|
||||
});
|
||||
|
||||
expect(result.riotAccount).toMatchObject({
|
||||
puuid: 'puuid-2',
|
||||
gameName: '새소환사',
|
||||
tagLine: 'KR2',
|
||||
isPrimary: false,
|
||||
});
|
||||
expect((result.user.riotAccounts as RiotAccount[])[0]).toMatchObject({
|
||||
puuid: 'puuid-1',
|
||||
isPrimary: true,
|
||||
});
|
||||
expect(result.user.riotAccounts).toHaveLength(2);
|
||||
expect(connectionService.getModel).toHaveBeenCalledWith('user');
|
||||
expect(connectionService.getModel).toHaveBeenCalledWith('community');
|
||||
expect(riotAccountService.getByRiotId).toHaveBeenCalledWith(
|
||||
'새소환사',
|
||||
'KR2',
|
||||
{
|
||||
region: 'asia',
|
||||
},
|
||||
);
|
||||
expect(enrichmentService.enrichRiotAccount).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
userId: expect.any(mongoose.Types.ObjectId),
|
||||
puuid: 'puuid-2',
|
||||
options: { force: true, platform: 'kr', region: 'asia' },
|
||||
}),
|
||||
);
|
||||
expect(save).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reuses an already attached Riot account by puuid', async () => {
|
||||
const save = jest.fn().mockResolvedValue(undefined);
|
||||
const existingAccount = {
|
||||
puuid: 'puuid-1',
|
||||
gameName: '기존소환사',
|
||||
tagLine: 'KR1',
|
||||
isPrimary: true,
|
||||
} as RiotAccount;
|
||||
const { service, enrichmentService } = makeService({
|
||||
user: {
|
||||
_id: objectId('222222222222222222222222'),
|
||||
riotAccounts: [existingAccount],
|
||||
save,
|
||||
} as Partial<UserDocument>,
|
||||
riotAccountService: {
|
||||
getByRiotId: jest.fn().mockResolvedValue({
|
||||
puuid: 'puuid-1',
|
||||
gameName: '바뀐소환사',
|
||||
tagLine: 'KR1',
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const result = await service.registerRiotAccount({
|
||||
communityId: objectId('111111111111111111111111'),
|
||||
kakaoTalkId: 'kakao-user-1',
|
||||
kakaoTalkNickname: '프리리',
|
||||
gameName: '바뀐소환사',
|
||||
tagLine: 'KR1',
|
||||
});
|
||||
|
||||
expect(result.user.riotAccounts).toHaveLength(1);
|
||||
expect(result.riotAccount).toMatchObject({
|
||||
puuid: 'puuid-1',
|
||||
gameName: '바뀐소환사',
|
||||
tagLine: 'KR1',
|
||||
isPrimary: true,
|
||||
});
|
||||
expect(enrichmentService.enrichRiotAccount).not.toHaveBeenCalled();
|
||||
expect(save).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('changes the primary Riot account for the Dakao user', async () => {
|
||||
const save = jest.fn().mockResolvedValue(undefined);
|
||||
const oldPrimary = {
|
||||
puuid: 'puuid-1',
|
||||
gameName: '기존소환사',
|
||||
tagLine: 'KR1',
|
||||
isPrimary: true,
|
||||
} as RiotAccount;
|
||||
const nextPrimary = {
|
||||
puuid: 'puuid-2',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
isPrimary: false,
|
||||
} as RiotAccount;
|
||||
const { service, findOne } = makeService({
|
||||
user: {
|
||||
_id: objectId('222222222222222222222222'),
|
||||
kakaoTalkNickname: '이전닉',
|
||||
riotAccounts: [oldPrimary, nextPrimary],
|
||||
save,
|
||||
} as Partial<UserDocument>,
|
||||
});
|
||||
|
||||
const result = await service.changePrimaryRiotAccount({
|
||||
communityId: objectId('111111111111111111111111'),
|
||||
kakaoTalkId: 'kakao-user-1',
|
||||
kakaoTalkNickname: '프리리',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
});
|
||||
|
||||
expect(findOne).toHaveBeenCalledWith({
|
||||
communityId: objectId('111111111111111111111111'),
|
||||
kakaoTalkId: 'kakao-user-1',
|
||||
});
|
||||
expect(oldPrimary.isPrimary).toBe(false);
|
||||
expect(nextPrimary.isPrimary).toBe(true);
|
||||
expect(result.riotAccount).toBe(nextPrimary);
|
||||
expect(result.user.kakaoTalkNickname).toBe('프리리');
|
||||
expect(save).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects primary account changes for unregistered Riot accounts', async () => {
|
||||
const save = jest.fn().mockResolvedValue(undefined);
|
||||
const { service } = makeService({
|
||||
user: {
|
||||
_id: objectId('222222222222222222222222'),
|
||||
riotAccounts: [
|
||||
{
|
||||
puuid: 'puuid-1',
|
||||
gameName: '기존소환사',
|
||||
tagLine: 'KR1',
|
||||
isPrimary: true,
|
||||
},
|
||||
],
|
||||
save,
|
||||
} as Partial<UserDocument>,
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.registerPrimaryRiotAccount({
|
||||
service.changePrimaryRiotAccount({
|
||||
communityId: objectId('111111111111111111111111'),
|
||||
kakaoTalkId: 'kakao-user-1',
|
||||
kakaoTalkNickname: '프리리',
|
||||
gameName: '새소환사',
|
||||
tagLine: 'KR2',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
}),
|
||||
).rejects.toMatchObject({
|
||||
code: 'riot_account_already_registered',
|
||||
detail: '기존소환사#KR1',
|
||||
} satisfies Partial<DakaoUserError>);
|
||||
|
||||
expect(connectionService.getModel).toHaveBeenCalledTimes(1);
|
||||
expect(connectionService.getModel).toHaveBeenCalledWith('user');
|
||||
expect(riotAccountService.getByRiotId).not.toHaveBeenCalled();
|
||||
expect(enrichmentService.enrichRiotAccount).not.toHaveBeenCalled();
|
||||
code: 'riot_account_not_found',
|
||||
detail: '프리리#KR1',
|
||||
});
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,12 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import mongoose, { isValidObjectId } from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import { RiotAccount, UserDocument } from '../global/database/schema';
|
||||
import {
|
||||
Position,
|
||||
PositionPreference,
|
||||
RiotAccount,
|
||||
UserDocument,
|
||||
} from '../global/database/schema';
|
||||
import { RiotApiError } from '../riot/riot.client.service';
|
||||
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
||||
import { RiotAccountService } from '../riot/riot-account.service';
|
||||
@@ -111,6 +116,17 @@ export class DakaoUserService {
|
||||
return user;
|
||||
}
|
||||
|
||||
public async findUserByKakaoTalkId(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
kakaoTalkId: string;
|
||||
}): Promise<UserDocument | null> {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
return UserModel.findOne({
|
||||
communityId: params.communityId,
|
||||
kakaoTalkId: params.kakaoTalkId,
|
||||
}).exec();
|
||||
}
|
||||
|
||||
public async resolveRiotAccount(
|
||||
context: ResolveContext,
|
||||
): Promise<ResolveResult> {
|
||||
@@ -118,6 +134,8 @@ export class DakaoUserService {
|
||||
const routing = await this.resolveRiotRouting(context.communityId);
|
||||
const { requestedGameName, requestedTagLine, dto } =
|
||||
await this.lookupRiotIdentity(context, routing);
|
||||
const nextGameName = dto.gameName ?? requestedGameName;
|
||||
const nextTagLine = dto.tagLine ?? requestedTagLine;
|
||||
|
||||
const existing = user.riotAccounts.find(
|
||||
(a) =>
|
||||
@@ -131,8 +149,6 @@ export class DakaoUserService {
|
||||
}
|
||||
|
||||
if (existing) {
|
||||
const nextGameName = dto.gameName ?? requestedGameName;
|
||||
const nextTagLine = dto.tagLine ?? requestedTagLine;
|
||||
if (existing.puuid !== dto.puuid) {
|
||||
this.logger.warn(
|
||||
`Riot account puuid mismatch for ${requestedGameName}#${requestedTagLine}: stored=${existing.puuid} resolved=${dto.puuid}. Updating stored account.`,
|
||||
@@ -161,37 +177,21 @@ export class DakaoUserService {
|
||||
return { user, riotAccount: existing };
|
||||
}
|
||||
|
||||
return this.attachRiotAccount({
|
||||
user,
|
||||
puuid: dto.puuid,
|
||||
gameName: dto.gameName ?? requestedGameName,
|
||||
tagLine: dto.tagLine ?? requestedTagLine,
|
||||
platform: routing.platform,
|
||||
region: routing.region,
|
||||
});
|
||||
}
|
||||
|
||||
public async registerPrimaryRiotAccount(
|
||||
context: ResolveContext,
|
||||
): Promise<ResolveResult> {
|
||||
const user = await this.upsertUser(context);
|
||||
const existingPrimary = user.riotAccounts.find(
|
||||
(account) => account.isPrimary,
|
||||
const existingByPuuid = user.riotAccounts.find(
|
||||
(account) => account.puuid === dto.puuid,
|
||||
);
|
||||
const existingAccount = existingPrimary ?? user.riotAccounts[0];
|
||||
if (existingAccount) {
|
||||
throw new DakaoUserError(
|
||||
'riot_account_already_registered',
|
||||
`${existingAccount.gameName}#${existingAccount.tagLine}`,
|
||||
);
|
||||
if (existingByPuuid) {
|
||||
if (
|
||||
existingByPuuid.gameName !== nextGameName ||
|
||||
existingByPuuid.tagLine !== nextTagLine
|
||||
) {
|
||||
existingByPuuid.gameName = nextGameName;
|
||||
existingByPuuid.tagLine = nextTagLine;
|
||||
await user.save();
|
||||
}
|
||||
return { user, riotAccount: existingByPuuid };
|
||||
}
|
||||
|
||||
const routing = await this.resolveRiotRouting(context.communityId);
|
||||
const { requestedGameName, requestedTagLine, dto } =
|
||||
await this.lookupRiotIdentity(context, routing);
|
||||
const nextGameName = dto.gameName ?? requestedGameName;
|
||||
const nextTagLine = dto.tagLine ?? requestedTagLine;
|
||||
|
||||
return this.attachRiotAccount({
|
||||
user,
|
||||
puuid: dto.puuid,
|
||||
@@ -202,6 +202,78 @@ export class DakaoUserService {
|
||||
});
|
||||
}
|
||||
|
||||
public async registerRiotAccount(
|
||||
context: ResolveContext,
|
||||
): Promise<ResolveResult> {
|
||||
return this.resolveRiotAccount(context);
|
||||
}
|
||||
|
||||
public async registerPrimaryRiotAccount(
|
||||
context: ResolveContext,
|
||||
): Promise<ResolveResult> {
|
||||
return this.registerRiotAccount(context);
|
||||
}
|
||||
|
||||
public async registerPreferredPositions(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
kakaoTalkId: string;
|
||||
kakaoTalkNickname: string;
|
||||
positions: Position[];
|
||||
}): Promise<UserDocument> {
|
||||
const user = await this.upsertUser({
|
||||
communityId: params.communityId,
|
||||
kakaoTalkId: params.kakaoTalkId,
|
||||
kakaoTalkNickname: params.kakaoTalkNickname,
|
||||
});
|
||||
user.preferredPositions = this.toPositionPreferences(params.positions);
|
||||
await user.save();
|
||||
return user;
|
||||
}
|
||||
|
||||
public async changePrimaryRiotAccount(
|
||||
context: ResolveContext,
|
||||
): Promise<ResolveResult> {
|
||||
const requestedGameName = normalizeRiotIdPart(context.gameName);
|
||||
const requestedTagLine = normalizeRiotIdPart(context.tagLine);
|
||||
const detail = `${requestedGameName}#${requestedTagLine}`;
|
||||
|
||||
const user = await this.findUserByKakaoTalkId({
|
||||
communityId: context.communityId,
|
||||
kakaoTalkId: context.kakaoTalkId,
|
||||
});
|
||||
if (!user) {
|
||||
throw new DakaoUserError('riot_account_not_found', detail);
|
||||
}
|
||||
|
||||
const target = user.riotAccounts.find(
|
||||
(account) =>
|
||||
normalizeRiotIdPart(account.gameName).toLowerCase() ===
|
||||
requestedGameName.toLowerCase() &&
|
||||
normalizeRiotIdPart(account.tagLine).toLowerCase() ===
|
||||
requestedTagLine.toLowerCase(),
|
||||
);
|
||||
if (!target) {
|
||||
throw new DakaoUserError('riot_account_not_found', detail);
|
||||
}
|
||||
|
||||
if (context.kakaoTalkNickname.trim()) {
|
||||
user.kakaoTalkNickname = context.kakaoTalkNickname;
|
||||
}
|
||||
for (const account of user.riotAccounts) {
|
||||
account.isPrimary = account.puuid === target.puuid;
|
||||
}
|
||||
await user.save();
|
||||
|
||||
return { user, riotAccount: target };
|
||||
}
|
||||
|
||||
private toPositionPreferences(positions: Position[]): PositionPreference[] {
|
||||
return positions.map((position, index) => ({
|
||||
position,
|
||||
priority: index + 1,
|
||||
}));
|
||||
}
|
||||
|
||||
private async lookupRiotIdentity(
|
||||
context: ResolveContext,
|
||||
routing: RiotRouting,
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MatchModule } from '../match/match.module';
|
||||
import { RiotModule } from '../riot/riot.module';
|
||||
import {
|
||||
DAKAO_OPTIONS,
|
||||
createDefaultDakaoOptions,
|
||||
} from './dakao.options';
|
||||
import { DAKAO_OPTIONS, createDefaultDakaoOptions } from './dakao.options';
|
||||
import { DakaoPublisher } from './dakao.publisher';
|
||||
import { DakaoSubscriber } from './dakao.subscriber';
|
||||
import { DakaoInboxService } from './dakao-inbox.service';
|
||||
import { DakaoJetStreamResourceService } from './dakao-jetstream-resource.service';
|
||||
import { DakaoOutboxSweeperService } from './dakao-outbox-sweeper.service';
|
||||
import { DakaoOutboxService } from './dakao-outbox.service';
|
||||
import { DakaoUserService } from './dakao-user.service';
|
||||
import { IdempotencyCache } from './idempotency.cache';
|
||||
import { DakaoSendResultSubscriber } from './dakao-send-result.subscriber';
|
||||
import { AccountRegisterHandler } from './handlers/account-register.handler';
|
||||
import { MatchCancelHandler } from './handlers/match-cancel.handler';
|
||||
import { MatchJoinHandler } from './handlers/match-join.handler';
|
||||
import { MatchListHandler } from './handlers/match-list.handler';
|
||||
import { PreferredPositionRegisterHandler } from './handlers/preferred-position-register.handler';
|
||||
import { PrimaryAccountChangeHandler } from './handlers/primary-account-change.handler';
|
||||
|
||||
@Module({
|
||||
imports: [RiotModule, MatchModule],
|
||||
@@ -20,13 +24,20 @@ import { MatchListHandler } from './handlers/match-list.handler';
|
||||
provide: DAKAO_OPTIONS,
|
||||
useFactory: createDefaultDakaoOptions,
|
||||
},
|
||||
DakaoOutboxService,
|
||||
DakaoOutboxSweeperService,
|
||||
DakaoInboxService,
|
||||
DakaoJetStreamResourceService,
|
||||
DakaoPublisher,
|
||||
DakaoSubscriber,
|
||||
DakaoSendResultSubscriber,
|
||||
DakaoUserService,
|
||||
IdempotencyCache,
|
||||
AccountRegisterHandler,
|
||||
MatchListHandler,
|
||||
MatchJoinHandler,
|
||||
MatchCancelHandler,
|
||||
PreferredPositionRegisterHandler,
|
||||
PrimaryAccountChangeHandler,
|
||||
],
|
||||
exports: [DakaoPublisher],
|
||||
})
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { resolveDakaoNatsNames } from './dakao.nats-names';
|
||||
|
||||
describe('resolveDakaoNatsNames', () => {
|
||||
it('resolves staging subjects and JetStream resources from NODE_ENV=staging', () => {
|
||||
expect(resolveDakaoNatsNames('staging')).toEqual({
|
||||
env: 'staging',
|
||||
shortEnv: 'STG',
|
||||
subjects: {
|
||||
botCommandSubmitted: 'staging.lolympus.dakao.bot-command.submitted.v1',
|
||||
chatSendMessage: 'staging.dakao.chat.send-message.v1',
|
||||
chatSendMessageSucceeded:
|
||||
'staging.lolympus.dakao.chat.send-message.succeeded.v1',
|
||||
chatSendMessageFailed:
|
||||
'staging.lolympus.dakao.chat.send-message.failed.v1',
|
||||
},
|
||||
streams: {
|
||||
botCommand: 'STG_DAKAO_TO_LOLYMPUS_BOTCMD',
|
||||
sendRequest: 'STG_DAKAO_SENDREQ',
|
||||
sendResult: 'STG_DAKAO_TO_LOLYMPUS_SENDRES',
|
||||
},
|
||||
consumers: {
|
||||
botCommand: 'STG_LOLYMPUS_BOTCMD',
|
||||
sendRequest: 'STG_DAKAO_SENDREQ_WORKER',
|
||||
sendResult: 'STG_LOLYMPUS_SENDRES',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps JetStream resource names within the 32 character safety target', () => {
|
||||
const names = resolveDakaoNatsNames('prod');
|
||||
const resources = [
|
||||
...Object.values(names.streams),
|
||||
...Object.values(names.consumers),
|
||||
];
|
||||
|
||||
expect(resources.every((name) => name.length <= 32)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
export type DakaoRuntimeEnv = 'dev' | 'staging' | 'prod';
|
||||
export type DakaoShortEnv = 'DEV' | 'STG' | 'PROD';
|
||||
|
||||
export interface DakaoNatsNames {
|
||||
env: DakaoRuntimeEnv;
|
||||
shortEnv: DakaoShortEnv;
|
||||
subjects: {
|
||||
botCommandSubmitted: string;
|
||||
chatSendMessage: string;
|
||||
chatSendMessageSucceeded: string;
|
||||
chatSendMessageFailed: string;
|
||||
};
|
||||
streams: {
|
||||
botCommand: string;
|
||||
sendRequest: string;
|
||||
sendResult: string;
|
||||
};
|
||||
consumers: {
|
||||
botCommand: string;
|
||||
sendRequest: string;
|
||||
sendResult: string;
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveDakaoNatsNames(
|
||||
nodeEnv = process.env.NODE_ENV,
|
||||
): DakaoNatsNames {
|
||||
const env = resolveRuntimeEnv(nodeEnv);
|
||||
const shortEnv = toShortEnv(env);
|
||||
|
||||
return {
|
||||
env,
|
||||
shortEnv,
|
||||
subjects: {
|
||||
botCommandSubmitted: `${env}.lolympus.dakao.bot-command.submitted.v1`,
|
||||
chatSendMessage: `${env}.dakao.chat.send-message.v1`,
|
||||
chatSendMessageSucceeded: `${env}.lolympus.dakao.chat.send-message.succeeded.v1`,
|
||||
chatSendMessageFailed: `${env}.lolympus.dakao.chat.send-message.failed.v1`,
|
||||
},
|
||||
streams: {
|
||||
botCommand: `${shortEnv}_DAKAO_TO_LOLYMPUS_BOTCMD`,
|
||||
sendRequest: `${shortEnv}_DAKAO_SENDREQ`,
|
||||
sendResult: `${shortEnv}_DAKAO_TO_LOLYMPUS_SENDRES`,
|
||||
},
|
||||
consumers: {
|
||||
botCommand: `${shortEnv}_LOLYMPUS_BOTCMD`,
|
||||
sendRequest: `${shortEnv}_DAKAO_SENDREQ_WORKER`,
|
||||
sendResult: `${shortEnv}_LOLYMPUS_SENDRES`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function resolveRuntimeEnv(nodeEnv?: string): DakaoRuntimeEnv {
|
||||
if (nodeEnv === 'prod' || nodeEnv === 'production') return 'prod';
|
||||
if (nodeEnv === 'staging') return 'staging';
|
||||
return 'dev';
|
||||
}
|
||||
|
||||
function toShortEnv(env: DakaoRuntimeEnv): DakaoShortEnv {
|
||||
switch (env) {
|
||||
case 'prod':
|
||||
return 'PROD';
|
||||
case 'staging':
|
||||
return 'STG';
|
||||
case 'dev':
|
||||
return 'DEV';
|
||||
}
|
||||
}
|
||||
@@ -1,32 +1,38 @@
|
||||
import { SecretService } from '../global/secret/secret.service';
|
||||
import { NatsService } from '../global/nats/nats.service';
|
||||
import { DakaoCommandEnvelope, DakaoSendMessagePayload } from './dakao.types';
|
||||
import { DakaoPublisher } from './dakao.publisher';
|
||||
import { DakaoOutboxService } from './dakao-outbox.service';
|
||||
|
||||
function makePublisher() {
|
||||
const natsService = {
|
||||
publish: jest.fn().mockResolvedValue(undefined),
|
||||
subscribe: jest.fn(),
|
||||
} as unknown as NatsService;
|
||||
const outboxService = {
|
||||
enqueueAndPublish: jest.fn().mockResolvedValue(undefined),
|
||||
} as unknown as DakaoOutboxService;
|
||||
const secretService = {} as SecretService;
|
||||
const publisher = new DakaoPublisher(natsService, secretService, {
|
||||
instanceId: 'test',
|
||||
});
|
||||
const previousNodeEnv = process.env.NODE_ENV;
|
||||
process.env.NODE_ENV = 'staging';
|
||||
|
||||
return { publisher, natsService };
|
||||
try {
|
||||
const publisher = new DakaoPublisher(secretService, outboxService, {
|
||||
instanceId: 'staging-instance',
|
||||
});
|
||||
|
||||
return { publisher, outboxService };
|
||||
} finally {
|
||||
process.env.NODE_ENV = previousNodeEnv;
|
||||
}
|
||||
}
|
||||
|
||||
function getPublishedPayload(natsService: NatsService): DakaoSendMessagePayload {
|
||||
const publish = natsService.publish as jest.Mock;
|
||||
const envelope = publish.mock.calls[0][1] as DakaoCommandEnvelope<
|
||||
DakaoSendMessagePayload
|
||||
>;
|
||||
return envelope.payload;
|
||||
function getPublishedEnvelope(
|
||||
outboxService: DakaoOutboxService,
|
||||
): DakaoCommandEnvelope<DakaoSendMessagePayload> {
|
||||
const enqueue = outboxService.enqueueAndPublish as jest.Mock;
|
||||
return enqueue.mock.calls[0][0]
|
||||
.envelope as DakaoCommandEnvelope<DakaoSendMessagePayload>;
|
||||
}
|
||||
|
||||
describe('DakaoPublisher', () => {
|
||||
it('keeps valid mention segments intact', async () => {
|
||||
const { publisher, natsService } = makePublisher();
|
||||
const { publisher, outboxService } = makePublisher();
|
||||
|
||||
await publisher.sendMessage({
|
||||
chatroomId: '18474390111480678',
|
||||
@@ -40,7 +46,7 @@ describe('DakaoPublisher', () => {
|
||||
],
|
||||
});
|
||||
|
||||
expect(getPublishedPayload(natsService).segments).toEqual([
|
||||
expect(getPublishedEnvelope(outboxService).payload.segments).toEqual([
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: '6215844374579825921',
|
||||
@@ -51,7 +57,7 @@ describe('DakaoPublisher', () => {
|
||||
});
|
||||
|
||||
it('downgrades invalid mention segments to text before publishing', async () => {
|
||||
const { publisher, natsService } = makePublisher();
|
||||
const { publisher, outboxService } = makePublisher();
|
||||
|
||||
await publisher.sendMessage({
|
||||
chatroomId: '18474390111480678',
|
||||
@@ -65,9 +71,39 @@ describe('DakaoPublisher', () => {
|
||||
],
|
||||
});
|
||||
|
||||
expect(getPublishedPayload(natsService).segments).toEqual([
|
||||
expect(getPublishedEnvelope(outboxService).payload.segments).toEqual([
|
||||
{ kind: 'text', text: '@소쿠리' },
|
||||
{ kind: 'text', text: ' 신청 완료' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('uses deterministic event ids and the shared Dakao send subject', async () => {
|
||||
const { publisher, outboxService } = makePublisher();
|
||||
|
||||
await publisher.sendMessage({
|
||||
chatroomId: '18474390111480678',
|
||||
segments: [{ kind: 'text', text: '신청 완료' }],
|
||||
correlationId: 'chat-log-1',
|
||||
});
|
||||
|
||||
const enqueue = outboxService.enqueueAndPublish as jest.Mock;
|
||||
expect(enqueue.mock.calls[0][0]).toMatchObject({
|
||||
subject: 'staging.dakao.chat.send-message.v1',
|
||||
eventId: 'lolympus:chat.send-message:chat-log-1',
|
||||
});
|
||||
expect(getPublishedEnvelope(outboxService)).toMatchObject({
|
||||
schema: 'dakao.command.v1',
|
||||
eventId: 'lolympus:chat.send-message:chat-log-1',
|
||||
eventSource: 'lolympus',
|
||||
type: 'chat.send-message',
|
||||
correlationId: 'chat-log-1',
|
||||
resultSubjects: {
|
||||
succeeded: 'staging.lolympus.dakao.chat.send-message.succeeded.v1',
|
||||
failed: 'staging.lolympus.dakao.chat.send-message.failed.v1',
|
||||
},
|
||||
});
|
||||
expect(getPublishedEnvelope(outboxService)).not.toHaveProperty(
|
||||
'replySubject',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,86 +1,86 @@
|
||||
import {
|
||||
Inject,
|
||||
Injectable,
|
||||
Logger,
|
||||
OnModuleDestroy,
|
||||
OnModuleInit,
|
||||
} from '@nestjs/common';
|
||||
import { Inject, Injectable, Logger, OnModuleInit } from '@nestjs/common';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { SecretService } from '../global/secret/secret.service';
|
||||
import { NatsService } from '../global/nats/nats.service';
|
||||
import {
|
||||
DakaoCommandEnvelope,
|
||||
DakaoResultEnvelope,
|
||||
DakaoResultSubjects,
|
||||
DakaoSegment,
|
||||
DakaoSendMessagePayload,
|
||||
} from './dakao.types';
|
||||
import type { DakaoOptions } from './dakao.options';
|
||||
import { DAKAO_OPTIONS } from './dakao.options';
|
||||
import { resolveDakaoNatsNames } from './dakao.nats-names';
|
||||
import { DakaoOutboxService } from './dakao-outbox.service';
|
||||
|
||||
const SEND_MESSAGE_SUBJECT_DEFAULT = 'dakao.command.chat.send-message.v1';
|
||||
const COMMAND_SOURCE_DEFAULT = 'lolympus-tournament-support';
|
||||
const EVENT_SOURCE_DEFAULT = 'lolympus';
|
||||
|
||||
@Injectable()
|
||||
export class DakaoPublisher implements OnModuleInit, OnModuleDestroy {
|
||||
export class DakaoPublisher implements OnModuleInit {
|
||||
private readonly logger = new Logger(DakaoPublisher.name);
|
||||
private replySubject = '';
|
||||
private sendMessageSubject = SEND_MESSAGE_SUBJECT_DEFAULT;
|
||||
private source = COMMAND_SOURCE_DEFAULT;
|
||||
private readonly names = resolveDakaoNatsNames();
|
||||
private sendMessageSubject = this.names.subjects.chatSendMessage;
|
||||
private resultSubjects: DakaoResultSubjects = {
|
||||
succeeded: this.names.subjects.chatSendMessageSucceeded,
|
||||
failed: this.names.subjects.chatSendMessageFailed,
|
||||
};
|
||||
private eventSource = EVENT_SOURCE_DEFAULT;
|
||||
|
||||
constructor(
|
||||
private readonly natsService: NatsService,
|
||||
private readonly secretService: SecretService,
|
||||
private readonly outboxService: DakaoOutboxService,
|
||||
@Inject(DAKAO_OPTIONS) private readonly options: DakaoOptions,
|
||||
) {}
|
||||
|
||||
async onModuleInit() {
|
||||
const replyOverride = await this.secretService
|
||||
.get<string>('DAKAO_REPLY_SUBJECT_PREFIX')
|
||||
.catch(() => undefined);
|
||||
const sendOverride = await this.secretService
|
||||
.get<string>('DAKAO_NATS_COMMAND_CHAT_SEND_MESSAGE_SUBJECT')
|
||||
.get<string>('DAKAO_CHAT_SEND_MESSAGE_SUBJECT')
|
||||
.catch(() => undefined);
|
||||
const sourceOverride = await this.secretService
|
||||
.get<string>('DAKAO_COMMAND_SOURCE')
|
||||
.get<string>('DAKAO_EVENT_SOURCE')
|
||||
.catch(() => undefined);
|
||||
|
||||
const replyPrefix = replyOverride || `dakao.result.${COMMAND_SOURCE_DEFAULT}`;
|
||||
this.replySubject = `${replyPrefix}.${this.options.instanceId}`;
|
||||
this.sendMessageSubject = sendOverride || SEND_MESSAGE_SUBJECT_DEFAULT;
|
||||
this.source = sourceOverride || COMMAND_SOURCE_DEFAULT;
|
||||
this.sendMessageSubject =
|
||||
sendOverride || resolveDakaoNatsNames().subjects.chatSendMessage;
|
||||
this.resultSubjects = {
|
||||
succeeded: this.names.subjects.chatSendMessageSucceeded,
|
||||
failed: this.names.subjects.chatSendMessageFailed,
|
||||
};
|
||||
this.eventSource = sourceOverride || EVENT_SOURCE_DEFAULT;
|
||||
|
||||
this.natsService.subscribe<DakaoResultEnvelope>(
|
||||
this.replySubject,
|
||||
(data) => this.handleReply(data),
|
||||
);
|
||||
this.logger.log(
|
||||
`Dakao reply subscriber ready on subject="${this.replySubject}"`,
|
||||
`Dakao send-message publisher ready on subject="${this.sendMessageSubject}" source="${this.eventSource}" instanceId="${this.options.instanceId}"`,
|
||||
);
|
||||
}
|
||||
|
||||
async onModuleDestroy() {
|
||||
// NatsService 가 subscription 정리한다.
|
||||
}
|
||||
|
||||
public async sendMessage(params: {
|
||||
chatroomId: string;
|
||||
segments: DakaoSegment[];
|
||||
correlationId?: string;
|
||||
eventId?: string;
|
||||
}): Promise<void> {
|
||||
const eventId =
|
||||
params.eventId ??
|
||||
(params.correlationId
|
||||
? `${this.eventSource}:chat.send-message:${params.correlationId}`
|
||||
: `${this.eventSource}:chat.send-message:${randomUUID()}`);
|
||||
const payload: DakaoSendMessagePayload = {
|
||||
chatroomId: params.chatroomId,
|
||||
segments: this.normalizeSegments(params.segments),
|
||||
};
|
||||
const envelope: DakaoCommandEnvelope<DakaoSendMessagePayload> = {
|
||||
schema: 'dakao.command.v1',
|
||||
id: randomUUID(),
|
||||
eventId,
|
||||
type: 'chat.send-message',
|
||||
source: this.source,
|
||||
eventSource: this.eventSource,
|
||||
correlationId: params.correlationId,
|
||||
replySubject: this.replySubject,
|
||||
resultSubjects: this.resultSubjects,
|
||||
payload,
|
||||
};
|
||||
await this.natsService.publish(this.sendMessageSubject, envelope);
|
||||
await this.outboxService.enqueueAndPublish({
|
||||
subject: this.sendMessageSubject,
|
||||
eventId,
|
||||
envelope,
|
||||
});
|
||||
}
|
||||
|
||||
private normalizeSegments(segments: DakaoSegment[]): DakaoSegment[] {
|
||||
@@ -111,11 +111,7 @@ export class DakaoPublisher implements OnModuleInit, OnModuleDestroy {
|
||||
|
||||
const id = segment.id.trim();
|
||||
const altText = segment.altText.trim();
|
||||
if (
|
||||
id.length > 0 &&
|
||||
altText.length > 0 &&
|
||||
!/[()@]/.test(altText)
|
||||
) {
|
||||
if (id.length > 0 && altText.length > 0 && !/[()@]/.test(altText)) {
|
||||
normalized.push({ kind: 'emoticon', id, altText });
|
||||
continue;
|
||||
}
|
||||
@@ -139,16 +135,4 @@ export class DakaoPublisher implements OnModuleInit, OnModuleDestroy {
|
||||
const label = displayText || userId || '사용자';
|
||||
return label.startsWith('@') ? label : `@${label}`;
|
||||
}
|
||||
|
||||
private handleReply(reply: DakaoResultEnvelope): void {
|
||||
if (reply.status === 'succeeded') {
|
||||
this.logger.log(
|
||||
`Dakao reply succeeded id=${reply.id} type=${reply.type} correlationId=${reply.correlationId ?? '-'}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.logger.warn(
|
||||
`Dakao reply failed id=${reply.id} type=${reply.type} code=${reply.error?.code ?? '-'} retryable=${reply.error?.retryable ?? false} message=${reply.error?.message ?? '-'}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,17 +6,20 @@ import { CommandParseError, parseCommand } from './parsers/command.parser';
|
||||
import { DakaoInboundEvent, DakaoLong, DakaoSegment } from './dakao.types';
|
||||
import { DakaoPublisher } from './dakao.publisher';
|
||||
import { DakaoUserError, DakaoUserService } from './dakao-user.service';
|
||||
import { IdempotencyCache } from './idempotency.cache';
|
||||
import { AccountRegisterHandler } from './handlers/account-register.handler';
|
||||
import { MatchCancelHandler } from './handlers/match-cancel.handler';
|
||||
import { MatchJoinHandler } from './handlers/match-join.handler';
|
||||
import { MatchListHandler } from './handlers/match-list.handler';
|
||||
|
||||
const INBOUND_SUBJECT_DEFAULT = 'lolympus-tournament-support.kakaotalk.command';
|
||||
import { PreferredPositionRegisterHandler } from './handlers/preferred-position-register.handler';
|
||||
import { PrimaryAccountChangeHandler } from './handlers/primary-account-change.handler';
|
||||
import { resolveDakaoNatsNames } from './dakao.nats-names';
|
||||
import { DakaoInboxService } from './dakao-inbox.service';
|
||||
import { DakaoJetStreamResourceService } from './dakao-jetstream-resource.service';
|
||||
|
||||
@Injectable()
|
||||
export class DakaoSubscriber implements OnModuleInit {
|
||||
private readonly logger = new Logger(DakaoSubscriber.name);
|
||||
private inboundSubject = INBOUND_SUBJECT_DEFAULT;
|
||||
private readonly natsNames = resolveDakaoNatsNames();
|
||||
private botUserId: string | undefined;
|
||||
|
||||
constructor(
|
||||
@@ -24,28 +27,31 @@ export class DakaoSubscriber implements OnModuleInit {
|
||||
private readonly secretService: SecretService,
|
||||
private readonly dakaoUserService: DakaoUserService,
|
||||
private readonly publisher: DakaoPublisher,
|
||||
private readonly idempotency: IdempotencyCache,
|
||||
private readonly inbox: DakaoInboxService,
|
||||
private readonly resources: DakaoJetStreamResourceService,
|
||||
private readonly accountRegisterHandler: AccountRegisterHandler,
|
||||
private readonly matchListHandler: MatchListHandler,
|
||||
private readonly matchJoinHandler: MatchJoinHandler,
|
||||
private readonly matchCancelHandler: MatchCancelHandler,
|
||||
private readonly preferredPositionRegisterHandler: PreferredPositionRegisterHandler,
|
||||
private readonly primaryAccountChangeHandler: PrimaryAccountChangeHandler,
|
||||
) {}
|
||||
|
||||
async onModuleInit() {
|
||||
const subjectOverride = await this.secretService
|
||||
.get<string>('DAKAO_INBOUND_SUBJECT')
|
||||
.catch(() => undefined);
|
||||
this.inboundSubject = subjectOverride || INBOUND_SUBJECT_DEFAULT;
|
||||
|
||||
this.botUserId = await this.secretService
|
||||
.get<string>('DAKAO_BOT_USER_ID')
|
||||
.catch(() => undefined);
|
||||
|
||||
this.natsService.subscribe<DakaoInboundEvent>(
|
||||
this.inboundSubject,
|
||||
await this.resources.ensure();
|
||||
void this.natsService.consumeJetStream<DakaoInboundEvent>(
|
||||
{
|
||||
stream: this.natsNames.streams.botCommand,
|
||||
durable: this.natsNames.consumers.botCommand,
|
||||
},
|
||||
(event) => this.handleEvent(event),
|
||||
);
|
||||
this.logger.log(
|
||||
`Dakao inbound subscriber ready on subject="${this.inboundSubject}"`,
|
||||
`Dakao inbound subscriber ready on stream="${this.natsNames.streams.botCommand}" durable="${this.natsNames.consumers.botCommand}"`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -56,35 +62,52 @@ export class DakaoSubscriber implements OnModuleInit {
|
||||
return;
|
||||
}
|
||||
|
||||
const logIdKey = this.deriveLogIdKey(event);
|
||||
if (logIdKey && this.idempotency.has(logIdKey)) {
|
||||
return;
|
||||
const chatLogLogId = this.serializeDakaoLong(event.origin.chatLog.logId);
|
||||
let claimed = false;
|
||||
if (chatLogLogId) {
|
||||
const claim = await this.inbox.claim({
|
||||
consumer: this.natsNames.consumers.botCommand,
|
||||
projectId: event.projectId,
|
||||
chatLogLogId,
|
||||
});
|
||||
if (claim.status === 'duplicate') return;
|
||||
if (claim.status === 'inflight') {
|
||||
throw new Error(
|
||||
`Dakao event is already being processed projectId=${event.projectId} logId=${chatLogLogId}`,
|
||||
);
|
||||
}
|
||||
claimed = true;
|
||||
}
|
||||
if (logIdKey) this.idempotency.remember(logIdKey);
|
||||
|
||||
let communityId: mongoose.Types.ObjectId;
|
||||
try {
|
||||
communityId = await this.dakaoUserService.resolveCommunityIdByDakaoProjectId(
|
||||
event.projectId,
|
||||
);
|
||||
communityId =
|
||||
await this.dakaoUserService.resolveCommunityIdByDakaoProjectId(
|
||||
event.projectId,
|
||||
);
|
||||
} catch (err) {
|
||||
if (err instanceof DakaoUserError) {
|
||||
if (err.code === 'invalid_project_id') {
|
||||
this.logger.warn(`Invalid dakao projectId format: ${event.projectId}`);
|
||||
this.logger.warn(
|
||||
`Invalid dakao projectId format: ${event.projectId}`,
|
||||
);
|
||||
if (claimed) await this.markProcessed(event, chatLogLogId);
|
||||
return;
|
||||
}
|
||||
if (err.code === 'community_not_found') {
|
||||
// 우리 쪽이 모르는 projectId. 메시지를 보내봤자 컨텍스트가 없으므로 로그만.
|
||||
this.logger.warn(`Unknown dakao projectId: ${event.projectId}`);
|
||||
if (claimed) await this.markProcessed(event, chatLogLogId);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (claimed) await this.markFailed(event, chatLogLogId, err);
|
||||
throw err;
|
||||
}
|
||||
|
||||
let segments: DakaoSegment[];
|
||||
const senderNickname = this.resolveSenderNickname(event);
|
||||
const correlationId = this.serializeDakaoLong(event.origin.chatLog.logId);
|
||||
const correlationId = chatLogLogId;
|
||||
try {
|
||||
const command = parseCommand(event.origin.chatLog.message);
|
||||
|
||||
@@ -105,17 +128,40 @@ export class DakaoSubscriber implements OnModuleInit {
|
||||
tagLine: command.tagLine,
|
||||
});
|
||||
break;
|
||||
case 'match-join':
|
||||
segments = await this.matchJoinHandler.handle({
|
||||
case 'primary-account-change':
|
||||
segments = await this.primaryAccountChangeHandler.handle({
|
||||
communityId,
|
||||
matchId: command.matchId,
|
||||
senderUserId: event.userId,
|
||||
senderNickname,
|
||||
gameName: command.gameName,
|
||||
tagLine: command.tagLine,
|
||||
});
|
||||
break;
|
||||
case 'match-join':
|
||||
segments = await this.matchJoinHandler.handle({
|
||||
communityId,
|
||||
matchAndRiotId: command.matchAndRiotId,
|
||||
senderUserId: event.userId,
|
||||
senderNickname,
|
||||
positions: command.positions?.positions,
|
||||
});
|
||||
break;
|
||||
case 'preferred-position-register':
|
||||
segments = await this.preferredPositionRegisterHandler.handle({
|
||||
communityId,
|
||||
senderUserId: event.userId,
|
||||
senderNickname,
|
||||
positions: command.positions.positions,
|
||||
});
|
||||
break;
|
||||
case 'match-cancel':
|
||||
segments = await this.matchCancelHandler.handle({
|
||||
communityId,
|
||||
matchId: command.matchId,
|
||||
senderUserId: event.userId,
|
||||
senderNickname,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
await this.publisher.sendMessage({
|
||||
@@ -123,27 +169,35 @@ export class DakaoSubscriber implements OnModuleInit {
|
||||
segments,
|
||||
correlationId,
|
||||
});
|
||||
if (claimed) await this.markProcessed(event, chatLogLogId);
|
||||
} catch (err) {
|
||||
if (err instanceof CommandParseError) {
|
||||
// not_a_command 는 명령이 아닌 일반 메시지 → 무시.
|
||||
if (err.code === 'not_a_command') return;
|
||||
if (err.code === 'not_a_command') {
|
||||
if (claimed) await this.markProcessed(event, chatLogLogId);
|
||||
return;
|
||||
}
|
||||
await this.publisher.sendMessage({
|
||||
chatroomId: event.chatroomId,
|
||||
segments: this.parseErrorReply(event, senderNickname, err),
|
||||
correlationId,
|
||||
});
|
||||
if (claimed) await this.markProcessed(event, chatLogLogId);
|
||||
return;
|
||||
}
|
||||
this.logger.error(
|
||||
`Unhandled dakao event error: ${(err as Error)?.stack ?? err}`,
|
||||
);
|
||||
if (claimed) await this.markFailed(event, chatLogLogId, err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private validate(event: unknown): event is DakaoInboundEvent {
|
||||
if (!event || typeof event !== 'object') return false;
|
||||
const e = event as Partial<DakaoInboundEvent>;
|
||||
if (typeof e.projectId !== 'string' || e.projectId.length === 0) return false;
|
||||
if (typeof e.projectId !== 'string' || e.projectId.length === 0)
|
||||
return false;
|
||||
if (typeof e.chatroomId !== 'string' || e.chatroomId.length === 0)
|
||||
return false;
|
||||
if (typeof e.nickname !== 'string') return false;
|
||||
@@ -156,11 +210,6 @@ export class DakaoSubscriber implements OnModuleInit {
|
||||
return true;
|
||||
}
|
||||
|
||||
private deriveLogIdKey(event: DakaoInboundEvent): string | null {
|
||||
const serialized = this.serializeDakaoLong(event.origin.chatLog.logId);
|
||||
return serialized ? `${event.projectId}:${serialized}` : null;
|
||||
}
|
||||
|
||||
private serializeDakaoLong(value: DakaoLong | string | undefined): string {
|
||||
if (typeof value === 'string') return value;
|
||||
if (!value || typeof value !== 'object') return '';
|
||||
@@ -179,6 +228,30 @@ export class DakaoSubscriber implements OnModuleInit {
|
||||
return fallback ?? '';
|
||||
}
|
||||
|
||||
private async markProcessed(
|
||||
event: DakaoInboundEvent,
|
||||
chatLogLogId: string,
|
||||
): Promise<void> {
|
||||
await this.inbox.markProcessed({
|
||||
consumer: this.natsNames.consumers.botCommand,
|
||||
projectId: event.projectId,
|
||||
chatLogLogId,
|
||||
});
|
||||
}
|
||||
|
||||
private async markFailed(
|
||||
event: DakaoInboundEvent,
|
||||
chatLogLogId: string,
|
||||
error: unknown,
|
||||
): Promise<void> {
|
||||
await this.inbox.markFailed({
|
||||
consumer: this.natsNames.consumers.botCommand,
|
||||
projectId: event.projectId,
|
||||
chatLogLogId,
|
||||
error,
|
||||
});
|
||||
}
|
||||
|
||||
private parseErrorReply(
|
||||
event: DakaoInboundEvent,
|
||||
senderNickname: string,
|
||||
@@ -194,15 +267,15 @@ export class DakaoSubscriber implements OnModuleInit {
|
||||
const text = ((): string => {
|
||||
switch (err.code) {
|
||||
case 'unknown_command':
|
||||
return ` 알 수 없는 명령어입니다. 사용법: !내전 목록, !내전 계정등록 <게임명>#<태그>, !내전 신청 <ID> <게임명>#<태그> <포지션1>,<포지션2>`;
|
||||
return ` 알 수 없는 명령어입니다. 사용법: !내전 일정, !내전 계정등록 <게임명>#<태그>, !내전 대표계정변경 <게임명>#<태그>, !내전 선호포지션등록 미드,정글, !내전 신청 [코드] [게임명#태그] [포지션1,포지션2], !내전 취소 <코드>`;
|
||||
case 'usage':
|
||||
return ` 사용법: !내전 목록, !내전 계정등록 <게임명>#<태그>, !내전 신청 <ID> <게임명>#<태그> <포지션1>,<포지션2>`;
|
||||
return ` 사용법: !내전 일정, !내전 계정등록 <게임명>#<태그>, !내전 대표계정변경 <게임명>#<태그>, !내전 선호포지션등록 미드,정글, !내전 신청 [코드] [게임명#태그] [포지션1,포지션2], !내전 취소 <코드>`;
|
||||
case 'invalid_match_id':
|
||||
return ` 매치 ID 형식이 올바르지 않습니다 (${err.detail ?? ''}).`;
|
||||
case 'invalid_riot_id':
|
||||
return ` 라이엇 ID 형식이 올바르지 않습니다 (예: 프리리#KR1).`;
|
||||
case 'invalid_position':
|
||||
return ` 포지션 입력이 올바르지 않습니다. 최소 2개, 중복 없이, 인식되는 별칭(탑/정글/미드/원딜/서폿) 사용.`;
|
||||
return ` 포지션 입력이 올바르지 않습니다. 쉼표로 구분해서 최소 2개를 중복 없이 입력해주세요. 사용 가능: 탑, 정글, 미드, 원딜, 서폿`;
|
||||
default:
|
||||
return ` 명령을 처리할 수 없습니다.`;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// dakao NATS contracts
|
||||
// inbound: dakao 가 lolympus-tournament-support.kakaotalk.command 로 발행하는 이벤트
|
||||
// outbound: 우리가 dakao.command.chat.send-message.v1 로 발행하는 명령
|
||||
// reply: dakao 가 우리 envelope 의 replySubject 로 publish 하는 결과
|
||||
// inbound: dakao 가 {env}.lolympus.dakao.bot-command.submitted.v1 로 발행하는 이벤트
|
||||
// outbound: 우리가 {env}.dakao.chat.send-message.v1 로 발행하는 명령
|
||||
// result: dakao 가 {env}.lolympus.dakao.chat.send-message.{succeeded|failed}.v1 로 발행하는 결과 이벤트
|
||||
|
||||
// ===== Inbound =====
|
||||
export interface DakaoLong {
|
||||
@@ -75,24 +75,33 @@ export interface DakaoSendMessagePayload {
|
||||
silence?: boolean;
|
||||
}
|
||||
|
||||
export interface DakaoResultSubjects {
|
||||
succeeded: string;
|
||||
failed: string;
|
||||
}
|
||||
|
||||
export interface DakaoCommandEnvelope<TPayload> {
|
||||
schema: 'dakao.command.v1';
|
||||
id: string;
|
||||
eventId: string;
|
||||
type: string;
|
||||
source: string;
|
||||
eventSource: string;
|
||||
correlationId?: string;
|
||||
replySubject?: string;
|
||||
resultSubjects?: DakaoResultSubjects;
|
||||
payload: TPayload;
|
||||
}
|
||||
|
||||
// ===== Reply =====
|
||||
// ===== Result =====
|
||||
export interface DakaoResultEnvelope {
|
||||
schema: 'dakao.result.v1';
|
||||
id: string;
|
||||
eventId: string;
|
||||
requestEventId: string;
|
||||
type: string;
|
||||
eventSource: string;
|
||||
requestEventSource: string;
|
||||
status: 'succeeded' | 'failed';
|
||||
handledAt: string;
|
||||
correlationId?: string;
|
||||
providerMessageId?: string;
|
||||
result?: Record<string, unknown>;
|
||||
error?: {
|
||||
code: string;
|
||||
|
||||
@@ -6,7 +6,7 @@ const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
|
||||
|
||||
function makeHandler(dakaoUserService?: Partial<DakaoUserService>) {
|
||||
return new AccountRegisterHandler({
|
||||
registerPrimaryRiotAccount: jest.fn(),
|
||||
registerRiotAccount: jest.fn(),
|
||||
...dakaoUserService,
|
||||
} as unknown as DakaoUserService);
|
||||
}
|
||||
@@ -20,15 +20,39 @@ const baseParams = {
|
||||
};
|
||||
|
||||
describe('AccountRegisterHandler', () => {
|
||||
it('translates already-registered Riot account errors', async () => {
|
||||
it('registers a Riot account through DakaoUserService', async () => {
|
||||
const registerRiotAccount = jest.fn().mockResolvedValue({
|
||||
user: { _id: objectId('222222222222222222222222') },
|
||||
riotAccount: { gameName: '프리리', tagLine: 'KR1' },
|
||||
});
|
||||
const handler = makeHandler({
|
||||
registerPrimaryRiotAccount: jest
|
||||
registerRiotAccount,
|
||||
});
|
||||
|
||||
const segments = await handler.handle(baseParams);
|
||||
|
||||
expect(registerRiotAccount).toHaveBeenCalledWith({
|
||||
communityId: baseParams.communityId,
|
||||
kakaoTalkId: 'kakao-user-1',
|
||||
kakaoTalkNickname: '프리리',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
});
|
||||
expect(segments).toEqual([
|
||||
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
|
||||
expect.objectContaining({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('등록 계정: 프리리#KR1'),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('translates Riot account conflict errors', async () => {
|
||||
const handler = makeHandler({
|
||||
registerRiotAccount: jest
|
||||
.fn()
|
||||
.mockRejectedValue(
|
||||
new DakaoUserError(
|
||||
'riot_account_already_registered',
|
||||
'기존소환사#KR1',
|
||||
),
|
||||
new DakaoUserError('riot_account_conflict', '기존소환사#KR1'),
|
||||
),
|
||||
});
|
||||
|
||||
@@ -38,7 +62,7 @@ describe('AccountRegisterHandler', () => {
|
||||
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
|
||||
expect.objectContaining({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('이미 등록된 라이엇 계정'),
|
||||
text: expect.stringContaining('이미 다른 사용자가 등록한 라이엇 계정'),
|
||||
}),
|
||||
]);
|
||||
expect(segments[1]).toMatchObject({
|
||||
|
||||
@@ -19,7 +19,7 @@ export class AccountRegisterHandler {
|
||||
params: AccountRegisterHandlerParams,
|
||||
): Promise<DakaoSegment[]> {
|
||||
try {
|
||||
const resolved = await this.dakaoUserService.registerPrimaryRiotAccount({
|
||||
const resolved = await this.dakaoUserService.registerRiotAccount({
|
||||
communityId: params.communityId,
|
||||
kakaoTalkId: params.senderUserId,
|
||||
kakaoTalkNickname: params.senderNickname,
|
||||
@@ -37,7 +37,7 @@ export class AccountRegisterHandler {
|
||||
kind: 'text',
|
||||
text:
|
||||
` 계정 등록 완료` +
|
||||
`\n대표 계정: ${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}`,
|
||||
`\n등록 계정: ${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}`,
|
||||
},
|
||||
];
|
||||
} catch (err) {
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { MatchService } from '../../match/match.service';
|
||||
import { DakaoUserService } from '../dakao-user.service';
|
||||
import { MatchCancelHandler } from './match-cancel.handler';
|
||||
|
||||
const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
|
||||
|
||||
function makeHandler(overrides?: {
|
||||
matchService?: Partial<MatchService>;
|
||||
dakaoUserService?: Partial<DakaoUserService>;
|
||||
}): MatchCancelHandler {
|
||||
const matchService = {
|
||||
cancelJoin: jest.fn(),
|
||||
list: jest.fn(),
|
||||
...overrides?.matchService,
|
||||
} as unknown as MatchService;
|
||||
const dakaoUserService = {
|
||||
findUserByKakaoTalkId: jest.fn(),
|
||||
...overrides?.dakaoUserService,
|
||||
} as unknown as DakaoUserService;
|
||||
return new MatchCancelHandler(matchService, dakaoUserService);
|
||||
}
|
||||
|
||||
const baseParams = {
|
||||
communityId: objectId('111111111111111111111111'),
|
||||
matchId: '69b63bc96da18dfdb218ee8c',
|
||||
senderUserId: 'kakao-user-1',
|
||||
senderNickname: '프리리',
|
||||
};
|
||||
|
||||
describe('MatchCancelHandler', () => {
|
||||
it('rejects unknown match reference without cancelling', async () => {
|
||||
const cancelJoin = jest.fn();
|
||||
const handler = makeHandler({
|
||||
matchService: {
|
||||
cancelJoin,
|
||||
list: jest.fn().mockResolvedValue([]),
|
||||
} as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
findUserByKakaoTalkId: jest.fn().mockResolvedValue({
|
||||
_id: objectId('222222222222222222222222'),
|
||||
}),
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
const segments = await handler.handle({
|
||||
...baseParams,
|
||||
matchId: 'not-an-id',
|
||||
});
|
||||
|
||||
expect(cancelJoin).not.toHaveBeenCalled();
|
||||
expect(segments).toEqual([
|
||||
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
|
||||
expect.objectContaining({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('모집 중인 내전이 없습니다'),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('replies with success for registered user cancellation', async () => {
|
||||
const cancelJoin = jest.fn().mockResolvedValue({
|
||||
title: '저녁 내전',
|
||||
participants: [{}, {}],
|
||||
maxParticipants: 10,
|
||||
});
|
||||
const findUserByKakaoTalkId = jest.fn().mockResolvedValue({
|
||||
_id: objectId('222222222222222222222222'),
|
||||
});
|
||||
const handler = makeHandler({
|
||||
matchService: { cancelJoin } as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
findUserByKakaoTalkId,
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
const segments = await handler.handle(baseParams);
|
||||
|
||||
expect(findUserByKakaoTalkId).toHaveBeenCalledWith({
|
||||
communityId: baseParams.communityId,
|
||||
kakaoTalkId: 'kakao-user-1',
|
||||
});
|
||||
expect(cancelJoin).toHaveBeenCalledWith({
|
||||
matchId: expect.any(mongoose.Types.ObjectId),
|
||||
userId: expect.any(mongoose.Types.ObjectId),
|
||||
});
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('참가 취소 완료 (2/10)'),
|
||||
});
|
||||
});
|
||||
|
||||
it('resolves cancellation by short code', async () => {
|
||||
const matchId = objectId('333333333333333333333333');
|
||||
const cancelJoin = jest.fn().mockResolvedValue({
|
||||
title: '저녁 내전',
|
||||
participants: [{}, {}],
|
||||
maxParticipants: 10,
|
||||
});
|
||||
const findUserByKakaoTalkId = jest.fn().mockResolvedValue({
|
||||
_id: objectId('222222222222222222222222'),
|
||||
});
|
||||
const handler = makeHandler({
|
||||
matchService: {
|
||||
cancelJoin,
|
||||
list: jest.fn().mockResolvedValue([
|
||||
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
|
||||
]),
|
||||
} as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
findUserByKakaoTalkId,
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
await handler.handle({
|
||||
...baseParams,
|
||||
matchId: 'AB12',
|
||||
});
|
||||
|
||||
expect(cancelJoin).toHaveBeenCalledWith({
|
||||
matchId,
|
||||
userId: expect.any(mongoose.Types.ObjectId),
|
||||
});
|
||||
});
|
||||
|
||||
it('asks unregistered user to register first', async () => {
|
||||
const cancelJoin = jest.fn();
|
||||
const handler = makeHandler({
|
||||
matchService: { cancelJoin } as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
findUserByKakaoTalkId: jest.fn().mockResolvedValue(null),
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
const segments = await handler.handle(baseParams);
|
||||
|
||||
expect(cancelJoin).not.toHaveBeenCalled();
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('계정을 등록'),
|
||||
});
|
||||
});
|
||||
|
||||
it('translates not-joined cancellation errors', async () => {
|
||||
const handler = makeHandler({
|
||||
matchService: {
|
||||
cancelJoin: jest
|
||||
.fn()
|
||||
.mockRejectedValue(
|
||||
new BadRequestException('User has not joined this match.'),
|
||||
),
|
||||
} as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
findUserByKakaoTalkId: jest.fn().mockResolvedValue({
|
||||
_id: objectId('222222222222222222222222'),
|
||||
}),
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
const segments = await handler.handle(baseParams);
|
||||
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('신청한 내전이 아닙니다'),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { MatchService } from '../../match/match.service';
|
||||
import { DakaoSegment } from '../dakao.types';
|
||||
import { DakaoUserService } from '../dakao-user.service';
|
||||
import { resolveRecruitingMatchReference } from './match-reference.util';
|
||||
|
||||
interface CancelHandlerParams {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
matchId: string;
|
||||
senderUserId: string; // kakaoTalkId
|
||||
senderNickname: string; // kakaoTalkNickname
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MatchCancelHandler {
|
||||
constructor(
|
||||
private readonly matchService: MatchService,
|
||||
private readonly dakaoUserService: DakaoUserService,
|
||||
) {}
|
||||
|
||||
public async handle(params: CancelHandlerParams): Promise<DakaoSegment[]> {
|
||||
const user = await this.dakaoUserService.findUserByKakaoTalkId({
|
||||
communityId: params.communityId,
|
||||
kakaoTalkId: params.senderUserId,
|
||||
});
|
||||
if (!user) {
|
||||
return this.errorReply(
|
||||
params,
|
||||
'먼저 !내전 계정등록 <닉네임>#<태그> 로 계정을 등록해주세요.',
|
||||
);
|
||||
}
|
||||
|
||||
const matchTarget = await this.resolveCancelTarget(params);
|
||||
if (typeof matchTarget === 'string') {
|
||||
return this.errorReply(params, matchTarget);
|
||||
}
|
||||
|
||||
try {
|
||||
const match = await this.matchService.cancelJoin({
|
||||
matchId: matchTarget,
|
||||
userId: user._id,
|
||||
});
|
||||
|
||||
return [
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: params.senderUserId,
|
||||
displayText: params.senderNickname,
|
||||
},
|
||||
{
|
||||
kind: 'text',
|
||||
text:
|
||||
` 참가 취소 완료 (${match.participants.length}/${match.maxParticipants})` +
|
||||
`\n내전: ${match.title}`,
|
||||
},
|
||||
];
|
||||
} catch (err) {
|
||||
if (err instanceof NotFoundException) {
|
||||
return this.errorReply(params, '내전을 찾을 수 없습니다.');
|
||||
}
|
||||
if (err instanceof BadRequestException) {
|
||||
return this.errorReply(params, this.translateBadRequest(err.message));
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private async resolveCancelTarget(
|
||||
params: CancelHandlerParams,
|
||||
): Promise<mongoose.Types.ObjectId | string> {
|
||||
if (mongoose.isValidObjectId(params.matchId)) {
|
||||
return new mongoose.Types.ObjectId(params.matchId);
|
||||
}
|
||||
|
||||
const recruitingMatches = await this.matchService.list({
|
||||
communityId: params.communityId,
|
||||
status: 'recruiting',
|
||||
limit: 50,
|
||||
});
|
||||
if (recruitingMatches.length === 0) {
|
||||
return '모집 중인 내전이 없습니다.';
|
||||
}
|
||||
|
||||
const result = resolveRecruitingMatchReference(
|
||||
params.matchId,
|
||||
recruitingMatches,
|
||||
);
|
||||
if (result.kind === 'matched') {
|
||||
return result.match._id;
|
||||
}
|
||||
if (result.kind === 'ambiguous') {
|
||||
return `내전 코드 또는 제목이 여러 개와 겹칩니다 (${result.titles.join(', ')}). 더 길게 입력하거나 ID를 사용해주세요.`;
|
||||
}
|
||||
return '모집 중인 내전을 찾을 수 없습니다. !내전 리스트에서 코드 또는 제목을 확인해주세요.';
|
||||
}
|
||||
|
||||
private errorReply(
|
||||
params: CancelHandlerParams,
|
||||
message: string,
|
||||
): DakaoSegment[] {
|
||||
return [
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: params.senderUserId,
|
||||
displayText: params.senderNickname,
|
||||
},
|
||||
{ kind: 'text', text: ` ${message}` },
|
||||
];
|
||||
}
|
||||
|
||||
private translateBadRequest(raw: string): string {
|
||||
if (raw.includes('different communities')) {
|
||||
return '이 내전은 현재 채팅방의 커뮤니티 소속이 아닙니다.';
|
||||
}
|
||||
if (raw.includes('not recruiting')) {
|
||||
return '모집 중인 내전만 참가 취소할 수 있습니다.';
|
||||
}
|
||||
if (raw.includes('has not joined')) return '신청한 내전이 아닙니다.';
|
||||
return raw;
|
||||
}
|
||||
}
|
||||
@@ -12,10 +12,12 @@ function makeHandler(overrides?: {
|
||||
}): MatchJoinHandler {
|
||||
const matchService = {
|
||||
join: jest.fn(),
|
||||
list: jest.fn(),
|
||||
...overrides?.matchService,
|
||||
} as unknown as MatchService;
|
||||
const dakaoUserService = {
|
||||
resolveRiotAccount: jest.fn(),
|
||||
findUserByKakaoTalkId: jest.fn(),
|
||||
...overrides?.dakaoUserService,
|
||||
} as unknown as DakaoUserService;
|
||||
return new MatchJoinHandler(matchService, dakaoUserService);
|
||||
@@ -23,27 +25,37 @@ function makeHandler(overrides?: {
|
||||
|
||||
const baseParams = {
|
||||
communityId: objectId('111111111111111111111111'),
|
||||
matchId: '69b63bc96da18dfdb218ee8c',
|
||||
matchAndRiotId: '69b63bc96da18dfdb218ee8c 프리리#KR1',
|
||||
senderUserId: 'kakao-user-1',
|
||||
senderNickname: '프리리',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
positions: ['MID', 'TOP'] as const,
|
||||
};
|
||||
|
||||
describe('MatchJoinHandler', () => {
|
||||
it('rejects invalid match id without touching services', async () => {
|
||||
const handler = makeHandler();
|
||||
it('rejects missing match reference when multiple matches are recruiting', async () => {
|
||||
const resolveRiotAccount = jest.fn();
|
||||
const handler = makeHandler({
|
||||
matchService: {
|
||||
list: jest.fn().mockResolvedValue([
|
||||
{ _id: objectId('333333333333333333333333'), title: '저녁 내전' },
|
||||
{ _id: objectId('444444444444444444444444'), title: '심야 내전' },
|
||||
]),
|
||||
} as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
resolveRiotAccount,
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
const segments = await handler.handle({
|
||||
...baseParams,
|
||||
matchId: 'not-an-id',
|
||||
matchAndRiotId: '프리리#KR1',
|
||||
positions: [...baseParams.positions],
|
||||
});
|
||||
expect(resolveRiotAccount).not.toHaveBeenCalled();
|
||||
expect(segments).toEqual([
|
||||
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
|
||||
expect.objectContaining({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('유효하지 않은 내전 ID'),
|
||||
text: expect.stringContaining('코드 또는 제목'),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
@@ -92,6 +104,245 @@ describe('MatchJoinHandler', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('uses the only recruiting match when match reference is omitted', async () => {
|
||||
const matchId = objectId('333333333333333333333333');
|
||||
const join = jest.fn().mockResolvedValue({
|
||||
title: '저녁 내전',
|
||||
participants: [{}],
|
||||
maxParticipants: 10,
|
||||
});
|
||||
const handler = makeHandler({
|
||||
matchService: {
|
||||
list: jest
|
||||
.fn()
|
||||
.mockResolvedValue([{ _id: matchId, title: '저녁 내전' }]),
|
||||
join,
|
||||
} as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
resolveRiotAccount: jest.fn().mockResolvedValue({
|
||||
user: { _id: objectId('222222222222222222222222') },
|
||||
riotAccount: { puuid: 'puuid-1', gameName: '프리리', tagLine: 'KR1' },
|
||||
}),
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
const segments = await handler.handle({
|
||||
...baseParams,
|
||||
matchAndRiotId: '프리리#KR1',
|
||||
positions: [...baseParams.positions],
|
||||
});
|
||||
|
||||
expect(join).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
matchId,
|
||||
}),
|
||||
);
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('신청 완료 (1/10)'),
|
||||
});
|
||||
});
|
||||
|
||||
it('resolves a unique recruiting match by title prefix', async () => {
|
||||
const matchId = objectId('333333333333333333333333');
|
||||
const join = jest.fn().mockResolvedValue({
|
||||
title: '저녁 내전',
|
||||
participants: [{}],
|
||||
maxParticipants: 10,
|
||||
});
|
||||
const handler = makeHandler({
|
||||
matchService: {
|
||||
list: jest.fn().mockResolvedValue([
|
||||
{ _id: matchId, title: '저녁 내전' },
|
||||
{ _id: objectId('444444444444444444444444'), title: '심야 내전' },
|
||||
]),
|
||||
join,
|
||||
} as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
resolveRiotAccount: jest.fn().mockResolvedValue({
|
||||
user: { _id: objectId('222222222222222222222222') },
|
||||
riotAccount: { puuid: 'puuid-1', gameName: '프리리', tagLine: 'KR1' },
|
||||
}),
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
await handler.handle({
|
||||
...baseParams,
|
||||
matchAndRiotId: '저녁 프리리#KR1',
|
||||
positions: [...baseParams.positions],
|
||||
});
|
||||
|
||||
expect(join).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
matchId,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('resolves a recruiting match by short code', async () => {
|
||||
const matchId = objectId('333333333333333333333333');
|
||||
const join = jest.fn().mockResolvedValue({
|
||||
title: '저녁 내전',
|
||||
participants: [{}],
|
||||
maxParticipants: 10,
|
||||
});
|
||||
const handler = makeHandler({
|
||||
matchService: {
|
||||
list: jest.fn().mockResolvedValue([
|
||||
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
|
||||
{
|
||||
_id: objectId('444444444444444444444444'),
|
||||
title: '심야 내전',
|
||||
shortCode: 'CD34',
|
||||
},
|
||||
]),
|
||||
join,
|
||||
} as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
resolveRiotAccount: jest.fn().mockResolvedValue({
|
||||
user: { _id: objectId('222222222222222222222222') },
|
||||
riotAccount: { puuid: 'puuid-1', gameName: '프리리', tagLine: 'KR1' },
|
||||
}),
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
await handler.handle({
|
||||
...baseParams,
|
||||
matchAndRiotId: 'AB12 프리리#KR1',
|
||||
positions: [...baseParams.positions],
|
||||
});
|
||||
|
||||
expect(join).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
matchId,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('uses registered account and preferred positions for abbreviated join', async () => {
|
||||
const matchId = objectId('333333333333333333333333');
|
||||
const userId = objectId('222222222222222222222222');
|
||||
const join = jest.fn().mockResolvedValue({
|
||||
title: '저녁 내전',
|
||||
participants: [{}],
|
||||
maxParticipants: 10,
|
||||
});
|
||||
const resolveRiotAccount = jest.fn();
|
||||
const handler = makeHandler({
|
||||
matchService: {
|
||||
list: jest.fn().mockResolvedValue([
|
||||
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
|
||||
]),
|
||||
join,
|
||||
} as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
resolveRiotAccount,
|
||||
findUserByKakaoTalkId: jest.fn().mockResolvedValue({
|
||||
_id: userId,
|
||||
riotAccounts: [
|
||||
{
|
||||
puuid: 'puuid-1',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
isPrimary: true,
|
||||
},
|
||||
],
|
||||
preferredPositions: [
|
||||
{ position: 'MID', priority: 1 },
|
||||
{ position: 'JGL', priority: 2 },
|
||||
],
|
||||
}),
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
const segments = await handler.handle({
|
||||
...baseParams,
|
||||
matchAndRiotId: 'AB12',
|
||||
positions: undefined,
|
||||
});
|
||||
|
||||
expect(resolveRiotAccount).not.toHaveBeenCalled();
|
||||
expect(join).toHaveBeenCalledWith({
|
||||
matchId,
|
||||
userId,
|
||||
preferredPositions: [
|
||||
{ position: 'MID', priority: 1 },
|
||||
{ position: 'JGL', priority: 2 },
|
||||
],
|
||||
riotPuuid: 'puuid-1',
|
||||
});
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('계정: 프리리#KR1'),
|
||||
});
|
||||
});
|
||||
|
||||
it('asks abbreviated join users to register missing preferred positions', async () => {
|
||||
const matchId = objectId('333333333333333333333333');
|
||||
const join = jest.fn();
|
||||
const handler = makeHandler({
|
||||
matchService: {
|
||||
list: jest.fn().mockResolvedValue([
|
||||
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
|
||||
]),
|
||||
join,
|
||||
} as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
findUserByKakaoTalkId: jest.fn().mockResolvedValue({
|
||||
_id: objectId('222222222222222222222222'),
|
||||
riotAccounts: [
|
||||
{
|
||||
puuid: 'puuid-1',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
isPrimary: true,
|
||||
},
|
||||
],
|
||||
preferredPositions: [],
|
||||
}),
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
const segments = await handler.handle({
|
||||
...baseParams,
|
||||
matchAndRiotId: 'AB12',
|
||||
positions: undefined,
|
||||
});
|
||||
|
||||
expect(join).not.toHaveBeenCalled();
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('선호포지션등록'),
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects ambiguous title prefixes', async () => {
|
||||
const resolveRiotAccount = jest.fn();
|
||||
const handler = makeHandler({
|
||||
matchService: {
|
||||
list: jest.fn().mockResolvedValue([
|
||||
{ _id: objectId('333333333333333333333333'), title: '저녁 내전 A' },
|
||||
{ _id: objectId('444444444444444444444444'), title: '저녁 내전 B' },
|
||||
]),
|
||||
} as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
resolveRiotAccount,
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
const segments = await handler.handle({
|
||||
...baseParams,
|
||||
matchAndRiotId: '저녁 프리리#KR1',
|
||||
positions: [...baseParams.positions],
|
||||
});
|
||||
|
||||
expect(resolveRiotAccount).not.toHaveBeenCalled();
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('여러 개와 겹칩니다'),
|
||||
});
|
||||
});
|
||||
|
||||
it('translates riot_account_not_found errors', async () => {
|
||||
const handler = makeHandler({
|
||||
dakaoUserService: {
|
||||
|
||||
@@ -5,18 +5,30 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { MatchService } from '../../match/match.service';
|
||||
import { Position, PositionPreference } from '../../global/database/schema';
|
||||
import {
|
||||
MatchDocument,
|
||||
Position,
|
||||
PositionPreference,
|
||||
RiotAccount,
|
||||
UserDocument,
|
||||
} from '../../global/database/schema';
|
||||
import { DakaoSegment } from '../dakao.types';
|
||||
import { DakaoUserError, DakaoUserService } from '../dakao-user.service';
|
||||
import { normalizeRiotIdPart } from '../riot-id.util';
|
||||
import { resolveRecruitingMatchReference } from './match-reference.util';
|
||||
|
||||
interface JoinHandlerParams {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
matchId: string;
|
||||
matchAndRiotId: string;
|
||||
senderUserId: string; // kakaoTalkId
|
||||
senderNickname: string; // kakaoTalkNickname
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
positions: Position[];
|
||||
positions?: Position[];
|
||||
}
|
||||
|
||||
interface ResolvedJoinTarget {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
gameName?: string;
|
||||
tagLine?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
@@ -27,34 +39,46 @@ export class MatchJoinHandler {
|
||||
) {}
|
||||
|
||||
public async handle(params: JoinHandlerParams): Promise<DakaoSegment[]> {
|
||||
if (!mongoose.isValidObjectId(params.matchId)) {
|
||||
return this.errorReply(params, '유효하지 않은 내전 ID 입니다.');
|
||||
const joinTarget = await this.resolveJoinTarget(params);
|
||||
if (typeof joinTarget === 'string') {
|
||||
return this.errorReply(params, joinTarget);
|
||||
}
|
||||
const matchObjectId = new mongoose.Types.ObjectId(params.matchId);
|
||||
|
||||
let resolved;
|
||||
let resolved:
|
||||
| { user: UserDocument; riotAccount: RiotAccount }
|
||||
| string;
|
||||
try {
|
||||
resolved = await this.dakaoUserService.resolveRiotAccount({
|
||||
communityId: params.communityId,
|
||||
kakaoTalkId: params.senderUserId,
|
||||
kakaoTalkNickname: params.senderNickname,
|
||||
gameName: params.gameName,
|
||||
tagLine: params.tagLine,
|
||||
});
|
||||
resolved =
|
||||
joinTarget.gameName && joinTarget.tagLine
|
||||
? await this.dakaoUserService.resolveRiotAccount({
|
||||
communityId: params.communityId,
|
||||
kakaoTalkId: params.senderUserId,
|
||||
kakaoTalkNickname: params.senderNickname,
|
||||
gameName: joinTarget.gameName,
|
||||
tagLine: joinTarget.tagLine,
|
||||
})
|
||||
: await this.resolveRegisteredRiotAccount(params);
|
||||
} catch (err) {
|
||||
if (err instanceof DakaoUserError) {
|
||||
return this.errorReply(params, this.translateUserError(err));
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
if (typeof resolved === 'string') {
|
||||
return this.errorReply(params, resolved);
|
||||
}
|
||||
|
||||
const preferredPositions: PositionPreference[] = params.positions.map(
|
||||
(position, index) => ({ position, priority: index + 1 }),
|
||||
const preferredPositions = this.resolvePreferredPositions(
|
||||
params.positions,
|
||||
resolved.user.preferredPositions,
|
||||
);
|
||||
if (typeof preferredPositions === 'string') {
|
||||
return this.errorReply(params, preferredPositions);
|
||||
}
|
||||
|
||||
try {
|
||||
const match = await this.matchService.join({
|
||||
matchId: matchObjectId,
|
||||
matchId: joinTarget.matchId,
|
||||
userId: resolved.user._id,
|
||||
preferredPositions,
|
||||
riotPuuid: resolved.riotAccount.puuid,
|
||||
@@ -72,7 +96,9 @@ export class MatchJoinHandler {
|
||||
` 신청 완료 (${match.participants.length}/${match.maxParticipants})` +
|
||||
`\n내전: ${match.title}` +
|
||||
`\n계정: ${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}` +
|
||||
`\n포지션: ${params.positions.join(', ')}`,
|
||||
`\n포지션: ${preferredPositions
|
||||
.map((entry) => entry.position)
|
||||
.join(', ')}`,
|
||||
},
|
||||
];
|
||||
} catch (err) {
|
||||
@@ -86,6 +112,196 @@ export class MatchJoinHandler {
|
||||
}
|
||||
}
|
||||
|
||||
private async resolveJoinTarget(
|
||||
params: JoinHandlerParams,
|
||||
): Promise<ResolvedJoinTarget | string> {
|
||||
if (!params.matchAndRiotId.includes('#')) {
|
||||
return this.resolveJoinTargetWithoutRiotId(params);
|
||||
}
|
||||
|
||||
const riotId = this.parseRiotId(params.matchAndRiotId);
|
||||
if (typeof riotId === 'string') return riotId;
|
||||
|
||||
const objectIdMatch = riotId.gameNameWithOptionalMatchRef.match(
|
||||
/^([a-f0-9]{24})(?:\s+(.+))?$/i,
|
||||
);
|
||||
if (objectIdMatch) {
|
||||
const gameName = normalizeRiotIdPart(objectIdMatch[2] ?? '');
|
||||
if (!gameName) {
|
||||
return '라이엇 ID 형식이 올바르지 않습니다 (예: 프리리#KR1).';
|
||||
}
|
||||
return {
|
||||
matchId: new mongoose.Types.ObjectId(objectIdMatch[1]),
|
||||
gameName,
|
||||
tagLine: riotId.tagLine,
|
||||
};
|
||||
}
|
||||
|
||||
const recruitingMatches = await this.matchService.list({
|
||||
communityId: params.communityId,
|
||||
status: 'recruiting',
|
||||
limit: 50,
|
||||
});
|
||||
if (recruitingMatches.length === 0) {
|
||||
return '모집 중인 내전이 없습니다.';
|
||||
}
|
||||
|
||||
const titleTarget = this.resolveTitleTarget(
|
||||
riotId.gameNameWithOptionalMatchRef,
|
||||
recruitingMatches,
|
||||
);
|
||||
if (titleTarget.kind === 'matched') {
|
||||
return {
|
||||
matchId: titleTarget.match._id,
|
||||
gameName: titleTarget.gameName,
|
||||
tagLine: riotId.tagLine,
|
||||
};
|
||||
}
|
||||
if (titleTarget.kind === 'ambiguous') {
|
||||
return `내전 코드 또는 제목이 여러 개와 겹칩니다 (${titleTarget.titles.join(', ')}). 더 길게 입력하거나 ID를 사용해주세요.`;
|
||||
}
|
||||
|
||||
if (recruitingMatches.length === 1) {
|
||||
return {
|
||||
matchId: recruitingMatches[0]._id,
|
||||
gameName: riotId.gameNameWithOptionalMatchRef,
|
||||
tagLine: riotId.tagLine,
|
||||
};
|
||||
}
|
||||
|
||||
return '모집 중인 내전을 찾을 수 없습니다. !내전 리스트에서 코드 또는 제목을 확인해주세요.';
|
||||
}
|
||||
|
||||
private async resolveJoinTargetWithoutRiotId(
|
||||
params: JoinHandlerParams,
|
||||
): Promise<ResolvedJoinTarget | string> {
|
||||
const reference = params.matchAndRiotId.trim();
|
||||
if (/^[a-f0-9]{24}$/i.test(reference)) {
|
||||
return {
|
||||
matchId: new mongoose.Types.ObjectId(reference),
|
||||
};
|
||||
}
|
||||
|
||||
const recruitingMatches = await this.matchService.list({
|
||||
communityId: params.communityId,
|
||||
status: 'recruiting',
|
||||
limit: 50,
|
||||
});
|
||||
if (recruitingMatches.length === 0) {
|
||||
return '모집 중인 내전이 없습니다.';
|
||||
}
|
||||
|
||||
if (!reference) {
|
||||
if (recruitingMatches.length === 1) {
|
||||
return { matchId: recruitingMatches[0]._id };
|
||||
}
|
||||
return '모집 중인 내전이 여러 개입니다. !내전 일정에서 코드 또는 제목을 확인해주세요.';
|
||||
}
|
||||
|
||||
const result = resolveRecruitingMatchReference(
|
||||
reference,
|
||||
recruitingMatches,
|
||||
);
|
||||
if (result.kind === 'matched') {
|
||||
return { matchId: result.match._id };
|
||||
}
|
||||
if (result.kind === 'ambiguous') {
|
||||
return `내전 코드 또는 제목이 여러 개와 겹칩니다 (${result.titles.join(', ')}). 더 길게 입력하거나 ID를 사용해주세요.`;
|
||||
}
|
||||
return '모집 중인 내전을 찾을 수 없습니다. !내전 일정에서 코드 또는 제목을 확인해주세요.';
|
||||
}
|
||||
|
||||
private parseRiotId(
|
||||
value: string,
|
||||
): { gameNameWithOptionalMatchRef: string; tagLine: string } | string {
|
||||
const hashIndex = value.lastIndexOf('#');
|
||||
if (hashIndex <= 0 || hashIndex === value.length - 1) {
|
||||
return '라이엇 ID 형식이 올바르지 않습니다 (예: 프리리#KR1).';
|
||||
}
|
||||
|
||||
const gameNameWithOptionalMatchRef = normalizeRiotIdPart(
|
||||
value.slice(0, hashIndex),
|
||||
);
|
||||
const tagLine = normalizeRiotIdPart(value.slice(hashIndex + 1));
|
||||
if (!gameNameWithOptionalMatchRef || !tagLine) {
|
||||
return '라이엇 ID 형식이 올바르지 않습니다 (예: 프리리#KR1).';
|
||||
}
|
||||
return { gameNameWithOptionalMatchRef, tagLine };
|
||||
}
|
||||
|
||||
private resolveTitleTarget(
|
||||
value: string,
|
||||
matches: MatchDocument[],
|
||||
):
|
||||
| { kind: 'matched'; match: MatchDocument; gameName: string }
|
||||
| { kind: 'ambiguous'; titles: string[] }
|
||||
| { kind: 'not-found' } {
|
||||
let ambiguousTitles: string[] | null = null;
|
||||
|
||||
for (const splitAt of splitPositionsFromRight(value)) {
|
||||
const matchTitlePrefix = value.slice(0, splitAt).trim();
|
||||
const gameName = normalizeRiotIdPart(value.slice(splitAt + 1));
|
||||
if (!matchTitlePrefix || !gameName) continue;
|
||||
|
||||
const result = resolveRecruitingMatchReference(
|
||||
matchTitlePrefix,
|
||||
matches,
|
||||
);
|
||||
if (result.kind === 'matched') {
|
||||
return { kind: 'matched', match: result.match, gameName };
|
||||
}
|
||||
if (result.kind === 'ambiguous') {
|
||||
ambiguousTitles = result.titles;
|
||||
}
|
||||
}
|
||||
|
||||
return ambiguousTitles
|
||||
? { kind: 'ambiguous', titles: ambiguousTitles }
|
||||
: { kind: 'not-found' };
|
||||
}
|
||||
|
||||
private async resolveRegisteredRiotAccount(
|
||||
params: JoinHandlerParams,
|
||||
): Promise<{ user: UserDocument; riotAccount: RiotAccount } | string> {
|
||||
const user = await this.dakaoUserService.findUserByKakaoTalkId({
|
||||
communityId: params.communityId,
|
||||
kakaoTalkId: params.senderUserId,
|
||||
});
|
||||
if (!user) {
|
||||
return '먼저 !내전 계정등록 <닉네임>#<태그> 로 계정을 등록해주세요.';
|
||||
}
|
||||
|
||||
const riotAccount =
|
||||
user.riotAccounts.find((account) => account.isPrimary) ??
|
||||
user.riotAccounts[0];
|
||||
if (!riotAccount) {
|
||||
return '먼저 !내전 계정등록 <닉네임>#<태그> 로 계정을 등록해주세요.';
|
||||
}
|
||||
|
||||
return { user, riotAccount };
|
||||
}
|
||||
|
||||
private resolvePreferredPositions(
|
||||
inputPositions: Position[] | undefined,
|
||||
registeredPositions: PositionPreference[],
|
||||
): PositionPreference[] | string {
|
||||
if (inputPositions?.length) {
|
||||
return inputPositions.map((position, index) => ({
|
||||
position,
|
||||
priority: index + 1,
|
||||
}));
|
||||
}
|
||||
|
||||
const preferredPositions = [...(registeredPositions ?? [])]
|
||||
.sort((left, right) => left.priority - right.priority)
|
||||
.filter((entry) => entry.position);
|
||||
if (preferredPositions.length < 2) {
|
||||
return '선호포지션을 입력하거나 !내전 선호포지션등록 미드,정글 로 먼저 등록해주세요.';
|
||||
}
|
||||
|
||||
return preferredPositions;
|
||||
}
|
||||
|
||||
private errorReply(
|
||||
params: JoinHandlerParams,
|
||||
message: string,
|
||||
@@ -126,3 +342,11 @@ export class MatchJoinHandler {
|
||||
return raw;
|
||||
}
|
||||
}
|
||||
|
||||
function splitPositionsFromRight(value: string): number[] {
|
||||
const positions: number[] = [];
|
||||
for (let index = value.length - 1; index >= 0; index -= 1) {
|
||||
if (/\s/.test(value[index])) positions.push(index);
|
||||
}
|
||||
return positions;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { MatchService } from '../../match/match.service';
|
||||
import { MatchListHandler } from './match-list.handler';
|
||||
|
||||
const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
|
||||
|
||||
describe('MatchListHandler', () => {
|
||||
it('prints short codes and compact KST dates', async () => {
|
||||
const match = {
|
||||
_id: objectId('333333333333333333333333'),
|
||||
title: '토요 내전',
|
||||
shortCode: 'AB12',
|
||||
participants: [{}, {}],
|
||||
maxParticipants: 10,
|
||||
scheduledAt: new Date('2026-05-02T10:30:00.000Z'),
|
||||
};
|
||||
const matchService = {
|
||||
list: jest.fn().mockResolvedValue([match]),
|
||||
ensureShortCode: jest.fn().mockResolvedValue(match),
|
||||
} as unknown as MatchService;
|
||||
const handler = new MatchListHandler(matchService);
|
||||
|
||||
const segments = await handler.handle({
|
||||
communityId: objectId('111111111111111111111111'),
|
||||
senderUserId: 'kakao-user-1',
|
||||
senderNickname: '프리리',
|
||||
});
|
||||
|
||||
expect(matchService.ensureShortCode).toHaveBeenCalledWith(match);
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('토요 내전 (2/10) 5/2 19:30'),
|
||||
});
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('코드: AB12'),
|
||||
});
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.not.stringContaining('2026-05-02'),
|
||||
});
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.not.stringContaining('ID:'),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -29,12 +29,15 @@ export class MatchListHandler {
|
||||
];
|
||||
}
|
||||
|
||||
const lines = matches.map((m, i) => {
|
||||
const id = (m._id as mongoose.Types.ObjectId).toString();
|
||||
const matchesWithCodes = await Promise.all(
|
||||
matches.map((match) => this.matchService.ensureShortCode(match)),
|
||||
);
|
||||
|
||||
const lines = matchesWithCodes.map((m, i) => {
|
||||
const filled = m.participants.length;
|
||||
const cap = m.maxParticipants;
|
||||
const time = formatScheduledAt(m.scheduledAt);
|
||||
return `\n${i + 1}. ${m.title} (${filled}/${cap}) ${time}\n ID: ${id}`;
|
||||
return `\n${i + 1}. ${m.title} (${filled}/${cap}) ${time}\n 코드: ${m.shortCode}`;
|
||||
});
|
||||
|
||||
return [
|
||||
@@ -45,19 +48,18 @@ export class MatchListHandler {
|
||||
},
|
||||
{
|
||||
kind: 'text',
|
||||
text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n계정등록: !내전 계정등록 <닉네임>#<태그>\n신청: !내전 신청 <ID> <닉네임>#<태그> <포지션1>,<포지션2>`,
|
||||
text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n계정등록: !내전 계정등록 <닉네임>#<태그>\n대표계정변경: !내전 대표계정변경 <닉네임>#<태그>\n선호포지션등록: !내전 선호포지션등록 미드,정글\n신청: !내전 신청 <코드> [닉네임#태그] [포지션1,포지션2]\n취소: !내전 취소 <코드>\n계정/선호포지션을 등록해두면 !내전 신청 <코드> 로 신청할 수 있습니다.`,
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
function formatScheduledAt(date: Date): string {
|
||||
// YYYY-MM-DD HH:mm (KST 표기)
|
||||
// M/D HH:mm (KST 표기)
|
||||
const kst = new Date(date.getTime() + 9 * 60 * 60 * 1000);
|
||||
const yyyy = kst.getUTCFullYear();
|
||||
const mm = String(kst.getUTCMonth() + 1).padStart(2, '0');
|
||||
const dd = String(kst.getUTCDate()).padStart(2, '0');
|
||||
const month = kst.getUTCMonth() + 1;
|
||||
const day = kst.getUTCDate();
|
||||
const hh = String(kst.getUTCHours()).padStart(2, '0');
|
||||
const mi = String(kst.getUTCMinutes()).padStart(2, '0');
|
||||
return `${yyyy}-${mm}-${dd} ${hh}:${mi}`;
|
||||
return `${month}/${day} ${hh}:${mi}`;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { MatchDocument } from '../../global/database/schema';
|
||||
|
||||
export type MatchReferenceResult =
|
||||
| { kind: 'matched'; match: MatchDocument }
|
||||
| { kind: 'ambiguous'; titles: string[] }
|
||||
| { kind: 'not-found' };
|
||||
|
||||
export function resolveRecruitingMatchReference(
|
||||
reference: string,
|
||||
matches: MatchDocument[],
|
||||
): MatchReferenceResult {
|
||||
const normalizedCode = normalizeShortCode(reference);
|
||||
const codeMatches = matches.filter(
|
||||
(match) =>
|
||||
match.shortCode && normalizeShortCode(match.shortCode) === normalizedCode,
|
||||
);
|
||||
if (codeMatches.length === 1) {
|
||||
return { kind: 'matched', match: codeMatches[0] };
|
||||
}
|
||||
if (codeMatches.length > 1) {
|
||||
return {
|
||||
kind: 'ambiguous',
|
||||
titles: codeMatches.map((match) => match.title),
|
||||
};
|
||||
}
|
||||
|
||||
const normalizedReference = normalizeLookup(reference);
|
||||
const exactMatches = matches.filter(
|
||||
(match) => normalizeLookup(match.title) === normalizedReference,
|
||||
);
|
||||
if (exactMatches.length === 1) {
|
||||
return { kind: 'matched', match: exactMatches[0] };
|
||||
}
|
||||
if (exactMatches.length > 1) {
|
||||
return {
|
||||
kind: 'ambiguous',
|
||||
titles: exactMatches.map((match) => match.title),
|
||||
};
|
||||
}
|
||||
|
||||
const prefixMatches = matches.filter((match) =>
|
||||
normalizeLookup(match.title).startsWith(normalizedReference),
|
||||
);
|
||||
if (prefixMatches.length === 1) {
|
||||
return { kind: 'matched', match: prefixMatches[0] };
|
||||
}
|
||||
if (prefixMatches.length > 1) {
|
||||
return {
|
||||
kind: 'ambiguous',
|
||||
titles: prefixMatches.map((match) => match.title),
|
||||
};
|
||||
}
|
||||
|
||||
return { kind: 'not-found' };
|
||||
}
|
||||
|
||||
function normalizeLookup(value: string): string {
|
||||
return value.normalize('NFC').trim().replace(/\s+/g, ' ').toLowerCase();
|
||||
}
|
||||
|
||||
function normalizeShortCode(value: string): string {
|
||||
return value.normalize('NFC').trim().replace(/\s+/g, '').toUpperCase();
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { DakaoUserService } from '../dakao-user.service';
|
||||
import { PreferredPositionRegisterHandler } from './preferred-position-register.handler';
|
||||
|
||||
const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
|
||||
|
||||
describe('PreferredPositionRegisterHandler', () => {
|
||||
it('registers preferred positions for abbreviated joins', async () => {
|
||||
const registerPreferredPositions = jest.fn().mockResolvedValue({
|
||||
preferredPositions: [
|
||||
{ position: 'MID', priority: 1 },
|
||||
{ position: 'JGL', priority: 2 },
|
||||
],
|
||||
});
|
||||
const handler = new PreferredPositionRegisterHandler({
|
||||
registerPreferredPositions,
|
||||
} as unknown as DakaoUserService);
|
||||
|
||||
const segments = await handler.handle({
|
||||
communityId: objectId('111111111111111111111111'),
|
||||
senderUserId: 'kakao-user-1',
|
||||
senderNickname: '프리리',
|
||||
positions: ['MID', 'JGL'],
|
||||
});
|
||||
|
||||
expect(registerPreferredPositions).toHaveBeenCalledWith({
|
||||
communityId: objectId('111111111111111111111111'),
|
||||
kakaoTalkId: 'kakao-user-1',
|
||||
kakaoTalkNickname: '프리리',
|
||||
positions: ['MID', 'JGL'],
|
||||
});
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('선호 포지션 등록 완료'),
|
||||
});
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('!내전 신청 <내전코드>'),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { Position } from '../../global/database/schema';
|
||||
import { DakaoSegment } from '../dakao.types';
|
||||
import { DakaoUserService } from '../dakao-user.service';
|
||||
|
||||
const POSITION_LABELS: Record<Position, string> = {
|
||||
TOP: '탑',
|
||||
JGL: '정글',
|
||||
MID: '미드',
|
||||
ADC: '원딜',
|
||||
SUP: '서포터',
|
||||
};
|
||||
|
||||
interface PreferredPositionRegisterHandlerParams {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
senderUserId: string;
|
||||
senderNickname: string;
|
||||
positions: Position[];
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class PreferredPositionRegisterHandler {
|
||||
constructor(private readonly dakaoUserService: DakaoUserService) {}
|
||||
|
||||
public async handle(
|
||||
params: PreferredPositionRegisterHandlerParams,
|
||||
): Promise<DakaoSegment[]> {
|
||||
const user = await this.dakaoUserService.registerPreferredPositions({
|
||||
communityId: params.communityId,
|
||||
kakaoTalkId: params.senderUserId,
|
||||
kakaoTalkNickname: params.senderNickname,
|
||||
positions: params.positions,
|
||||
});
|
||||
|
||||
return [
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: params.senderUserId,
|
||||
displayText: params.senderNickname,
|
||||
},
|
||||
{
|
||||
kind: 'text',
|
||||
text:
|
||||
` 선호 포지션 등록 완료` +
|
||||
`\n포지션: ${user.preferredPositions
|
||||
.sort((left, right) => left.priority - right.priority)
|
||||
.map((entry) => POSITION_LABELS[entry.position])
|
||||
.join(', ')}` +
|
||||
`\n이제 !내전 신청 <내전코드> 로 간단히 신청할 수 있습니다.`,
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { DakaoUserError, DakaoUserService } from '../dakao-user.service';
|
||||
import { PrimaryAccountChangeHandler } from './primary-account-change.handler';
|
||||
|
||||
const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
|
||||
|
||||
function makeHandler(dakaoUserService?: Partial<DakaoUserService>) {
|
||||
return new PrimaryAccountChangeHandler({
|
||||
changePrimaryRiotAccount: jest.fn(),
|
||||
...dakaoUserService,
|
||||
} as unknown as DakaoUserService);
|
||||
}
|
||||
|
||||
const baseParams = {
|
||||
communityId: objectId('111111111111111111111111'),
|
||||
senderUserId: 'kakao-user-1',
|
||||
senderNickname: '프리리',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
};
|
||||
|
||||
describe('PrimaryAccountChangeHandler', () => {
|
||||
it('changes the primary Riot account through DakaoUserService', async () => {
|
||||
const changePrimaryRiotAccount = jest.fn().mockResolvedValue({
|
||||
user: { _id: objectId('222222222222222222222222') },
|
||||
riotAccount: { gameName: '프리리', tagLine: 'KR1' },
|
||||
});
|
||||
const handler = makeHandler({
|
||||
changePrimaryRiotAccount,
|
||||
});
|
||||
|
||||
const segments = await handler.handle(baseParams);
|
||||
|
||||
expect(changePrimaryRiotAccount).toHaveBeenCalledWith({
|
||||
communityId: baseParams.communityId,
|
||||
kakaoTalkId: 'kakao-user-1',
|
||||
kakaoTalkNickname: '프리리',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
});
|
||||
expect(segments).toEqual([
|
||||
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
|
||||
expect.objectContaining({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('대표 계정 변경 완료'),
|
||||
}),
|
||||
]);
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('대표 계정: 프리리#KR1'),
|
||||
});
|
||||
});
|
||||
|
||||
it('asks users to register the Riot account first when not found', async () => {
|
||||
const handler = makeHandler({
|
||||
changePrimaryRiotAccount: jest
|
||||
.fn()
|
||||
.mockRejectedValue(
|
||||
new DakaoUserError('riot_account_not_found', '프리리#KR1'),
|
||||
),
|
||||
});
|
||||
|
||||
const segments = await handler.handle(baseParams);
|
||||
|
||||
expect(segments).toEqual([
|
||||
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
|
||||
expect.objectContaining({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('먼저 !내전 계정등록'),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { DakaoSegment } from '../dakao.types';
|
||||
import { DakaoUserError, DakaoUserService } from '../dakao-user.service';
|
||||
|
||||
interface PrimaryAccountChangeHandlerParams {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
senderUserId: string;
|
||||
senderNickname: string;
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class PrimaryAccountChangeHandler {
|
||||
constructor(private readonly dakaoUserService: DakaoUserService) {}
|
||||
|
||||
public async handle(
|
||||
params: PrimaryAccountChangeHandlerParams,
|
||||
): Promise<DakaoSegment[]> {
|
||||
try {
|
||||
const resolved = await this.dakaoUserService.changePrimaryRiotAccount({
|
||||
communityId: params.communityId,
|
||||
kakaoTalkId: params.senderUserId,
|
||||
kakaoTalkNickname: params.senderNickname,
|
||||
gameName: params.gameName,
|
||||
tagLine: params.tagLine,
|
||||
});
|
||||
|
||||
return [
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: params.senderUserId,
|
||||
displayText: params.senderNickname,
|
||||
},
|
||||
{
|
||||
kind: 'text',
|
||||
text:
|
||||
` 대표 계정 변경 완료` +
|
||||
`\n대표 계정: ${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}`,
|
||||
},
|
||||
];
|
||||
} catch (err) {
|
||||
if (err instanceof DakaoUserError) {
|
||||
return this.errorReply(params, this.translateUserError(err));
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private errorReply(
|
||||
params: PrimaryAccountChangeHandlerParams,
|
||||
message: string,
|
||||
): DakaoSegment[] {
|
||||
return [
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: params.senderUserId,
|
||||
displayText: params.senderNickname,
|
||||
},
|
||||
{ kind: 'text', text: ` ${message}` },
|
||||
];
|
||||
}
|
||||
|
||||
private translateUserError(err: DakaoUserError): string {
|
||||
switch (err.code) {
|
||||
case 'invalid_project_id':
|
||||
return '커뮤니티 식별자가 올바르지 않습니다.';
|
||||
case 'community_not_found':
|
||||
return '연결된 커뮤니티를 찾을 수 없습니다.';
|
||||
case 'riot_account_not_found':
|
||||
return `등록된 라이엇 계정을 찾을 수 없습니다 (${err.detail ?? ''}). 먼저 !내전 계정등록 <닉네임>#<태그> 로 계정을 등록해주세요.`;
|
||||
case 'riot_account_already_registered':
|
||||
return `이미 등록된 라이엇 계정이 있습니다 (${err.detail ?? ''}).`;
|
||||
case 'riot_account_conflict':
|
||||
return `이미 다른 사용자가 등록한 라이엇 계정입니다 (${err.detail ?? ''}).`;
|
||||
case 'riot_account_lookup_failed':
|
||||
return '라이엇 계정 조회 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요.';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,15 +9,17 @@ describe('parseCommand', () => {
|
||||
expect(parseCommand('!내전 리스트')).toEqual({ kind: 'match-list' });
|
||||
});
|
||||
|
||||
it('parses match-list command (일정)', () => {
|
||||
expect(parseCommand('!내전 일정')).toEqual({ kind: 'match-list' });
|
||||
});
|
||||
|
||||
it('parses match-join command with simple riot id', () => {
|
||||
const result = parseCommand(
|
||||
'!내전 신청 69b63bc96da18dfdb218ee8c 프리리#KR1 미드,탑',
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
kind: 'match-join',
|
||||
matchId: '69b63bc96da18dfdb218ee8c',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
matchAndRiotId: '69b63bc96da18dfdb218ee8c 프리리#KR1',
|
||||
});
|
||||
if (result.kind === 'match-join') {
|
||||
expect(result.positions.positions).toEqual(['MID', 'TOP']);
|
||||
@@ -30,12 +32,11 @@ describe('parseCommand', () => {
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
kind: 'match-join',
|
||||
gameName: 'hello world',
|
||||
tagLine: 'KR1',
|
||||
matchAndRiotId: '69b63bc96da18dfdb218ee8c hello world#KR1',
|
||||
});
|
||||
});
|
||||
|
||||
it('normalizes hidden unicode differences in riot id', () => {
|
||||
it('parses hidden unicode differences in riot id input', () => {
|
||||
const decomposedGameName = '프리리'.normalize('NFD');
|
||||
const result = parseCommand(
|
||||
`!내전 신청 69b63bc96da18dfdb218ee8c ${decomposedGameName}\u200B#KR1\uFEFF 미드,탑`,
|
||||
@@ -43,8 +44,72 @@ describe('parseCommand', () => {
|
||||
|
||||
expect(result).toMatchObject({
|
||||
kind: 'match-join',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
matchAndRiotId: `69b63bc96da18dfdb218ee8c ${decomposedGameName}\u200B#KR1`,
|
||||
});
|
||||
});
|
||||
|
||||
it('parses match-join command without explicit match id', () => {
|
||||
const result = parseCommand('!내전 신청 프리리#KR1 미드,탑');
|
||||
expect(result).toMatchObject({
|
||||
kind: 'match-join',
|
||||
matchAndRiotId: '프리리#KR1',
|
||||
});
|
||||
});
|
||||
|
||||
it('parses match-join command with title prefix', () => {
|
||||
const result = parseCommand('!내전 신청 저녁 프리리#KR1 미드,탑');
|
||||
expect(result).toMatchObject({
|
||||
kind: 'match-join',
|
||||
matchAndRiotId: '저녁 프리리#KR1',
|
||||
});
|
||||
});
|
||||
|
||||
it('parses abbreviated match-join command with only match code', () => {
|
||||
expect(parseCommand('!내전 신청 cab1')).toEqual({
|
||||
kind: 'match-join',
|
||||
matchAndRiotId: 'cab1',
|
||||
});
|
||||
});
|
||||
|
||||
it('parses match-join command with registered account and explicit positions', () => {
|
||||
const result = parseCommand('!내전 신청 cab1 미드,서포터');
|
||||
expect(result).toMatchObject({
|
||||
kind: 'match-join',
|
||||
matchAndRiotId: 'cab1',
|
||||
});
|
||||
if (result.kind === 'match-join') {
|
||||
expect(result.positions?.positions).toEqual(['MID', 'SUP']);
|
||||
}
|
||||
});
|
||||
|
||||
it('parses preferred position registration command', () => {
|
||||
const result = parseCommand('!내전 선호포지션등록 미드,SPT');
|
||||
expect(result).toMatchObject({
|
||||
kind: 'preferred-position-register',
|
||||
});
|
||||
if (result.kind === 'preferred-position-register') {
|
||||
expect(result.positions.positions).toEqual(['MID', 'SUP']);
|
||||
}
|
||||
});
|
||||
|
||||
it('parses match-cancel command (취소)', () => {
|
||||
expect(parseCommand('!내전 취소 69b63bc96da18dfdb218ee8c')).toEqual({
|
||||
kind: 'match-cancel',
|
||||
matchId: '69b63bc96da18dfdb218ee8c',
|
||||
});
|
||||
});
|
||||
|
||||
it('parses match-cancel command (참가취소)', () => {
|
||||
expect(parseCommand('!내전 참가취소 69b63bc96da18dfdb218ee8c')).toEqual({
|
||||
kind: 'match-cancel',
|
||||
matchId: '69b63bc96da18dfdb218ee8c',
|
||||
});
|
||||
});
|
||||
|
||||
it('parses match-cancel command with short code', () => {
|
||||
expect(parseCommand('!내전 취소 AB12')).toEqual({
|
||||
kind: 'match-cancel',
|
||||
matchId: 'AB12',
|
||||
});
|
||||
});
|
||||
|
||||
@@ -56,6 +121,25 @@ describe('parseCommand', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('parses primary account change command', () => {
|
||||
expect(parseCommand('!내전 대표계정변경 프리리#KR1')).toEqual({
|
||||
kind: 'primary-account-change',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
});
|
||||
});
|
||||
|
||||
it('normalizes primary account change riot id', () => {
|
||||
const decomposedGameName = '프리리'.normalize('NFD');
|
||||
expect(
|
||||
parseCommand(`!내전 대표계정변경 ${decomposedGameName}\u200B#KR1\uFEFF`),
|
||||
).toEqual({
|
||||
kind: 'primary-account-change',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
});
|
||||
});
|
||||
|
||||
it('normalizes account register riot id', () => {
|
||||
const decomposedGameName = '프리리'.normalize('NFD');
|
||||
expect(
|
||||
@@ -75,16 +159,22 @@ describe('parseCommand', () => {
|
||||
expect(() => parseCommand('!내전 폭파')).toThrow(/unknown_command/);
|
||||
});
|
||||
|
||||
it('throws invalid_match_id for non-objectid match', () => {
|
||||
expect(() =>
|
||||
it('allows non-objectid join match reference for title matching', () => {
|
||||
expect(
|
||||
parseCommand('!내전 신청 not-an-id 프리리#KR1 미드,탑'),
|
||||
).toThrow(/invalid_match_id/);
|
||||
).toMatchObject({
|
||||
kind: 'match-join',
|
||||
matchAndRiotId: 'not-an-id 프리리#KR1',
|
||||
});
|
||||
});
|
||||
|
||||
it('throws invalid_riot_id when # missing', () => {
|
||||
expect(() =>
|
||||
parseCommand('!내전 신청 69b63bc96da18dfdb218ee8c 프리리 미드,탑'),
|
||||
).toThrow(/invalid_riot_id/);
|
||||
it('allows match-join without riot id for registered-account flow', () => {
|
||||
expect(
|
||||
parseCommand('!내전 신청 69b63bc96da18dfdb218ee8c 미드,탑'),
|
||||
).toMatchObject({
|
||||
kind: 'match-join',
|
||||
matchAndRiotId: '69b63bc96da18dfdb218ee8c',
|
||||
});
|
||||
});
|
||||
|
||||
it('throws invalid_position for too few positions', () => {
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { ParsedPositions, parsePositionList } from './position.parser';
|
||||
import {
|
||||
ParsedPositions,
|
||||
isPositionAlias,
|
||||
parsePositionList,
|
||||
} from './position.parser';
|
||||
import { normalizeRiotIdPart } from '../riot-id.util';
|
||||
|
||||
export type DakaoCommand =
|
||||
@@ -9,10 +13,21 @@ export type DakaoCommand =
|
||||
tagLine: string;
|
||||
}
|
||||
| {
|
||||
kind: 'match-join';
|
||||
matchId: string;
|
||||
kind: 'primary-account-change';
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
}
|
||||
| {
|
||||
kind: 'match-join';
|
||||
matchAndRiotId: string;
|
||||
positions?: ParsedPositions;
|
||||
}
|
||||
| {
|
||||
kind: 'match-cancel';
|
||||
matchId: string;
|
||||
}
|
||||
| {
|
||||
kind: 'preferred-position-register';
|
||||
positions: ParsedPositions;
|
||||
};
|
||||
|
||||
@@ -51,17 +66,44 @@ export function parseCommand(rawMessage: string): DakaoCommand {
|
||||
switch (subCommand) {
|
||||
case '목록':
|
||||
case '리스트':
|
||||
case '일정':
|
||||
return { kind: 'match-list' };
|
||||
case '신청':
|
||||
return parseJoinArgs(args);
|
||||
case '취소':
|
||||
case '참가취소':
|
||||
return parseCancelArgs(args);
|
||||
case '계정등록':
|
||||
return parseAccountRegisterArgs(args);
|
||||
case '대표계정변경':
|
||||
return parsePrimaryAccountChangeArgs(args);
|
||||
case '선호포지션등록':
|
||||
case '포지션등록':
|
||||
return parsePreferredPositionRegisterArgs(args);
|
||||
default:
|
||||
throw new CommandParseError('unknown_command', subCommand);
|
||||
}
|
||||
}
|
||||
|
||||
function parseAccountRegisterArgs(args: string): DakaoCommand {
|
||||
const riotId = parseRiotIdArgs(args);
|
||||
return {
|
||||
kind: 'account-register',
|
||||
gameName: riotId.gameName,
|
||||
tagLine: riotId.tagLine,
|
||||
};
|
||||
}
|
||||
|
||||
function parsePrimaryAccountChangeArgs(args: string): DakaoCommand {
|
||||
const riotId = parseRiotIdArgs(args);
|
||||
return {
|
||||
kind: 'primary-account-change',
|
||||
gameName: riotId.gameName,
|
||||
tagLine: riotId.tagLine,
|
||||
};
|
||||
}
|
||||
|
||||
function parseRiotIdArgs(args: string): { gameName: string; tagLine: string } {
|
||||
if (args.length === 0) {
|
||||
throw new CommandParseError('usage');
|
||||
}
|
||||
@@ -77,71 +119,84 @@ function parseAccountRegisterArgs(args: string): DakaoCommand {
|
||||
throw new CommandParseError('invalid_riot_id', args);
|
||||
}
|
||||
|
||||
return { gameName, tagLine };
|
||||
}
|
||||
|
||||
function parseCancelArgs(args: string): DakaoCommand {
|
||||
const matchId = args.trim();
|
||||
if (matchId.length === 0) {
|
||||
throw new CommandParseError('usage');
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'account-register',
|
||||
gameName,
|
||||
tagLine,
|
||||
kind: 'match-cancel',
|
||||
matchId,
|
||||
};
|
||||
}
|
||||
|
||||
function parseJoinArgs(args: string): DakaoCommand {
|
||||
if (args.length === 0) {
|
||||
throw new CommandParseError('usage');
|
||||
const trimmed = args.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return { kind: 'match-join', matchAndRiotId: '' };
|
||||
}
|
||||
|
||||
// 마지막 토큰이 포지션 리스트(쉼표 포함). 그 앞이 라이엇 ID(공백 포함 가능). 그 앞이 matchId.
|
||||
// 형식: <matchId> <gameName...>#<tagLine> <pos1>,<pos2>...
|
||||
// 마지막 토큰이 포지션 리스트(쉼표 포함). 그 앞은 내전 식별자(선택)와 라이엇 ID.
|
||||
// 형식: [<matchId|title...>] <gameName...>#<tagLine> <pos1>,<pos2>...
|
||||
// 끝에서부터 토큰을 분리해 안정적으로 파싱한다.
|
||||
const lastSpace = args.lastIndexOf(' ');
|
||||
const lastSpace = trimmed.lastIndexOf(' ');
|
||||
if (lastSpace === -1) {
|
||||
throw new CommandParseError('usage');
|
||||
}
|
||||
const positionPart = args.slice(lastSpace + 1).trim();
|
||||
const head = args.slice(0, lastSpace).trim();
|
||||
if (positionPart.length === 0 || head.length === 0) {
|
||||
throw new CommandParseError('usage');
|
||||
const singlePartPositions = tryParseTrailingPositions(trimmed);
|
||||
if (singlePartPositions) {
|
||||
return {
|
||||
kind: 'match-join',
|
||||
matchAndRiotId: '',
|
||||
positions: singlePartPositions,
|
||||
};
|
||||
}
|
||||
return { kind: 'match-join', matchAndRiotId: trimmed };
|
||||
}
|
||||
|
||||
const headSpace = head.indexOf(' ');
|
||||
if (headSpace === -1) {
|
||||
throw new CommandParseError('usage');
|
||||
}
|
||||
const matchId = head.slice(0, headSpace).trim();
|
||||
const riotId = head.slice(headSpace + 1).trim();
|
||||
|
||||
if (!isObjectIdHex(matchId)) {
|
||||
throw new CommandParseError('invalid_match_id', matchId);
|
||||
}
|
||||
|
||||
const hashIndex = riotId.lastIndexOf('#');
|
||||
if (hashIndex <= 0 || hashIndex === riotId.length - 1) {
|
||||
throw new CommandParseError('invalid_riot_id', riotId);
|
||||
}
|
||||
const gameName = normalizeRiotIdPart(riotId.slice(0, hashIndex));
|
||||
const tagLine = normalizeRiotIdPart(riotId.slice(hashIndex + 1));
|
||||
if (gameName.length === 0 || tagLine.length === 0) {
|
||||
throw new CommandParseError('invalid_riot_id', riotId);
|
||||
}
|
||||
|
||||
let positions: ParsedPositions;
|
||||
try {
|
||||
positions = parsePositionList(positionPart);
|
||||
} catch (err) {
|
||||
throw new CommandParseError(
|
||||
'invalid_position',
|
||||
(err as Error)?.message ?? positionPart,
|
||||
);
|
||||
const trailingPart = trimmed.slice(lastSpace + 1).trim();
|
||||
const matchAndRiotId = trimmed.slice(0, lastSpace).trim();
|
||||
const positions = tryParseTrailingPositions(trailingPart);
|
||||
if (positions) {
|
||||
if (!matchAndRiotId) throw new CommandParseError('usage');
|
||||
return {
|
||||
kind: 'match-join',
|
||||
matchAndRiotId,
|
||||
positions,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'match-join',
|
||||
matchId,
|
||||
gameName,
|
||||
tagLine,
|
||||
positions,
|
||||
matchAndRiotId: trimmed,
|
||||
};
|
||||
}
|
||||
|
||||
function isObjectIdHex(value: string): boolean {
|
||||
return /^[a-f0-9]{24}$/i.test(value);
|
||||
function parsePreferredPositionRegisterArgs(args: string): DakaoCommand {
|
||||
if (args.trim().length === 0) {
|
||||
throw new CommandParseError('usage');
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'preferred-position-register',
|
||||
positions: parsePositionsOrThrow(args),
|
||||
};
|
||||
}
|
||||
|
||||
function tryParseTrailingPositions(input: string): ParsedPositions | undefined {
|
||||
if (!input.includes(',') && !isPositionAlias(input)) return undefined;
|
||||
return parsePositionsOrThrow(input);
|
||||
}
|
||||
|
||||
function parsePositionsOrThrow(input: string): ParsedPositions {
|
||||
try {
|
||||
return parsePositionList(input);
|
||||
} catch (err) {
|
||||
throw new CommandParseError(
|
||||
'invalid_position',
|
||||
(err as Error)?.message ?? input,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ describe('parsePositionList', () => {
|
||||
});
|
||||
|
||||
it('parses english aliases case-insensitively', () => {
|
||||
const result = parsePositionList('JGL, sup');
|
||||
const result = parsePositionList('JGL, SPT');
|
||||
expect(result.positions).toEqual(['JGL', 'SUP']);
|
||||
});
|
||||
|
||||
|
||||
@@ -26,6 +26,8 @@ const POSITION_ALIASES: Record<string, Position> = {
|
||||
// SUP
|
||||
sup: 'SUP',
|
||||
supp: 'SUP',
|
||||
spt: 'SUP',
|
||||
sp: 'SUP',
|
||||
support: 'SUP',
|
||||
서폿: 'SUP',
|
||||
서포터: 'SUP',
|
||||
@@ -71,7 +73,7 @@ export function parsePositionList(input: string): ParsedPositions {
|
||||
const seen = new Set<Position>();
|
||||
|
||||
for (const token of tokens) {
|
||||
const key = token.toLowerCase().replace(/\s+/g, '');
|
||||
const key = normalizePositionAlias(token);
|
||||
const mapped = POSITION_ALIASES[key];
|
||||
if (!mapped) {
|
||||
throw new PositionParseError('unknown', token);
|
||||
@@ -85,3 +87,11 @@ export function parsePositionList(input: string): ParsedPositions {
|
||||
|
||||
return { positions };
|
||||
}
|
||||
|
||||
export function isPositionAlias(input: string): boolean {
|
||||
return Boolean(POSITION_ALIASES[normalizePositionAlias(input)]);
|
||||
}
|
||||
|
||||
function normalizePositionAlias(input: string): string {
|
||||
return input.toLowerCase().replace(/\s+/g, '');
|
||||
}
|
||||
@@ -7,7 +7,7 @@ describe('resolveMongoDbName', () => {
|
||||
|
||||
it('uses isolated databases for non-production environments', () => {
|
||||
expect(resolveMongoDbName('dev')).toBe('lolympus-dev');
|
||||
expect(resolveMongoDbName('test')).toBe('lolympus-test');
|
||||
expect(resolveMongoDbName('staging')).toBe('lolympus-staging');
|
||||
expect(resolveMongoDbName('')).toBe('lolympus-dev');
|
||||
expect(resolveMongoDbName('local')).toBe('lolympus-dev');
|
||||
});
|
||||
|
||||
@@ -5,7 +5,7 @@ import { tournamentModelDefinitions, TournamentModelTypes } from './schema';
|
||||
|
||||
export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string {
|
||||
if (nodeEnv === 'prod') return 'lolympus';
|
||||
if (nodeEnv === 'test') return 'lolympus-test';
|
||||
if (nodeEnv === 'staging') return 'lolympus-staging';
|
||||
return 'lolympus-dev';
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import mongoose from 'mongoose';
|
||||
import { AppModule } from '../../../../app.module';
|
||||
import { ConnectionService } from '../connection.service';
|
||||
import { MatchStatsService } from '../../../community-stats/match-stats.service';
|
||||
|
||||
interface Options {
|
||||
communityId?: mongoose.Types.ObjectId;
|
||||
dryRun: boolean;
|
||||
force: boolean;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
const app = await NestFactory.createApplicationContext(AppModule, {
|
||||
logger: ['log', 'warn', 'error'],
|
||||
});
|
||||
|
||||
try {
|
||||
const connectionService = app.get(ConnectionService);
|
||||
const matchStatsService = app.get(MatchStatsService);
|
||||
const MatchModel = await connectionService.getModel('match');
|
||||
const MatchStatsModel = await connectionService.getModel('matchStats');
|
||||
|
||||
const filter: Record<string, unknown> = {
|
||||
status: { $in: ['finished', 'in-progress'] },
|
||||
'result.games.0': { $exists: true },
|
||||
};
|
||||
if (options.communityId) filter.communityId = options.communityId;
|
||||
|
||||
const matches = await MatchModel.find(filter)
|
||||
.sort({ scheduledAt: -1 })
|
||||
.select({ _id: 1 })
|
||||
.exec();
|
||||
console.log(`match_stats backfill target=${matches.length}`);
|
||||
|
||||
let processed = 0;
|
||||
let skipped = 0;
|
||||
let failed = 0;
|
||||
|
||||
for (const match of matches) {
|
||||
if (!options.force) {
|
||||
const existing = await MatchStatsModel.exists({ matchId: match._id });
|
||||
if (existing) {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (options.dryRun) {
|
||||
processed += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
await matchStatsService.buildAndUpsert(match._id);
|
||||
processed += 1;
|
||||
} catch (error) {
|
||||
failed += 1;
|
||||
console.warn(
|
||||
`failed ${match._id.toString()}: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
}
|
||||
|
||||
if ((processed + skipped + failed) % 50 === 0) {
|
||||
console.log(
|
||||
`progress processed=${processed} skipped=${skipped} failed=${failed}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(
|
||||
`done processed=${processed} skipped=${skipped} failed=${failed}`,
|
||||
);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
}
|
||||
|
||||
function parseArgs(args: string[]): Options {
|
||||
const options: Options = { dryRun: false, force: false };
|
||||
for (let index = 0; index < args.length; index += 1) {
|
||||
const arg = args[index];
|
||||
if (arg === '--dry-run') options.dryRun = true;
|
||||
if (arg === '--force') options.force = true;
|
||||
if (arg === '--community-id') {
|
||||
const value = args[index + 1];
|
||||
if (!value || !mongoose.isValidObjectId(value)) {
|
||||
throw new Error('--community-id requires a valid ObjectId');
|
||||
}
|
||||
options.communityId = new mongoose.Types.ObjectId(value);
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
void main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,574 @@
|
||||
import 'reflect-metadata';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import mongoose from 'mongoose';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
import { ConnectionService, resolveMongoDbName } from '../connection.service';
|
||||
import type {
|
||||
MatchGameResult,
|
||||
MatchParticipant,
|
||||
MatchSeriesResult,
|
||||
MatchTeam,
|
||||
Position,
|
||||
PositionPreference,
|
||||
TeamSide,
|
||||
TierInfo,
|
||||
} from '../schema';
|
||||
import { SecretModule } from '../../secret/secret.module';
|
||||
|
||||
const TEMP_JOB_ID = 'temp-finished-30-players-6-teams';
|
||||
const TEAM_COUNT = 6;
|
||||
const TEAM_SIZE = 5;
|
||||
const TOTAL_PLAYERS = TEAM_COUNT * TEAM_SIZE;
|
||||
const GAME_COUNT_PER_SERIES_GROUP = 5;
|
||||
const POSITIONS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
|
||||
const CHAMPION_IDS = [
|
||||
266, 64, 103, 222, 412, 24, 421, 134, 145, 497, 58, 121, 777, 202, 111, 39,
|
||||
120, 7, 81, 89, 114, 104, 157, 51, 432, 92, 234, 61, 21, 53,
|
||||
];
|
||||
|
||||
interface CliOptions {
|
||||
communityId?: string;
|
||||
dryRun: boolean;
|
||||
nodeEnv: string;
|
||||
replace: boolean;
|
||||
scheduledAt: Date;
|
||||
title: string;
|
||||
}
|
||||
|
||||
interface TempPlayer {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
puuid: string;
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
profileIconId: number;
|
||||
tier: TierInfo;
|
||||
preferredPositions: PositionPreference[];
|
||||
}
|
||||
|
||||
interface CommunityLean {
|
||||
_id: mongoose.Types.ObjectId;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
isGlobal: true,
|
||||
envFilePath: [
|
||||
resolve(__dirname, '../../../../../../project.env'),
|
||||
resolve(process.cwd(), '../project.env'),
|
||||
resolve(process.cwd(), 'apps/project.env'),
|
||||
resolve(process.cwd(), 'project.env'),
|
||||
],
|
||||
}),
|
||||
SecretModule,
|
||||
],
|
||||
providers: [ConnectionService],
|
||||
})
|
||||
class TempSeedModule {}
|
||||
|
||||
async function loadMachineEnvFile() {
|
||||
const homeDir = process.env.HOME ?? process.env.USERPROFILE;
|
||||
if (!homeDir) return;
|
||||
|
||||
const machineEnvFile = resolve(homeDir, 'source/global-env-vars.txt');
|
||||
|
||||
try {
|
||||
const file = await readFile(machineEnvFile, 'utf8');
|
||||
for (const rawLine of file.split(/\r?\n/)) {
|
||||
const line = rawLine.trim();
|
||||
if (!line || line.startsWith('#')) continue;
|
||||
|
||||
const matched = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
|
||||
if (!matched) continue;
|
||||
|
||||
const [, key, rawValue] = matched;
|
||||
process.env[key] = rawValue.replace(/^["']|["']$/g, '');
|
||||
}
|
||||
} catch {
|
||||
// 로컬 machine env 파일이 없으면 그냥 지나간다.
|
||||
}
|
||||
}
|
||||
|
||||
function parseArgs(argv: string[]): CliOptions {
|
||||
let communityId =
|
||||
process.env.VITE_DEFAULT_COMMUNITY_ID ?? process.env.DEFAULT_COMMUNITY_ID;
|
||||
let dryRun = false;
|
||||
let nodeEnv = process.env.NODE_ENV ?? 'dev';
|
||||
let replace = false;
|
||||
let scheduledAt = new Date(Date.now() - 24 * 60 * 60 * 1000);
|
||||
let title = `결과 검증 임시 내전 30인 6팀 ${formatStamp(new Date())}`;
|
||||
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const arg = argv[index];
|
||||
if (arg === '--community-id') {
|
||||
const value = argv[index + 1];
|
||||
if (!value) throw new Error('--community-id requires an ObjectId.');
|
||||
communityId = value;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith('--community-id=')) {
|
||||
communityId = arg.slice('--community-id='.length);
|
||||
continue;
|
||||
}
|
||||
if (arg === '--dry-run') {
|
||||
dryRun = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--env') {
|
||||
const value = argv[index + 1];
|
||||
if (!value) throw new Error('--env requires dev, staging, or prod.');
|
||||
nodeEnv = value;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith('--env=')) {
|
||||
nodeEnv = arg.slice('--env='.length);
|
||||
continue;
|
||||
}
|
||||
if (arg === '--replace') {
|
||||
replace = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--scheduled-at') {
|
||||
scheduledAt = parseDateArg(argv[index + 1], '--scheduled-at');
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith('--scheduled-at=')) {
|
||||
scheduledAt = parseDateArg(
|
||||
arg.slice('--scheduled-at='.length),
|
||||
'--scheduled-at',
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (arg === '--title') {
|
||||
const value = argv[index + 1];
|
||||
if (!value) throw new Error('--title requires a value.');
|
||||
title = value;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith('--title=')) {
|
||||
title = arg.slice('--title='.length);
|
||||
continue;
|
||||
}
|
||||
if (arg === '--help' || arg === '-h') {
|
||||
printHelp();
|
||||
process.exit(0);
|
||||
}
|
||||
throw new Error(`Unknown argument: ${arg}`);
|
||||
}
|
||||
|
||||
if (!['dev', 'staging', 'prod'].includes(nodeEnv)) {
|
||||
throw new Error('--env must be dev, staging, or prod.');
|
||||
}
|
||||
if (communityId && !mongoose.isValidObjectId(communityId)) {
|
||||
throw new Error('--community-id must be a valid ObjectId.');
|
||||
}
|
||||
|
||||
return {
|
||||
communityId: communityId?.trim() || undefined,
|
||||
dryRun,
|
||||
nodeEnv,
|
||||
replace,
|
||||
scheduledAt,
|
||||
title,
|
||||
};
|
||||
}
|
||||
|
||||
function parseDateArg(value: string | undefined, label: string): Date {
|
||||
if (!value) throw new Error(`${label} requires an ISO date value.`);
|
||||
const parsed = new Date(value);
|
||||
if (Number.isNaN(parsed.getTime())) {
|
||||
throw new Error(`${label} must be a valid ISO date value.`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function printHelp() {
|
||||
console.log(`Usage:
|
||||
pnpm --filter api exec ts-node src/modules/global/database/dev-seeds/create-temp-finished-match.ts
|
||||
pnpm --filter api exec ts-node src/modules/global/database/dev-seeds/create-temp-finished-match.ts --replace
|
||||
|
||||
Options:
|
||||
--community-id <id> Community ObjectId. Defaults to env or first community.
|
||||
--dry-run Print the payload summary without writing.
|
||||
--env <env> dev | staging | prod. Default: NODE_ENV or dev.
|
||||
--replace Delete previous temp matches created by this script first.
|
||||
--scheduled-at <iso> Scheduled date. Default: yesterday.
|
||||
--title <title> Match title. Default: timestamped temp title.
|
||||
`);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
process.env.NODE_ENV = options.nodeEnv;
|
||||
await loadMachineEnvFile();
|
||||
|
||||
const app = await NestFactory.createApplicationContext(TempSeedModule, {
|
||||
logger: ['log', 'warn', 'error'],
|
||||
});
|
||||
|
||||
try {
|
||||
const connectionService = app.get(ConnectionService);
|
||||
const CommunityModel = await connectionService.getModel('community');
|
||||
const MatchModel = await connectionService.getModel('match');
|
||||
const community = await resolveCommunity(
|
||||
CommunityModel,
|
||||
options.communityId,
|
||||
);
|
||||
|
||||
const payload = buildMatchPayload(community._id, options);
|
||||
|
||||
console.log(
|
||||
`[temp result seed] mode=${options.dryRun ? 'dry-run' : 'apply'} env=${options.nodeEnv} db=${resolveMongoDbName(options.nodeEnv)}`,
|
||||
);
|
||||
console.log(
|
||||
`[temp result seed] community=${community.name ?? '(unnamed)'} (${community._id.toString()})`,
|
||||
);
|
||||
console.log(
|
||||
`[temp result seed] title="${options.title}" participants=${payload.participants.length} teams=${payload.teams.length} games=${payload.result.games.length}`,
|
||||
);
|
||||
|
||||
if (options.dryRun) {
|
||||
console.log('[temp result seed] No writes were made.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (options.replace) {
|
||||
const deleteResult = await MatchModel.deleteMany({
|
||||
communityId: community._id,
|
||||
'legacyImportSource.jobId': TEMP_JOB_ID,
|
||||
}).exec();
|
||||
console.log(
|
||||
`[temp result seed] deleted=${deleteResult.deletedCount ?? 0}`,
|
||||
);
|
||||
}
|
||||
|
||||
const match = await MatchModel.create(payload);
|
||||
console.log(`[temp result seed] created=${match._id.toString()}`);
|
||||
console.log(`[temp result seed] route=/match/${match._id.toString()}`);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveCommunity(
|
||||
CommunityModel: mongoose.Model<unknown>,
|
||||
communityId?: string,
|
||||
): Promise<CommunityLean> {
|
||||
const community = communityId
|
||||
? await CommunityModel.findById(communityId)
|
||||
.select({ name: 1 })
|
||||
.lean<CommunityLean>()
|
||||
.exec()
|
||||
: await CommunityModel.findOne()
|
||||
.sort({ createdAt: 1 })
|
||||
.select({ name: 1 })
|
||||
.lean<CommunityLean>()
|
||||
.exec();
|
||||
|
||||
if (!community) {
|
||||
throw new Error(
|
||||
communityId
|
||||
? `Community not found: ${communityId}`
|
||||
: 'No community found. Pass --community-id.',
|
||||
);
|
||||
}
|
||||
|
||||
return community;
|
||||
}
|
||||
|
||||
function buildMatchPayload(
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
options: CliOptions,
|
||||
) {
|
||||
const now = new Date();
|
||||
const players = buildPlayers(now);
|
||||
const participants = players.map(
|
||||
(player, index): MatchParticipant => ({
|
||||
userId: player.userId,
|
||||
puuid: player.puuid,
|
||||
gameName: player.gameName,
|
||||
tagLine: player.tagLine,
|
||||
profileIconId: player.profileIconId,
|
||||
tier: player.tier,
|
||||
preferredPositions: player.preferredPositions,
|
||||
joinedAt: new Date(
|
||||
options.scheduledAt.getTime() - (TOTAL_PLAYERS - index) * 60000,
|
||||
),
|
||||
excluded: false,
|
||||
}),
|
||||
);
|
||||
const teams = buildTeams(players);
|
||||
const games = buildGames(players, options.scheduledAt);
|
||||
const seriesResults = buildSeriesResults(games);
|
||||
const winnerTeamIndex = resolveOverallWinner(seriesResults);
|
||||
|
||||
return {
|
||||
communityId,
|
||||
title: options.title,
|
||||
description:
|
||||
'결과 페이지 검증용으로 생성된 30명, 6팀, 15경기 완료 임시 데이터입니다.',
|
||||
mapId: 11,
|
||||
status: 'finished',
|
||||
scheduledAt: options.scheduledAt,
|
||||
maxParticipants: TOTAL_PLAYERS,
|
||||
gameCount: GAME_COUNT_PER_SERIES_GROUP,
|
||||
gameMode: 'round-robin',
|
||||
tournamentCodeIds: [],
|
||||
teamBuiltAt: new Date(options.scheduledAt.getTime() - 30 * 60000),
|
||||
participants,
|
||||
teams,
|
||||
result: {
|
||||
winnerTeamIndex,
|
||||
mvpUserId: players[0].userId,
|
||||
riotMatchIds: games.map((game) => game.riotMatchId),
|
||||
games,
|
||||
seriesResults,
|
||||
},
|
||||
resultPollState: {
|
||||
startedAt: new Date(options.scheduledAt.getTime() + 2 * 60 * 60 * 1000),
|
||||
lastPolledAt: now,
|
||||
lastPollOutcome: 'matched',
|
||||
matchedCount: games.length,
|
||||
expandedToAllPuuids: true,
|
||||
state: 'complete',
|
||||
},
|
||||
legacyImported: true,
|
||||
legacyImportSource: {
|
||||
importedAt: now,
|
||||
importedBy: players[0].userId,
|
||||
triggeringPuuid: players[0].puuid,
|
||||
jobId: TEMP_JOB_ID,
|
||||
},
|
||||
prizes: ['1등 팀: 결과 화면 검증용 임시 상품', 'MVP: Temp01'],
|
||||
notices: ['이 매치는 UI 검증용 임시 데이터입니다.'],
|
||||
schedule: [
|
||||
{ time: '20:00', label: '로비 오픈' },
|
||||
{ time: '20:10', label: '1경기 시작' },
|
||||
{ time: '23:30', label: '풀리그 종료' },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function buildPlayers(now: Date): TempPlayer[] {
|
||||
return Array.from({ length: TOTAL_PLAYERS }, (_, index) => {
|
||||
const playerNumber = index + 1;
|
||||
const primaryPosition = POSITIONS[index % POSITIONS.length];
|
||||
|
||||
return {
|
||||
userId: new mongoose.Types.ObjectId(),
|
||||
puuid: `temp-result-puuid-${playerNumber.toString().padStart(2, '0')}`,
|
||||
gameName: `Temp${playerNumber.toString().padStart(2, '0')}`,
|
||||
tagLine: `T${playerNumber.toString().padStart(3, '0')}`,
|
||||
profileIconId: 20 + playerNumber,
|
||||
tier: buildTier(playerNumber, now),
|
||||
preferredPositions: buildPreferredPositions(primaryPosition),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function buildPreferredPositions(
|
||||
primaryPosition: Position,
|
||||
): PositionPreference[] {
|
||||
const ordered = [
|
||||
primaryPosition,
|
||||
...POSITIONS.filter((position) => position !== primaryPosition),
|
||||
];
|
||||
return ordered.map((position, index) => ({
|
||||
position,
|
||||
priority: index + 1,
|
||||
}));
|
||||
}
|
||||
|
||||
function buildTier(playerNumber: number, fetchedAt: Date): TierInfo {
|
||||
const tiers = [
|
||||
['CHALLENGER', 'I'],
|
||||
['GRANDMASTER', 'I'],
|
||||
['MASTER', 'I'],
|
||||
['DIAMOND', 'I'],
|
||||
['DIAMOND', 'II'],
|
||||
['EMERALD', 'I'],
|
||||
['EMERALD', 'II'],
|
||||
['PLATINUM', 'I'],
|
||||
['PLATINUM', 'II'],
|
||||
['GOLD', 'I'],
|
||||
] as const;
|
||||
const [tier, rank] = tiers[(playerNumber - 1) % tiers.length];
|
||||
|
||||
return {
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier,
|
||||
rank,
|
||||
leaguePoints: (playerNumber * 17) % 100,
|
||||
wins: 40 + playerNumber,
|
||||
losses: 22 + (playerNumber % 13),
|
||||
fetchedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function buildTeams(players: TempPlayer[]): MatchTeam[] {
|
||||
return Array.from({ length: TEAM_COUNT }, (_, teamOffset) => {
|
||||
const teamIndex = teamOffset + 1;
|
||||
const members = players
|
||||
.slice(teamOffset * TEAM_SIZE, (teamOffset + 1) * TEAM_SIZE)
|
||||
.map((player, memberOffset) => ({
|
||||
userId: player.userId,
|
||||
assignedPosition: POSITIONS[memberOffset],
|
||||
cost: memberOffset === 0 ? 0 : 80 + teamIndex * 15 + memberOffset * 20,
|
||||
}));
|
||||
|
||||
return {
|
||||
teamIndex,
|
||||
name: `${teamIndex}팀`,
|
||||
captainUserId: members[0]?.userId,
|
||||
members,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function buildGames(
|
||||
players: TempPlayer[],
|
||||
scheduledAt: Date,
|
||||
): MatchGameResult[] {
|
||||
const games: MatchGameResult[] = [];
|
||||
const playersByTeam = new Map<number, TempPlayer[]>();
|
||||
|
||||
for (let teamIndex = 1; teamIndex <= TEAM_COUNT; teamIndex += 1) {
|
||||
playersByTeam.set(
|
||||
teamIndex,
|
||||
players.slice((teamIndex - 1) * TEAM_SIZE, teamIndex * TEAM_SIZE),
|
||||
);
|
||||
}
|
||||
|
||||
for (let teamAIndex = 1; teamAIndex <= TEAM_COUNT; teamAIndex += 1) {
|
||||
for (
|
||||
let teamBIndex = teamAIndex + 1;
|
||||
teamBIndex <= TEAM_COUNT;
|
||||
teamBIndex += 1
|
||||
) {
|
||||
const gameNumber = games.length + 1;
|
||||
const lowerTeamStartsBlue = gameNumber % 2 === 1;
|
||||
const blueTeamIndex = lowerTeamStartsBlue ? teamAIndex : teamBIndex;
|
||||
const redTeamIndex = lowerTeamStartsBlue ? teamBIndex : teamAIndex;
|
||||
const winnerTeamIndex = teamAIndex;
|
||||
const winnerSide: TeamSide =
|
||||
winnerTeamIndex === blueTeamIndex ? 'blue' : 'red';
|
||||
const gameCreation = scheduledAt.getTime() + gameNumber * 20 * 60 * 1000;
|
||||
const riotMatchId = `KR_TEMP_30X6_${formatStamp(scheduledAt)}_${gameNumber
|
||||
.toString()
|
||||
.padStart(2, '0')}`;
|
||||
|
||||
games.push({
|
||||
gameNumber,
|
||||
riotMatchId,
|
||||
blueTeamIndex,
|
||||
redTeamIndex,
|
||||
winnerTeamIndex,
|
||||
winnerSide,
|
||||
gameCreation,
|
||||
gameDuration: 1650 + gameNumber * 23,
|
||||
participants: [
|
||||
...buildGameParticipants({
|
||||
players: playersByTeam.get(blueTeamIndex) ?? [],
|
||||
teamIndex: blueTeamIndex,
|
||||
side: 'blue',
|
||||
winnerTeamIndex,
|
||||
gameNumber,
|
||||
}),
|
||||
...buildGameParticipants({
|
||||
players: playersByTeam.get(redTeamIndex) ?? [],
|
||||
teamIndex: redTeamIndex,
|
||||
side: 'red',
|
||||
winnerTeamIndex,
|
||||
gameNumber,
|
||||
}),
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return games;
|
||||
}
|
||||
|
||||
function buildGameParticipants(params: {
|
||||
players: TempPlayer[];
|
||||
teamIndex: number;
|
||||
side: TeamSide;
|
||||
winnerTeamIndex: number;
|
||||
gameNumber: number;
|
||||
}): MatchGameResult['participants'] {
|
||||
const didWin = params.teamIndex === params.winnerTeamIndex;
|
||||
|
||||
return params.players.map((player, index) => {
|
||||
const championIndex =
|
||||
(params.gameNumber + params.teamIndex + index) % CHAMPION_IDS.length;
|
||||
return {
|
||||
userId: player.userId,
|
||||
teamIndex: params.teamIndex,
|
||||
side: params.side,
|
||||
championId: CHAMPION_IDS[championIndex],
|
||||
kills: didWin
|
||||
? 4 + ((params.gameNumber + index) % 8)
|
||||
: 1 + ((params.gameNumber + index) % 5),
|
||||
deaths: didWin ? 1 + (index % 4) : 4 + ((params.gameNumber + index) % 7),
|
||||
assists: didWin
|
||||
? 7 + ((params.gameNumber + index) % 12)
|
||||
: 3 + ((params.gameNumber + index) % 8),
|
||||
win: didWin,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function buildSeriesResults(games: MatchGameResult[]): MatchSeriesResult[] {
|
||||
return games.map((game) => {
|
||||
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
|
||||
const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex);
|
||||
|
||||
return {
|
||||
teamAIndex,
|
||||
teamBIndex,
|
||||
teamAWins: game.winnerTeamIndex === teamAIndex ? 1 : 0,
|
||||
teamBWins: game.winnerTeamIndex === teamBIndex ? 1 : 0,
|
||||
winnerTeamIndex: game.winnerTeamIndex,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function resolveOverallWinner(
|
||||
seriesResults: MatchSeriesResult[],
|
||||
): number | undefined {
|
||||
const winsByTeam = new Map<number, number>();
|
||||
for (const series of seriesResults) {
|
||||
if (!series.winnerTeamIndex) continue;
|
||||
winsByTeam.set(
|
||||
series.winnerTeamIndex,
|
||||
(winsByTeam.get(series.winnerTeamIndex) ?? 0) + 1,
|
||||
);
|
||||
}
|
||||
|
||||
return [...winsByTeam.entries()].sort(
|
||||
(left, right) => right[1] - left[1],
|
||||
)[0]?.[0];
|
||||
}
|
||||
|
||||
function formatStamp(date: Date): string {
|
||||
const year = date.getFullYear();
|
||||
const month = `${date.getMonth() + 1}`.padStart(2, '0');
|
||||
const day = `${date.getDate()}`.padStart(2, '0');
|
||||
const hours = `${date.getHours()}`.padStart(2, '0');
|
||||
const minutes = `${date.getMinutes()}`.padStart(2, '0');
|
||||
const seconds = `${date.getSeconds()}`.padStart(2, '0');
|
||||
return `${year}${month}${day}-${hours}${minutes}${seconds}`;
|
||||
}
|
||||
|
||||
void main().catch((error: unknown) => {
|
||||
console.error(error instanceof Error ? error.message : error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
interface MigrationCollection {
|
||||
find(filter: Record<string, unknown>): {
|
||||
limit(limit: number): AsyncIterable<AnyDoc>;
|
||||
};
|
||||
bulkWrite(
|
||||
writes: Array<{
|
||||
updateOne: {
|
||||
filter: { _id: unknown };
|
||||
update: { $set: Record<string, unknown> };
|
||||
};
|
||||
}>,
|
||||
options: { ordered: boolean },
|
||||
): Promise<unknown>;
|
||||
}
|
||||
|
||||
interface MigrationDb {
|
||||
collection(name: string): MigrationCollection;
|
||||
}
|
||||
|
||||
interface MigrationOptions {
|
||||
dryRun?: boolean;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
interface MigrationStats {
|
||||
scannedAuctions: number;
|
||||
changedAuctions: number;
|
||||
}
|
||||
|
||||
type AnyDoc = Record<string, unknown> & { _id: unknown };
|
||||
|
||||
export async function migrateAuctionPassHistory(
|
||||
db: MigrationDb,
|
||||
options: MigrationOptions = {},
|
||||
): Promise<MigrationStats> {
|
||||
const dryRun = options.dryRun ?? true;
|
||||
const stats: MigrationStats = {
|
||||
scannedAuctions: 0,
|
||||
changedAuctions: 0,
|
||||
};
|
||||
const writes: Array<{
|
||||
updateOne: {
|
||||
filter: { _id: unknown };
|
||||
update: { $set: Record<string, unknown> };
|
||||
};
|
||||
}> = [];
|
||||
|
||||
for await (const doc of db.collection('auction').find({}).limit(options.limit ?? 0)) {
|
||||
stats.scannedAuctions += 1;
|
||||
const set: Record<string, unknown> = {};
|
||||
let changed = false;
|
||||
|
||||
if (!Array.isArray(doc.passedQueue)) {
|
||||
set.passedQueue = [];
|
||||
changed = true;
|
||||
}
|
||||
if (typeof doc.auctionRound !== 'number') {
|
||||
set.auctionRound = 1;
|
||||
changed = true;
|
||||
}
|
||||
if (typeof doc.topTierThreshold !== 'string') {
|
||||
set.topTierThreshold = 'NONE';
|
||||
changed = true;
|
||||
}
|
||||
if (!Array.isArray(doc.manualTopTierUserIds)) {
|
||||
set.manualTopTierUserIds = [];
|
||||
changed = true;
|
||||
}
|
||||
|
||||
const order = Array.isArray(doc.order)
|
||||
? doc.order.map((player) => {
|
||||
if (!isRecord(player) || typeof player.passCount === 'number') {
|
||||
return player;
|
||||
}
|
||||
changed = true;
|
||||
return { ...player, passCount: 0 };
|
||||
})
|
||||
: [];
|
||||
if (changed && order.length > 0) set.order = order;
|
||||
if (!changed) continue;
|
||||
|
||||
stats.changedAuctions += 1;
|
||||
writes.push({
|
||||
updateOne: {
|
||||
filter: { _id: doc._id },
|
||||
update: { $set: set },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (!dryRun && writes.length > 0) {
|
||||
await db.collection('auction').bulkWrite(writes, { ordered: false });
|
||||
}
|
||||
|
||||
return stats;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value && typeof value === 'object' && !Array.isArray(value));
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import { migrateTeamIndex } from './20260502-team-index';
|
||||
|
||||
function createDb(params: {
|
||||
auctions?: Array<Record<string, unknown>>;
|
||||
matches?: Array<Record<string, unknown>>;
|
||||
}) {
|
||||
const collections = {
|
||||
auction: params.auctions ?? [],
|
||||
match: params.matches ?? [],
|
||||
};
|
||||
|
||||
return {
|
||||
collections,
|
||||
db: {
|
||||
collection(name: string) {
|
||||
const key = name === 'auction' ? 'auction' : 'match';
|
||||
const docs = collections[key];
|
||||
return {
|
||||
find() {
|
||||
return {
|
||||
limit() {
|
||||
return {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
for (const doc of docs) yield doc;
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
async bulkWrite(writes: Array<{
|
||||
updateOne: {
|
||||
filter: { _id: unknown };
|
||||
update: {
|
||||
$set: Record<string, unknown>;
|
||||
$unset: Record<string, ''>;
|
||||
};
|
||||
};
|
||||
}>) {
|
||||
for (const write of writes) {
|
||||
const doc = docs.find((item) => item._id === write.updateOne.filter._id);
|
||||
if (!doc) continue;
|
||||
Object.assign(doc, write.updateOne.update.$set);
|
||||
for (const key of Object.keys(write.updateOne.update.$unset)) {
|
||||
delete doc[key];
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('migrateTeamIndex', () => {
|
||||
it('migrates auction and match team identity fields', async () => {
|
||||
const { db, collections } = createDb({
|
||||
auctions: [
|
||||
{
|
||||
_id: 'auction-1',
|
||||
teams: [{ side: 'blue', groupIndex: 1 }, { side: 'red', groupIndex: 1 }],
|
||||
bids: [{ side: 'red', groupIndex: 1, amount: 100 }],
|
||||
currentBidder: 'red',
|
||||
currentBidderGroupIndex: 1,
|
||||
},
|
||||
],
|
||||
matches: [
|
||||
{
|
||||
_id: 'match-1',
|
||||
teams: [{ side: 'blue', groupIndex: 1 }, { side: 'red', groupIndex: 1 }],
|
||||
result: {
|
||||
winnerSide: 'blue',
|
||||
blueScore: 1,
|
||||
redScore: 0,
|
||||
games: [
|
||||
{
|
||||
gameNumber: 1,
|
||||
riotMatchId: 'KR_1',
|
||||
winnerSide: 'blue',
|
||||
blueGroupIndex: 1,
|
||||
redGroupIndex: 1,
|
||||
participants: [
|
||||
{ userId: 'u1', side: 'blue' },
|
||||
{ userId: 'u2', side: 'red' },
|
||||
],
|
||||
},
|
||||
],
|
||||
seriesResults: [
|
||||
{
|
||||
blueGroupIndex: 1,
|
||||
redGroupIndex: 1,
|
||||
blueScore: 1,
|
||||
redScore: 0,
|
||||
winnerSide: 'blue',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const stats = await migrateTeamIndex(db, { dryRun: false });
|
||||
|
||||
expect(stats).toEqual({
|
||||
scannedAuctions: 1,
|
||||
changedAuctions: 1,
|
||||
scannedMatches: 1,
|
||||
changedMatches: 1,
|
||||
});
|
||||
expect(collections.auction[0]).toMatchObject({
|
||||
teams: [{ teamIndex: 1 }, { teamIndex: 2 }],
|
||||
bids: [{ teamIndex: 2, amount: 100 }],
|
||||
currentBidderTeamIndex: 2,
|
||||
});
|
||||
expect(collections.match[0]).toMatchObject({
|
||||
teams: [{ teamIndex: 1, name: '1팀' }, { teamIndex: 2, name: '2팀' }],
|
||||
result: {
|
||||
winnerTeamIndex: 1,
|
||||
games: [
|
||||
{
|
||||
blueTeamIndex: 1,
|
||||
redTeamIndex: 2,
|
||||
winnerTeamIndex: 1,
|
||||
participants: [
|
||||
{ teamIndex: 1, side: 'blue' },
|
||||
{ teamIndex: 2, side: 'red' },
|
||||
],
|
||||
},
|
||||
],
|
||||
seriesResults: [
|
||||
{
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 2,
|
||||
teamAWins: 1,
|
||||
teamBWins: 0,
|
||||
winnerTeamIndex: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(collections.auction[0]).not.toHaveProperty('currentBidder');
|
||||
expect(collections.match[0].result).not.toHaveProperty('blueScore');
|
||||
});
|
||||
|
||||
it('is idempotent after applying updates', async () => {
|
||||
const { db } = createDb({
|
||||
matches: [
|
||||
{
|
||||
_id: 'match-1',
|
||||
teams: [{ side: 'blue', groupIndex: 1 }],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await migrateTeamIndex(db, { dryRun: false });
|
||||
const stats = await migrateTeamIndex(db, { dryRun: false });
|
||||
|
||||
expect(stats.changedMatches).toBe(0);
|
||||
expect(stats.changedAuctions).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,335 @@
|
||||
type LegacySide = 'blue' | 'red';
|
||||
|
||||
interface MigrationCollection {
|
||||
find(filter: Record<string, unknown>): {
|
||||
limit(limit: number): AsyncIterable<AnyDoc>;
|
||||
};
|
||||
bulkWrite(
|
||||
writes: Array<{
|
||||
updateOne: {
|
||||
filter: { _id: unknown };
|
||||
update: { $set: Record<string, unknown>; $unset: Record<string, ''> };
|
||||
};
|
||||
}>,
|
||||
options: { ordered: boolean },
|
||||
): Promise<unknown>;
|
||||
}
|
||||
|
||||
interface MigrationDb {
|
||||
collection(name: string): MigrationCollection;
|
||||
}
|
||||
|
||||
interface MigrationOptions {
|
||||
dryRun?: boolean;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
interface MigrationStats {
|
||||
scannedAuctions: number;
|
||||
changedAuctions: number;
|
||||
scannedMatches: number;
|
||||
changedMatches: number;
|
||||
}
|
||||
|
||||
type AnyDoc = Record<string, unknown> & { _id: unknown };
|
||||
|
||||
export async function migrateTeamIndex(
|
||||
db: MigrationDb,
|
||||
options: MigrationOptions = {},
|
||||
): Promise<MigrationStats> {
|
||||
const dryRun = options.dryRun ?? true;
|
||||
const stats: MigrationStats = {
|
||||
scannedAuctions: 0,
|
||||
changedAuctions: 0,
|
||||
scannedMatches: 0,
|
||||
changedMatches: 0,
|
||||
};
|
||||
|
||||
await migrateCollection(db.collection('auction'), options.limit, dryRun, stats, 'auction');
|
||||
await migrateCollection(db.collection('match'), options.limit, dryRun, stats, 'match');
|
||||
|
||||
return stats;
|
||||
}
|
||||
|
||||
async function migrateCollection(
|
||||
collection: MigrationCollection,
|
||||
limit: number | undefined,
|
||||
dryRun: boolean,
|
||||
stats: MigrationStats,
|
||||
kind: 'auction' | 'match',
|
||||
) {
|
||||
const cursor = collection.find({}).limit(limit ?? 0);
|
||||
const writes: Array<{
|
||||
updateOne: {
|
||||
filter: { _id: unknown };
|
||||
update: { $set: Record<string, unknown>; $unset: Record<string, ''> };
|
||||
};
|
||||
}> = [];
|
||||
|
||||
for await (const doc of cursor) {
|
||||
if (kind === 'auction') stats.scannedAuctions += 1;
|
||||
if (kind === 'match') stats.scannedMatches += 1;
|
||||
|
||||
const update = kind === 'auction' ? migrateAuction(doc) : migrateMatch(doc);
|
||||
if (!update) continue;
|
||||
|
||||
if (kind === 'auction') stats.changedAuctions += 1;
|
||||
if (kind === 'match') stats.changedMatches += 1;
|
||||
writes.push({
|
||||
updateOne: {
|
||||
filter: { _id: doc._id },
|
||||
update,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (!dryRun && writes.length > 0) {
|
||||
await collection.bulkWrite(writes, { ordered: false });
|
||||
}
|
||||
}
|
||||
|
||||
function migrateAuction(doc: AnyDoc) {
|
||||
const set: Record<string, unknown> = {};
|
||||
const unset: Record<string, ''> = {};
|
||||
let changed = false;
|
||||
|
||||
const teams = asArray(doc.teams).map((team) => {
|
||||
const migrated = { ...team };
|
||||
const teamIndex = readTeamIndex(migrated);
|
||||
if (teamIndex !== undefined) migrated.teamIndex = teamIndex;
|
||||
if ('side' in migrated || 'groupIndex' in migrated) changed = true;
|
||||
delete migrated.side;
|
||||
delete migrated.groupIndex;
|
||||
return migrated;
|
||||
});
|
||||
if (changed) set.teams = teams;
|
||||
|
||||
const bids = asArray(doc.bids).map((bid) => {
|
||||
const migrated = { ...bid };
|
||||
const teamIndex = readTeamIndex(migrated);
|
||||
if (teamIndex !== undefined) migrated.teamIndex = teamIndex;
|
||||
if ('side' in migrated || 'groupIndex' in migrated) changed = true;
|
||||
delete migrated.side;
|
||||
delete migrated.groupIndex;
|
||||
return migrated;
|
||||
});
|
||||
if (changed) set.bids = bids;
|
||||
|
||||
if (
|
||||
typeof doc.currentBidderTeamIndex !== 'number' &&
|
||||
isSide(doc.currentBidder)
|
||||
) {
|
||||
set.currentBidderTeamIndex = sideGroupToTeamIndex(
|
||||
doc.currentBidder,
|
||||
numberOrDefault(doc.currentBidderGroupIndex, 1),
|
||||
);
|
||||
changed = true;
|
||||
}
|
||||
if ('currentBidder' in doc || 'currentBidderGroupIndex' in doc) {
|
||||
unset.currentBidder = '';
|
||||
unset.currentBidderGroupIndex = '';
|
||||
changed = true;
|
||||
}
|
||||
|
||||
return changed ? { $set: set, $unset: unset } : null;
|
||||
}
|
||||
|
||||
function migrateMatch(doc: AnyDoc) {
|
||||
const set: Record<string, unknown> = {};
|
||||
const unset: Record<string, ''> = {};
|
||||
let changed = false;
|
||||
|
||||
const teams = asArray(doc.teams).map((team) => {
|
||||
const migrated = { ...team };
|
||||
const teamIndex = readTeamIndex(migrated);
|
||||
if (teamIndex !== undefined) migrated.teamIndex = teamIndex;
|
||||
if (!migrated.name && typeof teamIndex === 'number') migrated.name = `${teamIndex}팀`;
|
||||
if ('side' in migrated || 'groupIndex' in migrated) changed = true;
|
||||
delete migrated.side;
|
||||
delete migrated.groupIndex;
|
||||
return migrated;
|
||||
});
|
||||
if (changed) set.teams = teams;
|
||||
|
||||
const result = isRecord(doc.result) ? migrateResult(doc.result) : null;
|
||||
if (result) {
|
||||
set.result = result;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
return changed ? { $set: set, $unset: unset } : null;
|
||||
}
|
||||
|
||||
function migrateResult(result: Record<string, unknown>) {
|
||||
let changed = false;
|
||||
const migrated = { ...result };
|
||||
|
||||
const games = asArray(result.games).map((game) => {
|
||||
const next = { ...game };
|
||||
const blueTeamIndex =
|
||||
numberOrUndefined(next.blueTeamIndex) ??
|
||||
sideGroupToTeamIndex('blue', numberOrDefault(next.blueGroupIndex, 1));
|
||||
const redTeamIndex =
|
||||
numberOrUndefined(next.redTeamIndex) ??
|
||||
sideGroupToTeamIndex('red', numberOrDefault(next.redGroupIndex, 1));
|
||||
const winnerSide = isSide(next.winnerSide) ? next.winnerSide : undefined;
|
||||
const winnerTeamIndex =
|
||||
numberOrUndefined(next.winnerTeamIndex) ??
|
||||
(winnerSide === 'blue'
|
||||
? blueTeamIndex
|
||||
: winnerSide === 'red'
|
||||
? redTeamIndex
|
||||
: undefined);
|
||||
|
||||
next.blueTeamIndex = blueTeamIndex;
|
||||
next.redTeamIndex = redTeamIndex;
|
||||
if (winnerTeamIndex !== undefined) next.winnerTeamIndex = winnerTeamIndex;
|
||||
next.participants = asArray(next.participants).map((participant) => {
|
||||
const migratedParticipant = { ...participant };
|
||||
if (typeof migratedParticipant.teamIndex !== 'number') {
|
||||
migratedParticipant.teamIndex =
|
||||
migratedParticipant.side === 'blue' ? blueTeamIndex : redTeamIndex;
|
||||
}
|
||||
return migratedParticipant;
|
||||
});
|
||||
if ('blueGroupIndex' in next || 'redGroupIndex' in next) changed = true;
|
||||
delete next.blueGroupIndex;
|
||||
delete next.redGroupIndex;
|
||||
return next;
|
||||
});
|
||||
migrated.games = games;
|
||||
|
||||
const seriesResults = asArray(result.seriesResults).map((series) => {
|
||||
if (typeof series.teamAIndex === 'number' && typeof series.teamBIndex === 'number') {
|
||||
return series;
|
||||
}
|
||||
changed = true;
|
||||
const legacyBlueTeamIndex = sideGroupToTeamIndex(
|
||||
'blue',
|
||||
numberOrDefault(series.blueGroupIndex, 1),
|
||||
);
|
||||
const legacyRedTeamIndex = sideGroupToTeamIndex(
|
||||
'red',
|
||||
numberOrDefault(series.redGroupIndex, 1),
|
||||
);
|
||||
const teamAIndex = Math.min(legacyBlueTeamIndex, legacyRedTeamIndex);
|
||||
const teamBIndex = Math.max(legacyBlueTeamIndex, legacyRedTeamIndex);
|
||||
const blueScore = numberOrDefault(series.blueScore, 0);
|
||||
const redScore = numberOrDefault(series.redScore, 0);
|
||||
const winnerSide = isSide(series.winnerSide) ? series.winnerSide : undefined;
|
||||
const winnerTeamIndex =
|
||||
winnerSide === 'blue'
|
||||
? legacyBlueTeamIndex
|
||||
: winnerSide === 'red'
|
||||
? legacyRedTeamIndex
|
||||
: undefined;
|
||||
return {
|
||||
teamAIndex,
|
||||
teamBIndex,
|
||||
teamAWins: teamAIndex === legacyBlueTeamIndex ? blueScore : redScore,
|
||||
teamBWins: teamBIndex === legacyBlueTeamIndex ? blueScore : redScore,
|
||||
winnerTeamIndex,
|
||||
};
|
||||
});
|
||||
migrated.seriesResults = seriesResults.length > 0 ? seriesResults : buildSeries(games);
|
||||
|
||||
if (typeof migrated.winnerTeamIndex !== 'number') {
|
||||
const migratedSeriesResults = Array.isArray(migrated.seriesResults)
|
||||
? migrated.seriesResults
|
||||
: [];
|
||||
migrated.winnerTeamIndex =
|
||||
resolveWinnerTeamIndex(migratedSeriesResults) ??
|
||||
(isSide(migrated.winnerSide)
|
||||
? sideGroupToTeamIndex(migrated.winnerSide, 1)
|
||||
: undefined);
|
||||
}
|
||||
|
||||
if ('winnerSide' in migrated || 'blueScore' in migrated || 'redScore' in migrated) {
|
||||
changed = true;
|
||||
}
|
||||
delete migrated.winnerSide;
|
||||
delete migrated.blueScore;
|
||||
delete migrated.redScore;
|
||||
|
||||
return changed ? migrated : null;
|
||||
}
|
||||
|
||||
function buildSeries(games: Record<string, unknown>[]) {
|
||||
const bySeries = new Map<
|
||||
string,
|
||||
{
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
teamAWins: number;
|
||||
teamBWins: number;
|
||||
winnerTeamIndex?: number;
|
||||
}
|
||||
>();
|
||||
for (const game of games) {
|
||||
const blueTeamIndex = numberOrDefault(game.blueTeamIndex, 1);
|
||||
const redTeamIndex = numberOrDefault(game.redTeamIndex, 2);
|
||||
const winnerTeamIndex = numberOrUndefined(game.winnerTeamIndex);
|
||||
const teamAIndex = Math.min(blueTeamIndex, redTeamIndex);
|
||||
const teamBIndex = Math.max(blueTeamIndex, redTeamIndex);
|
||||
const key = `${teamAIndex}:${teamBIndex}`;
|
||||
const current =
|
||||
bySeries.get(key) ?? { teamAIndex, teamBIndex, teamAWins: 0, teamBWins: 0 };
|
||||
if (winnerTeamIndex === teamAIndex) current.teamAWins += 1;
|
||||
if (winnerTeamIndex === teamBIndex) current.teamBWins += 1;
|
||||
current.winnerTeamIndex =
|
||||
current.teamAWins > current.teamBWins
|
||||
? teamAIndex
|
||||
: current.teamBWins > current.teamAWins
|
||||
? teamBIndex
|
||||
: undefined;
|
||||
bySeries.set(key, current);
|
||||
}
|
||||
return [...bySeries.values()];
|
||||
}
|
||||
|
||||
function resolveWinnerTeamIndex(
|
||||
seriesResults: Array<Record<string, unknown>>,
|
||||
): number | undefined {
|
||||
const wins = new Map<number, number>();
|
||||
for (const series of seriesResults) {
|
||||
const winnerTeamIndex = numberOrUndefined(series.winnerTeamIndex);
|
||||
if (!winnerTeamIndex) continue;
|
||||
wins.set(winnerTeamIndex, (wins.get(winnerTeamIndex) ?? 0) + 1);
|
||||
}
|
||||
const sorted = [...wins.entries()].sort((left, right) => right[1] - left[1]);
|
||||
if (sorted.length === 0) return undefined;
|
||||
if (sorted.length > 1 && sorted[0][1] === sorted[1][1]) return undefined;
|
||||
return sorted[0][0];
|
||||
}
|
||||
|
||||
function readTeamIndex(value: Record<string, unknown>): number | undefined {
|
||||
if (typeof value.teamIndex === 'number') return value.teamIndex;
|
||||
if (!isSide(value.side)) return undefined;
|
||||
return sideGroupToTeamIndex(value.side, numberOrDefault(value.groupIndex, 1));
|
||||
}
|
||||
|
||||
function sideGroupToTeamIndex(side: LegacySide, groupIndex: number) {
|
||||
return (Math.max(1, groupIndex) - 1) * 2 + (side === 'blue' ? 1 : 2);
|
||||
}
|
||||
|
||||
function asArray(value: unknown): Record<string, unknown>[] {
|
||||
return Array.isArray(value)
|
||||
? value.filter(isRecord).map((item) => ({ ...item }))
|
||||
: [];
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value && typeof value === 'object' && !Array.isArray(value));
|
||||
}
|
||||
|
||||
function isSide(value: unknown): value is LegacySide {
|
||||
return value === 'blue' || value === 'red';
|
||||
}
|
||||
|
||||
function numberOrDefault(value: unknown, fallback: number) {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : fallback;
|
||||
}
|
||||
|
||||
function numberOrUndefined(value: unknown) {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import 'reflect-metadata';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
import { ConnectionService, resolveMongoDbName } from '../connection.service';
|
||||
import { SecretModule } from '../../secret/secret.module';
|
||||
import { migrateTeamIndex } from './20260502-team-index';
|
||||
|
||||
interface CliOptions {
|
||||
dryRun: boolean;
|
||||
limit?: number;
|
||||
nodeEnv: string;
|
||||
}
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
isGlobal: true,
|
||||
envFilePath: [
|
||||
resolve(__dirname, '../../../../../../project.env'),
|
||||
resolve(process.cwd(), '../project.env'),
|
||||
resolve(process.cwd(), 'apps/project.env'),
|
||||
resolve(process.cwd(), 'project.env'),
|
||||
],
|
||||
}),
|
||||
SecretModule,
|
||||
],
|
||||
providers: [ConnectionService],
|
||||
})
|
||||
class MigrationModule {}
|
||||
|
||||
async function loadMachineEnvFile() {
|
||||
const homeDir = process.env.HOME ?? process.env.USERPROFILE;
|
||||
if (!homeDir) return;
|
||||
|
||||
const machineEnvFile = resolve(homeDir, 'source/global-env-vars.txt');
|
||||
|
||||
try {
|
||||
const file = await readFile(machineEnvFile, 'utf8');
|
||||
for (const rawLine of file.split(/\r?\n/)) {
|
||||
const line = rawLine.trim();
|
||||
if (!line || line.startsWith('#')) continue;
|
||||
|
||||
const matched = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
|
||||
if (!matched) continue;
|
||||
|
||||
const [, key, rawValue] = matched;
|
||||
process.env[key] = rawValue.replace(/^["']|["']$/g, '');
|
||||
}
|
||||
} catch {
|
||||
// 로컬 machine env 파일이 없으면 그냥 지나간다.
|
||||
}
|
||||
}
|
||||
|
||||
function parseArgs(argv: string[]): CliOptions {
|
||||
let dryRun = true;
|
||||
let limit: number | undefined;
|
||||
let nodeEnv = process.env.NODE_ENV ?? 'dev';
|
||||
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const arg = argv[index];
|
||||
if (arg === '--apply') {
|
||||
dryRun = false;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--dry-run') {
|
||||
dryRun = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--env') {
|
||||
const value = argv[index + 1];
|
||||
if (!value) throw new Error('--env requires dev, staging, or prod.');
|
||||
nodeEnv = value;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith('--env=')) {
|
||||
nodeEnv = arg.slice('--env='.length);
|
||||
continue;
|
||||
}
|
||||
if (arg === '--limit') {
|
||||
const value = Number(argv[index + 1]);
|
||||
if (!Number.isInteger(value) || value < 1) {
|
||||
throw new Error('--limit requires a positive integer.');
|
||||
}
|
||||
limit = value;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith('--limit=')) {
|
||||
const value = Number(arg.slice('--limit='.length));
|
||||
if (!Number.isInteger(value) || value < 1) {
|
||||
throw new Error('--limit requires a positive integer.');
|
||||
}
|
||||
limit = value;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--help' || arg === '-h') {
|
||||
printHelp();
|
||||
process.exit(0);
|
||||
}
|
||||
throw new Error(`Unknown argument: ${arg}`);
|
||||
}
|
||||
|
||||
if (!['dev', 'staging', 'prod'].includes(nodeEnv)) {
|
||||
throw new Error('--env must be dev, staging, or prod.');
|
||||
}
|
||||
|
||||
return { dryRun, limit, nodeEnv };
|
||||
}
|
||||
|
||||
function printHelp() {
|
||||
console.log(`Usage:
|
||||
pnpm --filter api exec ts-node src/modules/global/database/migrations/run-team-index.ts [--dry-run]
|
||||
pnpm --filter api exec ts-node src/modules/global/database/migrations/run-team-index.ts --apply
|
||||
|
||||
Options:
|
||||
--dry-run Print affected counts without writing. Default.
|
||||
--apply Apply updates to MongoDB.
|
||||
--env <env> dev | staging | prod. Default: NODE_ENV or dev.
|
||||
--limit <n> Only scan first n documents per collection.
|
||||
`);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
process.env.NODE_ENV = options.nodeEnv;
|
||||
await loadMachineEnvFile();
|
||||
|
||||
const app = await NestFactory.createApplicationContext(MigrationModule, {
|
||||
logger: options.dryRun
|
||||
? ['log', 'warn', 'error']
|
||||
: ['log', 'warn', 'error'],
|
||||
});
|
||||
|
||||
try {
|
||||
const connectionService = app.get(ConnectionService);
|
||||
const connection = await connectionService.getConnection();
|
||||
if (!connection.db) {
|
||||
throw new Error('MongoDB connection has no db handle.');
|
||||
}
|
||||
|
||||
const dbName = resolveMongoDbName(options.nodeEnv);
|
||||
console.log(
|
||||
`[team-index migration] mode=${options.dryRun ? 'dry-run' : 'apply'} env=${options.nodeEnv} db=${dbName}`,
|
||||
);
|
||||
|
||||
const stats = await migrateTeamIndex(
|
||||
connection.db as Parameters<typeof migrateTeamIndex>[0],
|
||||
{
|
||||
dryRun: options.dryRun,
|
||||
limit: options.limit,
|
||||
},
|
||||
);
|
||||
|
||||
console.table(stats);
|
||||
if (options.dryRun) {
|
||||
console.log(
|
||||
'No writes were made. Re-run with --apply to update documents.',
|
||||
);
|
||||
} else {
|
||||
console.log('Migration applied.');
|
||||
}
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
}
|
||||
|
||||
void main().catch((error: unknown) => {
|
||||
console.error(error instanceof Error ? error.message : error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -32,6 +32,13 @@ export const MATCH_STATUSES: MatchStatus[] = [
|
||||
export type TeamSide = 'blue' | 'red';
|
||||
export const TEAM_SIDES: TeamSide[] = ['blue', 'red'];
|
||||
|
||||
export type MatchGameMode = 'pair' | 'bracket' | 'round-robin';
|
||||
export const MATCH_GAME_MODES: MatchGameMode[] = [
|
||||
'pair',
|
||||
'bracket',
|
||||
'round-robin',
|
||||
];
|
||||
|
||||
export type CommunityRole = 'owner' | 'admin' | 'member';
|
||||
export const COMMUNITY_ROLES: CommunityRole[] = ['owner', 'admin', 'member'];
|
||||
|
||||
@@ -58,7 +65,11 @@ export const TOURNAMENT_SPECTATOR_TYPES: TournamentSpectatorType[] = [
|
||||
];
|
||||
|
||||
export type MatchResultPollOutcome = 'matched' | 'not-found' | 'failed';
|
||||
export type MatchResultPollStateValue = 'polling' | 'complete' | 'expired' | 'failed';
|
||||
export type MatchResultPollStateValue =
|
||||
| 'polling'
|
||||
| 'complete'
|
||||
| 'expired'
|
||||
| 'failed';
|
||||
export const MATCH_RESULT_POLL_STATES: MatchResultPollStateValue[] = [
|
||||
'polling',
|
||||
'complete',
|
||||
@@ -80,6 +91,39 @@ export const LEGACY_IMPORT_JOB_STATES: LegacyImportJobState[] = [
|
||||
'cancelled',
|
||||
];
|
||||
|
||||
export type DakaoInboundMessageState = 'processing' | 'processed' | 'failed';
|
||||
export const DAKAO_INBOUND_MESSAGE_STATES: DakaoInboundMessageState[] = [
|
||||
'processing',
|
||||
'processed',
|
||||
'failed',
|
||||
];
|
||||
|
||||
export type DakaoOutboxMessageState =
|
||||
| 'pending'
|
||||
| 'published'
|
||||
| 'sent'
|
||||
| 'failed';
|
||||
export const DAKAO_OUTBOX_MESSAGE_STATES: DakaoOutboxMessageState[] = [
|
||||
'pending',
|
||||
'published',
|
||||
'sent',
|
||||
'failed',
|
||||
];
|
||||
|
||||
export type DakaoOutboxCompensationState =
|
||||
| 'none'
|
||||
| 'pending'
|
||||
| 'completed'
|
||||
| 'failed';
|
||||
export const DAKAO_OUTBOX_COMPENSATION_STATES: DakaoOutboxCompensationState[] =
|
||||
['none', 'pending', 'completed', 'failed'];
|
||||
|
||||
export type DakaoSendResultStatus = 'succeeded' | 'failed';
|
||||
export const DAKAO_SEND_RESULT_STATUSES: DakaoSendResultStatus[] = [
|
||||
'succeeded',
|
||||
'failed',
|
||||
];
|
||||
|
||||
export interface PositionPreference {
|
||||
position: Position;
|
||||
priority: number; // 1 = 최우선, 숫자가 작을수록 높은 우선순위
|
||||
@@ -90,14 +134,33 @@ export type AuctionPhase =
|
||||
| 'presenting'
|
||||
| 'bidding'
|
||||
| 'sold'
|
||||
| 'passed'
|
||||
| 'complete';
|
||||
export const AUCTION_PHASES: AuctionPhase[] = [
|
||||
'waiting',
|
||||
'presenting',
|
||||
'bidding',
|
||||
'sold',
|
||||
'passed',
|
||||
'complete',
|
||||
];
|
||||
export const AUCTION_TOP_TIER_THRESHOLDS = [
|
||||
'NONE',
|
||||
'EMERALD',
|
||||
'DIAMOND',
|
||||
'MASTER',
|
||||
'MANUAL',
|
||||
] as const;
|
||||
export type AuctionTopTierThreshold =
|
||||
(typeof AUCTION_TOP_TIER_THRESHOLDS)[number];
|
||||
export type AuctionActionType =
|
||||
| 'start'
|
||||
| 'open-bidding'
|
||||
| 'bid'
|
||||
| 'sold'
|
||||
| 'passed'
|
||||
| 'next'
|
||||
| 'complete';
|
||||
|
||||
export interface MongooseTimestamps {
|
||||
createdAt: Date;
|
||||
@@ -270,9 +333,61 @@ export interface CommunitySeason {
|
||||
endedAt?: Date;
|
||||
}
|
||||
|
||||
export interface DakaoInboundMessage extends MongooseTimestamps {
|
||||
consumer: string;
|
||||
projectId: string;
|
||||
chatLogLogId: string;
|
||||
state: DakaoInboundMessageState;
|
||||
attempts: number;
|
||||
processingExpiresAt?: Date;
|
||||
processedAt?: Date;
|
||||
lastError?: string;
|
||||
}
|
||||
|
||||
export interface DakaoOutboxMessage extends MongooseTimestamps {
|
||||
eventId: string;
|
||||
eventSource: string;
|
||||
type: string;
|
||||
subject: string;
|
||||
correlationId?: string;
|
||||
resultSubjects?: {
|
||||
succeeded: string;
|
||||
failed: string;
|
||||
};
|
||||
payload: Record<string, unknown>;
|
||||
state: DakaoOutboxMessageState;
|
||||
publishAttempts: number;
|
||||
publishedAt?: Date;
|
||||
terminalAt?: Date;
|
||||
resultEventId?: string;
|
||||
lastPublishError?: string;
|
||||
terminalError?: Record<string, unknown>;
|
||||
compensationState: DakaoOutboxCompensationState;
|
||||
compensationReason?: string;
|
||||
}
|
||||
|
||||
export interface DakaoSendResultEvent extends MongooseTimestamps {
|
||||
eventId: string;
|
||||
requestEventId: string;
|
||||
eventSource: string;
|
||||
requestEventSource: string;
|
||||
type: string;
|
||||
subject: string;
|
||||
status: DakaoSendResultStatus;
|
||||
correlationId?: string;
|
||||
handledAt: Date;
|
||||
providerMessageId?: string;
|
||||
error?: Record<string, unknown>;
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export type CommunityDocument = HydratedDocument<Community>;
|
||||
export type IdentityDocument = HydratedDocument<Identity>;
|
||||
export type UserDocument = HydratedDocument<User>;
|
||||
export type DakaoInboundMessageDocument = HydratedDocument<DakaoInboundMessage>;
|
||||
export type DakaoOutboxMessageDocument = HydratedDocument<DakaoOutboxMessage>;
|
||||
export type DakaoSendResultEventDocument =
|
||||
HydratedDocument<DakaoSendResultEvent>;
|
||||
|
||||
// ===== RiotMatch (Riot 원본 매치 아카이브) =====
|
||||
export interface RiotMatch extends MongooseTimestamps {
|
||||
@@ -323,6 +438,7 @@ export interface MatchParticipant {
|
||||
tier?: TierInfo;
|
||||
preferredPositions: PositionPreference[];
|
||||
joinedAt: Date;
|
||||
excluded?: boolean;
|
||||
}
|
||||
|
||||
export interface MatchTeamMember {
|
||||
@@ -332,7 +448,7 @@ export interface MatchTeamMember {
|
||||
}
|
||||
|
||||
export interface MatchTeam {
|
||||
side: TeamSide;
|
||||
teamIndex: number;
|
||||
name: string;
|
||||
captainUserId?: mongoose.Types.ObjectId;
|
||||
members: MatchTeamMember[];
|
||||
@@ -340,6 +456,7 @@ export interface MatchTeam {
|
||||
|
||||
export interface MatchGameResultParticipant {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
teamIndex: number;
|
||||
side: TeamSide;
|
||||
championId: number;
|
||||
kills: number;
|
||||
@@ -351,19 +468,35 @@ export interface MatchGameResultParticipant {
|
||||
export interface MatchGameResult {
|
||||
gameNumber: number;
|
||||
riotMatchId: string;
|
||||
blueTeamIndex: number;
|
||||
redTeamIndex: number;
|
||||
winnerTeamIndex: number;
|
||||
winnerSide: TeamSide;
|
||||
gameCreation: number;
|
||||
gameDuration: number;
|
||||
participants: MatchGameResultParticipant[];
|
||||
}
|
||||
|
||||
export interface MatchSeriesResult {
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
teamAWins: number;
|
||||
teamBWins: number;
|
||||
winnerTeamIndex?: number;
|
||||
}
|
||||
|
||||
export interface MatchGameAssignment {
|
||||
gameNumber: number;
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
}
|
||||
|
||||
export interface MatchResult {
|
||||
winnerSide?: TeamSide;
|
||||
blueScore: number;
|
||||
redScore: number;
|
||||
winnerTeamIndex?: number;
|
||||
mvpUserId?: mongoose.Types.ObjectId;
|
||||
riotMatchIds: string[]; // 내전에서 플레이된 Riot matchId들
|
||||
games: MatchGameResult[];
|
||||
seriesResults?: MatchSeriesResult[];
|
||||
}
|
||||
|
||||
export interface MatchResultPollState {
|
||||
@@ -382,6 +515,7 @@ export interface MatchScheduleItem {
|
||||
|
||||
export interface Match extends MongooseTimestamps {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
shortCode?: string;
|
||||
title: string;
|
||||
description: string;
|
||||
mapId: number; // Riot Match-V5 mapId (11=소환사의 협곡, 12=ARAM 등)
|
||||
@@ -389,7 +523,9 @@ export interface Match extends MongooseTimestamps {
|
||||
scheduledAt: Date;
|
||||
maxParticipants: number;
|
||||
gameCount: number;
|
||||
gameMode: MatchGameMode;
|
||||
tournamentCodeIds: mongoose.Types.ObjectId[];
|
||||
gameSchedule: MatchGameAssignment[];
|
||||
teamBuiltAt?: Date;
|
||||
hostUserId?: mongoose.Types.ObjectId;
|
||||
participants: MatchParticipant[];
|
||||
@@ -457,8 +593,10 @@ export interface AuctionPlayerSnapshot {
|
||||
profileIconId: number;
|
||||
preferredPositions: PositionPreference[];
|
||||
tiers: TierInfo[];
|
||||
tierHistory: TierHistoryEntry[];
|
||||
masteries: ChampionMasteryEntry[];
|
||||
recentStatsSummary?: RiotRecentStatsSummary;
|
||||
passCount: number;
|
||||
}
|
||||
|
||||
export interface AuctionTeamMember {
|
||||
@@ -468,37 +606,135 @@ export interface AuctionTeamMember {
|
||||
}
|
||||
|
||||
export interface AuctionTeam {
|
||||
side: TeamSide;
|
||||
teamIndex: number;
|
||||
captainUserId: mongoose.Types.ObjectId;
|
||||
points: number;
|
||||
members: AuctionTeamMember[];
|
||||
}
|
||||
|
||||
export interface AuctionBid {
|
||||
side: TeamSide;
|
||||
teamIndex: number;
|
||||
amount: number;
|
||||
bidderUserId: mongoose.Types.ObjectId;
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
export interface AuctionChatMessage {
|
||||
id: string;
|
||||
userId?: mongoose.Types.ObjectId;
|
||||
displayName: string;
|
||||
message: string;
|
||||
sentAt: Date;
|
||||
}
|
||||
|
||||
export interface Auction extends MongooseTimestamps {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
phase: AuctionPhase;
|
||||
teams: AuctionTeam[];
|
||||
order: AuctionPlayerSnapshot[];
|
||||
passedQueue: AuctionPlayerSnapshot[];
|
||||
auctionRound: number;
|
||||
currentIndex: number;
|
||||
bids: AuctionBid[];
|
||||
currentBid: number;
|
||||
currentBidder?: TeamSide;
|
||||
currentBidderTeamIndex?: number;
|
||||
maxTimerSeconds: number;
|
||||
bidExtensionSeconds: number;
|
||||
currentDeadline?: Date;
|
||||
initialPoints: number;
|
||||
topTierThreshold: AuctionTopTierThreshold;
|
||||
manualTopTierUserIds: mongoose.Types.ObjectId[];
|
||||
chatMessages: AuctionChatMessage[];
|
||||
startedAt?: Date;
|
||||
completedAt?: Date;
|
||||
}
|
||||
|
||||
export type AuctionDocument = HydratedDocument<Auction>;
|
||||
|
||||
export interface AuctionHistoryEntry extends MongooseTimestamps {
|
||||
auctionId: mongoose.Types.ObjectId;
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
sequence: number;
|
||||
action: AuctionActionType;
|
||||
actorUserId?: mongoose.Types.ObjectId;
|
||||
snapshotBefore: Record<string, unknown>;
|
||||
takenAt: Date;
|
||||
}
|
||||
|
||||
export type AuctionHistoryEntryDocument = HydratedDocument<AuctionHistoryEntry>;
|
||||
|
||||
// ===== MatchStats (precomputed internal stats fragment) =====
|
||||
export interface MatchStatsRecord {
|
||||
matchId: string;
|
||||
title: string;
|
||||
scheduledAt: Date;
|
||||
gameNumber: number;
|
||||
riotMatchId: string;
|
||||
gameCreation: number;
|
||||
gameDuration: number;
|
||||
userId: string;
|
||||
summonerName: string;
|
||||
profileIconId: number;
|
||||
teamIndex: number;
|
||||
side: TeamSide;
|
||||
championId: number;
|
||||
championLevel: number;
|
||||
teamPosition: string;
|
||||
kills: number;
|
||||
deaths: number;
|
||||
assists: number;
|
||||
win: boolean;
|
||||
cs: number;
|
||||
csPerMin: number;
|
||||
gold: number;
|
||||
gpm: number;
|
||||
damageDealtToChampions: number;
|
||||
damageTaken: number;
|
||||
damageShare: number;
|
||||
killParticipation: number;
|
||||
visionScore: number;
|
||||
controlWardsBought: number;
|
||||
wardsPlaced: number;
|
||||
wardsKilled: number;
|
||||
items: number[];
|
||||
trinket: number;
|
||||
summonerSpells: [number, number];
|
||||
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
|
||||
rating: number;
|
||||
}
|
||||
|
||||
export interface MatchStatsGameDetail {
|
||||
gameNumber: number;
|
||||
riotMatchId: string;
|
||||
gameCreation: number;
|
||||
gameDuration: number;
|
||||
winnerSide: TeamSide;
|
||||
teams: Array<{
|
||||
teamIndex: number;
|
||||
side: TeamSide;
|
||||
win: boolean;
|
||||
objectives: { baron: number; dragon: number; tower: number };
|
||||
participants: MatchStatsRecord[];
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface MatchStats extends MongooseTimestamps {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
scheduledAt: Date;
|
||||
gameCreationMin: number;
|
||||
gameCreationMax: number;
|
||||
userIds: mongoose.Types.ObjectId[];
|
||||
championIds: number[];
|
||||
matchCard: Record<string, unknown>;
|
||||
records: MatchStatsRecord[];
|
||||
gameDetails: MatchStatsGameDetail[];
|
||||
builtAt: Date;
|
||||
builderVersion: number;
|
||||
}
|
||||
|
||||
export type MatchStatsDocument = HydratedDocument<MatchStats>;
|
||||
|
||||
// ===== Sub-schemas =====
|
||||
const PositionPreferenceSubSchema = new Schema<PositionPreference>(
|
||||
{
|
||||
@@ -703,6 +939,102 @@ CommunitySchema.index({ name: 1 }, { unique: true });
|
||||
CommunitySchema.index({ ownerUserId: 1 });
|
||||
CommunitySchema.index({ dakaoProjectId: 1 }, { unique: true, sparse: true });
|
||||
|
||||
export const DakaoInboundMessageSchema = new Schema<DakaoInboundMessage>(
|
||||
{
|
||||
consumer: { type: String, required: true },
|
||||
projectId: { type: String, required: true },
|
||||
chatLogLogId: { type: String, required: true },
|
||||
state: {
|
||||
type: String,
|
||||
enum: DAKAO_INBOUND_MESSAGE_STATES,
|
||||
required: true,
|
||||
default: 'processing',
|
||||
},
|
||||
attempts: { type: Number, required: true, default: 1 },
|
||||
processingExpiresAt: { type: Date },
|
||||
processedAt: { type: Date },
|
||||
lastError: { type: String },
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
collection: 'dakao_inbound_message',
|
||||
},
|
||||
);
|
||||
|
||||
DakaoInboundMessageSchema.index(
|
||||
{ consumer: 1, projectId: 1, chatLogLogId: 1 },
|
||||
{ unique: true },
|
||||
);
|
||||
DakaoInboundMessageSchema.index({ state: 1, processingExpiresAt: 1 });
|
||||
|
||||
export const DakaoOutboxMessageSchema = new Schema<DakaoOutboxMessage>(
|
||||
{
|
||||
eventId: { type: String, required: true, unique: true },
|
||||
eventSource: { type: String, required: true },
|
||||
type: { type: String, required: true },
|
||||
subject: { type: String, required: true },
|
||||
correlationId: { type: String },
|
||||
resultSubjects: {
|
||||
succeeded: { type: String },
|
||||
failed: { type: String },
|
||||
},
|
||||
payload: { type: Schema.Types.Mixed, required: true },
|
||||
state: {
|
||||
type: String,
|
||||
enum: DAKAO_OUTBOX_MESSAGE_STATES,
|
||||
required: true,
|
||||
default: 'pending',
|
||||
},
|
||||
publishAttempts: { type: Number, required: true, default: 0 },
|
||||
publishedAt: { type: Date },
|
||||
terminalAt: { type: Date },
|
||||
resultEventId: { type: String },
|
||||
lastPublishError: { type: String },
|
||||
terminalError: { type: Schema.Types.Mixed },
|
||||
compensationState: {
|
||||
type: String,
|
||||
enum: DAKAO_OUTBOX_COMPENSATION_STATES,
|
||||
required: true,
|
||||
default: 'none',
|
||||
},
|
||||
compensationReason: { type: String },
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
collection: 'dakao_outbox_message',
|
||||
},
|
||||
);
|
||||
|
||||
DakaoOutboxMessageSchema.index({ state: 1, updatedAt: 1 });
|
||||
DakaoOutboxMessageSchema.index({ correlationId: 1 }, { sparse: true });
|
||||
|
||||
export const DakaoSendResultEventSchema = new Schema<DakaoSendResultEvent>(
|
||||
{
|
||||
eventId: { type: String, required: true, unique: true },
|
||||
requestEventId: { type: String, required: true },
|
||||
eventSource: { type: String, required: true },
|
||||
requestEventSource: { type: String, required: true },
|
||||
type: { type: String, required: true },
|
||||
subject: { type: String, required: true },
|
||||
status: {
|
||||
type: String,
|
||||
enum: DAKAO_SEND_RESULT_STATUSES,
|
||||
required: true,
|
||||
},
|
||||
correlationId: { type: String },
|
||||
handledAt: { type: Date, required: true },
|
||||
providerMessageId: { type: String },
|
||||
error: { type: Schema.Types.Mixed },
|
||||
raw: { type: Schema.Types.Mixed, required: true },
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
collection: 'dakao_send_result_event',
|
||||
},
|
||||
);
|
||||
|
||||
DakaoSendResultEventSchema.index({ requestEventId: 1, status: 1 });
|
||||
|
||||
export const UserSchema = new Schema<User>(
|
||||
{
|
||||
communityId: {
|
||||
@@ -880,6 +1212,7 @@ const MatchParticipantSubSchema = new Schema<MatchParticipant>(
|
||||
default: [],
|
||||
},
|
||||
joinedAt: { type: Date, required: true, default: Date.now },
|
||||
excluded: { type: Boolean, required: true, default: false },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
@@ -895,7 +1228,7 @@ const MatchTeamMemberSubSchema = new Schema<MatchTeamMember>(
|
||||
|
||||
const MatchTeamSubSchema = new Schema<MatchTeam>(
|
||||
{
|
||||
side: { type: String, enum: TEAM_SIDES, required: true },
|
||||
teamIndex: { type: Number, required: true, min: 1 },
|
||||
name: { type: String, required: true },
|
||||
captainUserId: { type: Schema.Types.ObjectId, ref: 'user' },
|
||||
members: { type: [MatchTeamMemberSubSchema], required: true, default: [] },
|
||||
@@ -907,6 +1240,7 @@ const MatchGameResultParticipantSubSchema =
|
||||
new Schema<MatchGameResultParticipant>(
|
||||
{
|
||||
userId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
|
||||
teamIndex: { type: Number, required: true, min: 1 },
|
||||
side: { type: String, enum: TEAM_SIDES, required: true },
|
||||
championId: { type: Number, required: true },
|
||||
kills: { type: Number, required: true, default: 0 },
|
||||
@@ -921,6 +1255,9 @@ const MatchGameResultSubSchema = new Schema<MatchGameResult>(
|
||||
{
|
||||
gameNumber: { type: Number, required: true },
|
||||
riotMatchId: { type: String, required: true },
|
||||
blueTeamIndex: { type: Number, required: true, min: 1 },
|
||||
redTeamIndex: { type: Number, required: true, min: 1 },
|
||||
winnerTeamIndex: { type: Number, required: true, min: 1 },
|
||||
winnerSide: { type: String, enum: TEAM_SIDES, required: true },
|
||||
gameCreation: { type: Number, required: true },
|
||||
gameDuration: { type: Number, required: true },
|
||||
@@ -933,14 +1270,37 @@ const MatchGameResultSubSchema = new Schema<MatchGameResult>(
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const MatchSeriesResultSubSchema = new Schema<MatchSeriesResult>(
|
||||
{
|
||||
teamAIndex: { type: Number, required: true, min: 1 },
|
||||
teamBIndex: { type: Number, required: true, min: 1 },
|
||||
teamAWins: { type: Number, required: true, default: 0 },
|
||||
teamBWins: { type: Number, required: true, default: 0 },
|
||||
winnerTeamIndex: { type: Number, required: false, min: 1 },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const MatchGameAssignmentSubSchema = new Schema<MatchGameAssignment>(
|
||||
{
|
||||
gameNumber: { type: Number, required: true, min: 1 },
|
||||
teamAIndex: { type: Number, required: true, min: 1 },
|
||||
teamBIndex: { type: Number, required: true, min: 1 },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const MatchResultSubSchema = new Schema<MatchResult>(
|
||||
{
|
||||
winnerSide: { type: String, enum: TEAM_SIDES, required: false },
|
||||
blueScore: { type: Number, required: true, default: 0 },
|
||||
redScore: { type: Number, required: true, default: 0 },
|
||||
winnerTeamIndex: { type: Number, required: false, min: 1 },
|
||||
mvpUserId: { type: Schema.Types.ObjectId, ref: 'user' },
|
||||
riotMatchIds: { type: [String], required: true, default: [] },
|
||||
games: { type: [MatchGameResultSubSchema], required: true, default: [] },
|
||||
seriesResults: {
|
||||
type: [MatchSeriesResultSubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
@@ -974,7 +1334,9 @@ const MatchScheduleItemSubSchema = new Schema<MatchScheduleItem>(
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const MatchLegacyImportSourceSubSchema = new Schema<NonNullable<Match['legacyImportSource']>>(
|
||||
const MatchLegacyImportSourceSubSchema = new Schema<
|
||||
NonNullable<Match['legacyImportSource']>
|
||||
>(
|
||||
{
|
||||
importedAt: { type: Date, required: true },
|
||||
importedBy: { type: Schema.Types.ObjectId, ref: 'user', required: true },
|
||||
@@ -991,8 +1353,16 @@ export const MatchSchema = new Schema<Match>(
|
||||
ref: 'community',
|
||||
required: true,
|
||||
},
|
||||
shortCode: {
|
||||
type: String,
|
||||
required: false,
|
||||
trim: true,
|
||||
uppercase: true,
|
||||
minlength: 4,
|
||||
maxlength: 6,
|
||||
},
|
||||
title: { type: String, required: true },
|
||||
description: { type: String, required: true, default: '' },
|
||||
description: { type: String, required: false, default: '' },
|
||||
mapId: { type: Number, required: true, default: 11 },
|
||||
status: {
|
||||
type: String,
|
||||
@@ -1001,13 +1371,34 @@ export const MatchSchema = new Schema<Match>(
|
||||
default: 'recruiting',
|
||||
},
|
||||
scheduledAt: { type: Date, required: true },
|
||||
maxParticipants: { type: Number, required: true, default: 10 },
|
||||
maxParticipants: {
|
||||
type: Number,
|
||||
required: true,
|
||||
default: 10,
|
||||
min: 10,
|
||||
validate: {
|
||||
validator: (value: number) =>
|
||||
Number.isInteger(value) && value % 10 === 0,
|
||||
message: 'maxParticipants must be a multiple of 10.',
|
||||
},
|
||||
},
|
||||
gameCount: { type: Number, required: true, default: 3 },
|
||||
gameMode: {
|
||||
type: String,
|
||||
enum: MATCH_GAME_MODES,
|
||||
required: true,
|
||||
default: 'pair',
|
||||
},
|
||||
tournamentCodeIds: {
|
||||
type: [{ type: Schema.Types.ObjectId, ref: 'tournamentCode' }],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
gameSchedule: {
|
||||
type: [MatchGameAssignmentSubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
teamBuiltAt: { type: Date },
|
||||
hostUserId: { type: Schema.Types.ObjectId, ref: 'user' },
|
||||
participants: {
|
||||
@@ -1049,6 +1440,13 @@ export const MatchSchema = new Schema<Match>(
|
||||
|
||||
MatchSchema.index({ communityId: 1, scheduledAt: -1 });
|
||||
MatchSchema.index({ communityId: 1, status: 1, scheduledAt: -1 });
|
||||
MatchSchema.index(
|
||||
{ communityId: 1, shortCode: 1 },
|
||||
{
|
||||
unique: true,
|
||||
partialFilterExpression: { shortCode: { $type: 'string' } },
|
||||
},
|
||||
);
|
||||
MatchSchema.index({ legacyImported: 1, scheduledAt: -1 });
|
||||
MatchSchema.index({ 'result.games.riotMatchId': 1 }, { sparse: true });
|
||||
MatchSchema.index({ title: 'text', description: 'text' });
|
||||
@@ -1134,12 +1532,18 @@ const AuctionPlayerSnapshotSubSchema = new Schema<AuctionPlayerSnapshot>(
|
||||
default: [],
|
||||
},
|
||||
tiers: { type: [TierInfoSubSchema], required: true, default: [] },
|
||||
tierHistory: {
|
||||
type: [TierHistoryEntrySubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
masteries: {
|
||||
type: [ChampionMasteryEntrySubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
recentStatsSummary: { type: RiotRecentStatsSummarySubSchema },
|
||||
passCount: { type: Number, required: true, default: 0 },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
@@ -1155,7 +1559,7 @@ const AuctionTeamMemberSubSchema = new Schema<AuctionTeamMember>(
|
||||
|
||||
const AuctionTeamSubSchema = new Schema<AuctionTeam>(
|
||||
{
|
||||
side: { type: String, enum: TEAM_SIDES, required: true },
|
||||
teamIndex: { type: Number, required: true, min: 1 },
|
||||
captainUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
|
||||
points: { type: Number, required: true, default: 0 },
|
||||
members: {
|
||||
@@ -1169,7 +1573,7 @@ const AuctionTeamSubSchema = new Schema<AuctionTeam>(
|
||||
|
||||
const AuctionBidSubSchema = new Schema<AuctionBid>(
|
||||
{
|
||||
side: { type: String, enum: TEAM_SIDES, required: true },
|
||||
teamIndex: { type: Number, required: true, min: 1 },
|
||||
amount: { type: Number, required: true },
|
||||
bidderUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
|
||||
timestamp: { type: Date, required: true, default: Date.now },
|
||||
@@ -1177,6 +1581,17 @@ const AuctionBidSubSchema = new Schema<AuctionBid>(
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const AuctionChatMessageSubSchema = new Schema<AuctionChatMessage>(
|
||||
{
|
||||
id: { type: String, required: true },
|
||||
userId: { type: Schema.Types.ObjectId, ref: 'user', required: false },
|
||||
displayName: { type: String, required: true },
|
||||
message: { type: String, required: true },
|
||||
sentAt: { type: Date, required: true, default: Date.now },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
export const AuctionSchema = new Schema<Auction>(
|
||||
{
|
||||
matchId: {
|
||||
@@ -1197,13 +1612,37 @@ export const AuctionSchema = new Schema<Auction>(
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
passedQueue: {
|
||||
type: [AuctionPlayerSnapshotSubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
auctionRound: { type: Number, required: true, default: 1, min: 1 },
|
||||
currentIndex: { type: Number, required: true, default: 0 },
|
||||
bids: { type: [AuctionBidSubSchema], required: true, default: [] },
|
||||
currentBid: { type: Number, required: true, default: 0 },
|
||||
currentBidder: { type: String, enum: TEAM_SIDES, required: false },
|
||||
currentBidderTeamIndex: { type: Number, required: false, min: 1 },
|
||||
maxTimerSeconds: { type: Number, required: true, default: 30 },
|
||||
bidExtensionSeconds: { type: Number, required: true, default: 5, min: 0 },
|
||||
currentDeadline: { type: Date, required: false },
|
||||
initialPoints: { type: Number, required: true, default: 1000 },
|
||||
topTierThreshold: {
|
||||
type: String,
|
||||
enum: AUCTION_TOP_TIER_THRESHOLDS,
|
||||
required: true,
|
||||
default: 'NONE',
|
||||
},
|
||||
manualTopTierUserIds: {
|
||||
type: [Schema.Types.ObjectId],
|
||||
ref: 'user',
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
chatMessages: {
|
||||
type: [AuctionChatMessageSubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
startedAt: { type: Date, required: false },
|
||||
completedAt: { type: Date, required: false },
|
||||
},
|
||||
@@ -1213,9 +1652,100 @@ export const AuctionSchema = new Schema<Auction>(
|
||||
},
|
||||
);
|
||||
|
||||
const AuctionHistoryEntrySchema = new Schema<AuctionHistoryEntry>(
|
||||
{
|
||||
auctionId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: 'auction',
|
||||
required: true,
|
||||
index: true,
|
||||
},
|
||||
matchId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: 'match',
|
||||
required: true,
|
||||
index: true,
|
||||
},
|
||||
sequence: { type: Number, required: true, min: 1 },
|
||||
action: {
|
||||
type: String,
|
||||
enum: [
|
||||
'start',
|
||||
'open-bidding',
|
||||
'bid',
|
||||
'sold',
|
||||
'passed',
|
||||
'next',
|
||||
'complete',
|
||||
],
|
||||
required: true,
|
||||
},
|
||||
actorUserId: { type: Schema.Types.ObjectId, ref: 'user', required: false },
|
||||
snapshotBefore: { type: Schema.Types.Mixed, required: true },
|
||||
takenAt: { type: Date, required: true, default: Date.now },
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
collection: 'auctionHistory',
|
||||
},
|
||||
);
|
||||
|
||||
AuctionHistoryEntrySchema.index({ auctionId: 1, sequence: -1 });
|
||||
|
||||
export const MatchStatsSchema: mongoose.Schema<MatchStats> = new Schema(
|
||||
{
|
||||
matchId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: 'match',
|
||||
required: true,
|
||||
unique: true,
|
||||
},
|
||||
communityId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: 'community',
|
||||
required: true,
|
||||
},
|
||||
scheduledAt: { type: Date, required: true },
|
||||
gameCreationMin: { type: Number, required: true },
|
||||
gameCreationMax: { type: Number, required: true },
|
||||
userIds: { type: [Schema.Types.ObjectId], required: true, default: [] },
|
||||
championIds: { type: [Number], required: true, default: [] },
|
||||
matchCard: { type: Schema.Types.Mixed, required: true },
|
||||
records: { type: [Schema.Types.Mixed], required: true, default: [] },
|
||||
gameDetails: { type: [Schema.Types.Mixed], required: true, default: [] },
|
||||
builtAt: { type: Date, required: true, default: Date.now },
|
||||
builderVersion: { type: Number, required: true, default: 1 },
|
||||
} as mongoose.SchemaDefinition,
|
||||
{ timestamps: true, collection: 'match_stats' },
|
||||
) as mongoose.Schema<MatchStats>;
|
||||
|
||||
MatchStatsSchema.index({ communityId: 1, scheduledAt: -1 });
|
||||
MatchStatsSchema.index({
|
||||
communityId: 1,
|
||||
gameCreationMin: 1,
|
||||
gameCreationMax: 1,
|
||||
});
|
||||
MatchStatsSchema.index({ communityId: 1, userIds: 1 });
|
||||
MatchStatsSchema.index({ communityId: 1, championIds: 1 });
|
||||
|
||||
export const tournamentModelDefinitions: ModelDefinition[] = [
|
||||
{ name: 'identity', schema: IdentitySchema, schemaName: 'identity' },
|
||||
{ name: 'community', schema: CommunitySchema, schemaName: 'community' },
|
||||
{
|
||||
name: 'dakaoInboundMessage',
|
||||
schema: DakaoInboundMessageSchema,
|
||||
schemaName: 'dakaoInboundMessage',
|
||||
},
|
||||
{
|
||||
name: 'dakaoOutboxMessage',
|
||||
schema: DakaoOutboxMessageSchema,
|
||||
schemaName: 'dakaoOutboxMessage',
|
||||
},
|
||||
{
|
||||
name: 'dakaoSendResultEvent',
|
||||
schema: DakaoSendResultEventSchema,
|
||||
schemaName: 'dakaoSendResultEvent',
|
||||
},
|
||||
{ name: 'user', schema: UserSchema, schemaName: 'user' },
|
||||
{ name: 'riotMatch', schema: RiotMatchSchema, schemaName: 'riotMatch' },
|
||||
{
|
||||
@@ -1230,15 +1760,30 @@ export const tournamentModelDefinitions: ModelDefinition[] = [
|
||||
},
|
||||
{ name: 'match', schema: MatchSchema, schemaName: 'match' },
|
||||
{ name: 'auction', schema: AuctionSchema, schemaName: 'auction' },
|
||||
{
|
||||
name: 'auctionHistory',
|
||||
schema: AuctionHistoryEntrySchema,
|
||||
schemaName: 'auctionHistory',
|
||||
},
|
||||
{
|
||||
name: 'matchStats',
|
||||
schema: MatchStatsSchema,
|
||||
schemaName: 'matchStats',
|
||||
},
|
||||
];
|
||||
|
||||
export interface TournamentModelTypes {
|
||||
identity: Identity;
|
||||
community: Community;
|
||||
dakaoInboundMessage: DakaoInboundMessage;
|
||||
dakaoOutboxMessage: DakaoOutboxMessage;
|
||||
dakaoSendResultEvent: DakaoSendResultEvent;
|
||||
user: User;
|
||||
riotMatch: RiotMatch;
|
||||
tournamentCode: TournamentCode;
|
||||
legacyImportJob: LegacyImportJob;
|
||||
match: Match;
|
||||
auction: Auction;
|
||||
auctionHistory: AuctionHistoryEntry;
|
||||
matchStats: MatchStats;
|
||||
}
|
||||
@@ -1,9 +1,4 @@
|
||||
import {
|
||||
Inject,
|
||||
Injectable,
|
||||
Logger,
|
||||
OnModuleDestroy,
|
||||
} from '@nestjs/common';
|
||||
import { Inject, Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
|
||||
import type { createClient } from 'redis';
|
||||
import { GARNET_CLIENT } from './garnet.constants';
|
||||
|
||||
@@ -203,6 +198,13 @@ export class GarnetService implements OnModuleDestroy {
|
||||
return this.client.xAck(key, group, ids);
|
||||
}
|
||||
|
||||
public async deleteStreamEntries(
|
||||
key: string,
|
||||
ids: string | string[],
|
||||
): Promise<number> {
|
||||
return this.client.xDel(key, ids);
|
||||
}
|
||||
|
||||
public async streamLength(key: string): Promise<number> {
|
||||
return this.client.xLen(key);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,21 @@
|
||||
import { Inject, Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
|
||||
import {
|
||||
Inject,
|
||||
Injectable,
|
||||
Logger,
|
||||
OnModuleDestroy,
|
||||
} from '@nestjs/common';
|
||||
import { StringCodec } from 'nats';
|
||||
import type { Msg, NatsConnection, Subscription } from 'nats';
|
||||
AckPolicy,
|
||||
DeliverPolicy,
|
||||
nanos,
|
||||
ReplayPolicy,
|
||||
RetentionPolicy,
|
||||
StorageType,
|
||||
StringCodec,
|
||||
} from 'nats';
|
||||
import type {
|
||||
ConsumerMessages,
|
||||
JsMsg,
|
||||
Msg,
|
||||
NatsConnection,
|
||||
PubAck,
|
||||
Subscription,
|
||||
} from 'nats';
|
||||
import { NATS_CLIENT } from './nats.constants';
|
||||
|
||||
export type NatsMessageHandler<T = unknown> = (
|
||||
@@ -13,17 +23,62 @@ export type NatsMessageHandler<T = unknown> = (
|
||||
msg: Msg,
|
||||
) => Promise<void> | void;
|
||||
|
||||
export type JetStreamRetention = 'workqueue' | 'limits';
|
||||
|
||||
export type JetStreamMessageHandler<T = unknown> = (
|
||||
data: T,
|
||||
msg: JsMsg,
|
||||
) => Promise<void> | void;
|
||||
|
||||
export interface JetStreamStreamOptions {
|
||||
name: string;
|
||||
subjects: string[];
|
||||
retention: JetStreamRetention;
|
||||
maxAgeDays?: number;
|
||||
replicas?: number;
|
||||
}
|
||||
|
||||
export interface JetStreamConsumerOptions {
|
||||
stream: string;
|
||||
durable: string;
|
||||
filterSubject: string;
|
||||
description?: string;
|
||||
ackWaitMs?: number;
|
||||
backoffMs?: number[];
|
||||
maxDeliver?: number;
|
||||
maxAckPending?: number;
|
||||
replicas?: number;
|
||||
}
|
||||
|
||||
export interface JetStreamConsumeOptions {
|
||||
stream: string;
|
||||
durable: string;
|
||||
maxMessages?: number;
|
||||
expiresMs?: number;
|
||||
nakDelayMs?: number;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class NatsService implements OnModuleDestroy {
|
||||
private readonly logger = new Logger(NatsService.name);
|
||||
private readonly stringCodec = StringCodec();
|
||||
private readonly subscriptions = new Set<Subscription>();
|
||||
private readonly jetStreamConsumers = new Set<ConsumerMessages>();
|
||||
|
||||
constructor(
|
||||
@Inject(NATS_CLIENT) private readonly natsClient: NatsConnection,
|
||||
) {}
|
||||
|
||||
async onModuleDestroy() {
|
||||
for (const consumer of this.jetStreamConsumers) {
|
||||
try {
|
||||
await consumer.close();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
this.jetStreamConsumers.clear();
|
||||
|
||||
for (const sub of this.subscriptions) {
|
||||
try {
|
||||
sub.unsubscribe();
|
||||
@@ -68,6 +123,108 @@ export class NatsService implements OnModuleDestroy {
|
||||
return sub;
|
||||
}
|
||||
|
||||
public async publishJetStream<T = unknown>(
|
||||
subject: string,
|
||||
data: T,
|
||||
options?: { messageId?: string; timeoutMs?: number },
|
||||
): Promise<PubAck> {
|
||||
const ack = await this.natsClient
|
||||
.jetstream()
|
||||
.publish(subject, this.stringCodec.encode(JSON.stringify(data)), {
|
||||
msgID: options?.messageId,
|
||||
timeout: options?.timeoutMs ?? 5000,
|
||||
});
|
||||
return ack;
|
||||
}
|
||||
|
||||
public async ensureJetStreamStream(
|
||||
options: JetStreamStreamOptions,
|
||||
): Promise<void> {
|
||||
const manager = await this.natsClient.jetstreamManager();
|
||||
const config = {
|
||||
name: options.name,
|
||||
subjects: options.subjects,
|
||||
retention: this.toRetentionPolicy(options.retention),
|
||||
storage: StorageType.File,
|
||||
num_replicas: options.replicas ?? 1,
|
||||
max_age: options.maxAgeDays
|
||||
? nanos(options.maxAgeDays * 24 * 60 * 60 * 1000)
|
||||
: 0,
|
||||
};
|
||||
|
||||
try {
|
||||
await manager.streams.info(options.name);
|
||||
await manager.streams.update(options.name, {
|
||||
subjects: config.subjects,
|
||||
max_age: config.max_age,
|
||||
num_replicas: config.num_replicas,
|
||||
});
|
||||
return;
|
||||
} catch {
|
||||
await manager.streams.add(config);
|
||||
}
|
||||
}
|
||||
|
||||
public async ensureJetStreamConsumer(
|
||||
options: JetStreamConsumerOptions,
|
||||
): Promise<void> {
|
||||
const manager = await this.natsClient.jetstreamManager();
|
||||
const config = {
|
||||
durable_name: options.durable,
|
||||
name: options.durable,
|
||||
description: options.description,
|
||||
filter_subject: options.filterSubject,
|
||||
deliver_policy: DeliverPolicy.All,
|
||||
ack_policy: AckPolicy.Explicit,
|
||||
replay_policy: ReplayPolicy.Instant,
|
||||
ack_wait: nanos(options.ackWaitMs ?? 30000),
|
||||
backoff: (options.backoffMs ?? [5000, 30000, 120000, 600000]).map(
|
||||
(entry) => nanos(entry),
|
||||
),
|
||||
max_deliver: options.maxDeliver ?? 10,
|
||||
max_ack_pending: options.maxAckPending ?? 50,
|
||||
num_replicas: options.replicas ?? 1,
|
||||
};
|
||||
|
||||
try {
|
||||
await manager.consumers.info(options.stream, options.durable);
|
||||
await manager.consumers.update(options.stream, options.durable, config);
|
||||
return;
|
||||
} catch {
|
||||
await manager.consumers.add(options.stream, config);
|
||||
}
|
||||
}
|
||||
|
||||
public async consumeJetStream<T = unknown>(
|
||||
options: JetStreamConsumeOptions,
|
||||
handler: JetStreamMessageHandler<T>,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const consumer = await this.natsClient
|
||||
.jetstream()
|
||||
.consumers.get(options.stream, options.durable);
|
||||
const messages = await consumer.consume({
|
||||
max_messages: options.maxMessages ?? 10,
|
||||
expires: options.expiresMs ?? 30000,
|
||||
});
|
||||
this.jetStreamConsumers.add(messages);
|
||||
|
||||
try {
|
||||
for await (const msg of messages) {
|
||||
await this.dispatchJetStream(msg, handler, options);
|
||||
}
|
||||
} finally {
|
||||
this.jetStreamConsumers.delete(messages);
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.error(
|
||||
`JetStream consumer stream="${options.stream}" durable="${options.durable}" terminated: ${
|
||||
(err as Error)?.stack ?? err
|
||||
}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async consumeSubscription<T>(
|
||||
sub: Subscription,
|
||||
handler: NatsMessageHandler<T>,
|
||||
@@ -114,4 +271,46 @@ export class NatsService implements OnModuleDestroy {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async dispatchJetStream<T>(
|
||||
msg: JsMsg,
|
||||
handler: JetStreamMessageHandler<T>,
|
||||
options: JetStreamConsumeOptions,
|
||||
): Promise<void> {
|
||||
let data: T;
|
||||
try {
|
||||
data = JSON.parse(msg.string()) as T;
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Terminating undecodable JetStream message subject="${msg.subject}" stream="${options.stream}": ${
|
||||
(err as Error)?.message ?? err
|
||||
}`,
|
||||
);
|
||||
msg.term('invalid_json');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await handler(data, msg);
|
||||
const acked = await msg.ackAck({ timeout: 5000 });
|
||||
if (!acked) {
|
||||
this.logger.warn(
|
||||
`JetStream ack was not confirmed subject="${msg.subject}" stream="${options.stream}" seq=${msg.seq}`,
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.error(
|
||||
`JetStream handler error subject="${msg.subject}" stream="${options.stream}" seq=${msg.seq}: ${
|
||||
(err as Error)?.stack ?? err
|
||||
}`,
|
||||
);
|
||||
msg.nak(options.nakDelayMs ?? 5000);
|
||||
}
|
||||
}
|
||||
|
||||
private toRetentionPolicy(retention: JetStreamRetention): RetentionPolicy {
|
||||
return retention === 'workqueue'
|
||||
? RetentionPolicy.Workqueue
|
||||
: RetentionPolicy.Limits;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { SecretService } from './secret.service';
|
||||
|
||||
function makeConfig(values: Record<string, string | undefined> = {}) {
|
||||
return {
|
||||
get: jest.fn((key: string) => values[key] ?? process.env[key]),
|
||||
} as unknown as ConfigService;
|
||||
}
|
||||
|
||||
describe('SecretService', () => {
|
||||
const originalEnv = process.env;
|
||||
let fetchMock: jest.Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
process.env = { ...originalEnv };
|
||||
delete process.env.SECRET_SOURCE;
|
||||
delete process.env.TEST_SECRET;
|
||||
fetchMock = jest
|
||||
.fn()
|
||||
.mockRejectedValue(new Error('network calls are disabled in tests'));
|
||||
global.fetch = fetchMock;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.env = originalEnv;
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('defaults to environment-provided secrets without IMDS lookup', async () => {
|
||||
process.env.TEST_SECRET = 'from-env';
|
||||
const service = new SecretService(makeConfig());
|
||||
|
||||
await service.ready();
|
||||
|
||||
await expect(service.get('TEST_SECRET')).resolves.toBe('from-env');
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uses environment-provided secrets when SECRET_SOURCE is env', async () => {
|
||||
process.env.SECRET_SOURCE = 'env';
|
||||
process.env.TEST_SECRET = 'from-env-source';
|
||||
const service = new SecretService(makeConfig());
|
||||
|
||||
await service.ready();
|
||||
|
||||
await expect(service.get('TEST_SECRET')).resolves.toBe('from-env-source');
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uses the IMDS and Infisical bootstrap path only when SECRET_SOURCE is infisical', async () => {
|
||||
process.env.SECRET_SOURCE = 'infisical';
|
||||
const service = new SecretService(makeConfig());
|
||||
|
||||
await expect(service.ready()).rejects.toThrow(
|
||||
'Missing required bootstrap secret: INFISICAL_CLIENT_ID',
|
||||
);
|
||||
expect(fetchMock).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects unsupported SECRET_SOURCE values', async () => {
|
||||
process.env.SECRET_SOURCE = 'kubernetes';
|
||||
const service = new SecretService(makeConfig());
|
||||
|
||||
await expect(service.ready()).rejects.toThrow(
|
||||
'Invalid SECRET_SOURCE="kubernetes". Expected "env" or "infisical".',
|
||||
);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,23 @@ import { Injectable, Logger } from '@nestjs/common';
|
||||
import { InfisicalSDK } from '@infisical/sdk';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
type SecretMap = Record<string, string | boolean | undefined>;
|
||||
type SecretMap = Record<string, string | undefined>;
|
||||
type SecretSource = 'env' | 'infisical';
|
||||
|
||||
const DEFAULT_INFISICAL_SITE_URL = 'https://secret-manager.dahyeon.us/';
|
||||
const IMDS_TOKEN_TTL_SECONDS = 60;
|
||||
const IMDS_REQUEST_TIMEOUT_MS = 1500;
|
||||
const FALLBACK_IMDS_BASE_URLS = [
|
||||
'http://169.254.169.254',
|
||||
'http://host.docker.internal:8675',
|
||||
];
|
||||
|
||||
interface InfisicalBootstrapConfig {
|
||||
siteUrl: string;
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
projectId: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class SecretService {
|
||||
@@ -10,57 +26,8 @@ export class SecretService {
|
||||
|
||||
private secrets: SecretMap | null = null; // null = 아직 로드 전
|
||||
private loading?: Promise<void>; // 진행 중인 로드(중복 호출 방지)
|
||||
private infisicalClient: InfisicalSDK;
|
||||
|
||||
private readonly siteUrl: string;
|
||||
private readonly clientSecret: string;
|
||||
private readonly clientId: string;
|
||||
private readonly projectId: string;
|
||||
|
||||
private readonly PROCESS_ENVS = [
|
||||
'COSMOSDB_ENDPOINT',
|
||||
'COSMOSDB_KEY',
|
||||
'NATS_ENDPOINT',
|
||||
'NATS_TOKEN',
|
||||
'NATS_URL',
|
||||
'DAKAO_INBOUND_SUBJECT',
|
||||
'DAKAO_NATS_COMMAND_CHAT_SEND_MESSAGE_SUBJECT',
|
||||
'DAKAO_REPLY_SUBJECT_PREFIX',
|
||||
'DAKAO_COMMAND_SOURCE',
|
||||
'DAKAO_BOT_USER_ID',
|
||||
'DAKAO_INSTANCE_ID',
|
||||
'JWT_CLAIM_AUDIENCE',
|
||||
'MICROSOFT_ENTRAID_TENANT_ID',
|
||||
'MICROSOFT_ENTRAID_ALLOWED_ALGS',
|
||||
'AUTH_DEV_HEADER_ENABLED',
|
||||
// 필요시 추가
|
||||
] as const;
|
||||
|
||||
constructor(private readonly config: ConfigService) {
|
||||
this.siteUrl =
|
||||
this.config.get<string>('INFISICAL_SITE_URL') ??
|
||||
'https://secret-manager.dahyeon.us/';
|
||||
this.clientSecret = this.config.get<string>(
|
||||
'INFISICAL_CLIENT_SECRET',
|
||||
) as string;
|
||||
this.clientId = this.config.get<string>('INFISICAL_CLIENT_ID') as string;
|
||||
this.projectId = this.config.get<string>('INFISICAL_PROJECT_ID') as string;
|
||||
// console.log(this.siteUrl, this.clientSecret, this.clientId, this.projectId)
|
||||
|
||||
const missing = [
|
||||
!this.siteUrl && 'INFISICAL_SITE_URL',
|
||||
!this.clientId && 'INFISICAL_CLIENT_ID',
|
||||
!this.clientSecret && 'INFISICAL_CLIENT_SECRET',
|
||||
!this.projectId && 'INFISICAL_PROJECT_ID',
|
||||
].filter(Boolean);
|
||||
if (missing.length > 0) {
|
||||
throw new Error(
|
||||
`Missing required Infisical configuration: ${missing.join(', ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
this.infisicalClient = new InfisicalSDK({ siteUrl: this.siteUrl });
|
||||
}
|
||||
constructor(private readonly config: ConfigService) {}
|
||||
|
||||
/** 한 번만 로그인/페치. 동시에 여러 번 호출돼도 같은 Promise를 공유 */
|
||||
private async fetchSecrets(): Promise<void> {
|
||||
@@ -68,40 +35,13 @@ export class SecretService {
|
||||
if (this.loading) return this.loading; // 로드 중이면 그거 기다리기
|
||||
|
||||
this.loading = (async () => {
|
||||
await this.infisicalClient.auth().universalAuth.login({
|
||||
clientId: this.clientId,
|
||||
clientSecret: this.clientSecret,
|
||||
});
|
||||
// console.log(this.infisicalClient)
|
||||
|
||||
const res = await this.infisicalClient.secrets().listSecrets({
|
||||
environment:
|
||||
process.env.NODE_ENV === 'prod'
|
||||
? 'prod'
|
||||
: process.env.NODE_ENV === 'test'
|
||||
? 'staging'
|
||||
: 'dev',
|
||||
projectId: this.projectId,
|
||||
});
|
||||
|
||||
// 임시 객체에 채운 뒤 한 번에 교체(일관성 보장)
|
||||
const map: SecretMap = {};
|
||||
for (const s of res.secrets) {
|
||||
map[s.secretKey] = s.secretValue;
|
||||
const secretSource = this.resolveSecretSource();
|
||||
if (secretSource === 'env') {
|
||||
this.loadEnvironmentSecrets();
|
||||
return;
|
||||
}
|
||||
|
||||
// 필요한 값은 process.env에 반영
|
||||
for (const k of this.PROCESS_ENVS) {
|
||||
const v = map[k as string];
|
||||
if (typeof v === 'string' && v.length > 0) {
|
||||
process.env[k as string] = v;
|
||||
}
|
||||
}
|
||||
|
||||
this.secrets = map;
|
||||
this.logger.log(
|
||||
`Fetched ${Object.keys(map).length} secrets from Infisical`,
|
||||
);
|
||||
await this.fetchInfisicalSecrets();
|
||||
})();
|
||||
|
||||
try {
|
||||
@@ -111,6 +51,186 @@ export class SecretService {
|
||||
}
|
||||
}
|
||||
|
||||
private resolveSecretSource(): SecretSource {
|
||||
const source = this.config
|
||||
.get<string>('SECRET_SOURCE')
|
||||
?.trim()
|
||||
.toLowerCase();
|
||||
if (!source || source === 'env') return 'env';
|
||||
if (source === 'infisical') return 'infisical';
|
||||
|
||||
throw new Error(
|
||||
`Invalid SECRET_SOURCE="${source}". Expected "env" or "infisical".`,
|
||||
);
|
||||
}
|
||||
|
||||
private loadEnvironmentSecrets(): void {
|
||||
this.secrets = { ...process.env };
|
||||
this.logger.log('Using environment-provided secrets');
|
||||
}
|
||||
|
||||
private async fetchInfisicalSecrets(): Promise<void> {
|
||||
const bootstrapConfig = await this.resolveInfisicalBootstrapConfig();
|
||||
const infisicalClient = new InfisicalSDK({
|
||||
siteUrl: bootstrapConfig.siteUrl,
|
||||
});
|
||||
|
||||
await infisicalClient.auth().universalAuth.login({
|
||||
clientId: bootstrapConfig.clientId,
|
||||
clientSecret: bootstrapConfig.clientSecret,
|
||||
});
|
||||
|
||||
const res = await infisicalClient.secrets().listSecrets({
|
||||
environment:
|
||||
process.env.NODE_ENV === 'prod'
|
||||
? 'prod'
|
||||
: process.env.NODE_ENV === 'staging'
|
||||
? 'staging'
|
||||
: 'dev',
|
||||
projectId: bootstrapConfig.projectId,
|
||||
});
|
||||
|
||||
// 임시 객체에 채운 뒤 한 번에 교체(일관성 보장)
|
||||
const map: SecretMap = {};
|
||||
for (const s of res.secrets) {
|
||||
map[s.secretKey] = s.secretValue;
|
||||
}
|
||||
|
||||
// 앱 생명주기에서 필요한 env는 모두 SecretService가 process.env에 반영한다.
|
||||
for (const [k, v] of Object.entries(map)) {
|
||||
if (typeof v === 'string' && v.length > 0) {
|
||||
process.env[k] = v;
|
||||
}
|
||||
}
|
||||
|
||||
this.secrets = map;
|
||||
this.logger.log(
|
||||
`Fetched ${Object.keys(map).length} secrets from Infisical`,
|
||||
);
|
||||
}
|
||||
|
||||
private async resolveInfisicalBootstrapConfig(): Promise<InfisicalBootstrapConfig> {
|
||||
const [clientId, clientSecret, projectId] = await Promise.all([
|
||||
this.resolveBootstrapValue('INFISICAL_CLIENT_ID'),
|
||||
this.resolveBootstrapValue('INFISICAL_CLIENT_SECRET'),
|
||||
this.resolveBootstrapValue('INFISICAL_PROJECT_ID'),
|
||||
]);
|
||||
const siteUrl =
|
||||
(await this.resolveBootstrapValue('INFISICAL_SITE_URL', false)) ??
|
||||
DEFAULT_INFISICAL_SITE_URL;
|
||||
|
||||
const missing = [
|
||||
!siteUrl && 'INFISICAL_SITE_URL',
|
||||
!clientId && 'INFISICAL_CLIENT_ID',
|
||||
!clientSecret && 'INFISICAL_CLIENT_SECRET',
|
||||
!projectId && 'INFISICAL_PROJECT_ID',
|
||||
].filter(Boolean);
|
||||
if (missing.length > 0) {
|
||||
throw new Error(
|
||||
`Missing required Infisical bootstrap configuration: ${missing.join(', ')}`,
|
||||
);
|
||||
}
|
||||
if (!clientId || !clientSecret || !projectId) {
|
||||
throw new Error('Missing required Infisical bootstrap configuration.');
|
||||
}
|
||||
|
||||
return {
|
||||
siteUrl,
|
||||
clientId,
|
||||
clientSecret,
|
||||
projectId,
|
||||
};
|
||||
}
|
||||
|
||||
private async resolveBootstrapValue(
|
||||
key: string,
|
||||
required = true,
|
||||
): Promise<string | undefined> {
|
||||
const configured = this.config.get<string>(key)?.trim();
|
||||
if (configured) return configured;
|
||||
|
||||
const fromImds = await this.getImdsSecret(key);
|
||||
if (fromImds) {
|
||||
process.env[key] = fromImds;
|
||||
return fromImds;
|
||||
}
|
||||
|
||||
if (required) {
|
||||
throw new Error(`Missing required bootstrap secret: ${key}`);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private async getImdsSecret(key: string): Promise<string | undefined> {
|
||||
let lastError: Error | undefined;
|
||||
for (const baseUrl of this.resolveImdsBaseUrls()) {
|
||||
try {
|
||||
const token = await this.issueImdsToken(baseUrl);
|
||||
const secret = await this.fetchImdsText(
|
||||
`${baseUrl.replace(/\/$/u, '')}/latest/meta-data/secrets/${encodeURIComponent(key)}`,
|
||||
{
|
||||
'X-aws-ec2-metadata-token': token,
|
||||
},
|
||||
);
|
||||
return secret.trim() || undefined;
|
||||
} catch (error) {
|
||||
lastError = error instanceof Error ? error : new Error(String(error));
|
||||
}
|
||||
}
|
||||
|
||||
if (lastError) {
|
||||
this.logger.debug(
|
||||
`IMDS secret lookup failed for ${key}: ${lastError.message}`,
|
||||
);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private resolveImdsBaseUrls(): string[] {
|
||||
return [
|
||||
this.config.get<string>('IMDS_BASE_URL'),
|
||||
this.config.get<string>('MACHINE_METADATA_BASE_URL'),
|
||||
...FALLBACK_IMDS_BASE_URLS,
|
||||
]
|
||||
.map((value) => value?.trim())
|
||||
.filter((value): value is string => Boolean(value));
|
||||
}
|
||||
|
||||
private async issueImdsToken(baseUrl: string): Promise<string> {
|
||||
return this.fetchImdsText(
|
||||
`${baseUrl.replace(/\/$/u, '')}/latest/api/token`,
|
||||
{
|
||||
'X-aws-ec2-metadata-token-ttl-seconds': String(IMDS_TOKEN_TTL_SECONDS),
|
||||
},
|
||||
'PUT',
|
||||
);
|
||||
}
|
||||
|
||||
private async fetchImdsText(
|
||||
url: string,
|
||||
headers: Record<string, string>,
|
||||
method = 'GET',
|
||||
): Promise<string> {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(
|
||||
() => controller.abort(),
|
||||
IMDS_REQUEST_TIMEOUT_MS,
|
||||
);
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method,
|
||||
headers,
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`IMDS ${method} ${url} failed with ${response.status}`);
|
||||
}
|
||||
return response.text();
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
|
||||
/** lazy get: 필요할 때 처음 한번만 로드 */
|
||||
public async get<T = string>(key: string, fallback?: T): Promise<T> {
|
||||
if (!this.secrets) {
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'crypto';
|
||||
import mongoose from 'mongoose';
|
||||
import { MatchStatsService } from '../community-stats/match-stats.service';
|
||||
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type {
|
||||
@@ -26,7 +27,6 @@ import {
|
||||
buildUserByPuuidMap,
|
||||
countKnownParticipants,
|
||||
resolveExternalCount,
|
||||
resolveTeam100IsBlue,
|
||||
type UserByPuuidMap,
|
||||
} from './match-builder.util';
|
||||
import {
|
||||
@@ -56,6 +56,7 @@ export class LegacyImportService {
|
||||
private readonly garnetService: GarnetService,
|
||||
private readonly riotMatchService: RiotMatchService,
|
||||
private readonly communityStatsService: CommunityStatsService,
|
||||
private readonly matchStatsService: MatchStatsService,
|
||||
) {}
|
||||
|
||||
public async previewMembers(params: {
|
||||
@@ -108,8 +109,12 @@ export class LegacyImportService {
|
||||
]),
|
||||
);
|
||||
const windows = users
|
||||
.map((user) => this.resolveMemberWindow(user, windowStart, windowEnd, overrides))
|
||||
.filter((window) => window.startTime.getTime() <= window.endTime.getTime());
|
||||
.map((user) =>
|
||||
this.resolveMemberWindow(user, windowStart, windowEnd, overrides),
|
||||
)
|
||||
.filter(
|
||||
(window) => window.startTime.getTime() <= window.endTime.getTime(),
|
||||
);
|
||||
const LegacyImportJobModel =
|
||||
await this.connectionService.getModel('legacyImportJob');
|
||||
await LegacyImportJobModel.create({
|
||||
@@ -175,7 +180,9 @@ export class LegacyImportService {
|
||||
}): Promise<{ jobs: LegacyImportJobDocument[] }> {
|
||||
const LegacyImportJobModel =
|
||||
await this.connectionService.getModel('legacyImportJob');
|
||||
const jobs = await LegacyImportJobModel.find({ communityId: params.communityId })
|
||||
const jobs = await LegacyImportJobModel.find({
|
||||
communityId: params.communityId,
|
||||
})
|
||||
.sort({ startedAt: -1 })
|
||||
.limit(Math.min(params.limit ?? 10, 50))
|
||||
.exec();
|
||||
@@ -211,7 +218,8 @@ export class LegacyImportService {
|
||||
{ $set: { state: 'cancelled', completedAt: new Date() } },
|
||||
{ returnDocument: 'after' },
|
||||
).exec();
|
||||
if (!job) throw new NotFoundException('Running legacy import job not found.');
|
||||
if (!job)
|
||||
throw new NotFoundException('Running legacy import job not found.');
|
||||
await this.garnetService.delete(this.communityLockKey(params.communityId));
|
||||
return job;
|
||||
}
|
||||
@@ -285,7 +293,9 @@ export class LegacyImportService {
|
||||
.map((match) => match.result?.games[0]?.riotMatchId)
|
||||
.filter((matchId): matchId is string => Boolean(matchId));
|
||||
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
||||
const rawDocs = await RiotMatchModel.find({ matchId: { $in: riotMatchIds } })
|
||||
const rawDocs = await RiotMatchModel.find({
|
||||
matchId: { $in: riotMatchIds },
|
||||
})
|
||||
.lean()
|
||||
.exec();
|
||||
const rawById = new Map(
|
||||
@@ -306,14 +316,16 @@ export class LegacyImportService {
|
||||
externalCount: raw
|
||||
? resolveExternalCount(raw, userByPuuid)
|
||||
: Math.max(0, 10 - memberCount),
|
||||
blueScore: match.result?.blueScore ?? 0,
|
||||
redScore: match.result?.redScore ?? 0,
|
||||
winnerSide: match.result?.winnerSide,
|
||||
teamAIndex: match.result?.seriesResults?.[0]?.teamAIndex ?? 1,
|
||||
teamBIndex: match.result?.seriesResults?.[0]?.teamBIndex ?? 2,
|
||||
teamAWins: match.result?.seriesResults?.[0]?.teamAWins ?? 0,
|
||||
teamBWins: match.result?.seriesResults?.[0]?.teamBWins ?? 0,
|
||||
winnerTeamIndex: match.result?.winnerTeamIndex,
|
||||
};
|
||||
}),
|
||||
nextCursor:
|
||||
matches.length > limit
|
||||
? visible[visible.length - 1]?.scheduledAt.getTime() ?? null
|
||||
? (visible[visible.length - 1]?.scheduledAt.getTime() ?? null)
|
||||
: null,
|
||||
};
|
||||
}
|
||||
@@ -327,11 +339,22 @@ export class LegacyImportService {
|
||||
.map((id) => new mongoose.Types.ObjectId(id));
|
||||
if (ids.length === 0) return { deleted: 0 };
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const result = await MatchModel.deleteMany({
|
||||
const targets = await MatchModel.find({
|
||||
_id: { $in: ids },
|
||||
communityId: params.communityId,
|
||||
legacyImported: true,
|
||||
})
|
||||
.select({ _id: 1 })
|
||||
.exec();
|
||||
const targetIds = targets.map((match) => match._id);
|
||||
if (targetIds.length === 0) return { deleted: 0 };
|
||||
|
||||
const result = await MatchModel.deleteMany({
|
||||
_id: { $in: targetIds },
|
||||
communityId: params.communityId,
|
||||
legacyImported: true,
|
||||
}).exec();
|
||||
await this.matchStatsService.removeByMatches(targetIds);
|
||||
await this.communityStatsService.invalidateCommunity(params.communityId);
|
||||
return { deleted: result.deletedCount ?? 0 };
|
||||
}
|
||||
@@ -347,12 +370,15 @@ export class LegacyImportService {
|
||||
const riotMatchIds = matches
|
||||
.map(
|
||||
(match) =>
|
||||
match.result?.games[0]?.riotMatchId ?? match.result?.riotMatchIds?.[0],
|
||||
match.result?.games[0]?.riotMatchId ??
|
||||
match.result?.riotMatchIds?.[0],
|
||||
)
|
||||
.filter((matchId): matchId is string => Boolean(matchId));
|
||||
|
||||
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
||||
const rawDocs = await RiotMatchModel.find({ matchId: { $in: riotMatchIds } })
|
||||
const rawDocs = await RiotMatchModel.find({
|
||||
matchId: { $in: riotMatchIds },
|
||||
})
|
||||
.lean()
|
||||
.exec();
|
||||
const rawById = new Map<string, RiotMatchDto>();
|
||||
@@ -386,32 +412,46 @@ export class LegacyImportService {
|
||||
if (!raw || !riotMatchId) {
|
||||
result.skippedMissingRaw += 1;
|
||||
if (Object.keys(update).length > 0) {
|
||||
await MatchModel.updateOne({ _id: match._id }, { $set: update }).exec();
|
||||
await MatchModel.updateOne(
|
||||
{ _id: match._id },
|
||||
{ $set: update },
|
||||
).exec();
|
||||
await this.matchStatsService.buildAndUpsert(match._id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const team100IsBlue = resolveTeam100IsBlue(raw, userByPuuid);
|
||||
const participants = buildParticipantsSnapshot(raw, userByPuuid);
|
||||
const gameResult = buildGameResult(raw, userByPuuid, team100IsBlue, 1);
|
||||
const gameResult = buildGameResult(raw, userByPuuid, 1);
|
||||
if (!gameResult || participants.length === 0) {
|
||||
result.skippedNoKnownParticipants += 1;
|
||||
if (Object.keys(update).length > 0) {
|
||||
await MatchModel.updateOne({ _id: match._id }, { $set: update }).exec();
|
||||
await MatchModel.updateOne(
|
||||
{ _id: match._id },
|
||||
{ $set: update },
|
||||
).exec();
|
||||
await this.matchStatsService.buildAndUpsert(match._id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const winnerSide = gameResult.winnerSide;
|
||||
const winnerTeamIndex = gameResult.winnerTeamIndex;
|
||||
update.mapId = raw.info.mapId ?? match.mapId;
|
||||
update.participants = participants;
|
||||
update.teams = buildTeams(raw, userByPuuid, team100IsBlue);
|
||||
update.teams = buildTeams(raw, userByPuuid);
|
||||
update.result = {
|
||||
winnerSide,
|
||||
blueScore: winnerSide === 'blue' ? 1 : 0,
|
||||
redScore: winnerSide === 'red' ? 1 : 0,
|
||||
winnerTeamIndex,
|
||||
riotMatchIds: [riotMatchId],
|
||||
games: [gameResult],
|
||||
seriesResults: [
|
||||
{
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 2,
|
||||
teamAWins: winnerTeamIndex === 1 ? 1 : 0,
|
||||
teamBWins: winnerTeamIndex === 2 ? 1 : 0,
|
||||
winnerTeamIndex,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
await MatchModel.updateOne(
|
||||
@@ -422,6 +462,7 @@ export class LegacyImportService {
|
||||
},
|
||||
{ $set: update },
|
||||
).exec();
|
||||
await this.matchStatsService.buildAndUpsert(match._id);
|
||||
result.rebuilt += 1;
|
||||
}
|
||||
|
||||
@@ -432,7 +473,9 @@ export class LegacyImportService {
|
||||
return result;
|
||||
}
|
||||
|
||||
private async collectMatchIds(job: LegacyImportMemberJob): Promise<Set<string>> {
|
||||
private async collectMatchIds(
|
||||
job: LegacyImportMemberJob,
|
||||
): Promise<Set<string>> {
|
||||
const matchIds = new Set<string>();
|
||||
let start = 0;
|
||||
while (true) {
|
||||
@@ -471,16 +514,18 @@ export class LegacyImportService {
|
||||
});
|
||||
if (existing) return 'duplicate';
|
||||
|
||||
const detail = await this.ensureRiotMatchPersisted(riotMatchId, job.region);
|
||||
const detail = await this.ensureRiotMatchPersisted(
|
||||
riotMatchId,
|
||||
job.region,
|
||||
);
|
||||
if (!detail.info.tournamentCode) return 'skipped';
|
||||
const counts = countKnownParticipants(detail, userByPuuid);
|
||||
if (counts.total === 0) return 'skipped';
|
||||
|
||||
const team100IsBlue = resolveTeam100IsBlue(detail, userByPuuid);
|
||||
const gameResult = buildGameResult(detail, userByPuuid, team100IsBlue, 1);
|
||||
const gameResult = buildGameResult(detail, userByPuuid, 1);
|
||||
if (!gameResult || gameResult.participants.length === 0) return 'skipped';
|
||||
|
||||
const winnerSide = gameResult.winnerSide;
|
||||
const winnerTeamIndex = gameResult.winnerTeamIndex;
|
||||
const matchPayload: Partial<Match> = {
|
||||
communityId: new mongoose.Types.ObjectId(job.communityId),
|
||||
title: this.formatLegacyDate(detail.info.gameCreation),
|
||||
@@ -490,17 +535,25 @@ export class LegacyImportService {
|
||||
scheduledAt: new Date(detail.info.gameCreation),
|
||||
maxParticipants: 10,
|
||||
gameCount: 1,
|
||||
gameMode: 'pair',
|
||||
tournamentCodeIds: [],
|
||||
teamBuiltAt: new Date(detail.info.gameCreation),
|
||||
hostUserId: new mongoose.Types.ObjectId(job.triggeredBy),
|
||||
participants: buildParticipantsSnapshot(detail, userByPuuid),
|
||||
teams: buildTeams(detail, userByPuuid, team100IsBlue),
|
||||
teams: buildTeams(detail, userByPuuid),
|
||||
result: {
|
||||
winnerSide,
|
||||
blueScore: winnerSide === 'blue' ? 1 : 0,
|
||||
redScore: winnerSide === 'red' ? 1 : 0,
|
||||
winnerTeamIndex,
|
||||
riotMatchIds: [riotMatchId],
|
||||
games: [gameResult],
|
||||
seriesResults: [
|
||||
{
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 2,
|
||||
teamAWins: winnerTeamIndex === 1 ? 1 : 0,
|
||||
teamBWins: winnerTeamIndex === 2 ? 1 : 0,
|
||||
winnerTeamIndex,
|
||||
},
|
||||
],
|
||||
},
|
||||
legacyImported: true,
|
||||
legacyImportSource: {
|
||||
@@ -513,7 +566,8 @@ export class LegacyImportService {
|
||||
notices: [],
|
||||
schedule: [],
|
||||
};
|
||||
await MatchModel.create(matchPayload);
|
||||
const match = await MatchModel.create(matchPayload);
|
||||
await this.matchStatsService.buildAndUpsert(match._id);
|
||||
return 'imported';
|
||||
} catch (error) {
|
||||
await this.recordError(job.parentJobId, {
|
||||
@@ -532,7 +586,9 @@ export class LegacyImportService {
|
||||
region: RiotRegionalRoute,
|
||||
): Promise<RiotMatchDto> {
|
||||
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
||||
const stored = await RiotMatchModel.findOne({ matchId: riotMatchId }).exec();
|
||||
const stored = await RiotMatchModel.findOne({
|
||||
matchId: riotMatchId,
|
||||
}).exec();
|
||||
if (isRiotMatchDto(stored?.raw)) return stored.raw;
|
||||
|
||||
const dto = await this.riotMatchService.getMatch(riotMatchId, { region });
|
||||
@@ -574,7 +630,9 @@ export class LegacyImportService {
|
||||
const average =
|
||||
current.averageMemberSeconds === undefined
|
||||
? stats.elapsedSeconds
|
||||
: Math.round(current.averageMemberSeconds * 0.7 + stats.elapsedSeconds * 0.3);
|
||||
: Math.round(
|
||||
current.averageMemberSeconds * 0.7 + stats.elapsedSeconds * 0.3,
|
||||
);
|
||||
|
||||
const nextProcessed = current.processedMembers + 1;
|
||||
const completed = nextProcessed >= current.totalMembers;
|
||||
@@ -617,7 +675,8 @@ export class LegacyImportService {
|
||||
jobId: job.parentJobId,
|
||||
}).exec();
|
||||
if (!legacyJob || legacyJob.state === 'cancelled') return null;
|
||||
if (legacyJob.state === 'completed' || legacyJob.state === 'failed') return null;
|
||||
if (legacyJob.state === 'completed' || legacyJob.state === 'failed')
|
||||
return null;
|
||||
return legacyJob;
|
||||
}
|
||||
|
||||
@@ -672,7 +731,12 @@ export class LegacyImportService {
|
||||
windowStart: Date,
|
||||
windowEnd: Date,
|
||||
): LegacyImportMemberWindowView {
|
||||
const resolved = this.resolveMemberWindow(user, windowStart, windowEnd, new Map());
|
||||
const resolved = this.resolveMemberWindow(
|
||||
user,
|
||||
windowStart,
|
||||
windowEnd,
|
||||
new Map(),
|
||||
);
|
||||
const account =
|
||||
user.riotAccounts.find((riotAccount) => riotAccount.isPrimary) ??
|
||||
user.riotAccounts[0];
|
||||
@@ -717,10 +781,7 @@ export class LegacyImportService {
|
||||
};
|
||||
}
|
||||
|
||||
private resolveWindow(params: {
|
||||
windowStart?: string;
|
||||
windowEnd?: string;
|
||||
}) {
|
||||
private resolveWindow(params: { windowStart?: string; windowEnd?: string }) {
|
||||
const windowStart =
|
||||
this.parseOptionalDate(params.windowStart) ??
|
||||
new Date(LEGACY_IMPORT_DEFAULT_START_ISO);
|
||||
@@ -741,7 +802,9 @@ export class LegacyImportService {
|
||||
}
|
||||
|
||||
private minDate(...values: Array<Date | undefined>): Date {
|
||||
return new Date(Math.min(...values.filter(Boolean).map((date) => date!.getTime())));
|
||||
return new Date(
|
||||
Math.min(...values.filter(Boolean).map((date) => date!.getTime())),
|
||||
);
|
||||
}
|
||||
|
||||
private normalizeLegacyTitle(title: string, gameCreation: number): string {
|
||||
@@ -768,8 +831,8 @@ export class LegacyImportService {
|
||||
function isRiotMatchDto(value: unknown): value is RiotMatchDto {
|
||||
return Boolean(
|
||||
value &&
|
||||
typeof value === 'object' &&
|
||||
'metadata' in value &&
|
||||
'info' in value,
|
||||
typeof value === 'object' &&
|
||||
'metadata' in value &&
|
||||
'info' in value,
|
||||
);
|
||||
}
|
||||
@@ -55,9 +55,11 @@ export interface LegacyMatchListResponse {
|
||||
riotMatchId: string | null;
|
||||
memberCount: number;
|
||||
externalCount: number;
|
||||
blueScore: number;
|
||||
redScore: number;
|
||||
winnerSide?: 'blue' | 'red';
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
teamAWins: number;
|
||||
teamBWins: number;
|
||||
winnerTeamIndex?: number;
|
||||
}>;
|
||||
nextCursor: number | null;
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import type {
|
||||
MatchTeam,
|
||||
Position,
|
||||
RiotAccount,
|
||||
TeamSide,
|
||||
UserDocument,
|
||||
} from '../global/database/schema';
|
||||
import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types';
|
||||
@@ -91,10 +90,11 @@ export function buildParticipantsSnapshot(
|
||||
export function buildTeams(
|
||||
detail: RiotMatchDto,
|
||||
userByPuuid: UserByPuuidMap,
|
||||
team100IsBlue: boolean,
|
||||
): MatchTeam[] {
|
||||
return (['blue', 'red'] as TeamSide[]).map((side) => {
|
||||
const teamId = resolveRiotTeamId(side, team100IsBlue);
|
||||
return [
|
||||
{ teamIndex: 1, teamId: RIOT_BLUE_TEAM_ID },
|
||||
{ teamIndex: 2, teamId: RIOT_RED_TEAM_ID },
|
||||
].map(({ teamIndex, teamId }) => {
|
||||
const members = detail.info.participants
|
||||
.filter((participant) => participant.teamId === teamId)
|
||||
.map((participant) => {
|
||||
@@ -107,8 +107,8 @@ export function buildTeams(
|
||||
})
|
||||
.filter((member): member is NonNullable<typeof member> => Boolean(member));
|
||||
return {
|
||||
side,
|
||||
name: side === 'blue' ? '블루팀' : '레드팀',
|
||||
teamIndex,
|
||||
name: `${teamIndex}팀`,
|
||||
members,
|
||||
};
|
||||
});
|
||||
@@ -117,20 +117,21 @@ export function buildTeams(
|
||||
export function buildGameResult(
|
||||
detail: RiotMatchDto,
|
||||
userByPuuid: UserByPuuidMap,
|
||||
team100IsBlue: boolean,
|
||||
gameNumber = 1,
|
||||
): MatchGameResult | null {
|
||||
const winningTeam = detail.info.teams.find((team) => team.win);
|
||||
if (!winningTeam) return null;
|
||||
const winnerSide = resolveSide(winningTeam.teamId, team100IsBlue);
|
||||
const winnerSide = resolveSide(winningTeam.teamId);
|
||||
if (!winnerSide) return null;
|
||||
const winnerTeamIndex = winnerSide === 'blue' ? 1 : 2;
|
||||
const participants = detail.info.participants
|
||||
.map((participant) => {
|
||||
const user = userByPuuid.get(participant.puuid);
|
||||
const side = resolveSide(participant.teamId, team100IsBlue);
|
||||
const side = resolveSide(participant.teamId);
|
||||
if (!user || !side) return null;
|
||||
return {
|
||||
userId: user.userId,
|
||||
teamIndex: side === 'blue' ? 1 : 2,
|
||||
side,
|
||||
championId: participant.championId,
|
||||
kills: participant.kills,
|
||||
@@ -146,6 +147,9 @@ export function buildGameResult(
|
||||
return {
|
||||
gameNumber,
|
||||
riotMatchId: detail.metadata.matchId,
|
||||
blueTeamIndex: 1,
|
||||
redTeamIndex: 2,
|
||||
winnerTeamIndex,
|
||||
winnerSide,
|
||||
gameCreation: detail.info.gameCreation,
|
||||
gameDuration: detail.info.gameDuration,
|
||||
@@ -162,16 +166,9 @@ export function resolveExternalCount(
|
||||
).length;
|
||||
}
|
||||
|
||||
function resolveRiotTeamId(side: TeamSide, team100IsBlue: boolean): number {
|
||||
if (side === 'blue') {
|
||||
return team100IsBlue ? RIOT_BLUE_TEAM_ID : RIOT_RED_TEAM_ID;
|
||||
}
|
||||
return team100IsBlue ? RIOT_RED_TEAM_ID : RIOT_BLUE_TEAM_ID;
|
||||
}
|
||||
|
||||
function resolveSide(teamId: number, team100IsBlue: boolean): TeamSide | null {
|
||||
if (teamId === RIOT_BLUE_TEAM_ID) return team100IsBlue ? 'blue' : 'red';
|
||||
if (teamId === RIOT_RED_TEAM_ID) return team100IsBlue ? 'red' : 'blue';
|
||||
function resolveSide(teamId: number): 'blue' | 'red' | null {
|
||||
if (teamId === RIOT_BLUE_TEAM_ID) return 'blue';
|
||||
if (teamId === RIOT_RED_TEAM_ID) return 'red';
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -99,6 +99,18 @@ export class MatchHistoryService {
|
||||
losses: tier.losses,
|
||||
fetchedAt: tier.fetchedAt.toISOString(),
|
||||
})),
|
||||
tierHistory: [...context.account.tierHistory]
|
||||
.sort((left, right) => left.recordedAt.getTime() - right.recordedAt.getTime())
|
||||
.map((entry) => ({
|
||||
queueType: entry.queueType,
|
||||
tier: entry.tier,
|
||||
rank: entry.rank,
|
||||
leaguePoints: entry.leaguePoints,
|
||||
wins: entry.wins,
|
||||
losses: entry.losses,
|
||||
recordedAt: entry.recordedAt.toISOString(),
|
||||
season: entry.season,
|
||||
})),
|
||||
season: context.season,
|
||||
seasons: this.resolveSeasons(context.community),
|
||||
lastFetchedAt: lastFetchedAt?.toISOString() ?? null,
|
||||
@@ -579,16 +591,45 @@ export class MatchHistoryService {
|
||||
},
|
||||
participants: match.info.participants
|
||||
.filter((participant) => participant.teamId === team.teamId)
|
||||
.map((participant) => ({
|
||||
puuid: participant.puuid,
|
||||
gameName: participant.riotIdGameName || participant.summonerName || 'Unknown',
|
||||
tagLine: participant.riotIdTagLine || '',
|
||||
championId: participant.championId,
|
||||
teamPosition: participant.teamPosition || participant.individualPosition,
|
||||
kills: participant.kills,
|
||||
deaths: participant.deaths,
|
||||
assists: participant.assists,
|
||||
})),
|
||||
.map((participant) => {
|
||||
const totalCs = this.resolveTotalCs(participant);
|
||||
const minutes = this.resolveGameMinutes(match, participant);
|
||||
|
||||
return {
|
||||
puuid: participant.puuid,
|
||||
gameName: participant.riotIdGameName || participant.summonerName || 'Unknown',
|
||||
tagLine: participant.riotIdTagLine || '',
|
||||
championId: participant.championId,
|
||||
championLevel: participant.champLevel,
|
||||
teamPosition: participant.teamPosition || participant.individualPosition,
|
||||
kills: participant.kills,
|
||||
deaths: participant.deaths,
|
||||
assists: participant.assists,
|
||||
items: [
|
||||
participant.item0,
|
||||
participant.item1,
|
||||
participant.item2,
|
||||
participant.item3,
|
||||
participant.item4,
|
||||
participant.item5,
|
||||
],
|
||||
trinket: participant.item6,
|
||||
summonerSpells: [participant.summoner1Id, participant.summoner2Id],
|
||||
perks: this.resolvePerks(participant),
|
||||
totalCs,
|
||||
csPerMin: this.average(totalCs, minutes),
|
||||
goldEarned: participant.goldEarned,
|
||||
damageDealtToChampions: participant.totalDamageDealtToChampions,
|
||||
damageTaken: participant.totalDamageTaken,
|
||||
visionScore: participant.visionScore,
|
||||
wardsPlaced: participant.wardsPlaced,
|
||||
wardsKilled: participant.wardsKilled,
|
||||
controlWardsBought: this.numberField(
|
||||
participant,
|
||||
'visionWardsBoughtInGame',
|
||||
),
|
||||
};
|
||||
}),
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,16 @@ export interface UserHistoryProfileResponse {
|
||||
losses: number;
|
||||
fetchedAt: string;
|
||||
}>;
|
||||
tierHistory: Array<{
|
||||
queueType: string;
|
||||
tier: string;
|
||||
rank?: string;
|
||||
leaguePoints?: number;
|
||||
wins?: number;
|
||||
losses?: number;
|
||||
recordedAt: string;
|
||||
season?: string;
|
||||
}>;
|
||||
season: HistorySeasonDto;
|
||||
seasons: HistorySeasonDto[];
|
||||
lastFetchedAt: string | null;
|
||||
@@ -98,6 +108,31 @@ export interface RecentMatchesResponse {
|
||||
season: HistorySeasonDto;
|
||||
}
|
||||
|
||||
export interface RecentMatchTeamParticipantView {
|
||||
puuid: string;
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
championId: number;
|
||||
championLevel: number;
|
||||
teamPosition: string;
|
||||
kills: number;
|
||||
deaths: number;
|
||||
assists: number;
|
||||
items: number[];
|
||||
trinket: number;
|
||||
summonerSpells: [number, number];
|
||||
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
|
||||
totalCs: number;
|
||||
csPerMin: number;
|
||||
goldEarned: number;
|
||||
damageDealtToChampions: number;
|
||||
damageTaken: number;
|
||||
visionScore: number;
|
||||
wardsPlaced: number;
|
||||
wardsKilled: number;
|
||||
controlWardsBought: number;
|
||||
}
|
||||
|
||||
export interface RecentMatchView {
|
||||
matchId: string;
|
||||
queueId: number;
|
||||
@@ -132,15 +167,6 @@ export interface RecentMatchView {
|
||||
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;
|
||||
}>;
|
||||
participants: RecentMatchTeamParticipantView[];
|
||||
}>;
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { Type } from 'class-transformer';
|
||||
import {
|
||||
ArrayMaxSize,
|
||||
ArrayMinSize,
|
||||
registerDecorator,
|
||||
IsArray,
|
||||
IsDate,
|
||||
IsEnum,
|
||||
@@ -12,9 +13,40 @@ import {
|
||||
Min,
|
||||
MinLength,
|
||||
ValidateNested,
|
||||
ValidationArguments,
|
||||
ValidationOptions,
|
||||
} from 'class-validator';
|
||||
import { POSITIONS } from '../../global/database/schema';
|
||||
import type { Position } from '../../global/database/schema';
|
||||
import { MATCH_GAME_MODES, POSITIONS } from '../../global/database/schema';
|
||||
import type { MatchGameMode, Position } from '../../global/database/schema';
|
||||
|
||||
function IsMultipleOf(
|
||||
multiple: number,
|
||||
validationOptions?: ValidationOptions,
|
||||
): PropertyDecorator {
|
||||
return (object, propertyName) => {
|
||||
registerDecorator({
|
||||
name: 'isMultipleOf',
|
||||
target: object.constructor,
|
||||
propertyName: String(propertyName),
|
||||
constraints: [multiple],
|
||||
options: validationOptions,
|
||||
validator: {
|
||||
validate(value: unknown, args: ValidationArguments) {
|
||||
const [divisor] = args.constraints as [number];
|
||||
return (
|
||||
typeof value === 'number' &&
|
||||
Number.isInteger(value) &&
|
||||
value % divisor === 0
|
||||
);
|
||||
},
|
||||
defaultMessage(args: ValidationArguments) {
|
||||
const [divisor] = args.constraints as [number];
|
||||
return `${args.property} must be a multiple of ${divisor}.`;
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export class PositionPreferenceDto {
|
||||
@IsEnum(POSITIONS)
|
||||
@@ -56,7 +88,8 @@ export class CreateMatchDto {
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(2)
|
||||
@Min(10)
|
||||
@IsMultipleOf(10)
|
||||
maxParticipants?: number;
|
||||
|
||||
@IsOptional()
|
||||
@@ -64,6 +97,10 @@ export class CreateMatchDto {
|
||||
@Min(1)
|
||||
gameCount?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(MATCH_GAME_MODES)
|
||||
gameMode?: MatchGameMode;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
@@ -106,7 +143,8 @@ export class UpdateMatchDto {
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(2)
|
||||
@Min(10)
|
||||
@IsMultipleOf(10)
|
||||
maxParticipants?: number;
|
||||
|
||||
@IsOptional()
|
||||
@@ -114,6 +152,10 @@ export class UpdateMatchDto {
|
||||
@Min(1)
|
||||
gameCount?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(MATCH_GAME_MODES)
|
||||
gameMode?: MatchGameMode;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
@@ -131,6 +173,14 @@ export class UpdateMatchDto {
|
||||
schedule?: MatchScheduleItemDto[];
|
||||
}
|
||||
|
||||
export class UpdateParticipantDto {
|
||||
@IsEnum(POSITIONS)
|
||||
mainPosition!: Position;
|
||||
|
||||
@IsEnum(POSITIONS)
|
||||
subPosition!: Position;
|
||||
}
|
||||
|
||||
export class JoinMatchDto {
|
||||
@IsArray()
|
||||
@ArrayMinSize(1)
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
CreateMatchDto,
|
||||
JoinMatchDto,
|
||||
UpdateMatchDto,
|
||||
UpdateParticipantDto,
|
||||
} from './dto/create-match.dto';
|
||||
import { MatchService } from './match.service';
|
||||
|
||||
@@ -54,6 +55,7 @@ export class MatchController {
|
||||
scheduledAt: body.scheduledAt,
|
||||
maxParticipants: body.maxParticipants ?? 10,
|
||||
gameCount: body.gameCount,
|
||||
gameMode: body.gameMode ?? 'pair',
|
||||
prizes: body.prizes ?? [],
|
||||
notices: body.notices ?? [],
|
||||
schedule: body.schedule ?? [],
|
||||
@@ -136,6 +138,49 @@ export class MatchController {
|
||||
});
|
||||
}
|
||||
|
||||
// 관리자 전용 — 참가자 주/부 포지션 변경.
|
||||
@Patch(':matchId/participants/:userId')
|
||||
@Roles('admin', 'owner')
|
||||
@UseGuards(RolesGuard)
|
||||
public async updateParticipant(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
|
||||
@Body() body: UpdateParticipantDto,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
const match = await this.matchService.updateParticipantPositions({
|
||||
matchId,
|
||||
communityId,
|
||||
targetUserId: userId,
|
||||
mainPosition: body.mainPosition,
|
||||
subPosition: body.subPosition,
|
||||
});
|
||||
return this.matchService.serialize(match);
|
||||
}
|
||||
|
||||
// 관리자 전용 — 참가자 강제 제외.
|
||||
@Delete(':matchId/participants/:userId')
|
||||
@Roles('admin', 'owner')
|
||||
@UseGuards(RolesGuard)
|
||||
@HttpCode(HttpStatus.NO_CONTENT)
|
||||
public async removeParticipant(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
await this.matchService.removeParticipant({
|
||||
matchId,
|
||||
communityId,
|
||||
targetUserId: userId,
|
||||
});
|
||||
}
|
||||
|
||||
private resolveJoinerUserId(
|
||||
currentUser: UserDocument | undefined,
|
||||
bodyUserId?: string,
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { MatchService } from './match.service';
|
||||
|
||||
describe('MatchService', () => {
|
||||
function createService(match: Record<string, unknown>) {
|
||||
const MatchModel = {
|
||||
findById: jest.fn().mockResolvedValue(match),
|
||||
};
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockImplementation(async (name: string) => {
|
||||
if (name === 'match') return MatchModel;
|
||||
return {};
|
||||
}),
|
||||
};
|
||||
const tournamentCodeService = {
|
||||
buildSlots: jest.fn().mockResolvedValue([]),
|
||||
releaseFromMatch: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const communityStatsService = {
|
||||
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const matchStatsService = {
|
||||
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
|
||||
removeByMatch: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
|
||||
return {
|
||||
service: new MatchService(
|
||||
connectionService as never,
|
||||
tournamentCodeService as never,
|
||||
communityStatsService as never,
|
||||
matchStatsService as never,
|
||||
),
|
||||
tournamentCodeService,
|
||||
matchStatsService,
|
||||
};
|
||||
}
|
||||
|
||||
it('clears game schedule when a built match returns to recruiting', async () => {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const match = {
|
||||
communityId,
|
||||
status: 'team-built',
|
||||
tournamentCodeIds: [],
|
||||
gameSchedule: [{ gameNumber: 1, teamAIndex: 2, teamBIndex: 4 }],
|
||||
teams: [{ teamIndex: 1 }],
|
||||
teamBuiltAt: new Date(),
|
||||
result: { games: [] },
|
||||
resultPollState: { state: 'polling' },
|
||||
set: jest.fn(function (
|
||||
this: Record<string, unknown>,
|
||||
patch: Record<string, unknown>,
|
||||
) {
|
||||
Object.assign(this, patch);
|
||||
}),
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const { service, tournamentCodeService, matchStatsService } =
|
||||
createService(match);
|
||||
|
||||
await service.update({
|
||||
matchId: new mongoose.Types.ObjectId(),
|
||||
communityId,
|
||||
patch: { status: 'recruiting' },
|
||||
});
|
||||
|
||||
expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled();
|
||||
expect(match.tournamentCodeIds).toEqual([]);
|
||||
expect(match.gameSchedule).toEqual([]);
|
||||
expect(match.teamBuiltAt).toBeUndefined();
|
||||
expect(match.result).toBeUndefined();
|
||||
expect(match.resultPollState).toBeUndefined();
|
||||
expect(match.save).toHaveBeenCalledTimes(1);
|
||||
expect(matchStatsService.removeByMatch).toHaveBeenCalledWith(match._id);
|
||||
});
|
||||
|
||||
it('releases reserved codes when returning a built match to recruiting', async () => {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const codeId = new mongoose.Types.ObjectId();
|
||||
const match = {
|
||||
communityId,
|
||||
status: 'in-progress',
|
||||
tournamentCodeIds: [codeId],
|
||||
gameSchedule: [{ gameNumber: 1, teamAIndex: 1, teamBIndex: 3 }],
|
||||
set: jest.fn(function (
|
||||
this: Record<string, unknown>,
|
||||
patch: Record<string, unknown>,
|
||||
) {
|
||||
Object.assign(this, patch);
|
||||
}),
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const { service, tournamentCodeService } = createService(match);
|
||||
|
||||
await service.update({
|
||||
matchId: new mongoose.Types.ObjectId(),
|
||||
communityId,
|
||||
patch: { status: 'recruiting' },
|
||||
});
|
||||
|
||||
expect(tournamentCodeService.releaseFromMatch).toHaveBeenCalledWith(match);
|
||||
expect(match.tournamentCodeIds).toEqual([]);
|
||||
expect(match.gameSchedule).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,21 +1,29 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
InternalServerErrorException,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { MatchStatsService } from '../community-stats/match-stats.service';
|
||||
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import {
|
||||
Match,
|
||||
MatchDocument,
|
||||
MatchSeriesResult,
|
||||
MatchStatus,
|
||||
Position,
|
||||
PositionPreference,
|
||||
TierInfo,
|
||||
} from '../global/database/schema';
|
||||
import { DEFAULT_TOURNAMENT_GAME_COUNT } from '../tournament-code/tournament-code.constants';
|
||||
import { TournamentCodeService } from '../tournament-code/tournament-code.service';
|
||||
|
||||
const MATCH_SHORT_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||
const MATCH_SHORT_CODE_LENGTH = 4;
|
||||
const MATCH_SHORT_CODE_GENERATION_ATTEMPTS = 20;
|
||||
|
||||
interface CreateMatchParams {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
hostUserId?: mongoose.Types.ObjectId;
|
||||
@@ -42,12 +50,32 @@ interface JoinMatchParams {
|
||||
riotPuuid?: string;
|
||||
}
|
||||
|
||||
interface CancelMatchJoinParams {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
userId: mongoose.Types.ObjectId;
|
||||
}
|
||||
|
||||
interface RemoveParticipantParams {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
targetUserId: mongoose.Types.ObjectId;
|
||||
}
|
||||
|
||||
interface UpdateParticipantPositionsParams {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
targetUserId: mongoose.Types.ObjectId;
|
||||
mainPosition: Position;
|
||||
subPosition: Position;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MatchService {
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly tournamentCodeService: TournamentCodeService,
|
||||
private readonly communityStatsService: CommunityStatsService,
|
||||
private readonly matchStatsService: MatchStatsService,
|
||||
) {}
|
||||
|
||||
public async create(params: CreateMatchParams): Promise<MatchDocument> {
|
||||
@@ -59,6 +87,9 @@ export class MatchService {
|
||||
.exec();
|
||||
return MatchModel.create({
|
||||
...params.data,
|
||||
shortCode:
|
||||
params.data.shortCode ??
|
||||
(await this.generateUniqueShortCode(MatchModel, params.communityId)),
|
||||
gameCount:
|
||||
params.data.gameCount ??
|
||||
community?.matchGameCount ??
|
||||
@@ -83,6 +114,18 @@ export class MatchService {
|
||||
.exec();
|
||||
}
|
||||
|
||||
public async ensureShortCode(match: MatchDocument): Promise<MatchDocument> {
|
||||
if (match.shortCode) return match;
|
||||
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
match.shortCode = await this.generateUniqueShortCode(
|
||||
MatchModel,
|
||||
match.communityId,
|
||||
);
|
||||
await match.save();
|
||||
return match;
|
||||
}
|
||||
|
||||
public async getById(
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
): Promise<MatchDocument> {
|
||||
@@ -98,10 +141,22 @@ export class MatchService {
|
||||
obj.result.games = [...obj.result.games].sort(
|
||||
(left, right) => left.gameNumber - right.gameNumber,
|
||||
);
|
||||
if (!obj.result.seriesResults?.length) {
|
||||
obj.result.seriesResults = this.buildSeriesResults(obj.result.games);
|
||||
}
|
||||
}
|
||||
return {
|
||||
...obj,
|
||||
gameCount: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT,
|
||||
gameMode: match.gameMode ?? 'pair',
|
||||
participants: (obj.participants ?? []).map((participant) => ({
|
||||
...participant,
|
||||
excluded: participant.excluded ?? false,
|
||||
})),
|
||||
teams: (obj.teams ?? []).map((team) => ({
|
||||
...team,
|
||||
})),
|
||||
gameSchedule: obj.gameSchedule ?? [],
|
||||
tournamentCodes: await this.tournamentCodeService.buildSlots(match),
|
||||
};
|
||||
}
|
||||
@@ -114,19 +169,33 @@ export class MatchService {
|
||||
throw new BadRequestException('Match does not belong to this community.');
|
||||
}
|
||||
const previousStatus = match.status;
|
||||
match.set(params.patch);
|
||||
if (
|
||||
previousStatus !== 'recruiting' &&
|
||||
match.status === 'recruiting' &&
|
||||
match.tournamentCodeIds.length > 0
|
||||
('maxParticipants' in params.patch || 'gameMode' in params.patch)
|
||||
) {
|
||||
await this.tournamentCodeService.releaseFromMatch(match);
|
||||
throw new BadRequestException(
|
||||
'maxParticipants and gameMode can only be changed while recruiting.',
|
||||
);
|
||||
}
|
||||
match.set(params.patch);
|
||||
if (previousStatus !== 'recruiting' && match.status === 'recruiting') {
|
||||
if (match.tournamentCodeIds.length > 0) {
|
||||
await this.tournamentCodeService.releaseFromMatch(match);
|
||||
}
|
||||
match.tournamentCodeIds = [];
|
||||
match.gameSchedule = [];
|
||||
match.teamBuiltAt = undefined;
|
||||
match.result = undefined;
|
||||
match.resultPollState = undefined;
|
||||
}
|
||||
await match.save();
|
||||
if (previousStatus !== 'recruiting' && match.status === 'recruiting') {
|
||||
await this.matchStatsService.removeByMatch(match._id);
|
||||
await this.communityStatsService.invalidateCommunity(params.communityId);
|
||||
} else if (match.result?.games?.length) {
|
||||
await this.matchStatsService.buildAndUpsert(match._id);
|
||||
await this.communityStatsService.invalidateCommunity(params.communityId);
|
||||
}
|
||||
return match;
|
||||
}
|
||||
|
||||
@@ -141,6 +210,7 @@ export class MatchService {
|
||||
throw new BadRequestException('Match does not belong to this community.');
|
||||
}
|
||||
await this.tournamentCodeService.releaseFromMatch(match);
|
||||
await this.matchStatsService.removeByMatch(match._id);
|
||||
await match.deleteOne();
|
||||
await this.communityStatsService.invalidateCommunity(params.communityId);
|
||||
}
|
||||
@@ -183,11 +253,124 @@ export class MatchService {
|
||||
tier: selectedTier,
|
||||
preferredPositions: params.preferredPositions,
|
||||
joinedAt: new Date(),
|
||||
excluded: false,
|
||||
});
|
||||
await match.save();
|
||||
return match;
|
||||
}
|
||||
|
||||
public async cancelJoin(
|
||||
params: CancelMatchJoinParams,
|
||||
): Promise<MatchDocument> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
|
||||
const user = await UserModel.findById(params.userId);
|
||||
if (!user) throw new NotFoundException('User not found.');
|
||||
|
||||
const match = await MatchModel.findById(params.matchId);
|
||||
if (!match) throw new NotFoundException('Match not found.');
|
||||
if (!match.communityId.equals(user.communityId)) {
|
||||
throw new BadRequestException(
|
||||
'User and match belong to different communities.',
|
||||
);
|
||||
}
|
||||
if (match.status !== 'recruiting') {
|
||||
throw new BadRequestException('Match is not recruiting.');
|
||||
}
|
||||
|
||||
const participantIndex = match.participants.findIndex((participant) =>
|
||||
participant.userId.equals(user._id),
|
||||
);
|
||||
if (participantIndex === -1) {
|
||||
throw new BadRequestException('User has not joined this match.');
|
||||
}
|
||||
|
||||
match.participants.splice(participantIndex, 1);
|
||||
await match.save();
|
||||
return match;
|
||||
}
|
||||
|
||||
// 관리자 전용 — 특정 참가자를 강제로 제외한다.
|
||||
public async removeParticipant(
|
||||
params: RemoveParticipantParams,
|
||||
): Promise<MatchDocument> {
|
||||
const match = await this.loadRecruitingMatch(
|
||||
params.matchId,
|
||||
params.communityId,
|
||||
);
|
||||
const participantIndex = match.participants.findIndex((participant) =>
|
||||
participant.userId.equals(params.targetUserId),
|
||||
);
|
||||
if (participantIndex === -1) {
|
||||
throw new NotFoundException('Participant not found.');
|
||||
}
|
||||
match.participants.splice(participantIndex, 1);
|
||||
await match.save();
|
||||
return match;
|
||||
}
|
||||
|
||||
// 관리자 전용 — 참가자의 주/부 포지션(선호 우선순위 1·2)을 교체한다.
|
||||
public async updateParticipantPositions(
|
||||
params: UpdateParticipantPositionsParams,
|
||||
): Promise<MatchDocument> {
|
||||
const match = await this.loadRecruitingMatch(
|
||||
params.matchId,
|
||||
params.communityId,
|
||||
);
|
||||
const participant = match.participants.find((entry) =>
|
||||
entry.userId.equals(params.targetUserId),
|
||||
);
|
||||
if (!participant) {
|
||||
throw new NotFoundException('Participant not found.');
|
||||
}
|
||||
participant.preferredPositions = this.reorderPreferredPositions(
|
||||
params.mainPosition,
|
||||
params.subPosition,
|
||||
participant.preferredPositions,
|
||||
);
|
||||
match.markModified('participants');
|
||||
await match.save();
|
||||
return match;
|
||||
}
|
||||
|
||||
private async loadRecruitingMatch(
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
): Promise<MatchDocument> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const match = await MatchModel.findById(matchId);
|
||||
if (!match) throw new NotFoundException('Match not found.');
|
||||
if (!match.communityId.equals(communityId)) {
|
||||
throw new BadRequestException('Different community.');
|
||||
}
|
||||
if (match.status !== 'recruiting') {
|
||||
throw new BadRequestException('Match is not recruiting.');
|
||||
}
|
||||
return match;
|
||||
}
|
||||
|
||||
// 주/부 포지션을 priority 1·2로 올리고 기존 나머지 선호는 뒤로 보존한다.
|
||||
private reorderPreferredPositions(
|
||||
mainPosition: Position,
|
||||
subPosition: Position,
|
||||
current: PositionPreference[],
|
||||
): PositionPreference[] {
|
||||
const ordered: Position[] = [mainPosition];
|
||||
if (subPosition !== mainPosition) ordered.push(subPosition);
|
||||
for (const preference of [...current].sort(
|
||||
(left, right) => left.priority - right.priority,
|
||||
)) {
|
||||
if (!ordered.includes(preference.position)) {
|
||||
ordered.push(preference.position);
|
||||
}
|
||||
}
|
||||
return ordered.map((position, index) => ({
|
||||
position,
|
||||
priority: index + 1,
|
||||
}));
|
||||
}
|
||||
|
||||
private selectParticipantTier(tiers: TierInfo[]): TierInfo | undefined {
|
||||
const tier =
|
||||
tiers.find((entry) => entry.queueType === 'RANKED_SOLO_5x5') ?? tiers[0];
|
||||
@@ -210,4 +393,63 @@ export class MatchService {
|
||||
fetchedAt: tier.fetchedAt,
|
||||
};
|
||||
}
|
||||
|
||||
private async generateUniqueShortCode(
|
||||
MatchModel: mongoose.Model<Match>,
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
): Promise<string> {
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < MATCH_SHORT_CODE_GENERATION_ATTEMPTS;
|
||||
attempt += 1
|
||||
) {
|
||||
const shortCode = this.generateShortCode();
|
||||
const exists = await MatchModel.exists({ communityId, shortCode });
|
||||
if (!exists) return shortCode;
|
||||
}
|
||||
|
||||
throw new InternalServerErrorException(
|
||||
'Failed to generate unique match short code.',
|
||||
);
|
||||
}
|
||||
|
||||
private generateShortCode(): string {
|
||||
let code = '';
|
||||
for (let index = 0; index < MATCH_SHORT_CODE_LENGTH; index += 1) {
|
||||
const alphabetIndex = Math.floor(
|
||||
Math.random() * MATCH_SHORT_CODE_ALPHABET.length,
|
||||
);
|
||||
code += MATCH_SHORT_CODE_ALPHABET[alphabetIndex];
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
private buildSeriesResults(
|
||||
games: NonNullable<Match['result']>['games'],
|
||||
): MatchSeriesResult[] {
|
||||
const bySeries = new Map<string, MatchSeriesResult>();
|
||||
for (const game of games) {
|
||||
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
|
||||
const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex);
|
||||
const key = `${teamAIndex}:${teamBIndex}`;
|
||||
const current =
|
||||
bySeries.get(key) ??
|
||||
({
|
||||
teamAIndex,
|
||||
teamBIndex,
|
||||
teamAWins: 0,
|
||||
teamBWins: 0,
|
||||
} satisfies MatchSeriesResult);
|
||||
if (game.winnerTeamIndex === teamAIndex) current.teamAWins += 1;
|
||||
if (game.winnerTeamIndex === teamBIndex) current.teamBWins += 1;
|
||||
current.winnerTeamIndex =
|
||||
current.teamAWins > current.teamBWins
|
||||
? teamAIndex
|
||||
: current.teamBWins > current.teamAWins
|
||||
? teamBIndex
|
||||
: undefined;
|
||||
bySeries.set(key, current);
|
||||
}
|
||||
return [...bySeries.values()];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { RiotModule } from '../riot/riot.module';
|
||||
import { BackgroundRefreshScheduler } from './background-refresh.scheduler';
|
||||
import { StaleAccountRepository } from './stale-account.repository';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, RiotModule],
|
||||
providers: [BackgroundRefreshScheduler, StaleAccountRepository],
|
||||
})
|
||||
export class BackgroundRefreshModule {}
|
||||
@@ -0,0 +1,211 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { GarnetService } from '../global/garnet/garnet.service';
|
||||
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
||||
import { RiotRateLimiterService } from '../riot/riot-rate-limiter.service';
|
||||
import { BackgroundRefreshScheduler } from './background-refresh.scheduler';
|
||||
import {
|
||||
StaleAccountCandidate,
|
||||
StaleAccountRepository,
|
||||
} from './stale-account.repository';
|
||||
|
||||
type SchedulerInternals = BackgroundRefreshScheduler & {
|
||||
tick(): Promise<void>;
|
||||
};
|
||||
|
||||
function successResult() {
|
||||
return {
|
||||
summoner: 'fresh',
|
||||
league: 'fresh',
|
||||
masteries: 'fresh',
|
||||
recentMatches: 'fresh',
|
||||
account: {},
|
||||
};
|
||||
}
|
||||
|
||||
function candidate(puuid: string): StaleAccountCandidate {
|
||||
return {
|
||||
userId: new mongoose.Types.ObjectId(),
|
||||
puuid,
|
||||
};
|
||||
}
|
||||
|
||||
function makeScheduler() {
|
||||
const rawClient = {
|
||||
sendCommand: jest.fn().mockResolvedValue(1),
|
||||
};
|
||||
const garnet = {
|
||||
getString: jest.fn().mockResolvedValue(null),
|
||||
setString: jest.fn().mockResolvedValue(undefined),
|
||||
setStringIfAbsent: jest.fn().mockResolvedValue(true),
|
||||
delete: jest.fn().mockResolvedValue(1),
|
||||
raw: jest.fn().mockReturnValue(rawClient),
|
||||
} as unknown as jest.Mocked<GarnetService> & { raw: jest.Mock };
|
||||
const rateLimiter = {
|
||||
isRefreshWindowOpen: jest.fn().mockResolvedValue(true),
|
||||
} as unknown as jest.Mocked<RiotRateLimiterService>;
|
||||
const enrichmentService = {
|
||||
markRefreshRequested: jest.fn().mockResolvedValue(undefined),
|
||||
enrichRiotAccount: jest.fn().mockResolvedValue(successResult()),
|
||||
} as unknown as jest.Mocked<RiotAccountEnrichmentService>;
|
||||
const staleAccountRepository = {
|
||||
findStaleAccounts: jest.fn().mockResolvedValue([]),
|
||||
} as unknown as jest.Mocked<StaleAccountRepository>;
|
||||
const scheduler = new BackgroundRefreshScheduler(
|
||||
garnet,
|
||||
rateLimiter,
|
||||
enrichmentService,
|
||||
staleAccountRepository,
|
||||
) as SchedulerInternals;
|
||||
|
||||
return {
|
||||
scheduler,
|
||||
garnet,
|
||||
rawClient,
|
||||
rateLimiter,
|
||||
enrichmentService,
|
||||
staleAccountRepository,
|
||||
};
|
||||
}
|
||||
|
||||
describe('BackgroundRefreshScheduler', () => {
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('schedules ticks without requiring RIOT_BG_REFRESH_ENABLED', () => {
|
||||
jest.useFakeTimers();
|
||||
const setIntervalSpy = jest.spyOn(global, 'setInterval');
|
||||
const { scheduler } = makeScheduler();
|
||||
|
||||
scheduler.onModuleInit();
|
||||
|
||||
expect(setIntervalSpy).toHaveBeenCalledTimes(2);
|
||||
scheduler.onModuleDestroy();
|
||||
});
|
||||
|
||||
it('uses the dawn refresh gate ratio inside the KST background window', async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
|
||||
const { scheduler, rateLimiter } = makeScheduler();
|
||||
|
||||
await scheduler.tick();
|
||||
|
||||
expect(rateLimiter.isRefreshWindowOpen).toHaveBeenCalledWith(0.8);
|
||||
});
|
||||
|
||||
it('uses the opportunistic refresh gate ratio outside the KST background window', async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T17:59:59.000Z'));
|
||||
const { scheduler, rateLimiter, staleAccountRepository } = makeScheduler();
|
||||
|
||||
await scheduler.tick();
|
||||
|
||||
expect(rateLimiter.isRefreshWindowOpen).toHaveBeenCalledWith(0.5);
|
||||
expect(staleAccountRepository.findStaleAccounts).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not query stale accounts when the refresh gate is closed', async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
|
||||
const { scheduler, rateLimiter, staleAccountRepository } = makeScheduler();
|
||||
rateLimiter.isRefreshWindowOpen.mockResolvedValue(false);
|
||||
|
||||
await scheduler.tick();
|
||||
|
||||
expect(staleAccountRepository.findStaleAccounts).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not query stale accounts when another leader holds the lock', async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
|
||||
const { scheduler, garnet, staleAccountRepository } = makeScheduler();
|
||||
garnet.getString.mockResolvedValue('another-consumer');
|
||||
|
||||
await scheduler.tick();
|
||||
|
||||
expect(staleAccountRepository.findStaleAccounts).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('marks and enriches each stale candidate without background precharge', async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
|
||||
const { scheduler, enrichmentService, staleAccountRepository } =
|
||||
makeScheduler();
|
||||
const candidates = [candidate('puuid-1'), candidate('puuid-2')];
|
||||
staleAccountRepository.findStaleAccounts.mockResolvedValue(candidates);
|
||||
|
||||
await scheduler.tick();
|
||||
|
||||
expect(enrichmentService.markRefreshRequested).toHaveBeenCalledTimes(2);
|
||||
expect(enrichmentService.markRefreshRequested).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
candidates[0].userId,
|
||||
'puuid-1',
|
||||
);
|
||||
expect(enrichmentService.enrichRiotAccount).toHaveBeenNthCalledWith(2, {
|
||||
userId: candidates[1].userId,
|
||||
puuid: 'puuid-2',
|
||||
options: { force: false },
|
||||
});
|
||||
});
|
||||
|
||||
it('stops the candidate loop when the refresh gate closes mid-tick', async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
|
||||
const {
|
||||
scheduler,
|
||||
rateLimiter,
|
||||
enrichmentService,
|
||||
staleAccountRepository,
|
||||
} = makeScheduler();
|
||||
staleAccountRepository.findStaleAccounts.mockResolvedValue([
|
||||
candidate('puuid-1'),
|
||||
candidate('puuid-2'),
|
||||
]);
|
||||
rateLimiter.isRefreshWindowOpen
|
||||
.mockResolvedValueOnce(true)
|
||||
.mockResolvedValueOnce(true)
|
||||
.mockResolvedValueOnce(false);
|
||||
|
||||
await scheduler.tick();
|
||||
|
||||
expect(enrichmentService.enrichRiotAccount).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('continues after a candidate throws and records a failure counter', async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
|
||||
const { scheduler, rawClient, enrichmentService, staleAccountRepository } =
|
||||
makeScheduler();
|
||||
const candidates = [candidate('puuid-1'), candidate('puuid-2')];
|
||||
staleAccountRepository.findStaleAccounts.mockResolvedValue(candidates);
|
||||
enrichmentService.enrichRiotAccount
|
||||
.mockRejectedValueOnce(new Error('boom'))
|
||||
.mockResolvedValueOnce(successResult() as never);
|
||||
|
||||
await scheduler.tick();
|
||||
|
||||
expect(enrichmentService.enrichRiotAccount).toHaveBeenCalledTimes(2);
|
||||
expect(rawClient.sendCommand).toHaveBeenCalledWith([
|
||||
'INCR',
|
||||
'riot:bg:fail:puuid-1',
|
||||
]);
|
||||
expect(rawClient.sendCommand).toHaveBeenCalledWith([
|
||||
'EXPIRE',
|
||||
'riot:bg:fail:puuid-1',
|
||||
'86400',
|
||||
]);
|
||||
});
|
||||
|
||||
it('skips candidates already in failure backoff', async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
|
||||
const { scheduler, garnet, enrichmentService, staleAccountRepository } =
|
||||
makeScheduler();
|
||||
staleAccountRepository.findStaleAccounts.mockResolvedValue([
|
||||
candidate('skip-me'),
|
||||
]);
|
||||
garnet.getString.mockImplementation(async (key: string) => {
|
||||
if (key.includes('riot:bg:fail:skip-me')) return '3';
|
||||
return null;
|
||||
});
|
||||
|
||||
await scheduler.tick();
|
||||
|
||||
expect(enrichmentService.markRefreshRequested).not.toHaveBeenCalled();
|
||||
expect(enrichmentService.enrichRiotAccount).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,244 @@
|
||||
import {
|
||||
Injectable,
|
||||
Logger,
|
||||
OnModuleDestroy,
|
||||
OnModuleInit,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
type EnrichResult,
|
||||
RiotAccountEnrichmentService,
|
||||
} from '../riot/riot-account-enrichment.service';
|
||||
import { RiotRateLimiterService } from '../riot/riot-rate-limiter.service';
|
||||
import { GarnetService } from '../global/garnet/garnet.service';
|
||||
import { isInKstBackgroundWindow } from './kst-window.util';
|
||||
import { StaleAccountRepository } from './stale-account.repository';
|
||||
|
||||
const TICK_INTERVAL_MS = 60_000;
|
||||
const LEADER_KEY = 'riot:bg-refresh:leader';
|
||||
const LEADER_TTL_SECONDS = 90;
|
||||
const LEADER_RENEW_INTERVAL_MS = 30_000;
|
||||
const STALE_THRESHOLD_MS = 6 * 60 * 60 * 1000;
|
||||
const PER_TICK_CANDIDATE_LIMIT = 20;
|
||||
const DAWN_USAGE_RATIO = 0.8;
|
||||
const OPPORTUNISTIC_USAGE_RATIO = 0.5;
|
||||
const FAILURE_BACKOFF_KEY_PREFIX = 'riot:bg:fail';
|
||||
const FAILURE_BACKOFF_THRESHOLD = 3;
|
||||
const FAILURE_BACKOFF_TTL_SECONDS = 24 * 60 * 60;
|
||||
|
||||
interface RefreshGatePolicy {
|
||||
mode: 'dawn' | 'opportunistic';
|
||||
usageRatio: number;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class BackgroundRefreshScheduler
|
||||
implements OnModuleInit, OnModuleDestroy
|
||||
{
|
||||
private readonly logger = new Logger(BackgroundRefreshScheduler.name);
|
||||
private tickTimer?: NodeJS.Timeout;
|
||||
private leaderRenewTimer?: NodeJS.Timeout;
|
||||
private tickInProgress = false;
|
||||
private readonly consumer = `${process.pid}:${Math.random().toString(36).slice(2)}`;
|
||||
|
||||
constructor(
|
||||
private readonly garnet: GarnetService,
|
||||
private readonly rateLimiter: RiotRateLimiterService,
|
||||
private readonly enrichmentService: RiotAccountEnrichmentService,
|
||||
private readonly staleAccountRepository: StaleAccountRepository,
|
||||
) {}
|
||||
|
||||
public onModuleInit(): void {
|
||||
this.tickTimer = setInterval(() => void this.safeTick(), TICK_INTERVAL_MS);
|
||||
this.leaderRenewTimer = setInterval(
|
||||
() => void this.renewLeaderIfHeld(),
|
||||
LEADER_RENEW_INTERVAL_MS,
|
||||
);
|
||||
this.tickTimer.unref?.();
|
||||
this.leaderRenewTimer.unref?.();
|
||||
|
||||
void this.safeTick();
|
||||
}
|
||||
|
||||
public onModuleDestroy(): void {
|
||||
if (this.tickTimer) clearInterval(this.tickTimer);
|
||||
if (this.leaderRenewTimer) clearInterval(this.leaderRenewTimer);
|
||||
}
|
||||
|
||||
private async safeTick(): Promise<void> {
|
||||
if (this.tickInProgress) return;
|
||||
this.tickInProgress = true;
|
||||
try {
|
||||
await this.tick();
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Background refresh tick failed: ${
|
||||
err instanceof Error ? err.message : err
|
||||
}`,
|
||||
);
|
||||
} finally {
|
||||
this.tickInProgress = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async tick(): Promise<void> {
|
||||
const initialGate = this.currentRefreshGatePolicy();
|
||||
if (!(await this.rateLimiter.isRefreshWindowOpen(initialGate.usageRatio))) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isLeader = await this.tryBecomeLeader();
|
||||
if (!isLeader) return;
|
||||
|
||||
const olderThan = new Date(Date.now() - STALE_THRESHOLD_MS);
|
||||
const candidates = await this.staleAccountRepository.findStaleAccounts({
|
||||
olderThan,
|
||||
limit: PER_TICK_CANDIDATE_LIMIT,
|
||||
});
|
||||
if (candidates.length === 0) return;
|
||||
|
||||
let processed = 0;
|
||||
let failed = 0;
|
||||
let skipped = 0;
|
||||
let currentGate = initialGate;
|
||||
|
||||
for (const candidate of candidates) {
|
||||
currentGate = this.currentRefreshGatePolicy();
|
||||
if (
|
||||
!(await this.rateLimiter.isRefreshWindowOpen(currentGate.usageRatio))
|
||||
) {
|
||||
break;
|
||||
}
|
||||
if (await this.isInFailureBackoff(candidate.puuid)) {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
await this.enrichmentService.markRefreshRequested(
|
||||
candidate.userId,
|
||||
candidate.puuid,
|
||||
);
|
||||
|
||||
try {
|
||||
const result = await this.enrichmentService.enrichRiotAccount({
|
||||
userId: candidate.userId,
|
||||
puuid: candidate.puuid,
|
||||
options: { force: false },
|
||||
});
|
||||
|
||||
if (this.isFailedEnrichment(result)) {
|
||||
failed += 1;
|
||||
await this.bumpFailureCounter(candidate.puuid);
|
||||
continue;
|
||||
}
|
||||
|
||||
await this.clearFailureCounter(candidate.puuid);
|
||||
processed += 1;
|
||||
} catch (err) {
|
||||
failed += 1;
|
||||
await this.bumpFailureCounter(candidate.puuid);
|
||||
this.logger.warn(
|
||||
`Background enrichRiotAccount failed for ${candidate.puuid}: ${
|
||||
err instanceof Error ? err.message : err
|
||||
}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.debug(
|
||||
`Background refresh tick: processed=${processed} failed=${failed} skipped=${skipped} candidates=${candidates.length} mode=${currentGate.mode} ratio=${currentGate.usageRatio}`,
|
||||
);
|
||||
}
|
||||
|
||||
private currentRefreshGatePolicy(): RefreshGatePolicy {
|
||||
const isDawn = isInKstBackgroundWindow();
|
||||
return {
|
||||
mode: isDawn ? 'dawn' : 'opportunistic',
|
||||
usageRatio: isDawn ? DAWN_USAGE_RATIO : OPPORTUNISTIC_USAGE_RATIO,
|
||||
};
|
||||
}
|
||||
|
||||
private async tryBecomeLeader(): Promise<boolean> {
|
||||
const current = await this.garnet.getString(LEADER_KEY);
|
||||
if (current === this.consumer) {
|
||||
await this.garnet.setString(
|
||||
LEADER_KEY,
|
||||
this.consumer,
|
||||
LEADER_TTL_SECONDS,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
if (current) return false;
|
||||
|
||||
return this.garnet.setStringIfAbsent(
|
||||
LEADER_KEY,
|
||||
this.consumer,
|
||||
LEADER_TTL_SECONDS,
|
||||
);
|
||||
}
|
||||
|
||||
private async renewLeaderIfHeld(): Promise<void> {
|
||||
try {
|
||||
const current = await this.garnet.getString(LEADER_KEY);
|
||||
if (current !== this.consumer) return;
|
||||
await this.garnet.setString(
|
||||
LEADER_KEY,
|
||||
this.consumer,
|
||||
LEADER_TTL_SECONDS,
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Background refresh leader renew failed: ${
|
||||
err instanceof Error ? err.message : err
|
||||
}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async isInFailureBackoff(puuid: string): Promise<boolean> {
|
||||
const count = await this.getFailureCount(puuid);
|
||||
return count >= FAILURE_BACKOFF_THRESHOLD;
|
||||
}
|
||||
|
||||
private async getFailureCount(puuid: string): Promise<number> {
|
||||
const raw = await this.garnet.getString(this.failureBackoffKey(puuid));
|
||||
const count = Number(raw ?? 0);
|
||||
if (!Number.isFinite(count) || count < 0) return 0;
|
||||
return count;
|
||||
}
|
||||
|
||||
private async bumpFailureCounter(puuid: string): Promise<void> {
|
||||
const key = this.failureBackoffKey(puuid);
|
||||
const client = this.garnet.raw();
|
||||
const response = await client.sendCommand(['INCR', key]);
|
||||
await client.sendCommand([
|
||||
'EXPIRE',
|
||||
key,
|
||||
String(FAILURE_BACKOFF_TTL_SECONDS),
|
||||
]);
|
||||
|
||||
const count = Number(response ?? 0);
|
||||
if (Number.isFinite(count) && count >= FAILURE_BACKOFF_THRESHOLD) {
|
||||
this.logger.warn(
|
||||
`Background Riot refresh backoff enabled for ${puuid} after ${count} failures.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async clearFailureCounter(puuid: string): Promise<void> {
|
||||
await this.garnet.delete(this.failureBackoffKey(puuid));
|
||||
}
|
||||
|
||||
private isFailedEnrichment(result: EnrichResult): boolean {
|
||||
if (!result.account) return true;
|
||||
return [
|
||||
result.summoner,
|
||||
result.league,
|
||||
result.masteries,
|
||||
result.recentMatches,
|
||||
].every((status) => status === 'failed');
|
||||
}
|
||||
|
||||
private failureBackoffKey(puuid: string): string {
|
||||
return `${FAILURE_BACKOFF_KEY_PREFIX}:${puuid}`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { isInKstBackgroundWindow } from './kst-window.util';
|
||||
|
||||
describe('isInKstBackgroundWindow', () => {
|
||||
it('includes KST 03:00', () => {
|
||||
expect(isInKstBackgroundWindow(new Date('2026-05-02T18:00:00.000Z'))).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('includes KST 09:59', () => {
|
||||
expect(isInKstBackgroundWindow(new Date('2026-05-03T00:59:59.000Z'))).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('excludes KST 10:00', () => {
|
||||
expect(isInKstBackgroundWindow(new Date('2026-05-03T01:00:00.000Z'))).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it('excludes KST 02:59', () => {
|
||||
expect(isInKstBackgroundWindow(new Date('2026-05-02T17:59:59.000Z'))).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
const BG_WINDOW_START_HOUR = 3;
|
||||
const BG_WINDOW_END_HOUR = 10;
|
||||
const KST_HOUR_FORMAT = new Intl.DateTimeFormat('en-US', {
|
||||
timeZone: 'Asia/Seoul',
|
||||
hour: '2-digit',
|
||||
hour12: false,
|
||||
});
|
||||
|
||||
export function isInKstBackgroundWindow(now: Date = new Date()): boolean {
|
||||
const hourString = KST_HOUR_FORMAT.format(now);
|
||||
const hour = Number.parseInt(hourString, 10);
|
||||
if (Number.isNaN(hour)) return false;
|
||||
|
||||
const normalizedHour = hour % 24;
|
||||
return (
|
||||
normalizedHour >= BG_WINDOW_START_HOUR &&
|
||||
normalizedHour < BG_WINDOW_END_HOUR
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import {
|
||||
buildStaleAccountsPipeline,
|
||||
StaleAccountRepository,
|
||||
} from './stale-account.repository';
|
||||
|
||||
describe('buildStaleAccountsPipeline', () => {
|
||||
const olderThan = new Date('2026-05-03T00:00:00.000Z');
|
||||
|
||||
it('filters to active users before unwinding Riot accounts', () => {
|
||||
const pipeline = buildStaleAccountsPipeline({ olderThan, limit: 20 });
|
||||
|
||||
expect(pipeline[0]).toEqual({ $match: { isActivated: true } });
|
||||
expect(pipeline[1]).toEqual({ $unwind: '$riotAccounts' });
|
||||
});
|
||||
|
||||
it('matches missing or older lastRefreshRequestedAt values', () => {
|
||||
const pipeline = buildStaleAccountsPipeline({ olderThan, limit: 20 });
|
||||
|
||||
expect(pipeline[2]).toEqual({
|
||||
$match: {
|
||||
$or: [
|
||||
{ 'riotAccounts.lastRefreshRequestedAt': { $exists: false } },
|
||||
{ 'riotAccounts.lastRefreshRequestedAt': { $lt: olderThan } },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('sorts missing refresh timestamps first', () => {
|
||||
const pipeline = buildStaleAccountsPipeline({ olderThan, limit: 20 });
|
||||
|
||||
expect(pipeline[3]).toEqual({
|
||||
$addFields: {
|
||||
'riotAccounts.lastRefreshRequestedAtSort': {
|
||||
$ifNull: ['$riotAccounts.lastRefreshRequestedAt', new Date(0)],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(pipeline[4]).toEqual({
|
||||
$sort: { 'riotAccounts.lastRefreshRequestedAtSort': 1 },
|
||||
});
|
||||
});
|
||||
|
||||
it('applies the provided limit', () => {
|
||||
const pipeline = buildStaleAccountsPipeline({ olderThan, limit: 7 });
|
||||
|
||||
expect(pipeline[5]).toEqual({ $limit: 7 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('StaleAccountRepository', () => {
|
||||
it('returns aggregate candidates from the user model', async () => {
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
const candidates = [{ userId, puuid: 'puuid-1' }];
|
||||
const exec = jest.fn().mockResolvedValue(candidates);
|
||||
const aggregate = jest.fn().mockReturnValue({ exec });
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockResolvedValue({ aggregate }),
|
||||
} as unknown as ConnectionService;
|
||||
|
||||
const repository = new StaleAccountRepository(connectionService);
|
||||
await expect(
|
||||
repository.findStaleAccounts({
|
||||
olderThan: new Date('2026-05-03T00:00:00.000Z'),
|
||||
limit: 1,
|
||||
}),
|
||||
).resolves.toBe(candidates);
|
||||
|
||||
expect(connectionService.getModel).toHaveBeenCalledWith('user');
|
||||
expect(aggregate).toHaveBeenCalledWith(
|
||||
buildStaleAccountsPipeline({
|
||||
olderThan: new Date('2026-05-03T00:00:00.000Z'),
|
||||
limit: 1,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import mongoose, { type PipelineStage } from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
|
||||
export interface StaleAccountCandidate {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
puuid: string;
|
||||
lastRefreshRequestedAt?: Date;
|
||||
}
|
||||
|
||||
export function buildStaleAccountsPipeline(opts: {
|
||||
olderThan: Date;
|
||||
limit: number;
|
||||
}): PipelineStage[] {
|
||||
return [
|
||||
{ $match: { isActivated: true } },
|
||||
{ $unwind: '$riotAccounts' },
|
||||
{
|
||||
$match: {
|
||||
$or: [
|
||||
{ 'riotAccounts.lastRefreshRequestedAt': { $exists: false } },
|
||||
{ 'riotAccounts.lastRefreshRequestedAt': { $lt: opts.olderThan } },
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
$addFields: {
|
||||
'riotAccounts.lastRefreshRequestedAtSort': {
|
||||
$ifNull: ['$riotAccounts.lastRefreshRequestedAt', new Date(0)],
|
||||
},
|
||||
},
|
||||
},
|
||||
{ $sort: { 'riotAccounts.lastRefreshRequestedAtSort': 1 } },
|
||||
{ $limit: opts.limit },
|
||||
{
|
||||
$project: {
|
||||
_id: 0,
|
||||
userId: '$_id',
|
||||
puuid: '$riotAccounts.puuid',
|
||||
lastRefreshRequestedAt: '$riotAccounts.lastRefreshRequestedAt',
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class StaleAccountRepository {
|
||||
constructor(private readonly connectionService: ConnectionService) {}
|
||||
|
||||
public async findStaleAccounts(opts: {
|
||||
olderThan: Date;
|
||||
limit: number;
|
||||
}): Promise<StaleAccountCandidate[]> {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
return UserModel.aggregate<StaleAccountCandidate>(
|
||||
buildStaleAccountsPipeline(opts),
|
||||
).exec();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import { GarnetService } from '../global/garnet/garnet.service';
|
||||
import { LegacyImportService } from '../legacy-import/legacy-import.service';
|
||||
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
||||
import { RiotRecentMatchesService } from '../riot/riot-recent-matches.service';
|
||||
import { TournamentResultService } from '../tournament-result/tournament-result.service';
|
||||
import { RIOT_JOB_GROUP, RiotRefreshSubJob } from './riot-job-queue.types';
|
||||
import { RiotJobQueueService } from './riot-job-queue.service';
|
||||
import { RiotJobWorkerService } from './riot-job-worker.service';
|
||||
import { RiotRefreshGateway } from './riot-refresh.gateway';
|
||||
|
||||
function execResult<T>(value: T) {
|
||||
return { exec: jest.fn().mockResolvedValue(value) };
|
||||
}
|
||||
|
||||
function makeWorker() {
|
||||
const garnetService = {
|
||||
acknowledgeStream: jest.fn().mockResolvedValue(undefined),
|
||||
deleteStreamEntries: jest.fn().mockResolvedValue(undefined),
|
||||
} as unknown as jest.Mocked<GarnetService>;
|
||||
const jobQueueService = {
|
||||
markProcessing: jest.fn().mockResolvedValue(undefined),
|
||||
markCompleted: jest.fn().mockResolvedValue({
|
||||
parentJobId: 'parent-1',
|
||||
jobId: 'job-1',
|
||||
queueGroup: 'summoners-rift',
|
||||
puuid: 'puuid-1',
|
||||
state: 'completed',
|
||||
}),
|
||||
markFailed: jest.fn(),
|
||||
} as unknown as jest.Mocked<RiotJobQueueService>;
|
||||
const recentMatchesService = {
|
||||
ensureFreshForQueue: jest.fn().mockResolvedValue(undefined),
|
||||
} as unknown as jest.Mocked<RiotRecentMatchesService>;
|
||||
const userModel = {
|
||||
updateOne: jest.fn().mockReturnValue(execResult({ modifiedCount: 1 })),
|
||||
};
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockResolvedValue(userModel),
|
||||
} as unknown as jest.Mocked<ConnectionService>;
|
||||
const refreshGateway = {
|
||||
broadcastRefreshEvent: jest.fn(),
|
||||
} as unknown as jest.Mocked<RiotRefreshGateway>;
|
||||
const tournamentResultService = {
|
||||
processPollJob: jest.fn(),
|
||||
} as unknown as jest.Mocked<TournamentResultService>;
|
||||
const legacyImportService = {
|
||||
processMemberJob: jest.fn(),
|
||||
} as unknown as jest.Mocked<LegacyImportService>;
|
||||
const enrichmentService = {
|
||||
refreshLeagueEntries: jest.fn().mockResolvedValue('updated'),
|
||||
} as unknown as jest.Mocked<RiotAccountEnrichmentService>;
|
||||
|
||||
const worker = new RiotJobWorkerService(
|
||||
garnetService,
|
||||
jobQueueService,
|
||||
recentMatchesService,
|
||||
connectionService,
|
||||
refreshGateway,
|
||||
tournamentResultService,
|
||||
legacyImportService,
|
||||
enrichmentService,
|
||||
);
|
||||
|
||||
return {
|
||||
worker,
|
||||
garnetService,
|
||||
jobQueueService,
|
||||
recentMatchesService,
|
||||
connectionService,
|
||||
refreshGateway,
|
||||
enrichmentService,
|
||||
};
|
||||
}
|
||||
|
||||
describe('RiotJobWorkerService', () => {
|
||||
it('acknowledges and deletes invalid stream entries', async () => {
|
||||
const { worker, garnetService } = makeWorker();
|
||||
|
||||
await (
|
||||
worker as unknown as {
|
||||
processEntry: (
|
||||
stream: string,
|
||||
entry: { id: string; message: Record<string, string> },
|
||||
) => Promise<void>;
|
||||
}
|
||||
).processEntry('riot:queue:high', {
|
||||
id: 'bad-1',
|
||||
message: { job: 'not-json' },
|
||||
});
|
||||
|
||||
expect(garnetService.acknowledgeStream).toHaveBeenCalledWith(
|
||||
'riot:queue:high',
|
||||
RIOT_JOB_GROUP,
|
||||
'bad-1',
|
||||
);
|
||||
expect(garnetService.deleteStreamEntries).toHaveBeenCalledWith(
|
||||
'riot:queue:high',
|
||||
'bad-1',
|
||||
);
|
||||
});
|
||||
|
||||
it('refreshes league entries while processing user history refresh jobs', async () => {
|
||||
const { worker, enrichmentService, recentMatchesService, garnetService } =
|
||||
makeWorker();
|
||||
const userId = new mongoose.Types.ObjectId().toString();
|
||||
const job: RiotRefreshSubJob = {
|
||||
jobId: 'job-1',
|
||||
parentJobId: 'parent-1',
|
||||
userId,
|
||||
puuid: 'puuid-1',
|
||||
region: 'asia',
|
||||
platform: 'kr',
|
||||
queueGroup: 'summoners-rift',
|
||||
queueIds: [420, 430],
|
||||
requestedAt: Date.now(),
|
||||
priority: 'high',
|
||||
};
|
||||
|
||||
await (
|
||||
worker as unknown as {
|
||||
processEntry: (
|
||||
stream: string,
|
||||
entry: { id: string; message: Record<string, string> },
|
||||
) => Promise<void>;
|
||||
}
|
||||
).processEntry('riot:queue:high', {
|
||||
id: '1-0',
|
||||
message: { job: JSON.stringify(job) },
|
||||
});
|
||||
|
||||
expect(recentMatchesService.ensureFreshForQueue).toHaveBeenCalledTimes(2);
|
||||
expect(enrichmentService.refreshLeagueEntries).toHaveBeenCalledWith({
|
||||
userId: expect.any(mongoose.Types.ObjectId),
|
||||
puuid: 'puuid-1',
|
||||
platform: 'kr',
|
||||
});
|
||||
expect(garnetService.acknowledgeStream).toHaveBeenCalledWith(
|
||||
'riot:queue:high',
|
||||
RIOT_JOB_GROUP,
|
||||
'1-0',
|
||||
);
|
||||
expect(garnetService.deleteStreamEntries).toHaveBeenCalledWith(
|
||||
'riot:queue:high',
|
||||
'1-0',
|
||||
);
|
||||
expect(
|
||||
garnetService.acknowledgeStream.mock.invocationCallOrder[0],
|
||||
).toBeLessThan(
|
||||
garnetService.deleteStreamEntries.mock.invocationCallOrder[0],
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -9,7 +9,10 @@ import { ConnectionService } from '../global/database/connection.service';
|
||||
import { GarnetService, StreamEntry } from '../global/garnet/garnet.service';
|
||||
import { LegacyImportService } from '../legacy-import/legacy-import.service';
|
||||
import type { LegacyImportMemberJob } from '../legacy-import/legacy-import.types';
|
||||
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
||||
import { RiotRecentMatchesService } from '../riot/riot-recent-matches.service';
|
||||
import { TournamentResultService } from '../tournament-result/tournament-result.service';
|
||||
import type { PollTournamentResultJob } from '../tournament-result/tournament-result.types';
|
||||
import {
|
||||
RIOT_JOB_GROUP,
|
||||
RIOT_JOB_HIGH_STREAM,
|
||||
@@ -19,8 +22,6 @@ import {
|
||||
} from './riot-job-queue.types';
|
||||
import { RiotJobQueueService } from './riot-job-queue.service';
|
||||
import { RiotRefreshGateway } from './riot-refresh.gateway';
|
||||
import { TournamentResultService } from '../tournament-result/tournament-result.service';
|
||||
import type { PollTournamentResultJob } from '../tournament-result/tournament-result.types';
|
||||
|
||||
const LEADER_KEY = 'riot:worker:leader';
|
||||
const LEADER_TTL_SECONDS = 60;
|
||||
@@ -39,6 +40,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
||||
private readonly refreshGateway: RiotRefreshGateway,
|
||||
private readonly tournamentResultService: TournamentResultService,
|
||||
private readonly legacyImportService: LegacyImportService,
|
||||
private readonly enrichmentService: RiotAccountEnrichmentService,
|
||||
) {}
|
||||
|
||||
public async onModuleInit() {
|
||||
@@ -77,10 +79,13 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
private async processEntry(stream: string, entry: StreamEntry): Promise<void> {
|
||||
private async processEntry(
|
||||
stream: string,
|
||||
entry: StreamEntry,
|
||||
): Promise<void> {
|
||||
const job = this.parseJob(entry);
|
||||
if (!job) {
|
||||
await this.garnetService.acknowledgeStream(stream, RIOT_JOB_GROUP, entry.id);
|
||||
await this.acknowledgeAndDelete(stream, entry.id);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -102,6 +107,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
||||
queueId,
|
||||
});
|
||||
}
|
||||
await this.refreshLeagueEntries(job);
|
||||
await this.markUserFetchedAt(job);
|
||||
const event = await this.jobQueueService.markCompleted(job);
|
||||
this.refreshGateway.broadcastRefreshEvent(event);
|
||||
@@ -131,7 +137,50 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
||||
}`,
|
||||
);
|
||||
} finally {
|
||||
await this.garnetService.acknowledgeStream(stream, RIOT_JOB_GROUP, entry.id);
|
||||
await this.acknowledgeAndDelete(stream, entry.id);
|
||||
}
|
||||
}
|
||||
|
||||
private async acknowledgeAndDelete(
|
||||
stream: string,
|
||||
id: string,
|
||||
): Promise<void> {
|
||||
await this.garnetService.acknowledgeStream(stream, RIOT_JOB_GROUP, id);
|
||||
await this.deleteAcknowledgedEntry(stream, id);
|
||||
}
|
||||
|
||||
private async deleteAcknowledgedEntry(
|
||||
stream: string,
|
||||
id: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await this.garnetService.deleteStreamEntries(stream, id);
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
`Failed to delete acknowledged Riot job stream entry ${stream} ${id}: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async refreshLeagueEntries(job: RiotRefreshSubJob): Promise<void> {
|
||||
try {
|
||||
const result = await this.enrichmentService.refreshLeagueEntries({
|
||||
userId: new mongoose.Types.ObjectId(job.userId),
|
||||
puuid: job.puuid,
|
||||
platform: job.platform,
|
||||
});
|
||||
if (result !== 'failed') return;
|
||||
this.logger.warn(
|
||||
`Riot league refresh failed ${job.jobId}: puuid=${job.puuid}`,
|
||||
);
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
`Riot league refresh failed ${job.jobId}: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,9 +218,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
||||
return job.kind === 'poll-tournament-result';
|
||||
}
|
||||
|
||||
private isLegacyImportJob(
|
||||
job: RiotJobPayload,
|
||||
): job is LegacyImportMemberJob {
|
||||
private isLegacyImportJob(job: RiotJobPayload): job is LegacyImportMemberJob {
|
||||
return job.kind === 'legacy-import-member';
|
||||
}
|
||||
|
||||
@@ -196,7 +243,8 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
||||
try {
|
||||
await this.garnetService.createConsumerGroup(stream, RIOT_JOB_GROUP);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
const message =
|
||||
error instanceof Error ? error.message : String(error);
|
||||
if (!message.includes('BUSYGROUP')) throw error;
|
||||
}
|
||||
}),
|
||||
|
||||
@@ -70,9 +70,11 @@ function makeAccount(overrides: Partial<FakeAccount> = {}): FakeAccount {
|
||||
|
||||
function makeUser(account: FakeAccount) {
|
||||
const _id = new mongoose.Types.ObjectId();
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const save = jest.fn().mockResolvedValue(undefined);
|
||||
return {
|
||||
_id,
|
||||
communityId,
|
||||
riotAccounts: [account],
|
||||
save,
|
||||
};
|
||||
@@ -86,6 +88,7 @@ function makeService(overrides?: {
|
||||
mastery?: Partial<RiotChampionMasteryService>;
|
||||
recentMatches?: Partial<RiotRecentMatchesService>;
|
||||
recentStats?: Partial<RiotRecentStatsService>;
|
||||
match?: any;
|
||||
}) {
|
||||
const user = overrides?.user;
|
||||
const userFindById = jest.fn().mockReturnValue({
|
||||
@@ -98,10 +101,15 @@ function makeService(overrides?: {
|
||||
Promise.resolve({
|
||||
riotPlatform: 'kr',
|
||||
riotRegion: 'asia',
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
const matchUpdateManyExec = jest.fn().mockResolvedValue({ modifiedCount: 0 });
|
||||
const matchModel = {
|
||||
updateMany: jest.fn().mockReturnValue({ exec: matchUpdateManyExec }),
|
||||
...overrides?.match,
|
||||
};
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockImplementation(async (modelName: string) => {
|
||||
if (modelName === 'user') {
|
||||
@@ -110,6 +118,9 @@ function makeService(overrides?: {
|
||||
if (modelName === 'community') {
|
||||
return { findById: communityFindById };
|
||||
}
|
||||
if (modelName === 'match') {
|
||||
return matchModel;
|
||||
}
|
||||
throw new Error(`Unexpected model: ${modelName}`);
|
||||
}),
|
||||
} as unknown as ConnectionService;
|
||||
@@ -160,6 +171,8 @@ function makeService(overrides?: {
|
||||
masteryService,
|
||||
recentMatchesService,
|
||||
recentStatsService,
|
||||
matchModel,
|
||||
matchUpdateManyExec,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -370,6 +383,273 @@ describe('RiotAccountEnrichmentService', () => {
|
||||
expect(user.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refreshes league entries without refreshing recent matches', async () => {
|
||||
const recent = new Date(Date.now() - 60_000);
|
||||
const account = makeAccount({
|
||||
revisionDate: Date.now() - 60_000,
|
||||
tiers: [
|
||||
{
|
||||
leagueId: 'L1',
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'GOLD',
|
||||
rank: 'II',
|
||||
puuid: 'puuid-1',
|
||||
leaguePoints: 1,
|
||||
wins: 1,
|
||||
losses: 1,
|
||||
fetchedAt: recent,
|
||||
},
|
||||
],
|
||||
recentStatsFetchedAt: recent,
|
||||
recentStatsSummary: createEmptyRiotRecentStatsSummary(),
|
||||
});
|
||||
const user = makeUser(account);
|
||||
const { service, leagueService, recentMatchesService } = makeService({
|
||||
user,
|
||||
league: {
|
||||
getEntriesByPuuid: jest.fn().mockResolvedValue([
|
||||
{
|
||||
leagueId: 'L2',
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'PLATINUM',
|
||||
rank: 'IV',
|
||||
puuid: 'puuid-1',
|
||||
leaguePoints: 20,
|
||||
wins: 10,
|
||||
losses: 8,
|
||||
},
|
||||
]),
|
||||
} as Partial<RiotLeagueService>,
|
||||
});
|
||||
|
||||
const result = await service.refreshLeagueEntries({
|
||||
userId: user._id,
|
||||
puuid: 'puuid-1',
|
||||
platform: 'kr',
|
||||
});
|
||||
|
||||
expect(result).toBe('updated');
|
||||
expect(leagueService.getEntriesByPuuid).toHaveBeenCalledWith('puuid-1', {
|
||||
platform: 'kr',
|
||||
});
|
||||
expect(recentMatchesService.syncRecentMatches).not.toHaveBeenCalled();
|
||||
expect(account.tiers).toHaveLength(1);
|
||||
expect(account.tiers[0]).toMatchObject({
|
||||
leagueId: 'L2',
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'PLATINUM',
|
||||
rank: 'IV',
|
||||
leaguePoints: 20,
|
||||
});
|
||||
expect(account.tierHistory.at(-1)).toMatchObject({
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'PLATINUM',
|
||||
rank: 'IV',
|
||||
leaguePoints: 20,
|
||||
});
|
||||
expect(user.save).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('appends tier history when LP changes without tier or rank changes', async () => {
|
||||
const recent = new Date(Date.now() - 60_000);
|
||||
const account = makeAccount({
|
||||
revisionDate: Date.now() - 60_000,
|
||||
tiers: [
|
||||
{
|
||||
leagueId: 'L1',
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'GOLD',
|
||||
rank: 'II',
|
||||
puuid: 'puuid-1',
|
||||
leaguePoints: 10,
|
||||
wins: 20,
|
||||
losses: 12,
|
||||
fetchedAt: recent,
|
||||
},
|
||||
],
|
||||
tierHistory: [
|
||||
{
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'GOLD',
|
||||
rank: 'II',
|
||||
leaguePoints: 10,
|
||||
wins: 20,
|
||||
losses: 12,
|
||||
recordedAt: recent,
|
||||
},
|
||||
],
|
||||
recentStatsFetchedAt: recent,
|
||||
recentStatsSummary: createEmptyRiotRecentStatsSummary(),
|
||||
});
|
||||
const user = makeUser(account);
|
||||
const { service } = makeService({
|
||||
user,
|
||||
league: {
|
||||
getEntriesByPuuid: jest.fn().mockResolvedValue([
|
||||
{
|
||||
leagueId: 'L1',
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'GOLD',
|
||||
rank: 'II',
|
||||
puuid: 'puuid-1',
|
||||
leaguePoints: 44,
|
||||
wins: 21,
|
||||
losses: 12,
|
||||
},
|
||||
]),
|
||||
} as Partial<RiotLeagueService>,
|
||||
});
|
||||
|
||||
await service.refreshLeagueEntries({
|
||||
userId: user._id,
|
||||
puuid: 'puuid-1',
|
||||
platform: 'kr',
|
||||
});
|
||||
|
||||
expect(account.tierHistory).toHaveLength(2);
|
||||
expect(account.tierHistory.at(-1)).toMatchObject({
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'GOLD',
|
||||
rank: 'II',
|
||||
leaguePoints: 44,
|
||||
wins: 21,
|
||||
losses: 12,
|
||||
});
|
||||
});
|
||||
|
||||
it('syncs refreshed league tier into active match participant snapshots', async () => {
|
||||
const recent = new Date(Date.now() - 60_000);
|
||||
const account = makeAccount({
|
||||
revisionDate: Date.now() - 60_000,
|
||||
tiers: [
|
||||
{
|
||||
leagueId: 'L1',
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'GOLD',
|
||||
rank: 'II',
|
||||
puuid: 'puuid-1',
|
||||
leaguePoints: 1,
|
||||
wins: 1,
|
||||
losses: 1,
|
||||
fetchedAt: recent,
|
||||
},
|
||||
],
|
||||
recentStatsFetchedAt: recent,
|
||||
recentStatsSummary: createEmptyRiotRecentStatsSummary(),
|
||||
});
|
||||
const user = makeUser(account);
|
||||
const { service, matchModel } = makeService({
|
||||
user,
|
||||
league: {
|
||||
getEntriesByPuuid: jest.fn().mockResolvedValue([
|
||||
{
|
||||
leagueId: 'L2',
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'PLATINUM',
|
||||
rank: 'IV',
|
||||
puuid: 'puuid-1',
|
||||
leaguePoints: 20,
|
||||
wins: 10,
|
||||
losses: 8,
|
||||
},
|
||||
]),
|
||||
} as Partial<RiotLeagueService>,
|
||||
});
|
||||
|
||||
await service.refreshLeagueEntries({
|
||||
userId: user._id,
|
||||
puuid: 'puuid-1',
|
||||
platform: 'kr',
|
||||
});
|
||||
|
||||
expect(matchModel.updateMany).toHaveBeenCalledWith(
|
||||
{
|
||||
status: { $in: ['recruiting', 'team-built', 'in-progress'] },
|
||||
participants: {
|
||||
$elemMatch: {
|
||||
userId: user._id,
|
||||
puuid: 'puuid-1',
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
'participants.$[participant].tier': expect.objectContaining({
|
||||
leagueId: 'L2',
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'PLATINUM',
|
||||
rank: 'IV',
|
||||
leaguePoints: 20,
|
||||
}),
|
||||
},
|
||||
},
|
||||
{
|
||||
arrayFilters: [
|
||||
{
|
||||
'participant.userId': user._id,
|
||||
'participant.puuid': 'puuid-1',
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it('clears active match participant tier when refreshed league entries are empty', async () => {
|
||||
const recent = new Date(Date.now() - 60_000);
|
||||
const account = makeAccount({
|
||||
revisionDate: Date.now() - 60_000,
|
||||
tiers: [
|
||||
{
|
||||
leagueId: 'L1',
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'GOLD',
|
||||
rank: 'II',
|
||||
puuid: 'puuid-1',
|
||||
leaguePoints: 1,
|
||||
wins: 1,
|
||||
losses: 1,
|
||||
fetchedAt: recent,
|
||||
},
|
||||
],
|
||||
recentStatsFetchedAt: recent,
|
||||
recentStatsSummary: createEmptyRiotRecentStatsSummary(),
|
||||
});
|
||||
const user = makeUser(account);
|
||||
const { service, matchModel } = makeService({
|
||||
user,
|
||||
league: {
|
||||
getEntriesByPuuid: jest.fn().mockResolvedValue([]),
|
||||
} as Partial<RiotLeagueService>,
|
||||
});
|
||||
|
||||
await service.refreshLeagueEntries({
|
||||
userId: user._id,
|
||||
puuid: 'puuid-1',
|
||||
platform: 'kr',
|
||||
});
|
||||
|
||||
expect(matchModel.updateMany).toHaveBeenCalledWith(
|
||||
{
|
||||
status: { $in: ['recruiting', 'team-built', 'in-progress'] },
|
||||
participants: {
|
||||
$elemMatch: {
|
||||
userId: user._id,
|
||||
puuid: 'puuid-1',
|
||||
},
|
||||
},
|
||||
},
|
||||
{ $unset: { 'participants.$[participant].tier': '' } },
|
||||
{
|
||||
arrayFilters: [
|
||||
{
|
||||
'participant.userId': user._id,
|
||||
'participant.puuid': 'puuid-1',
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it('records failed for individual failing fetches but updates the rest', async () => {
|
||||
const account = makeAccount();
|
||||
const user = makeUser(account);
|
||||
|
||||
@@ -3,6 +3,7 @@ import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import {
|
||||
ChampionMasteryEntry,
|
||||
MatchStatus,
|
||||
RiotAccount,
|
||||
TierInfo,
|
||||
} from '../global/database/schema';
|
||||
@@ -33,6 +34,11 @@ const DEFAULT_SUMMONER_TTL_MS = 24 * 60 * 60 * 1000; // 24h
|
||||
const DEFAULT_LEAGUE_TTL_MS = 60 * 60 * 1000; // 1h
|
||||
const DEFAULT_MASTERY_TTL_MS = 6 * 60 * 60 * 1000; // 6h
|
||||
const DEFAULT_RECENT_MATCHES_TTL_MS = 6 * 60 * 60 * 1000; // 6h
|
||||
const ACTIVE_MATCH_STATUSES: MatchStatus[] = [
|
||||
'recruiting',
|
||||
'team-built',
|
||||
'in-progress',
|
||||
];
|
||||
|
||||
export interface EnrichOptions {
|
||||
platform?: RiotPlatformRoute;
|
||||
@@ -52,6 +58,8 @@ export interface EnrichResult {
|
||||
account: RiotAccount | null;
|
||||
}
|
||||
|
||||
export type RefreshLeagueEntriesResult = 'updated' | 'failed';
|
||||
|
||||
@Injectable()
|
||||
export class RiotAccountEnrichmentService {
|
||||
private readonly logger = new Logger(RiotAccountEnrichmentService.name);
|
||||
@@ -67,6 +75,18 @@ export class RiotAccountEnrichmentService {
|
||||
private readonly recentStatsService: RiotRecentStatsService,
|
||||
) {}
|
||||
|
||||
public async markRefreshRequested(
|
||||
userId: mongoose.Types.ObjectId,
|
||||
puuid: string,
|
||||
at: Date = new Date(),
|
||||
): Promise<void> {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
await UserModel.updateOne(
|
||||
{ _id: userId, 'riotAccounts.puuid': puuid },
|
||||
{ $set: { 'riotAccounts.$.lastRefreshRequestedAt': at } },
|
||||
).exec();
|
||||
}
|
||||
|
||||
public async enrichRiotAccount(params: {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
puuid: string;
|
||||
@@ -83,6 +103,34 @@ export class RiotAccountEnrichmentService {
|
||||
return promise;
|
||||
}
|
||||
|
||||
public async refreshLeagueEntries(params: {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
puuid: string;
|
||||
platform?: RiotPlatformRoute;
|
||||
}): Promise<RefreshLeagueEntriesResult> {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
const user = await UserModel.findById(params.userId).exec();
|
||||
if (!user) return 'failed';
|
||||
|
||||
const account = user.riotAccounts.find((a) => a.puuid === params.puuid);
|
||||
if (!account) return 'failed';
|
||||
|
||||
const outcome = await this.fetchLeagueSafe(
|
||||
params.puuid,
|
||||
params.platform ?? DEFAULT_PLATFORM,
|
||||
);
|
||||
if (outcome.status !== 'updated' || !outcome.dto) return 'failed';
|
||||
|
||||
this.applyLeagueEntries(account, outcome.dto);
|
||||
await user.save();
|
||||
await this.syncActiveMatchParticipantTier(
|
||||
user._id,
|
||||
params.puuid,
|
||||
account.tiers,
|
||||
);
|
||||
return 'updated';
|
||||
}
|
||||
|
||||
private async doEnrichRiotAccount(params: {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
puuid: string;
|
||||
@@ -117,7 +165,8 @@ export class RiotAccountEnrichmentService {
|
||||
.exec();
|
||||
|
||||
const opts = params.options ?? {};
|
||||
const platform = opts.platform ?? community?.riotPlatform ?? DEFAULT_PLATFORM;
|
||||
const platform =
|
||||
opts.platform ?? community?.riotPlatform ?? DEFAULT_PLATFORM;
|
||||
const region = opts.region ?? community?.riotRegion ?? DEFAULT_REGION;
|
||||
const now = Date.now();
|
||||
|
||||
@@ -161,19 +210,19 @@ export class RiotAccountEnrichmentService {
|
||||
|
||||
const [leagueOutcome, masteryOutcome, recentMatchesOutcome] =
|
||||
await Promise.all([
|
||||
leagueStale
|
||||
? this.fetchLeagueSafe(params.puuid, effectivePlatform)
|
||||
: Promise.resolve({ status: 'fresh' as const, dto: null }),
|
||||
masteryStale
|
||||
? this.fetchMasteriesSafe(params.puuid, effectivePlatform)
|
||||
: Promise.resolve({ status: 'fresh' as const, dto: null }),
|
||||
recentMatchesStale
|
||||
? this.fetchRecentMatchesSafe(params.puuid, region, seasonStartedAt)
|
||||
: Promise.resolve({
|
||||
status: 'fresh' as const,
|
||||
summary: null,
|
||||
matchIds: null,
|
||||
}),
|
||||
leagueStale
|
||||
? this.fetchLeagueSafe(params.puuid, effectivePlatform)
|
||||
: Promise.resolve({ status: 'fresh' as const, dto: null }),
|
||||
masteryStale
|
||||
? this.fetchMasteriesSafe(params.puuid, effectivePlatform)
|
||||
: Promise.resolve({ status: 'fresh' as const, dto: null }),
|
||||
recentMatchesStale
|
||||
? this.fetchRecentMatchesSafe(params.puuid, region, seasonStartedAt)
|
||||
: Promise.resolve({
|
||||
status: 'fresh' as const,
|
||||
summary: null,
|
||||
matchIds: null,
|
||||
}),
|
||||
]);
|
||||
|
||||
if (summonerOutcome.status === 'updated' && summonerOutcome.dto) {
|
||||
@@ -205,6 +254,13 @@ export class RiotAccountEnrichmentService {
|
||||
) {
|
||||
await user.save();
|
||||
}
|
||||
if (leagueOutcome.status === 'updated') {
|
||||
await this.syncActiveMatchParticipantTier(
|
||||
user._id,
|
||||
params.puuid,
|
||||
account.tiers,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
summoner: summonerOutcome.status,
|
||||
@@ -387,7 +443,10 @@ export class RiotAccountEnrichmentService {
|
||||
const changed =
|
||||
!last ||
|
||||
last.tier !== entry.tier ||
|
||||
(last.rank ?? '') !== (entry.rank ?? '');
|
||||
(last.rank ?? '') !== (entry.rank ?? '') ||
|
||||
last.leaguePoints !== entry.leaguePoints ||
|
||||
last.wins !== entry.wins ||
|
||||
last.losses !== entry.losses;
|
||||
if (!changed) continue;
|
||||
|
||||
account.tierHistory.push({
|
||||
@@ -425,6 +484,62 @@ export class RiotAccountEnrichmentService {
|
||||
account.matchIdsFetchedAt = fetchedAt;
|
||||
}
|
||||
|
||||
private async syncActiveMatchParticipantTier(
|
||||
userId: mongoose.Types.ObjectId,
|
||||
puuid: string,
|
||||
tiers: TierInfo[],
|
||||
): Promise<void> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const tier = this.selectParticipantTier(tiers);
|
||||
const update = tier
|
||||
? { $set: { 'participants.$[participant].tier': tier } }
|
||||
: { $unset: { 'participants.$[participant].tier': '' } };
|
||||
|
||||
await MatchModel.updateMany(
|
||||
{
|
||||
status: { $in: ACTIVE_MATCH_STATUSES },
|
||||
participants: {
|
||||
$elemMatch: {
|
||||
userId,
|
||||
puuid,
|
||||
},
|
||||
},
|
||||
},
|
||||
update,
|
||||
{
|
||||
arrayFilters: [
|
||||
{
|
||||
'participant.userId': userId,
|
||||
'participant.puuid': puuid,
|
||||
},
|
||||
],
|
||||
},
|
||||
).exec();
|
||||
}
|
||||
|
||||
private selectParticipantTier(tiers: TierInfo[]): TierInfo | undefined {
|
||||
const tier =
|
||||
tiers.find((entry) => entry.queueType === 'RANKED_SOLO_5x5') ?? tiers[0];
|
||||
if (!tier) return undefined;
|
||||
|
||||
return {
|
||||
leagueId: tier.leagueId,
|
||||
queueType: tier.queueType,
|
||||
tier: tier.tier,
|
||||
rank: tier.rank,
|
||||
puuid: tier.puuid,
|
||||
leaguePoints: tier.leaguePoints,
|
||||
wins: tier.wins,
|
||||
losses: tier.losses,
|
||||
veteran: tier.veteran,
|
||||
inactive: tier.inactive,
|
||||
freshBlood: tier.freshBlood,
|
||||
hotStreak: tier.hotStreak,
|
||||
miniSeries: tier.miniSeries,
|
||||
fetchedAt: tier.fetchedAt,
|
||||
};
|
||||
}
|
||||
|
||||
private tiersOldestAt(tiers: TierInfo[]): number {
|
||||
if (tiers.length === 0) return 0;
|
||||
let oldest = Infinity;
|
||||
|
||||
@@ -5,7 +5,7 @@ const DDRAGON_BASE = 'https://ddragon.leagueoflegends.com';
|
||||
const DDRAGON_CDN = `${DDRAGON_BASE}/cdn`;
|
||||
const DEFAULT_LOCALE = 'ko_KR';
|
||||
const CACHE_TTL_SECONDS = 24 * 60 * 60;
|
||||
const CACHE_VERSION = 'v2';
|
||||
const CACHE_VERSION = 'v3';
|
||||
const FETCH_TIMEOUT_MS = 10_000;
|
||||
|
||||
export interface DdragonChampionEntry {
|
||||
@@ -13,11 +13,29 @@ export interface DdragonChampionEntry {
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface DdragonSummonerSpellEntry {
|
||||
key: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface DdragonRuneEntry {
|
||||
id: number;
|
||||
key: string;
|
||||
icon: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface DdragonRuneStyleEntry extends DdragonRuneEntry {
|
||||
slots: Array<{ runes: DdragonRuneEntry[] }>;
|
||||
}
|
||||
|
||||
export interface DdragonManifest {
|
||||
version: string;
|
||||
cdn: string;
|
||||
locale: string;
|
||||
champions: Record<string, DdragonChampionEntry>;
|
||||
summonerSpells: Record<string, DdragonSummonerSpellEntry>;
|
||||
runesReforged: DdragonRuneStyleEntry[];
|
||||
fetchedAt: string;
|
||||
}
|
||||
|
||||
@@ -31,6 +49,27 @@ interface ChampionDataResponse {
|
||||
data: Record<string, ChampionDataEntry>;
|
||||
}
|
||||
|
||||
interface SummonerSpellDataEntry {
|
||||
key: string;
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface SummonerSpellDataResponse {
|
||||
data: Record<string, SummonerSpellDataEntry>;
|
||||
}
|
||||
|
||||
interface RuneDataEntry {
|
||||
id: number;
|
||||
key: string;
|
||||
icon: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface RuneStyleDataEntry extends RuneDataEntry {
|
||||
slots?: Array<{ runes?: RuneDataEntry[] }>;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class RiotDdragonService {
|
||||
private readonly logger = new Logger(RiotDdragonService.name);
|
||||
@@ -63,12 +102,18 @@ export class RiotDdragonService {
|
||||
|
||||
private async buildManifest(locale: string): Promise<DdragonManifest> {
|
||||
const version = await this.fetchLatestVersion();
|
||||
const champions = await this.fetchChampionMap(version, locale);
|
||||
const [champions, summonerSpells, runesReforged] = await Promise.all([
|
||||
this.fetchChampionMap(version, locale),
|
||||
this.fetchSummonerSpellMap(version, locale),
|
||||
this.fetchRuneStyles(version, locale),
|
||||
]);
|
||||
return {
|
||||
version,
|
||||
cdn: DDRAGON_CDN,
|
||||
locale,
|
||||
champions,
|
||||
summonerSpells,
|
||||
runesReforged,
|
||||
fetchedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
@@ -103,6 +148,58 @@ export class RiotDdragonService {
|
||||
return map;
|
||||
}
|
||||
|
||||
private async fetchSummonerSpellMap(
|
||||
version: string,
|
||||
locale: string,
|
||||
): Promise<Record<string, DdragonSummonerSpellEntry>> {
|
||||
const url = `${DDRAGON_CDN}/${version}/data/${locale}/summoner.json`;
|
||||
const payload = await this.fetchJson<SummonerSpellDataResponse>(url);
|
||||
if (!payload || typeof payload !== 'object' || !payload.data) {
|
||||
throw new Error(`ddragon summoner.json response is malformed (${url}).`);
|
||||
}
|
||||
|
||||
const map: Record<string, DdragonSummonerSpellEntry> = {};
|
||||
for (const entry of Object.values(payload.data)) {
|
||||
if (entry?.key && entry.id) {
|
||||
map[entry.key] = {
|
||||
key: entry.id,
|
||||
name: typeof entry.name === 'string' ? entry.name : entry.id,
|
||||
};
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private async fetchRuneStyles(
|
||||
version: string,
|
||||
locale: string,
|
||||
): Promise<DdragonRuneStyleEntry[]> {
|
||||
const url = `${DDRAGON_CDN}/${version}/data/${locale}/runesReforged.json`;
|
||||
const payload = await this.fetchJson<unknown>(url);
|
||||
if (!Array.isArray(payload)) {
|
||||
throw new Error(`ddragon runesReforged.json response is malformed (${url}).`);
|
||||
}
|
||||
|
||||
return payload
|
||||
.filter((style): style is RuneStyleDataEntry => isRuneEntry(style))
|
||||
.map((style) => ({
|
||||
id: style.id,
|
||||
key: style.key,
|
||||
icon: style.icon,
|
||||
name: style.name,
|
||||
slots: (style.slots ?? []).map((slot) => ({
|
||||
runes: (slot.runes ?? [])
|
||||
.filter((rune): rune is RuneDataEntry => isRuneEntry(rune))
|
||||
.map((rune) => ({
|
||||
id: rune.id,
|
||||
key: rune.key,
|
||||
icon: rune.icon,
|
||||
name: rune.name,
|
||||
})),
|
||||
})),
|
||||
}));
|
||||
}
|
||||
|
||||
private async fetchJson<T>(url: string): Promise<T> {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
||||
@@ -137,6 +234,17 @@ function normalizeLocale(locale: string): string {
|
||||
return `${trimmed.slice(0, 2).toLowerCase()}_${trimmed.slice(3).toUpperCase()}`;
|
||||
}
|
||||
|
||||
function isRuneEntry(value: unknown): value is RuneDataEntry {
|
||||
if (!value || typeof value !== 'object') return false;
|
||||
const entry = value as Partial<RuneDataEntry>;
|
||||
return (
|
||||
typeof entry.id === 'number' &&
|
||||
typeof entry.key === 'string' &&
|
||||
typeof entry.icon === 'string' &&
|
||||
typeof entry.name === 'string'
|
||||
);
|
||||
}
|
||||
|
||||
function manifestCacheKey(locale: string): string {
|
||||
return `ddragon:manifest:${CACHE_VERSION}:${locale}`;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { RiotClientService } from './riot.client.service';
|
||||
import { RiotLeagueService } from './riot-league.service';
|
||||
import type { RiotLeagueEntryDto, RiotResponseParser } from './riot.types';
|
||||
|
||||
describe('RiotLeagueService', () => {
|
||||
it('accepts Riot league entries without optional leagueId', async () => {
|
||||
const client = {
|
||||
get: jest.fn(
|
||||
async <T>(
|
||||
_path: string,
|
||||
_options: unknown,
|
||||
parser?: RiotResponseParser<T>,
|
||||
) =>
|
||||
parser
|
||||
? parser([
|
||||
{
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'EMERALD',
|
||||
rank: 'I',
|
||||
puuid: 'puuid-1',
|
||||
leaguePoints: 75,
|
||||
wins: 160,
|
||||
losses: 148,
|
||||
},
|
||||
])
|
||||
: ([] as T),
|
||||
),
|
||||
} as unknown as RiotClientService;
|
||||
const service = new RiotLeagueService(client);
|
||||
|
||||
const result = await service.getEntriesByPuuid('puuid-1', {
|
||||
platform: 'kr',
|
||||
});
|
||||
|
||||
expect(result).toEqual<RiotLeagueEntryDto[]>([
|
||||
{
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'EMERALD',
|
||||
rank: 'I',
|
||||
puuid: 'puuid-1',
|
||||
leaguePoints: 75,
|
||||
wins: 160,
|
||||
losses: 148,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -36,7 +36,10 @@ function parseEntry(value: unknown, index: number): RiotLeagueEntryDto {
|
||||
throw new TypeError(`leagueEntries[${index}] must be an object.`);
|
||||
}
|
||||
return {
|
||||
leagueId: requireString(value.leagueId, `leagueEntries[${index}].leagueId`),
|
||||
leagueId: optionalString(
|
||||
value.leagueId,
|
||||
`leagueEntries[${index}].leagueId`,
|
||||
),
|
||||
queueType: requireString(
|
||||
value.queueType,
|
||||
`leagueEntries[${index}].queueType`,
|
||||
@@ -71,6 +74,11 @@ function requireString(value: unknown, path: string): string {
|
||||
return value;
|
||||
}
|
||||
|
||||
function optionalString(value: unknown, path: string): string | undefined {
|
||||
if (value === undefined || value === null) return undefined;
|
||||
return requireString(value, path);
|
||||
}
|
||||
|
||||
function requireNumber(value: unknown, path: string): number {
|
||||
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
||||
throw new TypeError(`${path} must be a finite number.`);
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import { GarnetService } from '../global/garnet/garnet.service';
|
||||
import { RiotRateLimiterService } from './riot-rate-limiter.service';
|
||||
|
||||
function makeService(sendCommand = jest.fn().mockResolvedValue(0)) {
|
||||
const garnet = {
|
||||
getString: jest.fn().mockResolvedValue(null),
|
||||
raw: jest.fn().mockReturnValue({ sendCommand }),
|
||||
setString: jest.fn().mockResolvedValue(undefined),
|
||||
} as unknown as jest.Mocked<GarnetService>;
|
||||
return {
|
||||
service: new RiotRateLimiterService(garnet),
|
||||
garnet,
|
||||
sendCommand,
|
||||
};
|
||||
}
|
||||
|
||||
function observedState(params: {
|
||||
count120: number;
|
||||
limit120?: number;
|
||||
observedAt: number;
|
||||
windowStartAt: number;
|
||||
}) {
|
||||
return JSON.stringify({
|
||||
count120: params.count120,
|
||||
limit120: params.limit120 ?? 100,
|
||||
observedAt: params.observedAt,
|
||||
windowStartAt: params.windowStartAt,
|
||||
});
|
||||
}
|
||||
|
||||
describe('RiotRateLimiterService', () => {
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('uses global app rate keys and passes cost to the Lua script', async () => {
|
||||
jest.spyOn(Date, 'now').mockReturnValue(1_000);
|
||||
const { service, sendCommand } = makeService();
|
||||
|
||||
await service.acquire('asia', 3);
|
||||
|
||||
expect(sendCommand).toHaveBeenCalledTimes(1);
|
||||
const command = sendCommand.mock.calls[0][0] as string[];
|
||||
expect(command[0]).toBe('EVAL');
|
||||
expect(command[2]).toBe('2');
|
||||
expect(command[3]).toBe('riot:rl:app:1000');
|
||||
expect(command[4]).toBe('riot:rl:app:120000');
|
||||
expect(command[5]).toBe('1000');
|
||||
expect(command[7]).toBe('3');
|
||||
});
|
||||
|
||||
it('records the 120 second app rate observation from Riot headers', async () => {
|
||||
jest.spyOn(Date, 'now').mockReturnValue(1_000_000);
|
||||
const { service, garnet } = makeService();
|
||||
|
||||
await service.recordAppRateLimitObservation('47:120,3:1', '100:120,20:1');
|
||||
|
||||
expect(garnet.setString).toHaveBeenCalledTimes(1);
|
||||
const [key, raw, ttl] = garnet.setString.mock.calls[0];
|
||||
expect(key).toBe('riot:app:rl:observed');
|
||||
expect(ttl).toBe(300);
|
||||
expect(JSON.parse(raw)).toEqual({
|
||||
count120: 47,
|
||||
limit120: 100,
|
||||
observedAt: 1_000_000,
|
||||
windowStartAt: 1_000_000,
|
||||
});
|
||||
});
|
||||
|
||||
it('resets the inferred window when Riot count decreases or observation is stale', async () => {
|
||||
const { service, garnet } = makeService();
|
||||
|
||||
jest.spyOn(Date, 'now').mockReturnValue(1_060_000);
|
||||
garnet.getString.mockResolvedValueOnce(
|
||||
observedState({
|
||||
count120: 80,
|
||||
observedAt: 1_050_000,
|
||||
windowStartAt: 1_000_000,
|
||||
}),
|
||||
);
|
||||
|
||||
await service.recordAppRateLimitObservation('2:120', null);
|
||||
|
||||
expect(JSON.parse(garnet.setString.mock.calls[0][1])).toMatchObject({
|
||||
count120: 2,
|
||||
windowStartAt: 1_060_000,
|
||||
});
|
||||
|
||||
jest.spyOn(Date, 'now').mockReturnValue(1_240_000);
|
||||
garnet.getString.mockResolvedValueOnce(
|
||||
observedState({
|
||||
count120: 20,
|
||||
observedAt: 1_120_000,
|
||||
windowStartAt: 1_000_000,
|
||||
}),
|
||||
);
|
||||
|
||||
await service.recordAppRateLimitObservation('25:120', null);
|
||||
|
||||
expect(JSON.parse(garnet.setString.mock.calls[1][1])).toMatchObject({
|
||||
count120: 25,
|
||||
windowStartAt: 1_240_000,
|
||||
});
|
||||
});
|
||||
|
||||
it('opens the refresh gate when there is no active observation', async () => {
|
||||
const { service, garnet } = makeService();
|
||||
|
||||
await expect(service.isRefreshWindowOpen(0.5)).resolves.toBe(true);
|
||||
|
||||
garnet.getString.mockResolvedValueOnce(
|
||||
observedState({
|
||||
count120: 90,
|
||||
observedAt: 1_000_000,
|
||||
windowStartAt: 900_000,
|
||||
}),
|
||||
);
|
||||
jest.spyOn(Date, 'now').mockReturnValue(1_120_000);
|
||||
|
||||
await expect(service.isRefreshWindowOpen(0.5)).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ ratio: 0.5, count120: 49, expected: true },
|
||||
{ ratio: 0.5, count120: 50, expected: false },
|
||||
{ ratio: 0.8, count120: 79, expected: true },
|
||||
{ ratio: 0.8, count120: 80, expected: false },
|
||||
])(
|
||||
'checks tail headroom for refresh gate ratio=$ratio count=$count120',
|
||||
async ({ ratio, count120, expected }) => {
|
||||
jest.spyOn(Date, 'now').mockReturnValue(1_070_000);
|
||||
const { service, garnet } = makeService();
|
||||
garnet.getString.mockResolvedValue(
|
||||
observedState({
|
||||
count120,
|
||||
observedAt: 1_069_000,
|
||||
windowStartAt: 1_000_000,
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(service.isRefreshWindowOpen(ratio)).resolves.toBe(expected);
|
||||
},
|
||||
);
|
||||
|
||||
it('keeps the refresh gate closed before the 120 second window tail', async () => {
|
||||
jest.spyOn(Date, 'now').mockReturnValue(1_050_000);
|
||||
const { service, garnet } = makeService();
|
||||
garnet.getString.mockResolvedValue(
|
||||
observedState({
|
||||
count120: 10,
|
||||
observedAt: 1_049_000,
|
||||
windowStartAt: 1_000_000,
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(service.isRefreshWindowOpen(0.8)).resolves.toBe(false);
|
||||
});
|
||||
});
|
||||
Loaded 100 of 205 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user