Compare commits
36
Commits
release/86
...
ef141a13d0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ef141a13d0 | ||
|
|
f622ee5b1f | ||
|
|
4b8ccf0077 | ||
|
|
0c4c4239ec | ||
|
|
9117c9c0a4 | ||
|
|
5bc748dc4d | ||
|
|
de84ad5309 | ||
|
|
f223157542 | ||
|
|
cd1525c87a | ||
|
|
337970a12b | ||
|
|
58e24ccd75 | ||
|
|
827fc5b6b4 | ||
|
|
384d460ad6 | ||
|
|
71085d0ac4 | ||
|
|
904f1fc4a4 | ||
|
|
f526257d9c | ||
|
|
34a47c053e | ||
|
|
e3f39fd8b8 | ||
|
|
4385ba7b8b | ||
|
|
9cd5850d43 | ||
|
|
79534cf43c | ||
|
|
03be85d07b | ||
|
|
d269bdd92b | ||
|
|
2bac89d3dc | ||
|
|
760da1cbea | ||
|
|
ca786fd80a | ||
|
|
ac0d2b53f0 | ||
|
|
a4215f86fb | ||
|
|
a24726d7da | ||
|
|
bb68be14fa | ||
|
|
9e2f2c61e7 | ||
|
|
fd1fa2366c | ||
|
|
96fede9fe5 | ||
|
|
80fef25af3 | ||
|
|
1f75c6318a | ||
|
|
c155f26272 |
No files matched your search
+1
-5
@@ -19,19 +19,15 @@ website/LICENSE
|
|||||||
|
|
||||||
*.log
|
*.log
|
||||||
|
|
||||||
!.claude/settings.json
|
|
||||||
|
|
||||||
*.temp.MD
|
*.temp.MD
|
||||||
|
|
||||||
*.md
|
*.md
|
||||||
!README.md
|
!README.md
|
||||||
!AGENTS.md
|
|
||||||
!docs/specs/internal-match-game-analysis.md
|
!docs/specs/internal-match-game-analysis.md
|
||||||
!docs/plans/internal-match-game-analysis-p0-p1.md
|
!docs/plans/internal-match-game-analysis-p0-p1.md
|
||||||
!docs/specs/double-elimination-connector-routing.md
|
!docs/specs/double-elimination-connector-routing.md
|
||||||
!docs/plans/double-elimination-connector-routing.md
|
!docs/plans/double-elimination-connector-routing.md
|
||||||
!agents/**/*.md
|
!docs/plans/redis-8.10-optimization.md
|
||||||
!skills/**/*.md
|
|
||||||
/tmp/
|
/tmp/
|
||||||
/user-game-history/
|
/user-game-history/
|
||||||
/*.txt
|
/*.txt
|
||||||
|
|||||||
@@ -1,189 +0,0 @@
|
|||||||
# AGENTS.md
|
|
||||||
|
|
||||||
This file provides guidance to AI coding agents (Claude Code, Cursor, Copilot, Antigravity, etc.) when working with code in this repository.
|
|
||||||
|
|
||||||
## Repository Overview
|
|
||||||
|
|
||||||
A collection of skills for Claude.ai and Claude Code for senior software engineers. Skills are packaged instructions and scripts that extend Claude and your coding agents capabilities.
|
|
||||||
|
|
||||||
## OpenCode Integration
|
|
||||||
|
|
||||||
OpenCode uses a **skill-driven execution model** powered by the `skill` tool and this repository's `/skills` directory.
|
|
||||||
|
|
||||||
### Core Rules
|
|
||||||
|
|
||||||
- If a task matches a skill, you MUST invoke it
|
|
||||||
- Skills are located in `skills/<skill-name>/SKILL.md`
|
|
||||||
- Never implement directly if a skill applies
|
|
||||||
- Always follow the skill instructions exactly (do not partially apply them)
|
|
||||||
|
|
||||||
### Intent → Skill Mapping
|
|
||||||
|
|
||||||
The agent should automatically map user intent to skills:
|
|
||||||
|
|
||||||
- Feature / new functionality → `spec-driven-development`, then `incremental-implementation`, `test-driven-development`
|
|
||||||
- Planning / breakdown → `planning-and-task-breakdown`
|
|
||||||
- Bug / failure / unexpected behavior → `debugging-and-error-recovery`
|
|
||||||
- Code review → `code-review-and-quality`
|
|
||||||
- Refactoring / simplification → `code-simplification`
|
|
||||||
- API or interface design → `api-and-interface-design`
|
|
||||||
- UI work → `frontend-ui-engineering`
|
|
||||||
|
|
||||||
### Lifecycle Mapping (Implicit Commands)
|
|
||||||
|
|
||||||
OpenCode does not support slash commands like `/spec` or `/plan`.
|
|
||||||
|
|
||||||
Instead, the agent must internally follow this lifecycle:
|
|
||||||
|
|
||||||
- DEFINE → `spec-driven-development`
|
|
||||||
- PLAN → `planning-and-task-breakdown`
|
|
||||||
- BUILD → `incremental-implementation` + `test-driven-development`
|
|
||||||
- VERIFY → `debugging-and-error-recovery`
|
|
||||||
- REVIEW → `code-review-and-quality`
|
|
||||||
- SHIP → `shipping-and-launch`
|
|
||||||
|
|
||||||
### Execution Model
|
|
||||||
|
|
||||||
For every request:
|
|
||||||
|
|
||||||
1. Determine if any skill applies (even 1% chance)
|
|
||||||
2. Invoke the appropriate skill using the `skill` tool
|
|
||||||
3. Follow the skill workflow strictly
|
|
||||||
4. Only proceed to implementation after required steps (spec, plan, etc.) are complete
|
|
||||||
|
|
||||||
### Anti-Rationalization
|
|
||||||
|
|
||||||
The following thoughts are incorrect and must be ignored:
|
|
||||||
|
|
||||||
- "This is too small for a skill"
|
|
||||||
- "I can just quickly implement this"
|
|
||||||
- "I’ll gather context first"
|
|
||||||
|
|
||||||
Correct behavior:
|
|
||||||
|
|
||||||
- Always check for and use skills first
|
|
||||||
|
|
||||||
This ensures OpenCode behaves similarly to Claude Code with full workflow enforcement.
|
|
||||||
|
|
||||||
## Orchestration: Personas, Skills, and Commands
|
|
||||||
|
|
||||||
This repo has three composable layers. They have different jobs and should not be confused:
|
|
||||||
|
|
||||||
- **Skills** (`skills/<name>/SKILL.md`) — workflows with steps and exit criteria. The *how*. Mandatory hops when an intent matches.
|
|
||||||
- **Personas** (`agents/<role>.md`) — roles with a perspective and an output format. The *who*.
|
|
||||||
- **Slash commands** (`.claude/commands/*.md`) — user-facing entry points. The *when*. The orchestration layer.
|
|
||||||
|
|
||||||
Composition rule: **the user (or a slash command) is the orchestrator. Personas do not invoke other personas.** A persona may invoke skills.
|
|
||||||
|
|
||||||
The only multi-persona orchestration pattern this repo endorses is **parallel fan-out with a merge step** — used by `/ship` to run `code-reviewer`, `security-auditor`, and `test-engineer` concurrently and synthesize their reports. Do not build a "router" persona that decides which other persona to call; that's the job of slash commands and intent mapping.
|
|
||||||
|
|
||||||
See [agents/README.md](agents/README.md) for the decision matrix and [references/orchestration-patterns.md](references/orchestration-patterns.md) for the full pattern catalog.
|
|
||||||
|
|
||||||
**Claude Code interop:** the personas in `agents/` work as Claude Code subagents (auto-discovered from this plugin's `agents/` directory) and as Agent Teams teammates (referenced by name when spawning). Two platform constraints align with our rules: subagents cannot spawn other subagents, and teams cannot nest. Plugin agents silently ignore the `hooks`, `mcpServers`, and `permissionMode` frontmatter fields.
|
|
||||||
|
|
||||||
## Creating a New Skill
|
|
||||||
|
|
||||||
### Directory Structure
|
|
||||||
|
|
||||||
```
|
|
||||||
skills/
|
|
||||||
{skill-name}/ # kebab-case directory name
|
|
||||||
SKILL.md # Required: skill definition
|
|
||||||
scripts/ # Required: executable scripts
|
|
||||||
{script-name}.sh # Bash scripts (preferred)
|
|
||||||
{skill-name}.zip # Required: packaged for distribution
|
|
||||||
```
|
|
||||||
|
|
||||||
### Naming Conventions
|
|
||||||
|
|
||||||
- **Skill directory**: `kebab-case` (e.g. `web-quality`)
|
|
||||||
- **SKILL.md**: Always uppercase, always this exact filename
|
|
||||||
- **Scripts**: `kebab-case.sh` (e.g., `deploy.sh`, `fetch-logs.sh`)
|
|
||||||
- **Zip file**: Must match directory name exactly: `{skill-name}.zip`
|
|
||||||
|
|
||||||
### SKILL.md Format
|
|
||||||
|
|
||||||
```markdown
|
|
||||||
---
|
|
||||||
name: {skill-name}
|
|
||||||
description: {One sentence describing what the skill does, followed by one or more "Use when" trigger conditions. Include trigger phrases like "Deploy my app" or "Check logs" when helpful.}
|
|
||||||
---
|
|
||||||
|
|
||||||
# {Skill Title}
|
|
||||||
|
|
||||||
{Brief overview of what the skill does and why it matters.}
|
|
||||||
|
|
||||||
## How It Works
|
|
||||||
|
|
||||||
{Numbered list explaining the skill's workflow}
|
|
||||||
|
|
||||||
Equivalent headings like `Workflow`, `Core Process`, or `When to Use` are fine when they communicate the same structure clearly.
|
|
||||||
|
|
||||||
## Usage (Optional)
|
|
||||||
|
|
||||||
Include this section only if the skill ships runnable helpers under `scripts/`. Markdown-only skills can omit both the section and the directory entirely.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
bash /mnt/skills/user/{skill-name}/scripts/{script}.sh [args]
|
|
||||||
```
|
|
||||||
|
|
||||||
**Arguments:**
|
|
||||||
- `arg1` - Description (defaults to X)
|
|
||||||
|
|
||||||
**Examples:**
|
|
||||||
{Show 2-3 common usage patterns}
|
|
||||||
|
|
||||||
## Output
|
|
||||||
|
|
||||||
{Show example output users will see}
|
|
||||||
|
|
||||||
## Present Results to User
|
|
||||||
|
|
||||||
{Template for how Claude should format results when presenting to users}
|
|
||||||
|
|
||||||
## Troubleshooting
|
|
||||||
|
|
||||||
{Common issues and solutions, especially network/permissions errors}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Best Practices for Context Efficiency
|
|
||||||
|
|
||||||
Skills are loaded on-demand — only the skill name and description are loaded at startup. The full `SKILL.md` loads into context only when the agent decides the skill is relevant. To minimize context usage:
|
|
||||||
|
|
||||||
- **Keep SKILL.md under 500 lines** — put detailed reference material in separate files
|
|
||||||
- **Write specific descriptions** — helps the agent know exactly when to activate the skill
|
|
||||||
- **Use progressive disclosure** — reference supporting files that get read only when needed
|
|
||||||
- **Prefer scripts over inline code** — script execution doesn't consume context (only output does)
|
|
||||||
- **File references work one level deep** — link directly from SKILL.md to supporting files
|
|
||||||
|
|
||||||
### Script Requirements
|
|
||||||
|
|
||||||
- Use `#!/bin/bash` shebang
|
|
||||||
- Use `set -e` for fail-fast behavior
|
|
||||||
- Write status messages to stderr: `echo "Message" >&2`
|
|
||||||
- Write machine-readable output (JSON) to stdout
|
|
||||||
- Include a cleanup trap for temp files
|
|
||||||
- Reference the script path as `/mnt/skills/user/{skill-name}/scripts/{script}.sh`
|
|
||||||
|
|
||||||
### Creating the Zip Package
|
|
||||||
|
|
||||||
After creating or updating a skill:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd skills
|
|
||||||
zip -r {skill-name}.zip {skill-name}/
|
|
||||||
```
|
|
||||||
|
|
||||||
### End-User Installation
|
|
||||||
|
|
||||||
Document these two installation methods for users:
|
|
||||||
|
|
||||||
**Claude Code:**
|
|
||||||
```bash
|
|
||||||
cp -r skills/{skill-name} ~/.claude/skills/
|
|
||||||
```
|
|
||||||
|
|
||||||
**claude.ai:**
|
|
||||||
Add the skill to project knowledge or paste SKILL.md contents into the conversation.
|
|
||||||
|
|
||||||
If the skill requires network access, instruct users to add required domains at `claude.ai/settings/capabilities`.
|
|
||||||
+2
-2
@@ -1,11 +1,11 @@
|
|||||||
# syntax=docker/dockerfile:1.7
|
# syntax=docker/dockerfile:1.7
|
||||||
|
|
||||||
FROM node:24-bookworm-slim AS pnpm-base
|
FROM node:26-bookworm-slim AS pnpm-base
|
||||||
|
|
||||||
ENV PNPM_HOME=/pnpm
|
ENV PNPM_HOME=/pnpm
|
||||||
ENV PATH="${PNPM_HOME}:${PATH}"
|
ENV PATH="${PNPM_HOME}:${PATH}"
|
||||||
|
|
||||||
RUN corepack enable
|
RUN npm install --global pnpm@10.4.1
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
|
|||||||
@@ -94,9 +94,8 @@ LOLYMPUS는 이 반복 작업을 줄이는 데 초점을 맞췄습니다. 운영
|
|||||||
- TypeScript
|
- TypeScript
|
||||||
- TanStack Query
|
- TanStack Query
|
||||||
- NestJS
|
- NestJS
|
||||||
- MongoDB
|
- MongoDB 8.3
|
||||||
- Redis
|
- Redis 8.10 (일반 캐시/스트림과 경매 실시간 상태 공유)
|
||||||
- Redis 8.4 (경매 실시간 상태 전용)
|
|
||||||
- NATS
|
- NATS
|
||||||
- Riot API
|
- Riot API
|
||||||
- pnpm workspace
|
- pnpm workspace
|
||||||
@@ -118,9 +117,9 @@ scripts/ deployment and maintenance scripts
|
|||||||
|
|
||||||
- Node.js 24 이상
|
- Node.js 24 이상
|
||||||
- pnpm 10.4.1 (`packageManager` 기준, `corepack enable`로 활성화 권장)
|
- pnpm 10.4.1 (`packageManager` 기준, `corepack enable`로 활성화 권장)
|
||||||
- MongoDB 7.0, 일반 캐시/스트림용 Redis, 경매 실시간 상태 전용 Redis 8.4, NATS 실행 환경
|
- MongoDB 8.3, Redis 8.10, NATS 실행 환경
|
||||||
|
|
||||||
경매 Redis는 라이브 경매 상태의 source of truth로 사용되므로 일반 캐시/스트림 Redis와 물리적으로 분리해야 합니다. API는 `REDIS_URL`/`REDIS_ENDPOINT`와 별도로 `AUCTION_REDIS_URL`/`AUCTION_REDIS_ENDPOINT`를 읽고, 두 값이 같은 호스트/포트를 가리키면 부팅을 거부합니다.
|
일반 캐시/스트림, 경매 실시간 상태, WebSocket Pub/Sub는 `GARNET_ENDPOINT`로 지정한 하나의 Redis 인스턴스를 공유합니다. 값은 `host:port`, `redis://...`, `rediss://...` 형식을 지원합니다. 인증이 필요하면 기존 `GARNET_USERID`(또는 `GARNET_USERNAME`)와 `GARNET_PASSWORD`를 설정합니다. `REDIS_*`, `AUCTION_REDIS_*`, `GARNET_URL` 연결 설정은 사용하지 않습니다. 경매 점검 스크립트도 같은 설정을 사용합니다.
|
||||||
|
|
||||||
## 실행 방법
|
## 실행 방법
|
||||||
|
|
||||||
@@ -132,6 +131,21 @@ pnpm start:web:dev
|
|||||||
|
|
||||||
웹 앱은 기본적으로 `apps/web/.env.development` 값을 사용합니다. API 환경값은 `apps/project.env`와 실행 환경의 시크릿 설정을 함께 확인합니다.
|
웹 앱은 기본적으로 `apps/web/.env.development` 값을 사용합니다. API 환경값은 `apps/project.env`와 실행 환경의 시크릿 설정을 함께 확인합니다.
|
||||||
|
|
||||||
|
### Redis 변경 검증
|
||||||
|
|
||||||
|
Redis 8.10.x의 `XREADGROUP CLAIM`, `XACKDEL ACKED`, `DELEX`, `SET IFEQ`, `INCREX`, `HSETEX`를 사용합니다. 스트림의 대기 읽기는 별도 연결에서 실행하며, 처리되지 않은 작업은 길이 제한을 초과해도 보존합니다.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm --filter api test -- --runInBand
|
||||||
|
pnpm --filter api typecheck
|
||||||
|
pnpm --filter api test:redis
|
||||||
|
pnpm --filter api build
|
||||||
|
```
|
||||||
|
|
||||||
|
`test:redis`는 PATH의 `redis-server` 또는 `REDIS_TEST_SERVER`에 지정한 실행 파일로 Redis 8.10.x를 직접 실행합니다. 임의의 로컬 포트와 일회용 암호를 사용하고, 저장을 비활성화하며, 종료 후 프로세스와 임시 디렉터리를 정리합니다. 애플리케이션 Redis 연결 설정은 사용하지 않습니다. Windows에서는 PowerShell에서 `$env:REDIS_TEST_SERVER = 'C:\tools\redis\redis-server.exe'`처럼 지정할 수 있습니다.
|
||||||
|
|
||||||
|
커뮤니티 통계 캐시는 `riot:communitystats:v2:{communityId}:scope` Hash로 전환됩니다. 항목별 TTL은 일반 5분, 완성된 상세 24시간, 미완성 상세 60초를 유지합니다. 이전 String 캐시는 기존 TTL로 만료되며 새 캐시는 첫 조회에 생성됩니다. 구버전과 신버전은 무효화 대상이 다르므로 API 인스턴스를 같은 버전으로 함께 전환해야 합니다. 구현 범위와 검증 기록은 [Redis 변경 계획](docs/plans/redis-8.10-optimization.md)을 참고하세요.
|
||||||
|
|
||||||
### API New Relic APM
|
### API New Relic APM
|
||||||
|
|
||||||
API 서버는 `newrelic` Node.js agent를 앱 코드보다 먼저 preload합니다. Docker 런타임과 `pnpm start:api:*` 스크립트 모두 `NEW_RELIC_HOME`을 API 패키지로 지정해 `apps/api/newrelic.cjs` 설정을 읽습니다.
|
API 서버는 `newrelic` Node.js agent를 앱 코드보다 먼저 preload합니다. Docker 런타임과 `pnpm start:api:*` 스크립트 모두 `NEW_RELIC_HOME`을 API 패키지로 지정해 `apps/api/newrelic.cjs` 설정을 읽습니다.
|
||||||
@@ -164,6 +178,8 @@ API 성능 계측은 기본 비활성화이며 필요할 때 `API_PERF_OBSERVABI
|
|||||||
| `pnpm start:web:dev` | 웹 앱 개발 서버 실행 |
|
| `pnpm start:web:dev` | 웹 앱 개발 서버 실행 |
|
||||||
| `pnpm start:api:dev` | API 서버 dev 환경 실행 |
|
| `pnpm start:api:dev` | API 서버 dev 환경 실행 |
|
||||||
| `pnpm --filter api test` | API 테스트 실행 |
|
| `pnpm --filter api test` | API 테스트 실행 |
|
||||||
|
| `pnpm --filter api typecheck` | 테스트를 포함한 API 타입 검사 |
|
||||||
|
| `pnpm --filter api test:redis` | 격리된 Redis 8.10 통합 테스트 실행 |
|
||||||
| `pnpm --filter api perf:routes` | API 성능 리포트 대상 route 출력 |
|
| `pnpm --filter api perf:routes` | API 성능 리포트 대상 route 출력 |
|
||||||
| `pnpm --filter api perf:report` | API 성능 리포트 생성 |
|
| `pnpm --filter api perf:report` | API 성능 리포트 생성 |
|
||||||
| `pnpm --filter web build:staging` | 웹 staging 빌드 검증 |
|
| `pnpm --filter web build:staging` | 웹 staging 빌드 검증 |
|
||||||
|
|||||||
@@ -1,120 +0,0 @@
|
|||||||
# Agent Personas
|
|
||||||
|
|
||||||
Specialist personas that play a single role with a single perspective. Each persona is a Markdown file consumed as a system prompt by your harness (Claude Code, Cursor, Copilot, etc.).
|
|
||||||
|
|
||||||
| Persona | Role | Best for |
|
|
||||||
|---------|------|----------|
|
|
||||||
| [code-reviewer](code-reviewer.md) | Senior Staff Engineer | Five-axis review before merge |
|
|
||||||
| [security-auditor](security-auditor.md) | Security Engineer | Vulnerability detection, OWASP-style audit |
|
|
||||||
| [test-engineer](test-engineer.md) | QA Engineer | Test strategy, coverage analysis, Prove-It pattern |
|
|
||||||
|
|
||||||
## How personas relate to skills and commands
|
|
||||||
|
|
||||||
Three layers, each with a distinct job:
|
|
||||||
|
|
||||||
| Layer | What it is | Example | Composition role |
|
|
||||||
|-------|-----------|---------|------------------|
|
|
||||||
| **Skill** | A workflow with steps and exit criteria | `code-review-and-quality` | The *how* — invoked from inside a persona or command |
|
|
||||||
| **Persona** | A role with a perspective and an output format | `code-reviewer` | The *who* — adopts a viewpoint, produces a report |
|
|
||||||
| **Command** | A user-facing entry point | `/review`, `/ship` | The *when* — composes personas and skills |
|
|
||||||
|
|
||||||
The user (or a slash command) is the orchestrator. **Personas do not call other personas.** Skills are mandatory hops inside a persona's workflow.
|
|
||||||
|
|
||||||
## When to use each
|
|
||||||
|
|
||||||
### Direct persona invocation
|
|
||||||
Pick this when you want one perspective on the current change and the user is in the loop.
|
|
||||||
|
|
||||||
- "Review this PR" → invoke `code-reviewer` directly
|
|
||||||
- "Are there security issues in `auth.ts`?" → invoke `security-auditor` directly
|
|
||||||
- "What tests are missing for the checkout flow?" → invoke `test-engineer` directly
|
|
||||||
|
|
||||||
### Slash command (single persona behind it)
|
|
||||||
Pick this when there's a repeatable workflow you'd otherwise re-explain every time.
|
|
||||||
|
|
||||||
- `/review` → wraps `code-reviewer` with the project's review skill
|
|
||||||
- `/test` → wraps `test-engineer` with TDD skill
|
|
||||||
|
|
||||||
### Slash command (orchestrator — fan-out)
|
|
||||||
Pick this only when **independent** investigations can run in parallel and produce reports that a single agent then merges.
|
|
||||||
|
|
||||||
- `/ship` → fans out to `code-reviewer` + `security-auditor` + `test-engineer` in parallel, then synthesizes their reports into a go/no-go decision
|
|
||||||
|
|
||||||
This is the only orchestration pattern this repo endorses. See [references/orchestration-patterns.md](../references/orchestration-patterns.md) for the full pattern catalog and anti-patterns.
|
|
||||||
|
|
||||||
## Decision matrix
|
|
||||||
|
|
||||||
```
|
|
||||||
Is the work a single perspective on a single artifact?
|
|
||||||
├── Yes → Direct persona invocation
|
|
||||||
└── No → Are the sub-tasks independent (no shared mutable state, no ordering)?
|
|
||||||
├── Yes → Slash command with parallel fan-out (e.g. /ship)
|
|
||||||
└── No → Sequential slash commands run by the user (/spec → /plan → /build → /test → /review)
|
|
||||||
```
|
|
||||||
|
|
||||||
## Worked example: valid orchestration
|
|
||||||
|
|
||||||
`/ship` is the canonical fan-out orchestrator in this repo:
|
|
||||||
|
|
||||||
```
|
|
||||||
/ship
|
|
||||||
├── (parallel) code-reviewer → review report
|
|
||||||
├── (parallel) security-auditor → audit report
|
|
||||||
└── (parallel) test-engineer → coverage report
|
|
||||||
↓
|
|
||||||
merge phase (main agent)
|
|
||||||
↓
|
|
||||||
go/no-go decision + rollback plan
|
|
||||||
```
|
|
||||||
|
|
||||||
Why this works:
|
|
||||||
- Each sub-agent operates on the same diff but produces a **different perspective**
|
|
||||||
- They have no dependencies on each other → genuine parallelism, real wall-clock savings
|
|
||||||
- Each runs in a fresh context window → main session stays uncluttered
|
|
||||||
- The merge step is small and benefits from full context, so it stays in the main agent
|
|
||||||
|
|
||||||
## Worked example: invalid orchestration (do not build this)
|
|
||||||
|
|
||||||
A `meta-orchestrator` persona whose job is "decide which other persona to call":
|
|
||||||
|
|
||||||
```
|
|
||||||
/work-on-pr → meta-orchestrator
|
|
||||||
↓ (decides "this needs a review")
|
|
||||||
code-reviewer
|
|
||||||
↓ (returns)
|
|
||||||
meta-orchestrator (paraphrases result)
|
|
||||||
↓
|
|
||||||
user
|
|
||||||
```
|
|
||||||
|
|
||||||
Why this fails:
|
|
||||||
- Pure routing layer with no domain value
|
|
||||||
- Adds two paraphrasing hops → information loss + 2× token cost
|
|
||||||
- The user already knows they want a review; let them call `/review` directly
|
|
||||||
- Replicates work that slash commands and `AGENTS.md` intent-mapping already do
|
|
||||||
|
|
||||||
## Rules for personas
|
|
||||||
|
|
||||||
1. A persona is a single role with a single output format. If you find yourself adding a second role, create a second persona.
|
|
||||||
2. **Personas do not invoke other personas.** Composition is the job of slash commands or the user. On Claude Code this is also a hard platform constraint — *"subagents cannot spawn other subagents"* — so the rule is enforced for you.
|
|
||||||
3. A persona may invoke skills (the *how*).
|
|
||||||
4. Every persona file ends with a "Composition" block stating where it fits.
|
|
||||||
|
|
||||||
## Claude Code interop
|
|
||||||
|
|
||||||
The personas in this repo are designed to work as Claude Code subagents and as Agent Teams teammates without modification:
|
|
||||||
|
|
||||||
- **As subagents:** auto-discovered when this plugin is enabled (no path config needed). Use the Agent tool with `subagent_type: code-reviewer` (or `security-auditor`, `test-engineer`). `/ship` is the canonical example.
|
|
||||||
- **As Agent Teams teammates** (experimental, requires `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1`): reference the same persona name when spawning a teammate. The persona's body is **appended to** the teammate's system prompt as additional instructions (not a replacement), so your persona text sits on top of the team-coordination instructions the lead installs (SendMessage, task-list tools, etc.).
|
|
||||||
|
|
||||||
Subagents only report results back to the main agent. Agent Teams let teammates message each other directly. Use subagents when reports are enough; use Agent Teams when sub-agents need to challenge each other's findings (e.g. competing-hypothesis debugging). See [references/orchestration-patterns.md](../references/orchestration-patterns.md) for the full mapping.
|
|
||||||
|
|
||||||
Plugin agents do not support `hooks`, `mcpServers`, or `permissionMode` frontmatter — those fields are silently ignored. Avoid relying on them when authoring new personas here.
|
|
||||||
|
|
||||||
## Adding a new persona
|
|
||||||
|
|
||||||
1. Create `agents/<role>.md` with the same frontmatter format used by existing personas.
|
|
||||||
2. Define the role, scope, output format, and rules.
|
|
||||||
3. Add a **Composition** block at the bottom (Invoke directly when / Invoke via / Do not invoke from another persona).
|
|
||||||
4. Add the persona to the table at the top of this file.
|
|
||||||
5. If the persona enables a new orchestration pattern, document it in `references/orchestration-patterns.md` rather than inventing the pattern in the persona file itself.
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
---
|
|
||||||
name: code-reviewer
|
|
||||||
description: Senior code reviewer that evaluates changes across five dimensions — correctness, readability, architecture, security, and performance. Use for thorough code review before merge.
|
|
||||||
---
|
|
||||||
|
|
||||||
# Senior Code Reviewer
|
|
||||||
|
|
||||||
You are an experienced Staff Engineer conducting a thorough code review. Your role is to evaluate the proposed changes and provide actionable, categorized feedback.
|
|
||||||
|
|
||||||
## Review Framework
|
|
||||||
|
|
||||||
Evaluate every change across these five dimensions:
|
|
||||||
|
|
||||||
### 1. Correctness
|
|
||||||
- Does the code do what the spec/task says it should?
|
|
||||||
- Are edge cases handled (null, empty, boundary values, error paths)?
|
|
||||||
- Do the tests actually verify the behavior? Are they testing the right things?
|
|
||||||
- Are there race conditions, off-by-one errors, or state inconsistencies?
|
|
||||||
|
|
||||||
### 2. Readability
|
|
||||||
- Can another engineer understand this without explanation?
|
|
||||||
- Are names descriptive and consistent with project conventions?
|
|
||||||
- Is the control flow straightforward (no deeply nested logic)?
|
|
||||||
- Is the code well-organized (related code grouped, clear boundaries)?
|
|
||||||
|
|
||||||
### 3. Architecture
|
|
||||||
- Does the change follow existing patterns or introduce a new one?
|
|
||||||
- If a new pattern, is it justified and documented?
|
|
||||||
- Are module boundaries maintained? Any circular dependencies?
|
|
||||||
- Is the abstraction level appropriate (not over-engineered, not too coupled)?
|
|
||||||
- Are dependencies flowing in the right direction?
|
|
||||||
|
|
||||||
### 4. Security
|
|
||||||
- Is user input validated and sanitized at system boundaries?
|
|
||||||
- Are secrets kept out of code, logs, and version control?
|
|
||||||
- Is authentication/authorization checked where needed?
|
|
||||||
- Are queries parameterized? Is output encoded?
|
|
||||||
- Any new dependencies with known vulnerabilities?
|
|
||||||
|
|
||||||
### 5. Performance
|
|
||||||
- Any N+1 query patterns?
|
|
||||||
- Any unbounded loops or unconstrained data fetching?
|
|
||||||
- Any synchronous operations that should be async?
|
|
||||||
- Any unnecessary re-renders (in UI components)?
|
|
||||||
- Any missing pagination on list endpoints?
|
|
||||||
|
|
||||||
## Output Format
|
|
||||||
|
|
||||||
Categorize every finding:
|
|
||||||
|
|
||||||
**Critical** — Must fix before merge (security vulnerability, data loss risk, broken functionality)
|
|
||||||
|
|
||||||
**Important** — Should fix before merge (missing test, wrong abstraction, poor error handling)
|
|
||||||
|
|
||||||
**Suggestion** — Consider for improvement (naming, code style, optional optimization)
|
|
||||||
|
|
||||||
## Review Output Template
|
|
||||||
|
|
||||||
```markdown
|
|
||||||
## Review Summary
|
|
||||||
|
|
||||||
**Verdict:** APPROVE | REQUEST CHANGES
|
|
||||||
|
|
||||||
**Overview:** [1-2 sentences summarizing the change and overall assessment]
|
|
||||||
|
|
||||||
### Critical Issues
|
|
||||||
- [File:line] [Description and recommended fix]
|
|
||||||
|
|
||||||
### Important Issues
|
|
||||||
- [File:line] [Description and recommended fix]
|
|
||||||
|
|
||||||
### Suggestions
|
|
||||||
- [File:line] [Description]
|
|
||||||
|
|
||||||
### What's Done Well
|
|
||||||
- [Positive observation — always include at least one]
|
|
||||||
|
|
||||||
### Verification Story
|
|
||||||
- Tests reviewed: [yes/no, observations]
|
|
||||||
- Build verified: [yes/no]
|
|
||||||
- Security checked: [yes/no, observations]
|
|
||||||
```
|
|
||||||
|
|
||||||
## Rules
|
|
||||||
|
|
||||||
1. Review the tests first — they reveal intent and coverage
|
|
||||||
2. Read the spec or task description before reviewing code
|
|
||||||
3. Every Critical and Important finding should include a specific fix recommendation
|
|
||||||
4. Don't approve code with Critical issues
|
|
||||||
5. Acknowledge what's done well — specific praise motivates good practices
|
|
||||||
6. If you're uncertain about something, say so and suggest investigation rather than guessing
|
|
||||||
|
|
||||||
## Composition
|
|
||||||
|
|
||||||
- **Invoke directly when:** the user asks for a review of a specific change, file, or PR.
|
|
||||||
- **Invoke via:** `/review` (single-perspective review) or `/ship` (parallel fan-out alongside `security-auditor` and `test-engineer`).
|
|
||||||
- **Do not invoke from another persona.** If you find yourself wanting to delegate to `security-auditor` or `test-engineer`, surface that as a recommendation in your report instead — orchestration belongs to slash commands, not personas. See [agents/README.md](README.md).
|
|
||||||
@@ -1,101 +0,0 @@
|
|||||||
---
|
|
||||||
name: security-auditor
|
|
||||||
description: Security engineer focused on vulnerability detection, threat modeling, and secure coding practices. Use for security-focused code review, threat analysis, or hardening recommendations.
|
|
||||||
---
|
|
||||||
|
|
||||||
# Security Auditor
|
|
||||||
|
|
||||||
You are an experienced Security Engineer conducting a security review. Your role is to identify vulnerabilities, assess risk, and recommend mitigations. You focus on practical, exploitable issues rather than theoretical risks.
|
|
||||||
|
|
||||||
## Review Scope
|
|
||||||
|
|
||||||
### 1. Input Handling
|
|
||||||
- Is all user input validated at system boundaries?
|
|
||||||
- Are there injection vectors (SQL, NoSQL, OS command, LDAP)?
|
|
||||||
- Is HTML output encoded to prevent XSS?
|
|
||||||
- Are file uploads restricted by type, size, and content?
|
|
||||||
- Are URL redirects validated against an allowlist?
|
|
||||||
|
|
||||||
### 2. Authentication & Authorization
|
|
||||||
- Are passwords hashed with a strong algorithm (bcrypt, scrypt, argon2)?
|
|
||||||
- Are sessions managed securely (httpOnly, secure, sameSite cookies)?
|
|
||||||
- Is authorization checked on every protected endpoint?
|
|
||||||
- Can users access resources belonging to other users (IDOR)?
|
|
||||||
- Are password reset tokens time-limited and single-use?
|
|
||||||
- Is rate limiting applied to authentication endpoints?
|
|
||||||
|
|
||||||
### 3. Data Protection
|
|
||||||
- Are secrets in environment variables (not code)?
|
|
||||||
- Are sensitive fields excluded from API responses and logs?
|
|
||||||
- Is data encrypted in transit (HTTPS) and at rest (if required)?
|
|
||||||
- Is PII handled according to applicable regulations?
|
|
||||||
- Are database backups encrypted?
|
|
||||||
|
|
||||||
### 4. Infrastructure
|
|
||||||
- Are security headers configured (CSP, HSTS, X-Frame-Options)?
|
|
||||||
- Is CORS restricted to specific origins?
|
|
||||||
- Are dependencies audited for known vulnerabilities?
|
|
||||||
- Are error messages generic (no stack traces or internal details to users)?
|
|
||||||
- Is the principle of least privilege applied to service accounts?
|
|
||||||
|
|
||||||
### 5. Third-Party Integrations
|
|
||||||
- Are API keys and tokens stored securely?
|
|
||||||
- Are webhook payloads verified (signature validation)?
|
|
||||||
- Are third-party scripts loaded from trusted CDNs with integrity hashes?
|
|
||||||
- Are OAuth flows using PKCE and state parameters?
|
|
||||||
|
|
||||||
## Severity Classification
|
|
||||||
|
|
||||||
| Severity | Criteria | Action |
|
|
||||||
|----------|----------|--------|
|
|
||||||
| **Critical** | Exploitable remotely, leads to data breach or full compromise | Fix immediately, block release |
|
|
||||||
| **High** | Exploitable with some conditions, significant data exposure | Fix before release |
|
|
||||||
| **Medium** | Limited impact or requires authenticated access to exploit | Fix in current sprint |
|
|
||||||
| **Low** | Theoretical risk or defense-in-depth improvement | Schedule for next sprint |
|
|
||||||
| **Info** | Best practice recommendation, no current risk | Consider adopting |
|
|
||||||
|
|
||||||
## Output Format
|
|
||||||
|
|
||||||
```markdown
|
|
||||||
## Security Audit Report
|
|
||||||
|
|
||||||
### Summary
|
|
||||||
- Critical: [count]
|
|
||||||
- High: [count]
|
|
||||||
- Medium: [count]
|
|
||||||
- Low: [count]
|
|
||||||
|
|
||||||
### Findings
|
|
||||||
|
|
||||||
#### [CRITICAL] [Finding title]
|
|
||||||
- **Location:** [file:line]
|
|
||||||
- **Description:** [What the vulnerability is]
|
|
||||||
- **Impact:** [What an attacker could do]
|
|
||||||
- **Proof of concept:** [How to exploit it]
|
|
||||||
- **Recommendation:** [Specific fix with code example]
|
|
||||||
|
|
||||||
#### [HIGH] [Finding title]
|
|
||||||
...
|
|
||||||
|
|
||||||
### Positive Observations
|
|
||||||
- [Security practices done well]
|
|
||||||
|
|
||||||
### Recommendations
|
|
||||||
- [Proactive improvements to consider]
|
|
||||||
```
|
|
||||||
|
|
||||||
## Rules
|
|
||||||
|
|
||||||
1. Focus on exploitable vulnerabilities, not theoretical risks
|
|
||||||
2. Every finding must include a specific, actionable recommendation
|
|
||||||
3. Provide proof of concept or exploitation scenario for Critical/High findings
|
|
||||||
4. Acknowledge good security practices — positive reinforcement matters
|
|
||||||
5. Check the OWASP Top 10 as a minimum baseline
|
|
||||||
6. Review dependencies for known CVEs
|
|
||||||
7. Never suggest disabling security controls as a "fix"
|
|
||||||
|
|
||||||
## Composition
|
|
||||||
|
|
||||||
- **Invoke directly when:** the user wants a security-focused pass on a specific change, file, or system component.
|
|
||||||
- **Invoke via:** `/ship` (parallel fan-out alongside `code-reviewer` and `test-engineer`), or any future `/audit` command.
|
|
||||||
- **Do not invoke from another persona.** If `code-reviewer` flags something that warrants a deeper security pass, the user or a slash command initiates that pass — not the reviewer. See [agents/README.md](README.md).
|
|
||||||
@@ -1,95 +0,0 @@
|
|||||||
---
|
|
||||||
name: test-engineer
|
|
||||||
description: QA engineer specialized in test strategy, test writing, and coverage analysis. Use for designing test suites, writing tests for existing code, or evaluating test quality.
|
|
||||||
---
|
|
||||||
|
|
||||||
# Test Engineer
|
|
||||||
|
|
||||||
You are an experienced QA Engineer focused on test strategy and quality assurance. Your role is to design test suites, write tests, analyze coverage gaps, and ensure that code changes are properly verified.
|
|
||||||
|
|
||||||
## Approach
|
|
||||||
|
|
||||||
### 1. Analyze Before Writing
|
|
||||||
|
|
||||||
Before writing any test:
|
|
||||||
- Read the code being tested to understand its behavior
|
|
||||||
- Identify the public API / interface (what to test)
|
|
||||||
- Identify edge cases and error paths
|
|
||||||
- Check existing tests for patterns and conventions
|
|
||||||
|
|
||||||
### 2. Test at the Right Level
|
|
||||||
|
|
||||||
```
|
|
||||||
Pure logic, no I/O → Unit test
|
|
||||||
Crosses a boundary → Integration test
|
|
||||||
Critical user flow → E2E test
|
|
||||||
```
|
|
||||||
|
|
||||||
Test at the lowest level that captures the behavior. Don't write E2E tests for things unit tests can cover.
|
|
||||||
|
|
||||||
### 3. Follow the Prove-It Pattern for Bugs
|
|
||||||
|
|
||||||
When asked to write a test for a bug:
|
|
||||||
1. Write a test that demonstrates the bug (must FAIL with current code)
|
|
||||||
2. Confirm the test fails
|
|
||||||
3. Report the test is ready for the fix implementation
|
|
||||||
|
|
||||||
### 4. Write Descriptive Tests
|
|
||||||
|
|
||||||
```
|
|
||||||
describe('[Module/Function name]', () => {
|
|
||||||
it('[expected behavior in plain English]', () => {
|
|
||||||
// Arrange → Act → Assert
|
|
||||||
});
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
### 5. Cover These Scenarios
|
|
||||||
|
|
||||||
For every function or component:
|
|
||||||
|
|
||||||
| Scenario | Example |
|
|
||||||
|----------|---------|
|
|
||||||
| Happy path | Valid input produces expected output |
|
|
||||||
| Empty input | Empty string, empty array, null, undefined |
|
|
||||||
| Boundary values | Min, max, zero, negative |
|
|
||||||
| Error paths | Invalid input, network failure, timeout |
|
|
||||||
| Concurrency | Rapid repeated calls, out-of-order responses |
|
|
||||||
|
|
||||||
## Output Format
|
|
||||||
|
|
||||||
When analyzing test coverage:
|
|
||||||
|
|
||||||
```markdown
|
|
||||||
## Test Coverage Analysis
|
|
||||||
|
|
||||||
### Current Coverage
|
|
||||||
- [X] tests covering [Y] functions/components
|
|
||||||
- Coverage gaps identified: [list]
|
|
||||||
|
|
||||||
### Recommended Tests
|
|
||||||
1. **[Test name]** — [What it verifies, why it matters]
|
|
||||||
2. **[Test name]** — [What it verifies, why it matters]
|
|
||||||
|
|
||||||
### Priority
|
|
||||||
- Critical: [Tests that catch potential data loss or security issues]
|
|
||||||
- High: [Tests for core business logic]
|
|
||||||
- Medium: [Tests for edge cases and error handling]
|
|
||||||
- Low: [Tests for utility functions and formatting]
|
|
||||||
```
|
|
||||||
|
|
||||||
## Rules
|
|
||||||
|
|
||||||
1. Test behavior, not implementation details
|
|
||||||
2. Each test should verify one concept
|
|
||||||
3. Tests should be independent — no shared mutable state between tests
|
|
||||||
4. Avoid snapshot tests unless reviewing every change to the snapshot
|
|
||||||
5. Mock at system boundaries (database, network), not between internal functions
|
|
||||||
6. Every test name should read like a specification
|
|
||||||
7. A test that never fails is as useless as a test that always fails
|
|
||||||
|
|
||||||
## Composition
|
|
||||||
|
|
||||||
- **Invoke directly when:** the user asks for test design, coverage analysis, or a Prove-It test for a specific bug.
|
|
||||||
- **Invoke via:** `/test` (TDD workflow) or `/ship` (parallel fan-out for coverage gap analysis alongside `code-reviewer` and `security-auditor`).
|
|
||||||
- **Do not invoke from another persona.** Recommendations to add tests belong in your report; the user or a slash command decides when to act on them. See [agents/README.md](README.md).
|
|
||||||
@@ -29,7 +29,28 @@ export default tseslint.config(
|
|||||||
'@typescript-eslint/no-explicit-any': 'off',
|
'@typescript-eslint/no-explicit-any': 'off',
|
||||||
'@typescript-eslint/no-floating-promises': 'warn',
|
'@typescript-eslint/no-floating-promises': 'warn',
|
||||||
'@typescript-eslint/no-unsafe-argument': 'warn',
|
'@typescript-eslint/no-unsafe-argument': 'warn',
|
||||||
"prettier/prettier": ["error", { endOfLine: "auto" }],
|
'prettier/prettier': ['error', { endOfLine: 'auto' }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
files: ['**/*.spec.ts', 'test/**/*.ts'],
|
||||||
|
rules: {
|
||||||
|
'@typescript-eslint/no-unsafe-assignment': 'off',
|
||||||
|
'@typescript-eslint/no-unsafe-call': 'off',
|
||||||
|
'@typescript-eslint/no-unsafe-member-access': 'off',
|
||||||
|
'@typescript-eslint/no-unsafe-return': 'off',
|
||||||
|
'@typescript-eslint/no-this-alias': 'off',
|
||||||
|
'@typescript-eslint/require-await': 'off',
|
||||||
|
'@typescript-eslint/unbound-method': 'off',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
files: ['src/modules/global/database/migrations/**/*.ts'],
|
||||||
|
rules: {
|
||||||
|
'@typescript-eslint/no-unsafe-assignment': 'off',
|
||||||
|
'@typescript-eslint/no-unsafe-call': 'off',
|
||||||
|
'@typescript-eslint/no-unsafe-member-access': 'off',
|
||||||
|
'@typescript-eslint/no-unsafe-return': 'off',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
+11
-9
@@ -22,6 +22,8 @@
|
|||||||
"start:debug": "nest start --debug --watch",
|
"start:debug": "nest start --debug --watch",
|
||||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||||
"test": "jest",
|
"test": "jest",
|
||||||
|
"typecheck": "tsc --noEmit --incremental false",
|
||||||
|
"test:redis": "node test/run-redis-tests.mjs",
|
||||||
"test:watch": "jest --watch",
|
"test:watch": "jest --watch",
|
||||||
"test:cov": "jest --coverage",
|
"test:cov": "jest --coverage",
|
||||||
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||||
@@ -29,20 +31,20 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@lolympus/contracts": "workspace:*",
|
"@lolympus/contracts": "workspace:*",
|
||||||
"@nestjs/common": "^11.0.1",
|
"@nestjs/common": "^11.1.28",
|
||||||
"@nestjs/config": "^4.0.4",
|
"@nestjs/config": "^4.0.4",
|
||||||
"@nestjs/core": "^11.0.1",
|
"@nestjs/core": "^11.1.28",
|
||||||
"@nestjs/platform-express": "^11.0.1",
|
"@nestjs/platform-express": "^11.1.28",
|
||||||
"@nestjs/platform-socket.io": "^11.1.19",
|
"@nestjs/platform-socket.io": "^11.1.28",
|
||||||
"@nestjs/swagger": "^11.2.7",
|
"@nestjs/swagger": "^11.4.6",
|
||||||
"@nestjs/websockets": "^11.1.19",
|
"@nestjs/websockets": "^11.1.28",
|
||||||
"@socket.io/redis-adapter": "^8.3.0",
|
"@socket.io/redis-adapter": "^8.3.0",
|
||||||
"class-transformer": "^0.5.1",
|
"class-transformer": "^0.5.1",
|
||||||
"class-validator": "^0.15.1",
|
"class-validator": "^0.15.1",
|
||||||
"jose": "^6.2.2",
|
"jose": "^6.2.2",
|
||||||
"mongoose": "^9.4.1",
|
"mongoose": "9.4.1",
|
||||||
"nats": "^2.29.3",
|
"nats": "^2.29.3",
|
||||||
"newrelic": "^14.1.2",
|
"newrelic": "^14.3.3",
|
||||||
"redis": "^5.12.1",
|
"redis": "^5.12.1",
|
||||||
"reflect-metadata": "^0.2.2",
|
"reflect-metadata": "^0.2.2",
|
||||||
"rxjs": "^7.8.1",
|
"rxjs": "^7.8.1",
|
||||||
@@ -57,7 +59,7 @@
|
|||||||
"@nestjs/testing": "^11.0.1",
|
"@nestjs/testing": "^11.0.1",
|
||||||
"@types/express": "^5.0.0",
|
"@types/express": "^5.0.0",
|
||||||
"@types/jest": "^30.0.0",
|
"@types/jest": "^30.0.0",
|
||||||
"@types/node": "^24.0.0",
|
"@types/node": "^26.1.1",
|
||||||
"@types/supertest": "^7.0.0",
|
"@types/supertest": "^7.0.0",
|
||||||
"eslint": "^9.18.0",
|
"eslint": "^9.18.0",
|
||||||
"eslint-config-prettier": "^10.0.1",
|
"eslint-config-prettier": "^10.0.1",
|
||||||
|
|||||||
@@ -79,7 +79,9 @@ describe('AuctionDeadlineScheduler', () => {
|
|||||||
.spyOn(scheduler, 'processDueBidRoundDeadlines')
|
.spyOn(scheduler, 'processDueBidRoundDeadlines')
|
||||||
.mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 });
|
.mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 });
|
||||||
|
|
||||||
await (scheduler as unknown as { safeTick: () => Promise<void> }).safeTick();
|
await (
|
||||||
|
scheduler as unknown as { safeTick: () => Promise<void> }
|
||||||
|
).safeTick();
|
||||||
|
|
||||||
const leaderLockToken = redis.acquireTokenLock.mock.calls[0]?.[1];
|
const leaderLockToken = redis.acquireTokenLock.mock.calls[0]?.[1];
|
||||||
expect(redis.acquireTokenLock).toHaveBeenCalledWith(
|
expect(redis.acquireTokenLock).toHaveBeenCalledWith(
|
||||||
@@ -100,7 +102,9 @@ describe('AuctionDeadlineScheduler', () => {
|
|||||||
.spyOn(scheduler, 'processDueBidRoundDeadlines')
|
.spyOn(scheduler, 'processDueBidRoundDeadlines')
|
||||||
.mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 });
|
.mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 });
|
||||||
|
|
||||||
await (scheduler as unknown as { safeTick: () => Promise<void> }).safeTick();
|
await (
|
||||||
|
scheduler as unknown as { safeTick: () => Promise<void> }
|
||||||
|
).safeTick();
|
||||||
|
|
||||||
expect(processDueBidRoundDeadlinesSpy).not.toHaveBeenCalled();
|
expect(processDueBidRoundDeadlinesSpy).not.toHaveBeenCalled();
|
||||||
expect(redis.releaseTokenLock).not.toHaveBeenCalled();
|
expect(redis.releaseTokenLock).not.toHaveBeenCalled();
|
||||||
@@ -129,10 +133,12 @@ describe('AuctionDeadlineScheduler', () => {
|
|||||||
it('prepares and completes due auction deadlines', async () => {
|
it('prepares and completes due auction deadlines', async () => {
|
||||||
const matchId = '665f2f01f1f1f1f1f1f1f1f1';
|
const matchId = '665f2f01f1f1f1f1f1f1f1f1';
|
||||||
const completedState = { phase: 'passed', revision: 3 };
|
const completedState = { phase: 'passed', revision: 3 };
|
||||||
const { auctionService, eventBus, redisCommand, scheduler } = makeScheduler({
|
const { auctionService, eventBus, redisCommand, scheduler } = makeScheduler(
|
||||||
dueReply: [matchId],
|
{
|
||||||
completedState,
|
dueReply: [matchId],
|
||||||
});
|
completedState,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
await expect(scheduler.processDueBidRoundDeadlines(10)).resolves.toEqual({
|
await expect(scheduler.processDueBidRoundDeadlines(10)).resolves.toEqual({
|
||||||
completed: 1,
|
completed: 1,
|
||||||
@@ -149,7 +155,10 @@ describe('AuctionDeadlineScheduler', () => {
|
|||||||
expect(auctionService.completePreparedExpiry).toHaveBeenCalledTimes(1);
|
expect(auctionService.completePreparedExpiry).toHaveBeenCalledTimes(1);
|
||||||
// 만료 확정 결과는 즉시 1차 broadcast돼야 한다(클라가 입찰 라운드에 멈춰
|
// 만료 확정 결과는 즉시 1차 broadcast돼야 한다(클라가 입찰 라운드에 멈춰
|
||||||
// 후속 액션에서 CONFLICT가 반복되는 것을 막는 핵심 동작).
|
// 후속 액션에서 CONFLICT가 반복되는 것을 막는 핵심 동작).
|
||||||
expect(eventBus.broadcastState).toHaveBeenCalledWith(matchId, completedState);
|
expect(eventBus.broadcastState).toHaveBeenCalledWith(
|
||||||
|
matchId,
|
||||||
|
completedState,
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('skips noop expiry preparations', async () => {
|
it('skips noop expiry preparations', async () => {
|
||||||
@@ -189,10 +198,7 @@ describe('AuctionDeadlineScheduler', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('continues processing later deadline items after one item fails', async () => {
|
it('continues processing later deadline items after one item fails', async () => {
|
||||||
const matchIds = [
|
const matchIds = ['665f2f01f1f1f1f1f1f1f1f1', '665f2f02f1f1f1f1f1f1f1f1'];
|
||||||
'665f2f01f1f1f1f1f1f1f1f1',
|
|
||||||
'665f2f02f1f1f1f1f1f1f1f1',
|
|
||||||
];
|
|
||||||
const { auctionService, redisCommand, scheduler } = makeScheduler({
|
const { auctionService, redisCommand, scheduler } = makeScheduler({
|
||||||
dueReply: matchIds,
|
dueReply: matchIds,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -101,15 +101,17 @@ export class AuctionDeadlineScheduler implements OnModuleInit, OnModuleDestroy {
|
|||||||
currentRedisTimestampMS: number,
|
currentRedisTimestampMS: number,
|
||||||
batchLimit: number,
|
batchLimit: number,
|
||||||
): Promise<string[]> {
|
): Promise<string[]> {
|
||||||
const reply = await this.auctionRedisService.raw().sendCommand([
|
const reply = await this.auctionRedisService
|
||||||
'ZRANGEBYSCORE',
|
.raw()
|
||||||
BID_ROUND_DEADLINE_QUEUE_KEY,
|
.sendCommand([
|
||||||
'-inf',
|
'ZRANGEBYSCORE',
|
||||||
String(currentRedisTimestampMS),
|
BID_ROUND_DEADLINE_QUEUE_KEY,
|
||||||
'LIMIT',
|
'-inf',
|
||||||
'0',
|
String(currentRedisTimestampMS),
|
||||||
String(batchLimit),
|
'LIMIT',
|
||||||
]);
|
'0',
|
||||||
|
String(batchLimit),
|
||||||
|
]);
|
||||||
return Array.isArray(reply) ? reply.map(String) : [];
|
return Array.isArray(reply) ? reply.map(String) : [];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -177,11 +179,11 @@ export class AuctionDeadlineScheduler implements OnModuleInit, OnModuleDestroy {
|
|||||||
return { completed, prepared, skipped };
|
return { completed, prepared, skipped };
|
||||||
}
|
}
|
||||||
|
|
||||||
private async removeBidRoundDeadlineQueueEntry(matchId: string): Promise<void> {
|
private async removeBidRoundDeadlineQueueEntry(
|
||||||
await this.auctionRedisService.raw().sendCommand([
|
matchId: string,
|
||||||
'ZREM',
|
): Promise<void> {
|
||||||
BID_ROUND_DEADLINE_QUEUE_KEY,
|
await this.auctionRedisService
|
||||||
matchId,
|
.raw()
|
||||||
]);
|
.sendCommand(['ZREM', BID_ROUND_DEADLINE_QUEUE_KEY, matchId]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -20,9 +20,8 @@ export class AuctionEventBusService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public broadcastState(matchId: string, state: AuctionStateResponse): void {
|
public broadcastState(matchId: string, state: AuctionStateResponse): void {
|
||||||
this.auctionNamespace?.to(matchId).emit(
|
this.auctionNamespace
|
||||||
'state',
|
?.to(matchId)
|
||||||
serializeRealtimeAuction(state),
|
.emit('state', serializeRealtimeAuction(state));
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -74,13 +74,11 @@ function serializeRealtimeAuctionPlayer(
|
|||||||
return player;
|
return player;
|
||||||
}
|
}
|
||||||
|
|
||||||
const {
|
const lightweightPlayer = { ...player };
|
||||||
masteries: _masteries,
|
delete lightweightPlayer.masteries;
|
||||||
puuid: _puuid,
|
delete lightweightPlayer.puuid;
|
||||||
recentStatsSummary: _recentStatsSummary,
|
delete lightweightPlayer.recentStatsSummary;
|
||||||
tierHistory: _tierHistory,
|
delete lightweightPlayer.tierHistory;
|
||||||
...lightweightPlayer
|
|
||||||
} = player;
|
|
||||||
|
|
||||||
return lightweightPlayer;
|
return lightweightPlayer;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,15 @@ import {
|
|||||||
} from './auction-rejection';
|
} from './auction-rejection';
|
||||||
|
|
||||||
describe('resolveAuctionRejectionReason', () => {
|
describe('resolveAuctionRejectionReason', () => {
|
||||||
|
it('reports roster validation failures without recommending a retry', () => {
|
||||||
|
const reason = resolveAuctionRejectionReason(
|
||||||
|
'AUCTION_ROSTER_INVALID',
|
||||||
|
'Auction roster validation failed.',
|
||||||
|
);
|
||||||
|
expect(reason).toBe('AUCTION_TRANSITION_REJECTED_BECAUSE_ROSTER_INVALID');
|
||||||
|
expect(isAuctionResyncRecommended(reason)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
it('maps the internal CONFLICT code to the descriptive transition reason', () => {
|
it('maps the internal CONFLICT code to the descriptive transition reason', () => {
|
||||||
expect(resolveAuctionRejectionReason('CONFLICT')).toBe(
|
expect(resolveAuctionRejectionReason('CONFLICT')).toBe(
|
||||||
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_LIVE_STATE_CHANGED_BEFORE_APPLY,
|
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_LIVE_STATE_CHANGED_BEFORE_APPLY,
|
||||||
@@ -22,7 +31,10 @@ describe('resolveAuctionRejectionReason', () => {
|
|||||||
|
|
||||||
it('maps known BadRequest messages without a structured code', () => {
|
it('maps known BadRequest messages without a structured code', () => {
|
||||||
expect(
|
expect(
|
||||||
resolveAuctionRejectionReason(undefined, 'Cannot advance from current phase.'),
|
resolveAuctionRejectionReason(
|
||||||
|
undefined,
|
||||||
|
'Cannot advance from current phase.',
|
||||||
|
),
|
||||||
).toBe(
|
).toBe(
|
||||||
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE,
|
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
* resync 권장 여부:
|
* resync 권장 여부:
|
||||||
* - `AUCTION_RESYNC_RECOMMENDED_REASONS`에 속한 reason은 "클라가 본 상태가 이미
|
* - `AUCTION_RESYNC_RECOMMENDED_REASONS`에 속한 reason은 "클라가 본 상태가 이미
|
||||||
* 바뀌었다(낙관적 동시성 충돌/만료/단계 전이)"는 신호다. 이 경우 클라는 최신
|
* 바뀌었다(낙관적 동시성 충돌/만료/단계 전이)"는 신호다. 이 경우 클라는 최신
|
||||||
* state로 rebaseline한 뒤 (구조 액션이라면) 1회 재시도하는 것이 안전하다.
|
* state로 rebaseline한다. 구조 액션 재시도는 원래 대상과 단계가 같을 때만 허용한다.
|
||||||
* - 반대로 정원 초과/포인트 부족처럼 "상태를 새로고침해도 결과가 같은" 거부는
|
* - 반대로 정원 초과/포인트 부족처럼 "상태를 새로고침해도 결과가 같은" 거부는
|
||||||
* resync 권장 대상이 아니다(재시도해도 또 거부됨).
|
* resync 권장 대상이 아니다(재시도해도 또 거부됨).
|
||||||
*/
|
*/
|
||||||
@@ -29,9 +29,12 @@ export const AUCTION_REJECTION_REASON = {
|
|||||||
/** 입찰 단계가 아닌데 입찰 단계 전환을 시도함(이미 sold/passed/presenting 등). */
|
/** 입찰 단계가 아닌데 입찰 단계 전환을 시도함(이미 sold/passed/presenting 등). */
|
||||||
AUCTION_TRANSITION_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE:
|
AUCTION_TRANSITION_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE:
|
||||||
'AUCTION_TRANSITION_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE',
|
'AUCTION_TRANSITION_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE',
|
||||||
/** 현재 단계에서 "다음"으로 진행할 수 없음(sold/passed/presenting이 아님 — 보통 이미 진행됨). */
|
/** 낙찰 또는 유찰이 확정되지 않아 다음 선수로 진행할 수 없음. */
|
||||||
AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE:
|
AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE:
|
||||||
'AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE',
|
'AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE',
|
||||||
|
/** 원 참가자 명단과 실제 팀 배정이 일치하지 않아 완료할 수 없음. */
|
||||||
|
AUCTION_TRANSITION_REJECTED_BECAUSE_ROSTER_INVALID:
|
||||||
|
'AUCTION_TRANSITION_REJECTED_BECAUSE_ROSTER_INVALID',
|
||||||
/** 낙찰 처리할 유효한 최고 입찰이 없음(만료 처리로 이미 정리됐을 수 있음). */
|
/** 낙찰 처리할 유효한 최고 입찰이 없음(만료 처리로 이미 정리됐을 수 있음). */
|
||||||
AUCTION_TRANSITION_REJECTED_BECAUSE_NO_WINNING_BID_TO_MARK_SOLD:
|
AUCTION_TRANSITION_REJECTED_BECAUSE_NO_WINNING_BID_TO_MARK_SOLD:
|
||||||
'AUCTION_TRANSITION_REJECTED_BECAUSE_NO_WINNING_BID_TO_MARK_SOLD',
|
'AUCTION_TRANSITION_REJECTED_BECAUSE_NO_WINNING_BID_TO_MARK_SOLD',
|
||||||
@@ -83,6 +86,8 @@ export type AuctionRejectionReason =
|
|||||||
|
|
||||||
/** 내부 짧은 코드 → 설명적 reason. */
|
/** 내부 짧은 코드 → 설명적 reason. */
|
||||||
const INTERNAL_CODE_TO_REASON: Record<string, AuctionRejectionReason> = {
|
const INTERNAL_CODE_TO_REASON: Record<string, AuctionRejectionReason> = {
|
||||||
|
AUCTION_ROSTER_INVALID:
|
||||||
|
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_ROSTER_INVALID,
|
||||||
CONFLICT:
|
CONFLICT:
|
||||||
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_LIVE_STATE_CHANGED_BEFORE_APPLY,
|
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_LIVE_STATE_CHANGED_BEFORE_APPLY,
|
||||||
STALE_BID_ROUND:
|
STALE_BID_ROUND:
|
||||||
|
|||||||
@@ -41,22 +41,24 @@ export class AuctionSideEffectService {
|
|||||||
matchSideEffectStatus: AuctionMatchSideEffectStatus;
|
matchSideEffectStatus: AuctionMatchSideEffectStatus;
|
||||||
}): Promise<boolean> {
|
}): Promise<boolean> {
|
||||||
const keys = buildAuctionRedisKeys(params.matchId);
|
const keys = buildAuctionRedisKeys(params.matchId);
|
||||||
const result = await this.auctionRedisService.raw().sendCommand([
|
const result = await this.auctionRedisService
|
||||||
'EVAL',
|
.raw()
|
||||||
[
|
.sendCommand([
|
||||||
"if redis.call('HGET', KEYS[1], 'auctionLifecycleId') ~= ARGV[1] then return 0 end",
|
'EVAL',
|
||||||
"local currentRevision = tonumber(redis.call('HGET', KEYS[1], 'matchSideEffectRevision') or '-1')",
|
[
|
||||||
'local nextRevision = tonumber(ARGV[2])',
|
"if redis.call('HGET', KEYS[1], 'auctionLifecycleId') ~= ARGV[1] then return 0 end",
|
||||||
'if currentRevision >= nextRevision then return 0 end',
|
"local currentRevision = tonumber(redis.call('HGET', KEYS[1], 'matchSideEffectRevision') or '-1')",
|
||||||
"redis.call('HSET', KEYS[1], 'matchSideEffectRevision', ARGV[2], 'matchSideEffectStatus', ARGV[3])",
|
'local nextRevision = tonumber(ARGV[2])',
|
||||||
'return 1',
|
'if currentRevision >= nextRevision then return 0 end',
|
||||||
].join('\n'),
|
"redis.call('HSET', KEYS[1], 'matchSideEffectRevision', ARGV[2], 'matchSideEffectStatus', ARGV[3])",
|
||||||
'1',
|
'return 1',
|
||||||
keys.liveStateKey,
|
].join('\n'),
|
||||||
params.auctionLifecycleId,
|
'1',
|
||||||
String(params.matchSideEffectRevision),
|
keys.liveStateKey,
|
||||||
params.matchSideEffectStatus,
|
params.auctionLifecycleId,
|
||||||
]);
|
String(params.matchSideEffectRevision),
|
||||||
|
params.matchSideEffectStatus,
|
||||||
|
]);
|
||||||
return Number(result) === 1;
|
return Number(result) === 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -78,8 +80,7 @@ export function canAcquireSideEffectLease(
|
|||||||
if (state.state === 'pending' || state.state === 'failed') return true;
|
if (state.state === 'pending' || state.state === 'failed') return true;
|
||||||
if (state.state !== 'processing') return false;
|
if (state.state !== 'processing') return false;
|
||||||
return (
|
return (
|
||||||
(state.processingLeaseExpiresAtTimestampMS ?? 0) <=
|
(state.processingLeaseExpiresAtTimestampMS ?? 0) <= currentRedisTimestampMS
|
||||||
currentRedisTimestampMS
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -59,8 +59,7 @@ export class AuctionController {
|
|||||||
initialTeamBidPointAmount: c.initialTeamBidPointAmount,
|
initialTeamBidPointAmount: c.initialTeamBidPointAmount,
|
||||||
})),
|
})),
|
||||||
initialTeamBidPointAmount: body.initialTeamBidPointAmount ?? 1000,
|
initialTeamBidPointAmount: body.initialTeamBidPointAmount ?? 1000,
|
||||||
maximumBidRoundDurationSeconds:
|
maximumBidRoundDurationSeconds: body.maximumBidRoundDurationSeconds ?? 30,
|
||||||
body.maximumBidRoundDurationSeconds ?? 30,
|
|
||||||
bidRoundExtensionSeconds: body.bidRoundExtensionSeconds ?? 5,
|
bidRoundExtensionSeconds: body.bidRoundExtensionSeconds ?? 5,
|
||||||
topTierAuctionPriorityThreshold:
|
topTierAuctionPriorityThreshold:
|
||||||
body.topTierAuctionPriorityThreshold ?? 'NONE',
|
body.topTierAuctionPriorityThreshold ?? 'NONE',
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import {
|
|||||||
} from '@nestjs/websockets';
|
} from '@nestjs/websockets';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import type { JWTPayload } from 'jose';
|
import type { JWTPayload } from 'jose';
|
||||||
import { Namespace, Socket } from 'socket.io';
|
import type { DefaultEventsMap, Namespace, Socket } from 'socket.io';
|
||||||
import { AuthService } from '../auth/auth.service';
|
import { AuthService } from '../auth/auth.service';
|
||||||
import { IdentityService } from '../auth/identity.service';
|
import { IdentityService } from '../auth/identity.service';
|
||||||
import { JwtService } from '../auth/jwt.service';
|
import { JwtService } from '../auth/jwt.service';
|
||||||
@@ -78,6 +78,20 @@ interface BidRateLimitState {
|
|||||||
windowStartedAtTimestampMS: number;
|
windowStartedAtTimestampMS: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface AuctionSocketData {
|
||||||
|
auctionBidRateLimit?: BidRateLimitState;
|
||||||
|
identity?: IdentityDocument;
|
||||||
|
matchId?: string;
|
||||||
|
user?: UserDocument;
|
||||||
|
}
|
||||||
|
|
||||||
|
type AuctionSocket = Socket<
|
||||||
|
DefaultEventsMap,
|
||||||
|
DefaultEventsMap,
|
||||||
|
DefaultEventsMap,
|
||||||
|
AuctionSocketData
|
||||||
|
>;
|
||||||
|
|
||||||
const BID_RATE_LIMIT_WINDOW_MS = 1000;
|
const BID_RATE_LIMIT_WINDOW_MS = 1000;
|
||||||
const BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW = 8;
|
const BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW = 8;
|
||||||
const BID_RATE_LIMIT_REJECTION_CODE = 'BID_RATE_LIMITED';
|
const BID_RATE_LIMIT_REJECTION_CODE = 'BID_RATE_LIMITED';
|
||||||
@@ -92,9 +106,7 @@ const BID_RATE_LIMIT_REJECTION_MESSAGE =
|
|||||||
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
|
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
export class AuctionGateway
|
export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||||
implements OnGatewayConnection, OnGatewayInit
|
|
||||||
{
|
|
||||||
@WebSocketServer()
|
@WebSocketServer()
|
||||||
private server!: Namespace;
|
private server!: Namespace;
|
||||||
|
|
||||||
@@ -114,14 +126,14 @@ export class AuctionGateway
|
|||||||
this.auctionEventBusService.attachAuctionNamespace(server);
|
this.auctionEventBusService.attachAuctionNamespace(server);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async handleConnection(socket: Socket) {
|
public async handleConnection(socket: AuctionSocket) {
|
||||||
try {
|
try {
|
||||||
await this.authenticateSocket(socket);
|
await this.authenticateSocket(socket);
|
||||||
this.logger.debug(`Auction client connected: ${socket.id}`);
|
this.logger.debug(`Auction client connected: ${socket.id}`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.warn(
|
this.logger.warn(
|
||||||
`Auction client authentication failed: ${
|
`Auction client authentication failed: ${
|
||||||
err instanceof Error ? err.message : err
|
err instanceof Error ? err.message : String(err)
|
||||||
}`,
|
}`,
|
||||||
);
|
);
|
||||||
socket.disconnect(true);
|
socket.disconnect(true);
|
||||||
@@ -130,7 +142,7 @@ export class AuctionGateway
|
|||||||
|
|
||||||
@SubscribeMessage('join')
|
@SubscribeMessage('join')
|
||||||
public async handleJoin(
|
public async handleJoin(
|
||||||
@ConnectedSocket() socket: Socket,
|
@ConnectedSocket() socket: AuctionSocket,
|
||||||
@MessageBody() payload: JoinAuctionPayload,
|
@MessageBody() payload: JoinAuctionPayload,
|
||||||
) {
|
) {
|
||||||
if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) {
|
if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) {
|
||||||
@@ -158,7 +170,7 @@ export class AuctionGateway
|
|||||||
|
|
||||||
@SubscribeMessage('bid')
|
@SubscribeMessage('bid')
|
||||||
public async handleBid(
|
public async handleBid(
|
||||||
@ConnectedSocket() socket: Socket,
|
@ConnectedSocket() socket: AuctionSocket,
|
||||||
@MessageBody() payload: BidPayload,
|
@MessageBody() payload: BidPayload,
|
||||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||||
) {
|
) {
|
||||||
@@ -205,7 +217,9 @@ export class AuctionGateway
|
|||||||
ack?.({
|
ack?.({
|
||||||
...(bidDelta
|
...(bidDelta
|
||||||
? {}
|
? {}
|
||||||
: { state: this.serializeAuction(bidResult as AuctionStateResponse) }),
|
: {
|
||||||
|
state: this.serializeAuction(bidResult as AuctionStateResponse),
|
||||||
|
}),
|
||||||
ok: true,
|
ok: true,
|
||||||
bidRequestId,
|
bidRequestId,
|
||||||
bidDelta: broadcastBidDelta,
|
bidDelta: broadcastBidDelta,
|
||||||
@@ -220,7 +234,12 @@ export class AuctionGateway
|
|||||||
error,
|
error,
|
||||||
);
|
);
|
||||||
const bidServerTiming = this.extractBidServerTiming(rejectionAckFields);
|
const bidServerTiming = this.extractBidServerTiming(rejectionAckFields);
|
||||||
this.emitError(socket, String(rejectionAckFields.message ?? ''));
|
this.emitError(
|
||||||
|
socket,
|
||||||
|
typeof rejectionAckFields.message === 'string'
|
||||||
|
? rejectionAckFields.message
|
||||||
|
: '',
|
||||||
|
);
|
||||||
ack?.({
|
ack?.({
|
||||||
...rejectionAckFields,
|
...rejectionAckFields,
|
||||||
bidRequestId,
|
bidRequestId,
|
||||||
@@ -263,7 +282,7 @@ export class AuctionGateway
|
|||||||
|
|
||||||
@SubscribeMessage('open-bidding')
|
@SubscribeMessage('open-bidding')
|
||||||
public async handleOpenBidding(
|
public async handleOpenBidding(
|
||||||
@ConnectedSocket() socket: Socket,
|
@ConnectedSocket() socket: AuctionSocket,
|
||||||
@MessageBody() payload: AuctionActionPayload,
|
@MessageBody() payload: AuctionActionPayload,
|
||||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||||
) {
|
) {
|
||||||
@@ -292,7 +311,7 @@ export class AuctionGateway
|
|||||||
|
|
||||||
@SubscribeMessage('sold')
|
@SubscribeMessage('sold')
|
||||||
public async handleSold(
|
public async handleSold(
|
||||||
@ConnectedSocket() socket: Socket,
|
@ConnectedSocket() socket: AuctionSocket,
|
||||||
@MessageBody() payload: SoldPayload,
|
@MessageBody() payload: SoldPayload,
|
||||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||||
) {
|
) {
|
||||||
@@ -322,7 +341,7 @@ export class AuctionGateway
|
|||||||
|
|
||||||
@SubscribeMessage('next')
|
@SubscribeMessage('next')
|
||||||
public async handleNext(
|
public async handleNext(
|
||||||
@ConnectedSocket() socket: Socket,
|
@ConnectedSocket() socket: AuctionSocket,
|
||||||
@MessageBody() payload: AuctionActionPayload,
|
@MessageBody() payload: AuctionActionPayload,
|
||||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||||
) {
|
) {
|
||||||
@@ -351,7 +370,7 @@ export class AuctionGateway
|
|||||||
|
|
||||||
@SubscribeMessage('passed')
|
@SubscribeMessage('passed')
|
||||||
public async handlePassed(
|
public async handlePassed(
|
||||||
@ConnectedSocket() socket: Socket,
|
@ConnectedSocket() socket: AuctionSocket,
|
||||||
@MessageBody() payload: AuctionActionPayload,
|
@MessageBody() payload: AuctionActionPayload,
|
||||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||||
) {
|
) {
|
||||||
@@ -380,7 +399,7 @@ export class AuctionGateway
|
|||||||
|
|
||||||
@SubscribeMessage('chat-message')
|
@SubscribeMessage('chat-message')
|
||||||
public async handleChatMessage(
|
public async handleChatMessage(
|
||||||
@ConnectedSocket() socket: Socket,
|
@ConnectedSocket() socket: AuctionSocket,
|
||||||
@MessageBody() payload: ChatMessagePayload,
|
@MessageBody() payload: ChatMessagePayload,
|
||||||
) {
|
) {
|
||||||
const matchId = this.requireJoinedMatchId(socket);
|
const matchId = this.requireJoinedMatchId(socket);
|
||||||
@@ -406,7 +425,7 @@ export class AuctionGateway
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private requireJoinedMatchId(socket: Socket): string | null {
|
private requireJoinedMatchId(socket: AuctionSocket): string | null {
|
||||||
const matchId = this.getSocketMatchId(socket);
|
const matchId = this.getSocketMatchId(socket);
|
||||||
if (!matchId) {
|
if (!matchId) {
|
||||||
this.emitError(socket, 'Join a match room before sending events.');
|
this.emitError(socket, 'Join a match room before sending events.');
|
||||||
@@ -415,10 +434,9 @@ export class AuctionGateway
|
|||||||
return matchId;
|
return matchId;
|
||||||
}
|
}
|
||||||
|
|
||||||
private consumeBidRateLimit(socket: Socket): boolean {
|
private consumeBidRateLimit(socket: AuctionSocket): boolean {
|
||||||
const currentTimestampMS = Date.now();
|
const currentTimestampMS = Date.now();
|
||||||
const previousState = socket.data
|
const previousState = socket.data.auctionBidRateLimit;
|
||||||
.auctionBidRateLimit as BidRateLimitState | undefined;
|
|
||||||
if (
|
if (
|
||||||
!previousState ||
|
!previousState ||
|
||||||
currentTimestampMS - previousState.windowStartedAtTimestampMS >=
|
currentTimestampMS - previousState.windowStartedAtTimestampMS >=
|
||||||
@@ -436,10 +454,8 @@ export class AuctionGateway
|
|||||||
return previousState.count <= BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW;
|
return previousState.count <= BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW;
|
||||||
}
|
}
|
||||||
|
|
||||||
private getSocketMatchId(socket: Socket): string | undefined {
|
private getSocketMatchId(socket: AuctionSocket): string | undefined {
|
||||||
return typeof socket.data.matchId === 'string'
|
return socket.data.matchId;
|
||||||
? socket.data.matchId
|
|
||||||
: undefined;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private toAuctionActionRequest(payload?: AuctionActionPayload) {
|
private toAuctionActionRequest(payload?: AuctionActionPayload) {
|
||||||
@@ -463,8 +479,9 @@ export class AuctionGateway
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private readHandshakeUserId(socket: Socket): string | undefined {
|
private readHandshakeUserId(socket: AuctionSocket): string | undefined {
|
||||||
const authUserId = socket.handshake.auth['x-auth-user-id'];
|
const handshakeAuth = socket.handshake.auth as Record<string, unknown>;
|
||||||
|
const authUserId = handshakeAuth['x-auth-user-id'];
|
||||||
if (typeof authUserId === 'string') return authUserId;
|
if (typeof authUserId === 'string') return authUserId;
|
||||||
|
|
||||||
const header = socket.handshake.headers['x-auth-user-id'];
|
const header = socket.handshake.headers['x-auth-user-id'];
|
||||||
@@ -472,16 +489,16 @@ export class AuctionGateway
|
|||||||
}
|
}
|
||||||
|
|
||||||
private resolveSocketUserId(
|
private resolveSocketUserId(
|
||||||
socket: Socket,
|
socket: AuctionSocket,
|
||||||
): mongoose.Types.ObjectId | undefined {
|
): mongoose.Types.ObjectId | undefined {
|
||||||
return (socket.data.user as UserDocument | undefined)?._id;
|
return socket.data.user?._id;
|
||||||
}
|
}
|
||||||
|
|
||||||
private resolveChatDisplayName(
|
private resolveChatDisplayName(
|
||||||
socket: Socket,
|
socket: AuctionSocket,
|
||||||
fallbackDisplayName?: string,
|
fallbackDisplayName?: string,
|
||||||
): string {
|
): string {
|
||||||
const user = socket.data.user as UserDocument | undefined;
|
const user = socket.data.user;
|
||||||
const primaryRiotAccount =
|
const primaryRiotAccount =
|
||||||
user?.riotAccounts.find((entry) => entry.isPrimary) ??
|
user?.riotAccounts.find((entry) => entry.isPrimary) ??
|
||||||
user?.riotAccounts[0];
|
user?.riotAccounts[0];
|
||||||
@@ -494,14 +511,14 @@ export class AuctionGateway
|
|||||||
if (user?.kakaoTalkNickname) return user.kakaoTalkNickname;
|
if (user?.kakaoTalkNickname) return user.kakaoTalkNickname;
|
||||||
if (user?.discordNickname) return user.discordNickname;
|
if (user?.discordNickname) return user.discordNickname;
|
||||||
|
|
||||||
const identity = socket.data.identity as IdentityDocument | undefined;
|
const identity = socket.data.identity;
|
||||||
if (identity?.displayName) return identity.displayName;
|
if (identity?.displayName) return identity.displayName;
|
||||||
if (identity?.email) return identity.email;
|
if (identity?.email) return identity.email;
|
||||||
|
|
||||||
return fallbackDisplayName ?? '관전자';
|
return fallbackDisplayName ?? '관전자';
|
||||||
}
|
}
|
||||||
|
|
||||||
private async authenticateSocket(socket: Socket): Promise<void> {
|
private async authenticateSocket(socket: AuctionSocket): Promise<void> {
|
||||||
const fallback = await this.authService.resolveDevUserById(
|
const fallback = await this.authService.resolveDevUserById(
|
||||||
this.readHandshakeUserId(socket),
|
this.readHandshakeUserId(socket),
|
||||||
);
|
);
|
||||||
@@ -531,14 +548,20 @@ export class AuctionGateway
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private readHandshakeToken(socket: Socket): string | undefined {
|
private readHandshakeToken(socket: AuctionSocket): string | undefined {
|
||||||
const authToken = socket.handshake.auth.token;
|
const handshakeAuth = socket.handshake.auth as Record<string, unknown>;
|
||||||
|
const authToken = handshakeAuth.token;
|
||||||
if (typeof authToken === 'string' && authToken.trim()) {
|
if (typeof authToken === 'string' && authToken.trim()) {
|
||||||
return authToken.trim().replace(/^Bearer\s+/i, '');
|
return authToken.trim().replace(/^Bearer\s+/i, '');
|
||||||
}
|
}
|
||||||
|
|
||||||
const header = socket.handshake.headers.authorization;
|
const header: unknown = socket.handshake.headers.authorization;
|
||||||
const authorization = Array.isArray(header) ? header[0] : header;
|
const authorization =
|
||||||
|
typeof header === 'string'
|
||||||
|
? header
|
||||||
|
: Array.isArray(header) && typeof header[0] === 'string'
|
||||||
|
? header[0]
|
||||||
|
: undefined;
|
||||||
if (authorization?.startsWith('Bearer ')) {
|
if (authorization?.startsWith('Bearer ')) {
|
||||||
return authorization.slice('Bearer '.length).trim();
|
return authorization.slice('Bearer '.length).trim();
|
||||||
}
|
}
|
||||||
@@ -546,10 +569,11 @@ export class AuctionGateway
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async resolveSocketUserForMatch(
|
private async resolveSocketUserForMatch(
|
||||||
socket: Socket,
|
socket: AuctionSocket,
|
||||||
matchId: string,
|
matchId: string,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
if (socket.data.user || !socket.data.identity) return;
|
if (socket.data.user || !socket.data.identity) return;
|
||||||
|
const identity = socket.data.identity;
|
||||||
|
|
||||||
const MatchModel = await this.connectionService.getModel('match');
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
const match = await MatchModel.findById(matchId).select({
|
const match = await MatchModel.findById(matchId).select({
|
||||||
@@ -558,10 +582,11 @@ export class AuctionGateway
|
|||||||
if (!match) return;
|
if (!match) return;
|
||||||
|
|
||||||
const UserModel = await this.connectionService.getModel('user');
|
const UserModel = await this.connectionService.getModel('user');
|
||||||
socket.data.user = await UserModel.findOne({
|
const user = await UserModel.findOne({
|
||||||
communityId: match.communityId,
|
communityId: match.communityId,
|
||||||
identityId: (socket.data.identity as IdentityDocument)._id,
|
identityId: identity._id,
|
||||||
}).exec();
|
}).exec();
|
||||||
|
socket.data.user = user ?? undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
private requireStringClaim(payload: JWTPayload, key: string): string {
|
private requireStringClaim(payload: JWTPayload, key: string): string {
|
||||||
@@ -595,7 +620,7 @@ export class AuctionGateway
|
|||||||
this.server.to(matchId).emit('match-side-effect', delta);
|
this.server.to(matchId).emit('match-side-effect', delta);
|
||||||
}
|
}
|
||||||
|
|
||||||
private emitChatHistory(socket: Socket, auction: AuctionDocument) {
|
private emitChatHistory(socket: AuctionSocket, auction: AuctionDocument) {
|
||||||
socket.emit('chat-history', {
|
socket.emit('chat-history', {
|
||||||
messages: (auction.chatMessages ?? []).map((message) =>
|
messages: (auction.chatMessages ?? []).map((message) =>
|
||||||
this.serializeChatMessage(message),
|
this.serializeChatMessage(message),
|
||||||
@@ -603,16 +628,21 @@ export class AuctionGateway
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private emitKnownError(socket: Socket, error: unknown) {
|
private emitKnownError(socket: AuctionSocket, error: unknown) {
|
||||||
this.emitError(socket, this.resolveErrorPayload(error).message);
|
this.emitError(socket, this.resolveErrorPayload(error).message);
|
||||||
}
|
}
|
||||||
|
|
||||||
private emitError(socket: Socket, message: string) {
|
private emitError(socket: AuctionSocket, message: string) {
|
||||||
socket.emit('error', { message });
|
socket.emit('error', { message });
|
||||||
}
|
}
|
||||||
|
|
||||||
private serializeAuction(auction: AuctionStateResponse) {
|
private serializeAuction(
|
||||||
return JSON.parse(JSON.stringify(auction));
|
auction: AuctionStateResponse,
|
||||||
|
): Record<string, unknown> {
|
||||||
|
const serialized: unknown = JSON.parse(JSON.stringify(auction));
|
||||||
|
return typeof serialized === 'object' && serialized !== null
|
||||||
|
? (serialized as Record<string, unknown>)
|
||||||
|
: {};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -633,7 +663,9 @@ export class AuctionGateway
|
|||||||
typeof errorPayload.code === 'string' ? errorPayload.code : undefined,
|
typeof errorPayload.code === 'string' ? errorPayload.code : undefined,
|
||||||
errorPayload.message,
|
errorPayload.message,
|
||||||
);
|
);
|
||||||
const resyncRecommended = isAuctionResyncRecommended(auctionRejectionReason);
|
const resyncRecommended = isAuctionResyncRecommended(
|
||||||
|
auctionRejectionReason,
|
||||||
|
);
|
||||||
const state = resyncRecommended
|
const state = resyncRecommended
|
||||||
? await this.fetchSerializedAuctionState(matchId)
|
? await this.fetchSerializedAuctionState(matchId)
|
||||||
: undefined;
|
: undefined;
|
||||||
@@ -688,7 +720,9 @@ export class AuctionGateway
|
|||||||
return {
|
return {
|
||||||
code: error instanceof Error ? error.message : 'UNKNOWN',
|
code: error instanceof Error ? error.message : 'UNKNOWN',
|
||||||
message:
|
message:
|
||||||
error instanceof Error ? error.message : 'Unexpected auction gateway error.',
|
error instanceof Error
|
||||||
|
? error.message
|
||||||
|
: 'Unexpected auction gateway error.',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -716,7 +750,8 @@ export class AuctionGateway
|
|||||||
bidDelta: Record<string, unknown> | null,
|
bidDelta: Record<string, unknown> | null,
|
||||||
): Record<string, unknown> | null {
|
): Record<string, unknown> | null {
|
||||||
if (!bidDelta || !('bidServerTiming' in bidDelta)) return bidDelta;
|
if (!bidDelta || !('bidServerTiming' in bidDelta)) return bidDelta;
|
||||||
const { bidServerTiming: _bidServerTiming, ...publicBidDelta } = bidDelta;
|
const publicBidDelta = { ...bidDelta };
|
||||||
|
delete publicBidDelta.bidServerTiming;
|
||||||
return publicBidDelta;
|
return publicBidDelta;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -724,7 +759,7 @@ export class AuctionGateway
|
|||||||
auction: AuctionStateResponse,
|
auction: AuctionStateResponse,
|
||||||
bidRequestId?: string,
|
bidRequestId?: string,
|
||||||
): Record<string, unknown> | null {
|
): Record<string, unknown> | null {
|
||||||
const serialized = this.serializeAuction(auction) as Record<string, unknown>;
|
const serialized = this.serializeAuction(auction);
|
||||||
const revision = Number(serialized.revision);
|
const revision = Number(serialized.revision);
|
||||||
const currentHighestBidPointAmount = Number(
|
const currentHighestBidPointAmount = Number(
|
||||||
serialized.currentHighestBidPointAmount ?? serialized.currentBid,
|
serialized.currentHighestBidPointAmount ?? serialized.currentBid,
|
||||||
@@ -739,11 +774,13 @@ export class AuctionGateway
|
|||||||
? Date.parse(serialized.currentDeadline)
|
? Date.parse(serialized.currentDeadline)
|
||||||
: 0),
|
: 0),
|
||||||
);
|
);
|
||||||
const redisBidHistory = Array.isArray(serialized.auctionBidHistory)
|
const redisBidHistory: unknown[] = Array.isArray(
|
||||||
? serialized.auctionBidHistory
|
serialized.auctionBidHistory,
|
||||||
|
)
|
||||||
|
? (serialized.auctionBidHistory as unknown[])
|
||||||
: [];
|
: [];
|
||||||
const legacyBidHistory = Array.isArray(serialized.bids)
|
const legacyBidHistory: unknown[] = Array.isArray(serialized.bids)
|
||||||
? serialized.bids
|
? (serialized.bids as unknown[])
|
||||||
: [];
|
: [];
|
||||||
const auctionBidHistoryEntry =
|
const auctionBidHistoryEntry =
|
||||||
redisBidHistory[redisBidHistory.length - 1] ??
|
redisBidHistory[redisBidHistory.length - 1] ??
|
||||||
@@ -775,9 +812,7 @@ export class AuctionGateway
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private isBidDeltaResponse(
|
private isBidDeltaResponse(value: unknown): value is AuctionBidDeltaResponse {
|
||||||
value: unknown,
|
|
||||||
): value is AuctionBidDeltaResponse {
|
|
||||||
return (
|
return (
|
||||||
typeof value === 'object' &&
|
typeof value === 'object' &&
|
||||||
value !== null &&
|
value !== null &&
|
||||||
@@ -804,7 +839,12 @@ export class AuctionGateway
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private serializeChatMessage(message: AuctionChatMessage) {
|
private serializeChatMessage(
|
||||||
return JSON.parse(JSON.stringify(message));
|
message: AuctionChatMessage,
|
||||||
|
): Record<string, unknown> {
|
||||||
|
const serialized: unknown = JSON.parse(JSON.stringify(message));
|
||||||
|
return typeof serialized === 'object' && serialized !== null
|
||||||
|
? (serialized as Record<string, unknown>)
|
||||||
|
: {};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,30 @@ import mongoose from 'mongoose';
|
|||||||
import { AuctionService } from './auction.service';
|
import { AuctionService } from './auction.service';
|
||||||
|
|
||||||
describe('AuctionService', () => {
|
describe('AuctionService', () => {
|
||||||
|
function requireRecord(
|
||||||
|
value: unknown,
|
||||||
|
label: string,
|
||||||
|
): Record<string, unknown> {
|
||||||
|
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||||
|
throw new Error(`${label} must be an object.`);
|
||||||
|
}
|
||||||
|
return value as Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function requireArray(value: unknown, label: string): unknown[] {
|
||||||
|
if (!Array.isArray(value)) {
|
||||||
|
throw new Error(`${label} must be an array.`);
|
||||||
|
}
|
||||||
|
return value as unknown[];
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseJsonRecord(value: unknown, label: string) {
|
||||||
|
if (typeof value !== 'string') {
|
||||||
|
throw new Error(`${label} must be a JSON string.`);
|
||||||
|
}
|
||||||
|
return requireRecord(JSON.parse(value) as unknown, label);
|
||||||
|
}
|
||||||
|
|
||||||
function createService(models: Record<string, unknown>) {
|
function createService(models: Record<string, unknown>) {
|
||||||
const auctionHistoryModel = {
|
const auctionHistoryModel = {
|
||||||
findOne: jest.fn().mockReturnValue({
|
findOne: jest.fn().mockReturnValue({
|
||||||
@@ -158,12 +182,11 @@ describe('AuctionService', () => {
|
|||||||
it('rejects non-positive or fractional bid amounts before loading auction state', async () => {
|
it('rejects non-positive or fractional bid amounts before loading auction state', async () => {
|
||||||
const matchId = new mongoose.Types.ObjectId();
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
const auctionFindOne = jest.fn();
|
const auctionFindOne = jest.fn();
|
||||||
const { service, auctionRedisCommandService, auctionRedisService } =
|
const { service, auctionRedisCommandService } = createService({
|
||||||
createService({
|
auction: {
|
||||||
auction: {
|
findOne: auctionFindOne,
|
||||||
findOne: auctionFindOne,
|
},
|
||||||
},
|
});
|
||||||
});
|
|
||||||
|
|
||||||
await expect(
|
await expect(
|
||||||
service.placeBid({
|
service.placeBid({
|
||||||
@@ -1008,7 +1031,12 @@ describe('AuctionService', () => {
|
|||||||
);
|
);
|
||||||
const transitionInput =
|
const transitionInput =
|
||||||
auctionRedisCommandService.applyTransition.mock.calls[0][1];
|
auctionRedisCommandService.applyTransition.mock.calls[0][1];
|
||||||
expect(JSON.parse(transitionInput.durabilityPayloadJson)).toMatchObject({
|
expect(
|
||||||
|
parseJsonRecord(
|
||||||
|
transitionInput.durabilityPayloadJson,
|
||||||
|
'durabilityPayloadJson',
|
||||||
|
),
|
||||||
|
).toMatchObject({
|
||||||
afterAuctionMongoProjection: expect.objectContaining({
|
afterAuctionMongoProjection: expect.objectContaining({
|
||||||
phase: 'bidding',
|
phase: 'bidding',
|
||||||
revision: 2,
|
revision: 2,
|
||||||
@@ -1179,17 +1207,40 @@ describe('AuctionService', () => {
|
|||||||
|
|
||||||
const transitionInput =
|
const transitionInput =
|
||||||
auctionRedisCommandService.applyTransition.mock.calls[0][1];
|
auctionRedisCommandService.applyTransition.mock.calls[0][1];
|
||||||
const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson);
|
const durabilityPayload = parseJsonRecord(
|
||||||
expect(durabilityPayload.snapshotBefore).toMatchObject({
|
transitionInput.durabilityPayloadJson,
|
||||||
|
'durabilityPayloadJson',
|
||||||
|
);
|
||||||
|
const snapshotBefore = requireRecord(
|
||||||
|
durabilityPayload.snapshotBefore,
|
||||||
|
'snapshotBefore',
|
||||||
|
);
|
||||||
|
const snapshotBeforeTeams = requireArray(
|
||||||
|
snapshotBefore.auctionTeams,
|
||||||
|
'snapshotBefore.auctionTeams',
|
||||||
|
);
|
||||||
|
const snapshotBeforeTeam = requireRecord(
|
||||||
|
snapshotBeforeTeams[0],
|
||||||
|
'snapshotBefore.auctionTeams[0]',
|
||||||
|
);
|
||||||
|
const afterAuctionMongoProjection = requireRecord(
|
||||||
|
durabilityPayload.afterAuctionMongoProjection,
|
||||||
|
'afterAuctionMongoProjection',
|
||||||
|
);
|
||||||
|
const projectedTeams = requireArray(
|
||||||
|
afterAuctionMongoProjection.auctionTeams,
|
||||||
|
'afterAuctionMongoProjection.auctionTeams',
|
||||||
|
);
|
||||||
|
const projectedTeam = requireRecord(
|
||||||
|
projectedTeams[0],
|
||||||
|
'afterAuctionMongoProjection.auctionTeams[0]',
|
||||||
|
);
|
||||||
|
expect(snapshotBefore).toMatchObject({
|
||||||
phase: 'bidding',
|
phase: 'bidding',
|
||||||
revision: 4,
|
revision: 4,
|
||||||
});
|
});
|
||||||
expect(durabilityPayload.snapshotBefore.auctionTeams[0].members).toEqual(
|
expect(snapshotBeforeTeam.members).toEqual([]);
|
||||||
[],
|
expect(projectedTeam.members).toEqual([
|
||||||
);
|
|
||||||
expect(
|
|
||||||
durabilityPayload.afterAuctionMongoProjection.auctionTeams[0].members,
|
|
||||||
).toEqual([
|
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
memberAcquisitionBidPointAmount: 120,
|
memberAcquisitionBidPointAmount: 120,
|
||||||
userId: playerUserId.toString(),
|
userId: playerUserId.toString(),
|
||||||
@@ -1314,6 +1365,267 @@ describe('AuctionService', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('redis next safety', () => {
|
||||||
|
function createFortyPlayerAuction() {
|
||||||
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
|
const participantIds = Array.from(
|
||||||
|
{ length: 40 },
|
||||||
|
() => new mongoose.Types.ObjectId(),
|
||||||
|
);
|
||||||
|
const auction = {
|
||||||
|
_id: new mongoose.Types.ObjectId(),
|
||||||
|
matchId,
|
||||||
|
auctionEngineVersion: 'redis-v1',
|
||||||
|
auctionLifecycleId: 'life-1',
|
||||||
|
};
|
||||||
|
const state = {
|
||||||
|
auctionLifecycleId: 'life-1',
|
||||||
|
auctionTeams: participantIds
|
||||||
|
.slice(0, 8)
|
||||||
|
.map((captainUserId, index) => ({
|
||||||
|
teamIndex: index + 1,
|
||||||
|
captainUserId: captainUserId.toString(),
|
||||||
|
remainingBidPointAmount: 960,
|
||||||
|
members: participantIds
|
||||||
|
.slice(8 + index * 4, 12 + index * 4)
|
||||||
|
.map((userId) => ({
|
||||||
|
userId: userId.toString(),
|
||||||
|
assignedPosition: 'MID',
|
||||||
|
memberAcquisitionBidPointAmount: 10,
|
||||||
|
})),
|
||||||
|
})),
|
||||||
|
auctionPlayerOrder: participantIds.slice(8).map((userId) => ({
|
||||||
|
userId: userId.toString(),
|
||||||
|
preferredPositions: [{ position: 'MID', priority: 1 }],
|
||||||
|
passCount: 0,
|
||||||
|
})),
|
||||||
|
bidRoundExtensionSeconds: 5,
|
||||||
|
currentAuctionHistorySequence: 121,
|
||||||
|
currentAuctionPlayerOrderIndex: 31,
|
||||||
|
currentAuctionRound: 1,
|
||||||
|
initialTeamBidPointAmount: 1000,
|
||||||
|
maximumBidRoundDurationSeconds: 15,
|
||||||
|
passedAuctionPlayerQueue: [] as Array<{
|
||||||
|
userId: string;
|
||||||
|
preferredPositions: Array<{ position: string; priority: number }>;
|
||||||
|
passCount: number;
|
||||||
|
}>,
|
||||||
|
phase: 'sold',
|
||||||
|
revision: 479,
|
||||||
|
topTierAuctionPriorityThreshold: 'NONE',
|
||||||
|
};
|
||||||
|
const match = {
|
||||||
|
_id: matchId,
|
||||||
|
participants: participantIds.map((userId) => ({
|
||||||
|
userId,
|
||||||
|
excluded: false,
|
||||||
|
preferredPositions: [{ position: 'MID', priority: 1 }],
|
||||||
|
})),
|
||||||
|
status: 'team-built',
|
||||||
|
teams: [],
|
||||||
|
save: jest.fn().mockResolvedValue(undefined),
|
||||||
|
};
|
||||||
|
const dependencies = createService({
|
||||||
|
auction: { findOne: jest.fn().mockResolvedValue(auction) },
|
||||||
|
match: { findById: jest.fn().mockResolvedValue(match) },
|
||||||
|
});
|
||||||
|
dependencies.auctionRedisStateReaderService.readAuctionStateView.mockResolvedValue(
|
||||||
|
state,
|
||||||
|
);
|
||||||
|
dependencies.auctionRedisCommandService.applyTransition.mockImplementation(
|
||||||
|
async (_matchId: string, input: Record<string, unknown>) => {
|
||||||
|
Object.assign(
|
||||||
|
state,
|
||||||
|
parseJsonRecord(
|
||||||
|
input.afterAuctionStructureStateJson,
|
||||||
|
'afterAuctionStructureStateJson',
|
||||||
|
),
|
||||||
|
input.liveStatePatch,
|
||||||
|
{
|
||||||
|
revision: Number(input.expectedRevision) + 1,
|
||||||
|
currentAuctionHistorySequence: input.auctionHistorySequence,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
auctionStateTransitionId: String(input.auctionStateTransitionId),
|
||||||
|
currentServerTimestampMS: 1780000000000,
|
||||||
|
ok: true,
|
||||||
|
revision: state.revision,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return { ...dependencies, matchId, match, state, participantIds };
|
||||||
|
}
|
||||||
|
|
||||||
|
it.each([12, 31])(
|
||||||
|
'rejects next for a presenting player at index %i without skipping or completing',
|
||||||
|
async (index) => {
|
||||||
|
const { service, matchId, state, auctionRedisCommandService } =
|
||||||
|
createFortyPlayerAuction();
|
||||||
|
state.phase = 'presenting';
|
||||||
|
state.currentAuctionPlayerOrderIndex = index;
|
||||||
|
const before = structuredClone(state);
|
||||||
|
|
||||||
|
await expect(service.next(matchId)).rejects.toThrow(
|
||||||
|
'Cannot advance from current phase.',
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(state).toEqual(before);
|
||||||
|
expect(
|
||||||
|
auctionRedisCommandService.reserveActionRequest,
|
||||||
|
).not.toHaveBeenCalled();
|
||||||
|
expect(
|
||||||
|
auctionRedisCommandService.applyTransition,
|
||||||
|
).not.toHaveBeenCalled();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it('rejects completion when only 39 of the 40 participants are assigned', async () => {
|
||||||
|
const { service, matchId, state, match, auctionRedisCommandService } =
|
||||||
|
createFortyPlayerAuction();
|
||||||
|
state.auctionTeams[6].members.pop();
|
||||||
|
const before = structuredClone(state);
|
||||||
|
|
||||||
|
await expect(service.next(matchId)).rejects.toThrow(
|
||||||
|
'Auction roster validation failed.',
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(state).toEqual(before);
|
||||||
|
expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled();
|
||||||
|
expect(match.save).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('checks original eligible participants even if a missing player also disappeared from the order', async () => {
|
||||||
|
const { service, matchId, state, auctionRedisCommandService } =
|
||||||
|
createFortyPlayerAuction();
|
||||||
|
const missingPlayer = state.auctionTeams[6].members.pop()!;
|
||||||
|
state.auctionPlayerOrder = state.auctionPlayerOrder.filter(
|
||||||
|
(player) => player.userId !== missingPlayer.userId,
|
||||||
|
);
|
||||||
|
state.currentAuctionPlayerOrderIndex =
|
||||||
|
state.auctionPlayerOrder.length - 1;
|
||||||
|
const before = structuredClone(state);
|
||||||
|
|
||||||
|
await expect(service.next(matchId)).rejects.toThrow(
|
||||||
|
'Auction roster validation failed.',
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(state).toEqual(before);
|
||||||
|
expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a duplicate assignment even when the assigned count still equals 40', async () => {
|
||||||
|
const { service, matchId, state, auctionRedisCommandService } =
|
||||||
|
createFortyPlayerAuction();
|
||||||
|
state.auctionTeams[0].members[0].userId =
|
||||||
|
state.auctionTeams[1].members[0].userId;
|
||||||
|
|
||||||
|
await expect(service.next(matchId)).rejects.toThrow(
|
||||||
|
'Auction roster validation failed.',
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(state.phase).toBe('sold');
|
||||||
|
expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects duplicate captain membership even when every expected user is present', async () => {
|
||||||
|
const { service, matchId, state, auctionRedisCommandService } =
|
||||||
|
createFortyPlayerAuction();
|
||||||
|
state.auctionTeams[0].members.push({
|
||||||
|
userId: state.auctionTeams[0].captainUserId,
|
||||||
|
assignedPosition: 'MID',
|
||||||
|
memberAcquisitionBidPointAmount: 10,
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(service.next(matchId)).rejects.toThrow(
|
||||||
|
'Auction roster validation failed.',
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(state.phase).toBe('sold');
|
||||||
|
expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects an unexpected assigned user even when all 40 assignments are unique', async () => {
|
||||||
|
const { service, matchId, state, auctionRedisCommandService } =
|
||||||
|
createFortyPlayerAuction();
|
||||||
|
state.auctionTeams[0].members[0].userId =
|
||||||
|
new mongoose.Types.ObjectId().toString();
|
||||||
|
|
||||||
|
await expect(service.next(matchId)).rejects.toThrow(
|
||||||
|
'Auction roster validation failed.',
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(state.phase).toBe('sold');
|
||||||
|
expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('completes all 40 eligible participants once, allowing repeat order entries after passes and excluding cut participants', async () => {
|
||||||
|
const { service, matchId, state, match, auctionRedisCommandService } =
|
||||||
|
createFortyPlayerAuction();
|
||||||
|
state.auctionPlayerOrder.push({
|
||||||
|
...state.auctionPlayerOrder[12],
|
||||||
|
passCount: 1,
|
||||||
|
});
|
||||||
|
state.currentAuctionPlayerOrderIndex =
|
||||||
|
state.auctionPlayerOrder.length - 1;
|
||||||
|
state.currentAuctionRound = 2;
|
||||||
|
match.participants.push({
|
||||||
|
userId: new mongoose.Types.ObjectId(),
|
||||||
|
excluded: true,
|
||||||
|
preferredPositions: [{ position: 'MID', priority: 1 }],
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(service.next(matchId)).resolves.toMatchObject({
|
||||||
|
phase: 'complete',
|
||||||
|
revision: 480,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(auctionRedisCommandService.applyTransition).toHaveBeenCalledTimes(
|
||||||
|
1,
|
||||||
|
);
|
||||||
|
expect(state.auctionTeams).toHaveLength(8);
|
||||||
|
expect(
|
||||||
|
state.auctionTeams.every((team) => team.members.length === 4),
|
||||||
|
).toBe(true);
|
||||||
|
expect(match.save).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(['sold', 'passed'])(
|
||||||
|
'advances a nonterminal %s player without demanding a completed roster',
|
||||||
|
async (phase) => {
|
||||||
|
const { service, matchId, state } = createFortyPlayerAuction();
|
||||||
|
state.phase = phase;
|
||||||
|
state.currentAuctionPlayerOrderIndex = 12;
|
||||||
|
state.auctionTeams.forEach((team) => {
|
||||||
|
team.members = [];
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(service.next(matchId)).resolves.toMatchObject({
|
||||||
|
phase: 'presenting',
|
||||||
|
currentAuctionPlayerOrderIndex: 13,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it('requeues passed players for another round without completing an incomplete roster', async () => {
|
||||||
|
const { service, matchId, state } = createFortyPlayerAuction();
|
||||||
|
state.phase = 'passed';
|
||||||
|
state.auctionTeams[7].members.pop();
|
||||||
|
state.passedAuctionPlayerQueue.push({
|
||||||
|
...state.auctionPlayerOrder[31],
|
||||||
|
passCount: 1,
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(service.next(matchId)).resolves.toMatchObject({
|
||||||
|
phase: 'presenting',
|
||||||
|
currentAuctionPlayerOrderIndex: 32,
|
||||||
|
currentAuctionRound: 2,
|
||||||
|
passedAuctionPlayerQueue: [],
|
||||||
|
});
|
||||||
|
expect(state.auctionPlayerOrder).toHaveLength(33);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it('syncs match teams when a redis-v1 auction completes', async () => {
|
it('syncs match teams when a redis-v1 auction completes', async () => {
|
||||||
const matchId = new mongoose.Types.ObjectId();
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
const captainUserId = new mongoose.Types.ObjectId();
|
const captainUserId = new mongoose.Types.ObjectId();
|
||||||
@@ -1397,7 +1709,12 @@ describe('AuctionService', () => {
|
|||||||
});
|
});
|
||||||
const [, transitionInput] =
|
const [, transitionInput] =
|
||||||
auctionRedisCommandService.applyTransition.mock.calls.at(-1) ?? [];
|
auctionRedisCommandService.applyTransition.mock.calls.at(-1) ?? [];
|
||||||
expect(JSON.parse(transitionInput.durabilityPayloadJson)).toMatchObject({
|
expect(
|
||||||
|
parseJsonRecord(
|
||||||
|
transitionInput.durabilityPayloadJson,
|
||||||
|
'durabilityPayloadJson',
|
||||||
|
),
|
||||||
|
).toMatchObject({
|
||||||
afterAuctionMongoProjection: {
|
afterAuctionMongoProjection: {
|
||||||
matchSideEffectStatus: 'pending',
|
matchSideEffectStatus: 'pending',
|
||||||
phase: 'complete',
|
phase: 'complete',
|
||||||
@@ -1786,7 +2103,7 @@ describe('AuctionService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
expect(auction.currentBid).toBe(970);
|
expect(auction.currentBid).toBe(970);
|
||||||
expect(auction.currentBidderTeamIndex).toBe(1);
|
expect(auction).toHaveProperty('currentBidderTeamIndex', 1);
|
||||||
expect(auction.bids).toEqual([
|
expect(auction.bids).toEqual([
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
teamIndex: 1,
|
teamIndex: 1,
|
||||||
@@ -2080,7 +2397,7 @@ describe('AuctionService', () => {
|
|||||||
await service.next(matchId);
|
await service.next(matchId);
|
||||||
|
|
||||||
expect(auction.phase).toBe('complete');
|
expect(auction.phase).toBe('complete');
|
||||||
expect(auction.completedAt).toBeInstanceOf(Date);
|
expect(auction).toHaveProperty('completedAt', expect.any(Date));
|
||||||
expect(auction.save).toHaveBeenCalledTimes(1);
|
expect(auction.save).toHaveBeenCalledTimes(1);
|
||||||
expect(match.save).toHaveBeenCalledTimes(2);
|
expect(match.save).toHaveBeenCalledTimes(2);
|
||||||
expect(match.teams).toEqual([
|
expect(match.teams).toEqual([
|
||||||
@@ -2568,7 +2885,10 @@ describe('AuctionService', () => {
|
|||||||
durationSeconds: 30,
|
durationSeconds: 30,
|
||||||
mode: 'set-relative',
|
mode: 'set-relative',
|
||||||
});
|
});
|
||||||
const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson);
|
const durabilityPayload = parseJsonRecord(
|
||||||
|
transitionInput.durabilityPayloadJson,
|
||||||
|
'durabilityPayloadJson',
|
||||||
|
);
|
||||||
expect(durabilityPayload).toMatchObject({
|
expect(durabilityPayload).toMatchObject({
|
||||||
auctionActionType: 'undo',
|
auctionActionType: 'undo',
|
||||||
historyMutation: {
|
historyMutation: {
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ import {
|
|||||||
stringifyAuctionRedisStructureState,
|
stringifyAuctionRedisStructureState,
|
||||||
} from './redis/auction-redis-projection';
|
} from './redis/auction-redis-projection';
|
||||||
import { AuctionRedisService } from './redis/auction-redis.service';
|
import { AuctionRedisService } from './redis/auction-redis.service';
|
||||||
|
import { AUCTION_CLEANUP_DURABILITY_SCRIPT } from './redis/auction-redis.cleanup';
|
||||||
import { AuctionRedisStateReaderService } from './redis/auction-redis-state-reader.service';
|
import { AuctionRedisStateReaderService } from './redis/auction-redis-state-reader.service';
|
||||||
import { shouldHydrateRedisAuctionState } from './redis/auction-redis.state';
|
import { shouldHydrateRedisAuctionState } from './redis/auction-redis.state';
|
||||||
// [AUCTION-DEBUG] 경매 "중복 멤버" 조사용 임시 계측. 조사 종료 후 제거 대상.
|
// [AUCTION-DEBUG] 경매 "중복 멤버" 조사용 임시 계측. 조사 종료 후 제거 대상.
|
||||||
@@ -1193,11 +1194,7 @@ export class AuctionService {
|
|||||||
): Promise<AuctionStateResponse> {
|
): Promise<AuctionStateResponse> {
|
||||||
const matchId = auction.matchId.toString();
|
const matchId = auction.matchId.toString();
|
||||||
const state = await this.requireRedisAuctionState(matchId);
|
const state = await this.requireRedisAuctionState(matchId);
|
||||||
if (
|
if (state.phase !== 'sold' && state.phase !== 'passed') {
|
||||||
state.phase !== 'sold' &&
|
|
||||||
state.phase !== 'presenting' &&
|
|
||||||
state.phase !== 'passed'
|
|
||||||
) {
|
|
||||||
throw new BadRequestException('Cannot advance from current phase.');
|
throw new BadRequestException('Cannot advance from current phase.');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1218,6 +1215,10 @@ export class AuctionService {
|
|||||||
structureInput.currentAuctionRound += 1;
|
structureInput.currentAuctionRound += 1;
|
||||||
structureInput.currentAuctionPlayerOrderIndex = nextIndex;
|
structureInput.currentAuctionPlayerOrderIndex = nextIndex;
|
||||||
} else {
|
} else {
|
||||||
|
await this.assertCompleteAuctionRoster(
|
||||||
|
auction.matchId,
|
||||||
|
structureInput.auctionTeams,
|
||||||
|
);
|
||||||
action = 'complete';
|
action = 'complete';
|
||||||
nextPhase = 'complete';
|
nextPhase = 'complete';
|
||||||
}
|
}
|
||||||
@@ -1332,17 +1333,16 @@ export class AuctionService {
|
|||||||
if (this.isRedisV1Auction(auction)) {
|
if (this.isRedisV1Auction(auction)) {
|
||||||
return this.advanceRedisAuction(auction, actionRequest);
|
return this.advanceRedisAuction(auction, actionRequest);
|
||||||
}
|
}
|
||||||
if (
|
if (auction.phase !== 'sold' && auction.phase !== 'passed') {
|
||||||
auction.phase !== 'sold' &&
|
|
||||||
auction.phase !== 'presenting' &&
|
|
||||||
auction.phase !== 'passed'
|
|
||||||
) {
|
|
||||||
throw new BadRequestException('Cannot advance from current phase.');
|
throw new BadRequestException('Cannot advance from current phase.');
|
||||||
}
|
}
|
||||||
const nextIndex = auction.currentIndex + 1;
|
const nextIndex = auction.currentIndex + 1;
|
||||||
const completesAuction =
|
const completesAuction =
|
||||||
nextIndex >= auction.order.length &&
|
nextIndex >= auction.order.length &&
|
||||||
(auction.passedQueue?.length ?? 0) === 0;
|
(auction.passedQueue?.length ?? 0) === 0;
|
||||||
|
if (completesAuction) {
|
||||||
|
await this.assertCompleteAuctionRoster(matchId, auction.teams);
|
||||||
|
}
|
||||||
await this.recordSnapshot(auction, completesAuction ? 'complete' : 'next');
|
await this.recordSnapshot(auction, completesAuction ? 'complete' : 'next');
|
||||||
if (nextIndex >= auction.order.length) {
|
if (nextIndex >= auction.order.length) {
|
||||||
if ((auction.passedQueue?.length ?? 0) > 0) {
|
if ((auction.passedQueue?.length ?? 0) > 0) {
|
||||||
@@ -2515,6 +2515,52 @@ export class AuctionService {
|
|||||||
return ordered.slice(0, desiredAuctionCount);
|
return ordered.slice(0, desiredAuctionCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async assertCompleteAuctionRoster(
|
||||||
|
matchId: mongoose.Types.ObjectId,
|
||||||
|
teams: Array<{
|
||||||
|
captainUserId: mongoose.Types.ObjectId;
|
||||||
|
members: Array<{ userId: mongoose.Types.ObjectId }>;
|
||||||
|
}>,
|
||||||
|
): Promise<void> {
|
||||||
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
|
const match = await MatchModel.findById(matchId);
|
||||||
|
if (!match) throw new NotFoundException('Match not found.');
|
||||||
|
|
||||||
|
// The queue can contain reauction entries or be corrupted; use the original roster.
|
||||||
|
const expectedIds = match.participants
|
||||||
|
.filter((participant) => !participant.excluded)
|
||||||
|
.map((participant) => participant.userId.toString());
|
||||||
|
const expected = new Set(expectedIds);
|
||||||
|
const assignedIds = teams.flatMap((team) => [
|
||||||
|
team.captainUserId.toString(),
|
||||||
|
...team.members.map((member) => member.userId.toString()),
|
||||||
|
]);
|
||||||
|
const assigned = new Set(assignedIds);
|
||||||
|
const missingUserIds = expectedIds.filter((id) => !assigned.has(id));
|
||||||
|
const unexpectedUserIds = [...assigned].filter((id) => !expected.has(id));
|
||||||
|
if (
|
||||||
|
expected.size === 0 ||
|
||||||
|
expected.size !== expectedIds.length ||
|
||||||
|
assigned.size !== assignedIds.length ||
|
||||||
|
missingUserIds.length > 0 ||
|
||||||
|
unexpectedUserIds.length > 0
|
||||||
|
) {
|
||||||
|
this.logger.error({
|
||||||
|
event: 'auction_roster_validation_failed',
|
||||||
|
matchId: matchId.toString(),
|
||||||
|
expectedCount: expectedIds.length,
|
||||||
|
assignedCount: assignedIds.length,
|
||||||
|
assignedUniqueCount: assigned.size,
|
||||||
|
missingUserIds,
|
||||||
|
unexpectedUserIds,
|
||||||
|
});
|
||||||
|
throw new BadRequestException({
|
||||||
|
code: 'AUCTION_ROSTER_INVALID',
|
||||||
|
message: 'Auction roster validation failed.',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private assertCaptainAssignments(
|
private assertCaptainAssignments(
|
||||||
captains: StartAuctionParams['captains'],
|
captains: StartAuctionParams['captains'],
|
||||||
activeParticipants: Array<{ userId: mongoose.Types.ObjectId }>,
|
activeParticipants: Array<{ userId: mongoose.Types.ObjectId }>,
|
||||||
@@ -2925,54 +2971,16 @@ export class AuctionService {
|
|||||||
const payloadKeys = Array.isArray(reply[1]) ? reply[1].map(String) : [];
|
const payloadKeys = Array.isArray(reply[1]) ? reply[1].map(String) : [];
|
||||||
if (payloadKeys.length === 0) continue;
|
if (payloadKeys.length === 0) continue;
|
||||||
|
|
||||||
const values = await this.auctionRedisService
|
await this.auctionRedisService.evalScript(
|
||||||
.raw()
|
AUCTION_CLEANUP_DURABILITY_SCRIPT,
|
||||||
.sendCommand(['MGET', ...payloadKeys]);
|
[
|
||||||
const payloadKeysToDelete = payloadKeys.filter((payloadKey, index) =>
|
|
||||||
this.shouldDeleteRedisDurabilityPayload(
|
|
||||||
Array.isArray(values) ? values[index] : undefined,
|
|
||||||
expectedAuctionLifecycleId,
|
|
||||||
payloadKey,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
if (payloadKeysToDelete.length === 0) continue;
|
|
||||||
|
|
||||||
await this.auctionRedisService
|
|
||||||
.raw()
|
|
||||||
.sendCommand([
|
|
||||||
'ZREM',
|
|
||||||
keys.durabilityRetryQueueKey,
|
keys.durabilityRetryQueueKey,
|
||||||
...payloadKeysToDelete,
|
|
||||||
]);
|
|
||||||
await this.auctionRedisService
|
|
||||||
.raw()
|
|
||||||
.sendCommand([
|
|
||||||
'ZREM',
|
|
||||||
keys.durabilityDeadLetterQueueKey,
|
keys.durabilityDeadLetterQueueKey,
|
||||||
...payloadKeysToDelete,
|
...payloadKeys,
|
||||||
]);
|
],
|
||||||
await this.auctionRedisService
|
[expectedAuctionLifecycleId ?? ''],
|
||||||
.raw()
|
|
||||||
.sendCommand(['DEL', ...payloadKeysToDelete]);
|
|
||||||
} while (cursor !== '0');
|
|
||||||
}
|
|
||||||
|
|
||||||
private shouldDeleteRedisDurabilityPayload(
|
|
||||||
payloadValue: unknown,
|
|
||||||
expectedAuctionLifecycleId: string | undefined,
|
|
||||||
payloadKey: string,
|
|
||||||
): boolean {
|
|
||||||
if (!expectedAuctionLifecycleId) return true;
|
|
||||||
if (typeof payloadValue !== 'string') return false;
|
|
||||||
try {
|
|
||||||
const payload = JSON.parse(payloadValue) as Record<string, unknown>;
|
|
||||||
return payload.auctionLifecycleId === expectedAuctionLifecycleId;
|
|
||||||
} catch {
|
|
||||||
this.logger.warn(
|
|
||||||
`Failed to parse auction durability payload ${payloadKey}.`,
|
|
||||||
);
|
);
|
||||||
return false;
|
} while (cursor !== '0');
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private enqueueBackgroundOrderEnrichment(params: {
|
private enqueueBackgroundOrderEnrichment(params: {
|
||||||
|
|||||||
@@ -210,21 +210,25 @@ describe('AuctionRedisCommandService', () => {
|
|||||||
|
|
||||||
it('parses apply transition replay and rejected replies', async () => {
|
it('parses apply transition replay and rejected replies', async () => {
|
||||||
await expect(
|
await expect(
|
||||||
makeService(['REPLAY', 'APPLIED', 'transition-1', '2100'])
|
makeService([
|
||||||
.service.applyTransition('match-1', {
|
'REPLAY',
|
||||||
afterAuctionStructureStateJson: '{}',
|
'APPLIED',
|
||||||
auctionHistorySequence: 5,
|
'transition-1',
|
||||||
auctionLifecycleId: 'life-1',
|
'2100',
|
||||||
auctionStateTransitionId: 'transition-1',
|
]).service.applyTransition('match-1', {
|
||||||
broadcastStateRevision: 11,
|
afterAuctionStructureStateJson: '{}',
|
||||||
deadline: { mode: 'none' },
|
auctionHistorySequence: 5,
|
||||||
durabilityPayloadJson: '{}',
|
auctionLifecycleId: 'life-1',
|
||||||
expectedPhase: 'sold',
|
auctionStateTransitionId: 'transition-1',
|
||||||
expectedRevision: 10,
|
broadcastStateRevision: 11,
|
||||||
liveStatePatch: {},
|
deadline: { mode: 'none' },
|
||||||
matchId: 'match-1',
|
durabilityPayloadJson: '{}',
|
||||||
shouldBroadcastState: false,
|
expectedPhase: 'sold',
|
||||||
}),
|
expectedRevision: 10,
|
||||||
|
liveStatePatch: {},
|
||||||
|
matchId: 'match-1',
|
||||||
|
shouldBroadcastState: false,
|
||||||
|
}),
|
||||||
).resolves.toEqual({
|
).resolves.toEqual({
|
||||||
auctionStateTransitionId: 'transition-1',
|
auctionStateTransitionId: 'transition-1',
|
||||||
currentServerTimestampMS: 2100,
|
currentServerTimestampMS: 2100,
|
||||||
@@ -233,21 +237,25 @@ describe('AuctionRedisCommandService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
await expect(
|
await expect(
|
||||||
makeService(['REJECTED', 'CONFLICT', 'transition-1', '2200'])
|
makeService([
|
||||||
.service.applyTransition('match-1', {
|
'REJECTED',
|
||||||
afterAuctionStructureStateJson: '{}',
|
'CONFLICT',
|
||||||
auctionHistorySequence: 5,
|
'transition-1',
|
||||||
auctionLifecycleId: 'life-1',
|
'2200',
|
||||||
auctionStateTransitionId: 'transition-1',
|
]).service.applyTransition('match-1', {
|
||||||
broadcastStateRevision: 11,
|
afterAuctionStructureStateJson: '{}',
|
||||||
deadline: { mode: 'none' },
|
auctionHistorySequence: 5,
|
||||||
durabilityPayloadJson: '{}',
|
auctionLifecycleId: 'life-1',
|
||||||
expectedPhase: 'sold',
|
auctionStateTransitionId: 'transition-1',
|
||||||
expectedRevision: 10,
|
broadcastStateRevision: 11,
|
||||||
liveStatePatch: {},
|
deadline: { mode: 'none' },
|
||||||
matchId: 'match-1',
|
durabilityPayloadJson: '{}',
|
||||||
shouldBroadcastState: false,
|
expectedPhase: 'sold',
|
||||||
}),
|
expectedRevision: 10,
|
||||||
|
liveStatePatch: {},
|
||||||
|
matchId: 'match-1',
|
||||||
|
shouldBroadcastState: false,
|
||||||
|
}),
|
||||||
).resolves.toEqual({
|
).resolves.toEqual({
|
||||||
auctionStateTransitionId: 'transition-1',
|
auctionStateTransitionId: 'transition-1',
|
||||||
code: 'CONFLICT',
|
code: 'CONFLICT',
|
||||||
@@ -288,12 +296,17 @@ describe('AuctionRedisCommandService', () => {
|
|||||||
|
|
||||||
it('parses expire prepare replay and noop replies', async () => {
|
it('parses expire prepare replay and noop replies', async () => {
|
||||||
await expect(
|
await expect(
|
||||||
makeService(['REPLAY', 'passed', 'expire-1', '12', '3100'])
|
makeService([
|
||||||
.service.expirePrepare('match-1', {
|
'REPLAY',
|
||||||
auctionStateTransitionId: 'expire-1',
|
'passed',
|
||||||
bidRoundExpiryRetryDelayMS: 3000,
|
'expire-1',
|
||||||
matchId: 'match-1',
|
'12',
|
||||||
}),
|
'3100',
|
||||||
|
]).service.expirePrepare('match-1', {
|
||||||
|
auctionStateTransitionId: 'expire-1',
|
||||||
|
bidRoundExpiryRetryDelayMS: 3000,
|
||||||
|
matchId: 'match-1',
|
||||||
|
}),
|
||||||
).resolves.toMatchObject({
|
).resolves.toMatchObject({
|
||||||
auctionStateTransitionId: 'expire-1',
|
auctionStateTransitionId: 'expire-1',
|
||||||
bidRoundExpiryDecision: 'passed',
|
bidRoundExpiryDecision: 'passed',
|
||||||
@@ -360,16 +373,19 @@ describe('AuctionRedisCommandService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
await expect(
|
await expect(
|
||||||
makeService(['REJECTED', 'INVALID_PATCH_ARITY', '4200'])
|
makeService([
|
||||||
.service.hydrateState('match-1', {
|
'REJECTED',
|
||||||
auctionHistorySequence: 3,
|
'INVALID_PATCH_ARITY',
|
||||||
auctionLifecycleId: 'life-1',
|
'4200',
|
||||||
maximumBidRoundDurationSeconds: 30,
|
]).service.hydrateState('match-1', {
|
||||||
matchId: 'match-1',
|
auctionHistorySequence: 3,
|
||||||
phase: 'presenting',
|
auctionLifecycleId: 'life-1',
|
||||||
revision: 6,
|
maximumBidRoundDurationSeconds: 30,
|
||||||
structureStateJson: '{}',
|
matchId: 'match-1',
|
||||||
}),
|
phase: 'presenting',
|
||||||
|
revision: 6,
|
||||||
|
structureStateJson: '{}',
|
||||||
|
}),
|
||||||
).resolves.toEqual({
|
).resolves.toEqual({
|
||||||
code: 'INVALID_PATCH_ARITY',
|
code: 'INVALID_PATCH_ARITY',
|
||||||
currentServerTimestampMS: 4200,
|
currentServerTimestampMS: 4200,
|
||||||
|
|||||||
@@ -85,7 +85,9 @@ export function stringifyAuctionRedisStructureState(
|
|||||||
return JSON.stringify(buildAuctionRedisStructureState(input));
|
return JSON.stringify(buildAuctionRedisStructureState(input));
|
||||||
}
|
}
|
||||||
|
|
||||||
function countAuctionTeamMembersIncludingCaptain(team: RedisAuctionTeam): number {
|
function countAuctionTeamMembersIncludingCaptain(
|
||||||
|
team: RedisAuctionTeam,
|
||||||
|
): number {
|
||||||
const userIds = new Set<string>([team.captainUserId.toString()]);
|
const userIds = new Set<string>([team.captainUserId.toString()]);
|
||||||
for (const member of team.members) {
|
for (const member of team.members) {
|
||||||
userIds.add(member.userId.toString());
|
userIds.add(member.userId.toString());
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
import { AuctionRedisService } from './auction-redis.service';
|
import { AuctionRedisService } from './auction-redis.service';
|
||||||
import { AuctionRedisStateReaderService } from './auction-redis-state-reader.service';
|
import { AuctionRedisStateReaderService } from './auction-redis-state-reader.service';
|
||||||
|
|
||||||
function makeService(commandReplies: unknown[], currentServerTimestampMS = 1000) {
|
function makeService(
|
||||||
|
commandReplies: unknown[],
|
||||||
|
currentServerTimestampMS = 1000,
|
||||||
|
) {
|
||||||
const sendCommand = jest
|
const sendCommand = jest
|
||||||
.fn()
|
.fn()
|
||||||
.mockImplementation(() => Promise.resolve(commandReplies.shift()));
|
.mockImplementation(() => Promise.resolve(commandReplies.shift()));
|
||||||
@@ -149,7 +152,9 @@ describe('AuctionRedisStateReaderService', () => {
|
|||||||
[],
|
[],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
await expect(service.readAuctionStateView('match-1')).resolves.toMatchObject({
|
await expect(
|
||||||
|
service.readAuctionStateView('match-1'),
|
||||||
|
).resolves.toMatchObject({
|
||||||
auctionLifecycleId: 'life-1',
|
auctionLifecycleId: 'life-1',
|
||||||
auctionTeams: [],
|
auctionTeams: [],
|
||||||
phase: 'presenting',
|
phase: 'presenting',
|
||||||
@@ -181,7 +186,6 @@ describe('AuctionRedisStateReaderService', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
it('returns null when live or structure state is absent', async () => {
|
it('returns null when live or structure state is absent', async () => {
|
||||||
await expect(
|
await expect(
|
||||||
makeService([[], '{"auctionTeams":[]}', []]).service.readAuctionStateView(
|
makeService([[], '{"auctionTeams":[]}', []]).service.readAuctionStateView(
|
||||||
|
|||||||
@@ -42,12 +42,14 @@ export class AuctionRedisStateReaderService {
|
|||||||
matchId: string,
|
matchId: string,
|
||||||
): Promise<AuctionRedisLiveStateIdentity | null> {
|
): Promise<AuctionRedisLiveStateIdentity | null> {
|
||||||
const keys = buildAuctionRedisKeys(matchId);
|
const keys = buildAuctionRedisKeys(matchId);
|
||||||
const reply = await this.auctionRedisService.raw().sendCommand([
|
const reply = await this.auctionRedisService
|
||||||
'HMGET',
|
.raw()
|
||||||
keys.liveStateKey,
|
.sendCommand([
|
||||||
'auctionLifecycleId',
|
'HMGET',
|
||||||
'revision',
|
keys.liveStateKey,
|
||||||
]);
|
'auctionLifecycleId',
|
||||||
|
'revision',
|
||||||
|
]);
|
||||||
if (!Array.isArray(reply)) return null;
|
if (!Array.isArray(reply)) return null;
|
||||||
const auctionLifecycleId =
|
const auctionLifecycleId =
|
||||||
typeof reply[0] === 'string' && reply[0] ? reply[0] : undefined;
|
typeof reply[0] === 'string' && reply[0] ? reply[0] : undefined;
|
||||||
@@ -68,14 +70,16 @@ export class AuctionRedisStateReaderService {
|
|||||||
): Promise<AuctionRedisBidContext | null> {
|
): Promise<AuctionRedisBidContext | null> {
|
||||||
const keys = buildAuctionRedisKeys(matchId);
|
const keys = buildAuctionRedisKeys(matchId);
|
||||||
const bidderTeamCaptainUserIdField = `team:${bidderTeamIndex}:captainUserId`;
|
const bidderTeamCaptainUserIdField = `team:${bidderTeamIndex}:captainUserId`;
|
||||||
const liveReply = await this.auctionRedisService.raw().sendCommand([
|
const liveReply = await this.auctionRedisService
|
||||||
'HMGET',
|
.raw()
|
||||||
keys.liveStateKey,
|
.sendCommand([
|
||||||
'phase',
|
'HMGET',
|
||||||
'auctionLifecycleId',
|
keys.liveStateKey,
|
||||||
'currentBidRoundPlayerUserId',
|
'phase',
|
||||||
bidderTeamCaptainUserIdField,
|
'auctionLifecycleId',
|
||||||
]);
|
'currentBidRoundPlayerUserId',
|
||||||
|
bidderTeamCaptainUserIdField,
|
||||||
|
]);
|
||||||
if (!Array.isArray(liveReply)) return null;
|
if (!Array.isArray(liveReply)) return null;
|
||||||
|
|
||||||
const phase = stringValue(liveReply[0]);
|
const phase = stringValue(liveReply[0]);
|
||||||
@@ -102,18 +106,23 @@ export class AuctionRedisStateReaderService {
|
|||||||
options: AuctionRedisStateViewReadOptions = {},
|
options: AuctionRedisStateViewReadOptions = {},
|
||||||
): Promise<Record<string, unknown> | null> {
|
): Promise<Record<string, unknown> | null> {
|
||||||
const keys = buildAuctionRedisKeys(matchId);
|
const keys = buildAuctionRedisKeys(matchId);
|
||||||
const [currentServerTimestampMS, liveReply, structureStateJson, bidEntries] =
|
const [
|
||||||
await Promise.all([
|
currentServerTimestampMS,
|
||||||
this.auctionRedisService.getCurrentRedisTimestampMS(),
|
liveReply,
|
||||||
this.auctionRedisService.raw().sendCommand(['HGETALL', keys.liveStateKey]),
|
structureStateJson,
|
||||||
this.auctionRedisService.raw().sendCommand(['GET', keys.structureStateKey]),
|
bidEntries,
|
||||||
this.auctionRedisService.raw().sendCommand([
|
] = await Promise.all([
|
||||||
'LRANGE',
|
this.auctionRedisService.getCurrentRedisTimestampMS(),
|
||||||
keys.bidHistoryKey,
|
this.auctionRedisService
|
||||||
'0',
|
.raw()
|
||||||
'-1',
|
.sendCommand(['HGETALL', keys.liveStateKey]),
|
||||||
]),
|
this.auctionRedisService
|
||||||
]);
|
.raw()
|
||||||
|
.sendCommand(['GET', keys.structureStateKey]),
|
||||||
|
this.auctionRedisService
|
||||||
|
.raw()
|
||||||
|
.sendCommand(['LRANGE', keys.bidHistoryKey, '0', '-1']),
|
||||||
|
]);
|
||||||
|
|
||||||
const liveState = parseHashReply(liveReply, {
|
const liveState = parseHashReply(liveReply, {
|
||||||
includeInternalLiveStateFields:
|
includeInternalLiveStateFields:
|
||||||
@@ -142,7 +151,7 @@ export class AuctionRedisStateReaderService {
|
|||||||
revision: number;
|
revision: number;
|
||||||
},
|
},
|
||||||
shouldForceAuctionStateResync: options.shouldForceAuctionStateResync,
|
shouldForceAuctionStateResync: options.shouldForceAuctionStateResync,
|
||||||
structureState: JSON.parse(structureStateJson) as Record<string, unknown>,
|
structureState: parseJsonRecord(structureStateJson),
|
||||||
});
|
});
|
||||||
view.matchId = matchId;
|
view.matchId = matchId;
|
||||||
if (options.includeInternalLiveStateFields) {
|
if (options.includeInternalLiveStateFields) {
|
||||||
@@ -161,12 +170,9 @@ export class AuctionRedisStateReaderService {
|
|||||||
if (typeof structureStateJson !== 'string' || !structureStateJson) {
|
if (typeof structureStateJson !== 'string' || !structureStateJson) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
const structureState = JSON.parse(structureStateJson) as Record<
|
const structureState = parseJsonRecord(structureStateJson);
|
||||||
string,
|
const auctionTeams: unknown[] = Array.isArray(structureState.auctionTeams)
|
||||||
unknown
|
? (structureState.auctionTeams as unknown[])
|
||||||
>;
|
|
||||||
const auctionTeams = Array.isArray(structureState.auctionTeams)
|
|
||||||
? structureState.auctionTeams
|
|
||||||
: [];
|
: [];
|
||||||
const bidderTeam = auctionTeams.find((entry) => {
|
const bidderTeam = auctionTeams.find((entry) => {
|
||||||
if (!entry || typeof entry !== 'object') return false;
|
if (!entry || typeof entry !== 'object') return false;
|
||||||
@@ -183,6 +189,13 @@ function stringValue(value: unknown): string | undefined {
|
|||||||
return typeof value === 'string' && value ? value : undefined;
|
return typeof value === 'string' && value ? value : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function parseJsonRecord(json: string): Record<string, unknown> {
|
||||||
|
const value: unknown = JSON.parse(json);
|
||||||
|
return typeof value === 'object' && value !== null
|
||||||
|
? (value as Record<string, unknown>)
|
||||||
|
: {};
|
||||||
|
}
|
||||||
|
|
||||||
function parseHashReply(
|
function parseHashReply(
|
||||||
reply: unknown,
|
reply: unknown,
|
||||||
options: { includeInternalLiveStateFields?: boolean } = {},
|
options: { includeInternalLiveStateFields?: boolean } = {},
|
||||||
@@ -210,7 +223,10 @@ function parseHashEntries(
|
|||||||
): Record<string, unknown> {
|
): Record<string, unknown> {
|
||||||
const result: Record<string, unknown> = {};
|
const result: Record<string, unknown> = {};
|
||||||
for (const [field, rawValue] of entries) {
|
for (const [field, rawValue] of entries) {
|
||||||
if (!options.includeInternalLiveStateFields && isInternalLiveStateField(field)) {
|
if (
|
||||||
|
!options.includeInternalLiveStateFields &&
|
||||||
|
isInternalLiveStateField(field)
|
||||||
|
) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const value = String(rawValue);
|
const value = String(rawValue);
|
||||||
|
|||||||
@@ -91,9 +91,7 @@ describe('auction apply transition redis script contract', () => {
|
|||||||
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain(
|
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain(
|
||||||
'shouldBroadcastState',
|
'shouldBroadcastState',
|
||||||
);
|
);
|
||||||
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain(
|
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain("redis.call('SADD'");
|
||||||
"redis.call('SADD'",
|
|
||||||
);
|
|
||||||
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain(
|
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain(
|
||||||
"redis.call('HINCRBY'",
|
"redis.call('HINCRBY'",
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -317,7 +317,7 @@ if actionRequestScopeKey ~= '' then
|
|||||||
actionRequestPrefix .. 'responseServerTimestampMS',
|
actionRequestPrefix .. 'responseServerTimestampMS',
|
||||||
tostring(currentRedisTimestampMS)
|
tostring(currentRedisTimestampMS)
|
||||||
)
|
)
|
||||||
redis.call('RPUSH', auctionActionRequestResultOrderKey, actionRequestScopeKey)
|
-- The reservation already inserted this request into the order list.
|
||||||
end
|
end
|
||||||
|
|
||||||
return {'OK', auctionStateTransitionId, tostring(newRevision), tostring(currentRedisTimestampMS)}
|
return {'OK', auctionStateTransitionId, tostring(newRevision), tostring(currentRedisTimestampMS)}
|
||||||
|
|||||||
@@ -64,9 +64,7 @@ describe('auction bid redis script contract', () => {
|
|||||||
expect(AUCTION_BID_SCRIPT.lua).toContain("redis.call('TIME')");
|
expect(AUCTION_BID_SCRIPT.lua).toContain("redis.call('TIME')");
|
||||||
expect(AUCTION_BID_SCRIPT.lua).toContain("redis.call('HINCRBY'");
|
expect(AUCTION_BID_SCRIPT.lua).toContain("redis.call('HINCRBY'");
|
||||||
expect(AUCTION_BID_SCRIPT.lua).toContain('BID_REQUEST_RESULT_LIMIT');
|
expect(AUCTION_BID_SCRIPT.lua).toContain('BID_REQUEST_RESULT_LIMIT');
|
||||||
expect(AUCTION_BID_SCRIPT.lua).toContain(
|
expect(AUCTION_BID_SCRIPT.lua).toContain('currentHighestBidPointAmount');
|
||||||
'currentHighestBidPointAmount',
|
|
||||||
);
|
|
||||||
expect(AUCTION_BID_SCRIPT.lua).not.toContain('cjson.decode');
|
expect(AUCTION_BID_SCRIPT.lua).not.toContain('cjson.decode');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { defineAuctionRedisScript } from './auction-redis.scripts';
|
||||||
|
|
||||||
|
// Compare the lifecycle and remove the payload and its indexes atomically.
|
||||||
|
export const AUCTION_CLEANUP_DURABILITY_SCRIPT = defineAuctionRedisScript(
|
||||||
|
'auction.cleanupDurability',
|
||||||
|
`
|
||||||
|
local deleted = 0
|
||||||
|
for i = 3, #KEYS do
|
||||||
|
local key = KEYS[i]
|
||||||
|
local keyType = redis.call('TYPE', key).ok
|
||||||
|
local matches = ARGV[1] == ''
|
||||||
|
if not matches and keyType == 'hash' then
|
||||||
|
matches = redis.call('HGET', key, 'auctionLifecycleId') == ARGV[1]
|
||||||
|
elseif not matches and keyType == 'string' then
|
||||||
|
-- Retain compatibility with payloads written before the Hash format.
|
||||||
|
local ok, payload = pcall(cjson.decode, redis.call('GET', key))
|
||||||
|
matches = ok and type(payload) == 'table' and payload.auctionLifecycleId == ARGV[1]
|
||||||
|
end
|
||||||
|
if matches then
|
||||||
|
redis.call('ZREM', KEYS[1], key)
|
||||||
|
redis.call('ZREM', KEYS[2], key)
|
||||||
|
deleted = deleted + redis.call('UNLINK', key)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
return deleted
|
||||||
|
`,
|
||||||
|
);
|
||||||
@@ -3,9 +3,11 @@ import { buildAuctionRedisKeys } from './auction-redis.keys';
|
|||||||
describe('auction redis keys', () => {
|
describe('auction redis keys', () => {
|
||||||
it('builds lifecycle-safe key names from match id', () => {
|
it('builds lifecycle-safe key names from match id', () => {
|
||||||
expect(buildAuctionRedisKeys('match-1')).toMatchObject({
|
expect(buildAuctionRedisKeys('match-1')).toMatchObject({
|
||||||
actionRequestResultOrderKey: 'auction:match-1:auctionActionRequestResultOrder',
|
actionRequestResultOrderKey:
|
||||||
|
'auction:match-1:auctionActionRequestResultOrder',
|
||||||
actionRequestResultsKey: 'auction:match-1:auctionActionRequestResults',
|
actionRequestResultsKey: 'auction:match-1:auctionActionRequestResults',
|
||||||
appliedTransitionIdsKey: 'auction:match-1:appliedAuctionStateTransitionIds',
|
appliedTransitionIdsKey:
|
||||||
|
'auction:match-1:appliedAuctionStateTransitionIds',
|
||||||
bidHistoryKey: 'auction:match-1:auctionBidHistory',
|
bidHistoryKey: 'auction:match-1:auctionBidHistory',
|
||||||
bidRequestResultOrderKey: 'auction:match-1:bidRequestResultOrder',
|
bidRequestResultOrderKey: 'auction:match-1:bidRequestResultOrder',
|
||||||
bidRequestResultsKey: 'auction:match-1:bidRequestResults',
|
bidRequestResultsKey: 'auction:match-1:bidRequestResults',
|
||||||
|
|||||||
@@ -2,10 +2,7 @@ import { Logger, Module } from '@nestjs/common';
|
|||||||
import { createClient } from 'redis';
|
import { createClient } from 'redis';
|
||||||
import { SecretModule } from '../../global/secret/secret.module';
|
import { SecretModule } from '../../global/secret/secret.module';
|
||||||
import { SecretService } from '../../global/secret/secret.service';
|
import { SecretService } from '../../global/secret/secret.service';
|
||||||
import {
|
import { loadRedisClientOptions } from '../../global/redis/redis.config';
|
||||||
assertDistinctRedisInstances,
|
|
||||||
resolveRedisClientOptions,
|
|
||||||
} from '../../global/redis/redis.config';
|
|
||||||
import { AUCTION_REDIS_CLIENT } from './auction-redis.constants';
|
import { AUCTION_REDIS_CLIENT } from './auction-redis.constants';
|
||||||
import {
|
import {
|
||||||
AuctionRedisService,
|
AuctionRedisService,
|
||||||
@@ -14,18 +11,6 @@ import {
|
|||||||
import { AuctionRedisCommandService } from './auction-redis-command.service';
|
import { AuctionRedisCommandService } from './auction-redis-command.service';
|
||||||
import { AuctionRedisStateReaderService } from './auction-redis-state-reader.service';
|
import { AuctionRedisStateReaderService } from './auction-redis-state-reader.service';
|
||||||
|
|
||||||
async function readFirstSecret(
|
|
||||||
secretService: SecretService,
|
|
||||||
keys: string[],
|
|
||||||
): Promise<string | undefined> {
|
|
||||||
for (const key of keys) {
|
|
||||||
const value = await secretService.get<string>(key, '');
|
|
||||||
const trimmed = value.trim();
|
|
||||||
if (trimmed) return trimmed;
|
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [SecretModule],
|
imports: [SecretModule],
|
||||||
providers: [
|
providers: [
|
||||||
@@ -35,48 +20,15 @@ async function readFirstSecret(
|
|||||||
useFactory: async (
|
useFactory: async (
|
||||||
secretService: SecretService,
|
secretService: SecretService,
|
||||||
): Promise<AuctionRedisClient> => {
|
): Promise<AuctionRedisClient> => {
|
||||||
await secretService.ready();
|
|
||||||
|
|
||||||
const [
|
|
||||||
redisUrl,
|
|
||||||
redisEndpoint,
|
|
||||||
auctionRedisUrl,
|
|
||||||
auctionRedisEndpoint,
|
|
||||||
auctionRedisUsername,
|
|
||||||
auctionRedisPassword,
|
|
||||||
] = await Promise.all([
|
|
||||||
readFirstSecret(secretService, ['REDIS_URL', 'GARNET_URL']),
|
|
||||||
readFirstSecret(secretService, ['REDIS_ENDPOINT', 'GARNET_ENDPOINT']),
|
|
||||||
readFirstSecret(secretService, ['AUCTION_REDIS_URL']),
|
|
||||||
readFirstSecret(secretService, ['AUCTION_REDIS_ENDPOINT']),
|
|
||||||
readFirstSecret(secretService, [
|
|
||||||
'AUCTION_REDIS_USERNAME',
|
|
||||||
'AUCTION_REDIS_USERID',
|
|
||||||
]),
|
|
||||||
readFirstSecret(secretService, ['AUCTION_REDIS_PASSWORD']),
|
|
||||||
]);
|
|
||||||
|
|
||||||
const redisOptions = resolveRedisClientOptions({
|
|
||||||
endpoint: redisEndpoint,
|
|
||||||
endpointEnvName: 'REDIS_ENDPOINT',
|
|
||||||
url: redisUrl,
|
|
||||||
urlEnvName: 'REDIS_URL',
|
|
||||||
});
|
|
||||||
const auctionRedisOptions = resolveRedisClientOptions({
|
|
||||||
endpoint: auctionRedisEndpoint,
|
|
||||||
endpointEnvName: 'AUCTION_REDIS_ENDPOINT',
|
|
||||||
password: auctionRedisPassword,
|
|
||||||
url: auctionRedisUrl,
|
|
||||||
urlEnvName: 'AUCTION_REDIS_URL',
|
|
||||||
username: auctionRedisUsername,
|
|
||||||
});
|
|
||||||
assertDistinctRedisInstances(redisOptions.url, auctionRedisOptions.url);
|
|
||||||
|
|
||||||
const logger = new Logger('AuctionRedisClient');
|
const logger = new Logger('AuctionRedisClient');
|
||||||
const client = createClient(auctionRedisOptions);
|
const client = createClient(
|
||||||
client.on('error', (error) => {
|
await loadRedisClientOptions(secretService),
|
||||||
|
);
|
||||||
|
client.on('error', (error: unknown) => {
|
||||||
logger.error(
|
logger.error(
|
||||||
`Auction Redis client error: ${error?.message ?? error}`,
|
`Auction Redis client error: ${
|
||||||
|
error instanceof Error ? error.message : String(error)
|
||||||
|
}`,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -15,7 +15,9 @@ function makeService(sendCommand: jest.Mock) {
|
|||||||
|
|
||||||
describe('AuctionRedisService', () => {
|
describe('AuctionRedisService', () => {
|
||||||
it('uses Redis TIME as the timestamp source', async () => {
|
it('uses Redis TIME as the timestamp source', async () => {
|
||||||
const service = makeService(jest.fn().mockResolvedValue(['1781700000', '123000']));
|
const service = makeService(
|
||||||
|
jest.fn().mockResolvedValue(['1781700000', '123000']),
|
||||||
|
);
|
||||||
|
|
||||||
await expect(service.getCurrentRedisTimestampMS()).resolves.toBe(
|
await expect(service.getCurrentRedisTimestampMS()).resolves.toBe(
|
||||||
1_781_700_000_123,
|
1_781_700_000_123,
|
||||||
|
|||||||
@@ -22,7 +22,11 @@ export class AuctionRedisNoscriptError extends Error {
|
|||||||
function isNoscriptError(error: unknown): boolean {
|
function isNoscriptError(error: unknown): boolean {
|
||||||
if (error instanceof AuctionRedisNoscriptError) return true;
|
if (error instanceof AuctionRedisNoscriptError) return true;
|
||||||
const message =
|
const message =
|
||||||
error instanceof Error ? error.message : typeof error === 'string' ? error : '';
|
error instanceof Error
|
||||||
|
? error.message
|
||||||
|
: typeof error === 'string'
|
||||||
|
? error
|
||||||
|
: '';
|
||||||
return /\bNOSCRIPT\b/iu.test(message);
|
return /\bNOSCRIPT\b/iu.test(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,9 +85,15 @@ export class AuctionRedisService implements OnModuleDestroy {
|
|||||||
if (!isNoscriptError(error)) throw error;
|
if (!isNoscriptError(error)) throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
const loadedSha = String(
|
const loadedShaReply = await this.client.sendCommand([
|
||||||
await this.client.sendCommand(['SCRIPT', 'LOAD', params.script]),
|
'SCRIPT',
|
||||||
);
|
'LOAD',
|
||||||
|
params.script,
|
||||||
|
]);
|
||||||
|
if (typeof loadedShaReply !== 'string') {
|
||||||
|
throw new Error('Redis SCRIPT LOAD returned a non-string SHA.');
|
||||||
|
}
|
||||||
|
const loadedSha = loadedShaReply;
|
||||||
return (await this.client.sendCommand(
|
return (await this.client.sendCommand(
|
||||||
buildEvalShaCommand(loadedSha, params.keys, params.values),
|
buildEvalShaCommand(loadedSha, params.keys, params.values),
|
||||||
)) as T;
|
)) as T;
|
||||||
@@ -107,7 +117,7 @@ export class AuctionRedisService implements OnModuleDestroy {
|
|||||||
token: string,
|
token: string,
|
||||||
ttlMS: number,
|
ttlMS: number,
|
||||||
): Promise<boolean> {
|
): Promise<boolean> {
|
||||||
const result = await this.client.sendCommand([
|
const result = await this.client.sendCommand<string | null>([
|
||||||
'SET',
|
'SET',
|
||||||
key,
|
key,
|
||||||
token,
|
token,
|
||||||
@@ -115,17 +125,11 @@ export class AuctionRedisService implements OnModuleDestroy {
|
|||||||
String(ttlMS),
|
String(ttlMS),
|
||||||
'NX',
|
'NX',
|
||||||
]);
|
]);
|
||||||
return String(result) === 'OK';
|
return result === 'OK';
|
||||||
}
|
}
|
||||||
|
|
||||||
public async releaseTokenLock(key: string, token: string): Promise<boolean> {
|
public async releaseTokenLock(key: string, token: string): Promise<boolean> {
|
||||||
const result = await this.client.sendCommand([
|
const result = await this.client.sendCommand(['DELEX', key, 'IFEQ', token]);
|
||||||
'EVAL',
|
|
||||||
'if redis.call("GET", KEYS[1]) == ARGV[1] then return redis.call("DEL", KEYS[1]) else return 0 end',
|
|
||||||
'1',
|
|
||||||
key,
|
|
||||||
token,
|
|
||||||
]);
|
|
||||||
return Number(result) === 1;
|
return Number(result) === 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -100,9 +100,7 @@ describe('auction redis state assembly', () => {
|
|||||||
'1000',
|
'1000',
|
||||||
]);
|
]);
|
||||||
expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain("redis.call('TIME')");
|
expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain("redis.call('TIME')");
|
||||||
expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain(
|
expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain('INVALID_PATCH_ARITY');
|
||||||
'INVALID_PATCH_ARITY',
|
|
||||||
);
|
|
||||||
expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain(
|
expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain(
|
||||||
'mongoRevision > redisRevision',
|
'mongoRevision > redisRevision',
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -78,9 +78,7 @@ export function assembleAuctionViewFromRedisState(
|
|||||||
return {
|
return {
|
||||||
...params.structureState,
|
...params.structureState,
|
||||||
...params.liveState,
|
...params.liveState,
|
||||||
auctionBidHistory: params.auctionBidHistoryEntries.map((entry) =>
|
auctionBidHistory: params.auctionBidHistoryEntries.map(parseJsonValue),
|
||||||
JSON.parse(entry),
|
|
||||||
),
|
|
||||||
canPlaceBidInCurrentBidRound: !isExpiring,
|
canPlaceBidInCurrentBidRound: !isExpiring,
|
||||||
currentServerTimestampMS: params.currentServerTimestampMS,
|
currentServerTimestampMS: params.currentServerTimestampMS,
|
||||||
isAuctionStateTransitionInProgress: isExpiring,
|
isAuctionStateTransitionInProgress: isExpiring,
|
||||||
@@ -90,6 +88,11 @@ export function assembleAuctionViewFromRedisState(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function parseJsonValue(json: string): unknown {
|
||||||
|
const value: unknown = JSON.parse(json);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
export function buildHydrateAuctionStateScriptInvocation(
|
export function buildHydrateAuctionStateScriptInvocation(
|
||||||
keys: AuctionRedisKeys,
|
keys: AuctionRedisKeys,
|
||||||
input: HydrateAuctionStateScriptInput,
|
input: HydrateAuctionStateScriptInput,
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
import type { JWTHeaderParameters, JWTPayload } from 'jose';
|
import type { JWTHeaderParameters, JWTPayload } from 'jose';
|
||||||
import type {
|
import type { IdentityDocument, UserDocument } from '../global/database/schema';
|
||||||
IdentityDocument,
|
|
||||||
UserDocument,
|
|
||||||
} from '../global/database/schema';
|
|
||||||
import type { IdentityProviderName } from './jwt.service';
|
import type { IdentityProviderName } from './jwt.service';
|
||||||
|
|
||||||
declare module 'express' {
|
declare module 'express' {
|
||||||
|
|||||||
@@ -2,10 +2,7 @@ import { Injectable } from '@nestjs/common';
|
|||||||
import type { Request } from 'express';
|
import type { Request } from 'express';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
import {
|
import { IdentityDocument, UserDocument } from '../global/database/schema';
|
||||||
IdentityDocument,
|
|
||||||
UserDocument,
|
|
||||||
} from '../global/database/schema';
|
|
||||||
import { SecretService } from '../global/secret/secret.service';
|
import { SecretService } from '../global/secret/secret.service';
|
||||||
import './auth-request';
|
import './auth-request';
|
||||||
|
|
||||||
|
|||||||
@@ -26,8 +26,7 @@ export class JwtAuthGuard implements CanActivate {
|
|||||||
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
|
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
|
||||||
[context.getHandler(), context.getClass()],
|
[context.getHandler(), context.getClass()],
|
||||||
);
|
);
|
||||||
const authz = request.headers?.authorization;
|
const authzHeader = request.get('authorization');
|
||||||
const authzHeader = Array.isArray(authz) ? authz[0] : authz;
|
|
||||||
|
|
||||||
if (!authzHeader) {
|
if (!authzHeader) {
|
||||||
const fallback =
|
const fallback =
|
||||||
@@ -74,7 +73,7 @@ export class JwtAuthGuard implements CanActivate {
|
|||||||
|
|
||||||
private pickIdPFromToken(token: string): IdentityProviderName {
|
private pickIdPFromToken(token: string): IdentityProviderName {
|
||||||
try {
|
try {
|
||||||
const { iss } = decodeJwt(token) as { iss?: string };
|
const { iss } = decodeJwt(token);
|
||||||
if (!iss) {
|
if (!iss) {
|
||||||
throw new Error('Token has no issuer (iss) claim');
|
throw new Error('Token has no issuer (iss) claim');
|
||||||
}
|
}
|
||||||
@@ -84,7 +83,8 @@ export class JwtAuthGuard implements CanActivate {
|
|||||||
}
|
}
|
||||||
throw new Error(`Unknown issuer: ${iss}`);
|
throw new Error(`Unknown issuer: ${iss}`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const message = err instanceof Error ? err.message : 'Unable to decode token';
|
const message =
|
||||||
|
err instanceof Error ? err.message : 'Unable to decode token';
|
||||||
throw new UnauthorizedException(message);
|
throw new UnauthorizedException(message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,11 +35,13 @@ export class JwtService {
|
|||||||
throw new Error('Empty token');
|
throw new Error('Empty token');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (identityProvider !== 'MICROSOFT_ENTRAID') {
|
const provider =
|
||||||
throw new Error(`Identity provider not configured: ${identityProvider}`);
|
identityProvider === 'MICROSOFT_ENTRAID'
|
||||||
|
? await this.getEntraConfig()
|
||||||
|
: undefined;
|
||||||
|
if (!provider) {
|
||||||
|
throw new Error('Identity provider not configured.');
|
||||||
}
|
}
|
||||||
|
|
||||||
const provider = await this.getEntraConfig();
|
|
||||||
const result = await jwtVerify(token, provider.jwks, {
|
const result = await jwtVerify(token, provider.jwks, {
|
||||||
issuer: provider.issuer,
|
issuer: provider.issuer,
|
||||||
audience: provider.audience,
|
audience: provider.audience,
|
||||||
@@ -48,14 +50,22 @@ export class JwtService {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const { payload, protectedHeader } = result;
|
const { payload, protectedHeader } = result;
|
||||||
if (!provider.allowedAlgs.includes(protectedHeader.alg as string)) {
|
if (!provider.allowedAlgs.includes(protectedHeader.alg)) {
|
||||||
throw new Error(`Unexpected alg: ${protectedHeader.alg}`);
|
throw new Error(`Unexpected alg: ${protectedHeader.alg}`);
|
||||||
}
|
}
|
||||||
if (payload.ver && payload.ver !== '2.0') {
|
if (
|
||||||
throw new Error(`Unsupported Entra token version: ${payload.ver}`);
|
payload.ver !== undefined &&
|
||||||
|
(typeof payload.ver !== 'string' || payload.ver !== '2.0')
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
`Unsupported Entra token version: ${formatClaimValue(payload.ver)}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (payload.tid && payload.tid !== provider.tenantId) {
|
if (
|
||||||
throw new Error(`Unexpected tenant: ${payload.tid}`);
|
payload.tid !== undefined &&
|
||||||
|
(typeof payload.tid !== 'string' || payload.tid !== provider.tenantId)
|
||||||
|
) {
|
||||||
|
throw new Error(`Unexpected tenant: ${formatClaimValue(payload.tid)}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
@@ -98,3 +108,16 @@ export class JwtService {
|
|||||||
return this.entraConfig;
|
return this.entraConfig;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function formatClaimValue(value: unknown): string {
|
||||||
|
if (
|
||||||
|
typeof value === 'string' ||
|
||||||
|
typeof value === 'number' ||
|
||||||
|
typeof value === 'boolean' ||
|
||||||
|
typeof value === 'bigint'
|
||||||
|
) {
|
||||||
|
return String(value);
|
||||||
|
}
|
||||||
|
if (value === null) return 'null';
|
||||||
|
return JSON.stringify(value) ?? typeof value;
|
||||||
|
}
|
||||||
@@ -7,7 +7,7 @@ import {
|
|||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { Reflector } from '@nestjs/core';
|
import { Reflector } from '@nestjs/core';
|
||||||
import type { Request } from 'express';
|
import type { Request } from 'express';
|
||||||
import { CommunityRole, UserDocument } from '../global/database/schema';
|
import type { CommunityRole } from '../global/database/schema';
|
||||||
import { ROLES_KEY } from './roles.decorator';
|
import { ROLES_KEY } from './roles.decorator';
|
||||||
import './auth-request';
|
import './auth-request';
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@ export class RolesGuard implements CanActivate {
|
|||||||
if (!requiredRoles || requiredRoles.length === 0) return true;
|
if (!requiredRoles || requiredRoles.length === 0) return true;
|
||||||
|
|
||||||
const req = context.switchToHttp().getRequest<Request>();
|
const req = context.switchToHttp().getRequest<Request>();
|
||||||
const user = req.user as UserDocument | undefined;
|
const user = req.user;
|
||||||
if (!user && req.identity) {
|
if (!user && req.identity) {
|
||||||
throw new ForbiddenException('No membership in this community.');
|
throw new ForbiddenException('No membership in this community.');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { ConnectionService } from '../global/database/connection.service';
|
|||||||
import { IdentityDocument, UserDocument } from '../global/database/schema';
|
import { IdentityDocument, UserDocument } from '../global/database/schema';
|
||||||
import { UserResolverGuard } from './user-resolver.guard';
|
import { UserResolverGuard } from './user-resolver.guard';
|
||||||
import './auth-request';
|
import './auth-request';
|
||||||
|
import type { Request } from 'express';
|
||||||
|
|
||||||
function createContext(request: Record<string, unknown>): ExecutionContext {
|
function createContext(request: Record<string, unknown>): ExecutionContext {
|
||||||
return {
|
return {
|
||||||
@@ -24,7 +25,7 @@ describe('UserResolverGuard', () => {
|
|||||||
const connectionService = {
|
const connectionService = {
|
||||||
getModel: jest.fn().mockResolvedValue({ findOne }),
|
getModel: jest.fn().mockResolvedValue({ findOne }),
|
||||||
} as unknown as ConnectionService;
|
} as unknown as ConnectionService;
|
||||||
const request = {
|
const request: Pick<Request, 'params' | 'identity' | 'user'> = {
|
||||||
params: { communityId: communityId.toString() },
|
params: { communityId: communityId.toString() },
|
||||||
identity: { _id: identityId } as IdentityDocument,
|
identity: { _id: identityId } as IdentityDocument,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -7,9 +7,10 @@ import {
|
|||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class ParseObjectIdPipe
|
export class ParseObjectIdPipe implements PipeTransform<
|
||||||
implements PipeTransform<string, mongoose.Types.ObjectId>
|
string,
|
||||||
{
|
mongoose.Types.ObjectId
|
||||||
|
> {
|
||||||
public transform(
|
public transform(
|
||||||
value: string,
|
value: string,
|
||||||
metadata: ArgumentMetadata,
|
metadata: ArgumentMetadata,
|
||||||
|
|||||||
@@ -1,8 +1,67 @@
|
|||||||
import { Injectable, Logger } from '@nestjs/common';
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { randomUUID } from 'crypto';
|
||||||
import { RedisService } from '../global/redis/redis.service';
|
import { RedisService } from '../global/redis/redis.service';
|
||||||
|
|
||||||
const COMMUNITY_STATS_TTL_SECONDS = 5 * 60;
|
const COMMUNITY_STATS_TTL_SECONDS = 5 * 60;
|
||||||
const COMMUNITY_STATS_DETAIL_TTL_SECONDS = 24 * 60 * 60;
|
const COMMUNITY_STATS_DETAIL_TTL_SECONDS = 24 * 60 * 60;
|
||||||
|
const CACHE_SCOPES = [
|
||||||
|
'matches',
|
||||||
|
'leaderboard',
|
||||||
|
'teamInsights',
|
||||||
|
'matchDetail',
|
||||||
|
'userInternal',
|
||||||
|
] as const;
|
||||||
|
type CacheScope = (typeof CACHE_SCOPES)[number];
|
||||||
|
|
||||||
|
function communityPrefix(communityId: string): string {
|
||||||
|
return `riot:communitystats:v2:{${communityId}}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CommunityStatsCacheKey {
|
||||||
|
public readonly generationKey: string;
|
||||||
|
public readonly hashKey: string;
|
||||||
|
public generation?: string;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
communityId: string,
|
||||||
|
scope: CacheScope,
|
||||||
|
public readonly field: string,
|
||||||
|
) {
|
||||||
|
const prefix = communityPrefix(communityId);
|
||||||
|
this.generationKey = `${prefix}:generation`;
|
||||||
|
this.hashKey = `${prefix}:${scope}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
public get identity(): string {
|
||||||
|
return JSON.stringify([this.hashKey, this.generation, this.field]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const READ_CACHE_SCRIPT = `
|
||||||
|
local generation = redis.call('GET', KEYS[1])
|
||||||
|
if not generation then
|
||||||
|
generation = ARGV[1]
|
||||||
|
redis.call('SET', KEYS[1], generation)
|
||||||
|
end
|
||||||
|
return {generation, redis.call('HGET', KEYS[2], ARGV[2])}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const WRITE_CACHE_SCRIPT = `
|
||||||
|
if redis.call('GET', KEYS[1]) ~= ARGV[1] then return 0 end
|
||||||
|
redis.call('HSETEX', KEYS[2], 'EX', ARGV[4], 'FIELDS', 1, ARGV[2], ARGV[3])
|
||||||
|
return 1
|
||||||
|
`;
|
||||||
|
|
||||||
|
const INVALIDATE_CACHE_SCRIPT = `
|
||||||
|
-- A fill started before invalidation cannot publish into the new generation.
|
||||||
|
redis.call('SET', KEYS[1], ARGV[1])
|
||||||
|
local deleted = 0
|
||||||
|
for i = 2, #KEYS do
|
||||||
|
deleted = deleted + redis.call('HLEN', KEYS[i])
|
||||||
|
redis.call('UNLINK', KEYS[i])
|
||||||
|
end
|
||||||
|
return deleted
|
||||||
|
`;
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class CommunityStatsCacheService {
|
export class CommunityStatsCacheService {
|
||||||
@@ -10,48 +69,72 @@ export class CommunityStatsCacheService {
|
|||||||
|
|
||||||
constructor(private readonly redisService: RedisService) {}
|
constructor(private readonly redisService: RedisService) {}
|
||||||
|
|
||||||
public get<T>(key: string): Promise<T | null> {
|
public async get<T>(key: CommunityStatsCacheKey): Promise<T | null> {
|
||||||
return this.redisService.getJson<T>(key);
|
const reply = await this.redisService
|
||||||
|
.raw()
|
||||||
|
.sendCommand<
|
||||||
|
[string, string | null]
|
||||||
|
>(['EVAL', READ_CACHE_SCRIPT, '2', key.generationKey, key.hashKey, randomUUID(), key.field]);
|
||||||
|
key.generation = reply[0];
|
||||||
|
if (!reply[1]) return null;
|
||||||
|
try {
|
||||||
|
return JSON.parse(reply[1]) as T;
|
||||||
|
} catch {
|
||||||
|
this.logger.warn(
|
||||||
|
`Failed to parse community stats cache field in ${key.hashKey}.`,
|
||||||
|
);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public set(
|
public async set(
|
||||||
key: string,
|
key: CommunityStatsCacheKey,
|
||||||
value: unknown,
|
value: unknown,
|
||||||
ttlSeconds = COMMUNITY_STATS_TTL_SECONDS,
|
ttlSeconds = COMMUNITY_STATS_TTL_SECONDS,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
return this.redisService.setJson(key, value, ttlSeconds);
|
if (!key.generation)
|
||||||
|
throw new Error(
|
||||||
|
'Read the cache generation before starting a cache fill.',
|
||||||
|
);
|
||||||
|
if (!Number.isInteger(ttlSeconds) || ttlSeconds <= 0)
|
||||||
|
throw new Error('Cache TTL must be a positive integer.');
|
||||||
|
await this.redisService
|
||||||
|
.raw()
|
||||||
|
.sendCommand([
|
||||||
|
'EVAL',
|
||||||
|
WRITE_CACHE_SCRIPT,
|
||||||
|
'2',
|
||||||
|
key.generationKey,
|
||||||
|
key.hashKey,
|
||||||
|
key.generation,
|
||||||
|
key.field,
|
||||||
|
JSON.stringify(value),
|
||||||
|
String(ttlSeconds),
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public setDetail(key: string, value: unknown): Promise<void> {
|
public setDetail(key: CommunityStatsCacheKey, value: unknown): Promise<void> {
|
||||||
return this.set(key, value, COMMUNITY_STATS_DETAIL_TTL_SECONDS);
|
return this.set(key, value, COMMUNITY_STATS_DETAIL_TTL_SECONDS);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async invalidateCommunity(communityId: string): Promise<number> {
|
public async invalidateCommunity(communityId: string): Promise<number> {
|
||||||
const prefix = `riot:communitystats:`;
|
const prefix = communityPrefix(communityId);
|
||||||
const match = `${prefix}*${communityId}*`;
|
const deleted = Number(
|
||||||
const client = this.redisService.raw();
|
await this.redisService
|
||||||
let cursor = '0';
|
.raw()
|
||||||
let deleted = 0;
|
.sendCommand([
|
||||||
|
'EVAL',
|
||||||
do {
|
INVALIDATE_CACHE_SCRIPT,
|
||||||
const reply = (await client.sendCommand([
|
String(CACHE_SCOPES.length + 1),
|
||||||
'SCAN',
|
`${prefix}:generation`,
|
||||||
cursor,
|
...CACHE_SCOPES.map((scope) => `${prefix}:${scope}`),
|
||||||
'MATCH',
|
randomUUID(),
|
||||||
match,
|
]),
|
||||||
'COUNT',
|
);
|
||||||
'100',
|
|
||||||
])) as [string, string[]];
|
|
||||||
cursor = reply[0];
|
|
||||||
const keys = reply[1] ?? [];
|
|
||||||
if (keys.length > 0) {
|
|
||||||
deleted += await client.del(keys);
|
|
||||||
}
|
|
||||||
} while (cursor !== '0');
|
|
||||||
|
|
||||||
if (deleted > 0) {
|
if (deleted > 0) {
|
||||||
this.logger.debug(
|
this.logger.debug(
|
||||||
`Invalidated ${deleted} community stats cache keys for ${communityId}.`,
|
`Invalidated ${deleted} community stats cache entries for ${communityId}.`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return deleted;
|
return deleted;
|
||||||
|
|||||||
@@ -23,7 +23,14 @@ export class CommunityStatsController {
|
|||||||
) {
|
) {
|
||||||
return this.communityStatsService.getMatches({
|
return this.communityStatsService.getMatches({
|
||||||
communityId,
|
communityId,
|
||||||
filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }),
|
filters: this.toFilters({
|
||||||
|
seasonId,
|
||||||
|
from,
|
||||||
|
to,
|
||||||
|
championId,
|
||||||
|
cursor,
|
||||||
|
limit,
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -85,7 +92,14 @@ export class CommunityStatsController {
|
|||||||
return this.communityStatsService.getUserInternalHistory({
|
return this.communityStatsService.getUserInternalHistory({
|
||||||
communityId,
|
communityId,
|
||||||
userId,
|
userId,
|
||||||
filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }),
|
filters: this.toFilters({
|
||||||
|
seasonId,
|
||||||
|
from,
|
||||||
|
to,
|
||||||
|
championId,
|
||||||
|
cursor,
|
||||||
|
limit,
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
import { CommunityStatsCacheService } from './community-stats-cache.service';
|
import {
|
||||||
|
CommunityStatsCacheKey,
|
||||||
|
CommunityStatsCacheService,
|
||||||
|
} from './community-stats-cache.service';
|
||||||
import { CommunityStatsService } from './community-stats.service';
|
import { CommunityStatsService } from './community-stats.service';
|
||||||
import type {
|
import type {
|
||||||
InternalMatchCardView,
|
InternalMatchCardView,
|
||||||
@@ -281,7 +284,7 @@ describe('CommunityStatsService', () => {
|
|||||||
expect(setDetail).toHaveBeenCalledTimes(2);
|
expect(setDetail).toHaveBeenCalledTimes(2);
|
||||||
expect(setDetail).toHaveBeenNthCalledWith(
|
expect(setDetail).toHaveBeenNthCalledWith(
|
||||||
2,
|
2,
|
||||||
expect.stringContaining(':r4:'),
|
expect.objectContaining({ field: expect.stringContaining(':r4:') }),
|
||||||
invalidCheckpointResponse,
|
invalidCheckpointResponse,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -338,7 +341,7 @@ describe('CommunityStatsService', () => {
|
|||||||
const set = jest
|
const set = jest
|
||||||
.fn()
|
.fn()
|
||||||
.mockImplementation(
|
.mockImplementation(
|
||||||
(_key: string, value: InternalMatchDetailResponse) => {
|
(_key: CommunityStatsCacheKey, value: InternalMatchDetailResponse) => {
|
||||||
cachedResponse = value;
|
cachedResponse = value;
|
||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
},
|
},
|
||||||
@@ -346,7 +349,7 @@ describe('CommunityStatsService', () => {
|
|||||||
const setDetail = jest
|
const setDetail = jest
|
||||||
.fn()
|
.fn()
|
||||||
.mockImplementation(
|
.mockImplementation(
|
||||||
(_key: string, value: InternalMatchDetailResponse) => {
|
(_key: CommunityStatsCacheKey, value: InternalMatchDetailResponse) => {
|
||||||
cachedResponse = value;
|
cachedResponse = value;
|
||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
},
|
},
|
||||||
@@ -377,7 +380,7 @@ describe('CommunityStatsService', () => {
|
|||||||
expect(backedOff).toBe(fallback);
|
expect(backedOff).toBe(fallback);
|
||||||
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
|
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
|
||||||
expect(set).toHaveBeenCalledWith(
|
expect(set).toHaveBeenCalledWith(
|
||||||
expect.stringContaining(':r4:'),
|
expect.objectContaining({ field: expect.stringContaining(':r4:') }),
|
||||||
fallback,
|
fallback,
|
||||||
60,
|
60,
|
||||||
);
|
);
|
||||||
@@ -389,7 +392,7 @@ describe('CommunityStatsService', () => {
|
|||||||
expect(buildAndUpsert).toHaveBeenCalledTimes(2);
|
expect(buildAndUpsert).toHaveBeenCalledTimes(2);
|
||||||
expect(setDetail).toHaveBeenCalledTimes(1);
|
expect(setDetail).toHaveBeenCalledTimes(1);
|
||||||
expect(setDetail).toHaveBeenCalledWith(
|
expect(setDetail).toHaveBeenCalledWith(
|
||||||
expect.stringContaining(':r4:'),
|
expect.objectContaining({ field: expect.stringContaining(':r4:') }),
|
||||||
recovered,
|
recovered,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -547,7 +550,9 @@ describe('CommunityStatsService', () => {
|
|||||||
).toEqual([matchId.toString()]);
|
).toEqual([matchId.toString()]);
|
||||||
expect(buildBaseDataset).not.toHaveBeenCalled();
|
expect(buildBaseDataset).not.toHaveBeenCalled();
|
||||||
expect(cacheService.set).toHaveBeenCalledWith(
|
expect(cacheService.set).toHaveBeenCalledWith(
|
||||||
expect.stringContaining(`userInternal:v3:${userId.toString()}`),
|
expect.objectContaining({
|
||||||
|
field: expect.stringContaining(`userInternal:v3:${userId.toString()}`),
|
||||||
|
}),
|
||||||
response,
|
response,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -11,7 +11,10 @@ import type {
|
|||||||
HistorySeasonDto,
|
HistorySeasonDto,
|
||||||
RecentMatchView,
|
RecentMatchView,
|
||||||
} from '../match-history/match-history.types';
|
} from '../match-history/match-history.types';
|
||||||
import { CommunityStatsCacheService } from './community-stats-cache.service';
|
import {
|
||||||
|
CommunityStatsCacheKey,
|
||||||
|
CommunityStatsCacheService,
|
||||||
|
} from './community-stats-cache.service';
|
||||||
import type {
|
import type {
|
||||||
CommunityStatsFilters,
|
CommunityStatsFilters,
|
||||||
InternalMatchCardView,
|
InternalMatchCardView,
|
||||||
@@ -219,21 +222,25 @@ export class CommunityStatsService {
|
|||||||
communityId: mongoose.Types.ObjectId;
|
communityId: mongoose.Types.ObjectId;
|
||||||
matchId: mongoose.Types.ObjectId;
|
matchId: mongoose.Types.ObjectId;
|
||||||
}): Promise<InternalMatchDetailResponse> {
|
}): Promise<InternalMatchDetailResponse> {
|
||||||
const key = `riot:communitystats:matchDetail:v${MATCH_STATS_BUILDER_VERSION}:r${MATCH_DETAIL_RESPONSE_CACHE_VERSION}:${params.communityId.toString()}:${params.matchId.toString()}`;
|
const key = new CommunityStatsCacheKey(
|
||||||
|
params.communityId.toString(),
|
||||||
|
'matchDetail',
|
||||||
|
`v${MATCH_STATS_BUILDER_VERSION}:r${MATCH_DETAIL_RESPONSE_CACHE_VERSION}:${params.matchId.toString()}`,
|
||||||
|
);
|
||||||
const cached =
|
const cached =
|
||||||
await this.cacheService.get<InternalMatchDetailResponse>(key);
|
await this.cacheService.get<InternalMatchDetailResponse>(key);
|
||||||
if (cached && isCompleteMatchDetailResponse(cached)) return cached;
|
if (cached && isCompleteMatchDetailResponse(cached)) return cached;
|
||||||
|
|
||||||
const inFlight = this.matchDetailInFlight.get(key);
|
const inFlight = this.matchDetailInFlight.get(key.identity);
|
||||||
if (inFlight) return inFlight;
|
if (inFlight) return inFlight;
|
||||||
|
|
||||||
const promise = this.buildMatchDetailResponse(params, key);
|
const promise = this.buildMatchDetailResponse(params, key);
|
||||||
this.matchDetailInFlight.set(key, promise);
|
this.matchDetailInFlight.set(key.identity, promise);
|
||||||
try {
|
try {
|
||||||
return await promise;
|
return await promise;
|
||||||
} finally {
|
} finally {
|
||||||
if (this.matchDetailInFlight.get(key) === promise) {
|
if (this.matchDetailInFlight.get(key.identity) === promise) {
|
||||||
this.matchDetailInFlight.delete(key);
|
this.matchDetailInFlight.delete(key.identity);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -243,7 +250,7 @@ export class CommunityStatsService {
|
|||||||
communityId: mongoose.Types.ObjectId;
|
communityId: mongoose.Types.ObjectId;
|
||||||
matchId: mongoose.Types.ObjectId;
|
matchId: mongoose.Types.ObjectId;
|
||||||
},
|
},
|
||||||
key: string,
|
key: CommunityStatsCacheKey,
|
||||||
): Promise<InternalMatchDetailResponse> {
|
): Promise<InternalMatchDetailResponse> {
|
||||||
const dataset = await this.buildBaseDataset(params.communityId, {
|
const dataset = await this.buildBaseDataset(params.communityId, {
|
||||||
seasonId: 'all',
|
seasonId: 'all',
|
||||||
@@ -346,16 +353,16 @@ export class CommunityStatsService {
|
|||||||
|
|
||||||
// Auction viewers can all request the same next player's internal history
|
// Auction viewers can all request the same next player's internal history
|
||||||
// at once. Coalesce local cache misses so one player change does one DB read.
|
// at once. Coalesce local cache misses so one player change does one DB read.
|
||||||
const inFlight = this.userInternalHistoryInFlight.get(key);
|
const inFlight = this.userInternalHistoryInFlight.get(key.identity);
|
||||||
if (inFlight) return inFlight;
|
if (inFlight) return inFlight;
|
||||||
|
|
||||||
const promise = this.buildUserInternalHistoryResponse(params, key);
|
const promise = this.buildUserInternalHistoryResponse(params, key);
|
||||||
this.userInternalHistoryInFlight.set(key, promise);
|
this.userInternalHistoryInFlight.set(key.identity, promise);
|
||||||
try {
|
try {
|
||||||
return await promise;
|
return await promise;
|
||||||
} finally {
|
} finally {
|
||||||
if (this.userInternalHistoryInFlight.get(key) === promise) {
|
if (this.userInternalHistoryInFlight.get(key.identity) === promise) {
|
||||||
this.userInternalHistoryInFlight.delete(key);
|
this.userInternalHistoryInFlight.delete(key.identity);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -428,7 +435,7 @@ export class CommunityStatsService {
|
|||||||
userId: mongoose.Types.ObjectId;
|
userId: mongoose.Types.ObjectId;
|
||||||
filters: CommunityStatsFilters;
|
filters: CommunityStatsFilters;
|
||||||
},
|
},
|
||||||
cacheKey: string,
|
cacheKey: CommunityStatsCacheKey,
|
||||||
): Promise<UserInternalHistoryResponse> {
|
): Promise<UserInternalHistoryResponse> {
|
||||||
const context = await this.resolveContext(
|
const context = await this.resolveContext(
|
||||||
params.communityId,
|
params.communityId,
|
||||||
@@ -1138,18 +1145,31 @@ export class CommunityStatsService {
|
|||||||
scope: string,
|
scope: string,
|
||||||
communityId: mongoose.Types.ObjectId,
|
communityId: mongoose.Types.ObjectId,
|
||||||
filters: CommunityStatsFilters,
|
filters: CommunityStatsFilters,
|
||||||
): string {
|
): CommunityStatsCacheKey {
|
||||||
return [
|
const cacheScope = scope.startsWith('userInternal:')
|
||||||
'riot:communitystats',
|
? 'userInternal'
|
||||||
scope,
|
: scope;
|
||||||
|
if (
|
||||||
|
cacheScope !== 'matches' &&
|
||||||
|
cacheScope !== 'leaderboard' &&
|
||||||
|
cacheScope !== 'teamInsights' &&
|
||||||
|
cacheScope !== 'userInternal'
|
||||||
|
) {
|
||||||
|
throw new Error(`Unsupported community stats cache scope: ${scope}`);
|
||||||
|
}
|
||||||
|
return new CommunityStatsCacheKey(
|
||||||
communityId.toString(),
|
communityId.toString(),
|
||||||
filters.seasonId ?? 'current',
|
cacheScope,
|
||||||
filters.from ?? '',
|
JSON.stringify([
|
||||||
filters.to ?? '',
|
scope,
|
||||||
filters.championId ?? '',
|
filters.seasonId ?? 'current',
|
||||||
filters.cursor ?? '',
|
filters.from ?? '',
|
||||||
filters.limit ?? '',
|
filters.to ?? '',
|
||||||
].join(':');
|
filters.championId ?? '',
|
||||||
|
filters.cursor ?? '',
|
||||||
|
filters.limit ?? '',
|
||||||
|
]),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private clampLimit(
|
private clampLimit(
|
||||||
|
|||||||
@@ -7,7 +7,10 @@ import type {
|
|||||||
RiotLane,
|
RiotLane,
|
||||||
TeamSide,
|
TeamSide,
|
||||||
} from '../global/database/schema';
|
} from '../global/database/schema';
|
||||||
import type { RecentMatchView, HistorySeasonDto } from '../match-history/match-history.types';
|
import type {
|
||||||
|
RecentMatchView,
|
||||||
|
HistorySeasonDto,
|
||||||
|
} from '../match-history/match-history.types';
|
||||||
|
|
||||||
export interface CommunityStatsFilters {
|
export interface CommunityStatsFilters {
|
||||||
seasonId?: string;
|
seasonId?: string;
|
||||||
@@ -80,7 +83,9 @@ export interface LeaderboardRow {
|
|||||||
avgCsPerMin: number;
|
avgCsPerMin: number;
|
||||||
avgDamageShare: number;
|
avgDamageShare: number;
|
||||||
avgVisionScore: number;
|
avgVisionScore: number;
|
||||||
byLane: Partial<Record<RiotLane, { games: number; wins: number; kda: number }>>;
|
byLane: Partial<
|
||||||
|
Record<RiotLane, { games: number; wins: number; kda: number }>
|
||||||
|
>;
|
||||||
topChampions: Array<{ championId: number; games: number; winRate: number }>;
|
topChampions: Array<{ championId: number; games: number; winRate: number }>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -106,6 +106,8 @@ describe('MatchStatsFragmentBuilder', () => {
|
|||||||
puuid: 'puuid-2',
|
puuid: 'puuid-2',
|
||||||
gameName: 'Opponent',
|
gameName: 'Opponent',
|
||||||
profileIconId: 8,
|
profileIconId: 8,
|
||||||
|
preferredPositions: [],
|
||||||
|
joinedAt: new Date('2026-05-03T00:00:00.000Z'),
|
||||||
});
|
});
|
||||||
match.teams[1].members.push({ userId: redUserId, assignedPosition: 'TOP' });
|
match.teams[1].members.push({ userId: redUserId, assignedPosition: 'TOP' });
|
||||||
match.result?.games[0].participants.push({
|
match.result?.games[0].participants.push({
|
||||||
@@ -269,7 +271,7 @@ describe('MatchStatsFragmentBuilder', () => {
|
|||||||
teamId: 200,
|
teamId: 200,
|
||||||
win: false,
|
win: false,
|
||||||
});
|
});
|
||||||
const timeline = {
|
const timeline: RiotMatchTimelineDto = {
|
||||||
metadata: {
|
metadata: {
|
||||||
dataVersion: '2',
|
dataVersion: '2',
|
||||||
matchId: 'KR_1',
|
matchId: 'KR_1',
|
||||||
@@ -280,6 +282,7 @@ describe('MatchStatsFragmentBuilder', () => {
|
|||||||
frames: [
|
frames: [
|
||||||
{
|
{
|
||||||
timestamp: 0,
|
timestamp: 0,
|
||||||
|
events: [],
|
||||||
participantFrames: {
|
participantFrames: {
|
||||||
'1': {
|
'1': {
|
||||||
participantId: 1,
|
participantId: 1,
|
||||||
@@ -507,9 +510,7 @@ describe('MatchStatsFragmentBuilder', () => {
|
|||||||
const fragment = builder.buildFragment({
|
const fragment = builder.buildFragment({
|
||||||
match,
|
match,
|
||||||
rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]),
|
rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]),
|
||||||
timelineByRiotMatchId: new Map([
|
timelineByRiotMatchId: new Map([['KR_1', timeline]]),
|
||||||
['KR_1', timeline as RiotMatchTimelineDto],
|
|
||||||
]),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(fragment.gameDetails[0]).toMatchObject({
|
expect(fragment.gameDetails[0]).toMatchObject({
|
||||||
@@ -794,9 +795,7 @@ describe('MatchStatsFragmentBuilder', () => {
|
|||||||
} as RiotMatchDto,
|
} as RiotMatchDto,
|
||||||
],
|
],
|
||||||
]),
|
]),
|
||||||
timelineByRiotMatchId: new Map([
|
timelineByRiotMatchId: new Map([['KR_1', timeline]]),
|
||||||
['KR_1', timeline as RiotMatchTimelineDto],
|
|
||||||
]),
|
|
||||||
});
|
});
|
||||||
expect(
|
expect(
|
||||||
shortFragment.records.every((record) => record.checkpoints === undefined),
|
shortFragment.records.every((record) => record.checkpoints === undefined),
|
||||||
|
|||||||
@@ -227,9 +227,7 @@ export class MatchStatsFragmentBuilder {
|
|||||||
participant,
|
participant,
|
||||||
rawParticipant,
|
rawParticipant,
|
||||||
buildEvents: rawParticipant
|
buildEvents: rawParticipant
|
||||||
? buildEventsByParticipantId.get(
|
? buildEventsByParticipantId.get(rawParticipant.participantId)
|
||||||
rawParticipant.participantId,
|
|
||||||
)
|
|
||||||
: undefined,
|
: undefined,
|
||||||
checkpoints: rawParticipant
|
checkpoints: rawParticipant
|
||||||
? checkpointsByParticipantId.get(rawParticipant.participantId)
|
? checkpointsByParticipantId.get(rawParticipant.participantId)
|
||||||
@@ -420,7 +418,10 @@ export class MatchStatsFragmentBuilder {
|
|||||||
private toBuildEventsByParticipantId(
|
private toBuildEventsByParticipantId(
|
||||||
timeline?: RiotMatchTimelineDto,
|
timeline?: RiotMatchTimelineDto,
|
||||||
): Map<number, ParticipantBuildEvents> {
|
): Map<number, ParticipantBuildEvents> {
|
||||||
const buildEventsByParticipantId = new Map<number, ParticipantBuildEvents>();
|
const buildEventsByParticipantId = new Map<
|
||||||
|
number,
|
||||||
|
ParticipantBuildEvents
|
||||||
|
>();
|
||||||
if (!timeline?.info.frames.length) return buildEventsByParticipantId;
|
if (!timeline?.info.frames.length) return buildEventsByParticipantId;
|
||||||
|
|
||||||
const getEvents = (participantId: number): ParticipantBuildEvents => {
|
const getEvents = (participantId: number): ParticipantBuildEvents => {
|
||||||
@@ -796,15 +797,18 @@ export class MatchStatsFragmentBuilder {
|
|||||||
? timelineDragon
|
? timelineDragon
|
||||||
: (rawObjectives?.dragon?.kills ?? 0),
|
: (rawObjectives?.dragon?.kills ?? 0),
|
||||||
inhibitor: rawObjectives?.inhibitor?.kills ?? 0,
|
inhibitor: rawObjectives?.inhibitor?.kills ?? 0,
|
||||||
baron: (timelineObjectives?.baron ?? 0) > 0
|
baron:
|
||||||
? (timelineObjectives?.baron ?? 0)
|
(timelineObjectives?.baron ?? 0) > 0
|
||||||
: (rawObjectives?.baron?.kills ?? 0),
|
? (timelineObjectives?.baron ?? 0)
|
||||||
riftHerald: (timelineObjectives?.riftHerald ?? 0) > 0
|
: (rawObjectives?.baron?.kills ?? 0),
|
||||||
? (timelineObjectives?.riftHerald ?? 0)
|
riftHerald:
|
||||||
: (rawObjectives?.riftHerald?.kills ?? 0),
|
(timelineObjectives?.riftHerald ?? 0) > 0
|
||||||
voidGrub: (timelineObjectives?.voidGrub ?? 0) > 0
|
? (timelineObjectives?.riftHerald ?? 0)
|
||||||
? (timelineObjectives?.voidGrub ?? 0)
|
: (rawObjectives?.riftHerald?.kills ?? 0),
|
||||||
: (rawObjectives?.horde?.kills ?? 0),
|
voidGrub:
|
||||||
|
(timelineObjectives?.voidGrub ?? 0) > 0
|
||||||
|
? (timelineObjectives?.voidGrub ?? 0)
|
||||||
|
: (rawObjectives?.horde?.kills ?? 0),
|
||||||
elderDragon: hasProjectedDragon ? timelineElder : 0,
|
elderDragon: hasProjectedDragon ? timelineElder : 0,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -125,8 +125,8 @@ describe('MatchStatsRepository', () => {
|
|||||||
|
|
||||||
if (
|
if (
|
||||||
stored &&
|
stored &&
|
||||||
stored.sourceCompetitionId?.equals(fragment.sourceCompetitionId!) &&
|
stored.sourceCompetitionId?.equals(fragment.sourceCompetitionId) &&
|
||||||
stored.sourceRevision! <= fragment.sourceRevision!
|
stored.sourceRevision <= fragment.sourceRevision
|
||||||
) {
|
) {
|
||||||
stored = fragment;
|
stored = fragment;
|
||||||
return { matchedCount: 1, upsertedCount: 0 };
|
return { matchedCount: 1, upsertedCount: 0 };
|
||||||
|
|||||||
@@ -281,15 +281,26 @@ describe('MatchStatsService', () => {
|
|||||||
MatchStatsFragmentBuilder['buildFragment']
|
MatchStatsFragmentBuilder['buildFragment']
|
||||||
>[0];
|
>[0];
|
||||||
const buildCalls: BuildParams[] = [];
|
const buildCalls: BuildParams[] = [];
|
||||||
const builtFragment = {
|
const builtFragment: ReturnType<
|
||||||
matchCard: { matchId: matchId.toString() },
|
MatchStatsFragmentBuilder['buildFragment']
|
||||||
|
> = {
|
||||||
|
matchCard: {
|
||||||
|
matchId: matchId.toString(),
|
||||||
|
title: '내전',
|
||||||
|
scheduledAt: match.scheduledAt.toISOString(),
|
||||||
|
status: 'finished',
|
||||||
|
gameCount: 1,
|
||||||
|
games: [],
|
||||||
|
teams: [],
|
||||||
|
seriesResults: [],
|
||||||
|
},
|
||||||
records: [],
|
records: [],
|
||||||
gameDetails: [],
|
gameDetails: [],
|
||||||
userIds: [],
|
userIds: [],
|
||||||
championIds: [],
|
championIds: [],
|
||||||
gameCreationMin: 1_000,
|
gameCreationMin: 1_000,
|
||||||
gameCreationMax: 2_000,
|
gameCreationMax: 2_000,
|
||||||
} as ReturnType<MatchStatsFragmentBuilder['buildFragment']>;
|
};
|
||||||
const buildFragment = jest.fn((params: BuildParams) => {
|
const buildFragment = jest.fn((params: BuildParams) => {
|
||||||
buildCalls.push(params);
|
buildCalls.push(params);
|
||||||
return builtFragment;
|
return builtFragment;
|
||||||
|
|||||||
@@ -6,10 +6,7 @@ import {
|
|||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
import {
|
import { CommunityDocument, UserDocument } from '../global/database/schema';
|
||||||
CommunityDocument,
|
|
||||||
UserDocument,
|
|
||||||
} from '../global/database/schema';
|
|
||||||
|
|
||||||
export interface CreateCommunityInput {
|
export interface CreateCommunityInput {
|
||||||
name: string;
|
name: string;
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ describe('CompetitionBootstrapService', () => {
|
|||||||
it('creates a deterministic paired-Series Competition and immutable snapshots', async () => {
|
it('creates a deterministic paired-Series Competition and immutable snapshots', async () => {
|
||||||
const firstHarness = createHarness();
|
const firstHarness = createHarness();
|
||||||
const firstService = new CompetitionBootstrapService(
|
const firstService = new CompetitionBootstrapService(
|
||||||
firstHarness.connectionService as ConnectionService,
|
firstHarness.connectionService,
|
||||||
);
|
);
|
||||||
const match = matchSnapshot({ gameMode: 'pair', teamCount: 2 });
|
const match = matchSnapshot({ gameMode: 'pair', teamCount: 2 });
|
||||||
|
|
||||||
@@ -88,7 +88,7 @@ describe('CompetitionBootstrapService', () => {
|
|||||||
|
|
||||||
const secondHarness = createHarness();
|
const secondHarness = createHarness();
|
||||||
const secondService = new CompetitionBootstrapService(
|
const secondService = new CompetitionBootstrapService(
|
||||||
secondHarness.connectionService as ConnectionService,
|
secondHarness.connectionService,
|
||||||
);
|
);
|
||||||
await secondService.bootstrap({
|
await secondService.bootstrap({
|
||||||
...match,
|
...match,
|
||||||
@@ -106,9 +106,7 @@ describe('CompetitionBootstrapService', () => {
|
|||||||
|
|
||||||
it('maps round-robin configuration and preserves a limited round count', async () => {
|
it('maps round-robin configuration and preserves a limited round count', async () => {
|
||||||
const harness = createHarness();
|
const harness = createHarness();
|
||||||
const service = new CompetitionBootstrapService(
|
const service = new CompetitionBootstrapService(harness.connectionService);
|
||||||
harness.connectionService as ConnectionService,
|
|
||||||
);
|
|
||||||
|
|
||||||
await service.bootstrap(
|
await service.bootstrap(
|
||||||
matchSnapshot({
|
matchSnapshot({
|
||||||
@@ -132,9 +130,7 @@ describe('CompetitionBootstrapService', () => {
|
|||||||
|
|
||||||
it('maps double elimination seeds and stage-specific Series rules', async () => {
|
it('maps double elimination seeds and stage-specific Series rules', async () => {
|
||||||
const harness = createHarness();
|
const harness = createHarness();
|
||||||
const service = new CompetitionBootstrapService(
|
const service = new CompetitionBootstrapService(harness.connectionService);
|
||||||
harness.connectionService as ConnectionService,
|
|
||||||
);
|
|
||||||
const match = matchSnapshot({
|
const match = matchSnapshot({
|
||||||
gameMode: 'double-elimination',
|
gameMode: 'double-elimination',
|
||||||
teamCount: 4,
|
teamCount: 4,
|
||||||
@@ -177,14 +173,14 @@ describe('CompetitionBootstrapService', () => {
|
|||||||
{ legacyTeamIndex: 4, seedNumber: 3 },
|
{ legacyTeamIndex: 4, seedNumber: 3 },
|
||||||
]);
|
]);
|
||||||
expect(
|
expect(
|
||||||
inserted.seriesGraph.find(({ code }) => code === 'WB_R1_M1').rule,
|
inserted.seriesGraph.find(({ code }) => code === 'WB_R1_M1')?.rule,
|
||||||
).toEqual({ type: 'first-to', winsRequired: 3, maxGames: 5 });
|
).toEqual({ type: 'first-to', winsRequired: 3, maxGames: 5 });
|
||||||
expect(
|
expect(
|
||||||
inserted.seriesGraph.find(({ code }) => code?.startsWith('LB_')).rule,
|
inserted.seriesGraph.find(({ code }) => code?.startsWith('LB_'))?.rule,
|
||||||
|
).toEqual({ type: 'first-to', winsRequired: 1, maxGames: 1 });
|
||||||
|
expect(
|
||||||
|
inserted.seriesGraph.find(({ code }) => code === 'GF')?.rule,
|
||||||
).toEqual({ type: 'first-to', winsRequired: 1, maxGames: 1 });
|
).toEqual({ type: 'first-to', winsRequired: 1, maxGames: 1 });
|
||||||
expect(inserted.seriesGraph.find(({ code }) => code === 'GF').rule).toEqual(
|
|
||||||
{ type: 'first-to', winsRequired: 1, maxGames: 1 },
|
|
||||||
);
|
|
||||||
expect(
|
expect(
|
||||||
inserted.seriesGraph.find(({ code }) => code === 'GF_RESET'),
|
inserted.seriesGraph.find(({ code }) => code === 'GF_RESET'),
|
||||||
).toMatchObject({
|
).toMatchObject({
|
||||||
@@ -195,9 +191,7 @@ describe('CompetitionBootstrapService', () => {
|
|||||||
|
|
||||||
it('rejects double elimination until authoritative seeds are persisted', async () => {
|
it('rejects double elimination until authoritative seeds are persisted', async () => {
|
||||||
const harness = createHarness();
|
const harness = createHarness();
|
||||||
const service = new CompetitionBootstrapService(
|
const service = new CompetitionBootstrapService(harness.connectionService);
|
||||||
harness.connectionService as ConnectionService,
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(
|
await expect(
|
||||||
service.bootstrap(
|
service.bootstrap(
|
||||||
@@ -253,7 +247,7 @@ describe('CompetitionBootstrapService', () => {
|
|||||||
for (const [label, mutate] of cases) {
|
for (const [label, mutate] of cases) {
|
||||||
const harness = createHarness();
|
const harness = createHarness();
|
||||||
const service = new CompetitionBootstrapService(
|
const service = new CompetitionBootstrapService(
|
||||||
harness.connectionService as ConnectionService,
|
harness.connectionService,
|
||||||
);
|
);
|
||||||
const match = matchSnapshot({ gameMode: 'pair', teamCount: 2 });
|
const match = matchSnapshot({ gameMode: 'pair', teamCount: 2 });
|
||||||
mutate(match);
|
mutate(match);
|
||||||
@@ -272,7 +266,7 @@ describe('CompetitionBootstrapService', () => {
|
|||||||
it('rejects bracket mode live but explicitly maps it for legacy migration', async () => {
|
it('rejects bracket mode live but explicitly maps it for legacy migration', async () => {
|
||||||
const liveHarness = createHarness();
|
const liveHarness = createHarness();
|
||||||
const liveService = new CompetitionBootstrapService(
|
const liveService = new CompetitionBootstrapService(
|
||||||
liveHarness.connectionService as ConnectionService,
|
liveHarness.connectionService,
|
||||||
);
|
);
|
||||||
const match = matchSnapshot({ gameMode: 'bracket', teamCount: 2 });
|
const match = matchSnapshot({ gameMode: 'bracket', teamCount: 2 });
|
||||||
|
|
||||||
@@ -285,7 +279,7 @@ describe('CompetitionBootstrapService', () => {
|
|||||||
|
|
||||||
const migrationHarness = createHarness();
|
const migrationHarness = createHarness();
|
||||||
const migrationService = new CompetitionBootstrapService(
|
const migrationService = new CompetitionBootstrapService(
|
||||||
migrationHarness.connectionService as ConnectionService,
|
migrationHarness.connectionService,
|
||||||
);
|
);
|
||||||
await migrationService.bootstrap(match, { source: 'legacy-migration' });
|
await migrationService.bootstrap(match, { source: 'legacy-migration' });
|
||||||
|
|
||||||
@@ -296,9 +290,7 @@ describe('CompetitionBootstrapService', () => {
|
|||||||
|
|
||||||
it('upserts once and links only an unlinked or already-linked Match in one transaction', async () => {
|
it('upserts once and links only an unlinked or already-linked Match in one transaction', async () => {
|
||||||
const harness = createHarness();
|
const harness = createHarness();
|
||||||
const service = new CompetitionBootstrapService(
|
const service = new CompetitionBootstrapService(harness.connectionService);
|
||||||
harness.connectionService as ConnectionService,
|
|
||||||
);
|
|
||||||
|
|
||||||
const competition = await service.bootstrap(
|
const competition = await service.bootstrap(
|
||||||
matchSnapshot({ gameMode: 'pair', teamCount: 2 }),
|
matchSnapshot({ gameMode: 'pair', teamCount: 2 }),
|
||||||
@@ -342,9 +334,7 @@ describe('CompetitionBootstrapService', () => {
|
|||||||
revision: 4,
|
revision: 4,
|
||||||
};
|
};
|
||||||
const harness = createHarness({ existingCompetition: existing });
|
const harness = createHarness({ existingCompetition: existing });
|
||||||
const service = new CompetitionBootstrapService(
|
const service = new CompetitionBootstrapService(harness.connectionService);
|
||||||
harness.connectionService as ConnectionService,
|
|
||||||
);
|
|
||||||
|
|
||||||
const result = await service.bootstrap(
|
const result = await service.bootstrap(
|
||||||
matchSnapshot({ gameMode: 'pair', teamCount: 2 }),
|
matchSnapshot({ gameMode: 'pair', teamCount: 2 }),
|
||||||
@@ -372,9 +362,7 @@ describe('CompetitionBootstrapService', () => {
|
|||||||
competitionResults: [duplicateKey, winner],
|
competitionResults: [duplicateKey, winner],
|
||||||
sessionCount: 2,
|
sessionCount: 2,
|
||||||
});
|
});
|
||||||
const service = new CompetitionBootstrapService(
|
const service = new CompetitionBootstrapService(harness.connectionService);
|
||||||
harness.connectionService as ConnectionService,
|
|
||||||
);
|
|
||||||
|
|
||||||
const result = await service.bootstrap(
|
const result = await service.bootstrap(
|
||||||
matchSnapshot({ gameMode: 'pair', teamCount: 2 }),
|
matchSnapshot({ gameMode: 'pair', teamCount: 2 }),
|
||||||
@@ -391,9 +379,7 @@ describe('CompetitionBootstrapService', () => {
|
|||||||
|
|
||||||
it('aborts when the Match is already linked to a different Competition', async () => {
|
it('aborts when the Match is already linked to a different Competition', async () => {
|
||||||
const harness = createHarness({ matchUpdateResult: { matchedCount: 0 } });
|
const harness = createHarness({ matchUpdateResult: { matchedCount: 0 } });
|
||||||
const service = new CompetitionBootstrapService(
|
const service = new CompetitionBootstrapService(harness.connectionService);
|
||||||
harness.connectionService as ConnectionService,
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(
|
await expect(
|
||||||
service.bootstrap(matchSnapshot({ gameMode: 'pair', teamCount: 2 })),
|
service.bootstrap(matchSnapshot({ gameMode: 'pair', teamCount: 2 })),
|
||||||
@@ -485,11 +471,7 @@ function createHarness(
|
|||||||
let competitionCall = 0;
|
let competitionCall = 0;
|
||||||
const competitionModel = {
|
const competitionModel = {
|
||||||
findOneAndUpdate: jest.fn(
|
findOneAndUpdate: jest.fn(
|
||||||
(
|
(_filter: unknown, update: { $setOnInsert: InsertPayload }) => {
|
||||||
_filter: unknown,
|
|
||||||
update: { $setOnInsert: InsertPayload },
|
|
||||||
_queryOptions: unknown,
|
|
||||||
) => {
|
|
||||||
insertedPayloads.push(update.$setOnInsert);
|
insertedPayloads.push(update.$setOnInsert);
|
||||||
const selected = options.competitionResults?.[competitionCall++];
|
const selected = options.competitionResults?.[competitionCall++];
|
||||||
if (selected instanceof Error) return rejectedQuery(selected);
|
if (selected instanceof Error) return rejectedQuery(selected);
|
||||||
@@ -512,7 +494,7 @@ function createHarness(
|
|||||||
const connectionService = {
|
const connectionService = {
|
||||||
createSession: jest.fn(() => Promise.resolve(sessions[sessionIndex++])),
|
createSession: jest.fn(() => Promise.resolve(sessions[sessionIndex++])),
|
||||||
getModel: jest.fn((name: string) => Promise.resolve(models[name])),
|
getModel: jest.fn((name: string) => Promise.resolve(models[name])),
|
||||||
};
|
} as unknown as jest.Mocked<ConnectionService>;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
sessions,
|
sessions,
|
||||||
|
|||||||
@@ -22,9 +22,7 @@ describe('CompetitionCommandService', () => {
|
|||||||
|
|
||||||
it('rejects a stale expected revision and aborts without writing', async () => {
|
it('rejects a stale expected revision and aborts without writing', async () => {
|
||||||
const harness = createHarness({ competitionRevision: 8 });
|
const harness = createHarness({ competitionRevision: 8 });
|
||||||
const service = new CompetitionCommandService(
|
const service = new CompetitionCommandService(harness.connectionService);
|
||||||
harness.connectionService as ConnectionService,
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(service.acceptGame(acceptGameCommand())).rejects.toMatchObject(
|
await expect(service.acceptGame(acceptGameCommand())).rejects.toMatchObject(
|
||||||
{
|
{
|
||||||
@@ -44,9 +42,7 @@ describe('CompetitionCommandService', () => {
|
|||||||
|
|
||||||
it('uses the expected revision in the persistence CAS and aborts a lost race', async () => {
|
it('uses the expected revision in the persistence CAS and aborts a lost race', async () => {
|
||||||
const harness = createHarness({ casResult: null });
|
const harness = createHarness({ casResult: null });
|
||||||
const service = new CompetitionCommandService(
|
const service = new CompetitionCommandService(harness.connectionService);
|
||||||
harness.connectionService as ConnectionService,
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(service.acceptGame(acceptGameCommand())).rejects.toMatchObject(
|
await expect(service.acceptGame(acceptGameCommand())).rejects.toMatchObject(
|
||||||
{
|
{
|
||||||
@@ -86,9 +82,7 @@ describe('CompetitionCommandService', () => {
|
|||||||
return Promise.resolve([receipt]);
|
return Promise.resolve([receipt]);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
const service = new CompetitionCommandService(
|
const service = new CompetitionCommandService(harness.connectionService);
|
||||||
harness.connectionService as ConnectionService,
|
|
||||||
);
|
|
||||||
const command = acceptGameCommand();
|
const command = acceptGameCommand();
|
||||||
|
|
||||||
const first = await service.acceptGame(command);
|
const first = await service.acceptGame(command);
|
||||||
@@ -133,9 +127,7 @@ describe('CompetitionCommandService', () => {
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
const service = new CompetitionCommandService(
|
const service = new CompetitionCommandService(harness.connectionService);
|
||||||
harness.connectionService as ConnectionService,
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(
|
await expect(
|
||||||
service.acceptGame(acceptGameCommand()),
|
service.acceptGame(acceptGameCommand()),
|
||||||
@@ -162,9 +154,7 @@ describe('CompetitionCommandService', () => {
|
|||||||
revision: 8,
|
revision: 8,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
const service = new CompetitionCommandService(
|
const service = new CompetitionCommandService(harness.connectionService);
|
||||||
harness.connectionService as ConnectionService,
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(service.acceptGame(acceptGameCommand())).rejects.toMatchObject(
|
await expect(service.acceptGame(acceptGameCommand())).rejects.toMatchObject(
|
||||||
{
|
{
|
||||||
@@ -180,9 +170,7 @@ describe('CompetitionCommandService', () => {
|
|||||||
|
|
||||||
it('atomically accepts a code-backed game, projects it, and enqueues an event', async () => {
|
it('atomically accepts a code-backed game, projects it, and enqueues an event', async () => {
|
||||||
const harness = createHarness();
|
const harness = createHarness();
|
||||||
const service = new CompetitionCommandService(
|
const service = new CompetitionCommandService(harness.connectionService);
|
||||||
harness.connectionService as ConnectionService,
|
|
||||||
);
|
|
||||||
const command = {
|
const command = {
|
||||||
...acceptGameCommand(),
|
...acceptGameCommand(),
|
||||||
tournamentCode: {
|
tournamentCode: {
|
||||||
@@ -279,9 +267,7 @@ describe('CompetitionCommandService', () => {
|
|||||||
|
|
||||||
it('appends an administrative adjudication through the same command runner', async () => {
|
it('appends an administrative adjudication through the same command runner', async () => {
|
||||||
const harness = createHarness();
|
const harness = createHarness();
|
||||||
const service = new CompetitionCommandService(
|
const service = new CompetitionCommandService(harness.connectionService);
|
||||||
harness.connectionService as ConnectionService,
|
|
||||||
);
|
|
||||||
|
|
||||||
const result = await service.adjudicateSeries({
|
const result = await service.adjudicateSeries({
|
||||||
competitionId: COMPETITION_ID,
|
competitionId: COMPETITION_ID,
|
||||||
@@ -316,9 +302,7 @@ describe('CompetitionCommandService', () => {
|
|||||||
facts: reversal.facts,
|
facts: reversal.facts,
|
||||||
assignments: reversal.assignments,
|
assignments: reversal.assignments,
|
||||||
});
|
});
|
||||||
const service = new CompetitionCommandService(
|
const service = new CompetitionCommandService(harness.connectionService);
|
||||||
harness.connectionService as ConnectionService,
|
|
||||||
);
|
|
||||||
|
|
||||||
const preview = await service.previewSeriesReversal({
|
const preview = await service.previewSeriesReversal({
|
||||||
competitionId: COMPETITION_ID,
|
competitionId: COMPETITION_ID,
|
||||||
@@ -348,9 +332,7 @@ describe('CompetitionCommandService', () => {
|
|||||||
it('rejects a reversal preview at a stale revision', async () => {
|
it('rejects a reversal preview at a stale revision', async () => {
|
||||||
const reversal = reversalFixture();
|
const reversal = reversalFixture();
|
||||||
const harness = createHarness({ competition: reversal.competition });
|
const harness = createHarness({ competition: reversal.competition });
|
||||||
const service = new CompetitionCommandService(
|
const service = new CompetitionCommandService(harness.connectionService);
|
||||||
harness.connectionService as ConnectionService,
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(
|
await expect(
|
||||||
service.previewSeriesReversal({
|
service.previewSeriesReversal({
|
||||||
@@ -372,9 +354,7 @@ describe('CompetitionCommandService', () => {
|
|||||||
facts: reversal.facts,
|
facts: reversal.facts,
|
||||||
assignments: reversal.assignments,
|
assignments: reversal.assignments,
|
||||||
});
|
});
|
||||||
const service = new CompetitionCommandService(
|
const service = new CompetitionCommandService(harness.connectionService);
|
||||||
harness.connectionService as ConnectionService,
|
|
||||||
);
|
|
||||||
const preview = await service.previewSeriesReversal({
|
const preview = await service.previewSeriesReversal({
|
||||||
competitionId: COMPETITION_ID,
|
competitionId: COMPETITION_ID,
|
||||||
expectedRevision: 7,
|
expectedRevision: 7,
|
||||||
@@ -485,9 +465,7 @@ describe('CompetitionCommandService', () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.mockResolvedValueOnce([]);
|
.mockResolvedValueOnce([]);
|
||||||
const service = new CompetitionCommandService(
|
const service = new CompetitionCommandService(harness.connectionService);
|
||||||
harness.connectionService as ConnectionService,
|
|
||||||
);
|
|
||||||
const preview = await service.previewSeriesReversal({
|
const preview = await service.previewSeriesReversal({
|
||||||
competitionId: COMPETITION_ID,
|
competitionId: COMPETITION_ID,
|
||||||
expectedRevision: 7,
|
expectedRevision: 7,
|
||||||
@@ -635,7 +613,7 @@ function createHarness(
|
|||||||
const connectionService = {
|
const connectionService = {
|
||||||
createSession: jest.fn().mockResolvedValue(session),
|
createSession: jest.fn().mockResolvedValue(session),
|
||||||
getModel: jest.fn((name: string) => Promise.resolve(models[name])),
|
getModel: jest.fn((name: string) => Promise.resolve(models[name])),
|
||||||
};
|
} as unknown as jest.Mocked<ConnectionService>;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
session,
|
session,
|
||||||
|
|||||||
@@ -160,9 +160,7 @@ const SERIES_ID = 'series-1';
|
|||||||
const GAME_SLOT_ID = 'slot-1';
|
const GAME_SLOT_ID = 'slot-1';
|
||||||
|
|
||||||
function createService(harness: ReturnType<typeof createHarness>) {
|
function createService(harness: ReturnType<typeof createHarness>) {
|
||||||
return new CompetitionQueryService(
|
return new CompetitionQueryService(harness.connectionService);
|
||||||
harness.connectionService as ConnectionService,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function createHarness(options: { competition?: unknown } = {}) {
|
function createHarness(options: { competition?: unknown } = {}) {
|
||||||
@@ -244,7 +242,7 @@ function createHarness(options: { competition?: unknown } = {}) {
|
|||||||
factModel,
|
factModel,
|
||||||
connectionService: {
|
connectionService: {
|
||||||
getModel: jest.fn((name: string) => Promise.resolve(models[name])),
|
getModel: jest.fn((name: string) => Promise.resolve(models[name])),
|
||||||
},
|
} as unknown as jest.Mocked<ConnectionService>,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -127,7 +127,7 @@ describe('Competition persistence schemas', () => {
|
|||||||
|
|
||||||
function expectIndexes(
|
function expectIndexes(
|
||||||
schema: {
|
schema: {
|
||||||
indexes(): Array<[Record<string, number>, Record<string, unknown>]>;
|
indexes(): ReturnType<typeof CompetitionSchema.indexes>;
|
||||||
},
|
},
|
||||||
expected: Array<{
|
expected: Array<{
|
||||||
keys: Record<string, number>;
|
keys: Record<string, number>;
|
||||||
|
|||||||
@@ -429,8 +429,14 @@ export function applyCompetitionDomainInvariantIndexes(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type CompetitionModelName =
|
||||||
|
| 'competition'
|
||||||
|
| 'competitionFact'
|
||||||
|
| 'competitionOutbox'
|
||||||
|
| 'tournamentCodeAssignment';
|
||||||
|
|
||||||
export const competitionModelDefinitions: Array<{
|
export const competitionModelDefinitions: Array<{
|
||||||
name: string;
|
name: CompetitionModelName;
|
||||||
schema: mongoose.Schema;
|
schema: mongoose.Schema;
|
||||||
schemaName: string;
|
schemaName: string;
|
||||||
}> = [
|
}> = [
|
||||||
|
|||||||
@@ -1,4 +1,8 @@
|
|||||||
import { projectCompetition } from './competition-projector';
|
import { projectCompetition } from './competition-projector';
|
||||||
|
import {
|
||||||
|
CompetitionDomainError,
|
||||||
|
type CompetitionDomainErrorCode,
|
||||||
|
} from './domain-error';
|
||||||
import { generateSeriesGraph } from './series-graph';
|
import { generateSeriesGraph } from './series-graph';
|
||||||
|
|
||||||
describe('projectCompetition', () => {
|
describe('projectCompetition', () => {
|
||||||
@@ -323,20 +327,18 @@ describe('projectCompetition', () => {
|
|||||||
'team-1',
|
'team-1',
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(() =>
|
expectCompetitionDomainError(
|
||||||
projectCompetition({
|
() =>
|
||||||
competitionId,
|
projectCompetition({
|
||||||
revision: 1,
|
competitionId,
|
||||||
projectorVersion: 1,
|
revision: 1,
|
||||||
teams,
|
projectorVersion: 1,
|
||||||
format,
|
teams,
|
||||||
seriesGraph,
|
format,
|
||||||
facts: [{ ...accepted, seriesId: 'series-does-not-exist' }],
|
seriesGraph,
|
||||||
}),
|
facts: [{ ...accepted, seriesId: 'series-does-not-exist' }],
|
||||||
).toThrow(
|
}),
|
||||||
expect.objectContaining({
|
'GAME_SERIES_MISMATCH',
|
||||||
code: 'GAME_SERIES_MISMATCH',
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -356,20 +358,18 @@ describe('projectCompetition', () => {
|
|||||||
'team-1',
|
'team-1',
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(() =>
|
expectCompetitionDomainError(
|
||||||
projectCompetition({
|
() =>
|
||||||
competitionId,
|
projectCompetition({
|
||||||
revision: 1,
|
competitionId,
|
||||||
projectorVersion: 1,
|
revision: 1,
|
||||||
teams,
|
projectorVersion: 1,
|
||||||
format,
|
teams,
|
||||||
seriesGraph,
|
format,
|
||||||
facts: [{ ...accepted, gameSlotId: 'slot-does-not-exist' }],
|
seriesGraph,
|
||||||
}),
|
facts: [{ ...accepted, gameSlotId: 'slot-does-not-exist' }],
|
||||||
).toThrow(
|
}),
|
||||||
expect.objectContaining({
|
'GAME_SLOT_INVALID',
|
||||||
code: 'GAME_SLOT_INVALID',
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -382,36 +382,34 @@ describe('projectCompetition', () => {
|
|||||||
};
|
};
|
||||||
const seriesGraph = generateSeriesGraph({ competitionId, teams, format });
|
const seriesGraph = generateSeriesGraph({ competitionId, teams, format });
|
||||||
|
|
||||||
expect(() =>
|
expectCompetitionDomainError(
|
||||||
projectCompetition({
|
() =>
|
||||||
competitionId,
|
projectCompetition({
|
||||||
revision: 1,
|
competitionId,
|
||||||
projectorVersion: 1,
|
revision: 1,
|
||||||
teams,
|
projectorVersion: 1,
|
||||||
format,
|
teams,
|
||||||
seriesGraph,
|
format,
|
||||||
facts: [
|
seriesGraph,
|
||||||
{
|
facts: [
|
||||||
id: 'fact-unknown-adjudication-series',
|
{
|
||||||
type: 'series-adjudicated',
|
id: 'fact-unknown-adjudication-series',
|
||||||
competitionId,
|
type: 'series-adjudicated',
|
||||||
revision: 1,
|
competitionId,
|
||||||
ordinalWithinRevision: 1,
|
revision: 1,
|
||||||
commandId: 'command-unknown-adjudication-series',
|
ordinalWithinRevision: 1,
|
||||||
schemaVersion: 1,
|
commandId: 'command-unknown-adjudication-series',
|
||||||
actor: { type: 'user' },
|
schemaVersion: 1,
|
||||||
occurredAt: new Date('2026-07-12T00:00:01.000Z'),
|
actor: { type: 'user' },
|
||||||
recordedAt: new Date('2026-07-12T00:00:02.000Z'),
|
occurredAt: new Date('2026-07-12T00:00:01.000Z'),
|
||||||
seriesId: 'series-does-not-exist',
|
recordedAt: new Date('2026-07-12T00:00:02.000Z'),
|
||||||
decision: { type: 'administrative', winnerTeamId: 'team-1' },
|
seriesId: 'series-does-not-exist',
|
||||||
reason: 'Manual correction',
|
decision: { type: 'administrative', winnerTeamId: 'team-1' },
|
||||||
},
|
reason: 'Manual correction',
|
||||||
],
|
},
|
||||||
}),
|
],
|
||||||
).toThrow(
|
}),
|
||||||
expect.objectContaining({
|
'ADJUDICATION_INVALID',
|
||||||
code: 'ADJUDICATION_INVALID',
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -591,9 +589,10 @@ function acceptedGameFactory(competitionId: string) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function projectedSeries<
|
function projectedSeries<T extends { code?: string; seriesId: string }>(
|
||||||
T extends { series: Array<{ code?: string; seriesId: string }> },
|
projection: { series: T[] },
|
||||||
>(projection: T, code: string) {
|
code: string,
|
||||||
|
) {
|
||||||
const series = projection.series.find((candidate) => candidate.code === code);
|
const series = projection.series.find((candidate) => candidate.code === code);
|
||||||
if (!series) throw new Error(`Missing projected series ${code}`);
|
if (!series) throw new Error(`Missing projected series ${code}`);
|
||||||
return series;
|
return series;
|
||||||
@@ -617,3 +616,23 @@ interface GameSlotLike {
|
|||||||
id: string;
|
id: string;
|
||||||
ordinal: number;
|
ordinal: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function expectCompetitionDomainError(
|
||||||
|
action: () => unknown,
|
||||||
|
expectedCode: CompetitionDomainErrorCode,
|
||||||
|
): void {
|
||||||
|
let thrown: unknown;
|
||||||
|
try {
|
||||||
|
action();
|
||||||
|
} catch (error: unknown) {
|
||||||
|
thrown = error;
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(thrown).toBeInstanceOf(CompetitionDomainError);
|
||||||
|
if (!(thrown instanceof CompetitionDomainError)) {
|
||||||
|
throw new Error(
|
||||||
|
`Expected CompetitionDomainError, received ${String(thrown)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
expect(thrown.code).toBe(expectedCode);
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import {
|
import {
|
||||||
assertReversalPreview,
|
assertReversalPreview,
|
||||||
buildReversalFacts,
|
buildReversalFacts,
|
||||||
|
CompetitionReversalError,
|
||||||
previewSeriesReversal,
|
previewSeriesReversal,
|
||||||
} from './competition-reversal';
|
} from './competition-reversal';
|
||||||
|
|
||||||
@@ -19,18 +20,18 @@ describe('Competition reversal planning', () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
it('rejects strict reversal when a descendant has result activity', () => {
|
it('rejects strict reversal when a descendant has result activity', () => {
|
||||||
expect(() =>
|
expectCompetitionReversalError(
|
||||||
previewSeriesReversal({
|
() =>
|
||||||
competitionId: 'competition-1',
|
previewSeriesReversal({
|
||||||
revision: 2,
|
competitionId: 'competition-1',
|
||||||
seriesId: 'series-parent',
|
revision: 2,
|
||||||
mode: 'strict',
|
seriesId: 'series-parent',
|
||||||
graph,
|
mode: 'strict',
|
||||||
facts,
|
graph,
|
||||||
assignments,
|
facts,
|
||||||
}),
|
assignments,
|
||||||
).toThrow(
|
}),
|
||||||
expect.objectContaining({ code: 'REVERSAL_DESCENDANT_ACTIVITY' }),
|
'REVERSAL_DESCENDANT_ACTIVITY',
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -105,20 +106,22 @@ describe('Competition reversal planning', () => {
|
|||||||
assignments,
|
assignments,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(() =>
|
expectCompetitionReversalError(
|
||||||
assertReversalPreview(
|
() =>
|
||||||
{
|
assertReversalPreview(
|
||||||
competitionId: 'competition-1',
|
{
|
||||||
revision: 3,
|
competitionId: 'competition-1',
|
||||||
seriesId: 'series-parent',
|
revision: 3,
|
||||||
mode: 'cascade',
|
seriesId: 'series-parent',
|
||||||
graph,
|
mode: 'cascade',
|
||||||
facts,
|
graph,
|
||||||
assignments,
|
facts,
|
||||||
},
|
assignments,
|
||||||
preview.impactHash,
|
},
|
||||||
),
|
preview.impactHash,
|
||||||
).toThrow(expect.objectContaining({ code: 'REVERSAL_PREVIEW_STALE' }));
|
),
|
||||||
|
'REVERSAL_PREVIEW_STALE',
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('emits one append-only reversal fact for every active result fact', () => {
|
it('emits one append-only reversal fact for every active result fact', () => {
|
||||||
@@ -160,6 +163,26 @@ describe('Competition reversal planning', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
function expectCompetitionReversalError(
|
||||||
|
action: () => unknown,
|
||||||
|
expectedCode: CompetitionReversalError['code'],
|
||||||
|
): void {
|
||||||
|
let thrown: unknown;
|
||||||
|
try {
|
||||||
|
action();
|
||||||
|
} catch (error: unknown) {
|
||||||
|
thrown = error;
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(thrown).toBeInstanceOf(CompetitionReversalError);
|
||||||
|
if (!(thrown instanceof CompetitionReversalError)) {
|
||||||
|
throw new Error(
|
||||||
|
`Expected CompetitionReversalError, received ${String(thrown)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
expect(thrown.code).toBe(expectedCode);
|
||||||
|
}
|
||||||
|
|
||||||
function series(id: string, sources: Array<Record<string, unknown>>) {
|
function series(id: string, sources: Array<Record<string, unknown>>) {
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
|
|||||||
@@ -9,7 +9,8 @@ import { DakaoOutboxService } from './dakao-outbox.service';
|
|||||||
|
|
||||||
const SWEEP_INTERVAL_MS = 60 * 1000;
|
const SWEEP_INTERVAL_MS = 60 * 1000;
|
||||||
const STALE_OUTBOX_MS = 5 * 60 * 1000;
|
const STALE_OUTBOX_MS = 5 * 60 * 1000;
|
||||||
const SWEEP_LOCK_KEY = 'distributed-lock:dakao-outbox:sweep-stale-publish-leases';
|
const SWEEP_LOCK_KEY =
|
||||||
|
'distributed-lock:dakao-outbox:sweep-stale-publish-leases';
|
||||||
const SWEEP_LOCK_EXPIRATION_DURATION_MILLISECONDS = 55_000;
|
const SWEEP_LOCK_EXPIRATION_DURATION_MILLISECONDS = 55_000;
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
|
|||||||
@@ -78,35 +78,29 @@ export class DakaoOutboxService {
|
|||||||
await this.natsService.publishJetStream(params.subject, params.envelope, {
|
await this.natsService.publishJetStream(params.subject, params.envelope, {
|
||||||
messageId: params.eventId,
|
messageId: params.eventId,
|
||||||
});
|
});
|
||||||
await OutboxModel.updateOne(
|
await OutboxModel.updateOne(updateFilter, {
|
||||||
updateFilter,
|
$set: {
|
||||||
{
|
state: 'published',
|
||||||
$set: {
|
publishedAt: new Date(),
|
||||||
state: 'published',
|
|
||||||
publishedAt: new Date(),
|
|
||||||
},
|
|
||||||
$inc: { publishAttempts: 1 },
|
|
||||||
$unset: {
|
|
||||||
lastPublishError: '',
|
|
||||||
publishLeaseOwnerIdentifier: '',
|
|
||||||
publishLeaseExpiresAt: '',
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
).exec();
|
$inc: { publishAttempts: 1 },
|
||||||
|
$unset: {
|
||||||
|
lastPublishError: '',
|
||||||
|
publishLeaseOwnerIdentifier: '',
|
||||||
|
publishLeaseExpiresAt: '',
|
||||||
|
},
|
||||||
|
}).exec();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
await OutboxModel.updateOne(
|
await OutboxModel.updateOne(updateFilter, {
|
||||||
updateFilter,
|
$inc: { publishAttempts: 1 },
|
||||||
{
|
$set: {
|
||||||
$inc: { publishAttempts: 1 },
|
lastPublishError: (err as Error)?.message ?? String(err),
|
||||||
$set: {
|
|
||||||
lastPublishError: (err as Error)?.message ?? String(err),
|
|
||||||
},
|
|
||||||
$unset: {
|
|
||||||
publishLeaseOwnerIdentifier: '',
|
|
||||||
publishLeaseExpiresAt: '',
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
).exec();
|
$unset: {
|
||||||
|
publishLeaseOwnerIdentifier: '',
|
||||||
|
publishLeaseExpiresAt: '',
|
||||||
|
},
|
||||||
|
}).exec();
|
||||||
this.logger.error(
|
this.logger.error(
|
||||||
`Failed to publish Dakao outbox eventId=${params.eventId}: ${
|
`Failed to publish Dakao outbox eventId=${params.eventId}: ${
|
||||||
(err as Error)?.stack ?? err
|
(err as Error)?.stack ?? err
|
||||||
|
|||||||
@@ -0,0 +1,122 @@
|
|||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import { RiotAccountService } from '../riot/riot-account.service';
|
||||||
|
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
||||||
|
import { DakaoUserService } from './dakao-user.service';
|
||||||
|
|
||||||
|
const communityId = new mongoose.Types.ObjectId();
|
||||||
|
const params = {
|
||||||
|
communityId,
|
||||||
|
kakaoTalkId: 'new-id',
|
||||||
|
previousNickname: '예전 닉',
|
||||||
|
};
|
||||||
|
|
||||||
|
function setup() {
|
||||||
|
const user = {
|
||||||
|
_id: new mongoose.Types.ObjectId(),
|
||||||
|
communityId,
|
||||||
|
kakaoTalkId: 'old-id',
|
||||||
|
kakaoTalkNickname: '예전 닉',
|
||||||
|
riotAccounts: [{ puuid: 'puuid', gameName: '소환사', tagLine: 'KR1' }],
|
||||||
|
role: 'member',
|
||||||
|
};
|
||||||
|
const find = jest.fn().mockReturnValue({
|
||||||
|
limit: jest
|
||||||
|
.fn()
|
||||||
|
.mockReturnValue({ exec: jest.fn().mockResolvedValue([user]) }),
|
||||||
|
});
|
||||||
|
const findOne = jest
|
||||||
|
.fn()
|
||||||
|
.mockReturnValue({ exec: jest.fn().mockResolvedValue(null) });
|
||||||
|
const update = jest
|
||||||
|
.fn()
|
||||||
|
.mockImplementation(async () => ({ ...user, kakaoTalkId: 'new-id' }));
|
||||||
|
const findOneAndUpdate = jest.fn().mockReturnValue({ exec: update });
|
||||||
|
const service = new DakaoUserService(
|
||||||
|
{
|
||||||
|
getModel: jest
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValue({ find, findOne, findOneAndUpdate }),
|
||||||
|
} as unknown as ConnectionService,
|
||||||
|
{} as RiotAccountService,
|
||||||
|
{} as RiotAccountEnrichmentService,
|
||||||
|
);
|
||||||
|
return { service, user, find, findOne, findOneAndUpdate, update };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('DakaoUserService.transferKakaoTalkId', () => {
|
||||||
|
it('selects registered users by exact nickname in the current community and changes only the ID', async () => {
|
||||||
|
const { service, user, find, findOneAndUpdate } = setup();
|
||||||
|
expect(await service.transferKakaoTalkId(params)).toBe('transferred');
|
||||||
|
expect(find).toHaveBeenCalledWith({
|
||||||
|
communityId,
|
||||||
|
kakaoTalkNickname: '예전 닉',
|
||||||
|
'riotAccounts.0': { $exists: true },
|
||||||
|
});
|
||||||
|
expect(findOneAndUpdate).toHaveBeenCalledWith(
|
||||||
|
{
|
||||||
|
_id: user._id,
|
||||||
|
communityId,
|
||||||
|
kakaoTalkId: 'old-id',
|
||||||
|
kakaoTalkNickname: '예전 닉',
|
||||||
|
'riotAccounts.0': { $exists: true },
|
||||||
|
},
|
||||||
|
{ $set: { kakaoTalkId: 'new-id' } },
|
||||||
|
{ returnDocument: 'after' },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['not-found', 0],
|
||||||
|
['ambiguous', 2],
|
||||||
|
] as const)('returns %s without mutation', async (status, count) => {
|
||||||
|
const { service, user, find, findOneAndUpdate } = setup();
|
||||||
|
find.mockReturnValue({
|
||||||
|
limit: () => ({
|
||||||
|
exec: async () => Array.from({ length: count }, () => user),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
expect(await service.transferKakaoTalkId(params)).toBe(status);
|
||||||
|
expect(findOneAndUpdate).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not mutate an already linked user', async () => {
|
||||||
|
const { service, user, findOneAndUpdate } = setup();
|
||||||
|
user.kakaoTalkId = 'new-id';
|
||||||
|
expect(await service.transferKakaoTalkId(params)).toBe('already-linked');
|
||||||
|
expect(findOneAndUpdate).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses an ID occupied by another user', async () => {
|
||||||
|
const { service, findOne, findOneAndUpdate } = setup();
|
||||||
|
findOne.mockReturnValue({
|
||||||
|
exec: async () => ({ _id: new mongoose.Types.ObjectId() }),
|
||||||
|
});
|
||||||
|
expect(await service.transferKakaoTalkId(params)).toBe('id-conflict');
|
||||||
|
expect(findOne).toHaveBeenCalledWith({
|
||||||
|
communityId,
|
||||||
|
kakaoTalkId: 'new-id',
|
||||||
|
});
|
||||||
|
expect(findOneAndUpdate).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reports a concurrent change instead of overwriting it', async () => {
|
||||||
|
const { service, update } = setup();
|
||||||
|
update.mockResolvedValue(null);
|
||||||
|
expect(await service.transferKakaoTalkId(params)).toBe('changed');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles a concurrent ID collision', async () => {
|
||||||
|
const { service, update } = setup();
|
||||||
|
update.mockRejectedValue({ code: 11000 });
|
||||||
|
expect(await service.transferKakaoTalkId(params)).toBe('id-conflict');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('propagates unexpected database failures for retry', async () => {
|
||||||
|
const { service, update } = setup();
|
||||||
|
update.mockRejectedValue(new Error('database unavailable'));
|
||||||
|
await expect(service.transferKakaoTalkId(params)).rejects.toThrow(
|
||||||
|
'database unavailable',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -105,7 +105,7 @@ describe('DakaoUserService', () => {
|
|||||||
tagLine: 'KR2',
|
tagLine: 'KR2',
|
||||||
isPrimary: false,
|
isPrimary: false,
|
||||||
});
|
});
|
||||||
expect((result.user.riotAccounts as RiotAccount[])[0]).toMatchObject({
|
expect(result.user.riotAccounts[0]).toMatchObject({
|
||||||
puuid: 'puuid-1',
|
puuid: 'puuid-1',
|
||||||
isPrimary: true,
|
isPrimary: true,
|
||||||
});
|
});
|
||||||
@@ -223,11 +223,21 @@ describe('DakaoUserService', () => {
|
|||||||
puuid: 'puuid-1',
|
puuid: 'puuid-1',
|
||||||
gameName: '기존소환사',
|
gameName: '기존소환사',
|
||||||
tagLine: 'KR1',
|
tagLine: 'KR1',
|
||||||
|
profileIconId: 1,
|
||||||
|
revisionDate: 0,
|
||||||
|
summonerLevel: 30,
|
||||||
|
tiers: [],
|
||||||
|
tierHistory: [],
|
||||||
|
matchIds: [],
|
||||||
|
championMasteries: [],
|
||||||
|
championRecords: {},
|
||||||
isPrimary: true,
|
isPrimary: true,
|
||||||
|
createdAt: new Date('2026-05-03T00:00:00.000Z'),
|
||||||
|
updatedAt: new Date('2026-05-03T00:00:00.000Z'),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
save,
|
save,
|
||||||
} as Partial<UserDocument>,
|
} satisfies Partial<UserDocument>,
|
||||||
});
|
});
|
||||||
|
|
||||||
await expect(
|
await expect(
|
||||||
|
|||||||
@@ -60,6 +60,14 @@ interface ResolvedRiotIdentity {
|
|||||||
const DEFAULT_RIOT_PLATFORM: RiotPlatformRoute = 'kr';
|
const DEFAULT_RIOT_PLATFORM: RiotPlatformRoute = 'kr';
|
||||||
const DEFAULT_RIOT_REGION: RiotRegionalRoute = 'asia';
|
const DEFAULT_RIOT_REGION: RiotRegionalRoute = 'asia';
|
||||||
|
|
||||||
|
export type KakaoDataTransferResult =
|
||||||
|
| 'transferred'
|
||||||
|
| 'already-linked'
|
||||||
|
| 'not-found'
|
||||||
|
| 'ambiguous'
|
||||||
|
| 'id-conflict'
|
||||||
|
| 'changed';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class DakaoUserService {
|
export class DakaoUserService {
|
||||||
private readonly logger = new Logger(DakaoUserService.name);
|
private readonly logger = new Logger(DakaoUserService.name);
|
||||||
@@ -87,7 +95,7 @@ export class DakaoUserService {
|
|||||||
if (!community) {
|
if (!community) {
|
||||||
throw new DakaoUserError('community_not_found', dakaoProjectId);
|
throw new DakaoUserError('community_not_found', dakaoProjectId);
|
||||||
}
|
}
|
||||||
return community._id as mongoose.Types.ObjectId;
|
return community._id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async upsertUser(params: {
|
public async upsertUser(params: {
|
||||||
@@ -127,6 +135,44 @@ export class DakaoUserService {
|
|||||||
}).exec();
|
}).exec();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async transferKakaoTalkId(params: {
|
||||||
|
communityId: mongoose.Types.ObjectId;
|
||||||
|
kakaoTalkId: string;
|
||||||
|
previousNickname: string;
|
||||||
|
}): Promise<KakaoDataTransferResult> {
|
||||||
|
const UserModel = await this.connectionService.getModel('user');
|
||||||
|
const targetFilter = {
|
||||||
|
communityId: params.communityId,
|
||||||
|
kakaoTalkNickname: params.previousNickname,
|
||||||
|
'riotAccounts.0': { $exists: true },
|
||||||
|
};
|
||||||
|
const candidates = await UserModel.find(targetFilter).limit(2).exec();
|
||||||
|
if (candidates.length === 0) return 'not-found';
|
||||||
|
if (candidates.length > 1) return 'ambiguous';
|
||||||
|
|
||||||
|
const user = candidates[0];
|
||||||
|
if (user.kakaoTalkId === params.kakaoTalkId) return 'already-linked';
|
||||||
|
const occupied = await this.findUserByKakaoTalkId(params);
|
||||||
|
if (occupied) return 'id-conflict';
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Compare the previous ID so concurrent transfers cannot overwrite one another.
|
||||||
|
const updated = await UserModel.findOneAndUpdate(
|
||||||
|
{
|
||||||
|
...targetFilter,
|
||||||
|
_id: user._id,
|
||||||
|
kakaoTalkId: user.kakaoTalkId ?? null,
|
||||||
|
},
|
||||||
|
{ $set: { kakaoTalkId: params.kakaoTalkId } },
|
||||||
|
{ returnDocument: 'after' },
|
||||||
|
).exec();
|
||||||
|
return updated ? 'transferred' : 'changed';
|
||||||
|
} catch (error) {
|
||||||
|
if ((error as { code?: number })?.code === 11000) return 'id-conflict';
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public async resolveRiotAccount(
|
public async resolveRiotAccount(
|
||||||
context: ResolveContext,
|
context: ResolveContext,
|
||||||
): Promise<ResolveResult> {
|
): Promise<ResolveResult> {
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { DakaoUserService } from './dakao-user.service';
|
|||||||
import { DakaoSendResultSubscriber } from './dakao-send-result.subscriber';
|
import { DakaoSendResultSubscriber } from './dakao-send-result.subscriber';
|
||||||
import { DakaoUrlShortenerService } from './dakao-url-shortener.service';
|
import { DakaoUrlShortenerService } from './dakao-url-shortener.service';
|
||||||
import { AccountRegisterHandler } from './handlers/account-register.handler';
|
import { AccountRegisterHandler } from './handlers/account-register.handler';
|
||||||
|
import { DataTransferHandler } from './handlers/data-transfer.handler';
|
||||||
import { MatchCancelHandler } from './handlers/match-cancel.handler';
|
import { MatchCancelHandler } from './handlers/match-cancel.handler';
|
||||||
import { MatchJoinHandler } from './handlers/match-join.handler';
|
import { MatchJoinHandler } from './handlers/match-join.handler';
|
||||||
import { MatchListHandler } from './handlers/match-list.handler';
|
import { MatchListHandler } from './handlers/match-list.handler';
|
||||||
@@ -35,6 +36,7 @@ import { PrimaryAccountChangeHandler } from './handlers/primary-account-change.h
|
|||||||
DakaoUserService,
|
DakaoUserService,
|
||||||
DakaoUrlShortenerService,
|
DakaoUrlShortenerService,
|
||||||
AccountRegisterHandler,
|
AccountRegisterHandler,
|
||||||
|
DataTransferHandler,
|
||||||
MatchListHandler,
|
MatchListHandler,
|
||||||
MatchJoinHandler,
|
MatchJoinHandler,
|
||||||
MatchCancelHandler,
|
MatchCancelHandler,
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ function makeSubscriber(): DakaoSubscriber {
|
|||||||
{} as never,
|
{} as never,
|
||||||
{} as never,
|
{} as never,
|
||||||
{} as never,
|
{} as never,
|
||||||
|
{} as never,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -39,6 +40,48 @@ const event = {
|
|||||||
} satisfies DakaoInboundEvent;
|
} satisfies DakaoInboundEvent;
|
||||||
|
|
||||||
describe('DakaoSubscriber', () => {
|
describe('DakaoSubscriber', () => {
|
||||||
|
it('routes data transfer with the current sender ID and publishes its reply', async () => {
|
||||||
|
const subscriber = makeSubscriber();
|
||||||
|
const segments = [{ kind: 'text', text: ' 데이터 이관 완료' }];
|
||||||
|
const handle = jest.fn().mockResolvedValue(segments);
|
||||||
|
const sendMessage = jest.fn();
|
||||||
|
const markProcessed = jest.fn();
|
||||||
|
Object.assign(subscriber, {
|
||||||
|
dakaoUserService: {
|
||||||
|
resolveCommunityIdByDakaoProjectId: async () => event.projectId,
|
||||||
|
},
|
||||||
|
dataTransferHandler: { handle },
|
||||||
|
publisher: { sendMessage },
|
||||||
|
inbox: { claim: async () => ({ status: 'claimed' }), markProcessed },
|
||||||
|
});
|
||||||
|
await (
|
||||||
|
subscriber as unknown as {
|
||||||
|
handleEvent: (input: DakaoInboundEvent) => Promise<void>;
|
||||||
|
}
|
||||||
|
).handleEvent({
|
||||||
|
...event,
|
||||||
|
origin: {
|
||||||
|
...event.origin,
|
||||||
|
chatLog: {
|
||||||
|
...event.origin.chatLog,
|
||||||
|
message: '!내전 데이터이관 예전 닉',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(handle).toHaveBeenCalledWith({
|
||||||
|
communityId: event.projectId,
|
||||||
|
senderUserId: '12345',
|
||||||
|
senderNickname: '프리리',
|
||||||
|
previousNickname: '예전 닉',
|
||||||
|
});
|
||||||
|
expect(sendMessage).toHaveBeenCalledWith({
|
||||||
|
chatroomId: 'chatroom-1',
|
||||||
|
segments,
|
||||||
|
correlationId: 'log-1',
|
||||||
|
});
|
||||||
|
expect(markProcessed).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
it('renders usage help with star emoticon command lines', () => {
|
it('renders usage help with star emoticon command lines', () => {
|
||||||
const subscriber = makeSubscriber() as unknown as {
|
const subscriber = makeSubscriber() as unknown as {
|
||||||
parseErrorReply: (
|
parseErrorReply: (
|
||||||
@@ -65,6 +108,8 @@ describe('DakaoSubscriber', () => {
|
|||||||
text: ' !내전 신청 코드 소환사이름#태그 포지션1,포지션2\u3000\n',
|
text: ' !내전 신청 코드 소환사이름#태그 포지션1,포지션2\u3000\n',
|
||||||
},
|
},
|
||||||
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
||||||
|
{ kind: 'text', text: ' !내전 취소 코드\u3000\n' },
|
||||||
|
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
||||||
{ kind: 'text', text: ' !내전 계정등록 소환사이름#태그\u3000\n' },
|
{ kind: 'text', text: ' !내전 계정등록 소환사이름#태그\u3000\n' },
|
||||||
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
||||||
{
|
{
|
||||||
@@ -74,8 +119,10 @@ describe('DakaoSubscriber', () => {
|
|||||||
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
||||||
{
|
{
|
||||||
kind: 'text',
|
kind: 'text',
|
||||||
text: ' !내전 대표계정변경 소환사이름#태그',
|
text: ' !내전 대표계정변경 소환사이름#태그\u3000\n',
|
||||||
},
|
},
|
||||||
|
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
||||||
|
{ kind: 'text', text: ' !내전 데이터이관 이전카카오톡채팅방닉네임' },
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { DakaoInboundEvent, DakaoLong, DakaoSegment } from './dakao.types';
|
|||||||
import { DakaoPublisher } from './dakao.publisher';
|
import { DakaoPublisher } from './dakao.publisher';
|
||||||
import { DakaoUserError, DakaoUserService } from './dakao-user.service';
|
import { DakaoUserError, DakaoUserService } from './dakao-user.service';
|
||||||
import { AccountRegisterHandler } from './handlers/account-register.handler';
|
import { AccountRegisterHandler } from './handlers/account-register.handler';
|
||||||
|
import { DataTransferHandler } from './handlers/data-transfer.handler';
|
||||||
import { MatchCancelHandler } from './handlers/match-cancel.handler';
|
import { MatchCancelHandler } from './handlers/match-cancel.handler';
|
||||||
import { MatchJoinHandler } from './handlers/match-join.handler';
|
import { MatchJoinHandler } from './handlers/match-join.handler';
|
||||||
import { MatchListHandler } from './handlers/match-list.handler';
|
import { MatchListHandler } from './handlers/match-list.handler';
|
||||||
@@ -24,9 +25,11 @@ export class DakaoSubscriber implements OnModuleInit {
|
|||||||
private readonly usageCommands = [
|
private readonly usageCommands = [
|
||||||
'!내전 일정',
|
'!내전 일정',
|
||||||
'!내전 신청 코드 소환사이름#태그 포지션1,포지션2',
|
'!내전 신청 코드 소환사이름#태그 포지션1,포지션2',
|
||||||
|
'!내전 취소 코드',
|
||||||
'!내전 계정등록 소환사이름#태그',
|
'!내전 계정등록 소환사이름#태그',
|
||||||
'!내전 선호포지션등록 포지션1,포지션2',
|
'!내전 선호포지션등록 포지션1,포지션2',
|
||||||
'!내전 대표계정변경 소환사이름#태그',
|
'!내전 대표계정변경 소환사이름#태그',
|
||||||
|
'!내전 데이터이관 이전카카오톡채팅방닉네임',
|
||||||
];
|
];
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
@@ -42,6 +45,7 @@ export class DakaoSubscriber implements OnModuleInit {
|
|||||||
private readonly matchCancelHandler: MatchCancelHandler,
|
private readonly matchCancelHandler: MatchCancelHandler,
|
||||||
private readonly preferredPositionRegisterHandler: PreferredPositionRegisterHandler,
|
private readonly preferredPositionRegisterHandler: PreferredPositionRegisterHandler,
|
||||||
private readonly primaryAccountChangeHandler: PrimaryAccountChangeHandler,
|
private readonly primaryAccountChangeHandler: PrimaryAccountChangeHandler,
|
||||||
|
private readonly dataTransferHandler: DataTransferHandler,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async onModuleInit() {
|
async onModuleInit() {
|
||||||
@@ -119,6 +123,14 @@ export class DakaoSubscriber implements OnModuleInit {
|
|||||||
const command = parseCommand(event.origin.chatLog.message);
|
const command = parseCommand(event.origin.chatLog.message);
|
||||||
|
|
||||||
switch (command.kind) {
|
switch (command.kind) {
|
||||||
|
case 'data-transfer':
|
||||||
|
segments = await this.dataTransferHandler.handle({
|
||||||
|
communityId,
|
||||||
|
senderUserId: event.userId,
|
||||||
|
senderNickname,
|
||||||
|
previousNickname: command.previousNickname,
|
||||||
|
});
|
||||||
|
break;
|
||||||
case 'match-list':
|
case 'match-list':
|
||||||
segments = await this.matchListHandler.handle({
|
segments = await this.matchListHandler.handle({
|
||||||
communityId,
|
communityId,
|
||||||
@@ -301,7 +313,7 @@ export class DakaoSubscriber implements OnModuleInit {
|
|||||||
text:
|
text:
|
||||||
index === this.usageCommands.length - 1
|
index === this.usageCommands.length - 1
|
||||||
? ` ${command}`
|
? ` ${command}`
|
||||||
: ` ${command} \n`,
|
: ` ${command}\u3000\n`,
|
||||||
} as const,
|
} as const,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import mongoose from 'mongoose';
|
||||||
|
import {
|
||||||
|
DakaoUserService,
|
||||||
|
KakaoDataTransferResult,
|
||||||
|
} from '../dakao-user.service';
|
||||||
|
import { DataTransferHandler } from './data-transfer.handler';
|
||||||
|
|
||||||
|
const params = {
|
||||||
|
communityId: new mongoose.Types.ObjectId(),
|
||||||
|
senderUserId: 'new-id',
|
||||||
|
senderNickname: '현재 닉',
|
||||||
|
previousNickname: '예전 닉',
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('DataTransferHandler', () => {
|
||||||
|
it.each<[KakaoDataTransferResult, string]>([
|
||||||
|
['transferred', '데이터 이관 완료'],
|
||||||
|
['already-linked', '이미 현재 카카오톡 계정에 연결'],
|
||||||
|
['not-found', '찾을 수 없습니다'],
|
||||||
|
['ambiguous', '여러 명'],
|
||||||
|
['id-conflict', '이미 다른 사용자'],
|
||||||
|
['changed', '변경되었습니다'],
|
||||||
|
])('replies to the sender for %s', async (result, message) => {
|
||||||
|
const transferKakaoTalkId = jest.fn().mockResolvedValue(result);
|
||||||
|
const handler = new DataTransferHandler({
|
||||||
|
transferKakaoTalkId,
|
||||||
|
} as unknown as DakaoUserService);
|
||||||
|
expect(await handler.handle(params)).toEqual([
|
||||||
|
{ kind: 'mention', userId: 'new-id', displayText: '현재 닉' },
|
||||||
|
{ kind: 'text', text: expect.stringContaining(message) },
|
||||||
|
]);
|
||||||
|
expect(transferKakaoTalkId).toHaveBeenCalledWith({
|
||||||
|
communityId: params.communityId,
|
||||||
|
kakaoTalkId: 'new-id',
|
||||||
|
previousNickname: '예전 닉',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('propagates unexpected failures', async () => {
|
||||||
|
const handler = new DataTransferHandler({
|
||||||
|
transferKakaoTalkId: jest
|
||||||
|
.fn()
|
||||||
|
.mockRejectedValue(new Error('database unavailable')),
|
||||||
|
} as unknown as DakaoUserService);
|
||||||
|
await expect(handler.handle(params)).rejects.toThrow(
|
||||||
|
'database unavailable',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
import {
|
||||||
|
DakaoUserService,
|
||||||
|
KakaoDataTransferResult,
|
||||||
|
} from '../dakao-user.service';
|
||||||
|
import { DakaoSegment } from '../dakao.types';
|
||||||
|
|
||||||
|
const RESULT_MESSAGES: Record<KakaoDataTransferResult, string> = {
|
||||||
|
transferred:
|
||||||
|
'데이터 이관 완료. 기존 라이엇 계정과 내전 기록이 현재 카카오톡 계정에 연결되었습니다.',
|
||||||
|
'already-linked': '이미 현재 카카오톡 계정에 연결된 사용자입니다.',
|
||||||
|
'not-found':
|
||||||
|
'해당 예전 닉네임으로 라이엇 계정이 등록된 사용자를 찾을 수 없습니다.',
|
||||||
|
ambiguous:
|
||||||
|
'같은 예전 닉네임으로 등록된 사용자가 여러 명입니다. 운영자에게 문의해주세요.',
|
||||||
|
'id-conflict':
|
||||||
|
'현재 카카오톡 계정에 이미 다른 사용자가 등록되어 있습니다. 운영자에게 문의해주세요.',
|
||||||
|
changed: '이관 중 사용자 정보가 변경되었습니다. 다시 시도해주세요.',
|
||||||
|
};
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class DataTransferHandler {
|
||||||
|
constructor(private readonly dakaoUserService: DakaoUserService) {}
|
||||||
|
|
||||||
|
public async handle(params: {
|
||||||
|
communityId: mongoose.Types.ObjectId;
|
||||||
|
senderUserId: string;
|
||||||
|
senderNickname: string;
|
||||||
|
previousNickname: string;
|
||||||
|
}): Promise<DakaoSegment[]> {
|
||||||
|
const result = await this.dakaoUserService.transferKakaoTalkId({
|
||||||
|
communityId: params.communityId,
|
||||||
|
kakaoTalkId: params.senderUserId,
|
||||||
|
previousNickname: params.previousNickname,
|
||||||
|
});
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
kind: 'mention',
|
||||||
|
userId: params.senderUserId,
|
||||||
|
displayText: params.senderNickname,
|
||||||
|
},
|
||||||
|
{ kind: 'text', text: ` ${RESULT_MESSAGES[result]}` },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -104,9 +104,11 @@ describe('MatchCancelHandler', () => {
|
|||||||
const handler = makeHandler({
|
const handler = makeHandler({
|
||||||
matchService: {
|
matchService: {
|
||||||
cancelJoin,
|
cancelJoin,
|
||||||
list: jest.fn().mockResolvedValue([
|
list: jest
|
||||||
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
|
.fn()
|
||||||
]),
|
.mockResolvedValue([
|
||||||
|
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
|
||||||
|
]),
|
||||||
} as Partial<MatchService>,
|
} as Partial<MatchService>,
|
||||||
dakaoUserService: {
|
dakaoUserService: {
|
||||||
findUserByKakaoTalkId,
|
findUserByKakaoTalkId,
|
||||||
|
|||||||
@@ -230,9 +230,11 @@ describe('MatchJoinHandler', () => {
|
|||||||
const resolveRiotAccount = jest.fn();
|
const resolveRiotAccount = jest.fn();
|
||||||
const handler = makeHandler({
|
const handler = makeHandler({
|
||||||
matchService: {
|
matchService: {
|
||||||
list: jest.fn().mockResolvedValue([
|
list: jest
|
||||||
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
|
.fn()
|
||||||
]),
|
.mockResolvedValue([
|
||||||
|
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
|
||||||
|
]),
|
||||||
join,
|
join,
|
||||||
} as Partial<MatchService>,
|
} as Partial<MatchService>,
|
||||||
dakaoUserService: {
|
dakaoUserService: {
|
||||||
@@ -282,9 +284,11 @@ describe('MatchJoinHandler', () => {
|
|||||||
const join = jest.fn();
|
const join = jest.fn();
|
||||||
const handler = makeHandler({
|
const handler = makeHandler({
|
||||||
matchService: {
|
matchService: {
|
||||||
list: jest.fn().mockResolvedValue([
|
list: jest
|
||||||
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
|
.fn()
|
||||||
]),
|
.mockResolvedValue([
|
||||||
|
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
|
||||||
|
]),
|
||||||
join,
|
join,
|
||||||
} as Partial<MatchService>,
|
} as Partial<MatchService>,
|
||||||
dakaoUserService: {
|
dakaoUserService: {
|
||||||
|
|||||||
@@ -44,9 +44,7 @@ export class MatchJoinHandler {
|
|||||||
return this.errorReply(params, joinTarget);
|
return this.errorReply(params, joinTarget);
|
||||||
}
|
}
|
||||||
|
|
||||||
let resolved:
|
let resolved: { user: UserDocument; riotAccount: RiotAccount } | string;
|
||||||
| { user: UserDocument; riotAccount: RiotAccount }
|
|
||||||
| string;
|
|
||||||
try {
|
try {
|
||||||
resolved =
|
resolved =
|
||||||
joinTarget.gameName && joinTarget.tagLine
|
joinTarget.gameName && joinTarget.tagLine
|
||||||
@@ -243,10 +241,7 @@ export class MatchJoinHandler {
|
|||||||
const gameName = normalizeRiotIdPart(value.slice(splitAt + 1));
|
const gameName = normalizeRiotIdPart(value.slice(splitAt + 1));
|
||||||
if (!matchTitlePrefix || !gameName) continue;
|
if (!matchTitlePrefix || !gameName) continue;
|
||||||
|
|
||||||
const result = resolveRecruitingMatchReference(
|
const result = resolveRecruitingMatchReference(matchTitlePrefix, matches);
|
||||||
matchTitlePrefix,
|
|
||||||
matches,
|
|
||||||
);
|
|
||||||
if (result.kind === 'matched') {
|
if (result.kind === 'matched') {
|
||||||
return { kind: 'matched', match: result.match, gameName };
|
return { kind: 'matched', match: result.match, gameName };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,6 +22,33 @@ function makeHandler(params: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe('MatchListHandler', () => {
|
describe('MatchListHandler', () => {
|
||||||
|
afterEach(() => {
|
||||||
|
jest.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('queries only matches scheduled at or after command processing time', async () => {
|
||||||
|
const now = new Date('2026-07-25T07:30:00.000Z');
|
||||||
|
jest.useFakeTimers().setSystemTime(now);
|
||||||
|
const communityId = objectId('111111111111111111111111');
|
||||||
|
const list = jest.fn().mockResolvedValue([]);
|
||||||
|
const handler = makeHandler({
|
||||||
|
matchService: { list },
|
||||||
|
});
|
||||||
|
|
||||||
|
await handler.handle({
|
||||||
|
communityId,
|
||||||
|
senderUserId: 'kakao-user-1',
|
||||||
|
senderNickname: '프리리',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(list).toHaveBeenCalledWith({
|
||||||
|
communityId,
|
||||||
|
status: 'recruiting',
|
||||||
|
scheduledFrom: now,
|
||||||
|
limit: 10,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it('prints short codes, compact KST dates, and short links', async () => {
|
it('prints short codes, compact KST dates, and short links', async () => {
|
||||||
const match = {
|
const match = {
|
||||||
_id: objectId('333333333333333333333333'),
|
_id: objectId('333333333333333333333333'),
|
||||||
|
|||||||
@@ -19,9 +19,11 @@ export class MatchListHandler {
|
|||||||
senderUserId: string;
|
senderUserId: string;
|
||||||
senderNickname: string;
|
senderNickname: string;
|
||||||
}): Promise<DakaoSegment[]> {
|
}): Promise<DakaoSegment[]> {
|
||||||
|
const scheduledFrom = new Date();
|
||||||
const matches = await this.matchService.list({
|
const matches = await this.matchService.list({
|
||||||
communityId: params.communityId,
|
communityId: params.communityId,
|
||||||
status: 'recruiting',
|
status: 'recruiting',
|
||||||
|
scheduledFrom,
|
||||||
limit: 10,
|
limit: 10,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -20,8 +20,8 @@ export class IdempotencyCache {
|
|||||||
public remember(key: string): void {
|
public remember(key: string): void {
|
||||||
this.evictExpired();
|
this.evictExpired();
|
||||||
if (this.entries.size >= MAX_ENTRIES) {
|
if (this.entries.size >= MAX_ENTRIES) {
|
||||||
const oldestKey = this.entries.keys().next().value;
|
const oldestKey: unknown = this.entries.keys().next().value;
|
||||||
if (oldestKey !== undefined) this.entries.delete(oldestKey);
|
if (typeof oldestKey === 'string') this.entries.delete(oldestKey);
|
||||||
}
|
}
|
||||||
this.entries.set(key, Date.now() + TTL_MS);
|
this.entries.set(key, Date.now() + TTL_MS);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,19 @@
|
|||||||
import { CommandParseError, parseCommand } from './command.parser';
|
import { CommandParseError, parseCommand } from './command.parser';
|
||||||
|
|
||||||
describe('parseCommand', () => {
|
describe('parseCommand', () => {
|
||||||
|
it('parses data transfer with the complete previous nickname', () => {
|
||||||
|
expect(parseCommand(' !내전 데이터이관 예전 닉.* ')).toEqual({
|
||||||
|
kind: 'data-transfer',
|
||||||
|
previousNickname: '예전 닉.*',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requires a previous nickname for data transfer', () => {
|
||||||
|
expect(() => parseCommand('!내전 데이터이관 ')).toThrow(
|
||||||
|
new CommandParseError('usage'),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it('parses match-list command (목록)', () => {
|
it('parses match-list command (목록)', () => {
|
||||||
expect(parseCommand('!내전 목록')).toEqual({ kind: 'match-list' });
|
expect(parseCommand('!내전 목록')).toEqual({ kind: 'match-list' });
|
||||||
});
|
});
|
||||||
@@ -22,7 +35,7 @@ describe('parseCommand', () => {
|
|||||||
matchAndRiotId: '69b63bc96da18dfdb218ee8c 프리리#KR1',
|
matchAndRiotId: '69b63bc96da18dfdb218ee8c 프리리#KR1',
|
||||||
});
|
});
|
||||||
if (result.kind === 'match-join') {
|
if (result.kind === 'match-join') {
|
||||||
expect(result.positions.positions).toEqual(['MID', 'TOP']);
|
expect(result.positions?.positions).toEqual(['MID', 'TOP']);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { normalizeRiotIdPart } from '../riot-id.util';
|
|||||||
|
|
||||||
export type DakaoCommand =
|
export type DakaoCommand =
|
||||||
| { kind: 'match-list' }
|
| { kind: 'match-list' }
|
||||||
|
| { kind: 'data-transfer'; previousNickname: string }
|
||||||
| {
|
| {
|
||||||
kind: 'account-register';
|
kind: 'account-register';
|
||||||
gameName: string;
|
gameName: string;
|
||||||
@@ -75,6 +76,9 @@ export function parseCommand(rawMessage: string): DakaoCommand {
|
|||||||
return parseCancelArgs(args);
|
return parseCancelArgs(args);
|
||||||
case '계정등록':
|
case '계정등록':
|
||||||
return parseAccountRegisterArgs(args);
|
return parseAccountRegisterArgs(args);
|
||||||
|
case '데이터이관':
|
||||||
|
if (!args) throw new CommandParseError('usage');
|
||||||
|
return { kind: 'data-transfer', previousNickname: args };
|
||||||
case '대표계정변경':
|
case '대표계정변경':
|
||||||
return parsePrimaryAccountChangeArgs(args);
|
return parsePrimaryAccountChangeArgs(args);
|
||||||
case '선호포지션등록':
|
case '선호포지션등록':
|
||||||
|
|||||||
@@ -144,7 +144,7 @@ export function buildDoubleEliminationBracket(
|
|||||||
teamIndex,
|
teamIndex,
|
||||||
}));
|
}));
|
||||||
const bracket: DoubleEliminationBracket = {
|
const bracket: DoubleEliminationBracket = {
|
||||||
teamCount: seededTeamIndexes.length as 4 | 8,
|
teamCount: seededTeamIndexes.length,
|
||||||
resetFinalEnabled: options.resetFinalEnabled,
|
resetFinalEnabled: options.resetFinalEnabled,
|
||||||
resetFinalCreated: false,
|
resetFinalCreated: false,
|
||||||
seeds,
|
seeds,
|
||||||
|
|||||||
@@ -19,7 +19,9 @@ describe('auction Redis schema foundation', () => {
|
|||||||
expect(AuctionSchema.path('revision')).toBeDefined();
|
expect(AuctionSchema.path('revision')).toBeDefined();
|
||||||
expect(AuctionSchema.path('auctionEngineVersion')).toBeDefined();
|
expect(AuctionSchema.path('auctionEngineVersion')).toBeDefined();
|
||||||
expect(AuctionSchema.path('auctionLifecycleId')).toBeDefined();
|
expect(AuctionSchema.path('auctionLifecycleId')).toBeDefined();
|
||||||
expect(AuctionSchema.path('lastAppliedAuctionStateTransitionId')).toBeDefined();
|
expect(
|
||||||
|
AuctionSchema.path('lastAppliedAuctionStateTransitionId'),
|
||||||
|
).toBeDefined();
|
||||||
expect(AuctionSchema.path('currentAuctionHistorySequence')).toBeDefined();
|
expect(AuctionSchema.path('currentAuctionHistorySequence')).toBeDefined();
|
||||||
expect(AuctionSchema.path('startAuctionRequestId')).toBeDefined();
|
expect(AuctionSchema.path('startAuctionRequestId')).toBeDefined();
|
||||||
expect(AuctionSchema.path('startAuctionStateTransitionId')).toBeDefined();
|
expect(AuctionSchema.path('startAuctionStateTransitionId')).toBeDefined();
|
||||||
@@ -36,46 +38,73 @@ describe('auction Redis schema foundation', () => {
|
|||||||
expect(AuctionSchema.path('auctionBidHistory')).toBeDefined();
|
expect(AuctionSchema.path('auctionBidHistory')).toBeDefined();
|
||||||
expect(AuctionSchema.path('currentHighestBidPointAmount')).toBeDefined();
|
expect(AuctionSchema.path('currentHighestBidPointAmount')).toBeDefined();
|
||||||
expect(AuctionSchema.path('currentHighestBidderTeamIndex')).toBeDefined();
|
expect(AuctionSchema.path('currentHighestBidderTeamIndex')).toBeDefined();
|
||||||
expect(AuctionSchema.path('currentBidRoundDeadlineTimestampMS')).toBeDefined();
|
expect(
|
||||||
|
AuctionSchema.path('currentBidRoundDeadlineTimestampMS'),
|
||||||
|
).toBeDefined();
|
||||||
expect(AuctionSchema.path('maximumBidRoundDurationSeconds')).toBeDefined();
|
expect(AuctionSchema.path('maximumBidRoundDurationSeconds')).toBeDefined();
|
||||||
expect(AuctionSchema.path('bidRoundExtensionSeconds')).toBeDefined();
|
expect(AuctionSchema.path('bidRoundExtensionSeconds')).toBeDefined();
|
||||||
expect(AuctionSchema.path('initialTeamBidPointAmount')).toBeDefined();
|
expect(AuctionSchema.path('initialTeamBidPointAmount')).toBeDefined();
|
||||||
expect(AuctionSchema.path('topTierAuctionPriorityThreshold')).toBeDefined();
|
expect(AuctionSchema.path('topTierAuctionPriorityThreshold')).toBeDefined();
|
||||||
expect(AuctionSchema.path('manualTopTierAuctionPriorityUserIds')).toBeDefined();
|
expect(
|
||||||
|
AuctionSchema.path('manualTopTierAuctionPriorityUserIds'),
|
||||||
|
).toBeDefined();
|
||||||
expect(AuctionSchema.path('auctionStartedAtTimestampMS')).toBeDefined();
|
expect(AuctionSchema.path('auctionStartedAtTimestampMS')).toBeDefined();
|
||||||
expect(AuctionSchema.path('auctionCompletedAtTimestampMS')).toBeDefined();
|
expect(AuctionSchema.path('auctionCompletedAtTimestampMS')).toBeDefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('adds history transition fields and reset/undo action enum values', () => {
|
it('adds history transition fields and reset/undo action enum values', () => {
|
||||||
expect(AuctionHistoryEntrySchema.path('auctionStateTransitionId')).toBeDefined();
|
expect(
|
||||||
|
AuctionHistoryEntrySchema.path('auctionStateTransitionId'),
|
||||||
|
).toBeDefined();
|
||||||
expect(AuctionHistoryEntrySchema.path('auctionLifecycleId')).toBeDefined();
|
expect(AuctionHistoryEntrySchema.path('auctionLifecycleId')).toBeDefined();
|
||||||
expect(AuctionHistoryEntrySchema.path('revision')).toBeDefined();
|
expect(AuctionHistoryEntrySchema.path('revision')).toBeDefined();
|
||||||
expect(AuctionHistoryEntrySchema.path('historyMutation')).toBeDefined();
|
expect(AuctionHistoryEntrySchema.path('historyMutation')).toBeDefined();
|
||||||
expect(AuctionHistoryEntrySchema.path('matchSideEffectMutation')).toBeDefined();
|
|
||||||
expect(
|
expect(
|
||||||
AuctionHistoryEntrySchema.path<string>('action').options.enum,
|
AuctionHistoryEntrySchema.path('matchSideEffectMutation'),
|
||||||
).toEqual(
|
).toBeDefined();
|
||||||
expect.arrayContaining(['start', 'open-bidding', 'bid', 'sold', 'passed', 'next', 'complete', 'reset', 'undo']),
|
expect(AuctionHistoryEntrySchema.path('action').options.enum).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
'start',
|
||||||
|
'open-bidding',
|
||||||
|
'bid',
|
||||||
|
'sold',
|
||||||
|
'passed',
|
||||||
|
'next',
|
||||||
|
'complete',
|
||||||
|
'reset',
|
||||||
|
'undo',
|
||||||
|
]),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('adds unique history indexes for sequence and transition idempotency', () => {
|
it('adds unique history indexes for sequence and transition idempotency', () => {
|
||||||
const indexes = AuctionHistoryEntrySchema.indexes();
|
const indexes = AuctionHistoryEntrySchema.indexes();
|
||||||
|
|
||||||
expect(indexWithKeys(indexes, { auctionId: 1, sequence: 1 })?.[1]).toMatchObject({
|
expect(
|
||||||
|
indexWithKeys(indexes, { auctionId: 1, sequence: 1 })?.[1],
|
||||||
|
).toMatchObject({
|
||||||
unique: true,
|
unique: true,
|
||||||
});
|
});
|
||||||
expect(
|
expect(
|
||||||
indexWithKeys(indexes, { auctionId: 1, auctionStateTransitionId: 1 })?.[1],
|
indexWithKeys(indexes, {
|
||||||
|
auctionId: 1,
|
||||||
|
auctionStateTransitionId: 1,
|
||||||
|
})?.[1],
|
||||||
).toMatchObject({ unique: true, sparse: true });
|
).toMatchObject({ unique: true, sparse: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('registers auction side effect application model with lease fields and unique idempotency index', () => {
|
it('registers auction side effect application model with lease fields and unique idempotency index', () => {
|
||||||
expect(AuctionSideEffectApplicationSchema.path('processingOwnerToken')).toBeDefined();
|
|
||||||
expect(
|
expect(
|
||||||
AuctionSideEffectApplicationSchema.path('processingLeaseExpiresAtTimestampMS'),
|
AuctionSideEffectApplicationSchema.path('processingOwnerToken'),
|
||||||
|
).toBeDefined();
|
||||||
|
expect(
|
||||||
|
AuctionSideEffectApplicationSchema.path(
|
||||||
|
'processingLeaseExpiresAtTimestampMS',
|
||||||
|
),
|
||||||
|
).toBeDefined();
|
||||||
|
expect(
|
||||||
|
AuctionSideEffectApplicationSchema.path('payloadChecksum'),
|
||||||
).toBeDefined();
|
).toBeDefined();
|
||||||
expect(AuctionSideEffectApplicationSchema.path('payloadChecksum')).toBeDefined();
|
|
||||||
|
|
||||||
const indexes = AuctionSideEffectApplicationSchema.indexes();
|
const indexes = AuctionSideEffectApplicationSchema.indexes();
|
||||||
expect(
|
expect(
|
||||||
|
|||||||
@@ -2,7 +2,10 @@ import { Injectable, Logger, Scope, OnModuleInit } from '@nestjs/common';
|
|||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import { applyMongoosePerformancePlugin } from '../observability/mongoose-performance.plugin';
|
import { applyMongoosePerformancePlugin } from '../observability/mongoose-performance.plugin';
|
||||||
import { SecretService } from '../secret/secret.service';
|
import { SecretService } from '../secret/secret.service';
|
||||||
import { tournamentModelDefinitions, TournamentModelTypes } from './schema';
|
import {
|
||||||
|
tournamentModelDefinitions,
|
||||||
|
type TournamentModelTypes,
|
||||||
|
} from './schema';
|
||||||
|
|
||||||
export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string {
|
export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string {
|
||||||
if (nodeEnv === 'prod') return 'lolympus';
|
if (nodeEnv === 'prod') return 'lolympus';
|
||||||
@@ -42,7 +45,8 @@ export class ConnectionService implements OnModuleInit {
|
|||||||
private connectionPromise: Promise<mongoose.Connection> | null = null;
|
private connectionPromise: Promise<mongoose.Connection> | null = null;
|
||||||
constructor(private readonly secretService: SecretService) {}
|
constructor(private readonly secretService: SecretService) {}
|
||||||
|
|
||||||
private tournamentModels: Map<string, mongoose.Model<any>> | null = null;
|
private tournamentModels: Map<keyof TournamentModelTypes, unknown> | null =
|
||||||
|
null;
|
||||||
|
|
||||||
public async getConnection(): Promise<mongoose.Connection> {
|
public async getConnection(): Promise<mongoose.Connection> {
|
||||||
if (
|
if (
|
||||||
@@ -89,14 +93,18 @@ export class ConnectionService implements OnModuleInit {
|
|||||||
modelKey: K,
|
modelKey: K,
|
||||||
): Promise<mongoose.Model<TournamentModelTypes[K]>> {
|
): Promise<mongoose.Model<TournamentModelTypes[K]>> {
|
||||||
const connection = await this.getConnection();
|
const connection = await this.getConnection();
|
||||||
if (this.tournamentModels)
|
if (this.tournamentModels) {
|
||||||
return this.tournamentModels.get(modelKey) as mongoose.Model<
|
return this.requireTournamentModel(this.tournamentModels, modelKey);
|
||||||
TournamentModelTypes[K]
|
}
|
||||||
>;
|
|
||||||
|
|
||||||
const models = new Map<K, mongoose.Model<TournamentModelTypes[K]>>();
|
const models = new Map<keyof TournamentModelTypes, unknown>();
|
||||||
|
|
||||||
tournamentModelDefinitions.forEach((modelDefinition) => {
|
tournamentModelDefinitions.forEach((modelDefinition) => {
|
||||||
|
if (!(modelDefinition.schema instanceof mongoose.Schema)) {
|
||||||
|
throw new Error(
|
||||||
|
`Invalid Mongoose schema for model ${modelDefinition.name}.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
applyMongoosePerformancePlugin(modelDefinition.schema);
|
applyMongoosePerformancePlugin(modelDefinition.schema);
|
||||||
// 이미 생성된 경우 컴파일 스킵.
|
// 이미 생성된 경우 컴파일 스킵.
|
||||||
if (
|
if (
|
||||||
@@ -106,14 +114,14 @@ export class ConnectionService implements OnModuleInit {
|
|||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
models.set(
|
models.set(
|
||||||
modelDefinition.name as K,
|
modelDefinition.name,
|
||||||
connection.models[modelDefinition.name],
|
connection.models[modelDefinition.name],
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
} else {
|
} else {
|
||||||
models.set(
|
models.set(
|
||||||
modelDefinition.name as K,
|
modelDefinition.name,
|
||||||
connection.model<TournamentModelTypes[K]>(
|
connection.model(
|
||||||
modelDefinition.name,
|
modelDefinition.name,
|
||||||
modelDefinition.schema,
|
modelDefinition.schema,
|
||||||
modelDefinition.schemaName,
|
modelDefinition.schemaName,
|
||||||
@@ -123,7 +131,18 @@ export class ConnectionService implements OnModuleInit {
|
|||||||
});
|
});
|
||||||
|
|
||||||
this.tournamentModels = models;
|
this.tournamentModels = models;
|
||||||
return models.get(modelKey) as mongoose.Model<TournamentModelTypes[K]>;
|
return this.requireTournamentModel(models, modelKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
private requireTournamentModel<K extends keyof TournamentModelTypes>(
|
||||||
|
models: ReadonlyMap<keyof TournamentModelTypes, unknown>,
|
||||||
|
modelKey: K,
|
||||||
|
): mongoose.Model<TournamentModelTypes[K]> {
|
||||||
|
const model = models.get(modelKey);
|
||||||
|
if (model === undefined) {
|
||||||
|
throw new Error(`Mongoose model ${modelKey} is not registered.`);
|
||||||
|
}
|
||||||
|
return model as mongoose.Model<TournamentModelTypes[K]>;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async createSession(
|
public async createSession(
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { DynamicModule, Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { ConnectionService } from './connection.service';
|
import { ConnectionService } from './connection.service';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
|
|||||||
@@ -45,7 +45,10 @@ export async function migrateAuctionPassHistory(
|
|||||||
};
|
};
|
||||||
}> = [];
|
}> = [];
|
||||||
|
|
||||||
for await (const doc of db.collection('auction').find({}).limit(options.limit ?? 0)) {
|
for await (const doc of db
|
||||||
|
.collection('auction')
|
||||||
|
.find({})
|
||||||
|
.limit(options.limit ?? 0)) {
|
||||||
stats.scannedAuctions += 1;
|
stats.scannedAuctions += 1;
|
||||||
const set: Record<string, unknown> = {};
|
const set: Record<string, unknown> = {};
|
||||||
let changed = false;
|
let changed = false;
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import { migrateTeamIndex } from './20260502-team-index';
|
import { migrateTeamIndex } from './20260502-team-index';
|
||||||
|
|
||||||
|
type MigrationDocument = Record<string, unknown> & { _id: unknown };
|
||||||
|
|
||||||
function createDb(params: {
|
function createDb(params: {
|
||||||
auctions?: Array<Record<string, unknown>>;
|
auctions?: MigrationDocument[];
|
||||||
matches?: Array<Record<string, unknown>>;
|
matches?: MigrationDocument[];
|
||||||
}) {
|
}) {
|
||||||
const collections = {
|
const collections = {
|
||||||
auction: params.auctions ?? [],
|
auction: params.auctions ?? [],
|
||||||
@@ -27,17 +29,21 @@ function createDb(params: {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
async bulkWrite(writes: Array<{
|
async bulkWrite(
|
||||||
updateOne: {
|
writes: Array<{
|
||||||
filter: { _id: unknown };
|
updateOne: {
|
||||||
update: {
|
filter: { _id: unknown };
|
||||||
$set: Record<string, unknown>;
|
update: {
|
||||||
$unset: Record<string, ''>;
|
$set: Record<string, unknown>;
|
||||||
|
$unset: Record<string, ''>;
|
||||||
|
};
|
||||||
};
|
};
|
||||||
};
|
}>,
|
||||||
}>) {
|
) {
|
||||||
for (const write of writes) {
|
for (const write of writes) {
|
||||||
const doc = docs.find((item) => item._id === write.updateOne.filter._id);
|
const doc = docs.find(
|
||||||
|
(item) => item._id === write.updateOne.filter._id,
|
||||||
|
);
|
||||||
if (!doc) continue;
|
if (!doc) continue;
|
||||||
Object.assign(doc, write.updateOne.update.$set);
|
Object.assign(doc, write.updateOne.update.$set);
|
||||||
for (const key of Object.keys(write.updateOne.update.$unset)) {
|
for (const key of Object.keys(write.updateOne.update.$unset)) {
|
||||||
@@ -57,7 +63,10 @@ describe('migrateTeamIndex', () => {
|
|||||||
auctions: [
|
auctions: [
|
||||||
{
|
{
|
||||||
_id: 'auction-1',
|
_id: 'auction-1',
|
||||||
teams: [{ side: 'blue', groupIndex: 1 }, { side: 'red', groupIndex: 1 }],
|
teams: [
|
||||||
|
{ side: 'blue', groupIndex: 1 },
|
||||||
|
{ side: 'red', groupIndex: 1 },
|
||||||
|
],
|
||||||
bids: [{ side: 'red', groupIndex: 1, amount: 100 }],
|
bids: [{ side: 'red', groupIndex: 1, amount: 100 }],
|
||||||
currentBidder: 'red',
|
currentBidder: 'red',
|
||||||
currentBidderGroupIndex: 1,
|
currentBidderGroupIndex: 1,
|
||||||
@@ -66,7 +75,10 @@ describe('migrateTeamIndex', () => {
|
|||||||
matches: [
|
matches: [
|
||||||
{
|
{
|
||||||
_id: 'match-1',
|
_id: 'match-1',
|
||||||
teams: [{ side: 'blue', groupIndex: 1 }, { side: 'red', groupIndex: 1 }],
|
teams: [
|
||||||
|
{ side: 'blue', groupIndex: 1 },
|
||||||
|
{ side: 'red', groupIndex: 1 },
|
||||||
|
],
|
||||||
result: {
|
result: {
|
||||||
winnerSide: 'blue',
|
winnerSide: 'blue',
|
||||||
blueScore: 1,
|
blueScore: 1,
|
||||||
@@ -112,7 +124,10 @@ describe('migrateTeamIndex', () => {
|
|||||||
currentBidderTeamIndex: 2,
|
currentBidderTeamIndex: 2,
|
||||||
});
|
});
|
||||||
expect(collections.match[0]).toMatchObject({
|
expect(collections.match[0]).toMatchObject({
|
||||||
teams: [{ teamIndex: 1, name: '1팀' }, { teamIndex: 2, name: '2팀' }],
|
teams: [
|
||||||
|
{ teamIndex: 1, name: '1팀' },
|
||||||
|
{ teamIndex: 2, name: '2팀' },
|
||||||
|
],
|
||||||
result: {
|
result: {
|
||||||
winnerTeamIndex: 1,
|
winnerTeamIndex: 1,
|
||||||
games: [
|
games: [
|
||||||
|
|||||||
@@ -45,8 +45,20 @@ export async function migrateTeamIndex(
|
|||||||
changedMatches: 0,
|
changedMatches: 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
await migrateCollection(db.collection('auction'), options.limit, dryRun, stats, 'auction');
|
await migrateCollection(
|
||||||
await migrateCollection(db.collection('match'), options.limit, dryRun, stats, 'match');
|
db.collection('auction'),
|
||||||
|
options.limit,
|
||||||
|
dryRun,
|
||||||
|
stats,
|
||||||
|
'auction',
|
||||||
|
);
|
||||||
|
await migrateCollection(
|
||||||
|
db.collection('match'),
|
||||||
|
options.limit,
|
||||||
|
dryRun,
|
||||||
|
stats,
|
||||||
|
'match',
|
||||||
|
);
|
||||||
|
|
||||||
return stats;
|
return stats;
|
||||||
}
|
}
|
||||||
@@ -60,7 +72,7 @@ async function migrateCollection(
|
|||||||
) {
|
) {
|
||||||
const cursor = collection.find({}).limit(limit ?? 0);
|
const cursor = collection.find({}).limit(limit ?? 0);
|
||||||
const writes: Array<{
|
const writes: Array<{
|
||||||
updateOne: {
|
updateOne: {
|
||||||
filter: { _id: unknown };
|
filter: { _id: unknown };
|
||||||
update: { $set: Record<string, unknown>; $unset: Record<string, ''> };
|
update: { $set: Record<string, unknown>; $unset: Record<string, ''> };
|
||||||
};
|
};
|
||||||
@@ -143,7 +155,8 @@ function migrateMatch(doc: AnyDoc) {
|
|||||||
const migrated = { ...team };
|
const migrated = { ...team };
|
||||||
const teamIndex = readTeamIndex(migrated);
|
const teamIndex = readTeamIndex(migrated);
|
||||||
if (teamIndex !== undefined) migrated.teamIndex = teamIndex;
|
if (teamIndex !== undefined) migrated.teamIndex = teamIndex;
|
||||||
if (!migrated.name && typeof teamIndex === 'number') migrated.name = `${teamIndex}팀`;
|
if (!migrated.name && typeof teamIndex === 'number')
|
||||||
|
migrated.name = `${teamIndex}팀`;
|
||||||
if ('side' in migrated || 'groupIndex' in migrated) changed = true;
|
if ('side' in migrated || 'groupIndex' in migrated) changed = true;
|
||||||
delete migrated.side;
|
delete migrated.side;
|
||||||
delete migrated.groupIndex;
|
delete migrated.groupIndex;
|
||||||
@@ -200,7 +213,10 @@ function migrateResult(result: Record<string, unknown>) {
|
|||||||
migrated.games = games;
|
migrated.games = games;
|
||||||
|
|
||||||
const seriesResults = asArray(result.seriesResults).map((series) => {
|
const seriesResults = asArray(result.seriesResults).map((series) => {
|
||||||
if (typeof series.teamAIndex === 'number' && typeof series.teamBIndex === 'number') {
|
if (
|
||||||
|
typeof series.teamAIndex === 'number' &&
|
||||||
|
typeof series.teamBIndex === 'number'
|
||||||
|
) {
|
||||||
return series;
|
return series;
|
||||||
}
|
}
|
||||||
changed = true;
|
changed = true;
|
||||||
@@ -216,7 +232,9 @@ function migrateResult(result: Record<string, unknown>) {
|
|||||||
const teamBIndex = Math.max(legacyBlueTeamIndex, legacyRedTeamIndex);
|
const teamBIndex = Math.max(legacyBlueTeamIndex, legacyRedTeamIndex);
|
||||||
const blueScore = numberOrDefault(series.blueScore, 0);
|
const blueScore = numberOrDefault(series.blueScore, 0);
|
||||||
const redScore = numberOrDefault(series.redScore, 0);
|
const redScore = numberOrDefault(series.redScore, 0);
|
||||||
const winnerSide = isSide(series.winnerSide) ? series.winnerSide : undefined;
|
const winnerSide = isSide(series.winnerSide)
|
||||||
|
? series.winnerSide
|
||||||
|
: undefined;
|
||||||
const winnerTeamIndex =
|
const winnerTeamIndex =
|
||||||
winnerSide === 'blue'
|
winnerSide === 'blue'
|
||||||
? legacyBlueTeamIndex
|
? legacyBlueTeamIndex
|
||||||
@@ -231,12 +249,11 @@ function migrateResult(result: Record<string, unknown>) {
|
|||||||
winnerTeamIndex,
|
winnerTeamIndex,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
migrated.seriesResults = seriesResults.length > 0 ? seriesResults : buildSeries(games);
|
migrated.seriesResults =
|
||||||
|
seriesResults.length > 0 ? seriesResults : buildSeries(games);
|
||||||
|
|
||||||
if (typeof migrated.winnerTeamIndex !== 'number') {
|
if (typeof migrated.winnerTeamIndex !== 'number') {
|
||||||
const migratedSeriesResults = Array.isArray(migrated.seriesResults)
|
const migratedSeriesResults = asArray(migrated.seriesResults);
|
||||||
? migrated.seriesResults
|
|
||||||
: [];
|
|
||||||
migrated.winnerTeamIndex =
|
migrated.winnerTeamIndex =
|
||||||
resolveWinnerTeamIndex(migratedSeriesResults) ??
|
resolveWinnerTeamIndex(migratedSeriesResults) ??
|
||||||
(isSide(migrated.winnerSide)
|
(isSide(migrated.winnerSide)
|
||||||
@@ -244,7 +261,11 @@ function migrateResult(result: Record<string, unknown>) {
|
|||||||
: undefined);
|
: undefined);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ('winnerSide' in migrated || 'blueScore' in migrated || 'redScore' in migrated) {
|
if (
|
||||||
|
'winnerSide' in migrated ||
|
||||||
|
'blueScore' in migrated ||
|
||||||
|
'redScore' in migrated
|
||||||
|
) {
|
||||||
changed = true;
|
changed = true;
|
||||||
}
|
}
|
||||||
delete migrated.winnerSide;
|
delete migrated.winnerSide;
|
||||||
@@ -272,8 +293,12 @@ function buildSeries(games: Record<string, unknown>[]) {
|
|||||||
const teamAIndex = Math.min(blueTeamIndex, redTeamIndex);
|
const teamAIndex = Math.min(blueTeamIndex, redTeamIndex);
|
||||||
const teamBIndex = Math.max(blueTeamIndex, redTeamIndex);
|
const teamBIndex = Math.max(blueTeamIndex, redTeamIndex);
|
||||||
const key = `${teamAIndex}:${teamBIndex}`;
|
const key = `${teamAIndex}:${teamBIndex}`;
|
||||||
const current =
|
const current = bySeries.get(key) ?? {
|
||||||
bySeries.get(key) ?? { teamAIndex, teamBIndex, teamAWins: 0, teamBWins: 0 };
|
teamAIndex,
|
||||||
|
teamBIndex,
|
||||||
|
teamAWins: 0,
|
||||||
|
teamBWins: 0,
|
||||||
|
};
|
||||||
if (winnerTeamIndex === teamAIndex) current.teamAWins += 1;
|
if (winnerTeamIndex === teamAIndex) current.teamAWins += 1;
|
||||||
if (winnerTeamIndex === teamBIndex) current.teamBWins += 1;
|
if (winnerTeamIndex === teamBIndex) current.teamBWins += 1;
|
||||||
current.winnerTeamIndex =
|
current.winnerTeamIndex =
|
||||||
@@ -331,5 +356,7 @@ function numberOrDefault(value: unknown, fallback: number) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function numberOrUndefined(value: unknown) {
|
function numberOrUndefined(value: unknown) {
|
||||||
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
return typeof value === 'number' && Number.isFinite(value)
|
||||||
|
? value
|
||||||
|
: undefined;
|
||||||
}
|
}
|
||||||
+16
-10
@@ -30,20 +30,26 @@ function createDb(params: { auctions?: Doc[]; history?: Doc[] }) {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
async bulkWrite(writes: Array<{
|
async bulkWrite(
|
||||||
updateOne: {
|
writes: Array<{
|
||||||
filter: { _id: unknown };
|
updateOne: {
|
||||||
update: {
|
filter: { _id: unknown };
|
||||||
$set?: Record<string, unknown>;
|
update: {
|
||||||
$unset?: Record<string, ''>;
|
$set?: Record<string, unknown>;
|
||||||
|
$unset?: Record<string, ''>;
|
||||||
|
};
|
||||||
};
|
};
|
||||||
};
|
}>,
|
||||||
}>) {
|
) {
|
||||||
for (const write of writes) {
|
for (const write of writes) {
|
||||||
const doc = docs.find((item) => item._id === write.updateOne.filter._id);
|
const doc = docs.find(
|
||||||
|
(item) => item._id === write.updateOne.filter._id,
|
||||||
|
);
|
||||||
if (!doc) continue;
|
if (!doc) continue;
|
||||||
Object.assign(doc, write.updateOne.update.$set ?? {});
|
Object.assign(doc, write.updateOne.update.$set ?? {});
|
||||||
for (const key of Object.keys(write.updateOne.update.$unset ?? {})) {
|
for (const key of Object.keys(
|
||||||
|
write.updateOne.update.$unset ?? {},
|
||||||
|
)) {
|
||||||
delete doc[key];
|
delete doc[key];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+14
-3
@@ -31,7 +31,10 @@ interface MigrationStats {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type AnyDoc = Record<string, unknown> & { _id: unknown };
|
type AnyDoc = Record<string, unknown> & { _id: unknown };
|
||||||
type UpdateDoc = { $set?: Record<string, unknown>; $unset?: Record<string, ''> };
|
type UpdateDoc = {
|
||||||
|
$set?: Record<string, unknown>;
|
||||||
|
$unset?: Record<string, ''>;
|
||||||
|
};
|
||||||
|
|
||||||
const AUCTION_FIELD_RENAMES: Array<{
|
const AUCTION_FIELD_RENAMES: Array<{
|
||||||
from: string;
|
from: string;
|
||||||
@@ -43,7 +46,11 @@ const AUCTION_FIELD_RENAMES: Array<{
|
|||||||
{ from: 'passedQueue', to: 'passedAuctionPlayerQueue' },
|
{ from: 'passedQueue', to: 'passedAuctionPlayerQueue' },
|
||||||
{ from: 'auctionRound', to: 'currentAuctionRound' },
|
{ from: 'auctionRound', to: 'currentAuctionRound' },
|
||||||
{ from: 'currentIndex', to: 'currentAuctionPlayerOrderIndex' },
|
{ from: 'currentIndex', to: 'currentAuctionPlayerOrderIndex' },
|
||||||
{ from: 'bids', to: 'auctionBidHistory', transform: transformAuctionBidHistory },
|
{
|
||||||
|
from: 'bids',
|
||||||
|
to: 'auctionBidHistory',
|
||||||
|
transform: transformAuctionBidHistory,
|
||||||
|
},
|
||||||
{ from: 'currentBid', to: 'currentHighestBidPointAmount' },
|
{ from: 'currentBid', to: 'currentHighestBidPointAmount' },
|
||||||
{ from: 'currentBidderTeamIndex', to: 'currentHighestBidderTeamIndex' },
|
{ from: 'currentBidderTeamIndex', to: 'currentHighestBidderTeamIndex' },
|
||||||
{
|
{
|
||||||
@@ -157,7 +164,8 @@ async function countDuplicateHistorySequences(
|
|||||||
const duplicates = new Set<string>();
|
const duplicates = new Set<string>();
|
||||||
for await (const doc of collection.find({}).limit(limit ?? 0)) {
|
for await (const doc of collection.find({}).limit(limit ?? 0)) {
|
||||||
const auctionId = stringifyId(doc.auctionId);
|
const auctionId = stringifyId(doc.auctionId);
|
||||||
const sequence = typeof doc.sequence === 'number' ? doc.sequence : undefined;
|
const sequence =
|
||||||
|
typeof doc.sequence === 'number' ? doc.sequence : undefined;
|
||||||
if (!auctionId || sequence === undefined) continue;
|
if (!auctionId || sequence === undefined) continue;
|
||||||
|
|
||||||
const key = `${auctionId}:${sequence}`;
|
const key = `${auctionId}:${sequence}`;
|
||||||
@@ -322,6 +330,9 @@ function legacyAuctionLifecycleId(value: unknown): string {
|
|||||||
|
|
||||||
function stringifyId(value: unknown): string | undefined {
|
function stringifyId(value: unknown): string | undefined {
|
||||||
if (value === undefined || value === null) return undefined;
|
if (value === undefined || value === null) return undefined;
|
||||||
|
// MongoDB ObjectId and migration fixture IDs intentionally rely on their
|
||||||
|
// stable string representation.
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-base-to-string
|
||||||
return typeof value === 'string' ? value : String(value);
|
return typeof value === 'string' ? value : String(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+3
-1
@@ -117,7 +117,9 @@ function createDb(params: {
|
|||||||
function matchesFilter(doc: Doc, filter: Record<string, unknown>): boolean {
|
function matchesFilter(doc: Doc, filter: Record<string, unknown>): boolean {
|
||||||
const clauses = filter.$or;
|
const clauses = filter.$or;
|
||||||
if (Array.isArray(clauses)) {
|
if (Array.isArray(clauses)) {
|
||||||
return clauses.some((clause) => matchesFilter(doc, clause));
|
return (clauses as unknown[]).some(
|
||||||
|
(clause) => isRecord(clause) && matchesFilter(doc, clause),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return Object.entries(filter).every(([key, value]) => {
|
return Object.entries(filter).every(([key, value]) => {
|
||||||
|
|||||||
+14
-16
@@ -1,11 +1,4 @@
|
|||||||
type TournamentCodeState =
|
type TournamentCodeState = string;
|
||||||
| 'available'
|
|
||||||
| 'reserved'
|
|
||||||
| 'used'
|
|
||||||
| 'released'
|
|
||||||
| 'expired'
|
|
||||||
| 'voided'
|
|
||||||
| string;
|
|
||||||
|
|
||||||
type AnyDoc = Record<string, unknown> & { _id: unknown };
|
type AnyDoc = Record<string, unknown> & { _id: unknown };
|
||||||
type IndexKey = Record<string, 1 | -1>;
|
type IndexKey = Record<string, 1 | -1>;
|
||||||
@@ -36,7 +29,7 @@ interface MigrationCollection {
|
|||||||
$unset?: Record<string, ''>;
|
$unset?: Record<string, ''>;
|
||||||
},
|
},
|
||||||
options?: { ordered?: boolean },
|
options?: { ordered?: boolean },
|
||||||
): Promise<{ matchedCount?: number; modifiedCount?: number } | unknown>;
|
): Promise<unknown>;
|
||||||
indexes?(): Promise<MigrationIndex[]>;
|
indexes?(): Promise<MigrationIndex[]>;
|
||||||
dropIndex?(name: string): Promise<unknown>;
|
dropIndex?(name: string): Promise<unknown>;
|
||||||
createIndex?(
|
createIndex?(
|
||||||
@@ -516,15 +509,17 @@ function summarizeGroups(
|
|||||||
function summarizeCode(doc: TournamentCodeDoc): TournamentCodeDuplicateSummary {
|
function summarizeCode(doc: TournamentCodeDoc): TournamentCodeDuplicateSummary {
|
||||||
return {
|
return {
|
||||||
bracketMatchId:
|
bracketMatchId:
|
||||||
doc.bracketMatchId === undefined ? undefined : String(doc.bracketMatchId),
|
doc.bracketMatchId === undefined
|
||||||
code: doc.code === undefined ? undefined : String(doc.code),
|
? undefined
|
||||||
|
: stringifyId(doc.bracketMatchId),
|
||||||
|
code: doc.code === undefined ? undefined : stringifyId(doc.code),
|
||||||
gameNumber:
|
gameNumber:
|
||||||
doc.gameNumber === undefined ? undefined : String(doc.gameNumber),
|
doc.gameNumber === undefined ? undefined : stringifyId(doc.gameNumber),
|
||||||
id: stringifyId(doc._id) ?? '',
|
id: stringifyId(doc._id) ?? '',
|
||||||
matchId: doc.matchId === undefined ? undefined : stringifyId(doc.matchId),
|
matchId: doc.matchId === undefined ? undefined : stringifyId(doc.matchId),
|
||||||
riotMatchId:
|
riotMatchId:
|
||||||
doc.riotMatchId === undefined ? undefined : String(doc.riotMatchId),
|
doc.riotMatchId === undefined ? undefined : stringifyId(doc.riotMatchId),
|
||||||
state: doc.state === undefined ? undefined : String(doc.state),
|
state: doc.state,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -749,16 +744,19 @@ function readModifiedCount(result: unknown): number {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function hasField(doc: Record<string, unknown>, key: string): boolean {
|
function hasField(doc: Record<string, unknown>, key: string): boolean {
|
||||||
return Object.prototype.hasOwnProperty.call(doc, key);
|
return Object.hasOwn(doc, key);
|
||||||
}
|
}
|
||||||
|
|
||||||
function stringifyKeyPart(value: unknown): string {
|
function stringifyKeyPart(value: unknown): string {
|
||||||
if (value === null) return '<null>';
|
if (value === null) return '<null>';
|
||||||
if (value === undefined) return '<undefined>';
|
if (value === undefined) return '<undefined>';
|
||||||
return stringifyId(value) ?? String(value);
|
return stringifyId(value) ?? '<unknown>';
|
||||||
}
|
}
|
||||||
|
|
||||||
function stringifyId(value: unknown): string | undefined {
|
function stringifyId(value: unknown): string | undefined {
|
||||||
if (value === undefined || value === null) return undefined;
|
if (value === undefined || value === null) return undefined;
|
||||||
|
// MongoDB ObjectId and migration fixture IDs intentionally rely on their
|
||||||
|
// stable string representation.
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-base-to-string
|
||||||
return typeof value === 'string' ? value : String(value);
|
return typeof value === 'string' ? value : String(value);
|
||||||
}
|
}
|
||||||
+8
@@ -40,6 +40,14 @@ describe('repair-double-elimination-series-rules buildRepairPlan', () => {
|
|||||||
{
|
{
|
||||||
gameNumber: 1,
|
gameNumber: 1,
|
||||||
bracketMatchId: 'WB_R2_M1',
|
bracketMatchId: 'WB_R2_M1',
|
||||||
|
riotMatchId: 'KR_1',
|
||||||
|
blueTeamIndex: 4,
|
||||||
|
redTeamIndex: 6,
|
||||||
|
winnerTeamIndex: 4,
|
||||||
|
winnerSide: 'blue',
|
||||||
|
gameCreation: Date.parse('2026-05-03T00:00:00.000Z'),
|
||||||
|
gameDuration: 1800,
|
||||||
|
participants: [],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
seriesResults: [],
|
seriesResults: [],
|
||||||
|
|||||||
+6
-2
@@ -11,7 +11,11 @@ import {
|
|||||||
} from '../../../double-elimination/double-elimination.util';
|
} from '../../../double-elimination/double-elimination.util';
|
||||||
import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../../../tournament-code/tournament-code.constants';
|
import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../../../tournament-code/tournament-code.constants';
|
||||||
import { ConnectionService } from '../connection.service';
|
import { ConnectionService } from '../connection.service';
|
||||||
import type { MatchDocument, TournamentCodeDocument } from '../schema';
|
import type {
|
||||||
|
MatchDocument,
|
||||||
|
TournamentCode,
|
||||||
|
TournamentCodeDocument,
|
||||||
|
} from '../schema';
|
||||||
import { SecretModule } from '../../secret/secret.module';
|
import { SecretModule } from '../../secret/secret.module';
|
||||||
|
|
||||||
interface CliOptions {
|
interface CliOptions {
|
||||||
@@ -334,7 +338,7 @@ function printPlan(plan: MatchRepairPlan) {
|
|||||||
async function applyPlan(
|
async function applyPlan(
|
||||||
match: MatchDocument,
|
match: MatchDocument,
|
||||||
plan: MatchRepairPlan,
|
plan: MatchRepairPlan,
|
||||||
TournamentCodeModel: mongoose.Model<any>,
|
TournamentCodeModel: mongoose.Model<TournamentCode>,
|
||||||
session: mongoose.ClientSession,
|
session: mongoose.ClientSession,
|
||||||
) {
|
) {
|
||||||
if (plan.skippedReason) return;
|
if (plan.skippedReason) return;
|
||||||
|
|||||||
+14
-12
@@ -5,10 +5,7 @@ import { NestFactory } from '@nestjs/core';
|
|||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import { readFile } from 'node:fs/promises';
|
import { readFile } from 'node:fs/promises';
|
||||||
import { resolve } from 'node:path';
|
import { resolve } from 'node:path';
|
||||||
import {
|
import { ConnectionService, resolveMongoDbName } from '../connection.service';
|
||||||
ConnectionService,
|
|
||||||
resolveMongoDbName,
|
|
||||||
} from '../connection.service';
|
|
||||||
import type {
|
import type {
|
||||||
MatchDocument,
|
MatchDocument,
|
||||||
MatchGameAssignment,
|
MatchGameAssignment,
|
||||||
@@ -214,12 +211,16 @@ async function main() {
|
|||||||
printPlan(options, match, codes, plan);
|
printPlan(options, match, codes, plan);
|
||||||
|
|
||||||
if (options.dryRun) {
|
if (options.dryRun) {
|
||||||
console.log('No writes were made. Re-run with --apply to update MongoDB.');
|
console.log(
|
||||||
|
'No writes were made. Re-run with --apply to update MongoDB.',
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const session = await (await connectionService.getConnection()).startSession();
|
const session = await (
|
||||||
|
await connectionService.getConnection()
|
||||||
|
).startSession();
|
||||||
try {
|
try {
|
||||||
await session.withTransaction(async () => {
|
await session.withTransaction(async () => {
|
||||||
await applyTournamentCodeUpdates(plan, now, session);
|
await applyTournamentCodeUpdates(plan, now, session);
|
||||||
@@ -230,9 +231,9 @@ async function main() {
|
|||||||
status: 'finished',
|
status: 'finished',
|
||||||
roundRobinMaxRounds: options.maxRounds,
|
roundRobinMaxRounds: options.maxRounds,
|
||||||
gameSchedule: plan.schedule,
|
gameSchedule: plan.schedule,
|
||||||
tournamentCodeIds: [
|
tournamentCodeIds: [...plan.usedCodeByOldGameNumber.values()].map(
|
||||||
...plan.usedCodeByOldGameNumber.values(),
|
(code) => code._id,
|
||||||
].map((code) => code._id),
|
),
|
||||||
resultPollState: {
|
resultPollState: {
|
||||||
startedAt: match.resultPollState?.startedAt ?? now,
|
startedAt: match.resultPollState?.startedAt ?? now,
|
||||||
lastPolledAt: now,
|
lastPolledAt: now,
|
||||||
@@ -423,7 +424,9 @@ function partitionIntoRounds(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!fillRound(0)) {
|
if (!fillRound(0)) {
|
||||||
throw new Error('Could not partition result games into simultaneous rounds.');
|
throw new Error(
|
||||||
|
'Could not partition result games into simultaneous rounds.',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return rounds;
|
return rounds;
|
||||||
@@ -586,8 +589,7 @@ function buildSeriesResults(games: MatchGameResult[]): MatchSeriesResult[] {
|
|||||||
}
|
}
|
||||||
return [...bySeries.values()].sort(
|
return [...bySeries.values()].sort(
|
||||||
(left, right) =>
|
(left, right) =>
|
||||||
left.teamAIndex - right.teamAIndex ||
|
left.teamAIndex - right.teamAIndex || left.teamBIndex - right.teamBIndex,
|
||||||
left.teamBIndex - right.teamBIndex,
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -219,9 +219,9 @@ async function listDuplicateHistorySequences(
|
|||||||
.toArray();
|
.toArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
function printDuplicateHistorySequences(groups: Awaited<
|
function printDuplicateHistorySequences(
|
||||||
ReturnType<typeof listDuplicateHistorySequences>
|
groups: Awaited<ReturnType<typeof listDuplicateHistorySequences>>,
|
||||||
>) {
|
) {
|
||||||
if (groups.length === 0) {
|
if (groups.length === 0) {
|
||||||
console.log('No duplicate auctionHistory auctionId+sequence groups found.');
|
console.log('No duplicate auctionHistory auctionId+sequence groups found.');
|
||||||
return;
|
return;
|
||||||
@@ -248,7 +248,8 @@ async function repairDuplicateHistorySequences(
|
|||||||
): Promise<DuplicateSequenceRepairStats> {
|
): Promise<DuplicateSequenceRepairStats> {
|
||||||
const historyCollection = db.collection('auctionHistory');
|
const historyCollection = db.collection('auctionHistory');
|
||||||
const auctionCollection = db.collection('auction');
|
const auctionCollection = db.collection('auction');
|
||||||
const affectedAuctionIds = await findAuctionIdsWithDuplicateHistorySequences(db);
|
const affectedAuctionIds =
|
||||||
|
await findAuctionIdsWithDuplicateHistorySequences(db);
|
||||||
const stats: DuplicateSequenceRepairStats = {
|
const stats: DuplicateSequenceRepairStats = {
|
||||||
affectedAuctions: affectedAuctionIds.length,
|
affectedAuctions: affectedAuctionIds.length,
|
||||||
changedAuctionSequenceFields: 0,
|
changedAuctionSequenceFields: 0,
|
||||||
|
|||||||
+4
-4
@@ -177,7 +177,9 @@ function parseArgs(argv: string[]): CliOptions {
|
|||||||
|
|
||||||
function parseCommitQuorum(value: string | undefined, label: string) {
|
function parseCommitQuorum(value: string | undefined, label: string) {
|
||||||
if (!value) {
|
if (!value) {
|
||||||
throw new Error(`${label} requires a positive integer, majority, or votingMembers.`);
|
throw new Error(
|
||||||
|
`${label} requires a positive integer, majority, or votingMembers.`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (value === 'majority' || value === 'votingMembers') return value;
|
if (value === 'majority' || value === 'votingMembers') return value;
|
||||||
return parsePositiveInteger(value, label);
|
return parsePositiveInteger(value, label);
|
||||||
@@ -230,9 +232,7 @@ function printDuplicateGroups(groups: TournamentCodeDuplicateGroupSummary[]) {
|
|||||||
kind: group.kind,
|
kind: group.kind,
|
||||||
loserCodes: group.losers.map((loser) => loser.code ?? '').join(', '),
|
loserCodes: group.losers.map((loser) => loser.code ?? '').join(', '),
|
||||||
loserIds: group.losers.map((loser) => loser.id).join(', '),
|
loserIds: group.losers.map((loser) => loser.id).join(', '),
|
||||||
loserStates: group.losers
|
loserStates: group.losers.map((loser) => loser.state ?? '').join(', '),
|
||||||
.map((loser) => loser.state ?? '')
|
|
||||||
.join(', '),
|
|
||||||
})),
|
})),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2485,7 +2485,9 @@ MatchStatsSchema.index({ communityId: 1, userIds: 1 });
|
|||||||
MatchStatsSchema.index({ communityId: 1, userIds: 1, scheduledAt: -1 });
|
MatchStatsSchema.index({ communityId: 1, userIds: 1, scheduledAt: -1 });
|
||||||
MatchStatsSchema.index({ communityId: 1, championIds: 1 });
|
MatchStatsSchema.index({ communityId: 1, championIds: 1 });
|
||||||
|
|
||||||
export const tournamentModelDefinitions: ModelDefinition[] = [
|
export const tournamentModelDefinitions: Array<
|
||||||
|
ModelDefinition & { name: keyof TournamentModelTypes }
|
||||||
|
> = [
|
||||||
...competitionModelDefinitions,
|
...competitionModelDefinitions,
|
||||||
{ name: 'identity', schema: IdentitySchema, schemaName: 'identity' },
|
{ name: 'identity', schema: IdentitySchema, schemaName: 'identity' },
|
||||||
{ name: 'community', schema: CommunitySchema, schemaName: 'community' },
|
{ name: 'community', schema: CommunitySchema, schemaName: 'community' },
|
||||||
|
|||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
export interface ModelDefinition {
|
export interface ModelDefinition {
|
||||||
name: string;
|
name: string;
|
||||||
schema: mongoose.Schema<any>;
|
schema: unknown;
|
||||||
schemaName?: string;
|
schemaName?: string;
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import fs from 'fs/promises';
|
|
||||||
import { connect } from 'nats';
|
import { connect } from 'nats';
|
||||||
import type { NatsConnection } from 'nats';
|
import type { NatsConnection } from 'nats';
|
||||||
import { SecretModule } from '../secret/secret.module';
|
import { SecretModule } from '../secret/secret.module';
|
||||||
|
|||||||
@@ -34,31 +34,32 @@ type SchemaWithPerformanceMarker = mongoose.Schema & {
|
|||||||
[PERFORMANCE_PLUGIN_APPLIED]?: boolean;
|
[PERFORMANCE_PLUGIN_APPLIED]?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function applyMongoosePerformancePlugin(schema: mongoose.Schema): void {
|
export function applyMongoosePerformancePlugin(schemaValue: unknown): void {
|
||||||
const markedSchema = schema as SchemaWithPerformanceMarker;
|
if (!(schemaValue instanceof mongoose.Schema)) {
|
||||||
if (markedSchema[PERFORMANCE_PLUGIN_APPLIED]) return;
|
throw new TypeError('Mongoose performance plugin requires a Schema.');
|
||||||
markedSchema[PERFORMANCE_PLUGIN_APPLIED] = true;
|
}
|
||||||
const hookableSchema = schema as any;
|
const schema = schemaValue as SchemaWithPerformanceMarker;
|
||||||
|
if (schema[PERFORMANCE_PLUGIN_APPLIED]) return;
|
||||||
|
schema[PERFORMANCE_PLUGIN_APPLIED] = true;
|
||||||
|
|
||||||
hookableSchema.pre(QUERY_OPERATION_REGEX, function () {
|
schema.pre(QUERY_OPERATION_REGEX, function () {
|
||||||
const query = this as QueryWithPerformanceState;
|
const query = this as QueryWithPerformanceState;
|
||||||
query[QUERY_PERFORMANCE_START] = process.hrtime.bigint();
|
query[QUERY_PERFORMANCE_START] = process.hrtime.bigint();
|
||||||
query[QUERY_PERFORMANCE_RECORDED] = false;
|
query[QUERY_PERFORMANCE_RECORDED] = false;
|
||||||
});
|
});
|
||||||
|
|
||||||
hookableSchema.post(
|
schema.post(QUERY_OPERATION_REGEX, function (result: unknown) {
|
||||||
QUERY_OPERATION_REGEX,
|
recordQueryPerformance(this as QueryWithPerformanceState, result);
|
||||||
function (result: unknown) {
|
});
|
||||||
recordQueryPerformance(
|
|
||||||
this as unknown as QueryWithPerformanceState,
|
|
||||||
result,
|
|
||||||
);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
hookableSchema.post(
|
schema.post(
|
||||||
QUERY_OPERATION_REGEX,
|
QUERY_OPERATION_REGEX,
|
||||||
function (error: unknown, _result: unknown, next: (error: unknown) => void) {
|
{ errorHandler: true },
|
||||||
|
function (
|
||||||
|
error: Error,
|
||||||
|
_result: unknown,
|
||||||
|
next: (error?: mongoose.CallbackError) => void,
|
||||||
|
) {
|
||||||
recordQueryPerformance(
|
recordQueryPerformance(
|
||||||
this as unknown as QueryWithPerformanceState,
|
this as unknown as QueryWithPerformanceState,
|
||||||
undefined,
|
undefined,
|
||||||
@@ -68,19 +69,24 @@ export function applyMongoosePerformancePlugin(schema: mongoose.Schema): void {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
hookableSchema.pre('aggregate', function () {
|
schema.pre('aggregate', function () {
|
||||||
const aggregate = this as AggregateWithPerformanceState;
|
const aggregate = this as AggregateWithPerformanceState;
|
||||||
aggregate[QUERY_PERFORMANCE_START] = process.hrtime.bigint();
|
aggregate[QUERY_PERFORMANCE_START] = process.hrtime.bigint();
|
||||||
aggregate[QUERY_PERFORMANCE_RECORDED] = false;
|
aggregate[QUERY_PERFORMANCE_RECORDED] = false;
|
||||||
});
|
});
|
||||||
|
|
||||||
hookableSchema.post('aggregate', function (result: unknown) {
|
schema.post('aggregate', function (result: unknown) {
|
||||||
recordAggregatePerformance(this as AggregateWithPerformanceState, result);
|
recordAggregatePerformance(this as AggregateWithPerformanceState, result);
|
||||||
});
|
});
|
||||||
|
|
||||||
hookableSchema.post(
|
schema.post(
|
||||||
'aggregate',
|
'aggregate',
|
||||||
function (error: unknown, _result: unknown, next: (error: unknown) => void) {
|
{ errorHandler: true },
|
||||||
|
function (
|
||||||
|
error: Error,
|
||||||
|
_result: unknown,
|
||||||
|
next: (error?: mongoose.CallbackError) => void,
|
||||||
|
) {
|
||||||
recordAggregatePerformance(
|
recordAggregatePerformance(
|
||||||
this as AggregateWithPerformanceState,
|
this as AggregateWithPerformanceState,
|
||||||
undefined,
|
undefined,
|
||||||
@@ -164,8 +170,8 @@ export function countHydratedDocuments(result: unknown): number {
|
|||||||
function isHydratedDocument(value: unknown): boolean {
|
function isHydratedDocument(value: unknown): boolean {
|
||||||
return Boolean(
|
return Boolean(
|
||||||
value &&
|
value &&
|
||||||
typeof value === 'object' &&
|
typeof value === 'object' &&
|
||||||
'$__' in (value as Record<string, unknown>),
|
'$__' in (value as Record<string, unknown>),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,9 +11,7 @@ interface NewRelicCustomEventApi {
|
|||||||
eventType: string,
|
eventType: string,
|
||||||
attributes: Record<string, NewRelicAttributeValue>,
|
attributes: Record<string, NewRelicAttributeValue>,
|
||||||
): void;
|
): void;
|
||||||
addCustomAttributes(
|
addCustomAttributes(attributes: Record<string, NewRelicAttributeValue>): void;
|
||||||
attributes: Record<string, NewRelicAttributeValue>,
|
|
||||||
): void;
|
|
||||||
setTransactionName(name: string): void;
|
setTransactionName(name: string): void;
|
||||||
}
|
}
|
||||||
const agent = newrelicAgent as unknown as NewRelicCustomEventApi;
|
const agent = newrelicAgent as unknown as NewRelicCustomEventApi;
|
||||||
|
|||||||
@@ -52,8 +52,7 @@ export interface ApiRequestPerformanceEvent {
|
|||||||
leanQueryCount: number;
|
leanQueryCount: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MongooseQueryPerformanceEvent
|
export interface MongooseQueryPerformanceEvent extends MongooseQueryPerformance {
|
||||||
extends MongooseQueryPerformance {
|
|
||||||
type: 'mongoose-query';
|
type: 'mongoose-query';
|
||||||
timestamp: string;
|
timestamp: string;
|
||||||
requestId?: string;
|
requestId?: string;
|
||||||
@@ -92,10 +91,7 @@ export function resolveApiPerformanceConfig(
|
|||||||
const enabled = readBoolean(env.API_PERF_OBSERVABILITY_ENABLED, false);
|
const enabled = readBoolean(env.API_PERF_OBSERVABILITY_ENABLED, false);
|
||||||
return {
|
return {
|
||||||
enabled,
|
enabled,
|
||||||
localEventsEnabled: readBoolean(
|
localEventsEnabled: readBoolean(env.API_PERF_LOCAL_EVENTS_ENABLED, enabled),
|
||||||
env.API_PERF_LOCAL_EVENTS_ENABLED,
|
|
||||||
enabled,
|
|
||||||
),
|
|
||||||
localEventFile:
|
localEventFile:
|
||||||
env.API_PERF_LOCAL_EVENT_FILE || '/tmp/lolympus-api-performance.ndjson',
|
env.API_PERF_LOCAL_EVENT_FILE || '/tmp/lolympus-api-performance.ndjson',
|
||||||
newRelicRequestEventsEnabled: readBoolean(
|
newRelicRequestEventsEnabled: readBoolean(
|
||||||
|
|||||||
Loaded 100 of 218 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user