Compare commits
35
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0d7617e2d2 | ||
|
|
20e1e6ec04 | ||
|
|
664af15255 | ||
|
|
7e0cd7cb19 | ||
|
|
38a89b5374 | ||
|
|
da7b502936 | ||
|
|
f649490cd2 | ||
|
|
f2eec479d9 | ||
|
|
ef141a13d0 | ||
|
|
f622ee5b1f | ||
|
|
4b8ccf0077 | ||
|
|
0c4c4239ec | ||
|
|
9117c9c0a4 | ||
|
|
5bc748dc4d | ||
|
|
de84ad5309 | ||
|
|
cd1525c87a | ||
|
|
58e24ccd75 | ||
|
|
384d460ad6 | ||
|
|
904f1fc4a4 | ||
|
|
f526257d9c | ||
|
|
34a47c053e | ||
|
|
e3f39fd8b8 | ||
|
|
4385ba7b8b | ||
|
|
9cd5850d43 | ||
|
|
79534cf43c | ||
|
|
03be85d07b | ||
|
|
d269bdd92b | ||
|
|
760da1cbea | ||
|
|
ac0d2b53f0 | ||
|
|
a24726d7da | ||
|
|
9e2f2c61e7 | ||
|
|
1f75c6318a | ||
|
|
8ec9edc35f | ||
|
|
61f1db0e6a | ||
|
|
c155f26272 |
No files matched your search
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"version": "0.0.1",
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"name": "web-staging",
|
||||||
|
"runtimeExecutable": "pnpm",
|
||||||
|
"runtimeArgs": ["--filter", "web", "start:staging"],
|
||||||
|
"port": 5173
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
+5
-7
@@ -19,17 +19,15 @@ website/LICENSE
|
|||||||
|
|
||||||
*.log
|
*.log
|
||||||
|
|
||||||
!.claude/settings.json
|
|
||||||
|
|
||||||
*.temp.MD
|
*.temp.MD
|
||||||
|
|
||||||
*.md
|
*.md
|
||||||
!README.md
|
!README.md
|
||||||
!AGENTS.md
|
!design-qa.md
|
||||||
!docs/specs/internal-match-game-analysis.md
|
!docs/specs/home-banner-production.md
|
||||||
!docs/plans/internal-match-game-analysis-p0-p1.md
|
!docs/specs/match-status-and-result-presentation.md
|
||||||
!agents/**/*.md
|
!docs/ux-audit-2026-11-10/06-ui-improvement-review.md
|
||||||
!skills/**/*.md
|
!docs/ux-audit-2026-11-10/07-visual-design-review.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`.
|
|
||||||
@@ -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,23 @@ 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 인스턴스를 같은 버전으로 함께 전환해야 합니다.
|
||||||
|
|
||||||
|
스트림이 계속 커지면 소비자 그룹별 미처리 항목을 확인합니다. 사용이 중단된 그룹도 미처리 항목을 계속 보존할 수 있습니다.
|
||||||
|
|
||||||
### 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` 설정을 읽습니다.
|
||||||
@@ -157,6 +173,8 @@ API 성능 계측은 기본 비활성화이며 필요할 때 `API_PERF_OBSERVABI
|
|||||||
|
|
||||||
카카오톡 기반 명령어 기능은 Dakao(커스텀 카카오톡 게이트웨이) 연동이 필요합니다. Dakao가 실행 중이 아니거나 NATS를 통해 API 서버와 연결되어 있지 않으면 일정 조회, 내전 참가, 참가 취소, 계정 등록 같은 카카오톡 명령어는 사용할 수 없습니다.
|
카카오톡 기반 명령어 기능은 Dakao(커스텀 카카오톡 게이트웨이) 연동이 필요합니다. Dakao가 실행 중이 아니거나 NATS를 통해 API 서버와 연결되어 있지 않으면 일정 조회, 내전 참가, 참가 취소, 계정 등록 같은 카카오톡 명령어는 사용할 수 없습니다.
|
||||||
|
|
||||||
|
카카오톡 방을 옮긴 뒤에는 새 방에서 `!내전 데이터이관 예전 닉네임`을 실행합니다. 같은 커뮤니티에서 Riot 계정이 등록된 기존 사용자의 카카오톡 ID만 바뀝니다. 기존 사용자 ID, 권한, 참가 기록은 유지됩니다. 닉네임이 중복되거나 새 ID가 이미 다른 사용자에 연결돼 있으면 운영자가 확인합니다. 계정 소유권 확인은 운영 절차에서 담당합니다.
|
||||||
|
|
||||||
## 커맨드
|
## 커맨드
|
||||||
|
|
||||||
| Command | Description |
|
| Command | Description |
|
||||||
@@ -164,6 +182,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).
|
|
||||||
@@ -62,6 +62,92 @@ $ pnpm run test:e2e
|
|||||||
|
|
||||||
# test coverage
|
# test coverage
|
||||||
$ pnpm run test:cov
|
$ pnpm run test:cov
|
||||||
|
|
||||||
|
# auction cancellation/undo transactions against a real local MongoDB replica set
|
||||||
|
$ pnpm run test:mongodb
|
||||||
|
```
|
||||||
|
|
||||||
|
`test:mongodb` requires `mongod` on PATH, or `MONGODB_TEST_SERVER` set to its
|
||||||
|
executable path. The runner starts an isolated replica set on a random loopback
|
||||||
|
port, uses a temporary database directory, and removes it after the tests. It
|
||||||
|
does not use the application's database connection settings.
|
||||||
|
|
||||||
|
## Auction durability
|
||||||
|
|
||||||
|
Accepted Redis bids now enter `auction:bidArchivePayloads` and
|
||||||
|
`auction:bidArchiveQueue` atomically with the bid. The durability scheduler saves
|
||||||
|
them to `auctionBidRecords` using deterministic IDs before removing queue entries.
|
||||||
|
Recent state snapshots remain capped at 1000 bids; the archive is not capped and
|
||||||
|
retains accepted bids across undo/cancellation for audit. These records begin with
|
||||||
|
this deployment; bids already discarded by an older version cannot be recovered.
|
||||||
|
`GET /communities/:communityId/matches/:matchId/auction/bids/history` pages through
|
||||||
|
the current lifecycle's persisted archive using `afterRevision` and `limit` (1–200).
|
||||||
|
Persistence is asynchronous, so an empty last page may gain entries afterward.
|
||||||
|
|
||||||
|
Invalid archive entries are moved atomically to `auction:bidArchiveDeadLetterQueue`
|
||||||
|
and `auction:bidArchiveDeadLetterPayloads`. The payload stores the original text
|
||||||
|
(or `null` for a missing payload), error, ID, and quarantine time. Monitor these
|
||||||
|
keys and review quarantined data before repairing/requeuing it; it is not retried
|
||||||
|
automatically or expired. Other bids continue to persist. Mongo write failures
|
||||||
|
leave valid entries in the pending queue for idempotent retries.
|
||||||
|
|
||||||
|
Older in-flight rounds can produce `bidRoundId: ''`; the archive treats this as
|
||||||
|
an absent optional round ID. Empty player IDs and other invalid field types
|
||||||
|
remain validation errors.
|
||||||
|
|
||||||
|
Cancellation commits its completion marker and pending cleanup fields in Match.
|
||||||
|
The scheduler retries cleanup after restarts, with a delay capped at 60 seconds.
|
||||||
|
Reset notifications include the lifecycle to protect a newly started auction.
|
||||||
|
Dead-letter status notifications use `auction:deadLetterStatusQueue`; failures to
|
||||||
|
persist or mirror the terminal status are retried without rerunning the side effect.
|
||||||
|
Older side-effect dead letters are also reconciled automatically.
|
||||||
|
|
||||||
|
Before deploying the cleanup worker, create its partial Match index using the
|
||||||
|
additive, repeatable migration below. Schema declarations alone do not create
|
||||||
|
indexes when `MONGODB_AUTO_INDEX` is disabled (the default). Choose the target
|
||||||
|
environment explicitly; dry-run does not create indexes or modify documents.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm --filter api auction:indexes -- --env staging --dry-run
|
||||||
|
pnpm --filter api auction:indexes -- --env staging --apply
|
||||||
|
# Use --env prod for production.
|
||||||
|
```
|
||||||
|
|
||||||
|
The index is `{ auctionCancellationCleanupRetryAt: 1 }`, restricted to
|
||||||
|
`{ auctionCancellationCleanupPending: true }`. The worker only reads due pending
|
||||||
|
entries; it no longer scans legacy cancellation markers without a pending flag.
|
||||||
|
|
||||||
|
## Riot archive recovery
|
||||||
|
|
||||||
|
Newly saved or repaired Riot match data refreshes affected internal match
|
||||||
|
statistics at the same Competition revision. Existing archives and duplicate
|
||||||
|
imports do not trigger recovery. Recovery failures are logged and do not block
|
||||||
|
result collection or match refresh. Only communities with recovered statistics
|
||||||
|
have their caches invalidated, once per recovery batch; one failed rebuild does
|
||||||
|
not prevent other successful rebuilds from being reflected. Detail
|
||||||
|
requests also check for newly archived data when a cached game is missing raw
|
||||||
|
data. An absent archive does not trigger a rebuild or a Riot match fetch. If a
|
||||||
|
detail rebuild makes no progress, the process waits 60 seconds before retrying
|
||||||
|
that source revision and does not invalidate the community cache.
|
||||||
|
|
||||||
|
Recovery cache invalidations first try Redis with a one-second command timeout.
|
||||||
|
On failure they return immediately and schedule up to three in-process retries,
|
||||||
|
waiting 1, 5, then 30 seconds between attempts. A community has one retry budget;
|
||||||
|
additional immediate failures do not reset it, and a successful current request
|
||||||
|
cancels the pending retry. Timers are unreferenced and cleared on shutdown.
|
||||||
|
Retries are not persisted or resumed after a restart. Detail requests detect
|
||||||
|
newly archived raw data even behind a stale cache, and other response caches
|
||||||
|
expire after five minutes. A detail response whose immediate invalidation fails
|
||||||
|
is returned without being cached. No Mongo invalidation collection or periodic
|
||||||
|
queue scan is used.
|
||||||
|
|
||||||
|
Before deploying this recovery path, add its Riot ID lookup index. The migration
|
||||||
|
defaults to dry-run and leaves other indexes and game records unchanged.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm --filter api stats:indexes -- --env staging --dry-run
|
||||||
|
pnpm --filter api stats:indexes -- --env staging --apply
|
||||||
|
# Use --env prod for production.
|
||||||
```
|
```
|
||||||
|
|
||||||
## Deployment
|
## Deployment
|
||||||
|
|||||||
@@ -9,6 +9,9 @@
|
|||||||
"build": "nest build",
|
"build": "nest build",
|
||||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
"competition:migrate": "ts-node src/modules/global/database/migrations/run-competition-domain.ts",
|
"competition:migrate": "ts-node src/modules/global/database/migrations/run-competition-domain.ts",
|
||||||
|
"competition:repair-grand-final": "ts-node src/modules/global/database/migrations/repair-grand-final-bo3.ts",
|
||||||
|
"auction:indexes": "ts-node src/modules/global/database/migrations/run-auction-cancellation-index.ts",
|
||||||
|
"stats:indexes": "ts-node src/modules/global/database/migrations/run-match-stats-raw-index.ts",
|
||||||
"seed:dev": "ts-node src/seed.ts",
|
"seed:dev": "ts-node src/seed.ts",
|
||||||
"seed:dakao-participant": "ts-node src/seed-dakao-participant.ts",
|
"seed:dakao-participant": "ts-node src/seed-dakao-participant.ts",
|
||||||
"start:dev": "NODE_ENV=dev NEW_RELIC_HOME=. node --import newrelic/esm-loader.mjs -r newrelic dist/main.js",
|
"start:dev": "NODE_ENV=dev NEW_RELIC_HOME=. node --import newrelic/esm-loader.mjs -r newrelic dist/main.js",
|
||||||
@@ -22,6 +25,9 @@
|
|||||||
"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:mongodb": "node test/run-mongo-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",
|
||||||
|
|||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { AuctionBidArchiveService } from './auction-bid-archive.service';
|
||||||
|
|
||||||
|
const matchId = new mongoose.Types.ObjectId().toString();
|
||||||
|
|
||||||
|
function bid(overrides: Record<string, unknown> = {}) {
|
||||||
|
return {
|
||||||
|
_id: `${matchId}:life:${String(1).padStart(16, '0')}`,
|
||||||
|
matchId,
|
||||||
|
auctionLifecycleId: 'life',
|
||||||
|
revision: 1,
|
||||||
|
bidRequestId: 'bid-1',
|
||||||
|
bidderUserId: new mongoose.Types.ObjectId().toString(),
|
||||||
|
playerUserId: new mongoose.Types.ObjectId().toString(),
|
||||||
|
bidderTeamIndex: 1,
|
||||||
|
bidPointAmount: 10,
|
||||||
|
bidPlacedAtTimestampMS: 1_700_000_000_000,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function fixture(payload: Record<string, unknown>) {
|
||||||
|
const raw = JSON.stringify(payload);
|
||||||
|
const commands: string[][] = [];
|
||||||
|
const sendCommand = jest.fn(async (command: string[]) => {
|
||||||
|
commands.push(command);
|
||||||
|
if (command[0] === 'ZRANGE') return [payload._id];
|
||||||
|
if (command[0] === 'HMGET') return [raw];
|
||||||
|
return 1;
|
||||||
|
});
|
||||||
|
const bulkWrite = jest.fn(async (operations: unknown[]) => ({
|
||||||
|
matchedCount: 0,
|
||||||
|
upsertedCount: operations.length,
|
||||||
|
}));
|
||||||
|
const service = new AuctionBidArchiveService(
|
||||||
|
{ getModel: async () => ({ bulkWrite }) } as never,
|
||||||
|
{ raw: () => ({ sendCommand }) } as never,
|
||||||
|
);
|
||||||
|
return { service, bulkWrite, commands };
|
||||||
|
}
|
||||||
|
|
||||||
|
function savedEvent(bulkWrite: jest.Mock) {
|
||||||
|
const [[operations]] = bulkWrite.mock.calls as unknown as [
|
||||||
|
[
|
||||||
|
Array<{
|
||||||
|
updateOne: { update: { $setOnInsert: Record<string, unknown> } };
|
||||||
|
}>,
|
||||||
|
],
|
||||||
|
];
|
||||||
|
return operations[0].updateOne.update.$setOnInsert;
|
||||||
|
}
|
||||||
|
|
||||||
|
function quarantined(commands: string[][]) {
|
||||||
|
return commands.some(
|
||||||
|
(command) =>
|
||||||
|
command[0] === 'EVAL' &&
|
||||||
|
command[1].includes("redis.call('ZADD', KEYS[4]"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
it('archives a pre-upgrade bid with an empty round ID without the field', async () => {
|
||||||
|
const f = fixture(bid({ bidRoundId: '' }));
|
||||||
|
await expect(f.service.persistPendingBids()).resolves.toBe(1);
|
||||||
|
expect(quarantined(f.commands)).toBe(false);
|
||||||
|
expect(savedEvent(f.bulkWrite)).not.toHaveProperty('bidRoundId');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps a non-empty round ID on the archived bid', async () => {
|
||||||
|
const f = fixture(bid({ bidRoundId: 'round-1' }));
|
||||||
|
await expect(f.service.persistPendingBids()).resolves.toBe(1);
|
||||||
|
expect(savedEvent(f.bulkWrite)).toMatchObject({ bidRoundId: 'round-1' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([' ', null, 1])(
|
||||||
|
'still quarantines an invalid round ID %j',
|
||||||
|
async (bidRoundId) => {
|
||||||
|
const f = fixture(bid({ bidRoundId }));
|
||||||
|
await expect(f.service.persistPendingBids()).resolves.toBe(0);
|
||||||
|
expect(f.bulkWrite).not.toHaveBeenCalled();
|
||||||
|
expect(quarantined(f.commands)).toBe(true);
|
||||||
|
},
|
||||||
|
);
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
Injectable,
|
||||||
|
Logger,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
import type { AuctionBidRecord } from '../global/database/schema';
|
||||||
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import { AuctionRedisService } from './redis/auction-redis.service';
|
||||||
|
import {
|
||||||
|
AUCTION_BID_ARCHIVE_PAYLOADS_KEY,
|
||||||
|
AUCTION_BID_ARCHIVE_QUEUE_KEY,
|
||||||
|
AUCTION_BID_ARCHIVE_DEAD_LETTER_QUEUE_KEY,
|
||||||
|
AUCTION_BID_ARCHIVE_DEAD_LETTER_PAYLOADS_KEY,
|
||||||
|
} from './redis/auction-redis.keys';
|
||||||
|
|
||||||
|
// Compare the payload as well as the ID: a concurrent repair must not be moved
|
||||||
|
// or acknowledged by a worker that read an older value.
|
||||||
|
const QUARANTINE_BID_ARCHIVE_SCRIPT = `
|
||||||
|
local moved = 0
|
||||||
|
for i = 2, #ARGV, 4 do
|
||||||
|
local current = redis.call('HGET', KEYS[1], ARGV[i])
|
||||||
|
local matches = (ARGV[i+1] == '0' and current == false) or (ARGV[i+1] == '1' and current == ARGV[i+2])
|
||||||
|
if matches and redis.call('ZSCORE', KEYS[2], ARGV[i]) then
|
||||||
|
redis.call('HSET', KEYS[3], ARGV[i], ARGV[i+3])
|
||||||
|
redis.call('ZADD', KEYS[4], ARGV[1], ARGV[i])
|
||||||
|
redis.call('HDEL', KEYS[1], ARGV[i])
|
||||||
|
redis.call('ZREM', KEYS[2], ARGV[i])
|
||||||
|
moved = moved + 1
|
||||||
|
end
|
||||||
|
end
|
||||||
|
return moved
|
||||||
|
`;
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AuctionBidArchiveService {
|
||||||
|
private readonly logger = new Logger(AuctionBidArchiveService.name);
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly database: ConnectionService,
|
||||||
|
private readonly redis: AuctionRedisService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public async persistPendingBids(limit = 200): Promise<number> {
|
||||||
|
const client = this.redis.raw();
|
||||||
|
const reply = await client.sendCommand([
|
||||||
|
'ZRANGE',
|
||||||
|
AUCTION_BID_ARCHIVE_QUEUE_KEY,
|
||||||
|
'0',
|
||||||
|
String(limit - 1),
|
||||||
|
]);
|
||||||
|
const ids = Array.isArray(reply) ? reply.map(String) : [];
|
||||||
|
if (!ids.length) return 0;
|
||||||
|
const values = await client.sendCommand<Array<string | null>>([
|
||||||
|
'HMGET',
|
||||||
|
AUCTION_BID_ARCHIVE_PAYLOADS_KEY,
|
||||||
|
...ids,
|
||||||
|
]);
|
||||||
|
const valid: Array<{ event: AuctionBidRecord; raw: string }> = [];
|
||||||
|
const invalid: Array<{ id: string; raw: string | null; error: string }> =
|
||||||
|
[];
|
||||||
|
for (let index = 0; index < ids.length; index++) {
|
||||||
|
const raw = values[index] ?? null;
|
||||||
|
try {
|
||||||
|
valid.push({ event: parseBidArchiveEvent(ids[index], raw), raw: raw! });
|
||||||
|
} catch (error) {
|
||||||
|
invalid.push({
|
||||||
|
id: ids[index],
|
||||||
|
raw,
|
||||||
|
error: String(error).slice(0, 2000),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (invalid.length) {
|
||||||
|
const now = Date.now();
|
||||||
|
const moved = await client.sendCommand<number>([
|
||||||
|
'EVAL',
|
||||||
|
QUARANTINE_BID_ARCHIVE_SCRIPT,
|
||||||
|
'4',
|
||||||
|
AUCTION_BID_ARCHIVE_PAYLOADS_KEY,
|
||||||
|
AUCTION_BID_ARCHIVE_QUEUE_KEY,
|
||||||
|
AUCTION_BID_ARCHIVE_DEAD_LETTER_PAYLOADS_KEY,
|
||||||
|
AUCTION_BID_ARCHIVE_DEAD_LETTER_QUEUE_KEY,
|
||||||
|
String(now),
|
||||||
|
...invalid.flatMap(({ id, raw, error }) => [
|
||||||
|
id,
|
||||||
|
raw === null ? '0' : '1',
|
||||||
|
raw ?? '',
|
||||||
|
JSON.stringify({
|
||||||
|
id,
|
||||||
|
rawPayload: raw,
|
||||||
|
error,
|
||||||
|
quarantinedAtTimestampMS: now,
|
||||||
|
}),
|
||||||
|
]),
|
||||||
|
]);
|
||||||
|
if (moved > 0)
|
||||||
|
this.logger.warn(`Quarantined ${moved} invalid bid archive events.`);
|
||||||
|
}
|
||||||
|
if (valid.length) {
|
||||||
|
const model = await this.database.getModel('auctionBidRecord');
|
||||||
|
// The deterministic _id is the dedupe key, including after a crash between
|
||||||
|
// Mongo acknowledgement and Redis cleanup. Never trim unpersisted events.
|
||||||
|
const result = await model.bulkWrite(
|
||||||
|
valid.map(({ event }) => ({
|
||||||
|
updateOne: {
|
||||||
|
filter: { _id: event._id },
|
||||||
|
update: { $setOnInsert: event },
|
||||||
|
upsert: true,
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
{ ordered: false, throwOnValidationError: true },
|
||||||
|
);
|
||||||
|
// A partial/ambiguous write leaves valid entries queued. Replaying the
|
||||||
|
// upserts is safe; assuming that a resolved bulkWrite saved all is not.
|
||||||
|
if (result.matchedCount + result.upsertedCount !== valid.length) {
|
||||||
|
throw new Error(
|
||||||
|
'Bid archive batch was not fully acknowledged by MongoDB.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await client.sendCommand([
|
||||||
|
'EVAL',
|
||||||
|
"for i = 1, #ARGV, 2 do if redis.call('HGET', KEYS[1], ARGV[i]) == ARGV[i+1] then redis.call('HDEL', KEYS[1], ARGV[i]); redis.call('ZREM', KEYS[2], ARGV[i]) end end return 1",
|
||||||
|
'2',
|
||||||
|
AUCTION_BID_ARCHIVE_PAYLOADS_KEY,
|
||||||
|
AUCTION_BID_ARCHIVE_QUEUE_KEY,
|
||||||
|
...valid.flatMap(({ event, raw }) => [event._id, raw]),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
return valid.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async list(
|
||||||
|
matchId: mongoose.Types.ObjectId,
|
||||||
|
afterRevision = -1,
|
||||||
|
limit = 100,
|
||||||
|
) {
|
||||||
|
if (
|
||||||
|
!Number.isSafeInteger(afterRevision) ||
|
||||||
|
afterRevision < -1 ||
|
||||||
|
!Number.isSafeInteger(limit) ||
|
||||||
|
limit < 1 ||
|
||||||
|
limit > 200
|
||||||
|
) {
|
||||||
|
throw new BadRequestException('Invalid bid history cursor or limit.');
|
||||||
|
}
|
||||||
|
const AuctionModel = await this.database.getModel('auction');
|
||||||
|
const auction = await AuctionModel.findOne({ matchId })
|
||||||
|
.select({ auctionLifecycleId: 1 })
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
if (!auction) throw new NotFoundException('Auction not found.');
|
||||||
|
const prefix = `${matchId.toString()}:${auction.auctionLifecycleId}:`;
|
||||||
|
const model = await this.database.getModel('auctionBidRecord');
|
||||||
|
// The built-in _id index supports ordered pagination without an additional
|
||||||
|
// production index or an unbounded array inside an Auction document.
|
||||||
|
const items = await model
|
||||||
|
.find({
|
||||||
|
_id: {
|
||||||
|
$gt:
|
||||||
|
afterRevision < 0
|
||||||
|
? prefix
|
||||||
|
: prefix + String(afterRevision).padStart(16, '0'),
|
||||||
|
$lt: prefix + '\uffff',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.sort({ _id: 1 })
|
||||||
|
.limit(limit + 1)
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
const hasMore = items.length > limit;
|
||||||
|
if (hasMore) items.pop();
|
||||||
|
return {
|
||||||
|
items,
|
||||||
|
hasMore,
|
||||||
|
nextRevision: items.at(-1)?.revision ?? afterRevision,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseBidArchiveEvent(
|
||||||
|
id: string,
|
||||||
|
raw: string | null,
|
||||||
|
): AuctionBidRecord {
|
||||||
|
if (raw === null) throw new Error('Missing bid archive payload.');
|
||||||
|
const value: unknown = JSON.parse(raw);
|
||||||
|
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||||
|
throw new Error('Bid archive payload must be an object.');
|
||||||
|
}
|
||||||
|
const event = value as Record<string, unknown>;
|
||||||
|
const string = (field: string): string => {
|
||||||
|
const value = event[field];
|
||||||
|
if (typeof value !== 'string' || !value.trim()) {
|
||||||
|
throw new Error(`Invalid bid archive ${field}.`);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
};
|
||||||
|
const integer = (field: string, minimum = 0): number => {
|
||||||
|
const value = event[field];
|
||||||
|
if (
|
||||||
|
typeof value !== 'number' ||
|
||||||
|
!Number.isSafeInteger(value) ||
|
||||||
|
value < minimum
|
||||||
|
) {
|
||||||
|
throw new Error(`Invalid bid archive ${field}.`);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
};
|
||||||
|
const objectId = (field: string): mongoose.Types.ObjectId => {
|
||||||
|
const value = string(field);
|
||||||
|
if (!mongoose.isObjectIdOrHexString(value)) {
|
||||||
|
throw new Error(`Invalid bid archive ${field}.`);
|
||||||
|
}
|
||||||
|
return new mongoose.Types.ObjectId(value);
|
||||||
|
};
|
||||||
|
const matchId = objectId('matchId');
|
||||||
|
const auctionLifecycleId = string('auctionLifecycleId');
|
||||||
|
const revision = integer('revision');
|
||||||
|
const expectedId = `${matchId.toString()}:${auctionLifecycleId}:${String(revision).padStart(16, '0')}`;
|
||||||
|
if (event._id !== id || id !== expectedId) {
|
||||||
|
throw new Error('Bid archive identity does not match its payload.');
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
_id: id,
|
||||||
|
matchId,
|
||||||
|
auctionLifecycleId,
|
||||||
|
revision,
|
||||||
|
bidRequestId: string('bidRequestId'),
|
||||||
|
bidderUserId: objectId('bidderUserId'),
|
||||||
|
bidderTeamIndex: integer('bidderTeamIndex', 1),
|
||||||
|
bidPointAmount: integer('bidPointAmount'),
|
||||||
|
bidPlacedAtTimestampMS: integer('bidPlacedAtTimestampMS'),
|
||||||
|
...(event.playerUserId !== undefined
|
||||||
|
? { playerUserId: objectId('playerUserId') }
|
||||||
|
: {}),
|
||||||
|
// Pre-upgrade rounds have no Redis round ID; the bid Lua records ''.
|
||||||
|
...(event.bidRoundId !== undefined && event.bidRoundId !== ''
|
||||||
|
? { bidRoundId: string('bidRoundId') }
|
||||||
|
: {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
import { NotFoundException } from '@nestjs/common';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { AuctionService } from './auction.service';
|
||||||
|
|
||||||
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
|
const communityId = new mongoose.Types.ObjectId();
|
||||||
|
|
||||||
|
function sessionQuery<T>(value: T) {
|
||||||
|
return { session: async () => value };
|
||||||
|
}
|
||||||
|
|
||||||
|
function fixture(options: {
|
||||||
|
auction: Record<string, unknown> | null;
|
||||||
|
match: Record<string, unknown>;
|
||||||
|
failRedisCleanup?: boolean;
|
||||||
|
}) {
|
||||||
|
const session = {
|
||||||
|
startTransaction: jest.fn(),
|
||||||
|
commitTransaction: jest.fn().mockResolvedValue(undefined),
|
||||||
|
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
||||||
|
endSession: jest.fn().mockResolvedValue(undefined),
|
||||||
|
};
|
||||||
|
const deleteMany = jest.fn(() => sessionQuery(undefined));
|
||||||
|
const models: Record<string, unknown> = {
|
||||||
|
auction: { findOne: () => sessionQuery(options.auction) },
|
||||||
|
auctionHistory: { deleteMany },
|
||||||
|
auctionSideEffectApplication: { deleteMany },
|
||||||
|
match: { findById: () => sessionQuery(options.match) },
|
||||||
|
};
|
||||||
|
const redisCommands: string[][] = [];
|
||||||
|
const sendCommand = jest.fn(async (command: string[]) => {
|
||||||
|
redisCommands.push(command);
|
||||||
|
if (command[0] === 'EVAL' && options.failRedisCleanup)
|
||||||
|
throw new Error('redis unavailable');
|
||||||
|
return command[0] === 'SCAN' ? ['0', []] : 1;
|
||||||
|
});
|
||||||
|
const service = new AuctionService(
|
||||||
|
{
|
||||||
|
getModel: async (name: string) => models[name],
|
||||||
|
createSession: async () => session,
|
||||||
|
} as never,
|
||||||
|
{} as never,
|
||||||
|
{ releaseFromMatch: jest.fn().mockResolvedValue(undefined) } as never,
|
||||||
|
{ cancelPolling: jest.fn().mockResolvedValue(undefined) } as never,
|
||||||
|
{
|
||||||
|
acquireTokenLock: async () => true,
|
||||||
|
releaseTokenLock: async () => true,
|
||||||
|
raw: () => ({ sendCommand }),
|
||||||
|
} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
);
|
||||||
|
return { service, session, redisCommands };
|
||||||
|
}
|
||||||
|
|
||||||
|
function liveMatch(): Record<string, unknown> {
|
||||||
|
return {
|
||||||
|
communityId,
|
||||||
|
status: 'team-built',
|
||||||
|
teams: [],
|
||||||
|
tournamentCodeIds: [],
|
||||||
|
gameSchedule: [],
|
||||||
|
participants: [],
|
||||||
|
save: jest.fn().mockResolvedValue(undefined),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function redisAuction() {
|
||||||
|
return {
|
||||||
|
_id: new mongoose.Types.ObjectId(),
|
||||||
|
auctionEngineVersion: 'redis-v1',
|
||||||
|
auctionLifecycleId: 'life',
|
||||||
|
deleteOne: jest.fn().mockResolvedValue(undefined),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
it('records the cancelled lifecycle and still succeeds when Redis cleanup fails', async () => {
|
||||||
|
const match = liveMatch();
|
||||||
|
const f = fixture({
|
||||||
|
auction: redisAuction(),
|
||||||
|
match,
|
||||||
|
failRedisCleanup: true,
|
||||||
|
});
|
||||||
|
await expect(
|
||||||
|
f.service.reset({
|
||||||
|
matchId,
|
||||||
|
communityId,
|
||||||
|
clientObservedAuctionLifecycleId: 'life',
|
||||||
|
}),
|
||||||
|
).resolves.toBeUndefined();
|
||||||
|
expect(f.session.commitTransaction).toHaveBeenCalledTimes(1);
|
||||||
|
expect(match.lastCancelledAuctionLifecycleId).toBe('life');
|
||||||
|
expect(match.status).toBe('recruiting');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('answers a retransmitted cancellation and durably schedules Redis cleanup', async () => {
|
||||||
|
const match = { ...liveMatch(), lastCancelledAuctionLifecycleId: 'life' };
|
||||||
|
const f = fixture({ auction: null, match });
|
||||||
|
await expect(
|
||||||
|
f.service.reset({
|
||||||
|
matchId,
|
||||||
|
communityId,
|
||||||
|
clientObservedAuctionLifecycleId: 'life',
|
||||||
|
}),
|
||||||
|
).resolves.toBeUndefined();
|
||||||
|
expect(match).toMatchObject({
|
||||||
|
auctionCancellationCleanupPending: true,
|
||||||
|
auctionCancellationCleanupRetryAt: expect.any(Date),
|
||||||
|
});
|
||||||
|
expect(f.redisCommands).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('preserves a committed cancellation even if its lock renewal fails before returning', async () => {
|
||||||
|
jest.useFakeTimers();
|
||||||
|
try {
|
||||||
|
const match = liveMatch();
|
||||||
|
const f = fixture({ auction: redisAuction(), match });
|
||||||
|
f.session.commitTransaction.mockImplementation(async () => {
|
||||||
|
await jest.advanceTimersByTimeAsync(10000);
|
||||||
|
});
|
||||||
|
await expect(
|
||||||
|
f.service.reset({
|
||||||
|
matchId,
|
||||||
|
communityId,
|
||||||
|
clientObservedAuctionLifecycleId: 'life',
|
||||||
|
}),
|
||||||
|
).resolves.toBeUndefined();
|
||||||
|
expect(match.auctionCancellationCleanupPending).toBe(true);
|
||||||
|
expect(f.session.commitTransaction).toHaveBeenCalledTimes(1);
|
||||||
|
} finally {
|
||||||
|
jest.useRealTimers();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps 404 for a missing auction that was not cancelled with this lifecycle', async () => {
|
||||||
|
for (const [observed, recorded] of [
|
||||||
|
['other', 'life'],
|
||||||
|
[undefined, 'life'],
|
||||||
|
['life', undefined],
|
||||||
|
] as const) {
|
||||||
|
const f = fixture({
|
||||||
|
auction: null,
|
||||||
|
match: { ...liveMatch(), lastCancelledAuctionLifecycleId: recorded },
|
||||||
|
});
|
||||||
|
await expect(
|
||||||
|
f.service.reset({
|
||||||
|
matchId,
|
||||||
|
communityId,
|
||||||
|
clientObservedAuctionLifecycleId: observed,
|
||||||
|
}),
|
||||||
|
).rejects.toBeInstanceOf(NotFoundException);
|
||||||
|
expect(f.session.abortTransaction).toHaveBeenCalled();
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,607 @@
|
|||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { AuctionService } from './auction.service';
|
||||||
|
import {
|
||||||
|
AuctionDurabilityScheduler,
|
||||||
|
buildAuctionProjectionGuardedUpdate,
|
||||||
|
type AuctionDurabilityPayload,
|
||||||
|
} from './auction-durability.scheduler';
|
||||||
|
import { AuctionDeadlineScheduler } from './auction-deadline.scheduler';
|
||||||
|
import { AuctionLifecycleLock } from './auction-lifecycle-lock';
|
||||||
|
|
||||||
|
const query = <T>(value: T) => ({
|
||||||
|
select() {
|
||||||
|
return this;
|
||||||
|
},
|
||||||
|
session() {
|
||||||
|
return this;
|
||||||
|
},
|
||||||
|
lean() {
|
||||||
|
return this;
|
||||||
|
},
|
||||||
|
exec: async () => value,
|
||||||
|
});
|
||||||
|
const session = () => ({
|
||||||
|
startTransaction: jest.fn(),
|
||||||
|
commitTransaction: jest.fn(),
|
||||||
|
abortTransaction: jest.fn(),
|
||||||
|
endSession: jest.fn(),
|
||||||
|
});
|
||||||
|
const state = {
|
||||||
|
auctionLifecycleId: 'life',
|
||||||
|
revision: 12,
|
||||||
|
phase: 'presenting',
|
||||||
|
currentAuctionHistorySequence: 7,
|
||||||
|
currentAuctionPlayerOrderIndex: 0,
|
||||||
|
currentAuctionRound: 1,
|
||||||
|
auctionTeams: [],
|
||||||
|
auctionPlayerOrder: [],
|
||||||
|
passedAuctionPlayerQueue: [],
|
||||||
|
currentHighestBidPointAmount: 0,
|
||||||
|
currentHighestBidderTeamIndex: -1,
|
||||||
|
auctionCompletedAtTimestampMS: 0,
|
||||||
|
currentBidRoundDeadlineTimestampMS: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
jest
|
||||||
|
.spyOn(AuctionLifecycleLock.prototype, 'run')
|
||||||
|
.mockImplementation(async (_id, work) => work());
|
||||||
|
});
|
||||||
|
afterEach(() => jest.restoreAllMocks());
|
||||||
|
|
||||||
|
function matches(
|
||||||
|
document: Record<string, unknown>,
|
||||||
|
filter: Record<string, unknown>,
|
||||||
|
): boolean {
|
||||||
|
return Object.entries(filter).every(([key, value]) => {
|
||||||
|
if (key === '$or')
|
||||||
|
return (value as Record<string, unknown>[]).some((alternative) =>
|
||||||
|
matches(document, alternative),
|
||||||
|
);
|
||||||
|
if (value && typeof value === 'object') {
|
||||||
|
return Object.entries(value).every(([operator, limit]) => {
|
||||||
|
if (operator === '$exists')
|
||||||
|
return (document[key] !== undefined) === limit;
|
||||||
|
if (operator === '$lt') return Number(document[key]) < Number(limit);
|
||||||
|
if (operator === '$lte') return Number(document[key]) <= Number(limit);
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return document[key] === value;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
function update(
|
||||||
|
document: Record<string, unknown>,
|
||||||
|
mutation: Record<string, Record<string, unknown>>,
|
||||||
|
) {
|
||||||
|
Object.assign(document, mutation.$set);
|
||||||
|
for (const [key, amount] of Object.entries(mutation.$inc ?? {}))
|
||||||
|
document[key] = Number(document[key] ?? 0) + Number(amount);
|
||||||
|
for (const key of Object.keys(mutation.$unset ?? {})) delete document[key];
|
||||||
|
}
|
||||||
|
|
||||||
|
function sideEffectFixture(withReader = false) {
|
||||||
|
const projection: Record<string, unknown> = {
|
||||||
|
_id: 'auction',
|
||||||
|
auctionLifecycleId: 'life',
|
||||||
|
revision: 9,
|
||||||
|
matchSideEffectRevision: 0,
|
||||||
|
};
|
||||||
|
const application: Record<string, unknown> = {};
|
||||||
|
const payload: AuctionDurabilityPayload = {
|
||||||
|
auctionId: 'auction',
|
||||||
|
matchId: 'match',
|
||||||
|
auctionLifecycleId: 'life',
|
||||||
|
auctionStateTransitionId: 'complete',
|
||||||
|
auctionActionType: 'complete',
|
||||||
|
auctionHistorySequence: 10,
|
||||||
|
revision: 10,
|
||||||
|
snapshotBefore: {},
|
||||||
|
historyMutation: { type: 'append' },
|
||||||
|
matchSideEffectMutation: { type: 'syncMatchTeamsAfterComplete' },
|
||||||
|
afterAuctionMongoProjection: {
|
||||||
|
auctionLifecycleId: 'life',
|
||||||
|
revision: 10,
|
||||||
|
phase: 'complete',
|
||||||
|
matchSideEffectRevision: 1,
|
||||||
|
matchSideEffectStatus: 'pending',
|
||||||
|
matchSideEffectTransitionId: 'complete',
|
||||||
|
auctionTeams: [{ teamIndex: 1, captainUserId: 'captain', members: [] }],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const AuctionModel = {
|
||||||
|
findById: () => query({ ...projection }),
|
||||||
|
updateOne: (
|
||||||
|
filter: Record<string, unknown>,
|
||||||
|
mutation: Record<string, Record<string, unknown>>,
|
||||||
|
) => {
|
||||||
|
const matchedCount = Number(matches(projection, filter));
|
||||||
|
if (matchedCount) update(projection, mutation);
|
||||||
|
return query({ matchedCount });
|
||||||
|
},
|
||||||
|
findOneAndUpdate: (
|
||||||
|
filter: Record<string, unknown>,
|
||||||
|
mutation: Record<string, Record<string, unknown>>,
|
||||||
|
) => {
|
||||||
|
if (!matches(projection, filter)) return query(null);
|
||||||
|
update(projection, mutation);
|
||||||
|
return query({ ...projection });
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const ApplicationModel = {
|
||||||
|
findOne: () => query({ ...application }),
|
||||||
|
updateOne: (
|
||||||
|
filter: Record<string, unknown>,
|
||||||
|
mutation: Record<string, Record<string, unknown>>,
|
||||||
|
) => {
|
||||||
|
if (mutation.$setOnInsert) {
|
||||||
|
if (!application.state)
|
||||||
|
Object.assign(application, mutation.$setOnInsert);
|
||||||
|
return query({ matchedCount: 1 });
|
||||||
|
}
|
||||||
|
const matchedCount = Number(matches(application, filter));
|
||||||
|
if (matchedCount) update(application, mutation);
|
||||||
|
return query({ matchedCount });
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const match = {
|
||||||
|
participants: [],
|
||||||
|
teams: [],
|
||||||
|
save: jest.fn().mockResolvedValue(undefined),
|
||||||
|
};
|
||||||
|
const historyFindOne = jest.fn().mockReturnValue(query(null));
|
||||||
|
const historyUpdateOne = jest
|
||||||
|
.fn()
|
||||||
|
.mockReturnValue(query({ matchedCount: 1 }));
|
||||||
|
const models: Record<string, unknown> = {
|
||||||
|
auction: AuctionModel,
|
||||||
|
auctionHistory: {
|
||||||
|
findOne: historyFindOne,
|
||||||
|
updateOne: historyUpdateOne,
|
||||||
|
},
|
||||||
|
auctionSideEffectApplication: ApplicationModel,
|
||||||
|
match: {
|
||||||
|
findById: () => ({ ...query(match), session: async () => match }),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const reserveForMatch = jest
|
||||||
|
.fn()
|
||||||
|
.mockRejectedValueOnce(new Error('temporary reservation error'))
|
||||||
|
.mockResolvedValue(match);
|
||||||
|
const scheduleInitialPoll = jest.fn().mockResolvedValue(undefined);
|
||||||
|
const releaseFromMatch = jest.fn().mockResolvedValue(undefined);
|
||||||
|
const cancelPolling = jest.fn().mockResolvedValue(undefined);
|
||||||
|
let queued = true;
|
||||||
|
const sendCommand = jest.fn(async (command: string[]) => {
|
||||||
|
if (command[0] === 'ZRANGEBYSCORE') return queued ? ['payload'] : [];
|
||||||
|
if (command[0] === 'HGETALL')
|
||||||
|
return { payloadJson: JSON.stringify(payload) };
|
||||||
|
if (command[0] === 'DEL') queued = false;
|
||||||
|
if (command[0] === 'HINCRBY') return 1;
|
||||||
|
return 1;
|
||||||
|
});
|
||||||
|
const scheduler = new AuctionDurabilityScheduler(
|
||||||
|
{
|
||||||
|
getModel: async (name: string) => models[name],
|
||||||
|
createSession: async () => session(),
|
||||||
|
} as never,
|
||||||
|
{
|
||||||
|
getCurrentRedisTimestampMS: async () => 10000,
|
||||||
|
raw: () => ({ sendCommand }),
|
||||||
|
} as never,
|
||||||
|
{ reserveForMatch, releaseFromMatch } as never,
|
||||||
|
{ scheduleInitialPoll, cancelPolling } as never,
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
withReader
|
||||||
|
? ({
|
||||||
|
readAuctionStateView: async () => ({
|
||||||
|
auctionLifecycleId: 'life',
|
||||||
|
phase: payload.afterAuctionMongoProjection.phase,
|
||||||
|
matchSideEffectTransitionId: 'complete',
|
||||||
|
}),
|
||||||
|
} as never)
|
||||||
|
: undefined,
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
scheduler,
|
||||||
|
payload,
|
||||||
|
projection,
|
||||||
|
application,
|
||||||
|
reserveForMatch,
|
||||||
|
scheduleInitialPoll,
|
||||||
|
sendCommand,
|
||||||
|
match,
|
||||||
|
historyFindOne,
|
||||||
|
historyUpdateOne,
|
||||||
|
releaseFromMatch,
|
||||||
|
cancelPolling,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
it('retries failed completion work with the current generation and only then deletes the payload', async () => {
|
||||||
|
const f = sideEffectFixture();
|
||||||
|
expect(await f.scheduler.processDueDurabilityPayloads(20)).toMatchObject({
|
||||||
|
failed: 1,
|
||||||
|
});
|
||||||
|
expect(f.projection.matchSideEffectStatus).toBe('failed');
|
||||||
|
expect(await f.scheduler.processDueDurabilityPayloads(20)).toMatchObject({
|
||||||
|
applied: 1,
|
||||||
|
});
|
||||||
|
expect(f.reserveForMatch).toHaveBeenCalledTimes(2);
|
||||||
|
expect(f.scheduleInitialPoll).toHaveBeenCalledTimes(1);
|
||||||
|
expect(f.application.state).toBe('completed');
|
||||||
|
expect(f.projection.matchSideEffectStatus).toBe('completed');
|
||||||
|
expect(f.projection.matchSideEffectRevision).toBe(5);
|
||||||
|
expect(f.sendCommand).toHaveBeenCalledWith(['DEL', 'payload']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps an outbox payload while another worker owns its side-effect lease', async () => {
|
||||||
|
const f = sideEffectFixture();
|
||||||
|
Object.assign(f.application, {
|
||||||
|
auctionId: 'auction',
|
||||||
|
auctionStateTransitionId: 'complete',
|
||||||
|
sideEffectType: 'syncMatchTeamsAfterComplete',
|
||||||
|
state: 'processing',
|
||||||
|
processingOwnerToken: 'other',
|
||||||
|
processingLeaseExpiresAtTimestampMS: 50000,
|
||||||
|
});
|
||||||
|
expect(await f.scheduler.processDueDurabilityPayloads(20)).toEqual({
|
||||||
|
applied: 0,
|
||||||
|
failed: 0,
|
||||||
|
skipped: 1,
|
||||||
|
});
|
||||||
|
expect(f.sendCommand).not.toHaveBeenCalledWith(['DEL', 'payload']);
|
||||||
|
expect(
|
||||||
|
f.sendCommand.mock.calls.some(([command]) => command[0] === 'HINCRBY'),
|
||||||
|
).toBe(false);
|
||||||
|
expect(f.reserveForMatch).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('recovers side effects when a later ordinary projection was persisted first', async () => {
|
||||||
|
const f = sideEffectFixture(true);
|
||||||
|
f.reserveForMatch.mockReset().mockResolvedValue(undefined);
|
||||||
|
Object.assign(f.projection, { revision: 12 });
|
||||||
|
await f.scheduler.applyDurabilityPayload(f.payload);
|
||||||
|
expect(f.reserveForMatch).toHaveBeenCalledTimes(1);
|
||||||
|
expect(f.projection.revision).toBe(12);
|
||||||
|
expect(f.projection.matchSideEffectTransitionId).toBe('complete');
|
||||||
|
expect(f.projection.matchSideEffectStatus).toBe('completed');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('still cleans up completed Match state when a second undo invalidates the first undo history', async () => {
|
||||||
|
const f = sideEffectFixture(true);
|
||||||
|
Object.assign(f.projection, { revision: 12 });
|
||||||
|
Object.assign(f.payload, {
|
||||||
|
matchSideEffectMutation: { type: 'undoCompletedAuctionSideEffects' },
|
||||||
|
});
|
||||||
|
f.payload.afterAuctionMongoProjection.phase = 'presenting';
|
||||||
|
Object.assign(f.match, {
|
||||||
|
teams: [{ teamIndex: 1 }],
|
||||||
|
teamBuiltAt: new Date(),
|
||||||
|
tournamentCodeIds: ['code'],
|
||||||
|
gameSchedule: [{}],
|
||||||
|
});
|
||||||
|
f.historyFindOne.mockReturnValue(
|
||||||
|
query({
|
||||||
|
sequence: 12,
|
||||||
|
historyMutation: {
|
||||||
|
type: 'deleteAfterSequenceAndAppendUndo',
|
||||||
|
targetHistorySequence: 2,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await f.scheduler.applyDurabilityPayload(f.payload);
|
||||||
|
expect(f.historyUpdateOne).not.toHaveBeenCalled();
|
||||||
|
expect(f.releaseFromMatch).toHaveBeenCalledTimes(1);
|
||||||
|
expect(f.cancelPolling).toHaveBeenCalledTimes(1);
|
||||||
|
expect(f.match).toMatchObject({
|
||||||
|
teams: [],
|
||||||
|
teamBuiltAt: undefined,
|
||||||
|
tournamentCodeIds: [],
|
||||||
|
gameSchedule: [],
|
||||||
|
});
|
||||||
|
expect(f.projection.matchSideEffectStatus).toBe('completed');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not let a superseded side effect overwrite the newer generation', async () => {
|
||||||
|
const f = sideEffectFixture();
|
||||||
|
Object.assign(f.projection, {
|
||||||
|
revision: 12,
|
||||||
|
matchSideEffectTransitionId: 'undo',
|
||||||
|
matchSideEffectRevision: 6,
|
||||||
|
});
|
||||||
|
await f.scheduler.applyDurabilityPayload(f.payload);
|
||||||
|
expect(f.reserveForMatch).not.toHaveBeenCalled();
|
||||||
|
expect(f.projection.matchSideEffectTransitionId).toBe('undo');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('removes obsolete projection fields both from Mongo updates and subsequent undo snapshots', () => {
|
||||||
|
const service = new AuctionService(
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
);
|
||||||
|
const internal = service as unknown as {
|
||||||
|
buildAuctionMongoProjectionFromState(
|
||||||
|
auction: unknown,
|
||||||
|
state: Record<string, unknown>,
|
||||||
|
): Record<string, unknown>;
|
||||||
|
buildAuctionSnapshotFromRedisState(
|
||||||
|
auction: unknown,
|
||||||
|
state: Record<string, unknown>,
|
||||||
|
): Record<string, unknown>;
|
||||||
|
};
|
||||||
|
const old = {
|
||||||
|
_id: new mongoose.Types.ObjectId(),
|
||||||
|
matchId: new mongoose.Types.ObjectId(),
|
||||||
|
completedAt: new Date(),
|
||||||
|
auctionCompletedAtTimestampMS: 100,
|
||||||
|
currentHighestBidderTeamIndex: 2,
|
||||||
|
currentBidderTeamIndex: 2,
|
||||||
|
};
|
||||||
|
const projection = internal.buildAuctionMongoProjectionFromState(old, state);
|
||||||
|
const mutation = buildAuctionProjectionGuardedUpdate({
|
||||||
|
auctionId: old._id,
|
||||||
|
auctionLifecycleId: 'life',
|
||||||
|
revision: 12,
|
||||||
|
afterAuctionMongoProjection: projection,
|
||||||
|
} as AuctionDurabilityPayload).update;
|
||||||
|
const stored = { ...old } as Record<string, unknown>;
|
||||||
|
update(stored, mutation);
|
||||||
|
const snapshot = internal.buildAuctionSnapshotFromRedisState(old, state);
|
||||||
|
for (const record of [stored, snapshot]) {
|
||||||
|
expect(record).not.toHaveProperty('completedAt');
|
||||||
|
expect(record).not.toHaveProperty('currentHighestBidderTeamIndex');
|
||||||
|
expect(record.phase).toBe('presenting');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('applies delayed undo history cleanup without deleting newer branch entries or rolling back projection', async () => {
|
||||||
|
const deleteMany = jest.fn().mockReturnValue(query({}));
|
||||||
|
const updateOne = jest.fn().mockReturnValue(query({}));
|
||||||
|
const projectionUpdate = jest.fn();
|
||||||
|
const models: Record<string, unknown> = {
|
||||||
|
auction: {
|
||||||
|
findById: () => query({ auctionLifecycleId: 'life', revision: 12 }),
|
||||||
|
updateOne: projectionUpdate,
|
||||||
|
},
|
||||||
|
auctionHistory: { findOne: () => query(null), deleteMany, updateOne },
|
||||||
|
auctionSideEffectApplication: {},
|
||||||
|
};
|
||||||
|
const scheduler = new AuctionDurabilityScheduler(
|
||||||
|
{
|
||||||
|
getModel: async (name: string) => models[name],
|
||||||
|
createSession: async () => null,
|
||||||
|
} as never,
|
||||||
|
{} as never,
|
||||||
|
);
|
||||||
|
await scheduler.applyDurabilityPayload({
|
||||||
|
auctionId: 'auction',
|
||||||
|
matchId: 'match',
|
||||||
|
auctionStateTransitionId: 'undo',
|
||||||
|
auctionLifecycleId: 'life',
|
||||||
|
revision: 11,
|
||||||
|
auctionHistorySequence: 9,
|
||||||
|
auctionActionType: 'undo',
|
||||||
|
historyMutation: {
|
||||||
|
type: 'deleteAfterSequenceAndAppendUndo',
|
||||||
|
targetHistorySequence: 3,
|
||||||
|
},
|
||||||
|
matchSideEffectMutation: { type: 'none' },
|
||||||
|
afterAuctionMongoProjection: {},
|
||||||
|
snapshotBefore: {},
|
||||||
|
} as AuctionDurabilityPayload);
|
||||||
|
expect(deleteMany).toHaveBeenCalledWith(
|
||||||
|
{ auctionId: 'auction', sequence: { $gt: 3, $lt: 9 } },
|
||||||
|
{ session: null },
|
||||||
|
);
|
||||||
|
expect(updateOne).toHaveBeenCalledTimes(1);
|
||||||
|
expect(projectionUpdate).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a cancellation from a prior lifecycle before deleting anything', async () => {
|
||||||
|
const matchId = new mongoose.Types.ObjectId(),
|
||||||
|
communityId = new mongoose.Types.ObjectId();
|
||||||
|
const deleteOne = jest.fn();
|
||||||
|
const service = new AuctionService(
|
||||||
|
{
|
||||||
|
createSession: async () => session(),
|
||||||
|
getModel: async () => ({
|
||||||
|
findOne: () => ({
|
||||||
|
session: async () => ({
|
||||||
|
auctionEngineVersion: 'redis-v1',
|
||||||
|
auctionLifecycleId: 'new-life',
|
||||||
|
deleteOne,
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
);
|
||||||
|
await expect(
|
||||||
|
service.reset({
|
||||||
|
matchId,
|
||||||
|
communityId,
|
||||||
|
clientObservedAuctionLifecycleId: 'old-life',
|
||||||
|
}),
|
||||||
|
).rejects.toThrow('lifecycle has changed');
|
||||||
|
expect(deleteOne).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resumes startup after Mongo creation instead of returning an unfinished auction', async () => {
|
||||||
|
const matchId = new mongoose.Types.ObjectId(),
|
||||||
|
communityId = new mongoose.Types.ObjectId();
|
||||||
|
const captain = new mongoose.Types.ObjectId(),
|
||||||
|
player = new mongoose.Types.ObjectId(),
|
||||||
|
lateJoiner = new mongoose.Types.ObjectId();
|
||||||
|
const auction = {
|
||||||
|
_id: new mongoose.Types.ObjectId(),
|
||||||
|
matchId,
|
||||||
|
auctionLifecycleId: 'life',
|
||||||
|
revision: 1,
|
||||||
|
phase: 'presenting',
|
||||||
|
startupCompleted: false,
|
||||||
|
startAuctionRequestId: 'same-request',
|
||||||
|
teams: [{ captainUserId: captain, members: [], teamIndex: 1 }],
|
||||||
|
order: [{ userId: player }],
|
||||||
|
};
|
||||||
|
const match = {
|
||||||
|
communityId,
|
||||||
|
status: 'recruiting',
|
||||||
|
participants: [captain, player, lateJoiner].map((userId) => ({
|
||||||
|
userId,
|
||||||
|
excluded: false,
|
||||||
|
})),
|
||||||
|
save: jest.fn(),
|
||||||
|
};
|
||||||
|
const updateOne = jest.fn();
|
||||||
|
const historyUpdate = jest.fn();
|
||||||
|
const models: Record<string, unknown> = {
|
||||||
|
auction: { findOne: async () => auction, updateOne },
|
||||||
|
match: { findById: async () => match },
|
||||||
|
auctionHistory: { updateOne: historyUpdate },
|
||||||
|
};
|
||||||
|
const hydrateState = jest.fn().mockResolvedValue({ hydrated: true });
|
||||||
|
const service = new AuctionService(
|
||||||
|
{ getModel: async (name: string) => models[name] } as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{ hydrateState } as never,
|
||||||
|
{} as never,
|
||||||
|
);
|
||||||
|
await service.start({
|
||||||
|
matchId,
|
||||||
|
communityId,
|
||||||
|
startAuctionRequestId: 'same-request',
|
||||||
|
} as never);
|
||||||
|
expect(hydrateState).toHaveBeenCalledTimes(1);
|
||||||
|
expect(historyUpdate).toHaveBeenCalledTimes(1);
|
||||||
|
expect(match.save).toHaveBeenCalledTimes(1);
|
||||||
|
expect(match.status).toBe('team-built');
|
||||||
|
expect(auction.startupCompleted).toBe(true);
|
||||||
|
expect(match.participants.map((entry) => entry.excluded)).toEqual([
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not open bidding until interrupted startup has been completed', async () => {
|
||||||
|
const service = new AuctionService(
|
||||||
|
{
|
||||||
|
getModel: async () => ({
|
||||||
|
findOne: async () => ({
|
||||||
|
auctionEngineVersion: 'redis-v1',
|
||||||
|
startupCompleted: false,
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
);
|
||||||
|
await expect(
|
||||||
|
service.openBidding(new mongoose.Types.ObjectId()),
|
||||||
|
).rejects.toThrow('startup is not complete');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses Redis completion state to schedule cleanup despite a delayed Mongo projection', async () => {
|
||||||
|
const matchId = new mongoose.Types.ObjectId(),
|
||||||
|
communityId = new mongoose.Types.ObjectId();
|
||||||
|
const auction = {
|
||||||
|
_id: new mongoose.Types.ObjectId(),
|
||||||
|
matchId,
|
||||||
|
auctionEngineVersion: 'redis-v1',
|
||||||
|
auctionLifecycleId: 'life',
|
||||||
|
phase: 'sold',
|
||||||
|
revision: 9,
|
||||||
|
};
|
||||||
|
const snapshot = { ...state, phase: 'bidding', revision: 5 };
|
||||||
|
const models: Record<string, unknown> = {
|
||||||
|
auction: { findOne: () => ({ session: async () => auction }) },
|
||||||
|
match: { findById: () => ({ session: async () => ({ communityId }) }) },
|
||||||
|
auctionHistory: { findOne: () => query({ snapshotBefore: snapshot }) },
|
||||||
|
};
|
||||||
|
const applyTransition = jest.fn().mockResolvedValue({ ok: true });
|
||||||
|
const commands = {
|
||||||
|
reserveActionRequest: async () => ({
|
||||||
|
reserved: true,
|
||||||
|
actionRequestScopeKey: 'scope',
|
||||||
|
auctionStateTransitionId: 'undo',
|
||||||
|
observedProcessingLeaseVersion: 1,
|
||||||
|
}),
|
||||||
|
applyTransition,
|
||||||
|
};
|
||||||
|
const service = new AuctionService(
|
||||||
|
{
|
||||||
|
getModel: async (name: string) => models[name],
|
||||||
|
createSession: async () => session(),
|
||||||
|
} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
commands as never,
|
||||||
|
{
|
||||||
|
readAuctionStateView: async () => ({
|
||||||
|
...state,
|
||||||
|
phase: 'complete',
|
||||||
|
revision: 10,
|
||||||
|
}),
|
||||||
|
} as never,
|
||||||
|
);
|
||||||
|
await service.undoTo({ matchId, communityId, sequence: 2 });
|
||||||
|
const input = applyTransition.mock.calls[0][1] as {
|
||||||
|
durabilityPayloadJson: string;
|
||||||
|
};
|
||||||
|
expect(JSON.parse(input.durabilityPayloadJson)).toMatchObject({
|
||||||
|
matchSideEffectMutation: { type: 'undoCompletedAuctionSideEffects' },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(['deadline', 'durability'])(
|
||||||
|
'continues %s ticks when lock release fails',
|
||||||
|
async (kind) => {
|
||||||
|
const redis = {
|
||||||
|
acquireTokenLock: jest.fn().mockResolvedValue(true),
|
||||||
|
releaseTokenLock: jest
|
||||||
|
.fn()
|
||||||
|
.mockRejectedValue(new Error('redis disconnected')),
|
||||||
|
};
|
||||||
|
const scheduler =
|
||||||
|
kind === 'deadline'
|
||||||
|
? new AuctionDeadlineScheduler(
|
||||||
|
redis as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
)
|
||||||
|
: new AuctionDurabilityScheduler({} as never, redis as never);
|
||||||
|
const work = jest.fn().mockResolvedValue({});
|
||||||
|
Object.assign(
|
||||||
|
scheduler,
|
||||||
|
kind === 'deadline'
|
||||||
|
? { processDueBidRoundDeadlines: work }
|
||||||
|
: { processDueDurabilityPayloads: work },
|
||||||
|
);
|
||||||
|
const internal = scheduler as unknown as { safeTick(): Promise<void> };
|
||||||
|
await internal.safeTick();
|
||||||
|
await internal.safeTick();
|
||||||
|
expect(work).toHaveBeenCalledTimes(2);
|
||||||
|
},
|
||||||
|
);
|
||||||
@@ -88,10 +88,13 @@ export class AuctionDeadlineScheduler implements OnModuleInit, OnModuleDestroy {
|
|||||||
);
|
);
|
||||||
} finally {
|
} finally {
|
||||||
if (leaderLockAcquired) {
|
if (leaderLockAcquired) {
|
||||||
await this.auctionRedisService.releaseTokenLock(
|
await this.auctionRedisService
|
||||||
BID_ROUND_DEADLINE_LEADER_LOCK_KEY,
|
.releaseTokenLock(BID_ROUND_DEADLINE_LEADER_LOCK_KEY, leaderLockToken)
|
||||||
leaderLockToken,
|
.catch((error: unknown) => {
|
||||||
);
|
this.logger.warn(
|
||||||
|
`Auction deadline lock release failed: ${String(error)}`,
|
||||||
|
);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
this.tickInProgress = false;
|
this.tickInProgress = false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { AuctionLifecycleLock } from './auction-lifecycle-lock';
|
||||||
|
import { buildAuctionProjectionUnset } from './auction-projection';
|
||||||
import {
|
import {
|
||||||
AuctionDurabilityScheduler,
|
AuctionDurabilityScheduler,
|
||||||
buildAuctionHistoryUpsert,
|
buildAuctionHistoryUpsert,
|
||||||
@@ -23,6 +25,12 @@ const payload = {
|
|||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
describe('auction durability projection helpers', () => {
|
describe('auction durability projection helpers', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
jest
|
||||||
|
.spyOn(AuctionLifecycleLock.prototype, 'run')
|
||||||
|
.mockImplementation(async (_id, work) => work());
|
||||||
|
});
|
||||||
|
afterEach(() => jest.restoreAllMocks());
|
||||||
it('builds idempotent history upsert by auction and transition id', () => {
|
it('builds idempotent history upsert by auction and transition id', () => {
|
||||||
expect(buildAuctionHistoryUpsert(payload)).toEqual({
|
expect(buildAuctionHistoryUpsert(payload)).toEqual({
|
||||||
updateOne: {
|
updateOne: {
|
||||||
@@ -59,6 +67,9 @@ describe('auction durability projection helpers', () => {
|
|||||||
},
|
},
|
||||||
update: {
|
update: {
|
||||||
$set: { phase: 'sold', revision: 9 },
|
$set: { phase: 'sold', revision: 9 },
|
||||||
|
$unset: buildAuctionProjectionUnset(
|
||||||
|
payload.afterAuctionMongoProjection,
|
||||||
|
),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -210,7 +221,12 @@ describe('auction durability projection helpers', () => {
|
|||||||
auctionLifecycleId: 'life-1',
|
auctionLifecycleId: 'life-1',
|
||||||
revision: { $lt: 9 },
|
revision: { $lt: 9 },
|
||||||
},
|
},
|
||||||
{ $set: { phase: 'sold', revision: 9 } },
|
{
|
||||||
|
$set: { phase: 'sold', revision: 9 },
|
||||||
|
$unset: buildAuctionProjectionUnset(
|
||||||
|
payload.afterAuctionMongoProjection,
|
||||||
|
),
|
||||||
|
},
|
||||||
{ session },
|
{ session },
|
||||||
);
|
);
|
||||||
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
|
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
|
||||||
@@ -370,7 +386,7 @@ describe('auction durability projection helpers', () => {
|
|||||||
expect(historyDeleteMany).toHaveBeenCalledWith(
|
expect(historyDeleteMany).toHaveBeenCalledWith(
|
||||||
{
|
{
|
||||||
auctionId: 'auction-1',
|
auctionId: 'auction-1',
|
||||||
sequence: { $gt: 2 },
|
sequence: { $gt: 2, $lt: 4 },
|
||||||
},
|
},
|
||||||
{ session },
|
{ session },
|
||||||
);
|
);
|
||||||
@@ -811,21 +827,14 @@ describe('auction durability projection helpers', () => {
|
|||||||
skipped: 0,
|
skipped: 0,
|
||||||
});
|
});
|
||||||
expect(sendCommand).toHaveBeenNthCalledWith(5, [
|
expect(sendCommand).toHaveBeenNthCalledWith(5, [
|
||||||
'ZREM',
|
'EVAL',
|
||||||
|
expect.stringContaining("redis.call('HEXISTS'"),
|
||||||
|
'4',
|
||||||
|
'payload-1',
|
||||||
'auction:auctionDurabilityRetryQueue',
|
'auction:auctionDurabilityRetryQueue',
|
||||||
'payload-1',
|
|
||||||
]);
|
|
||||||
expect(sendCommand).toHaveBeenNthCalledWith(6, [
|
|
||||||
'HSET',
|
|
||||||
'payload-1',
|
|
||||||
'deadLetteredAtRedisTimestampMS',
|
|
||||||
'1000',
|
|
||||||
]);
|
|
||||||
expect(sendCommand).toHaveBeenNthCalledWith(7, [
|
|
||||||
'ZADD',
|
|
||||||
'auction:auctionDurabilityDeadLetterQueue',
|
'auction:auctionDurabilityDeadLetterQueue',
|
||||||
|
'auction:deadLetterStatusQueue',
|
||||||
'1000',
|
'1000',
|
||||||
'payload-1',
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1030,11 +1039,20 @@ describe('auction durability projection helpers', () => {
|
|||||||
{
|
{
|
||||||
_id: 'auction-1',
|
_id: 'auction-1',
|
||||||
auctionLifecycleId: 'life-1',
|
auctionLifecycleId: 'life-1',
|
||||||
matchSideEffectRevision: 1,
|
$or: [
|
||||||
|
{ matchSideEffectTransitionId: 'transition-1' },
|
||||||
|
{
|
||||||
|
matchSideEffectTransitionId: { $exists: false },
|
||||||
|
matchSideEffectRevision: 1,
|
||||||
|
},
|
||||||
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
$inc: { matchSideEffectRevision: 1 },
|
$inc: { matchSideEffectRevision: 1 },
|
||||||
$set: { matchSideEffectStatus: 'processing' },
|
$set: {
|
||||||
|
matchSideEffectStatus: 'processing',
|
||||||
|
matchSideEffectTransitionId: 'transition-1',
|
||||||
|
},
|
||||||
$unset: { matchSideEffectError: '' },
|
$unset: { matchSideEffectError: '' },
|
||||||
},
|
},
|
||||||
expect.objectContaining({ returnDocument: 'after' }),
|
expect.objectContaining({ returnDocument: 'after' }),
|
||||||
@@ -1045,34 +1063,42 @@ describe('auction durability projection helpers', () => {
|
|||||||
_id: 'auction-1',
|
_id: 'auction-1',
|
||||||
auctionLifecycleId: 'life-1',
|
auctionLifecycleId: 'life-1',
|
||||||
matchSideEffectRevision: 2,
|
matchSideEffectRevision: 2,
|
||||||
|
matchSideEffectTransitionId: 'transition-1',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
$inc: { matchSideEffectRevision: 1 },
|
$inc: { matchSideEffectRevision: 1 },
|
||||||
$set: { matchSideEffectStatus: 'completed' },
|
$set: {
|
||||||
|
matchSideEffectStatus: 'completed',
|
||||||
|
matchSideEffectTransitionId: 'transition-1',
|
||||||
|
},
|
||||||
$unset: { matchSideEffectError: '' },
|
$unset: { matchSideEffectError: '' },
|
||||||
},
|
},
|
||||||
expect.objectContaining({ returnDocument: 'after' }),
|
expect.objectContaining({ returnDocument: 'after' }),
|
||||||
);
|
);
|
||||||
expect(mirrorMatchSideEffectStatus).toHaveBeenCalledWith({
|
expect(mirrorMatchSideEffectStatus).toHaveBeenCalledWith({
|
||||||
auctionLifecycleId: 'life-1',
|
auctionLifecycleId: 'life-1',
|
||||||
|
auctionStateTransitionId: 'transition-1',
|
||||||
matchId: 'match-1',
|
matchId: 'match-1',
|
||||||
matchSideEffectRevision: 2,
|
matchSideEffectRevision: 2,
|
||||||
matchSideEffectStatus: 'processing',
|
matchSideEffectStatus: 'processing',
|
||||||
});
|
});
|
||||||
expect(mirrorMatchSideEffectStatus).toHaveBeenLastCalledWith({
|
expect(mirrorMatchSideEffectStatus).toHaveBeenLastCalledWith({
|
||||||
auctionLifecycleId: 'life-1',
|
auctionLifecycleId: 'life-1',
|
||||||
|
auctionStateTransitionId: 'transition-1',
|
||||||
matchId: 'match-1',
|
matchId: 'match-1',
|
||||||
matchSideEffectRevision: 3,
|
matchSideEffectRevision: 3,
|
||||||
matchSideEffectStatus: 'completed',
|
matchSideEffectStatus: 'completed',
|
||||||
});
|
});
|
||||||
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(1, 'match-1', {
|
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(1, 'match-1', {
|
||||||
auctionLifecycleId: 'life-1',
|
auctionLifecycleId: 'life-1',
|
||||||
|
auctionStateTransitionId: 'transition-1',
|
||||||
currentServerTimestampMS: 2000,
|
currentServerTimestampMS: 2000,
|
||||||
matchSideEffectRevision: 2,
|
matchSideEffectRevision: 2,
|
||||||
matchSideEffectStatus: 'processing',
|
matchSideEffectStatus: 'processing',
|
||||||
});
|
});
|
||||||
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(2, 'match-1', {
|
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(2, 'match-1', {
|
||||||
auctionLifecycleId: 'life-1',
|
auctionLifecycleId: 'life-1',
|
||||||
|
auctionStateTransitionId: 'transition-1',
|
||||||
currentServerTimestampMS: 3000,
|
currentServerTimestampMS: 3000,
|
||||||
matchSideEffectRevision: 3,
|
matchSideEffectRevision: 3,
|
||||||
matchSideEffectStatus: 'completed',
|
matchSideEffectStatus: 'completed',
|
||||||
@@ -1080,7 +1106,7 @@ describe('auction durability projection helpers', () => {
|
|||||||
expect(sendCommand).toHaveBeenCalledWith([
|
expect(sendCommand).toHaveBeenCalledWith([
|
||||||
'EVAL',
|
'EVAL',
|
||||||
expect.stringContaining("redis.call('EXPIRE'"),
|
expect.stringContaining("redis.call('EXPIRE'"),
|
||||||
'11',
|
'12',
|
||||||
'auction:match-1:liveAuctionState',
|
'auction:match-1:liveAuctionState',
|
||||||
'auction:bidRoundDeadlineQueue',
|
'auction:bidRoundDeadlineQueue',
|
||||||
'auction:match-1:auctionStructureState',
|
'auction:match-1:auctionStructureState',
|
||||||
@@ -1092,6 +1118,7 @@ describe('auction durability projection helpers', () => {
|
|||||||
'auction:match-1:auctionActionRequestResultOrder',
|
'auction:match-1:auctionActionRequestResultOrder',
|
||||||
'auction:match-1:rehydrateLock',
|
'auction:match-1:rehydrateLock',
|
||||||
'auction:match-1:auctionStateTransitionLock',
|
'auction:match-1:auctionStateTransitionLock',
|
||||||
|
'auction:match-1:rejectedBidRequestResultOrder',
|
||||||
'match-1',
|
'match-1',
|
||||||
'life-1',
|
'life-1',
|
||||||
String(7 * 24 * 60 * 60),
|
String(7 * 24 * 60 * 60),
|
||||||
@@ -1263,7 +1290,12 @@ describe('auction durability projection helpers', () => {
|
|||||||
const broadcastMatchSideEffect = jest.fn();
|
const broadcastMatchSideEffect = jest.fn();
|
||||||
const scheduler = new AuctionDurabilityScheduler(
|
const scheduler = new AuctionDurabilityScheduler(
|
||||||
{
|
{
|
||||||
createSession: jest.fn().mockResolvedValue(null),
|
createSession: jest.fn().mockResolvedValueOnce(null).mockResolvedValue({
|
||||||
|
startTransaction: jest.fn(),
|
||||||
|
commitTransaction: jest.fn(),
|
||||||
|
abortTransaction: jest.fn(),
|
||||||
|
endSession: jest.fn(),
|
||||||
|
}),
|
||||||
getModel: jest.fn((name: string) => {
|
getModel: jest.fn((name: string) => {
|
||||||
if (name === 'auctionHistory') {
|
if (name === 'auctionHistory') {
|
||||||
return {
|
return {
|
||||||
@@ -1282,7 +1314,11 @@ describe('auction durability projection helpers', () => {
|
|||||||
return { updateOne: sideEffectUpdateOne };
|
return { updateOne: sideEffectUpdateOne };
|
||||||
}
|
}
|
||||||
if (name === 'match')
|
if (name === 'match')
|
||||||
return { findById: jest.fn().mockReturnValue(match) };
|
return {
|
||||||
|
findById: jest.fn().mockReturnValue({
|
||||||
|
session: jest.fn().mockResolvedValue(match),
|
||||||
|
}),
|
||||||
|
};
|
||||||
return {};
|
return {};
|
||||||
}),
|
}),
|
||||||
} as never,
|
} as never,
|
||||||
@@ -1301,8 +1337,8 @@ describe('auction durability projection helpers', () => {
|
|||||||
|
|
||||||
await scheduler.applyDurabilityPayload(resetPayload);
|
await scheduler.applyDurabilityPayload(resetPayload);
|
||||||
|
|
||||||
expect(releaseFromMatch).toHaveBeenCalledWith(match);
|
expect(releaseFromMatch).toHaveBeenCalledWith(match, expect.any(Object));
|
||||||
expect(cancelPolling).toHaveBeenCalledWith(match);
|
expect(cancelPolling).toHaveBeenCalledWith(match, expect.any(Object));
|
||||||
expect(match).toMatchObject({
|
expect(match).toMatchObject({
|
||||||
gameSchedule: [],
|
gameSchedule: [],
|
||||||
result: undefined,
|
result: undefined,
|
||||||
@@ -1328,12 +1364,14 @@ describe('auction durability projection helpers', () => {
|
|||||||
);
|
);
|
||||||
expect(mirrorMatchSideEffectStatus).toHaveBeenLastCalledWith({
|
expect(mirrorMatchSideEffectStatus).toHaveBeenLastCalledWith({
|
||||||
auctionLifecycleId: 'life-1',
|
auctionLifecycleId: 'life-1',
|
||||||
|
auctionStateTransitionId: 'transition-1',
|
||||||
matchId: 'match-1',
|
matchId: 'match-1',
|
||||||
matchSideEffectRevision: 3,
|
matchSideEffectRevision: 3,
|
||||||
matchSideEffectStatus: 'completed',
|
matchSideEffectStatus: 'completed',
|
||||||
});
|
});
|
||||||
expect(broadcastMatchSideEffect).toHaveBeenLastCalledWith('match-1', {
|
expect(broadcastMatchSideEffect).toHaveBeenLastCalledWith('match-1', {
|
||||||
auctionLifecycleId: 'life-1',
|
auctionLifecycleId: 'life-1',
|
||||||
|
auctionStateTransitionId: 'transition-1',
|
||||||
currentServerTimestampMS: 3000,
|
currentServerTimestampMS: 3000,
|
||||||
matchSideEffectRevision: 3,
|
matchSideEffectRevision: 3,
|
||||||
matchSideEffectStatus: 'completed',
|
matchSideEffectStatus: 'completed',
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
OnModuleDestroy,
|
OnModuleDestroy,
|
||||||
OnModuleInit,
|
OnModuleInit,
|
||||||
Optional,
|
Optional,
|
||||||
|
ConflictException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { createHash, randomUUID } from 'crypto';
|
import { createHash, randomUUID } from 'crypto';
|
||||||
import type mongoose from 'mongoose';
|
import type mongoose from 'mongoose';
|
||||||
@@ -16,6 +17,10 @@ import type {
|
|||||||
import { TournamentCodeService } from '../tournament-code/tournament-code.service';
|
import { TournamentCodeService } from '../tournament-code/tournament-code.service';
|
||||||
import { TournamentResultService } from '../tournament-result/tournament-result.service';
|
import { TournamentResultService } from '../tournament-result/tournament-result.service';
|
||||||
import { AuctionEventBusService } from './auction-event-bus.service';
|
import { AuctionEventBusService } from './auction-event-bus.service';
|
||||||
|
import { AuctionService } from './auction.service';
|
||||||
|
import { AuctionBidArchiveService } from './auction-bid-archive.service';
|
||||||
|
import { AuctionLifecycleLock } from './auction-lifecycle-lock';
|
||||||
|
import { buildAuctionProjectionUnset } from './auction-projection';
|
||||||
import {
|
import {
|
||||||
AuctionSideEffectService,
|
AuctionSideEffectService,
|
||||||
buildMatchSideEffectDelta,
|
buildMatchSideEffectDelta,
|
||||||
@@ -26,6 +31,7 @@ import { AuctionRedisService } from './redis/auction-redis.service';
|
|||||||
import { AuctionRedisStateReaderService } from './redis/auction-redis-state-reader.service';
|
import { AuctionRedisStateReaderService } from './redis/auction-redis-state-reader.service';
|
||||||
import {
|
import {
|
||||||
AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY,
|
AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY,
|
||||||
|
AUCTION_DEAD_LETTER_STATUS_QUEUE_KEY,
|
||||||
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
|
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
|
||||||
buildAuctionRedisKeys,
|
buildAuctionRedisKeys,
|
||||||
} from './redis/auction-redis.keys';
|
} from './redis/auction-redis.keys';
|
||||||
@@ -36,6 +42,8 @@ const AUCTION_DURABILITY_BATCH_LIMIT = 20;
|
|||||||
const AUCTION_DURABILITY_RETRY_DELAY_MS = 5000;
|
const AUCTION_DURABILITY_RETRY_DELAY_MS = 5000;
|
||||||
const AUCTION_DURABILITY_MAX_RETRY_DELAY_MS = 60_000;
|
const AUCTION_DURABILITY_MAX_RETRY_DELAY_MS = 60_000;
|
||||||
const AUCTION_DURABILITY_MAX_ATTEMPTS = 10;
|
const AUCTION_DURABILITY_MAX_ATTEMPTS = 10;
|
||||||
|
const AUCTION_DURABILITY_MAX_PENDING_ATTEMPTS = 120;
|
||||||
|
const AUCTION_DURABILITY_MAX_PENDING_DURATION_MS = 10 * 60 * 1000;
|
||||||
const AUCTION_DURABILITY_ERROR_MESSAGE_MAX_LENGTH = 2000;
|
const AUCTION_DURABILITY_ERROR_MESSAGE_MAX_LENGTH = 2000;
|
||||||
const AUCTION_DURABILITY_LEADER_LOCK_KEY =
|
const AUCTION_DURABILITY_LEADER_LOCK_KEY =
|
||||||
'auction:auctionDurabilityScheduler:leader';
|
'auction:auctionDurabilityScheduler:leader';
|
||||||
@@ -45,6 +53,7 @@ const AUCTION_SIDE_EFFECT_LEASE_DURATION_MS = 30_000;
|
|||||||
const SYNC_MATCH_TEAMS_SIDE_EFFECT_TYPE = 'syncMatchTeamsAfterComplete';
|
const SYNC_MATCH_TEAMS_SIDE_EFFECT_TYPE = 'syncMatchTeamsAfterComplete';
|
||||||
const RESET_MATCH_SIDE_EFFECT_TYPE = 'resetMatchAfterAuctionReset';
|
const RESET_MATCH_SIDE_EFFECT_TYPE = 'resetMatchAfterAuctionReset';
|
||||||
const UNDO_COMPLETED_MATCH_SIDE_EFFECT_TYPE = 'undoCompletedAuctionSideEffects';
|
const UNDO_COMPLETED_MATCH_SIDE_EFFECT_TYPE = 'undoCompletedAuctionSideEffects';
|
||||||
|
class SideEffectPendingError extends Error {}
|
||||||
|
|
||||||
export interface AuctionDurabilityPayload {
|
export interface AuctionDurabilityPayload {
|
||||||
actorUserId?: unknown;
|
actorUserId?: unknown;
|
||||||
@@ -67,6 +76,7 @@ export interface AuctionDurabilityPayload {
|
|||||||
export interface AuctionProjectionIdentity {
|
export interface AuctionProjectionIdentity {
|
||||||
auctionLifecycleId?: string;
|
auctionLifecycleId?: string;
|
||||||
revision?: number;
|
revision?: number;
|
||||||
|
matchSideEffectTransitionId?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
type ParsedAuctionHistoryMutation =
|
type ParsedAuctionHistoryMutation =
|
||||||
@@ -85,7 +95,7 @@ interface CleanupSideEffectMatchDocument {
|
|||||||
participants: Array<{ excluded?: boolean }>;
|
participants: Array<{ excluded?: boolean }>;
|
||||||
result?: unknown;
|
result?: unknown;
|
||||||
resultPollState?: unknown;
|
resultPollState?: unknown;
|
||||||
save(): Promise<unknown>;
|
save(options?: { session: mongoose.ClientSession }): Promise<unknown>;
|
||||||
status: string;
|
status: string;
|
||||||
teamBuiltAt?: Date;
|
teamBuiltAt?: Date;
|
||||||
teams?: unknown[];
|
teams?: unknown[];
|
||||||
@@ -99,6 +109,7 @@ export class AuctionDurabilityScheduler
|
|||||||
private readonly logger = new Logger(AuctionDurabilityScheduler.name);
|
private readonly logger = new Logger(AuctionDurabilityScheduler.name);
|
||||||
private tickTimer?: NodeJS.Timeout;
|
private tickTimer?: NodeJS.Timeout;
|
||||||
private tickInProgress = false;
|
private tickInProgress = false;
|
||||||
|
private deadLetterScanCursor = '0';
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly connectionService: ConnectionService,
|
private readonly connectionService: ConnectionService,
|
||||||
@@ -113,6 +124,9 @@ export class AuctionDurabilityScheduler
|
|||||||
private readonly auctionEventBusService?: AuctionEventBusService,
|
private readonly auctionEventBusService?: AuctionEventBusService,
|
||||||
@Optional()
|
@Optional()
|
||||||
private readonly auctionRedisStateReaderService?: AuctionRedisStateReaderService,
|
private readonly auctionRedisStateReaderService?: AuctionRedisStateReaderService,
|
||||||
|
@Optional() private readonly auctionService?: AuctionService,
|
||||||
|
@Optional()
|
||||||
|
private readonly auctionBidArchiveService?: AuctionBidArchiveService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public onModuleInit(): void {
|
public onModuleInit(): void {
|
||||||
@@ -187,6 +201,23 @@ export class AuctionDurabilityScheduler
|
|||||||
});
|
});
|
||||||
await this.clearDurabilityPayload(payloadKey);
|
await this.clearDurabilityPayload(payloadKey);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
if (
|
||||||
|
error instanceof SideEffectPendingError ||
|
||||||
|
error instanceof ConflictException
|
||||||
|
) {
|
||||||
|
const disposition = await this.deferDurabilityPayload(
|
||||||
|
payloadKey,
|
||||||
|
currentRedisTimestampMS,
|
||||||
|
error,
|
||||||
|
);
|
||||||
|
if (disposition === 'dead-lettered') {
|
||||||
|
failed += 1;
|
||||||
|
this.logger.warn(
|
||||||
|
`Auction durability payload exceeded its pending limit: ${payloadKey}`,
|
||||||
|
);
|
||||||
|
} else skipped += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
failed += 1;
|
failed += 1;
|
||||||
const failureDisposition = await this.recordDurabilityPayloadFailure(
|
const failureDisposition = await this.recordDurabilityPayloadFailure(
|
||||||
payloadKey,
|
payloadKey,
|
||||||
@@ -214,6 +245,14 @@ export class AuctionDurabilityScheduler
|
|||||||
const payloadJson = hash.payloadJson;
|
const payloadJson = hash.payloadJson;
|
||||||
if (!payloadJson) return null;
|
if (!payloadJson) return null;
|
||||||
const payload = JSON.parse(payloadJson) as AuctionDurabilityPayload;
|
const payload = JSON.parse(payloadJson) as AuctionDurabilityPayload;
|
||||||
|
const committedDeadline = Number(hash.committedBidRoundDeadlineTimestampMS);
|
||||||
|
if (Number.isFinite(committedDeadline) && committedDeadline > 0) {
|
||||||
|
payload.afterAuctionMongoProjection.currentBidRoundDeadlineTimestampMS =
|
||||||
|
committedDeadline;
|
||||||
|
payload.afterAuctionMongoProjection.currentDeadline = new Date(
|
||||||
|
committedDeadline,
|
||||||
|
).toISOString();
|
||||||
|
}
|
||||||
const committedAtRedisTimestampMS = Number(
|
const committedAtRedisTimestampMS = Number(
|
||||||
hash.committedAtRedisTimestampMS,
|
hash.committedAtRedisTimestampMS,
|
||||||
);
|
);
|
||||||
@@ -240,12 +279,12 @@ export class AuctionDurabilityScheduler
|
|||||||
const sideEffectMutation = parseMatchSideEffectMutation(
|
const sideEffectMutation = parseMatchSideEffectMutation(
|
||||||
payload.matchSideEffectMutation,
|
payload.matchSideEffectMutation,
|
||||||
);
|
);
|
||||||
|
let shouldUpdateProjection = true;
|
||||||
|
let shouldApplySideEffects = true;
|
||||||
|
let shouldApplyHistoryMutation = true;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
session?.startTransaction();
|
session?.startTransaction();
|
||||||
const historyMutation = parseAuctionHistoryMutation(
|
|
||||||
payload.historyMutation,
|
|
||||||
);
|
|
||||||
if (typeof AuctionModel.findById === 'function') {
|
if (typeof AuctionModel.findById === 'function') {
|
||||||
const currentProjection =
|
const currentProjection =
|
||||||
await readAuctionProjectionIdentityForMutation(
|
await readAuctionProjectionIdentityForMutation(
|
||||||
@@ -256,37 +295,44 @@ export class AuctionDurabilityScheduler
|
|||||||
if (
|
if (
|
||||||
!shouldProcessAuctionDurabilityPayload(currentProjection, payload)
|
!shouldProcessAuctionDurabilityPayload(currentProjection, payload)
|
||||||
) {
|
) {
|
||||||
// 뒤 payload가 먼저 projection revision을 올리면 앞 append payload가 stale이 된다.
|
|
||||||
// 이때 projection/side effect는 건드리지 않고 undo용 history만 멱등 복구한다.
|
|
||||||
if (
|
if (
|
||||||
historyMutation.type === 'append' &&
|
currentProjection.auctionLifecycleId !== payload.auctionLifecycleId
|
||||||
currentProjection.auctionLifecycleId === payload.auctionLifecycleId
|
|
||||||
) {
|
) {
|
||||||
await this.applyStaleAppendHistoryRecovery({
|
if (session) await session.commitTransaction();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
shouldApplyHistoryMutation =
|
||||||
|
!(await this.isAppendHistoryInvalidatedByLaterDestructiveMutation({
|
||||||
AuctionHistoryModel,
|
AuctionHistoryModel,
|
||||||
payload,
|
payload,
|
||||||
session,
|
session,
|
||||||
});
|
}));
|
||||||
}
|
// History operations have their own sequence bounds. A newer ordinary
|
||||||
if (session) await session.commitTransaction();
|
// projection must not discard an earlier undo's history cleanup.
|
||||||
return;
|
shouldUpdateProjection = false;
|
||||||
|
shouldApplySideEffects =
|
||||||
|
Boolean(this.auctionRedisStateReaderService) ||
|
||||||
|
currentProjection.matchSideEffectTransitionId ===
|
||||||
|
payload.auctionStateTransitionId;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
await this.applyAuctionHistoryMutation({
|
if (shouldApplyHistoryMutation)
|
||||||
AuctionHistoryModel,
|
await this.applyAuctionHistoryMutation({
|
||||||
AuctionModel,
|
AuctionHistoryModel,
|
||||||
payload,
|
AuctionModel,
|
||||||
session,
|
payload,
|
||||||
});
|
session,
|
||||||
|
});
|
||||||
const projectionOperation = buildAuctionProjectionGuardedUpdate(payload);
|
const projectionOperation = buildAuctionProjectionGuardedUpdate(payload);
|
||||||
await execMaybe(
|
if (shouldUpdateProjection)
|
||||||
AuctionModel.updateOne(
|
await execMaybe(
|
||||||
projectionOperation.filter as never,
|
AuctionModel.updateOne(
|
||||||
projectionOperation.update as never,
|
projectionOperation.filter as never,
|
||||||
{ session } as never,
|
projectionOperation.update as never,
|
||||||
),
|
{ session } as never,
|
||||||
);
|
),
|
||||||
if (sideEffectMutation) {
|
);
|
||||||
|
if (sideEffectMutation && shouldApplySideEffects) {
|
||||||
const sideEffectOperation = buildSideEffectApplicationUpsert(
|
const sideEffectOperation = buildSideEffectApplicationUpsert(
|
||||||
payload,
|
payload,
|
||||||
sideEffectMutation,
|
sideEffectMutation,
|
||||||
@@ -312,7 +358,7 @@ export class AuctionDurabilityScheduler
|
|||||||
|
|
||||||
await this.broadcastLatestRedisAuctionStateIfRequested(payload);
|
await this.broadcastLatestRedisAuctionStateIfRequested(payload);
|
||||||
|
|
||||||
if (sideEffectMutation) {
|
if (sideEffectMutation && shouldApplySideEffects) {
|
||||||
await this.applyMatchSideEffect(payload, sideEffectMutation);
|
await this.applyMatchSideEffect(payload, sideEffectMutation);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -352,6 +398,64 @@ export class AuctionDurabilityScheduler
|
|||||||
private async applyMatchSideEffect(
|
private async applyMatchSideEffect(
|
||||||
payload: AuctionDurabilityPayload,
|
payload: AuctionDurabilityPayload,
|
||||||
mutation: ParsedMatchSideEffectMutation,
|
mutation: ParsedMatchSideEffectMutation,
|
||||||
|
): Promise<void> {
|
||||||
|
return new AuctionLifecycleLock(this.auctionRedisService).run(
|
||||||
|
String(payload.matchId),
|
||||||
|
async () => {
|
||||||
|
if (this.auctionRedisStateReaderService) {
|
||||||
|
const state =
|
||||||
|
await this.auctionRedisStateReaderService.readAuctionStateView(
|
||||||
|
String(payload.matchId),
|
||||||
|
);
|
||||||
|
if (!state)
|
||||||
|
throw new SideEffectPendingError(
|
||||||
|
'Auction realtime state is unavailable.',
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
state.auctionLifecycleId !== payload.auctionLifecycleId ||
|
||||||
|
(state.matchSideEffectTransitionId &&
|
||||||
|
state.matchSideEffectTransitionId !==
|
||||||
|
payload.auctionStateTransitionId) ||
|
||||||
|
(mutation.type === SYNC_MATCH_TEAMS_SIDE_EFFECT_TYPE &&
|
||||||
|
state.phase !== 'complete')
|
||||||
|
)
|
||||||
|
return;
|
||||||
|
// An ordinary later projection may have reached Mongo before this
|
||||||
|
// side-effect-bearing transition. Install its pending generation only
|
||||||
|
// while Redis still names it and Mongo has not advanced beyond it.
|
||||||
|
const AuctionModel = await this.connectionService.getModel('auction');
|
||||||
|
const pendingRevision = Number(
|
||||||
|
payload.afterAuctionMongoProjection.matchSideEffectRevision ?? 0,
|
||||||
|
);
|
||||||
|
await execMaybe(
|
||||||
|
AuctionModel.updateOne(
|
||||||
|
{
|
||||||
|
_id: payload.auctionId,
|
||||||
|
auctionLifecycleId: payload.auctionLifecycleId,
|
||||||
|
$or: [
|
||||||
|
{ matchSideEffectRevision: { $lt: pendingRevision } },
|
||||||
|
{ matchSideEffectRevision: { $exists: false } },
|
||||||
|
],
|
||||||
|
} as never,
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
matchSideEffectTransitionId: payload.auctionStateTransitionId,
|
||||||
|
matchSideEffectRevision: pendingRevision,
|
||||||
|
matchSideEffectStatus: 'pending',
|
||||||
|
},
|
||||||
|
$unset: { matchSideEffectError: '' },
|
||||||
|
} as never,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await this.applyMatchSideEffectWhileLocked(payload, mutation);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async applyMatchSideEffectWhileLocked(
|
||||||
|
payload: AuctionDurabilityPayload,
|
||||||
|
mutation: ParsedMatchSideEffectMutation,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
if (mutation.type === SYNC_MATCH_TEAMS_SIDE_EFFECT_TYPE) {
|
if (mutation.type === SYNC_MATCH_TEAMS_SIDE_EFFECT_TYPE) {
|
||||||
await this.applySyncMatchTeamsSideEffect(payload, mutation);
|
await this.applySyncMatchTeamsSideEffect(payload, mutation);
|
||||||
@@ -407,7 +511,26 @@ export class AuctionDurabilityScheduler
|
|||||||
}) as never,
|
}) as never,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
if (!hasMatchedDocument(leaseResult)) return;
|
if (!hasMatchedDocument(leaseResult)) {
|
||||||
|
const existing = await AuctionSideEffectApplicationModel.findOne(
|
||||||
|
identity as never,
|
||||||
|
)
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
if (existing?.state === 'completed') {
|
||||||
|
await this.persistAndBroadcastMatchSideEffectStatus({
|
||||||
|
AuctionModel,
|
||||||
|
currentServerTimestampMS: currentRedisTimestampMS,
|
||||||
|
payload,
|
||||||
|
status: 'completed',
|
||||||
|
});
|
||||||
|
await this.expireCompletedAuctionRedisRuntime(payload);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new SideEffectPendingError(
|
||||||
|
'Auction side effect is still owned by another worker.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus(
|
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus(
|
||||||
{
|
{
|
||||||
@@ -420,7 +543,11 @@ export class AuctionDurabilityScheduler
|
|||||||
status: 'processing',
|
status: 'processing',
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
if (!processingDelta) return;
|
if (!processingDelta) {
|
||||||
|
throw new SideEffectPendingError(
|
||||||
|
'Auction side-effect generation is not ready.',
|
||||||
|
);
|
||||||
|
}
|
||||||
const expectedMatchSideEffectRevision =
|
const expectedMatchSideEffectRevision =
|
||||||
processingDelta.matchSideEffectRevision;
|
processingDelta.matchSideEffectRevision;
|
||||||
|
|
||||||
@@ -489,7 +616,11 @@ export class AuctionDurabilityScheduler
|
|||||||
await this.auctionRedisService.getCurrentRedisTimestampMS();
|
await this.auctionRedisService.getCurrentRedisTimestampMS();
|
||||||
await execMaybe(
|
await execMaybe(
|
||||||
AuctionSideEffectApplicationModel.updateOne(
|
AuctionSideEffectApplicationModel.updateOne(
|
||||||
identity as never,
|
{
|
||||||
|
...identity,
|
||||||
|
processingOwnerToken: ownerToken,
|
||||||
|
state: 'processing',
|
||||||
|
} as never,
|
||||||
{
|
{
|
||||||
$set: {
|
$set: {
|
||||||
completedAtTimestampMS,
|
completedAtTimestampMS,
|
||||||
@@ -518,7 +649,11 @@ export class AuctionDurabilityScheduler
|
|||||||
await this.auctionRedisService.getCurrentRedisTimestampMS();
|
await this.auctionRedisService.getCurrentRedisTimestampMS();
|
||||||
await execMaybe(
|
await execMaybe(
|
||||||
AuctionSideEffectApplicationModel.updateOne(
|
AuctionSideEffectApplicationModel.updateOne(
|
||||||
identity as never,
|
{
|
||||||
|
...identity,
|
||||||
|
processingOwnerToken: ownerToken,
|
||||||
|
state: 'processing',
|
||||||
|
} as never,
|
||||||
{
|
{
|
||||||
$set: {
|
$set: {
|
||||||
lastError: error instanceof Error ? error.message : String(error),
|
lastError: error instanceof Error ? error.message : String(error),
|
||||||
@@ -544,33 +679,6 @@ export class AuctionDurabilityScheduler
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async applyStaleAppendHistoryRecovery(params: {
|
|
||||||
AuctionHistoryModel: {
|
|
||||||
findOne?: (...args: never[]) => unknown;
|
|
||||||
updateOne: (...args: never[]) => unknown;
|
|
||||||
};
|
|
||||||
payload: AuctionDurabilityPayload;
|
|
||||||
session: mongoose.ClientSession | null | undefined;
|
|
||||||
}): Promise<void> {
|
|
||||||
const invalidated =
|
|
||||||
await this.isAppendHistoryInvalidatedByLaterDestructiveMutation(params);
|
|
||||||
if (invalidated) return;
|
|
||||||
|
|
||||||
const historyOperation = buildAuctionHistoryUpsert(
|
|
||||||
params.payload,
|
|
||||||
).updateOne;
|
|
||||||
await execMaybe(
|
|
||||||
params.AuctionHistoryModel.updateOne(
|
|
||||||
historyOperation.filter as never,
|
|
||||||
historyOperation.update as never,
|
|
||||||
{
|
|
||||||
session: params.session,
|
|
||||||
upsert: true,
|
|
||||||
} as never,
|
|
||||||
) as Promise<unknown> | { exec(): Promise<unknown> },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async isAppendHistoryInvalidatedByLaterDestructiveMutation(params: {
|
private async isAppendHistoryInvalidatedByLaterDestructiveMutation(params: {
|
||||||
AuctionHistoryModel: {
|
AuctionHistoryModel: {
|
||||||
findOne?: (...args: never[]) => unknown;
|
findOne?: (...args: never[]) => unknown;
|
||||||
@@ -622,9 +730,7 @@ export class AuctionDurabilityScheduler
|
|||||||
await this.applyMatchCleanupSideEffect({
|
await this.applyMatchCleanupSideEffect({
|
||||||
mutation,
|
mutation,
|
||||||
payload,
|
payload,
|
||||||
updateMatch: async (match) => {
|
updateMatch: (match) => {
|
||||||
await this.tournamentCodeService?.releaseFromMatch(match as never);
|
|
||||||
await this.tournamentResultService?.cancelPolling(match as never);
|
|
||||||
match.status = 'recruiting';
|
match.status = 'recruiting';
|
||||||
match.teams = [];
|
match.teams = [];
|
||||||
match.tournamentCodeIds = [];
|
match.tournamentCodeIds = [];
|
||||||
@@ -635,7 +741,6 @@ export class AuctionDurabilityScheduler
|
|||||||
match.teamBuiltAt = undefined;
|
match.teamBuiltAt = undefined;
|
||||||
match.result = undefined;
|
match.result = undefined;
|
||||||
match.resultPollState = undefined;
|
match.resultPollState = undefined;
|
||||||
await match.save();
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -647,13 +752,14 @@ export class AuctionDurabilityScheduler
|
|||||||
await this.applyMatchCleanupSideEffect({
|
await this.applyMatchCleanupSideEffect({
|
||||||
mutation,
|
mutation,
|
||||||
payload,
|
payload,
|
||||||
updateMatch: async (match) => {
|
updateMatch: (match) => {
|
||||||
await this.tournamentCodeService?.releaseFromMatch(match as never);
|
|
||||||
await this.tournamentResultService?.cancelPolling(match as never);
|
|
||||||
match.status = 'team-built';
|
match.status = 'team-built';
|
||||||
|
match.teams = [];
|
||||||
|
match.teamBuiltAt = undefined;
|
||||||
|
match.tournamentCodeIds = [];
|
||||||
|
match.gameSchedule = [];
|
||||||
match.result = undefined;
|
match.result = undefined;
|
||||||
match.resultPollState = undefined;
|
match.resultPollState = undefined;
|
||||||
await match.save();
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -661,7 +767,7 @@ export class AuctionDurabilityScheduler
|
|||||||
private async applyMatchCleanupSideEffect(params: {
|
private async applyMatchCleanupSideEffect(params: {
|
||||||
mutation: ParsedMatchSideEffectMutation;
|
mutation: ParsedMatchSideEffectMutation;
|
||||||
payload: AuctionDurabilityPayload;
|
payload: AuctionDurabilityPayload;
|
||||||
updateMatch: (match: CleanupSideEffectMatchDocument) => Promise<void>;
|
updateMatch: (match: CleanupSideEffectMatchDocument) => void;
|
||||||
}): Promise<void> {
|
}): Promise<void> {
|
||||||
if (!this.tournamentCodeService || !this.tournamentResultService) {
|
if (!this.tournamentCodeService || !this.tournamentResultService) {
|
||||||
throw new Error('Auction side-effect services are not available.');
|
throw new Error('Auction side-effect services are not available.');
|
||||||
@@ -700,7 +806,25 @@ export class AuctionDurabilityScheduler
|
|||||||
}) as never,
|
}) as never,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
if (!hasMatchedDocument(leaseResult)) return;
|
if (!hasMatchedDocument(leaseResult)) {
|
||||||
|
const existing = await AuctionSideEffectApplicationModel.findOne(
|
||||||
|
identity as never,
|
||||||
|
)
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
if (existing?.state === 'completed') {
|
||||||
|
await this.persistAndBroadcastMatchSideEffectStatus({
|
||||||
|
AuctionModel,
|
||||||
|
currentServerTimestampMS: currentRedisTimestampMS,
|
||||||
|
payload: params.payload,
|
||||||
|
status: 'completed',
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new SideEffectPendingError(
|
||||||
|
'Auction side effect is still owned by another worker.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus(
|
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus(
|
||||||
{
|
{
|
||||||
@@ -714,29 +838,56 @@ export class AuctionDurabilityScheduler
|
|||||||
status: 'processing',
|
status: 'processing',
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
if (!processingDelta) return;
|
if (!processingDelta) {
|
||||||
|
throw new SideEffectPendingError(
|
||||||
|
'Auction side-effect generation is not ready.',
|
||||||
|
);
|
||||||
|
}
|
||||||
const expectedMatchSideEffectRevision =
|
const expectedMatchSideEffectRevision =
|
||||||
processingDelta.matchSideEffectRevision;
|
processingDelta.matchSideEffectRevision;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const match = (await execMaybe(
|
const session = await this.connectionService.createSession();
|
||||||
MatchModel.findById(params.payload.matchId) as never,
|
if (!session)
|
||||||
)) as CleanupSideEffectMatchDocument | null;
|
throw new Error('Failed to start Match cleanup transaction.');
|
||||||
if (!match) {
|
try {
|
||||||
throw new Error(`Match not found: ${String(params.payload.matchId)}`);
|
session.startTransaction();
|
||||||
}
|
const match = (await MatchModel.findById(
|
||||||
if (match.competitionId) {
|
params.payload.matchId,
|
||||||
throw new Error(
|
).session(session)) as CleanupSideEffectMatchDocument | null;
|
||||||
'Cannot reset or undo Match teams after the immutable Competition has been created.',
|
if (!match)
|
||||||
|
throw new Error(`Match not found: ${String(params.payload.matchId)}`);
|
||||||
|
if (match.competitionId)
|
||||||
|
throw new Error(
|
||||||
|
'Cannot reset or undo Match teams after the immutable Competition has been created.',
|
||||||
|
);
|
||||||
|
await this.tournamentCodeService.releaseFromMatch(
|
||||||
|
match as never,
|
||||||
|
session,
|
||||||
);
|
);
|
||||||
|
await this.tournamentResultService.cancelPolling(
|
||||||
|
match as never,
|
||||||
|
session,
|
||||||
|
);
|
||||||
|
params.updateMatch(match);
|
||||||
|
await match.save({ session });
|
||||||
|
await session.commitTransaction();
|
||||||
|
} catch (error) {
|
||||||
|
await session.abortTransaction();
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
await session.endSession();
|
||||||
}
|
}
|
||||||
await params.updateMatch(match);
|
|
||||||
|
|
||||||
const completedAtTimestampMS =
|
const completedAtTimestampMS =
|
||||||
await this.auctionRedisService.getCurrentRedisTimestampMS();
|
await this.auctionRedisService.getCurrentRedisTimestampMS();
|
||||||
await execMaybe(
|
await execMaybe(
|
||||||
AuctionSideEffectApplicationModel.updateOne(
|
AuctionSideEffectApplicationModel.updateOne(
|
||||||
identity as never,
|
{
|
||||||
|
...identity,
|
||||||
|
processingOwnerToken: ownerToken,
|
||||||
|
state: 'processing',
|
||||||
|
} as never,
|
||||||
{
|
{
|
||||||
$set: {
|
$set: {
|
||||||
completedAtTimestampMS,
|
completedAtTimestampMS,
|
||||||
@@ -766,7 +917,11 @@ export class AuctionDurabilityScheduler
|
|||||||
error instanceof Error ? error.message : String(error);
|
error instanceof Error ? error.message : String(error);
|
||||||
await execMaybe(
|
await execMaybe(
|
||||||
AuctionSideEffectApplicationModel.updateOne(
|
AuctionSideEffectApplicationModel.updateOne(
|
||||||
identity as never,
|
{
|
||||||
|
...identity,
|
||||||
|
processingOwnerToken: ownerToken,
|
||||||
|
state: 'processing',
|
||||||
|
} as never,
|
||||||
{
|
{
|
||||||
$set: {
|
$set: {
|
||||||
lastError: errorMessage,
|
lastError: errorMessage,
|
||||||
@@ -828,7 +983,10 @@ export class AuctionDurabilityScheduler
|
|||||||
params.AuctionHistoryModel.deleteMany(
|
params.AuctionHistoryModel.deleteMany(
|
||||||
{
|
{
|
||||||
auctionId: params.payload.auctionId,
|
auctionId: params.payload.auctionId,
|
||||||
sequence: { $gt: mutation.targetHistorySequence },
|
sequence: {
|
||||||
|
$gt: mutation.targetHistorySequence,
|
||||||
|
$lt: params.payload.auctionHistorySequence,
|
||||||
|
},
|
||||||
} as never,
|
} as never,
|
||||||
{ session: params.session } as never,
|
{ session: params.session } as never,
|
||||||
) as Promise<unknown> | { exec(): Promise<unknown> },
|
) as Promise<unknown> | { exec(): Promise<unknown> },
|
||||||
@@ -842,6 +1000,7 @@ export class AuctionDurabilityScheduler
|
|||||||
params.AuctionHistoryModel.deleteMany(
|
params.AuctionHistoryModel.deleteMany(
|
||||||
{
|
{
|
||||||
auctionId: params.payload.auctionId,
|
auctionId: params.payload.auctionId,
|
||||||
|
sequence: { $lt: params.payload.auctionHistorySequence },
|
||||||
} as never,
|
} as never,
|
||||||
{ session: params.session } as never,
|
{ session: params.session } as never,
|
||||||
) as Promise<unknown> | { exec(): Promise<unknown> },
|
) as Promise<unknown> | { exec(): Promise<unknown> },
|
||||||
@@ -874,16 +1033,43 @@ export class AuctionDurabilityScheduler
|
|||||||
};
|
};
|
||||||
currentServerTimestampMS: number;
|
currentServerTimestampMS: number;
|
||||||
errorMessage?: string;
|
errorMessage?: string;
|
||||||
expectedMatchSideEffectRevision: number;
|
expectedMatchSideEffectRevision?: number;
|
||||||
payload: AuctionDurabilityPayload;
|
payload: AuctionDurabilityPayload;
|
||||||
status: AuctionMatchSideEffectStatus;
|
status: AuctionMatchSideEffectStatus;
|
||||||
|
onlyUnfinished?: boolean;
|
||||||
}): Promise<MatchSideEffectDelta | null> {
|
}): Promise<MatchSideEffectDelta | null> {
|
||||||
const updatedAuction = (await execMaybe(
|
const updatedAuction = (await execMaybe(
|
||||||
params.AuctionModel.findOneAndUpdate(
|
params.AuctionModel.findOneAndUpdate(
|
||||||
{
|
{
|
||||||
_id: params.payload.auctionId,
|
_id: params.payload.auctionId,
|
||||||
auctionLifecycleId: params.payload.auctionLifecycleId,
|
auctionLifecycleId: params.payload.auctionLifecycleId,
|
||||||
matchSideEffectRevision: params.expectedMatchSideEffectRevision,
|
...(params.onlyUnfinished
|
||||||
|
? { matchSideEffectStatus: { $ne: 'completed' } }
|
||||||
|
: {}),
|
||||||
|
...(params.status === 'processing'
|
||||||
|
? {
|
||||||
|
$or: [
|
||||||
|
{
|
||||||
|
matchSideEffectTransitionId:
|
||||||
|
params.payload.auctionStateTransitionId,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
matchSideEffectTransitionId: { $exists: false },
|
||||||
|
matchSideEffectRevision:
|
||||||
|
params.expectedMatchSideEffectRevision,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
matchSideEffectTransitionId:
|
||||||
|
params.payload.auctionStateTransitionId,
|
||||||
|
...(params.expectedMatchSideEffectRevision === undefined
|
||||||
|
? {}
|
||||||
|
: {
|
||||||
|
matchSideEffectRevision:
|
||||||
|
params.expectedMatchSideEffectRevision,
|
||||||
|
}),
|
||||||
|
}),
|
||||||
} as never,
|
} as never,
|
||||||
{
|
{
|
||||||
$inc: { matchSideEffectRevision: 1 },
|
$inc: { matchSideEffectRevision: 1 },
|
||||||
@@ -892,6 +1078,8 @@ export class AuctionDurabilityScheduler
|
|||||||
? { matchSideEffectError: params.errorMessage }
|
? { matchSideEffectError: params.errorMessage }
|
||||||
: {}),
|
: {}),
|
||||||
matchSideEffectStatus: params.status,
|
matchSideEffectStatus: params.status,
|
||||||
|
matchSideEffectTransitionId:
|
||||||
|
params.payload.auctionStateTransitionId,
|
||||||
},
|
},
|
||||||
...(params.errorMessage
|
...(params.errorMessage
|
||||||
? {}
|
? {}
|
||||||
@@ -915,6 +1103,7 @@ export class AuctionDurabilityScheduler
|
|||||||
|
|
||||||
const delta = buildMatchSideEffectDelta({
|
const delta = buildMatchSideEffectDelta({
|
||||||
auctionLifecycleId: updatedAuction.auctionLifecycleId,
|
auctionLifecycleId: updatedAuction.auctionLifecycleId,
|
||||||
|
auctionStateTransitionId: params.payload.auctionStateTransitionId,
|
||||||
currentServerTimestampMS: params.currentServerTimestampMS,
|
currentServerTimestampMS: params.currentServerTimestampMS,
|
||||||
matchSideEffectRevision: Number(
|
matchSideEffectRevision: Number(
|
||||||
updatedAuction.matchSideEffectRevision ?? 0,
|
updatedAuction.matchSideEffectRevision ?? 0,
|
||||||
@@ -923,19 +1112,170 @@ export class AuctionDurabilityScheduler
|
|||||||
updatedAuction.matchSideEffectStatus ?? params.status,
|
updatedAuction.matchSideEffectStatus ?? params.status,
|
||||||
});
|
});
|
||||||
|
|
||||||
await this.auctionSideEffectService?.mirrorMatchSideEffectStatus({
|
const mirrored =
|
||||||
auctionLifecycleId: delta.auctionLifecycleId,
|
await this.auctionSideEffectService?.mirrorMatchSideEffectStatus({
|
||||||
matchId: String(params.payload.matchId),
|
auctionLifecycleId: delta.auctionLifecycleId,
|
||||||
matchSideEffectRevision: delta.matchSideEffectRevision,
|
auctionStateTransitionId: params.payload.auctionStateTransitionId,
|
||||||
matchSideEffectStatus: delta.matchSideEffectStatus,
|
matchId: String(params.payload.matchId),
|
||||||
});
|
matchSideEffectRevision: delta.matchSideEffectRevision,
|
||||||
this.auctionEventBusService?.broadcastMatchSideEffect(
|
matchSideEffectStatus: delta.matchSideEffectStatus,
|
||||||
String(params.payload.matchId),
|
});
|
||||||
delta,
|
if (mirrored !== false) {
|
||||||
);
|
this.auctionEventBusService?.broadcastMatchSideEffect(
|
||||||
|
String(params.payload.matchId),
|
||||||
|
delta,
|
||||||
|
);
|
||||||
|
}
|
||||||
return delta;
|
return delta;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async reconcileDeadLetterStatuses(limit = 20): Promise<void> {
|
||||||
|
const client = this.auctionRedisService.raw();
|
||||||
|
const now = await this.auctionRedisService.getCurrentRedisTimestampMS();
|
||||||
|
// Also reconcile entries dead-lettered before status notifications existed.
|
||||||
|
const scanned = await client.sendCommand([
|
||||||
|
'ZSCAN',
|
||||||
|
AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY,
|
||||||
|
this.deadLetterScanCursor,
|
||||||
|
'COUNT',
|
||||||
|
String(limit),
|
||||||
|
]);
|
||||||
|
if (Array.isArray(scanned) && Array.isArray(scanned[1])) {
|
||||||
|
this.deadLetterScanCursor = String(scanned[0]);
|
||||||
|
for (let index = 0; index < scanned[1].length; index += 2) {
|
||||||
|
const key = String(scanned[1][index]);
|
||||||
|
if (
|
||||||
|
!(await client.sendCommand([
|
||||||
|
'HGET',
|
||||||
|
key,
|
||||||
|
'deadLetterStatusReconciledAtTimestampMS',
|
||||||
|
]))
|
||||||
|
) {
|
||||||
|
await client.sendCommand([
|
||||||
|
'ZADD',
|
||||||
|
AUCTION_DEAD_LETTER_STATUS_QUEUE_KEY,
|
||||||
|
'NX',
|
||||||
|
String(now),
|
||||||
|
key,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const reply = await client.sendCommand([
|
||||||
|
'ZRANGEBYSCORE',
|
||||||
|
AUCTION_DEAD_LETTER_STATUS_QUEUE_KEY,
|
||||||
|
'-inf',
|
||||||
|
String(now),
|
||||||
|
'LIMIT',
|
||||||
|
'0',
|
||||||
|
String(limit),
|
||||||
|
]);
|
||||||
|
if (!Array.isArray(reply)) return;
|
||||||
|
for (const key of reply.map(String)) {
|
||||||
|
try {
|
||||||
|
const payload = await this.readDurabilityPayload(key);
|
||||||
|
if (
|
||||||
|
payload &&
|
||||||
|
parseMatchSideEffectMutation(payload.matchSideEffectMutation)
|
||||||
|
) {
|
||||||
|
const state =
|
||||||
|
await this.auctionRedisStateReaderService?.readAuctionStateView(
|
||||||
|
String(payload.matchId),
|
||||||
|
);
|
||||||
|
// A terminal notification for a previous generation must not change
|
||||||
|
// a new completion/undo, even when Mongo is behind Redis.
|
||||||
|
const superseded =
|
||||||
|
state &&
|
||||||
|
(state.auctionLifecycleId !== payload.auctionLifecycleId ||
|
||||||
|
state.matchSideEffectStatus === 'completed' ||
|
||||||
|
(state.matchSideEffectTransitionId &&
|
||||||
|
state.matchSideEffectTransitionId !==
|
||||||
|
payload.auctionStateTransitionId));
|
||||||
|
if (!superseded) {
|
||||||
|
const AuctionModel =
|
||||||
|
await this.connectionService.getModel('auction');
|
||||||
|
if (
|
||||||
|
state?.matchSideEffectTransitionId ===
|
||||||
|
payload.auctionStateTransitionId
|
||||||
|
) {
|
||||||
|
const revision = Number(
|
||||||
|
payload.afterAuctionMongoProjection.matchSideEffectRevision ??
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
await AuctionModel.updateOne(
|
||||||
|
{
|
||||||
|
_id: payload.auctionId,
|
||||||
|
auctionLifecycleId: payload.auctionLifecycleId,
|
||||||
|
$or: [
|
||||||
|
{ matchSideEffectRevision: { $lt: revision } },
|
||||||
|
{ matchSideEffectRevision: { $exists: false } },
|
||||||
|
],
|
||||||
|
} as never,
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
matchSideEffectTransitionId:
|
||||||
|
payload.auctionStateTransitionId,
|
||||||
|
matchSideEffectRevision: revision,
|
||||||
|
matchSideEffectStatus: 'pending',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
// Heal a same-generation revision mismatch before sending the
|
||||||
|
// terminal status; otherwise Redis could ignore it as older.
|
||||||
|
await AuctionModel.updateOne(
|
||||||
|
{
|
||||||
|
_id: payload.auctionId,
|
||||||
|
auctionLifecycleId: payload.auctionLifecycleId,
|
||||||
|
matchSideEffectTransitionId: payload.auctionStateTransitionId,
|
||||||
|
matchSideEffectStatus: { $ne: 'completed' },
|
||||||
|
} as never,
|
||||||
|
{
|
||||||
|
$max: {
|
||||||
|
matchSideEffectRevision: Number(
|
||||||
|
state.matchSideEffectRevision ?? revision,
|
||||||
|
),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const error = await client.sendCommand(['HGET', key, 'lastError']);
|
||||||
|
await this.persistAndBroadcastMatchSideEffectStatus({
|
||||||
|
AuctionModel: AuctionModel as never,
|
||||||
|
payload,
|
||||||
|
currentServerTimestampMS: now,
|
||||||
|
status: 'failed',
|
||||||
|
onlyUnfinished: true,
|
||||||
|
errorMessage:
|
||||||
|
typeof error === 'string'
|
||||||
|
? error
|
||||||
|
: 'Auction side effect exhausted its retry limit.',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await client.sendCommand([
|
||||||
|
'EVAL',
|
||||||
|
"if redis.call('HEXISTS', KEYS[1], 'payloadJson') == 1 then redis.call('HSET', KEYS[1], 'deadLetterStatusReconciledAtTimestampMS', ARGV[1]) end redis.call('ZREM', KEYS[2], KEYS[1]); return 1",
|
||||||
|
'2',
|
||||||
|
key,
|
||||||
|
AUCTION_DEAD_LETTER_STATUS_QUEUE_KEY,
|
||||||
|
String(now),
|
||||||
|
]);
|
||||||
|
} catch (error) {
|
||||||
|
// Mongo or Redis mirroring may be unavailable at dead-letter time. Keep
|
||||||
|
// the notification durable until the failure can be shown to viewers.
|
||||||
|
await client.sendCommand([
|
||||||
|
'ZADD',
|
||||||
|
AUCTION_DEAD_LETTER_STATUS_QUEUE_KEY,
|
||||||
|
String(now + 5000),
|
||||||
|
key,
|
||||||
|
]);
|
||||||
|
this.logger.warn(
|
||||||
|
`Auction terminal status will retry for ${key}: ${String(error)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private async safeTick(): Promise<void> {
|
private async safeTick(): Promise<void> {
|
||||||
if (this.tickInProgress) return;
|
if (this.tickInProgress) return;
|
||||||
this.tickInProgress = true;
|
this.tickInProgress = true;
|
||||||
@@ -948,7 +1288,22 @@ export class AuctionDurabilityScheduler
|
|||||||
AUCTION_DURABILITY_LEADER_LOCK_TTL_MS,
|
AUCTION_DURABILITY_LEADER_LOCK_TTL_MS,
|
||||||
);
|
);
|
||||||
if (!leaderLockAcquired) return;
|
if (!leaderLockAcquired) return;
|
||||||
await this.processDueDurabilityPayloads(AUCTION_DURABILITY_BATCH_LIMIT);
|
// A failed maintenance task must not starve the other durable queues.
|
||||||
|
for (const work of [
|
||||||
|
() => this.processDueDurabilityPayloads(AUCTION_DURABILITY_BATCH_LIMIT),
|
||||||
|
() => this.reconcileDeadLetterStatuses(AUCTION_DURABILITY_BATCH_LIMIT),
|
||||||
|
() => this.auctionBidArchiveService?.persistPendingBids(),
|
||||||
|
() =>
|
||||||
|
this.auctionService?.retryPendingCancellations(
|
||||||
|
AUCTION_DURABILITY_BATCH_LIMIT,
|
||||||
|
),
|
||||||
|
]) {
|
||||||
|
try {
|
||||||
|
await work();
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.warn(`Auction maintenance task failed: ${String(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.warn(
|
this.logger.warn(
|
||||||
`Auction durability tick failed: ${
|
`Auction durability tick failed: ${
|
||||||
@@ -957,10 +1312,13 @@ export class AuctionDurabilityScheduler
|
|||||||
);
|
);
|
||||||
} finally {
|
} finally {
|
||||||
if (leaderLockAcquired) {
|
if (leaderLockAcquired) {
|
||||||
await this.auctionRedisService.releaseTokenLock(
|
await this.auctionRedisService
|
||||||
AUCTION_DURABILITY_LEADER_LOCK_KEY,
|
.releaseTokenLock(AUCTION_DURABILITY_LEADER_LOCK_KEY, leaderLockToken)
|
||||||
leaderLockToken,
|
.catch((error: unknown) => {
|
||||||
);
|
this.logger.warn(
|
||||||
|
`Auction durability lock release failed: ${String(error)}`,
|
||||||
|
);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
this.tickInProgress = false;
|
this.tickInProgress = false;
|
||||||
}
|
}
|
||||||
@@ -987,6 +1345,51 @@ export class AuctionDurabilityScheduler
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async deferDurabilityPayload(
|
||||||
|
payloadKey: string,
|
||||||
|
timestampMS: number,
|
||||||
|
error: unknown,
|
||||||
|
): Promise<'gone' | 'requeued' | 'dead-lettered'> {
|
||||||
|
// Keep coordination waits separate from failed work, but bound them across
|
||||||
|
// restarts too. Updating the payload and queue atomically avoids orphan jobs.
|
||||||
|
const result = await this.auctionRedisService
|
||||||
|
.raw()
|
||||||
|
.sendCommand([
|
||||||
|
'EVAL',
|
||||||
|
[
|
||||||
|
"if redis.call('HEXISTS', KEYS[1], 'payloadJson') == 0 then return 0 end",
|
||||||
|
"local count = redis.call('HINCRBY', KEYS[1], 'pendingAttempts', 1)",
|
||||||
|
"redis.call('HSETNX', KEYS[1], 'pendingSinceTimestampMS', ARGV[1])",
|
||||||
|
"local since = tonumber(redis.call('HGET', KEYS[1], 'pendingSinceTimestampMS'))",
|
||||||
|
"redis.call('HSET', KEYS[1], 'lastPendingReason', ARGV[5], 'lastPendingAtTimestampMS', ARGV[1])",
|
||||||
|
'if count >= tonumber(ARGV[3]) or tonumber(ARGV[1]) - since >= tonumber(ARGV[4]) then',
|
||||||
|
" redis.call('ZREM', KEYS[2], KEYS[1])",
|
||||||
|
" redis.call('HSET', KEYS[1], 'deadLetteredAtRedisTimestampMS', ARGV[1], 'lastError', ARGV[5])",
|
||||||
|
" redis.call('ZADD', KEYS[3], ARGV[1], KEYS[1])",
|
||||||
|
" redis.call('ZADD', KEYS[4], ARGV[1], KEYS[1])",
|
||||||
|
' return 2',
|
||||||
|
'end',
|
||||||
|
"redis.call('ZADD', KEYS[2], tonumber(ARGV[1]) + tonumber(ARGV[2]), KEYS[1])",
|
||||||
|
'return 1',
|
||||||
|
].join('\n'),
|
||||||
|
'4',
|
||||||
|
payloadKey,
|
||||||
|
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
|
||||||
|
AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY,
|
||||||
|
AUCTION_DEAD_LETTER_STATUS_QUEUE_KEY,
|
||||||
|
String(timestampMS),
|
||||||
|
String(AUCTION_DURABILITY_RETRY_DELAY_MS),
|
||||||
|
String(AUCTION_DURABILITY_MAX_PENDING_ATTEMPTS),
|
||||||
|
String(AUCTION_DURABILITY_MAX_PENDING_DURATION_MS),
|
||||||
|
formatErrorMessageForRedis(error),
|
||||||
|
]);
|
||||||
|
return Number(result) === 2
|
||||||
|
? 'dead-lettered'
|
||||||
|
: Number(result) === 1
|
||||||
|
? 'requeued'
|
||||||
|
: 'gone';
|
||||||
|
}
|
||||||
|
|
||||||
private async recordDurabilityPayloadFailure(
|
private async recordDurabilityPayloadFailure(
|
||||||
payloadKey: string,
|
payloadKey: string,
|
||||||
currentRedisTimestampMS: number,
|
currentRedisTimestampMS: number,
|
||||||
@@ -1012,24 +1415,17 @@ export class AuctionDurabilityScheduler
|
|||||||
Number.isFinite(attempts) &&
|
Number.isFinite(attempts) &&
|
||||||
attempts >= AUCTION_DURABILITY_MAX_ATTEMPTS
|
attempts >= AUCTION_DURABILITY_MAX_ATTEMPTS
|
||||||
) {
|
) {
|
||||||
await this.auctionRedisService
|
|
||||||
.raw()
|
|
||||||
.sendCommand(['ZREM', AUCTION_DURABILITY_RETRY_QUEUE_KEY, payloadKey]);
|
|
||||||
await this.auctionRedisService
|
await this.auctionRedisService
|
||||||
.raw()
|
.raw()
|
||||||
.sendCommand([
|
.sendCommand([
|
||||||
'HSET',
|
'EVAL',
|
||||||
|
"if redis.call('HEXISTS', KEYS[1], 'payloadJson') == 0 then return 0 end redis.call('HSET', KEYS[1], 'deadLetteredAtRedisTimestampMS', ARGV[1]); redis.call('ZREM', KEYS[2], KEYS[1]); redis.call('ZADD', KEYS[3], ARGV[1], KEYS[1]); redis.call('ZADD', KEYS[4], ARGV[1], KEYS[1]); return 1",
|
||||||
|
'4',
|
||||||
payloadKey,
|
payloadKey,
|
||||||
'deadLetteredAtRedisTimestampMS',
|
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
|
||||||
String(currentRedisTimestampMS),
|
|
||||||
]);
|
|
||||||
await this.auctionRedisService
|
|
||||||
.raw()
|
|
||||||
.sendCommand([
|
|
||||||
'ZADD',
|
|
||||||
AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY,
|
AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY,
|
||||||
|
AUCTION_DEAD_LETTER_STATUS_QUEUE_KEY,
|
||||||
String(currentRedisTimestampMS),
|
String(currentRedisTimestampMS),
|
||||||
payloadKey,
|
|
||||||
]);
|
]);
|
||||||
return 'dead-lettered';
|
return 'dead-lettered';
|
||||||
}
|
}
|
||||||
@@ -1064,7 +1460,7 @@ export class AuctionDurabilityScheduler
|
|||||||
'end',
|
'end',
|
||||||
'return 1',
|
'return 1',
|
||||||
].join('\n'),
|
].join('\n'),
|
||||||
'11',
|
'12',
|
||||||
keys.liveStateKey,
|
keys.liveStateKey,
|
||||||
keys.deadlineQueueKey,
|
keys.deadlineQueueKey,
|
||||||
keys.structureStateKey,
|
keys.structureStateKey,
|
||||||
@@ -1076,6 +1472,7 @@ export class AuctionDurabilityScheduler
|
|||||||
keys.actionRequestResultOrderKey,
|
keys.actionRequestResultOrderKey,
|
||||||
keys.rehydrateLockKey,
|
keys.rehydrateLockKey,
|
||||||
keys.stateTransitionLockKey,
|
keys.stateTransitionLockKey,
|
||||||
|
keys.rejectedBidRequestResultOrderKey,
|
||||||
matchId,
|
matchId,
|
||||||
payload.auctionLifecycleId,
|
payload.auctionLifecycleId,
|
||||||
String(AUCTION_REDIS_COMPLETED_RETAIN_SECONDS),
|
String(AUCTION_REDIS_COMPLETED_RETAIN_SECONDS),
|
||||||
@@ -1159,6 +1556,7 @@ async function readAuctionProjectionIdentityForMutation(
|
|||||||
? (query as { select: (...args: never[]) => unknown }).select({
|
? (query as { select: (...args: never[]) => unknown }).select({
|
||||||
auctionLifecycleId: 1,
|
auctionLifecycleId: 1,
|
||||||
revision: 1,
|
revision: 1,
|
||||||
|
matchSideEffectTransitionId: 1,
|
||||||
} as never)
|
} as never)
|
||||||
: query;
|
: query;
|
||||||
const scoped =
|
const scoped =
|
||||||
@@ -1178,6 +1576,10 @@ async function readAuctionProjectionIdentityForMutation(
|
|||||||
if (!projection || typeof projection !== 'object') return {};
|
if (!projection || typeof projection !== 'object') return {};
|
||||||
const record = projection as Record<string, unknown>;
|
const record = projection as Record<string, unknown>;
|
||||||
return {
|
return {
|
||||||
|
matchSideEffectTransitionId:
|
||||||
|
typeof record.matchSideEffectTransitionId === 'string'
|
||||||
|
? record.matchSideEffectTransitionId
|
||||||
|
: undefined,
|
||||||
auctionLifecycleId:
|
auctionLifecycleId:
|
||||||
typeof record.auctionLifecycleId === 'string'
|
typeof record.auctionLifecycleId === 'string'
|
||||||
? record.auctionLifecycleId
|
? record.auctionLifecycleId
|
||||||
@@ -1200,6 +1602,7 @@ export function buildAuctionProjectionGuardedUpdate(
|
|||||||
},
|
},
|
||||||
update: {
|
update: {
|
||||||
$set: payload.afterAuctionMongoProjection,
|
$set: payload.afterAuctionMongoProjection,
|
||||||
|
$unset: buildAuctionProjectionUnset(payload.afterAuctionMongoProjection),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,4 +24,10 @@ export class AuctionEventBusService {
|
|||||||
?.to(matchId)
|
?.to(matchId)
|
||||||
.emit('state', serializeRealtimeAuction(state));
|
.emit('state', serializeRealtimeAuction(state));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public broadcastReset(matchId: string, auctionLifecycleId: string): void {
|
||||||
|
this.auctionNamespace
|
||||||
|
?.to(matchId)
|
||||||
|
.emit('reset', { matchId, auctionLifecycleId });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { AuctionLifecycleLock } from './auction-lifecycle-lock';
|
||||||
|
|
||||||
|
afterEach(() => jest.useRealTimers());
|
||||||
|
|
||||||
|
it('renews ownership and handles renewal/release failures without unhandled rejection', async () => {
|
||||||
|
jest.useFakeTimers();
|
||||||
|
const sendCommand = jest
|
||||||
|
.fn()
|
||||||
|
.mockRejectedValue(new Error('redis disconnected'));
|
||||||
|
const releaseTokenLock = jest
|
||||||
|
.fn()
|
||||||
|
.mockRejectedValue(new Error('release failed'));
|
||||||
|
const lock = new AuctionLifecycleLock({
|
||||||
|
acquireTokenLock: jest.fn().mockResolvedValue(true),
|
||||||
|
releaseTokenLock,
|
||||||
|
raw: () => ({ sendCommand }),
|
||||||
|
} as never);
|
||||||
|
const result = lock.run('match', async () => {
|
||||||
|
await jest.advanceTimersByTimeAsync(10000);
|
||||||
|
});
|
||||||
|
await expect(result).rejects.toThrow('redis disconnected');
|
||||||
|
expect(releaseTokenLock).toHaveBeenCalledTimes(1);
|
||||||
|
expect(jest.getTimerCount()).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('preserves an operation result if only lock release fails', async () => {
|
||||||
|
const lock = new AuctionLifecycleLock({
|
||||||
|
acquireTokenLock: jest.fn().mockResolvedValue(true),
|
||||||
|
releaseTokenLock: jest.fn().mockRejectedValue(new Error('release failed')),
|
||||||
|
} as never);
|
||||||
|
await expect(lock.run('match', async () => 42)).resolves.toBe(42);
|
||||||
|
});
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import { ConflictException, Logger } from '@nestjs/common';
|
||||||
|
import { randomUUID } from 'crypto';
|
||||||
|
import { AuctionRedisService } from './redis/auction-redis.service';
|
||||||
|
|
||||||
|
export class AuctionLifecycleBusyError extends ConflictException {
|
||||||
|
constructor() {
|
||||||
|
super({
|
||||||
|
code: 'AUCTION_LIFECYCLE_BUSY',
|
||||||
|
message: '다른 경매 작업을 처리 중입니다. 잠시 후 다시 시도해 주세요.',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Serializes startup, cancellation, undo and Match side effects across nodes. */
|
||||||
|
export class AuctionLifecycleLock {
|
||||||
|
private readonly logger = new Logger(AuctionLifecycleLock.name);
|
||||||
|
|
||||||
|
constructor(private readonly redis: AuctionRedisService) {}
|
||||||
|
|
||||||
|
async run<T>(matchId: string, operation: () => Promise<T>): Promise<T> {
|
||||||
|
// Kept outside runtime cleanup: cancelling an auction must not release a
|
||||||
|
// lock still held by its cancellation/recovery operation.
|
||||||
|
const key = `auction:${matchId}:lifecycleMutationLock`;
|
||||||
|
const token = randomUUID();
|
||||||
|
if (!(await this.redis.acquireTokenLock(key, token, 30_000))) {
|
||||||
|
throw new AuctionLifecycleBusyError();
|
||||||
|
}
|
||||||
|
let renewal: Promise<void> | undefined;
|
||||||
|
let ownershipError: Error | undefined;
|
||||||
|
const timer = setInterval(() => {
|
||||||
|
if (renewal) return;
|
||||||
|
renewal = this.redis
|
||||||
|
.raw()
|
||||||
|
.sendCommand<string | null>([
|
||||||
|
'SET',
|
||||||
|
key,
|
||||||
|
token,
|
||||||
|
'IFEQ',
|
||||||
|
token,
|
||||||
|
'PX',
|
||||||
|
'30000',
|
||||||
|
])
|
||||||
|
.then((result) => {
|
||||||
|
if (result !== 'OK')
|
||||||
|
throw new Error('Auction lifecycle lock ownership was lost.');
|
||||||
|
})
|
||||||
|
.catch((error: unknown) => {
|
||||||
|
ownershipError =
|
||||||
|
error instanceof Error ? error : new Error(String(error));
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
renewal = undefined;
|
||||||
|
});
|
||||||
|
}, 10_000);
|
||||||
|
timer.unref?.();
|
||||||
|
try {
|
||||||
|
const result = await operation();
|
||||||
|
clearInterval(timer);
|
||||||
|
await renewal;
|
||||||
|
if (ownershipError) throw ownershipError;
|
||||||
|
return result;
|
||||||
|
} finally {
|
||||||
|
clearInterval(timer);
|
||||||
|
await renewal;
|
||||||
|
await this.redis.releaseTokenLock(key, token).catch((error: unknown) => {
|
||||||
|
this.logger.warn(
|
||||||
|
`Auction lifecycle lock release failed: ${String(error)}`,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
/** Missing optional fields in a complete projection mean deletion, not retention. */
|
||||||
|
export const AUCTION_OPTIONAL_PROJECTION_FIELDS = [
|
||||||
|
'completedAt',
|
||||||
|
'auctionCompletedAtTimestampMS',
|
||||||
|
'currentBidderTeamIndex',
|
||||||
|
'currentHighestBidderTeamIndex',
|
||||||
|
'currentDeadline',
|
||||||
|
'currentBidRoundDeadlineTimestampMS',
|
||||||
|
'currentBidRoundId',
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export function buildAuctionProjectionUnset(
|
||||||
|
projection: Record<string, unknown>,
|
||||||
|
) {
|
||||||
|
return Object.fromEntries(
|
||||||
|
AUCTION_OPTIONAL_PROJECTION_FIELDS.filter(
|
||||||
|
(field) => projection[field] === undefined,
|
||||||
|
).map((field) => [field, '']),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -5,6 +5,20 @@ import {
|
|||||||
} from './auction-rejection';
|
} from './auction-rejection';
|
||||||
|
|
||||||
describe('resolveAuctionRejectionReason', () => {
|
describe('resolveAuctionRejectionReason', () => {
|
||||||
|
it('distinguishes an outdated client from a stale round and does not suggest a state-only resync', () => {
|
||||||
|
const reason = resolveAuctionRejectionReason('BID_CLIENT_UPDATE_REQUIRED');
|
||||||
|
expect(reason).toBe('BID_REJECTED_BECAUSE_CLIENT_UPDATE_REQUIRED');
|
||||||
|
expect(isAuctionResyncRecommended(reason)).toBe(false);
|
||||||
|
});
|
||||||
|
it('reports roster validation failures without recommending a retry', () => {
|
||||||
|
const reason = resolveAuctionRejectionReason(
|
||||||
|
'AUCTION_ROSTER_INVALID',
|
||||||
|
'Auction roster validation failed.',
|
||||||
|
);
|
||||||
|
expect(reason).toBe('AUCTION_TRANSITION_REJECTED_BECAUSE_ROSTER_INVALID');
|
||||||
|
expect(isAuctionResyncRecommended(reason)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
it('maps the internal CONFLICT code to the descriptive transition reason', () => {
|
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,
|
||||||
|
|||||||
@@ -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',
|
||||||
@@ -43,6 +46,8 @@ export const AUCTION_REJECTION_REASON = {
|
|||||||
'AUCTION_TRANSITION_REJECTED_BECAUSE_REQUEST_COORDINATION_RETRYABLE',
|
'AUCTION_TRANSITION_REJECTED_BECAUSE_REQUEST_COORDINATION_RETRYABLE',
|
||||||
|
|
||||||
// === 입찰(bid) ===
|
// === 입찰(bid) ===
|
||||||
|
BID_REJECTED_BECAUSE_CLIENT_UPDATE_REQUIRED:
|
||||||
|
'BID_REJECTED_BECAUSE_CLIENT_UPDATE_REQUIRED',
|
||||||
/** 입찰 라운드가 이미 다음 선수/다음 라운드로 넘어감(내부 `STALE_BID_ROUND`). */
|
/** 입찰 라운드가 이미 다음 선수/다음 라운드로 넘어감(내부 `STALE_BID_ROUND`). */
|
||||||
BID_REJECTED_BECAUSE_BID_ROUND_ALREADY_ADVANCED:
|
BID_REJECTED_BECAUSE_BID_ROUND_ALREADY_ADVANCED:
|
||||||
'BID_REJECTED_BECAUSE_BID_ROUND_ALREADY_ADVANCED',
|
'BID_REJECTED_BECAUSE_BID_ROUND_ALREADY_ADVANCED',
|
||||||
@@ -83,6 +88,10 @@ export type AuctionRejectionReason =
|
|||||||
|
|
||||||
/** 내부 짧은 코드 → 설명적 reason. */
|
/** 내부 짧은 코드 → 설명적 reason. */
|
||||||
const INTERNAL_CODE_TO_REASON: Record<string, AuctionRejectionReason> = {
|
const INTERNAL_CODE_TO_REASON: Record<string, AuctionRejectionReason> = {
|
||||||
|
BID_CLIENT_UPDATE_REQUIRED:
|
||||||
|
AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_CLIENT_UPDATE_REQUIRED,
|
||||||
|
AUCTION_ROSTER_INVALID:
|
||||||
|
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_ROSTER_INVALID,
|
||||||
CONFLICT:
|
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:
|
||||||
|
|||||||
@@ -96,6 +96,7 @@ describe('auction side effect helpers', () => {
|
|||||||
'life-1',
|
'life-1',
|
||||||
'2',
|
'2',
|
||||||
'completed',
|
'completed',
|
||||||
|
'',
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -25,6 +25,7 @@ export interface BuildSideEffectLeaseAcquireUpdateParams {
|
|||||||
|
|
||||||
export interface MatchSideEffectDelta {
|
export interface MatchSideEffectDelta {
|
||||||
auctionLifecycleId: string;
|
auctionLifecycleId: string;
|
||||||
|
auctionStateTransitionId?: string;
|
||||||
currentServerTimestampMS: number;
|
currentServerTimestampMS: number;
|
||||||
matchSideEffectRevision: number;
|
matchSideEffectRevision: number;
|
||||||
matchSideEffectStatus: AuctionMatchSideEffectStatus;
|
matchSideEffectStatus: AuctionMatchSideEffectStatus;
|
||||||
@@ -36,6 +37,7 @@ export class AuctionSideEffectService {
|
|||||||
|
|
||||||
public async mirrorMatchSideEffectStatus(params: {
|
public async mirrorMatchSideEffectStatus(params: {
|
||||||
auctionLifecycleId: string;
|
auctionLifecycleId: string;
|
||||||
|
auctionStateTransitionId?: string;
|
||||||
matchId: string;
|
matchId: string;
|
||||||
matchSideEffectRevision: number;
|
matchSideEffectRevision: number;
|
||||||
matchSideEffectStatus: AuctionMatchSideEffectStatus;
|
matchSideEffectStatus: AuctionMatchSideEffectStatus;
|
||||||
@@ -47,6 +49,8 @@ export class AuctionSideEffectService {
|
|||||||
'EVAL',
|
'EVAL',
|
||||||
[
|
[
|
||||||
"if redis.call('HGET', KEYS[1], 'auctionLifecycleId') ~= ARGV[1] then return 0 end",
|
"if redis.call('HGET', KEYS[1], 'auctionLifecycleId') ~= ARGV[1] then return 0 end",
|
||||||
|
"local generation = redis.call('HGET', KEYS[1], 'matchSideEffectTransitionId')",
|
||||||
|
"if ARGV[4] ~= '' and generation and generation ~= ARGV[4] then return 0 end",
|
||||||
"local currentRevision = tonumber(redis.call('HGET', KEYS[1], 'matchSideEffectRevision') or '-1')",
|
"local currentRevision = tonumber(redis.call('HGET', KEYS[1], 'matchSideEffectRevision') or '-1')",
|
||||||
'local nextRevision = tonumber(ARGV[2])',
|
'local nextRevision = tonumber(ARGV[2])',
|
||||||
'if currentRevision >= nextRevision then return 0 end',
|
'if currentRevision >= nextRevision then return 0 end',
|
||||||
@@ -58,6 +62,7 @@ export class AuctionSideEffectService {
|
|||||||
params.auctionLifecycleId,
|
params.auctionLifecycleId,
|
||||||
String(params.matchSideEffectRevision),
|
String(params.matchSideEffectRevision),
|
||||||
params.matchSideEffectStatus,
|
params.matchSideEffectStatus,
|
||||||
|
params.auctionStateTransitionId ?? '',
|
||||||
]);
|
]);
|
||||||
return Number(result) === 1;
|
return Number(result) === 1;
|
||||||
}
|
}
|
||||||
@@ -104,6 +109,9 @@ export function buildMatchSideEffectDelta(
|
|||||||
): MatchSideEffectDelta {
|
): MatchSideEffectDelta {
|
||||||
return {
|
return {
|
||||||
auctionLifecycleId: params.auctionLifecycleId,
|
auctionLifecycleId: params.auctionLifecycleId,
|
||||||
|
...(params.auctionStateTransitionId
|
||||||
|
? { auctionStateTransitionId: params.auctionStateTransitionId }
|
||||||
|
: {}),
|
||||||
currentServerTimestampMS: params.currentServerTimestampMS,
|
currentServerTimestampMS: params.currentServerTimestampMS,
|
||||||
matchSideEffectRevision: params.matchSideEffectRevision,
|
matchSideEffectRevision: params.matchSideEffectRevision,
|
||||||
matchSideEffectStatus: params.matchSideEffectStatus,
|
matchSideEffectStatus: params.matchSideEffectStatus,
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
Param,
|
Param,
|
||||||
Post,
|
Post,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
|
Query,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
|
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
|
||||||
@@ -19,6 +20,7 @@ import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
|||||||
import type { UserDocument } from '../global/database/schema';
|
import type { UserDocument } from '../global/database/schema';
|
||||||
import { AuctionService } from './auction.service';
|
import { AuctionService } from './auction.service';
|
||||||
import { AuctionGateway } from './auction.gateway';
|
import { AuctionGateway } from './auction.gateway';
|
||||||
|
import { AuctionBidArchiveService } from './auction-bid-archive.service';
|
||||||
import {
|
import {
|
||||||
NextAuctionDto,
|
NextAuctionDto,
|
||||||
OpenBiddingDto,
|
OpenBiddingDto,
|
||||||
@@ -35,6 +37,7 @@ export class AuctionController {
|
|||||||
constructor(
|
constructor(
|
||||||
private readonly auctionService: AuctionService,
|
private readonly auctionService: AuctionService,
|
||||||
private readonly auctionGateway: AuctionGateway,
|
private readonly auctionGateway: AuctionGateway,
|
||||||
|
private readonly auctionBidArchiveService: AuctionBidArchiveService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@Post()
|
@Post()
|
||||||
@@ -77,7 +80,21 @@ export class AuctionController {
|
|||||||
return this.auctionService.getStateByMatchId(matchId);
|
return this.auctionService.getStateByMatchId(matchId);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 공개 — 팀장 2명만 쓸 엔드포인트(트러스트 기반, 10명 동시 관전).
|
// 공개 입찰 기록 조회.
|
||||||
|
@Get('bids/history')
|
||||||
|
@AllowPublicAccess()
|
||||||
|
public async getBidHistory(
|
||||||
|
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||||
|
@Query('afterRevision') afterRevision?: string,
|
||||||
|
@Query('limit') limit?: string,
|
||||||
|
) {
|
||||||
|
return this.auctionBidArchiveService.list(
|
||||||
|
matchId,
|
||||||
|
afterRevision === undefined ? -1 : Number(afterRevision),
|
||||||
|
limit === undefined ? 100 : Number(limit),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@Post('open-bidding')
|
@Post('open-bidding')
|
||||||
@AllowPublicAccess()
|
@AllowPublicAccess()
|
||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
@@ -89,17 +106,24 @@ export class AuctionController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Post('bids')
|
@Post('bids')
|
||||||
@AllowPublicAccess()
|
@Roles('admin', 'owner', 'member')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
public async placeBid(
|
public async placeBid(
|
||||||
|
@CurrentUser() currentUser: UserDocument,
|
||||||
|
@Param('communityId', ParseObjectIdPipe)
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||||
@Body() body: PlaceBidDto,
|
@Body() body: PlaceBidDto,
|
||||||
) {
|
) {
|
||||||
|
this.assertSameCommunity(currentUser, communityId);
|
||||||
return this.auctionService.placeBid({
|
return this.auctionService.placeBid({
|
||||||
matchId,
|
matchId,
|
||||||
|
bidderUserId: currentUser._id,
|
||||||
teamIndex: body.bidderTeamIndex,
|
teamIndex: body.bidderTeamIndex,
|
||||||
amount: body.bidPointAmount,
|
amount: body.bidPointAmount,
|
||||||
bidRequestId: body.bidRequestId,
|
bidRequestId: body.bidRequestId,
|
||||||
|
clientObservedBidRoundId: body.clientObservedBidRoundId,
|
||||||
clientObservedAuctionLifecycleId: body.clientObservedAuctionLifecycleId,
|
clientObservedAuctionLifecycleId: body.clientObservedAuctionLifecycleId,
|
||||||
clientObservedCurrentBidRoundPlayerUserId:
|
clientObservedCurrentBidRoundPlayerUserId:
|
||||||
body.clientObservedCurrentBidRoundPlayerUserId,
|
body.clientObservedCurrentBidRoundPlayerUserId,
|
||||||
@@ -213,7 +237,10 @@ export class AuctionController {
|
|||||||
clientObservedPhase: body.clientObservedPhase,
|
clientObservedPhase: body.clientObservedPhase,
|
||||||
clientObservedRevision: body.clientObservedRevision,
|
clientObservedRevision: body.clientObservedRevision,
|
||||||
});
|
});
|
||||||
this.auctionGateway.broadcastReset(matchId.toString());
|
this.auctionGateway.broadcastReset(
|
||||||
|
matchId.toString(),
|
||||||
|
body.clientObservedAuctionLifecycleId,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private assertSameCommunity(
|
private assertSameCommunity(
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
|
import { ServiceUnavailableException } from '@nestjs/common';
|
||||||
|
|
||||||
jest.mock('../auth/jwt.service', () => ({
|
jest.mock('../auth/jwt.service', () => ({
|
||||||
JwtService: class JwtService {},
|
JwtService: class JwtService {},
|
||||||
@@ -7,6 +8,78 @@ jest.mock('../auth/jwt.service', () => ({
|
|||||||
import { AuctionGateway } from './auction.gateway';
|
import { AuctionGateway } from './auction.gateway';
|
||||||
|
|
||||||
describe('AuctionGateway', () => {
|
describe('AuctionGateway', () => {
|
||||||
|
it('signals pending initial state so the client can retry privately after recovery', async () => {
|
||||||
|
const matchId = new mongoose.Types.ObjectId().toString();
|
||||||
|
const gateway = new AuctionGateway(
|
||||||
|
{
|
||||||
|
getByMatchId: async () => ({}),
|
||||||
|
getStateByMatchId: async () => {
|
||||||
|
throw new ServiceUnavailableException({
|
||||||
|
code: 'AUCTION_STATE_RECOVERING',
|
||||||
|
message: 'recovering',
|
||||||
|
});
|
||||||
|
},
|
||||||
|
} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
);
|
||||||
|
const socket = { data: { matchId }, join: jest.fn(), emit: jest.fn() };
|
||||||
|
await gateway.handleJoin(socket as never, { matchId });
|
||||||
|
expect(socket.emit).toHaveBeenCalledTimes(1);
|
||||||
|
expect(socket.emit).toHaveBeenCalledWith('state-pending', {
|
||||||
|
retryAfterMS: 500,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
it('sends join and resync snapshots only to the requesting socket and coalesces in-flight resyncs', async () => {
|
||||||
|
const matchId = new mongoose.Types.ObjectId().toString();
|
||||||
|
const getStateByMatchId = jest.fn().mockResolvedValue({ revision: 3 });
|
||||||
|
const gateway = new AuctionGateway(
|
||||||
|
{
|
||||||
|
getByMatchId: async () => ({ chatMessages: [] }),
|
||||||
|
getStateByMatchId,
|
||||||
|
} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
);
|
||||||
|
const broadcast = jest.fn();
|
||||||
|
(gateway as unknown as { server: unknown }).server = {
|
||||||
|
to: () => ({ emit: broadcast }),
|
||||||
|
};
|
||||||
|
const socket = { data: { matchId }, join: jest.fn(), emit: jest.fn() };
|
||||||
|
await gateway.handleJoin(socket as never, { matchId });
|
||||||
|
expect(socket.emit).toHaveBeenCalledWith('state', { revision: 3 });
|
||||||
|
expect(broadcast).not.toHaveBeenCalled();
|
||||||
|
let finish!: (value: unknown) => void;
|
||||||
|
getStateByMatchId.mockImplementationOnce(
|
||||||
|
() =>
|
||||||
|
new Promise((resolve) => {
|
||||||
|
finish = resolve;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const ack = jest.fn(),
|
||||||
|
busyAck = jest.fn();
|
||||||
|
const pending = gateway.handleResync(socket as never, {}, ack);
|
||||||
|
await gateway.handleResync(socket as never, {}, busyAck);
|
||||||
|
expect(busyAck).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ code: 'RESYNC_BUSY' }),
|
||||||
|
);
|
||||||
|
finish({ revision: 4 });
|
||||||
|
await pending;
|
||||||
|
expect(ack).toHaveBeenCalledWith({ ok: true, state: { revision: 4 } });
|
||||||
|
expect(getStateByMatchId).toHaveBeenCalledTimes(2);
|
||||||
|
expect(broadcast).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
const bidderUserId = new mongoose.Types.ObjectId();
|
||||||
|
|
||||||
function createGateway(params?: {
|
function createGateway(params?: {
|
||||||
getCurrentRedisTimestampMS?: jest.Mock;
|
getCurrentRedisTimestampMS?: jest.Mock;
|
||||||
placeBidDelta?: jest.Mock;
|
placeBidDelta?: jest.Mock;
|
||||||
@@ -41,6 +114,23 @@ describe('AuctionGateway', () => {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
it('requires an authenticated user before forwarding a bid', async () => {
|
||||||
|
const matchId = new mongoose.Types.ObjectId().toString();
|
||||||
|
const { gateway, auctionService } = createGateway();
|
||||||
|
const ack = jest.fn();
|
||||||
|
|
||||||
|
await gateway.handleBid(
|
||||||
|
{ data: { matchId }, emit: jest.fn() } as never,
|
||||||
|
{ bidderTeamIndex: 1, bidPointAmount: 100 },
|
||||||
|
ack,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(auctionService.placeBidDelta).not.toHaveBeenCalled();
|
||||||
|
expect(ack).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ rejected: true }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it('broadcasts a bid delta and acknowledges the matching bid request', async () => {
|
it('broadcasts a bid delta and acknowledges the matching bid request', async () => {
|
||||||
const matchId = new mongoose.Types.ObjectId().toString();
|
const matchId = new mongoose.Types.ObjectId().toString();
|
||||||
const auctionBidHistoryEntry = {
|
const auctionBidHistoryEntry = {
|
||||||
@@ -62,7 +152,10 @@ describe('AuctionGateway', () => {
|
|||||||
const ack = jest.fn();
|
const ack = jest.fn();
|
||||||
|
|
||||||
await gateway.handleBid(
|
await gateway.handleBid(
|
||||||
{ data: { matchId }, emit: jest.fn() } as never,
|
{
|
||||||
|
data: { matchId, user: { _id: bidderUserId } },
|
||||||
|
emit: jest.fn(),
|
||||||
|
} as never,
|
||||||
{
|
{
|
||||||
bidPointAmount: 120,
|
bidPointAmount: 120,
|
||||||
bidderTeamIndex: 2,
|
bidderTeamIndex: 2,
|
||||||
@@ -76,6 +169,7 @@ describe('AuctionGateway', () => {
|
|||||||
expect(placeBidDelta).toHaveBeenCalledWith({
|
expect(placeBidDelta).toHaveBeenCalledWith({
|
||||||
amount: 120,
|
amount: 120,
|
||||||
bidRequestId: 'bid-1',
|
bidRequestId: 'bid-1',
|
||||||
|
bidderUserId,
|
||||||
clientObservedAuctionLifecycleId: 'life-1',
|
clientObservedAuctionLifecycleId: 'life-1',
|
||||||
clientObservedCurrentBidRoundPlayerUserId: 'player-1',
|
clientObservedCurrentBidRoundPlayerUserId: 'player-1',
|
||||||
matchId: new mongoose.Types.ObjectId(matchId),
|
matchId: new mongoose.Types.ObjectId(matchId),
|
||||||
@@ -129,7 +223,10 @@ describe('AuctionGateway', () => {
|
|||||||
const ack = jest.fn();
|
const ack = jest.fn();
|
||||||
|
|
||||||
await gateway.handleBid(
|
await gateway.handleBid(
|
||||||
{ data: { matchId }, emit: jest.fn() } as never,
|
{
|
||||||
|
data: { matchId, user: { _id: bidderUserId } },
|
||||||
|
emit: jest.fn(),
|
||||||
|
} as never,
|
||||||
{
|
{
|
||||||
bidPointAmount: 50,
|
bidPointAmount: 50,
|
||||||
bidderTeamIndex: 1,
|
bidderTeamIndex: 1,
|
||||||
@@ -176,7 +273,10 @@ describe('AuctionGateway', () => {
|
|||||||
const ack = jest.fn();
|
const ack = jest.fn();
|
||||||
|
|
||||||
await gateway.handleBid(
|
await gateway.handleBid(
|
||||||
{ data: { matchId }, emit: socketEmit } as never,
|
{
|
||||||
|
data: { matchId, user: { _id: bidderUserId } },
|
||||||
|
emit: socketEmit,
|
||||||
|
} as never,
|
||||||
{
|
{
|
||||||
bidPointAmount: 50,
|
bidPointAmount: 50,
|
||||||
bidderTeamIndex: 1,
|
bidderTeamIndex: 1,
|
||||||
@@ -247,7 +347,10 @@ describe('AuctionGateway', () => {
|
|||||||
revision: 3,
|
revision: 3,
|
||||||
});
|
});
|
||||||
const socketEmit = jest.fn();
|
const socketEmit = jest.fn();
|
||||||
const socket = { data: { matchId }, emit: socketEmit };
|
const socket = {
|
||||||
|
data: { matchId, user: { _id: bidderUserId } },
|
||||||
|
emit: socketEmit,
|
||||||
|
};
|
||||||
const { gateway } = createGateway({ placeBidDelta });
|
const { gateway } = createGateway({ placeBidDelta });
|
||||||
const acknowledgements: Array<Record<string, unknown>> = [];
|
const acknowledgements: Array<Record<string, unknown>> = [];
|
||||||
|
|
||||||
@@ -288,7 +391,10 @@ describe('AuctionGateway', () => {
|
|||||||
currentHighestBidPointAmount: 50,
|
currentHighestBidPointAmount: 50,
|
||||||
revision: 3,
|
revision: 3,
|
||||||
});
|
});
|
||||||
const socket = { data: { matchId }, emit: jest.fn() };
|
const socket = {
|
||||||
|
data: { matchId, user: { _id: bidderUserId } },
|
||||||
|
emit: jest.fn(),
|
||||||
|
};
|
||||||
const { gateway } = createGateway({ placeBidDelta });
|
const { gateway } = createGateway({ placeBidDelta });
|
||||||
|
|
||||||
for (let index = 0; index < 8; index += 1) {
|
for (let index = 0; index < 8; index += 1) {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Logger } from '@nestjs/common';
|
import { ForbiddenException, Logger } from '@nestjs/common';
|
||||||
import { randomUUID } from 'crypto';
|
import { randomUUID } from 'crypto';
|
||||||
import { performance } from 'perf_hooks';
|
import { performance } from 'perf_hooks';
|
||||||
import {
|
import {
|
||||||
@@ -44,6 +44,7 @@ interface JoinAuctionPayload {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface BidPayload {
|
interface BidPayload {
|
||||||
|
clientObservedBidRoundId?: string;
|
||||||
bidderTeamIndex: number;
|
bidderTeamIndex: number;
|
||||||
bidPointAmount: number;
|
bidPointAmount: number;
|
||||||
bidRequestId?: string;
|
bidRequestId?: string;
|
||||||
@@ -79,10 +80,13 @@ interface BidRateLimitState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface AuctionSocketData {
|
interface AuctionSocketData {
|
||||||
|
auctionResyncAtTimestampMS?: number;
|
||||||
|
auctionResyncInProgress?: boolean;
|
||||||
auctionBidRateLimit?: BidRateLimitState;
|
auctionBidRateLimit?: BidRateLimitState;
|
||||||
identity?: IdentityDocument;
|
identity?: IdentityDocument;
|
||||||
matchId?: string;
|
matchId?: string;
|
||||||
user?: UserDocument;
|
user?: UserDocument;
|
||||||
|
devUser?: UserDocument;
|
||||||
}
|
}
|
||||||
|
|
||||||
type AuctionSocket = Socket<
|
type AuctionSocket = Socket<
|
||||||
@@ -111,6 +115,10 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
private server!: Namespace;
|
private server!: Namespace;
|
||||||
|
|
||||||
private readonly logger = new Logger(AuctionGateway.name);
|
private readonly logger = new Logger(AuctionGateway.name);
|
||||||
|
private readonly socketAuthentication = new WeakMap<
|
||||||
|
AuctionSocket,
|
||||||
|
Promise<void>
|
||||||
|
>();
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly auctionService: AuctionService,
|
private readonly auctionService: AuctionService,
|
||||||
@@ -127,8 +135,10 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async handleConnection(socket: AuctionSocket) {
|
public async handleConnection(socket: AuctionSocket) {
|
||||||
|
const authentication = this.authenticateSocket(socket);
|
||||||
|
this.socketAuthentication.set(socket, authentication);
|
||||||
try {
|
try {
|
||||||
await this.authenticateSocket(socket);
|
await authentication;
|
||||||
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(
|
||||||
@@ -150,11 +160,13 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await socket.join(payload.matchId);
|
|
||||||
socket.data.matchId = payload.matchId;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
socket.data.matchId = undefined;
|
||||||
|
socket.data.user = undefined;
|
||||||
|
await this.socketAuthentication.get(socket);
|
||||||
|
await socket.join(payload.matchId);
|
||||||
await this.resolveSocketUserForMatch(socket, payload.matchId);
|
await this.resolveSocketUserForMatch(socket, payload.matchId);
|
||||||
|
socket.data.matchId = payload.matchId;
|
||||||
const auction = await this.auctionService.getByMatchId(
|
const auction = await this.auctionService.getByMatchId(
|
||||||
new mongoose.Types.ObjectId(payload.matchId),
|
new mongoose.Types.ObjectId(payload.matchId),
|
||||||
);
|
);
|
||||||
@@ -162,9 +174,55 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
new mongoose.Types.ObjectId(payload.matchId),
|
new mongoose.Types.ObjectId(payload.matchId),
|
||||||
);
|
);
|
||||||
this.emitChatHistory(socket, auction);
|
this.emitChatHistory(socket, auction);
|
||||||
this.broadcastState(payload.matchId, auctionState);
|
socket.emit('state', serializeRealtimeAuction(auctionState));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.emitKnownError(socket, error);
|
const rejection = this.resolveErrorPayload(error);
|
||||||
|
if (rejection.code === 'AUCTION_STATE_RECOVERING') {
|
||||||
|
socket.emit('state-pending', { retryAfterMS: 500 });
|
||||||
|
} else {
|
||||||
|
this.emitKnownError(socket, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@SubscribeMessage('resync')
|
||||||
|
public async handleResync(
|
||||||
|
@ConnectedSocket() socket: AuctionSocket,
|
||||||
|
@MessageBody() _payload: unknown,
|
||||||
|
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||||
|
) {
|
||||||
|
const matchId = this.requireJoinedMatchId(socket);
|
||||||
|
if (!matchId) {
|
||||||
|
ack?.({ ok: false, code: 'JOIN_REQUIRED' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const now = Date.now();
|
||||||
|
const retryAfterMS =
|
||||||
|
500 - (now - (socket.data.auctionResyncAtTimestampMS ?? 0));
|
||||||
|
if (socket.data.auctionResyncInProgress || retryAfterMS > 0) {
|
||||||
|
ack?.({
|
||||||
|
ok: false,
|
||||||
|
code: 'RESYNC_BUSY',
|
||||||
|
retryAfterMS: Math.max(500, retryAfterMS),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
socket.data.auctionResyncInProgress = true;
|
||||||
|
socket.data.auctionResyncAtTimestampMS = now;
|
||||||
|
try {
|
||||||
|
const state = await this.auctionService.getStateByMatchId(
|
||||||
|
new mongoose.Types.ObjectId(matchId),
|
||||||
|
);
|
||||||
|
// Only the requesting socket receives the full snapshot.
|
||||||
|
ack?.({ ok: true, state: serializeRealtimeAuction(state) });
|
||||||
|
} catch (error) {
|
||||||
|
ack?.({
|
||||||
|
...this.resolveErrorPayload(error),
|
||||||
|
ok: false,
|
||||||
|
retryAfterMS: 500,
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
socket.data.auctionResyncInProgress = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -191,11 +249,18 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
const bidderUserId = this.resolveSocketUserId(socket);
|
||||||
|
if (!bidderUserId)
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'팀장 계정으로 로그인해야 입찰할 수 있습니다.',
|
||||||
|
);
|
||||||
const bidResult = await this.auctionService.placeBidDelta({
|
const bidResult = await this.auctionService.placeBidDelta({
|
||||||
matchId: new mongoose.Types.ObjectId(matchId),
|
matchId: new mongoose.Types.ObjectId(matchId),
|
||||||
teamIndex: payload.bidderTeamIndex,
|
teamIndex: payload.bidderTeamIndex,
|
||||||
amount: payload.bidPointAmount,
|
amount: payload.bidPointAmount,
|
||||||
bidRequestId,
|
bidRequestId,
|
||||||
|
bidderUserId,
|
||||||
|
clientObservedBidRoundId: payload.clientObservedBidRoundId,
|
||||||
clientObservedAuctionLifecycleId:
|
clientObservedAuctionLifecycleId:
|
||||||
payload.clientObservedAuctionLifecycleId,
|
payload.clientObservedAuctionLifecycleId,
|
||||||
clientObservedCurrentBidRoundPlayerUserId:
|
clientObservedCurrentBidRoundPlayerUserId:
|
||||||
@@ -523,14 +588,13 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
this.readHandshakeUserId(socket),
|
this.readHandshakeUserId(socket),
|
||||||
);
|
);
|
||||||
if (fallback) {
|
if (fallback) {
|
||||||
socket.data.user = fallback.user;
|
socket.data.devUser = fallback.user;
|
||||||
socket.data.identity = fallback.identity;
|
socket.data.identity = fallback.identity;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const token = this.readHandshakeToken(socket);
|
const token = this.readHandshakeToken(socket);
|
||||||
if (!token) {
|
if (!token) {
|
||||||
// 임시 운영용: 경매 진행 중에는 로그인 없이도 관전/팀장 모드 선택/입찰을 허용한다.
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -572,14 +636,22 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
socket: AuctionSocket,
|
socket: AuctionSocket,
|
||||||
matchId: string,
|
matchId: string,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
if (socket.data.user || !socket.data.identity) return;
|
const devUser = socket.data.devUser;
|
||||||
const identity = socket.data.identity;
|
const identity = socket.data.identity;
|
||||||
|
if (!devUser && !identity) return;
|
||||||
|
|
||||||
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({
|
||||||
communityId: 1,
|
communityId: 1,
|
||||||
});
|
});
|
||||||
if (!match) return;
|
if (!match) return;
|
||||||
|
if (devUser) {
|
||||||
|
socket.data.user = devUser.communityId.equals(match.communityId)
|
||||||
|
? devUser
|
||||||
|
: undefined;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!identity) return;
|
||||||
|
|
||||||
const UserModel = await this.connectionService.getModel('user');
|
const UserModel = await this.connectionService.getModel('user');
|
||||||
const user = await UserModel.findOne({
|
const user = await UserModel.findOne({
|
||||||
@@ -609,8 +681,11 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
this.server.to(matchId).emit('bid', delta);
|
this.server.to(matchId).emit('bid', delta);
|
||||||
}
|
}
|
||||||
|
|
||||||
public broadcastReset(matchId: string) {
|
public broadcastReset(matchId: string, auctionLifecycleId?: string) {
|
||||||
this.server.to(matchId).emit('reset', { matchId });
|
this.server.to(matchId).emit('reset', {
|
||||||
|
matchId,
|
||||||
|
...(auctionLifecycleId ? { auctionLifecycleId } : {}),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public broadcastMatchSideEffect(
|
public broadcastMatchSideEffect(
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { AuctionEventBusService } from './auction-event-bus.service';
|
|||||||
import { AuctionRedisModule } from './redis/auction-redis.module';
|
import { AuctionRedisModule } from './redis/auction-redis.module';
|
||||||
import { AuctionSideEffectService } from './auction-side-effect.service';
|
import { AuctionSideEffectService } from './auction-side-effect.service';
|
||||||
import { AuctionService } from './auction.service';
|
import { AuctionService } from './auction.service';
|
||||||
|
import { AuctionBidArchiveService } from './auction-bid-archive.service';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -21,6 +22,7 @@ import { AuctionService } from './auction.service';
|
|||||||
controllers: [AuctionController],
|
controllers: [AuctionController],
|
||||||
providers: [
|
providers: [
|
||||||
AuctionService,
|
AuctionService,
|
||||||
|
AuctionBidArchiveService,
|
||||||
AuctionGateway,
|
AuctionGateway,
|
||||||
AuctionEventBusService,
|
AuctionEventBusService,
|
||||||
AuctionDeadlineScheduler,
|
AuctionDeadlineScheduler,
|
||||||
|
|||||||
@@ -45,6 +45,10 @@ describe('AuctionService', () => {
|
|||||||
const allModels = {
|
const allModels = {
|
||||||
auctionHistory: auctionHistoryModel,
|
auctionHistory: auctionHistoryModel,
|
||||||
...models,
|
...models,
|
||||||
|
auction: {
|
||||||
|
updateOne: jest.fn().mockResolvedValue({ matchedCount: 1 }),
|
||||||
|
...((models.auction as object) ?? {}),
|
||||||
|
},
|
||||||
};
|
};
|
||||||
const connectionService = {
|
const connectionService = {
|
||||||
getModel: jest.fn((name: string) => allModels[name]),
|
getModel: jest.fn((name: string) => allModels[name]),
|
||||||
@@ -697,7 +701,7 @@ describe('AuctionService', () => {
|
|||||||
expect(auctionRedisService.raw().sendCommand).toHaveBeenCalledWith([
|
expect(auctionRedisService.raw().sendCommand).toHaveBeenCalledWith([
|
||||||
'EVAL',
|
'EVAL',
|
||||||
expect.stringContaining('currentAuctionLifecycleId'),
|
expect.stringContaining('currentAuctionLifecycleId'),
|
||||||
'11',
|
'12',
|
||||||
`auction:${matchId.toString()}:liveAuctionState`,
|
`auction:${matchId.toString()}:liveAuctionState`,
|
||||||
'auction:bidRoundDeadlineQueue',
|
'auction:bidRoundDeadlineQueue',
|
||||||
`auction:${matchId.toString()}:auctionStructureState`,
|
`auction:${matchId.toString()}:auctionStructureState`,
|
||||||
@@ -709,6 +713,7 @@ describe('AuctionService', () => {
|
|||||||
`auction:${matchId.toString()}:auctionActionRequestResultOrder`,
|
`auction:${matchId.toString()}:auctionActionRequestResultOrder`,
|
||||||
`auction:${matchId.toString()}:rehydrateLock`,
|
`auction:${matchId.toString()}:rehydrateLock`,
|
||||||
`auction:${matchId.toString()}:auctionStateTransitionLock`,
|
`auction:${matchId.toString()}:auctionStateTransitionLock`,
|
||||||
|
`auction:${matchId.toString()}:rejectedBidRequestResultOrder`,
|
||||||
matchId.toString(),
|
matchId.toString(),
|
||||||
'old-life-1',
|
'old-life-1',
|
||||||
]);
|
]);
|
||||||
@@ -909,9 +914,9 @@ describe('AuctionService', () => {
|
|||||||
shouldForceAuctionStateResync: true,
|
shouldForceAuctionStateResync: true,
|
||||||
});
|
});
|
||||||
expect(auctionRedisService.acquireTokenLock).toHaveBeenCalledWith(
|
expect(auctionRedisService.acquireTokenLock).toHaveBeenCalledWith(
|
||||||
`auction:${matchId.toString()}:rehydrateLock`,
|
`auction:${matchId.toString()}:lifecycleMutationLock`,
|
||||||
expect.any(String),
|
expect.any(String),
|
||||||
5000,
|
30000,
|
||||||
);
|
);
|
||||||
expect(auctionRedisCommandService.hydrateState).toHaveBeenCalledWith(
|
expect(auctionRedisCommandService.hydrateState).toHaveBeenCalledWith(
|
||||||
matchId.toString(),
|
matchId.toString(),
|
||||||
@@ -1365,6 +1370,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();
|
||||||
@@ -1842,7 +2108,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,
|
||||||
@@ -2136,7 +2402,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([
|
||||||
@@ -2360,8 +2626,14 @@ describe('AuctionService', () => {
|
|||||||
auctionRedisCommandService.reserveActionRequest,
|
auctionRedisCommandService.reserveActionRequest,
|
||||||
).not.toHaveBeenCalled();
|
).not.toHaveBeenCalled();
|
||||||
expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled();
|
expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled();
|
||||||
expect(tournamentCodeService.releaseFromMatch).toHaveBeenCalledWith(match);
|
expect(tournamentCodeService.releaseFromMatch).toHaveBeenCalledWith(
|
||||||
expect(tournamentResultService.cancelPolling).toHaveBeenCalledWith(match);
|
match,
|
||||||
|
session,
|
||||||
|
);
|
||||||
|
expect(tournamentResultService.cancelPolling).toHaveBeenCalledWith(
|
||||||
|
match,
|
||||||
|
session,
|
||||||
|
);
|
||||||
expect(match).toMatchObject({
|
expect(match).toMatchObject({
|
||||||
gameSchedule: [],
|
gameSchedule: [],
|
||||||
result: undefined,
|
result: undefined,
|
||||||
@@ -2381,13 +2653,12 @@ describe('AuctionService', () => {
|
|||||||
auctionId,
|
auctionId,
|
||||||
});
|
});
|
||||||
expect(auction.deleteOne).toHaveBeenCalledWith({ session });
|
expect(auction.deleteOne).toHaveBeenCalledWith({ session });
|
||||||
expect(redisClient.sendCommand).toHaveBeenCalledWith(
|
expect(redisClient.sendCommand).not.toHaveBeenCalled();
|
||||||
expect.arrayContaining([
|
expect(match).toMatchObject({
|
||||||
'auction:bidRoundDeadlineQueue',
|
lastCancelledAuctionLifecycleId: 'life-1',
|
||||||
matchId.toString(),
|
auctionCancellationCleanupPending: true,
|
||||||
'life-1',
|
auctionCancellationCleanupRetryAt: expect.any(Date),
|
||||||
]),
|
});
|
||||||
);
|
|
||||||
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
|
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -2471,8 +2742,14 @@ describe('AuctionService', () => {
|
|||||||
service.undoTo({ matchId, communityId, sequence: 3 }),
|
service.undoTo({ matchId, communityId, sequence: 3 }),
|
||||||
).resolves.toBe(restored);
|
).resolves.toBe(restored);
|
||||||
|
|
||||||
expect(tournamentCodeService.releaseFromMatch).toHaveBeenCalledWith(match);
|
expect(tournamentCodeService.releaseFromMatch).toHaveBeenCalledWith(
|
||||||
expect(tournamentResultService.cancelPolling).toHaveBeenCalledWith(match);
|
match,
|
||||||
|
session,
|
||||||
|
);
|
||||||
|
expect(tournamentResultService.cancelPolling).toHaveBeenCalledWith(
|
||||||
|
match,
|
||||||
|
session,
|
||||||
|
);
|
||||||
expect(match.status).toBe('team-built');
|
expect(match.status).toBe('team-built');
|
||||||
expect(match.result).toBeUndefined();
|
expect(match.result).toBeUndefined();
|
||||||
expect(auctionReplaceOne).toHaveBeenCalledWith(
|
expect(auctionReplaceOne).toHaveBeenCalledWith(
|
||||||
|
|||||||
@@ -1,12 +1,21 @@
|
|||||||
import {
|
import {
|
||||||
BadRequestException,
|
BadRequestException,
|
||||||
|
ForbiddenException,
|
||||||
ConflictException,
|
ConflictException,
|
||||||
Injectable,
|
Injectable,
|
||||||
InternalServerErrorException,
|
InternalServerErrorException,
|
||||||
Logger,
|
Logger,
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
|
ServiceUnavailableException,
|
||||||
|
Optional,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { randomUUID } from 'crypto';
|
import { randomUUID } from 'crypto';
|
||||||
|
import {
|
||||||
|
AuctionLifecycleLock,
|
||||||
|
AuctionLifecycleBusyError,
|
||||||
|
} from './auction-lifecycle-lock';
|
||||||
|
import { AUCTION_OPTIONAL_PROJECTION_FIELDS } from './auction-projection';
|
||||||
|
import { AuctionEventBusService } from './auction-event-bus.service';
|
||||||
import { performance } from 'perf_hooks';
|
import { performance } from 'perf_hooks';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
@@ -39,6 +48,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] 경매 "중복 멤버" 조사용 임시 계측. 조사 종료 후 제거 대상.
|
||||||
@@ -57,8 +67,6 @@ const AUCTION_BID_REQUEST_REPLAY_WINDOW_MS = 5 * 60 * 1000;
|
|||||||
const AUCTION_MAX_STORED_ACTION_REQUEST_RESULT_COUNT = 500;
|
const AUCTION_MAX_STORED_ACTION_REQUEST_RESULT_COUNT = 500;
|
||||||
const AUCTION_ACTION_REQUEST_REPLAY_WINDOW_MS = 5 * 60 * 1000;
|
const AUCTION_ACTION_REQUEST_REPLAY_WINDOW_MS = 5 * 60 * 1000;
|
||||||
const AUCTION_ACTION_REQUEST_LEASE_DURATION_MS = 15 * 1000;
|
const AUCTION_ACTION_REQUEST_LEASE_DURATION_MS = 15 * 1000;
|
||||||
const AUCTION_REHYDRATE_LOCK_TTL_MS = 5 * 1000;
|
|
||||||
const AUCTION_REHYDRATE_LOCK_WAIT_MS = 50;
|
|
||||||
const AUCTION_HISTORY_LIST_LIMIT = 100;
|
const AUCTION_HISTORY_LIST_LIMIT = 100;
|
||||||
const AUCTION_HISTORY_LIST_CACHE_TTL_MS = 2 * 1000;
|
const AUCTION_HISTORY_LIST_CACHE_TTL_MS = 2 * 1000;
|
||||||
const AUCTION_HISTORY_LIST_CACHE_MAX_ENTRIES = 256;
|
const AUCTION_HISTORY_LIST_CACHE_MAX_ENTRIES = 256;
|
||||||
@@ -81,6 +89,7 @@ interface StartAuctionParams {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface PlaceBidParams {
|
interface PlaceBidParams {
|
||||||
|
clientObservedBidRoundId?: string;
|
||||||
matchId: mongoose.Types.ObjectId;
|
matchId: mongoose.Types.ObjectId;
|
||||||
teamIndex: number;
|
teamIndex: number;
|
||||||
amount: number;
|
amount: number;
|
||||||
@@ -159,6 +168,7 @@ interface AuctionHistoryListCacheEntry {
|
|||||||
export type AuctionStateResponse = AuctionDocument | Record<string, unknown>;
|
export type AuctionStateResponse = AuctionDocument | Record<string, unknown>;
|
||||||
|
|
||||||
export interface AuctionBidDeltaResponse {
|
export interface AuctionBidDeltaResponse {
|
||||||
|
currentBidRoundId?: string;
|
||||||
auctionBidHistoryEntry: Record<string, unknown>;
|
auctionBidHistoryEntry: Record<string, unknown>;
|
||||||
auctionLifecycleId?: string;
|
auctionLifecycleId?: string;
|
||||||
bidServerTiming?: AuctionBidServerTiming;
|
bidServerTiming?: AuctionBidServerTiming;
|
||||||
@@ -211,9 +221,20 @@ export class AuctionService {
|
|||||||
private readonly auctionRedisService: AuctionRedisService,
|
private readonly auctionRedisService: AuctionRedisService,
|
||||||
private readonly auctionRedisCommandService: AuctionRedisCommandService,
|
private readonly auctionRedisCommandService: AuctionRedisCommandService,
|
||||||
private readonly auctionRedisStateReaderService: AuctionRedisStateReaderService,
|
private readonly auctionRedisStateReaderService: AuctionRedisStateReaderService,
|
||||||
|
@Optional()
|
||||||
|
private readonly auctionEventBusService?: AuctionEventBusService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public async start(params: StartAuctionParams): Promise<AuctionDocument> {
|
public async start(params: StartAuctionParams): Promise<AuctionDocument> {
|
||||||
|
return new AuctionLifecycleLock(this.auctionRedisService).run(
|
||||||
|
params.matchId.toString(),
|
||||||
|
() => this.startLocked(params),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async startLocked(
|
||||||
|
params: StartAuctionParams,
|
||||||
|
): Promise<AuctionDocument> {
|
||||||
const MatchModel = await this.connectionService.getModel('match');
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
const UserModel = await this.connectionService.getModel('user');
|
const UserModel = await this.connectionService.getModel('user');
|
||||||
const AuctionModel = await this.connectionService.getModel('auction');
|
const AuctionModel = await this.connectionService.getModel('auction');
|
||||||
@@ -230,7 +251,7 @@ export class AuctionService {
|
|||||||
const existing = await AuctionModel.findOne({ matchId: params.matchId });
|
const existing = await AuctionModel.findOne({ matchId: params.matchId });
|
||||||
if (existing) {
|
if (existing) {
|
||||||
if (existing.startAuctionRequestId === params.startAuctionRequestId) {
|
if (existing.startAuctionRequestId === params.startAuctionRequestId) {
|
||||||
return existing;
|
return this.finishAuctionStartup(existing, match);
|
||||||
}
|
}
|
||||||
if (this.isRestartableResetRedisAuction(existing)) {
|
if (this.isRestartableResetRedisAuction(existing)) {
|
||||||
await this.clearRedisAuctionRuntimeForLifecycle(
|
await this.clearRedisAuctionRuntimeForLifecycle(
|
||||||
@@ -248,6 +269,19 @@ export class AuctionService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// No Mongo auction owns this match. Remove runtime left by an interrupted
|
||||||
|
// cancellation before creating a new lifecycle (under the lifecycle lock).
|
||||||
|
const orphanedRuntime =
|
||||||
|
await this.auctionRedisStateReaderService.readLiveStateIdentity(
|
||||||
|
params.matchId.toString(),
|
||||||
|
);
|
||||||
|
if (orphanedRuntime?.auctionLifecycleId) {
|
||||||
|
await this.clearRedisAuctionRuntimeForLifecycle(
|
||||||
|
params.matchId.toString(),
|
||||||
|
orphanedRuntime.auctionLifecycleId,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const activeParticipants = this.applyAuctionCut(match);
|
const activeParticipants = this.applyAuctionCut(match);
|
||||||
const desiredAuctionCount = activeParticipants.length;
|
const desiredAuctionCount = activeParticipants.length;
|
||||||
if (desiredAuctionCount < 10) {
|
if (desiredAuctionCount < 10) {
|
||||||
@@ -380,6 +414,7 @@ export class AuctionService {
|
|||||||
auctionStartedByUserId: params.actorUserId,
|
auctionStartedByUserId: params.actorUserId,
|
||||||
matchSideEffectStatus: 'none',
|
matchSideEffectStatus: 'none',
|
||||||
matchSideEffectRevision: 0,
|
matchSideEffectRevision: 0,
|
||||||
|
startupCompleted: false,
|
||||||
teams: legacyTeams,
|
teams: legacyTeams,
|
||||||
order: prioritizedOrder,
|
order: prioritizedOrder,
|
||||||
passedQueue: [],
|
passedQueue: [],
|
||||||
@@ -418,12 +453,12 @@ export class AuctionService {
|
|||||||
matchId: params.matchId,
|
matchId: params.matchId,
|
||||||
});
|
});
|
||||||
if (raceWinner?.startAuctionRequestId === params.startAuctionRequestId) {
|
if (raceWinner?.startAuctionRequestId === params.startAuctionRequestId) {
|
||||||
return raceWinner;
|
return this.finishAuctionStartup(raceWinner, match);
|
||||||
}
|
}
|
||||||
throw new BadRequestException('Auction already exists for this match.');
|
throw new BadRequestException('Auction already exists for this match.');
|
||||||
}
|
}
|
||||||
await this.recordSnapshot(auction, 'start');
|
await this.recordSnapshot(auction, 'start');
|
||||||
await this.auctionRedisCommandService.hydrateState(
|
const hydration = await this.auctionRedisCommandService.hydrateState(
|
||||||
params.matchId.toString(),
|
params.matchId.toString(),
|
||||||
{
|
{
|
||||||
auctionHistorySequence: 1,
|
auctionHistorySequence: 1,
|
||||||
@@ -436,9 +471,18 @@ export class AuctionService {
|
|||||||
structureStateJson,
|
structureStateJson,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
if ('rejected' in hydration)
|
||||||
|
throw new ConflictException(
|
||||||
|
`Auction initialization failed: ${hydration.code}.`,
|
||||||
|
);
|
||||||
|
|
||||||
match.status = 'team-built';
|
match.status = 'team-built';
|
||||||
await match.save();
|
await match.save();
|
||||||
|
auction.startupCompleted = true;
|
||||||
|
await AuctionModel.updateOne(
|
||||||
|
{ _id: auction._id },
|
||||||
|
{ $set: { startupCompleted: true } },
|
||||||
|
);
|
||||||
this.enqueueBackgroundOrderEnrichment({
|
this.enqueueBackgroundOrderEnrichment({
|
||||||
auctionId: auction._id,
|
auctionId: auction._id,
|
||||||
targets: enrichTargets,
|
targets: enrichTargets,
|
||||||
@@ -449,6 +493,61 @@ export class AuctionService {
|
|||||||
return auction;
|
return auction;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async finishAuctionStartup(
|
||||||
|
auction: AuctionDocument,
|
||||||
|
match: MatchDocument,
|
||||||
|
): Promise<AuctionDocument> {
|
||||||
|
// Documents predating the startup marker already completed the old path.
|
||||||
|
if (auction.startupCompleted !== false) return auction;
|
||||||
|
// Retry the original cut; recruiting may have changed since Mongo creation.
|
||||||
|
const roster = new Set([
|
||||||
|
...auction.teams.map((team) => team.captainUserId.toString()),
|
||||||
|
...auction.order.map((player) => player.userId.toString()),
|
||||||
|
]);
|
||||||
|
const participants = new Set(
|
||||||
|
match.participants.map((entry) => entry.userId.toString()),
|
||||||
|
);
|
||||||
|
if ([...roster].some((id) => !participants.has(id))) {
|
||||||
|
throw new ConflictException(
|
||||||
|
'Auction startup roster has changed. Cancel and restart the auction.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const History = await this.connectionService.getModel('auctionHistory');
|
||||||
|
await History.updateOne(
|
||||||
|
{ auctionId: auction._id, sequence: 1 },
|
||||||
|
{
|
||||||
|
$setOnInsert: {
|
||||||
|
auctionId: auction._id,
|
||||||
|
matchId: auction.matchId,
|
||||||
|
sequence: 1,
|
||||||
|
action: 'start',
|
||||||
|
snapshotBefore: this.cloneJson(
|
||||||
|
typeof auction.toObject === 'function'
|
||||||
|
? auction.toObject()
|
||||||
|
: auction,
|
||||||
|
),
|
||||||
|
takenAt: auction.startedAt ?? new Date(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ upsert: true },
|
||||||
|
);
|
||||||
|
await this.hydrateRedisStateFromAuctionDocument(auction);
|
||||||
|
if (match.status === 'recruiting') {
|
||||||
|
match.participants.forEach((participant) => {
|
||||||
|
participant.excluded = !roster.has(participant.userId.toString());
|
||||||
|
});
|
||||||
|
match.status = 'team-built';
|
||||||
|
await match.save();
|
||||||
|
}
|
||||||
|
const AuctionModel = await this.connectionService.getModel('auction');
|
||||||
|
await AuctionModel.updateOne(
|
||||||
|
{ _id: auction._id },
|
||||||
|
{ $set: { startupCompleted: true } },
|
||||||
|
);
|
||||||
|
auction.startupCompleted = true;
|
||||||
|
return auction;
|
||||||
|
}
|
||||||
|
|
||||||
public async getByMatchId(
|
public async getByMatchId(
|
||||||
matchId: mongoose.Types.ObjectId,
|
matchId: mongoose.Types.ObjectId,
|
||||||
): Promise<AuctionDocument> {
|
): Promise<AuctionDocument> {
|
||||||
@@ -461,18 +560,46 @@ export class AuctionService {
|
|||||||
public async getStateByMatchId(
|
public async getStateByMatchId(
|
||||||
matchId: mongoose.Types.ObjectId,
|
matchId: mongoose.Types.ObjectId,
|
||||||
): Promise<AuctionStateResponse> {
|
): Promise<AuctionStateResponse> {
|
||||||
const auction = await this.getByMatchId(matchId);
|
for (let attempt = 0; ; attempt++) {
|
||||||
|
try {
|
||||||
|
return await this.getStateByMatchIdOnce(matchId);
|
||||||
|
} catch (error) {
|
||||||
|
if (!(error instanceof AuctionLifecycleBusyError)) throw error;
|
||||||
|
if (attempt >= 4)
|
||||||
|
throw new ServiceUnavailableException({
|
||||||
|
code: 'AUCTION_STATE_RECOVERING',
|
||||||
|
retryAfterMS: 500,
|
||||||
|
message: '경매 상태를 복구 중입니다. 잠시 후 다시 시도해 주세요.',
|
||||||
|
});
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getStateByMatchIdOnce(
|
||||||
|
matchId: mongoose.Types.ObjectId,
|
||||||
|
): Promise<AuctionStateResponse> {
|
||||||
|
let auction = await this.getByMatchId(matchId);
|
||||||
if (!this.isRedisV1Auction(auction)) return auction;
|
if (!this.isRedisV1Auction(auction)) return auction;
|
||||||
|
|
||||||
|
if (auction.startupCompleted === false) {
|
||||||
|
auction = await new AuctionLifecycleLock(this.auctionRedisService).run(
|
||||||
|
matchId.toString(),
|
||||||
|
async () => {
|
||||||
|
const current = await this.getByMatchId(matchId);
|
||||||
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
|
const match = await MatchModel.findById(matchId);
|
||||||
|
if (!match) throw new NotFoundException('Match not found.');
|
||||||
|
return this.finishAuctionStartup(current, match);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const redisState = await this.readRedisAuctionStateOrRehydrate(auction);
|
const redisState = await this.readRedisAuctionStateOrRehydrate(auction);
|
||||||
if (!redisState) return auction;
|
if (!redisState) return auction;
|
||||||
|
|
||||||
const mongoState =
|
|
||||||
typeof auction.toObject === 'function'
|
|
||||||
? auction.toObject({ depopulate: true })
|
|
||||||
: auction;
|
|
||||||
return {
|
return {
|
||||||
...this.cloneJson(mongoState),
|
...this.buildAuctionSnapshotFromRedisState(auction, redisState),
|
||||||
...redisState,
|
...redisState,
|
||||||
chatMessages: auction.chatMessages ?? [],
|
chatMessages: auction.chatMessages ?? [],
|
||||||
};
|
};
|
||||||
@@ -484,12 +611,15 @@ export class AuctionService {
|
|||||||
const matchId = auction.matchId.toString();
|
const matchId = auction.matchId.toString();
|
||||||
const mongoRevision = auction.revision ?? 0;
|
const mongoRevision = auction.revision ?? 0;
|
||||||
const mongoAuctionLifecycleId = auction.auctionLifecycleId;
|
const mongoAuctionLifecycleId = auction.auctionLifecycleId;
|
||||||
if (!mongoAuctionLifecycleId || auction.phase === 'complete') {
|
if (!mongoAuctionLifecycleId) {
|
||||||
return this.auctionRedisStateReaderService.readAuctionStateView(matchId);
|
return this.auctionRedisStateReaderService.readAuctionStateView(matchId);
|
||||||
}
|
}
|
||||||
|
|
||||||
const liveIdentity =
|
const liveIdentity =
|
||||||
await this.auctionRedisStateReaderService.readLiveStateIdentity(matchId);
|
await this.auctionRedisStateReaderService.readLiveStateIdentity(matchId);
|
||||||
|
// Completed runtimes expire after the retention period. Mongo remains the
|
||||||
|
// archive; viewing it must not create an immortal Redis runtime again.
|
||||||
|
if (!liveIdentity && auction.phase === 'complete') return null;
|
||||||
const shouldHydrate = shouldHydrateRedisAuctionState({
|
const shouldHydrate = shouldHydrateRedisAuctionState({
|
||||||
live: liveIdentity,
|
live: liveIdentity,
|
||||||
mongo: {
|
mongo: {
|
||||||
@@ -502,29 +632,32 @@ export class AuctionService {
|
|||||||
return this.auctionRedisStateReaderService.readAuctionStateView(matchId);
|
return this.auctionRedisStateReaderService.readAuctionStateView(matchId);
|
||||||
}
|
}
|
||||||
|
|
||||||
const keys = buildAuctionRedisKeys(matchId);
|
await new AuctionLifecycleLock(this.auctionRedisService).run(
|
||||||
const lockToken = randomUUID();
|
matchId,
|
||||||
const lockAcquired = await this.auctionRedisService.acquireTokenLock(
|
async () => {
|
||||||
keys.rehydrateLockKey,
|
const currentAuction = await this.getByMatchId(auction.matchId);
|
||||||
lockToken,
|
if (currentAuction.auctionLifecycleId !== mongoAuctionLifecycleId) {
|
||||||
AUCTION_REHYDRATE_LOCK_TTL_MS,
|
throw new ConflictException(
|
||||||
|
'Auction lifecycle has changed. Refresh the auction.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const currentLive =
|
||||||
|
await this.auctionRedisStateReaderService.readLiveStateIdentity(
|
||||||
|
matchId,
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
currentLive?.auctionLifecycleId &&
|
||||||
|
currentLive.auctionLifecycleId !== mongoAuctionLifecycleId
|
||||||
|
) {
|
||||||
|
await this.clearRedisAuctionRuntimeForLifecycle(
|
||||||
|
matchId,
|
||||||
|
currentLive.auctionLifecycleId,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await this.hydrateRedisStateFromAuctionDocument(currentAuction);
|
||||||
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
if (lockAcquired) {
|
|
||||||
try {
|
|
||||||
await this.hydrateRedisStateFromAuctionDocument(auction);
|
|
||||||
} finally {
|
|
||||||
await this.auctionRedisService.releaseTokenLock(
|
|
||||||
keys.rehydrateLockKey,
|
|
||||||
lockToken,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
await new Promise((resolve) =>
|
|
||||||
setTimeout(resolve, AUCTION_REHYDRATE_LOCK_WAIT_MS),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.auctionRedisStateReaderService.readAuctionStateView(matchId, {
|
return this.auctionRedisStateReaderService.readAuctionStateView(matchId, {
|
||||||
shouldForceAuctionStateResync: true,
|
shouldForceAuctionStateResync: true,
|
||||||
});
|
});
|
||||||
@@ -663,6 +796,10 @@ export class AuctionService {
|
|||||||
}
|
}
|
||||||
const team = this.findAuctionTeamByIndex(auction, params.teamIndex);
|
const team = this.findAuctionTeamByIndex(auction, params.teamIndex);
|
||||||
if (!team) throw new BadRequestException('Unknown team.');
|
if (!team) throw new BadRequestException('Unknown team.');
|
||||||
|
this.assertBidderIsCaptain(
|
||||||
|
params.bidderUserId,
|
||||||
|
team.captainUserId.toString(),
|
||||||
|
);
|
||||||
if (params.amount <= auction.currentBid) {
|
if (params.amount <= auction.currentBid) {
|
||||||
throw new BadRequestException('Bid must exceed current bid.');
|
throw new BadRequestException('Bid must exceed current bid.');
|
||||||
}
|
}
|
||||||
@@ -675,8 +812,6 @@ export class AuctionService {
|
|||||||
'Bid must reserve minimum points for remaining slots.',
|
'Bid must reserve minimum points for remaining slots.',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
// 임시 운영용: 클라이언트에서 선택한 팀장 모드를 신뢰하고 실제 로그인 사용자 검증은 건너뛴다.
|
|
||||||
|
|
||||||
await this.recordSnapshot(auction, 'bid', params.bidderUserId);
|
await this.recordSnapshot(auction, 'bid', params.bidderUserId);
|
||||||
auction.currentBid = params.amount;
|
auction.currentBid = params.amount;
|
||||||
auction.currentBidderTeamIndex = params.teamIndex;
|
auction.currentBidderTeamIndex = params.teamIndex;
|
||||||
@@ -797,6 +932,10 @@ export class AuctionService {
|
|||||||
if (!bidContext.bidderTeamCaptainUserId) {
|
if (!bidContext.bidderTeamCaptainUserId) {
|
||||||
throw new BadRequestException('Unknown team.');
|
throw new BadRequestException('Unknown team.');
|
||||||
}
|
}
|
||||||
|
this.assertBidderIsCaptain(
|
||||||
|
params.bidderUserId,
|
||||||
|
bidContext.bidderTeamCaptainUserId,
|
||||||
|
);
|
||||||
|
|
||||||
const auctionLifecycleId =
|
const auctionLifecycleId =
|
||||||
params.clientObservedAuctionLifecycleId ?? bidContext.auctionLifecycleId;
|
params.clientObservedAuctionLifecycleId ?? bidContext.auctionLifecycleId;
|
||||||
@@ -813,6 +952,7 @@ export class AuctionService {
|
|||||||
bidderTeamIndex: params.teamIndex,
|
bidderTeamIndex: params.teamIndex,
|
||||||
bidderUserId: bidContext.bidderTeamCaptainUserId,
|
bidderUserId: bidContext.bidderTeamCaptainUserId,
|
||||||
bidRequestId: params.bidRequestId ?? randomUUID(),
|
bidRequestId: params.bidRequestId ?? randomUUID(),
|
||||||
|
clientObservedBidRoundId: params.clientObservedBidRoundId,
|
||||||
clientObservedAuctionLifecycleId: auctionLifecycleId,
|
clientObservedAuctionLifecycleId: auctionLifecycleId,
|
||||||
clientObservedCurrentBidRoundPlayerUserId: currentBidRoundPlayerUserId,
|
clientObservedCurrentBidRoundPlayerUserId: currentBidRoundPlayerUserId,
|
||||||
matchId,
|
matchId,
|
||||||
@@ -872,6 +1012,10 @@ export class AuctionService {
|
|||||||
(entry) => Number(entry.teamIndex) === params.teamIndex,
|
(entry) => Number(entry.teamIndex) === params.teamIndex,
|
||||||
);
|
);
|
||||||
if (!team) throw new BadRequestException('Unknown team.');
|
if (!team) throw new BadRequestException('Unknown team.');
|
||||||
|
this.assertBidderIsCaptain(
|
||||||
|
params.bidderUserId,
|
||||||
|
this.stringFromState(team.captainUserId),
|
||||||
|
);
|
||||||
|
|
||||||
const auctionLifecycleId =
|
const auctionLifecycleId =
|
||||||
params.clientObservedAuctionLifecycleId ??
|
params.clientObservedAuctionLifecycleId ??
|
||||||
@@ -889,6 +1033,7 @@ export class AuctionService {
|
|||||||
bidderTeamIndex: params.teamIndex,
|
bidderTeamIndex: params.teamIndex,
|
||||||
bidderUserId: this.stringFromState(team.captainUserId),
|
bidderUserId: this.stringFromState(team.captainUserId),
|
||||||
bidRequestId: params.bidRequestId ?? randomUUID(),
|
bidRequestId: params.bidRequestId ?? randomUUID(),
|
||||||
|
clientObservedBidRoundId: params.clientObservedBidRoundId,
|
||||||
clientObservedAuctionLifecycleId: auctionLifecycleId,
|
clientObservedAuctionLifecycleId: auctionLifecycleId,
|
||||||
clientObservedCurrentBidRoundPlayerUserId: currentBidRoundPlayerUserId,
|
clientObservedCurrentBidRoundPlayerUserId: currentBidRoundPlayerUserId,
|
||||||
matchId,
|
matchId,
|
||||||
@@ -922,6 +1067,10 @@ export class AuctionService {
|
|||||||
): AuctionBidDeltaResponse {
|
): AuctionBidDeltaResponse {
|
||||||
return {
|
return {
|
||||||
auctionBidHistoryEntry: result.auctionBidHistoryEntry,
|
auctionBidHistoryEntry: result.auctionBidHistoryEntry,
|
||||||
|
currentBidRoundId:
|
||||||
|
typeof result.auctionBidHistoryEntry.bidRoundId === 'string'
|
||||||
|
? result.auctionBidHistoryEntry.bidRoundId
|
||||||
|
: undefined,
|
||||||
auctionLifecycleId: this.stringFromState(state.auctionLifecycleId),
|
auctionLifecycleId: this.stringFromState(state.auctionLifecycleId),
|
||||||
bidRequestId: result.bidRequestId,
|
bidRequestId: result.bidRequestId,
|
||||||
currentBidRoundDeadlineTimestampMS:
|
currentBidRoundDeadlineTimestampMS:
|
||||||
@@ -1193,11 +1342,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 +1363,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 +1481,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) {
|
||||||
@@ -1408,6 +1556,34 @@ export class AuctionService {
|
|||||||
matchId: mongoose.Types.ObjectId;
|
matchId: mongoose.Types.ObjectId;
|
||||||
communityId: mongoose.Types.ObjectId;
|
communityId: mongoose.Types.ObjectId;
|
||||||
}): Promise<void> {
|
}): Promise<void> {
|
||||||
|
let committed = false;
|
||||||
|
try {
|
||||||
|
await new AuctionLifecycleLock(this.auctionRedisService).run(
|
||||||
|
params.matchId.toString(),
|
||||||
|
() =>
|
||||||
|
this.resetLocked(params, () => {
|
||||||
|
committed = true;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
if (!committed) throw error;
|
||||||
|
// A committed cancellation is successful even if lock renewal/teardown
|
||||||
|
// fails afterward. Cleanup is durably queued in the same Mongo transaction.
|
||||||
|
this.logger.warn(
|
||||||
|
`Auction cancellation committed; post-commit coordination failed: ${String(error)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async resetLocked(
|
||||||
|
params: {
|
||||||
|
matchId: mongoose.Types.ObjectId;
|
||||||
|
communityId: mongoose.Types.ObjectId;
|
||||||
|
clientObservedAuctionLifecycleId?: string;
|
||||||
|
clientObservedRevision?: number;
|
||||||
|
},
|
||||||
|
onCommitted: () => void,
|
||||||
|
): Promise<void> {
|
||||||
const AuctionModel = await this.connectionService.getModel('auction');
|
const AuctionModel = await this.connectionService.getModel('auction');
|
||||||
const AuctionHistoryModel =
|
const AuctionHistoryModel =
|
||||||
await this.connectionService.getModel('auctionHistory');
|
await this.connectionService.getModel('auctionHistory');
|
||||||
@@ -1419,70 +1595,155 @@ export class AuctionService {
|
|||||||
if (!session) {
|
if (!session) {
|
||||||
throw new InternalServerErrorException('Failed to start DB session.');
|
throw new InternalServerErrorException('Failed to start DB session.');
|
||||||
}
|
}
|
||||||
let redisRuntimeToClear: {
|
|
||||||
auctionLifecycleId?: string;
|
|
||||||
matchId: string;
|
|
||||||
} | null = null;
|
|
||||||
try {
|
try {
|
||||||
session.startTransaction();
|
session.startTransaction();
|
||||||
const auction = await AuctionModel.findOne({
|
const auction = await AuctionModel.findOne({
|
||||||
matchId: params.matchId,
|
matchId: params.matchId,
|
||||||
}).session(session);
|
}).session(session);
|
||||||
if (!auction) throw new NotFoundException('Auction not found.');
|
if (!auction) {
|
||||||
|
// 이미 커밋된 취소의 재전송이면 성공으로 응답하고 남은 Redis 정리만 재시도한다.
|
||||||
const match = await MatchModel.findById(params.matchId).session(session);
|
const cancelledMatch = params.clientObservedAuctionLifecycleId
|
||||||
if (!match) throw new NotFoundException('Match not found.');
|
? await MatchModel.findById(params.matchId).session(session)
|
||||||
if (!match.communityId.equals(params.communityId)) {
|
: null;
|
||||||
throw new BadRequestException('Community mismatch.');
|
if (
|
||||||
}
|
!cancelledMatch ||
|
||||||
this.assertCompetitionLifecycleMutable(match, 'reset the auction');
|
cancelledMatch.lastCancelledAuctionLifecycleId !==
|
||||||
|
params.clientObservedAuctionLifecycleId
|
||||||
if (this.isRedisV1Auction(auction)) {
|
) {
|
||||||
redisRuntimeToClear = {
|
throw new NotFoundException('Auction not found.');
|
||||||
auctionLifecycleId: auction.auctionLifecycleId,
|
}
|
||||||
matchId: params.matchId.toString(),
|
if (!cancelledMatch.communityId.equals(params.communityId)) {
|
||||||
};
|
throw new BadRequestException('Community mismatch.');
|
||||||
await this.resetMatchAfterAuctionCancellation(match, session);
|
}
|
||||||
await AuctionSideEffectApplicationModel.deleteMany({
|
cancelledMatch.auctionCancellationCleanupPending = true;
|
||||||
auctionId: auction._id,
|
cancelledMatch.auctionCancellationCleanupRetryAt = new Date();
|
||||||
}).session(session);
|
await cancelledMatch.save({ session });
|
||||||
await AuctionHistoryModel.deleteMany({
|
|
||||||
auctionId: auction._id,
|
|
||||||
}).session(session);
|
|
||||||
await auction.deleteOne({ session });
|
|
||||||
} else {
|
} else {
|
||||||
await auction.deleteOne({ session });
|
if (
|
||||||
await AuctionHistoryModel.deleteMany({
|
this.isRedisV1Auction(auction) &&
|
||||||
auctionId: auction._id,
|
(!params.clientObservedAuctionLifecycleId ||
|
||||||
}).session(session);
|
params.clientObservedAuctionLifecycleId !==
|
||||||
if (match.status === 'team-built') {
|
auction.auctionLifecycleId)
|
||||||
await this.tournamentCodeService.releaseFromMatch(match);
|
) {
|
||||||
match.status = 'recruiting';
|
throw new ConflictException(
|
||||||
match.teams = [];
|
'Auction lifecycle has changed. Refresh before cancelling.',
|
||||||
match.tournamentCodeIds = [];
|
);
|
||||||
match.gameSchedule = [];
|
}
|
||||||
match.participants.forEach((participant) => {
|
|
||||||
participant.excluded = false;
|
const match = await MatchModel.findById(params.matchId).session(
|
||||||
});
|
session,
|
||||||
match.teamBuiltAt = undefined;
|
);
|
||||||
match.result = undefined;
|
if (!match) throw new NotFoundException('Match not found.');
|
||||||
match.resultPollState = undefined;
|
if (!match.communityId.equals(params.communityId)) {
|
||||||
await match.save({ session });
|
throw new BadRequestException('Community mismatch.');
|
||||||
|
}
|
||||||
|
this.assertCompetitionLifecycleMutable(match, 'reset the auction');
|
||||||
|
|
||||||
|
if (this.isRedisV1Auction(auction)) {
|
||||||
|
// 같은 트랜잭션에서 취소 완료를 기록해, 재전송을 멱등 처리한다.
|
||||||
|
match.lastCancelledAuctionLifecycleId = auction.auctionLifecycleId;
|
||||||
|
match.auctionCancellationCleanupPending = true;
|
||||||
|
match.auctionCancellationCleanupRetryAt = new Date();
|
||||||
|
match.auctionCancellationCleanupAttempts = 0;
|
||||||
|
match.auctionCancellationCleanupError = undefined;
|
||||||
|
await this.resetMatchAfterAuctionCancellation(match, session);
|
||||||
|
await AuctionSideEffectApplicationModel.deleteMany({
|
||||||
|
auctionId: auction._id,
|
||||||
|
}).session(session);
|
||||||
|
await AuctionHistoryModel.deleteMany({
|
||||||
|
auctionId: auction._id,
|
||||||
|
}).session(session);
|
||||||
|
await auction.deleteOne({ session });
|
||||||
|
} else {
|
||||||
|
await auction.deleteOne({ session });
|
||||||
|
await AuctionHistoryModel.deleteMany({
|
||||||
|
auctionId: auction._id,
|
||||||
|
}).session(session);
|
||||||
|
if (match.status === 'team-built') {
|
||||||
|
await this.tournamentCodeService.releaseFromMatch(match, session);
|
||||||
|
match.status = 'recruiting';
|
||||||
|
match.teams = [];
|
||||||
|
match.tournamentCodeIds = [];
|
||||||
|
match.gameSchedule = [];
|
||||||
|
match.participants.forEach((participant) => {
|
||||||
|
participant.excluded = false;
|
||||||
|
});
|
||||||
|
match.teamBuiltAt = undefined;
|
||||||
|
match.result = undefined;
|
||||||
|
match.resultPollState = undefined;
|
||||||
|
await match.save({ session });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
await session.commitTransaction();
|
await session.commitTransaction();
|
||||||
|
onCommitted();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
await session.abortTransaction();
|
await session.abortTransaction();
|
||||||
throw err;
|
throw err;
|
||||||
} finally {
|
} finally {
|
||||||
await session.endSession();
|
await session.endSession();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (redisRuntimeToClear) {
|
public async retryPendingCancellations(batchLimit = 20): Promise<void> {
|
||||||
await this.clearRedisAuctionRuntimeForLifecycle(
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
redisRuntimeToClear.matchId,
|
const pending = await MatchModel.find({
|
||||||
redisRuntimeToClear.auctionLifecycleId,
|
auctionCancellationCleanupPending: true,
|
||||||
);
|
auctionCancellationCleanupRetryAt: { $lte: new Date() },
|
||||||
|
})
|
||||||
|
.sort({ auctionCancellationCleanupRetryAt: 1 })
|
||||||
|
.limit(batchLimit)
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
for (const match of pending) {
|
||||||
|
const lifecycle = match.lastCancelledAuctionLifecycleId;
|
||||||
|
if (!lifecycle) continue;
|
||||||
|
const filter = {
|
||||||
|
_id: match._id,
|
||||||
|
lastCancelledAuctionLifecycleId: lifecycle,
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
await new AuctionLifecycleLock(this.auctionRedisService).run(
|
||||||
|
match._id.toString(),
|
||||||
|
async () => {
|
||||||
|
// Compare-and-delete in Redis also protects a newly started lifecycle.
|
||||||
|
await this.clearRedisAuctionRuntimeForLifecycle(
|
||||||
|
match._id.toString(),
|
||||||
|
lifecycle,
|
||||||
|
);
|
||||||
|
const AuctionModel =
|
||||||
|
await this.connectionService.getModel('auction');
|
||||||
|
if (!(await AuctionModel.exists({ matchId: match._id }))) {
|
||||||
|
this.auctionEventBusService?.broadcastReset(
|
||||||
|
match._id.toString(),
|
||||||
|
lifecycle,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await MatchModel.updateOne(filter, {
|
||||||
|
$set: { auctionCancellationCleanupPending: false },
|
||||||
|
$unset: {
|
||||||
|
auctionCancellationCleanupRetryAt: '',
|
||||||
|
auctionCancellationCleanupError: '',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
const attempts = (match.auctionCancellationCleanupAttempts ?? 0) + 1;
|
||||||
|
await MatchModel.updateOne(filter, {
|
||||||
|
$set: {
|
||||||
|
auctionCancellationCleanupPending: true,
|
||||||
|
auctionCancellationCleanupRetryAt: new Date(
|
||||||
|
Date.now() + Math.min(60000, 1000 * 2 ** Math.min(attempts, 6)),
|
||||||
|
),
|
||||||
|
auctionCancellationCleanupError: String(error).slice(0, 2000),
|
||||||
|
},
|
||||||
|
$inc: { auctionCancellationCleanupAttempts: 1 },
|
||||||
|
});
|
||||||
|
this.logger.warn(
|
||||||
|
`Auction cancellation cleanup will retry for ${match._id.toString()}: ${String(error)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1497,6 +1758,19 @@ export class AuctionService {
|
|||||||
communityId: mongoose.Types.ObjectId;
|
communityId: mongoose.Types.ObjectId;
|
||||||
sequence: number;
|
sequence: number;
|
||||||
}): Promise<AuctionStateResponse> {
|
}): Promise<AuctionStateResponse> {
|
||||||
|
return new AuctionLifecycleLock(this.auctionRedisService).run(
|
||||||
|
params.matchId.toString(),
|
||||||
|
() => this.undoToLocked(params),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async undoToLocked(
|
||||||
|
params: AuctionStructureActionRequestParams & {
|
||||||
|
matchId: mongoose.Types.ObjectId;
|
||||||
|
communityId: mongoose.Types.ObjectId;
|
||||||
|
sequence: number;
|
||||||
|
},
|
||||||
|
): Promise<AuctionStateResponse> {
|
||||||
const AuctionModel = await this.connectionService.getModel('auction');
|
const AuctionModel = await this.connectionService.getModel('auction');
|
||||||
const AuctionHistoryModel =
|
const AuctionHistoryModel =
|
||||||
await this.connectionService.getModel('auctionHistory');
|
await this.connectionService.getModel('auctionHistory');
|
||||||
@@ -1508,6 +1782,7 @@ export class AuctionService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let redisUndoContext: {
|
let redisUndoContext: {
|
||||||
|
state?: Record<string, unknown>;
|
||||||
actionRequestParams?: AuctionStructureActionRequestParams;
|
actionRequestParams?: AuctionStructureActionRequestParams;
|
||||||
auction: AuctionDocument;
|
auction: AuctionDocument;
|
||||||
snapshot: Record<string, unknown>;
|
snapshot: Record<string, unknown>;
|
||||||
@@ -1543,8 +1818,12 @@ export class AuctionService {
|
|||||||
throw new BadRequestException('Auction history snapshot is invalid.');
|
throw new BadRequestException('Auction history snapshot is invalid.');
|
||||||
}
|
}
|
||||||
|
|
||||||
const undoingCompletedAuction =
|
const liveState = this.isRedisV1Auction(auction)
|
||||||
Boolean(auction.completedAt) && !('completedAt' in snapshot);
|
? await this.requireRedisAuctionState(params.matchId.toString())
|
||||||
|
: undefined;
|
||||||
|
const undoingCompletedAuction = liveState
|
||||||
|
? liveState.phase === 'complete' && snapshot.phase !== 'complete'
|
||||||
|
: Boolean(auction.completedAt) && !('completedAt' in snapshot);
|
||||||
if (undoingCompletedAuction) {
|
if (undoingCompletedAuction) {
|
||||||
this.assertCompetitionLifecycleMutable(
|
this.assertCompetitionLifecycleMutable(
|
||||||
match,
|
match,
|
||||||
@@ -1553,6 +1832,7 @@ export class AuctionService {
|
|||||||
}
|
}
|
||||||
if (this.isRedisV1Auction(auction)) {
|
if (this.isRedisV1Auction(auction)) {
|
||||||
redisUndoContext = {
|
redisUndoContext = {
|
||||||
|
state: liveState,
|
||||||
auction,
|
auction,
|
||||||
actionRequestParams: params,
|
actionRequestParams: params,
|
||||||
snapshot: snapshot,
|
snapshot: snapshot,
|
||||||
@@ -1562,8 +1842,8 @@ export class AuctionService {
|
|||||||
await session.commitTransaction();
|
await session.commitTransaction();
|
||||||
} else {
|
} else {
|
||||||
if (undoingCompletedAuction) {
|
if (undoingCompletedAuction) {
|
||||||
await this.tournamentCodeService.releaseFromMatch(match);
|
await this.tournamentCodeService.releaseFromMatch(match, session);
|
||||||
await this.tournamentResultService.cancelPolling(match);
|
await this.tournamentResultService.cancelPolling(match, session);
|
||||||
match.status = 'team-built';
|
match.status = 'team-built';
|
||||||
match.result = undefined;
|
match.result = undefined;
|
||||||
await match.save({ session });
|
await match.save({ session });
|
||||||
@@ -1758,6 +2038,14 @@ export class AuctionService {
|
|||||||
currentAuctionHistorySequence: auctionHistorySequence,
|
currentAuctionHistorySequence: auctionHistorySequence,
|
||||||
lastAppliedAuctionStateTransitionId: auctionStateTransitionId,
|
lastAppliedAuctionStateTransitionId: auctionStateTransitionId,
|
||||||
revision: expectedRevision + 1,
|
revision: expectedRevision + 1,
|
||||||
|
currentBidRoundId:
|
||||||
|
params.deadline.mode === 'set-relative'
|
||||||
|
? auctionStateTransitionId
|
||||||
|
: params.state.currentBidRoundId,
|
||||||
|
currentBidRoundDeadlineTimestampMS:
|
||||||
|
params.deadline.mode === 'remove'
|
||||||
|
? 0
|
||||||
|
: params.state.currentBidRoundDeadlineTimestampMS,
|
||||||
};
|
};
|
||||||
const afterAuctionMongoProjection =
|
const afterAuctionMongoProjection =
|
||||||
this.buildAuctionMongoProjectionFromState(params.auction, afterState);
|
this.buildAuctionMongoProjectionFromState(params.auction, afterState);
|
||||||
@@ -1769,8 +2057,18 @@ export class AuctionService {
|
|||||||
if (matchSideEffectMutation.type !== 'none') {
|
if (matchSideEffectMutation.type !== 'none') {
|
||||||
afterAuctionMongoProjection.matchSideEffectStatus = 'pending';
|
afterAuctionMongoProjection.matchSideEffectStatus = 'pending';
|
||||||
afterAuctionMongoProjection.matchSideEffectRevision =
|
afterAuctionMongoProjection.matchSideEffectRevision =
|
||||||
(params.auction.matchSideEffectRevision ?? 0) + 1;
|
Math.max(
|
||||||
|
params.auction.matchSideEffectRevision ?? 0,
|
||||||
|
this.numberFromState(params.state.matchSideEffectRevision),
|
||||||
|
) + 1;
|
||||||
afterAuctionMongoProjection.matchSideEffectError = undefined;
|
afterAuctionMongoProjection.matchSideEffectError = undefined;
|
||||||
|
afterAuctionMongoProjection.matchSideEffectTransitionId =
|
||||||
|
auctionStateTransitionId;
|
||||||
|
params.liveStatePatch.matchSideEffectTransitionId =
|
||||||
|
auctionStateTransitionId;
|
||||||
|
params.liveStatePatch.matchSideEffectStatus = 'pending';
|
||||||
|
params.liveStatePatch.matchSideEffectRevision =
|
||||||
|
afterAuctionMongoProjection.matchSideEffectRevision as number;
|
||||||
}
|
}
|
||||||
|
|
||||||
const durabilityPayload = {
|
const durabilityPayload = {
|
||||||
@@ -1925,6 +2223,7 @@ export class AuctionService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async undoRedisAuction(params: {
|
private async undoRedisAuction(params: {
|
||||||
|
state?: Record<string, unknown>;
|
||||||
actionRequestParams?: AuctionStructureActionRequestParams;
|
actionRequestParams?: AuctionStructureActionRequestParams;
|
||||||
auction: AuctionDocument;
|
auction: AuctionDocument;
|
||||||
snapshot: Record<string, unknown>;
|
snapshot: Record<string, unknown>;
|
||||||
@@ -1932,7 +2231,8 @@ export class AuctionService {
|
|||||||
undoingCompletedAuction: boolean;
|
undoingCompletedAuction: boolean;
|
||||||
}): Promise<AuctionStateResponse> {
|
}): Promise<AuctionStateResponse> {
|
||||||
const matchId = params.auction.matchId.toString();
|
const matchId = params.auction.matchId.toString();
|
||||||
const state = await this.requireRedisAuctionState(matchId);
|
const state =
|
||||||
|
params.state ?? (await this.requireRedisAuctionState(matchId));
|
||||||
const actionRequest = await this.reserveRedisStructureActionRequest({
|
const actionRequest = await this.reserveRedisStructureActionRequest({
|
||||||
action: 'undo',
|
action: 'undo',
|
||||||
matchId,
|
matchId,
|
||||||
@@ -2118,8 +2418,11 @@ export class AuctionService {
|
|||||||
typeof auction.toObject === 'function'
|
typeof auction.toObject === 'function'
|
||||||
? (auction.toObject({ depopulate: true }) as Record<string, unknown>)
|
? (auction.toObject({ depopulate: true }) as Record<string, unknown>)
|
||||||
: (auction as unknown as Record<string, unknown>);
|
: (auction as unknown as Record<string, unknown>);
|
||||||
|
const snapshotBase = this.cloneJson(base);
|
||||||
|
for (const field of AUCTION_OPTIONAL_PROJECTION_FIELDS)
|
||||||
|
delete snapshotBase[field];
|
||||||
return {
|
return {
|
||||||
...this.cloneJson(base),
|
...snapshotBase,
|
||||||
...this.buildAuctionMongoProjectionFromState(auction, state),
|
...this.buildAuctionMongoProjectionFromState(auction, state),
|
||||||
_id: auction._id,
|
_id: auction._id,
|
||||||
matchId: auction.matchId,
|
matchId: auction.matchId,
|
||||||
@@ -2145,6 +2448,7 @@ export class AuctionService {
|
|||||||
);
|
);
|
||||||
const phase = this.stringFromState(state.phase) || 'presenting';
|
const phase = this.stringFromState(state.phase) || 'presenting';
|
||||||
const projection: Record<string, unknown> = {
|
const projection: Record<string, unknown> = {
|
||||||
|
currentBidRoundId: state.currentBidRoundId || undefined,
|
||||||
auctionBidHistory,
|
auctionBidHistory,
|
||||||
auctionCompletedAtTimestampMS:
|
auctionCompletedAtTimestampMS:
|
||||||
phase === 'complete' &&
|
phase === 'complete' &&
|
||||||
@@ -2285,6 +2589,8 @@ export class AuctionService {
|
|||||||
|
|
||||||
private formatRedisBidRejectCode(code: string): string {
|
private formatRedisBidRejectCode(code: string): string {
|
||||||
switch (code) {
|
switch (code) {
|
||||||
|
case 'BID_CLIENT_UPDATE_REQUIRED':
|
||||||
|
return '경매 화면이 업데이트되었습니다. 새로고침한 뒤 다시 입찰해 주세요.';
|
||||||
case 'PHASE':
|
case 'PHASE':
|
||||||
return 'Auction is not in bidding phase.';
|
return 'Auction is not in bidding phase.';
|
||||||
case 'STALE_BID_ROUND':
|
case 'STALE_BID_ROUND':
|
||||||
@@ -2515,6 +2821,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 }>,
|
||||||
@@ -2565,6 +2917,15 @@ export class AuctionService {
|
|||||||
return auction.teams.find((team) => team.teamIndex === teamIndex);
|
return auction.teams.find((team) => team.teamIndex === teamIndex);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private assertBidderIsCaptain(
|
||||||
|
bidderUserId: mongoose.Types.ObjectId | undefined,
|
||||||
|
captainUserId: string,
|
||||||
|
) {
|
||||||
|
if (bidderUserId && bidderUserId.toString() !== captainUserId) {
|
||||||
|
throw new ForbiddenException('해당 팀의 팀장만 입찰할 수 있습니다.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private createDeadline(secondsFromNow: number): Date {
|
private createDeadline(secondsFromNow: number): Date {
|
||||||
return new Date(Date.now() + secondsFromNow * 1000);
|
return new Date(Date.now() + secondsFromNow * 1000);
|
||||||
}
|
}
|
||||||
@@ -2655,8 +3016,8 @@ export class AuctionService {
|
|||||||
match: MatchDocument,
|
match: MatchDocument,
|
||||||
session: mongoose.ClientSession,
|
session: mongoose.ClientSession,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
await this.tournamentCodeService.releaseFromMatch(match);
|
await this.tournamentCodeService.releaseFromMatch(match, session);
|
||||||
await this.tournamentResultService.cancelPolling(match);
|
await this.tournamentResultService.cancelPolling(match, session);
|
||||||
match.status = 'recruiting';
|
match.status = 'recruiting';
|
||||||
match.teams = [];
|
match.teams = [];
|
||||||
match.tournamentCodeIds = [];
|
match.tournamentCodeIds = [];
|
||||||
@@ -2671,6 +3032,11 @@ export class AuctionService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private assertLiveAuctionOperationSupported(auction: AuctionDocument): void {
|
private assertLiveAuctionOperationSupported(auction: AuctionDocument): void {
|
||||||
|
if (auction.startupCompleted === false) {
|
||||||
|
throw new ConflictException(
|
||||||
|
'Auction startup is not complete. Refresh to resume initialization.',
|
||||||
|
);
|
||||||
|
}
|
||||||
if (auction.auctionEngineVersion && !this.isRedisV1Auction(auction)) {
|
if (auction.auctionEngineVersion && !this.isRedisV1Auction(auction)) {
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
'Legacy auction live operations are not supported.',
|
'Legacy auction live operations are not supported.',
|
||||||
@@ -2835,7 +3201,7 @@ export class AuctionService {
|
|||||||
auction.topTierThreshold ??
|
auction.topTierThreshold ??
|
||||||
'NONE',
|
'NONE',
|
||||||
};
|
};
|
||||||
await this.auctionRedisCommandService.hydrateState(
|
const hydration = await this.auctionRedisCommandService.hydrateState(
|
||||||
auction.matchId.toString(),
|
auction.matchId.toString(),
|
||||||
{
|
{
|
||||||
auctionHistorySequence: auction.currentAuctionHistorySequence ?? 0,
|
auctionHistorySequence: auction.currentAuctionHistorySequence ?? 0,
|
||||||
@@ -2843,6 +3209,10 @@ export class AuctionService {
|
|||||||
auction.auctionLifecycleId ??
|
auction.auctionLifecycleId ??
|
||||||
`auction:${auction._id.toString()}:rehydrated`,
|
`auction:${auction._id.toString()}:rehydrated`,
|
||||||
liveStatePatch: {
|
liveStatePatch: {
|
||||||
|
currentBidRoundId: auction.phase === 'bidding' ? randomUUID() : '',
|
||||||
|
matchSideEffectTransitionId: auction.matchSideEffectTransitionId,
|
||||||
|
matchSideEffectRevision: auction.matchSideEffectRevision,
|
||||||
|
matchSideEffectStatus: auction.matchSideEffectStatus,
|
||||||
...buildAuctionRedisLiveStatePatchFromStructure(structureInput),
|
...buildAuctionRedisLiveStatePatchFromStructure(structureInput),
|
||||||
currentHighestBidPointAmount:
|
currentHighestBidPointAmount:
|
||||||
auction.currentHighestBidPointAmount ?? auction.currentBid ?? 0,
|
auction.currentHighestBidPointAmount ?? auction.currentBid ?? 0,
|
||||||
@@ -2859,6 +3229,10 @@ export class AuctionService {
|
|||||||
structureStateJson: stringifyAuctionRedisStructureState(structureInput),
|
structureStateJson: stringifyAuctionRedisStructureState(structureInput),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
if ('rejected' in hydration)
|
||||||
|
throw new ConflictException(
|
||||||
|
`Auction recovery failed: ${hydration.code}.`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async clearRedisAuctionRuntimeForLifecycle(
|
private async clearRedisAuctionRuntimeForLifecycle(
|
||||||
@@ -2879,10 +3253,10 @@ export class AuctionService {
|
|||||||
' end',
|
' end',
|
||||||
'end',
|
'end',
|
||||||
"redis.call('ZREM', KEYS[2], ARGV[1])",
|
"redis.call('ZREM', KEYS[2], ARGV[1])",
|
||||||
"redis.call('DEL', KEYS[1], KEYS[3], KEYS[4], KEYS[5], KEYS[6], KEYS[7], KEYS[8], KEYS[9], KEYS[10], KEYS[11])",
|
"redis.call('DEL', KEYS[1], KEYS[3], KEYS[4], KEYS[5], KEYS[6], KEYS[7], KEYS[8], KEYS[9], KEYS[10], KEYS[11], KEYS[12])",
|
||||||
'return 1',
|
'return 1',
|
||||||
].join('\n'),
|
].join('\n'),
|
||||||
'11',
|
'12',
|
||||||
keys.liveStateKey,
|
keys.liveStateKey,
|
||||||
keys.deadlineQueueKey,
|
keys.deadlineQueueKey,
|
||||||
keys.structureStateKey,
|
keys.structureStateKey,
|
||||||
@@ -2894,6 +3268,7 @@ export class AuctionService {
|
|||||||
keys.actionRequestResultOrderKey,
|
keys.actionRequestResultOrderKey,
|
||||||
keys.rehydrateLockKey,
|
keys.rehydrateLockKey,
|
||||||
keys.stateTransitionLockKey,
|
keys.stateTransitionLockKey,
|
||||||
|
keys.rejectedBidRequestResultOrderKey,
|
||||||
matchId,
|
matchId,
|
||||||
expectedAuctionLifecycleId ?? '',
|
expectedAuctionLifecycleId ?? '',
|
||||||
]);
|
]);
|
||||||
@@ -2925,54 +3300,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: {
|
||||||
|
|||||||
@@ -72,6 +72,10 @@ export class StartAuctionDto {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class PlaceBidDto {
|
export class PlaceBidDto {
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
clientObservedBidRoundId?: string;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsUUID()
|
@IsUUID()
|
||||||
bidRequestId?: string;
|
bidRequestId?: string;
|
||||||
|
|||||||
@@ -7,7 +7,13 @@ function makeService(
|
|||||||
) {
|
) {
|
||||||
const sendCommand = jest
|
const sendCommand = jest
|
||||||
.fn()
|
.fn()
|
||||||
.mockImplementation(() => Promise.resolve(commandReplies.shift()));
|
.mockImplementation((command: string[]) =>
|
||||||
|
Promise.resolve(
|
||||||
|
command[0] === 'EVAL'
|
||||||
|
? [currentServerTimestampMS, ...commandReplies.splice(0, 3)]
|
||||||
|
: commandReplies.shift(),
|
||||||
|
),
|
||||||
|
);
|
||||||
const auctionRedisService = {
|
const auctionRedisService = {
|
||||||
getCurrentRedisTimestampMS: jest
|
getCurrentRedisTimestampMS: jest
|
||||||
.fn()
|
.fn()
|
||||||
@@ -125,19 +131,14 @@ describe('AuctionRedisStateReaderService', () => {
|
|||||||
});
|
});
|
||||||
expect(view).not.toHaveProperty('team:2:remainingBidPointAmount');
|
expect(view).not.toHaveProperty('team:2:remainingBidPointAmount');
|
||||||
expect(view).not.toHaveProperty('bidRoundExpiryDecision');
|
expect(view).not.toHaveProperty('bidRoundExpiryDecision');
|
||||||
expect(sendCommand).toHaveBeenNthCalledWith(1, [
|
expect(sendCommand).toHaveBeenCalledTimes(1);
|
||||||
'HGETALL',
|
expect(sendCommand).toHaveBeenCalledWith([
|
||||||
|
'EVAL',
|
||||||
|
expect.stringContaining("redis.call('TIME')"),
|
||||||
|
'3',
|
||||||
'auction:match-1:liveAuctionState',
|
'auction:match-1:liveAuctionState',
|
||||||
]);
|
|
||||||
expect(sendCommand).toHaveBeenNthCalledWith(2, [
|
|
||||||
'GET',
|
|
||||||
'auction:match-1:auctionStructureState',
|
'auction:match-1:auctionStructureState',
|
||||||
]);
|
|
||||||
expect(sendCommand).toHaveBeenNthCalledWith(3, [
|
|
||||||
'LRANGE',
|
|
||||||
'auction:match-1:auctionBidHistory',
|
'auction:match-1:auctionBidHistory',
|
||||||
'0',
|
|
||||||
'-1',
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -111,18 +111,11 @@ export class AuctionRedisStateReaderService {
|
|||||||
liveReply,
|
liveReply,
|
||||||
structureStateJson,
|
structureStateJson,
|
||||||
bidEntries,
|
bidEntries,
|
||||||
] = await Promise.all([
|
] = await this.auctionRedisService
|
||||||
this.auctionRedisService.getCurrentRedisTimestampMS(),
|
.raw()
|
||||||
this.auctionRedisService
|
.sendCommand<
|
||||||
.raw()
|
unknown[]
|
||||||
.sendCommand(['HGETALL', keys.liveStateKey]),
|
>(['EVAL', ["local now = redis.call('TIME')", 'local timestamp = tonumber(now[1]) * 1000 + math.floor(tonumber(now[2]) / 1000)', "return {tostring(timestamp), redis.call('HGETALL', KEYS[1]), redis.call('GET', KEYS[2]), redis.call('LRANGE', KEYS[3], 0, -1)}"].join('\n'), '3', keys.liveStateKey, keys.structureStateKey, keys.bidHistoryKey]);
|
||||||
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:
|
||||||
@@ -144,7 +137,7 @@ export class AuctionRedisStateReaderService {
|
|||||||
auctionBidHistoryEntries: Array.isArray(bidEntries)
|
auctionBidHistoryEntries: Array.isArray(bidEntries)
|
||||||
? bidEntries.map(String)
|
? bidEntries.map(String)
|
||||||
: [],
|
: [],
|
||||||
currentServerTimestampMS,
|
currentServerTimestampMS: Number(currentServerTimestampMS),
|
||||||
liveState: liveState as Record<string, unknown> & {
|
liveState: liveState as Record<string, unknown> & {
|
||||||
auctionLifecycleId: string;
|
auctionLifecycleId: string;
|
||||||
phase: string;
|
phase: string;
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ describe('auction apply transition redis script contract', () => {
|
|||||||
'auction:match-1:bidRequestResults',
|
'auction:match-1:bidRequestResults',
|
||||||
'auction:match-1:bidRequestResultOrder',
|
'auction:match-1:bidRequestResultOrder',
|
||||||
'auction:bidRoundDeadlineQueue',
|
'auction:bidRoundDeadlineQueue',
|
||||||
|
'auction:match-1:rejectedBidRequestResultOrder',
|
||||||
]);
|
]);
|
||||||
expect(invocation.values.slice(0, 19)).toEqual([
|
expect(invocation.values.slice(0, 19)).toEqual([
|
||||||
'match-1',
|
'match-1',
|
||||||
|
|||||||
@@ -79,6 +79,7 @@ export function buildAuctionApplyTransitionScriptInvocation(
|
|||||||
keys.bidRequestResultsKey,
|
keys.bidRequestResultsKey,
|
||||||
keys.bidRequestResultOrderKey,
|
keys.bidRequestResultOrderKey,
|
||||||
keys.deadlineQueueKey,
|
keys.deadlineQueueKey,
|
||||||
|
keys.rejectedBidRequestResultOrderKey,
|
||||||
],
|
],
|
||||||
script: AUCTION_APPLY_TRANSITION_SCRIPT,
|
script: AUCTION_APPLY_TRANSITION_SCRIPT,
|
||||||
values: [
|
values: [
|
||||||
@@ -128,6 +129,7 @@ local auctionBidHistoryKey = KEYS[8]
|
|||||||
local bidRequestResultsKey = KEYS[9]
|
local bidRequestResultsKey = KEYS[9]
|
||||||
local bidRequestResultOrderKey = KEYS[10]
|
local bidRequestResultOrderKey = KEYS[10]
|
||||||
local bidRoundDeadlineQueueKey = KEYS[11]
|
local bidRoundDeadlineQueueKey = KEYS[11]
|
||||||
|
local rejectedBidRequestResultOrderKey = KEYS[12]
|
||||||
|
|
||||||
local matchId = ARGV[1]
|
local matchId = ARGV[1]
|
||||||
local auctionLifecycleId = ARGV[2]
|
local auctionLifecycleId = ARGV[2]
|
||||||
@@ -270,16 +272,27 @@ for i = 1, liveStatePatchPairCount do
|
|||||||
end
|
end
|
||||||
redis.call('HSET', unpack(hsetArgs))
|
redis.call('HSET', unpack(hsetArgs))
|
||||||
|
|
||||||
|
local committedBidRoundDeadlineTimestampMS = ''
|
||||||
if deadlineMode == 'set-relative' then
|
if deadlineMode == 'set-relative' then
|
||||||
local currentBidRoundDeadlineTimestampMS = currentRedisTimestampMS + (deadlineDurationSeconds * 1000)
|
local currentBidRoundDeadlineTimestampMS = currentRedisTimestampMS + (deadlineDurationSeconds * 1000)
|
||||||
|
committedBidRoundDeadlineTimestampMS = tostring(currentBidRoundDeadlineTimestampMS)
|
||||||
redis.call('HSET', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS', tostring(currentBidRoundDeadlineTimestampMS))
|
redis.call('HSET', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS', tostring(currentBidRoundDeadlineTimestampMS))
|
||||||
|
redis.call('HSET', liveAuctionStateKey, 'currentBidRoundId', auctionStateTransitionId)
|
||||||
redis.call('ZADD', bidRoundDeadlineQueueKey, currentBidRoundDeadlineTimestampMS, matchId)
|
redis.call('ZADD', bidRoundDeadlineQueueKey, currentBidRoundDeadlineTimestampMS, matchId)
|
||||||
elseif deadlineMode == 'remove' then
|
elseif deadlineMode == 'remove' then
|
||||||
redis.call('ZREM', bidRoundDeadlineQueueKey, matchId)
|
redis.call('ZREM', bidRoundDeadlineQueueKey, matchId)
|
||||||
|
redis.call('HDEL', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS')
|
||||||
|
end
|
||||||
|
|
||||||
|
-- A resumed auction must not disappear when its former completion TTL elapses.
|
||||||
|
if redis.call('HGET', liveAuctionStateKey, 'phase') ~= 'complete' then
|
||||||
|
for _, index in ipairs({1, 2, 3, 6, 7, 8, 9, 10, 12}) do
|
||||||
|
redis.call('PERSIST', KEYS[index])
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
if shouldResetBidRuntime == '1' then
|
if shouldResetBidRuntime == '1' then
|
||||||
redis.call('DEL', auctionBidHistoryKey, bidRequestResultsKey, bidRequestResultOrderKey)
|
redis.call('DEL', auctionBidHistoryKey, bidRequestResultsKey, bidRequestResultOrderKey, rejectedBidRequestResultOrderKey)
|
||||||
end
|
end
|
||||||
|
|
||||||
redis.call('SADD', appliedAuctionStateTransitionIdsKey, transitionDedupeMember)
|
redis.call('SADD', appliedAuctionStateTransitionIdsKey, transitionDedupeMember)
|
||||||
@@ -288,6 +301,8 @@ redis.call(
|
|||||||
durabilityPayloadKey,
|
durabilityPayloadKey,
|
||||||
'payloadJson',
|
'payloadJson',
|
||||||
durabilityPayloadJson,
|
durabilityPayloadJson,
|
||||||
|
'committedBidRoundDeadlineTimestampMS',
|
||||||
|
committedBidRoundDeadlineTimestampMS,
|
||||||
'preparedAtRedisTimestampMS',
|
'preparedAtRedisTimestampMS',
|
||||||
tostring(currentRedisTimestampMS),
|
tostring(currentRedisTimestampMS),
|
||||||
'committedAtRedisTimestampMS',
|
'committedAtRedisTimestampMS',
|
||||||
@@ -317,7 +332,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)}
|
||||||
|
|||||||
@@ -30,6 +30,9 @@ describe('auction bid redis script contract', () => {
|
|||||||
'auction:match-1:bidRequestResults',
|
'auction:match-1:bidRequestResults',
|
||||||
'auction:match-1:bidRequestResultOrder',
|
'auction:match-1:bidRequestResultOrder',
|
||||||
'auction:bidRoundDeadlineQueue',
|
'auction:bidRoundDeadlineQueue',
|
||||||
|
'auction:match-1:rejectedBidRequestResultOrder',
|
||||||
|
'auction:bidArchiveQueue',
|
||||||
|
'auction:bidArchivePayloads',
|
||||||
]);
|
]);
|
||||||
expect(invocation.values).toEqual([
|
expect(invocation.values).toEqual([
|
||||||
'match-1',
|
'match-1',
|
||||||
@@ -45,6 +48,7 @@ describe('auction bid redis script contract', () => {
|
|||||||
'100',
|
'100',
|
||||||
'60000',
|
'60000',
|
||||||
'200',
|
'200',
|
||||||
|
'',
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,8 @@
|
|||||||
import type { AuctionRedisKeys } from './auction-redis.keys';
|
import type { AuctionRedisKeys } from './auction-redis.keys';
|
||||||
|
import {
|
||||||
|
AUCTION_BID_ARCHIVE_QUEUE_KEY,
|
||||||
|
AUCTION_BID_ARCHIVE_PAYLOADS_KEY,
|
||||||
|
} from './auction-redis.keys';
|
||||||
import { defineAuctionRedisScript } from './auction-redis.scripts';
|
import { defineAuctionRedisScript } from './auction-redis.scripts';
|
||||||
|
|
||||||
export interface AuctionBidScriptInput {
|
export interface AuctionBidScriptInput {
|
||||||
@@ -8,6 +12,7 @@ export interface AuctionBidScriptInput {
|
|||||||
bidderUserId: string;
|
bidderUserId: string;
|
||||||
clientObservedAuctionLifecycleId: string;
|
clientObservedAuctionLifecycleId: string;
|
||||||
clientObservedCurrentBidRoundPlayerUserId: string;
|
clientObservedCurrentBidRoundPlayerUserId: string;
|
||||||
|
clientObservedBidRoundId?: string;
|
||||||
maximumAuctionTeamMemberCount: number;
|
maximumAuctionTeamMemberCount: number;
|
||||||
maximumStoredAuctionBidHistoryCount: number;
|
maximumStoredAuctionBidHistoryCount: number;
|
||||||
maximumStoredBidRequestResultCount: number;
|
maximumStoredBidRequestResultCount: number;
|
||||||
@@ -40,15 +45,19 @@ export function buildBidRequestPayloadFingerprint(params: {
|
|||||||
bidPointAmount: number;
|
bidPointAmount: number;
|
||||||
clientObservedAuctionLifecycleId: string;
|
clientObservedAuctionLifecycleId: string;
|
||||||
clientObservedCurrentBidRoundPlayerUserId: string;
|
clientObservedCurrentBidRoundPlayerUserId: string;
|
||||||
|
clientObservedBidRoundId?: string;
|
||||||
matchId: string;
|
matchId: string;
|
||||||
}): string {
|
}): string {
|
||||||
return [
|
const parts = [
|
||||||
params.matchId,
|
params.matchId,
|
||||||
params.clientObservedAuctionLifecycleId,
|
params.clientObservedAuctionLifecycleId,
|
||||||
params.clientObservedCurrentBidRoundPlayerUserId,
|
params.clientObservedCurrentBidRoundPlayerUserId,
|
||||||
params.bidderTeamIndex,
|
params.bidderTeamIndex,
|
||||||
params.bidPointAmount,
|
params.bidPointAmount,
|
||||||
].join('|');
|
];
|
||||||
|
if (params.clientObservedBidRoundId)
|
||||||
|
parts.push(params.clientObservedBidRoundId);
|
||||||
|
return parts.join('|');
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildAuctionBidScriptInvocation(
|
export function buildAuctionBidScriptInvocation(
|
||||||
@@ -62,6 +71,9 @@ export function buildAuctionBidScriptInvocation(
|
|||||||
keys.bidRequestResultsKey,
|
keys.bidRequestResultsKey,
|
||||||
keys.bidRequestResultOrderKey,
|
keys.bidRequestResultOrderKey,
|
||||||
keys.deadlineQueueKey,
|
keys.deadlineQueueKey,
|
||||||
|
keys.rejectedBidRequestResultOrderKey,
|
||||||
|
AUCTION_BID_ARCHIVE_QUEUE_KEY,
|
||||||
|
AUCTION_BID_ARCHIVE_PAYLOADS_KEY,
|
||||||
],
|
],
|
||||||
script: AUCTION_BID_SCRIPT,
|
script: AUCTION_BID_SCRIPT,
|
||||||
values: [
|
values: [
|
||||||
@@ -78,6 +90,7 @@ export function buildAuctionBidScriptInvocation(
|
|||||||
String(input.maximumStoredBidRequestResultCount),
|
String(input.maximumStoredBidRequestResultCount),
|
||||||
String(input.minimumBidRequestResultReplayWindowMS),
|
String(input.minimumBidRequestResultReplayWindowMS),
|
||||||
String(input.maximumStoredAuctionBidHistoryCount),
|
String(input.maximumStoredAuctionBidHistoryCount),
|
||||||
|
input.clientObservedBidRoundId ?? '',
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -90,6 +103,9 @@ local auctionBidHistoryKey = KEYS[2]
|
|||||||
local bidRequestResultsKey = KEYS[3]
|
local bidRequestResultsKey = KEYS[3]
|
||||||
local bidRequestResultOrderKey = KEYS[4]
|
local bidRequestResultOrderKey = KEYS[4]
|
||||||
local bidRoundDeadlineQueueKey = KEYS[5]
|
local bidRoundDeadlineQueueKey = KEYS[5]
|
||||||
|
local rejectedBidRequestResultOrderKey = KEYS[6]
|
||||||
|
local bidArchiveQueueKey = KEYS[7]
|
||||||
|
local bidArchivePayloadsKey = KEYS[8]
|
||||||
|
|
||||||
local matchId = ARGV[1]
|
local matchId = ARGV[1]
|
||||||
local bidderTeamIndex = ARGV[2]
|
local bidderTeamIndex = ARGV[2]
|
||||||
@@ -104,6 +120,7 @@ local bidRequestPayloadFingerprint = ARGV[10]
|
|||||||
local maximumStoredBidRequestResultCount = tonumber(ARGV[11])
|
local maximumStoredBidRequestResultCount = tonumber(ARGV[11])
|
||||||
local minimumBidRequestResultReplayWindowMS = tonumber(ARGV[12])
|
local minimumBidRequestResultReplayWindowMS = tonumber(ARGV[12])
|
||||||
local maximumStoredAuctionBidHistoryCount = tonumber(ARGV[13])
|
local maximumStoredAuctionBidHistoryCount = tonumber(ARGV[13])
|
||||||
|
local clientObservedBidRoundId = ARGV[14] or ''
|
||||||
|
|
||||||
local redisTime = redis.call('TIME')
|
local redisTime = redis.call('TIME')
|
||||||
local currentRedisTimestampMS = (tonumber(redisTime[1]) * 1000) + math.floor(tonumber(redisTime[2]) / 1000)
|
local currentRedisTimestampMS = (tonumber(redisTime[1]) * 1000) + math.floor(tonumber(redisTime[2]) / 1000)
|
||||||
@@ -168,12 +185,23 @@ if existingFingerprint then
|
|||||||
return replayExistingRequest()
|
return replayExistingRequest()
|
||||||
end
|
end
|
||||||
|
|
||||||
trimOldBidRequestResults()
|
-- Upgrade the old shared queue once, preserving every accepted replay record.
|
||||||
if redis.call('LLEN', bidRequestResultOrderKey) >= maximumStoredBidRequestResultCount then
|
if redis.call('HSETNX', bidRequestResultsKey, '_acceptedOnlyOrderV1', '1') == 1 then
|
||||||
return {'REJECTED', 'BID_REQUEST_RESULT_LIMIT', bidRequestId, tostring(currentRedisTimestampMS)}
|
for _, oldRequestId in ipairs(redis.call('LRANGE', bidRequestResultOrderKey, 0, -1)) do
|
||||||
|
if redis.call('HGET', bidRequestResultsKey, oldRequestId .. ':status') == 'rejected' then
|
||||||
|
redis.call('LREM', bidRequestResultOrderKey, 0, oldRequestId)
|
||||||
|
hdelBidRequest(oldRequestId)
|
||||||
|
end
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
local function storeRejectedRequest(rejectCode)
|
local function storeRejectedRequest(rejectCode)
|
||||||
|
-- Rejections have their own bounded retention. They must never consume the
|
||||||
|
-- protected replay capacity of accepted bids.
|
||||||
|
while redis.call('LLEN', rejectedBidRequestResultOrderKey) >= maximumStoredBidRequestResultCount do
|
||||||
|
local oldest = redis.call('LPOP', rejectedBidRequestResultOrderKey)
|
||||||
|
if oldest then hdelBidRequest(oldest) end
|
||||||
|
end
|
||||||
local rejectedCurrentBidRoundDeadlineTimestampMS = redis.call('HGET', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS') or ''
|
local rejectedCurrentBidRoundDeadlineTimestampMS = redis.call('HGET', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS') or ''
|
||||||
redis.call(
|
redis.call(
|
||||||
'HSET',
|
'HSET',
|
||||||
@@ -191,7 +219,7 @@ local function storeRejectedRequest(rejectCode)
|
|||||||
requestField('createdAtTimestampMS'),
|
requestField('createdAtTimestampMS'),
|
||||||
tostring(currentRedisTimestampMS)
|
tostring(currentRedisTimestampMS)
|
||||||
)
|
)
|
||||||
redis.call('RPUSH', bidRequestResultOrderKey, bidRequestId)
|
redis.call('RPUSH', rejectedBidRequestResultOrderKey, bidRequestId)
|
||||||
return {'REJECTED', rejectCode, bidRequestId, tostring(currentRedisTimestampMS), rejectedCurrentBidRoundDeadlineTimestampMS}
|
return {'REJECTED', rejectCode, bidRequestId, tostring(currentRedisTimestampMS), rejectedCurrentBidRoundDeadlineTimestampMS}
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -202,9 +230,16 @@ end
|
|||||||
|
|
||||||
local auctionLifecycleId = redis.call('HGET', liveAuctionStateKey, 'auctionLifecycleId')
|
local auctionLifecycleId = redis.call('HGET', liveAuctionStateKey, 'auctionLifecycleId')
|
||||||
local currentBidRoundPlayerUserId = redis.call('HGET', liveAuctionStateKey, 'currentBidRoundPlayerUserId')
|
local currentBidRoundPlayerUserId = redis.call('HGET', liveAuctionStateKey, 'currentBidRoundPlayerUserId')
|
||||||
|
local currentBidRoundId = redis.call('HGET', liveAuctionStateKey, 'currentBidRoundId') or ''
|
||||||
|
if currentBidRoundId ~= '' and clientObservedBidRoundId == '' then
|
||||||
|
return storeRejectedRequest('BID_CLIENT_UPDATE_REQUIRED')
|
||||||
|
end
|
||||||
if auctionLifecycleId ~= clientObservedAuctionLifecycleId or currentBidRoundPlayerUserId ~= clientObservedCurrentBidRoundPlayerUserId then
|
if auctionLifecycleId ~= clientObservedAuctionLifecycleId or currentBidRoundPlayerUserId ~= clientObservedCurrentBidRoundPlayerUserId then
|
||||||
return storeRejectedRequest('STALE_BID_ROUND')
|
return storeRejectedRequest('STALE_BID_ROUND')
|
||||||
end
|
end
|
||||||
|
if currentBidRoundId ~= clientObservedBidRoundId then
|
||||||
|
return storeRejectedRequest('STALE_BID_ROUND')
|
||||||
|
end
|
||||||
|
|
||||||
local currentBidRoundDeadlineTimestampMS = tonumber(redis.call('HGET', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS') or '0')
|
local currentBidRoundDeadlineTimestampMS = tonumber(redis.call('HGET', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS') or '0')
|
||||||
if currentBidRoundDeadlineTimestampMS <= currentRedisTimestampMS then
|
if currentBidRoundDeadlineTimestampMS <= currentRedisTimestampMS then
|
||||||
@@ -235,8 +270,9 @@ if bidPointAmount + requiredReserveAfterBid > remainingBidPointAmount then
|
|||||||
return storeRejectedRequest('INSUFFICIENT')
|
return storeRejectedRequest('INSUFFICIENT')
|
||||||
end
|
end
|
||||||
|
|
||||||
if redis.call('LLEN', auctionBidHistoryKey) >= maximumStoredAuctionBidHistoryCount then
|
trimOldBidRequestResults()
|
||||||
return storeRejectedRequest('BID_HISTORY_LIMIT')
|
if redis.call('LLEN', bidRequestResultOrderKey) >= maximumStoredBidRequestResultCount then
|
||||||
|
return {'REJECTED', 'BID_REQUEST_RESULT_LIMIT', bidRequestId, tostring(currentRedisTimestampMS)}
|
||||||
end
|
end
|
||||||
|
|
||||||
local maximumBidRoundDurationSeconds = tonumber(redis.call('HGET', liveAuctionStateKey, 'maximumBidRoundDurationSeconds') or '0')
|
local maximumBidRoundDurationSeconds = tonumber(redis.call('HGET', liveAuctionStateKey, 'maximumBidRoundDurationSeconds') or '0')
|
||||||
@@ -254,14 +290,36 @@ end
|
|||||||
local nextBidRoundDeadlineTimestampMS = currentRedisTimestampMS + nextRemainingBidRoundTimeMS
|
local nextBidRoundDeadlineTimestampMS = currentRedisTimestampMS + nextRemainingBidRoundTimeMS
|
||||||
|
|
||||||
local revision = redis.call('HINCRBY', liveAuctionStateKey, 'revision', 1)
|
local revision = redis.call('HINCRBY', liveAuctionStateKey, 'revision', 1)
|
||||||
local auctionBidHistoryEntryJson =
|
local auctionBidHistoryEntryJson = cjson.encode({
|
||||||
'{"bidderTeamIndex":' .. bidderTeamIndex ..
|
bidRequestId = bidRequestId,
|
||||||
',"bidPointAmount":' .. tostring(bidPointAmount) ..
|
revision = revision,
|
||||||
',"bidderUserId":"' .. bidderUserId ..
|
bidderTeamIndex = tonumber(bidderTeamIndex),
|
||||||
'","bidPlacedAtTimestampMS":' .. tostring(currentRedisTimestampMS) ..
|
bidPointAmount = bidPointAmount,
|
||||||
'}'
|
bidderUserId = bidderUserId,
|
||||||
|
playerUserId = currentBidRoundPlayerUserId,
|
||||||
|
bidRoundId = currentBidRoundId,
|
||||||
|
bidPlacedAtTimestampMS = currentRedisTimestampMS
|
||||||
|
})
|
||||||
|
|
||||||
|
-- Accepted replay returns above this point. Persist every accepted event before
|
||||||
|
-- trimming the recent view; the durable archive worker removes only saved events.
|
||||||
|
local archiveId = matchId .. ':' .. auctionLifecycleId .. ':' .. string.format('%016d', revision)
|
||||||
|
redis.call('HSET', bidArchivePayloadsKey, archiveId, cjson.encode({
|
||||||
|
_id = archiveId,
|
||||||
|
matchId = matchId,
|
||||||
|
auctionLifecycleId = auctionLifecycleId,
|
||||||
|
revision = revision,
|
||||||
|
bidRequestId = bidRequestId,
|
||||||
|
bidderTeamIndex = tonumber(bidderTeamIndex),
|
||||||
|
bidPointAmount = bidPointAmount,
|
||||||
|
bidderUserId = bidderUserId,
|
||||||
|
playerUserId = currentBidRoundPlayerUserId,
|
||||||
|
bidRoundId = currentBidRoundId,
|
||||||
|
bidPlacedAtTimestampMS = currentRedisTimestampMS
|
||||||
|
}))
|
||||||
|
redis.call('ZADD', bidArchiveQueueKey, currentRedisTimestampMS, archiveId)
|
||||||
redis.call('RPUSH', auctionBidHistoryKey, auctionBidHistoryEntryJson)
|
redis.call('RPUSH', auctionBidHistoryKey, auctionBidHistoryEntryJson)
|
||||||
|
redis.call('LTRIM', auctionBidHistoryKey, -maximumStoredAuctionBidHistoryCount, -1)
|
||||||
redis.call(
|
redis.call(
|
||||||
'HSET',
|
'HSET',
|
||||||
liveAuctionStateKey,
|
liveAuctionStateKey,
|
||||||
|
|||||||
@@ -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
|
||||||
|
`,
|
||||||
|
);
|
||||||
@@ -4,6 +4,14 @@ export const AUCTION_DURABILITY_RETRY_QUEUE_KEY =
|
|||||||
'auction:auctionDurabilityRetryQueue';
|
'auction:auctionDurabilityRetryQueue';
|
||||||
export const AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY =
|
export const AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY =
|
||||||
'auction:auctionDurabilityDeadLetterQueue';
|
'auction:auctionDurabilityDeadLetterQueue';
|
||||||
|
export const AUCTION_DEAD_LETTER_STATUS_QUEUE_KEY =
|
||||||
|
'auction:deadLetterStatusQueue';
|
||||||
|
export const AUCTION_BID_ARCHIVE_QUEUE_KEY = 'auction:bidArchiveQueue';
|
||||||
|
export const AUCTION_BID_ARCHIVE_PAYLOADS_KEY = 'auction:bidArchivePayloads';
|
||||||
|
export const AUCTION_BID_ARCHIVE_DEAD_LETTER_QUEUE_KEY =
|
||||||
|
'auction:bidArchiveDeadLetterQueue';
|
||||||
|
export const AUCTION_BID_ARCHIVE_DEAD_LETTER_PAYLOADS_KEY =
|
||||||
|
'auction:bidArchiveDeadLetterPayloads';
|
||||||
|
|
||||||
export interface AuctionRedisKeys {
|
export interface AuctionRedisKeys {
|
||||||
actionRequestResultOrderKey: string;
|
actionRequestResultOrderKey: string;
|
||||||
@@ -12,6 +20,7 @@ export interface AuctionRedisKeys {
|
|||||||
bidHistoryKey: string;
|
bidHistoryKey: string;
|
||||||
bidRequestResultOrderKey: string;
|
bidRequestResultOrderKey: string;
|
||||||
bidRequestResultsKey: string;
|
bidRequestResultsKey: string;
|
||||||
|
rejectedBidRequestResultOrderKey: string;
|
||||||
deadlineQueueKey: string;
|
deadlineQueueKey: string;
|
||||||
durabilityDeadLetterQueueKey: string;
|
durabilityDeadLetterQueueKey: string;
|
||||||
durabilityPayloadKey: (auctionStateTransitionId: string) => string;
|
durabilityPayloadKey: (auctionStateTransitionId: string) => string;
|
||||||
@@ -33,6 +42,7 @@ export function buildAuctionRedisKeys(matchId: string): AuctionRedisKeys {
|
|||||||
bidHistoryKey: `${prefix}:auctionBidHistory`,
|
bidHistoryKey: `${prefix}:auctionBidHistory`,
|
||||||
bidRequestResultOrderKey: `${prefix}:bidRequestResultOrder`,
|
bidRequestResultOrderKey: `${prefix}:bidRequestResultOrder`,
|
||||||
bidRequestResultsKey: `${prefix}:bidRequestResults`,
|
bidRequestResultsKey: `${prefix}:bidRequestResults`,
|
||||||
|
rejectedBidRequestResultOrderKey: `${prefix}:rejectedBidRequestResultOrder`,
|
||||||
deadlineQueueKey: AUCTION_BID_ROUND_DEADLINE_QUEUE_KEY,
|
deadlineQueueKey: AUCTION_BID_ROUND_DEADLINE_QUEUE_KEY,
|
||||||
durabilityDeadLetterQueueKey: AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY,
|
durabilityDeadLetterQueueKey: AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY,
|
||||||
durabilityPayloadKey: (auctionStateTransitionId: string) =>
|
durabilityPayloadKey: (auctionStateTransitionId: string) =>
|
||||||
|
|||||||
@@ -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,45 +20,10 @@ 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(
|
||||||
|
await loadRedisClientOptions(secretService),
|
||||||
|
);
|
||||||
client.on('error', (error: unknown) => {
|
client.on('error', (error: unknown) => {
|
||||||
logger.error(
|
logger.error(
|
||||||
`Auction Redis client error: ${
|
`Auction Redis client error: ${
|
||||||
|
|||||||
@@ -129,13 +129,7 @@ export class AuctionRedisService implements OnModuleDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -24,7 +24,7 @@ describe('auction redis state assembly', () => {
|
|||||||
mongo: { auctionLifecycleId: 'new-life', revision: 2 },
|
mongo: { auctionLifecycleId: 'new-life', revision: 2 },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
expected: false,
|
expected: true,
|
||||||
live: { auctionLifecycleId: 'redis-life', revision: 3 },
|
live: { auctionLifecycleId: 'redis-life', revision: 3 },
|
||||||
mongo: { auctionLifecycleId: 'mongo-life', revision: 2 },
|
mongo: { auctionLifecycleId: 'mongo-life', revision: 2 },
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -62,13 +62,11 @@ export function shouldHydrateRedisAuctionState(
|
|||||||
params: ShouldHydrateRedisAuctionStateParams,
|
params: ShouldHydrateRedisAuctionStateParams,
|
||||||
): boolean {
|
): boolean {
|
||||||
if (!params.live) return true;
|
if (!params.live) return true;
|
||||||
|
if (params.mongo.auctionLifecycleId !== params.live.auctionLifecycleId)
|
||||||
|
return true;
|
||||||
const redisRevision = params.live.revision ?? -1;
|
const redisRevision = params.live.revision ?? -1;
|
||||||
const mongoRevision = params.mongo.revision;
|
const mongoRevision = params.mongo.revision;
|
||||||
if (mongoRevision > redisRevision) return true;
|
return mongoRevision > redisRevision;
|
||||||
return (
|
|
||||||
mongoRevision === redisRevision &&
|
|
||||||
params.mongo.auctionLifecycleId !== params.live.auctionLifecycleId
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function assembleAuctionViewFromRedisState(
|
export function assembleAuctionViewFromRedisState(
|
||||||
@@ -140,13 +138,17 @@ if not liveStatePatchPairCount or #ARGV ~= 8 + (liveStatePatchPairCount * 2) the
|
|||||||
return {'REJECTED', 'INVALID_PATCH_ARITY', tostring(currentRedisTimestampMS)}
|
return {'REJECTED', 'INVALID_PATCH_ARITY', tostring(currentRedisTimestampMS)}
|
||||||
end
|
end
|
||||||
|
|
||||||
|
-- A lifecycle replacement requires Mongo authority and an explicit cleanup
|
||||||
|
-- under the lifecycle lock. Revision numbers from different runs are unrelated.
|
||||||
|
if redisAuctionLifecycleId and redisAuctionLifecycleId ~= mongoAuctionLifecycleId then
|
||||||
|
return {'REJECTED', 'LIFECYCLE_CONFLICT', tostring(currentRedisTimestampMS)}
|
||||||
|
end
|
||||||
|
|
||||||
local shouldHydrate = false
|
local shouldHydrate = false
|
||||||
if redisRevision < 0 then
|
if redisRevision < 0 then
|
||||||
shouldHydrate = true
|
shouldHydrate = true
|
||||||
elseif mongoRevision > redisRevision then
|
elseif mongoRevision > redisRevision then
|
||||||
shouldHydrate = true
|
shouldHydrate = true
|
||||||
elseif mongoRevision == redisRevision and mongoAuctionLifecycleId ~= redisAuctionLifecycleId then
|
|
||||||
shouldHydrate = true
|
|
||||||
end
|
end
|
||||||
|
|
||||||
if not shouldHydrate then
|
if not shouldHydrate then
|
||||||
@@ -184,6 +186,7 @@ if phase == 'bidding' then
|
|||||||
redis.call('ZADD', bidRoundDeadlineQueueKey, currentBidRoundDeadlineTimestampMS, matchId)
|
redis.call('ZADD', bidRoundDeadlineQueueKey, currentBidRoundDeadlineTimestampMS, matchId)
|
||||||
else
|
else
|
||||||
redis.call('ZREM', bidRoundDeadlineQueueKey, matchId)
|
redis.call('ZREM', bidRoundDeadlineQueueKey, matchId)
|
||||||
|
redis.call('HDEL', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS')
|
||||||
end
|
end
|
||||||
|
|
||||||
return {'OK', tostring(hydratedRevision), tostring(currentRedisTimestampMS)}
|
return {'OK', tostring(hydratedRevision), tostring(currentRedisTimestampMS)}
|
||||||
|
|||||||
@@ -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,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,198 @@
|
|||||||
|
import { Logger } from '@nestjs/common';
|
||||||
|
import { CommunityStatsCacheService } from './community-stats-cache.service';
|
||||||
|
|
||||||
|
describe('Community stats cache invalidation retries', () => {
|
||||||
|
let service: CommunityStatsCacheService;
|
||||||
|
let invalidate: jest.SpyInstance<Promise<number>, [string, number?]>;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.useFakeTimers();
|
||||||
|
jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
|
||||||
|
service = new CommunityStatsCacheService({} as never);
|
||||||
|
invalidate = jest
|
||||||
|
.spyOn(service, 'invalidateCommunity')
|
||||||
|
.mockRejectedValue(new Error('Redis down'));
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
service.onModuleDestroy();
|
||||||
|
jest.restoreAllMocks();
|
||||||
|
jest.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns true even when successful invalidation deletes no cache entries', async () => {
|
||||||
|
invalidate.mockResolvedValue(0);
|
||||||
|
expect(await service.invalidateCommunityWithRetry('community')).toBe(true);
|
||||||
|
expect(invalidate).toHaveBeenCalledWith('community', 1_000);
|
||||||
|
expect(jest.getTimerCount()).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns false immediately, then retries at most three times with increasing delays', async () => {
|
||||||
|
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
|
||||||
|
expect(invalidate).toHaveBeenCalledTimes(1);
|
||||||
|
for (const [index, delay] of [1_000, 5_000, 30_000].entries()) {
|
||||||
|
await jest.advanceTimersByTimeAsync(delay - 1);
|
||||||
|
expect(invalidate).toHaveBeenCalledTimes(index + 1);
|
||||||
|
await jest.advanceTimersByTimeAsync(1);
|
||||||
|
expect(invalidate).toHaveBeenCalledTimes(index + 2);
|
||||||
|
}
|
||||||
|
expect(jest.getTimerCount()).toBe(0);
|
||||||
|
await jest.advanceTimersByTimeAsync(60_000);
|
||||||
|
expect(invalidate).toHaveBeenCalledTimes(4);
|
||||||
|
expect(Logger.prototype.warn).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining('retries exhausted for community'),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not reset the scheduled delay or remaining budget after another immediate failure', async () => {
|
||||||
|
await service.invalidateCommunityWithRetry('community');
|
||||||
|
await jest.advanceTimersByTimeAsync(1_000);
|
||||||
|
expect(invalidate).toHaveBeenCalledTimes(2);
|
||||||
|
await jest.advanceTimersByTimeAsync(2_000);
|
||||||
|
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
|
||||||
|
expect(jest.getTimerCount()).toBe(1);
|
||||||
|
await jest.advanceTimersByTimeAsync(2_999);
|
||||||
|
expect(invalidate).toHaveBeenCalledTimes(3);
|
||||||
|
await jest.advanceTimersByTimeAsync(1);
|
||||||
|
expect(invalidate).toHaveBeenCalledTimes(4);
|
||||||
|
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
|
||||||
|
await jest.advanceTimersByTimeAsync(30_000);
|
||||||
|
expect(invalidate).toHaveBeenCalledTimes(6);
|
||||||
|
expect(jest.getTimerCount()).toBe(0);
|
||||||
|
await jest.advanceTimersByTimeAsync(60_000);
|
||||||
|
expect(invalidate).toHaveBeenCalledTimes(6);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(['immediate', 'background'] as const)(
|
||||||
|
'cancels remaining retries after a successful %s attempt',
|
||||||
|
async (attempt) => {
|
||||||
|
await service.invalidateCommunityWithRetry('community');
|
||||||
|
invalidate.mockResolvedValue(0);
|
||||||
|
if (attempt === 'immediate') {
|
||||||
|
expect(await service.invalidateCommunityWithRetry('community')).toBe(
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
await jest.advanceTimersByTimeAsync(1_000);
|
||||||
|
}
|
||||||
|
expect(jest.getTimerCount()).toBe(0);
|
||||||
|
await jest.advanceTimersByTimeAsync(60_000);
|
||||||
|
expect(invalidate).toHaveBeenCalledTimes(2);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it('unrefs every retry timer so it does not keep the process alive', async () => {
|
||||||
|
const setTimeoutSpy = jest.spyOn(global, 'setTimeout');
|
||||||
|
await service.invalidateCommunityWithRetry('community');
|
||||||
|
for (const delay of [1_000, 5_000, 30_000]) {
|
||||||
|
const timer = setTimeoutSpy.mock.results.at(-1)!.value as NodeJS.Timeout;
|
||||||
|
expect(timer.hasRef()).toBe(false);
|
||||||
|
await jest.advanceTimersByTimeAsync(delay);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps different communities independent when one continues to fail', async () => {
|
||||||
|
await service.invalidateCommunityWithRetry('first');
|
||||||
|
await service.invalidateCommunityWithRetry('second');
|
||||||
|
invalidate.mockImplementation(async (id) => {
|
||||||
|
if (id === 'first') throw new Error('still unavailable');
|
||||||
|
return 1;
|
||||||
|
});
|
||||||
|
await jest.advanceTimersByTimeAsync(36_000);
|
||||||
|
expect(invalidate.mock.calls.filter(([id]) => id === 'first')).toHaveLength(
|
||||||
|
4,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
invalidate.mock.calls.filter(([id]) => id === 'second'),
|
||||||
|
).toHaveLength(2);
|
||||||
|
expect(jest.getTimerCount()).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears scheduled retries on shutdown', async () => {
|
||||||
|
await service.invalidateCommunityWithRetry('community');
|
||||||
|
service.onModuleDestroy();
|
||||||
|
expect(jest.getTimerCount()).toBe(0);
|
||||||
|
await jest.advanceTimersByTimeAsync(60_000);
|
||||||
|
expect(invalidate).toHaveBeenCalledTimes(1);
|
||||||
|
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
|
||||||
|
expect(invalidate).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(['shutdown', 'immediate success'] as const)(
|
||||||
|
'does not reschedule an in-flight retry after %s',
|
||||||
|
async (finish) => {
|
||||||
|
await service.invalidateCommunityWithRetry('community');
|
||||||
|
const pending = deferred();
|
||||||
|
invalidate.mockImplementationOnce(() => pending.promise);
|
||||||
|
await jest.advanceTimersByTimeAsync(1_000);
|
||||||
|
expect(invalidate).toHaveBeenCalledTimes(2);
|
||||||
|
if (finish === 'shutdown') {
|
||||||
|
service.onModuleDestroy();
|
||||||
|
} else {
|
||||||
|
invalidate.mockResolvedValueOnce(1);
|
||||||
|
expect(await service.invalidateCommunityWithRetry('community')).toBe(
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
pending.reject(new Error('late failure'));
|
||||||
|
await jest.advanceTimersByTimeAsync(60_000);
|
||||||
|
expect(invalidate).toHaveBeenCalledTimes(finish === 'shutdown' ? 2 : 3);
|
||||||
|
expect(jest.getTimerCount()).toBe(0);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it('does not cancel a newer failed request when an older immediate attempt succeeds late', async () => {
|
||||||
|
const pending = deferred();
|
||||||
|
invalidate.mockImplementationOnce(() => pending.promise);
|
||||||
|
const first = service.invalidateCommunityWithRetry('community');
|
||||||
|
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
|
||||||
|
pending.resolve(1);
|
||||||
|
expect(await first).toBe(true);
|
||||||
|
expect(jest.getTimerCount()).toBe(1);
|
||||||
|
invalidate.mockResolvedValue(1);
|
||||||
|
await jest.advanceTimersByTimeAsync(1_000);
|
||||||
|
expect(invalidate).toHaveBeenCalledTimes(3);
|
||||||
|
expect(jest.getTimerCount()).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('preserves the retry budget when an immediate request fails during an in-flight retry', async () => {
|
||||||
|
await service.invalidateCommunityWithRetry('community');
|
||||||
|
const pending = deferred();
|
||||||
|
invalidate.mockImplementationOnce(() => pending.promise);
|
||||||
|
await jest.advanceTimersByTimeAsync(1_000);
|
||||||
|
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
|
||||||
|
await jest.advanceTimersByTimeAsync(5_000);
|
||||||
|
expect(invalidate).toHaveBeenCalledTimes(3);
|
||||||
|
pending.resolve(1);
|
||||||
|
await jest.advanceTimersByTimeAsync(5_000);
|
||||||
|
expect(invalidate).toHaveBeenCalledTimes(4);
|
||||||
|
await jest.advanceTimersByTimeAsync(30_000);
|
||||||
|
expect(invalidate).toHaveBeenCalledTimes(5);
|
||||||
|
expect(jest.getTimerCount()).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not restart an exhausted budget when an older immediate request fails late', async () => {
|
||||||
|
await service.invalidateCommunityWithRetry('community');
|
||||||
|
await jest.advanceTimersByTimeAsync(6_000);
|
||||||
|
const pending = deferred();
|
||||||
|
invalidate.mockImplementationOnce(() => pending.promise);
|
||||||
|
const immediate = service.invalidateCommunityWithRetry('community');
|
||||||
|
await jest.advanceTimersByTimeAsync(30_000);
|
||||||
|
expect(invalidate).toHaveBeenCalledTimes(5);
|
||||||
|
pending.reject(new Error('late failure'));
|
||||||
|
expect(await immediate).toBe(false);
|
||||||
|
expect(jest.getTimerCount()).toBe(0);
|
||||||
|
await jest.advanceTimersByTimeAsync(60_000);
|
||||||
|
expect(invalidate).toHaveBeenCalledTimes(5);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function deferred() {
|
||||||
|
let resolve!: (value: number) => void;
|
||||||
|
let reject!: (reason: Error) => void;
|
||||||
|
const promise = new Promise<number>((done, fail) => {
|
||||||
|
resolve = done;
|
||||||
|
reject = fail;
|
||||||
|
});
|
||||||
|
return { promise, resolve, reject };
|
||||||
|
}
|
||||||
@@ -1,70 +1,246 @@
|
|||||||
import { Injectable, Logger } from '@nestjs/common';
|
import { Injectable, Logger, OnModuleDestroy } 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 INVALIDATION_RETRY_DELAYS_MS = [1_000, 5_000, 30_000] as const;
|
||||||
|
interface InvalidationRetry {
|
||||||
|
attempts: number;
|
||||||
|
requestVersion: number;
|
||||||
|
timer?: NodeJS.Timeout;
|
||||||
|
}
|
||||||
|
const CACHE_SCOPES = [
|
||||||
|
'matches',
|
||||||
|
'leaderboard',
|
||||||
|
'teamInsights',
|
||||||
|
'matchDetail',
|
||||||
|
'userInternal',
|
||||||
|
] as const;
|
||||||
|
type CacheScope = (typeof CACHE_SCOPES)[number];
|
||||||
|
|
||||||
|
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 implements OnModuleDestroy {
|
||||||
private readonly logger = new Logger(CommunityStatsCacheService.name);
|
private readonly logger = new Logger(CommunityStatsCacheService.name);
|
||||||
|
private readonly invalidationRetries = new Map<string, InvalidationRetry>();
|
||||||
|
private destroyed = false;
|
||||||
|
|
||||||
constructor(private readonly redisService: RedisService) {}
|
constructor(private readonly redisService: RedisService) {}
|
||||||
|
|
||||||
public get<T>(key: string): Promise<T | null> {
|
public onModuleDestroy(): void {
|
||||||
return this.redisService.getJson<T>(key);
|
this.destroyed = true;
|
||||||
|
for (const pending of this.invalidationRetries.values()) {
|
||||||
|
if (pending.timer) clearTimeout(pending.timer);
|
||||||
|
}
|
||||||
|
this.invalidationRetries.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
public set(
|
// Only the immediate attempt determines whether the caller may cache its response.
|
||||||
key: string,
|
public async invalidateCommunityWithRetry(
|
||||||
|
communityId: string,
|
||||||
|
): Promise<boolean> {
|
||||||
|
if (this.destroyed) return false;
|
||||||
|
const pending = this.invalidationRetries.get(communityId) ?? {
|
||||||
|
attempts: 0,
|
||||||
|
requestVersion: 0,
|
||||||
|
};
|
||||||
|
this.invalidationRetries.set(communityId, pending);
|
||||||
|
const version = ++pending.requestVersion;
|
||||||
|
const succeeded = await this.tryInvalidateCommunity(communityId);
|
||||||
|
if (succeeded && pending.requestVersion === version) {
|
||||||
|
this.clearInvalidationRetry(communityId, pending);
|
||||||
|
} else if (!succeeded) {
|
||||||
|
// An existing retry keeps its remaining budget, including while in flight.
|
||||||
|
this.scheduleInvalidationRetry(communityId, pending);
|
||||||
|
}
|
||||||
|
return succeeded;
|
||||||
|
}
|
||||||
|
|
||||||
|
private scheduleInvalidationRetry(
|
||||||
|
communityId: string,
|
||||||
|
pending: InvalidationRetry,
|
||||||
|
): void {
|
||||||
|
if (
|
||||||
|
this.destroyed ||
|
||||||
|
this.invalidationRetries.get(communityId) !== pending ||
|
||||||
|
pending.timer
|
||||||
|
)
|
||||||
|
return;
|
||||||
|
const delay = INVALIDATION_RETRY_DELAYS_MS[pending.attempts];
|
||||||
|
if (delay === undefined) {
|
||||||
|
this.clearInvalidationRetry(communityId, pending);
|
||||||
|
this.logger.warn(
|
||||||
|
`Stats cache invalidation retries exhausted for ${communityId}; detail recovery and cache expiry will refresh stale responses.`,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
pending.attempts += 1;
|
||||||
|
pending.timer = setTimeout(
|
||||||
|
() => void this.retryInvalidation(communityId, pending),
|
||||||
|
delay,
|
||||||
|
);
|
||||||
|
pending.timer.unref();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async retryInvalidation(
|
||||||
|
communityId: string,
|
||||||
|
pending: InvalidationRetry,
|
||||||
|
): Promise<void> {
|
||||||
|
const version = pending.requestVersion;
|
||||||
|
const succeeded = await this.tryInvalidateCommunity(communityId);
|
||||||
|
if (this.invalidationRetries.get(communityId) !== pending) return;
|
||||||
|
pending.timer = undefined;
|
||||||
|
// An older completion must not cancel a newer request's retry.
|
||||||
|
if (succeeded && pending.requestVersion === version) {
|
||||||
|
this.clearInvalidationRetry(communityId, pending);
|
||||||
|
} else {
|
||||||
|
this.scheduleInvalidationRetry(communityId, pending);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private clearInvalidationRetry(
|
||||||
|
communityId: string,
|
||||||
|
pending: InvalidationRetry,
|
||||||
|
): void {
|
||||||
|
if (this.invalidationRetries.get(communityId) !== pending) return;
|
||||||
|
if (pending.timer) clearTimeout(pending.timer);
|
||||||
|
this.invalidationRetries.delete(communityId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async tryInvalidateCommunity(communityId: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
await this.invalidateCommunity(communityId, 1_000);
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.warn(
|
||||||
|
`Stats cache invalidation failed for ${communityId}: ${String(error)}`,
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async get<T>(key: CommunityStatsCacheKey): Promise<T | null> {
|
||||||
|
const reply = await this.redisService
|
||||||
|
.raw()
|
||||||
|
.sendCommand<
|
||||||
|
[string, string | null]
|
||||||
|
>(['EVAL', READ_CACHE_SCRIPT, '2', key.generationKey, key.hashKey, randomUUID(), key.field]);
|
||||||
|
key.generation = reply[0];
|
||||||
|
if (!reply[1]) return null;
|
||||||
|
try {
|
||||||
|
return JSON.parse(reply[1]) as T;
|
||||||
|
} catch {
|
||||||
|
this.logger.warn(
|
||||||
|
`Failed to parse community stats cache field in ${key.hashKey}.`,
|
||||||
|
);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async set(
|
||||||
|
key: CommunityStatsCacheKey,
|
||||||
value: unknown,
|
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(
|
||||||
const prefix = `riot:communitystats:`;
|
communityId: string,
|
||||||
const match = `${prefix}*${communityId}*`;
|
timeoutMs?: number,
|
||||||
const client = this.redisService.raw();
|
): Promise<number> {
|
||||||
let cursor = '0';
|
const prefix = communityPrefix(communityId);
|
||||||
let deleted = 0;
|
const deleted = Number(
|
||||||
|
await this.redisService
|
||||||
do {
|
.raw()
|
||||||
const reply = await client.sendCommand([
|
.sendCommand(
|
||||||
'SCAN',
|
[
|
||||||
cursor,
|
'EVAL',
|
||||||
'MATCH',
|
INVALIDATE_CACHE_SCRIPT,
|
||||||
match,
|
String(CACHE_SCOPES.length + 1),
|
||||||
'COUNT',
|
`${prefix}:generation`,
|
||||||
'100',
|
...CACHE_SCOPES.map((scope) => `${prefix}:${scope}`),
|
||||||
]);
|
randomUUID(),
|
||||||
if (!Array.isArray(reply)) {
|
],
|
||||||
throw new Error('Redis SCAN returned an invalid response.');
|
timeoutMs === undefined ? undefined : { timeout: timeoutMs },
|
||||||
}
|
),
|
||||||
const values = reply as unknown[];
|
);
|
||||||
const nextCursor = values[0];
|
|
||||||
const rawKeys = values[1];
|
|
||||||
if (typeof nextCursor !== 'string') {
|
|
||||||
throw new Error('Redis SCAN returned an invalid cursor.');
|
|
||||||
}
|
|
||||||
cursor = nextCursor;
|
|
||||||
const keys = Array.isArray(rawKeys)
|
|
||||||
? (rawKeys as unknown[]).filter(
|
|
||||||
(key): key is string => typeof key === 'string',
|
|
||||||
)
|
|
||||||
: [];
|
|
||||||
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;
|
||||||
|
|||||||
@@ -0,0 +1,321 @@
|
|||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { CommunityStatsService } from './community-stats.service';
|
||||||
|
import { CommunityStatsCacheKey } from './community-stats-cache.service';
|
||||||
|
import type { InternalMatchDetailResponse } from './community-stats.types';
|
||||||
|
|
||||||
|
describe('Community stats raw archive recovery', () => {
|
||||||
|
it.each([true, false])(
|
||||||
|
'recovers a cached missing game even if invalidation needs retry (%s)',
|
||||||
|
async (invalidationSucceeds) => {
|
||||||
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
|
const communityId = new mongoose.Types.ObjectId();
|
||||||
|
let archived = false;
|
||||||
|
let enriched = false;
|
||||||
|
let generation = 'before';
|
||||||
|
let cached: InternalMatchDetailResponse | null = null;
|
||||||
|
const exists = jest.fn(() => query(archived ? { _id: 'archive' } : null));
|
||||||
|
const buildAndUpsert = jest.fn(async () => {
|
||||||
|
enriched = true;
|
||||||
|
});
|
||||||
|
const invalidateCommunity = jest.fn(async () => {
|
||||||
|
if (!invalidationSucceeds) return false;
|
||||||
|
cached = null;
|
||||||
|
generation = 'after';
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
const setDetail = jest.fn(
|
||||||
|
async (
|
||||||
|
key: CommunityStatsCacheKey,
|
||||||
|
value: InternalMatchDetailResponse,
|
||||||
|
) => {
|
||||||
|
expect(key.generation).toBe(generation);
|
||||||
|
cached = value;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
const service = new CommunityStatsService(
|
||||||
|
{ getModel: async () => ({ exists }) } as never,
|
||||||
|
{
|
||||||
|
get: async (key: CommunityStatsCacheKey) => {
|
||||||
|
key.generation = generation;
|
||||||
|
return cached;
|
||||||
|
},
|
||||||
|
setDetail,
|
||||||
|
invalidateCommunityWithRetry: invalidateCommunity,
|
||||||
|
} as never,
|
||||||
|
{} as never,
|
||||||
|
{ buildAndUpsert } as never,
|
||||||
|
);
|
||||||
|
const internals = service as unknown as {
|
||||||
|
getDetailRevision: () => Promise<string>;
|
||||||
|
buildBaseDataset: () => Promise<unknown>;
|
||||||
|
matchDetailInFlight: Map<string, unknown>;
|
||||||
|
};
|
||||||
|
jest
|
||||||
|
.spyOn(internals, 'getDetailRevision')
|
||||||
|
.mockResolvedValue('same-revision');
|
||||||
|
jest
|
||||||
|
.spyOn(internals, 'buildBaseDataset')
|
||||||
|
.mockImplementation(async () => ({
|
||||||
|
matches: [{ matchId: matchId.toString() }],
|
||||||
|
detailsByMatchId: new Map([
|
||||||
|
[
|
||||||
|
matchId.toString(),
|
||||||
|
[
|
||||||
|
{
|
||||||
|
gameNumber: 1,
|
||||||
|
riotMatchId: 'KR_1',
|
||||||
|
rawAvailable: enriched,
|
||||||
|
timelineLoaded: enriched,
|
||||||
|
teams: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
competition: {
|
||||||
|
projection: {
|
||||||
|
games: [
|
||||||
|
{
|
||||||
|
id: 'official-game',
|
||||||
|
displayNumber: 1,
|
||||||
|
evidence: { type: 'riot', riotMatchId: 'KR_1' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
const missing = await service.getMatchDetail({ communityId, matchId });
|
||||||
|
expect(missing.games[0].analysisAvailability).toBe('missing');
|
||||||
|
expect(await service.getMatchDetail({ communityId, matchId })).toBe(
|
||||||
|
missing,
|
||||||
|
);
|
||||||
|
expect(buildAndUpsert).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
archived = true;
|
||||||
|
const recovered = await service.getMatchDetail({ communityId, matchId });
|
||||||
|
expect(recovered.games[0]).toMatchObject({
|
||||||
|
gameId: 'official-game',
|
||||||
|
analysisAvailability: 'available',
|
||||||
|
riotMatchId: 'KR_1',
|
||||||
|
});
|
||||||
|
expect(buildAndUpsert).toHaveBeenCalledWith(matchId, {
|
||||||
|
includeTimeline: true,
|
||||||
|
});
|
||||||
|
expect(invalidateCommunity).toHaveBeenCalledWith(communityId.toString());
|
||||||
|
expect(internals.matchDetailInFlight.size).toBe(0);
|
||||||
|
expect(setDetail).toHaveBeenCalledTimes(invalidationSucceeds ? 2 : 1);
|
||||||
|
expect(await service.getMatchDetail({ communityId, matchId })).toEqual(
|
||||||
|
recovered,
|
||||||
|
);
|
||||||
|
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it('rebuilds only affected missing fragments and invalidates every affected community after the writes', async () => {
|
||||||
|
const first = new mongoose.Types.ObjectId();
|
||||||
|
const second = new mongoose.Types.ObjectId();
|
||||||
|
const fragments = [
|
||||||
|
{
|
||||||
|
matchId: new mongoose.Types.ObjectId(),
|
||||||
|
communityId: first,
|
||||||
|
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: false }],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
matchId: new mongoose.Types.ObjectId(),
|
||||||
|
communityId: first,
|
||||||
|
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: true }],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
matchId: new mongoose.Types.ObjectId(),
|
||||||
|
communityId: second,
|
||||||
|
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: false }],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const order: string[] = [];
|
||||||
|
const buildAndUpsert = jest.fn(async () => {
|
||||||
|
order.push('build');
|
||||||
|
});
|
||||||
|
const invalidateCommunity = jest.fn(async () => {
|
||||||
|
order.push('invalidate');
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
const findByRiotMatchIds = jest.fn().mockResolvedValue(fragments);
|
||||||
|
const service = new CommunityStatsService(
|
||||||
|
{
|
||||||
|
getModel: async () => ({ find: () => query([{ matchId: 'KR_1' }]) }),
|
||||||
|
} as never,
|
||||||
|
{ invalidateCommunityWithRetry: invalidateCommunity } as never,
|
||||||
|
{
|
||||||
|
findByRiotMatchIds,
|
||||||
|
findByMatch: async () => ({
|
||||||
|
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: true }],
|
||||||
|
}),
|
||||||
|
} as never,
|
||||||
|
{ buildAndUpsert } as never,
|
||||||
|
);
|
||||||
|
|
||||||
|
await service.refreshForRiotMatches(['KR_1', 'KR_1', 'KR_ABSENT']);
|
||||||
|
|
||||||
|
expect(findByRiotMatchIds).toHaveBeenCalledWith(['KR_1']);
|
||||||
|
expect(buildAndUpsert.mock.calls).toEqual([
|
||||||
|
[fragments[0].matchId],
|
||||||
|
[fragments[2].matchId],
|
||||||
|
]);
|
||||||
|
expect(invalidateCommunity.mock.calls).toEqual([
|
||||||
|
[first.toString()],
|
||||||
|
[second.toString()],
|
||||||
|
]);
|
||||||
|
expect(order).toEqual(['build', 'build', 'invalidate', 'invalidate']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not invalidate already enriched games or builds that make no progress', async () => {
|
||||||
|
const game = { riotMatchId: 'KR_1', rawAvailable: false };
|
||||||
|
const fragment = {
|
||||||
|
matchId: new mongoose.Types.ObjectId(),
|
||||||
|
communityId: new mongoose.Types.ObjectId(),
|
||||||
|
gameDetails: [game],
|
||||||
|
};
|
||||||
|
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
|
||||||
|
const invalidateCommunity = jest.fn();
|
||||||
|
const service = new CommunityStatsService(
|
||||||
|
{
|
||||||
|
getModel: async () => ({ find: () => query([{ matchId: 'KR_1' }]) }),
|
||||||
|
} as never,
|
||||||
|
{ invalidateCommunityWithRetry: invalidateCommunity } as never,
|
||||||
|
{
|
||||||
|
findByRiotMatchIds: async () => [fragment],
|
||||||
|
findByMatch: async () => fragment,
|
||||||
|
} as never,
|
||||||
|
{ buildAndUpsert } as never,
|
||||||
|
);
|
||||||
|
await service.refreshForRiotMatches(['KR_1']);
|
||||||
|
game.rawAvailable = true;
|
||||||
|
await service.refreshForRiotMatches(['KR_1']);
|
||||||
|
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
|
||||||
|
expect(invalidateCommunity).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not rebuild when raw is still absent', async () => {
|
||||||
|
const findByRiotMatchIds = jest.fn();
|
||||||
|
const buildAndUpsert = jest.fn();
|
||||||
|
const service = new CommunityStatsService(
|
||||||
|
{ getModel: async () => ({ find: () => query([]) }) } as never,
|
||||||
|
{} as never,
|
||||||
|
{ findByRiotMatchIds } as never,
|
||||||
|
{ buildAndUpsert } as never,
|
||||||
|
);
|
||||||
|
await service.refreshForRiotMatches(['KR_1']);
|
||||||
|
expect(findByRiotMatchIds).not.toHaveBeenCalled();
|
||||||
|
expect(buildAndUpsert).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('invalidates successful communities once even when another game fails mid-batch', async () => {
|
||||||
|
const communities = Array.from(
|
||||||
|
{ length: 4 },
|
||||||
|
() => new mongoose.Types.ObjectId(),
|
||||||
|
);
|
||||||
|
const fragments = [0, 1, 0, 2, 3].map((community, index) => ({
|
||||||
|
matchId: new mongoose.Types.ObjectId(),
|
||||||
|
communityId: communities[community],
|
||||||
|
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: index === 4 }],
|
||||||
|
}));
|
||||||
|
const buildAndUpsert = jest.fn(async (matchId: mongoose.Types.ObjectId) => {
|
||||||
|
const fragment = fragments.find((item) => item.matchId === matchId)!;
|
||||||
|
if (fragment === fragments[1]) throw new Error('one build fails');
|
||||||
|
fragment.gameDetails[0].rawAvailable = true;
|
||||||
|
});
|
||||||
|
const invalidate = jest.fn().mockResolvedValue(true);
|
||||||
|
const service = new CommunityStatsService(
|
||||||
|
{
|
||||||
|
getModel: async () => ({ find: () => query([{ matchId: 'KR_1' }]) }),
|
||||||
|
} as never,
|
||||||
|
{ invalidateCommunityWithRetry: invalidate } as never,
|
||||||
|
{
|
||||||
|
findByRiotMatchIds: async () => fragments,
|
||||||
|
findByMatch: async (id: mongoose.Types.ObjectId) =>
|
||||||
|
fragments.find((item) => item.matchId === id),
|
||||||
|
} as never,
|
||||||
|
{ buildAndUpsert } as never,
|
||||||
|
);
|
||||||
|
await service.refreshForRiotMatches(['KR_1']);
|
||||||
|
expect(buildAndUpsert).toHaveBeenCalledTimes(4);
|
||||||
|
expect(invalidate.mock.calls).toEqual([
|
||||||
|
[communities[0].toString()],
|
||||||
|
[communities[2].toString()],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('backs off raw recovery that makes no progress and does not invalidate the community', async () => {
|
||||||
|
let now = 1000;
|
||||||
|
const clock = jest.spyOn(Date, 'now').mockImplementation(() => now);
|
||||||
|
try {
|
||||||
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
|
const communityId = new mongoose.Types.ObjectId();
|
||||||
|
let cached: InternalMatchDetailResponse | null = null;
|
||||||
|
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
|
||||||
|
const invalidate = jest.fn();
|
||||||
|
const service = new CommunityStatsService(
|
||||||
|
{
|
||||||
|
getModel: async () => ({ exists: () => query({ _id: 'archive' }) }),
|
||||||
|
} as never,
|
||||||
|
{
|
||||||
|
get: async () => cached,
|
||||||
|
setDetail: async (
|
||||||
|
_key: unknown,
|
||||||
|
value: InternalMatchDetailResponse,
|
||||||
|
) => {
|
||||||
|
cached = value;
|
||||||
|
},
|
||||||
|
invalidateCommunityWithRetry: invalidate,
|
||||||
|
} as never,
|
||||||
|
{} as never,
|
||||||
|
{ buildAndUpsert } as never,
|
||||||
|
);
|
||||||
|
const internals = service as unknown as {
|
||||||
|
getDetailRevision: () => Promise<string>;
|
||||||
|
buildBaseDataset: () => Promise<unknown>;
|
||||||
|
};
|
||||||
|
jest
|
||||||
|
.spyOn(internals, 'getDetailRevision')
|
||||||
|
.mockResolvedValue('same-revision');
|
||||||
|
jest.spyOn(internals, 'buildBaseDataset').mockResolvedValue({
|
||||||
|
matches: [{ matchId: matchId.toString() }],
|
||||||
|
detailsByMatchId: new Map([
|
||||||
|
[
|
||||||
|
matchId.toString(),
|
||||||
|
[
|
||||||
|
{
|
||||||
|
gameNumber: 1,
|
||||||
|
riotMatchId: 'KR_1',
|
||||||
|
rawAvailable: false,
|
||||||
|
timelineLoaded: false,
|
||||||
|
teams: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
});
|
||||||
|
await service.getMatchDetail({ communityId, matchId });
|
||||||
|
await service.getMatchDetail({ communityId, matchId });
|
||||||
|
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
|
||||||
|
now += 60_000;
|
||||||
|
await service.getMatchDetail({ communityId, matchId });
|
||||||
|
expect(buildAndUpsert).toHaveBeenCalledTimes(2);
|
||||||
|
expect(invalidate).not.toHaveBeenCalled();
|
||||||
|
} finally {
|
||||||
|
clock.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function query<T>(value: T) {
|
||||||
|
return {
|
||||||
|
select() {
|
||||||
|
return this;
|
||||||
|
},
|
||||||
|
lean() {
|
||||||
|
return this;
|
||||||
|
},
|
||||||
|
exec: async () => value,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,4 +1,10 @@
|
|||||||
import { Controller, Get, Param, Query } from '@nestjs/common';
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
Param,
|
||||||
|
Query,
|
||||||
|
} from '@nestjs/common';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
|
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
|
||||||
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
||||||
@@ -9,6 +15,15 @@ import type { CommunityStatsFilters } from './community-stats.types';
|
|||||||
export class CommunityStatsController {
|
export class CommunityStatsController {
|
||||||
constructor(private readonly communityStatsService: CommunityStatsService) {}
|
constructor(private readonly communityStatsService: CommunityStatsService) {}
|
||||||
|
|
||||||
|
@Get('internal-stats/seasons')
|
||||||
|
@AllowPublicAccess()
|
||||||
|
public getSeasons(
|
||||||
|
@Param('communityId', ParseObjectIdPipe)
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
) {
|
||||||
|
return this.communityStatsService.getSeasons(communityId);
|
||||||
|
}
|
||||||
|
|
||||||
@Get('internal-stats/matches')
|
@Get('internal-stats/matches')
|
||||||
@AllowPublicAccess()
|
@AllowPublicAccess()
|
||||||
public getMatches(
|
public getMatches(
|
||||||
@@ -20,7 +35,30 @@ export class CommunityStatsController {
|
|||||||
@Query('championId') championId?: string,
|
@Query('championId') championId?: string,
|
||||||
@Query('cursor') cursor?: string,
|
@Query('cursor') cursor?: string,
|
||||||
@Query('limit') limit?: string,
|
@Query('limit') limit?: string,
|
||||||
|
@Query('q') query?: string,
|
||||||
|
@Query('format') format?: string,
|
||||||
|
@Query('playerId') playerId?: string,
|
||||||
|
@Query('cursorMatchId') cursorMatchId?: string,
|
||||||
) {
|
) {
|
||||||
|
if (format !== undefined && format !== 'pair' && format !== 'tournament') {
|
||||||
|
throw new BadRequestException('Invalid format.');
|
||||||
|
}
|
||||||
|
if (playerId !== undefined && !mongoose.isObjectIdOrHexString(playerId)) {
|
||||||
|
throw new BadRequestException('Invalid playerId.');
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
cursorMatchId !== undefined &&
|
||||||
|
(!mongoose.isObjectIdOrHexString(cursorMatchId) ||
|
||||||
|
this.toNumber(cursor) === undefined)
|
||||||
|
) {
|
||||||
|
throw new BadRequestException('Invalid cursor.');
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
cursor !== undefined &&
|
||||||
|
Number.isNaN(new Date(this.toNumber(cursor) ?? NaN).getTime())
|
||||||
|
) {
|
||||||
|
throw new BadRequestException('Invalid cursor.');
|
||||||
|
}
|
||||||
return this.communityStatsService.getMatches({
|
return this.communityStatsService.getMatches({
|
||||||
communityId,
|
communityId,
|
||||||
filters: this.toFilters({
|
filters: this.toFilters({
|
||||||
@@ -30,6 +68,10 @@ export class CommunityStatsController {
|
|||||||
championId,
|
championId,
|
||||||
cursor,
|
cursor,
|
||||||
limit,
|
limit,
|
||||||
|
query,
|
||||||
|
format,
|
||||||
|
playerId,
|
||||||
|
cursorMatchId,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -43,10 +85,11 @@ export class CommunityStatsController {
|
|||||||
@Query('from') from?: string,
|
@Query('from') from?: string,
|
||||||
@Query('to') to?: string,
|
@Query('to') to?: string,
|
||||||
@Query('championId') championId?: string,
|
@Query('championId') championId?: string,
|
||||||
|
@Query('q') query?: string,
|
||||||
) {
|
) {
|
||||||
return this.communityStatsService.getLeaderboard({
|
return this.communityStatsService.getLeaderboard({
|
||||||
communityId,
|
communityId,
|
||||||
filters: this.toFilters({ seasonId, from, to, championId }),
|
filters: this.toFilters({ seasonId, from, to, championId, query }),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,7 +153,17 @@ export class CommunityStatsController {
|
|||||||
championId?: string;
|
championId?: string;
|
||||||
cursor?: string;
|
cursor?: string;
|
||||||
limit?: string;
|
limit?: string;
|
||||||
|
query?: string;
|
||||||
|
format?: CommunityStatsFilters['format'];
|
||||||
|
playerId?: string;
|
||||||
|
cursorMatchId?: string;
|
||||||
}): CommunityStatsFilters {
|
}): CommunityStatsFilters {
|
||||||
|
if (
|
||||||
|
params.query !== undefined &&
|
||||||
|
(typeof params.query !== 'string' || params.query.length > 100)
|
||||||
|
) {
|
||||||
|
throw new BadRequestException('Invalid search query.');
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
seasonId: params.seasonId,
|
seasonId: params.seasonId,
|
||||||
from: params.from,
|
from: params.from,
|
||||||
@@ -118,6 +171,10 @@ export class CommunityStatsController {
|
|||||||
championId: this.toNumber(params.championId),
|
championId: this.toNumber(params.championId),
|
||||||
cursor: this.toNumber(params.cursor),
|
cursor: this.toNumber(params.cursor),
|
||||||
limit: this.toNumber(params.limit),
|
limit: this.toNumber(params.limit),
|
||||||
|
query: params.query?.trim(),
|
||||||
|
format: params.format,
|
||||||
|
playerId: params.playerId,
|
||||||
|
cursorMatchId: params.cursorMatchId,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { forwardRef, Module } from '@nestjs/common';
|
||||||
import { RiotModule } from '../riot/riot.module';
|
import { RiotModule } from '../riot/riot.module';
|
||||||
import { CommunityStatsCacheService } from './community-stats-cache.service';
|
import { CommunityStatsCacheService } from './community-stats-cache.service';
|
||||||
import { CommunityStatsController } from './community-stats.controller';
|
import { CommunityStatsController } from './community-stats.controller';
|
||||||
@@ -8,7 +8,7 @@ import { MatchStatsRepository } from './match-stats.repository';
|
|||||||
import { MatchStatsService } from './match-stats.service';
|
import { MatchStatsService } from './match-stats.service';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [RiotModule],
|
imports: [forwardRef(() => RiotModule)],
|
||||||
controllers: [CommunityStatsController],
|
controllers: [CommunityStatsController],
|
||||||
providers: [
|
providers: [
|
||||||
CommunityStatsService,
|
CommunityStatsService,
|
||||||
|
|||||||
@@ -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,
|
||||||
@@ -83,6 +86,244 @@ function record(matchId: mongoose.Types.ObjectId): InternalRecord {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe('CommunityStatsService', () => {
|
describe('CommunityStatsService', () => {
|
||||||
|
it('reads the official result again on a filtered page cache hit and excludes games from stale revisions', async () => {
|
||||||
|
const communityId = new mongoose.Types.ObjectId();
|
||||||
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
|
const competitionId = new mongoose.Types.ObjectId();
|
||||||
|
const playerId = new mongoose.Types.ObjectId().toString();
|
||||||
|
const scheduledAt = new Date('2026-06-18T12:00:00Z');
|
||||||
|
const matchCard = {
|
||||||
|
matchId: matchId.toString(),
|
||||||
|
scheduledAt: scheduledAt.toISOString(),
|
||||||
|
games: [{ gameNumber: 1, winnerTeamIndex: 1 }],
|
||||||
|
};
|
||||||
|
const findMatchPage = jest.fn().mockResolvedValue([
|
||||||
|
{
|
||||||
|
matchId,
|
||||||
|
scheduledAt,
|
||||||
|
matchCard,
|
||||||
|
gameDetails: [{ gameNumber: 1, gameCreation: 1000 }],
|
||||||
|
sourceCompetitionId: competitionId,
|
||||||
|
sourceRevision: 4,
|
||||||
|
},
|
||||||
|
{ matchId: new mongoose.Types.ObjectId() },
|
||||||
|
]);
|
||||||
|
const source = {
|
||||||
|
_id: competitionId,
|
||||||
|
matchId,
|
||||||
|
communityId,
|
||||||
|
revision: 4,
|
||||||
|
createdAt: scheduledAt,
|
||||||
|
updatedAt: scheduledAt,
|
||||||
|
teams: [],
|
||||||
|
projection: {
|
||||||
|
phase: 'completed',
|
||||||
|
formatType: 'double-elimination',
|
||||||
|
series: [],
|
||||||
|
outcome: { type: 'double-elimination', championTeamId: 'winner' },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const find = jest.fn().mockReturnValue({
|
||||||
|
select: () => ({ lean: () => ({ exec: async () => [source] }) }),
|
||||||
|
});
|
||||||
|
let cachedPage: unknown = null;
|
||||||
|
const service = new CommunityStatsService(
|
||||||
|
{
|
||||||
|
getModel: async (name: string) =>
|
||||||
|
name === 'community'
|
||||||
|
? { findById: () => ({ exec: async () => ({ _id: communityId }) }) }
|
||||||
|
: { find },
|
||||||
|
} as unknown as ConnectionService,
|
||||||
|
{
|
||||||
|
get: async () => cachedPage,
|
||||||
|
set: async (_key: unknown, page: unknown) => {
|
||||||
|
cachedPage = JSON.parse(JSON.stringify(page));
|
||||||
|
},
|
||||||
|
} as unknown as CommunityStatsCacheService,
|
||||||
|
{ findMatchPage } as unknown as MatchStatsRepository,
|
||||||
|
{} as MatchStatsService,
|
||||||
|
);
|
||||||
|
jest
|
||||||
|
.spyOn(
|
||||||
|
service as unknown as {
|
||||||
|
repairCommunityFragments: () => Promise<number>;
|
||||||
|
},
|
||||||
|
'repairCommunityFragments',
|
||||||
|
)
|
||||||
|
.mockResolvedValue(0);
|
||||||
|
|
||||||
|
const params = {
|
||||||
|
communityId,
|
||||||
|
filters: {
|
||||||
|
seasonId: 'all',
|
||||||
|
query: '결승',
|
||||||
|
format: 'tournament' as const,
|
||||||
|
playerId,
|
||||||
|
limit: 1,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const initial = await service.getMatches(params);
|
||||||
|
expect(initial.matches[0]).toMatchObject({
|
||||||
|
games: [{ gameNumber: 1 }],
|
||||||
|
resultPresentation: {
|
||||||
|
type: 'official',
|
||||||
|
phase: 'completed',
|
||||||
|
sourceRevision: 4,
|
||||||
|
outcome: { championTeamId: 'winner' },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
Object.assign(source, {
|
||||||
|
revision: 5,
|
||||||
|
projection: {
|
||||||
|
...source.projection,
|
||||||
|
phase: 'running',
|
||||||
|
outcome: undefined,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const result = await service.getMatches(params);
|
||||||
|
|
||||||
|
expect(findMatchPage).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
query: '결승',
|
||||||
|
format: 'tournament',
|
||||||
|
playerId,
|
||||||
|
limit: 2,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(find).toHaveBeenCalledWith({
|
||||||
|
communityId,
|
||||||
|
matchId: { $in: [matchId] },
|
||||||
|
});
|
||||||
|
expect(findMatchPage).toHaveBeenCalledTimes(1);
|
||||||
|
expect(find).toHaveBeenCalledTimes(2);
|
||||||
|
expect(result.matches[0]).toMatchObject({
|
||||||
|
games: [],
|
||||||
|
resultPresentation: {
|
||||||
|
type: 'official',
|
||||||
|
competitionId: competitionId.toString(),
|
||||||
|
sourceRevision: 5,
|
||||||
|
phase: 'running',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(result.nextCursor).toBe(scheduledAt.getTime());
|
||||||
|
expect(result.nextCursorMatchId).toBe(matchId.toString());
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(['legacy', 'riot', 'unlinked'] as const)(
|
||||||
|
'preserves the scoreboard without retrying a missing Riot archive for %s evidence',
|
||||||
|
async (type) => {
|
||||||
|
const communityId = new mongoose.Types.ObjectId();
|
||||||
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
|
const match = { matchId: matchId.toString() };
|
||||||
|
const participant = record(matchId);
|
||||||
|
const matchKey = type === 'legacy' ? 'legacy-reference' : 'KR_1';
|
||||||
|
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
|
||||||
|
const set = jest.fn();
|
||||||
|
const setDetail = jest.fn();
|
||||||
|
const service = new CommunityStatsService(
|
||||||
|
{
|
||||||
|
getModel: async () => ({ exists: () => ({ exec: async () => null }) }),
|
||||||
|
} as unknown as ConnectionService,
|
||||||
|
{
|
||||||
|
get: async () => null,
|
||||||
|
set,
|
||||||
|
setDetail,
|
||||||
|
} as unknown as CommunityStatsCacheService,
|
||||||
|
{} as MatchStatsRepository,
|
||||||
|
{ buildAndUpsert } as unknown as MatchStatsService,
|
||||||
|
);
|
||||||
|
jest
|
||||||
|
.spyOn(
|
||||||
|
service as unknown as { getDetailRevision: () => Promise<string> },
|
||||||
|
'getDetailRevision',
|
||||||
|
)
|
||||||
|
.mockResolvedValue('revision-1');
|
||||||
|
(service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset =
|
||||||
|
jest.fn().mockResolvedValue({
|
||||||
|
matches: [match],
|
||||||
|
detailsByMatchId: new Map([
|
||||||
|
[
|
||||||
|
match.matchId,
|
||||||
|
[
|
||||||
|
{
|
||||||
|
gameNumber: 1,
|
||||||
|
riotMatchId: matchKey,
|
||||||
|
gameCreation: 1000,
|
||||||
|
gameDuration: 1800,
|
||||||
|
rawAvailable: false,
|
||||||
|
timelineLoaded: false,
|
||||||
|
teams: [
|
||||||
|
{
|
||||||
|
teamIndex: 1,
|
||||||
|
side: 'blue',
|
||||||
|
win: true,
|
||||||
|
objectives: objectives(),
|
||||||
|
participants: [participant],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
competition:
|
||||||
|
type === 'unlinked'
|
||||||
|
? undefined
|
||||||
|
: {
|
||||||
|
projection: {
|
||||||
|
games: [
|
||||||
|
{
|
||||||
|
id: 'game-1',
|
||||||
|
seriesId: 'series-1',
|
||||||
|
gameSlotId: 'slot-1',
|
||||||
|
ordinal: 1,
|
||||||
|
displayNumber: 1,
|
||||||
|
evidence:
|
||||||
|
type === 'legacy'
|
||||||
|
? { type, legacyReference: matchKey }
|
||||||
|
: { type, riotMatchId: matchKey },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await service.getMatchDetail({ communityId, matchId });
|
||||||
|
const afterCacheMiss = await service.getMatchDetail({
|
||||||
|
communityId,
|
||||||
|
matchId,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.games).toHaveLength(1);
|
||||||
|
expect(response.games).toMatchObject([
|
||||||
|
{
|
||||||
|
...(type === 'unlinked' ? {} : { gameId: 'game-1' }),
|
||||||
|
analysisAvailability: 'missing',
|
||||||
|
teams: [
|
||||||
|
{
|
||||||
|
win: true,
|
||||||
|
participants: [
|
||||||
|
{
|
||||||
|
kills: participant.kills,
|
||||||
|
deaths: participant.deaths,
|
||||||
|
assists: participant.assists,
|
||||||
|
championId: participant.championId,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
expect(afterCacheMiss).toEqual(response);
|
||||||
|
expect(buildAndUpsert).not.toHaveBeenCalled();
|
||||||
|
expect(set).not.toHaveBeenCalled();
|
||||||
|
expect(setDetail).toHaveBeenCalledTimes(2);
|
||||||
|
expect(setDetail).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ field: expect.stringContaining(':r8:') }),
|
||||||
|
response,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
it('ignores detail caches missing unified events or containing invalid checkpoints', async () => {
|
it('ignores detail caches missing unified events or containing invalid checkpoints', async () => {
|
||||||
const communityId = new mongoose.Types.ObjectId();
|
const communityId = new mongoose.Types.ObjectId();
|
||||||
const matchId = new mongoose.Types.ObjectId();
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
@@ -219,7 +460,13 @@ describe('CommunityStatsService', () => {
|
|||||||
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
|
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
|
||||||
} as unknown as jest.Mocked<MatchStatsService>;
|
} as unknown as jest.Mocked<MatchStatsService>;
|
||||||
const service = new CommunityStatsService(
|
const service = new CommunityStatsService(
|
||||||
{} as ConnectionService,
|
{
|
||||||
|
getModel: jest.fn().mockResolvedValue({
|
||||||
|
findOne: () => ({
|
||||||
|
select: () => ({ lean: () => ({ exec: async () => null }) }),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
} as unknown as ConnectionService,
|
||||||
cacheService,
|
cacheService,
|
||||||
{} as MatchStatsRepository,
|
{} as MatchStatsRepository,
|
||||||
matchStatsService,
|
matchStatsService,
|
||||||
@@ -281,7 +528,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(':r8:') }),
|
||||||
invalidCheckpointResponse,
|
invalidCheckpointResponse,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -306,6 +553,7 @@ describe('CommunityStatsService', () => {
|
|||||||
gameCreation: 1_000,
|
gameCreation: 1_000,
|
||||||
gameDuration: 1_800,
|
gameDuration: 1_800,
|
||||||
winnerSide: 'blue',
|
winnerSide: 'blue',
|
||||||
|
rawAvailable: true,
|
||||||
timelineLoaded: false,
|
timelineLoaded: false,
|
||||||
timeline: [],
|
timeline: [],
|
||||||
objectiveEvents: [],
|
objectiveEvents: [],
|
||||||
@@ -338,7 +586,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 +594,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();
|
||||||
},
|
},
|
||||||
@@ -358,7 +606,13 @@ describe('CommunityStatsService', () => {
|
|||||||
} as unknown as jest.Mocked<CommunityStatsCacheService>;
|
} as unknown as jest.Mocked<CommunityStatsCacheService>;
|
||||||
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
|
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
|
||||||
const service = new CommunityStatsService(
|
const service = new CommunityStatsService(
|
||||||
{} as ConnectionService,
|
{
|
||||||
|
getModel: jest.fn().mockResolvedValue({
|
||||||
|
findOne: () => ({
|
||||||
|
select: () => ({ lean: () => ({ exec: async () => null }) }),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
} as unknown as ConnectionService,
|
||||||
cacheService,
|
cacheService,
|
||||||
{} as MatchStatsRepository,
|
{} as MatchStatsRepository,
|
||||||
{ buildAndUpsert } as unknown as MatchStatsService,
|
{ buildAndUpsert } as unknown as MatchStatsService,
|
||||||
@@ -375,9 +629,13 @@ describe('CommunityStatsService', () => {
|
|||||||
const backedOff = await service.getMatchDetail({ communityId, matchId });
|
const backedOff = await service.getMatchDetail({ communityId, matchId });
|
||||||
|
|
||||||
expect(backedOff).toBe(fallback);
|
expect(backedOff).toBe(fallback);
|
||||||
|
expect(fallback.games[0].analysisAvailability).toBe('available');
|
||||||
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
|
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
|
||||||
|
expect(buildAndUpsert).toHaveBeenCalledWith(matchId, {
|
||||||
|
includeTimeline: true,
|
||||||
|
});
|
||||||
expect(set).toHaveBeenCalledWith(
|
expect(set).toHaveBeenCalledWith(
|
||||||
expect.stringContaining(':r4:'),
|
expect.objectContaining({ field: expect.stringContaining(':r8:') }),
|
||||||
fallback,
|
fallback,
|
||||||
60,
|
60,
|
||||||
);
|
);
|
||||||
@@ -389,7 +647,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(':r8:') }),
|
||||||
recovered,
|
recovered,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -456,7 +714,13 @@ describe('CommunityStatsService', () => {
|
|||||||
setDetail,
|
setDetail,
|
||||||
} as unknown as jest.Mocked<CommunityStatsCacheService>;
|
} as unknown as jest.Mocked<CommunityStatsCacheService>;
|
||||||
const service = new CommunityStatsService(
|
const service = new CommunityStatsService(
|
||||||
{} as ConnectionService,
|
{
|
||||||
|
getModel: jest.fn().mockResolvedValue({
|
||||||
|
findOne: () => ({
|
||||||
|
select: () => ({ lean: () => ({ exec: async () => null }) }),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
} as unknown as ConnectionService,
|
||||||
cacheService,
|
cacheService,
|
||||||
{} as MatchStatsRepository,
|
{} as MatchStatsRepository,
|
||||||
{} as MatchStatsService,
|
{} as MatchStatsService,
|
||||||
@@ -547,7 +811,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,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -1,3 +1,11 @@
|
|||||||
|
import type {
|
||||||
|
GameAnalysisAvailability,
|
||||||
|
GameId,
|
||||||
|
GameSlotId,
|
||||||
|
InternalMatchCompetition,
|
||||||
|
InternalMatchResultPresentation,
|
||||||
|
SeriesId,
|
||||||
|
} from '@lolympus/contracts';
|
||||||
import type {
|
import type {
|
||||||
MatchStatsParticipantCheckpoints,
|
MatchStatsParticipantCheckpoints,
|
||||||
MatchStatsItemBuildEvent,
|
MatchStatsItemBuildEvent,
|
||||||
@@ -19,11 +27,16 @@ export interface CommunityStatsFilters {
|
|||||||
championId?: number;
|
championId?: number;
|
||||||
cursor?: number;
|
cursor?: number;
|
||||||
limit?: number;
|
limit?: number;
|
||||||
|
query?: string;
|
||||||
|
format?: 'pair' | 'tournament';
|
||||||
|
playerId?: string;
|
||||||
|
cursorMatchId?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface InternalMatchListResponse {
|
export interface InternalMatchListResponse {
|
||||||
matches: InternalMatchCardView[];
|
matches: InternalMatchCardView[];
|
||||||
nextCursor: number | null;
|
nextCursor: number | null;
|
||||||
|
nextCursorMatchId?: string;
|
||||||
season: HistorySeasonDto;
|
season: HistorySeasonDto;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,6 +47,7 @@ export interface InternalMatchCardView {
|
|||||||
status: 'finished' | 'in-progress';
|
status: 'finished' | 'in-progress';
|
||||||
gameCount: number;
|
gameCount: number;
|
||||||
winnerTeamIndex?: number;
|
winnerTeamIndex?: number;
|
||||||
|
resultPresentation?: InternalMatchResultPresentation;
|
||||||
seriesResults: Array<{
|
seriesResults: Array<{
|
||||||
teamAIndex: number;
|
teamAIndex: number;
|
||||||
teamBIndex: number;
|
teamBIndex: number;
|
||||||
@@ -64,11 +78,13 @@ export interface InternalMatchCardView {
|
|||||||
export interface LeaderboardResponse {
|
export interface LeaderboardResponse {
|
||||||
rows: LeaderboardRow[];
|
rows: LeaderboardRow[];
|
||||||
season: HistorySeasonDto;
|
season: HistorySeasonDto;
|
||||||
|
matchedUserIds?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface LeaderboardRow {
|
export interface LeaderboardRow {
|
||||||
userId: string;
|
userId: string;
|
||||||
summonerName: string;
|
summonerName: string;
|
||||||
|
tagLine?: string;
|
||||||
profileIconId: number;
|
profileIconId: number;
|
||||||
games: number;
|
games: number;
|
||||||
wins: number;
|
wins: number;
|
||||||
@@ -105,6 +121,7 @@ export interface TeamInsightsResponse {
|
|||||||
red: number;
|
red: number;
|
||||||
bluePicks: number;
|
bluePicks: number;
|
||||||
redPicks: number;
|
redPicks: number;
|
||||||
|
confirmed: { sampleSize: number; blue: number; red: number };
|
||||||
};
|
};
|
||||||
topKda: LeaderHighlight | null;
|
topKda: LeaderHighlight | null;
|
||||||
mostKills: LeaderHighlight | null;
|
mostKills: LeaderHighlight | null;
|
||||||
@@ -116,8 +133,14 @@ export interface TeamInsightsResponse {
|
|||||||
|
|
||||||
export interface InternalMatchDetailResponse {
|
export interface InternalMatchDetailResponse {
|
||||||
match: InternalMatchCardView;
|
match: InternalMatchCardView;
|
||||||
|
competition?: InternalMatchCompetition;
|
||||||
games: Array<{
|
games: Array<{
|
||||||
gameNumber: number;
|
gameNumber: number;
|
||||||
|
gameId?: GameId;
|
||||||
|
analysisAvailability?: GameAnalysisAvailability;
|
||||||
|
gameSlotId?: GameSlotId;
|
||||||
|
seriesId?: SeriesId;
|
||||||
|
ordinal?: number;
|
||||||
riotMatchId: string;
|
riotMatchId: string;
|
||||||
gameCreation: number;
|
gameCreation: number;
|
||||||
gameDuration: number;
|
gameDuration: 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),
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { readMultiKills } from '../riot/riot-multi-kill';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import type {
|
import type {
|
||||||
MatchDocument,
|
MatchDocument,
|
||||||
@@ -183,6 +184,7 @@ export class MatchStatsFragmentBuilder {
|
|||||||
winnerSide: game.winnerSide,
|
winnerSide: game.winnerSide,
|
||||||
timeline: this.toTimeline(raw, rawTeamIdBySide, usableTimeline),
|
timeline: this.toTimeline(raw, rawTeamIdBySide, usableTimeline),
|
||||||
timelineLoaded: Boolean(usableTimeline),
|
timelineLoaded: Boolean(usableTimeline),
|
||||||
|
rawAvailable: true,
|
||||||
objectiveEvents,
|
objectiveEvents,
|
||||||
timelineEvents,
|
timelineEvents,
|
||||||
teams: (['blue', 'red'] as TeamSide[]).map((side) => {
|
teams: (['blue', 'red'] as TeamSide[]).map((side) => {
|
||||||
@@ -253,6 +255,7 @@ export class MatchStatsFragmentBuilder {
|
|||||||
winnerSide: game.winnerSide,
|
winnerSide: game.winnerSide,
|
||||||
timeline: [],
|
timeline: [],
|
||||||
timelineLoaded: false,
|
timelineLoaded: false,
|
||||||
|
rawAvailable: false,
|
||||||
objectiveEvents: [],
|
objectiveEvents: [],
|
||||||
timelineEvents: [],
|
timelineEvents: [],
|
||||||
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
|
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
|
||||||
@@ -349,6 +352,8 @@ export class MatchStatsFragmentBuilder {
|
|||||||
rawParticipant?.individualPosition ||
|
rawParticipant?.individualPosition ||
|
||||||
'',
|
'',
|
||||||
kills: participant.kills,
|
kills: participant.kills,
|
||||||
|
multiKills: readMultiKills(rawParticipant),
|
||||||
|
tier: snapshot?.tier,
|
||||||
deaths: participant.deaths,
|
deaths: participant.deaths,
|
||||||
assists: participant.assists,
|
assists: participant.assists,
|
||||||
win: participant.win,
|
win: participant.win,
|
||||||
|
|||||||
@@ -0,0 +1,173 @@
|
|||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
|
||||||
|
import { MatchStatsRepository } from './match-stats.repository';
|
||||||
|
import { MatchStatsService } from './match-stats.service';
|
||||||
|
import { MATCH_STATS_BUILDER_VERSION } from './match-stats.types';
|
||||||
|
|
||||||
|
describe('MatchStatsService outbox idempotency', () => {
|
||||||
|
it('reuses the latest stored revision when an older outbox event is delivered', async () => {
|
||||||
|
const h = createHarness();
|
||||||
|
h.isCurrent.mockResolvedValue(true);
|
||||||
|
|
||||||
|
await h.service.buildAndUpsert(h.matchId, { sourceRevision: 10 });
|
||||||
|
|
||||||
|
expect(h.isCurrent).toHaveBeenCalledWith({
|
||||||
|
matchId: h.matchId,
|
||||||
|
sourceCompetitionId: h.competitionId,
|
||||||
|
sourceRevision: 12,
|
||||||
|
projectorVersion: 3,
|
||||||
|
builderVersion: MATCH_STATS_BUILDER_VERSION,
|
||||||
|
});
|
||||||
|
expect(h.riotFind).not.toHaveBeenCalled();
|
||||||
|
expect(h.builder.buildFragment).not.toHaveBeenCalled();
|
||||||
|
expect(h.upsert).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('builds once across repeated deliveries after the write succeeds', async () => {
|
||||||
|
const h = createHarness();
|
||||||
|
h.upsert.mockImplementation(async () => {
|
||||||
|
h.isCurrent.mockResolvedValue(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
await h.service.buildAndUpsert(h.matchId, { sourceRevision: 12 });
|
||||||
|
await h.service.buildAndUpsert(h.matchId, { sourceRevision: 12 });
|
||||||
|
|
||||||
|
expect(h.riotFind).toHaveBeenCalledTimes(1);
|
||||||
|
expect(h.builder.buildFragment).toHaveBeenCalledTimes(1);
|
||||||
|
expect(h.upsert).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('retries a failed write without treating an attempted build as complete', async () => {
|
||||||
|
const h = createHarness();
|
||||||
|
h.upsert.mockRejectedValueOnce(new Error('database unavailable'));
|
||||||
|
await expect(
|
||||||
|
h.service.buildAndUpsert(h.matchId, { sourceRevision: 12 }),
|
||||||
|
).rejects.toThrow('database unavailable');
|
||||||
|
|
||||||
|
await h.service.buildAndUpsert(h.matchId, { sourceRevision: 12 });
|
||||||
|
|
||||||
|
expect(h.builder.buildFragment).toHaveBeenCalledTimes(2);
|
||||||
|
expect(h.upsert).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([{}, { sourceRevision: 12, includeTimeline: true }])(
|
||||||
|
'still performs explicit rebuilds and timeline hydration (%j)',
|
||||||
|
async (options) => {
|
||||||
|
const h = createHarness();
|
||||||
|
h.isCurrent.mockResolvedValue(true);
|
||||||
|
|
||||||
|
await h.service.buildAndUpsert(h.matchId, options);
|
||||||
|
|
||||||
|
expect(h.isCurrent).not.toHaveBeenCalled();
|
||||||
|
expect(h.builder.buildFragment).toHaveBeenCalledTimes(1);
|
||||||
|
expect(h.upsert).toHaveBeenCalledTimes(1);
|
||||||
|
if ('includeTimeline' in options) {
|
||||||
|
expect(h.getMatchTimeline).toHaveBeenCalledWith('KR_1', {
|
||||||
|
region: 'asia',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it('deletes reversed zero-game stats even if their versions were current', async () => {
|
||||||
|
const h = createHarness();
|
||||||
|
h.competition.projection.games = [];
|
||||||
|
h.isCurrent.mockResolvedValue(true);
|
||||||
|
|
||||||
|
await h.service.buildAndUpsert(h.matchId, { sourceRevision: 12 });
|
||||||
|
|
||||||
|
expect(h.isCurrent).not.toHaveBeenCalled();
|
||||||
|
expect(h.deleteByMatch).toHaveBeenCalledWith(h.matchId, {
|
||||||
|
sourceCompetitionId: h.competitionId,
|
||||||
|
sourceRevision: 12,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function createHarness() {
|
||||||
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
|
const competitionId = new mongoose.Types.ObjectId();
|
||||||
|
const teamAId = new mongoose.Types.ObjectId();
|
||||||
|
const teamBId = new mongoose.Types.ObjectId();
|
||||||
|
const match = {
|
||||||
|
_id: matchId,
|
||||||
|
communityId: new mongoose.Types.ObjectId(),
|
||||||
|
status: 'in-progress',
|
||||||
|
scheduledAt: new Date(),
|
||||||
|
teams: [],
|
||||||
|
};
|
||||||
|
const competition = {
|
||||||
|
_id: competitionId,
|
||||||
|
revision: 12,
|
||||||
|
projectorVersion: 3,
|
||||||
|
teams: [
|
||||||
|
{ teamId: teamAId, displayOrder: 1 },
|
||||||
|
{ teamId: teamBId, displayOrder: 2 },
|
||||||
|
],
|
||||||
|
projection: {
|
||||||
|
phase: 'running',
|
||||||
|
games: [
|
||||||
|
{
|
||||||
|
displayNumber: 1,
|
||||||
|
evidence: { type: 'riot', riotMatchId: 'KR_1' },
|
||||||
|
teams: { blue: { teamId: teamAId }, red: { teamId: teamBId } },
|
||||||
|
winnerTeamId: teamAId,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const riotFind = jest.fn(() => query([{ matchId: 'KR_1', raw: {} }]));
|
||||||
|
const models = {
|
||||||
|
match: { findById: () => query(match) },
|
||||||
|
competition: { findOne: () => query(competition) },
|
||||||
|
riotMatch: { find: riotFind },
|
||||||
|
community: { findById: () => query({ riotRegion: 'asia' }) },
|
||||||
|
};
|
||||||
|
const connection = {
|
||||||
|
getModel: async (name: keyof typeof models) => models[name],
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const isCurrent = jest.fn().mockResolvedValue(false);
|
||||||
|
const upsert = jest.fn().mockResolvedValue(undefined);
|
||||||
|
const deleteByMatch = jest.fn().mockResolvedValue(undefined);
|
||||||
|
const repository = {
|
||||||
|
hasCurrentCompetitionFragment: isCurrent,
|
||||||
|
upsert,
|
||||||
|
deleteByMatch,
|
||||||
|
} as unknown as MatchStatsRepository;
|
||||||
|
const builder = {
|
||||||
|
buildFragment: jest.fn().mockReturnValue({
|
||||||
|
matchCard: {},
|
||||||
|
records: [],
|
||||||
|
gameDetails: [],
|
||||||
|
userIds: [],
|
||||||
|
championIds: [],
|
||||||
|
gameCreationMin: 1,
|
||||||
|
gameCreationMax: 2,
|
||||||
|
}),
|
||||||
|
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
|
||||||
|
const getMatchTimeline = jest.fn().mockResolvedValue(undefined);
|
||||||
|
const service = new MatchStatsService(connection, repository, builder, {
|
||||||
|
getMatchTimeline,
|
||||||
|
} as never);
|
||||||
|
return {
|
||||||
|
service,
|
||||||
|
matchId,
|
||||||
|
competitionId,
|
||||||
|
competition,
|
||||||
|
isCurrent,
|
||||||
|
upsert,
|
||||||
|
deleteByMatch,
|
||||||
|
riotFind,
|
||||||
|
builder,
|
||||||
|
getMatchTimeline,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function query<T>(value: T) {
|
||||||
|
return {
|
||||||
|
select: jest.fn().mockReturnThis(),
|
||||||
|
lean: jest.fn().mockReturnThis(),
|
||||||
|
exec: async () => value,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -4,6 +4,35 @@ import type { MatchStats } from '../global/database/schema';
|
|||||||
import { MatchStatsRepository } from './match-stats.repository';
|
import { MatchStatsRepository } from './match-stats.repository';
|
||||||
|
|
||||||
describe('MatchStatsRepository', () => {
|
describe('MatchStatsRepository', () => {
|
||||||
|
it.each([null, { _id: new Types.ObjectId() }])(
|
||||||
|
'checks persisted source identity and every build version without loading payloads (%j)',
|
||||||
|
async (stored) => {
|
||||||
|
const exists = jest.fn(() => ({ exec: async () => stored }));
|
||||||
|
const connection = {
|
||||||
|
getModel: jest.fn().mockResolvedValue({ exists }),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const repository = new MatchStatsRepository(connection);
|
||||||
|
const source = {
|
||||||
|
matchId: new Types.ObjectId(),
|
||||||
|
sourceCompetitionId: new Types.ObjectId(),
|
||||||
|
sourceRevision: 12,
|
||||||
|
projectorVersion: 3,
|
||||||
|
builderVersion: 10,
|
||||||
|
};
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
repository.hasCurrentCompetitionFragment(source),
|
||||||
|
).resolves.toBe(Boolean(stored));
|
||||||
|
expect(exists).toHaveBeenCalledWith({
|
||||||
|
matchId: source.matchId,
|
||||||
|
sourceCompetitionId: source.sourceCompetitionId,
|
||||||
|
sourceRevision: { $gte: 12 },
|
||||||
|
projectorVersion: { $gte: 3 },
|
||||||
|
builderVersion: { $gte: 10 },
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
it('does not let a legacy upsert overwrite a Competition-backed fragment', async () => {
|
it('does not let a legacy upsert overwrite a Competition-backed fragment', async () => {
|
||||||
const fragment = {
|
const fragment = {
|
||||||
...statsFragment(12),
|
...statsFragment(12),
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import type { MatchStats, MatchStatsDocument } from '../global/database/schema';
|
|||||||
|
|
||||||
export type MatchStatsUserRecordFragment = Pick<
|
export type MatchStatsUserRecordFragment = Pick<
|
||||||
MatchStats,
|
MatchStats,
|
||||||
'matchId' | 'records'
|
'matchId' | 'records' | 'builderVersion'
|
||||||
>;
|
>;
|
||||||
|
|
||||||
export type MatchStatsDetailFragment = Pick<
|
export type MatchStatsDetailFragment = Pick<
|
||||||
@@ -22,6 +22,25 @@ export interface MatchStatsDeleteGuard {
|
|||||||
export class MatchStatsRepository {
|
export class MatchStatsRepository {
|
||||||
constructor(private readonly connectionService: ConnectionService) {}
|
constructor(private readonly connectionService: ConnectionService) {}
|
||||||
|
|
||||||
|
public async hasCurrentCompetitionFragment(params: {
|
||||||
|
matchId: mongoose.Types.ObjectId;
|
||||||
|
sourceCompetitionId: mongoose.Types.ObjectId;
|
||||||
|
sourceRevision: number;
|
||||||
|
projectorVersion: number;
|
||||||
|
builderVersion: number;
|
||||||
|
}): Promise<boolean> {
|
||||||
|
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||||
|
return Boolean(
|
||||||
|
await MatchStatsModel.exists({
|
||||||
|
matchId: params.matchId,
|
||||||
|
sourceCompetitionId: params.sourceCompetitionId,
|
||||||
|
sourceRevision: { $gte: params.sourceRevision },
|
||||||
|
projectorVersion: { $gte: params.projectorVersion },
|
||||||
|
builderVersion: { $gte: params.builderVersion },
|
||||||
|
}).exec(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
public async upsert(
|
public async upsert(
|
||||||
fragment: Omit<MatchStats, 'createdAt' | 'updatedAt'>,
|
fragment: Omit<MatchStats, 'createdAt' | 'updatedAt'>,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
@@ -133,6 +152,111 @@ export class MatchStatsRepository {
|
|||||||
return MatchStatsModel.findOne({ matchId }).exec();
|
return MatchStatsModel.findOne({ matchId }).exec();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async findByRiotMatchIds(riotMatchIds: string[]) {
|
||||||
|
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||||
|
return MatchStatsModel.find({
|
||||||
|
'gameDetails.riotMatchId': { $in: riotMatchIds },
|
||||||
|
})
|
||||||
|
.select({
|
||||||
|
matchId: 1,
|
||||||
|
communityId: 1,
|
||||||
|
'gameDetails.riotMatchId': 1,
|
||||||
|
'gameDetails.rawAvailable': 1,
|
||||||
|
})
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async findMatchPage(params: {
|
||||||
|
communityId: mongoose.Types.ObjectId;
|
||||||
|
from?: number;
|
||||||
|
to?: number;
|
||||||
|
query?: string;
|
||||||
|
format?: 'pair' | 'tournament';
|
||||||
|
playerId?: string;
|
||||||
|
championId?: number;
|
||||||
|
cursor?: number;
|
||||||
|
cursorMatchId?: string;
|
||||||
|
limit: number;
|
||||||
|
}) {
|
||||||
|
const model = await this.connectionService.getModel('matchStats');
|
||||||
|
const filter: Record<string, unknown> = { communityId: params.communityId };
|
||||||
|
const conditions: Array<Record<string, unknown>> = [];
|
||||||
|
const gameCreation = {
|
||||||
|
...(params.from === undefined ? {} : { $gte: params.from }),
|
||||||
|
...(params.to === undefined ? {} : { $lte: params.to }),
|
||||||
|
};
|
||||||
|
if (Object.keys(gameCreation).length > 0) {
|
||||||
|
conditions.push({
|
||||||
|
$or: [
|
||||||
|
{ gameDetails: { $elemMatch: { gameCreation } } },
|
||||||
|
{
|
||||||
|
'gameDetails.0': { $exists: false },
|
||||||
|
gameCreationMin: gameCreation,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (params.from !== undefined)
|
||||||
|
filter.gameCreationMax = { $gte: params.from };
|
||||||
|
if (params.to !== undefined) filter.gameCreationMin = { $lte: params.to };
|
||||||
|
if (params.championId) {
|
||||||
|
filter.records = {
|
||||||
|
$elemMatch: {
|
||||||
|
championId: params.championId,
|
||||||
|
...(Object.keys(gameCreation).length > 0 ? { gameCreation } : {}),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (params.query) {
|
||||||
|
filter['matchCard.title'] = {
|
||||||
|
$regex: params.query.replace(/[.*+?^$\x7b\x7d()|[\]\\]/g, '\\$&'),
|
||||||
|
$options: 'i',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (params.format) {
|
||||||
|
filter['matchCard.teams.1'] = { $exists: true };
|
||||||
|
filter['matchCard.teams.2'] = { $exists: params.format === 'tournament' };
|
||||||
|
}
|
||||||
|
if (params.playerId) {
|
||||||
|
filter['matchCard.teams.members.userId'] = params.playerId;
|
||||||
|
}
|
||||||
|
if (params.cursor !== undefined) {
|
||||||
|
const cursor = new Date(params.cursor);
|
||||||
|
if (params.cursorMatchId) {
|
||||||
|
conditions.push({
|
||||||
|
$or: [
|
||||||
|
{ scheduledAt: { $lt: cursor } },
|
||||||
|
{
|
||||||
|
scheduledAt: cursor,
|
||||||
|
matchId: {
|
||||||
|
$lt: new mongoose.Types.ObjectId(params.cursorMatchId),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
filter.scheduledAt = { $lt: cursor };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (conditions.length > 0) filter.$and = conditions;
|
||||||
|
return model
|
||||||
|
.find(filter)
|
||||||
|
.select({
|
||||||
|
matchId: 1,
|
||||||
|
scheduledAt: 1,
|
||||||
|
matchCard: 1,
|
||||||
|
sourceCompetitionId: 1,
|
||||||
|
sourceRevision: 1,
|
||||||
|
'gameDetails.gameNumber': 1,
|
||||||
|
'gameDetails.gameCreation': 1,
|
||||||
|
})
|
||||||
|
.sort({ scheduledAt: -1, matchId: -1 })
|
||||||
|
.limit(params.limit)
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
}
|
||||||
|
|
||||||
public async findByCommunity(params: {
|
public async findByCommunity(params: {
|
||||||
communityId: mongoose.Types.ObjectId;
|
communityId: mongoose.Types.ObjectId;
|
||||||
fromGameCreation?: number;
|
fromGameCreation?: number;
|
||||||
@@ -156,6 +280,51 @@ export class MatchStatsRepository {
|
|||||||
.exec();
|
.exec();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async findSeasonStats(params: {
|
||||||
|
communityId: mongoose.Types.ObjectId;
|
||||||
|
from?: number;
|
||||||
|
to?: number;
|
||||||
|
}) {
|
||||||
|
const model = await this.connectionService.getModel('matchStats');
|
||||||
|
return model
|
||||||
|
.find({
|
||||||
|
communityId: params.communityId,
|
||||||
|
...(params.from === undefined
|
||||||
|
? {}
|
||||||
|
: { gameCreationMax: { $gte: params.from } }),
|
||||||
|
...(params.to === undefined
|
||||||
|
? {}
|
||||||
|
: { gameCreationMin: { $lte: params.to } }),
|
||||||
|
})
|
||||||
|
.select({
|
||||||
|
_id: 0,
|
||||||
|
'records.userId': 1,
|
||||||
|
'records.summonerName': 1,
|
||||||
|
'records.tagLine': 1,
|
||||||
|
'records.profileIconId': 1,
|
||||||
|
'records.gameCreation': 1,
|
||||||
|
'records.gameNumber': 1,
|
||||||
|
'records.matchId': 1,
|
||||||
|
'records.championId': 1,
|
||||||
|
'records.teamPosition': 1,
|
||||||
|
'records.win': 1,
|
||||||
|
'records.kills': 1,
|
||||||
|
'records.deaths': 1,
|
||||||
|
'records.assists': 1,
|
||||||
|
'records.gpm': 1,
|
||||||
|
'records.csPerMin': 1,
|
||||||
|
'records.killParticipation': 1,
|
||||||
|
'records.visionScore': 1,
|
||||||
|
'records.damageShare': 1,
|
||||||
|
'gameDetails.gameCreation': 1,
|
||||||
|
'gameDetails.gameNumber': 1,
|
||||||
|
'gameDetails.winnerSide': 1,
|
||||||
|
})
|
||||||
|
.sort({ scheduledAt: -1 })
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
}
|
||||||
|
|
||||||
public async findByUser(params: {
|
public async findByUser(params: {
|
||||||
communityId: mongoose.Types.ObjectId;
|
communityId: mongoose.Types.ObjectId;
|
||||||
userId: mongoose.Types.ObjectId;
|
userId: mongoose.Types.ObjectId;
|
||||||
@@ -183,7 +352,7 @@ export class MatchStatsRepository {
|
|||||||
return MatchStatsModel.find(filter)
|
return MatchStatsModel.find(filter)
|
||||||
.sort({ scheduledAt: -1 })
|
.sort({ scheduledAt: -1 })
|
||||||
.limit(params.limit ?? 300)
|
.limit(params.limit ?? 300)
|
||||||
.select({ _id: 0, matchId: 1, records: 1 })
|
.select({ _id: 0, matchId: 1, records: 1, builderVersion: 1 })
|
||||||
.lean<MatchStatsUserRecordFragment[]>()
|
.lean<MatchStatsUserRecordFragment[]>()
|
||||||
.exec();
|
.exec();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ describe('MatchStatsService', () => {
|
|||||||
}),
|
}),
|
||||||
} as unknown as ConnectionService;
|
} as unknown as ConnectionService;
|
||||||
const repository = {
|
const repository = {
|
||||||
|
hasCurrentCompetitionFragment: jest.fn().mockResolvedValue(false),
|
||||||
deleteByMatch: jest.fn().mockResolvedValue(undefined),
|
deleteByMatch: jest.fn().mockResolvedValue(undefined),
|
||||||
upsert: jest.fn(),
|
upsert: jest.fn(),
|
||||||
} as unknown as jest.Mocked<MatchStatsRepository>;
|
} as unknown as jest.Mocked<MatchStatsRepository>;
|
||||||
@@ -72,6 +73,7 @@ describe('MatchStatsService', () => {
|
|||||||
}),
|
}),
|
||||||
} as unknown as ConnectionService;
|
} as unknown as ConnectionService;
|
||||||
const repository = {
|
const repository = {
|
||||||
|
hasCurrentCompetitionFragment: jest.fn().mockResolvedValue(false),
|
||||||
deleteByMatch: jest.fn().mockResolvedValue(undefined),
|
deleteByMatch: jest.fn().mockResolvedValue(undefined),
|
||||||
upsert: jest.fn(),
|
upsert: jest.fn(),
|
||||||
} as unknown as jest.Mocked<MatchStatsRepository>;
|
} as unknown as jest.Mocked<MatchStatsRepository>;
|
||||||
@@ -132,6 +134,7 @@ describe('MatchStatsService', () => {
|
|||||||
}),
|
}),
|
||||||
} as unknown as ConnectionService;
|
} as unknown as ConnectionService;
|
||||||
const repository = {
|
const repository = {
|
||||||
|
hasCurrentCompetitionFragment: jest.fn().mockResolvedValue(false),
|
||||||
upsert: jest.fn().mockResolvedValue(undefined),
|
upsert: jest.fn().mockResolvedValue(undefined),
|
||||||
deleteByMatch: jest.fn(),
|
deleteByMatch: jest.fn(),
|
||||||
} as unknown as jest.Mocked<MatchStatsRepository>;
|
} as unknown as jest.Mocked<MatchStatsRepository>;
|
||||||
@@ -273,6 +276,7 @@ describe('MatchStatsService', () => {
|
|||||||
}),
|
}),
|
||||||
} as unknown as ConnectionService;
|
} as unknown as ConnectionService;
|
||||||
const repository = {
|
const repository = {
|
||||||
|
hasCurrentCompetitionFragment: jest.fn().mockResolvedValue(false),
|
||||||
upsert: jest.fn().mockResolvedValue(undefined),
|
upsert: jest.fn().mockResolvedValue(undefined),
|
||||||
deleteByMatch: jest.fn(),
|
deleteByMatch: jest.fn(),
|
||||||
deleteLegacyByMatch: jest.fn(),
|
deleteLegacyByMatch: jest.fn(),
|
||||||
@@ -281,15 +285,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;
|
||||||
@@ -397,6 +412,7 @@ describe('MatchStatsService', () => {
|
|||||||
}),
|
}),
|
||||||
} as unknown as ConnectionService;
|
} as unknown as ConnectionService;
|
||||||
const repository = {
|
const repository = {
|
||||||
|
hasCurrentCompetitionFragment: jest.fn().mockResolvedValue(false),
|
||||||
upsert: jest.fn().mockResolvedValue(undefined),
|
upsert: jest.fn().mockResolvedValue(undefined),
|
||||||
deleteByMatch: jest.fn(),
|
deleteByMatch: jest.fn(),
|
||||||
} as unknown as jest.Mocked<MatchStatsRepository>;
|
} as unknown as jest.Mocked<MatchStatsRepository>;
|
||||||
@@ -501,6 +517,7 @@ describe('MatchStatsService', () => {
|
|||||||
}),
|
}),
|
||||||
} as unknown as ConnectionService;
|
} as unknown as ConnectionService;
|
||||||
const repository = {
|
const repository = {
|
||||||
|
hasCurrentCompetitionFragment: jest.fn().mockResolvedValue(false),
|
||||||
upsert: jest.fn().mockResolvedValue(undefined),
|
upsert: jest.fn().mockResolvedValue(undefined),
|
||||||
deleteByMatch: jest.fn().mockResolvedValue(undefined),
|
deleteByMatch: jest.fn().mockResolvedValue(undefined),
|
||||||
deleteLegacyByMatch: jest.fn(),
|
deleteLegacyByMatch: jest.fn(),
|
||||||
@@ -562,6 +579,7 @@ describe('MatchStatsService', () => {
|
|||||||
}),
|
}),
|
||||||
} as unknown as ConnectionService;
|
} as unknown as ConnectionService;
|
||||||
const repository = {
|
const repository = {
|
||||||
|
hasCurrentCompetitionFragment: jest.fn().mockResolvedValue(false),
|
||||||
upsert: jest.fn(),
|
upsert: jest.fn(),
|
||||||
deleteByMatch: jest.fn(),
|
deleteByMatch: jest.fn(),
|
||||||
} as unknown as jest.Mocked<MatchStatsRepository>;
|
} as unknown as jest.Mocked<MatchStatsRepository>;
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ export class MatchStatsService {
|
|||||||
? competitionStatsSource(match, competition)
|
? competitionStatsSource(match, competition)
|
||||||
: undefined;
|
: undefined;
|
||||||
const sourceMatch = competitionSource?.match ?? match;
|
const sourceMatch = competitionSource?.match ?? match;
|
||||||
if (!this.isEligible(sourceMatch)) {
|
if (!this.isEligible(sourceMatch) && competition?.phase !== 'completed') {
|
||||||
if (competitionSource) {
|
if (competitionSource) {
|
||||||
await this.repository.deleteByMatch(matchId, {
|
await this.repository.deleteByMatch(matchId, {
|
||||||
sourceCompetitionId: competitionSource.sourceCompetitionId,
|
sourceCompetitionId: competitionSource.sourceCompetitionId,
|
||||||
@@ -59,6 +59,24 @@ export class MatchStatsService {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Outbox redelivery (including older events observing the latest revision)
|
||||||
|
// must not reload Riot payloads or replace an already enriched fragment.
|
||||||
|
// Explicit rebuilds and timeline hydration still run at the same revision.
|
||||||
|
if (
|
||||||
|
options.sourceRevision !== undefined &&
|
||||||
|
!options.includeTimeline &&
|
||||||
|
competitionSource &&
|
||||||
|
(await this.repository.hasCurrentCompetitionFragment({
|
||||||
|
matchId,
|
||||||
|
sourceCompetitionId: competitionSource.sourceCompetitionId,
|
||||||
|
sourceRevision: competitionSource.sourceRevision,
|
||||||
|
projectorVersion: competitionSource.projectorVersion,
|
||||||
|
builderVersion: MATCH_STATS_BUILDER_VERSION,
|
||||||
|
}))
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const riotIds = competitionSource?.riotMatchIds ?? [
|
const riotIds = competitionSource?.riotMatchIds ?? [
|
||||||
...new Set(
|
...new Set(
|
||||||
(match.result?.games ?? [])
|
(match.result?.games ?? [])
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import type {
|
|||||||
} from '../global/database/schema';
|
} from '../global/database/schema';
|
||||||
import type { InternalMatchCardView } from './community-stats.types';
|
import type { InternalMatchCardView } from './community-stats.types';
|
||||||
|
|
||||||
export const MATCH_STATS_BUILDER_VERSION = 10;
|
export const MATCH_STATS_BUILDER_VERSION = 11;
|
||||||
|
|
||||||
export type InternalRecord = MatchStatsRecord;
|
export type InternalRecord = MatchStatsRecord;
|
||||||
export type InternalGameDetail = MatchStatsGameDetail;
|
export type InternalGameDetail = MatchStatsGameDetail;
|
||||||
|
|||||||
@@ -5,12 +5,13 @@ import {
|
|||||||
CompetitionBootstrapService,
|
CompetitionBootstrapService,
|
||||||
type CompetitionBootstrapMatch,
|
type CompetitionBootstrapMatch,
|
||||||
} from './competition-bootstrap.service';
|
} from './competition-bootstrap.service';
|
||||||
|
import type { SeriesDefinition } from './domain/series-graph';
|
||||||
|
|
||||||
describe('CompetitionBootstrapService', () => {
|
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 +89,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 +107,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 +131,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 +174,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 +192,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(
|
||||||
@@ -216,6 +211,40 @@ describe('CompetitionBootstrapService', () => {
|
|||||||
expect(harness.competitionModel.findOneAndUpdate).not.toHaveBeenCalled();
|
expect(harness.competitionModel.findOneAndUpdate).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('gives a configured BO3 grand final three slots without changing the other stage rules', async () => {
|
||||||
|
const harness = createHarness();
|
||||||
|
const service = new CompetitionBootstrapService(harness.connectionService);
|
||||||
|
const match = matchSnapshot({
|
||||||
|
gameMode: 'double-elimination',
|
||||||
|
teamCount: 4,
|
||||||
|
gameCount: 5,
|
||||||
|
});
|
||||||
|
match.doubleElimination = {
|
||||||
|
teamCount: 4,
|
||||||
|
resetFinalEnabled: true,
|
||||||
|
grandFinalGameCount: 3,
|
||||||
|
seeds: [1, 2, 3, 4].map((teamIndex) => ({
|
||||||
|
seedNumber: teamIndex,
|
||||||
|
teamIndex,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
|
||||||
|
await service.bootstrap(match);
|
||||||
|
|
||||||
|
const { format, seriesGraph } = harness.insertedPayloads[0];
|
||||||
|
expect(format).toMatchObject({
|
||||||
|
rules: {
|
||||||
|
upper: { maxGames: 5, winsRequired: 3 },
|
||||||
|
lower: { maxGames: 1, winsRequired: 1 },
|
||||||
|
grandFinal: { maxGames: 3, winsRequired: 2 },
|
||||||
|
resetFinal: { maxGames: 1, winsRequired: 1 },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
seriesGraph.find(({ code }) => code === 'GF')?.gameSlots,
|
||||||
|
).toHaveLength(3);
|
||||||
|
});
|
||||||
|
|
||||||
it('rejects incomplete and duplicate team assignments before opening a transaction', async () => {
|
it('rejects incomplete and duplicate team assignments before opening a transaction', async () => {
|
||||||
const cases: Array<[string, (match: CompetitionBootstrapMatch) => void]> = [
|
const cases: Array<[string, (match: CompetitionBootstrapMatch) => void]> = [
|
||||||
[
|
[
|
||||||
@@ -253,7 +282,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 +301,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 +314,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 +325,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 +369,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 +397,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 +414,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 })),
|
||||||
@@ -465,7 +486,7 @@ interface InsertPayload {
|
|||||||
legacyTeamIndex: number;
|
legacyTeamIndex: number;
|
||||||
seedNumber: number;
|
seedNumber: number;
|
||||||
}>;
|
}>;
|
||||||
seriesGraph: Array<{ code?: string; rule: unknown }>;
|
seriesGraph: SeriesDefinition[];
|
||||||
[key: string]: any;
|
[key: string]: any;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -508,7 +529,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,
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ export interface CompetitionBootstrapMatch {
|
|||||||
doubleElimination?: {
|
doubleElimination?: {
|
||||||
teamCount: 4 | 8;
|
teamCount: 4 | 8;
|
||||||
resetFinalEnabled: boolean;
|
resetFinalEnabled: boolean;
|
||||||
|
grandFinalGameCount?: 1 | 3 | 5;
|
||||||
seeds: Array<{ seedNumber: number; teamIndex: number }>;
|
seeds: Array<{ seedNumber: number; teamIndex: number }>;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -514,6 +515,8 @@ function mapMatchFormat(
|
|||||||
winsRequired: 1,
|
winsRequired: 1,
|
||||||
maxGames: 1,
|
maxGames: 1,
|
||||||
};
|
};
|
||||||
|
const grandFinalGameCount =
|
||||||
|
match.doubleElimination?.grandFinalGameCount ?? 1;
|
||||||
return {
|
return {
|
||||||
type: 'double-elimination',
|
type: 'double-elimination',
|
||||||
teamCount: teams.length,
|
teamCount: teams.length,
|
||||||
@@ -525,7 +528,11 @@ function mapMatchFormat(
|
|||||||
maxGames: match.gameCount,
|
maxGames: match.gameCount,
|
||||||
},
|
},
|
||||||
lower: { ...bestOfOne },
|
lower: { ...bestOfOne },
|
||||||
grandFinal: { ...bestOfOne },
|
grandFinal: {
|
||||||
|
type: 'first-to',
|
||||||
|
winsRequired: Math.floor(grandFinalGameCount / 2) + 1,
|
||||||
|
maxGames: grandFinalGameCount,
|
||||||
|
},
|
||||||
resetFinal: { ...bestOfOne },
|
resetFinal: { ...bestOfOne },
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -821,7 +821,7 @@ function buildOutbox(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function factForProjection(
|
export function factForProjection(
|
||||||
fact: Readonly<Record<string, unknown>>,
|
fact: Readonly<Record<string, unknown>>,
|
||||||
): Readonly<Record<string, unknown>> {
|
): Readonly<Record<string, unknown>> {
|
||||||
const plain = toPlain(fact) as Readonly<Record<string, unknown>>;
|
const plain = toPlain(fact) as Readonly<Record<string, unknown>>;
|
||||||
|
|||||||
@@ -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>;
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ export const COMPETITION_FACT_TYPES = [
|
|||||||
'game-voided',
|
'game-voided',
|
||||||
'series-adjudicated',
|
'series-adjudicated',
|
||||||
'adjudication-reversed',
|
'adjudication-reversed',
|
||||||
|
'grand-final-rule-corrected',
|
||||||
] as const;
|
] as const;
|
||||||
export type CompetitionFactType = (typeof COMPETITION_FACT_TYPES)[number];
|
export type CompetitionFactType = (typeof COMPETITION_FACT_TYPES)[number];
|
||||||
|
|
||||||
@@ -200,6 +201,7 @@ export interface CompetitionFact {
|
|||||||
adjudicationFactId?: mongoose.Types.ObjectId;
|
adjudicationFactId?: mongoose.Types.ObjectId;
|
||||||
decision?: Record<string, unknown>;
|
decision?: Record<string, unknown>;
|
||||||
reason?: string;
|
reason?: string;
|
||||||
|
ruleCorrection?: { previousMaxGames: 1; nextMaxGames: 3 };
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
updatedAt: Date;
|
updatedAt: Date;
|
||||||
}
|
}
|
||||||
@@ -339,6 +341,7 @@ export const CompetitionFactSchema = new Schema<CompetitionFact>(
|
|||||||
adjudicationFactId: { type: Schema.Types.ObjectId },
|
adjudicationFactId: { type: Schema.Types.ObjectId },
|
||||||
decision: { type: Schema.Types.Mixed },
|
decision: { type: Schema.Types.Mixed },
|
||||||
reason: { type: String },
|
reason: { type: String },
|
||||||
|
ruleCorrection: { type: Schema.Types.Mixed },
|
||||||
},
|
},
|
||||||
{ timestamps: true, collection: 'competition_fact' },
|
{ timestamps: true, collection: 'competition_fact' },
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -589,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;
|
||||||
|
|||||||
@@ -131,7 +131,12 @@ export interface CompetitionProjection {
|
|||||||
export function projectCompetition(
|
export function projectCompetition(
|
||||||
input: ProjectCompetitionInput,
|
input: ProjectCompetitionInput,
|
||||||
): CompetitionProjection {
|
): CompetitionProjection {
|
||||||
assertPrimaryFactTargetsGraph(input.seriesGraph, input.facts);
|
// The repair commits the corrected graph and its audit fact together. The
|
||||||
|
// audit fact occupies a revision but is not a game or adjudication.
|
||||||
|
const resultFacts = input.facts.filter(
|
||||||
|
(fact) => !isRecord(fact) || fact.type !== 'grand-final-rule-corrected',
|
||||||
|
);
|
||||||
|
assertPrimaryFactTargetsGraph(input.seriesGraph, resultFacts);
|
||||||
const teamBySeed = new Map<number, string>();
|
const teamBySeed = new Map<number, string>();
|
||||||
const knownTeams = new Set<string>();
|
const knownTeams = new Set<string>();
|
||||||
for (const team of input.teams) {
|
for (const team of input.teams) {
|
||||||
@@ -169,7 +174,7 @@ export function projectCompetition(
|
|||||||
teamBySeed,
|
teamBySeed,
|
||||||
projectedById,
|
projectedById,
|
||||||
),
|
),
|
||||||
facts: input.facts,
|
facts: resultFacts,
|
||||||
active: false,
|
active: false,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -188,7 +193,7 @@ export function projectCompetition(
|
|||||||
projectSeries({
|
projectSeries({
|
||||||
definition: asProjectorDefinition(definition),
|
definition: asProjectorDefinition(definition),
|
||||||
participants,
|
participants,
|
||||||
facts: input.facts,
|
facts: resultFacts,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
remaining.delete(seriesId);
|
remaining.delete(seriesId);
|
||||||
@@ -211,7 +216,7 @@ export function projectCompetition(
|
|||||||
projectSeries({
|
projectSeries({
|
||||||
definition: asProjectorDefinition(definition),
|
definition: asProjectorDefinition(definition),
|
||||||
participants,
|
participants,
|
||||||
facts: input.facts,
|
facts: resultFacts,
|
||||||
...(definition.activation ? { active: false } : {}),
|
...(definition.activation ? { active: false } : {}),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -221,7 +226,7 @@ export function projectCompetition(
|
|||||||
const gameProjection = projectGamesAndSlots(
|
const gameProjection = projectGamesAndSlots(
|
||||||
input.seriesGraph,
|
input.seriesGraph,
|
||||||
series,
|
series,
|
||||||
input.facts,
|
resultFacts,
|
||||||
);
|
);
|
||||||
const common = {
|
const common = {
|
||||||
competitionId: input.competitionId,
|
competitionId: input.competitionId,
|
||||||
|
|||||||
@@ -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(
|
||||||
|
|||||||
@@ -35,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']);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -88,6 +88,7 @@ export interface DoubleEliminationEvent {
|
|||||||
export interface DoubleEliminationBracket {
|
export interface DoubleEliminationBracket {
|
||||||
teamCount: 4 | 8;
|
teamCount: 4 | 8;
|
||||||
resetFinalEnabled: boolean;
|
resetFinalEnabled: boolean;
|
||||||
|
grandFinalGameCount?: 1 | 3 | 5;
|
||||||
resetFinalCreated: boolean;
|
resetFinalCreated: boolean;
|
||||||
seeds: DoubleEliminationSeed[];
|
seeds: DoubleEliminationSeed[];
|
||||||
bracketMatches: DoubleEliminationBracketMatch[];
|
bracketMatches: DoubleEliminationBracketMatch[];
|
||||||
@@ -98,6 +99,7 @@ export interface DoubleEliminationBracket {
|
|||||||
export interface BuildDoubleEliminationBracketOptions {
|
export interface BuildDoubleEliminationBracketOptions {
|
||||||
resetFinalEnabled: boolean;
|
resetFinalEnabled: boolean;
|
||||||
winnerBracketGameCount?: number;
|
winnerBracketGameCount?: number;
|
||||||
|
grandFinalGameCount?: 1 | 3 | 5;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DoubleEliminationSeriesRule {
|
export interface DoubleEliminationSeriesRule {
|
||||||
@@ -146,6 +148,9 @@ export function buildDoubleEliminationBracket(
|
|||||||
const bracket: DoubleEliminationBracket = {
|
const bracket: DoubleEliminationBracket = {
|
||||||
teamCount: seededTeamIndexes.length,
|
teamCount: seededTeamIndexes.length,
|
||||||
resetFinalEnabled: options.resetFinalEnabled,
|
resetFinalEnabled: options.resetFinalEnabled,
|
||||||
|
...(options.grandFinalGameCount === undefined
|
||||||
|
? {}
|
||||||
|
: { grandFinalGameCount: options.grandFinalGameCount }),
|
||||||
resetFinalCreated: false,
|
resetFinalCreated: false,
|
||||||
seeds,
|
seeds,
|
||||||
bracketMatches:
|
bracketMatches:
|
||||||
@@ -171,11 +176,17 @@ export function resolveDoubleEliminationSeriesRule(
|
|||||||
bracketMatchId: string;
|
bracketMatchId: string;
|
||||||
roundNumber: number;
|
roundNumber: number;
|
||||||
},
|
},
|
||||||
options: { winnerBracketGameCount?: number } = {},
|
options: Pick<
|
||||||
|
BuildDoubleEliminationBracketOptions,
|
||||||
|
'winnerBracketGameCount' | 'grandFinalGameCount'
|
||||||
|
> = {},
|
||||||
): DoubleEliminationSeriesRule {
|
): DoubleEliminationSeriesRule {
|
||||||
if (params.bracketSide === 'winner') {
|
if (params.bracketSide === 'winner') {
|
||||||
return seriesRule(options.winnerBracketGameCount ?? 3);
|
return seriesRule(options.winnerBracketGameCount ?? 3);
|
||||||
}
|
}
|
||||||
|
if (params.bracketSide === 'grand-final') {
|
||||||
|
return seriesRule(options.grandFinalGameCount ?? 1);
|
||||||
|
}
|
||||||
return seriesRule(1);
|
return seriesRule(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -431,6 +442,7 @@ function rebuildWithSeeds(
|
|||||||
): DoubleEliminationBracket {
|
): DoubleEliminationBracket {
|
||||||
const next = buildDoubleEliminationBracket(teamIndexes, {
|
const next = buildDoubleEliminationBracket(teamIndexes, {
|
||||||
resetFinalEnabled: bracket.resetFinalEnabled,
|
resetFinalEnabled: bracket.resetFinalEnabled,
|
||||||
|
grandFinalGameCount: bracket.grandFinalGameCount,
|
||||||
});
|
});
|
||||||
next.events = [
|
next.events = [
|
||||||
...bracket.events,
|
...bracket.events,
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
export const AUCTION_CANCELLATION_CLEANUP_INDEX = {
|
||||||
|
key: { auctionCancellationCleanupRetryAt: 1 as const },
|
||||||
|
options: {
|
||||||
|
name: 'auction_cancellation_cleanup_due',
|
||||||
|
partialFilterExpression: { auctionCancellationCleanupPending: true },
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -62,9 +62,7 @@ describe('auction Redis schema foundation', () => {
|
|||||||
expect(
|
expect(
|
||||||
AuctionHistoryEntrySchema.path('matchSideEffectMutation'),
|
AuctionHistoryEntrySchema.path('matchSideEffectMutation'),
|
||||||
).toBeDefined();
|
).toBeDefined();
|
||||||
expect(
|
expect(AuctionHistoryEntrySchema.path('action').options.enum).toEqual(
|
||||||
AuctionHistoryEntrySchema.path<string>('action').options.enum,
|
|
||||||
).toEqual(
|
|
||||||
expect.arrayContaining([
|
expect.arrayContaining([
|
||||||
'start',
|
'start',
|
||||||
'open-bidding',
|
'open-bidding',
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
export const MATCH_STATS_RIOT_MATCH_INDEX = {
|
||||||
|
key: { 'gameDetails.riotMatchId': 1 as const },
|
||||||
|
options: { name: 'gameDetails.riotMatchId_1' },
|
||||||
|
};
|
||||||
@@ -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 ?? [],
|
||||||
|
|||||||
+39
@@ -0,0 +1,39 @@
|
|||||||
|
import type { mongo } from 'mongoose';
|
||||||
|
import { AUCTION_CANCELLATION_CLEANUP_INDEX } from '../auction-cancellation-index';
|
||||||
|
|
||||||
|
/** Creates only this additive index; never drops or rebuilds other indexes. */
|
||||||
|
export async function migrateAuctionCancellationIndex(
|
||||||
|
db: mongo.Db,
|
||||||
|
{ dryRun = true }: { dryRun?: boolean } = {},
|
||||||
|
) {
|
||||||
|
const { key, options } = AUCTION_CANCELLATION_CLEANUP_INDEX;
|
||||||
|
const collection = db.collection('match');
|
||||||
|
const indexes = await collection
|
||||||
|
.listIndexes()
|
||||||
|
.toArray()
|
||||||
|
.catch((error: unknown) => {
|
||||||
|
if (error instanceof Error && 'code' in error && error.code === 26)
|
||||||
|
return [];
|
||||||
|
throw error;
|
||||||
|
});
|
||||||
|
const existing = indexes.find((index) => index.name === options.name);
|
||||||
|
if (
|
||||||
|
existing &&
|
||||||
|
(JSON.stringify(existing.key) !== JSON.stringify(key) ||
|
||||||
|
JSON.stringify(existing.partialFilterExpression) !==
|
||||||
|
JSON.stringify(options.partialFilterExpression) ||
|
||||||
|
existing.unique === true ||
|
||||||
|
existing.sparse === true ||
|
||||||
|
existing.hidden === true)
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
`Index ${options.name} already exists with a different definition.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!dryRun) await collection.createIndex(key, options);
|
||||||
|
return {
|
||||||
|
dryRun,
|
||||||
|
alreadyPresent: Boolean(existing),
|
||||||
|
index: { key, ...options },
|
||||||
|
};
|
||||||
|
}
|
||||||
+47
@@ -0,0 +1,47 @@
|
|||||||
|
import type { mongo } from 'mongoose';
|
||||||
|
import { migrateMatchStatsRawIndex } from './20261111-match-stats-raw-index';
|
||||||
|
import { MATCH_STATS_RIOT_MATCH_INDEX } from '../match-stats-raw-index';
|
||||||
|
import { parseMatchStatsIndexOptions } from './run-match-stats-raw-index';
|
||||||
|
|
||||||
|
it('defaults to a read-only plan and validates the target environment', async () => {
|
||||||
|
expect(parseMatchStatsIndexOptions(['--env', 'prod']).dryRun).toBe(true);
|
||||||
|
expect(() => parseMatchStatsIndexOptions(['--env', 'unknown'])).toThrow();
|
||||||
|
const createIndex = jest.fn();
|
||||||
|
await migrateMatchStatsRawIndex(database([], createIndex));
|
||||||
|
expect(createIndex).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('adds only the lookup index and accepts an identical existing index', async () => {
|
||||||
|
const { key, options } = MATCH_STATS_RIOT_MATCH_INDEX;
|
||||||
|
const createIndex = jest.fn();
|
||||||
|
const result = await migrateMatchStatsRawIndex(
|
||||||
|
database([{ key, ...options }], createIndex),
|
||||||
|
{ dryRun: false },
|
||||||
|
);
|
||||||
|
expect(result.alreadyPresent).toBe(true);
|
||||||
|
expect(createIndex).toHaveBeenCalledWith(key, options);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects an incompatible existing index without dropping or recreating it', async () => {
|
||||||
|
const { key, options } = MATCH_STATS_RIOT_MATCH_INDEX;
|
||||||
|
const createIndex = jest.fn();
|
||||||
|
await expect(
|
||||||
|
migrateMatchStatsRawIndex(
|
||||||
|
database([{ key, ...options, unique: true }], createIndex),
|
||||||
|
{ dryRun: false },
|
||||||
|
),
|
||||||
|
).rejects.toThrow('different definition');
|
||||||
|
expect(createIndex).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
function database(indexes: unknown[], createIndex: jest.Mock): mongo.Db {
|
||||||
|
return {
|
||||||
|
collection: (name: string) => {
|
||||||
|
expect(name).toBe('match_stats');
|
||||||
|
return {
|
||||||
|
listIndexes: () => ({ toArray: async () => indexes }),
|
||||||
|
createIndex,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
} as unknown as mongo.Db;
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import type { mongo } from 'mongoose';
|
||||||
|
import { MATCH_STATS_RIOT_MATCH_INDEX } from '../match-stats-raw-index';
|
||||||
|
|
||||||
|
/** Adds the lookup index without dropping indexes or modifying game records. */
|
||||||
|
export async function migrateMatchStatsRawIndex(
|
||||||
|
db: mongo.Db,
|
||||||
|
{ dryRun = true }: { dryRun?: boolean } = {},
|
||||||
|
) {
|
||||||
|
const { key, options } = MATCH_STATS_RIOT_MATCH_INDEX;
|
||||||
|
const collection = db.collection('match_stats');
|
||||||
|
const indexes = await collection
|
||||||
|
.listIndexes()
|
||||||
|
.toArray()
|
||||||
|
.catch((error: unknown) => {
|
||||||
|
if (error instanceof Error && 'code' in error && error.code === 26)
|
||||||
|
return [];
|
||||||
|
throw error;
|
||||||
|
});
|
||||||
|
const existing = indexes.find((index) => index.name === options.name);
|
||||||
|
if (
|
||||||
|
existing &&
|
||||||
|
(JSON.stringify(existing.key) !== JSON.stringify(key) ||
|
||||||
|
existing.unique === true ||
|
||||||
|
existing.sparse === true ||
|
||||||
|
existing.hidden === true ||
|
||||||
|
existing.partialFilterExpression !== undefined)
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
`Index ${options.name} already exists with a different definition.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!dryRun) await collection.createIndex(key, options);
|
||||||
|
return {
|
||||||
|
dryRun,
|
||||||
|
alreadyPresent: Boolean(existing),
|
||||||
|
index: { key, ...options },
|
||||||
|
};
|
||||||
|
}
|
||||||
+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: [],
|
||||||
|
|||||||
@@ -0,0 +1,293 @@
|
|||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { projectCompetition } from '../../../competition/domain/competition-projector';
|
||||||
|
import { generateSeriesGraph } from '../../../competition/domain/series-graph';
|
||||||
|
import {
|
||||||
|
parseGrandFinalRepairOptions,
|
||||||
|
planGrandFinalBo3Repair,
|
||||||
|
repairGrandFinalBo3,
|
||||||
|
} from './repair-grand-final-bo3';
|
||||||
|
|
||||||
|
describe('grand final BO3 repair', () => {
|
||||||
|
it.each([false, true])(
|
||||||
|
'keeps game 28 and finishes only after two wins (split: %s)',
|
||||||
|
(split) => {
|
||||||
|
const input = finishedTournament();
|
||||||
|
const plan = planGrandFinalBo3Repair(input);
|
||||||
|
|
||||||
|
expect(plan.before.phase).toBe('completed');
|
||||||
|
expect(plan.preservedGame).toBe(28);
|
||||||
|
expect(plan.newGameNumbers).toEqual([29, 30]);
|
||||||
|
expect(plan.projection.games).toEqual(plan.before.games);
|
||||||
|
expect(plan.projection).toMatchObject({
|
||||||
|
phase: 'running',
|
||||||
|
placements: [],
|
||||||
|
});
|
||||||
|
expect(plan.projection).not.toHaveProperty('outcome');
|
||||||
|
expect(
|
||||||
|
plan.projection.series.find(
|
||||||
|
({ seriesId }) => seriesId === plan.seriesId,
|
||||||
|
),
|
||||||
|
).toMatchObject({
|
||||||
|
status: 'in-progress',
|
||||||
|
entries: [
|
||||||
|
{ slot: 'A', gameWins: 1 },
|
||||||
|
{ slot: 'B', gameWins: 0 },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const facts = [
|
||||||
|
...input.facts,
|
||||||
|
{
|
||||||
|
id: 'rule-audit',
|
||||||
|
type: 'grand-final-rule-corrected',
|
||||||
|
seriesId: plan.seriesId,
|
||||||
|
revision: plan.projection.sourceRevision,
|
||||||
|
ordinalWithinRevision: 1,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const replay = () =>
|
||||||
|
projectCompetition({
|
||||||
|
...input,
|
||||||
|
facts,
|
||||||
|
revision: facts.length,
|
||||||
|
format: plan.format,
|
||||||
|
seriesGraph: plan.seriesGraph,
|
||||||
|
});
|
||||||
|
expect(replay()).toEqual(plan.projection);
|
||||||
|
|
||||||
|
const second = replay().gameSlots.find(
|
||||||
|
({ displayNumber }) => displayNumber === 29,
|
||||||
|
)!;
|
||||||
|
facts.push(acceptedGame(second, facts.length + 1, split ? 'B' : 'A'));
|
||||||
|
if (split) {
|
||||||
|
expect(replay().phase).toBe('running');
|
||||||
|
const third = replay().gameSlots.find(
|
||||||
|
({ displayNumber }) => displayNumber === 30,
|
||||||
|
)!;
|
||||||
|
expect(third.status).toBe('ready');
|
||||||
|
facts.push(acceptedGame(third, facts.length + 1, 'A'));
|
||||||
|
}
|
||||||
|
const completed = replay();
|
||||||
|
expect(completed.phase).toBe('completed');
|
||||||
|
expect(
|
||||||
|
completed.gameSlots.find(({ displayNumber }) => displayNumber === 30)
|
||||||
|
?.status,
|
||||||
|
).toBe(split ? 'completed' : 'inactive');
|
||||||
|
expect(completed.games.at(-1)?.displayNumber).toBe(split ? 30 : 29);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it('refuses to reopen a bracket that enables a reset final', () => {
|
||||||
|
const input = finishedTournament();
|
||||||
|
expect(() =>
|
||||||
|
planGrandFinalBo3Repair({
|
||||||
|
...input,
|
||||||
|
format: { ...input.format, resetFinalEnabled: true },
|
||||||
|
}),
|
||||||
|
).toThrow('no reset or later series');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requires a target and a reviewed revision before applying', () => {
|
||||||
|
const target = ['--match-id', '000000000000000000000001', '--env', 'prod'];
|
||||||
|
expect(parseGrandFinalRepairOptions(target)).toMatchObject({
|
||||||
|
apply: false,
|
||||||
|
});
|
||||||
|
expect(() => parseGrandFinalRepairOptions(['--apply', ...target])).toThrow(
|
||||||
|
'--expected-revision',
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
parseGrandFinalRepairOptions([
|
||||||
|
'--apply',
|
||||||
|
...target,
|
||||||
|
'--expected-revision',
|
||||||
|
'23',
|
||||||
|
]),
|
||||||
|
).toMatchObject({ apply: true, expectedRevision: 23 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('previews without writes and applies the graph, match status and audit in one transaction', async () => {
|
||||||
|
const input = finishedTournament();
|
||||||
|
const competitionId = new mongoose.Types.ObjectId(input.competitionId);
|
||||||
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
|
const communityId = new mongoose.Types.ObjectId();
|
||||||
|
const match = {
|
||||||
|
_id: matchId,
|
||||||
|
competitionId,
|
||||||
|
communityId,
|
||||||
|
gameMode: 'double-elimination',
|
||||||
|
status: 'finished',
|
||||||
|
teamBuiltAt: new Date(),
|
||||||
|
doubleElimination: { resetFinalEnabled: false },
|
||||||
|
resultPollState: { state: 'complete' },
|
||||||
|
};
|
||||||
|
const competition = {
|
||||||
|
...input,
|
||||||
|
_id: competitionId,
|
||||||
|
schemaVersion: 1,
|
||||||
|
phase: 'completed',
|
||||||
|
teams: input.teams.map((team) => ({
|
||||||
|
...team,
|
||||||
|
teamId: new mongoose.Types.ObjectId(team.teamId),
|
||||||
|
})),
|
||||||
|
projection: projectCompetition(input),
|
||||||
|
};
|
||||||
|
const query = (value: unknown) => ({
|
||||||
|
session: jest.fn().mockReturnThis(),
|
||||||
|
lean: jest.fn().mockReturnThis(),
|
||||||
|
sort: jest.fn().mockReturnThis(),
|
||||||
|
exec: jest.fn().mockResolvedValue(value),
|
||||||
|
});
|
||||||
|
const update = () => jest.fn(() => query({ matchedCount: 1 }));
|
||||||
|
const models = {
|
||||||
|
match: { findById: jest.fn(() => query(match)), updateOne: update() },
|
||||||
|
competition: {
|
||||||
|
findOne: jest.fn(() => query(competition)),
|
||||||
|
updateOne: update(),
|
||||||
|
},
|
||||||
|
competitionFact: {
|
||||||
|
find: jest.fn(() => query(input.facts)),
|
||||||
|
insertMany: jest.fn(),
|
||||||
|
},
|
||||||
|
competitionOutbox: { insertMany: jest.fn() },
|
||||||
|
};
|
||||||
|
const session = {
|
||||||
|
withTransaction: jest.fn((run: () => unknown) => run()),
|
||||||
|
endSession: jest.fn(),
|
||||||
|
};
|
||||||
|
const connections = {
|
||||||
|
getModel: jest.fn((name: keyof typeof models) => models[name]),
|
||||||
|
createSession: jest.fn().mockResolvedValue(session),
|
||||||
|
} as never;
|
||||||
|
const options = { matchId, nodeEnv: 'prod', apply: false };
|
||||||
|
|
||||||
|
const preview = await repairGrandFinalBo3(connections, options);
|
||||||
|
expect(preview).toMatchObject({
|
||||||
|
mode: 'dry-run',
|
||||||
|
preservedGame: 28,
|
||||||
|
newGameNumbers: [29, 30],
|
||||||
|
});
|
||||||
|
expect(models.match.updateOne).not.toHaveBeenCalled();
|
||||||
|
expect(models.competition.updateOne).not.toHaveBeenCalled();
|
||||||
|
expect(models.competitionFact.insertMany).not.toHaveBeenCalled();
|
||||||
|
expect(models.competitionOutbox.insertMany).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
repairGrandFinalBo3(connections, {
|
||||||
|
...options,
|
||||||
|
apply: true,
|
||||||
|
expectedRevision: preview.revisionBefore,
|
||||||
|
}),
|
||||||
|
).resolves.toMatchObject({
|
||||||
|
mode: 'applied',
|
||||||
|
phase: 'completed -> running',
|
||||||
|
});
|
||||||
|
expect(session.withTransaction).toHaveBeenCalledTimes(1);
|
||||||
|
expect(models.match.updateOne).toHaveBeenCalledWith(
|
||||||
|
{ _id: matchId, status: 'finished', competitionId },
|
||||||
|
{
|
||||||
|
$set: expect.objectContaining({
|
||||||
|
status: 'in-progress',
|
||||||
|
'resultPollState.state': 'polling',
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
{ session, runValidators: true },
|
||||||
|
);
|
||||||
|
expect(models.competition.updateOne).toHaveBeenCalledWith(
|
||||||
|
{ _id: competitionId, revision: preview.revisionBefore },
|
||||||
|
{
|
||||||
|
$set: expect.objectContaining({
|
||||||
|
phase: 'running',
|
||||||
|
revision: preview.revisionAfter,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
{ session, runValidators: true },
|
||||||
|
);
|
||||||
|
expect(models.competitionFact.insertMany).toHaveBeenCalledWith(
|
||||||
|
[
|
||||||
|
expect.objectContaining({
|
||||||
|
type: 'grand-final-rule-corrected',
|
||||||
|
revision: preview.revisionAfter,
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
{ session },
|
||||||
|
);
|
||||||
|
expect(models.competitionOutbox.insertMany).toHaveBeenCalledWith(
|
||||||
|
[
|
||||||
|
expect.objectContaining({
|
||||||
|
type: 'competition.projection-updated',
|
||||||
|
revision: preview.revisionAfter,
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
{ session },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function finishedTournament() {
|
||||||
|
const competitionId = '000000000000000000000001';
|
||||||
|
const teams = Array.from({ length: 8 }, (_, index) => ({
|
||||||
|
teamId: (index + 1).toString(16).padStart(24, '0'),
|
||||||
|
displayOrder: index + 1,
|
||||||
|
seedNumber: index + 1,
|
||||||
|
}));
|
||||||
|
const bo1 = { type: 'first-to', maxGames: 1, winsRequired: 1 } as const;
|
||||||
|
const format = {
|
||||||
|
type: 'double-elimination' as const,
|
||||||
|
teamCount: 8 as const,
|
||||||
|
resetFinalEnabled: false,
|
||||||
|
rules: {
|
||||||
|
upper: { ...bo1, maxGames: 3, winsRequired: 2 },
|
||||||
|
lower: bo1,
|
||||||
|
grandFinal: bo1,
|
||||||
|
resetFinal: bo1,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const seriesGraph = generateSeriesGraph({ competitionId, teams, format });
|
||||||
|
const facts: Record<string, unknown>[] = [];
|
||||||
|
const input = {
|
||||||
|
competitionId,
|
||||||
|
teams,
|
||||||
|
format,
|
||||||
|
seriesGraph,
|
||||||
|
facts,
|
||||||
|
projectorVersion: 1,
|
||||||
|
revision: 0,
|
||||||
|
};
|
||||||
|
for (let index = 0; index < 28; index += 1) {
|
||||||
|
const slot = projectCompetition(input).gameSlots.find(
|
||||||
|
({ status }) => status === 'ready',
|
||||||
|
);
|
||||||
|
if (!slot) break;
|
||||||
|
facts.push(acceptedGame(slot, index + 1, 'A'));
|
||||||
|
input.revision += 1;
|
||||||
|
}
|
||||||
|
return input;
|
||||||
|
}
|
||||||
|
|
||||||
|
function acceptedGame(
|
||||||
|
slot: ReturnType<typeof projectCompetition>['gameSlots'][number],
|
||||||
|
revision: number,
|
||||||
|
winner: 'A' | 'B',
|
||||||
|
): Record<string, unknown> {
|
||||||
|
const [a, b] = slot.entries;
|
||||||
|
const recordedAt = new Date(Date.UTC(2026, 6, 26, 0, revision)).toISOString();
|
||||||
|
return {
|
||||||
|
id: `fact-${revision}`,
|
||||||
|
type: 'game-accepted',
|
||||||
|
revision,
|
||||||
|
ordinalWithinRevision: 1,
|
||||||
|
gameId: `game-${revision}`,
|
||||||
|
seriesId: slot.seriesId,
|
||||||
|
gameSlotId: slot.id,
|
||||||
|
ordinal: slot.ordinal,
|
||||||
|
recordedAt,
|
||||||
|
occurredAt: recordedAt,
|
||||||
|
evidence: { type: 'riot', riotMatchId: `KR_${revision}` },
|
||||||
|
mapping: {
|
||||||
|
blueTeamId: a.teamId,
|
||||||
|
redTeamId: b.teamId,
|
||||||
|
winnerTeamId: winner === 'A' ? a.teamId : b.teamId,
|
||||||
|
participantAssignments: [],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,410 @@
|
|||||||
|
import 'reflect-metadata';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { createHash } from 'node:crypto';
|
||||||
|
import { isDeepStrictEqual } from 'node:util';
|
||||||
|
import { factForProjection } from '../../../competition/competition-command.service';
|
||||||
|
import { projectCompetition } from '../../../competition/domain/competition-projector';
|
||||||
|
import {
|
||||||
|
generateSeriesGraph,
|
||||||
|
type CompetitionGraphFormat,
|
||||||
|
type CompetitionGraphTeam,
|
||||||
|
type SeriesDefinition,
|
||||||
|
} from '../../../competition/domain/series-graph';
|
||||||
|
import { SecretService } from '../../secret/secret.service';
|
||||||
|
import { ConnectionService, resolveMongoDbName } from '../connection.service';
|
||||||
|
|
||||||
|
const CORRECTION_TYPE = 'grand-final-rule-corrected' as const;
|
||||||
|
const BO3 = { type: 'first-to', winsRequired: 2, maxGames: 3 } as const;
|
||||||
|
|
||||||
|
interface RepairInput {
|
||||||
|
competitionId: string;
|
||||||
|
revision: number;
|
||||||
|
projectorVersion: number;
|
||||||
|
teams: readonly CompetitionGraphTeam[];
|
||||||
|
format: CompetitionGraphFormat;
|
||||||
|
seriesGraph: readonly SeriesDefinition[];
|
||||||
|
facts: readonly Record<string, unknown>[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function planGrandFinalBo3Repair(input: RepairInput) {
|
||||||
|
const { format, seriesGraph, facts } = input;
|
||||||
|
const final = seriesGraph.find(({ stage }) => stage.type === 'grand-final');
|
||||||
|
if (
|
||||||
|
format.type !== 'double-elimination' ||
|
||||||
|
format.resetFinalEnabled ||
|
||||||
|
format.rules.grandFinal.type !== 'first-to' ||
|
||||||
|
format.rules.grandFinal.maxGames !== 1 ||
|
||||||
|
format.rules.grandFinal.winsRequired !== 1 ||
|
||||||
|
!final ||
|
||||||
|
!isDeepStrictEqual(final.rule, format.rules.grandFinal) ||
|
||||||
|
final.gameSlots.length !== 1 ||
|
||||||
|
seriesGraph.some(
|
||||||
|
({ stage }) => stage.displayOrder > final.stage.displayOrder,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
'Expected a BO1 grand final with no reset or later series.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const before = projectCompetition(input);
|
||||||
|
const previousFinal = before.series.find(
|
||||||
|
({ seriesId }) => seriesId === final.id,
|
||||||
|
);
|
||||||
|
const finalGames = before.games.filter(
|
||||||
|
({ seriesId }) => seriesId === final.id,
|
||||||
|
);
|
||||||
|
const firstGame = finalGames[0];
|
||||||
|
if (
|
||||||
|
before.phase !== 'completed' ||
|
||||||
|
previousFinal?.status !== 'completed' ||
|
||||||
|
previousFinal.outcome.type !== 'played' ||
|
||||||
|
finalGames.length !== 1 ||
|
||||||
|
firstGame.ordinal !== 1 ||
|
||||||
|
firstGame.evidence.type !== 'riot' ||
|
||||||
|
facts.filter((fact) => fact.seriesId === final.id).length !== 1
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
'Expected exactly one Riot result and no other final facts.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const correctedFormat = {
|
||||||
|
...format,
|
||||||
|
rules: { ...format.rules, grandFinal: BO3 },
|
||||||
|
};
|
||||||
|
const generatedFinal = generateSeriesGraph({
|
||||||
|
competitionId: input.competitionId,
|
||||||
|
teams: input.teams,
|
||||||
|
format: correctedFormat,
|
||||||
|
}).find(({ stage }) => stage.type === 'grand-final');
|
||||||
|
if (
|
||||||
|
generatedFinal?.id !== final.id ||
|
||||||
|
!isDeepStrictEqual(generatedFinal.gameSlots[0], final.gameSlots[0])
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
'The existing grand final does not match its stable slot identity.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const correctedGraph = seriesGraph.map((series) =>
|
||||||
|
series.id === final.id
|
||||||
|
? { ...series, rule: BO3, gameSlots: generatedFinal.gameSlots }
|
||||||
|
: series,
|
||||||
|
);
|
||||||
|
const projection = projectCompetition({
|
||||||
|
...input,
|
||||||
|
revision: input.revision + 1,
|
||||||
|
format: correctedFormat,
|
||||||
|
seriesGraph: correctedGraph,
|
||||||
|
});
|
||||||
|
const readySlots = projection.gameSlots.filter(
|
||||||
|
({ status }) => status === 'ready',
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
projection.phase !== 'running' ||
|
||||||
|
!isDeepStrictEqual(projection.games, before.games) ||
|
||||||
|
readySlots.length !== 2 ||
|
||||||
|
readySlots.some(
|
||||||
|
(slot, index) =>
|
||||||
|
slot.seriesId !== final.id ||
|
||||||
|
slot.ordinal !== index + 2 ||
|
||||||
|
slot.displayNumber !== firstGame.displayNumber + index + 1,
|
||||||
|
) ||
|
||||||
|
!isDeepStrictEqual(
|
||||||
|
projection.series.filter(({ seriesId }) => seriesId !== final.id),
|
||||||
|
before.series.filter(({ seriesId }) => seriesId !== final.id),
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
'Repair would change existing results or fail to reopen the final.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
before,
|
||||||
|
format: correctedFormat,
|
||||||
|
seriesGraph: correctedGraph,
|
||||||
|
projection,
|
||||||
|
seriesId: final.id,
|
||||||
|
preservedGame: firstGame.displayNumber,
|
||||||
|
newGameNumbers: readySlots.map(({ displayNumber }) => displayNumber),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CliOptions {
|
||||||
|
matchId: mongoose.Types.ObjectId;
|
||||||
|
nodeEnv: string;
|
||||||
|
expectedRevision?: number;
|
||||||
|
apply: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseGrandFinalRepairOptions(argv: string[]): CliOptions {
|
||||||
|
let matchId: mongoose.Types.ObjectId | undefined;
|
||||||
|
let nodeEnv = 'dev';
|
||||||
|
let expectedRevision: number | undefined;
|
||||||
|
let apply = false;
|
||||||
|
for (let index = 0; index < argv.length; index += 1) {
|
||||||
|
switch (argv[index]) {
|
||||||
|
case '--':
|
||||||
|
break;
|
||||||
|
case '--apply':
|
||||||
|
apply = true;
|
||||||
|
break;
|
||||||
|
case '--match-id': {
|
||||||
|
const value = argv[++index];
|
||||||
|
if (!/^[a-f\d]{24}$/i.test(value ?? '')) {
|
||||||
|
throw new Error('--match-id must be a 24-character ObjectId.');
|
||||||
|
}
|
||||||
|
matchId = new mongoose.Types.ObjectId(value);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case '--env':
|
||||||
|
nodeEnv = argv[++index];
|
||||||
|
if (!['dev', 'staging', 'prod'].includes(nodeEnv)) {
|
||||||
|
throw new Error('--env must be dev, staging, or prod.');
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case '--expected-revision': {
|
||||||
|
const value = argv[++index];
|
||||||
|
expectedRevision = Number(value);
|
||||||
|
if (
|
||||||
|
!/^\d+$/.test(value ?? '') ||
|
||||||
|
!Number.isSafeInteger(expectedRevision)
|
||||||
|
) {
|
||||||
|
throw new Error('--expected-revision must be a nonnegative integer.');
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
throw new Error(`Unknown argument: ${argv[index]}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!matchId || (apply && expectedRevision === undefined)) {
|
||||||
|
throw new Error(
|
||||||
|
'--match-id is required; --apply also requires --expected-revision from the dry run.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return { matchId, nodeEnv, expectedRevision, apply };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function repairGrandFinalBo3(
|
||||||
|
connectionService: ConnectionService,
|
||||||
|
options: CliOptions,
|
||||||
|
) {
|
||||||
|
if (options.apply && options.expectedRevision === undefined) {
|
||||||
|
throw new Error('An expected revision is required to apply the repair.');
|
||||||
|
}
|
||||||
|
const [Match, Competition, Fact, Outbox] = await Promise.all([
|
||||||
|
connectionService.getModel('match'),
|
||||||
|
connectionService.getModel('competition'),
|
||||||
|
connectionService.getModel('competitionFact'),
|
||||||
|
connectionService.getModel('competitionOutbox'),
|
||||||
|
]);
|
||||||
|
async function run(session: mongoose.ClientSession | null) {
|
||||||
|
const match = await Match.findById(options.matchId)
|
||||||
|
.session(session)
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
if (
|
||||||
|
!match?.competitionId ||
|
||||||
|
match.gameMode !== 'double-elimination' ||
|
||||||
|
match.status !== 'finished' ||
|
||||||
|
!match.teamBuiltAt ||
|
||||||
|
!match.doubleElimination
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
'Expected a finished double-elimination Match with a linked Competition.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const competition = await Competition.findOne({
|
||||||
|
_id: match.competitionId,
|
||||||
|
matchId: match._id,
|
||||||
|
communityId: match.communityId,
|
||||||
|
})
|
||||||
|
.session(session)
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
if (!competition || competition.phase !== 'completed') {
|
||||||
|
throw new Error('Expected a completed Competition linked to this Match.');
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
options.expectedRevision !== undefined &&
|
||||||
|
competition.revision !== options.expectedRevision
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
`Competition revision is ${competition.revision}; run the preview again.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const facts = await Fact.find({ competitionId: competition._id })
|
||||||
|
.sort({ revision: 1, ordinalWithinRevision: 1 })
|
||||||
|
.session(session)
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
const plan = planGrandFinalBo3Repair({
|
||||||
|
competitionId: competition._id.toHexString(),
|
||||||
|
revision: competition.revision,
|
||||||
|
projectorVersion: competition.projectorVersion,
|
||||||
|
teams: competition.teams.map(({ teamId, displayOrder, seedNumber }) => ({
|
||||||
|
teamId: teamId.toHexString(),
|
||||||
|
displayOrder,
|
||||||
|
seedNumber,
|
||||||
|
})),
|
||||||
|
format: competition.format as unknown as CompetitionGraphFormat,
|
||||||
|
seriesGraph: competition.seriesGraph as unknown as SeriesDefinition[],
|
||||||
|
facts: facts.map((fact) => factForProjection({ ...fact })),
|
||||||
|
});
|
||||||
|
if (!isDeepStrictEqual(plan.before, competition.projection)) {
|
||||||
|
throw new Error(
|
||||||
|
'The fact ledger does not reproduce the stored projection.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const revision = plan.projection.sourceRevision;
|
||||||
|
if (session) {
|
||||||
|
const now = new Date();
|
||||||
|
const idempotencyKey = `repair:grand-final-bo3:${competition._id.toHexString()}`;
|
||||||
|
const requestHash = createHash('sha256')
|
||||||
|
.update(idempotencyKey)
|
||||||
|
.digest('hex');
|
||||||
|
const commandId = `cmpcmd_${requestHash.slice(0, 32)}`;
|
||||||
|
const receipt = {
|
||||||
|
competitionId: competition._id,
|
||||||
|
revision,
|
||||||
|
commandId,
|
||||||
|
idempotencyKey,
|
||||||
|
requestHash,
|
||||||
|
};
|
||||||
|
const factId = new mongoose.Types.ObjectId();
|
||||||
|
const competitionWrite = await Competition.updateOne(
|
||||||
|
{ _id: competition._id, revision: competition.revision },
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
revision,
|
||||||
|
format: plan.format,
|
||||||
|
seriesGraph: plan.seriesGraph,
|
||||||
|
projection: plan.projection,
|
||||||
|
phase: plan.projection.phase,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ session, runValidators: true },
|
||||||
|
).exec();
|
||||||
|
const matchWrite = await Match.updateOne(
|
||||||
|
{ _id: match._id, status: 'finished', competitionId: competition._id },
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
status: 'in-progress',
|
||||||
|
'doubleElimination.grandFinalGameCount': 3,
|
||||||
|
...(match.resultPollState
|
||||||
|
? {
|
||||||
|
'resultPollState.state': 'polling',
|
||||||
|
'resultPollState.matchedCount': plan.projection.games.length,
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ session, runValidators: true },
|
||||||
|
).exec();
|
||||||
|
if (
|
||||||
|
competitionWrite.matchedCount !== 1 ||
|
||||||
|
matchWrite.matchedCount !== 1
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
'Match or Competition changed during repair; run the preview again.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await Fact.insertMany(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
...receipt,
|
||||||
|
_id: factId,
|
||||||
|
type: CORRECTION_TYPE,
|
||||||
|
ordinalWithinRevision: 1,
|
||||||
|
schemaVersion: competition.schemaVersion,
|
||||||
|
actor: { type: 'system' },
|
||||||
|
seriesId: new mongoose.Types.ObjectId(plan.seriesId),
|
||||||
|
occurredAt: now,
|
||||||
|
recordedAt: now,
|
||||||
|
reason:
|
||||||
|
'Restore the intended BO3 grand final without voiding the first game.',
|
||||||
|
ruleCorrection: { previousMaxGames: 1, nextMaxGames: 3 },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
{ session },
|
||||||
|
);
|
||||||
|
await Outbox.insertMany(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
...receipt,
|
||||||
|
eventId: `${commandId}:competition-projected`,
|
||||||
|
type: 'competition.projection-updated',
|
||||||
|
payload: {
|
||||||
|
competitionId: competition._id.toHexString(),
|
||||||
|
sourceRevision: revision,
|
||||||
|
factIds: [factId.toHexString()],
|
||||||
|
projection: plan.projection,
|
||||||
|
phase: plan.projection.phase,
|
||||||
|
updatedAt: now,
|
||||||
|
},
|
||||||
|
state: 'pending',
|
||||||
|
availableAt: now,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
{ session },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
mode: session ? 'applied' : 'dry-run',
|
||||||
|
database: resolveMongoDbName(options.nodeEnv),
|
||||||
|
matchId: match._id.toHexString(),
|
||||||
|
competitionId: competition._id.toHexString(),
|
||||||
|
revisionBefore: competition.revision,
|
||||||
|
revisionAfter: revision,
|
||||||
|
phase: `${competition.phase} -> ${plan.projection.phase}`,
|
||||||
|
preservedGame: plan.preservedGame,
|
||||||
|
totalPreservedGames: plan.projection.games.length,
|
||||||
|
newGameNumbers: plan.newGameNumbers,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!options.apply) return run(null);
|
||||||
|
const session = await connectionService.createSession();
|
||||||
|
if (!session) throw new Error('Repair requires a MongoDB transaction.');
|
||||||
|
try {
|
||||||
|
return await session.withTransaction(() => run(session));
|
||||||
|
} finally {
|
||||||
|
await session.endSession();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const args = process.argv.slice(2);
|
||||||
|
if (args.includes('--help')) {
|
||||||
|
process.stdout.write(
|
||||||
|
'Usage: pnpm --filter api competition:repair-grand-final --env <dev|staging|prod> --match-id <id> [--expected-revision <n> --apply]\n',
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const options = parseGrandFinalRepairOptions(args);
|
||||||
|
process.env.NODE_ENV = options.nodeEnv;
|
||||||
|
process.env.MONGODB_AUTO_INDEX = 'false';
|
||||||
|
const connections = new ConnectionService(
|
||||||
|
new SecretService(new ConfigService()),
|
||||||
|
);
|
||||||
|
const connection = await connections.getConnection();
|
||||||
|
try {
|
||||||
|
process.stdout.write(
|
||||||
|
`${JSON.stringify(await repairGrandFinalBo3(connections, options), null, 2)}\n`,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await connection.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (require.main === module) {
|
||||||
|
void main().catch((error: unknown) => {
|
||||||
|
process.stderr.write(
|
||||||
|
`${error instanceof Error ? error.message : String(error)}\n`,
|
||||||
|
);
|
||||||
|
process.exitCode = 1;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
import 'reflect-metadata';
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { ConfigModule } from '@nestjs/config';
|
||||||
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import { readFile } from 'node:fs/promises';
|
||||||
|
import { resolve } from 'node:path';
|
||||||
|
import { ConnectionService, resolveMongoDbName } from '../connection.service';
|
||||||
|
import { SecretModule } from '../../secret/secret.module';
|
||||||
|
import { migrateAuctionCancellationIndex } from './20261109-auction-cancellation-index';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
ConfigModule.forRoot({
|
||||||
|
isGlobal: true,
|
||||||
|
envFilePath: [
|
||||||
|
resolve(__dirname, '../../../../../../project.env'),
|
||||||
|
resolve(process.cwd(), '../project.env'),
|
||||||
|
resolve(process.cwd(), 'apps/project.env'),
|
||||||
|
resolve(process.cwd(), 'project.env'),
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
SecretModule,
|
||||||
|
],
|
||||||
|
providers: [ConnectionService],
|
||||||
|
})
|
||||||
|
class MigrationModule {}
|
||||||
|
|
||||||
|
export function parseAuctionIndexOptions(argv: string[]) {
|
||||||
|
let dryRun = true;
|
||||||
|
let help = false;
|
||||||
|
let nodeEnv = process.env.NODE_ENV ?? 'dev';
|
||||||
|
for (let index = 0; index < argv.length; index++) {
|
||||||
|
const argument = argv[index];
|
||||||
|
if (argument === '--') continue;
|
||||||
|
if (argument === '--apply') dryRun = false;
|
||||||
|
else if (argument === '--dry-run') dryRun = true;
|
||||||
|
else if (argument === '--help' || argument === '-h') help = true;
|
||||||
|
else if (argument === '--env') nodeEnv = argv[++index] ?? '';
|
||||||
|
else if (argument.startsWith('--env=')) nodeEnv = argument.slice(6);
|
||||||
|
else throw new Error(`Unknown argument: ${argument}`);
|
||||||
|
}
|
||||||
|
if (!help && !['dev', 'staging', 'prod'].includes(nodeEnv)) {
|
||||||
|
throw new Error('--env must be dev, staging, or prod.');
|
||||||
|
}
|
||||||
|
return { dryRun, help, nodeEnv };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main(): Promise<void> {
|
||||||
|
const options = parseAuctionIndexOptions(process.argv.slice(2));
|
||||||
|
if (options.help) {
|
||||||
|
console.log(`Usage:
|
||||||
|
pnpm --filter api auction:indexes -- --env staging --dry-run
|
||||||
|
pnpm --filter api auction:indexes -- --env prod --apply
|
||||||
|
|
||||||
|
Defaults to dry-run. --env accepts dev, staging, or prod (NODE_ENV or dev by default).
|
||||||
|
Creates the Match cancellation cleanup partial index; does not modify documents.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Use the same optional machine environment as the existing migration runners.
|
||||||
|
const machineHome = process.env.HOME ?? process.env.USERPROFILE;
|
||||||
|
if (machineHome) {
|
||||||
|
const contents = await readFile(
|
||||||
|
resolve(machineHome, 'source/global-env-vars.txt'),
|
||||||
|
'utf8',
|
||||||
|
).catch(() => '');
|
||||||
|
for (const line of contents.split(/\r?\n/)) {
|
||||||
|
const match = line.trim().match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
|
||||||
|
if (match) process.env[match[1]] = match[2].replace(/^["']|["']$/g, '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
process.env.NODE_ENV = options.nodeEnv;
|
||||||
|
// Even a dry-run with auto-index enabled in the environment must not write.
|
||||||
|
process.env.MONGODB_AUTO_INDEX = 'false';
|
||||||
|
const app = await NestFactory.createApplicationContext(MigrationModule, {
|
||||||
|
logger: ['warn', 'error'],
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const connection = await app.get(ConnectionService).getConnection();
|
||||||
|
if (!connection.db) throw new Error('MongoDB connection has no db handle.');
|
||||||
|
const result = await migrateAuctionCancellationIndex(
|
||||||
|
connection.db,
|
||||||
|
options,
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
JSON.stringify(
|
||||||
|
{
|
||||||
|
env: options.nodeEnv,
|
||||||
|
db: resolveMongoDbName(options.nodeEnv),
|
||||||
|
...result,
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
2,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await app.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (require.main === module) {
|
||||||
|
void main().catch((error: unknown) => {
|
||||||
|
console.error(error instanceof Error ? error.message : error);
|
||||||
|
process.exitCode = 1;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import 'reflect-metadata';
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { ConfigModule } from '@nestjs/config';
|
||||||
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import { readFile } from 'node:fs/promises';
|
||||||
|
import { resolve } from 'node:path';
|
||||||
|
import { ConnectionService, resolveMongoDbName } from '../connection.service';
|
||||||
|
import { SecretModule } from '../../secret/secret.module';
|
||||||
|
import { migrateMatchStatsRawIndex } from './20261111-match-stats-raw-index';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
ConfigModule.forRoot({
|
||||||
|
isGlobal: true,
|
||||||
|
envFilePath: [
|
||||||
|
resolve(__dirname, '../../../../../../project.env'),
|
||||||
|
resolve(process.cwd(), '../project.env'),
|
||||||
|
resolve(process.cwd(), 'apps/project.env'),
|
||||||
|
resolve(process.cwd(), 'project.env'),
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
SecretModule,
|
||||||
|
],
|
||||||
|
providers: [ConnectionService],
|
||||||
|
})
|
||||||
|
class MigrationModule {}
|
||||||
|
|
||||||
|
export function parseMatchStatsIndexOptions(argv: string[]) {
|
||||||
|
let dryRun = true;
|
||||||
|
let help = false;
|
||||||
|
let nodeEnv = process.env.NODE_ENV ?? 'dev';
|
||||||
|
for (let index = 0; index < argv.length; index++) {
|
||||||
|
const argument = argv[index];
|
||||||
|
if (argument === '--') continue;
|
||||||
|
if (argument === '--apply') dryRun = false;
|
||||||
|
else if (argument === '--dry-run') dryRun = true;
|
||||||
|
else if (argument === '--help' || argument === '-h') help = true;
|
||||||
|
else if (argument === '--env') nodeEnv = argv[++index] ?? '';
|
||||||
|
else if (argument.startsWith('--env=')) nodeEnv = argument.slice(6);
|
||||||
|
else throw new Error(`Unknown argument: ${argument}`);
|
||||||
|
}
|
||||||
|
if (!help && !['dev', 'staging', 'prod'].includes(nodeEnv)) {
|
||||||
|
throw new Error('--env must be dev, staging, or prod.');
|
||||||
|
}
|
||||||
|
return { dryRun, help, nodeEnv };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main(): Promise<void> {
|
||||||
|
const options = parseMatchStatsIndexOptions(process.argv.slice(2));
|
||||||
|
if (options.help) {
|
||||||
|
console.log(`Usage:
|
||||||
|
pnpm --filter api stats:indexes -- --env staging --dry-run
|
||||||
|
pnpm --filter api stats:indexes -- --env prod --apply
|
||||||
|
|
||||||
|
Defaults to dry-run. --env accepts dev, staging, or prod (NODE_ENV or dev by default).
|
||||||
|
Creates the internal stats Riot match ID index; does not modify documents.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Use the same optional machine environment as the existing migration runners.
|
||||||
|
const machineHome = process.env.HOME ?? process.env.USERPROFILE;
|
||||||
|
if (machineHome) {
|
||||||
|
const contents = await readFile(
|
||||||
|
resolve(machineHome, 'source/global-env-vars.txt'),
|
||||||
|
'utf8',
|
||||||
|
).catch(() => '');
|
||||||
|
for (const line of contents.split(/\r?\n/)) {
|
||||||
|
const match = line.trim().match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
|
||||||
|
if (match) process.env[match[1]] = match[2].replace(/^["']|["']$/g, '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
process.env.NODE_ENV = options.nodeEnv;
|
||||||
|
// Even a dry-run with auto-index enabled in the environment must not write.
|
||||||
|
process.env.MONGODB_AUTO_INDEX = 'false';
|
||||||
|
const app = await NestFactory.createApplicationContext(MigrationModule, {
|
||||||
|
logger: ['warn', 'error'],
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const connection = await app.get(ConnectionService).getConnection();
|
||||||
|
if (!connection.db) throw new Error('MongoDB connection has no db handle.');
|
||||||
|
const result = await migrateMatchStatsRawIndex(connection.db, options);
|
||||||
|
console.log(
|
||||||
|
JSON.stringify(
|
||||||
|
{
|
||||||
|
env: options.nodeEnv,
|
||||||
|
db: resolveMongoDbName(options.nodeEnv),
|
||||||
|
...result,
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
2,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await app.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (require.main === module) {
|
||||||
|
void main().catch((error: unknown) => {
|
||||||
|
console.error(error instanceof Error ? error.message : error);
|
||||||
|
process.exitCode = 1;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import mongoose, { Schema, HydratedDocument } from 'mongoose';
|
import mongoose, { Schema, HydratedDocument } from 'mongoose';
|
||||||
|
import type { MatchEventType } from '@lolympus/contracts';
|
||||||
import type {
|
import type {
|
||||||
RiotPlatformRoute,
|
RiotPlatformRoute,
|
||||||
RiotRegionalRoute,
|
RiotRegionalRoute,
|
||||||
@@ -12,6 +13,8 @@ import {
|
|||||||
competitionModelDefinitions,
|
competitionModelDefinitions,
|
||||||
} from '../../competition/competition.schema';
|
} from '../../competition/competition.schema';
|
||||||
import { ModelDefinition } from './types';
|
import { ModelDefinition } from './types';
|
||||||
|
import { AUCTION_CANCELLATION_CLEANUP_INDEX } from './auction-cancellation-index';
|
||||||
|
import { MATCH_STATS_RIOT_MATCH_INDEX } from './match-stats-raw-index';
|
||||||
|
|
||||||
export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
|
export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
|
||||||
export const POSITIONS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
|
export const POSITIONS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
|
||||||
@@ -37,6 +40,8 @@ export const MATCH_STATUSES: MatchStatus[] = [
|
|||||||
'finished',
|
'finished',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
export const MATCH_EVENT_TYPES = ['inhouse', 'tournament'] as const satisfies readonly MatchEventType[];
|
||||||
|
|
||||||
export type TeamSide = 'blue' | 'red';
|
export type TeamSide = 'blue' | 'red';
|
||||||
export const TEAM_SIDES: TeamSide[] = ['blue', 'red'];
|
export const TEAM_SIDES: TeamSide[] = ['blue', 'red'];
|
||||||
|
|
||||||
@@ -643,6 +648,7 @@ export interface DoubleEliminationEvent {
|
|||||||
export interface DoubleEliminationBracket {
|
export interface DoubleEliminationBracket {
|
||||||
teamCount: 4 | 8;
|
teamCount: 4 | 8;
|
||||||
resetFinalEnabled: boolean;
|
resetFinalEnabled: boolean;
|
||||||
|
grandFinalGameCount?: 1 | 3 | 5;
|
||||||
resetFinalCreated: boolean;
|
resetFinalCreated: boolean;
|
||||||
seeds: DoubleEliminationSeed[];
|
seeds: DoubleEliminationSeed[];
|
||||||
bracketMatches: DoubleEliminationBracketMatch[];
|
bracketMatches: DoubleEliminationBracketMatch[];
|
||||||
@@ -684,6 +690,7 @@ export interface Match extends MongooseTimestamps {
|
|||||||
competitionId?: mongoose.Types.ObjectId;
|
competitionId?: mongoose.Types.ObjectId;
|
||||||
shortCode?: string;
|
shortCode?: string;
|
||||||
title: string;
|
title: string;
|
||||||
|
eventType?: MatchEventType;
|
||||||
description: string;
|
description: string;
|
||||||
mapId: number; // Riot Match-V5 mapId (11=소환사의 협곡, 12=ARAM 등)
|
mapId: number; // Riot Match-V5 mapId (11=소환사의 협곡, 12=ARAM 등)
|
||||||
status: MatchStatus;
|
status: MatchStatus;
|
||||||
@@ -700,6 +707,12 @@ export interface Match extends MongooseTimestamps {
|
|||||||
teams: MatchTeam[];
|
teams: MatchTeam[];
|
||||||
result?: MatchResult;
|
result?: MatchResult;
|
||||||
resultPollState?: MatchResultPollState;
|
resultPollState?: MatchResultPollState;
|
||||||
|
/** 마지막으로 취소된 Redis 경매 lifecycle. 취소 재전송을 멱등 처리한다. */
|
||||||
|
lastCancelledAuctionLifecycleId?: string;
|
||||||
|
auctionCancellationCleanupPending?: boolean;
|
||||||
|
auctionCancellationCleanupRetryAt?: Date;
|
||||||
|
auctionCancellationCleanupAttempts?: number;
|
||||||
|
auctionCancellationCleanupError?: string;
|
||||||
doubleElimination?: DoubleEliminationBracket;
|
doubleElimination?: DoubleEliminationBracket;
|
||||||
legacyImported?: boolean;
|
legacyImported?: boolean;
|
||||||
legacyImportSource?: {
|
legacyImportSource?: {
|
||||||
@@ -804,12 +817,41 @@ export interface AuctionBid {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface AuctionBidHistoryEntry {
|
export interface AuctionBidHistoryEntry {
|
||||||
|
bidRequestId?: string;
|
||||||
|
revision?: number;
|
||||||
|
bidRoundId?: string;
|
||||||
|
playerUserId?: mongoose.Types.ObjectId;
|
||||||
bidderTeamIndex: number;
|
bidderTeamIndex: number;
|
||||||
bidPointAmount: number;
|
bidPointAmount: number;
|
||||||
bidderUserId: mongoose.Types.ObjectId;
|
bidderUserId: mongoose.Types.ObjectId;
|
||||||
bidPlacedAtTimestampMS: number;
|
bidPlacedAtTimestampMS: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface AuctionBidRecord extends AuctionBidHistoryEntry {
|
||||||
|
_id: string;
|
||||||
|
matchId: mongoose.Types.ObjectId;
|
||||||
|
auctionLifecycleId: string;
|
||||||
|
revision: number;
|
||||||
|
bidRequestId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const AuctionBidRecordSchema = new Schema<AuctionBidRecord>(
|
||||||
|
{
|
||||||
|
_id: { type: String, required: true },
|
||||||
|
matchId: { type: Schema.Types.ObjectId, required: true },
|
||||||
|
auctionLifecycleId: { type: String, required: true },
|
||||||
|
revision: { type: Number, required: true },
|
||||||
|
bidRequestId: { type: String, required: true },
|
||||||
|
bidRoundId: { type: String },
|
||||||
|
playerUserId: { type: Schema.Types.ObjectId },
|
||||||
|
bidderUserId: { type: Schema.Types.ObjectId, required: true },
|
||||||
|
bidderTeamIndex: { type: Number, required: true },
|
||||||
|
bidPointAmount: { type: Number, required: true },
|
||||||
|
bidPlacedAtTimestampMS: { type: Number, required: true },
|
||||||
|
},
|
||||||
|
{ collection: 'auctionBidRecords', versionKey: false },
|
||||||
|
);
|
||||||
|
|
||||||
export interface AuctionChatMessage {
|
export interface AuctionChatMessage {
|
||||||
id: string;
|
id: string;
|
||||||
userId?: mongoose.Types.ObjectId;
|
userId?: mongoose.Types.ObjectId;
|
||||||
@@ -832,6 +874,8 @@ export interface Auction extends MongooseTimestamps {
|
|||||||
matchSideEffectStatus: AuctionMatchSideEffectStatus;
|
matchSideEffectStatus: AuctionMatchSideEffectStatus;
|
||||||
matchSideEffectRevision: number;
|
matchSideEffectRevision: number;
|
||||||
matchSideEffectError?: string;
|
matchSideEffectError?: string;
|
||||||
|
matchSideEffectTransitionId?: string;
|
||||||
|
startupCompleted?: boolean;
|
||||||
teams: AuctionTeam[];
|
teams: AuctionTeam[];
|
||||||
order: AuctionPlayerSnapshot[];
|
order: AuctionPlayerSnapshot[];
|
||||||
passedQueue: AuctionPlayerSnapshot[];
|
passedQueue: AuctionPlayerSnapshot[];
|
||||||
@@ -858,6 +902,7 @@ export interface Auction extends MongooseTimestamps {
|
|||||||
currentHighestBidPointAmount?: number;
|
currentHighestBidPointAmount?: number;
|
||||||
currentHighestBidderTeamIndex?: number;
|
currentHighestBidderTeamIndex?: number;
|
||||||
currentBidRoundDeadlineTimestampMS?: number;
|
currentBidRoundDeadlineTimestampMS?: number;
|
||||||
|
currentBidRoundId?: string;
|
||||||
maximumBidRoundDurationSeconds?: number;
|
maximumBidRoundDurationSeconds?: number;
|
||||||
bidRoundExtensionSeconds?: number;
|
bidRoundExtensionSeconds?: number;
|
||||||
initialTeamBidPointAmount?: number;
|
initialTeamBidPointAmount?: number;
|
||||||
@@ -975,6 +1020,14 @@ export interface MatchStatsRecord {
|
|||||||
championLevel: number;
|
championLevel: number;
|
||||||
teamPosition: string;
|
teamPosition: string;
|
||||||
kills: number;
|
kills: number;
|
||||||
|
multiKills?: {
|
||||||
|
doubleKills: number;
|
||||||
|
tripleKills: number;
|
||||||
|
quadraKills: number;
|
||||||
|
pentaKills: number;
|
||||||
|
largestMultiKill: number;
|
||||||
|
};
|
||||||
|
tier?: TierInfo;
|
||||||
deaths: number;
|
deaths: number;
|
||||||
assists: number;
|
assists: number;
|
||||||
win: boolean;
|
win: boolean;
|
||||||
@@ -1007,6 +1060,7 @@ export interface MatchStatsGameDetail {
|
|||||||
gameCreation: number;
|
gameCreation: number;
|
||||||
gameDuration: number;
|
gameDuration: number;
|
||||||
gameVersion?: string;
|
gameVersion?: string;
|
||||||
|
rawAvailable?: boolean;
|
||||||
winnerSide: TeamSide;
|
winnerSide: TeamSide;
|
||||||
timeline: MatchStatsTimelinePoint[];
|
timeline: MatchStatsTimelinePoint[];
|
||||||
timelineLoaded?: boolean;
|
timelineLoaded?: boolean;
|
||||||
@@ -1811,6 +1865,7 @@ const DoubleEliminationBracketSubSchema = new Schema<DoubleEliminationBracket>(
|
|||||||
{
|
{
|
||||||
teamCount: { type: Number, enum: [4, 8], required: true },
|
teamCount: { type: Number, enum: [4, 8], required: true },
|
||||||
resetFinalEnabled: { type: Boolean, required: true, default: false },
|
resetFinalEnabled: { type: Boolean, required: true, default: false },
|
||||||
|
grandFinalGameCount: { type: Number, enum: [1, 3, 5] },
|
||||||
resetFinalCreated: { type: Boolean, required: true, default: false },
|
resetFinalCreated: { type: Boolean, required: true, default: false },
|
||||||
seeds: {
|
seeds: {
|
||||||
type: [DoubleEliminationSeedSubSchema],
|
type: [DoubleEliminationSeedSubSchema],
|
||||||
@@ -1913,6 +1968,7 @@ export const MatchSchema = new Schema<Match>(
|
|||||||
maxlength: 6,
|
maxlength: 6,
|
||||||
},
|
},
|
||||||
title: { type: String, required: true },
|
title: { type: String, required: true },
|
||||||
|
eventType: { type: String, enum: MATCH_EVENT_TYPES, default: 'inhouse' },
|
||||||
description: { type: String, required: false, default: '' },
|
description: { type: String, required: false, default: '' },
|
||||||
mapId: { type: Number, required: true, default: 11 },
|
mapId: { type: Number, required: true, default: 11 },
|
||||||
status: {
|
status: {
|
||||||
@@ -1971,6 +2027,11 @@ export const MatchSchema = new Schema<Match>(
|
|||||||
type: MatchResultPollStateSubSchema,
|
type: MatchResultPollStateSubSchema,
|
||||||
required: false,
|
required: false,
|
||||||
},
|
},
|
||||||
|
lastCancelledAuctionLifecycleId: { type: String, required: false },
|
||||||
|
auctionCancellationCleanupPending: { type: Boolean },
|
||||||
|
auctionCancellationCleanupRetryAt: { type: Date },
|
||||||
|
auctionCancellationCleanupAttempts: { type: Number },
|
||||||
|
auctionCancellationCleanupError: { type: String },
|
||||||
doubleElimination: {
|
doubleElimination: {
|
||||||
type: DoubleEliminationBracketSubSchema,
|
type: DoubleEliminationBracketSubSchema,
|
||||||
required: false,
|
required: false,
|
||||||
@@ -1995,6 +2056,10 @@ export const MatchSchema = new Schema<Match>(
|
|||||||
);
|
);
|
||||||
|
|
||||||
MatchSchema.index({ communityId: 1, scheduledAt: -1 });
|
MatchSchema.index({ communityId: 1, scheduledAt: -1 });
|
||||||
|
MatchSchema.index(
|
||||||
|
AUCTION_CANCELLATION_CLEANUP_INDEX.key,
|
||||||
|
AUCTION_CANCELLATION_CLEANUP_INDEX.options,
|
||||||
|
);
|
||||||
applyCompetitionDomainInvariantIndexes(MatchSchema, 'match');
|
applyCompetitionDomainInvariantIndexes(MatchSchema, 'match');
|
||||||
MatchSchema.index({ communityId: 1, status: 1, scheduledAt: -1 });
|
MatchSchema.index({ communityId: 1, status: 1, scheduledAt: -1 });
|
||||||
MatchSchema.index(
|
MatchSchema.index(
|
||||||
@@ -2174,6 +2239,8 @@ const AuctionBidSubSchema = new Schema<AuctionBid>(
|
|||||||
|
|
||||||
const AuctionBidHistoryEntrySubSchema = new Schema<AuctionBidHistoryEntry>(
|
const AuctionBidHistoryEntrySubSchema = new Schema<AuctionBidHistoryEntry>(
|
||||||
{
|
{
|
||||||
|
bidRoundId: { type: String },
|
||||||
|
playerUserId: { type: Schema.Types.ObjectId, ref: 'user' },
|
||||||
bidderTeamIndex: { type: Number, required: true, min: 1 },
|
bidderTeamIndex: { type: Number, required: true, min: 1 },
|
||||||
bidPointAmount: { type: Number, required: true },
|
bidPointAmount: { type: Number, required: true },
|
||||||
bidderUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
|
bidderUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
|
||||||
@@ -2195,6 +2262,9 @@ const AuctionChatMessageSubSchema = new Schema<AuctionChatMessage>(
|
|||||||
|
|
||||||
export const AuctionSchema = new Schema<Auction>(
|
export const AuctionSchema = new Schema<Auction>(
|
||||||
{
|
{
|
||||||
|
startupCompleted: { type: Boolean },
|
||||||
|
matchSideEffectTransitionId: { type: String },
|
||||||
|
currentBidRoundId: { type: String },
|
||||||
matchId: {
|
matchId: {
|
||||||
type: Schema.Types.ObjectId,
|
type: Schema.Types.ObjectId,
|
||||||
ref: 'match',
|
ref: 'match',
|
||||||
@@ -2475,7 +2545,7 @@ export const MatchStatsSchema: mongoose.Schema<MatchStats> = new Schema(
|
|||||||
{ timestamps: true, collection: 'match_stats' },
|
{ timestamps: true, collection: 'match_stats' },
|
||||||
) as mongoose.Schema<MatchStats>;
|
) as mongoose.Schema<MatchStats>;
|
||||||
|
|
||||||
MatchStatsSchema.index({ communityId: 1, scheduledAt: -1 });
|
MatchStatsSchema.index({ communityId: 1, scheduledAt: -1, matchId: -1 });
|
||||||
MatchStatsSchema.index({
|
MatchStatsSchema.index({
|
||||||
communityId: 1,
|
communityId: 1,
|
||||||
gameCreationMin: 1,
|
gameCreationMin: 1,
|
||||||
@@ -2484,6 +2554,7 @@ MatchStatsSchema.index({
|
|||||||
MatchStatsSchema.index({ communityId: 1, userIds: 1 });
|
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 });
|
||||||
|
MatchStatsSchema.index(MATCH_STATS_RIOT_MATCH_INDEX.key, MATCH_STATS_RIOT_MATCH_INDEX.options);
|
||||||
|
|
||||||
export const tournamentModelDefinitions: Array<
|
export const tournamentModelDefinitions: Array<
|
||||||
ModelDefinition & { name: keyof TournamentModelTypes }
|
ModelDefinition & { name: keyof TournamentModelTypes }
|
||||||
@@ -2520,6 +2591,11 @@ export const tournamentModelDefinitions: Array<
|
|||||||
},
|
},
|
||||||
{ name: 'match', schema: MatchSchema, schemaName: 'match' },
|
{ name: 'match', schema: MatchSchema, schemaName: 'match' },
|
||||||
{ name: 'auction', schema: AuctionSchema, schemaName: 'auction' },
|
{ name: 'auction', schema: AuctionSchema, schemaName: 'auction' },
|
||||||
|
{
|
||||||
|
name: 'auctionBidRecord',
|
||||||
|
schema: AuctionBidRecordSchema,
|
||||||
|
schemaName: 'auctionBidRecords',
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: 'auctionHistory',
|
name: 'auctionHistory',
|
||||||
schema: AuctionHistoryEntrySchema,
|
schema: AuctionHistoryEntrySchema,
|
||||||
@@ -2553,6 +2629,7 @@ export interface TournamentModelTypes {
|
|||||||
legacyImportJob: LegacyImportJob;
|
legacyImportJob: LegacyImportJob;
|
||||||
match: Match;
|
match: Match;
|
||||||
auction: Auction;
|
auction: Auction;
|
||||||
|
auctionBidRecord: AuctionBidRecord;
|
||||||
auctionHistory: AuctionHistoryEntry;
|
auctionHistory: AuctionHistoryEntry;
|
||||||
auctionSideEffectApplication: AuctionSideEffectApplication;
|
auctionSideEffectApplication: AuctionSideEffectApplication;
|
||||||
matchStats: MatchStats;
|
matchStats: MatchStats;
|
||||||
|
|||||||
@@ -59,16 +59,15 @@ describe('DistributedLockService', () => {
|
|||||||
).resolves.toBe(true);
|
).resolves.toBe(true);
|
||||||
|
|
||||||
expect(sendCommand).toHaveBeenCalledWith([
|
expect(sendCommand).toHaveBeenCalledWith([
|
||||||
'EVAL',
|
'DELEX',
|
||||||
expect.stringContaining('redis.call("GET", KEYS[1]) == ARGV[1]'),
|
|
||||||
'1',
|
|
||||||
'distributed-lock:test',
|
'distributed-lock:test',
|
||||||
|
'IFEQ',
|
||||||
'owner-token',
|
'owner-token',
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('extends a lock only when the ownership token matches', async () => {
|
it('extends a lock only when the ownership token matches', async () => {
|
||||||
const sendCommand = jest.fn().mockResolvedValue(1);
|
const sendCommand = jest.fn().mockResolvedValue('OK');
|
||||||
const service = createService(sendCommand);
|
const service = createService(sendCommand);
|
||||||
|
|
||||||
await expect(
|
await expect(
|
||||||
@@ -83,11 +82,12 @@ describe('DistributedLockService', () => {
|
|||||||
).resolves.toBe(true);
|
).resolves.toBe(true);
|
||||||
|
|
||||||
expect(sendCommand).toHaveBeenCalledWith([
|
expect(sendCommand).toHaveBeenCalledWith([
|
||||||
'EVAL',
|
'SET',
|
||||||
expect.stringContaining('PEXPIRE'),
|
|
||||||
'1',
|
|
||||||
'distributed-lock:test',
|
'distributed-lock:test',
|
||||||
'owner-token',
|
'owner-token',
|
||||||
|
'IFEQ',
|
||||||
|
'owner-token',
|
||||||
|
'PX',
|
||||||
'45000',
|
'45000',
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,20 +2,6 @@ import { Injectable, Logger } from '@nestjs/common';
|
|||||||
import { randomUUID } from 'crypto';
|
import { randomUUID } from 'crypto';
|
||||||
import { RedisService } from './redis.service';
|
import { RedisService } from './redis.service';
|
||||||
|
|
||||||
const RELEASE_LOCK_IF_OWNED_SCRIPT = `
|
|
||||||
if redis.call("GET", KEYS[1]) == ARGV[1] then
|
|
||||||
return redis.call("DEL", KEYS[1])
|
|
||||||
end
|
|
||||||
return 0
|
|
||||||
`;
|
|
||||||
|
|
||||||
const EXTEND_LOCK_IF_OWNED_SCRIPT = `
|
|
||||||
if redis.call("GET", KEYS[1]) == ARGV[1] then
|
|
||||||
return redis.call("PEXPIRE", KEYS[1], ARGV[2])
|
|
||||||
end
|
|
||||||
return 0
|
|
||||||
`;
|
|
||||||
|
|
||||||
export interface DistributedLockOwnership {
|
export interface DistributedLockOwnership {
|
||||||
lockKey: string;
|
lockKey: string;
|
||||||
lockOwnershipToken: string;
|
lockOwnershipToken: string;
|
||||||
@@ -75,10 +61,9 @@ export class DistributedLockService {
|
|||||||
const result = await this.redisService
|
const result = await this.redisService
|
||||||
.raw()
|
.raw()
|
||||||
.sendCommand([
|
.sendCommand([
|
||||||
'EVAL',
|
'DELEX',
|
||||||
RELEASE_LOCK_IF_OWNED_SCRIPT,
|
|
||||||
'1',
|
|
||||||
lockOwnership.lockKey,
|
lockOwnership.lockKey,
|
||||||
|
'IFEQ',
|
||||||
lockOwnership.lockOwnershipToken,
|
lockOwnership.lockOwnershipToken,
|
||||||
]);
|
]);
|
||||||
return Number(result) === 1;
|
return Number(result) === 1;
|
||||||
@@ -95,15 +80,10 @@ export class DistributedLockService {
|
|||||||
|
|
||||||
const result = await this.redisService
|
const result = await this.redisService
|
||||||
.raw()
|
.raw()
|
||||||
.sendCommand([
|
.sendCommand<
|
||||||
'EVAL',
|
string | null
|
||||||
EXTEND_LOCK_IF_OWNED_SCRIPT,
|
>(['SET', lockOwnership.lockKey, lockOwnership.lockOwnershipToken, 'IFEQ', lockOwnership.lockOwnershipToken, 'PX', String(lockExpirationDurationMilliseconds)]);
|
||||||
'1',
|
return result === 'OK';
|
||||||
lockOwnership.lockKey,
|
|
||||||
lockOwnership.lockOwnershipToken,
|
|
||||||
String(lockExpirationDurationMilliseconds),
|
|
||||||
]);
|
|
||||||
return Number(result) === 1;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async runWithLock<TResult>(
|
public async runWithLock<TResult>(
|
||||||
|
|||||||
@@ -1,12 +1,8 @@
|
|||||||
import {
|
import { normalizeRedisUrl, resolveRedisClientOptions } from './redis.config';
|
||||||
assertDistinctRedisInstances,
|
|
||||||
normalizeRedisUrl,
|
|
||||||
resolveRedisClientOptions,
|
|
||||||
} from './redis.config';
|
|
||||||
|
|
||||||
describe('redis.config', () => {
|
describe('redis.config', () => {
|
||||||
it('normalizes host:port endpoints into redis URLs', () => {
|
it('normalizes host:port endpoints into redis URLs', () => {
|
||||||
expect(normalizeRedisUrl('127.0.0.1:6379', 'REDIS_ENDPOINT')).toBe(
|
expect(normalizeRedisUrl(' 127.0.0.1:6379 ')).toBe(
|
||||||
'redis://127.0.0.1:6379',
|
'redis://127.0.0.1:6379',
|
||||||
);
|
);
|
||||||
expect(normalizeRedisUrl('rediss://cache.example.com:6380')).toBe(
|
expect(normalizeRedisUrl('rediss://cache.example.com:6380')).toBe(
|
||||||
@@ -15,8 +11,8 @@ describe('redis.config', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('throws a clear error for empty endpoints', () => {
|
it('throws a clear error for empty endpoints', () => {
|
||||||
expect(() => normalizeRedisUrl(' ', 'REDIS_ENDPOINT')).toThrow(
|
expect(() => normalizeRedisUrl(' ')).toThrow(
|
||||||
'REDIS_ENDPOINT cannot be empty',
|
'GARNET_ENDPOINT cannot be empty',
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -26,34 +22,32 @@ describe('redis.config', () => {
|
|||||||
endpoint: 'redis.internal:6379',
|
endpoint: 'redis.internal:6379',
|
||||||
username: '',
|
username: '',
|
||||||
password: undefined,
|
password: undefined,
|
||||||
endpointEnvName: 'REDIS_ENDPOINT',
|
|
||||||
}),
|
}),
|
||||||
).toEqual({
|
).toEqual({
|
||||||
url: 'redis://redis.internal:6379',
|
url: 'redis://redis.internal:6379',
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('rejects auction Redis when it points at the same physical Redis instance', () => {
|
it.each([undefined, '', ' '])(
|
||||||
expect(() =>
|
'rejects a missing or blank endpoint: %p',
|
||||||
assertDistinctRedisInstances(
|
(endpoint) => {
|
||||||
'redis://cache.internal:6379/0',
|
expect(() => resolveRedisClientOptions({ endpoint })).toThrow(
|
||||||
'redis://cache.internal:6379/1',
|
'GARNET_ENDPOINT cannot be empty',
|
||||||
),
|
);
|
||||||
).toThrow('AUCTION_REDIS must use a separate Redis instance');
|
},
|
||||||
});
|
);
|
||||||
|
|
||||||
it('allows different Redis hosts or ports', () => {
|
it('preserves TLS, database selection, and credentials', () => {
|
||||||
expect(() =>
|
expect(
|
||||||
assertDistinctRedisInstances(
|
resolveRedisClientOptions({
|
||||||
'redis://cache.internal:6379',
|
endpoint: ' rediss://garnet.internal:6380/1 ',
|
||||||
'redis://auction.internal:6379',
|
username: ' garnet-user ',
|
||||||
),
|
password: ' garnet-password ',
|
||||||
).not.toThrow();
|
}),
|
||||||
expect(() =>
|
).toEqual({
|
||||||
assertDistinctRedisInstances(
|
url: 'rediss://garnet.internal:6380/1',
|
||||||
'redis://cache.internal:6379',
|
username: 'garnet-user',
|
||||||
'redis://cache.internal:6380',
|
password: 'garnet-password',
|
||||||
),
|
});
|
||||||
).not.toThrow();
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import type { SecretService } from '../secret/secret.service';
|
||||||
|
|
||||||
export interface RedisClientOptions {
|
export interface RedisClientOptions {
|
||||||
password?: string;
|
password?: string;
|
||||||
url: string;
|
url: string;
|
||||||
@@ -6,10 +8,7 @@ export interface RedisClientOptions {
|
|||||||
|
|
||||||
export interface ResolveRedisClientOptionsParams {
|
export interface ResolveRedisClientOptionsParams {
|
||||||
endpoint?: string;
|
endpoint?: string;
|
||||||
endpointEnvName?: string;
|
|
||||||
password?: string;
|
password?: string;
|
||||||
url?: string;
|
|
||||||
urlEnvName?: string;
|
|
||||||
username?: string;
|
username?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -18,13 +17,10 @@ function trimOptional(value: string | undefined): string | undefined {
|
|||||||
return trimmed ? trimmed : undefined;
|
return trimmed ? trimmed : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function normalizeRedisUrl(
|
export function normalizeRedisUrl(endpointOrUrl: string): string {
|
||||||
endpointOrUrl: string,
|
|
||||||
envName = 'REDIS_URL',
|
|
||||||
): string {
|
|
||||||
const trimmed = endpointOrUrl.trim();
|
const trimmed = endpointOrUrl.trim();
|
||||||
if (!trimmed) {
|
if (!trimmed) {
|
||||||
throw new Error(`${envName} cannot be empty`);
|
throw new Error('GARNET_ENDPOINT cannot be empty');
|
||||||
}
|
}
|
||||||
if (/^redis(s)?:\/\//iu.test(trimmed)) {
|
if (/^redis(s)?:\/\//iu.test(trimmed)) {
|
||||||
return trimmed;
|
return trimmed;
|
||||||
@@ -35,19 +31,8 @@ export function normalizeRedisUrl(
|
|||||||
export function resolveRedisClientOptions(
|
export function resolveRedisClientOptions(
|
||||||
params: ResolveRedisClientOptionsParams,
|
params: ResolveRedisClientOptionsParams,
|
||||||
): RedisClientOptions {
|
): RedisClientOptions {
|
||||||
const url = trimOptional(params.url);
|
|
||||||
const endpoint = trimOptional(params.endpoint);
|
|
||||||
const selectedEndpoint = url ?? endpoint;
|
|
||||||
const selectedEnvName = url
|
|
||||||
? (params.urlEnvName ?? 'REDIS_URL')
|
|
||||||
: (params.endpointEnvName ?? 'REDIS_ENDPOINT');
|
|
||||||
|
|
||||||
if (!selectedEndpoint) {
|
|
||||||
throw new Error(`${selectedEnvName} cannot be empty`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const options: RedisClientOptions = {
|
const options: RedisClientOptions = {
|
||||||
url: normalizeRedisUrl(selectedEndpoint, selectedEnvName),
|
url: normalizeRedisUrl(params.endpoint ?? ''),
|
||||||
};
|
};
|
||||||
const username = trimOptional(params.username);
|
const username = trimOptional(params.username);
|
||||||
const password = trimOptional(params.password);
|
const password = trimOptional(params.password);
|
||||||
@@ -56,22 +41,20 @@ export function resolveRedisClientOptions(
|
|||||||
return options;
|
return options;
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseRedisInstanceIdentity(redisUrl: string): string {
|
export async function loadRedisClientOptions(
|
||||||
const url = new URL(normalizeRedisUrl(redisUrl));
|
secretService: Pick<SecretService, 'get' | 'ready'>,
|
||||||
const hostname = url.hostname.toLowerCase();
|
): Promise<RedisClientOptions> {
|
||||||
const port = url.port || '6379';
|
await secretService.ready();
|
||||||
return `${hostname}:${port}`;
|
const [endpoint, username, userId, password] = await Promise.all([
|
||||||
}
|
secretService.get<string>('GARNET_ENDPOINT', ''),
|
||||||
|
secretService.get<string>('GARNET_USERNAME', ''),
|
||||||
|
secretService.get<string>('GARNET_USERID', ''),
|
||||||
|
secretService.get<string>('GARNET_PASSWORD', ''),
|
||||||
|
]);
|
||||||
|
|
||||||
export function assertDistinctRedisInstances(
|
return resolveRedisClientOptions({
|
||||||
redisUrl: string,
|
endpoint,
|
||||||
auctionRedisUrl: string,
|
password,
|
||||||
): void {
|
username: trimOptional(username) ?? userId,
|
||||||
const redisIdentity = parseRedisInstanceIdentity(redisUrl);
|
});
|
||||||
const auctionRedisIdentity = parseRedisInstanceIdentity(auctionRedisUrl);
|
|
||||||
if (redisIdentity === auctionRedisIdentity) {
|
|
||||||
throw new Error(
|
|
||||||
'AUCTION_REDIS must use a separate Redis instance from REDIS because auction Redis is a live state source of truth.',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
import { Test } from '@nestjs/testing';
|
||||||
|
import { createClient } from 'redis';
|
||||||
|
import { AuctionRedisModule } from '../../auction/redis/auction-redis.module';
|
||||||
|
import { AuctionRedisService } from '../../auction/redis/auction-redis.service';
|
||||||
|
import { SecretService } from '../secret/secret.service';
|
||||||
|
import { RedisModule } from './redis.module';
|
||||||
|
import { RedisService, type RedisClient } from './redis.service';
|
||||||
|
|
||||||
|
jest.mock('redis', () => ({ createClient: jest.fn() }));
|
||||||
|
|
||||||
|
describe('shared Garnet instance', () => {
|
||||||
|
it.each([
|
||||||
|
{
|
||||||
|
name: 'only GARNET_ENDPOINT is configured',
|
||||||
|
secrets: { GARNET_ENDPOINT: 'garnet.internal:6379' },
|
||||||
|
options: { url: 'redis://garnet.internal:6379' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'existing Garnet credentials are configured',
|
||||||
|
secrets: {
|
||||||
|
GARNET_ENDPOINT: ' rediss://garnet.internal:6380/1 ',
|
||||||
|
GARNET_USERID: 'garnet-user',
|
||||||
|
GARNET_PASSWORD: 'garnet-password',
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
url: 'rediss://garnet.internal:6380/1',
|
||||||
|
username: 'garnet-user',
|
||||||
|
password: 'garnet-password',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'obsolete Redis settings are also configured',
|
||||||
|
secrets: {
|
||||||
|
GARNET_ENDPOINT: 'garnet.internal:6379',
|
||||||
|
GARNET_USERNAME: 'garnet-user',
|
||||||
|
GARNET_PASSWORD: 'garnet-password',
|
||||||
|
GARNET_URL: 'redis://obsolete-garnet.internal:6379',
|
||||||
|
REDIS_URL: 'redis://obsolete-common.internal:6379',
|
||||||
|
REDIS_ENDPOINT: 'obsolete-common.internal:6379',
|
||||||
|
REDIS_USERNAME: 'obsolete-common-user',
|
||||||
|
REDIS_PASSWORD: 'obsolete-common-password',
|
||||||
|
AUCTION_REDIS_URL: 'redis://obsolete-common.internal:6379',
|
||||||
|
AUCTION_REDIS_ENDPOINT: 'obsolete-common.internal:6379',
|
||||||
|
AUCTION_REDIS_USERNAME: 'obsolete-auction-user',
|
||||||
|
AUCTION_REDIS_PASSWORD: 'obsolete-auction-password',
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
url: 'redis://garnet.internal:6379',
|
||||||
|
username: 'garnet-user',
|
||||||
|
password: 'garnet-password',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])('boots both Redis modules when $name', async ({ secrets, options }) => {
|
||||||
|
const values: Record<string, string | undefined> = secrets;
|
||||||
|
const secretService = {
|
||||||
|
ready: jest.fn().mockResolvedValue(undefined),
|
||||||
|
get: jest.fn((key: string, fallback: string) =>
|
||||||
|
Promise.resolve(values[key] ?? fallback),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
const clients = Array.from({ length: 2 }, () => ({
|
||||||
|
connect: jest.fn().mockResolvedValue(undefined),
|
||||||
|
on: jest.fn(),
|
||||||
|
quit: jest.fn().mockResolvedValue(undefined),
|
||||||
|
destroy: jest.fn(),
|
||||||
|
}));
|
||||||
|
const createClientMock = jest.mocked(createClient);
|
||||||
|
createClientMock.mockReset();
|
||||||
|
for (const client of clients) {
|
||||||
|
createClientMock.mockReturnValueOnce(client as unknown as RedisClient);
|
||||||
|
}
|
||||||
|
|
||||||
|
const module = await Test.createTestingModule({
|
||||||
|
imports: [RedisModule, AuctionRedisModule],
|
||||||
|
})
|
||||||
|
.overrideProvider(SecretService)
|
||||||
|
.useValue(secretService)
|
||||||
|
.compile();
|
||||||
|
|
||||||
|
try {
|
||||||
|
await module.init();
|
||||||
|
expect(createClientMock).toHaveBeenCalledTimes(2);
|
||||||
|
for (let index = 0; index < clients.length; index++) {
|
||||||
|
expect(createClientMock).toHaveBeenNthCalledWith(index + 1, options);
|
||||||
|
expect(clients[index].connect).toHaveBeenCalledTimes(1);
|
||||||
|
}
|
||||||
|
expect(clients).toContain(module.get(RedisService).raw());
|
||||||
|
expect(clients).toContain(module.get(AuctionRedisService).raw());
|
||||||
|
expect(module.get(RedisService).raw()).not.toBe(
|
||||||
|
module.get(AuctionRedisService).raw(),
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await module.close();
|
||||||
|
}
|
||||||
|
for (const client of clients) {
|
||||||
|
expect(client.quit).toHaveBeenCalledTimes(1);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -3,22 +3,10 @@ import { createClient } from 'redis';
|
|||||||
import { SecretModule } from '../secret/secret.module';
|
import { SecretModule } from '../secret/secret.module';
|
||||||
import { SecretService } from '../secret/secret.service';
|
import { SecretService } from '../secret/secret.service';
|
||||||
import { REDIS_CLIENT } from './redis.constants';
|
import { REDIS_CLIENT } from './redis.constants';
|
||||||
import { resolveRedisClientOptions } from './redis.config';
|
import { loadRedisClientOptions } from './redis.config';
|
||||||
import { DistributedLockService } from './distributed-lock.service';
|
import { DistributedLockService } from './distributed-lock.service';
|
||||||
import { RedisService, type RedisClient } from './redis.service';
|
import { RedisService, type RedisClient } from './redis.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: [
|
||||||
@@ -28,30 +16,9 @@ async function readFirstSecret(
|
|||||||
useFactory: async (
|
useFactory: async (
|
||||||
secretService: SecretService,
|
secretService: SecretService,
|
||||||
): Promise<RedisClient> => {
|
): Promise<RedisClient> => {
|
||||||
await secretService.ready();
|
|
||||||
|
|
||||||
const [url, endpoint, username, password] = await Promise.all([
|
|
||||||
readFirstSecret(secretService, ['REDIS_URL', 'GARNET_URL']),
|
|
||||||
readFirstSecret(secretService, ['REDIS_ENDPOINT', 'GARNET_ENDPOINT']),
|
|
||||||
readFirstSecret(secretService, [
|
|
||||||
'REDIS_USERNAME',
|
|
||||||
'REDIS_USERID',
|
|
||||||
'GARNET_USERNAME',
|
|
||||||
'GARNET_USERID',
|
|
||||||
]),
|
|
||||||
readFirstSecret(secretService, ['REDIS_PASSWORD', 'GARNET_PASSWORD']),
|
|
||||||
]);
|
|
||||||
|
|
||||||
const logger = new Logger('RedisClient');
|
const logger = new Logger('RedisClient');
|
||||||
const client = createClient(
|
const client = createClient(
|
||||||
resolveRedisClientOptions({
|
await loadRedisClientOptions(secretService),
|
||||||
endpoint,
|
|
||||||
endpointEnvName: 'REDIS_ENDPOINT',
|
|
||||||
password,
|
|
||||||
url,
|
|
||||||
urlEnvName: 'REDIS_URL',
|
|
||||||
username,
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
client.on('error', (error: unknown) => {
|
client.on('error', (error: unknown) => {
|
||||||
|
|||||||
@@ -5,6 +5,24 @@ function createRedisService(client: Record<string, unknown>) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe('RedisService stream pending recovery', () => {
|
describe('RedisService stream pending recovery', () => {
|
||||||
|
it('destroys a dedicated client when connection startup fails without closing the shared client', async () => {
|
||||||
|
const error = new Error('connection failed');
|
||||||
|
const dedicated = {
|
||||||
|
on: jest.fn(),
|
||||||
|
connect: jest.fn().mockRejectedValue(error),
|
||||||
|
isOpen: true,
|
||||||
|
destroy: jest.fn(),
|
||||||
|
};
|
||||||
|
const shared = {
|
||||||
|
duplicate: jest.fn().mockReturnValue(dedicated),
|
||||||
|
destroy: jest.fn(),
|
||||||
|
};
|
||||||
|
const service = createRedisService(shared);
|
||||||
|
await expect(service.createDedicatedConnection()).rejects.toBe(error);
|
||||||
|
expect(dedicated.destroy).toHaveBeenCalledTimes(1);
|
||||||
|
expect(shared.destroy).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
it('normalizes XAUTOCLAIM array replies into stream entries', async () => {
|
it('normalizes XAUTOCLAIM array replies into stream entries', async () => {
|
||||||
const sendCommand = jest
|
const sendCommand = jest
|
||||||
.fn()
|
.fn()
|
||||||
|
|||||||
@@ -83,6 +83,20 @@ export class RedisService implements OnModuleDestroy {
|
|||||||
return this.client;
|
return this.client;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async createDedicatedConnection(): Promise<RedisService> {
|
||||||
|
const client = this.client.duplicate();
|
||||||
|
client.on('error', (error: unknown) => {
|
||||||
|
this.logger.warn(`Dedicated Redis connection error: ${String(error)}`);
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
await client.connect();
|
||||||
|
return new RedisService(client);
|
||||||
|
} catch (error) {
|
||||||
|
if (client.isOpen) client.destroy();
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public async getJson<T>(key: string): Promise<T | null> {
|
public async getJson<T>(key: string): Promise<T | null> {
|
||||||
const raw = await this.client.get(key);
|
const raw = await this.client.get(key);
|
||||||
if (!raw) return null;
|
if (!raw) return null;
|
||||||
@@ -142,6 +156,13 @@ export class RedisService implements OnModuleDestroy {
|
|||||||
return this.client.del(key);
|
return this.client.del(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async deleteStringIfEqual(
|
||||||
|
key: string,
|
||||||
|
value: string,
|
||||||
|
): Promise<number> {
|
||||||
|
return this.client.sendCommand<number>(['DELEX', key, 'IFEQ', value]);
|
||||||
|
}
|
||||||
|
|
||||||
public async appendStream(
|
public async appendStream(
|
||||||
key: string,
|
key: string,
|
||||||
fields: Record<string, string>,
|
fields: Record<string, string>,
|
||||||
@@ -158,7 +179,10 @@ export class RedisService implements OnModuleDestroy {
|
|||||||
}
|
}
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
return this.client.xAdd(key, '*', fields, trimOptions);
|
return this.client.xAdd(key, '*', fields, {
|
||||||
|
...trimOptions,
|
||||||
|
policy: 'ACKED',
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public async createConsumerGroup(
|
public async createConsumerGroup(
|
||||||
@@ -174,11 +198,13 @@ export class RedisService implements OnModuleDestroy {
|
|||||||
group: string,
|
group: string,
|
||||||
consumer: string,
|
consumer: string,
|
||||||
startId: string,
|
startId: string,
|
||||||
options?: { blockMs?: number; count?: number },
|
options?: { blockMs?: number; count?: number; claimMinIdleMs?: number },
|
||||||
): Promise<StreamReadResult[] | null> {
|
): Promise<StreamReadResult[] | null> {
|
||||||
const readOptions: { BLOCK?: number; COUNT?: number } = {};
|
const readOptions: { BLOCK?: number; COUNT?: number; CLAIM?: number } = {};
|
||||||
if (options?.blockMs !== undefined) readOptions.BLOCK = options.blockMs;
|
if (options?.blockMs !== undefined) readOptions.BLOCK = options.blockMs;
|
||||||
if (options?.count !== undefined) readOptions.COUNT = options.count;
|
if (options?.count !== undefined) readOptions.COUNT = options.count;
|
||||||
|
if (options?.claimMinIdleMs !== undefined)
|
||||||
|
readOptions.CLAIM = options.claimMinIdleMs;
|
||||||
|
|
||||||
const reply = await this.client.xReadGroup(
|
const reply = await this.client.xReadGroup(
|
||||||
group,
|
group,
|
||||||
@@ -244,6 +270,14 @@ export class RedisService implements OnModuleDestroy {
|
|||||||
return this.client.xAck(key, group, ids);
|
return this.client.xAck(key, group, ids);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async acknowledgeAndDeleteStream(
|
||||||
|
key: string,
|
||||||
|
group: string,
|
||||||
|
ids: string | string[],
|
||||||
|
): Promise<void> {
|
||||||
|
await this.client.xAckDel(key, group, ids, 'ACKED');
|
||||||
|
}
|
||||||
|
|
||||||
public async deleteStreamEntries(
|
public async deleteStreamEntries(
|
||||||
key: string,
|
key: string,
|
||||||
ids: string | string[],
|
ids: string | string[],
|
||||||
|
|||||||
@@ -0,0 +1,183 @@
|
|||||||
|
import { loadInfisicalSecrets } from './infisical-client';
|
||||||
|
|
||||||
|
const options = {
|
||||||
|
siteUrl: 'https://infisical.example.test/prefix',
|
||||||
|
clientId: 'test-client',
|
||||||
|
clientSecret: 'test-secret',
|
||||||
|
projectId: 'test-project',
|
||||||
|
environment: 'staging',
|
||||||
|
};
|
||||||
|
const secrets = [{ secretKey: 'TEST_SECRET', secretValue: 'value' }];
|
||||||
|
const json = (value: unknown, status = 200) =>
|
||||||
|
new Response(JSON.stringify(value), { status });
|
||||||
|
|
||||||
|
describe('Infisical bootstrap client', () => {
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
let fetchMock: jest.Mock;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
fetchMock = jest.fn();
|
||||||
|
global.fetch = fetchMock;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
jest.useRealTimers();
|
||||||
|
jest.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
'https://infisical.example.test/prefix',
|
||||||
|
'https://infisical.example.test/prefix/',
|
||||||
|
])(
|
||||||
|
'preserves SDK URLs, auth headers and list defaults for %s',
|
||||||
|
async (siteUrl) => {
|
||||||
|
fetchMock
|
||||||
|
.mockResolvedValueOnce(json({ accessToken: 'token' }))
|
||||||
|
.mockResolvedValueOnce(json({ secrets }));
|
||||||
|
await expect(
|
||||||
|
loadInfisicalSecrets({ ...options, siteUrl }),
|
||||||
|
).resolves.toEqual({ secrets });
|
||||||
|
expect(fetchMock).toHaveBeenNthCalledWith(
|
||||||
|
1,
|
||||||
|
'https://infisical.example.test/prefix/api/v1/auth/universal-auth/login',
|
||||||
|
expect.objectContaining({
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
clientId: options.clientId,
|
||||||
|
clientSecret: options.clientSecret,
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(fetchMock).toHaveBeenNthCalledWith(
|
||||||
|
2,
|
||||||
|
'https://infisical.example.test/prefix/api/v3/secrets/raw?workspaceId=test-project&environment=staging&expandSecretReferences=true&include_imports=false&recursive=false&viewSecretValue=true',
|
||||||
|
expect.objectContaining({
|
||||||
|
method: 'GET',
|
||||||
|
headers: { Authorization: 'Bearer token' },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it('retries network errors and 429 using the same request', async () => {
|
||||||
|
jest.useFakeTimers();
|
||||||
|
jest.spyOn(Math, 'random').mockReturnValue(0.5);
|
||||||
|
fetchMock
|
||||||
|
.mockRejectedValueOnce(new Error('network error'))
|
||||||
|
.mockResolvedValueOnce(json({}, 429))
|
||||||
|
.mockResolvedValueOnce(json({ accessToken: 'token' }))
|
||||||
|
.mockResolvedValueOnce(json({ secrets }));
|
||||||
|
const result = loadInfisicalSecrets(options);
|
||||||
|
await jest.runAllTimersAsync();
|
||||||
|
await expect(result).resolves.toEqual({ secrets });
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(4);
|
||||||
|
expect(fetchMock.mock.calls.slice(0, 3).map(([url]) => url)).toEqual(
|
||||||
|
Array(3).fill(
|
||||||
|
'https://infisical.example.test/prefix/api/v1/auth/universal-auth/login',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(jest.getTimerCount()).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([401, 403, 500])(
|
||||||
|
'does not retry HTTP %i or fetch secrets after failed login',
|
||||||
|
async (status) => {
|
||||||
|
fetchMock.mockResolvedValueOnce(json({ message: 'test-secret' }, status));
|
||||||
|
await expect(loadInfisicalSecrets(options)).rejects.toThrow(
|
||||||
|
`failed with ${status}`,
|
||||||
|
);
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it('stops after four retries and does not expose response bodies', async () => {
|
||||||
|
jest.useFakeTimers();
|
||||||
|
fetchMock.mockImplementation(() =>
|
||||||
|
Promise.resolve(json({ message: 'test-secret' }, 429)),
|
||||||
|
);
|
||||||
|
const error = loadInfisicalSecrets(options).catch(
|
||||||
|
(value: unknown) => value,
|
||||||
|
);
|
||||||
|
await jest.runAllTimersAsync();
|
||||||
|
expect(await error).toEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
message: expect.stringContaining('failed with 429'),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(((await error) as Error).message).not.toContain('test-secret');
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(5);
|
||||||
|
expect(jest.getTimerCount()).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('aborts each stalled attempt after ten seconds and bounds the retries', async () => {
|
||||||
|
jest.useFakeTimers();
|
||||||
|
jest.spyOn(Math, 'random').mockReturnValue(0.5);
|
||||||
|
fetchMock.mockImplementation(
|
||||||
|
(_url: string, init: RequestInit) =>
|
||||||
|
new Promise((_resolve, reject) => {
|
||||||
|
init.signal!.addEventListener(
|
||||||
|
'abort',
|
||||||
|
() => reject(new Error('aborted')),
|
||||||
|
{ once: true },
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const error = loadInfisicalSecrets(options).catch(
|
||||||
|
(value: unknown) => value,
|
||||||
|
);
|
||||||
|
await jest.advanceTimersByTimeAsync(9_999);
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||||
|
expect((fetchMock.mock.calls[0][1] as RequestInit).signal!.aborted).toBe(
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
await jest.runAllTimersAsync();
|
||||||
|
expect(await error).toEqual(new Error('aborted'));
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(5);
|
||||||
|
expect(jest.getTimerCount()).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([{}, { accessToken: '' }, { accessToken: 123 }])(
|
||||||
|
'rejects invalid login response %j',
|
||||||
|
async (login) => {
|
||||||
|
fetchMock.mockResolvedValueOnce(json(login));
|
||||||
|
await expect(loadInfisicalSecrets(options)).rejects.toThrow(
|
||||||
|
'did not return an access token',
|
||||||
|
);
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it.each(['login', 'secrets'])(
|
||||||
|
'does not leak malformed %s response bodies through errors',
|
||||||
|
async (operation) => {
|
||||||
|
if (operation === 'secrets') {
|
||||||
|
fetchMock.mockResolvedValueOnce(json({ accessToken: 'token' }));
|
||||||
|
}
|
||||||
|
fetchMock.mockResolvedValueOnce(new Response('sensitive-secret'));
|
||||||
|
const error = await loadInfisicalSecrets(options).catch(
|
||||||
|
(value: unknown) => value,
|
||||||
|
);
|
||||||
|
expect(error).toHaveProperty(
|
||||||
|
'message',
|
||||||
|
'Infisical returned an invalid JSON response',
|
||||||
|
);
|
||||||
|
expect((error as Error).stack).not.toContain('sensitive-secret');
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(operation === 'login' ? 1 : 2);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
{},
|
||||||
|
{ secrets: null },
|
||||||
|
{ secrets: [{ secretKey: 'KEY', secretValue: 123 }] },
|
||||||
|
])('rejects invalid secrets response %j', async (result) => {
|
||||||
|
fetchMock
|
||||||
|
.mockResolvedValueOnce(json({ accessToken: 'token' }))
|
||||||
|
.mockResolvedValueOnce(json(result));
|
||||||
|
await expect(loadInfisicalSecrets(options)).rejects.toThrow(
|
||||||
|
'invalid secrets response',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
interface InfisicalOptions {
|
||||||
|
siteUrl: string;
|
||||||
|
clientId: string;
|
||||||
|
clientSecret: string;
|
||||||
|
projectId: string;
|
||||||
|
environment: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface InfisicalSecret {
|
||||||
|
secretKey: string;
|
||||||
|
secretValue: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const REQUEST_TIMEOUT_MS = 10_000;
|
||||||
|
const MAX_RETRIES = 4;
|
||||||
|
|
||||||
|
/** The two Infisical operations used during SecretService initialization. */
|
||||||
|
export async function loadInfisicalSecrets(
|
||||||
|
options: InfisicalOptions,
|
||||||
|
): Promise<{ secrets: InfisicalSecret[] }> {
|
||||||
|
const baseUrl = options.siteUrl.endsWith('/')
|
||||||
|
? options.siteUrl
|
||||||
|
: `${options.siteUrl}/`;
|
||||||
|
const login = await requestJson(
|
||||||
|
new URL('api/v1/auth/universal-auth/login', baseUrl),
|
||||||
|
{
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
clientId: options.clientId,
|
||||||
|
clientSecret: options.clientSecret,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
!isRecord(login) ||
|
||||||
|
typeof login.accessToken !== 'string' ||
|
||||||
|
!login.accessToken
|
||||||
|
) {
|
||||||
|
throw new Error('Infisical login did not return an access token');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Preserve the SDK's v3 endpoint and defaults, including self-hosted URL prefixes.
|
||||||
|
const url = new URL('api/v3/secrets/raw', baseUrl);
|
||||||
|
url.search = new URLSearchParams({
|
||||||
|
workspaceId: options.projectId,
|
||||||
|
environment: options.environment,
|
||||||
|
expandSecretReferences: 'true',
|
||||||
|
include_imports: 'false',
|
||||||
|
recursive: 'false',
|
||||||
|
viewSecretValue: 'true',
|
||||||
|
}).toString();
|
||||||
|
const result = await requestJson(url, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: { Authorization: `Bearer ${login.accessToken}` },
|
||||||
|
});
|
||||||
|
if (
|
||||||
|
!isRecord(result) ||
|
||||||
|
!Array.isArray(result.secrets) ||
|
||||||
|
!result.secrets.every(isSecret)
|
||||||
|
) {
|
||||||
|
throw new Error('Infisical returned an invalid secrets response');
|
||||||
|
}
|
||||||
|
return { secrets: result.secrets };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function requestJson(url: URL, init: RequestInit): Promise<unknown> {
|
||||||
|
for (let attempt = 0; ; attempt += 1) {
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
||||||
|
let response: Response;
|
||||||
|
try {
|
||||||
|
response = await fetch(url.toString(), {
|
||||||
|
...init,
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (attempt >= MAX_RETRIES) throw error;
|
||||||
|
clearTimeout(timeout);
|
||||||
|
await retryDelay(attempt);
|
||||||
|
continue;
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Match the SDK: retry network errors and 429, but not other HTTP errors.
|
||||||
|
if (response.status === 429 && attempt < MAX_RETRIES) {
|
||||||
|
await response.body?.cancel();
|
||||||
|
await retryDelay(attempt);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!response.ok) {
|
||||||
|
await response.body?.cancel();
|
||||||
|
throw new Error(
|
||||||
|
`Infisical ${init.method} ${url.pathname} failed with ${response.status}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return await response.json();
|
||||||
|
} catch {
|
||||||
|
// JSON parse errors can contain secrets from the response body.
|
||||||
|
throw new Error('Infisical returned an invalid JSON response');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function retryDelay(attempt: number): Promise<void> {
|
||||||
|
const base = 1_000 * 2 ** attempt;
|
||||||
|
const delay = base + base * 0.2 * (Math.random() * 2 - 1);
|
||||||
|
return new Promise((resolve) => setTimeout(resolve, delay));
|
||||||
|
}
|
||||||
|
|
||||||
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
|
return typeof value === 'object' && value !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSecret(value: unknown): value is InfisicalSecret {
|
||||||
|
return (
|
||||||
|
isRecord(value) &&
|
||||||
|
typeof value.secretKey === 'string' &&
|
||||||
|
typeof value.secretValue === 'string'
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@ function makeConfig(values: Record<string, string | undefined> = {}) {
|
|||||||
|
|
||||||
describe('SecretService', () => {
|
describe('SecretService', () => {
|
||||||
const originalEnv = process.env;
|
const originalEnv = process.env;
|
||||||
|
const originalFetch = global.fetch;
|
||||||
let fetchMock: jest.Mock;
|
let fetchMock: jest.Mock;
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
@@ -23,9 +24,94 @@ describe('SecretService', () => {
|
|||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
process.env = originalEnv;
|
process.env = originalEnv;
|
||||||
|
global.fetch = originalFetch;
|
||||||
jest.restoreAllMocks();
|
jest.restoreAllMocks();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
function infisicalConfig() {
|
||||||
|
return makeConfig({
|
||||||
|
SECRET_SOURCE: 'infisical',
|
||||||
|
INFISICAL_SITE_URL: 'https://infisical.example.test/',
|
||||||
|
INFISICAL_CLIENT_ID: 'test-client',
|
||||||
|
INFISICAL_CLIENT_SECRET: 'test-secret',
|
||||||
|
INFISICAL_PROJECT_ID: 'test-project',
|
||||||
|
CONFIG_FALLBACK: 'config-value',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['prod', 'prod'],
|
||||||
|
['staging', 'staging'],
|
||||||
|
['dev', 'dev'],
|
||||||
|
['production', 'dev'],
|
||||||
|
])('preserves environment mapping %s -> %s', async (nodeEnv, environment) => {
|
||||||
|
process.env.NODE_ENV = nodeEnv;
|
||||||
|
fetchMock
|
||||||
|
.mockResolvedValueOnce(Response.json({ accessToken: 'token' }))
|
||||||
|
.mockResolvedValueOnce(Response.json({ secrets: [] }));
|
||||||
|
await new SecretService(infisicalConfig()).ready();
|
||||||
|
const url = new URL(fetchMock.mock.calls[1][0] as string);
|
||||||
|
expect(url.searchParams.get('environment')).toBe(environment);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shares initialization, caches secrets, and preserves empty values and fallbacks', async () => {
|
||||||
|
process.env.TEST_EMPTY = 'existing-value';
|
||||||
|
fetchMock
|
||||||
|
.mockResolvedValueOnce(Response.json({ accessToken: 'token' }))
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
Response.json({
|
||||||
|
secrets: [
|
||||||
|
{ secretKey: 'TEST_SECRET', secretValue: 'first' },
|
||||||
|
{ secretKey: 'TEST_SECRET', secretValue: 'last' },
|
||||||
|
{ secretKey: 'TEST_EMPTY', secretValue: '' },
|
||||||
|
],
|
||||||
|
imports: [
|
||||||
|
{ secrets: [{ secretKey: 'TEST_IMPORT', secretValue: 'ignored' }] },
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const service = new SecretService(infisicalConfig());
|
||||||
|
await Promise.all([
|
||||||
|
service.ready(),
|
||||||
|
service.get('TEST_SECRET'),
|
||||||
|
service.ready(),
|
||||||
|
]);
|
||||||
|
await expect(service.get('TEST_SECRET')).resolves.toBe('last');
|
||||||
|
await expect(service.get('TEST_EMPTY')).resolves.toBe('');
|
||||||
|
await expect(service.get('CONFIG_FALLBACK')).resolves.toBe('config-value');
|
||||||
|
await expect(service.get('TEST_IMPORT', 'missing')).resolves.toBe(
|
||||||
|
'missing',
|
||||||
|
);
|
||||||
|
expect(process.env.TEST_SECRET).toBe('last');
|
||||||
|
expect(process.env.TEST_EMPTY).toBe('existing-value');
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not publish partial secrets after failure and permits a later retry', async () => {
|
||||||
|
fetchMock
|
||||||
|
.mockResolvedValueOnce(Response.json({ accessToken: 'token' }))
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
Response.json({
|
||||||
|
secrets: [
|
||||||
|
{ secretKey: 'TEST_SECRET', secretValue: 'partial' },
|
||||||
|
{ secretKey: 'INVALID', secretValue: 123 },
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.mockResolvedValueOnce(Response.json({ accessToken: 'new-token' }))
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
Response.json({
|
||||||
|
secrets: [{ secretKey: 'TEST_SECRET', secretValue: 'complete' }],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const service = new SecretService(infisicalConfig());
|
||||||
|
await expect(service.ready()).rejects.toThrow('invalid secrets response');
|
||||||
|
expect(process.env.TEST_SECRET).toBeUndefined();
|
||||||
|
await service.ready();
|
||||||
|
await expect(service.get('TEST_SECRET')).resolves.toBe('complete');
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(4);
|
||||||
|
});
|
||||||
|
|
||||||
it('defaults to environment-provided secrets without IMDS lookup', async () => {
|
it('defaults to environment-provided secrets without IMDS lookup', async () => {
|
||||||
process.env.TEST_SECRET = 'from-env';
|
process.env.TEST_SECRET = 'from-env';
|
||||||
const service = new SecretService(makeConfig());
|
const service = new SecretService(makeConfig());
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Injectable, Logger } from '@nestjs/common';
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
import { InfisicalSDK } from '@infisical/sdk';
|
|
||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { loadInfisicalSecrets } from './infisical-client';
|
||||||
|
|
||||||
type SecretMap = Record<string, string | undefined>;
|
type SecretMap = Record<string, string | undefined>;
|
||||||
type SecretSource = 'env' | 'infisical';
|
type SecretSource = 'env' | 'infisical';
|
||||||
@@ -71,23 +71,14 @@ export class SecretService {
|
|||||||
|
|
||||||
private async fetchInfisicalSecrets(): Promise<void> {
|
private async fetchInfisicalSecrets(): Promise<void> {
|
||||||
const bootstrapConfig = await this.resolveInfisicalBootstrapConfig();
|
const bootstrapConfig = await this.resolveInfisicalBootstrapConfig();
|
||||||
const infisicalClient = new InfisicalSDK({
|
const res = await loadInfisicalSecrets({
|
||||||
siteUrl: bootstrapConfig.siteUrl,
|
...bootstrapConfig,
|
||||||
});
|
|
||||||
|
|
||||||
await infisicalClient.auth().universalAuth.login({
|
|
||||||
clientId: bootstrapConfig.clientId,
|
|
||||||
clientSecret: bootstrapConfig.clientSecret,
|
|
||||||
});
|
|
||||||
|
|
||||||
const res = await infisicalClient.secrets().listSecrets({
|
|
||||||
environment:
|
environment:
|
||||||
process.env.NODE_ENV === 'prod'
|
process.env.NODE_ENV === 'prod'
|
||||||
? 'prod'
|
? 'prod'
|
||||||
: process.env.NODE_ENV === 'staging'
|
: process.env.NODE_ENV === 'staging'
|
||||||
? 'staging'
|
? 'staging'
|
||||||
: 'dev',
|
: 'dev',
|
||||||
projectId: bootstrapConfig.projectId,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// 임시 객체에 채운 뒤 한 번에 교체(일관성 보장)
|
// 임시 객체에 채운 뒤 한 번에 교체(일관성 보장)
|
||||||
|
|||||||
@@ -389,6 +389,7 @@ describe('Legacy import Competition result cutover', () => {
|
|||||||
}),
|
}),
|
||||||
} as unknown as ConnectionService;
|
} as unknown as ConnectionService;
|
||||||
const communityStatsService = {
|
const communityStatsService = {
|
||||||
|
refreshForRiotMatches: jest.fn().mockResolvedValue(undefined),
|
||||||
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
|
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
|
||||||
} as unknown as jest.Mocked<CommunityStatsService>;
|
} as unknown as jest.Mocked<CommunityStatsService>;
|
||||||
const service = createService({
|
const service = createService({
|
||||||
@@ -642,6 +643,7 @@ function createService(
|
|||||||
{} as RiotMatchService,
|
{} as RiotMatchService,
|
||||||
options.communityStatsService ??
|
options.communityStatsService ??
|
||||||
({
|
({
|
||||||
|
refreshForRiotMatches: jest.fn().mockResolvedValue(undefined),
|
||||||
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
|
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
|
||||||
} as unknown as CommunityStatsService),
|
} as unknown as CommunityStatsService),
|
||||||
options.matchStatsService ?? ({} as MatchStatsService),
|
options.matchStatsService ?? ({} as MatchStatsService),
|
||||||
@@ -691,12 +693,20 @@ function createImportFixture() {
|
|||||||
gameName: `player-${index + 1}`,
|
gameName: `player-${index + 1}`,
|
||||||
tagLine: 'KR1',
|
tagLine: 'KR1',
|
||||||
profileIconId: index + 1,
|
profileIconId: index + 1,
|
||||||
|
revisionDate: 0,
|
||||||
|
summonerLevel: 30,
|
||||||
tiers: [],
|
tiers: [],
|
||||||
|
tierHistory: [],
|
||||||
|
matchIds: [],
|
||||||
|
championMasteries: [],
|
||||||
|
championRecords: {},
|
||||||
isPrimary: true,
|
isPrimary: true,
|
||||||
|
createdAt: new Date('2026-07-12T00:00:00.000Z'),
|
||||||
|
updatedAt: new Date('2026-07-12T00:00:00.000Z'),
|
||||||
},
|
},
|
||||||
displayName: `player-${index + 1}`,
|
displayName: `player-${index + 1}`,
|
||||||
preferredPositions: [],
|
preferredPositions: [],
|
||||||
} as LegacyUserSnapshot,
|
} satisfies LegacyUserSnapshot,
|
||||||
]),
|
]),
|
||||||
);
|
);
|
||||||
const participants = users.map(({ puuid }, index) => ({
|
const participants = users.map(({ puuid }, index) => ({
|
||||||
@@ -969,6 +979,7 @@ function createBulkDeleteFailureHarness(options: {
|
|||||||
}),
|
}),
|
||||||
} as unknown as ConnectionService;
|
} as unknown as ConnectionService;
|
||||||
const communityStatsService = {
|
const communityStatsService = {
|
||||||
|
refreshForRiotMatches: jest.fn().mockResolvedValue(undefined),
|
||||||
invalidateCommunity: jest.fn().mockResolvedValue(0),
|
invalidateCommunity: jest.fn().mockResolvedValue(0),
|
||||||
} as unknown as jest.Mocked<CommunityStatsService>;
|
} as unknown as jest.Mocked<CommunityStatsService>;
|
||||||
const service = createService({ connectionService, communityStatsService });
|
const service = createService({ connectionService, communityStatsService });
|
||||||
|
|||||||
@@ -59,6 +59,7 @@ describe('LegacyImportService member job completion', () => {
|
|||||||
releaseLockIfOwned: jest.fn().mockResolvedValue(true),
|
releaseLockIfOwned: jest.fn().mockResolvedValue(true),
|
||||||
} as unknown as jest.Mocked<DistributedLockService>;
|
} as unknown as jest.Mocked<DistributedLockService>;
|
||||||
const communityStatsService = {
|
const communityStatsService = {
|
||||||
|
refreshForRiotMatches: jest.fn().mockResolvedValue(undefined),
|
||||||
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
|
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
|
||||||
} as unknown as jest.Mocked<CommunityStatsService>;
|
} as unknown as jest.Mocked<CommunityStatsService>;
|
||||||
const service = new LegacyImportService(
|
const service = new LegacyImportService(
|
||||||
|
|||||||
Loaded 100 of 345 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user