Compare commits

..
59 Commits
Author SHA1 Message Date
dahyeon 640e593676 docs: specify legacy slot migration rules 2026-07-13 03:41:39 +00:00
dahyeon ee96f8d48b fix: normalize missing legacy match game mode 2026-07-13 03:13:28 +00:00
dahyeon 683d602d63 fix: close competition cutover integrity gaps 2026-07-12 21:22:22 +00:00
dahyeon 7ea2002975 refactor: harden competition persistence type boundaries 2026-07-12 20:18:48 +00:00
dahyeon ec92494211 style: normalize competition contract endings 2026-07-12 20:13:28 +00:00
dahyeon 6bddb666fc refactor: cut web results over to competition projections 2026-07-12 20:11:24 +00:00
dahyeon 7db97c540b refactor: import historical results as competition facts 2026-07-12 20:08:29 +00:00
dahyeon 6aa2cb9009 fix: reject ambiguous Riot winner evidence 2026-07-12 20:08:12 +00:00
dahyeon 575cd911cb refactor: remove live legacy bracket mode 2026-07-12 20:05:25 +00:00
dahyeon 78a2c7cf0d fix: reject unfinishable first-to rules 2026-07-12 20:01:22 +00:00
dahyeon 0c2c7b59fc test: cover full double elimination projection 2026-07-12 19:59:57 +00:00
dahyeon 5049220e03 feat: deliver competition projection outbox effects 2026-07-12 19:57:47 +00:00
dahyeon ab9c48b1e6 refactor: cut tournament results over to competition facts 2026-07-12 19:53:04 +00:00
dahyeon 2958106e42 refactor: remove legacy match result writers 2026-07-12 19:47:53 +00:00
dahyeon ce07bfa0c8 fix: make competition reversals replayable 2026-07-12 19:47:34 +00:00
dahyeon 4d6fa2625e fix: guard competition stats rebuild revisions 2026-07-12 19:40:29 +00:00
dahyeon ee4c3eeb27 feat: add resumable competition migration runner 2026-07-12 19:34:52 +00:00
dahyeon 55e5b8df70 feat: expose revision-safe competition API 2026-07-12 19:34:15 +00:00
dahyeon f3286e7fd1 feat: preserve normalized accepted game facts 2026-07-12 19:32:19 +00:00
dahyeon e6e434d13f refactor: rebuild stats from competition revision 2026-07-12 19:28:04 +00:00
dahyeon 28e9ac1529 refactor: whitelist public match responses 2026-07-12 19:28:04 +00:00
dahyeon 874d785381 feat: plan deterministic competition migration 2026-07-12 19:08:38 +00:00
dahyeon 0c31a78df0 feat: execute competition result commands atomically 2026-07-12 19:08:18 +00:00
dahyeon 3b274b4ec2 feat: bootstrap competition aggregates from built teams 2026-07-12 19:08:10 +00:00
dahyeon 59b9ef79e5 feat: plan strict and cascade result reversals 2026-07-12 19:08:04 +00:00
dahyeon 5d4fe443d0 feat: project competition results by team identity 2026-07-12 19:01:22 +00:00
dahyeon 39112ff7ff build: wire shared competition contracts 2026-07-12 18:53:59 +00:00
dahyeon 2135af7107 feat: add competition persistence schemas 2026-07-12 18:49:37 +00:00
dahyeon 05a83db886 feat: define competition domain contracts 2026-07-12 18:44:26 +00:00
dahyeon f4ba3d524f docs: specify competition result domain 2026-07-12 18:36:38 +00:00
dahyeon 3a76fd8c88 chore: update api container runtime 2026-07-10 08:44:55 -07:00
dahyeon 3357d4c9c8 fix: repair double-elimination tournament codes 2026-07-10 08:44:42 -07:00
dahyeon 2d1c33f1e9 fix: hide bracket completion badges 2026-07-07 18:21:59 -07:00
dahyeon 03358cab4f fix: clone hydrated double-elimination brackets 2026-07-07 18:06:16 -07:00
dahyeon e188828423 feat: support double-elimination series games 2026-07-07 17:34:59 -07:00
dahyeon 2ee8c3807b perf: aggregate champion stats in MongoDB 2026-06-28 01:10:37 -07:00
dahyeon 88de2148ae feat: add API performance observability reporting 2026-06-28 00:40:05 -07:00
dahyeon 871a5fe78a chore: restore api test baseline and logging 2026-06-27 14:19:00 -07:00
dahyeon 60a006008a fix: harden multi-instance scheduler and worker execution 2026-06-27 13:19:43 -07:00
dahyeon df7dcd3a9c Harden match and tournament code concurrency 2026-06-27 12:28:05 -07:00
dahyeon 292e37aaac feat: add spell and rune tooltips 2026-06-26 23:29:47 -07:00
dahyeon 4906f665fd feat: polish match history UI 2026-06-26 23:10:42 -07:00
dahyeon 68afaf0cb8 feat: add item tooltips to match history 2026-06-26 23:07:06 -07:00
dahyeon 38c2d1f1b4 fix: disable automatic mongoose index creation 2026-06-26 10:49:38 -07:00
dahyeon 4ab5722759 chore: identify api mongo connections 2026-06-26 09:56:58 -07:00
dahyeon 51ea9c42d3 feat: route internal match game details by community 2026-06-26 09:41:04 -07:00
dahyeon d6e0bbf0e8 perf: optimize user internal history reads 2026-06-26 05:56:04 -07:00
dahyeon e80313e459 fix: refine double elimination bracket UI 2026-06-26 05:42:12 -07:00
dahyeon 9decc6866f fix: hide tournament code state from bracket 2026-06-26 05:09:16 -07:00
dahyeon e12f182e7f feat: add double elimination match mode 2026-06-26 05:00:08 -07:00
dahyeon b9aaf55193 perf: cache auction history summaries 2026-06-26 04:56:59 -07:00
dahyeon 8567948084 fix: recover stale auction durability history 2026-06-26 04:02:11 -07:00
dahyeon 37f1f4225d fix: prevent auction snapshot mutation 2026-06-26 03:12:13 -07:00
dahyeon 6dbc643c44 chore: add api new relic observability 2026-06-26 01:22:55 -07:00
dahyeon d2fc126fed chore: reflect observability updates in release 83 2026-06-25 23:57:51 -07:00
dahyeon ab721873f3 fix: prevent empty-team auction completion state 2026-06-25 05:26:09 -07:00
dahyeon 2984bd1604 fix: resume tournament result polling after delayed codes 2026-06-25 04:58:10 -07:00
dahyeon e50a683336 feat: enhance auction internal profile 2026-06-24 02:47:10 -07:00
dahyeon 9c69e35cfa fix: smooth auction timer bar 2026-06-23 22:48:41 -07:00
173 changed files with 41043 additions and 6857 deletions

No files matched your search

+1 -1
View File
@@ -1 +1 @@
77
83
+10 -3
View File
@@ -31,7 +31,7 @@ COPY apps/web/package.json apps/web/package.json
RUN pnpm install --prod --frozen-lockfile --filter api... --filter lolympus-tournament-support
FROM gcr.io/distroless/nodejs24-debian13:nonroot AS runtime
FROM gcr.io/distroless/nodejs26-debian13:nonroot AS runtime
WORKDIR /app
@@ -41,9 +41,16 @@ COPY --from=prod-deps --chown=nonroot:nonroot /app/package.json ./package.json
COPY --from=prod-deps --chown=nonroot:nonroot /app/node_modules ./node_modules
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/package.json ./apps/api/package.json
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/node_modules ./apps/api/node_modules
COPY --chown=nonroot:nonroot apps/api/newrelic.cjs ./apps/api/newrelic.cjs
COPY --from=build --chown=nonroot:nonroot /app/apps/api/dist ./apps/api/dist
COPY --chown=nonroot:nonroot apps/project.env ./project.env
EXPOSE 10712
EXPOSE 3000
CMD ["apps/api/dist/main.js"]
ENV NEW_RELIC_HOME=/app/apps/api \
NEW_RELIC_APP_NAME=lolympus \
NEW_RELIC_AI_MONITORING_ENABLED=true \
NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED=100000 \
NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED=10000
CMD ["--import", "/app/apps/api/node_modules/newrelic/esm-loader.mjs", "-r", "/app/apps/api/node_modules/newrelic", "apps/api/dist/main.js"]
+35 -6
View File
@@ -4,7 +4,7 @@ LOLYMPUS는 리그 오브 레전드 커뮤니티의 여러 이벤트 중 내전(
<p align="center">
<video
src="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/77/docs/screenshots/lolympus-demo.mp4"
src="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/84/docs/screenshots/lolympus-demo.mp4"
poster="docs/screenshots/lolympus-auction.png"
width="960"
autoplay="autoplay"
@@ -13,20 +13,20 @@ LOLYMPUS는 리그 오브 레전드 커뮤니티의 여러 이벤트 중 내전(
playsinline="playsinline"
controls
>
<a href="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/77/docs/screenshots/lolympus-demo.mp4">3초 간격 데모 영상 보기</a>
<a href="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/84/docs/screenshots/lolympus-demo.mp4">3초 간격 데모 영상 보기</a>
</video>
</p>
<p align="center">
<a href="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/77/docs/screenshots/lolympus-demo.mp4">3초 간격 데모 영상 보기</a>
<a href="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/84/docs/screenshots/lolympus-demo.mp4">3초 간격 데모 영상 보기</a>
</p>
## 배포 주소
| Environment | Version | URL |
| ----------- | ------- | -------------------------------------- |
| Production | v77 | <https://lolympus.dahyeon.us/> |
| Staging | v77 | <https://890c50be.lolympus.pages.dev/> |
| Production | v84 | <https://lolympus.dahyeon.us/> |
| Staging | v84 | <https://release-84.lolympus.pages.dev/> |
## 개요
@@ -48,7 +48,10 @@ LOLYMPUS는 이 반복 작업을 줄이는 데 초점을 맞췄습니다. 운영
4. **팀별 진행 페이지**
각 팀은 예정 경기, 상대 팀, 라인업, 토너먼트 코드를 한 화면에서 확인하고 복사할 수 있습니다.
5. **결과 수집과 통계**
5. **더블 엘리미네이션 운영**
4팀/8팀 더블 엘리미네이션 대진표를 생성하고, 시드 교체, 부전승, 제한적 결과 취소, 그랜드 파이널 리셋을 관리합니다.
6. **결과 수집과 통계**
Riot Match-V5 데이터를 이용해 경기 결과를 수집하고, 소환사별 전적과 커뮤니티 리더보드를 제공합니다.
## 스크린샷
@@ -78,6 +81,7 @@ LOLYMPUS는 이 반복 작업을 줄이는 데 초점을 맞췄습니다. 운영
- Riot 계정 기반 참가자 프로필, 티어, 포지션 확인
- 팀장 지정, 포지션 기반 팀 구성, 다팀 내전 지원
- 팀장 경매 방식의 참가자 낙찰과 입찰 기록 관리
- 4팀/8팀 더블 엘리미네이션 대진표, 시드 관리, 부전승, 제한적 취소, 그랜드 파이널 리셋 지원
- 경기별 토너먼트 코드 배정과 팀별 복사 UI
- 팀별 경기 일정, 상대 팀, 라인업, 결과 확인
- Riot Match-V5 기반 결과 수집, 개인 전적, 리더보드 제공
@@ -128,6 +132,29 @@ pnpm start:web:dev
웹 앱은 기본적으로 `apps/web/.env.development` 값을 사용합니다. API 환경값은 `apps/project.env`와 실행 환경의 시크릿 설정을 함께 확인합니다.
### API New Relic APM
API 서버는 `newrelic` Node.js agent를 앱 코드보다 먼저 preload합니다. Docker 런타임과 `pnpm start:api:*` 스크립트 모두 `NEW_RELIC_HOME`을 API 패키지로 지정해 `apps/api/newrelic.cjs` 설정을 읽습니다.
Kubernetes에서는 Infisical이 `NEW_RELIC_LICENSE_KEY`를 프로세스 시작 전에 환경변수로 주입해야 합니다. 저장소에는 라이선스 키를 두지 않습니다.
비밀이 아닌 기본값은 Dockerfile과 `apps/api/newrelic.cjs`에 정의되어 있으며 필요하면 런타임 환경변수로 덮어쓸 수 있습니다.
```bash
NEW_RELIC_APP_NAME=lolympus
NEW_RELIC_AI_MONITORING_ENABLED=true
NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED=100000
NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED=10000
```
New Relic Node agent의 정수 환경변수는 `100k` 같은 축약형 대신 `100000`처럼 숫자 문자열을 사용합니다.
### API 성능 리포트 운영
API 성능 계측은 기본 비활성화이며 필요할 때 `API_PERF_OBSERVABILITY_ENABLED=true`로 켭니다. 전체 API route 목록은 `pnpm --filter api perf:routes`, 성능 리포트는 `pnpm --filter api perf:report`로 생성합니다. New Relic Transaction 실측 duration, New Relic custom event, local NDJSON 파일을 데이터 소스로 사용할 수 있습니다.
운영 절차와 해석 기준은 `docs/operations/api-performance-runbook.md`를 참고합니다.
카카오톡 기반 명령어 기능은 Dakao(커스텀 카카오톡 게이트웨이) 연동이 필요합니다. Dakao가 실행 중이 아니거나 NATS를 통해 API 서버와 연결되어 있지 않으면 일정 조회, 내전 참가, 참가 취소, 계정 등록 같은 카카오톡 명령어는 사용할 수 없습니다.
## 커맨드
@@ -137,6 +164,8 @@ pnpm start:web:dev
| `pnpm start:web:dev` | 웹 앱 개발 서버 실행 |
| `pnpm start:api:dev` | API 서버 dev 환경 실행 |
| `pnpm --filter api test` | API 테스트 실행 |
| `pnpm --filter api perf:routes` | API 성능 리포트 대상 route 출력 |
| `pnpm --filter api perf:report` | API 성능 리포트 생성 |
| `pnpm --filter web build:staging` | 웹 staging 빌드 검증 |
| `pnpm deploy:web:staging` | Cloudflare Pages staging 배포 |
| `pnpm deploy:web:prod` | Cloudflare Pages production 배포 |
+69
View File
@@ -0,0 +1,69 @@
'use strict';
function readBoolean(name, defaultValue) {
const value = process.env[name];
if (value == null || value === '') return defaultValue;
return !['0', 'false', 'f', 'no', 'n', 'disabled'].includes(
value.toLowerCase(),
);
}
function readInteger(name, defaultValue) {
const rawValue = process.env[name]?.trim();
if (!rawValue) return defaultValue;
if (/^\d+$/.test(rawValue)) {
return Number.parseInt(rawValue, 10);
}
process.env[name] = String(defaultValue);
return defaultValue;
}
const hasLicenseKey = Boolean(process.env.NEW_RELIC_LICENSE_KEY);
exports.config = {
app_name: [process.env.NEW_RELIC_APP_NAME || 'lolympus'],
license_key: process.env.NEW_RELIC_LICENSE_KEY || '',
agent_enabled: readBoolean('NEW_RELIC_ENABLED', hasLicenseKey),
distributed_tracing: {
enabled: true,
},
ai_monitoring: {
enabled: readBoolean('NEW_RELIC_AI_MONITORING_ENABLED', true),
},
custom_insights_events: {
max_samples_stored: readInteger(
'NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED',
100000,
),
},
span_events: {
max_samples_stored: readInteger(
'NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED',
10000,
),
},
logging: {
level: process.env.NEW_RELIC_LOG_LEVEL || 'info',
},
instrumentation: {
timers: {
enabled: false,
},
},
allow_all_headers: false,
attributes: {
exclude: [
'request.headers.cookie',
'request.headers.authorization',
'request.headers.proxyAuthorization',
'request.headers.setCookie*',
'response.headers.cookie',
'response.headers.authorization',
'response.headers.proxyAuthorization',
'response.headers.setCookie*',
],
},
};
+8 -3
View File
@@ -8,14 +8,17 @@
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"competition:migrate": "ts-node src/modules/global/database/migrations/run-competition-domain.ts",
"seed:dev": "ts-node src/seed.ts",
"seed:dakao-participant": "ts-node src/seed-dakao-participant.ts",
"start:dev": "node -e \"process.env.NODE_ENV='dev'; require('./dist/main.js')\"",
"start:staging": "node -e \"process.env.NODE_ENV='staging'; require('./dist/main.js')\"",
"start:prod": "node -e \"process.env.NODE_ENV='prod'; require('./dist/main.js')\"",
"start:dev": "NODE_ENV=dev NEW_RELIC_HOME=. node --import newrelic/esm-loader.mjs -r newrelic dist/main.js",
"start:staging": "NODE_ENV=staging NEW_RELIC_HOME=. node --import newrelic/esm-loader.mjs -r newrelic dist/main.js",
"start:prod": "NODE_ENV=prod NEW_RELIC_HOME=. node --import newrelic/esm-loader.mjs -r newrelic dist/main.js",
"pm2:dev": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:dev",
"pm2:staging": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:staging",
"pm2:prod": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:prod",
"perf:report": "ts-node src/scripts/api-performance-report.ts",
"perf:routes": "ts-node src/scripts/api-performance-report.ts --routes-only",
"start:debug": "nest start --debug --watch",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
@@ -25,6 +28,7 @@
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@lolympus/contracts": "workspace:*",
"@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.4",
"@nestjs/core": "^11.0.1",
@@ -38,6 +42,7 @@
"jose": "^6.2.2",
"mongoose": "^9.4.1",
"nats": "^2.29.3",
"newrelic": "^14.1.2",
"redis": "^5.12.1",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
+11 -1
View File
@@ -1,11 +1,14 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ApiPerformanceInterceptor } from './modules/global/observability/api-performance.interceptor';
import { AuctionModule } from './modules/auction/auction.module';
import { AuthModule } from './modules/auth/auth.module';
import { CommunityModule } from './modules/community/community.module';
import { CommunityStatsModule } from './modules/community-stats/community-stats.module';
import { CompetitionModule } from './modules/competition/competition.module';
import { DakaoModule } from './modules/dakao/dakao.module';
import { GlobalModule } from './modules/global/global.module';
import { LegacyImportModule } from './modules/legacy-import/legacy-import.module';
@@ -29,6 +32,7 @@ import { UserModule } from './modules/user/user.module';
BackgroundRefreshModule,
CommunityModule,
CommunityStatsModule,
CompetitionModule,
MatchModule,
MatchHistoryModule,
LegacyImportModule,
@@ -39,6 +43,12 @@ import { UserModule } from './modules/user/user.module';
DakaoModule,
],
controllers: [AppController],
providers: [AppService],
providers: [
AppService,
{
provide: APP_INTERCEPTOR,
useClass: ApiPerformanceInterceptor,
},
],
})
export class AppModule {}
+8 -1
View File
@@ -18,7 +18,14 @@ async function bootstrap() {
app.enableCors({
origin: createCorsOrigin(nodeEnv),
credentials: true,
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
allowedHeaders: [
'Authorization',
'Content-Type',
'X-Auth-User-Id',
'If-Match',
'Idempotency-Key',
],
exposedHeaders: ['ETag'],
});
app.useGlobalPipes(
new ValidationPipe({
@@ -92,7 +92,10 @@ describe('auction durability projection helpers', () => {
it.each([
{ current: { auctionLifecycleId: 'life-1', revision: 8 }, expected: true },
{ current: { auctionLifecycleId: 'life-1', revision: 9 }, expected: false },
{ current: { auctionLifecycleId: 'new-life', revision: 1 }, expected: false },
{
current: { auctionLifecycleId: 'new-life', revision: 1 },
expected: false,
},
])('decides whether projection can apply %#', ({ current, expected }) => {
expect(shouldApplyAuctionProjection(current, payload)).toBe(expected);
});
@@ -100,14 +103,23 @@ describe('auction durability projection helpers', () => {
it.each([
{ current: { auctionLifecycleId: 'life-1', revision: 8 }, expected: true },
{ current: { auctionLifecycleId: 'life-1', revision: 9 }, expected: true },
{ current: { auctionLifecycleId: 'life-1', revision: 10 }, expected: false },
{ current: { auctionLifecycleId: 'new-life', revision: 1 }, expected: false },
{
current: { auctionLifecycleId: 'life-1', revision: 10 },
expected: false,
},
{
current: { auctionLifecycleId: 'new-life', revision: 1 },
expected: false,
},
{ current: {}, expected: false },
])('decides whether a durability payload can be processed %#', ({ current, expected }) => {
expect(shouldProcessAuctionDurabilityPayload(current, payload)).toBe(
expected,
);
});
])(
'decides whether a durability payload can be processed %#',
({ current, expected }) => {
expect(shouldProcessAuctionDurabilityPayload(current, payload)).toBe(
expected,
);
},
);
it('reads due durability payload keys from Redis', async () => {
const sendCommand = jest.fn().mockResolvedValue(['payload-1']);
@@ -333,7 +345,10 @@ describe('auction durability projection helpers', () => {
createSession: jest.fn().mockResolvedValue(session),
getModel: jest.fn((name: string) => {
if (name === 'auctionHistory') {
return { deleteMany: historyDeleteMany, updateOne: historyUpdateOne };
return {
deleteMany: historyDeleteMany,
updateOne: historyUpdateOne,
};
}
if (name === 'auction') {
return { findById: auctionFindById, updateOne: auctionUpdateOne };
@@ -404,7 +419,10 @@ describe('auction durability projection helpers', () => {
createSession: jest.fn().mockResolvedValue(session),
getModel: jest.fn((name: string) => {
if (name === 'auctionHistory') {
return { deleteMany: historyDeleteMany, updateOne: historyUpdateOne };
return {
deleteMany: historyDeleteMany,
updateOne: historyUpdateOne,
};
}
if (name === 'auction') {
return { findById: auctionFindById, updateOne: auctionUpdateOne };
@@ -428,6 +446,216 @@ describe('auction durability projection helpers', () => {
expect(auctionUpdateOne).not.toHaveBeenCalled();
});
it('recovers stale append payloads as history-only records', async () => {
const session = {
abortTransaction: jest.fn().mockResolvedValue(undefined),
commitTransaction: jest.fn().mockResolvedValue(undefined),
endSession: jest.fn().mockResolvedValue(undefined),
startTransaction: jest.fn(),
};
const historyFindOne = jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(null),
}),
}),
});
const historyUpdateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ upsertedCount: 1 }),
});
const auctionUpdateOne = jest.fn();
const sideEffectUpdateOne = jest.fn();
const projectionExec = jest.fn().mockResolvedValue({
auctionLifecycleId: 'life-1',
revision: 10,
});
const auctionFindById = jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({ exec: projectionExec }),
}),
}),
});
const scheduler = new AuctionDurabilityScheduler(
{
createSession: jest.fn().mockResolvedValue(session),
getModel: jest.fn((name: string) => {
if (name === 'auctionHistory') {
return {
findOne: historyFindOne,
updateOne: historyUpdateOne,
};
}
if (name === 'auction') {
return { findById: auctionFindById, updateOne: auctionUpdateOne };
}
return { updateOne: sideEffectUpdateOne };
}),
} as never,
{ raw: jest.fn() } as never,
);
await scheduler.applyDurabilityPayload({
...payload,
matchSideEffectMutation: { type: 'syncMatchTeamsAfterComplete' },
});
expect(historyFindOne).toHaveBeenCalledWith(
expect.objectContaining({
auctionId: 'auction-1',
sequence: { $gt: 4 },
}),
);
expect(historyUpdateOne).toHaveBeenCalledWith(
{
auctionId: 'auction-1',
auctionStateTransitionId: 'transition-1',
},
expect.objectContaining({
$setOnInsert: expect.objectContaining({
sequence: 4,
}),
}),
{ session, upsert: true },
);
expect(auctionUpdateOne).not.toHaveBeenCalled();
expect(sideEffectUpdateOne).not.toHaveBeenCalled();
});
it('does not resurrect stale append payloads invalidated by later undo', async () => {
const session = {
abortTransaction: jest.fn().mockResolvedValue(undefined),
commitTransaction: jest.fn().mockResolvedValue(undefined),
endSession: jest.fn().mockResolvedValue(undefined),
startTransaction: jest.fn(),
};
const historyFindOne = jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({
historyMutation: {
targetHistorySequence: 2,
type: 'deleteAfterSequenceAndAppendUndo',
},
}),
}),
}),
});
const historyUpdateOne = jest.fn();
const auctionUpdateOne = jest.fn();
const projectionExec = jest.fn().mockResolvedValue({
auctionLifecycleId: 'life-1',
revision: 10,
});
const auctionFindById = jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({ exec: projectionExec }),
}),
}),
});
const scheduler = new AuctionDurabilityScheduler(
{
createSession: jest.fn().mockResolvedValue(session),
getModel: jest.fn((name: string) => {
if (name === 'auctionHistory') {
return {
findOne: historyFindOne,
updateOne: historyUpdateOne,
};
}
if (name === 'auction') {
return { findById: auctionFindById, updateOne: auctionUpdateOne };
}
return { updateOne: jest.fn() };
}),
} as never,
{ raw: jest.fn() } as never,
);
await scheduler.applyDurabilityPayload(payload);
expect(historyFindOne).toHaveBeenCalled();
expect(historyUpdateOne).not.toHaveBeenCalled();
expect(auctionUpdateOne).not.toHaveBeenCalled();
});
it('clears stale append payloads after history-only recovery', async () => {
const sendCommand = jest
.fn()
.mockResolvedValueOnce(['payload-1'])
.mockResolvedValueOnce({
committedAtRedisTimestampMS: '1780000000000',
payloadJson: JSON.stringify({
...payload,
matchSideEffectMutation: { type: 'syncMatchTeamsAfterComplete' },
}),
})
.mockResolvedValueOnce(1)
.mockResolvedValueOnce(1);
const historyFindOne = jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(null),
}),
}),
});
const historyUpdateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ upsertedCount: 1 }),
});
const auctionUpdateOne = jest.fn();
const sideEffectUpdateOne = jest.fn();
const auctionFindById = jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({
auctionLifecycleId: 'life-1',
revision: 10,
}),
}),
}),
}),
});
const scheduler = new AuctionDurabilityScheduler(
{
createSession: jest.fn().mockResolvedValue(null),
getModel: jest.fn((name: string) => {
if (name === 'auctionHistory') {
return {
findOne: historyFindOne,
updateOne: historyUpdateOne,
};
}
if (name === 'auction') {
return { findById: auctionFindById, updateOne: auctionUpdateOne };
}
return { updateOne: sideEffectUpdateOne };
}),
} as never,
{
getCurrentRedisTimestampMS: jest.fn().mockResolvedValue(1000),
raw: jest.fn().mockReturnValue({ sendCommand }),
} as never,
);
await expect(scheduler.processDueDurabilityPayloads(10)).resolves.toEqual({
applied: 1,
failed: 0,
skipped: 0,
});
expect(historyUpdateOne).toHaveBeenCalledTimes(1);
expect(auctionUpdateOne).not.toHaveBeenCalled();
expect(sideEffectUpdateOne).not.toHaveBeenCalled();
expect(sendCommand).toHaveBeenNthCalledWith(3, [
'ZREM',
'auction:auctionDurabilityRetryQueue',
'payload-1',
]);
expect(sendCommand).toHaveBeenNthCalledWith(4, ['DEL', 'payload-1']);
});
it('processes due payloads and clears successful outbox entries', async () => {
const sendCommand = jest
.fn()
@@ -613,7 +841,9 @@ describe('auction durability projection helpers', () => {
.spyOn(scheduler, 'processDueDurabilityPayloads')
.mockResolvedValue({ applied: 0, failed: 0, skipped: 0 });
await (scheduler as unknown as { safeTick: () => Promise<void> }).safeTick();
await (
scheduler as unknown as { safeTick: () => Promise<void> }
).safeTick();
const auctionRedisService = (
scheduler as unknown as {
@@ -649,7 +879,9 @@ describe('auction durability projection helpers', () => {
.spyOn(scheduler, 'processDueDurabilityPayloads')
.mockResolvedValue({ applied: 0, failed: 0, skipped: 0 });
await (scheduler as unknown as { safeTick: () => Promise<void> }).safeTick();
await (
scheduler as unknown as { safeTick: () => Promise<void> }
).safeTick();
const auctionRedisService = (
scheduler as unknown as {
@@ -728,7 +960,10 @@ describe('auction durability projection helpers', () => {
const sideEffectUpdateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ matchedCount: 1, modifiedCount: 1 }),
});
const reserveForMatch = jest.fn().mockResolvedValue(match);
const reserveForMatch = jest.fn().mockImplementation(() => {
expect(match.teamBuiltAt).toBeUndefined();
return Promise.resolve(match);
});
const scheduleInitialPoll = jest.fn().mockResolvedValue(null);
const mirrorMatchSideEffectStatus = jest.fn().mockResolvedValue(true);
const broadcastMatchSideEffect = jest.fn();
@@ -747,7 +982,8 @@ describe('auction durability projection helpers', () => {
if (name === 'auctionSideEffectApplication') {
return { updateOne: sideEffectUpdateOne };
}
if (name === 'match') return { findById: jest.fn().mockReturnValue(match) };
if (name === 'match')
return { findById: jest.fn().mockReturnValue(match) };
return {};
}),
} as never,
@@ -777,7 +1013,7 @@ describe('auction durability projection helpers', () => {
teamIndex: 1,
},
]);
expect(match.save).toHaveBeenCalledTimes(1);
expect(match.save).toHaveBeenCalledTimes(2);
expect(reserveForMatch).toHaveBeenCalledWith(match);
expect(scheduleInitialPoll).toHaveBeenCalledWith(match);
expect(sideEffectUpdateOne).toHaveBeenCalledWith(
@@ -829,26 +1065,18 @@ describe('auction durability projection helpers', () => {
matchSideEffectRevision: 3,
matchSideEffectStatus: 'completed',
});
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(
1,
'match-1',
{
auctionLifecycleId: 'life-1',
currentServerTimestampMS: 2000,
matchSideEffectRevision: 2,
matchSideEffectStatus: 'processing',
},
);
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(
2,
'match-1',
{
auctionLifecycleId: 'life-1',
currentServerTimestampMS: 3000,
matchSideEffectRevision: 3,
matchSideEffectStatus: 'completed',
},
);
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(1, 'match-1', {
auctionLifecycleId: 'life-1',
currentServerTimestampMS: 2000,
matchSideEffectRevision: 2,
matchSideEffectStatus: 'processing',
});
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(2, 'match-1', {
auctionLifecycleId: 'life-1',
currentServerTimestampMS: 3000,
matchSideEffectRevision: 3,
matchSideEffectStatus: 'completed',
});
expect(sendCommand).toHaveBeenCalledWith([
'EVAL',
expect.stringContaining("redis.call('EXPIRE'"),
@@ -870,6 +1098,101 @@ describe('auction durability projection helpers', () => {
]);
});
it('fails sync match teams side effect when the completed projection has no teams', async () => {
const completePayload = {
...payload,
afterAuctionMongoProjection: {
auctionTeams: [],
matchSideEffectRevision: 1,
phase: 'complete',
revision: 10,
},
auctionActionType: 'complete',
matchSideEffectMutation: { type: 'syncMatchTeamsAfterComplete' },
revision: 10,
} as const;
const match = {
participants: [],
save: jest.fn().mockResolvedValue(undefined),
status: 'team-built',
teamBuiltAt: undefined,
teams: [],
};
const historyUpdateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ upsertedCount: 1 }),
});
const auctionUpdateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ modifiedCount: 1 }),
});
const auctionFindOneAndUpdate = jest
.fn()
.mockReturnValueOnce({
exec: jest.fn().mockResolvedValue({
auctionLifecycleId: 'life-1',
matchSideEffectRevision: 2,
matchSideEffectStatus: 'processing',
}),
})
.mockReturnValueOnce({
exec: jest.fn().mockResolvedValue({
auctionLifecycleId: 'life-1',
matchSideEffectRevision: 3,
matchSideEffectStatus: 'failed',
}),
});
const sideEffectUpdateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ matchedCount: 1, modifiedCount: 1 }),
});
const reserveForMatch = jest.fn().mockResolvedValue(match);
const scheduleInitialPoll = jest.fn().mockResolvedValue(null);
const mirrorMatchSideEffectStatus = jest.fn().mockResolvedValue(true);
const broadcastMatchSideEffect = jest.fn();
const scheduler = new AuctionDurabilityScheduler(
{
createSession: jest.fn().mockResolvedValue(null),
getModel: jest.fn((name: string) => {
if (name === 'auctionHistory') return { updateOne: historyUpdateOne };
if (name === 'auction') {
return {
findOneAndUpdate: auctionFindOneAndUpdate,
updateOne: auctionUpdateOne,
};
}
if (name === 'auctionSideEffectApplication') {
return { updateOne: sideEffectUpdateOne };
}
if (name === 'match')
return { findById: jest.fn().mockReturnValue(match) };
return {};
}),
} as never,
{
getCurrentRedisTimestampMS: jest
.fn()
.mockResolvedValueOnce(2000)
.mockResolvedValueOnce(3000),
raw: jest.fn().mockReturnValue({ sendCommand: jest.fn() }),
} as never,
{ reserveForMatch } as never,
{ scheduleInitialPoll } as never,
{ mirrorMatchSideEffectStatus } as never,
{ broadcastMatchSideEffect } as never,
);
await expect(
scheduler.applyDurabilityPayload(completePayload),
).rejects.toThrow('produced no match teams');
expect(match.save).not.toHaveBeenCalled();
expect(reserveForMatch).not.toHaveBeenCalled();
expect(scheduleInitialPoll).not.toHaveBeenCalled();
expect(mirrorMatchSideEffectStatus).toHaveBeenLastCalledWith(
expect.objectContaining({
matchSideEffectStatus: 'failed',
}),
);
});
it('applies reset match side effect after durable projection', async () => {
const resetPayload = {
...payload,
@@ -943,7 +1266,10 @@ describe('auction durability projection helpers', () => {
createSession: jest.fn().mockResolvedValue(null),
getModel: jest.fn((name: string) => {
if (name === 'auctionHistory') {
return { deleteMany: historyDeleteMany, updateOne: historyUpdateOne };
return {
deleteMany: historyDeleteMany,
updateOne: historyUpdateOne,
};
}
if (name === 'auction') {
return {
@@ -955,7 +1281,8 @@ describe('auction durability projection helpers', () => {
if (name === 'auctionSideEffectApplication') {
return { updateOne: sideEffectUpdateOne };
}
if (name === 'match') return { findById: jest.fn().mockReturnValue(match) };
if (name === 'match')
return { findById: jest.fn().mockReturnValue(match) };
return {};
}),
} as never,
@@ -985,7 +1312,10 @@ describe('auction durability projection helpers', () => {
teams: [],
tournamentCodeIds: [],
});
expect(match.participants).toEqual([{ excluded: false }, { excluded: false }]);
expect(match.participants).toEqual([
{ excluded: false },
{ excluded: false },
]);
expect(match.save).toHaveBeenCalledTimes(1);
expect(sideEffectUpdateOne).toHaveBeenCalledWith(
expect.objectContaining({
@@ -29,6 +29,8 @@ import {
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
buildAuctionRedisKeys,
} from './redis/auction-redis.keys';
// [AUCTION-DEBUG] 경매 "중복 멤버" 조사용 임시 계측. 조사 종료 후 제거 대상.
import { recordNewRelicCustomEvent } from '../global/observability/new-relic';
const AUCTION_DURABILITY_TICK_INTERVAL_MS = 1000;
const AUCTION_DURABILITY_BATCH_LIMIT = 20;
const AUCTION_DURABILITY_RETRY_DELAY_MS = 5000;
@@ -78,6 +80,7 @@ type ParsedMatchSideEffectMutation =
| { type: typeof UNDO_COMPLETED_MATCH_SIDE_EFFECT_TYPE };
interface CleanupSideEffectMatchDocument {
competitionId?: unknown;
gameSchedule?: unknown[];
participants: Array<{ excluded?: boolean }>;
result?: unknown;
@@ -128,15 +131,17 @@ export class AuctionDurabilityScheduler
currentRedisTimestampMS: number,
batchLimit: number,
): Promise<string[]> {
const reply = await this.auctionRedisService.raw().sendCommand([
'ZRANGEBYSCORE',
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
'-inf',
String(currentRedisTimestampMS),
'LIMIT',
'0',
String(batchLimit),
]);
const reply = await this.auctionRedisService
.raw()
.sendCommand([
'ZRANGEBYSCORE',
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
'-inf',
String(currentRedisTimestampMS),
'LIMIT',
'0',
String(batchLimit),
]);
return Array.isArray(reply) ? reply.map(String) : [];
}
@@ -165,15 +170,29 @@ export class AuctionDurabilityScheduler
}
await this.applyDurabilityPayload(payload);
applied += 1;
// [AUCTION-DEBUG] 제거 대상. 영속 지연(lag): Redis 커밋 → Mongo 영속까지 걸린 시간 + 배치 백로그.
// 사용자가 본 "되돌리기/이력이 2~3 뒤처짐"을 수치화한다(지연이 클수록 undo
// 패널이 stale 시퀀스를 보여 엉뚱한 스냅샷 복원 가능성↑).
recordNewRelicCustomEvent('AuctionServerDurability', {
matchId: typeof payload.matchId === 'string' ? payload.matchId : '',
auctionStateTransitionId: payload.auctionStateTransitionId,
auctionActionType: payload.auctionActionType,
revision: payload.revision,
auctionHistorySequence: payload.auctionHistorySequence,
persistLatencyMS:
typeof payload.committedAtRedisTimestampMS === 'number'
? currentRedisTimestampMS - payload.committedAtRedisTimestampMS
: -1,
batchBacklog: payloadKeys.length,
});
await this.clearDurabilityPayload(payloadKey);
} catch (error) {
failed += 1;
const failureDisposition =
await this.recordDurabilityPayloadFailure(
payloadKey,
currentRedisTimestampMS,
error,
);
const failureDisposition = await this.recordDurabilityPayloadFailure(
payloadKey,
currentRedisTimestampMS,
error,
);
this.logger.warn(
`Auction durability payload failed for ${payloadKey} (${failureDisposition}): ${
error instanceof Error ? error.message : error
@@ -195,7 +214,9 @@ export class AuctionDurabilityScheduler
const payloadJson = hash.payloadJson;
if (!payloadJson) return null;
const payload = JSON.parse(payloadJson) as AuctionDurabilityPayload;
const committedAtRedisTimestampMS = Number(hash.committedAtRedisTimestampMS);
const committedAtRedisTimestampMS = Number(
hash.committedAtRedisTimestampMS,
);
if (Number.isFinite(committedAtRedisTimestampMS)) {
payload.committedAtRedisTimestampMS = committedAtRedisTimestampMS;
}
@@ -222,13 +243,31 @@ export class AuctionDurabilityScheduler
try {
session?.startTransaction();
const historyMutation = parseAuctionHistoryMutation(
payload.historyMutation,
);
if (typeof AuctionModel.findById === 'function') {
const currentProjection = await readAuctionProjectionIdentityForMutation(
AuctionModel,
payload.auctionId,
session,
);
if (!shouldProcessAuctionDurabilityPayload(currentProjection, payload)) {
const currentProjection =
await readAuctionProjectionIdentityForMutation(
AuctionModel,
payload.auctionId,
session,
);
if (
!shouldProcessAuctionDurabilityPayload(currentProjection, payload)
) {
// 뒤 payload가 먼저 projection revision을 올리면 앞 append payload가 stale이 된다.
// 이때 projection/side effect는 건드리지 않고 undo용 history만 멱등 복구한다.
if (
historyMutation.type === 'append' &&
currentProjection.auctionLifecycleId === payload.auctionLifecycleId
) {
await this.applyStaleAppendHistoryRecovery({
AuctionHistoryModel,
payload,
session,
});
}
if (session) await session.commitTransaction();
return;
}
@@ -370,23 +409,26 @@ export class AuctionDurabilityScheduler
);
if (!hasMatchedDocument(leaseResult)) return;
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus({
AuctionModel,
currentServerTimestampMS: currentRedisTimestampMS,
expectedMatchSideEffectRevision: Number(
payload.afterAuctionMongoProjection.matchSideEffectRevision ?? 0,
),
payload,
status: 'processing',
});
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus(
{
AuctionModel,
currentServerTimestampMS: currentRedisTimestampMS,
expectedMatchSideEffectRevision: Number(
payload.afterAuctionMongoProjection.matchSideEffectRevision ?? 0,
),
payload,
status: 'processing',
},
);
if (!processingDelta) return;
let expectedMatchSideEffectRevision =
const expectedMatchSideEffectRevision =
processingDelta.matchSideEffectRevision;
try {
const match = (await execMaybe(
MatchModel.findById(payload.matchId) as never,
)) as {
competitionId?: unknown;
participants: Array<{
preferredPositions?: Array<{ position?: Position }>;
userId: { toString(): string };
@@ -396,16 +438,52 @@ export class AuctionDurabilityScheduler
teamBuiltAt?: Date;
teams: ReturnType<typeof buildMatchTeamsFromProjection>;
} | null;
if (!match) throw new Error(`Match not found: ${String(payload.matchId)}`);
match.teams = buildMatchTeamsFromProjection(
payload.afterAuctionMongoProjection,
match,
);
match.status = 'team-built';
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
await match.save();
await this.tournamentCodeService.reserveForMatch(match as never);
await this.tournamentResultService.scheduleInitialPoll(match as never);
if (!match)
throw new Error(`Match not found: ${String(payload.matchId)}`);
if (match.competitionId) {
await this.tournamentResultService.scheduleInitialPoll(match as never);
} else {
const matchTeams = buildMatchTeamsFromProjection(
payload.afterAuctionMongoProjection,
match,
);
// [AUCTION-DEBUG] 제거 대상. 최종 팀에 같은 유저가 2번 들어갔는지 무조건 검사
// (출처가 markSold든 undo 복원이든 projection이든 여기서 결정적으로 잡힌다).
const allMemberUserIds = matchTeams.flatMap((team) =>
team.members.map((member) => member.userId.toString()),
);
const distinctMemberCount = new Set(allMemberUserIds).size;
recordNewRelicCustomEvent('AuctionServerTeamBuild', {
matchId: typeof payload.matchId === 'string' ? payload.matchId : '',
auctionStateTransitionId: payload.auctionStateTransitionId,
teamCount: matchTeams.length,
totalMemberCount: allMemberUserIds.length,
distinctMemberCount,
hasDuplicateMember: allMemberUserIds.length !== distinctMemberCount,
duplicateUserId:
allMemberUserIds.find(
(id, idx) => allMemberUserIds.indexOf(id) !== idx,
) ?? null,
});
if (matchTeams.length === 0) {
throw new Error(
`Auction complete side effect produced no match teams for match ${String(payload.matchId)}.`,
);
}
const finalizedAt = match.teamBuiltAt ?? new Date();
match.teams = matchTeams;
match.status = 'team-built';
match.teamBuiltAt = undefined;
await match.save();
const preparedMatch =
(await this.tournamentCodeService.reserveForMatch(match as never)) ??
match;
preparedMatch.teamBuiltAt = finalizedAt;
await preparedMatch.save();
await this.tournamentResultService.scheduleInitialPoll(
preparedMatch as never,
);
}
const completedAtTimestampMS =
await this.auctionRedisService.getCurrentRedisTimestampMS();
@@ -466,6 +544,77 @@ 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: {
AuctionHistoryModel: {
findOne?: (...args: never[]) => unknown;
};
payload: AuctionDurabilityPayload;
session: mongoose.ClientSession | null | undefined;
}): Promise<boolean> {
if (!params.AuctionHistoryModel.findOne) return true;
// 늦게 도착한 append는 history gap을 메울 수 있지만,
// 이후 undo/reset이 의도적으로 삭제한 sequence를 되살리면 안 된다.
const query = params.AuctionHistoryModel.findOne({
auctionId: params.payload.auctionId,
sequence: { $gt: params.payload.auctionHistorySequence },
$or: [
{
'historyMutation.targetHistorySequence': {
$lt: params.payload.auctionHistorySequence,
},
'historyMutation.type': 'deleteAfterSequenceAndAppendUndo',
},
{
'historyMutation.resetMode': { $ne: 'preserve-audit' },
'historyMutation.type': 'reset',
},
],
} as never);
const scoped =
query && typeof query === 'object' && 'session' in query
? (query as { session: (...args: never[]) => unknown }).session(
params.session as never,
)
: query;
const leaned =
scoped && typeof scoped === 'object' && 'lean' in scoped
? (scoped as { lean: () => unknown }).lean()
: scoped;
const result =
leaned && typeof leaned === 'object' && 'exec' in leaned
? await (leaned as { exec: () => Promise<unknown> }).exec()
: await Promise.resolve(leaned);
return Boolean(result);
}
private async applyResetMatchSideEffect(
payload: AuctionDurabilityPayload,
mutation: ParsedMatchSideEffectMutation,
@@ -553,17 +702,20 @@ export class AuctionDurabilityScheduler
);
if (!hasMatchedDocument(leaseResult)) return;
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus({
AuctionModel,
currentServerTimestampMS: currentRedisTimestampMS,
expectedMatchSideEffectRevision: Number(
params.payload.afterAuctionMongoProjection.matchSideEffectRevision ?? 0,
),
payload: params.payload,
status: 'processing',
});
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus(
{
AuctionModel,
currentServerTimestampMS: currentRedisTimestampMS,
expectedMatchSideEffectRevision: Number(
params.payload.afterAuctionMongoProjection.matchSideEffectRevision ??
0,
),
payload: params.payload,
status: 'processing',
},
);
if (!processingDelta) return;
let expectedMatchSideEffectRevision =
const expectedMatchSideEffectRevision =
processingDelta.matchSideEffectRevision;
try {
@@ -573,6 +725,11 @@ export class AuctionDurabilityScheduler
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 params.updateMatch(match);
const completedAtTimestampMS =
@@ -605,7 +762,8 @@ export class AuctionDurabilityScheduler
} catch (error) {
const failureTimestampMS =
await this.auctionRedisService.getCurrentRedisTimestampMS();
const errorMessage = error instanceof Error ? error.message : String(error);
const errorMessage =
error instanceof Error ? error.message : String(error);
await execMaybe(
AuctionSideEffectApplicationModel.updateOne(
identity as never,
@@ -658,7 +816,9 @@ export class AuctionDurabilityScheduler
payload: AuctionDurabilityPayload;
session: mongoose.ClientSession | null | undefined;
}): Promise<void> {
const mutation = parseAuctionHistoryMutation(params.payload.historyMutation);
const mutation = parseAuctionHistoryMutation(
params.payload.historyMutation,
);
if (isDestructiveHistoryMutation(mutation)) {
if (mutation.type === 'deleteAfterSequenceAndAppendUndo') {
if (!params.AuctionHistoryModel.deleteMany) {
@@ -689,7 +849,9 @@ export class AuctionDurabilityScheduler
}
}
const historyOperation = buildAuctionHistoryUpsert(params.payload).updateOne;
const historyOperation = buildAuctionHistoryUpsert(
params.payload,
).updateOne;
await execMaybe(
params.AuctionHistoryModel.updateOne(
historyOperation.filter as never,
@@ -731,7 +893,9 @@ export class AuctionDurabilityScheduler
: {}),
matchSideEffectStatus: params.status,
},
...(params.errorMessage ? {} : { $unset: { matchSideEffectError: '' } }),
...(params.errorMessage
? {}
: { $unset: { matchSideEffectError: '' } }),
} as never,
{
projection: {
@@ -742,13 +906,11 @@ export class AuctionDurabilityScheduler
returnDocument: 'after',
} as never,
),
)) as
| {
auctionLifecycleId?: string;
matchSideEffectRevision?: number;
matchSideEffectStatus?: AuctionMatchSideEffectStatus;
}
| null;
)) as {
auctionLifecycleId?: string;
matchSideEffectRevision?: number;
matchSideEffectStatus?: AuctionMatchSideEffectStatus;
} | null;
if (!updatedAuction?.auctionLifecycleId) return null;
const delta = buildMatchSideEffectDelta({
@@ -815,12 +977,14 @@ export class AuctionDurabilityScheduler
payloadKey: string,
retryAtRedisTimestampMS: number,
): Promise<void> {
await this.auctionRedisService.raw().sendCommand([
'ZADD',
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
String(retryAtRedisTimestampMS),
payloadKey,
]);
await this.auctionRedisService
.raw()
.sendCommand([
'ZADD',
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
String(retryAtRedisTimestampMS),
payloadKey,
]);
}
private async recordDurabilityPayloadFailure(
@@ -829,43 +993,44 @@ export class AuctionDurabilityScheduler
error: unknown,
): Promise<'dead-lettered' | 'requeued'> {
const errorMessage = formatErrorMessageForRedis(error);
const attemptReply = await this.auctionRedisService.raw().sendCommand([
'HINCRBY',
payloadKey,
'attempts',
'1',
]);
const attemptReply = await this.auctionRedisService
.raw()
.sendCommand(['HINCRBY', payloadKey, 'attempts', '1']);
const attempts = Number(attemptReply);
await this.auctionRedisService.raw().sendCommand([
'HSET',
payloadKey,
'lastError',
errorMessage,
'lastFailedAtRedisTimestampMS',
String(currentRedisTimestampMS),
]);
await this.auctionRedisService
.raw()
.sendCommand([
'HSET',
payloadKey,
'lastError',
errorMessage,
'lastFailedAtRedisTimestampMS',
String(currentRedisTimestampMS),
]);
if (
Number.isFinite(attempts) &&
attempts >= AUCTION_DURABILITY_MAX_ATTEMPTS
) {
await this.auctionRedisService.raw().sendCommand([
'ZREM',
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
payloadKey,
]);
await this.auctionRedisService.raw().sendCommand([
'HSET',
payloadKey,
'deadLetteredAtRedisTimestampMS',
String(currentRedisTimestampMS),
]);
await this.auctionRedisService.raw().sendCommand([
'ZADD',
AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY,
String(currentRedisTimestampMS),
payloadKey,
]);
await this.auctionRedisService
.raw()
.sendCommand(['ZREM', AUCTION_DURABILITY_RETRY_QUEUE_KEY, payloadKey]);
await this.auctionRedisService
.raw()
.sendCommand([
'HSET',
payloadKey,
'deadLetteredAtRedisTimestampMS',
String(currentRedisTimestampMS),
]);
await this.auctionRedisService
.raw()
.sendCommand([
'ZADD',
AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY,
String(currentRedisTimestampMS),
payloadKey,
]);
return 'dead-lettered';
}
@@ -881,38 +1046,40 @@ export class AuctionDurabilityScheduler
): Promise<void> {
const matchId = String(payload.matchId);
const keys = buildAuctionRedisKeys(matchId);
await this.auctionRedisService.raw().sendCommand([
'EVAL',
[
"local expectedAuctionLifecycleId = ARGV[2]",
"local currentAuctionLifecycleId = redis.call('HGET', KEYS[1], 'auctionLifecycleId')",
"if currentAuctionLifecycleId ~= expectedAuctionLifecycleId then",
' return 0',
'end',
"redis.call('ZREM', KEYS[2], ARGV[1])",
'for index = 1, #KEYS do',
' if index ~= 2 then',
" redis.call('EXPIRE', KEYS[index], ARGV[3])",
' end',
'end',
'return 1',
].join('\n'),
'11',
keys.liveStateKey,
keys.deadlineQueueKey,
keys.structureStateKey,
keys.appliedTransitionIdsKey,
keys.bidHistoryKey,
keys.bidRequestResultsKey,
keys.bidRequestResultOrderKey,
keys.actionRequestResultsKey,
keys.actionRequestResultOrderKey,
keys.rehydrateLockKey,
keys.stateTransitionLockKey,
matchId,
payload.auctionLifecycleId,
String(AUCTION_REDIS_COMPLETED_RETAIN_SECONDS),
]);
await this.auctionRedisService
.raw()
.sendCommand([
'EVAL',
[
'local expectedAuctionLifecycleId = ARGV[2]',
"local currentAuctionLifecycleId = redis.call('HGET', KEYS[1], 'auctionLifecycleId')",
'if currentAuctionLifecycleId ~= expectedAuctionLifecycleId then',
' return 0',
'end',
"redis.call('ZREM', KEYS[2], ARGV[1])",
'for index = 1, #KEYS do',
' if index ~= 2 then',
" redis.call('EXPIRE', KEYS[index], ARGV[3])",
' end',
'end',
'return 1',
].join('\n'),
'11',
keys.liveStateKey,
keys.deadlineQueueKey,
keys.structureStateKey,
keys.appliedTransitionIdsKey,
keys.bidHistoryKey,
keys.bidRequestResultsKey,
keys.bidRequestResultOrderKey,
keys.actionRequestResultsKey,
keys.actionRequestResultOrderKey,
keys.rehydrateLockKey,
keys.stateTransitionLockKey,
matchId,
payload.auctionLifecycleId,
String(AUCTION_REDIS_COMPLETED_RETAIN_SECONDS),
]);
}
}
@@ -961,7 +1128,9 @@ export function parseAuctionHistoryMutation(
}
if (record.type === 'reset') {
const resetMode =
record.resetMode === 'preserve-audit' ? 'preserve-audit' : 'clear-history';
record.resetMode === 'preserve-audit'
? 'preserve-audit'
: 'clear-history';
return { resetMode, type: 'reset' };
}
return { type: 'append' };
@@ -1055,7 +1224,10 @@ export function buildSideEffectApplicationUpsert(
payload: AuctionDurabilityPayload,
mutation: ParsedMatchSideEffectMutation,
) {
const identity = buildSideEffectApplicationIdentityFromPayload(payload, mutation);
const identity = buildSideEffectApplicationIdentityFromPayload(
payload,
mutation,
);
return {
filter: identity,
update: {
@@ -1100,7 +1272,12 @@ function buildSideEffectApplicationIdentityFromPayload(
function hashStableJson(value: unknown): string {
return createHash('sha256')
.update(JSON.stringify(value, Object.keys(value as Record<string, unknown>).sort()))
.update(
JSON.stringify(
value,
Object.keys(value as Record<string, unknown>).sort(),
),
)
.digest('hex');
}
@@ -1140,13 +1317,16 @@ function buildMatchTeamsFromProjection(
const members: MatchTeamMember[] = [
{
assignedPosition:
(captain?.preferredPositions?.[0]?.position as Position | undefined) ??
'MID',
(captain?.preferredPositions?.[0]?.position as
| Position
| undefined) ?? 'MID',
cost: 0,
userId: captainUserId,
},
...rawMembers
.filter((member) => member.userId?.toString() !== captainUserId.toString())
.filter(
(member) => member.userId?.toString() !== captainUserId.toString(),
)
.map((member) => ({
assignedPosition: (member.assignedPosition ?? 'MID') as Position,
cost: Number(member.memberAcquisitionBidPointAmount ?? 0),
@@ -1198,7 +1378,9 @@ function calculateDurabilityRetryDelayMS(attempts: number): number {
);
}
async function execMaybe<T>(queryOrPromise: Promise<T> | { exec(): Promise<T> }) {
async function execMaybe<T>(
queryOrPromise: Promise<T> | { exec(): Promise<T> },
) {
if (
queryOrPromise &&
typeof (queryOrPromise as { exec?: unknown }).exec === 'function'
@@ -158,11 +158,12 @@ describe('AuctionService', () => {
it('rejects non-positive or fractional bid amounts before loading auction state', async () => {
const matchId = new mongoose.Types.ObjectId();
const auctionFindOne = jest.fn();
const { service, auctionRedisCommandService, auctionRedisService } = createService({
auction: {
findOne: auctionFindOne,
},
});
const { service, auctionRedisCommandService, auctionRedisService } =
createService({
auction: {
findOne: auctionFindOne,
},
});
await expect(
service.placeBid({
@@ -182,6 +183,77 @@ describe('AuctionService', () => {
expect(auctionRedisCommandService.placeBid).not.toHaveBeenCalled();
});
it('lists auction history with a summary projection and short local cache', async () => {
const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(1000);
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const match = {
communityId: {
equals: jest.fn((value) => value.toString() === communityId.toString()),
},
};
const historyRows = [
{
action: 'sold',
sequence: 4,
takenAt: new Date('2026-06-26T00:00:00.000Z'),
},
{
action: 'open-bidding',
sequence: 3,
takenAt: new Date('2026-06-26T00:00:01.000Z'),
},
];
const historyExec = jest.fn().mockResolvedValue(historyRows);
const historyLean = jest.fn().mockReturnValue({ exec: historyExec });
const historyLimit = jest.fn().mockReturnValue({ lean: historyLean });
const historySort = jest.fn().mockReturnValue({ limit: historyLimit });
const historySelect = jest.fn().mockReturnValue({ sort: historySort });
const historyFind = jest.fn().mockReturnValue({ select: historySelect });
const { service } = createService({
auctionHistory: {
find: historyFind,
},
match: {
findById: jest.fn().mockReturnValue({
select: jest.fn().mockResolvedValue(match),
}),
},
});
await expect(
service.listHistory({ matchId, communityId }),
).resolves.toEqual([
{
action: 'sold',
actionLabel: '낙찰 처리',
sequence: 4,
takenAt: historyRows[0].takenAt,
},
{
action: 'open-bidding',
actionLabel: '입찰 열기',
sequence: 3,
takenAt: historyRows[1].takenAt,
},
]);
await service.listHistory({ matchId, communityId });
expect(historyFind).toHaveBeenCalledTimes(1);
expect(historySelect).toHaveBeenCalledWith({
_id: 0,
action: 1,
sequence: 1,
takenAt: 1,
});
expect(historySort).toHaveBeenCalledWith({ sequence: -1 });
expect(historyLimit).toHaveBeenCalledWith(100);
nowSpy.mockReturnValue(3101);
await service.listHistory({ matchId, communityId });
expect(historyFind).toHaveBeenCalledTimes(2);
});
it('starts an auction without reserving tournament codes before teams are complete', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
@@ -266,7 +338,7 @@ describe('AuctionService', () => {
});
expect(match.status).toBe('team-built');
expect(match.teamBuiltAt).toBeInstanceOf(Date);
expect(match.teamBuiltAt).toBeUndefined();
expect(match.save).toHaveBeenCalledTimes(1);
expect(tournamentCodeService.reserveForMatch).not.toHaveBeenCalled();
expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled();
@@ -542,44 +614,45 @@ describe('AuctionService', () => {
}));
const auctionDeleteOne = jest.fn().mockResolvedValue({ deletedCount: 1 });
const historyDeleteMany = jest.fn().mockResolvedValue({ deletedCount: 2 });
const { service, auctionRedisCommandService, auctionRedisService } = createService({
match: {
findById: jest.fn().mockResolvedValue(match),
},
user: {
find: jest.fn().mockResolvedValue(users),
},
auction: {
create: auctionCreate,
deleteOne: auctionDeleteOne,
findOne: jest.fn().mockResolvedValue(existingAuction),
},
auctionHistory: {
create: jest.fn().mockResolvedValue(undefined),
deleteMany: historyDeleteMany,
findOne: jest.fn().mockReturnValue({
sort: jest.fn().mockReturnValue({
const { service, auctionRedisCommandService, auctionRedisService } =
createService({
match: {
findById: jest.fn().mockResolvedValue(match),
},
user: {
find: jest.fn().mockResolvedValue(users),
},
auction: {
create: auctionCreate,
deleteOne: auctionDeleteOne,
findOne: jest.fn().mockResolvedValue(existingAuction),
},
auctionHistory: {
create: jest.fn().mockResolvedValue(undefined),
deleteMany: historyDeleteMany,
findOne: jest.fn().mockReturnValue({
sort: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(null),
}),
}),
}),
}),
},
community: {
findById: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(null),
exec: jest.fn().mockResolvedValue({
riotPlatform: 'kr',
riotRegion: 'asia',
}),
}),
}),
}),
}),
},
community: {
findById: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({
riotPlatform: 'kr',
riotRegion: 'asia',
}),
}),
}),
}),
},
});
},
});
await service.start({
matchId,
@@ -800,7 +873,9 @@ describe('AuctionService', () => {
findOne: jest.fn().mockResolvedValue(auction),
},
});
auctionRedisStateReaderService.readLiveStateIdentity.mockResolvedValue(null);
auctionRedisStateReaderService.readLiveStateIdentity.mockResolvedValue(
null,
);
auctionRedisStateReaderService.readAuctionStateView.mockResolvedValue(
redisState,
);
@@ -870,12 +945,15 @@ describe('AuctionService', () => {
phase: 'bidding',
revision: 2,
};
const { service, auctionRedisCommandService, auctionRedisStateReaderService } =
createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
});
const {
service,
auctionRedisCommandService,
auctionRedisStateReaderService,
} = createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
});
auctionRedisStateReaderService.readAuctionStateView
.mockResolvedValueOnce(presentingState)
.mockResolvedValueOnce(biddingState);
@@ -973,12 +1051,15 @@ describe('AuctionService', () => {
currentHighestBidPointAmount: 120,
revision: 3,
};
const { service, auctionRedisCommandService, auctionRedisStateReaderService } =
createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
});
const {
service,
auctionRedisCommandService,
auctionRedisStateReaderService,
} = createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
});
auctionRedisStateReaderService.readAuctionStateView
.mockResolvedValueOnce(biddingState)
.mockResolvedValueOnce(afterBidState);
@@ -1007,6 +1088,115 @@ describe('AuctionService', () => {
);
});
it('keeps Redis sold snapshotBefore isolated from the sold structure mutation', async () => {
const matchId = new mongoose.Types.ObjectId();
const captainUserId = new mongoose.Types.ObjectId();
const playerUserId = new mongoose.Types.ObjectId();
const auction = {
_id: new mongoose.Types.ObjectId(),
auctionEngineVersion: 'redis-v1',
matchId,
matchSideEffectRevision: 0,
};
const biddingState = {
auctionBidHistory: [],
auctionLifecycleId: 'life-1',
auctionPlayerOrder: [
{
userId: playerUserId.toString(),
preferredPositions: [{ position: 'MID', priority: 1 }],
},
],
auctionTeams: [
{
captainUserId: captainUserId.toString(),
members: [],
remainingBidPointAmount: 1000,
teamIndex: 1,
},
],
bidRoundExtensionSeconds: 5,
currentAuctionHistorySequence: 3,
currentAuctionPlayerOrderIndex: 0,
currentAuctionRound: 1,
currentBidRoundPlayerUserId: playerUserId.toString(),
currentHighestBidPointAmount: 120,
currentHighestBidderTeamIndex: 1,
initialTeamBidPointAmount: 1000,
maximumBidRoundDurationSeconds: 30,
passedAuctionPlayerQueue: [],
phase: 'bidding',
revision: 4,
topTierAuctionPriorityThreshold: 'NONE',
};
const soldState = {
...biddingState,
auctionTeams: [
{
...biddingState.auctionTeams[0],
members: [
{
assignedPosition: 'MID',
memberAcquisitionBidPointAmount: 120,
userId: playerUserId.toString(),
},
],
remainingBidPointAmount: 880,
},
],
currentAuctionHistorySequence: 4,
currentHighestBidPointAmount: 120,
phase: 'sold',
revision: 5,
};
const {
service,
auctionRedisCommandService,
auctionRedisStateReaderService,
} = createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
});
auctionRedisStateReaderService.readAuctionStateView
.mockResolvedValueOnce(biddingState)
.mockResolvedValueOnce(soldState);
await expect(
service.markSold({
auctionActionRequestId: '00000000-0000-4000-8000-000000000061',
clientObservedAuctionLifecycleId: 'life-1',
clientObservedCurrentAuctionPlayerOrderIndex: 0,
clientObservedCurrentBidRoundPlayerUserId: playerUserId.toString(),
clientObservedPhase: 'bidding',
clientObservedRevision: 4,
matchId,
}),
).resolves.toMatchObject({
phase: 'sold',
revision: 5,
});
const transitionInput =
auctionRedisCommandService.applyTransition.mock.calls[0][1];
const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson);
expect(durabilityPayload.snapshotBefore).toMatchObject({
phase: 'bidding',
revision: 4,
});
expect(durabilityPayload.snapshotBefore.auctionTeams[0].members).toEqual(
[],
);
expect(
durabilityPayload.afterAuctionMongoProjection.auctionTeams[0].members,
).toEqual([
expect.objectContaining({
memberAcquisitionBidPointAmount: 120,
userId: playerUserId.toString(),
}),
]);
});
it('returns bid deltas without re-reading the full Redis state', async () => {
const matchId = new mongoose.Types.ObjectId();
const captainUserId = new mongoose.Types.ObjectId();
@@ -1189,15 +1379,14 @@ describe('AuctionService', () => {
auctionRedisStateReaderService,
tournamentCodeService,
tournamentResultService,
} =
createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
match: {
findById: jest.fn().mockResolvedValue(match),
},
});
} = createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
match: {
findById: jest.fn().mockResolvedValue(match),
},
});
auctionRedisStateReaderService.readAuctionStateView
.mockResolvedValueOnce(soldState)
.mockResolvedValueOnce(completeState);
@@ -1377,8 +1566,7 @@ describe('AuctionService', () => {
const signupOrder = userIds.slice(2).map((userId) => userId.toString());
const auctionOrder = auctionCreate.mock.calls[0][0].order.map(
(player: { userId: mongoose.Types.ObjectId }) =>
player.userId.toString(),
(player: { userId: mongoose.Types.ObjectId }) => player.userId.toString(),
);
expect(auctionOrder).not.toEqual(signupOrder);
@@ -1647,9 +1835,7 @@ describe('AuctionService', () => {
amount: 20,
});
expect(auction.currentDeadline).toEqual(
new Date(now.getTime() + 12000),
);
expect(auction.currentDeadline).toEqual(new Date(now.getTime() + 12000));
expect(auction.save).toHaveBeenCalledTimes(1);
});
@@ -1886,13 +2072,17 @@ describe('AuctionService', () => {
findById: jest.fn().mockResolvedValue(match),
},
});
tournamentCodeService.reserveForMatch.mockImplementation((candidate) => {
expect(candidate.teamBuiltAt).toBeUndefined();
return Promise.resolve(candidate);
});
await service.next(matchId);
expect(auction.phase).toBe('complete');
expect(auction.completedAt).toBeInstanceOf(Date);
expect(auction.save).toHaveBeenCalledTimes(1);
expect(match.save).toHaveBeenCalledTimes(1);
expect(match.save).toHaveBeenCalledTimes(2);
expect(match.teams).toEqual([
{
teamIndex: 1,
@@ -1988,6 +2178,55 @@ describe('AuctionService', () => {
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
});
it('rejects auction reset after Competition bootstrap', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const session = {
startTransaction: jest.fn(),
commitTransaction: jest.fn().mockResolvedValue(undefined),
abortTransaction: jest.fn().mockResolvedValue(undefined),
endSession: jest.fn().mockResolvedValue(undefined),
};
const auction = {
deleteOne: jest.fn(),
};
const match = {
communityId,
competitionId: new mongoose.Types.ObjectId(),
status: 'team-built',
teams: [{ teamIndex: 1 }],
tournamentCodeIds: [],
gameSchedule: [],
participants: [],
save: jest.fn(),
};
const { service, connectionService, tournamentCodeService } = createService(
{
auction: {
findOne: jest.fn().mockReturnValue({
session: jest.fn().mockResolvedValue(auction),
}),
},
match: {
findById: jest.fn().mockReturnValue({
session: jest.fn().mockResolvedValue(match),
}),
},
},
);
connectionService.createSession.mockResolvedValue(session);
await expect(service.reset({ matchId, communityId })).rejects.toThrow(
'immutable Competition',
);
expect(session.abortTransaction).toHaveBeenCalledTimes(1);
expect(session.commitTransaction).not.toHaveBeenCalled();
expect(auction.deleteOne).not.toHaveBeenCalled();
expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled();
expect(match.save).not.toHaveBeenCalled();
});
it('fully deletes redis-v1 auction data when cancelling an auction', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
@@ -2151,21 +2390,25 @@ describe('AuctionService', () => {
const auctionReplaceOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(undefined),
});
const { service, connectionService, tournamentCodeService, tournamentResultService } =
createService({
auction: {
findOne: jest.fn().mockReturnValue(auctionFindOneQuery),
replaceOne: auctionReplaceOne,
findById: jest.fn().mockResolvedValue(restored),
},
auctionHistory: {
findOne: jest.fn().mockReturnValue(historyFindOneQuery),
deleteMany: jest.fn().mockReturnValue(historyDeleteManyQuery),
},
match: {
findById: jest.fn().mockReturnValue(matchFindByIdQuery),
},
});
const {
service,
connectionService,
tournamentCodeService,
tournamentResultService,
} = createService({
auction: {
findOne: jest.fn().mockReturnValue(auctionFindOneQuery),
replaceOne: auctionReplaceOne,
findById: jest.fn().mockResolvedValue(restored),
},
auctionHistory: {
findOne: jest.fn().mockReturnValue(historyFindOneQuery),
deleteMany: jest.fn().mockReturnValue(historyDeleteManyQuery),
},
match: {
findById: jest.fn().mockReturnValue(matchFindByIdQuery),
},
});
connectionService.createSession.mockResolvedValue(session);
await expect(
@@ -2261,23 +2504,27 @@ describe('AuctionService', () => {
}),
};
const auctionReplaceOne = jest.fn();
const { service, connectionService, auctionRedisCommandService, auctionRedisStateReaderService } =
createService({
auction: {
findOne: jest.fn().mockReturnValue({
session: jest.fn().mockResolvedValue(auction),
}),
replaceOne: auctionReplaceOne,
},
auctionHistory: {
findOne: jest.fn().mockReturnValue(historyFindOneQuery),
},
match: {
findById: jest.fn().mockReturnValue({
session: jest.fn().mockResolvedValue(match),
}),
},
});
const {
service,
connectionService,
auctionRedisCommandService,
auctionRedisStateReaderService,
} = createService({
auction: {
findOne: jest.fn().mockReturnValue({
session: jest.fn().mockResolvedValue(auction),
}),
replaceOne: auctionReplaceOne,
},
auctionHistory: {
findOne: jest.fn().mockReturnValue(historyFindOneQuery),
},
match: {
findById: jest.fn().mockReturnValue({
session: jest.fn().mockResolvedValue(match),
}),
},
});
connectionService.createSession.mockResolvedValue(session);
auctionRedisStateReaderService.readAuctionStateView
.mockResolvedValueOnce(currentRedisState)
@@ -2298,7 +2545,9 @@ describe('AuctionService', () => {
).resolves.toBe(restoredRedisState);
expect(auctionReplaceOne).not.toHaveBeenCalled();
expect(auctionRedisCommandService.reserveActionRequest).toHaveBeenCalledWith(
expect(
auctionRedisCommandService.reserveActionRequest,
).toHaveBeenCalledWith(
matchId.toString(),
expect.objectContaining({
auctionActionRequestId: '00000000-0000-4000-8000-000000000070',
@@ -2319,9 +2568,7 @@ describe('AuctionService', () => {
durationSeconds: 30,
mode: 'set-relative',
});
const durabilityPayload = JSON.parse(
transitionInput.durabilityPayloadJson,
);
const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson);
expect(durabilityPayload).toMatchObject({
auctionActionType: 'undo',
historyMutation: {
File diff suppressed because it is too large. Load diff
@@ -8,7 +8,11 @@ import type {
} from './community-stats.types';
import { MatchStatsRepository } from './match-stats.repository';
import { MatchStatsService } from './match-stats.service';
import type { InternalGameDetail, InternalRecord } from './match-stats.types';
import {
MATCH_STATS_BUILDER_VERSION,
type InternalGameDetail,
type InternalRecord,
} from './match-stats.types';
function objectives() {
return {
@@ -191,4 +195,228 @@ describe('CommunityStatsService', () => {
response,
);
});
it('includes internal match route fields in user internal history matches', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
const participant = record(matchId);
participant.userId = userId.toString();
participant.gameNumber = 2;
participant.riotMatchId = 'KR_1234';
const cacheService = {
get: jest.fn().mockResolvedValue(null),
set: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<CommunityStatsCacheService>;
const matchStatsRepository = {
findUserRecordFragments: jest
.fn()
.mockResolvedValue([{ matchId, records: [participant] }]),
findDetailsByMatches: jest
.fn()
.mockResolvedValue([{ matchId, gameDetails: [] }]),
} as unknown as jest.Mocked<MatchStatsRepository>;
const service = new CommunityStatsService(
{} as ConnectionService,
cacheService,
matchStatsRepository,
{} as MatchStatsService,
);
(service as unknown as { resolveContext: jest.Mock }).resolveContext = jest
.fn()
.mockResolvedValue({
community: {},
season: {
id: 'all',
label: '전체',
startedAt: null,
endedAt: null,
},
from: null,
to: null,
});
const buildBaseDataset = jest.spyOn(
service as unknown as { buildBaseDataset: jest.Mock },
'buildBaseDataset',
);
const response = await service.getUserInternalHistory({
communityId,
userId,
filters: { limit: 5 },
});
expect(response.matches[0]).toMatchObject({
matchId: 'KR_1234',
internalMatchId: matchId.toString(),
gameNumber: 2,
queueLabel: '내전',
});
expect(matchStatsRepository.findUserRecordFragments).toHaveBeenCalledWith({
communityId,
userId,
fromGameCreation: undefined,
toGameCreation: undefined,
limit: 300,
});
expect(
matchStatsRepository.findDetailsByMatches.mock.calls[0][0].matchIds.map(
(id) => id.toString(),
),
).toEqual([matchId.toString()]);
expect(buildBaseDataset).not.toHaveBeenCalled();
expect(cacheService.set).toHaveBeenCalledWith(
expect.stringContaining(`userInternal:v3:${userId.toString()}`),
response,
);
});
it('coalesces concurrent user internal history cache misses', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
const participant = record(matchId);
participant.userId = userId.toString();
let resolveFragments:
| ((
fragments: Array<{
matchId: mongoose.Types.ObjectId;
records: InternalRecord[];
}>,
) => void)
| undefined;
const fragmentsPromise = new Promise<
Array<{ matchId: mongoose.Types.ObjectId; records: InternalRecord[] }>
>((resolve) => {
resolveFragments = resolve;
});
const cacheService = {
get: jest.fn().mockResolvedValue(null),
set: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<CommunityStatsCacheService>;
const matchStatsRepository = {
findUserRecordFragments: jest.fn().mockReturnValue(fragmentsPromise),
findDetailsByMatches: jest.fn().mockResolvedValue([]),
} as unknown as jest.Mocked<MatchStatsRepository>;
const service = new CommunityStatsService(
{} as ConnectionService,
cacheService,
matchStatsRepository,
{} as MatchStatsService,
);
(service as unknown as { resolveContext: jest.Mock }).resolveContext = jest
.fn()
.mockResolvedValue({
community: {},
season: {
id: 'all',
label: '전체',
startedAt: null,
endedAt: null,
},
from: null,
to: null,
});
const first = service.getUserInternalHistory({
communityId,
userId,
filters: { limit: 5 },
});
const second = service.getUserInternalHistory({
communityId,
userId,
filters: { limit: 5 },
});
await Promise.resolve();
resolveFragments?.([{ matchId, records: [participant] }]);
const [firstResponse, secondResponse] = await Promise.all([first, second]);
expect(firstResponse).toBe(secondResponse);
expect(matchStatsRepository.findUserRecordFragments).toHaveBeenCalledTimes(
1,
);
expect(cacheService.set).toHaveBeenCalledTimes(1);
});
it('self-heals Competition fragments when their source revision is stale', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const matches = [{ _id: matchId, competitionId }];
const MatchModel = {
find: jest.fn().mockReturnValue({
sort: jest.fn().mockReturnValue({
limit: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(matches),
}),
}),
}),
}),
};
const CompetitionModel = {
find: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue([
{
_id: competitionId,
revision: 7,
projectorVersion: 3,
},
]),
}),
}),
}),
};
const connectionService = {
getModel: jest.fn().mockImplementation((name: string) => {
if (name === 'match') return Promise.resolve(MatchModel);
if (name === 'competition') return Promise.resolve(CompetitionModel);
throw new Error(`Unexpected model ${name}`);
}),
} as unknown as ConnectionService;
const matchStatsRepository = {
findByCommunity: jest.fn().mockResolvedValue([
{
matchId,
builderVersion: MATCH_STATS_BUILDER_VERSION,
sourceCompetitionId: competitionId,
sourceRevision: 6,
projectorVersion: 3,
},
]),
} as unknown as jest.Mocked<MatchStatsRepository>;
const matchStatsService = {
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<MatchStatsService>;
const service = new CommunityStatsService(
connectionService,
{} as CommunityStatsCacheService,
matchStatsRepository,
matchStatsService,
);
const rebuilt = await (
service as unknown as {
rebuildMissingOrStaleFragments(
communityId: mongoose.Types.ObjectId,
): Promise<number>;
}
).rebuildMissingOrStaleFragments(communityId);
expect(MatchModel.find).toHaveBeenCalledWith({
communityId,
status: { $in: ['finished', 'in-progress'] },
$or: [
{ competitionId: { $exists: true } },
{ 'result.games.0': { $exists: true } },
],
});
expect(matchStatsService.buildAndUpsert).toHaveBeenCalledWith(matchId);
expect(rebuilt).toBe(1);
});
});
@@ -24,7 +24,11 @@ import type {
TeamInsightsResponse,
UserInternalHistoryResponse,
} from './community-stats.types';
import { MatchStatsRepository } from './match-stats.repository';
import {
MatchStatsDetailFragment,
MatchStatsRepository,
MatchStatsUserRecordFragment,
} from './match-stats.repository';
import { MatchStatsService } from './match-stats.service';
import {
InternalGameDetail,
@@ -55,6 +59,10 @@ interface BaseDataset {
@Injectable()
export class CommunityStatsService {
private readonly logger = new Logger(CommunityStatsService.name);
private readonly userInternalHistoryInFlight = new Map<
string,
Promise<UserInternalHistoryResponse>
>();
constructor(
private readonly connectionService: ConnectionService,
@@ -230,58 +238,56 @@ export class CommunityStatsService {
}
const response: InternalMatchDetailResponse = {
match,
games: gameDetails.map(
(game) => ({
gameNumber: game.gameNumber,
riotMatchId: game.riotMatchId,
gameCreation: game.gameCreation,
gameDuration: game.gameDuration,
gameVersion: game.gameVersion,
timeline: game.timeline ?? [],
objectiveEvents: game.objectiveEvents ?? [],
teams: game.teams.map((team) => ({
teamIndex: team.teamIndex,
side: team.side,
win: team.win,
objectives: team.objectives,
bans: team.bans ?? [],
participants: team.participants.map((record) => ({
userId: record.userId,
summonerName: record.summonerName,
tagLine: record.tagLine,
teamIndex: record.teamIndex,
side: record.side,
teamPosition: record.teamPosition,
championId: record.championId,
championLevel: record.championLevel,
kills: record.kills,
deaths: record.deaths,
assists: record.assists,
cs: record.cs,
csPerMin: record.csPerMin,
gold: record.gold,
gpm: record.gpm,
damageDealtToChampions: record.damageDealtToChampions,
damageTaken: record.damageTaken,
damageShare: record.damageShare,
killParticipation: record.killParticipation,
visionScore: record.visionScore,
wardsPlaced: record.wardsPlaced,
wardsKilled: record.wardsKilled,
controlWardsBought: record.controlWardsBought,
firstBloodKill: record.firstBloodKill ?? false,
firstBloodAssist: record.firstBloodAssist ?? false,
items: record.items,
trinket: record.trinket,
summonerSpells: record.summonerSpells,
perks: record.perks,
itemBuild: record.itemBuild ?? [],
skillBuild: record.skillBuild ?? [],
win: record.win,
})),
games: gameDetails.map((game) => ({
gameNumber: game.gameNumber,
riotMatchId: game.riotMatchId,
gameCreation: game.gameCreation,
gameDuration: game.gameDuration,
gameVersion: game.gameVersion,
timeline: game.timeline ?? [],
objectiveEvents: game.objectiveEvents ?? [],
teams: game.teams.map((team) => ({
teamIndex: team.teamIndex,
side: team.side,
win: team.win,
objectives: team.objectives,
bans: team.bans ?? [],
participants: team.participants.map((record) => ({
userId: record.userId,
summonerName: record.summonerName,
tagLine: record.tagLine,
teamIndex: record.teamIndex,
side: record.side,
teamPosition: record.teamPosition,
championId: record.championId,
championLevel: record.championLevel,
kills: record.kills,
deaths: record.deaths,
assists: record.assists,
cs: record.cs,
csPerMin: record.csPerMin,
gold: record.gold,
gpm: record.gpm,
damageDealtToChampions: record.damageDealtToChampions,
damageTaken: record.damageTaken,
damageShare: record.damageShare,
killParticipation: record.killParticipation,
visionScore: record.visionScore,
wardsPlaced: record.wardsPlaced,
wardsKilled: record.wardsKilled,
controlWardsBought: record.controlWardsBought,
firstBloodKill: record.firstBloodKill ?? false,
firstBloodAssist: record.firstBloodAssist ?? false,
items: record.items,
trinket: record.trinket,
summonerSpells: record.summonerSpells,
perks: record.perks,
itemBuild: record.itemBuild ?? [],
skillBuild: record.skillBuild ?? [],
win: record.win,
})),
}),
),
})),
})),
};
await this.cacheService.setDetail(key, response);
return response;
@@ -293,7 +299,7 @@ export class CommunityStatsService {
filters: CommunityStatsFilters;
}): Promise<UserInternalHistoryResponse> {
const key = this.cacheKey(
`userInternal:${params.userId.toString()}`,
`userInternal:v3:${params.userId.toString()}`,
params.communityId,
params.filters,
);
@@ -301,38 +307,20 @@ export class CommunityStatsService {
await this.cacheService.get<UserInternalHistoryResponse>(key);
if (cached) return cached;
const dataset = await this.buildBaseDataset(
params.communityId,
params.filters,
);
const allUserRecords = dataset.records
.filter((record) => record.userId === params.userId.toString())
.sort((left, right) => right.gameCreation - left.gameCreation);
const records = this.applyChampionFilter(allUserRecords, params.filters);
const limit = this.clampLimit(params.filters.limit, 30, 50);
const cursor = params.filters.cursor;
const page = records
.filter((record) => !cursor || record.gameCreation < cursor)
.slice(0, limit + 1);
const visible = page.slice(0, limit);
const response: UserInternalHistoryResponse = {
season: dataset.season,
championStats: this.buildUserChampionStats(
allUserRecords,
dataset.season,
),
summary: this.buildUserSummary(records, visible.length || limit),
matches: visible.map((record) => this.toRecentMatchView(record, dataset)),
nextCursor:
page.length > limit
? (visible[visible.length - 1]?.gameCreation ?? null)
: null,
lastFetchedAt: records[0]
? new Date(records[0].gameCreation).toISOString()
: null,
};
await this.cacheService.set(key, response);
return response;
// Auction viewers can all request the same next player's internal history
// at once. Coalesce local cache misses so one player change does one DB read.
const inFlight = this.userInternalHistoryInFlight.get(key);
if (inFlight) return inFlight;
const promise = this.buildUserInternalHistoryResponse(params, key);
this.userInternalHistoryInFlight.set(key, promise);
try {
return await promise;
} finally {
if (this.userInternalHistoryInFlight.get(key) === promise) {
this.userInternalHistoryInFlight.delete(key);
}
}
}
public invalidateCommunity(
@@ -367,7 +355,7 @@ export class CommunityStatsService {
const detailsByMatchId = new Map<string, InternalGameDetail[]>();
for (const fragment of fragments) {
const filteredGames = (fragment.gameDetails as InternalGameDetail[])
const filteredGames = fragment.gameDetails
.filter((game) => this.isGameInRange(game.gameCreation, context))
.sort((left, right) => left.gameNumber - right.gameNumber);
if (filteredGames.length === 0) continue;
@@ -383,7 +371,7 @@ export class CommunityStatsService {
filteredGames.map((game) => game.gameNumber),
);
records.push(
...(fragment.records as InternalRecord[]).filter((record) =>
...fragment.records.filter((record) =>
allowedGameNumbers.has(record.gameNumber),
),
);
@@ -397,6 +385,116 @@ export class CommunityStatsService {
};
}
private async buildUserInternalHistoryResponse(
params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
filters: CommunityStatsFilters;
},
cacheKey: string,
): Promise<UserInternalHistoryResponse> {
const context = await this.resolveContext(
params.communityId,
params.filters,
);
const userId = params.userId.toString();
const fragments = await this.matchStatsRepository.findUserRecordFragments({
communityId: params.communityId,
userId: params.userId,
fromGameCreation: context.from?.getTime(),
toGameCreation: context.to?.getTime(),
limit: MAX_MATCH_SCAN,
});
const allUserRecords = this.extractUserRecords(fragments, userId, context);
const records = this.applyChampionFilter(allUserRecords, params.filters);
const limit = this.clampLimit(params.filters.limit, 30, 50);
const cursor = params.filters.cursor;
const page = records
.filter((record) => !cursor || record.gameCreation < cursor)
.slice(0, limit + 1);
const visible = page.slice(0, limit);
const detailsByMatchId = await this.loadVisibleDetails(
params.communityId,
visible,
context,
);
const dataset: BaseDataset = {
season: context.season,
matches: [],
records: allUserRecords,
detailsByMatchId,
};
const response: UserInternalHistoryResponse = {
season: context.season,
championStats: this.buildUserChampionStats(
allUserRecords,
context.season,
),
summary: this.buildUserSummary(records, visible.length || limit),
matches: visible.map((record) => this.toRecentMatchView(record, dataset)),
nextCursor:
page.length > limit
? (visible[visible.length - 1]?.gameCreation ?? null)
: null,
lastFetchedAt: records[0]
? new Date(records[0].gameCreation).toISOString()
: null,
};
await this.cacheService.set(cacheKey, response);
return response;
}
private extractUserRecords(
fragments: MatchStatsUserRecordFragment[],
userId: string,
context: CommunityStatsContext,
): InternalRecord[] {
return fragments
.flatMap((fragment) =>
fragment.records.filter(
(record) =>
record.userId === userId &&
this.isGameInRange(record.gameCreation, context),
),
)
.sort((left, right) => right.gameCreation - left.gameCreation);
}
private async loadVisibleDetails(
communityId: mongoose.Types.ObjectId,
visible: InternalRecord[],
context: CommunityStatsContext,
): Promise<Map<string, InternalGameDetail[]>> {
const matchIds = [
...new Set(
visible
.map((record) => record.matchId)
.filter((matchId) => mongoose.isValidObjectId(matchId)),
),
].map((matchId) => new mongoose.Types.ObjectId(matchId));
const fragments = await this.matchStatsRepository.findDetailsByMatches({
communityId,
matchIds,
});
return this.toDetailsByMatchId(fragments, context);
}
private toDetailsByMatchId(
fragments: MatchStatsDetailFragment[],
context: CommunityStatsContext,
): Map<string, InternalGameDetail[]> {
const detailsByMatchId = new Map<string, InternalGameDetail[]>();
for (const fragment of fragments) {
detailsByMatchId.set(
fragment.matchId.toString(),
fragment.gameDetails.filter((game) =>
this.isGameInRange(game.gameCreation, context),
),
);
}
return detailsByMatchId;
}
private async rebuildMissingOrStaleFragments(
communityId: mongoose.Types.ObjectId,
): Promise<number> {
@@ -405,11 +503,14 @@ export class CommunityStatsService {
MatchModel.find({
communityId,
status: { $in: ['finished', 'in-progress'] },
'result.games.0': { $exists: true },
$or: [
{ competitionId: { $exists: true } },
{ 'result.games.0': { $exists: true } },
],
})
.sort({ scheduledAt: -1 })
.limit(MAX_MATCH_SCAN)
.select({ _id: 1 })
.select({ _id: 1, competitionId: 1 })
.exec(),
this.matchStatsRepository.findByCommunity({
communityId,
@@ -419,11 +520,45 @@ export class CommunityStatsService {
const fragmentByMatchId = new Map(
fragments.map((fragment) => [fragment.matchId.toString(), fragment]),
);
const competitionIds = matches.flatMap((match) =>
match.competitionId ? [match.competitionId] : [],
);
const CompetitionModel =
await this.connectionService.getModel('competition');
const competitions =
competitionIds.length > 0
? await CompetitionModel.find({ _id: { $in: competitionIds } })
.select({ _id: 1, revision: 1, projectorVersion: 1 })
.lean()
.exec()
: [];
const competitionById = new Map(
competitions.map((competition) => [
competition._id.toString(),
competition,
]),
);
let rebuilt = 0;
for (const match of matches) {
const fragment = fragmentByMatchId.get(match._id.toString());
if (fragment && fragment.builderVersion >= MATCH_STATS_BUILDER_VERSION) {
const competition = match.competitionId
? competitionById.get(match.competitionId.toString())
: undefined;
const sourceIsCurrent = match.competitionId
? Boolean(
competition &&
fragment?.sourceCompetitionId?.toString() ===
competition._id.toString() &&
(fragment.sourceRevision ?? -1) >= competition.revision &&
(fragment.projectorVersion ?? -1) >= competition.projectorVersion,
)
: true;
if (
fragment &&
fragment.builderVersion >= MATCH_STATS_BUILDER_VERSION &&
sourceIsCurrent
) {
continue;
}
@@ -789,6 +924,8 @@ export class CommunityStatsService {
?.find((game) => game.riotMatchId === record.riotMatchId);
return {
matchId: record.riotMatchId,
internalMatchId: record.matchId,
gameNumber: record.gameNumber,
queueId: 0,
queueLabel: '내전',
gameCreation: record.gameCreation,
@@ -0,0 +1,216 @@
import { Types } from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type { MatchStats } from '../global/database/schema';
import { MatchStatsRepository } from './match-stats.repository';
describe('MatchStatsRepository', () => {
it('does not let a legacy upsert overwrite a Competition-backed fragment', async () => {
const fragment = {
...statsFragment(12),
sourceCompetitionId: undefined,
sourceRevision: undefined,
projectorVersion: undefined,
};
const updateOne = jest
.fn()
.mockReturnValueOnce({
exec: jest.fn().mockResolvedValue({ matchedCount: 0 }),
})
.mockReturnValueOnce({
exec: jest
.fn()
.mockResolvedValue({ matchedCount: 1, upsertedCount: 0 }),
});
const connection = {
getModel: jest.fn().mockResolvedValue({ updateOne }),
} as unknown as ConnectionService;
const repository = new MatchStatsRepository(connection);
await repository.upsert(fragment);
expect(updateOne).toHaveBeenNthCalledWith(
1,
{
matchId: fragment.matchId,
sourceCompetitionId: { $exists: false },
},
{ $set: fragment },
{ upsert: false },
);
expect(updateOne).toHaveBeenNthCalledWith(
2,
{ matchId: fragment.matchId },
{ $setOnInsert: fragment },
{ upsert: true },
);
});
it('only updates a Competition projection when its revision is not stale', async () => {
const updateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ matchedCount: 1, upsertedCount: 0 }),
});
const connection = {
getModel: jest.fn().mockResolvedValue({ updateOne }),
} as unknown as ConnectionService;
const repository = new MatchStatsRepository(connection);
const fragment = statsFragment(12);
await repository.upsert(fragment);
expect(updateOne).toHaveBeenCalledWith(
{
matchId: fragment.matchId,
$or: [
{ sourceCompetitionId: { $exists: false } },
{ sourceCompetitionId: fragment.sourceCompetitionId },
],
$and: [
{
$or: [
{ sourceRevision: { $exists: false } },
{ sourceRevision: { $lte: 12 } },
],
},
],
},
{ $set: fragment },
{ upsert: false },
);
});
it('converges concurrent initial upserts to the highest Competition revision', async () => {
const older = statsFragment(12);
const newer = {
...statsFragment(13),
matchId: older.matchId,
sourceCompetitionId: older.sourceCompetitionId,
};
let stored: ReturnType<typeof statsFragment> | undefined;
let initialGuardCount = 0;
let releaseInitialGuards!: () => void;
const initialGuardsReady = new Promise<void>((resolve) => {
releaseInitialGuards = resolve;
});
let releaseOlderInsert!: () => void;
const olderInserted = new Promise<void>((resolve) => {
releaseOlderInsert = resolve;
});
const updateOne = jest.fn(
(
_filter: Record<string, unknown>,
update: {
$set?: ReturnType<typeof statsFragment>;
$setOnInsert?: ReturnType<typeof statsFragment>;
},
) => ({
exec: async () => {
const fragment = update.$set ?? update.$setOnInsert!;
if (update.$set && !stored && initialGuardCount < 2) {
initialGuardCount += 1;
if (initialGuardCount === 2) releaseInitialGuards();
await initialGuardsReady;
return { matchedCount: 0, upsertedCount: 0 };
}
if (update.$setOnInsert) {
if (fragment.sourceRevision === 13) await olderInserted;
const existed = stored !== undefined;
if (!stored) stored = fragment;
if (fragment.sourceRevision === 12) releaseOlderInsert();
return {
matchedCount: existed ? 1 : 0,
upsertedCount: existed ? 0 : 1,
};
}
if (
stored &&
stored.sourceCompetitionId?.equals(fragment.sourceCompetitionId!) &&
stored.sourceRevision! <= fragment.sourceRevision!
) {
stored = fragment;
return { matchedCount: 1, upsertedCount: 0 };
}
return { matchedCount: 0, upsertedCount: 0 };
},
}),
);
const connection = {
getModel: jest.fn().mockResolvedValue({ updateOne }),
} as unknown as ConnectionService;
const repository = new MatchStatsRepository(connection);
await Promise.all([repository.upsert(older), repository.upsert(newer)]);
expect(stored?.sourceRevision).toBe(13);
});
it('guards a zero-game delete so an observed revision cannot remove newer stats', async () => {
const matchId = new Types.ObjectId();
const sourceCompetitionId = new Types.ObjectId();
const deleteOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ deletedCount: 0 }),
});
const connection = {
getModel: jest.fn().mockResolvedValue({ deleteOne }),
} as unknown as ConnectionService;
const repository = new MatchStatsRepository(connection);
await repository.deleteByMatch(matchId, {
sourceCompetitionId,
sourceRevision: 12,
});
expect(deleteOne).toHaveBeenCalledWith({
matchId,
$or: [
{ sourceCompetitionId: { $exists: false } },
{
sourceCompetitionId,
$or: [
{ sourceRevision: { $exists: false } },
{ sourceRevision: { $lte: 12 } },
],
},
],
});
});
it('deletes only non-Competition stats during legacy source cleanup', async () => {
const matchId = new Types.ObjectId();
const deleteOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ deletedCount: 0 }),
});
const connection = {
getModel: jest.fn().mockResolvedValue({ deleteOne }),
} as unknown as ConnectionService;
const repository = new MatchStatsRepository(connection);
await repository.deleteLegacyByMatch(matchId);
expect(deleteOne).toHaveBeenCalledWith({
matchId,
sourceCompetitionId: { $exists: false },
});
});
});
function statsFragment(sourceRevision: number) {
return {
matchId: new Types.ObjectId(),
communityId: new Types.ObjectId(),
sourceCompetitionId: new Types.ObjectId(),
sourceRevision,
projectorVersion: 3,
scheduledAt: new Date(),
gameCreationMin: 1,
gameCreationMax: 2,
userIds: [],
championIds: [],
matchCard: {},
records: [],
gameDetails: [],
builtAt: new Date(),
builderVersion: 9,
} satisfies Omit<MatchStats, 'createdAt' | 'updatedAt'>;
}
@@ -3,6 +3,21 @@ import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type { MatchStats, MatchStatsDocument } from '../global/database/schema';
export type MatchStatsUserRecordFragment = Pick<
MatchStats,
'matchId' | 'records'
>;
export type MatchStatsDetailFragment = Pick<
MatchStats,
'matchId' | 'gameDetails'
>;
export interface MatchStatsDeleteGuard {
sourceCompetitionId: mongoose.Types.ObjectId;
sourceRevision: number;
}
@Injectable()
export class MatchStatsRepository {
constructor(private readonly connectionService: ConnectionService) {}
@@ -11,16 +26,86 @@ export class MatchStatsRepository {
fragment: Omit<MatchStats, 'createdAt' | 'updatedAt'>,
): Promise<void> {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
await MatchStatsModel.updateOne(
{ matchId: fragment.matchId },
if (
!fragment.sourceCompetitionId ||
fragment.sourceRevision === undefined
) {
const updated = await MatchStatsModel.updateOne(
{
matchId: fragment.matchId,
sourceCompetitionId: { $exists: false },
},
{ $set: fragment },
{ upsert: false },
).exec();
if (updated.matchedCount > 0) return;
// A legacy builder must never overwrite a Competition-backed fragment
// that appeared while the legacy source was being read.
try {
await MatchStatsModel.updateOne(
{ matchId: fragment.matchId },
{ $setOnInsert: fragment },
{ upsert: true },
).exec();
} catch (error) {
if (!isDuplicateKeyError(error)) throw error;
}
return;
}
const revisionGuard = competitionRevisionGuard(fragment);
const updated = await MatchStatsModel.updateOne(
revisionGuard,
{ $set: fragment },
{ upsert: true },
{ upsert: false },
).exec();
if (updated.matchedCount > 0) return;
// If no read model exists, insert it. If a newer revision won the race,
// this filter matches it and $setOnInsert intentionally changes nothing.
try {
await MatchStatsModel.updateOne(
{ matchId: fragment.matchId },
{ $setOnInsert: fragment },
{ upsert: true },
).exec();
} catch (error) {
if (!isDuplicateKeyError(error)) throw error;
}
// A lower revision can win the initial insert between the guarded miss and
// the upsert. Re-run the monotonic CAS so every concurrent builder converges
// to the highest source revision; a newer winner simply does not match.
await MatchStatsModel.updateOne(
revisionGuard,
{ $set: fragment },
{ upsert: false },
).exec();
}
public async deleteByMatch(matchId: mongoose.Types.ObjectId): Promise<void> {
public async deleteByMatch(
matchId: mongoose.Types.ObjectId,
guard?: MatchStatsDeleteGuard,
): Promise<void> {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
await MatchStatsModel.deleteOne({ matchId }).exec();
await MatchStatsModel.deleteOne(
guard
? {
matchId,
$or: [
{ sourceCompetitionId: { $exists: false } },
{
sourceCompetitionId: guard.sourceCompetitionId,
$or: [
{ sourceRevision: { $exists: false } },
{ sourceRevision: { $lte: guard.sourceRevision } },
],
},
],
}
: { matchId },
).exec();
}
public async deleteByMatches(
@@ -31,6 +116,16 @@ export class MatchStatsRepository {
await MatchStatsModel.deleteMany({ matchId: { $in: matchIds } }).exec();
}
public async deleteLegacyByMatch(
matchId: mongoose.Types.ObjectId,
): Promise<void> {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
await MatchStatsModel.deleteOne({
matchId,
sourceCompetitionId: { $exists: false },
}).exec();
}
public async findByMatch(
matchId: mongoose.Types.ObjectId,
): Promise<MatchStatsDocument | null> {
@@ -68,6 +163,53 @@ export class MatchStatsRepository {
toGameCreation?: number;
}): Promise<MatchStatsDocument[]> {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
const filter = this.buildUserFilter(params);
return MatchStatsModel.find(filter).sort({ scheduledAt: -1 }).exec();
}
public async findUserRecordFragments(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
fromGameCreation?: number;
toGameCreation?: number;
limit?: number;
}): Promise<MatchStatsUserRecordFragment[]> {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
const filter = this.buildUserFilter(params);
// User history only needs records for summaries/page selection; gameDetails
// are much larger and are fetched separately for the visible page.
return MatchStatsModel.find(filter)
.sort({ scheduledAt: -1 })
.limit(params.limit ?? 300)
.select({ _id: 0, matchId: 1, records: 1 })
.lean<MatchStatsUserRecordFragment[]>()
.exec();
}
public async findDetailsByMatches(params: {
communityId: mongoose.Types.ObjectId;
matchIds: mongoose.Types.ObjectId[];
}): Promise<MatchStatsDetailFragment[]> {
if (params.matchIds.length === 0) return [];
const MatchStatsModel = await this.connectionService.getModel('matchStats');
return MatchStatsModel.find({
communityId: params.communityId,
matchId: { $in: params.matchIds },
})
.select({ _id: 0, matchId: 1, gameDetails: 1 })
.lean<MatchStatsDetailFragment[]>()
.exec();
}
private buildUserFilter(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
fromGameCreation?: number;
toGameCreation?: number;
}): Record<string, unknown> {
const filter: Record<string, unknown> = {
communityId: params.communityId,
userIds: params.userId,
@@ -78,7 +220,35 @@ export class MatchStatsRepository {
if (params.toGameCreation !== undefined) {
filter.gameCreationMin = { $lte: params.toGameCreation };
}
return MatchStatsModel.find(filter).sort({ scheduledAt: -1 }).exec();
return filter;
}
}
function competitionRevisionGuard(
fragment: Omit<MatchStats, 'createdAt' | 'updatedAt'>,
) {
return {
matchId: fragment.matchId,
$or: [
{ sourceCompetitionId: { $exists: false } },
{ sourceCompetitionId: fragment.sourceCompetitionId },
],
$and: [
{
$or: [
{ sourceRevision: { $exists: false } },
{ sourceRevision: { $lte: fragment.sourceRevision } },
],
},
],
};
}
function isDuplicateKeyError(error: unknown): boolean {
return (
typeof error === 'object' &&
error !== null &&
'code' in error &&
error.code === 11_000
);
}
@@ -17,6 +17,7 @@ describe('MatchStatsService', () => {
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') return { findById };
if (name === 'competition') return { findOne: () => queryResult(null) };
if (name === 'riotMatch') return {};
throw new Error(`Unexpected model: ${name}`);
}),
@@ -38,6 +39,57 @@ describe('MatchStatsService', () => {
expect(repository.upsert).not.toHaveBeenCalled();
});
it('revision-guards deletion when a Competition reversal leaves zero games', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const match = {
_id: matchId,
communityId,
scheduledAt: new Date('2026-07-12T10:00:00.000Z'),
status: 'in-progress',
teams: [],
result: undefined,
};
const competition = {
_id: competitionId,
revision: 12,
projectorVersion: 3,
teams: [],
projection: { phase: 'ready', games: [] },
};
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') {
return { findById: () => queryResult(match, false) };
}
if (name === 'competition') {
return { findOne: () => queryResult(competition) };
}
if (name === 'riotMatch') return {};
throw new Error(`Unexpected model: ${name}`);
}),
} as unknown as ConnectionService;
const repository = {
deleteByMatch: jest.fn().mockResolvedValue(undefined),
upsert: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
const service = new MatchStatsService(
connectionService,
repository,
{} as MatchStatsFragmentBuilder,
{ getMatchTimeline: jest.fn() } as never,
);
await service.buildAndUpsert(matchId, { sourceRevision: 12 });
expect(repository.deleteByMatch).toHaveBeenCalledWith(matchId, {
sourceCompetitionId: competitionId,
sourceRevision: 12,
});
expect(repository.upsert).not.toHaveBeenCalled();
});
it('upserts a fragment for eligible matches', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
@@ -73,6 +125,7 @@ describe('MatchStatsService', () => {
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') return { findById };
if (name === 'competition') return { findOne: () => queryResult(null) };
if (name === 'riotMatch') return { find: riotFind };
throw new Error(`Unexpected model: ${name}`);
}),
@@ -118,4 +171,283 @@ describe('MatchStatsService', () => {
}),
);
});
it('builds from the Competition projection and records its source revision', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const teamAId = new mongoose.Types.ObjectId();
const teamBId = new mongoose.Types.ObjectId();
const userAId = new mongoose.Types.ObjectId();
const userBId = new mongoose.Types.ObjectId();
const match = {
_id: matchId,
communityId,
scheduledAt: new Date('2026-07-12T10:00:00.000Z'),
status: 'in-progress',
teams: [],
result: { games: [{ riotMatchId: 'KR_LEGACY_MUST_NOT_BE_USED' }] },
};
const competition = {
_id: competitionId,
revision: 12,
projectorVersion: 3,
teams: [
{ teamId: teamAId, legacyTeamIndex: 8, displayOrder: 1 },
{ teamId: teamBId, legacyTeamIndex: 3, displayOrder: 2 },
],
projection: {
phase: 'running',
games: [
{
displayNumber: 4,
evidence: { type: 'riot', riotMatchId: 'KR_COMPETITION' },
teams: {
blue: { teamId: teamAId.toString() },
red: { teamId: teamBId.toString() },
},
winnerTeamId: teamAId.toString(),
startedAt: '2026-07-12T10:00:00.000Z',
durationSeconds: 1800,
participants: [
participant(userAId, teamAId, 'blue', true),
participant(userBId, teamBId, 'red', false),
],
},
],
},
};
const riotFind = jest.fn().mockReturnValue({
lean: () => ({
exec: jest
.fn()
.mockResolvedValue([{ matchId: 'KR_COMPETITION', raw: {} }]),
}),
});
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match')
return { findById: () => queryResult(match, false) };
if (name === 'competition') {
return { findOne: () => queryResult(competition) };
}
if (name === 'riotMatch') return { find: riotFind };
throw new Error(`Unexpected model: ${name}`);
}),
} as unknown as ConnectionService;
const repository = {
upsert: jest.fn().mockResolvedValue(undefined),
deleteByMatch: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
const builder = {
buildFragment: jest.fn().mockReturnValue({
matchCard: {},
records: [],
gameDetails: [],
userIds: [],
championIds: [],
gameCreationMin: 1,
gameCreationMax: 2,
}),
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
const service = new MatchStatsService(
connectionService,
repository,
builder,
{ getMatchTimeline: jest.fn() } as never,
);
await service.buildAndUpsert(matchId, { sourceRevision: 12 });
expect(riotFind).toHaveBeenCalledWith({
matchId: { $in: ['KR_COMPETITION'] },
});
expect(builder.buildFragment).toHaveBeenCalledWith(
expect.objectContaining({
match: expect.objectContaining({
result: expect.objectContaining({
riotMatchIds: ['KR_COMPETITION'],
games: [
expect.objectContaining({
gameNumber: 4,
blueTeamIndex: 8,
redTeamIndex: 3,
winnerTeamIndex: 8,
}),
],
}),
}),
}),
);
expect(repository.upsert).toHaveBeenCalledWith(
expect.objectContaining({
sourceCompetitionId: competitionId,
sourceRevision: 12,
projectorVersion: 3,
}),
);
});
it('removes a fragment written after its Competition Match was deleted', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const teamAId = new mongoose.Types.ObjectId();
const teamBId = new mongoose.Types.ObjectId();
const match = {
_id: matchId,
communityId,
scheduledAt: new Date('2026-07-12T10:00:00.000Z'),
status: 'in-progress',
teams: [],
result: undefined,
};
const competition = {
_id: competitionId,
revision: 12,
projectorVersion: 3,
teams: [
{ teamId: teamAId, legacyTeamIndex: 1, displayOrder: 1 },
{ teamId: teamBId, legacyTeamIndex: 2, displayOrder: 2 },
],
projection: {
phase: 'running',
games: [
{
id: new mongoose.Types.ObjectId(),
displayNumber: 1,
evidence: { type: 'legacy', legacyReference: 'legacy:1' },
teams: {
blue: { teamId: teamAId.toString() },
red: { teamId: teamBId.toString() },
},
winnerTeamId: teamAId.toString(),
},
],
},
};
const findById = jest
.fn()
.mockReturnValueOnce(queryResult(match, false))
.mockReturnValueOnce(queryResult(null, false));
const findCompetition = jest.fn().mockReturnValue(queryResult(competition));
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') return { findById };
if (name === 'competition') return { findOne: findCompetition };
if (name === 'riotMatch') return {};
throw new Error(`Unexpected model: ${name}`);
}),
} as unknown as ConnectionService;
const repository = {
upsert: jest.fn().mockResolvedValue(undefined),
deleteByMatch: jest.fn().mockResolvedValue(undefined),
deleteLegacyByMatch: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
const builder = {
buildFragment: jest.fn().mockReturnValue({
matchCard: {},
records: [],
gameDetails: [],
userIds: [],
championIds: [],
gameCreationMin: 1,
gameCreationMax: 2,
}),
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
const service = new MatchStatsService(
connectionService,
repository,
builder,
{ getMatchTimeline: jest.fn() } as never,
);
await service.buildAndUpsert(matchId, { sourceRevision: 12 });
expect(repository.upsert).toHaveBeenCalled();
expect(repository.deleteByMatch).toHaveBeenCalledWith(matchId, {
sourceCompetitionId: competitionId,
sourceRevision: 12,
});
expect(repository.upsert.mock.invocationCallOrder[0]).toBeLessThan(
repository.deleteByMatch.mock.invocationCallOrder[0],
);
});
it('does not rebuild before the requested Competition revision is visible', async () => {
const matchId = new mongoose.Types.ObjectId();
const riotFind = jest.fn();
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') {
return {
findById: () =>
queryResult(
{
_id: matchId,
status: 'in-progress',
},
false,
),
};
}
if (name === 'competition') {
return {
findOne: () => queryResult({ revision: 11 }),
};
}
if (name === 'riotMatch') return { find: riotFind };
throw new Error(`Unexpected model: ${name}`);
}),
} as unknown as ConnectionService;
const repository = {
upsert: jest.fn(),
deleteByMatch: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
const builder = {
buildFragment: jest.fn(),
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
const service = new MatchStatsService(
connectionService,
repository,
builder,
{ getMatchTimeline: jest.fn() } as never,
);
await service.buildAndUpsert(matchId, { sourceRevision: 12 });
expect(riotFind).not.toHaveBeenCalled();
expect(builder.buildFragment).not.toHaveBeenCalled();
expect(repository.upsert).not.toHaveBeenCalled();
expect(repository.deleteByMatch).not.toHaveBeenCalled();
});
});
function participant(
userId: mongoose.Types.ObjectId,
teamId: mongoose.Types.ObjectId,
side: 'blue' | 'red',
win: boolean,
) {
return {
userId: userId.toString(),
teamId: teamId.toString(),
side,
summonerName: 'player',
tagLine: 'KR1',
championId: 1,
kills: 1,
deaths: 1,
assists: 1,
win,
};
}
function queryResult<T>(value: T, lean = true) {
const query = {
lean: jest.fn(),
exec: jest.fn().mockResolvedValue(value),
};
query.lean.mockReturnValue(query);
return lean ? query : { exec: query.exec };
}
@@ -26,18 +26,40 @@ export class MatchStatsService {
public async buildAndUpsert(
matchId: mongoose.Types.ObjectId,
options: { includeTimeline?: boolean } = {},
options: { includeTimeline?: boolean; sourceRevision?: number } = {},
): Promise<void> {
const MatchModel = await this.connectionService.getModel('match');
const CompetitionModel =
await this.connectionService.getModel('competition');
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const match = await MatchModel.findById(matchId).exec();
if (!match) return;
if (!this.isEligible(match)) {
await this.repository.deleteByMatch(matchId);
const competition = await CompetitionModel.findOne({ matchId })
.lean()
.exec();
if (
options.sourceRevision !== undefined &&
(!competition || competition.revision < options.sourceRevision)
) {
return;
}
const competitionSource = competition
? competitionStatsSource(match, competition)
: undefined;
const sourceMatch = competitionSource?.match ?? match;
if (!this.isEligible(sourceMatch)) {
if (competitionSource) {
await this.repository.deleteByMatch(matchId, {
sourceCompetitionId: competitionSource.sourceCompetitionId,
sourceRevision: competitionSource.sourceRevision,
});
} else {
await this.repository.deleteByMatch(matchId);
}
return;
}
const riotIds = [
const riotIds = competitionSource?.riotMatchIds ?? [
...new Set(
(match.result?.games ?? [])
.map((game) => game.riotMatchId)
@@ -93,7 +115,7 @@ export class MatchStatsService {
}
const fragment = this.builder.buildFragment({
match,
match: sourceMatch,
rawByRiotMatchId,
timelineByRiotMatchId,
timelineLoadAttempted: options.includeTimeline === true,
@@ -112,7 +134,19 @@ export class MatchStatsService {
gameDetails: fragment.gameDetails,
builtAt: new Date(),
builderVersion: MATCH_STATS_BUILDER_VERSION,
...(competitionSource
? {
sourceCompetitionId: competitionSource.sourceCompetitionId,
sourceRevision: competitionSource.sourceRevision,
projectorVersion: competitionSource.projectorVersion,
}
: {}),
});
// Source reads and the read-model write are intentionally separated by
// Riot/timeline work. Revalidate after the write so a concurrent aggregate
// deletion cannot resurrect MatchStats after the delete transaction.
await this.removeFragmentIfSourceChanged(matchId, competitionSource);
}
public async removeByMatch(matchId: mongoose.Types.ObjectId): Promise<void> {
@@ -132,7 +166,10 @@ export class MatchStatsService {
const matches = await MatchModel.find({
communityId,
status: { $in: ['finished', 'in-progress'] },
'result.games.0': { $exists: true },
$or: [
{ competitionId: { $exists: true } },
{ 'result.games.0': { $exists: true } },
],
})
.sort({ scheduledAt: -1 })
.select({ _id: 1 })
@@ -171,11 +208,52 @@ export class MatchStatsService {
? (region as RiotRegionalRoute)
: 'asia';
}
private async removeFragmentIfSourceChanged(
matchId: mongoose.Types.ObjectId,
source:
| {
sourceCompetitionId: mongoose.Types.ObjectId;
sourceRevision: number;
}
| undefined,
): Promise<void> {
const [MatchModel, CompetitionModel] = await Promise.all([
this.connectionService.getModel('match'),
this.connectionService.getModel('competition'),
]);
const [currentMatch, currentCompetition] = await Promise.all([
MatchModel.findById(matchId).exec(),
CompetitionModel.findOne({
matchId,
...(source
? {
_id: source.sourceCompetitionId,
revision: source.sourceRevision,
}
: {}),
})
.lean()
.exec(),
]);
if (source) {
if (!currentMatch || !currentCompetition) {
await this.repository.deleteByMatch(matchId, {
sourceCompetitionId: source.sourceCompetitionId,
sourceRevision: source.sourceRevision,
});
}
return;
}
if (!currentMatch || currentCompetition) {
await this.repository.deleteLegacyByMatch(matchId);
}
}
}
function isRiotMatchTimelineDto(
value: unknown,
): value is RiotMatchTimelineDto {
function isRiotMatchTimelineDto(value: unknown): value is RiotMatchTimelineDto {
if (!isRecord(value) || !isRecord(value.info)) return false;
return Array.isArray(value.info.frames);
}
@@ -183,3 +261,153 @@ function isRiotMatchTimelineDto(
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
function competitionStatsSource(
match: MatchDocument,
competition: {
_id: mongoose.Types.ObjectId;
revision: number;
projectorVersion: number;
teams: unknown[];
projection: Record<string, unknown>;
},
): {
match: MatchDocument;
riotMatchIds: string[];
sourceCompetitionId: mongoose.Types.ObjectId;
sourceRevision: number;
projectorVersion: number;
} {
const teamIndexById = new Map<string, number>();
for (const rawTeam of competition.teams) {
if (!isRecord(rawTeam)) continue;
const teamId = identifier(rawTeam.teamId);
const legacyTeamIndex = finiteNumber(rawTeam.legacyTeamIndex);
const displayOrder = finiteNumber(rawTeam.displayOrder);
if (teamId && (legacyTeamIndex ?? displayOrder)) {
teamIndexById.set(teamId, legacyTeamIndex ?? displayOrder!);
}
}
const rawGames = Array.isArray(competition.projection.games)
? competition.projection.games
: [];
const riotMatchIds = new Set<string>();
const games = rawGames.flatMap((rawGame, gameIndex) => {
if (!isRecord(rawGame)) return [];
const teams = isRecord(rawGame.teams) ? rawGame.teams : undefined;
const blue = teams && isRecord(teams.blue) ? teams.blue : undefined;
const red = teams && isRecord(teams.red) ? teams.red : undefined;
const blueTeamId = identifier(blue?.teamId);
const redTeamId = identifier(red?.teamId);
const winnerTeamId = identifier(rawGame.winnerTeamId);
const blueTeamIndex = blueTeamId
? teamIndexById.get(blueTeamId)
: undefined;
const redTeamIndex = redTeamId ? teamIndexById.get(redTeamId) : undefined;
const winnerTeamIndex = winnerTeamId
? teamIndexById.get(winnerTeamId)
: undefined;
if (!blueTeamIndex || !redTeamIndex || !winnerTeamIndex) return [];
const evidence = isRecord(rawGame.evidence) ? rawGame.evidence : undefined;
const riotMatchId =
evidence?.type === 'riot' && typeof evidence.riotMatchId === 'string'
? evidence.riotMatchId
: typeof evidence?.legacyReference === 'string'
? evidence.legacyReference
: `competition:${identifier(rawGame.id) ?? 'game'}`;
if (evidence?.type === 'riot') riotMatchIds.add(riotMatchId);
const participantValues = Array.isArray(rawGame.participants)
? rawGame.participants
: [];
const participants = participantValues.flatMap((rawParticipant) => {
if (!isRecord(rawParticipant)) return [];
const userId = identifier(rawParticipant.userId);
const teamId = identifier(rawParticipant.teamId);
const teamIndex = teamId ? teamIndexById.get(teamId) : undefined;
const side = rawParticipant.side;
if (
!userId ||
!mongoose.isValidObjectId(userId) ||
!teamIndex ||
(side !== 'blue' && side !== 'red')
) {
return [];
}
return [
{
userId: new mongoose.Types.ObjectId(userId),
teamIndex,
side,
championId: finiteNumber(rawParticipant.championId) ?? 0,
kills: finiteNumber(rawParticipant.kills) ?? 0,
deaths: finiteNumber(rawParticipant.deaths) ?? 0,
assists: finiteNumber(rawParticipant.assists) ?? 0,
win: teamId === winnerTeamId,
},
];
});
const startedAt = dateFromUnknown(rawGame.startedAt);
return [
{
gameNumber: finiteNumber(rawGame.displayNumber) ?? gameIndex + 1,
riotMatchId,
blueTeamIndex,
redTeamIndex,
winnerTeamIndex,
winnerSide:
winnerTeamIndex === blueTeamIndex
? ('blue' as const)
: ('red' as const),
gameCreation: Number.isNaN(startedAt.getTime())
? 0
: startedAt.getTime(),
gameDuration: finiteNumber(rawGame.durationSeconds) ?? 0,
participants,
},
];
});
const base =
typeof match.toObject === 'function' ? match.toObject() : { ...match };
return {
match: {
...base,
status:
competition.projection.phase === 'completed'
? 'finished'
: games.length > 0
? 'in-progress'
: match.status,
result: {
riotMatchIds: games.map(({ riotMatchId }) => riotMatchId),
games,
seriesResults: [],
},
} as unknown as MatchDocument,
riotMatchIds: [...riotMatchIds],
sourceCompetitionId: competition._id,
sourceRevision: competition.revision,
projectorVersion: competition.projectorVersion,
};
}
function identifier(value: unknown): string | undefined {
if (typeof value === 'string' && value.length > 0) return value;
if (value instanceof mongoose.Types.ObjectId) return value.toHexString();
return undefined;
}
function dateFromUnknown(value: unknown): Date {
if (value instanceof Date) return new Date(value.getTime());
if (typeof value === 'string' || typeof value === 'number') {
return new Date(value);
}
return new Date(Number.NaN);
}
function finiteNumber(value: unknown): number | undefined {
return typeof value === 'number' && Number.isFinite(value)
? value
: undefined;
}
@@ -0,0 +1,541 @@
import { Types } from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import {
CompetitionBootstrapError,
CompetitionBootstrapService,
type CompetitionBootstrapMatch,
} from './competition-bootstrap.service';
describe('CompetitionBootstrapService', () => {
it('creates a deterministic paired-Series Competition and immutable snapshots', async () => {
const firstHarness = createHarness();
const firstService = new CompetitionBootstrapService(
firstHarness.connectionService as ConnectionService,
);
const match = matchSnapshot({ gameMode: 'pair', teamCount: 2 });
const first = await firstService.bootstrap(match);
const inserted = firstHarness.insertedPayloads[0];
expect(inserted).toMatchObject({
_id: expect.any(Types.ObjectId),
matchId: MATCH_ID,
communityId: COMMUNITY_ID,
schemaVersion: 1,
projectorVersion: 1,
revision: 0,
phase: 'ready',
format: {
type: 'paired-series',
rule: { type: 'fixed-games', gameCount: 3, drawPolicy: 'allow' },
},
});
expect(inserted.teams).toEqual([
expect.objectContaining({
teamId: expect.any(Types.ObjectId),
legacyTeamIndex: 1,
displayOrder: 1,
seedNumber: 1,
name: 'Team 1',
members: [
expect.objectContaining({
userId: USER_IDS[0],
displayName: 'Player 1#KR1',
gameName: 'Player 1',
tagLine: 'KR1',
profileIconId: 101,
assignedPosition: 'TOP',
cost: 10,
}),
],
}),
expect.objectContaining({
teamId: expect.any(Types.ObjectId),
legacyTeamIndex: 2,
displayOrder: 2,
seedNumber: 2,
name: 'Team 2',
}),
]);
expect(inserted.seriesGraph).toHaveLength(1);
expect(inserted.seriesGraph[0]).toMatchObject({
code: 'PAIR_M1',
slots: [
{
position: 'A',
source: {
type: 'team',
teamId: inserted.teams[0].teamId.toString(),
},
},
{
position: 'B',
source: {
type: 'team',
teamId: inserted.teams[1].teamId.toString(),
},
},
],
});
expect(inserted.projection).toMatchObject({
competitionId: inserted._id.toString(),
sourceRevision: 0,
projectorVersion: 1,
formatType: 'paired-series',
phase: 'ready',
});
expect(first._id).toEqual(inserted._id);
const secondHarness = createHarness();
const secondService = new CompetitionBootstrapService(
secondHarness.connectionService as ConnectionService,
);
await secondService.bootstrap({
...match,
teams: [...match.teams].reverse(),
participants: [...match.participants].reverse(),
});
const secondInserted = secondHarness.insertedPayloads[0];
expect(secondInserted._id).toEqual(inserted._id);
expect(secondInserted.teams.map(({ teamId }) => teamId)).toEqual(
inserted.teams.map(({ teamId }) => teamId),
);
expect(secondInserted.seriesGraph).toEqual(inserted.seriesGraph);
});
it('maps round-robin configuration and preserves a limited round count', async () => {
const harness = createHarness();
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
await service.bootstrap(
matchSnapshot({
gameMode: 'round-robin',
teamCount: 4,
gameCount: 2,
roundRobinMaxRounds: 2,
}),
);
expect(harness.insertedPayloads[0]).toMatchObject({
format: {
type: 'round-robin',
rule: { type: 'fixed-games', gameCount: 2, drawPolicy: 'allow' },
maxRounds: 2,
tieBreakers: ['series-wins', 'game-diff', 'head-to-head'],
},
});
expect(harness.insertedPayloads[0].seriesGraph).toHaveLength(4);
});
it('maps double elimination seeds and stage-specific Series rules', async () => {
const harness = createHarness();
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
const match = matchSnapshot({
gameMode: 'double-elimination',
teamCount: 4,
gameCount: 5,
});
match.doubleElimination = {
teamCount: 4,
resetFinalEnabled: true,
seeds: [
{ seedNumber: 1, teamIndex: 3 },
{ seedNumber: 2, teamIndex: 1 },
{ seedNumber: 3, teamIndex: 4 },
{ seedNumber: 4, teamIndex: 2 },
],
};
await service.bootstrap(match);
const inserted = harness.insertedPayloads[0];
expect(inserted.format).toEqual({
type: 'double-elimination',
teamCount: 4,
resetFinalEnabled: true,
rules: {
upper: { type: 'first-to', winsRequired: 3, maxGames: 5 },
lower: { type: 'first-to', winsRequired: 1, maxGames: 1 },
grandFinal: { type: 'first-to', winsRequired: 1, maxGames: 1 },
resetFinal: { type: 'first-to', winsRequired: 1, maxGames: 1 },
},
});
expect(
inserted.teams.map(({ legacyTeamIndex, seedNumber }) => ({
legacyTeamIndex,
seedNumber,
})),
).toEqual([
{ legacyTeamIndex: 1, seedNumber: 2 },
{ legacyTeamIndex: 2, seedNumber: 4 },
{ legacyTeamIndex: 3, seedNumber: 1 },
{ legacyTeamIndex: 4, seedNumber: 3 },
]);
expect(
inserted.seriesGraph.find(({ code }) => code === 'WB_R1_M1').rule,
).toEqual({ type: 'first-to', winsRequired: 3, maxGames: 5 });
expect(
inserted.seriesGraph.find(({ code }) => code?.startsWith('LB_')).rule,
).toEqual({ type: 'first-to', winsRequired: 1, maxGames: 1 });
expect(inserted.seriesGraph.find(({ code }) => code === 'GF').rule).toEqual(
{ type: 'first-to', winsRequired: 1, maxGames: 1 },
);
expect(
inserted.seriesGraph.find(({ code }) => code === 'GF_RESET'),
).toMatchObject({
rule: { type: 'first-to', winsRequired: 1, maxGames: 1 },
activation: { type: 'grand-final-reset-required' },
});
});
it('rejects double elimination until authoritative seeds are persisted', async () => {
const harness = createHarness();
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
await expect(
service.bootstrap(
matchSnapshot({
gameMode: 'double-elimination',
teamCount: 4,
gameCount: 3,
}),
),
).rejects.toMatchObject({
code: 'INVALID_MATCH_TEAM_SNAPSHOT',
httpStatus: 422,
});
expect(harness.connectionService.createSession).not.toHaveBeenCalled();
expect(harness.competitionModel.findOneAndUpdate).not.toHaveBeenCalled();
});
it('rejects incomplete and duplicate team assignments before opening a transaction', async () => {
const cases: Array<[string, (match: CompetitionBootstrapMatch) => void]> = [
[
'the Match lifecycle is still recruiting',
(match) => {
match.status = 'recruiting';
},
],
[
'an active participant is not assigned',
(match) => {
match.teams[1].members = [];
},
],
[
'the same team index is repeated',
(match) => {
match.teams[1].teamIndex = match.teams[0].teamIndex;
},
],
[
'one member is assigned to multiple teams',
(match) => {
match.teams[1].members[0].userId = match.teams[0].members[0].userId;
},
],
[
'a team member has no participant snapshot',
(match) => {
match.teams[1].members[0].userId = new Types.ObjectId();
},
],
];
for (const [label, mutate] of cases) {
const harness = createHarness();
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
const match = matchSnapshot({ gameMode: 'pair', teamCount: 2 });
mutate(match);
await expect(service.bootstrap(match)).rejects.toMatchObject({
name: 'CompetitionBootstrapError',
code: 'INVALID_MATCH_TEAM_SNAPSHOT',
httpStatus: 422,
});
expect(harness.connectionService.createSession).not.toHaveBeenCalled();
expect(harness.competitionModel.findOneAndUpdate).not.toHaveBeenCalled();
expect(label).toBeTruthy();
}
});
it('rejects bracket mode live but explicitly maps it for legacy migration', async () => {
const liveHarness = createHarness();
const liveService = new CompetitionBootstrapService(
liveHarness.connectionService as ConnectionService,
);
const match = matchSnapshot({ gameMode: 'bracket', teamCount: 2 });
await expect(liveService.bootstrap(match)).rejects.toEqual(
expect.objectContaining<Partial<CompetitionBootstrapError>>({
code: 'UNSUPPORTED_LIVE_MATCH_MODE',
httpStatus: 422,
}),
);
const migrationHarness = createHarness();
const migrationService = new CompetitionBootstrapService(
migrationHarness.connectionService as ConnectionService,
);
await migrationService.bootstrap(match, { source: 'legacy-migration' });
expect(migrationHarness.insertedPayloads[0].format.type).toBe(
'paired-series',
);
});
it('upserts once and links only an unlinked or already-linked Match in one transaction', async () => {
const harness = createHarness();
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
const competition = await service.bootstrap(
matchSnapshot({ gameMode: 'pair', teamCount: 2 }),
);
expect(harness.competitionModel.findOneAndUpdate).toHaveBeenCalledWith(
{ matchId: MATCH_ID },
{ $setOnInsert: harness.insertedPayloads[0] },
expect.objectContaining({
upsert: true,
returnDocument: 'after',
setDefaultsOnInsert: true,
session: harness.sessions[0],
}),
);
expect(harness.matchModel.updateOne).toHaveBeenCalledWith(
{
_id: MATCH_ID,
status: 'team-built',
teamBuiltAt: new Date('2026-07-12T00:05:00.000Z'),
$or: [
{ competitionId: { $exists: false } },
{ competitionId: null },
{ competitionId: competition._id },
],
},
{ $set: { competitionId: competition._id } },
{ session: harness.sessions[0] },
);
expect(harness.sessions[0].commitTransaction).toHaveBeenCalledTimes(1);
expect(harness.sessions[0].abortTransaction).not.toHaveBeenCalled();
expect(harness.sessions[0].endSession).toHaveBeenCalledTimes(1);
});
it('reuses an existing Competition without replacing its immutable snapshot', async () => {
const existingId = new Types.ObjectId('64b000000000000000000099');
const existing = {
_id: existingId,
matchId: MATCH_ID,
teams: [{ name: 'Original immutable team snapshot' }],
revision: 4,
};
const harness = createHarness({ existingCompetition: existing });
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
const result = await service.bootstrap(
matchSnapshot({ gameMode: 'pair', teamCount: 2 }),
);
expect(result).toBe(existing);
expect(harness.competitionModel.findOneAndUpdate.mock.calls[0][1]).toEqual({
$setOnInsert: harness.insertedPayloads[0],
});
expect(harness.matchModel.updateOne.mock.calls[0][1]).toEqual({
$set: { competitionId: existingId },
});
});
it('retries a duplicate-key bootstrap race and safely converges on the winner', async () => {
const duplicateKey = Object.assign(new Error('duplicate key'), {
code: 11000,
});
const winner = {
_id: new Types.ObjectId('64b000000000000000000098'),
matchId: MATCH_ID,
revision: 0,
};
const harness = createHarness({
competitionResults: [duplicateKey, winner],
sessionCount: 2,
});
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
const result = await service.bootstrap(
matchSnapshot({ gameMode: 'pair', teamCount: 2 }),
);
expect(result).toBe(winner);
expect(harness.connectionService.createSession).toHaveBeenCalledTimes(2);
expect(harness.sessions[0].abortTransaction).toHaveBeenCalledTimes(1);
expect(harness.sessions[0].commitTransaction).not.toHaveBeenCalled();
expect(harness.sessions[0].endSession).toHaveBeenCalledTimes(1);
expect(harness.sessions[1].commitTransaction).toHaveBeenCalledTimes(1);
expect(harness.matchModel.updateOne).toHaveBeenCalledTimes(1);
});
it('aborts when the Match is already linked to a different Competition', async () => {
const harness = createHarness({ matchUpdateResult: { matchedCount: 0 } });
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
await expect(
service.bootstrap(matchSnapshot({ gameMode: 'pair', teamCount: 2 })),
).rejects.toMatchObject({
code: 'MATCH_COMPETITION_LINK_CONFLICT',
httpStatus: 409,
});
expect(harness.sessions[0].abortTransaction).toHaveBeenCalledTimes(1);
expect(harness.sessions[0].commitTransaction).not.toHaveBeenCalled();
});
});
const MATCH_ID = new Types.ObjectId('64b000000000000000000001');
const COMMUNITY_ID = new Types.ObjectId('64b000000000000000000002');
const USER_IDS = Array.from(
{ length: 8 },
(_, index) =>
new Types.ObjectId(
`64b0000000000000000001${String(index + 1).padStart(2, '0')}`,
),
);
function matchSnapshot(params: {
gameMode: CompetitionBootstrapMatch['gameMode'];
teamCount: number;
gameCount?: number;
roundRobinMaxRounds?: number;
}): CompetitionBootstrapMatch {
const participants = USER_IDS.slice(0, params.teamCount).map(
(userId, index) => ({
userId,
gameName: `Player ${index + 1}`,
tagLine: 'KR1',
profileIconId: 101 + index,
preferredPositions: [],
joinedAt: new Date('2026-07-12T00:00:00.000Z'),
}),
);
return {
_id: MATCH_ID,
communityId: COMMUNITY_ID,
status: 'team-built',
teamBuiltAt: new Date('2026-07-12T00:05:00.000Z'),
gameCount: params.gameCount ?? 3,
gameMode: params.gameMode,
...(params.roundRobinMaxRounds === undefined
? {}
: { roundRobinMaxRounds: params.roundRobinMaxRounds }),
participants,
teams: participants.map((participant, index) => ({
teamIndex: index + 1,
name: `Team ${index + 1}`,
captainUserId: participant.userId,
members: [
{
userId: participant.userId,
assignedPosition: 'TOP',
cost: 10 + index,
},
],
})),
};
}
interface InsertPayload {
_id: Types.ObjectId;
teams: Array<{
teamId: Types.ObjectId;
legacyTeamIndex: number;
seedNumber: number;
}>;
seriesGraph: Array<{ code?: string; rule: unknown }>;
[key: string]: any;
}
function createHarness(
options: {
existingCompetition?: Record<string, unknown>;
competitionResults?: Array<Record<string, unknown> | Error>;
matchUpdateResult?: { matchedCount: number };
sessionCount?: number;
} = {},
) {
const sessions = Array.from(
{ length: options.sessionCount ?? 1 },
createSession,
);
const insertedPayloads: InsertPayload[] = [];
let competitionCall = 0;
const competitionModel = {
findOneAndUpdate: jest.fn(
(
_filter: unknown,
update: { $setOnInsert: InsertPayload },
_queryOptions: unknown,
) => {
insertedPayloads.push(update.$setOnInsert);
const selected = options.competitionResults?.[competitionCall++];
if (selected instanceof Error) return rejectedQuery(selected);
return queryResult(
selected ?? options.existingCompetition ?? update.$setOnInsert,
);
},
),
};
const matchModel = {
updateOne: jest
.fn()
.mockResolvedValue(options.matchUpdateResult ?? { matchedCount: 1 }),
};
const models: Record<string, unknown> = {
competition: competitionModel,
match: matchModel,
};
let sessionIndex = 0;
const connectionService = {
createSession: jest.fn(() => Promise.resolve(sessions[sessionIndex++])),
getModel: jest.fn((name: string) => Promise.resolve(models[name])),
};
return {
sessions,
insertedPayloads,
competitionModel,
matchModel,
connectionService,
};
}
function createSession() {
return {
startTransaction: jest.fn(),
commitTransaction: jest.fn().mockResolvedValue(undefined),
abortTransaction: jest.fn().mockResolvedValue(undefined),
endSession: jest.fn().mockResolvedValue(undefined),
};
}
function queryResult<T>(value: T) {
return { exec: jest.fn().mockResolvedValue(value) };
}
function rejectedQuery(error: Error) {
return { exec: jest.fn().mockRejectedValue(error) };
}
@@ -0,0 +1,639 @@
import { createHash } from 'node:crypto';
import { Injectable } from '@nestjs/common';
import mongoose, { Types } from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type {
MatchGameMode,
MatchParticipant,
MatchStatus,
MatchTeam,
} from '../global/database/schema';
import type {
CompetitionDocument,
CompetitionTeamSnapshot,
} from './competition.schema';
import {
generateSeriesGraph,
type CompetitionGraphFormat,
type CompetitionGraphTeam,
type SeriesDefinition,
} from './domain/series-graph';
import {
projectCompetition,
type CompetitionProjection,
} from './domain/competition-projector';
const COMPETITION_SCHEMA_VERSION = 1;
const COMPETITION_PROJECTOR_VERSION = 1;
const BOOTSTRAP_TRANSACTION_ATTEMPTS = 3;
export interface CompetitionBootstrapMatch {
_id: Types.ObjectId;
communityId: Types.ObjectId;
competitionId?: Types.ObjectId;
status: MatchStatus;
teamBuiltAt: Date;
gameCount: number;
gameMode: MatchGameMode;
roundRobinMaxRounds?: number;
participants: MatchParticipant[];
teams: MatchTeam[];
doubleElimination?: {
teamCount: 4 | 8;
resetFinalEnabled: boolean;
seeds: Array<{ seedNumber: number; teamIndex: number }>;
};
}
export interface CompetitionBootstrapOptions {
/** `bracket` is accepted only by the explicit legacy migration path. */
source?: 'live' | 'legacy-migration';
}
export type CompetitionBootstrapErrorCode =
| 'INVALID_MATCH_TEAM_SNAPSHOT'
| 'INVALID_MATCH_FORMAT'
| 'UNSUPPORTED_LIVE_MATCH_MODE'
| 'COMPETITION_TRANSACTION_UNAVAILABLE'
| 'COMPETITION_BOOTSTRAP_FAILED'
| 'COMPETITION_BOOTSTRAP_RACE'
| 'MATCH_COMPETITION_LINK_CONFLICT';
export class CompetitionBootstrapError extends Error {
constructor(
public readonly code: CompetitionBootstrapErrorCode,
message: string,
public readonly httpStatus: 409 | 422 | 500,
public readonly details?: Readonly<Record<string, unknown>>,
) {
super(message);
this.name = 'CompetitionBootstrapError';
}
}
interface CompetitionInsertPayload {
_id: Types.ObjectId;
matchId: Types.ObjectId;
communityId: Types.ObjectId;
schemaVersion: number;
projectorVersion: number;
revision: number;
phase: CompetitionProjection['phase'];
teams: CompetitionTeamSnapshot[];
format: CompetitionGraphFormat;
seriesGraph: SeriesDefinition[];
projection: CompetitionProjection;
}
/**
* Freezes the recruiting Match into the one-to-one Competition aggregate.
* Retries only repeat deterministic upserts, so duplicate creators and unknown
* commit outcomes converge without replacing an existing immutable snapshot.
*/
@Injectable()
export class CompetitionBootstrapService {
constructor(private readonly connectionService: ConnectionService) {}
public async bootstrap(
match: CompetitionBootstrapMatch,
options: CompetitionBootstrapOptions = {},
): Promise<CompetitionDocument> {
const payload = buildCompetitionInsertPayload(
match,
options.source ?? 'live',
);
const [CompetitionModel, MatchModel] = await Promise.all([
this.connectionService.getModel('competition'),
this.connectionService.getModel('match'),
]);
let lastRetryableError: unknown;
for (
let attempt = 1;
attempt <= BOOTSTRAP_TRANSACTION_ATTEMPTS;
attempt += 1
) {
const session = await this.connectionService.createSession();
if (!session) {
throw new CompetitionBootstrapError(
'COMPETITION_TRANSACTION_UNAVAILABLE',
'A MongoDB transaction is required to bootstrap a Competition.',
500,
);
}
try {
session.startTransaction();
const competition = await CompetitionModel.findOneAndUpdate(
{ matchId: match._id },
{ $setOnInsert: payload },
{
upsert: true,
returnDocument: 'after',
setDefaultsOnInsert: true,
session,
},
).exec();
if (!competition) {
throw new CompetitionBootstrapError(
'COMPETITION_BOOTSTRAP_FAILED',
'Competition upsert returned no document.',
500,
);
}
const linkResult = await MatchModel.updateOne(
{
_id: match._id,
status: match.status,
teamBuiltAt: match.teamBuiltAt,
$or: [
{ competitionId: { $exists: false } },
{ competitionId: null },
{ competitionId: competition._id },
],
},
{ $set: { competitionId: competition._id } },
{ session },
);
if (linkResult.matchedCount !== 1) {
throw new CompetitionBootstrapError(
'MATCH_COMPETITION_LINK_CONFLICT',
'Match is missing or linked to a different Competition.',
409,
{ matchId: match._id.toString() },
);
}
await session.commitTransaction();
return competition;
} catch (error) {
await session.abortTransaction().catch(() => undefined);
if (
attempt < BOOTSTRAP_TRANSACTION_ATTEMPTS &&
isRetryableBootstrapError(error)
) {
lastRetryableError = error;
continue;
}
if (isRetryableBootstrapError(error)) {
throw new CompetitionBootstrapError(
'COMPETITION_BOOTSTRAP_RACE',
'Competition bootstrap did not converge after concurrent writes.',
409,
{ matchId: match._id.toString() },
);
}
throw error;
} finally {
await session.endSession().catch(() => undefined);
}
}
throw new CompetitionBootstrapError(
'COMPETITION_BOOTSTRAP_RACE',
'Competition bootstrap retry budget was exhausted.',
409,
{
matchId: match._id.toString(),
cause:
lastRetryableError instanceof Error
? lastRetryableError.message
: String(lastRetryableError),
},
);
}
}
function buildCompetitionInsertPayload(
match: CompetitionBootstrapMatch,
source: NonNullable<CompetitionBootstrapOptions['source']>,
): CompetitionInsertPayload {
assertObjectId(match._id, 'Match ID');
assertObjectId(match.communityId, 'Community ID');
if (match.status === 'recruiting' || !(match.teamBuiltAt instanceof Date)) {
throw new CompetitionBootstrapError(
'INVALID_MATCH_TEAM_SNAPSHOT',
'Competition bootstrap requires a finalized team-built Match lifecycle.',
422,
);
}
assertPositiveInteger(match.gameCount, 'Match game count');
const competitionId = stableObjectId(match._id, 'competition');
const teams = snapshotTeams(match, competitionId);
const graphTeams = teams.map(
({ teamId, displayOrder, seedNumber }): CompetitionGraphTeam => ({
teamId: teamId.toString(),
displayOrder,
seedNumber,
}),
);
const format = mapMatchFormat(match, teams, source);
let seriesGraph: SeriesDefinition[];
let projection: CompetitionProjection;
try {
seriesGraph = generateSeriesGraph({
competitionId: competitionId.toString(),
teams: graphTeams,
format,
});
projection = projectCompetition({
competitionId: competitionId.toString(),
revision: 0,
projectorVersion: COMPETITION_PROJECTOR_VERSION,
teams: graphTeams,
format,
seriesGraph,
facts: [],
});
} catch (error) {
throw new CompetitionBootstrapError(
'INVALID_MATCH_FORMAT',
error instanceof Error
? error.message
: 'The Match cannot produce a valid Competition graph.',
422,
{
matchId: match._id.toString(),
domainCode: readErrorCode(error),
},
);
}
return {
_id: competitionId,
matchId: match._id,
communityId: match.communityId,
schemaVersion: COMPETITION_SCHEMA_VERSION,
projectorVersion: COMPETITION_PROJECTOR_VERSION,
revision: 0,
phase: projection.phase,
teams,
format,
seriesGraph,
projection,
};
}
function snapshotTeams(
match: CompetitionBootstrapMatch,
competitionId: Types.ObjectId,
): CompetitionTeamSnapshot[] {
if (!Array.isArray(match.teams) || match.teams.length < 2) {
throw invalidTeamSnapshot(
'A Competition requires at least two built teams.',
);
}
if (!Array.isArray(match.participants)) {
throw invalidTeamSnapshot('Match participants are missing.');
}
const participantById = new Map<string, MatchParticipant>();
for (const participant of match.participants) {
const userId = objectIdString(participant?.userId);
if (!userId || participantById.has(userId)) {
throw invalidTeamSnapshot(
'Match participants must have unique ObjectId user identities.',
);
}
participantById.set(userId, participant);
}
const orderedTeams = [...match.teams].sort(
(left, right) => left.teamIndex - right.teamIndex,
);
const teamIndexes = new Set<number>();
const assignedUserIds = new Set<string>();
const memberCounts = new Set<number>();
const snapshots: CompetitionTeamSnapshot[] = [];
for (const [displayIndex, team] of orderedTeams.entries()) {
if (
!Number.isInteger(team.teamIndex) ||
team.teamIndex < 1 ||
teamIndexes.has(team.teamIndex)
) {
throw invalidTeamSnapshot(
'Built teams must have unique positive integer team indexes.',
);
}
teamIndexes.add(team.teamIndex);
if (typeof team.name !== 'string' || team.name.trim().length === 0) {
throw invalidTeamSnapshot('Every built team needs a non-empty name.');
}
if (!Array.isArray(team.members) || team.members.length === 0) {
throw invalidTeamSnapshot('Every built team needs at least one member.');
}
memberCounts.add(team.members.length);
const memberSnapshots = [...team.members]
.sort(compareTeamMembers)
.map((member) => {
const userId = objectIdString(member.userId);
const participant = userId ? participantById.get(userId) : undefined;
if (
!userId ||
!participant ||
participant.excluded === true ||
assignedUserIds.has(userId)
) {
throw invalidTeamSnapshot(
'Every non-excluded participant must be assigned to exactly one team.',
);
}
assignedUserIds.add(userId);
const gameName = nonEmptyString(participant.gameName);
const tagLine = nonEmptyString(participant.tagLine);
return {
userId: member.userId,
displayName: gameName
? tagLine
? `${gameName}#${tagLine}`
: gameName
: userId,
...(gameName ? { gameName } : {}),
...(tagLine ? { tagLine } : {}),
...(participant.profileIconId === undefined
? {}
: { profileIconId: participant.profileIconId }),
assignedPosition: member.assignedPosition,
...(member.cost === undefined ? {} : { cost: member.cost }),
};
});
if (team.captainUserId) {
const captainUserId = team.captainUserId.toString();
if (
!memberSnapshots.some(
({ userId }) => userId.toString() === captainUserId,
)
) {
throw invalidTeamSnapshot('A team captain must belong to that team.');
}
}
snapshots.push({
teamId: stableObjectId(
competitionId,
'team',
`legacy-team-index:${team.teamIndex}`,
),
legacyTeamIndex: team.teamIndex,
displayOrder: displayIndex + 1,
seedNumber: displayIndex + 1,
name: team.name.trim(),
...(team.captainUserId ? { captainUserId: team.captainUserId } : {}),
members: memberSnapshots,
});
}
if (memberCounts.size !== 1) {
throw invalidTeamSnapshot(
'All built teams must have the same member count.',
);
}
const activeParticipantIds = [...participantById]
.filter(([, participant]) => participant.excluded !== true)
.map(([userId]) => userId);
if (
activeParticipantIds.length !== assignedUserIds.size ||
activeParticipantIds.some((userId) => !assignedUserIds.has(userId))
) {
throw invalidTeamSnapshot(
'Every non-excluded participant must be assigned to exactly one team.',
);
}
applySeeds(match, snapshots);
return snapshots;
}
function applySeeds(
match: CompetitionBootstrapMatch,
teams: CompetitionTeamSnapshot[],
): void {
if (match.gameMode !== 'double-elimination') return;
const configuredSeeds = match.doubleElimination?.seeds ?? [];
if (configuredSeeds.length === 0) {
throw invalidTeamSnapshot(
'Double-elimination seeds must be finalized before Competition bootstrap.',
);
}
if (configuredSeeds.length !== teams.length) {
throw invalidTeamSnapshot(
'Double-elimination seeds must include every built team exactly once.',
);
}
const validTeamIndexes = new Set(
teams.map(({ legacyTeamIndex }) => legacyTeamIndex as number),
);
const seedByTeamIndex = new Map<number, number>();
const seedNumbers = new Set<number>();
for (const seed of configuredSeeds) {
if (
!Number.isInteger(seed.seedNumber) ||
seed.seedNumber < 1 ||
seed.seedNumber > teams.length ||
seedNumbers.has(seed.seedNumber) ||
!validTeamIndexes.has(seed.teamIndex) ||
seedByTeamIndex.has(seed.teamIndex)
) {
throw invalidTeamSnapshot(
'Double-elimination seeds must be unique and contiguous.',
);
}
seedNumbers.add(seed.seedNumber);
seedByTeamIndex.set(seed.teamIndex, seed.seedNumber);
}
for (const team of teams) {
team.seedNumber = seedByTeamIndex.get(team.legacyTeamIndex as number)!;
}
}
function mapMatchFormat(
match: CompetitionBootstrapMatch,
teams: CompetitionTeamSnapshot[],
source: NonNullable<CompetitionBootstrapOptions['source']>,
): CompetitionGraphFormat {
switch (match.gameMode) {
case 'pair':
return fixedGameFormat('paired-series', match.gameCount);
case 'bracket':
if (source !== 'legacy-migration') {
throw new CompetitionBootstrapError(
'UNSUPPORTED_LIVE_MATCH_MODE',
'Legacy bracket mode can only be bootstrapped by migration.',
422,
);
}
return fixedGameFormat('paired-series', match.gameCount);
case 'round-robin':
if (
match.roundRobinMaxRounds !== undefined &&
(!Number.isInteger(match.roundRobinMaxRounds) ||
match.roundRobinMaxRounds < 1)
) {
throw new CompetitionBootstrapError(
'INVALID_MATCH_FORMAT',
'Round-robin max rounds must be a positive integer.',
422,
);
}
return {
type: 'round-robin',
rule: fixedGamesRule(match.gameCount),
...(match.roundRobinMaxRounds === undefined
? {}
: { maxRounds: match.roundRobinMaxRounds }),
tieBreakers: ['series-wins', 'game-diff', 'head-to-head'],
};
case 'double-elimination': {
if (teams.length !== 4 && teams.length !== 8) {
throw new CompetitionBootstrapError(
'INVALID_MATCH_FORMAT',
'Double elimination supports only four or eight teams.',
422,
);
}
if (
match.doubleElimination?.teamCount !== undefined &&
match.doubleElimination.teamCount !== teams.length
) {
throw new CompetitionBootstrapError(
'INVALID_MATCH_FORMAT',
'Double-elimination team count does not match the built teams.',
422,
);
}
const bestOfOne = {
type: 'first-to' as const,
winsRequired: 1,
maxGames: 1,
};
return {
type: 'double-elimination',
teamCount: teams.length,
resetFinalEnabled: match.doubleElimination?.resetFinalEnabled ?? false,
rules: {
upper: {
type: 'first-to',
winsRequired: Math.floor(match.gameCount / 2) + 1,
maxGames: match.gameCount,
},
lower: { ...bestOfOne },
grandFinal: { ...bestOfOne },
resetFinal: { ...bestOfOne },
},
};
}
}
}
function fixedGameFormat(
type: 'paired-series',
gameCount: number,
): Extract<CompetitionGraphFormat, { type: 'paired-series' }> {
return { type, rule: fixedGamesRule(gameCount) };
}
function fixedGamesRule(gameCount: number) {
return {
type: 'fixed-games' as const,
gameCount,
drawPolicy: 'allow' as const,
};
}
function stableObjectId(
namespaceId: Types.ObjectId,
entityKind: string,
...logicalKey: string[]
): Types.ObjectId {
const hex = createHash('sha256')
.update(JSON.stringify([namespaceId.toString(), entityKind, ...logicalKey]))
.digest('hex')
.slice(0, 24);
return new Types.ObjectId(hex);
}
function compareTeamMembers(
left: MatchTeam['members'][number],
right: MatchTeam['members'][number],
): number {
const positionOrder = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
return (
positionOrder.indexOf(left.assignedPosition) -
positionOrder.indexOf(right.assignedPosition) ||
left.userId.toString().localeCompare(right.userId.toString())
);
}
function invalidTeamSnapshot(message: string): CompetitionBootstrapError {
return new CompetitionBootstrapError(
'INVALID_MATCH_TEAM_SNAPSHOT',
message,
422,
);
}
function assertPositiveInteger(value: number, label: string): void {
if (!Number.isInteger(value) || value < 1) {
throw new CompetitionBootstrapError(
'INVALID_MATCH_FORMAT',
`${label} must be a positive integer.`,
422,
);
}
}
function assertObjectId(
value: unknown,
label: string,
): asserts value is Types.ObjectId {
if (!(value instanceof mongoose.Types.ObjectId)) {
throw invalidTeamSnapshot(`${label} must be a MongoDB ObjectId.`);
}
}
function objectIdString(value: unknown): string | undefined {
return value instanceof mongoose.Types.ObjectId
? value.toString()
: undefined;
}
function nonEmptyString(value: unknown): string | undefined {
if (typeof value !== 'string') return undefined;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
function readErrorCode(error: unknown): string | undefined {
if (
typeof error === 'object' &&
error !== null &&
'code' in error &&
typeof error.code === 'string'
) {
return error.code;
}
return undefined;
}
function isRetryableBootstrapError(error: unknown): boolean {
const candidate = error as {
code?: number;
codeName?: string;
hasErrorLabel?: (label: string) => boolean;
};
return Boolean(
candidate?.code === 11000 ||
candidate?.code === 112 ||
candidate?.codeName === 'WriteConflict' ||
candidate?.hasErrorLabel?.('TransientTransactionError') ||
candidate?.hasErrorLabel?.('UnknownTransactionCommitResult'),
);
}
@@ -0,0 +1,784 @@
import { Types } from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { CompetitionCommandService } from './competition-command.service';
import { projectCompetition } from './domain/competition-projector';
jest.mock('./domain/competition-projector', () => ({
projectCompetition: jest.fn(),
}));
const mockedProjectCompetition = jest.mocked(projectCompetition);
describe('CompetitionCommandService', () => {
beforeEach(() => {
jest.useFakeTimers().setSystemTime(new Date('2026-07-12T10:00:00.000Z'));
mockedProjectCompetition.mockReset();
mockedProjectCompetition.mockReturnValue(PROJECTION as never);
});
afterEach(() => {
jest.useRealTimers();
});
it('rejects a stale expected revision and aborts without writing', async () => {
const harness = createHarness({ competitionRevision: 8 });
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
await expect(service.acceptGame(acceptGameCommand())).rejects.toMatchObject(
{
code: 'STALE_COMPETITION_REVISION',
httpStatus: 412,
details: { expectedRevision: 7, actualRevision: 8 },
},
);
expect(harness.factModel.insertMany).not.toHaveBeenCalled();
expect(harness.competitionModel.findOneAndUpdate).not.toHaveBeenCalled();
expect(harness.outboxModel.insertMany).not.toHaveBeenCalled();
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).not.toHaveBeenCalled();
expect(harness.session.endSession).toHaveBeenCalledTimes(1);
});
it('uses the expected revision in the persistence CAS and aborts a lost race', async () => {
const harness = createHarness({ casResult: null });
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
await expect(service.acceptGame(acceptGameCommand())).rejects.toMatchObject(
{
code: 'STALE_COMPETITION_REVISION',
httpStatus: 412,
},
);
const [casFilter, casUpdate, casOptions] = harness.competitionModel
.findOneAndUpdate.mock.calls[0] as unknown as [
Record<string, unknown>,
{ $inc: Record<string, unknown>; $set: Record<string, unknown> },
Record<string, unknown>,
];
expect(casFilter).toEqual({ _id: COMPETITION_ID, revision: 7 });
expect(casUpdate).toMatchObject({
$inc: { revision: 1 },
$set: { projection: PROJECTION },
});
expect(casOptions).toMatchObject({ new: true, session: harness.session });
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).not.toHaveBeenCalled();
});
it('replays an exact Idempotency-Key request without appending a second fact', async () => {
const harness = createHarness();
let storedReceipt: Record<string, unknown> | null = null;
harness.outboxModel.findOne.mockImplementation(() =>
queryResult(storedReceipt),
);
harness.outboxModel.insertMany.mockImplementation(
([receipt]: Array<Record<string, unknown>>) => {
storedReceipt = receipt;
return Promise.resolve([receipt]);
},
);
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const command = acceptGameCommand();
const first = await service.acceptGame(command);
const replay = await service.acceptGame(command);
expect(first).toMatchObject({ revision: 8, replayed: false });
expect(replay).toMatchObject({
commandId: first.commandId,
revision: 8,
replayed: true,
});
expect(replay.competition).toEqual(first.competition);
expect(harness.factModel.insertMany).toHaveBeenCalledTimes(1);
expect(harness.competitionModel.findOneAndUpdate).toHaveBeenCalledTimes(1);
expect(harness.outboxModel.insertMany).toHaveBeenCalledTimes(1);
expect(mockedProjectCompetition).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(2);
expect(harness.session.abortTransaction).not.toHaveBeenCalled();
});
it('replays a concurrently committed identical command after a duplicate-key race', async () => {
const harness = createHarness();
let committedReceipt: Record<string, unknown> | null = null;
harness.outboxModel.findOne.mockImplementation(() =>
queryResult(committedReceipt),
);
harness.factModel.insertMany.mockImplementationOnce(
async ([fact]: Array<Record<string, unknown>>) => {
committedReceipt = {
competitionId: COMPETITION_ID,
idempotencyKey: fact.idempotencyKey,
requestHash: fact.requestHash,
commandId: fact.commandId,
revision: fact.revision,
payload: {
projection: PROJECTION,
phase: PROJECTION.phase,
},
};
throw Object.assign(new Error('duplicate command fact'), {
code: 11_000,
});
},
);
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
await expect(
service.acceptGame(acceptGameCommand()),
).resolves.toMatchObject({
revision: 8,
replayed: true,
});
expect(harness.connectionService.createSession).toHaveBeenCalledTimes(2);
expect(harness.factModel.insertMany).toHaveBeenCalledTimes(1);
expect(harness.competitionModel.findOneAndUpdate).not.toHaveBeenCalled();
expect(harness.outboxModel.insertMany).not.toHaveBeenCalled();
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(1);
});
it('rejects the same Idempotency-Key when its payload hash differs', async () => {
const harness = createHarness();
harness.outboxModel.findOne.mockReturnValue(
queryResult({
idempotencyKey: 'riot:KR_7000000001',
requestHash: 'a-different-payload-hash',
commandId: 'cmpcmd_original',
revision: 8,
}),
);
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
await expect(service.acceptGame(acceptGameCommand())).rejects.toMatchObject(
{
code: 'IDEMPOTENCY_KEY_CONFLICT',
httpStatus: 409,
},
);
expect(harness.competitionModel.findById).not.toHaveBeenCalled();
expect(harness.factModel.insertMany).not.toHaveBeenCalled();
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
});
it('atomically accepts a code-backed game, projects it, and enqueues an event', async () => {
const harness = createHarness();
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const command = {
...acceptGameCommand(),
tournamentCode: {
tournamentCodeId: TOURNAMENT_CODE_ID,
riotMatchId: 'KR_7000000001',
},
};
const result = await service.acceptGame(command);
expect(result).toMatchObject({ revision: 8, replayed: false });
expect(harness.session.startTransaction).toHaveBeenCalledTimes(1);
const [insertedFacts, factOptions] = harness.factModel.insertMany.mock
.calls[0] as unknown as [
Array<Record<string, unknown>>,
Record<string, unknown>,
];
expect(insertedFacts).toHaveLength(1);
expect(insertedFacts[0]).toMatchObject({
type: 'game-accepted',
revision: 8,
ordinalWithinRevision: 1,
gameId: GAME_ID,
seriesId: SERIES_ID,
gameSlotId: GAME_SLOT_ID,
startedAt: new Date('2026-07-12T09:30:00.000Z'),
durationSeconds: 1_800,
participants: [
{
userId: USER_ID.toHexString(),
teamId: TEAM_A_ID.toHexString(),
side: 'blue',
},
],
});
expect(factOptions).toEqual({ session: harness.session });
const projectionInput = mockedProjectCompetition.mock.calls[0][0];
const projectedFact = projectionInput.facts[0] as Record<string, unknown>;
const projectedMapping = projectedFact.mapping as Record<string, unknown>;
expect(projectionInput.competitionId).toBe(COMPETITION_ID.toHexString());
expect(projectionInput.revision).toBe(8);
expect(typeof projectedFact.id).toBe('string');
expect(projectedFact).toMatchObject({
type: 'game-accepted',
seriesId: SERIES_ID.toHexString(),
});
expect(projectedMapping.winnerTeamId).toBe(TEAM_A_ID.toHexString());
const [assignmentFilter, assignmentUpdate, assignmentOptions] = harness
.assignmentModel.updateOne.mock.calls[0] as unknown as [
Record<string, unknown>,
{ $set: Record<string, unknown> },
Record<string, unknown>,
];
expect(assignmentFilter).toMatchObject({
competitionId: COMPETITION_ID,
gameSlotId: GAME_SLOT_ID,
tournamentCodeId: TOURNAMENT_CODE_ID,
state: 'reserved',
});
expect(assignmentUpdate.$set.state).toBe('used');
expect(assignmentOptions).toEqual({ session: harness.session });
const [codeFilter, codeUpdate, codeOptions] = harness.tournamentCodeModel
.updateOne.mock.calls[0] as unknown as [
Record<string, unknown>,
{ $set: Record<string, unknown> },
Record<string, unknown>,
];
expect(codeFilter).toEqual({
_id: TOURNAMENT_CODE_ID,
state: 'reserved',
});
expect(codeUpdate.$set.state).toBe('used');
expect(codeOptions).toEqual({ session: harness.session });
const [outboxRecords, outboxOptions] = harness.outboxModel.insertMany.mock
.calls[0] as unknown as [
Array<Record<string, unknown>>,
Record<string, unknown>,
];
expect(outboxRecords).toHaveLength(1);
expect(outboxRecords[0]).toMatchObject({
revision: 8,
type: 'competition.projection-updated',
state: 'pending',
payload: { projection: PROJECTION },
});
expect(outboxOptions).toEqual({ session: harness.session });
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(1);
expect(harness.session.abortTransaction).not.toHaveBeenCalled();
});
it('appends an administrative adjudication through the same command runner', async () => {
const harness = createHarness();
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const result = await service.adjudicateSeries({
competitionId: COMPETITION_ID,
expectedRevision: 7,
idempotencyKey: 'admin:series:walkover:1',
actor: { type: 'user', userId: USER_ID },
seriesId: SERIES_ID,
decision: { type: 'walkover', winnerTeamId: TEAM_B_ID },
reason: 'Opponent did not appear before the deadline.',
});
expect(result).toMatchObject({ revision: 8, replayed: false });
expect(harness.factModel.insertMany).toHaveBeenCalledWith(
[
expect.objectContaining({
type: 'series-adjudicated',
seriesId: SERIES_ID,
decision: { type: 'walkover', winnerTeamId: TEAM_B_ID },
reason: 'Opponent did not appear before the deadline.',
}),
],
{ session: harness.session },
);
expect(harness.assignmentModel.updateOne).not.toHaveBeenCalled();
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(1);
});
it('previews a strict or cascade reversal against the requested revision', async () => {
const reversal = reversalFixture();
const harness = createHarness({
competition: reversal.competition,
facts: reversal.facts,
assignments: reversal.assignments,
});
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const preview = await service.previewSeriesReversal({
competitionId: COMPETITION_ID,
expectedRevision: 7,
seriesId: reversal.parentSeriesId,
mode: 'cascade',
});
expect(preview).toMatchObject({
sourceRevision: 7,
impactHash: expect.stringMatching(/^[a-f0-9]{64}$/),
impact: {
seriesIds: [
reversal.parentSeriesId.toHexString(),
reversal.childSeriesId.toHexString(),
],
factIds: [
reversal.parentFactId.toHexString(),
reversal.childFactId.toHexString(),
],
releasesReservedCodes: 1,
voidsUsedCodes: 1,
},
});
});
it('rejects a reversal preview at a stale revision', async () => {
const reversal = reversalFixture();
const harness = createHarness({ competition: reversal.competition });
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
await expect(
service.previewSeriesReversal({
competitionId: COMPETITION_ID,
expectedRevision: 6,
seriesId: reversal.parentSeriesId,
mode: 'strict',
}),
).rejects.toMatchObject({
code: 'STALE_COMPETITION_REVISION',
httpStatus: 412,
});
});
it('hash-confirms and atomically appends cascade reversal facts', async () => {
const reversal = reversalFixture();
const harness = createHarness({
competition: reversal.competition,
facts: reversal.facts,
assignments: reversal.assignments,
});
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const preview = await service.previewSeriesReversal({
competitionId: COMPETITION_ID,
expectedRevision: 7,
seriesId: reversal.parentSeriesId,
mode: 'cascade',
});
const result = await service.reverseSeries({
competitionId: COMPETITION_ID,
expectedRevision: 7,
idempotencyKey: 'admin:reverse:1',
actor: { type: 'user', userId: USER_ID },
seriesId: reversal.parentSeriesId,
mode: 'cascade',
reason: 'Wrong result ingestion',
impactHash: preview.impactHash,
});
expect(result).toMatchObject({ revision: 8, replayed: false });
expect(harness.factModel.insertMany).toHaveBeenCalledWith(
[
expect.objectContaining({
_id: expect.any(Types.ObjectId),
type: 'game-voided',
gameAcceptedFactId: reversal.parentFactId,
revision: 8,
ordinalWithinRevision: 1,
reason: 'Wrong result ingestion',
}),
expect.objectContaining({
_id: expect.any(Types.ObjectId),
type: 'game-voided',
gameAcceptedFactId: reversal.childFactId,
revision: 8,
ordinalWithinRevision: 2,
}),
],
{ session: harness.session },
);
expect(harness.assignmentModel.updateMany).toHaveBeenCalledWith(
expect.objectContaining({
competitionId: COMPETITION_ID,
gameSlotId: {
$in: expect.arrayContaining([
reversal.parentGameSlotId,
reversal.childGameSlotId,
]),
},
}),
expect.any(Array),
{ session: harness.session },
);
expect(harness.tournamentCodeModel.updateMany).toHaveBeenCalled();
expect(harness.matchModel.updateOne).toHaveBeenCalledWith(
{ _id: reversal.competition.matchId },
{
$pull: {
tournamentCodeIds: {
$in: [reversal.parentCodeId, reversal.childCodeId],
},
},
},
{ session: harness.session },
);
const [, codeReversalPipeline] = harness.tournamentCodeModel.updateMany.mock
.calls[0] as unknown as [
Record<string, unknown>,
Array<Record<string, any>>,
];
expect(codeReversalPipeline[0].$set).toMatchObject({
state: {
$cond: [{ $eq: ['$state', 'reserved'] }, 'released', 'voided'],
},
matchId: {
$cond: [{ $eq: ['$state', 'reserved'] }, '$$REMOVE', '$matchId'],
},
gameNumber: {
$cond: [{ $eq: ['$state', 'reserved'] }, '$$REMOVE', '$gameNumber'],
},
bracketMatchId: {
$cond: [{ $eq: ['$state', 'reserved'] }, '$$REMOVE', '$bracketMatchId'],
},
reservedAt: {
$cond: [{ $eq: ['$state', 'reserved'] }, '$$REMOVE', '$reservedAt'],
},
});
expect(harness.competitionModel.findOneAndUpdate).toHaveBeenCalledWith(
{ _id: COMPETITION_ID, revision: 7 },
expect.objectContaining({ $inc: { revision: 1 } }),
expect.objectContaining({ session: harness.session }),
);
expect(harness.outboxModel.insertMany).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(1);
});
it('retries a cascade reversal after a transient transaction conflict', async () => {
const reversal = reversalFixture();
const harness = createHarness({
competition: reversal.competition,
facts: reversal.facts,
assignments: reversal.assignments,
});
harness.factModel.insertMany
.mockRejectedValueOnce(
Object.assign(new Error('write conflict'), {
code: 112,
codeName: 'WriteConflict',
}),
)
.mockResolvedValueOnce([]);
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const preview = await service.previewSeriesReversal({
competitionId: COMPETITION_ID,
expectedRevision: 7,
seriesId: reversal.parentSeriesId,
mode: 'cascade',
});
await expect(
service.reverseSeries({
competitionId: COMPETITION_ID,
expectedRevision: 7,
idempotencyKey: 'admin:reverse:transient-retry',
actor: { type: 'user', userId: USER_ID },
seriesId: reversal.parentSeriesId,
mode: 'cascade',
reason: 'Wrong result ingestion',
impactHash: preview.impactHash,
}),
).resolves.toMatchObject({ revision: 8, replayed: false });
expect(harness.connectionService.createSession).toHaveBeenCalledTimes(2);
expect(harness.factModel.insertMany).toHaveBeenCalledTimes(2);
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(1);
});
});
const COMPETITION_ID = new Types.ObjectId('64b000000000000000000001');
const SERIES_ID = new Types.ObjectId('64b000000000000000000002');
const GAME_SLOT_ID = new Types.ObjectId('64b000000000000000000003');
const GAME_ID = new Types.ObjectId('64b000000000000000000004');
const TEAM_A_ID = new Types.ObjectId('64b000000000000000000005');
const TEAM_B_ID = new Types.ObjectId('64b000000000000000000006');
const USER_ID = new Types.ObjectId('64b000000000000000000007');
const TOURNAMENT_CODE_ID = new Types.ObjectId('64b000000000000000000008');
const PROJECTION = {
sourceRevision: 8,
projectorVersion: 1,
phase: 'running',
formatType: 'paired-series',
series: [],
games: [],
gameSlots: [],
rounds: [],
connectors: [],
};
function acceptGameCommand() {
return {
competitionId: COMPETITION_ID,
expectedRevision: 7,
idempotencyKey: 'riot:KR_7000000001',
actor: { type: 'system' as const },
occurredAt: new Date('2026-07-12T09:59:00.000Z'),
gameId: GAME_ID,
seriesId: SERIES_ID,
gameSlotId: GAME_SLOT_ID,
ordinal: 1,
evidence: {
type: 'riot' as const,
riotMatchId: 'KR_7000000001',
payloadHash: 'sha256:riot-payload',
},
mapping: {
mappingVersion: 1,
confidence: 1,
blueTeamId: TEAM_A_ID,
redTeamId: TEAM_B_ID,
winnerTeamId: TEAM_A_ID,
participantAssignments: [],
},
startedAt: new Date('2026-07-12T09:30:00.000Z'),
durationSeconds: 1_800,
participants: [
{
userId: USER_ID.toHexString(),
teamId: TEAM_A_ID.toHexString(),
side: 'blue',
},
],
};
}
function createHarness(
options: {
competitionRevision?: number;
casResult?: Record<string, unknown> | null;
competition?: Record<string, unknown>;
facts?: Array<Record<string, unknown>>;
assignments?: Array<Record<string, unknown>>;
} = {},
) {
const session = {
startTransaction: jest.fn(),
commitTransaction: jest.fn().mockResolvedValue(undefined),
abortTransaction: jest.fn().mockResolvedValue(undefined),
endSession: jest.fn().mockResolvedValue(undefined),
};
const competition =
options.competition ??
competitionDocument(options.competitionRevision ?? 7);
const competitionModel = {
findById: jest.fn().mockReturnValue(queryResult(competition)),
findOneAndUpdate: jest
.fn()
.mockReturnValue(
queryResult(
options.casResult === undefined
? competitionDocument(8, PROJECTION)
: options.casResult,
),
),
};
const factModel = {
find: jest.fn().mockReturnValue(queryResult(options.facts ?? [])),
insertMany: jest.fn().mockResolvedValue([]),
};
const outboxModel = {
findOne: jest.fn().mockReturnValue(queryResult(null)),
insertMany: jest.fn().mockResolvedValue([]),
};
const assignmentModel = {
find: jest.fn().mockReturnValue(queryResult(options.assignments ?? [])),
updateOne: jest.fn().mockResolvedValue({ modifiedCount: 1 }),
updateMany: jest.fn().mockResolvedValue({ modifiedCount: 2 }),
};
const tournamentCodeModel = {
updateOne: jest.fn().mockResolvedValue({ modifiedCount: 1 }),
updateMany: jest.fn().mockResolvedValue({ modifiedCount: 2 }),
};
const matchModel = {
updateOne: jest
.fn()
.mockResolvedValue({ matchedCount: 1, modifiedCount: 1 }),
};
const models: Record<string, unknown> = {
competition: competitionModel,
competitionFact: factModel,
competitionOutbox: outboxModel,
tournamentCodeAssignment: assignmentModel,
tournamentCode: tournamentCodeModel,
match: matchModel,
};
const connectionService = {
createSession: jest.fn().mockResolvedValue(session),
getModel: jest.fn((name: string) => Promise.resolve(models[name])),
};
return {
session,
competitionModel,
factModel,
outboxModel,
assignmentModel,
tournamentCodeModel,
matchModel,
connectionService,
};
}
function competitionDocument(revision: number, projection = PROJECTION) {
return {
_id: COMPETITION_ID,
matchId: new Types.ObjectId('64b000000000000000000010'),
communityId: new Types.ObjectId('64b000000000000000000011'),
schemaVersion: 1,
projectorVersion: 1,
revision,
phase: 'running',
teams: [
{ teamId: TEAM_A_ID, displayOrder: 1, seedNumber: 1 },
{ teamId: TEAM_B_ID, displayOrder: 2, seedNumber: 2 },
],
format: {
type: 'paired-series',
rule: { type: 'first-to', winsRequired: 2, maxGames: 3 },
},
seriesGraph: [],
projection,
};
}
function queryResult<T>(value: T) {
const query = {
session: jest.fn(),
sort: jest.fn(),
lean: jest.fn(),
exec: jest.fn().mockResolvedValue(value),
};
query.session.mockReturnValue(query);
query.sort.mockReturnValue(query);
query.lean.mockReturnValue(query);
return query;
}
function reversalFixture() {
const parentSeriesId = new Types.ObjectId('64b000000000000000000021');
const childSeriesId = new Types.ObjectId('64b000000000000000000022');
const parentFactId = new Types.ObjectId('64b000000000000000000023');
const childFactId = new Types.ObjectId('64b000000000000000000024');
const parentGameSlotId = new Types.ObjectId('64b000000000000000000025');
const childGameSlotId = new Types.ObjectId('64b000000000000000000026');
const parentCodeId = new Types.ObjectId('64b000000000000000000027');
const childCodeId = new Types.ObjectId('64b000000000000000000028');
const series = (
id: Types.ObjectId,
sourceA: Record<string, unknown>,
sourceB: Record<string, unknown>,
) => ({
id: id.toHexString(),
stage: { type: 'upper', displayOrder: 1 },
slots: [
{ position: 'A', source: sourceA },
{ position: 'B', source: sourceB },
],
rule: { type: 'first-to', winsRequired: 1, maxGames: 1 },
gameSlots: [],
});
const accepted = (
_id: Types.ObjectId,
seriesId: Types.ObjectId,
gameSlotId: Types.ObjectId,
) => ({
_id,
competitionId: COMPETITION_ID,
type: 'game-accepted',
revision: 1,
ordinalWithinRevision: 1,
commandId: `command-${_id.toHexString()}`,
idempotencyKey: `key-${_id.toHexString()}`,
requestHash: `hash-${_id.toHexString()}`,
schemaVersion: 1,
actor: { type: 'system' },
occurredAt: new Date('2026-07-12T00:00:00.000Z'),
recordedAt: new Date('2026-07-12T00:00:00.000Z'),
gameId: new Types.ObjectId(),
seriesId,
gameSlotId,
ordinal: 1,
evidence: { type: 'legacy', legacyReference: 'legacy' },
mapping: {
blueTeamId: TEAM_A_ID,
redTeamId: TEAM_B_ID,
winnerTeamId: TEAM_A_ID,
},
});
return {
parentSeriesId,
childSeriesId,
parentFactId,
childFactId,
parentGameSlotId,
childGameSlotId,
parentCodeId,
childCodeId,
competition: {
...competitionDocument(7),
seriesGraph: [
series(
parentSeriesId,
{ type: 'team', teamId: TEAM_A_ID.toHexString() },
{ type: 'team', teamId: TEAM_B_ID.toHexString() },
),
series(
childSeriesId,
{
type: 'series-outcome',
seriesId: parentSeriesId.toHexString(),
select: 'winner',
},
{ type: 'team', teamId: TEAM_B_ID.toHexString() },
),
],
},
facts: [
accepted(parentFactId, parentSeriesId, parentGameSlotId),
accepted(childFactId, childSeriesId, childGameSlotId),
],
assignments: [
{
competitionId: COMPETITION_ID,
seriesId: parentSeriesId,
gameSlotId: parentGameSlotId,
tournamentCodeId: parentCodeId,
state: 'used',
},
{
competitionId: COMPETITION_ID,
seriesId: childSeriesId,
gameSlotId: childGameSlotId,
tournamentCodeId: childCodeId,
state: 'reserved',
},
],
};
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,331 @@
import { ConflictException, ForbiddenException } from '@nestjs/common';
import { Types } from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { CompetitionQueryService } from './competition-query.service';
describe('CompetitionQueryService', () => {
it('does not let a public read race the team-build bootstrap workflow', async () => {
const harness = createHarness({ competition: null });
const service = createService(harness);
await expect(
service.getCompetition({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
}),
).rejects.toBeInstanceOf(ConflictException);
expect(harness.matchModel.findOne).toHaveBeenCalledWith({
_id: MATCH_ID,
communityId: COMMUNITY_ID,
});
});
it('returns an explicit team view with codes only for the callers team', async () => {
const harness = createHarness();
const service = createService(harness);
const result = await service.getTeamView({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
userId: TEAM_A_USER_ID,
});
expect(result).toMatchObject({
competitionId: COMPETITION_ID.toHexString(),
revision: 4,
teamId: TEAM_A_ID.toHexString(),
activeSeries: [expect.objectContaining({ seriesId: SERIES_ID })],
tournamentCodes: [
{
gameSlotId: GAME_SLOT_ID,
seriesId: SERIES_ID,
ordinal: 1,
displayNumber: 1,
state: 'reserved',
code: 'TEAM-A-SECRET-CODE',
expiresAt: '2026-07-13T00:00:00.000Z',
},
],
});
expect(JSON.stringify(result)).not.toContain('OPPONENT-SECRET-CODE');
expect(harness.tournamentCodeModel.find).toHaveBeenCalledWith({
_id: { $in: [TEAM_A_CODE_ID] },
state: { $in: ['reserved', 'used'] },
});
});
it('does not reveal a team view to an authenticated non-participant', async () => {
const service = createService(createHarness());
await expect(
service.getTeamView({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
userId: new Types.ObjectId('64c000000000000000000099'),
}),
).rejects.toBeInstanceOf(ForbiddenException);
});
it('does not expose a stale code whose active assignment no longer matches', async () => {
const harness = createHarness();
harness.tournamentCodeModel.find.mockReturnValueOnce(queryResult([]));
const service = createService(harness);
await expect(
service.getTeamView({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
userId: TEAM_A_USER_ID,
}),
).rejects.toBeInstanceOf(ConflictException);
});
it('pages facts in immutable revision order using an opaque cursor', async () => {
const harness = createHarness();
harness.factModel.find.mockReturnValueOnce(
queryResult([
factDocument('64c000000000000000000031', 1, 1),
factDocument('64c000000000000000000032', 2, 1),
factDocument('64c000000000000000000033', 3, 1),
]),
);
const service = createService(harness);
const first = await service.listFacts({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
limit: 2,
});
expect(first.facts).toHaveLength(2);
expect(first.nextCursor).toEqual(expect.any(String));
expect(first.facts[0]).toMatchObject({
id: '64c000000000000000000031',
competitionId: COMPETITION_ID.toHexString(),
type: 'game-accepted',
revision: 1,
});
expect(first.facts[0]).not.toHaveProperty('requestHash');
expect(first.facts[0]).not.toHaveProperty('idempotencyKey');
});
});
const COMMUNITY_ID = new Types.ObjectId('64c000000000000000000001');
const MATCH_ID = new Types.ObjectId('64c000000000000000000002');
const COMPETITION_ID = new Types.ObjectId('64c000000000000000000003');
const TEAM_A_ID = new Types.ObjectId('64c000000000000000000004');
const TEAM_B_ID = new Types.ObjectId('64c000000000000000000005');
const TEAM_A_USER_ID = new Types.ObjectId('64c000000000000000000006');
const TEAM_B_USER_ID = new Types.ObjectId('64c000000000000000000007');
const TEAM_A_CODE_ID = new Types.ObjectId('64c000000000000000000008');
const TEAM_B_CODE_ID = new Types.ObjectId('64c000000000000000000009');
const SERIES_ID = 'series-1';
const GAME_SLOT_ID = 'slot-1';
function createService(harness: ReturnType<typeof createHarness>) {
return new CompetitionQueryService(
harness.connectionService as ConnectionService,
);
}
function createHarness(options: { competition?: unknown } = {}) {
const competition =
options.competition === undefined
? competitionDocument()
: options.competition;
const competitionModel = {
findOne: jest.fn().mockReturnValue(queryResult(competition)),
};
const matchModel = {
findOne: jest.fn().mockReturnValue(
queryResult({
_id: MATCH_ID,
communityId: COMMUNITY_ID,
status: 'team-built',
teams: [{ teamIndex: 1 }, { teamIndex: 2 }],
participants: [],
gameMode: 'pair',
gameCount: 3,
}),
),
};
const assignmentModel = {
find: jest.fn().mockReturnValue(
queryResult([
{
competitionId: COMPETITION_ID,
seriesId: SERIES_ID,
gameSlotId: GAME_SLOT_ID,
tournamentCodeId: TEAM_A_CODE_ID,
state: 'reserved',
},
{
competitionId: COMPETITION_ID,
seriesId: 'series-opponent-only',
gameSlotId: 'slot-opponent-only',
tournamentCodeId: TEAM_B_CODE_ID,
state: 'reserved',
},
]),
),
};
const tournamentCodeModel = {
find: jest.fn().mockReturnValue(
queryResult([
{
_id: TEAM_A_CODE_ID,
code: 'TEAM-A-SECRET-CODE',
state: 'reserved',
matchId: MATCH_ID,
expiresAt: new Date('2026-07-13T00:00:00.000Z'),
},
{
_id: TEAM_B_CODE_ID,
code: 'OPPONENT-SECRET-CODE',
state: 'reserved',
matchId: MATCH_ID,
expiresAt: new Date('2026-07-13T00:00:00.000Z'),
},
]),
),
};
const factModel = {
find: jest.fn().mockReturnValue(queryResult([])),
};
const models: Record<string, unknown> = {
competition: competitionModel,
match: matchModel,
tournamentCodeAssignment: assignmentModel,
tournamentCode: tournamentCodeModel,
competitionFact: factModel,
};
return {
competitionModel,
matchModel,
assignmentModel,
tournamentCodeModel,
factModel,
connectionService: {
getModel: jest.fn((name: string) => Promise.resolve(models[name])),
},
};
}
function competitionDocument() {
return {
_id: COMPETITION_ID,
matchId: MATCH_ID,
communityId: COMMUNITY_ID,
schemaVersion: 1,
projectorVersion: 1,
revision: 4,
phase: 'running',
teams: [
{
teamId: TEAM_A_ID,
displayOrder: 1,
seedNumber: 1,
name: 'Team A',
members: [{ userId: TEAM_A_USER_ID, displayName: 'A' }],
},
{
teamId: TEAM_B_ID,
displayOrder: 2,
seedNumber: 2,
name: 'Team B',
members: [{ userId: TEAM_B_USER_ID, displayName: 'B' }],
},
],
format: {
type: 'paired-series',
rule: { type: 'fixed-games', gameCount: 3, drawPolicy: 'allow' },
},
seriesGraph: [],
projection: {
sourceRevision: 4,
projectorVersion: 1,
phase: 'running',
formatType: 'paired-series',
series: [
{
seriesId: SERIES_ID,
status: 'in-progress',
stage: { type: 'pair', displayOrder: 1 },
rule: { type: 'fixed-games', gameCount: 3, drawPolicy: 'allow' },
entries: [
{ slot: 'A', teamId: TEAM_A_ID.toHexString(), gameWins: 1 },
{ slot: 'B', teamId: TEAM_B_ID.toHexString(), gameWins: 0 },
],
},
{
seriesId: 'series-opponent-only',
status: 'in-progress',
stage: { type: 'pair', displayOrder: 2 },
rule: { type: 'fixed-games', gameCount: 3, drawPolicy: 'allow' },
entries: [
{ slot: 'A', teamId: TEAM_B_ID.toHexString(), gameWins: 0 },
{ slot: 'B', teamId: 'other-team', gameWins: 1 },
],
},
],
games: [],
gameSlots: [
{
id: GAME_SLOT_ID,
seriesId: SERIES_ID,
ordinal: 1,
displayNumber: 1,
status: 'reserved',
entries: [],
},
],
rounds: [],
connectors: [],
},
createdAt: new Date('2026-07-11T00:00:00.000Z'),
updatedAt: new Date('2026-07-12T00:00:00.000Z'),
};
}
function factDocument(id: string, revision: number, ordinal: number) {
return {
_id: new Types.ObjectId(id),
competitionId: COMPETITION_ID,
type: 'game-accepted',
revision,
ordinalWithinRevision: ordinal,
commandId: `command-${revision}`,
idempotencyKey: `secret-${revision}`,
requestHash: `hash-${revision}`,
schemaVersion: 1,
actor: { type: 'system' },
occurredAt: new Date('2026-07-12T00:00:00.000Z'),
recordedAt: new Date('2026-07-12T00:00:01.000Z'),
gameId: new Types.ObjectId('64c000000000000000000041'),
seriesId: new Types.ObjectId('64c000000000000000000042'),
gameSlotId: new Types.ObjectId('64c000000000000000000043'),
ordinal: 1,
evidence: { type: 'legacy', legacyReference: 'legacy-1' },
mapping: {
mappingVersion: 1,
confidence: 1,
blueTeamId: TEAM_A_ID,
redTeamId: TEAM_B_ID,
winnerTeamId: TEAM_A_ID,
},
};
}
function queryResult<T>(value: T) {
const query = {
sort: jest.fn(),
limit: jest.fn(),
lean: jest.fn(),
exec: jest.fn().mockResolvedValue(value),
};
query.sort.mockReturnValue(query);
query.limit.mockReturnValue(query);
query.lean.mockReturnValue(query);
return query;
}
@@ -0,0 +1,390 @@
import type {
CompetitionFactView,
CompetitionFactsResponse,
TeamCompetitionViewResponse,
} from '@lolympus/contracts';
import {
ConflictException,
ForbiddenException,
Injectable,
NotFoundException,
UnprocessableEntityException,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type { Competition, CompetitionFact } from './competition.schema';
type PersistenceId = string | mongoose.Types.ObjectId;
type CompetitionRecord = Competition & { _id: mongoose.Types.ObjectId };
export interface CompetitionScope {
communityId: mongoose.Types.ObjectId;
matchId: mongoose.Types.ObjectId;
}
interface CompetitionProjectionSource {
series?: Array<Record<string, unknown>>;
gameSlots?: Array<Record<string, unknown>>;
}
@Injectable()
export class CompetitionQueryService {
constructor(private readonly connectionService: ConnectionService) {}
/** Resolve the aggregate created by the finalized team-build workflow. */
public async getCompetition(
scope: CompetitionScope,
): Promise<CompetitionRecord> {
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findOne({
_id: scope.matchId,
communityId: scope.communityId,
})
.lean()
.exec();
if (!match) throw new NotFoundException('Match not found.');
if (
match.status === 'recruiting' ||
!Array.isArray(match.teams) ||
match.teams.length < 2
) {
throw new ConflictException(
'Competition is unavailable until team building is complete.',
);
}
const CompetitionModel =
await this.connectionService.getModel('competition');
const existing = await CompetitionModel.findOne({
matchId: scope.matchId,
communityId: scope.communityId,
})
.lean()
.exec();
if (existing) return existing as CompetitionRecord;
throw new ConflictException(
'Competition is still being initialized by the team-build workflow.',
);
}
public async getTeamView(
scope: CompetitionScope & { userId: mongoose.Types.ObjectId },
): Promise<TeamCompetitionViewResponse> {
const competition = (await this.getCompetition(scope)) as Competition & {
_id: PersistenceId;
};
const team = competition.teams.find(({ members }) =>
members.some(({ userId }) => sameId(userId, scope.userId)),
);
if (!team) {
throw new ForbiddenException(
'Only a Competition team member may access the team view.',
);
}
const projection = competition.projection as CompetitionProjectionSource;
const allSeries = Array.isArray(projection.series) ? projection.series : [];
const teamId = idString(team.teamId);
const activeSeries = allSeries.filter(
(series) =>
series.status !== 'completed' &&
series.status !== 'inactive' &&
Array.isArray(series.entries) &&
series.entries.some(
(entry) =>
isRecord(entry) &&
idString(entry.teamId as PersistenceId) === teamId,
),
);
const activeSeriesIds = new Set(
activeSeries.map((series) => idString(series.seriesId as PersistenceId)),
);
const gameSlots = (
Array.isArray(projection.gameSlots) ? projection.gameSlots : []
).filter((slot) =>
activeSeriesIds.has(idString(slot.seriesId as PersistenceId)),
);
const AssignmentModel = await this.connectionService.getModel(
'tournamentCodeAssignment',
);
const queriedAssignments = await AssignmentModel.find({
competitionId: competition._id,
seriesId: { $in: [...activeSeriesIds] },
state: { $in: ['reserved', 'used'] },
})
.lean()
.exec();
// Keep this defensive filter even when the persistence query is mocked or
// changed: an opponent-only assignment must never cross this boundary.
const assignments = queriedAssignments.filter((assignment) =>
activeSeriesIds.has(idString(assignment.seriesId)),
);
const codeIds = assignments.map(({ tournamentCodeId }) => tournamentCodeId);
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const codes = codeIds.length
? await TournamentCodeModel.find({
_id: { $in: codeIds },
state: { $in: ['reserved', 'used'] },
})
.lean()
.exec()
: [];
const codeById = new Map(codes.map((code) => [idString(code._id), code]));
const assignmentBySlot = new Map(
assignments.map((assignment) => [
idString(assignment.gameSlotId),
assignment,
]),
);
return {
competitionId: idString(competition._id) as never,
revision: competition.revision,
phase: competition.phase,
teamId: teamId as never,
activeSeries: toWire(activeSeries) as never,
tournamentCodes: gameSlots.map((slot) => {
const gameSlotId = idString(slot.id as PersistenceId);
const assignment = assignmentBySlot.get(gameSlotId);
const code = assignment
? codeById.get(idString(assignment.tournamentCodeId))
: undefined;
if (
assignment &&
(!code ||
code.state !== assignment.state ||
!code.matchId ||
!sameId(code.matchId, competition.matchId))
) {
throw new ConflictException(
'Tournament Code assignment is inconsistent and cannot be exposed.',
);
}
return {
gameSlotId: gameSlotId as never,
seriesId: idString(slot.seriesId as PersistenceId) as never,
ordinal: numberValue(slot.ordinal),
displayNumber: numberValue(slot.displayNumber),
state:
assignment?.state === 'reserved' || assignment?.state === 'used'
? assignment.state
: 'pending',
code: typeof code?.code === 'string' ? code.code : null,
expiresAt: code?.expiresAt ? isoDate(code.expiresAt) : null,
};
}),
};
}
public async listFacts(
scope: CompetitionScope & { cursor?: string; limit?: number },
): Promise<CompetitionFactsResponse> {
const competition = (await this.getCompetition(scope)) as Competition & {
_id: PersistenceId;
};
const limit = normalizeLimit(scope.limit);
const cursor = scope.cursor ? decodeCursor(scope.cursor) : undefined;
const cursorFilter = cursor
? {
$or: [
{ revision: { $gt: cursor.revision } },
{
revision: cursor.revision,
ordinalWithinRevision: { $gt: cursor.ordinalWithinRevision },
},
{
revision: cursor.revision,
ordinalWithinRevision: cursor.ordinalWithinRevision,
_id: { $gt: new mongoose.Types.ObjectId(cursor.id) },
},
],
}
: {};
const FactModel = await this.connectionService.getModel('competitionFact');
const rows = await FactModel.find({
competitionId: competition._id,
...cursorFilter,
})
.sort({ revision: 1, ordinalWithinRevision: 1, _id: 1 })
.limit(limit + 1)
.lean()
.exec();
const page = rows.slice(0, limit);
const last = page.at(-1);
return {
facts: page.map(presentFact),
nextCursor:
rows.length > limit && last
? encodeCursor({
revision: requiredNumber(last.revision, 'revision'),
ordinalWithinRevision: requiredNumber(
last.ordinalWithinRevision,
'ordinalWithinRevision',
),
id: requiredId(last._id, '_id'),
})
: null,
};
}
}
function presentFact(
source: CompetitionFact & { _id: mongoose.Types.ObjectId },
): CompetitionFactView {
const common = {
id: requiredId(source._id, '_id') as never,
competitionId: requiredId(source.competitionId, 'competitionId') as never,
revision: requiredNumber(source.revision, 'revision'),
ordinalWithinRevision: requiredNumber(
source.ordinalWithinRevision,
'ordinalWithinRevision',
),
commandId: requiredString(source.commandId, 'commandId') as never,
schemaVersion: requiredNumber(source.schemaVersion, 'schemaVersion'),
actor: toWire(source.actor) as never,
occurredAt: isoDate(source.occurredAt),
recordedAt: isoDate(source.recordedAt),
...(typeof source.causationId === 'string' && source.causationId.length > 0
? { causationId: source.causationId }
: {}),
};
switch (source.type) {
case 'game-accepted':
return {
...common,
type: 'game-accepted',
gameId: requiredId(source.gameId, 'gameId') as never,
seriesId: requiredId(source.seriesId, 'seriesId') as never,
gameSlotId: requiredId(source.gameSlotId, 'gameSlotId') as never,
ordinal: requiredNumber(source.ordinal, 'ordinal'),
startedAt: isoDate(source.startedAt ?? source.occurredAt),
durationSeconds: numberValue(source.durationSeconds ?? 0),
participants: toWire(source.participants ?? []) as never,
evidence: toWire(source.evidence) as never,
mapping: toWire(source.mapping) as never,
};
case 'game-voided':
return {
...common,
type: 'game-voided',
gameAcceptedFactId: requiredId(
source.gameAcceptedFactId,
'gameAcceptedFactId',
) as never,
reason: requiredString(source.reason, 'reason'),
};
case 'series-adjudicated':
return {
...common,
type: 'series-adjudicated',
seriesId: requiredId(source.seriesId, 'seriesId') as never,
decision: toWire(source.decision) as never,
reason: requiredString(source.reason, 'reason'),
};
case 'adjudication-reversed':
return {
...common,
type: 'adjudication-reversed',
adjudicationFactId: requiredId(
source.adjudicationFactId,
'adjudicationFactId',
) as never,
reason: requiredString(source.reason, 'reason'),
};
default:
throw new Error('Unsupported Competition fact type.');
}
}
interface FactCursor {
revision: number;
ordinalWithinRevision: number;
id: string;
}
function encodeCursor(cursor: FactCursor): string {
return Buffer.from(JSON.stringify(cursor)).toString('base64url');
}
function decodeCursor(value: string): FactCursor {
try {
const parsed: unknown = JSON.parse(
Buffer.from(value, 'base64url').toString('utf8'),
);
if (
!isRecord(parsed) ||
!Number.isInteger(parsed.revision) ||
!Number.isInteger(parsed.ordinalWithinRevision) ||
typeof parsed.id !== 'string' ||
!mongoose.isValidObjectId(parsed.id)
) {
throw new Error('malformed cursor');
}
return parsed as unknown as FactCursor;
} catch {
throw new UnprocessableEntityException('Invalid facts cursor.');
}
}
function normalizeLimit(value: number | undefined): number {
if (value === undefined) return 50;
if (!Number.isInteger(value) || value < 1 || value > 100) {
throw new UnprocessableEntityException(
'Facts page limit must be an integer from 1 through 100.',
);
}
return value;
}
function sameId(left: PersistenceId, right: PersistenceId): boolean {
return idString(left) === idString(right);
}
function idString(value: PersistenceId): string {
return value instanceof mongoose.Types.ObjectId
? value.toHexString()
: String(value);
}
function isoDate(value: unknown): string {
if (value instanceof Date) return value.toISOString();
if (typeof value === 'string') return value;
throw new Error('Competition fact contains an invalid date.');
}
function numberValue(value: unknown): number {
return typeof value === 'number' ? value : Number(value);
}
function toWire(value: unknown): unknown {
if (value instanceof mongoose.Types.ObjectId) return value.toHexString();
if (value instanceof Date) return value.toISOString();
if (Array.isArray(value)) return value.map(toWire);
if (isRecord(value)) {
return Object.fromEntries(
Object.entries(value).map(([key, child]) => [key, toWire(child)]),
);
}
return value;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function requiredId(value: unknown, field: string): string {
if (value instanceof mongoose.Types.ObjectId) return value.toHexString();
return requiredString(value, field);
}
function requiredString(value: unknown, field: string): string {
if (typeof value === 'string' && value.length > 0) return value;
throw new Error(`Competition fact contains an invalid ${field}.`);
}
function requiredNumber(value: unknown, field: string): number {
if (typeof value === 'number' && Number.isFinite(value)) return value;
throw new Error(`Competition fact contains an invalid ${field}.`);
}
@@ -0,0 +1,356 @@
import { HttpException } from '@nestjs/common';
import { Types } from 'mongoose';
import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from '../auth/allow-public-access.decorator';
import { ROLES_KEY } from '../auth/roles.decorator';
import { CompetitionCommandService } from './competition-command.service';
import { CompetitionController } from './competition.controller';
import { CompetitionQueryService } from './competition-query.service';
describe('CompetitionController', () => {
it('marks only the detail endpoint public and writes a revision ETag', async () => {
const { controller, queryService } = createHarness();
const response = { setHeader: jest.fn() };
const result = await controller.getDetail(
COMMUNITY_ID,
MATCH_ID,
response as never,
);
expect(
Reflect.getMetadata(
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
CompetitionController.prototype.getDetail,
),
).toBe(true);
expect(
Reflect.getMetadata(
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
CompetitionController.prototype.getTeamView,
),
).not.toBe(true);
expect(response.setHeader).toHaveBeenCalledWith('ETag', '"7"');
expect(result).toMatchObject({ revision: 7 });
expect(queryService.getCompetition).toHaveBeenCalledWith({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
});
});
it('protects audit and mutation endpoints with admin roles', () => {
for (const method of [
'listFacts',
'acceptGame',
'adjudicateSeries',
'previewReversal',
'reverseSeries',
] as const) {
expect(
Reflect.getMetadata(ROLES_KEY, CompetitionController.prototype[method]),
).toEqual(['owner', 'admin']);
}
});
it('requires If-Match and Idempotency-Key for a mutation', async () => {
const { controller } = createHarness();
await expect(
controller.acceptGame(
adminUser(),
COMMUNITY_ID,
MATCH_ID,
undefined,
undefined,
acceptGameBody(),
),
).rejects.toMatchObject({
status: 422,
response: {
error: { code: 'INVALID_COMPETITION_COMMAND_HEADERS' },
},
});
});
it('passes revision, idempotency and the authenticated actor to accept-game', async () => {
const { controller, commandService } = createHarness();
await controller.acceptGame(
adminUser(),
COMMUNITY_ID,
MATCH_ID,
'W/"7"',
'operator:accept:1',
acceptGameBody(),
);
expect(commandService.acceptGame).toHaveBeenCalledWith(
expect.objectContaining({
expectedRevision: 7,
idempotencyKey: 'operator:accept:1',
}),
);
const accepted = commandService.acceptGame.mock.calls[0][0];
expect(accepted.competitionId.toHexString()).toBe(
COMPETITION_ID.toHexString(),
);
expect(accepted.actor.userId.toHexString()).toBe(ADMIN_ID.toHexString());
expect(accepted.gameId.toHexString()).toBe(GAME_ID.toHexString());
expect(accepted.seriesId.toHexString()).toBe(SERIES_ID);
expect(accepted.gameSlotId.toHexString()).toBe(GAME_SLOT_ID.toHexString());
});
it('maps command conflicts to the explicit error envelope', async () => {
const { controller, commandService } = createHarness();
commandService.adjudicateSeries.mockRejectedValue({
code: 'IDEMPOTENCY_KEY_CONFLICT',
message: 'duplicate key with another payload',
httpStatus: 409,
details: { idempotencyKey: 'same-key' },
});
let thrown: unknown;
try {
await controller.adjudicateSeries(
adminUser(),
COMMUNITY_ID,
MATCH_ID,
new Types.ObjectId(SERIES_ID),
'"7"',
'same-key',
{
decision: { type: 'administrative-draw' },
reason: '운영 판단',
},
);
} catch (error) {
thrown = error;
}
expect(thrown).toBeInstanceOf(HttpException);
expect(thrown).toMatchObject({
status: 409,
response: {
error: {
code: 'IDEMPOTENCY_KEY_CONFLICT',
details: { idempotencyKey: 'same-key' },
},
},
});
});
it.each([
{
source: {
code: 'STALE_COMPETITION_REVISION',
message: 'stale',
httpStatus: 412,
},
status: 412,
},
{
source: {
code: 'GAME_TEAM_MISMATCH',
message: 'invalid evidence mapping',
},
status: 422,
},
])('maps $source.code to HTTP $status', async ({ source, status }) => {
const { controller, commandService } = createHarness();
commandService.acceptGame.mockRejectedValue(source);
await expect(
controller.acceptGame(
adminUser(),
COMMUNITY_ID,
MATCH_ID,
'"7"',
`operator:error:${status}`,
acceptGameBody(),
),
).rejects.toMatchObject({
status,
response: { error: { code: source.code } },
});
});
it('returns an explicit 422 envelope for an invalid command body', async () => {
const { controller, commandService } = createHarness();
await expect(
controller.adjudicateSeries(
adminUser(),
COMMUNITY_ID,
MATCH_ID,
new Types.ObjectId(SERIES_ID),
'"7"',
'operator:invalid-body:1',
{
decision: { type: 'walkover' },
reason: '',
},
),
).rejects.toMatchObject({
status: 422,
response: {
error: { code: 'INVALID_COMPETITION_REQUEST' },
},
});
expect(commandService.adjudicateSeries).not.toHaveBeenCalled();
});
it('rejects malformed game evidence before it reaches the ledger', async () => {
const { controller, commandService } = createHarness();
await expect(
controller.acceptGame(
adminUser(),
COMMUNITY_ID,
MATCH_ID,
'"7"',
'operator:bad-evidence:1',
{
...acceptGameBody(),
evidence: { type: 'invented-evidence' },
},
),
).rejects.toMatchObject({
status: 422,
response: {
error: { code: 'INVALID_COMPETITION_REQUEST' },
},
});
expect(commandService.acceptGame).not.toHaveBeenCalled();
});
it('requires the same revision for preview and hash-confirmed reversal', async () => {
const { controller, commandService } = createHarness();
await controller.previewReversal(
adminUser(),
COMMUNITY_ID,
MATCH_ID,
new Types.ObjectId(SERIES_ID),
'"7"',
{ mode: 'cascade', reason: '잘못 수집됨' },
);
await controller.reverseSeries(
adminUser(),
COMMUNITY_ID,
MATCH_ID,
new Types.ObjectId(SERIES_ID),
'"7"',
'operator:reverse:1',
{
mode: 'cascade',
reason: '잘못 수집됨',
impactHash: 'a'.repeat(64),
},
);
expect(commandService.previewSeriesReversal).toHaveBeenCalledWith({
competitionId: COMPETITION_ID,
expectedRevision: 7,
seriesId: new Types.ObjectId(SERIES_ID),
mode: 'cascade',
});
expect(commandService.reverseSeries).toHaveBeenCalledWith(
expect.objectContaining({
competitionId: COMPETITION_ID,
expectedRevision: 7,
idempotencyKey: 'operator:reverse:1',
impactHash: 'a'.repeat(64),
}),
);
});
});
const COMMUNITY_ID = new Types.ObjectId('64d000000000000000000001');
const MATCH_ID = new Types.ObjectId('64d000000000000000000002');
const COMPETITION_ID = new Types.ObjectId('64d000000000000000000003');
const ADMIN_ID = new Types.ObjectId('64d000000000000000000004');
const GAME_ID = new Types.ObjectId('64d000000000000000000005');
const SERIES_ID = '64d000000000000000000006';
const GAME_SLOT_ID = new Types.ObjectId('64d000000000000000000007');
const TEAM_A_ID = new Types.ObjectId('64d000000000000000000008');
const TEAM_B_ID = new Types.ObjectId('64d000000000000000000009');
function createHarness() {
const competition = {
_id: COMPETITION_ID,
matchId: MATCH_ID,
communityId: COMMUNITY_ID,
schemaVersion: 1,
revision: 7,
phase: 'running',
teams: [],
format: {
type: 'paired-series',
rule: { type: 'fixed-games', gameCount: 3, drawPolicy: 'allow' },
},
projection: {
sourceRevision: 7,
projectorVersion: 1,
phase: 'running',
formatType: 'paired-series',
series: [],
games: [],
gameSlots: [],
rounds: [],
connectors: [],
},
createdAt: new Date('2026-07-11T00:00:00.000Z'),
updatedAt: new Date('2026-07-12T00:00:00.000Z'),
};
const queryService = {
getCompetition: jest.fn().mockResolvedValue(competition),
getTeamView: jest.fn(),
listFacts: jest.fn(),
};
const commandService = {
acceptGame: jest.fn().mockResolvedValue({ competition, revision: 8 }),
adjudicateSeries: jest.fn().mockResolvedValue({ competition, revision: 8 }),
previewSeriesReversal: jest.fn().mockResolvedValue({
sourceRevision: 7,
impactHash: 'a'.repeat(64),
impact: {},
}),
reverseSeries: jest.fn().mockResolvedValue({ competition, revision: 8 }),
};
return {
queryService,
commandService,
controller: new CompetitionController(
queryService as unknown as CompetitionQueryService,
commandService as unknown as CompetitionCommandService,
),
};
}
function adminUser() {
return {
_id: ADMIN_ID,
communityId: COMMUNITY_ID,
role: 'admin',
} as never;
}
function acceptGameBody() {
return {
gameId: GAME_ID.toHexString(),
seriesId: SERIES_ID,
gameSlotId: GAME_SLOT_ID.toHexString(),
ordinal: 1,
evidence: {
type: 'riot',
riotMatchId: 'KR_1',
payloadHash: 'sha256:value',
},
mapping: {
mappingVersion: 1,
confidence: 1,
blueTeamId: TEAM_A_ID.toHexString(),
redTeamId: TEAM_B_ID.toHexString(),
winnerTeamId: TEAM_A_ID.toHexString(),
},
};
}
@@ -0,0 +1,499 @@
import type {
CompetitionCommandResponse,
CompetitionDetailResponse,
CompetitionFactsResponse,
SeriesReversalPreviewResponse,
TeamCompetitionViewResponse,
} from '@lolympus/contracts';
import {
Body,
Controller,
Get,
Headers,
HttpException,
Param,
Post,
Query,
Res,
UseGuards,
} from '@nestjs/common';
import type { Response } from 'express';
import mongoose from 'mongoose';
import { plainToInstance } from 'class-transformer';
import { validateSync, type ValidationError } from 'class-validator';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { CurrentUser } from '../auth/current-user.decorator';
import { Roles } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import type { UserDocument } from '../global/database/schema';
import { CompetitionCommandService } from './competition-command.service';
import { presentCompetitionDetail } from './competition.presenter';
import { CompetitionQueryService } from './competition-query.service';
import {
AcceptCompetitionGameDto,
AdjudicateCompetitionSeriesDto,
CompetitionFactsQueryDto,
PreviewCompetitionSeriesReversalDto,
ReverseCompetitionSeriesDto,
} from './dto/competition-command.dto';
@Controller('communities/:communityId/matches/:matchId/competition')
export class CompetitionController {
constructor(
private readonly queryService: CompetitionQueryService,
private readonly commandService: CompetitionCommandService,
) {}
@Get()
@AllowPublicAccess()
public async getDetail(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Res({ passthrough: true }) response: Response,
): Promise<CompetitionDetailResponse> {
return this.translate(async () => {
const competition = await this.queryService.getCompetition({
communityId,
matchId,
});
response.setHeader('ETag', revisionEtag(competition.revision));
return presentCompetitionDetail(competition as never);
});
}
@Get('team')
public async getTeamView(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Res({ passthrough: true }) response?: Response,
): Promise<TeamCompetitionViewResponse> {
return this.translate(async () => {
assertSameCommunity(currentUser, communityId);
const result = await this.queryService.getTeamView({
communityId,
matchId,
userId: currentUser._id,
});
response?.setHeader('ETag', revisionEtag(result.revision));
return result;
});
}
@Get('facts')
@Roles('owner', 'admin')
@UseGuards(RolesGuard)
public async listFacts(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Query() rawQuery: unknown,
): Promise<CompetitionFactsResponse> {
return this.translate(async () => {
assertSameCommunity(currentUser, communityId);
const query = validateDto(CompetitionFactsQueryDto, rawQuery);
return this.queryService.listFacts({
communityId,
matchId,
cursor: query.cursor,
limit: query.limit,
});
});
}
@Post('games/accept')
@Roles('owner', 'admin')
@UseGuards(RolesGuard)
public async acceptGame(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Headers('if-match') ifMatch: string | undefined,
@Headers('idempotency-key') idempotencyKey: string | undefined,
@Body() rawBody: unknown,
): Promise<CompetitionCommandResponse> {
return this.translate(async () => {
assertSameCommunity(currentUser, communityId);
const body = validateDto(AcceptCompetitionGameDto, rawBody);
const expectedRevision = requireCommandHeaders(ifMatch, idempotencyKey);
const competition = await this.queryService.getCompetition({
communityId,
matchId,
});
const result = await this.commandService.acceptGame({
competitionId: competition._id,
expectedRevision,
idempotencyKey: idempotencyKey!,
actor: { type: 'user', userId: currentUser._id },
gameId: new mongoose.Types.ObjectId(body.gameId),
seriesId: new mongoose.Types.ObjectId(body.seriesId),
gameSlotId: new mongoose.Types.ObjectId(body.gameSlotId),
ordinal: body.ordinal,
evidence: { ...body.evidence },
mapping: { ...body.mapping },
...(body.startedAt ? { startedAt: body.startedAt } : {}),
...(body.durationSeconds === undefined
? {}
: { durationSeconds: body.durationSeconds }),
...(body.participants ? { participants: body.participants } : {}),
...(body.tournamentCode
? {
tournamentCode: {
tournamentCodeId: new mongoose.Types.ObjectId(
body.tournamentCode.tournamentCodeId,
),
riotMatchId: body.tournamentCode.riotMatchId,
},
}
: {}),
});
return {
competition: presentCompetitionDetail(result.competition as never),
};
});
}
@Post('series/:seriesId/adjudications')
@Roles('owner', 'admin')
@UseGuards(RolesGuard)
public async adjudicateSeries(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Param('seriesId', ParseObjectIdPipe) seriesId: mongoose.Types.ObjectId,
@Headers('if-match') ifMatch: string | undefined,
@Headers('idempotency-key') idempotencyKey: string | undefined,
@Body() rawBody: unknown,
): Promise<CompetitionCommandResponse> {
return this.translate(async () => {
assertSameCommunity(currentUser, communityId);
const body = validateDto(AdjudicateCompetitionSeriesDto, rawBody);
const expectedRevision = requireCommandHeaders(ifMatch, idempotencyKey);
const competition = await this.queryService.getCompetition({
communityId,
matchId,
});
const decision =
body.decision.type === 'administrative-draw'
? ({ type: 'administrative-draw' } as const)
: {
type: body.decision.type,
winnerTeamId: new mongoose.Types.ObjectId(
body.decision.winnerTeamId!,
),
};
const result = await this.commandService.adjudicateSeries({
competitionId: competition._id,
expectedRevision,
idempotencyKey: idempotencyKey!,
actor: { type: 'user', userId: currentUser._id },
seriesId,
decision,
reason: body.reason,
});
return {
competition: presentCompetitionDetail(result.competition as never),
};
});
}
@Post('series/:seriesId/reversal-preview')
@Roles('owner', 'admin')
@UseGuards(RolesGuard)
public async previewReversal(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Param('seriesId', ParseObjectIdPipe) seriesId: mongoose.Types.ObjectId,
@Headers('if-match') ifMatch: string | undefined,
@Body() rawBody: unknown,
): Promise<SeriesReversalPreviewResponse> {
return this.translate(async () => {
assertSameCommunity(currentUser, communityId);
const body = validateDto(PreviewCompetitionSeriesReversalDto, rawBody);
const expectedRevision = requireRevisionHeader(ifMatch);
const competition = await this.queryService.getCompetition({
communityId,
matchId,
});
return (await this.commandService.previewSeriesReversal({
competitionId: competition._id,
expectedRevision,
seriesId,
mode: body.mode,
})) as SeriesReversalPreviewResponse;
});
}
@Post('series/:seriesId/reverse')
@Roles('owner', 'admin')
@UseGuards(RolesGuard)
public async reverseSeries(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Param('seriesId', ParseObjectIdPipe) seriesId: mongoose.Types.ObjectId,
@Headers('if-match') ifMatch: string | undefined,
@Headers('idempotency-key') idempotencyKey: string | undefined,
@Body() rawBody: unknown,
): Promise<CompetitionCommandResponse> {
return this.translate(async () => {
assertSameCommunity(currentUser, communityId);
const body = validateDto(ReverseCompetitionSeriesDto, rawBody);
const expectedRevision = requireCommandHeaders(ifMatch, idempotencyKey);
const competition = await this.queryService.getCompetition({
communityId,
matchId,
});
const result = await this.commandService.reverseSeries({
competitionId: competition._id,
expectedRevision,
idempotencyKey: idempotencyKey!,
actor: { type: 'user', userId: currentUser._id },
seriesId,
mode: body.mode,
reason: body.reason,
impactHash: body.impactHash,
});
return {
competition: presentCompetitionDetail(result.competition as never),
};
});
}
private async translate<T>(operation: () => Promise<T>): Promise<T> {
try {
return await operation();
} catch (error) {
throw explicitHttpError(error);
}
}
}
function requireCommandHeaders(
ifMatch: string | undefined,
idempotencyKey: string | undefined,
): number {
const revision = parseRevision(ifMatch);
if (
revision === undefined ||
typeof idempotencyKey !== 'string' ||
idempotencyKey.trim().length === 0 ||
idempotencyKey.length > 200
) {
throw apiHttpError(
422,
'INVALID_COMPETITION_COMMAND_HEADERS',
'A numeric If-Match revision and non-empty Idempotency-Key are required.',
);
}
return revision;
}
function requireRevisionHeader(ifMatch: string | undefined): number {
const revision = parseRevision(ifMatch);
if (revision === undefined) {
throw apiHttpError(
422,
'INVALID_COMPETITION_COMMAND_HEADERS',
'A numeric If-Match revision is required.',
);
}
return revision;
}
function parseRevision(value: string | undefined): number | undefined {
if (!value) return undefined;
const match = /^(?:W\/)?"?(\d+)"?$/.exec(value.trim());
if (!match) return undefined;
const revision = Number(match[1]);
return Number.isSafeInteger(revision) ? revision : undefined;
}
function revisionEtag(revision: number): string {
return `"${revision}"`;
}
function assertSameCommunity(
user: UserDocument,
communityId: mongoose.Types.ObjectId,
): void {
if (!user?.communityId?.equals(communityId)) {
throw apiHttpError(
403,
'COMPETITION_COMMUNITY_FORBIDDEN',
'The authenticated user does not belong to this community.',
);
}
}
function explicitHttpError(error: unknown): HttpException {
if (error instanceof HttpException) {
const response = error.getResponse();
if (
typeof response === 'object' &&
response !== null &&
'error' in response
) {
return error;
}
return apiHttpError(
error.getStatus(),
statusCodeName(error.getStatus()),
typeof response === 'string'
? response
: error.message || 'Competition request failed.',
);
}
if (isCodedError(error)) {
return apiHttpError(
error.httpStatus ?? codedErrorStatus(error.code),
error.code,
error.message,
error.details,
);
}
return apiHttpError(
500,
'COMPETITION_INTERNAL_ERROR',
'Competition request failed.',
);
}
function codedErrorStatus(code: string): number {
switch (code) {
case 'REVERSAL_SERIES_NOT_FOUND':
case 'REVERSAL_REASON_REQUIRED':
return 422;
case 'REVERSAL_DESCENDANT_ACTIVITY':
case 'REVERSAL_NO_ACTIVE_RESULT':
case 'REVERSAL_PREVIEW_STALE':
case 'DUPLICATE_FACT_ID':
case 'DUPLICATE_GAME_ID':
case 'DUPLICATE_RIOT_MATCH_ID':
case 'DUPLICATE_GAME_SLOT':
case 'DUPLICATE_GAME_ORDINAL':
case 'DUPLICATE_ADJUDICATION':
case 'FACT_ALREADY_REVERSED':
case 'SERIES_ALREADY_COMPLETED':
case 'WALKOVER_HAS_ACTIVE_GAMES':
return 409;
case 'FACT_REFERENCE_NOT_FOUND':
case 'FACT_TYPE_INVALID':
case 'GAME_SLOT_INVALID':
case 'GAME_ORDINAL_INVALID':
case 'GAME_SERIES_MISMATCH':
case 'GAME_TEAM_MISMATCH':
case 'GAME_WINNER_INVALID':
case 'SERIES_DEFINITION_INVALID':
case 'SERIES_PARTICIPANTS_INVALID':
case 'ADJUDICATION_INVALID':
case 'ADJUDICATION_DRAW_NOT_ALLOWED':
return 422;
default:
return 500;
}
}
function statusCodeName(status: number): string {
switch (status) {
case 403:
return 'COMPETITION_FORBIDDEN';
case 404:
return 'COMPETITION_NOT_FOUND';
case 409:
return 'COMPETITION_CONFLICT';
case 412:
return 'STALE_COMPETITION_REVISION';
case 422:
return 'INVALID_COMPETITION_REQUEST';
default:
return 'COMPETITION_REQUEST_FAILED';
}
}
function apiHttpError(
status: number,
code: string,
message: string,
details?: unknown,
): HttpException {
return new HttpException(
{
error: {
code,
message,
...(details === undefined ? {} : { details }),
},
},
status,
);
}
function isCodedError(error: unknown): error is {
code: string;
message: string;
httpStatus?: number;
details?: unknown;
} {
return (
typeof error === 'object' &&
error !== null &&
typeof (error as { code?: unknown }).code === 'string' &&
typeof (error as { message?: unknown }).message === 'string'
);
}
type DtoConstructor<T extends object> = new () => T;
function validateDto<T extends object>(
constructor: DtoConstructor<T>,
value: unknown,
): T {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
throw apiHttpError(
422,
'INVALID_COMPETITION_REQUEST',
'The Competition request body must be an object.',
);
}
const instance = plainToInstance(constructor, value);
const errors = validateSync(instance, {
whitelist: true,
forbidNonWhitelisted: true,
forbidUnknownValues: true,
});
if (errors.length > 0) {
throw apiHttpError(
422,
'INVALID_COMPETITION_REQUEST',
'The Competition request payload is invalid.',
{ fields: flattenValidationErrors(errors) },
);
}
return instance;
}
function flattenValidationErrors(
errors: readonly ValidationError[],
prefix = '',
): Array<{ field: string; constraints: string[] }> {
return errors.flatMap((error) => {
const field = prefix ? `${prefix}.${error.property}` : error.property;
const current = error.constraints
? [{ field, constraints: Object.values(error.constraints) }]
: [];
return [
...current,
...flattenValidationErrors(error.children ?? [], field),
];
});
}
@@ -0,0 +1,23 @@
export type CompetitionCommandErrorCode =
| 'COMPETITION_NOT_FOUND'
| 'COMPETITION_TRANSACTION_UNAVAILABLE'
| 'IDEMPOTENCY_KEY_CONFLICT'
| 'INVALID_COMPETITION_COMMAND'
| 'STALE_COMPETITION_REVISION'
| 'TOURNAMENT_CODE_ASSIGNMENT_CONFLICT';
/**
* Transport-neutral command failure. Controllers may translate `httpStatus`
* directly while command handlers remain usable by jobs and migrations.
*/
export class CompetitionCommandError extends Error {
constructor(
public readonly code: CompetitionCommandErrorCode,
message: string,
public readonly httpStatus: 404 | 409 | 412 | 422 | 500,
public readonly details?: Readonly<Record<string, unknown>>,
) {
super(message);
this.name = 'CompetitionCommandError';
}
}
@@ -0,0 +1,32 @@
import { MODULE_METADATA } from '@nestjs/common/constants';
import { CompetitionBootstrapService } from './competition-bootstrap.service';
import { CompetitionCommandService } from './competition-command.service';
import { CompetitionController } from './competition.controller';
import { CompetitionModule } from './competition.module';
import { CompetitionQueryService } from './competition-query.service';
describe('CompetitionModule', () => {
it('owns and exports the Competition transport and application services', () => {
expect(
Reflect.getMetadata(MODULE_METADATA.CONTROLLERS, CompetitionModule),
).toEqual([CompetitionController]);
expect(
Reflect.getMetadata(MODULE_METADATA.PROVIDERS, CompetitionModule),
).toEqual(
expect.arrayContaining([
CompetitionBootstrapService,
CompetitionCommandService,
CompetitionQueryService,
]),
);
expect(
Reflect.getMetadata(MODULE_METADATA.EXPORTS, CompetitionModule),
).toEqual(
expect.arrayContaining([
CompetitionBootstrapService,
CompetitionCommandService,
CompetitionQueryService,
]),
);
});
});
@@ -0,0 +1,20 @@
import { Module } from '@nestjs/common';
import { CompetitionBootstrapService } from './competition-bootstrap.service';
import { CompetitionCommandService } from './competition-command.service';
import { CompetitionController } from './competition.controller';
import { CompetitionQueryService } from './competition-query.service';
@Module({
controllers: [CompetitionController],
providers: [
CompetitionBootstrapService,
CompetitionCommandService,
CompetitionQueryService,
],
exports: [
CompetitionBootstrapService,
CompetitionCommandService,
CompetitionQueryService,
],
})
export class CompetitionModule {}
@@ -0,0 +1,97 @@
import { presentCompetitionDetail } from './competition.presenter';
describe('presentCompetitionDetail', () => {
it('returns the explicit public contract without persistence-only fields', () => {
const response = presentCompetitionDetail({
_id: objectId('competition-1'),
matchId: objectId('match-1'),
communityId: objectId('community-1'),
schemaVersion: 1,
projectorVersion: 3,
revision: 7,
phase: 'running',
teams: [
{
teamId: objectId('team-8'),
legacyTeamIndex: 8,
displayOrder: 2,
seedNumber: 2,
name: '똥칼라파워',
captainUserId: objectId('captain-8'),
members: [
{
userId: objectId('user-8'),
displayName: 'player 8',
gameName: '칼라',
tagLine: 'KR1',
assignedPosition: 'MID',
cost: 42,
secretPuuid: 'must-not-leak',
},
],
},
],
format: {
type: 'paired-series',
rule: { type: 'fixed-games', gameCount: 3, drawPolicy: 'allow' },
},
seriesGraph: [{ internal: true }],
projection: {
sourceRevision: 7,
projectorVersion: 3,
phase: 'running',
formatType: 'paired-series',
series: [],
games: [],
gameSlots: [],
rounds: [],
connectors: [],
},
internalCommandReceipts: [{ idempotencyKey: 'secret' }],
createdAt: new Date('2026-07-11T00:00:00.000Z'),
updatedAt: new Date('2026-07-12T00:00:00.000Z'),
});
expect(response).toMatchObject({
id: 'competition-1',
matchId: 'match-1',
communityId: 'community-1',
schemaVersion: 1,
revision: 7,
phase: 'running',
createdAt: '2026-07-11T00:00:00.000Z',
updatedAt: '2026-07-12T00:00:00.000Z',
teams: [
{
teamId: 'team-8',
displayOrder: 2,
name: '똥칼라파워',
captainUserId: 'captain-8',
members: [
{
userId: 'user-8',
displayName: 'player 8',
gameName: '칼라',
tagLine: 'KR1',
assignedPosition: 'MID',
cost: 42,
},
],
},
],
projection: {
sourceRevision: 7,
projectorVersion: 3,
},
});
expect(response).not.toHaveProperty('seriesGraph');
expect(response).not.toHaveProperty('internalCommandReceipts');
expect(response.teams[0]).not.toHaveProperty('legacyTeamIndex');
expect(response.teams[0]).not.toHaveProperty('seedNumber');
expect(response.teams[0].members[0]).not.toHaveProperty('secretPuuid');
});
});
function objectId(value: string) {
return { toString: () => value };
}
@@ -0,0 +1,115 @@
import type {
CommunityId,
CompetitionDetailResponse,
CompetitionFormat,
CompetitionId,
CompetitionPhase,
CompetitionProjection,
MatchId,
PlayerPosition,
TeamId,
UserId,
} from '@lolympus/contracts';
type IdLike = string | { toString(): string };
interface CompetitionMemberSource {
userId: IdLike;
displayName: string;
gameName?: string;
tagLine?: string;
profileIconId?: number;
assignedPosition?: string;
cost?: number;
[key: string]: unknown;
}
interface CompetitionTeamSource {
teamId: IdLike;
displayOrder: number;
name: string;
captainUserId?: IdLike;
members: CompetitionMemberSource[];
[key: string]: unknown;
}
export interface CompetitionDetailSource {
_id: IdLike;
matchId: IdLike;
communityId: IdLike;
schemaVersion: number;
revision: number;
phase: CompetitionPhase;
teams: CompetitionTeamSource[];
format: Record<string, unknown>;
projection: Record<string, unknown>;
createdAt: Date | string;
updatedAt: Date | string;
[key: string]: unknown;
}
/** Build the public wire DTO without ever spreading a persistence document. */
export function presentCompetitionDetail(
source: CompetitionDetailSource,
): CompetitionDetailResponse {
return {
id: asId<CompetitionId>(source._id),
matchId: asId<MatchId>(source.matchId),
communityId: asId<CommunityId>(source.communityId),
schemaVersion: source.schemaVersion,
revision: source.revision,
phase: source.phase,
teams: source.teams.map((team) => ({
teamId: asId<TeamId>(team.teamId),
displayOrder: team.displayOrder,
name: team.name,
...(team.captainUserId
? { captainUserId: asId<UserId>(team.captainUserId) }
: {}),
members: team.members.map((member) => ({
userId: asId<UserId>(member.userId),
displayName: member.displayName,
...(member.gameName ? { gameName: member.gameName } : {}),
...(member.tagLine ? { tagLine: member.tagLine } : {}),
...(member.profileIconId !== undefined
? { profileIconId: member.profileIconId }
: {}),
...(member.assignedPosition
? { assignedPosition: member.assignedPosition as PlayerPosition }
: {}),
...(member.cost !== undefined ? { cost: member.cost } : {}),
})),
})),
format: toWireValue(source.format) as CompetitionFormat,
projection: toWireValue(source.projection) as CompetitionProjection,
createdAt: asIsoDateTime(source.createdAt),
updatedAt: asIsoDateTime(source.updatedAt),
};
}
function asId<T extends string>(value: IdLike): T {
return value.toString() as T;
}
function asIsoDateTime(value: Date | string): string {
return value instanceof Date ? value.toISOString() : value;
}
function toWireValue(value: unknown): unknown {
if (value instanceof Date) return value.toISOString();
if (Array.isArray(value)) return value.map(toWireValue);
if (isPlainRecord(value)) {
return Object.fromEntries(
Object.entries(value).map(([key, entry]) => [key, toWireValue(entry)]),
);
}
return value;
}
function isPlainRecord(value: unknown): value is Record<string, unknown> {
return (
typeof value === 'object' &&
value !== null &&
Object.getPrototypeOf(value) === Object.prototype
);
}
@@ -0,0 +1,145 @@
import {
COMPETITION_OUTBOX_STATES,
CompetitionFactSchema,
CompetitionOutboxSchema,
CompetitionSchema,
TournamentCodeAssignmentSchema,
competitionModelDefinitions,
} from './competition.schema';
import {
MatchSchema,
MatchStatsSchema,
tournamentModelDefinitions,
} from '../global/database/schema';
describe('Competition persistence schemas', () => {
it('registers every Competition-owned collection', () => {
expect(
competitionModelDefinitions.map(({ name, schemaName }) => ({
name,
schemaName,
})),
).toEqual([
{ name: 'competition', schemaName: 'competition' },
{ name: 'competitionFact', schemaName: 'competition_fact' },
{ name: 'competitionOutbox', schemaName: 'competition_outbox' },
{
name: 'tournamentCodeAssignment',
schemaName: 'tournament_code_assignment',
},
]);
expect(tournamentModelDefinitions).toEqual(
expect.arrayContaining(
competitionModelDefinitions.map(({ name, schemaName }) =>
expect.objectContaining({ name, schemaName }),
),
),
);
});
it('links Match and stats projections to the Competition revision', () => {
expect(MatchSchema.path('competitionId')).toBeDefined();
expect(MatchStatsSchema.path('sourceCompetitionId')).toBeDefined();
expect(MatchStatsSchema.path('sourceRevision')).toBeDefined();
expect(MatchStatsSchema.path('projectorVersion')).toBeDefined();
expectIndexes(MatchSchema, [
{
keys: { competitionId: 1 },
options: { unique: true },
},
]);
});
it('enforces one Competition per Match and monotonic revisions', () => {
expectIndexes(CompetitionSchema, [
{
keys: { matchId: 1 },
options: { unique: true },
},
{
keys: { communityId: 1, phase: 1, updatedAt: -1 },
},
]);
});
it('makes fact ordering and command replay identities unique', () => {
expect(CompetitionFactSchema.path('startedAt')).toBeDefined();
expect(CompetitionFactSchema.path('durationSeconds')).toBeDefined();
expect(CompetitionFactSchema.path('participants')).toBeDefined();
expectIndexes(CompetitionFactSchema, [
{
keys: { competitionId: 1, revision: 1, ordinalWithinRevision: 1 },
options: { unique: true },
},
{
keys: { competitionId: 1, commandId: 1, ordinalWithinRevision: 1 },
options: { unique: true },
},
{
keys: { 'evidence.riotMatchId': 1 },
options: { unique: true },
},
]);
});
it('prevents duplicate outbox events', () => {
expectIndexes(CompetitionOutboxSchema, [
{
keys: { eventId: 1 },
options: { unique: true },
},
{
keys: { state: 1, availableAt: 1 },
},
]);
});
it('defines a terminal dead-letter state for poison outbox events', () => {
expect(COMPETITION_OUTBOX_STATES).toContain('dead-letter');
expect(CompetitionOutboxSchema.path('state').options.enum).toContain(
'dead-letter',
);
});
it('allows only one active assignment for a code or GameSlot', () => {
expectIndexes(TournamentCodeAssignmentSchema, [
{
keys: { gameSlotId: 1 },
options: {
unique: true,
partialFilterExpression: { state: { $in: ['reserved', 'used'] } },
},
},
{
keys: { tournamentCodeId: 1 },
options: {
unique: true,
partialFilterExpression: { state: { $in: ['reserved', 'used'] } },
},
},
{
keys: { riotMatchId: 1 },
options: { unique: true },
},
]);
});
});
function expectIndexes(
schema: {
indexes(): Array<[Record<string, number>, Record<string, unknown>]>;
},
expected: Array<{
keys: Record<string, number>;
options?: Record<string, unknown>;
}>,
) {
const indexes = schema.indexes();
for (const candidate of expected) {
expect(indexes).toEqual(
expect.arrayContaining([
[candidate.keys, expect.objectContaining(candidate.options ?? {})],
]),
);
}
}
@@ -0,0 +1,457 @@
import mongoose, { HydratedDocument, Schema } from 'mongoose';
export const COMPETITION_PHASES = [
'ready',
'running',
'completed',
'cancelled',
] as const;
export type CompetitionPhase = (typeof COMPETITION_PHASES)[number];
export const COMPETITION_FACT_TYPES = [
'game-accepted',
'game-voided',
'series-adjudicated',
'adjudication-reversed',
] as const;
export type CompetitionFactType = (typeof COMPETITION_FACT_TYPES)[number];
export const COMPETITION_OUTBOX_STATES = [
'pending',
'published',
'failed',
'dead-letter',
] as const;
export type CompetitionOutboxState = (typeof COMPETITION_OUTBOX_STATES)[number];
export const TOURNAMENT_CODE_ASSIGNMENT_STATES = [
'reserved',
'used',
'released',
'voided',
] as const;
export type TournamentCodeAssignmentState =
(typeof TOURNAMENT_CODE_ASSIGNMENT_STATES)[number];
export interface CompetitionDomainInvariantIndex {
collection:
| 'match'
| 'competition'
| 'competition_fact'
| 'competition_outbox'
| 'tournament_code_assignment';
key: mongoose.IndexDefinition;
options: mongoose.IndexOptions & { name: string; unique: true };
}
/**
* Database-enforced Competition identities. Runtime schemas and the one-off
* migration consume this same list so production cannot silently run with a
* weaker set of uniqueness guarantees than command handling expects.
*/
export const COMPETITION_DOMAIN_INVARIANT_INDEXES: CompetitionDomainInvariantIndex[] =
[
{
collection: 'match',
key: { competitionId: 1 },
options: {
name: 'competitionId_1',
unique: true,
partialFilterExpression: {
competitionId: { $type: 'objectId' },
},
},
},
{
collection: 'competition',
key: { matchId: 1 },
options: { name: 'matchId_1', unique: true },
},
{
collection: 'competition_fact',
key: { competitionId: 1, revision: 1, ordinalWithinRevision: 1 },
options: {
name: 'competitionId_1_revision_1_ordinalWithinRevision_1',
unique: true,
},
},
{
collection: 'competition_fact',
key: { competitionId: 1, commandId: 1, ordinalWithinRevision: 1 },
options: {
name: 'competitionId_1_commandId_1_ordinalWithinRevision_1',
unique: true,
},
},
{
collection: 'competition_fact',
key: { 'evidence.riotMatchId': 1 },
options: {
name: 'evidence.riotMatchId_1',
unique: true,
partialFilterExpression: {
type: 'game-accepted',
'evidence.riotMatchId': { $type: 'string' },
},
},
},
{
collection: 'competition_outbox',
key: { eventId: 1 },
options: { name: 'eventId_1', unique: true },
},
{
collection: 'competition_outbox',
key: { competitionId: 1, idempotencyKey: 1 },
options: {
name: 'competitionId_1_idempotencyKey_1',
unique: true,
},
},
{
collection: 'tournament_code_assignment',
key: { gameSlotId: 1 },
options: {
name: 'gameSlotId_1',
unique: true,
partialFilterExpression: { state: { $in: ['reserved', 'used'] } },
},
},
{
collection: 'tournament_code_assignment',
key: { tournamentCodeId: 1 },
options: {
name: 'tournamentCodeId_1',
unique: true,
partialFilterExpression: { state: { $in: ['reserved', 'used'] } },
},
},
{
collection: 'tournament_code_assignment',
key: { riotMatchId: 1 },
options: {
name: 'riotMatchId_1',
unique: true,
partialFilterExpression: { riotMatchId: { $type: 'string' } },
},
},
];
export interface CompetitionTeamMemberSnapshot {
userId: mongoose.Types.ObjectId;
displayName: string;
gameName?: string;
tagLine?: string;
profileIconId?: number;
assignedPosition?: string;
cost?: number;
}
export interface CompetitionTeamSnapshot {
teamId: mongoose.Types.ObjectId;
legacyTeamIndex?: number;
displayOrder: number;
seedNumber: number;
name: string;
captainUserId?: mongoose.Types.ObjectId;
members: CompetitionTeamMemberSnapshot[];
}
export interface Competition {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
schemaVersion: number;
projectorVersion: number;
revision: number;
phase: CompetitionPhase;
teams: CompetitionTeamSnapshot[];
format: Record<string, unknown>;
seriesGraph: Array<Record<string, unknown>>;
projection: Record<string, unknown>;
createdAt: Date;
updatedAt: Date;
}
export type CompetitionDocument = HydratedDocument<Competition>;
export interface CompetitionFact {
competitionId: mongoose.Types.ObjectId;
type: CompetitionFactType;
revision: number;
ordinalWithinRevision: number;
commandId: string;
idempotencyKey: string;
requestHash: string;
schemaVersion: number;
actor: Record<string, unknown>;
occurredAt: Date;
recordedAt: Date;
causationId?: string;
gameId?: mongoose.Types.ObjectId;
seriesId?: mongoose.Types.ObjectId;
gameSlotId?: mongoose.Types.ObjectId;
ordinal?: number;
startedAt?: Date;
durationSeconds?: number;
participants?: Array<Record<string, unknown>>;
evidence?: Record<string, unknown>;
mapping?: Record<string, unknown>;
gameAcceptedFactId?: mongoose.Types.ObjectId;
adjudicationFactId?: mongoose.Types.ObjectId;
decision?: Record<string, unknown>;
reason?: string;
createdAt: Date;
updatedAt: Date;
}
export type CompetitionFactDocument = HydratedDocument<CompetitionFact>;
export interface CompetitionOutbox {
eventId: string;
competitionId: mongoose.Types.ObjectId;
revision: number;
commandId: string;
idempotencyKey: string;
requestHash: string;
type: string;
payload: Record<string, unknown>;
state: CompetitionOutboxState;
attemptCount: number;
availableAt: Date;
publishedAt?: Date;
lastError?: string;
createdAt: Date;
updatedAt: Date;
}
export type CompetitionOutboxDocument = HydratedDocument<CompetitionOutbox>;
export interface TournamentCodeAssignment {
competitionId: mongoose.Types.ObjectId;
seriesId: mongoose.Types.ObjectId;
gameSlotId: mongoose.Types.ObjectId;
tournamentCodeId: mongoose.Types.ObjectId;
state: TournamentCodeAssignmentState;
reservedAt: Date;
usedAt?: Date;
releasedAt?: Date;
voidedAt?: Date;
riotMatchId?: string;
commandId: string;
createdAt: Date;
updatedAt: Date;
}
export type TournamentCodeAssignmentDocument =
HydratedDocument<TournamentCodeAssignment>;
const CompetitionTeamMemberSchema = new Schema<CompetitionTeamMemberSnapshot>(
{
userId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
displayName: { type: String, required: true },
gameName: { type: String },
tagLine: { type: String },
profileIconId: { type: Number },
assignedPosition: { type: String },
cost: { type: Number },
},
{ _id: false },
);
const CompetitionTeamSchema = new Schema<CompetitionTeamSnapshot>(
{
teamId: { type: Schema.Types.ObjectId, required: true },
legacyTeamIndex: { type: Number, min: 1 },
displayOrder: { type: Number, required: true, min: 1 },
seedNumber: { type: Number, required: true, min: 1 },
name: { type: String, required: true },
captainUserId: { type: Schema.Types.ObjectId, ref: 'user' },
members: {
type: [CompetitionTeamMemberSchema],
required: true,
default: [],
},
},
{ _id: false },
);
export const CompetitionSchema: mongoose.Schema<Competition> =
new Schema<Competition>(
{
matchId: {
type: Schema.Types.ObjectId,
ref: 'match',
required: true,
},
communityId: {
type: Schema.Types.ObjectId,
ref: 'community',
required: true,
},
schemaVersion: { type: Number, required: true, min: 1 },
projectorVersion: { type: Number, required: true, min: 1 },
revision: { type: Number, required: true, min: 0, default: 0 },
phase: {
type: String,
enum: COMPETITION_PHASES,
required: true,
default: 'ready',
},
teams: { type: [CompetitionTeamSchema], required: true },
format: { type: Schema.Types.Mixed, required: true },
seriesGraph: { type: Schema.Types.Mixed, required: true },
projection: { type: Schema.Types.Mixed, required: true },
},
{ timestamps: true, collection: 'competition' },
);
applyCompetitionDomainInvariantIndexes(CompetitionSchema, 'competition');
CompetitionSchema.index({ communityId: 1, phase: 1, updatedAt: -1 });
export const CompetitionFactSchema = new Schema<CompetitionFact>(
{
competitionId: {
type: Schema.Types.ObjectId,
ref: 'competition',
required: true,
},
type: { type: String, enum: COMPETITION_FACT_TYPES, required: true },
revision: { type: Number, required: true, min: 1 },
ordinalWithinRevision: { type: Number, required: true, min: 1 },
commandId: { type: String, required: true },
idempotencyKey: { type: String, required: true },
requestHash: { type: String, required: true },
schemaVersion: { type: Number, required: true, min: 1 },
actor: { type: Schema.Types.Mixed, required: true },
occurredAt: { type: Date, required: true },
recordedAt: { type: Date, required: true },
causationId: { type: String },
gameId: { type: Schema.Types.ObjectId },
seriesId: { type: Schema.Types.ObjectId },
gameSlotId: { type: Schema.Types.ObjectId },
ordinal: { type: Number, min: 1 },
startedAt: { type: Date },
durationSeconds: { type: Number, min: 0 },
participants: { type: Schema.Types.Mixed },
evidence: { type: Schema.Types.Mixed },
mapping: { type: Schema.Types.Mixed },
gameAcceptedFactId: { type: Schema.Types.ObjectId },
adjudicationFactId: { type: Schema.Types.ObjectId },
decision: { type: Schema.Types.Mixed },
reason: { type: String },
},
{ timestamps: true, collection: 'competition_fact' },
);
applyCompetitionDomainInvariantIndexes(
CompetitionFactSchema,
'competition_fact',
);
CompetitionFactSchema.index({ competitionId: 1, seriesId: 1, recordedAt: 1 });
export const CompetitionOutboxSchema = new Schema<CompetitionOutbox>(
{
eventId: { type: String, required: true },
competitionId: {
type: Schema.Types.ObjectId,
ref: 'competition',
required: true,
},
revision: { type: Number, required: true, min: 1 },
commandId: { type: String, required: true },
idempotencyKey: { type: String, required: true },
requestHash: { type: String, required: true },
type: { type: String, required: true },
payload: { type: Schema.Types.Mixed, required: true },
state: {
type: String,
enum: COMPETITION_OUTBOX_STATES,
required: true,
default: 'pending',
},
attemptCount: { type: Number, required: true, min: 0, default: 0 },
availableAt: { type: Date, required: true },
publishedAt: { type: Date },
lastError: { type: String },
},
{ timestamps: true, collection: 'competition_outbox' },
);
applyCompetitionDomainInvariantIndexes(
CompetitionOutboxSchema,
'competition_outbox',
);
CompetitionOutboxSchema.index({ state: 1, availableAt: 1 });
export const TournamentCodeAssignmentSchema =
new Schema<TournamentCodeAssignment>(
{
competitionId: {
type: Schema.Types.ObjectId,
ref: 'competition',
required: true,
},
seriesId: { type: Schema.Types.ObjectId, required: true },
gameSlotId: { type: Schema.Types.ObjectId, required: true },
tournamentCodeId: {
type: Schema.Types.ObjectId,
ref: 'tournamentCode',
required: true,
},
state: {
type: String,
enum: TOURNAMENT_CODE_ASSIGNMENT_STATES,
required: true,
},
reservedAt: { type: Date, required: true },
usedAt: { type: Date },
releasedAt: { type: Date },
voidedAt: { type: Date },
riotMatchId: { type: String },
commandId: { type: String, required: true },
},
{ timestamps: true, collection: 'tournament_code_assignment' },
);
applyCompetitionDomainInvariantIndexes(
TournamentCodeAssignmentSchema,
'tournament_code_assignment',
);
TournamentCodeAssignmentSchema.index({ competitionId: 1, state: 1 });
export function applyCompetitionDomainInvariantIndexes(
schema: mongoose.Schema,
collection: CompetitionDomainInvariantIndex['collection'],
): void {
for (const index of COMPETITION_DOMAIN_INVARIANT_INDEXES) {
if (index.collection !== collection) continue;
schema.index(index.key, index.options);
}
}
export const competitionModelDefinitions: Array<{
name: string;
schema: mongoose.Schema;
schemaName: string;
}> = [
{
name: 'competition',
schema: CompetitionSchema,
schemaName: 'competition',
},
{
name: 'competitionFact',
schema: CompetitionFactSchema,
schemaName: 'competition_fact',
},
{
name: 'competitionOutbox',
schema: CompetitionOutboxSchema,
schemaName: 'competition_outbox',
},
{
name: 'tournamentCodeAssignment',
schema: TournamentCodeAssignmentSchema,
schemaName: 'tournament_code_assignment',
},
];
@@ -0,0 +1,619 @@
import { projectCompetition } from './competition-projector';
import { generateSeriesGraph } from './series-graph';
describe('projectCompetition', () => {
it('keeps a three-way round-robin cycle on a shared rank', () => {
const competitionId = 'competition-round-robin-tie';
const teams = ['team-1', 'team-2', 'team-3'].map((teamId, index) => ({
teamId,
displayOrder: index + 1,
seedNumber: index + 1,
}));
const format = {
type: 'round-robin' as const,
rule: fixedGames(1),
tieBreakers: ['series-wins', 'game-diff', 'head-to-head'] as const,
};
const seriesGraph = generateSeriesGraph({
competitionId,
teams,
format,
});
const accept = acceptedGameFactory(competitionId);
const oneVersusTwo = requireRoundRobinSeries(
seriesGraph,
'team-1',
'team-2',
);
const oneVersusThree = requireRoundRobinSeries(
seriesGraph,
'team-1',
'team-3',
);
const twoVersusThree = requireRoundRobinSeries(
seriesGraph,
'team-2',
'team-3',
);
const facts = [
accept(oneVersusTwo, 1, 'team-1', 'team-2', 'team-1'),
accept(twoVersusThree, 1, 'team-2', 'team-3', 'team-2'),
accept(oneVersusThree, 1, 'team-3', 'team-1', 'team-3'),
];
const projection = projectCompetition({
competitionId,
revision: facts.length,
projectorVersion: 1,
teams,
format,
seriesGraph,
facts,
});
expect(projection.outcome).toEqual({
type: 'round-robin',
leaderTeamIds: ['team-1', 'team-2', 'team-3'],
standings: [
standing('team-1', 1),
standing('team-2', 1),
standing('team-3', 1),
],
completedAt: '2026-07-12T00:00:03.000Z',
});
expect(projection.games).toHaveLength(3);
expect(projection.gameSlots).toHaveLength(3);
expect(projection.rounds).toEqual(
expect.arrayContaining([
expect.objectContaining({ stage: 'round-robin', roundNumber: 1 }),
]),
);
});
it('attributes WB_R2_M2 wins to team ids when series and bracket slot orders differ', () => {
const competitionId = 'competition-wb-r2-m2-regression';
const teams = [
seededTeam('team-1', 1),
seededTeam('team-8', 2),
seededTeam('team-3', 3),
seededTeam('team-4', 4),
seededTeam('team-5', 5),
seededTeam('team-6', 6),
seededTeam('team-7', 7),
seededTeam('team-2', 8),
];
const format = doubleEliminationFormat({ upperWinsRequired: 2 });
const seriesGraph = generateSeriesGraph({
competitionId,
teams,
format,
});
const wbRoundOneMatchThree = requireSeries(seriesGraph, 'WB_R1_M3');
const wbRoundOneMatchFour = requireSeries(seriesGraph, 'WB_R1_M4');
const wbRoundTwoMatchTwo = requireSeries(seriesGraph, 'WB_R2_M2');
const accept = acceptedGameFactory(competitionId);
const facts = [
accept(wbRoundOneMatchThree, 1, 'team-8', 'team-7', 'team-8'),
accept(wbRoundOneMatchThree, 2, 'team-7', 'team-8', 'team-8'),
accept(wbRoundOneMatchFour, 1, 'team-3', 'team-6', 'team-3'),
accept(wbRoundOneMatchFour, 2, 'team-6', 'team-3', 'team-3'),
accept(wbRoundTwoMatchTwo, 1, 'team-3', 'team-8', 'team-8'),
accept(wbRoundTwoMatchTwo, 2, 'team-8', 'team-3', 'team-3'),
accept(wbRoundTwoMatchTwo, 3, 'team-3', 'team-8', 'team-8'),
];
const projection = projectCompetition({
competitionId,
revision: facts.length,
projectorVersion: 1,
teams,
format,
seriesGraph,
facts,
});
expect(projectedSeries(projection, 'WB_R2_M2')).toMatchObject({
status: 'completed',
entries: [
{ slot: 'A', teamId: 'team-8', gameWins: 2 },
{ slot: 'B', teamId: 'team-3', gameWins: 1 },
],
outcome: {
type: 'played',
winnerTeamId: 'team-8',
loserTeamId: 'team-3',
},
});
expect(projectedSeries(projection, 'WB_FINAL').entries).toContainEqual({
slot: 'B',
teamId: 'team-8',
gameWins: 0,
});
expect(projectedSeries(projection, 'LB_R2_M1').entries).toContainEqual({
slot: 'B',
teamId: 'team-3',
gameWins: 0,
});
expect(projection.games).toHaveLength(7);
expect(
projection.games.filter(
(game) => game.seriesId === wbRoundTwoMatchTwo.id,
),
).toEqual([
expect.objectContaining({ winnerTeamId: 'team-8', ordinal: 1 }),
expect.objectContaining({ winnerTeamId: 'team-3', ordinal: 2 }),
expect.objectContaining({ winnerTeamId: 'team-8', ordinal: 3 }),
]);
expect(
projection.connectors.some(
(connector) =>
connector.from.seriesId === wbRoundTwoMatchTwo.id &&
connector.from.select === 'winner' &&
connector.to.slot === 'B',
),
).toBe(true);
});
it('activates the predefined reset final only when the lower-bracket finalist wins GF', () => {
const competitionId = 'competition-grand-final-reset';
const teams = Array.from({ length: 4 }, (_, index) =>
seededTeam(`team-${index + 1}`, index + 1),
);
const format = doubleEliminationFormat({ upperWinsRequired: 1 });
const seriesGraph = generateSeriesGraph({
competitionId,
teams,
format,
});
const resetDefinition = requireSeries(seriesGraph, 'GF_RESET');
const initial = projectCompetition({
competitionId,
revision: 0,
projectorVersion: 1,
teams,
format,
seriesGraph,
facts: [],
});
expect(projectedSeries(initial, 'GF_RESET')).toMatchObject({
seriesId: resetDefinition.id,
status: 'inactive',
});
const accept = acceptedGameFactory(competitionId);
const facts = [
accept(
requireSeries(seriesGraph, 'WB_R1_M1'),
1,
'team-1',
'team-4',
'team-1',
),
accept(
requireSeries(seriesGraph, 'WB_R1_M2'),
1,
'team-2',
'team-3',
'team-2',
),
accept(
requireSeries(seriesGraph, 'WB_FINAL'),
1,
'team-1',
'team-2',
'team-1',
),
accept(
requireSeries(seriesGraph, 'LB_R1_M1'),
1,
'team-3',
'team-4',
'team-3',
),
accept(
requireSeries(seriesGraph, 'LB_FINAL'),
1,
'team-3',
'team-2',
'team-2',
),
accept(requireSeries(seriesGraph, 'GF'), 1, 'team-2', 'team-1', 'team-2'),
];
const afterGrandFinal = projectCompetition({
competitionId,
revision: facts.length,
projectorVersion: 1,
teams,
format,
seriesGraph,
facts,
});
expect(projectedSeries(afterGrandFinal, 'GF_RESET')).toMatchObject({
seriesId: resetDefinition.id,
status: 'ready',
entries: [
{ slot: 'A', teamId: 'team-1', gameWins: 0 },
{ slot: 'B', teamId: 'team-2', gameWins: 0 },
],
});
expect(afterGrandFinal).not.toHaveProperty('outcome');
expect(afterGrandFinal.gameSlots).toEqual(
expect.arrayContaining([
expect.objectContaining({
seriesId: resetDefinition.id,
status: 'ready',
entries: [
{ slot: 'A', teamId: 'team-1' },
{ slot: 'B', teamId: 'team-2' },
],
}),
]),
);
});
it('makes a voided GameSlot ready again when its Series can be replayed', () => {
const competitionId = 'competition-replay-voided-slot';
const teams = [seededTeam('team-1', 1), seededTeam('team-2', 2)];
const format = {
type: 'paired-series' as const,
rule: fixedGames(1),
};
const seriesGraph = generateSeriesGraph({
competitionId,
teams,
format,
});
const definition = seriesGraph[0];
const accepted = acceptedGameFactory(competitionId)(
definition,
1,
'team-1',
'team-2',
'team-1',
);
const projection = projectCompetition({
competitionId,
revision: 2,
projectorVersion: 1,
teams,
format,
seriesGraph,
facts: [
accepted,
{
id: 'fact-void-game-1',
type: 'game-voided',
competitionId,
revision: 2,
ordinalWithinRevision: 1,
commandId: 'command-void-game-1',
schemaVersion: 1,
actor: { type: 'user' as const },
occurredAt: new Date('2026-07-12T00:00:02.000Z'),
recordedAt: new Date('2026-07-12T00:01:02.000Z'),
gameAcceptedFactId: accepted.id,
reason: 'Incorrect Riot evidence',
},
],
});
expect(projection.phase).toBe('ready');
expect(projection.series[0]).toMatchObject({ status: 'ready' });
expect(projection.gameSlots[0]).toMatchObject({ status: 'ready' });
expect(projection.games).toEqual([]);
});
it('rejects an accepted game that targets a Series outside the graph', () => {
const competitionId = 'competition-unknown-game-series';
const teams = [seededTeam('team-1', 1), seededTeam('team-2', 2)];
const format = {
type: 'paired-series' as const,
rule: fixedGames(1),
};
const seriesGraph = generateSeriesGraph({ competitionId, teams, format });
const accepted = acceptedGameFactory(competitionId)(
seriesGraph[0],
1,
'team-1',
'team-2',
'team-1',
);
expect(() =>
projectCompetition({
competitionId,
revision: 1,
projectorVersion: 1,
teams,
format,
seriesGraph,
facts: [{ ...accepted, seriesId: 'series-does-not-exist' }],
}),
).toThrow(
expect.objectContaining({
code: 'GAME_SERIES_MISMATCH',
}),
);
});
it('rejects an accepted game that targets an unknown GameSlot', () => {
const competitionId = 'competition-unknown-game-slot';
const teams = [seededTeam('team-1', 1), seededTeam('team-2', 2)];
const format = {
type: 'paired-series' as const,
rule: fixedGames(1),
};
const seriesGraph = generateSeriesGraph({ competitionId, teams, format });
const accepted = acceptedGameFactory(competitionId)(
seriesGraph[0],
1,
'team-1',
'team-2',
'team-1',
);
expect(() =>
projectCompetition({
competitionId,
revision: 1,
projectorVersion: 1,
teams,
format,
seriesGraph,
facts: [{ ...accepted, gameSlotId: 'slot-does-not-exist' }],
}),
).toThrow(
expect.objectContaining({
code: 'GAME_SLOT_INVALID',
}),
);
});
it('rejects an adjudication that targets a Series outside the graph', () => {
const competitionId = 'competition-unknown-adjudication-series';
const teams = [seededTeam('team-1', 1), seededTeam('team-2', 2)];
const format = {
type: 'paired-series' as const,
rule: fixedGames(1),
};
const seriesGraph = generateSeriesGraph({ competitionId, teams, format });
expect(() =>
projectCompetition({
competitionId,
revision: 1,
projectorVersion: 1,
teams,
format,
seriesGraph,
facts: [
{
id: 'fact-unknown-adjudication-series',
type: 'series-adjudicated',
competitionId,
revision: 1,
ordinalWithinRevision: 1,
commandId: 'command-unknown-adjudication-series',
schemaVersion: 1,
actor: { type: 'user' },
occurredAt: new Date('2026-07-12T00:00:01.000Z'),
recordedAt: new Date('2026-07-12T00:00:02.000Z'),
seriesId: 'series-does-not-exist',
decision: { type: 'administrative', winnerTeamId: 'team-1' },
reason: 'Manual correction',
},
],
}),
).toThrow(
expect.objectContaining({
code: 'ADJUDICATION_INVALID',
}),
);
});
it('completes an eight-team double elimination with shared elimination-round placements', () => {
const competitionId = 'competition-eight-team-completion';
const teams = Array.from({ length: 8 }, (_, index) =>
seededTeam(`team-${index + 1}`, index + 1),
);
const format = doubleEliminationFormat({ upperWinsRequired: 1 });
const seriesGraph = generateSeriesGraph({ competitionId, teams, format });
const accept = acceptedGameFactory(competitionId);
const facts: ReturnType<typeof accept>[] = [];
let projection = projectCompetition({
competitionId,
revision: 0,
projectorVersion: 1,
teams,
format,
seriesGraph,
facts,
});
for (let guard = 0; projection.phase !== 'completed'; guard += 1) {
if (guard > seriesGraph.length) {
throw new Error('Double-elimination projection did not converge.');
}
const playable = projection.series.find(
(series) => series.status === 'ready',
);
if (!playable) throw new Error('Missing playable Series.');
const definition = seriesGraph.find(
(series) => series.id === playable.seriesId,
);
const [entryA, entryB] = playable.entries;
if (!definition || !entryA.teamId || !entryB.teamId) {
throw new Error('Playable Series has unresolved participants.');
}
facts.push(
accept(definition, 1, entryA.teamId, entryB.teamId, entryA.teamId),
);
projection = projectCompetition({
competitionId,
revision: facts.length,
projectorVersion: 1,
teams,
format,
seriesGraph,
facts,
});
}
expect(projection.outcome?.type).toBe('double-elimination');
if (projection.outcome?.type !== 'double-elimination') {
throw new Error('Expected a double-elimination outcome.');
}
expect(typeof projection.outcome.championTeamId).toBe('string');
expect(projection.outcome.placements).toHaveLength(8);
expect(projection.placements?.map(({ rank }) => rank)).toEqual([
1, 2, 3, 4, 5, 5, 7, 7,
]);
});
});
function fixedGames(gameCount: number) {
return {
type: 'fixed-games' as const,
gameCount,
drawPolicy: 'allow' as const,
};
}
function seededTeam(teamId: string, seedNumber: number) {
return { teamId, displayOrder: seedNumber, seedNumber };
}
function doubleEliminationFormat(params: { upperWinsRequired: 1 | 2 }) {
const upper =
params.upperWinsRequired === 1
? { type: 'first-to' as const, winsRequired: 1, maxGames: 1 }
: { type: 'first-to' as const, winsRequired: 2, maxGames: 3 };
const singleGame = {
type: 'first-to' as const,
winsRequired: 1,
maxGames: 1,
};
return {
type: 'double-elimination' as const,
resetFinalEnabled: true,
rules: {
upper,
lower: singleGame,
grandFinal: singleGame,
resetFinal: singleGame,
},
};
}
function requireSeries<
T extends { code?: string; id: string; gameSlots: Array<GameSlotLike> },
>(graph: T[], code: string): T {
const definition = graph.find((series) => series.code === code);
if (!definition) throw new Error(`Missing series ${code}`);
return definition;
}
function requireRoundRobinSeries<
T extends {
id: string;
gameSlots: Array<GameSlotLike>;
slots: Array<{ source: { type: string; teamId?: string } }>;
},
>(graph: T[], leftTeamId: string, rightTeamId: string): T {
const expected = new Set([leftTeamId, rightTeamId]);
const definition = graph.find((series) => {
const actual = series.slots
.filter((slot) => slot.source.type === 'team')
.map((slot) => slot.source.teamId);
return (
actual.length === 2 && actual.every((teamId) => expected.has(teamId!))
);
});
if (!definition) {
throw new Error(`Missing round-robin series ${leftTeamId}/${rightTeamId}`);
}
return definition;
}
function acceptedGameFactory(competitionId: string) {
let revision = 0;
return <T extends { id: string; gameSlots: Array<GameSlotLike> }>(
definition: T,
ordinal: number,
blueTeamId: string,
redTeamId: string,
winnerTeamId: string,
) => {
revision += 1;
const gameSlot = definition.gameSlots.find(
(candidate) => candidate.ordinal === ordinal,
);
if (!gameSlot) {
throw new Error(`Missing game slot ${definition.id}/${ordinal}`);
}
return {
id: `fact-${revision}`,
type: 'game-accepted' as const,
competitionId,
revision,
ordinalWithinRevision: 1,
commandId: `command-${revision}`,
schemaVersion: 1,
actor: { type: 'system' as const },
occurredAt: new Date(
`2026-07-12T00:00:${String(revision).padStart(2, '0')}.000Z`,
),
recordedAt: new Date(
`2026-07-12T00:01:${String(revision).padStart(2, '0')}.000Z`,
),
gameId: `game-${revision}`,
seriesId: definition.id,
gameSlotId: gameSlot.id,
ordinal,
evidence: {
type: 'riot' as const,
riotMatchId: `KR_${competitionId}_${revision}`,
payloadHash: `sha256:${competitionId}:${revision}`,
},
mapping: {
mappingVersion: 1,
confidence: 1,
blueTeamId,
redTeamId,
winnerTeamId,
participantAssignments: [],
},
};
};
}
function projectedSeries<
T extends { series: Array<{ code?: string; seriesId: string }> },
>(projection: T, code: string) {
const series = projection.series.find((candidate) => candidate.code === code);
if (!series) throw new Error(`Missing projected series ${code}`);
return series;
}
function standing(teamId: string, rank: number) {
return {
teamId,
rank,
seriesPlayed: 2,
seriesWins: 1,
seriesLosses: 1,
seriesDraws: 0,
gameWins: 1,
gameLosses: 1,
gameDiff: 0,
};
}
interface GameSlotLike {
id: string;
ordinal: number;
}
@@ -0,0 +1,995 @@
import { assertCompetitionInvariant } from './domain-error';
import type {
CompetitionGraphFormat,
CompetitionGraphTeam,
ParticipantSource,
SeriesDefinition,
} from './series-graph';
import {
projectSeries,
type SeriesDefinitionLike,
type SeriesProjection,
type SeriesProjectionOutcome,
} from './series-projector';
export interface ProjectCompetitionInput {
competitionId: string;
revision: number;
projectorVersion: number;
teams: readonly CompetitionGraphTeam[];
format: CompetitionGraphFormat;
seriesGraph: readonly SeriesDefinition[];
facts: readonly unknown[];
}
export interface RoundRobinStanding {
teamId: string;
rank: number;
seriesPlayed: number;
seriesWins: number;
seriesLosses: number;
seriesDraws: number;
gameWins: number;
gameLosses: number;
gameDiff: number;
}
export interface CompetitionPlacement {
teamId: string;
rank: number;
}
export interface CompetitionGameProjection {
id: string;
seriesId: string;
gameSlotId: string;
ordinal: number;
displayNumber: number;
evidence:
| { type: 'riot'; riotMatchId: string }
| { type: 'legacy'; legacyReference: string };
teams: {
blue: { side: 'blue'; teamId: string };
red: { side: 'red'; teamId: string };
};
winnerTeamId: string;
startedAt: string;
durationSeconds: number;
participants: unknown[];
}
export interface GameSlotProjection {
id: string;
seriesId: string;
ordinal: number;
displayNumber: number;
status: 'inactive' | 'waiting' | 'ready' | 'completed' | 'voided';
entries: [
{ slot: 'A'; teamId: string | null },
{ slot: 'B'; teamId: string | null },
];
gameId?: string;
}
export interface BracketRoundProjection {
stage: SeriesDefinition['stage']['type'];
roundNumber?: number;
displayOrder: number;
label: string;
seriesIds: string[];
}
export interface SeriesConnectorProjection {
from: {
seriesId: string;
select: 'winner' | 'loser' | 'slot-a' | 'slot-b';
};
to: { seriesId: string; slot: 'A' | 'B' };
}
export type CompetitionProjectionOutcome =
| {
type: 'paired-series';
completedSeriesIds: string[];
drawnSeriesIds: string[];
completedAt: string;
}
| {
type: 'round-robin';
leaderTeamIds: string[];
standings: RoundRobinStanding[];
completedAt: string;
}
| {
type: 'double-elimination';
championTeamId: string;
placements: CompetitionPlacement[];
completedAt: string;
};
export interface CompetitionProjection {
competitionId: string;
sourceRevision: number;
projectorVersion: number;
formatType: CompetitionGraphFormat['type'];
phase: 'ready' | 'running' | 'completed';
series: SeriesProjection[];
games: CompetitionGameProjection[];
gameSlots: GameSlotProjection[];
rounds: BracketRoundProjection[];
connectors: SeriesConnectorProjection[];
standings?: RoundRobinStanding[];
placements?: CompetitionPlacement[];
outcome?: CompetitionProjectionOutcome;
}
/**
* Rebuilds all official Competition state from the immutable graph and fact
* ledger. Participant identity is always resolved through explicit sources;
* display codes and slot/array order are never used as team identity.
*/
export function projectCompetition(
input: ProjectCompetitionInput,
): CompetitionProjection {
assertPrimaryFactTargetsGraph(input.seriesGraph, input.facts);
const teamBySeed = new Map<number, string>();
const knownTeams = new Set<string>();
for (const team of input.teams) {
knownTeams.add(team.teamId);
if (team.seedNumber !== undefined) {
teamBySeed.set(team.seedNumber, team.teamId);
}
}
const definitionsById = new Map(
input.seriesGraph.map((definition) => [definition.id, definition]),
);
const projectedById = new Map<string, SeriesProjection>();
const remaining = new Set(input.seriesGraph.map(({ id }) => id));
// A graph can be stored in any display order. Resolve it as a DAG rather
// than relying on that order or parsing diagnostic codes such as WB_R2_M2.
let madeProgress = true;
while (remaining.size > 0 && madeProgress) {
madeProgress = false;
for (const seriesId of [...remaining]) {
const definition = definitionsById.get(seriesId)!;
const activation = resolveActivation(definition, projectedById);
if (activation === 'pending') continue;
if (activation === 'inactive') {
projectedById.set(
definition.id,
projectSeries({
definition: asProjectorDefinition(definition),
participants: resolveAvailableParticipants(
definition,
knownTeams,
teamBySeed,
projectedById,
),
facts: input.facts,
active: false,
}),
);
remaining.delete(seriesId);
madeProgress = true;
continue;
}
const participants = definition.slots.map(({ source }) =>
resolveParticipant(source, knownTeams, teamBySeed, projectedById),
);
if (participants.some((teamId) => teamId === undefined)) continue;
projectedById.set(
definition.id,
projectSeries({
definition: asProjectorDefinition(definition),
participants,
facts: input.facts,
}),
);
remaining.delete(seriesId);
madeProgress = true;
}
}
// An unresolved outcome source is a normal waiting bracket node. Conditional
// reset nodes remain inactive until their grand-final condition is known.
for (const seriesId of remaining) {
const definition = definitionsById.get(seriesId)!;
const participants = resolveAvailableParticipants(
definition,
knownTeams,
teamBySeed,
projectedById,
);
projectedById.set(
definition.id,
projectSeries({
definition: asProjectorDefinition(definition),
participants,
facts: input.facts,
...(definition.activation ? { active: false } : {}),
}),
);
}
const series = input.seriesGraph.map(({ id }) => projectedById.get(id)!);
const gameProjection = projectGamesAndSlots(
input.seriesGraph,
series,
input.facts,
);
const common = {
competitionId: input.competitionId,
sourceRevision: input.revision,
projectorVersion: input.projectorVersion,
formatType: input.format.type,
series,
games: gameProjection.games,
gameSlots: gameProjection.gameSlots,
rounds: projectRounds(input.seriesGraph),
connectors: projectConnectors(input.seriesGraph),
};
switch (input.format.type) {
case 'paired-series': {
const outcome = pairedSeriesOutcome(series);
return {
...common,
phase: phaseFor(series, outcome),
...(outcome ? { outcome } : {}),
};
}
case 'round-robin': {
const standings = roundRobinStandings(input.teams, series);
const outcome =
series.length > 0 &&
series.every(({ status }) => status === 'completed')
? {
type: 'round-robin' as const,
leaderTeamIds: standings
.filter(({ rank }) => rank === 1)
.map(({ teamId }) => teamId),
standings,
completedAt: competitionCompletedAt(series),
}
: undefined;
return {
...common,
phase: phaseFor(series, outcome),
standings,
...(outcome ? { outcome } : {}),
};
}
case 'double-elimination': {
const outcome = doubleEliminationOutcome(
input.teams,
input.format.resetFinalEnabled,
series,
);
return {
...common,
phase: phaseFor(series, outcome),
placements: outcome?.placements ?? [],
...(outcome ? { outcome } : {}),
};
}
}
}
function assertPrimaryFactTargetsGraph(
graph: readonly SeriesDefinition[],
facts: readonly unknown[],
): void {
const definitionsById = new Map(
graph.map((definition) => [definition.id, definition]),
);
for (const fact of facts) {
if (!isRecord(fact)) continue;
if (fact.type === 'game-accepted') {
const seriesId =
typeof fact.seriesId === 'string' ? fact.seriesId : undefined;
const definition = seriesId ? definitionsById.get(seriesId) : undefined;
assertCompetitionInvariant(
definition !== undefined,
'GAME_SERIES_MISMATCH',
`Accepted game targets an unknown Series ${String(fact.seriesId)}`,
{ factId: fact.id, seriesId: fact.seriesId },
);
const gameSlot = definition.gameSlots.find(
({ id }) => id === fact.gameSlotId,
);
assertCompetitionInvariant(
gameSlot !== undefined,
'GAME_SLOT_INVALID',
`Accepted game targets an unknown GameSlot ${String(fact.gameSlotId)}`,
{
factId: fact.id,
seriesId: definition.id,
gameSlotId: fact.gameSlotId,
},
);
assertCompetitionInvariant(
gameSlot.ordinal === fact.ordinal,
'GAME_ORDINAL_INVALID',
`Accepted game ordinal does not match GameSlot ${gameSlot.id}`,
{
factId: fact.id,
gameSlotId: gameSlot.id,
expectedOrdinal: gameSlot.ordinal,
actualOrdinal: fact.ordinal,
},
);
continue;
}
if (fact.type === 'series-adjudicated') {
const seriesId =
typeof fact.seriesId === 'string' ? fact.seriesId : undefined;
assertCompetitionInvariant(
seriesId !== undefined && definitionsById.has(seriesId),
'ADJUDICATION_INVALID',
`Adjudication targets an unknown Series ${String(fact.seriesId)}`,
{ factId: fact.id, seriesId: fact.seriesId },
);
}
}
}
function asProjectorDefinition(
definition: SeriesDefinition,
): SeriesDefinitionLike {
return definition as unknown as SeriesDefinitionLike;
}
function resolveActivation(
definition: SeriesDefinition,
projections: ReadonlyMap<string, SeriesProjection>,
): 'active' | 'inactive' | 'pending' {
if (!definition.activation) return 'active';
const grandFinal = projections.get(definition.activation.grandFinalSeriesId);
if (!grandFinal || grandFinal.status !== 'completed') return 'pending';
if (grandFinal.outcome.type === 'draw') return 'inactive';
const lowerBracketFinalist = grandFinal.entries.find(
({ slot }) => slot === 'B',
)?.teamId;
return grandFinal.outcome.winnerTeamId === lowerBracketFinalist
? 'active'
: 'inactive';
}
function resolveAvailableParticipants(
definition: SeriesDefinition,
knownTeams: ReadonlySet<string>,
teamBySeed: ReadonlyMap<number, string>,
projections: ReadonlyMap<string, SeriesProjection>,
): Array<string | null> {
return definition.slots.map(
({ source }) =>
resolveParticipant(source, knownTeams, teamBySeed, projections) ?? null,
);
}
function resolveParticipant(
source: ParticipantSource,
knownTeams: ReadonlySet<string>,
teamBySeed: ReadonlyMap<number, string>,
projections: ReadonlyMap<string, SeriesProjection>,
): string | undefined {
switch (source.type) {
case 'team':
return knownTeams.has(source.teamId) ? source.teamId : undefined;
case 'seed':
return teamBySeed.get(source.seedNumber);
case 'series-outcome': {
const sourceSeries = projections.get(source.seriesId);
if (!sourceSeries || sourceSeries.status !== 'completed') {
return undefined;
}
if (sourceSeries.outcome.type === 'draw') return undefined;
return source.select === 'winner'
? sourceSeries.outcome.winnerTeamId
: sourceSeries.outcome.loserTeamId;
}
case 'series-slot': {
const sourceSeries = projections.get(source.seriesId);
return (
sourceSeries?.entries.find(({ slot }) => slot === source.slot)
?.teamId ?? undefined
);
}
}
}
function pairedSeriesOutcome(
series: readonly SeriesProjection[],
):
| Extract<CompetitionProjectionOutcome, { type: 'paired-series' }>
| undefined {
if (
series.length === 0 ||
!series.every(({ status }) => status === 'completed')
) {
return undefined;
}
return {
type: 'paired-series',
completedSeriesIds: series
.filter(
(candidate) =>
candidate.status === 'completed' && candidate.outcome.type !== 'draw',
)
.map(({ seriesId }) => seriesId),
completedAt: competitionCompletedAt(series),
drawnSeriesIds: series
.filter(
(candidate) =>
candidate.status === 'completed' && candidate.outcome.type === 'draw',
)
.map(({ seriesId }) => seriesId),
};
}
function roundRobinStandings(
teams: readonly CompetitionGraphTeam[],
series: readonly SeriesProjection[],
): RoundRobinStanding[] {
const standingByTeam = new Map(
teams.map((team) => [team.teamId, emptyStanding(team.teamId)]),
);
const completed = series.filter(
(candidate): candidate is SeriesProjection & { status: 'completed' } =>
candidate.status === 'completed',
);
for (const projected of completed) {
addSeriesToStandings(standingByTeam, projected);
}
const displayOrderByTeam = new Map(
teams.map(({ teamId, displayOrder }) => [teamId, displayOrder]),
);
const base = [...standingByTeam.values()].sort(
(left, right) =>
right.seriesWins - left.seriesWins ||
right.gameDiff - left.gameDiff ||
stableTeamOrder(left.teamId, right.teamId, displayOrderByTeam),
);
const ranked: RoundRobinStanding[] = [];
let start = 0;
while (start < base.length) {
let end = start + 1;
while (
end < base.length &&
base[end].seriesWins === base[start].seriesWins &&
base[end].gameDiff === base[start].gameDiff
) {
end += 1;
}
const tiedGroup = base.slice(start, end);
const teamIds = new Set(tiedGroup.map(({ teamId }) => teamId));
const miniTable = new Map(
tiedGroup.map(({ teamId }) => [teamId, emptyMiniTableRow()]),
);
for (const projected of completed) {
const participants = projected.entries.map(({ teamId }) => teamId);
if (
participants.length === 2 &&
participants.every(
(teamId): teamId is string => teamId !== null && teamIds.has(teamId),
)
) {
addSeriesToMiniTable(miniTable, projected);
}
}
tiedGroup.sort((left, right) => {
const leftMini = miniTable.get(left.teamId)!;
const rightMini = miniTable.get(right.teamId)!;
return (
rightMini.seriesWins - leftMini.seriesWins ||
rightMini.gameDiff - leftMini.gameDiff ||
stableTeamOrder(left.teamId, right.teamId, displayOrderByTeam)
);
});
let tiedStart = 0;
while (tiedStart < tiedGroup.length) {
const reference = miniTable.get(tiedGroup[tiedStart].teamId)!;
let tiedEnd = tiedStart + 1;
while (tiedEnd < tiedGroup.length) {
const candidate = miniTable.get(tiedGroup[tiedEnd].teamId)!;
if (
candidate.seriesWins !== reference.seriesWins ||
candidate.gameDiff !== reference.gameDiff
) {
break;
}
tiedEnd += 1;
}
const rank = start + tiedStart + 1;
for (const standing of tiedGroup.slice(tiedStart, tiedEnd)) {
ranked.push({ ...standing, rank });
}
tiedStart = tiedEnd;
}
start = end;
}
return ranked;
}
function emptyStanding(teamId: string): RoundRobinStanding {
return {
teamId,
rank: 0,
seriesWins: 0,
seriesLosses: 0,
seriesDraws: 0,
seriesPlayed: 0,
gameWins: 0,
gameLosses: 0,
gameDiff: 0,
};
}
function addSeriesToStandings(
rows: Map<string, RoundRobinStanding>,
projected: SeriesProjection & { status: 'completed' },
): void {
const [entryA, entryB] = projected.entries;
if (entryA.teamId === null || entryB.teamId === null) return;
const rowA = rows.get(entryA.teamId);
const rowB = rows.get(entryB.teamId);
if (!rowA || !rowB) return;
rowA.gameWins += entryA.gameWins;
rowA.gameLosses += entryB.gameWins;
rowB.gameWins += entryB.gameWins;
rowB.gameLosses += entryA.gameWins;
rowA.gameDiff = rowA.gameWins - rowA.gameLosses;
rowB.gameDiff = rowB.gameWins - rowB.gameLosses;
rowA.seriesPlayed += 1;
rowB.seriesPlayed += 1;
if (projected.outcome.type === 'draw') {
rowA.seriesDraws += 1;
rowB.seriesDraws += 1;
return;
}
rows.get(projected.outcome.winnerTeamId)!.seriesWins += 1;
rows.get(projected.outcome.loserTeamId)!.seriesLosses += 1;
}
interface MiniTableRow {
seriesWins: number;
gameWins: number;
gameLosses: number;
gameDiff: number;
}
function emptyMiniTableRow(): MiniTableRow {
return { seriesWins: 0, gameWins: 0, gameLosses: 0, gameDiff: 0 };
}
function addSeriesToMiniTable(
rows: Map<string, MiniTableRow>,
projected: SeriesProjection & { status: 'completed' },
): void {
const [entryA, entryB] = projected.entries;
if (entryA.teamId === null || entryB.teamId === null) return;
const rowA = rows.get(entryA.teamId)!;
const rowB = rows.get(entryB.teamId)!;
rowA.gameWins += entryA.gameWins;
rowA.gameLosses += entryB.gameWins;
rowB.gameWins += entryB.gameWins;
rowB.gameLosses += entryA.gameWins;
rowA.gameDiff = rowA.gameWins - rowA.gameLosses;
rowB.gameDiff = rowB.gameWins - rowB.gameLosses;
if (projected.outcome.type !== 'draw') {
rows.get(projected.outcome.winnerTeamId)!.seriesWins += 1;
}
}
function doubleEliminationOutcome(
teams: readonly CompetitionGraphTeam[],
resetFinalEnabled: boolean,
series: readonly SeriesProjection[],
):
| Extract<CompetitionProjectionOutcome, { type: 'double-elimination' }>
| undefined {
const grandFinal = series.find(({ stage }) => stage.type === 'grand-final');
if (!grandFinal || grandFinal.status !== 'completed') return undefined;
if (grandFinal.outcome.type === 'draw') return undefined;
let decisiveOutcome: Exclude<SeriesProjectionOutcome, { type: 'draw' }> =
grandFinal.outcome;
const lowerFinalist = grandFinal.entries.find(
({ slot }) => slot === 'B',
)?.teamId;
if (resetFinalEnabled && grandFinal.outcome.winnerTeamId === lowerFinalist) {
const resetFinal = series.find(({ stage }) => stage.type === 'reset-final');
if (!resetFinal || resetFinal.status !== 'completed') return undefined;
if (resetFinal.outcome.type === 'draw') return undefined;
decisiveOutcome = resetFinal.outcome;
}
const championTeamId = decisiveOutcome.winnerTeamId;
const runnerUpTeamId = decisiveOutcome.loserTeamId;
const placements: CompetitionPlacement[] = [
{ teamId: championTeamId, rank: 1 },
{ teamId: runnerUpTeamId, rank: 2 },
];
const alreadyPlaced = new Set([championTeamId, runnerUpTeamId]);
const eliminatedByRound = new Map<number, string[]>();
for (const projected of series) {
if (
projected.stage.type !== 'lower' ||
projected.status !== 'completed' ||
projected.outcome.type === 'draw'
) {
continue;
}
const key = projected.stage.roundNumber ?? projected.stage.displayOrder;
const eliminated = eliminatedByRound.get(key) ?? [];
if (!alreadyPlaced.has(projected.outcome.loserTeamId)) {
eliminated.push(projected.outcome.loserTeamId);
}
eliminatedByRound.set(key, eliminated);
}
let nextRank = 3;
for (const [, eliminated] of [...eliminatedByRound].sort(
([left], [right]) => right - left,
)) {
const unique = [...new Set(eliminated)].filter(
(teamId) => !alreadyPlaced.has(teamId),
);
unique.sort(
(left, right) =>
teamDisplayOrder(left, teams) - teamDisplayOrder(right, teams),
);
for (const teamId of unique) {
placements.push({ teamId, rank: nextRank });
alreadyPlaced.add(teamId);
}
nextRank += unique.length;
}
// With a valid 4/8-team graph every team is accounted for by the decisive
// final or a lower-bracket elimination. Keep replay deterministic if an old
// migrated graph omitted placement metadata.
const unplaced = teams
.filter(({ teamId }) => !alreadyPlaced.has(teamId))
.sort((left, right) => left.displayOrder - right.displayOrder);
for (const { teamId } of unplaced) {
placements.push({ teamId, rank: nextRank });
nextRank += 1;
}
return {
type: 'double-elimination',
championTeamId,
placements,
completedAt: decisiveOutcome.completedAt,
};
}
interface AcceptedGameProjectionFact {
id: string;
type: 'game-accepted';
revision: number;
ordinalWithinRevision: number;
gameId: string;
seriesId: string;
gameSlotId: string;
ordinal: number;
occurredAt: Date | string;
startedAt?: Date | string;
durationSeconds?: number;
participants?: unknown[];
evidence?: {
type?: string;
riotMatchId?: string;
legacyReference?: string;
};
mapping: {
blueTeamId: string;
redTeamId: string;
winnerTeamId: string;
};
}
interface VoidedGameProjectionFact {
type: 'game-voided';
revision: number;
ordinalWithinRevision: number;
gameAcceptedFactId: string;
}
function projectGamesAndSlots(
graph: readonly SeriesDefinition[],
series: readonly SeriesProjection[],
facts: readonly unknown[],
): {
games: CompetitionGameProjection[];
gameSlots: GameSlotProjection[];
} {
const acceptedByFactId = new Map<string, AcceptedGameProjectionFact>();
const activeBySlotId = new Map<string, AcceptedGameProjectionFact>();
for (const fact of projectionGameFacts(facts)) {
if (fact.type === 'game-accepted') {
acceptedByFactId.set(fact.id, fact);
activeBySlotId.set(fact.gameSlotId, fact);
continue;
}
const accepted = acceptedByFactId.get(fact.gameAcceptedFactId);
if (!accepted) continue;
if (activeBySlotId.get(accepted.gameSlotId)?.id === accepted.id) {
activeBySlotId.delete(accepted.gameSlotId);
}
}
const displayNumberBySlotId = new Map<string, number>();
let displayNumber = 0;
for (const definition of graph) {
for (const slot of [...definition.gameSlots].sort(
(left, right) => left.ordinal - right.ordinal,
)) {
displayNumber += 1;
displayNumberBySlotId.set(slot.id, displayNumber);
}
}
const games = [...activeBySlotId.values()]
.sort(
(left, right) =>
(displayNumberBySlotId.get(left.gameSlotId) ?? 0) -
(displayNumberBySlotId.get(right.gameSlotId) ?? 0),
)
.map((fact) => ({
id: fact.gameId,
seriesId: fact.seriesId,
gameSlotId: fact.gameSlotId,
ordinal: fact.ordinal,
displayNumber: displayNumberBySlotId.get(fact.gameSlotId) ?? 0,
evidence:
fact.evidence?.type === 'riot' && fact.evidence.riotMatchId
? {
type: 'riot' as const,
riotMatchId: fact.evidence.riotMatchId,
}
: {
type: 'legacy' as const,
legacyReference:
fact.evidence?.legacyReference ?? `fact:${fact.id}`,
},
teams: {
blue: {
side: 'blue' as const,
teamId: fact.mapping.blueTeamId,
},
red: { side: 'red' as const, teamId: fact.mapping.redTeamId },
},
winnerTeamId: fact.mapping.winnerTeamId,
startedAt: toIsoString(fact.startedAt ?? fact.occurredAt),
durationSeconds:
typeof fact.durationSeconds === 'number' ? fact.durationSeconds : 0,
participants: Array.isArray(fact.participants)
? [...fact.participants]
: [],
}));
const projectedBySeriesId = new Map(
series.map((projection) => [projection.seriesId, projection]),
);
const gameSlots = graph.flatMap((definition) => {
const projected = projectedBySeriesId.get(definition.id)!;
const entries: GameSlotProjection['entries'] = [
{
slot: 'A',
teamId:
projected.entries.find(({ slot }) => slot === 'A')?.teamId ?? null,
},
{
slot: 'B',
teamId:
projected.entries.find(({ slot }) => slot === 'B')?.teamId ?? null,
},
];
return [...definition.gameSlots]
.sort((left, right) => left.ordinal - right.ordinal)
.map((slot) => {
const game = activeBySlotId.get(slot.id);
const status = game
? ('completed' as const)
: gameSlotStatus(projected.status);
return {
id: slot.id,
seriesId: definition.id,
ordinal: slot.ordinal,
displayNumber: displayNumberBySlotId.get(slot.id) ?? 0,
status,
entries,
...(game ? { gameId: game.gameId } : {}),
};
});
});
return { games, gameSlots };
}
function projectionGameFacts(
facts: readonly unknown[],
): Array<AcceptedGameProjectionFact | VoidedGameProjectionFact> {
return facts
.filter(
(fact): fact is AcceptedGameProjectionFact | VoidedGameProjectionFact =>
isRecord(fact) &&
(fact.type === 'game-accepted' || fact.type === 'game-voided'),
)
.sort(
(left, right) =>
left.revision - right.revision ||
left.ordinalWithinRevision - right.ordinalWithinRevision,
);
}
function gameSlotStatus(
status: SeriesProjection['status'],
): GameSlotProjection['status'] {
switch (status) {
case 'inactive':
return 'inactive';
case 'waiting':
return 'waiting';
case 'ready':
case 'in-progress':
return 'ready';
case 'completed':
return 'inactive';
}
}
function projectRounds(
graph: readonly SeriesDefinition[],
): BracketRoundProjection[] {
const rounds = new Map<string, BracketRoundProjection>();
for (const definition of graph) {
const { type: stage, roundNumber, displayOrder } = definition.stage;
const key = `${stage}:${roundNumber ?? 'none'}`;
const existing = rounds.get(key);
if (existing) {
existing.seriesIds.push(definition.id);
existing.displayOrder = Math.min(existing.displayOrder, displayOrder);
continue;
}
rounds.set(key, {
stage,
...(roundNumber !== undefined ? { roundNumber } : {}),
displayOrder,
label: roundLabel(stage, roundNumber),
seriesIds: [definition.id],
});
}
return [...rounds.values()].sort(
(left, right) => left.displayOrder - right.displayOrder,
);
}
function roundLabel(
stage: SeriesDefinition['stage']['type'],
roundNumber?: number,
): string {
switch (stage) {
case 'pair':
return 'Pair';
case 'round-robin':
return `Round ${roundNumber ?? 1}`;
case 'upper':
return `Upper ${roundNumber ?? 1}`;
case 'lower':
return `Lower ${roundNumber ?? 1}`;
case 'grand-final':
return 'Grand Final';
case 'reset-final':
return 'Reset Final';
}
}
function projectConnectors(
graph: readonly SeriesDefinition[],
): SeriesConnectorProjection[] {
const connectors: SeriesConnectorProjection[] = [];
for (const definition of graph) {
for (const { position, source } of definition.slots) {
if (source.type === 'series-outcome') {
connectors.push({
from: {
seriesId: source.seriesId,
select: source.select,
},
to: { seriesId: definition.id, slot: position },
});
continue;
}
if (source.type === 'series-slot') {
connectors.push({
from: {
seriesId: source.seriesId,
select: source.slot === 'A' ? 'slot-a' : 'slot-b',
},
to: { seriesId: definition.id, slot: position },
});
}
}
}
return connectors;
}
function competitionCompletedAt(series: readonly SeriesProjection[]): string {
return series
.filter(
(projection): projection is SeriesProjection & { status: 'completed' } =>
projection.status === 'completed',
)
.map(({ outcome }) => outcome.completedAt)
.sort()
.at(-1)!;
}
function toIsoString(value: Date | string): string {
return value instanceof Date ? value.toISOString() : value;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
function phaseFor(
series: readonly SeriesProjection[],
outcome: CompetitionProjectionOutcome | undefined,
): CompetitionProjection['phase'] {
if (outcome) return 'completed';
return series.some(
({ status }) => status === 'in-progress' || status === 'completed',
)
? 'running'
: 'ready';
}
function stableTeamOrder(
left: string,
right: string,
displayOrderByTeam: ReadonlyMap<string, number>,
): number {
return (
(displayOrderByTeam.get(left) ?? Number.MAX_SAFE_INTEGER) -
(displayOrderByTeam.get(right) ?? Number.MAX_SAFE_INTEGER) ||
left.localeCompare(right)
);
}
function teamDisplayOrder(
teamId: string,
teams: readonly CompetitionGraphTeam[],
): number {
return (
teams.find((candidate) => candidate.teamId === teamId)?.displayOrder ??
Number.MAX_SAFE_INTEGER
);
}
@@ -0,0 +1,215 @@
import {
assertReversalPreview,
buildReversalFacts,
previewSeriesReversal,
} from './competition-reversal';
describe('Competition reversal planning', () => {
const graph = [
series('series-parent', [team('team-8'), team('team-3')]),
series('series-child', [winner('series-parent'), loser('series-parent')]),
];
const facts = [
accepted('fact-parent', 'series-parent', 'slot-parent', 'team-8', 'team-3'),
accepted('fact-child', 'series-child', 'slot-child', 'team-8', 'team-3'),
];
const assignments = [
assignment('assignment-parent', 'series-parent', 'slot-parent', 'used'),
assignment('assignment-child', 'series-child', 'slot-child', 'reserved'),
];
it('rejects strict reversal when a descendant has result activity', () => {
expect(() =>
previewSeriesReversal({
competitionId: 'competition-1',
revision: 2,
seriesId: 'series-parent',
mode: 'strict',
graph,
facts,
assignments,
}),
).toThrow(
expect.objectContaining({ code: 'REVERSAL_DESCENDANT_ACTIVITY' }),
);
});
it('builds a deterministic cascade impact from graph descendants', () => {
const first = previewSeriesReversal({
competitionId: 'competition-1',
revision: 2,
seriesId: 'series-parent',
mode: 'cascade',
graph,
facts,
assignments,
});
const second = previewSeriesReversal({
competitionId: 'competition-1',
revision: 2,
seriesId: 'series-parent',
mode: 'cascade',
graph,
facts,
assignments,
});
const extraAssignments = [
...assignments,
assignment('assignment-extra-z', 'series-child', 'slot-z', 'reserved'),
assignment('assignment-extra-a', 'series-child', 'slot-a', 'reserved'),
];
const unorderedFirst = previewSeriesReversal({
competitionId: 'competition-1',
revision: 2,
seriesId: 'series-parent',
mode: 'cascade',
graph,
facts,
assignments: extraAssignments,
});
const unorderedSecond = previewSeriesReversal({
competitionId: 'competition-1',
revision: 2,
seriesId: 'series-parent',
mode: 'cascade',
graph,
facts,
assignments: [...extraAssignments].reverse(),
});
expect(second).toEqual(first);
expect(unorderedSecond).toEqual(unorderedFirst);
expect(first).toEqual({
sourceRevision: 2,
impactHash: expect.stringMatching(/^[a-f0-9]{64}$/),
impact: {
seriesIds: ['series-parent', 'series-child'],
factIds: ['fact-parent', 'fact-child'],
gameSlotIds: ['slot-child', 'slot-parent'],
teamIds: ['team-3', 'team-8'],
releasesReservedCodes: 1,
voidsUsedCodes: 1,
requiresStatsRebuild: true,
},
});
});
it('rejects a stale or changed preview before emitting reversal facts', () => {
const preview = previewSeriesReversal({
competitionId: 'competition-1',
revision: 2,
seriesId: 'series-parent',
mode: 'cascade',
graph,
facts,
assignments,
});
expect(() =>
assertReversalPreview(
{
competitionId: 'competition-1',
revision: 3,
seriesId: 'series-parent',
mode: 'cascade',
graph,
facts,
assignments,
},
preview.impactHash,
),
).toThrow(expect.objectContaining({ code: 'REVERSAL_PREVIEW_STALE' }));
});
it('emits one append-only reversal fact for every active result fact', () => {
const preview = previewSeriesReversal({
competitionId: 'competition-1',
revision: 2,
seriesId: 'series-parent',
mode: 'cascade',
graph,
facts,
assignments,
});
expect(
buildReversalFacts({
preview,
facts,
competitionId: 'competition-1',
commandId: 'command-reverse',
nextRevision: 3,
actor: { type: 'user', userId: 'admin-1' },
reason: '잘못 수집된 게임',
occurredAt: new Date('2026-07-12T01:00:00.000Z'),
}),
).toEqual([
expect.objectContaining({
type: 'game-voided',
gameAcceptedFactId: 'fact-parent',
revision: 3,
ordinalWithinRevision: 1,
}),
expect.objectContaining({
type: 'game-voided',
gameAcceptedFactId: 'fact-child',
revision: 3,
ordinalWithinRevision: 2,
}),
]);
});
});
function series(id: string, sources: Array<Record<string, unknown>>) {
return {
id,
stage: { type: 'upper' as const, displayOrder: 1 },
slots: [
{ position: 'A' as const, source: sources[0] },
{ position: 'B' as const, source: sources[1] },
],
rule: { type: 'first-to' as const, winsRequired: 1, maxGames: 1 },
gameSlots: [{ id: id.replace('series', 'slot'), seriesId: id, ordinal: 1 }],
};
}
function team(teamId: string) {
return { type: 'team', teamId };
}
function winner(seriesId: string) {
return { type: 'series-outcome', seriesId, select: 'winner' };
}
function loser(seriesId: string) {
return { type: 'series-outcome', seriesId, select: 'loser' };
}
function accepted(
id: string,
seriesId: string,
gameSlotId: string,
winnerTeamId: string,
loserTeamId: string,
) {
return {
id,
type: 'game-accepted',
seriesId,
gameSlotId,
mapping: {
blueTeamId: winnerTeamId,
redTeamId: loserTeamId,
winnerTeamId,
},
};
}
function assignment(
id: string,
seriesId: string,
gameSlotId: string,
state: 'reserved' | 'used',
) {
return { id, seriesId, gameSlotId, state };
}
@@ -0,0 +1,362 @@
import { createHash } from 'node:crypto';
export type SeriesReversalMode = 'strict' | 'cascade';
interface ReversalGraphSeries {
id: string;
slots: ReadonlyArray<{
source: Readonly<{
type?: unknown;
seriesId?: unknown;
}>;
}>;
}
interface ReversalFactBase {
id: string;
type: string;
seriesId?: string;
}
interface AcceptedGameFact extends ReversalFactBase {
type: 'game-accepted';
seriesId: string;
gameSlotId: string;
mapping: {
blueTeamId: string;
redTeamId: string;
winnerTeamId: string;
};
}
interface AdjudicatedFact extends ReversalFactBase {
type: 'series-adjudicated';
seriesId: string;
decision:
| { type: string; winnerTeamId?: string }
| { type: 'administrative-draw' };
}
interface VoidedGameFact extends ReversalFactBase {
type: 'game-voided';
gameAcceptedFactId: string;
}
interface ReversedAdjudicationFact extends ReversalFactBase {
type: 'adjudication-reversed';
adjudicationFactId: string;
}
type ReversalFact =
| AcceptedGameFact
| AdjudicatedFact
| VoidedGameFact
| ReversedAdjudicationFact;
interface ReversalAssignment {
seriesId: string;
gameSlotId: string;
state: string;
}
export interface ReversalPreviewInput {
competitionId: string;
revision: number;
seriesId: string;
mode: SeriesReversalMode;
graph: readonly ReversalGraphSeries[];
facts: readonly unknown[];
assignments: readonly ReversalAssignment[];
}
export interface SeriesReversalImpact {
seriesIds: string[];
factIds: string[];
gameSlotIds: string[];
teamIds: string[];
releasesReservedCodes: number;
voidsUsedCodes: number;
requiresStatsRebuild: boolean;
}
export interface SeriesReversalPreview {
sourceRevision: number;
impactHash: string;
impact: SeriesReversalImpact;
}
export class CompetitionReversalError extends Error {
constructor(
public readonly code:
| 'REVERSAL_SERIES_NOT_FOUND'
| 'REVERSAL_NO_ACTIVE_RESULT'
| 'REVERSAL_DESCENDANT_ACTIVITY'
| 'REVERSAL_PREVIEW_STALE'
| 'REVERSAL_REASON_REQUIRED',
message: string,
public readonly details?: Readonly<Record<string, unknown>>,
) {
super(message);
this.name = 'CompetitionReversalError';
}
}
/** Calculate the exact immutable facts and code assignments affected by a reversal. */
export function previewSeriesReversal(
input: ReversalPreviewInput,
): SeriesReversalPreview {
const seriesOrder = affectedSeries(input.graph, input.seriesId);
const facts = normalizeReversalFacts(input.facts);
const active = activeResultFacts(facts);
const affectedSet = new Set(seriesOrder);
const descendantSet = new Set(seriesOrder.slice(1));
const descendantActivity = active.filter((fact) =>
descendantSet.has(fact.seriesId),
);
const descendantUsedAssignments = input.assignments.filter(
(assignment) =>
descendantSet.has(assignment.seriesId) && assignment.state === 'used',
);
if (
input.mode === 'strict' &&
(descendantActivity.length > 0 || descendantUsedAssignments.length > 0)
) {
throw new CompetitionReversalError(
'REVERSAL_DESCENDANT_ACTIVITY',
'A descendant Series has result or used-code activity. Preview a cascade reversal.',
{
seriesIds: [
...new Set([
...descendantActivity.map(({ seriesId }) => seriesId),
...descendantUsedAssignments.map(({ seriesId }) => seriesId),
]),
],
},
);
}
const selectedFacts = active.filter(
(fact) =>
fact.seriesId === input.seriesId ||
(input.mode === 'cascade' && descendantSet.has(fact.seriesId)),
);
if (!selectedFacts.some(({ seriesId }) => seriesId === input.seriesId)) {
throw new CompetitionReversalError(
'REVERSAL_NO_ACTIVE_RESULT',
`Series ${input.seriesId} has no active result to reverse.`,
{ seriesId: input.seriesId },
);
}
const factOrder = new Map(
seriesOrder.map((seriesId, index) => [seriesId, index]),
);
selectedFacts.sort(
(left, right) =>
factOrder.get(left.seriesId)! - factOrder.get(right.seriesId)!,
);
const assignments = input.assignments.filter((assignment) =>
affectedSet.has(assignment.seriesId),
);
const teamIds = new Set<string>();
const gameSlotIds = new Set<string>();
for (const fact of selectedFacts) {
if (fact.type === 'game-accepted') {
gameSlotIds.add(fact.gameSlotId);
teamIds.add(fact.mapping.blueTeamId);
teamIds.add(fact.mapping.redTeamId);
} else if ('winnerTeamId' in fact.decision && fact.decision.winnerTeamId) {
teamIds.add(fact.decision.winnerTeamId);
}
}
for (const assignment of assignments) gameSlotIds.add(assignment.gameSlotId);
const impact: SeriesReversalImpact = {
seriesIds: seriesOrder,
factIds: selectedFacts.map(({ id }) => id),
gameSlotIds: [...gameSlotIds].sort(),
teamIds: [...teamIds].sort(),
releasesReservedCodes: assignments.filter(
({ state }) => state === 'reserved',
).length,
voidsUsedCodes: assignments.filter(({ state }) => state === 'used').length,
requiresStatsRebuild: selectedFacts.some(
({ type }) => type === 'game-accepted',
),
};
return {
sourceRevision: input.revision,
impactHash: hashImpact(input, impact),
impact,
};
}
export function assertReversalPreview(
input: ReversalPreviewInput,
expectedImpactHash: string,
): SeriesReversalPreview {
const current = previewSeriesReversal(input);
if (current.impactHash !== expectedImpactHash) {
throw new CompetitionReversalError(
'REVERSAL_PREVIEW_STALE',
'The Competition changed after the reversal preview.',
{ sourceRevision: input.revision },
);
}
return current;
}
export function buildReversalFacts(input: {
preview: SeriesReversalPreview;
facts: readonly unknown[];
competitionId: string;
commandId: string;
nextRevision: number;
actor: Readonly<Record<string, unknown>>;
reason: string;
occurredAt: Date;
}): Array<Record<string, unknown>> {
if (!input.reason.trim()) {
throw new CompetitionReversalError(
'REVERSAL_REASON_REQUIRED',
'A reversal reason is required.',
);
}
const byId = new Map(
normalizeReversalFacts(input.facts).map((fact) => [fact.id, fact]),
);
const causationId = deterministicId(
input.competitionId,
input.commandId,
'reversal',
);
return input.preview.impact.factIds.map((factId, index) => {
const target = byId.get(factId);
if (!target) {
throw new CompetitionReversalError(
'REVERSAL_PREVIEW_STALE',
`Fact ${factId} no longer matches the preview.`,
);
}
const common = {
id: deterministicId(input.competitionId, input.commandId, factId),
competitionId: input.competitionId,
revision: input.nextRevision,
ordinalWithinRevision: index + 1,
commandId: input.commandId,
schemaVersion: 1,
actor: input.actor,
occurredAt: input.occurredAt,
recordedAt: input.occurredAt,
causationId,
reason: input.reason,
};
return target.type === 'game-accepted'
? {
...common,
type: 'game-voided',
gameAcceptedFactId: target.id,
}
: {
...common,
type: 'adjudication-reversed',
adjudicationFactId: target.id,
};
});
}
function affectedSeries(
graph: readonly ReversalGraphSeries[],
sourceSeriesId: string,
): string[] {
if (!graph.some(({ id }) => id === sourceSeriesId)) {
throw new CompetitionReversalError(
'REVERSAL_SERIES_NOT_FOUND',
`Series ${sourceSeriesId} does not exist.`,
);
}
const affected = new Set([sourceSeriesId]);
let changed = true;
while (changed) {
changed = false;
for (const definition of graph) {
if (affected.has(definition.id)) continue;
if (
definition.slots.some(({ source }) =>
typeof source.seriesId === 'string'
? affected.has(source.seriesId)
: false,
)
) {
affected.add(definition.id);
changed = true;
}
}
}
return graph.filter(({ id }) => affected.has(id)).map(({ id }) => id);
}
function normalizeReversalFacts(facts: readonly unknown[]): ReversalFact[] {
return facts.filter((fact): fact is ReversalFact => {
if (!isRecord(fact) || typeof fact.id !== 'string') return false;
return (
fact.type === 'game-accepted' ||
fact.type === 'series-adjudicated' ||
fact.type === 'game-voided' ||
fact.type === 'adjudication-reversed'
);
});
}
function activeResultFacts(
facts: readonly ReversalFact[],
): Array<AcceptedGameFact | AdjudicatedFact> {
const voided = new Set(
facts
.filter((fact): fact is VoidedGameFact => fact.type === 'game-voided')
.map(({ gameAcceptedFactId }) => gameAcceptedFactId),
);
const reversed = new Set(
facts
.filter(
(fact): fact is ReversedAdjudicationFact =>
fact.type === 'adjudication-reversed',
)
.map(({ adjudicationFactId }) => adjudicationFactId),
);
return facts.filter(
(fact): fact is AcceptedGameFact | AdjudicatedFact =>
(fact.type === 'game-accepted' && !voided.has(fact.id)) ||
(fact.type === 'series-adjudicated' && !reversed.has(fact.id)),
);
}
function hashImpact(
input: ReversalPreviewInput,
impact: SeriesReversalImpact,
): string {
return createHash('sha256')
.update(
JSON.stringify({
competitionId: input.competitionId,
sourceRevision: input.revision,
seriesId: input.seriesId,
mode: input.mode,
impact,
}),
)
.digest('hex');
}
function deterministicId(...parts: string[]): string {
return createHash('sha256')
.update(JSON.stringify(parts))
.digest('hex')
.slice(0, 24);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
@@ -0,0 +1,48 @@
export type CompetitionDomainErrorCode =
| 'DUPLICATE_FACT_ID'
| 'DUPLICATE_GAME_ID'
| 'DUPLICATE_RIOT_MATCH_ID'
| 'DUPLICATE_GAME_SLOT'
| 'DUPLICATE_GAME_ORDINAL'
| 'DUPLICATE_ADJUDICATION'
| 'FACT_REFERENCE_NOT_FOUND'
| 'FACT_ALREADY_REVERSED'
| 'FACT_TYPE_INVALID'
| 'GAME_SLOT_INVALID'
| 'GAME_ORDINAL_INVALID'
| 'GAME_SERIES_MISMATCH'
| 'GAME_TEAM_MISMATCH'
| 'GAME_WINNER_INVALID'
| 'SERIES_ALREADY_COMPLETED'
| 'SERIES_DEFINITION_INVALID'
| 'SERIES_PARTICIPANTS_INVALID'
| 'ADJUDICATION_INVALID'
| 'ADJUDICATION_DRAW_NOT_ALLOWED'
| 'WALKOVER_HAS_ACTIVE_GAMES';
/**
* A deterministic domain-invariant failure. Command handlers translate these
* errors to the appropriate HTTP conflict/validation response; projectors do
* not depend on NestJS or transport concerns.
*/
export class CompetitionDomainError extends Error {
constructor(
public readonly code: CompetitionDomainErrorCode,
message: string,
public readonly details?: Readonly<Record<string, unknown>>,
) {
super(message);
this.name = 'CompetitionDomainError';
}
}
export function assertCompetitionInvariant(
condition: unknown,
code: CompetitionDomainErrorCode,
message: string,
details?: Readonly<Record<string, unknown>>,
): asserts condition {
if (!condition) {
throw new CompetitionDomainError(code, message, details);
}
}
@@ -0,0 +1,119 @@
import { generateSeriesGraph } from './series-graph';
describe('generateSeriesGraph', () => {
it('generates a deterministic graph with stable opaque ids', () => {
const input = {
competitionId: 'competition-deterministic',
teams: Array.from({ length: 8 }, (_, index) => ({
teamId: `team-${index + 1}`,
displayOrder: index + 1,
seedNumber: index + 1,
})),
format: {
type: 'double-elimination' as const,
resetFinalEnabled: true,
rules: {
upper: firstTo(2, 3),
lower: firstTo(1, 1),
grandFinal: firstTo(1, 1),
resetFinal: firstTo(1, 1),
},
},
};
const first = generateSeriesGraph(input);
const second = generateSeriesGraph(input);
expect(second).toEqual(first);
expect(first.map((series) => series.id)).toHaveLength(15);
expect(new Set(first.map((series) => series.id))).toHaveProperty(
'size',
15,
);
expect(first.every((series) => series.id.length > 0)).toBe(true);
});
it('predefines a conditional grand-final reset node using only slot sources', () => {
const graph = generateSeriesGraph({
competitionId: 'competition-reset-node',
teams: Array.from({ length: 4 }, (_, index) => ({
teamId: `team-${index + 1}`,
displayOrder: index + 1,
seedNumber: index + 1,
})),
format: {
type: 'double-elimination' as const,
resetFinalEnabled: true,
rules: {
upper: firstTo(2, 3),
lower: firstTo(1, 1),
grandFinal: firstTo(1, 1),
resetFinal: firstTo(1, 1),
},
},
});
const grandFinal = graph.find((series) => series.code === 'GF');
const resetFinal = graph.find((series) => series.code === 'GF_RESET');
expect(grandFinal).toBeDefined();
expect(resetFinal).toMatchObject({
stage: { type: 'reset-final' },
activation: {
type: 'grand-final-reset-required',
grandFinalSeriesId: grandFinal!.id,
},
slots: [
{
position: 'A',
source: {
type: 'series-slot',
seriesId: grandFinal!.id,
slot: 'A',
},
},
{
position: 'B',
source: {
type: 'series-slot',
seriesId: grandFinal!.id,
slot: 'B',
},
},
],
});
for (const series of graph) {
expect(series).not.toHaveProperty('winnerAdvancesTo');
expect(series).not.toHaveProperty('loserAdvancesTo');
}
});
it('rejects a first-to rule that can exhaust every GameSlot without a winner', () => {
try {
generateSeriesGraph({
competitionId: 'competition-unfinishable-first-to',
teams: Array.from({ length: 4 }, (_, index) => ({
teamId: `team-${index + 1}`,
displayOrder: index + 1,
seedNumber: index + 1,
})),
format: {
type: 'double-elimination',
resetFinalEnabled: false,
rules: {
upper: firstTo(2, 2),
lower: firstTo(1, 1),
grandFinal: firstTo(1, 1),
resetFinal: firstTo(1, 1),
},
},
});
throw new Error('Expected INVALID_FIRST_TO_RULE');
} catch (error) {
expect(error).toMatchObject({ code: 'INVALID_FIRST_TO_RULE' });
}
});
});
function firstTo(winsRequired: number, maxGames: number) {
return { type: 'first-to' as const, winsRequired, maxGames };
}
@@ -0,0 +1,647 @@
import { createHash } from 'node:crypto';
export type SeriesSlot = 'A' | 'B';
export type FirstToSeriesRule = {
type: 'first-to';
winsRequired: number;
maxGames: number;
};
export type FixedGamesSeriesRule = {
type: 'fixed-games';
gameCount: number;
drawPolicy: 'allow' | 'tiebreak-required';
};
export type SeriesRule = FirstToSeriesRule | FixedGamesSeriesRule;
export type ParticipantSource =
| { type: 'team'; teamId: string }
| { type: 'seed'; seedNumber: number }
| {
type: 'series-outcome';
seriesId: string;
select: 'winner' | 'loser';
}
| {
type: 'series-slot';
seriesId: string;
slot: SeriesSlot;
};
export type SeriesStageType =
| 'pair'
| 'round-robin'
| 'upper'
| 'lower'
| 'grand-final'
| 'reset-final';
export interface SeriesDefinition {
id: string;
code?: string;
stage: {
type: SeriesStageType;
roundNumber?: number;
displayOrder: number;
};
slots: [
{ position: 'A'; source: ParticipantSource },
{ position: 'B'; source: ParticipantSource },
];
rule: SeriesRule;
activation?: {
type: 'grand-final-reset-required';
grandFinalSeriesId: string;
};
gameSlots: Array<{
id: string;
seriesId: string;
ordinal: number;
}>;
}
export interface CompetitionGraphTeam {
teamId: string;
displayOrder: number;
seedNumber?: number;
}
export type CompetitionGraphFormat =
| {
type: 'paired-series';
rule: FixedGamesSeriesRule;
}
| {
type: 'round-robin';
rule: FixedGamesSeriesRule;
maxRounds?: number;
tieBreakers: readonly ['series-wins', 'game-diff', 'head-to-head'];
}
| {
type: 'double-elimination';
teamCount?: 4 | 8;
resetFinalEnabled: boolean;
rules: {
upper: FirstToSeriesRule;
lower: FirstToSeriesRule;
grandFinal: FirstToSeriesRule;
resetFinal: FirstToSeriesRule;
};
};
export interface GenerateSeriesGraphInput {
competitionId: string;
teams: readonly CompetitionGraphTeam[];
format: CompetitionGraphFormat;
}
interface DoubleEliminationTemplate {
code: string;
stage: Extract<
SeriesStageType,
'upper' | 'lower' | 'grand-final' | 'reset-final'
>;
roundNumber: number;
sources: [TemplateParticipantSource, TemplateParticipantSource];
}
type TemplateParticipantSource =
| { type: 'seed'; seedNumber: number }
| {
type: 'series-outcome';
seriesCode: string;
select: 'winner' | 'loser';
}
| { type: 'series-slot'; seriesCode: string; slot: SeriesSlot };
interface RoundRobinPairing {
roundNumber: number;
teamAIndex: number;
teamBIndex: number;
}
/**
* Builds the immutable Series graph. Identifiers depend only on the Competition
* identity and the logical node/slot key, never on array position or a display
* number supplied by a client.
*/
export function generateSeriesGraph(
input: GenerateSeriesGraphInput,
): SeriesDefinition[] {
assertCompetitionId(input.competitionId);
const teams = normalizeTeams(input.teams);
let graph: SeriesDefinition[];
switch (input.format.type) {
case 'paired-series':
graph = generatePairedSeriesGraph(
input.competitionId,
teams,
input.format.rule,
);
break;
case 'round-robin':
graph = generateRoundRobinGraph(
input.competitionId,
teams,
input.format.rule,
input.format.maxRounds,
);
break;
case 'double-elimination':
graph = generateDoubleEliminationGraph(
input.competitionId,
teams,
input.format,
);
break;
}
assertValidGraph(graph);
return graph;
}
function generatePairedSeriesGraph(
competitionId: string,
teams: CompetitionGraphTeam[],
rule: FixedGamesSeriesRule,
): SeriesDefinition[] {
assertFixedGamesRule(rule);
if (teams.length < 2 || teams.length % 2 !== 0) {
throw graphError(
'INVALID_PAIRED_TEAM_COUNT',
'Paired Series requires a positive, even number of teams.',
);
}
const definitions: SeriesDefinition[] = [];
for (let teamIndex = 0; teamIndex < teams.length; teamIndex += 2) {
const code = `PAIR_M${teamIndex / 2 + 1}`;
definitions.push(
createSeriesDefinition({
competitionId,
code,
stage: 'pair',
roundNumber: 1,
displayOrder: definitions.length + 1,
sources: [
{ type: 'team', teamId: teams[teamIndex].teamId },
{ type: 'team', teamId: teams[teamIndex + 1].teamId },
],
rule,
}),
);
}
return definitions;
}
function generateRoundRobinGraph(
competitionId: string,
teams: CompetitionGraphTeam[],
rule: FixedGamesSeriesRule,
maxRounds?: number,
): SeriesDefinition[] {
assertFixedGamesRule(rule);
if (teams.length < 2) {
throw graphError(
'INVALID_ROUND_ROBIN_TEAM_COUNT',
'Round robin requires at least two teams.',
);
}
const pairings = roundRobinPairings(teams.length, maxRounds);
const matchNumberByRound = new Map<number, number>();
return pairings.map((pairing, index) => {
const matchNumber = (matchNumberByRound.get(pairing.roundNumber) ?? 0) + 1;
matchNumberByRound.set(pairing.roundNumber, matchNumber);
const code = `RR_R${pairing.roundNumber}_M${matchNumber}`;
return createSeriesDefinition({
competitionId,
code,
stage: 'round-robin',
roundNumber: pairing.roundNumber,
displayOrder: index + 1,
sources: [
{ type: 'team', teamId: teams[pairing.teamAIndex].teamId },
{ type: 'team', teamId: teams[pairing.teamBIndex].teamId },
],
rule,
});
});
}
function generateDoubleEliminationGraph(
competitionId: string,
teams: CompetitionGraphTeam[],
format: Extract<CompetitionGraphFormat, { type: 'double-elimination' }>,
): SeriesDefinition[] {
if (teams.length !== 4 && teams.length !== 8) {
throw graphError(
'INVALID_DOUBLE_ELIMINATION_TEAM_COUNT',
'Double elimination supports only four or eight teams.',
);
}
if (format.teamCount !== undefined && format.teamCount !== teams.length) {
throw graphError(
'DOUBLE_ELIMINATION_TEAM_COUNT_MISMATCH',
'The configured team count does not match the team snapshots.',
);
}
assertContiguousSeeds(teams);
assertFirstToRule(format.rules.upper);
assertFirstToRule(format.rules.lower);
assertFirstToRule(format.rules.grandFinal);
assertFirstToRule(format.rules.resetFinal);
const templates =
teams.length === 4
? fourTeamDoubleEliminationTemplate()
: eightTeamDoubleEliminationTemplate();
if (format.resetFinalEnabled) templates.push(resetFinalTemplate());
return templates.map((template, index) => {
const rule = ruleForStage(template.stage, format.rules);
const grandFinalSeriesId = stableSeriesId(competitionId, 'GF');
return createSeriesDefinition({
competitionId,
code: template.code,
stage: template.stage,
roundNumber: template.roundNumber,
displayOrder: index + 1,
sources: template.sources.map((source) =>
resolveTemplateSource(competitionId, source),
) as [ParticipantSource, ParticipantSource],
rule,
activation:
template.stage === 'reset-final'
? {
type: 'grand-final-reset-required',
grandFinalSeriesId,
}
: undefined,
});
});
}
function createSeriesDefinition(params: {
competitionId: string;
code: string;
stage: SeriesStageType;
roundNumber: number;
displayOrder: number;
sources: [ParticipantSource, ParticipantSource];
rule: SeriesRule;
activation?: SeriesDefinition['activation'];
}): SeriesDefinition {
const id = stableSeriesId(params.competitionId, params.code);
const rule = cloneRule(params.rule);
const gameCount =
rule.type === 'fixed-games' ? rule.gameCount : rule.maxGames;
return {
id,
code: params.code,
stage: {
type: params.stage,
roundNumber: params.roundNumber,
displayOrder: params.displayOrder,
},
slots: [
{ position: 'A', source: { ...params.sources[0] } },
{ position: 'B', source: { ...params.sources[1] } },
],
rule,
...(params.activation ? { activation: { ...params.activation } } : {}),
gameSlots: Array.from({ length: gameCount }, (_, index) => ({
id: stableGameSlotId(params.competitionId, params.code, index + 1),
seriesId: id,
ordinal: index + 1,
})),
};
}
function fourTeamDoubleEliminationTemplate(): DoubleEliminationTemplate[] {
return [
deSeries('WB_R1_M1', 'upper', 1, seed(1), seed(4)),
deSeries('WB_R1_M2', 'upper', 1, seed(2), seed(3)),
deSeries('WB_FINAL', 'upper', 2, winner('WB_R1_M1'), winner('WB_R1_M2')),
deSeries('LB_R1_M1', 'lower', 1, loser('WB_R1_M1'), loser('WB_R1_M2')),
deSeries('LB_FINAL', 'lower', 2, winner('LB_R1_M1'), loser('WB_FINAL')),
deSeries('GF', 'grand-final', 1, winner('WB_FINAL'), winner('LB_FINAL')),
];
}
function eightTeamDoubleEliminationTemplate(): DoubleEliminationTemplate[] {
return [
deSeries('WB_R1_M1', 'upper', 1, seed(1), seed(8)),
deSeries('WB_R1_M2', 'upper', 1, seed(4), seed(5)),
deSeries('WB_R1_M3', 'upper', 1, seed(2), seed(7)),
deSeries('WB_R1_M4', 'upper', 1, seed(3), seed(6)),
deSeries('WB_R2_M1', 'upper', 2, winner('WB_R1_M1'), winner('WB_R1_M2')),
deSeries('WB_R2_M2', 'upper', 2, winner('WB_R1_M3'), winner('WB_R1_M4')),
deSeries('WB_FINAL', 'upper', 3, winner('WB_R2_M1'), winner('WB_R2_M2')),
deSeries('LB_R1_M1', 'lower', 1, loser('WB_R1_M1'), loser('WB_R1_M2')),
deSeries('LB_R1_M2', 'lower', 1, loser('WB_R1_M3'), loser('WB_R1_M4')),
deSeries('LB_R2_M1', 'lower', 2, winner('LB_R1_M1'), loser('WB_R2_M2')),
deSeries('LB_R2_M2', 'lower', 2, winner('LB_R1_M2'), loser('WB_R2_M1')),
deSeries('LB_R3_M1', 'lower', 3, winner('LB_R2_M1'), winner('LB_R2_M2')),
deSeries('LB_FINAL', 'lower', 4, winner('LB_R3_M1'), loser('WB_FINAL')),
deSeries('GF', 'grand-final', 1, winner('WB_FINAL'), winner('LB_FINAL')),
];
}
function resetFinalTemplate(): DoubleEliminationTemplate {
return deSeries(
'GF_RESET',
'reset-final',
1,
seriesSlot('GF', 'A'),
seriesSlot('GF', 'B'),
);
}
function deSeries(
code: string,
stage: DoubleEliminationTemplate['stage'],
roundNumber: number,
sourceA: TemplateParticipantSource,
sourceB: TemplateParticipantSource,
): DoubleEliminationTemplate {
return { code, stage, roundNumber, sources: [sourceA, sourceB] };
}
function seed(seedNumber: number): TemplateParticipantSource {
return { type: 'seed', seedNumber };
}
function winner(seriesCode: string): TemplateParticipantSource {
return { type: 'series-outcome', seriesCode, select: 'winner' };
}
function loser(seriesCode: string): TemplateParticipantSource {
return { type: 'series-outcome', seriesCode, select: 'loser' };
}
function seriesSlot(
seriesCode: string,
slot: SeriesSlot,
): TemplateParticipantSource {
return { type: 'series-slot', seriesCode, slot };
}
function resolveTemplateSource(
competitionId: string,
source: TemplateParticipantSource,
): ParticipantSource {
switch (source.type) {
case 'seed':
return { ...source };
case 'series-outcome':
return {
type: 'series-outcome',
seriesId: stableSeriesId(competitionId, source.seriesCode),
select: source.select,
};
case 'series-slot':
return {
type: 'series-slot',
seriesId: stableSeriesId(competitionId, source.seriesCode),
slot: source.slot,
};
}
}
function ruleForStage(
stage: DoubleEliminationTemplate['stage'],
rules: Extract<
CompetitionGraphFormat,
{ type: 'double-elimination' }
>['rules'],
): FirstToSeriesRule {
switch (stage) {
case 'upper':
return rules.upper;
case 'lower':
return rules.lower;
case 'grand-final':
return rules.grandFinal;
case 'reset-final':
return rules.resetFinal;
}
}
function roundRobinPairings(
teamCount: number,
maxRounds?: number,
): RoundRobinPairing[] {
const bye = -1;
const rotating = Array.from({ length: teamCount }, (_, index) => index);
if (rotating.length % 2 === 1) rotating.push(bye);
const fullRoundCount = rotating.length - 1;
const requestedRounds =
maxRounds === undefined
? fullRoundCount
: Number.isFinite(maxRounds)
? Math.floor(maxRounds)
: fullRoundCount;
const roundCount = Math.max(0, Math.min(fullRoundCount, requestedRounds));
const pairings: RoundRobinPairing[] = [];
for (let roundIndex = 0; roundIndex < roundCount; roundIndex += 1) {
for (let index = 0; index < rotating.length / 2; index += 1) {
const left = rotating[index];
const right = rotating[rotating.length - 1 - index];
if (left === bye || right === bye) continue;
pairings.push({
roundNumber: roundIndex + 1,
teamAIndex: Math.min(left, right),
teamBIndex: Math.max(left, right),
});
}
const fixed = rotating[0];
const tail = rotating.slice(1);
tail.unshift(tail.pop() as number);
rotating.splice(0, rotating.length, fixed, ...tail);
}
return pairings;
}
function normalizeTeams(
teams: readonly CompetitionGraphTeam[],
): CompetitionGraphTeam[] {
const normalized = teams.map((team) => ({ ...team }));
const teamIds = new Set<string>();
const displayOrders = new Set<number>();
for (const team of normalized) {
if (typeof team.teamId !== 'string' || team.teamId.trim().length === 0) {
throw graphError('INVALID_TEAM_ID', 'Every team needs an opaque ID.');
}
if (teamIds.has(team.teamId)) {
throw graphError(
'DUPLICATE_TEAM_ID',
`Duplicate team ID: ${team.teamId}`,
);
}
if (!Number.isInteger(team.displayOrder) || team.displayOrder < 1) {
throw graphError(
'INVALID_TEAM_DISPLAY_ORDER',
'Team display order must be a positive integer.',
);
}
if (displayOrders.has(team.displayOrder)) {
throw graphError(
'DUPLICATE_TEAM_DISPLAY_ORDER',
`Duplicate team display order: ${team.displayOrder}`,
);
}
teamIds.add(team.teamId);
displayOrders.add(team.displayOrder);
}
return normalized.sort(
(left, right) =>
left.displayOrder - right.displayOrder ||
left.teamId.localeCompare(right.teamId),
);
}
function assertContiguousSeeds(teams: CompetitionGraphTeam[]): void {
const seeds = teams.map((team) => team.seedNumber);
if (
seeds.some((seedNumber) => !Number.isInteger(seedNumber)) ||
new Set(seeds).size !== teams.length
) {
throw graphError(
'INVALID_DOUBLE_ELIMINATION_SEEDS',
'Double-elimination seeds must be unique integers.',
);
}
const sorted = [...(seeds as number[])].sort((left, right) => left - right);
if (sorted.some((seedNumber, index) => seedNumber !== index + 1)) {
throw graphError(
'INVALID_DOUBLE_ELIMINATION_SEEDS',
'Double-elimination seeds must be contiguous from one to the team count.',
);
}
}
function assertCompetitionId(competitionId: string): void {
if (typeof competitionId !== 'string' || competitionId.trim().length === 0) {
throw graphError(
'INVALID_COMPETITION_ID',
'Competition ID must be a non-empty string.',
);
}
}
function assertFixedGamesRule(rule: FixedGamesSeriesRule): void {
if (!Number.isInteger(rule.gameCount) || rule.gameCount < 1) {
throw graphError(
'INVALID_FIXED_GAMES_RULE',
'Fixed-game Series need a positive game count.',
);
}
if (rule.drawPolicy !== 'allow' && rule.drawPolicy !== 'tiebreak-required') {
throw graphError(
'INVALID_FIXED_GAMES_RULE',
'Fixed-game Series need a supported draw policy.',
);
}
}
function assertFirstToRule(rule: FirstToSeriesRule): void {
if (
!Number.isInteger(rule.winsRequired) ||
rule.winsRequired < 1 ||
!Number.isInteger(rule.maxGames) ||
rule.maxGames < rule.winsRequired * 2 - 1
) {
throw graphError(
'INVALID_FIRST_TO_RULE',
'First-to Series need positive, achievable win and game limits.',
);
}
}
function cloneRule(rule: SeriesRule): SeriesRule {
return rule.type === 'fixed-games' ? { ...rule } : { ...rule };
}
function assertValidGraph(graph: SeriesDefinition[]): void {
const seriesIndexById = new Map<string, number>();
const gameSlotIds = new Set<string>();
graph.forEach((series, index) => {
if (seriesIndexById.has(series.id)) {
throw graphError('DUPLICATE_SERIES_ID', 'Series IDs must be unique.');
}
seriesIndexById.set(series.id, index);
for (const gameSlot of series.gameSlots) {
if (gameSlotIds.has(gameSlot.id)) {
throw graphError(
'DUPLICATE_GAME_SLOT_ID',
'GameSlot IDs must be unique.',
);
}
gameSlotIds.add(gameSlot.id);
}
});
graph.forEach((series, index) => {
for (const slot of series.slots) {
if (
slot.source.type !== 'series-outcome' &&
slot.source.type !== 'series-slot'
) {
continue;
}
const sourceIndex = seriesIndexById.get(slot.source.seriesId);
if (sourceIndex === undefined) {
throw graphError(
'UNKNOWN_SERIES_SOURCE',
`Series ${series.id} references an unknown source.`,
);
}
if (sourceIndex >= index) {
throw graphError(
'CYCLIC_SERIES_GRAPH',
`Series ${series.id} does not follow its source in topological order.`,
);
}
}
});
}
function stableSeriesId(competitionId: string, code: string): string {
return stableOpaqueId(competitionId, 'series', code);
}
function stableGameSlotId(
competitionId: string,
seriesCode: string,
ordinal: number,
): string {
return stableOpaqueId(competitionId, 'game-slot', seriesCode, ordinal);
}
function stableOpaqueId(
competitionId: string,
entityKind: string,
...logicalKey: Array<string | number>
): string {
return createHash('sha256')
.update(JSON.stringify([competitionId, entityKind, ...logicalKey]))
.digest('hex')
.slice(0, 24);
}
function graphError(code: string, message: string): Error & { code: string } {
return Object.assign(new Error(message), { code });
}
@@ -0,0 +1,354 @@
import { projectSeries } from './series-projector';
describe('projectSeries', () => {
it('keeps a fixed-games pair in progress until every game slot is filled', () => {
const definition = seriesDefinition({
id: 'series-pair',
stage: 'pair',
rule: {
type: 'fixed-games',
gameCount: 3,
drawPolicy: 'allow',
},
});
const firstTwoGames = [
acceptedGame({
definition,
ordinal: 1,
blueTeamId: 'team-8',
redTeamId: 'team-3',
winnerTeamId: 'team-8',
}),
acceptedGame({
definition,
ordinal: 2,
blueTeamId: 'team-3',
redTeamId: 'team-8',
winnerTeamId: 'team-8',
}),
];
const inProgress = projectSeries({
definition,
participants: ['team-8', 'team-3'],
facts: firstTwoGames,
});
expect(inProgress).toMatchObject({
status: 'in-progress',
leaderTeamId: 'team-8',
entries: [
{ slot: 'A', teamId: 'team-8', gameWins: 2 },
{ slot: 'B', teamId: 'team-3', gameWins: 0 },
],
});
expect(inProgress).not.toHaveProperty('outcome');
const completed = projectSeries({
definition,
participants: ['team-8', 'team-3'],
facts: [
...firstTwoGames,
acceptedGame({
definition,
ordinal: 3,
blueTeamId: 'team-8',
redTeamId: 'team-3',
winnerTeamId: 'team-3',
}),
],
});
expect(completed).toMatchObject({
status: 'completed',
entries: [
{ slot: 'A', teamId: 'team-8', gameWins: 2 },
{ slot: 'B', teamId: 'team-3', gameWins: 1 },
],
outcome: {
type: 'played',
winnerTeamId: 'team-8',
loserTeamId: 'team-3',
},
});
expect(completed).not.toHaveProperty('leaderTeamId');
});
it('reports a leader during first-to play and a winner only after the threshold', () => {
const definition = seriesDefinition({
id: 'series-first-to',
stage: 'upper',
rule: { type: 'first-to', winsRequired: 2, maxGames: 3 },
});
const firstGame = acceptedGame({
definition,
ordinal: 1,
blueTeamId: 'team-8',
redTeamId: 'team-3',
winnerTeamId: 'team-8',
});
const oneToZero = projectSeries({
definition,
participants: ['team-8', 'team-3'],
facts: [firstGame],
});
expect(oneToZero).toMatchObject({
status: 'in-progress',
leaderTeamId: 'team-8',
});
expect(oneToZero).not.toHaveProperty('outcome');
const twoToOne = projectSeries({
definition,
participants: ['team-8', 'team-3'],
facts: [
firstGame,
acceptedGame({
definition,
ordinal: 2,
blueTeamId: 'team-8',
redTeamId: 'team-3',
winnerTeamId: 'team-3',
}),
acceptedGame({
definition,
ordinal: 3,
blueTeamId: 'team-3',
redTeamId: 'team-8',
winnerTeamId: 'team-8',
}),
],
});
expect(twoToOne).toMatchObject({
status: 'completed',
outcome: {
type: 'played',
winnerTeamId: 'team-8',
loserTeamId: 'team-3',
decidedByGameIds: [
'game-series-first-to-1',
'game-series-first-to-2',
'game-series-first-to-3',
],
},
});
expect(twoToOne).not.toHaveProperty('leaderTeamId');
});
it('rejects accepted evidence whose teams do not match the series participants', () => {
const definition = seriesDefinition({
id: 'series-invalid-team',
stage: 'upper',
rule: { type: 'first-to', winsRequired: 2, maxGames: 3 },
});
expectInvariant(
() =>
projectSeries({
definition,
participants: ['team-8', 'team-3'],
facts: [
acceptedGame({
definition,
ordinal: 1,
blueTeamId: 'team-8',
redTeamId: 'team-9',
winnerTeamId: 'team-8',
}),
],
}),
'GAME_TEAM_MISMATCH',
);
});
it('rejects a game accepted after a first-to series was already complete', () => {
const definition = seriesDefinition({
id: 'series-extra-game',
stage: 'upper',
rule: { type: 'first-to', winsRequired: 2, maxGames: 3 },
});
expectInvariant(
() =>
projectSeries({
definition,
participants: ['team-8', 'team-3'],
facts: [
acceptedGame({
definition,
ordinal: 1,
blueTeamId: 'team-8',
redTeamId: 'team-3',
winnerTeamId: 'team-8',
}),
acceptedGame({
definition,
ordinal: 2,
blueTeamId: 'team-3',
redTeamId: 'team-8',
winnerTeamId: 'team-8',
}),
acceptedGame({
definition,
ordinal: 3,
blueTeamId: 'team-8',
redTeamId: 'team-3',
winnerTeamId: 'team-3',
}),
],
}),
'SERIES_ALREADY_COMPLETED',
);
});
it('allows an inactive descendant after all of its historical activity was reversed', () => {
const definition = seriesDefinition({
id: 'series-reversed-descendant',
stage: 'upper',
rule: { type: 'first-to', winsRequired: 1, maxGames: 1 },
});
const accepted = acceptedGame({
definition,
ordinal: 1,
blueTeamId: 'team-8',
redTeamId: 'team-3',
winnerTeamId: 'team-8',
});
expect(
projectSeries({
definition,
participants: [null, null],
active: false,
facts: [
accepted,
{
id: 'fact-series-reversed-descendant-void',
type: 'game-voided',
competitionId: 'competition-series-projector',
revision: 2,
ordinalWithinRevision: 1,
commandId: 'command-series-reversed-descendant-void',
schemaVersion: 1,
actor: { type: 'user' },
occurredAt: new Date('2026-07-12T00:02:00.000Z'),
recordedAt: new Date('2026-07-12T00:02:01.000Z'),
gameAcceptedFactId: accepted.id,
reason: 'Cascade reversal',
},
],
}),
).toMatchObject({ status: 'inactive' });
});
it('rejects an unfinishable persisted first-to definition', () => {
const definition = seriesDefinition({
id: 'series-unfinishable',
stage: 'upper',
rule: { type: 'first-to', winsRequired: 2, maxGames: 2 },
});
expectInvariant(
() =>
projectSeries({
definition,
participants: ['team-8', 'team-3'],
facts: [],
}),
'SERIES_DEFINITION_INVALID',
);
});
});
function seriesDefinition(params: {
id: string;
stage: 'pair' | 'upper';
rule:
| {
type: 'fixed-games';
gameCount: number;
drawPolicy: 'allow';
}
| { type: 'first-to'; winsRequired: number; maxGames: number };
}) {
const gameCount =
params.rule.type === 'fixed-games'
? params.rule.gameCount
: params.rule.maxGames;
return {
id: params.id,
code: params.id,
stage: { type: params.stage, displayOrder: 1 },
slots: [
{
position: 'A' as const,
source: { type: 'team' as const, teamId: 'team-8' },
},
{
position: 'B' as const,
source: { type: 'team' as const, teamId: 'team-3' },
},
],
rule: params.rule,
gameSlots: Array.from({ length: gameCount }, (_, index) => ({
id: `${params.id}-slot-${index + 1}`,
seriesId: params.id,
ordinal: index + 1,
})),
};
}
function acceptedGame(params: {
definition: ReturnType<typeof seriesDefinition>;
ordinal: number;
blueTeamId: string;
redTeamId: string;
winnerTeamId: string;
}) {
const gameSlot = params.definition.gameSlots.find(
(slot) => slot.ordinal === params.ordinal,
);
if (!gameSlot) throw new Error(`Missing game slot ${params.ordinal}`);
return {
id: `fact-${params.definition.id}-${params.ordinal}`,
type: 'game-accepted' as const,
competitionId: 'competition-series-projector',
revision: params.ordinal,
ordinalWithinRevision: 1,
commandId: `command-${params.definition.id}-${params.ordinal}`,
schemaVersion: 1,
actor: { type: 'system' as const },
occurredAt: new Date(`2026-07-12T00:0${params.ordinal}:00.000Z`),
recordedAt: new Date(`2026-07-12T00:0${params.ordinal}:01.000Z`),
gameId: `game-${params.definition.id}-${params.ordinal}`,
seriesId: params.definition.id,
gameSlotId: gameSlot.id,
ordinal: params.ordinal,
evidence: {
type: 'riot' as const,
riotMatchId: `KR_${params.definition.id}_${params.ordinal}`,
payloadHash: `sha256:${params.definition.id}:${params.ordinal}`,
},
mapping: {
mappingVersion: 1,
confidence: 1,
blueTeamId: params.blueTeamId,
redTeamId: params.redTeamId,
winnerTeamId: params.winnerTeamId,
participantAssignments: [],
},
};
}
function expectInvariant(action: () => unknown, code: string) {
try {
action();
throw new Error(`Expected invariant ${code}`);
} catch (error) {
expect(error).toMatchObject({ code });
}
}
@@ -0,0 +1,819 @@
import {
assertCompetitionInvariant,
CompetitionDomainError,
} from './domain-error';
export type SeriesSlot = 'A' | 'B';
export type SeriesRule =
| { type: 'first-to'; winsRequired: number; maxGames: number }
| {
type: 'fixed-games';
gameCount: number;
drawPolicy: 'allow' | 'tiebreak-required';
};
export interface SeriesDefinitionLike {
id: string;
code?: string;
stage: {
type: string;
roundNumber?: number;
displayOrder: number;
};
slots: ReadonlyArray<{
position: SeriesSlot;
source: Readonly<Record<string, unknown>>;
}>;
rule: SeriesRule;
gameSlots: ReadonlyArray<{
id: string;
seriesId: string;
ordinal: number;
}>;
}
export interface ProjectSeriesInput {
definition: SeriesDefinitionLike;
participants: readonly (string | null | undefined)[];
facts: readonly unknown[];
/** A stable conditional node can exist before it is eligible for play. */
active?: boolean;
}
export interface SeriesProjectionEntry {
slot: SeriesSlot;
teamId: string | null;
gameWins: number;
}
export type SeriesProjectionOutcome =
| {
type: 'played';
winnerTeamId: string;
loserTeamId: string;
decidedByGameIds: string[];
completedAt: string;
}
| {
type: 'draw';
basis:
| { type: 'played'; decidedByGameIds: string[] }
| { type: 'administrative'; decisionFactId: string };
completedAt: string;
}
| {
type: 'walkover' | 'forfeit' | 'administrative';
winnerTeamId: string;
loserTeamId: string;
decisionFactId: string;
completedAt: string;
};
interface SeriesProjectionBase {
seriesId: string;
code?: string;
stage: SeriesDefinitionLike['stage'];
rule: SeriesRule;
entries: [SeriesProjectionEntry, SeriesProjectionEntry];
}
export type SeriesProjection = SeriesProjectionBase &
(
| { status: 'inactive' | 'waiting' | 'ready' }
| { status: 'in-progress'; leaderTeamId?: string }
| { status: 'completed'; outcome: SeriesProjectionOutcome }
);
interface FactBase {
id: string;
type: string;
revision: number;
ordinalWithinRevision: number;
occurredAt: Date | string;
recordedAt?: Date | string;
}
interface GameAcceptedFact extends FactBase {
type: 'game-accepted';
gameId: string;
seriesId: string;
gameSlotId: string;
ordinal: number;
evidence?: {
type?: string;
riotMatchId?: string;
};
mapping: {
blueTeamId: string;
redTeamId: string;
winnerTeamId: string;
};
}
interface GameVoidedFact extends FactBase {
type: 'game-voided';
gameAcceptedFactId: string;
reason?: string;
}
interface SeriesAdjudicatedFact extends FactBase {
type: 'series-adjudicated';
seriesId: string;
decision:
| { type: 'walkover' | 'forfeit' | 'administrative'; winnerTeamId: string }
| { type: 'administrative-draw' };
reason: string;
}
interface AdjudicationReversedFact extends FactBase {
type: 'adjudication-reversed';
adjudicationFactId: string;
reason?: string;
}
type CompetitionFact =
| GameAcceptedFact
| GameVoidedFact
| SeriesAdjudicatedFact
| AdjudicationReversedFact;
interface PlayedState {
activeGames: GameAcceptedFact[];
winsByTeam: Map<string, number>;
completed: boolean;
}
/** Project one Series exclusively from its definition, resolved participants and fact ledger. */
export function projectSeries(input: ProjectSeriesInput): SeriesProjection {
validateDefinition(input.definition);
const participants = normalizeParticipants(input.participants);
const facts = normalizeFacts(input.facts);
const base = projectionBase(input.definition, participants);
if (input.active === false) {
assertNoSeriesActivity(input.definition.id, facts);
return { ...base, status: 'inactive' };
}
if (participants.some((teamId) => teamId === null)) {
assertNoSeriesActivity(input.definition.id, facts);
return { ...base, status: 'waiting' };
}
const resolvedParticipants = participants as [string, string];
const relevantFacts = selectRelevantFacts(input.definition.id, facts);
const activeGames = new Map<string, GameAcceptedFact>();
const voidedGameFacts = new Set<string>();
const adjudications = new Map<string, SeriesAdjudicatedFact>();
const reversedAdjudications = new Set<string>();
let activeAdjudication: SeriesAdjudicatedFact | undefined;
for (const fact of relevantFacts) {
switch (fact.type) {
case 'game-accepted': {
assertCompetitionInvariant(
activeAdjudication === undefined &&
!derivePlayedState(
input.definition.rule,
[...activeGames.values()],
resolvedParticipants,
).completed,
'SERIES_ALREADY_COMPLETED',
`Series ${input.definition.id} was already completed before game ${fact.gameId}`,
{ seriesId: input.definition.id, factId: fact.id },
);
validateAcceptedGame(input.definition, resolvedParticipants, fact);
validateActiveGameUniqueness(activeGames.values(), fact);
activeGames.set(fact.id, fact);
break;
}
case 'game-voided': {
const accepted = facts.find(
(candidate): candidate is GameAcceptedFact =>
candidate.type === 'game-accepted' &&
candidate.id === fact.gameAcceptedFactId,
);
assertCompetitionInvariant(
accepted !== undefined,
'FACT_REFERENCE_NOT_FOUND',
`Voided game fact ${fact.gameAcceptedFactId} does not exist`,
{ factId: fact.id, referencedFactId: fact.gameAcceptedFactId },
);
assertCompetitionInvariant(
activeGames.has(accepted.id) && !voidedGameFacts.has(accepted.id),
'FACT_ALREADY_REVERSED',
`Game fact ${accepted.id} is already voided`,
{ factId: fact.id, referencedFactId: accepted.id },
);
activeGames.delete(accepted.id);
voidedGameFacts.add(accepted.id);
break;
}
case 'series-adjudicated': {
const played = derivePlayedState(
input.definition.rule,
[...activeGames.values()],
resolvedParticipants,
);
assertCompetitionInvariant(
!played.completed && activeAdjudication === undefined,
activeAdjudication
? 'DUPLICATE_ADJUDICATION'
: 'SERIES_ALREADY_COMPLETED',
`Series ${input.definition.id} already has an official outcome`,
{ seriesId: input.definition.id, factId: fact.id },
);
validateAdjudication(
input.definition,
resolvedParticipants,
played.activeGames,
fact,
);
adjudications.set(fact.id, fact);
activeAdjudication = fact;
break;
}
case 'adjudication-reversed': {
const adjudication = adjudications.get(fact.adjudicationFactId);
assertCompetitionInvariant(
adjudication !== undefined,
'FACT_REFERENCE_NOT_FOUND',
`Adjudication fact ${fact.adjudicationFactId} does not exist or is not active in this Series`,
{ factId: fact.id, referencedFactId: fact.adjudicationFactId },
);
assertCompetitionInvariant(
!reversedAdjudications.has(adjudication.id) &&
activeAdjudication?.id === adjudication.id,
'FACT_ALREADY_REVERSED',
`Adjudication fact ${adjudication.id} is already reversed`,
{ factId: fact.id, referencedFactId: adjudication.id },
);
reversedAdjudications.add(adjudication.id);
activeAdjudication = undefined;
break;
}
}
}
const played = derivePlayedState(
input.definition.rule,
[...activeGames.values()],
resolvedParticipants,
);
const entries = entriesFor(resolvedParticipants, played.winsByTeam);
const projectedBase = { ...base, entries };
if (activeAdjudication) {
return {
...projectedBase,
status: 'completed',
outcome: adjudicatedOutcome(activeAdjudication, resolvedParticipants),
};
}
if (played.completed) {
return {
...projectedBase,
status: 'completed',
outcome: playedOutcome(
input.definition.rule,
played.activeGames,
resolvedParticipants,
played.winsByTeam,
),
};
}
if (played.activeGames.length === 0) {
return { ...projectedBase, status: 'ready' };
}
const leaderTeamId = deriveLeader(resolvedParticipants, played.winsByTeam);
return {
...projectedBase,
status: 'in-progress',
...(leaderTeamId ? { leaderTeamId } : {}),
};
}
function validateDefinition(definition: SeriesDefinitionLike): void {
assertCompetitionInvariant(
typeof definition.id === 'string' && definition.id.length > 0,
'SERIES_DEFINITION_INVALID',
'A Series must have an opaque id',
);
assertCompetitionInvariant(
definition.slots.length === 2 &&
definition.slots[0]?.position === 'A' &&
definition.slots[1]?.position === 'B',
'SERIES_DEFINITION_INVALID',
`Series ${definition.id} must define exactly the local A and B slots`,
);
const requiredSlots =
definition.rule.type === 'fixed-games'
? definition.rule.gameCount
: definition.rule.maxGames;
assertCompetitionInvariant(
Number.isInteger(requiredSlots) && requiredSlots > 0,
'SERIES_DEFINITION_INVALID',
`Series ${definition.id} has an invalid game count`,
);
if (definition.rule.type === 'first-to') {
assertCompetitionInvariant(
Number.isInteger(definition.rule.winsRequired) &&
definition.rule.winsRequired > 0 &&
definition.rule.maxGames >= definition.rule.winsRequired * 2 - 1,
'SERIES_DEFINITION_INVALID',
`Series ${definition.id} has an invalid first-to threshold`,
);
}
assertCompetitionInvariant(
definition.gameSlots.length === requiredSlots,
'SERIES_DEFINITION_INVALID',
`Series ${definition.id} must predefine every GameSlot`,
);
const ids = new Set<string>();
const ordinals = new Set<number>();
for (const slot of definition.gameSlots) {
assertCompetitionInvariant(
slot.seriesId === definition.id &&
typeof slot.id === 'string' &&
slot.id.length > 0,
'SERIES_DEFINITION_INVALID',
`GameSlot ${slot.id} does not belong to Series ${definition.id}`,
);
assertCompetitionInvariant(
Number.isInteger(slot.ordinal) &&
slot.ordinal >= 1 &&
slot.ordinal <= requiredSlots,
'SERIES_DEFINITION_INVALID',
`GameSlot ${slot.id} has an invalid ordinal`,
);
assertCompetitionInvariant(
!ids.has(slot.id) && !ordinals.has(slot.ordinal),
'SERIES_DEFINITION_INVALID',
`Series ${definition.id} has duplicate GameSlot identity or ordinal`,
);
ids.add(slot.id);
ordinals.add(slot.ordinal);
}
}
function normalizeParticipants(
participants: readonly (string | null | undefined)[],
): [string | null, string | null] {
assertCompetitionInvariant(
participants.length === 2,
'SERIES_PARTICIPANTS_INVALID',
'A Series projection requires exactly two participant slots',
);
const normalized = participants.map((teamId) => teamId ?? null) as [
string | null,
string | null,
];
for (const teamId of normalized) {
assertCompetitionInvariant(
teamId === null || (typeof teamId === 'string' && teamId.length > 0),
'SERIES_PARTICIPANTS_INVALID',
'Resolved participant ids must be opaque non-empty strings',
);
}
assertCompetitionInvariant(
normalized[0] === null ||
normalized[1] === null ||
normalized[0] !== normalized[1],
'SERIES_PARTICIPANTS_INVALID',
'A team cannot occupy both Series slots',
);
return normalized;
}
function normalizeFacts(facts: readonly unknown[]): CompetitionFact[] {
const normalized = facts.map(normalizeFact).sort(compareFacts);
const factIds = new Set<string>();
const gameIds = new Set<string>();
const riotMatchIds = new Set<string>();
for (const fact of normalized) {
assertCompetitionInvariant(
!factIds.has(fact.id),
'DUPLICATE_FACT_ID',
`Duplicate fact id ${fact.id}`,
{ factId: fact.id },
);
factIds.add(fact.id);
if (fact.type === 'game-accepted') {
assertCompetitionInvariant(
!gameIds.has(fact.gameId),
'DUPLICATE_GAME_ID',
`Duplicate game id ${fact.gameId}`,
{ gameId: fact.gameId },
);
gameIds.add(fact.gameId);
const riotMatchId = fact.evidence?.riotMatchId;
if (fact.evidence?.type === 'riot' && riotMatchId) {
assertCompetitionInvariant(
!riotMatchIds.has(riotMatchId),
'DUPLICATE_RIOT_MATCH_ID',
`Riot match ${riotMatchId} was accepted more than once`,
{ riotMatchId },
);
riotMatchIds.add(riotMatchId);
}
}
}
return normalized;
}
function normalizeFact(value: unknown): CompetitionFact {
assertCompetitionInvariant(
isRecord(value) &&
typeof value.id === 'string' &&
typeof value.type === 'string' &&
Number.isFinite(value.revision) &&
Number.isFinite(value.ordinalWithinRevision),
'FACT_TYPE_INVALID',
'Competition facts require identity and ledger ordering fields',
);
switch (value.type) {
case 'game-accepted':
case 'game-voided':
case 'series-adjudicated':
case 'adjudication-reversed':
return value as unknown as CompetitionFact;
default:
throw new CompetitionDomainError(
'FACT_TYPE_INVALID',
`Unsupported Competition fact type ${value.type}`,
{ factType: value.type },
);
}
}
function selectRelevantFacts(
seriesId: string,
facts: CompetitionFact[],
): CompetitionFact[] {
const acceptedSeriesById = new Map(
facts
.filter((fact): fact is GameAcceptedFact => fact.type === 'game-accepted')
.map((fact) => [fact.id, fact.seriesId]),
);
const adjudicationSeriesById = new Map(
facts
.filter(
(fact): fact is SeriesAdjudicatedFact =>
fact.type === 'series-adjudicated',
)
.map((fact) => [fact.id, fact.seriesId]),
);
return facts.filter((fact) => {
switch (fact.type) {
case 'game-accepted':
case 'series-adjudicated':
return fact.seriesId === seriesId;
case 'game-voided': {
const targetSeriesId = acceptedSeriesById.get(fact.gameAcceptedFactId);
assertCompetitionInvariant(
targetSeriesId !== undefined,
'FACT_REFERENCE_NOT_FOUND',
`Voided game fact ${fact.gameAcceptedFactId} does not exist`,
{ factId: fact.id, referencedFactId: fact.gameAcceptedFactId },
);
return targetSeriesId === seriesId;
}
case 'adjudication-reversed': {
const targetSeriesId = adjudicationSeriesById.get(
fact.adjudicationFactId,
);
assertCompetitionInvariant(
targetSeriesId !== undefined,
'FACT_REFERENCE_NOT_FOUND',
`Adjudication fact ${fact.adjudicationFactId} does not exist`,
{ factId: fact.id, referencedFactId: fact.adjudicationFactId },
);
return targetSeriesId === seriesId;
}
}
});
}
function assertNoSeriesActivity(
seriesId: string,
facts: CompetitionFact[],
): void {
const acceptedSeriesById = new Map(
facts
.filter((fact): fact is GameAcceptedFact => fact.type === 'game-accepted')
.map((fact) => [fact.id, fact.seriesId]),
);
const adjudicationSeriesById = new Map(
facts
.filter(
(fact): fact is SeriesAdjudicatedFact =>
fact.type === 'series-adjudicated',
)
.map((fact) => [fact.id, fact.seriesId]),
);
const activeGames = new Set<string>();
const activeAdjudications = new Set<string>();
for (const fact of facts) {
switch (fact.type) {
case 'game-accepted':
if (fact.seriesId === seriesId) activeGames.add(fact.id);
break;
case 'game-voided':
if (acceptedSeriesById.get(fact.gameAcceptedFactId) === seriesId) {
assertCompetitionInvariant(
activeGames.delete(fact.gameAcceptedFactId),
'FACT_ALREADY_REVERSED',
`Game fact ${fact.gameAcceptedFactId} is already voided`,
{ factId: fact.id, referencedFactId: fact.gameAcceptedFactId },
);
}
break;
case 'series-adjudicated':
if (fact.seriesId === seriesId) activeAdjudications.add(fact.id);
break;
case 'adjudication-reversed':
if (adjudicationSeriesById.get(fact.adjudicationFactId) === seriesId) {
assertCompetitionInvariant(
activeAdjudications.delete(fact.adjudicationFactId),
'FACT_ALREADY_REVERSED',
`Adjudication fact ${fact.adjudicationFactId} is already reversed`,
{ factId: fact.id, referencedFactId: fact.adjudicationFactId },
);
}
break;
}
}
assertCompetitionInvariant(
activeGames.size === 0 && activeAdjudications.size === 0,
'SERIES_PARTICIPANTS_INVALID',
`Series ${seriesId} cannot contain facts before both participants are active`,
{ seriesId },
);
}
function validateAcceptedGame(
definition: SeriesDefinitionLike,
participants: [string, string],
fact: GameAcceptedFact,
): void {
assertCompetitionInvariant(
fact.seriesId === definition.id,
'GAME_SERIES_MISMATCH',
`Game ${fact.gameId} targets a different Series`,
);
const slot = definition.gameSlots.find(
(candidate) => candidate.id === fact.gameSlotId,
);
assertCompetitionInvariant(
slot !== undefined,
'GAME_SLOT_INVALID',
`Game ${fact.gameId} targets an unknown GameSlot`,
{ gameId: fact.gameId, gameSlotId: fact.gameSlotId },
);
assertCompetitionInvariant(
slot.ordinal === fact.ordinal,
'GAME_ORDINAL_INVALID',
`Game ${fact.gameId} ordinal does not match its GameSlot`,
{ gameId: fact.gameId, ordinal: fact.ordinal },
);
const { blueTeamId, redTeamId, winnerTeamId } = fact.mapping;
const expectedTeams = new Set(participants);
const actualTeams = new Set([blueTeamId, redTeamId]);
assertCompetitionInvariant(
actualTeams.size === 2 &&
expectedTeams.size === actualTeams.size &&
[...expectedTeams].every((teamId) => actualTeams.has(teamId)),
'GAME_TEAM_MISMATCH',
`Game ${fact.gameId} teams do not match Series ${definition.id}`,
{
gameId: fact.gameId,
expectedTeamIds: participants,
actualTeamIds: [blueTeamId, redTeamId],
},
);
assertCompetitionInvariant(
winnerTeamId === blueTeamId || winnerTeamId === redTeamId,
'GAME_WINNER_INVALID',
`Game ${fact.gameId} winner is not a participant`,
{ gameId: fact.gameId, winnerTeamId },
);
}
function validateActiveGameUniqueness(
activeGames: Iterable<GameAcceptedFact>,
fact: GameAcceptedFact,
): void {
for (const active of activeGames) {
assertCompetitionInvariant(
active.gameSlotId !== fact.gameSlotId,
'DUPLICATE_GAME_SLOT',
`GameSlot ${fact.gameSlotId} already has an accepted game`,
{ gameSlotId: fact.gameSlotId },
);
assertCompetitionInvariant(
active.ordinal !== fact.ordinal,
'DUPLICATE_GAME_ORDINAL',
`Series ordinal ${fact.ordinal} already has an accepted game`,
{ ordinal: fact.ordinal },
);
}
}
function validateAdjudication(
definition: SeriesDefinitionLike,
participants: [string, string],
activeGames: GameAcceptedFact[],
fact: SeriesAdjudicatedFact,
): void {
assertCompetitionInvariant(
typeof fact.reason === 'string' && fact.reason.trim().length > 0,
'ADJUDICATION_INVALID',
`Adjudication ${fact.id} requires a reason`,
);
if (fact.decision.type === 'administrative-draw') {
assertCompetitionInvariant(
definition.rule.type === 'fixed-games' &&
definition.rule.drawPolicy === 'allow',
'ADJUDICATION_DRAW_NOT_ALLOWED',
`Series ${definition.id} cannot be adjudicated as a draw`,
);
return;
}
assertCompetitionInvariant(
participants.includes(fact.decision.winnerTeamId),
'ADJUDICATION_INVALID',
`Adjudication winner is not a Series participant`,
);
if (fact.decision.type === 'walkover') {
assertCompetitionInvariant(
activeGames.length === 0,
'WALKOVER_HAS_ACTIVE_GAMES',
`Walkover Series ${definition.id} cannot retain played games`,
);
}
}
function derivePlayedState(
rule: SeriesRule,
games: GameAcceptedFact[],
participants: [string, string],
): PlayedState {
const activeGames = [...games].sort(compareGames);
const winsByTeam = new Map(participants.map((teamId) => [teamId, 0]));
for (const game of activeGames) {
const winnerTeamId = game.mapping.winnerTeamId;
winsByTeam.set(winnerTeamId, (winsByTeam.get(winnerTeamId) ?? 0) + 1);
}
const completed =
rule.type === 'fixed-games'
? activeGames.length === rule.gameCount
: participants.some(
(teamId) => (winsByTeam.get(teamId) ?? 0) >= rule.winsRequired,
);
return { activeGames, winsByTeam, completed };
}
function playedOutcome(
rule: SeriesRule,
activeGames: GameAcceptedFact[],
participants: [string, string],
winsByTeam: Map<string, number>,
): SeriesProjectionOutcome {
const decidedByGameIds = activeGames.map((game) => game.gameId);
const completedAt = toIsoString(activeGames.at(-1)!.occurredAt);
const [teamAId, teamBId] = participants;
const teamAWins = winsByTeam.get(teamAId) ?? 0;
const teamBWins = winsByTeam.get(teamBId) ?? 0;
if (teamAWins === teamBWins) {
assertCompetitionInvariant(
rule.type === 'fixed-games' && rule.drawPolicy === 'allow',
'SERIES_DEFINITION_INVALID',
'This Series completed tied but its rule requires a winner',
);
return {
type: 'draw',
basis: { type: 'played', decidedByGameIds },
completedAt,
};
}
const winnerTeamId = teamAWins > teamBWins ? teamAId : teamBId;
return {
type: 'played',
winnerTeamId,
loserTeamId: winnerTeamId === teamAId ? teamBId : teamAId,
decidedByGameIds,
completedAt,
};
}
function adjudicatedOutcome(
fact: SeriesAdjudicatedFact,
participants: [string, string],
): SeriesProjectionOutcome {
const completedAt = toIsoString(fact.occurredAt);
if (fact.decision.type === 'administrative-draw') {
return {
type: 'draw',
basis: { type: 'administrative', decisionFactId: fact.id },
completedAt,
};
}
const winnerTeamId = fact.decision.winnerTeamId;
return {
type: fact.decision.type,
winnerTeamId,
loserTeamId:
participants[0] === winnerTeamId ? participants[1] : participants[0],
decisionFactId: fact.id,
completedAt,
};
}
function projectionBase(
definition: SeriesDefinitionLike,
participants: [string | null, string | null],
): SeriesProjectionBase {
return {
seriesId: definition.id,
...(definition.code ? { code: definition.code } : {}),
stage: definition.stage,
rule: definition.rule,
entries: [
{ slot: 'A', teamId: participants[0], gameWins: 0 },
{ slot: 'B', teamId: participants[1], gameWins: 0 },
],
};
}
function entriesFor(
participants: [string, string],
winsByTeam: Map<string, number>,
): [SeriesProjectionEntry, SeriesProjectionEntry] {
return [
{
slot: 'A',
teamId: participants[0],
gameWins: winsByTeam.get(participants[0]) ?? 0,
},
{
slot: 'B',
teamId: participants[1],
gameWins: winsByTeam.get(participants[1]) ?? 0,
},
];
}
function deriveLeader(
participants: [string, string],
winsByTeam: Map<string, number>,
): string | undefined {
const firstWins = winsByTeam.get(participants[0]) ?? 0;
const secondWins = winsByTeam.get(participants[1]) ?? 0;
if (firstWins === secondWins) return undefined;
return firstWins > secondWins ? participants[0] : participants[1];
}
function compareFacts(left: CompetitionFact, right: CompetitionFact): number {
return (
left.revision - right.revision ||
left.ordinalWithinRevision - right.ordinalWithinRevision ||
left.id.localeCompare(right.id)
);
}
function compareGames(left: GameAcceptedFact, right: GameAcceptedFact): number {
return (
left.ordinal - right.ordinal ||
left.revision - right.revision ||
left.id.localeCompare(right.id)
);
}
function toIsoString(value: Date | string): string {
const date = value instanceof Date ? value : new Date(value);
assertCompetitionInvariant(
!Number.isNaN(date.getTime()),
'FACT_TYPE_INVALID',
'Fact timestamps must be valid dates',
);
return date.toISOString();
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
@@ -0,0 +1,178 @@
import { Type } from 'class-transformer';
import {
IsEnum,
IsArray,
IsDate,
IsInt,
IsMongoId,
IsNumber,
IsObject,
IsOptional,
IsString,
Matches,
Max,
MaxLength,
Min,
MinLength,
ValidateIf,
ValidateNested,
} from 'class-validator';
const ADJUDICATION_TYPES = [
'walkover',
'forfeit',
'administrative',
'administrative-draw',
] as const;
const REVERSAL_MODES = ['strict', 'cascade'] as const;
const EVIDENCE_TYPES = ['riot', 'legacy'] as const;
export class CompetitionGameEvidenceDto {
@IsEnum(EVIDENCE_TYPES)
type!: (typeof EVIDENCE_TYPES)[number];
@ValidateIf(({ type }) => type === 'riot')
@IsString()
@MinLength(1)
@MaxLength(128)
riotMatchId?: string;
@ValidateIf(({ type }) => type === 'riot')
@IsString()
@MinLength(1)
@MaxLength(256)
payloadHash?: string;
@ValidateIf(({ type }) => type === 'legacy')
@IsString()
@MinLength(1)
@MaxLength(512)
legacyReference?: string;
}
export class CompetitionGameMappingDto {
@IsInt()
@Min(1)
mappingVersion!: number;
@IsNumber()
@Min(0)
@Max(1)
confidence!: number;
@IsMongoId()
blueTeamId!: string;
@IsMongoId()
redTeamId!: string;
@IsMongoId()
winnerTeamId!: string;
@IsOptional()
@IsArray()
@IsObject({ each: true })
participantAssignments?: Array<Record<string, unknown>>;
}
export class TournamentCodeReferenceDto {
@IsMongoId()
tournamentCodeId!: string;
@IsString()
@MinLength(1)
@MaxLength(128)
riotMatchId!: string;
}
export class AcceptCompetitionGameDto {
@IsMongoId()
gameId!: string;
@IsMongoId()
seriesId!: string;
@IsMongoId()
gameSlotId!: string;
@IsInt()
@Min(1)
ordinal!: number;
@ValidateNested()
@Type(() => CompetitionGameEvidenceDto)
evidence!: CompetitionGameEvidenceDto;
@ValidateNested()
@Type(() => CompetitionGameMappingDto)
mapping!: CompetitionGameMappingDto;
@IsOptional()
@IsDate()
@Type(() => Date)
startedAt?: Date;
@IsOptional()
@IsInt()
@Min(0)
durationSeconds?: number;
@IsOptional()
@IsArray()
@IsObject({ each: true })
participants?: Array<Record<string, unknown>>;
@IsOptional()
@ValidateNested()
@Type(() => TournamentCodeReferenceDto)
tournamentCode?: TournamentCodeReferenceDto;
}
export class CompetitionAdjudicationDecisionDto {
@IsEnum(ADJUDICATION_TYPES)
type!: (typeof ADJUDICATION_TYPES)[number];
@ValidateIf(({ type }) => type !== 'administrative-draw')
@IsMongoId()
winnerTeamId?: string;
}
export class AdjudicateCompetitionSeriesDto {
@ValidateNested()
@Type(() => CompetitionAdjudicationDecisionDto)
decision!: CompetitionAdjudicationDecisionDto;
@IsString()
@MinLength(1)
@MaxLength(2000)
reason!: string;
}
export class PreviewCompetitionSeriesReversalDto {
@IsEnum(REVERSAL_MODES)
mode!: (typeof REVERSAL_MODES)[number];
@IsString()
@MinLength(1)
@MaxLength(2000)
reason!: string;
}
export class ReverseCompetitionSeriesDto extends PreviewCompetitionSeriesReversalDto {
@Matches(/^[a-f0-9]{64}$/)
impactHash!: string;
}
export class CompetitionFactsQueryDto {
@IsOptional()
@IsString()
@MaxLength(512)
cursor?: string;
@IsOptional()
@IsInt()
@Min(1)
@Max(100)
@Type(() => Number)
limit?: number;
}
@@ -4,10 +4,13 @@ import {
OnModuleDestroy,
OnModuleInit,
} from '@nestjs/common';
import { DistributedLockService } from '../global/redis/distributed-lock.service';
import { DakaoOutboxService } from './dakao-outbox.service';
const SWEEP_INTERVAL_MS = 60 * 1000;
const STALE_OUTBOX_MS = 5 * 60 * 1000;
const SWEEP_LOCK_KEY = 'distributed-lock:dakao-outbox:sweep-stale-publish-leases';
const SWEEP_LOCK_EXPIRATION_DURATION_MILLISECONDS = 55_000;
@Injectable()
export class DakaoOutboxSweeperService
@@ -16,7 +19,10 @@ export class DakaoOutboxSweeperService
private readonly logger = new Logger(DakaoOutboxSweeperService.name);
private timer: NodeJS.Timeout | undefined;
constructor(private readonly outboxService: DakaoOutboxService) {}
constructor(
private readonly outboxService: DakaoOutboxService,
private readonly distributedLockService: DistributedLockService,
) {}
onModuleInit() {
this.timer = setInterval(() => {
@@ -31,12 +37,23 @@ export class DakaoOutboxSweeperService
private async sweep(): Promise<void> {
try {
const swept = await this.outboxService.sweepStale({
staleMs: STALE_OUTBOX_MS,
limit: 20,
});
if (swept > 0) {
this.logger.warn(`Re-published ${swept} stale Dakao outbox messages.`);
const swept = await this.distributedLockService.runWithLock(
{
lockKey: SWEEP_LOCK_KEY,
lockExpirationDurationMilliseconds:
SWEEP_LOCK_EXPIRATION_DURATION_MILLISECONDS,
},
async () =>
this.outboxService.sweepStale({
staleMs: STALE_OUTBOX_MS,
limit: 20,
}),
);
const sweptCount = swept ?? 0;
if (sweptCount > 0) {
this.logger.warn(
`Re-published ${sweptCount} stale Dakao outbox messages.`,
);
}
} catch (err) {
this.logger.error(
@@ -70,44 +70,55 @@ describe('DakaoOutboxService', () => {
process.env.NODE_ENV = 'staging';
try {
const exec = jest.fn().mockResolvedValue([
{
eventId: 'lolympus:chat.send-message:chat-log-1',
type: 'chat.send-message',
eventSource: 'lolympus',
subject: 'staging.dakao.chat.send-message.v1',
correlationId: 'chat-log-1',
payload: {
chatroomId: '18474390111480678',
segments: [{ kind: 'text', text: 'done' }],
},
const staleRow = {
eventId: 'lolympus:chat.send-message:chat-log-1',
type: 'chat.send-message',
eventSource: 'lolympus',
subject: 'staging.dakao.chat.send-message.v1',
correlationId: 'chat-log-1',
payload: {
chatroomId: '18474390111480678',
segments: [{ kind: 'text', text: 'done' }],
},
]);
};
const exec = jest.fn().mockResolvedValue([staleRow]);
const lean = jest.fn().mockReturnValue({ exec });
const limit = jest.fn().mockReturnValue({ lean });
const sort = jest.fn().mockReturnValue({ limit });
const claimExec = jest.fn().mockResolvedValue(staleRow);
const claimLean = jest.fn().mockReturnValue({ exec: claimExec });
const outboxModel = {
find: jest.fn().mockReturnValue({ sort }),
findOneAndUpdate: jest.fn().mockReturnValue({ lean: claimLean }),
updateOne: jest.fn().mockReturnValue(execResult({ modifiedCount: 1 })),
};
const { service } = makeService(outboxModel);
const enqueue = jest
.spyOn(service, 'enqueueAndPublish')
.mockResolvedValue(undefined);
const { service, natsService } = makeService(outboxModel);
await expect(service.sweepStale({ staleMs: 1, limit: 1 })).resolves.toBe(
1,
);
expect(enqueue).toHaveBeenCalledWith(
expect(outboxModel.findOneAndUpdate).toHaveBeenCalledWith(
expect.objectContaining({
envelope: expect.objectContaining({
resultSubjects: {
succeeded:
'staging.lolympus.dakao.chat.send-message.succeeded.v1',
failed: 'staging.lolympus.dakao.chat.send-message.failed.v1',
},
eventId: 'lolympus:chat.send-message:chat-log-1',
}),
expect.objectContaining({
$set: expect.objectContaining({
publishLeaseOwnerIdentifier: expect.any(String),
publishLeaseExpiresAt: expect.any(Date),
}),
}),
{ returnDocument: 'after' },
);
expect(natsService.publishJetStream).toHaveBeenCalledWith(
'staging.dakao.chat.send-message.v1',
expect.objectContaining({
resultSubjects: {
succeeded: 'staging.lolympus.dakao.chat.send-message.succeeded.v1',
failed: 'staging.lolympus.dakao.chat.send-message.failed.v1',
},
}),
{ messageId: 'lolympus:chat.send-message:chat-log-1' },
);
} finally {
process.env.NODE_ENV = previousNodeEnv;
@@ -1,4 +1,5 @@
import { Injectable, Logger } from '@nestjs/common';
import { randomUUID } from 'crypto';
import { ConnectionService } from '../global/database/connection.service';
import { NatsService } from '../global/nats/nats.service';
import { resolveDakaoNatsNames } from './dakao.nats-names';
@@ -10,6 +11,7 @@ import {
const CHAT_SEND_MESSAGE_TYPE = 'chat.send-message';
const TERMINAL_STATES = ['sent', 'failed'] as const;
const DEFAULT_PUBLISH_LEASE_DURATION_MILLISECONDS = 60_000;
@Injectable()
export class DakaoOutboxService {
@@ -50,35 +52,59 @@ export class DakaoOutboxService {
{ upsert: true, returnDocument: 'after', setDefaultsOnInsert: true },
).exec();
await this.publishCommand({
subject: params.subject,
eventId: params.eventId,
envelope: params.envelope,
});
}
private async publishCommand<TPayload>(params: {
subject: string;
eventId: string;
envelope: DakaoCommandEnvelope<TPayload>;
publishLeaseOwnerIdentifier?: string;
}): Promise<void> {
const OutboxModel =
await this.connectionService.getModel('dakaoOutboxMessage');
const updateFilter = {
eventId: params.eventId,
state: { $nin: TERMINAL_STATES },
...(params.publishLeaseOwnerIdentifier
? { publishLeaseOwnerIdentifier: params.publishLeaseOwnerIdentifier }
: {}),
};
try {
await this.natsService.publishJetStream(params.subject, params.envelope, {
messageId: params.eventId,
});
await OutboxModel.updateOne(
{
eventId: params.eventId,
state: { $nin: TERMINAL_STATES },
},
updateFilter,
{
$set: {
state: 'published',
publishedAt: new Date(),
},
$inc: { publishAttempts: 1 },
$unset: { lastPublishError: '' },
$unset: {
lastPublishError: '',
publishLeaseOwnerIdentifier: '',
publishLeaseExpiresAt: '',
},
},
).exec();
} catch (err) {
await OutboxModel.updateOne(
{
eventId: params.eventId,
state: { $nin: TERMINAL_STATES },
},
updateFilter,
{
$inc: { publishAttempts: 1 },
$set: {
lastPublishError: (err as Error)?.message ?? String(err),
},
$unset: {
publishLeaseOwnerIdentifier: '',
publishLeaseExpiresAt: '',
},
},
).exec();
this.logger.error(
@@ -146,40 +172,77 @@ export class DakaoOutboxService {
public async sweepStale(params?: {
staleMs?: number;
publishLeaseDurationMilliseconds?: number;
limit?: number;
}): Promise<number> {
const OutboxModel =
await this.connectionService.getModel('dakaoOutboxMessage');
const currentTimestamp = new Date();
const staleBefore = new Date(
Date.now() - (params?.staleMs ?? 5 * 60 * 1000),
currentTimestamp.getTime() - (params?.staleMs ?? 5 * 60 * 1000),
);
const publishLeaseOwnerIdentifier = `dakao-outbox-sweeper:${process.pid}:${randomUUID()}`;
const publishLeaseExpiresAt = new Date(
currentTimestamp.getTime() +
(params?.publishLeaseDurationMilliseconds ??
DEFAULT_PUBLISH_LEASE_DURATION_MILLISECONDS),
);
const rows = await OutboxModel.find({
state: { $in: ['pending', 'published'] },
updatedAt: { $lte: staleBefore },
$or: [
{ publishLeaseExpiresAt: { $exists: false } },
{ publishLeaseExpiresAt: { $lte: currentTimestamp } },
],
})
.sort({ updatedAt: 1 })
.limit(params?.limit ?? 20)
.lean()
.exec();
let swept = 0;
for (const row of rows) {
await this.enqueueAndPublish({
subject: row.subject,
eventId: row.eventId,
const claimedRow = await OutboxModel.findOneAndUpdate(
{
eventId: row.eventId,
state: { $in: ['pending', 'published'] },
$or: [
{ publishLeaseExpiresAt: { $exists: false } },
{ publishLeaseExpiresAt: { $lte: currentTimestamp } },
],
},
{
$set: {
publishLeaseOwnerIdentifier,
publishLeaseExpiresAt,
},
},
{ returnDocument: 'after' },
)
.lean()
.exec();
if (!claimedRow) continue;
await this.publishCommand({
subject: claimedRow.subject,
eventId: claimedRow.eventId,
publishLeaseOwnerIdentifier,
envelope: {
schema: 'dakao.command.v1',
eventId: row.eventId,
type: row.type,
eventSource: row.eventSource,
correlationId: row.correlationId,
eventId: claimedRow.eventId,
type: claimedRow.type,
eventSource: claimedRow.eventSource,
correlationId: claimedRow.correlationId,
resultSubjects:
row.resultSubjects ?? this.resolveDefaultResultSubjects(row.type),
payload: row.payload,
claimedRow.resultSubjects ??
this.resolveDefaultResultSubjects(claimedRow.type),
payload: claimedRow.payload,
},
});
swept += 1;
}
return rows.length;
return swept;
}
private resolveDefaultResultSubjects(
@@ -56,20 +56,20 @@ describe('DakaoSubscriber', () => {
expect(segments).toEqual([
{ kind: 'mention', userId: '12345', displayText: '프리리' },
{ kind: 'text', text: ' 사용법\n' },
{ kind: 'text', text: ' 내전 명령어 사용법\n' },
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
{ kind: 'text', text: ' !내전 일정\n' },
{ kind: 'text', text: ' !내전 일정\u3000\n' },
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
{
kind: 'text',
text: ' !내전 신청 코드 소환사이름#태그 포지션1,포지션2\n',
text: ' !내전 신청 코드 소환사이름#태그 포지션1,포지션2\u3000\n',
},
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
{ kind: 'text', text: ' !내전 계정등록 소환사이름#태그\n' },
{ kind: 'text', text: ' !내전 계정등록 소환사이름#태그\u3000\n' },
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
{
kind: 'text',
text: ' !내전 선호포지션등록 포지션1,포지션2\n',
text: ' !내전 선호포지션등록 포지션1,포지션2\u3000\n',
},
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
{
@@ -0,0 +1,306 @@
import {
buildDoubleEliminationGameSlots,
buildDoubleEliminationBracket,
cancelDoubleEliminationBracketMatch,
completeDoubleEliminationBracketMatch,
resolveDoubleEliminationSeriesWinner,
reshuffleDoubleEliminationSeeds,
swapDoubleEliminationSeeds,
} from './double-elimination.util';
function mongooseSubdocumentLike<T extends object>(value: T): T {
const wrapper = {
toObject: () => value,
} as T & { toObject: () => T };
for (const [key, entryValue] of Object.entries(value)) {
Object.defineProperty(wrapper, key, {
enumerable: false,
get: () => entryValue,
});
}
return wrapper;
}
describe('double-elimination util', () => {
it('builds a 4-team bracket with winner, loser, and grand final matches', () => {
const bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
resetFinalEnabled: true,
});
expect(bracket.bracketMatches.map((match) => match.bracketMatchId)).toEqual(
['WB_R1_M1', 'WB_R1_M2', 'WB_FINAL', 'LB_R1_M1', 'LB_FINAL', 'GF'],
);
expect(
bracket.bracketMatches.find(
(match) => match.bracketMatchId === 'WB_R1_M1',
),
).toMatchObject({
teamAIndex: 1,
teamBIndex: 4,
winnerAdvancesTo: { bracketMatchId: 'WB_FINAL', position: 'A' },
loserAdvancesTo: { bracketMatchId: 'LB_R1_M1', position: 'A' },
state: 'ready',
});
});
it('assigns extensible series rules to winner-bracket matches', () => {
const bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
resetFinalEnabled: true,
winnerBracketGameCount: 5,
});
expect(
bracket.bracketMatches
.filter((match) => match.bracketSide === 'winner')
.map((match) => ({
bracketMatchId: match.bracketMatchId,
gameCount: match.gameCount,
requiredWins: match.requiredWins,
})),
).toEqual([
{ bracketMatchId: 'WB_R1_M1', gameCount: 5, requiredWins: 3 },
{ bracketMatchId: 'WB_R1_M2', gameCount: 5, requiredWins: 3 },
{ bracketMatchId: 'WB_FINAL', gameCount: 5, requiredWins: 3 },
]);
expect(
bracket.bracketMatches.find(
(match) => match.bracketMatchId === 'LB_R1_M1',
),
).toMatchObject({ gameCount: 1, requiredWins: 1 });
expect(
bracket.bracketMatches.find((match) => match.bracketMatchId === 'GF'),
).toMatchObject({ gameCount: 1, requiredWins: 1 });
});
it('expands bracket match series into game slots', () => {
const bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
resetFinalEnabled: true,
});
expect(
buildDoubleEliminationGameSlots(bracket.bracketMatches).slice(0, 7),
).toEqual([
expect.objectContaining({
gameNumber: 1,
seriesGameNumber: 1,
bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M1' }),
}),
expect.objectContaining({
gameNumber: 2,
seriesGameNumber: 2,
bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M1' }),
}),
expect.objectContaining({
gameNumber: 3,
seriesGameNumber: 3,
bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M1' }),
}),
expect.objectContaining({
gameNumber: 4,
seriesGameNumber: 1,
bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M2' }),
}),
expect.objectContaining({
gameNumber: 5,
seriesGameNumber: 2,
bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M2' }),
}),
expect.objectContaining({
gameNumber: 6,
seriesGameNumber: 3,
bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M2' }),
}),
expect.objectContaining({
gameNumber: 7,
seriesGameNumber: 1,
bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_FINAL' }),
}),
]);
});
it('requires the configured number of wins before resolving a series winner', () => {
const bracketMatch = buildDoubleEliminationBracket([1, 2, 3, 4], {
resetFinalEnabled: true,
}).bracketMatches.find((match) => match.bracketMatchId === 'WB_R1_M1');
expect(
resolveDoubleEliminationSeriesWinner(
{ teamAIndex: 1, teamBIndex: 4, teamAWins: 1, teamBWins: 0 },
bracketMatch!,
),
).toBeUndefined();
expect(
resolveDoubleEliminationSeriesWinner(
{ teamAIndex: 1, teamBIndex: 4, teamAWins: 2, teamBWins: 1 },
bracketMatch!,
),
).toBe(1);
});
it('completes a hydrated Mongoose-style bracket without losing subdocument fields', () => {
const bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
resetFinalEnabled: false,
});
const hydratedLikeBracket = {
...bracket,
seeds: bracket.seeds.map(mongooseSubdocumentLike),
bracketMatches: bracket.bracketMatches.map(mongooseSubdocumentLike),
events: bracket.events.map(mongooseSubdocumentLike),
};
const next = completeDoubleEliminationBracketMatch(hydratedLikeBracket, {
bracketMatchId: 'WB_R1_M1',
winnerTeamIndex: 1,
completedBy: 'riot-result',
});
expect(
next.bracketMatches.find((match) => match.bracketMatchId === 'WB_FINAL'),
).toMatchObject({ teamAIndex: 1 });
expect(
next.bracketMatches.find((match) => match.bracketMatchId === 'LB_R1_M1'),
).toMatchObject({ teamAIndex: 4 });
});
it('moves winners and losers through a 4-team bracket and records top 3', () => {
let bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
resetFinalEnabled: false,
});
bracket = completeDoubleEliminationBracketMatch(bracket, {
bracketMatchId: 'WB_R1_M1',
winnerTeamIndex: 1,
completedBy: 'riot-result',
completedAt: new Date('2026-06-01T10:00:00.000Z'),
});
bracket = completeDoubleEliminationBracketMatch(bracket, {
bracketMatchId: 'WB_R1_M2',
winnerTeamIndex: 2,
completedBy: 'riot-result',
completedAt: new Date('2026-06-01T10:30:00.000Z'),
});
expect(
bracket.bracketMatches.find(
(match) => match.bracketMatchId === 'WB_FINAL',
),
).toMatchObject({ teamAIndex: 1, teamBIndex: 2, state: 'ready' });
expect(
bracket.bracketMatches.find(
(match) => match.bracketMatchId === 'LB_R1_M1',
),
).toMatchObject({ teamAIndex: 4, teamBIndex: 3, state: 'ready' });
bracket = completeDoubleEliminationBracketMatch(bracket, {
bracketMatchId: 'WB_FINAL',
winnerTeamIndex: 1,
completedBy: 'riot-result',
});
bracket = completeDoubleEliminationBracketMatch(bracket, {
bracketMatchId: 'LB_R1_M1',
winnerTeamIndex: 3,
completedBy: 'riot-result',
});
bracket = completeDoubleEliminationBracketMatch(bracket, {
bracketMatchId: 'LB_FINAL',
winnerTeamIndex: 2,
completedBy: 'riot-result',
});
bracket = completeDoubleEliminationBracketMatch(bracket, {
bracketMatchId: 'GF',
winnerTeamIndex: 1,
completedBy: 'riot-result',
});
expect(bracket.placements).toEqual({
firstTeamIndex: 1,
secondTeamIndex: 2,
thirdTeamIndex: 3,
});
});
it('creates reset final only when the loser bracket finalist wins grand final', () => {
let bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
resetFinalEnabled: true,
});
for (const [bracketMatchId, winnerTeamIndex] of [
['WB_R1_M1', 1],
['WB_R1_M2', 2],
['WB_FINAL', 1],
['LB_R1_M1', 3],
['LB_FINAL', 2],
['GF', 2],
] as const) {
bracket = completeDoubleEliminationBracketMatch(bracket, {
bracketMatchId,
winnerTeamIndex,
completedBy: 'riot-result',
});
}
expect(bracket.resetFinalCreated).toBe(true);
expect(bracket.placements).toEqual({ thirdTeamIndex: 3 });
expect(
bracket.bracketMatches.find(
(match) => match.bracketMatchId === 'GF_RESET',
),
).toMatchObject({
gameNumber: 7,
bracketSide: 'reset-final',
teamAIndex: 1,
teamBIndex: 2,
state: 'ready',
});
});
it('rejects completion cancellation when downstream matches are already completed', () => {
let bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
resetFinalEnabled: false,
});
bracket = completeDoubleEliminationBracketMatch(bracket, {
bracketMatchId: 'WB_R1_M1',
winnerTeamIndex: 1,
completedBy: 'riot-result',
});
bracket = completeDoubleEliminationBracketMatch(bracket, {
bracketMatchId: 'WB_R1_M2',
winnerTeamIndex: 2,
completedBy: 'riot-result',
});
bracket = completeDoubleEliminationBracketMatch(bracket, {
bracketMatchId: 'WB_FINAL',
winnerTeamIndex: 1,
completedBy: 'riot-result',
});
expect(() =>
cancelDoubleEliminationBracketMatch(bracket, {
bracketMatchId: 'WB_R1_M1',
}),
).toThrow('downstream');
});
it('allows changing seeds before the bracket has completed matches', () => {
const bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
resetFinalEnabled: false,
});
const swapped = swapDoubleEliminationSeeds(bracket, {
leftSeedNumber: 1,
rightSeedNumber: 4,
});
expect(swapped.seeds).toEqual([
{ seedNumber: 1, teamIndex: 4 },
{ seedNumber: 2, teamIndex: 2 },
{ seedNumber: 3, teamIndex: 3 },
{ seedNumber: 4, teamIndex: 1 },
]);
expect(
reshuffleDoubleEliminationSeeds(bracket, () => 0).seeds.map(
(seed) => seed.teamIndex,
),
).toEqual([2, 3, 4, 1]);
});
});
@@ -0,0 +1,834 @@
import type mongoose from 'mongoose';
export type DoubleEliminationBracketSide =
| 'winner'
| 'loser'
| 'grand-final'
| 'reset-final';
export type DoubleEliminationBracketMatchState =
| 'pending'
| 'ready'
| 'completed';
export type DoubleEliminationCompletionType = 'riot-result' | 'walkover';
export interface DoubleEliminationSeed {
seedNumber: number;
teamIndex: number;
}
export interface DoubleEliminationBracketMatchSource {
type: 'seed' | 'winner' | 'loser';
seedNumber?: number;
bracketMatchId?: string;
}
export interface DoubleEliminationBracketMatchDestination {
bracketMatchId: string;
position: 'A' | 'B';
}
export interface DoubleEliminationWalkover {
winnerTeamIndex: number;
reason?: string;
awardedBy?: mongoose.Types.ObjectId;
awardedAt: Date;
cancelledBy?: mongoose.Types.ObjectId;
cancelledAt?: Date;
cancelReason?: string;
active: boolean;
}
export interface DoubleEliminationBracketMatch {
bracketMatchId: string;
gameNumber: number;
gameCount: number;
requiredWins: number;
bracketSide: DoubleEliminationBracketSide;
roundNumber: number;
matchNumber: number;
state: DoubleEliminationBracketMatchState;
teamAIndex?: number;
teamBIndex?: number;
teamASource?: DoubleEliminationBracketMatchSource;
teamBSource?: DoubleEliminationBracketMatchSource;
winnerAdvancesTo?: DoubleEliminationBracketMatchDestination;
loserAdvancesTo?: DoubleEliminationBracketMatchDestination;
winnerTeamIndex?: number;
loserTeamIndex?: number;
completedBy?: DoubleEliminationCompletionType;
completedAt?: Date;
walkover?: DoubleEliminationWalkover;
}
export interface DoubleEliminationPlacements {
firstTeamIndex?: number;
secondTeamIndex?: number;
thirdTeamIndex?: number;
}
export interface DoubleEliminationEvent {
type:
| 'bracket-created'
| 'seeds-reshuffled'
| 'seeds-swapped'
| 'bracket-match-completed'
| 'bracket-match-cancelled'
| 'walkover-awarded'
| 'walkover-cancelled'
| 'reset-final-created'
| 'riot-result-cancelled';
bracketMatchId?: string;
actorUserId?: mongoose.Types.ObjectId;
reason?: string;
createdAt: Date;
}
export interface DoubleEliminationBracket {
teamCount: 4 | 8;
resetFinalEnabled: boolean;
resetFinalCreated: boolean;
seeds: DoubleEliminationSeed[];
bracketMatches: DoubleEliminationBracketMatch[];
placements: DoubleEliminationPlacements;
events: DoubleEliminationEvent[];
}
export interface BuildDoubleEliminationBracketOptions {
resetFinalEnabled: boolean;
winnerBracketGameCount?: number;
}
export interface DoubleEliminationSeriesRule {
gameCount: number;
requiredWins: number;
}
export interface DoubleEliminationGameSlot {
gameNumber: number;
seriesGameNumber: number;
seriesGameCount: number;
seriesRequiredWins: number;
bracketMatch: DoubleEliminationBracketMatch;
}
export interface DoubleEliminationSeriesScore {
teamAIndex: number;
teamBIndex: number;
teamAWins: number;
teamBWins: number;
}
export interface CompleteDoubleEliminationBracketMatchParams {
bracketMatchId: string;
winnerTeamIndex: number;
completedBy: DoubleEliminationCompletionType;
completedAt?: Date;
walkover?: DoubleEliminationWalkover;
}
export interface CancelDoubleEliminationBracketMatchParams {
bracketMatchId: string;
cancelledBy?: mongoose.Types.ObjectId;
cancelReason?: string;
}
export function buildDoubleEliminationBracket(
seededTeamIndexes: number[],
options: BuildDoubleEliminationBracketOptions,
): DoubleEliminationBracket {
assertSupportedTeamCount(seededTeamIndexes.length);
const seeds = seededTeamIndexes.map((teamIndex, index) => ({
seedNumber: index + 1,
teamIndex,
}));
const bracket: DoubleEliminationBracket = {
teamCount: seededTeamIndexes.length as 4 | 8,
resetFinalEnabled: options.resetFinalEnabled,
resetFinalCreated: false,
seeds,
bracketMatches:
seededTeamIndexes.length === 4
? buildFourTeamBracketMatches(options)
: buildEightTeamBracketMatches(options),
placements: {},
events: [
{
type: 'bracket-created',
createdAt: new Date(),
},
],
};
applySeedTeams(bracket);
refreshBracketMatchStates(bracket);
return bracket;
}
export function resolveDoubleEliminationSeriesRule(
params: {
bracketSide: DoubleEliminationBracketSide;
bracketMatchId: string;
roundNumber: number;
},
options: { winnerBracketGameCount?: number } = {},
): DoubleEliminationSeriesRule {
if (params.bracketSide === 'winner') {
return seriesRule(options.winnerBracketGameCount ?? 3);
}
return seriesRule(1);
}
export function buildDoubleEliminationGameSlots(
bracketMatches: DoubleEliminationBracketMatch[],
): DoubleEliminationGameSlot[] {
const slots: DoubleEliminationGameSlot[] = [];
let gameNumber = 1;
for (const bracketMatch of bracketMatches) {
const seriesGameCount = normalizeSeriesGameCount(bracketMatch.gameCount);
const seriesRequiredWins =
bracketMatch.requiredWins ?? requiredWinsForGameCount(seriesGameCount);
for (
let seriesGameNumber = 1;
seriesGameNumber <= seriesGameCount;
seriesGameNumber += 1
) {
slots.push({
gameNumber,
seriesGameNumber,
seriesGameCount,
seriesRequiredWins,
bracketMatch,
});
gameNumber += 1;
}
}
return slots;
}
export function resolveDoubleEliminationSeriesWinner(
series: DoubleEliminationSeriesScore | undefined,
bracketMatch: Pick<
DoubleEliminationBracketMatch,
'requiredWins' | 'teamAIndex' | 'teamBIndex'
>,
): number | undefined {
if (!series) return undefined;
const requiredWins = bracketMatch.requiredWins ?? 1;
if (
bracketMatch.teamAIndex &&
series.teamAWins >= requiredWins &&
series.teamAWins > series.teamBWins
) {
return bracketMatch.teamAIndex;
}
if (
bracketMatch.teamBIndex &&
series.teamBWins >= requiredWins &&
series.teamBWins > series.teamAWins
) {
return bracketMatch.teamBIndex;
}
return undefined;
}
export function reshuffleDoubleEliminationSeeds(
bracket: DoubleEliminationBracket,
rng: () => number = Math.random,
): DoubleEliminationBracket {
assertSeedChangeAllowed(bracket);
const teamIndexes = shuffleInPlace(
bracket.seeds.map((seed) => seed.teamIndex),
rng,
);
return rebuildWithSeeds(bracket, teamIndexes, 'seeds-reshuffled');
}
export function swapDoubleEliminationSeeds(
bracket: DoubleEliminationBracket,
params: { leftSeedNumber: number; rightSeedNumber: number },
): DoubleEliminationBracket {
assertSeedChangeAllowed(bracket);
const teamIndexes = [...bracket.seeds]
.sort((left, right) => left.seedNumber - right.seedNumber)
.map((seed) => seed.teamIndex);
const leftIndex = params.leftSeedNumber - 1;
const rightIndex = params.rightSeedNumber - 1;
if (!teamIndexes[leftIndex] || !teamIndexes[rightIndex]) {
throw new Error('Invalid seed number.');
}
[teamIndexes[leftIndex], teamIndexes[rightIndex]] = [
teamIndexes[rightIndex],
teamIndexes[leftIndex],
];
return rebuildWithSeeds(bracket, teamIndexes, 'seeds-swapped');
}
export function completeDoubleEliminationBracketMatch(
bracket: DoubleEliminationBracket,
params: CompleteDoubleEliminationBracketMatchParams,
): DoubleEliminationBracket {
const next = cloneBracket(bracket);
const bracketMatch = requireBracketMatch(next, params.bracketMatchId);
if (bracketMatch.state !== 'ready') {
throw new Error('Bracket match is not ready.');
}
if (
bracketMatch.teamAIndex !== params.winnerTeamIndex &&
bracketMatch.teamBIndex !== params.winnerTeamIndex
) {
throw new Error('Winner team is not assigned to this bracket match.');
}
const loserTeamIndex =
bracketMatch.teamAIndex === params.winnerTeamIndex
? bracketMatch.teamBIndex
: bracketMatch.teamAIndex;
if (!loserTeamIndex) throw new Error('Loser team is missing.');
bracketMatch.state = 'completed';
bracketMatch.winnerTeamIndex = params.winnerTeamIndex;
bracketMatch.loserTeamIndex = loserTeamIndex;
bracketMatch.completedBy = params.completedBy;
bracketMatch.completedAt = params.completedAt ?? new Date();
if (params.walkover) {
bracketMatch.walkover = params.walkover;
}
advanceTeam(next, bracketMatch.winnerAdvancesTo, params.winnerTeamIndex);
advanceTeam(next, bracketMatch.loserAdvancesTo, loserTeamIndex);
if (bracketMatch.bracketMatchId === 'LB_FINAL') {
next.placements.thirdTeamIndex = loserTeamIndex;
}
if (bracketMatch.bracketMatchId === 'GF') {
completeGrandFinal(next, bracketMatch);
}
if (bracketMatch.bracketMatchId === 'GF_RESET') {
next.placements.firstTeamIndex = params.winnerTeamIndex;
next.placements.secondTeamIndex = loserTeamIndex;
}
refreshBracketMatchStates(next);
next.events.push({
type:
params.completedBy === 'walkover'
? 'walkover-awarded'
: 'bracket-match-completed',
bracketMatchId: bracketMatch.bracketMatchId,
createdAt: bracketMatch.completedAt,
});
return next;
}
export function cancelDoubleEliminationBracketMatch(
bracket: DoubleEliminationBracket,
params: CancelDoubleEliminationBracketMatchParams,
): DoubleEliminationBracket {
const next = cloneBracket(bracket);
const bracketMatch = requireBracketMatch(next, params.bracketMatchId);
if (bracketMatch.state !== 'completed') {
throw new Error('Bracket match is not completed.');
}
const descendants = collectDescendantBracketMatchIds(
next,
bracketMatch.bracketMatchId,
);
const completedDescendant = next.bracketMatches.find(
(match) =>
descendants.has(match.bracketMatchId) && match.state === 'completed',
);
if (completedDescendant) {
throw new Error(
'Cannot cancel because a downstream bracket match is completed.',
);
}
if (bracketMatch.bracketMatchId === 'GF') {
next.bracketMatches = next.bracketMatches.filter(
(match) => match.bracketMatchId !== 'GF_RESET',
);
next.resetFinalCreated = false;
}
for (const descendantId of descendants) {
const descendant = next.bracketMatches.find(
(match) => match.bracketMatchId === descendantId,
);
if (!descendant) continue;
if (
referencesBracketMatch(
descendant.teamASource,
bracketMatch.bracketMatchId,
)
) {
descendant.teamAIndex = undefined;
}
if (
referencesBracketMatch(
descendant.teamBSource,
bracketMatch.bracketMatchId,
)
) {
descendant.teamBIndex = undefined;
}
descendant.winnerTeamIndex = undefined;
descendant.loserTeamIndex = undefined;
descendant.completedBy = undefined;
descendant.completedAt = undefined;
}
bracketMatch.winnerTeamIndex = undefined;
bracketMatch.loserTeamIndex = undefined;
bracketMatch.completedBy = undefined;
bracketMatch.completedAt = undefined;
if (bracketMatch.walkover?.active) {
bracketMatch.walkover = {
...bracketMatch.walkover,
active: false,
cancelledBy: params.cancelledBy,
cancelledAt: new Date(),
cancelReason: params.cancelReason,
};
}
next.placements = {};
refreshBracketMatchStates(next);
next.events.push({
type:
bracketMatch.walkover && !bracketMatch.walkover.active
? 'walkover-cancelled'
: 'bracket-match-cancelled',
bracketMatchId: bracketMatch.bracketMatchId,
actorUserId: params.cancelledBy,
reason: params.cancelReason,
createdAt: new Date(),
});
return next;
}
export function findNextReadyDoubleEliminationBracketMatches(
bracket: DoubleEliminationBracket | undefined,
): DoubleEliminationBracketMatch[] {
return (bracket?.bracketMatches ?? []).filter(
(bracketMatch) => bracketMatch.state === 'ready',
);
}
export function hasCompletedDoubleEliminationBracketMatches(
bracket: DoubleEliminationBracket | undefined,
): boolean {
return Boolean(
bracket?.bracketMatches.some(
(bracketMatch) => bracketMatch.state === 'completed',
),
);
}
function rebuildWithSeeds(
bracket: DoubleEliminationBracket,
teamIndexes: number[],
eventType: DoubleEliminationEvent['type'],
): DoubleEliminationBracket {
const next = buildDoubleEliminationBracket(teamIndexes, {
resetFinalEnabled: bracket.resetFinalEnabled,
});
next.events = [
...bracket.events,
{
type: eventType,
createdAt: new Date(),
},
];
return next;
}
function completeGrandFinal(
bracket: DoubleEliminationBracket,
grandFinal: DoubleEliminationBracketMatch,
): void {
if (!grandFinal.winnerTeamIndex || !grandFinal.loserTeamIndex) return;
const winnerBracketTeamIndex = grandFinal.teamAIndex;
if (
bracket.resetFinalEnabled &&
!bracket.resetFinalCreated &&
grandFinal.winnerTeamIndex !== winnerBracketTeamIndex
) {
bracket.resetFinalCreated = true;
const resetRule = seriesRule(1);
bracket.bracketMatches.push({
bracketMatchId: 'GF_RESET',
gameNumber: nextGameNumber(bracket),
gameCount: resetRule.gameCount,
requiredWins: resetRule.requiredWins,
bracketSide: 'reset-final',
roundNumber: 1,
matchNumber: 1,
state: 'ready',
teamAIndex: grandFinal.teamAIndex,
teamBIndex: grandFinal.teamBIndex,
teamASource: { type: 'winner', bracketMatchId: 'GF' },
teamBSource: { type: 'loser', bracketMatchId: 'GF' },
});
bracket.events.push({
type: 'reset-final-created',
bracketMatchId: 'GF_RESET',
createdAt: new Date(),
});
return;
}
bracket.placements.firstTeamIndex = grandFinal.winnerTeamIndex;
bracket.placements.secondTeamIndex = grandFinal.loserTeamIndex;
}
function advanceTeam(
bracket: DoubleEliminationBracket,
destination: DoubleEliminationBracketMatchDestination | undefined,
teamIndex: number,
): void {
if (!destination) return;
const target = requireBracketMatch(bracket, destination.bracketMatchId);
if (destination.position === 'A') {
target.teamAIndex = teamIndex;
} else {
target.teamBIndex = teamIndex;
}
}
function refreshBracketMatchStates(bracket: DoubleEliminationBracket): void {
for (const bracketMatch of bracket.bracketMatches) {
if (bracketMatch.winnerTeamIndex) {
bracketMatch.state = 'completed';
continue;
}
bracketMatch.state =
bracketMatch.teamAIndex && bracketMatch.teamBIndex ? 'ready' : 'pending';
}
}
function applySeedTeams(bracket: DoubleEliminationBracket): void {
const bySeedNumber = new Map(
bracket.seeds.map((seed) => [seed.seedNumber, seed.teamIndex]),
);
for (const bracketMatch of bracket.bracketMatches) {
if (bracketMatch.teamASource?.type === 'seed') {
bracketMatch.teamAIndex = bySeedNumber.get(
bracketMatch.teamASource.seedNumber ?? 0,
);
}
if (bracketMatch.teamBSource?.type === 'seed') {
bracketMatch.teamBIndex = bySeedNumber.get(
bracketMatch.teamBSource.seedNumber ?? 0,
);
}
}
}
function buildFourTeamBracketMatches(
options: BuildDoubleEliminationBracketOptions,
): DoubleEliminationBracketMatch[] {
return [
bracketMatch('WB_R1_M1', 1, 'winner', 1, 1, options, {
teamASource: seedSource(1),
teamBSource: seedSource(4),
winnerAdvancesTo: destination('WB_FINAL', 'A'),
loserAdvancesTo: destination('LB_R1_M1', 'A'),
}),
bracketMatch('WB_R1_M2', 2, 'winner', 1, 2, options, {
teamASource: seedSource(2),
teamBSource: seedSource(3),
winnerAdvancesTo: destination('WB_FINAL', 'B'),
loserAdvancesTo: destination('LB_R1_M1', 'B'),
}),
bracketMatch('WB_FINAL', 3, 'winner', 2, 1, options, {
teamASource: winnerSource('WB_R1_M1'),
teamBSource: winnerSource('WB_R1_M2'),
winnerAdvancesTo: destination('GF', 'A'),
loserAdvancesTo: destination('LB_FINAL', 'B'),
}),
bracketMatch('LB_R1_M1', 4, 'loser', 1, 1, options, {
teamASource: loserSource('WB_R1_M1'),
teamBSource: loserSource('WB_R1_M2'),
winnerAdvancesTo: destination('LB_FINAL', 'A'),
}),
bracketMatch('LB_FINAL', 5, 'loser', 2, 1, options, {
teamASource: winnerSource('LB_R1_M1'),
teamBSource: loserSource('WB_FINAL'),
winnerAdvancesTo: destination('GF', 'B'),
}),
bracketMatch('GF', 6, 'grand-final', 1, 1, options, {
teamASource: winnerSource('WB_FINAL'),
teamBSource: winnerSource('LB_FINAL'),
}),
];
}
function buildEightTeamBracketMatches(
options: BuildDoubleEliminationBracketOptions,
): DoubleEliminationBracketMatch[] {
return [
bracketMatch('WB_R1_M1', 1, 'winner', 1, 1, options, {
teamASource: seedSource(1),
teamBSource: seedSource(8),
winnerAdvancesTo: destination('WB_R2_M1', 'A'),
loserAdvancesTo: destination('LB_R1_M1', 'A'),
}),
bracketMatch('WB_R1_M2', 2, 'winner', 1, 2, options, {
teamASource: seedSource(4),
teamBSource: seedSource(5),
winnerAdvancesTo: destination('WB_R2_M1', 'B'),
loserAdvancesTo: destination('LB_R1_M1', 'B'),
}),
bracketMatch('WB_R1_M3', 3, 'winner', 1, 3, options, {
teamASource: seedSource(2),
teamBSource: seedSource(7),
winnerAdvancesTo: destination('WB_R2_M2', 'A'),
loserAdvancesTo: destination('LB_R1_M2', 'A'),
}),
bracketMatch('WB_R1_M4', 4, 'winner', 1, 4, options, {
teamASource: seedSource(3),
teamBSource: seedSource(6),
winnerAdvancesTo: destination('WB_R2_M2', 'B'),
loserAdvancesTo: destination('LB_R1_M2', 'B'),
}),
bracketMatch('WB_R2_M1', 5, 'winner', 2, 1, options, {
teamASource: winnerSource('WB_R1_M1'),
teamBSource: winnerSource('WB_R1_M2'),
winnerAdvancesTo: destination('WB_FINAL', 'A'),
loserAdvancesTo: destination('LB_R2_M2', 'B'),
}),
bracketMatch('WB_R2_M2', 6, 'winner', 2, 2, options, {
teamASource: winnerSource('WB_R1_M3'),
teamBSource: winnerSource('WB_R1_M4'),
winnerAdvancesTo: destination('WB_FINAL', 'B'),
loserAdvancesTo: destination('LB_R2_M1', 'B'),
}),
bracketMatch('WB_FINAL', 7, 'winner', 3, 1, options, {
teamASource: winnerSource('WB_R2_M1'),
teamBSource: winnerSource('WB_R2_M2'),
winnerAdvancesTo: destination('GF', 'A'),
loserAdvancesTo: destination('LB_FINAL', 'B'),
}),
bracketMatch('LB_R1_M1', 8, 'loser', 1, 1, options, {
teamASource: loserSource('WB_R1_M1'),
teamBSource: loserSource('WB_R1_M2'),
winnerAdvancesTo: destination('LB_R2_M1', 'A'),
}),
bracketMatch('LB_R1_M2', 9, 'loser', 1, 2, options, {
teamASource: loserSource('WB_R1_M3'),
teamBSource: loserSource('WB_R1_M4'),
winnerAdvancesTo: destination('LB_R2_M2', 'A'),
}),
bracketMatch('LB_R2_M1', 10, 'loser', 2, 1, options, {
teamASource: winnerSource('LB_R1_M1'),
teamBSource: loserSource('WB_R2_M2'),
winnerAdvancesTo: destination('LB_R3_M1', 'A'),
}),
bracketMatch('LB_R2_M2', 11, 'loser', 2, 2, options, {
teamASource: winnerSource('LB_R1_M2'),
teamBSource: loserSource('WB_R2_M1'),
winnerAdvancesTo: destination('LB_R3_M1', 'B'),
}),
bracketMatch('LB_R3_M1', 12, 'loser', 3, 1, options, {
teamASource: winnerSource('LB_R2_M1'),
teamBSource: winnerSource('LB_R2_M2'),
winnerAdvancesTo: destination('LB_FINAL', 'A'),
}),
bracketMatch('LB_FINAL', 13, 'loser', 4, 1, options, {
teamASource: winnerSource('LB_R3_M1'),
teamBSource: loserSource('WB_FINAL'),
winnerAdvancesTo: destination('GF', 'B'),
}),
bracketMatch('GF', 14, 'grand-final', 1, 1, options, {
teamASource: winnerSource('WB_FINAL'),
teamBSource: winnerSource('LB_FINAL'),
}),
];
}
function bracketMatch(
bracketMatchId: string,
gameNumber: number,
bracketSide: DoubleEliminationBracketSide,
roundNumber: number,
matchNumber: number,
options: BuildDoubleEliminationBracketOptions,
params: Partial<DoubleEliminationBracketMatch>,
): DoubleEliminationBracketMatch {
const rule = resolveDoubleEliminationSeriesRule(
{ bracketMatchId, bracketSide, roundNumber },
options,
);
return {
bracketMatchId,
gameNumber,
gameCount: params.gameCount ?? rule.gameCount,
requiredWins: params.requiredWins ?? rule.requiredWins,
bracketSide,
roundNumber,
matchNumber,
state: 'pending',
...params,
};
}
function seedSource(seedNumber: number): DoubleEliminationBracketMatchSource {
return { type: 'seed', seedNumber };
}
function winnerSource(
bracketMatchId: string,
): DoubleEliminationBracketMatchSource {
return { type: 'winner', bracketMatchId };
}
function loserSource(
bracketMatchId: string,
): DoubleEliminationBracketMatchSource {
return { type: 'loser', bracketMatchId };
}
function destination(
bracketMatchId: string,
position: 'A' | 'B',
): DoubleEliminationBracketMatchDestination {
return { bracketMatchId, position };
}
function collectDescendantBracketMatchIds(
bracket: DoubleEliminationBracket,
bracketMatchId: string,
): Set<string> {
const descendants = new Set<string>();
let changed = true;
while (changed) {
changed = false;
for (const match of bracket.bracketMatches) {
const sourceIds = [
match.teamASource?.bracketMatchId,
match.teamBSource?.bracketMatchId,
].filter((id): id is string => Boolean(id));
if (
sourceIds.some((id) => id === bracketMatchId || descendants.has(id)) &&
!descendants.has(match.bracketMatchId)
) {
descendants.add(match.bracketMatchId);
changed = true;
}
}
}
return descendants;
}
function referencesBracketMatch(
source: DoubleEliminationBracketMatchSource | undefined,
bracketMatchId: string,
): boolean {
return source?.bracketMatchId === bracketMatchId;
}
function requireBracketMatch(
bracket: DoubleEliminationBracket,
bracketMatchId: string,
): DoubleEliminationBracketMatch {
const bracketMatch = bracket.bracketMatches.find(
(match) => match.bracketMatchId === bracketMatchId,
);
if (!bracketMatch) {
throw new Error(
`Bracket match not found: ${bracketMatchId}. Available: ${bracket.bracketMatches
.map((match) => match.bracketMatchId)
.filter(Boolean)
.join(', ')}`,
);
}
return bracketMatch;
}
function assertSeedChangeAllowed(bracket: DoubleEliminationBracket): void {
if (hasCompletedDoubleEliminationBracketMatches(bracket)) {
throw new Error('Cannot change seeds after a bracket match is completed.');
}
}
function assertSupportedTeamCount(
teamCount: number,
): asserts teamCount is 4 | 8 {
if (teamCount !== 4 && teamCount !== 8) {
throw new Error('Double elimination supports only 4 or 8 teams.');
}
}
function nextGameNumber(bracket: DoubleEliminationBracket): number {
return (
Math.max(...bracket.bracketMatches.map((match) => match.gameNumber)) + 1
);
}
function seriesRule(gameCount: number): DoubleEliminationSeriesRule {
const normalizedGameCount = normalizeSeriesGameCount(gameCount);
return {
gameCount: normalizedGameCount,
requiredWins: requiredWinsForGameCount(normalizedGameCount),
};
}
function normalizeSeriesGameCount(gameCount: number | undefined): number {
if (!Number.isInteger(gameCount) || !gameCount || gameCount < 1) return 1;
return gameCount % 2 === 0 ? gameCount + 1 : gameCount;
}
function requiredWinsForGameCount(gameCount: number): number {
return Math.floor(gameCount / 2) + 1;
}
function cloneBracket(
bracket: DoubleEliminationBracket,
): DoubleEliminationBracket {
const plainBracket = toPlainObject(bracket);
return {
...plainBracket,
seeds: plainBracket.seeds.map((seed) => ({ ...toPlainObject(seed) })),
bracketMatches: plainBracket.bracketMatches.map((rawMatch) => {
const match = toPlainObject(rawMatch);
return {
...match,
teamASource: match.teamASource
? { ...toPlainObject(match.teamASource) }
: undefined,
teamBSource: match.teamBSource
? { ...toPlainObject(match.teamBSource) }
: undefined,
winnerAdvancesTo: match.winnerAdvancesTo
? { ...toPlainObject(match.winnerAdvancesTo) }
: undefined,
loserAdvancesTo: match.loserAdvancesTo
? { ...toPlainObject(match.loserAdvancesTo) }
: undefined,
walkover: match.walkover
? { ...toPlainObject(match.walkover) }
: undefined,
};
}),
placements: { ...toPlainObject(plainBracket.placements) },
events: plainBracket.events.map((event) => ({
...toPlainObject(event),
})),
};
}
function toPlainObject<T>(value: T): T {
const candidate = value as { toObject?: () => T };
if (candidate && typeof candidate.toObject === 'function') {
return candidate.toObject();
}
return value;
}
function shuffleInPlace<T>(items: T[], rng: () => number = Math.random): T[] {
for (let index = items.length - 1; index > 0; index -= 1) {
const swapIndex = Math.floor(rng() * (index + 1));
[items[index], items[swapIndex]] = [items[swapIndex], items[index]];
}
return items;
}
@@ -1,4 +1,8 @@
import { resolveMongoDbName } from './connection.service';
import {
resolveMongoAppName,
resolveMongoConnectionOptions,
resolveMongoDbName,
} from './connection.service';
describe('resolveMongoDbName', () => {
it('uses production database only for prod', () => {
@@ -12,3 +16,47 @@ describe('resolveMongoDbName', () => {
expect(resolveMongoDbName('local')).toBe('lolympus-dev');
});
});
describe('resolveMongoAppName', () => {
it('identifies api environment and process for MongoDB connection tracking', () => {
expect(resolveMongoAppName('staging', 1234)).toBe(
'lolympus-api:staging:1234',
);
});
it('uses dev as the fallback environment label', () => {
expect(resolveMongoAppName('', 1234)).toBe('lolympus-api:dev:1234');
});
});
describe('resolveMongoConnectionOptions', () => {
it('disables automatic collection and index creation by default', () => {
expect(
resolveMongoConnectionOptions('lolympus-dev', 'lolympus-api:dev:1'),
).toEqual({
dbName: 'lolympus-dev',
appName: 'lolympus-api:dev:1',
minPoolSize: 10,
maxPoolSize: 20,
autoIndex: false,
autoCreate: false,
});
});
it('enables automatic index creation when explicitly requested', () => {
expect(
resolveMongoConnectionOptions(
'lolympus-staging',
'lolympus-api:staging:1',
'true',
),
).toEqual({
dbName: 'lolympus-staging',
appName: 'lolympus-api:staging:1',
minPoolSize: 10,
maxPoolSize: 20,
autoIndex: true,
autoCreate: false,
});
});
});
@@ -1,5 +1,6 @@
import { Injectable, Scope, OnModuleInit } from '@nestjs/common';
import { Injectable, Logger, Scope, OnModuleInit } from '@nestjs/common';
import mongoose from 'mongoose';
import { applyMongoosePerformancePlugin } from '../observability/mongoose-performance.plugin';
import { SecretService } from '../secret/secret.service';
import { tournamentModelDefinitions, TournamentModelTypes } from './schema';
@@ -9,15 +10,44 @@ export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string {
return 'lolympus-dev';
}
export function resolveMongoAppName(
nodeEnv = process.env.NODE_ENV,
pid = process.pid,
): string {
return `lolympus-api:${nodeEnv || 'dev'}:${pid}`;
}
export function resolveMongoConnectionOptions(
dbName: string,
appName: string,
mongoAutoIndex = process.env.MONGODB_AUTO_INDEX,
): mongoose.ConnectOptions {
const shouldEnableMongoAutoIndex =
mongoAutoIndex?.trim().toLowerCase() === 'true';
return {
dbName,
appName,
minPoolSize: 10,
maxPoolSize: 20,
autoIndex: shouldEnableMongoAutoIndex,
autoCreate: false,
};
}
@Injectable({ scope: Scope.DEFAULT })
export class ConnectionService implements OnModuleInit {
private readonly logger = new Logger(ConnectionService.name);
private connection: mongoose.Connection | null = null;
constructor(private readonly secretService: SecretService) {}
private tournamentModels: Map<string, mongoose.Model<any>> | null = null;
public async getConnection(): Promise<mongoose.Connection> {
if (this.connection !== null && this.connection.readyState === 1) {
if (
this.connection !== null &&
this.connection.readyState === mongoose.ConnectionStates.connected
) {
return this.connection;
}
@@ -25,15 +55,17 @@ export class ConnectionService implements OnModuleInit {
'MONGODB_CONNECTION_STRING',
);
const dbName = resolveMongoDbName();
const appName = resolveMongoAppName();
const connectionOptions = resolveMongoConnectionOptions(dbName, appName);
const defaultConnection = await mongoose
.createConnection(connectionString, {
dbName,
minPoolSize: 10,
maxPoolSize: 20,
})
.createConnection(connectionString, connectionOptions)
.asPromise();
this.connection = defaultConnection;
console.log(`Default Connection이 새로 생성됨. dbName=${dbName}`);
this.logger.log(
`MongoDB connection created. dbName=${dbName} appName=${appName} autoIndex=${
connectionOptions.autoIndex === true
}`,
);
return this.connection;
}
@@ -50,6 +82,7 @@ export class ConnectionService implements OnModuleInit {
const connection = await this.getConnection();
tournamentModelDefinitions.forEach((modelDefinition) => {
applyMongoosePerformancePlugin(modelDefinition.schema);
// 이미 생성된 경우 컴파일 스킵.
if (
Object.prototype.hasOwnProperty.call(
@@ -86,15 +119,24 @@ export class ConnectionService implements OnModuleInit {
const session = await connection.startSession(options);
return session as unknown as mongoose.ClientSession;
} catch (error) {
console.log(error);
this.logError('Failed to start MongoDB session', error);
}
}
public async onModuleInit() {
await this.getConnection().catch(console.error);
await this.getConnection().catch((error: unknown) => {
this.logError('Failed to initialize MongoDB connection', error);
});
}
public async onModuleDestroy() {
await this.connection?.close();
}
private logError(message: string, error: unknown): void {
this.logger.error(
`${message}: ${error instanceof Error ? error.message : String(error)}`,
error instanceof Error ? error.stack : undefined,
);
}
}
@@ -0,0 +1,618 @@
import { migrateTournamentCodeUniqueIndexes } from './20260627-tournament-code-unique-indexes';
type Doc = Record<string, unknown> & { _id: string };
type FakeIndex = {
commitQuorum?: number | string;
key: Record<string, 1 | -1>;
maxTimeMS?: number;
name: string;
partialFilterExpression?: Record<string, unknown>;
unique?: boolean;
};
type Projection = Record<string, 0 | 1>;
function createDb(params: {
codes?: Doc[];
indexes?: FakeIndex[];
matches?: Doc[];
missingTournamentCodeNamespace?: boolean;
}) {
const collections = {
match: params.matches ?? [],
tournamentCode: params.codes ?? [],
};
const indexes = [...(params.indexes ?? [])];
const collectionNames: string[] = [];
let tournamentCodeNamespaceMissing =
params.missingTournamentCodeNamespace ?? false;
return {
collectionNames,
collections,
indexes,
db: {
collection(name: string) {
collectionNames.push(name);
const docs =
name === 'tournamentCode'
? collections.tournamentCode
: name === 'match'
? collections.match
: [];
return {
find(
filter: Record<string, unknown> = {},
options?: { projection?: Projection },
) {
return {
limit() {
return {
async *[Symbol.asyncIterator]() {
for (const doc of docs) {
if (!matchesFilter(doc, filter)) continue;
yield applyProjection(doc, options?.projection);
}
},
};
},
};
},
async updateMany(
filter: Record<string, unknown>,
update: {
$pull?: Record<string, unknown>;
$set?: Record<string, unknown>;
$unset?: Record<string, ''>;
},
) {
let matchedCount = 0;
let modifiedCount = 0;
for (const doc of docs) {
if (!matchesFilter(doc, filter)) continue;
matchedCount += 1;
const before = JSON.stringify(doc);
applyUpdate(doc, update);
if (JSON.stringify(doc) !== before) modifiedCount += 1;
}
return { matchedCount, modifiedCount };
},
async indexes() {
if (name === 'tournamentCode' && tournamentCodeNamespaceMissing) {
const error = new Error(
'ns does not exist: lolympus.tournamentCode',
) as Error & { code: number; codeName: string };
error.code = 26;
error.codeName = 'NamespaceNotFound';
throw error;
}
return indexes.map((index) => ({ ...index }));
},
async dropIndex(name: string) {
const index = indexes.findIndex((item) => item.name === name);
if (index >= 0) indexes.splice(index, 1);
},
async createIndex(
key: Record<string, 1 | -1>,
options: {
name: string;
partialFilterExpression?: Record<string, unknown>;
unique?: boolean;
},
) {
if (name === 'tournamentCode') {
tournamentCodeNamespaceMissing = false;
}
indexes.push({ key, ...options });
return options.name;
},
};
},
},
};
}
function matchesFilter(doc: Doc, filter: Record<string, unknown>): boolean {
const clauses = filter.$or;
if (Array.isArray(clauses)) {
return clauses.some((clause) => matchesFilter(doc, clause));
}
return Object.entries(filter).every(([key, value]) => {
if (key === '$or') return true;
return matchesValue(readPath(doc, key), value);
});
}
function matchesValue(actual: unknown, expectedValue: unknown): boolean {
if (isRecord(expectedValue)) {
if ('$exists' in expectedValue) {
const exists = actual !== undefined;
if (exists !== expectedValue.$exists) return false;
}
if ('$in' in expectedValue) {
const expected = (expectedValue.$in as unknown[]).map(String);
if (Array.isArray(actual)) {
if (!actual.some((item) => expected.includes(String(item)))) {
return false;
}
} else if (!expected.includes(String(actual))) {
return false;
}
}
if ('$ne' in expectedValue) {
if (JSON.stringify(actual) === JSON.stringify(expectedValue.$ne)) {
return false;
}
}
if ('$type' in expectedValue) {
if (expectedValue.$type === 'string' && typeof actual !== 'string') {
return false;
}
}
return true;
}
return actual === expectedValue;
}
function applyUpdate(
doc: Doc,
update: {
$pull?: Record<string, unknown>;
$set?: Record<string, unknown>;
$unset?: Record<string, ''>;
},
) {
Object.assign(doc, update.$set ?? {});
for (const key of Object.keys(update.$unset ?? {})) {
delete doc[key];
}
for (const [key, pull] of Object.entries(update.$pull ?? {})) {
const current = doc[key];
if (!Array.isArray(current)) continue;
if (!isRecord(pull) || !('$in' in pull)) continue;
const pulled = (pull.$in as unknown[]).map(String);
doc[key] = current.filter((item) => !pulled.includes(String(item)));
}
}
function applyProjection(doc: Doc, projection?: Projection): Doc {
if (!projection) return doc;
const projected: Doc = { _id: doc._id };
for (const [key, value] of Object.entries(projection)) {
if (value !== 1 || key === '_id') continue;
const actual = readPath(doc, key);
if (actual !== undefined) projected[key] = actual;
}
return projected;
}
function readPath(doc: Record<string, unknown>, path: string): unknown {
const parts = path.split('.');
let current: unknown = doc;
for (const part of parts) {
if (Array.isArray(current) && /^\d+$/.test(part)) {
current = current[Number(part)];
continue;
}
if (!isRecord(current)) return undefined;
current = current[part];
}
return current;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value && typeof value === 'object' && !Array.isArray(value));
}
describe('migrateTournamentCodeUniqueIndexes', () => {
it('dry-runs duplicate cleanup without mutating documents or indexes', async () => {
const { db, collectionNames, collections, indexes } = createDb({
codes: [
{
_id: 'code-1',
code: 'A',
matchId: 'match-1',
gameNumber: 1,
reservedAt: new Date('2026-06-01T00:00:00.000Z'),
state: 'reserved',
},
{
_id: 'code-2',
code: 'B',
matchId: 'match-1',
gameNumber: 1,
reservedAt: new Date('2026-06-02T00:00:00.000Z'),
state: 'reserved',
},
{
_id: 'code-3',
code: 'C',
riotMatchId: 'KR_1',
state: 'released',
},
{
_id: 'code-4',
code: 'D',
riotMatchId: 'KR_1',
state: 'used',
},
{
_id: 'code-5',
code: 'E',
riotMatchId: ' ',
state: 'reserved',
},
],
indexes: [{ key: { riotMatchId: 1 }, name: 'riotMatchId_1' }],
matches: [{ _id: 'match-1', tournamentCodeIds: ['code-1', 'code-2'] }],
});
const beforeCodes = JSON.stringify(collections.tournamentCode);
const beforeIndexes = JSON.stringify(indexes);
const progressPhases: string[] = [];
const result = await migrateTournamentCodeUniqueIndexes(db, {
dryRun: true,
onProgress: (progress) => progressPhases.push(progress.phase),
});
expect(result.stats).toMatchObject({
blankRiotMatchIdsToUnset: 1,
blankRiotMatchIdsUnset: 0,
duplicateCodesReleased: 0,
duplicateCodesToRelease: 2,
duplicateGameNumberGroups: 1,
duplicateRiotMatchGroups: 1,
indexesCreated: 0,
indexesDropped: 0,
scannedCodes: 5,
scannedMatches: 1,
});
expect(result.sampleDuplicateGroups).toHaveLength(2);
expect(progressPhases).toEqual(
expect.arrayContaining(['scanMatches', 'scanTournamentCodes']),
);
expect(collectionNames).toContain('tournamentCode');
expect(collectionNames).not.toContain('tournament_code');
expect(JSON.stringify(collections.tournamentCode)).toBe(beforeCodes);
expect(JSON.stringify(indexes)).toBe(beforeIndexes);
});
it('releases duplicate losers, pulls them from matches, and replaces old indexes', async () => {
const now = new Date('2026-06-27T00:00:00.000Z');
const { db, collections, indexes } = createDb({
codes: [
{
_id: 'code-1',
code: 'A',
matchId: 'match-1',
gameNumber: 1,
reservedAt: new Date('2026-06-01T00:00:00.000Z'),
state: 'reserved',
},
{
_id: 'code-2',
code: 'B',
matchId: 'match-1',
gameNumber: 1,
reservedAt: new Date('2026-06-02T00:00:00.000Z'),
state: 'reserved',
},
{
_id: 'code-3',
code: 'C',
riotMatchId: 'KR_1',
state: 'used',
},
{
_id: 'code-4',
code: 'D',
riotMatchId: 'KR_1',
state: 'released',
},
{
_id: 'code-5',
code: 'E',
riotMatchId: '',
state: 'reserved',
},
],
indexes: [
{ key: { matchId: 1, gameNumber: 1 }, name: 'matchId_1_gameNumber_1' },
{
key: { matchId: 1, bracketMatchId: 1 },
name: 'matchId_1_bracketMatchId_1',
},
{ key: { riotMatchId: 1 }, name: 'riotMatchId_1' },
],
matches: [{ _id: 'match-1', tournamentCodeIds: ['code-1', 'code-4'] }],
});
const result = await migrateTournamentCodeUniqueIndexes(db, {
dryRun: false,
now,
});
expect(result.stats).toMatchObject({
blankRiotMatchIdsToUnset: 1,
blankRiotMatchIdsUnset: 1,
duplicateCodesReleased: 2,
duplicateCodesToRelease: 2,
indexesCreated: 3,
indexesDropped: 3,
matchesUpdated: 1,
});
expect(
collections.tournamentCode.find((code) => code._id === 'code-2'),
).toMatchObject({
code: 'B',
releasedAt: now,
state: 'released',
});
expect(
collections.tournamentCode.find((code) => code._id === 'code-2'),
).not.toHaveProperty('matchId');
expect(
collections.tournamentCode.find((code) => code._id === 'code-4'),
).not.toHaveProperty('riotMatchId');
expect(
collections.tournamentCode.find((code) => code._id === 'code-5'),
).not.toHaveProperty('riotMatchId');
expect(collections.match[0].tournamentCodeIds).toEqual(['code-1']);
expect(indexes).toEqual(
expect.arrayContaining([
expect.objectContaining({
key: { matchId: 1, gameNumber: 1 },
name: 'matchId_1_gameNumber_1',
partialFilterExpression: expect.objectContaining({
state: { $in: ['reserved', 'used'] },
}),
unique: true,
}),
expect.objectContaining({
key: { matchId: 1, bracketMatchId: 1 },
name: 'matchId_1_bracketMatchId_1',
partialFilterExpression: expect.objectContaining({
state: { $in: ['reserved', 'used'] },
}),
}),
expect.objectContaining({
key: { riotMatchId: 1 },
name: 'riotMatchId_1',
partialFilterExpression: { riotMatchId: { $type: 'string' } },
unique: true,
}),
]),
);
});
it('creates indexes when the tournament code collection does not exist yet', async () => {
const { db, indexes } = createDb({
missingTournamentCodeNamespace: true,
});
const progress: string[] = [];
const result = await migrateTournamentCodeUniqueIndexes(db, {
dryRun: false,
indexCommitQuorum: 1,
indexMaxTimeMS: 60_000,
onProgress: (event) =>
progress.push(`${event.action ?? ''}:${event.indexName ?? ''}`),
});
expect(result.stats).toMatchObject({
duplicateCodesReleased: 0,
indexesAlreadyCorrect: 0,
indexesCreated: 3,
indexesDropped: 0,
scannedCodes: 0,
scannedMatches: 0,
});
expect(indexes).toEqual(
expect.arrayContaining([
expect.objectContaining({
commitQuorum: 1,
key: { matchId: 1, gameNumber: 1 },
maxTimeMS: 60_000,
name: 'matchId_1_gameNumber_1',
unique: true,
}),
expect.objectContaining({
key: { matchId: 1, bracketMatchId: 1 },
name: 'matchId_1_bracketMatchId_1',
}),
expect.objectContaining({
key: { riotMatchId: 1 },
name: 'riotMatchId_1',
unique: true,
}),
]),
);
expect(progress).toEqual(
expect.arrayContaining([
'create:matchId_1_gameNumber_1',
'created:matchId_1_gameNumber_1',
]),
);
});
it('refuses to release used duplicate losers by default', async () => {
const { db, collections } = createDb({
codes: [
{
_id: 'code-1',
matchId: 'match-1',
gameNumber: 1,
state: 'used',
usedAt: new Date('2026-06-01T00:00:00.000Z'),
},
{
_id: 'code-2',
matchId: 'match-1',
gameNumber: 1,
state: 'used',
usedAt: new Date('2026-06-02T00:00:00.000Z'),
},
],
matches: [{ _id: 'match-1', tournamentCodeIds: ['code-1', 'code-2'] }],
});
await expect(
migrateTournamentCodeUniqueIndexes(db, { dryRun: false }),
).rejects.toThrow('Refusing to release 1 used duplicate tournament codes');
expect(collections.tournamentCode[0]).toMatchObject({
matchId: 'match-1',
state: 'used',
});
});
it('keeps the match-referenced slot code before state priority', async () => {
const { db, collections } = createDb({
codes: [
{
_id: 'code-1',
code: 'USED-NOT-REFERENCED',
matchId: 'match-1',
gameNumber: 1,
state: 'used',
usedAt: new Date('2026-06-02T00:00:00.000Z'),
},
{
_id: 'code-2',
code: 'RESERVED-REFERENCED',
matchId: 'match-1',
gameNumber: 1,
state: 'reserved',
reservedAt: new Date('2026-06-01T00:00:00.000Z'),
},
],
matches: [{ _id: 'match-1', tournamentCodeIds: ['code-2'] }],
});
const beforeCodes = JSON.stringify(collections.tournamentCode);
const beforeMatches = JSON.stringify(collections.match);
await expect(
migrateTournamentCodeUniqueIndexes(db, { dryRun: false }),
).rejects.toThrow('Refusing to release 1 used duplicate tournament codes');
expect(JSON.stringify(collections.tournamentCode)).toBe(beforeCodes);
expect(JSON.stringify(collections.match)).toBe(beforeMatches);
});
it('allows multiple active codes for the same double-elimination bracket match', async () => {
const { db, collections } = createDb({
codes: [
{
_id: 'code-1',
matchId: 'match-1',
gameNumber: 1,
bracketMatchId: 'WB_R1_M1',
state: 'reserved',
},
{
_id: 'code-2',
matchId: 'match-1',
gameNumber: 2,
bracketMatchId: 'WB_R1_M1',
state: 'reserved',
},
],
matches: [{ _id: 'match-1', tournamentCodeIds: ['code-1', 'code-2'] }],
});
const result = await migrateTournamentCodeUniqueIndexes(db, {
dryRun: false,
createIndexes: false,
});
expect(result.stats).toMatchObject({
duplicateBracketMatchGroups: 0,
duplicateCodesReleased: 0,
duplicateCodesToRelease: 0,
});
expect(collections.tournamentCode).toEqual(
expect.arrayContaining([
expect.objectContaining({ _id: 'code-1', state: 'reserved' }),
expect.objectContaining({ _id: 'code-2', state: 'reserved' }),
]),
);
expect(collections.match[0].tournamentCodeIds).toEqual([
'code-1',
'code-2',
]);
});
it('unsets blank riot match ids without treating them as duplicate releases', async () => {
const { db, collections } = createDb({
codes: [
{ _id: 'code-1', riotMatchId: '', state: 'reserved' },
{ _id: 'code-2', riotMatchId: ' ', state: 'available' },
],
});
const result = await migrateTournamentCodeUniqueIndexes(db, {
dryRun: false,
createIndexes: false,
});
expect(result.stats).toMatchObject({
blankRiotMatchIdsToUnset: 2,
blankRiotMatchIdsUnset: 2,
duplicateCodesReleased: 0,
duplicateCodesToRelease: 0,
duplicateRiotMatchGroups: 0,
});
expect(collections.tournamentCode[0]).toMatchObject({
_id: 'code-1',
state: 'reserved',
});
expect(collections.tournamentCode[0]).not.toHaveProperty('riotMatchId');
expect(collections.tournamentCode[1]).not.toHaveProperty('riotMatchId');
});
it('allows used duplicate cleanup only when explicitly requested', async () => {
const now = new Date('2026-06-27T00:00:00.000Z');
const { db, collections } = createDb({
codes: [
{
_id: 'code-1',
matchId: 'match-1',
gameNumber: 1,
state: 'used',
usedAt: new Date('2026-06-01T00:00:00.000Z'),
},
{
_id: 'code-2',
matchId: 'match-1',
gameNumber: 1,
state: 'used',
usedAt: new Date('2026-06-02T00:00:00.000Z'),
},
],
matches: [{ _id: 'match-1', tournamentCodeIds: ['code-1', 'code-2'] }],
});
const result = await migrateTournamentCodeUniqueIndexes(db, {
allowUsedDuplicateRelease: true,
dryRun: false,
now,
});
expect(result.stats).toMatchObject({
duplicateCodesReleased: 1,
unsafeUsedDuplicateCodes: 1,
unsafeUsedDuplicateGroups: 1,
});
expect(collections.tournamentCode[0]).toMatchObject({
releasedAt: now,
state: 'released',
});
expect(collections.tournamentCode[0]).not.toHaveProperty('usedAt');
expect(collections.match[0].tournamentCodeIds).toEqual(['code-2']);
});
});
@@ -0,0 +1,764 @@
type TournamentCodeState =
| 'available'
| 'reserved'
| 'used'
| 'released'
| 'expired'
| 'voided'
| string;
type AnyDoc = Record<string, unknown> & { _id: unknown };
type IndexKey = Record<string, 1 | -1>;
type PartialFilterExpression = Record<string, unknown>;
type Projection = Record<string, 0 | 1>;
interface MigrationCursor {
limit(limit: number): AsyncIterable<AnyDoc>;
}
interface MigrationIndex {
key: IndexKey;
name: string;
partialFilterExpression?: PartialFilterExpression;
unique?: boolean;
}
interface MigrationCollection {
find(
filter: Record<string, unknown>,
options?: { projection?: Projection },
): MigrationCursor;
updateMany(
filter: Record<string, unknown>,
update: {
$pull?: Record<string, unknown>;
$set?: Record<string, unknown>;
$unset?: Record<string, ''>;
},
options?: { ordered?: boolean },
): Promise<{ matchedCount?: number; modifiedCount?: number } | unknown>;
indexes?(): Promise<MigrationIndex[]>;
dropIndex?(name: string): Promise<unknown>;
createIndex?(
key: IndexKey,
options: {
commitQuorum?: number | string;
maxTimeMS?: number;
name: string;
partialFilterExpression?: PartialFilterExpression;
unique?: boolean;
},
): Promise<string>;
}
interface MigrationDb {
collection(name: string): MigrationCollection;
}
interface TournamentCodeDoc extends AnyDoc {
bracketMatchId?: unknown;
code?: unknown;
createdAt?: unknown;
gameNumber?: unknown;
matchId?: unknown;
reservedAt?: unknown;
riotMatchId?: unknown;
state?: TournamentCodeState;
updatedAt?: unknown;
uploadedAt?: unknown;
usedAt?: unknown;
}
interface MatchDoc extends AnyDoc {
tournamentCodeIds?: unknown;
}
interface DesiredIndex {
key: IndexKey;
options: {
name: string;
partialFilterExpression?: PartialFilterExpression;
unique?: boolean;
};
}
interface DuplicateGroup {
codeDocs: TournamentCodeDoc[];
key: string;
kind: TournamentCodeDuplicateKind;
}
interface ReleasePlanEntry {
code: TournamentCodeDoc;
reasons: string[];
}
export type TournamentCodeDuplicateKind =
| 'gameNumber'
| 'bracketMatchId'
| 'riotMatchId';
export interface TournamentCodeDuplicateSummary {
bracketMatchId?: string;
code?: string;
gameNumber?: string;
id: string;
matchId?: string;
riotMatchId?: string;
state?: string;
}
export interface TournamentCodeDuplicateGroupSummary {
keeper: TournamentCodeDuplicateSummary;
key: string;
kind: TournamentCodeDuplicateKind;
losers: TournamentCodeDuplicateSummary[];
}
export interface TournamentCodeUniqueIndexMigrationOptions {
allowUsedDuplicateRelease?: boolean;
createIndexes?: boolean;
dryRun?: boolean;
duplicateSampleLimit?: number;
indexCommitQuorum?: number | string;
indexMaxTimeMS?: number;
now?: Date;
onProgress?: (progress: TournamentCodeUniqueIndexMigrationProgress) => void;
progressInterval?: number;
}
export interface TournamentCodeUniqueIndexMigrationStats {
blankRiotMatchIdsToUnset: number;
blankRiotMatchIdsUnset: number;
duplicateBracketMatchGroups: number;
duplicateCodesReleased: number;
duplicateCodesToRelease: number;
duplicateGameNumberGroups: number;
duplicateRiotMatchGroups: number;
indexesAlreadyCorrect: number;
indexesCreated: number;
indexesDropped: number;
matchesUpdated: number;
scannedCodes: number;
scannedMatches: number;
unsafeUsedDuplicateCodes: number;
unsafeUsedDuplicateGroups: number;
}
export interface TournamentCodeUniqueIndexMigrationResult {
sampleDuplicateGroups: TournamentCodeDuplicateGroupSummary[];
stats: TournamentCodeUniqueIndexMigrationStats;
}
export interface TournamentCodeUniqueIndexMigrationProgress {
action?:
| 'alreadyCorrect'
| 'create'
| 'created'
| 'drop'
| 'dropped'
| 'list';
phase:
| 'scanMatches'
| 'scanTournamentCodes'
| 'cleanupBlankRiotMatchIds'
| 'cleanupDuplicateCodes'
| 'ensureIndexes';
scanned?: number;
indexName?: string;
total?: number;
}
const ACTIVE_CODE_STATES = new Set(['reserved', 'used']);
const MATCH_SCAN_FILTER = { 'tournamentCodeIds.0': { $exists: true } };
const MATCH_SCAN_PROJECTION: Projection = { _id: 1, tournamentCodeIds: 1 };
const TOURNAMENT_CODE_SCAN_FILTER = {
$or: [
{ state: { $in: ['reserved', 'used'] }, matchId: { $exists: true } },
{ riotMatchId: { $type: 'string' } },
],
};
const TOURNAMENT_CODE_SCAN_PROJECTION: Projection = {
_id: 1,
bracketMatchId: 1,
code: 1,
createdAt: 1,
gameNumber: 1,
matchId: 1,
reservedAt: 1,
riotMatchId: 1,
state: 1,
updatedAt: 1,
uploadedAt: 1,
usedAt: 1,
};
const DESIRED_TOURNAMENT_CODE_INDEXES: DesiredIndex[] = [
{
key: { matchId: 1, gameNumber: 1 },
options: {
name: 'matchId_1_gameNumber_1',
unique: true,
partialFilterExpression: {
matchId: { $exists: true },
gameNumber: { $exists: true },
state: { $in: ['reserved', 'used'] },
},
},
},
{
key: { matchId: 1, bracketMatchId: 1 },
options: {
name: 'matchId_1_bracketMatchId_1',
partialFilterExpression: {
matchId: { $exists: true },
bracketMatchId: { $exists: true },
state: { $in: ['reserved', 'used'] },
},
},
},
{
key: { riotMatchId: 1 },
options: {
name: 'riotMatchId_1',
unique: true,
partialFilterExpression: { riotMatchId: { $type: 'string' } },
},
},
];
export async function migrateTournamentCodeUniqueIndexes(
db: MigrationDb,
options: TournamentCodeUniqueIndexMigrationOptions = {},
): Promise<TournamentCodeUniqueIndexMigrationResult> {
const dryRun = options.dryRun ?? true;
const now = options.now ?? new Date();
const tournamentCodeCollection = db.collection('tournamentCode');
const matchCollection = db.collection('match');
const matchScan = await readReferencedTournamentCodeIds(
matchCollection,
options,
);
const codeDocs = await readTournamentCodes(tournamentCodeCollection, options);
const groups = findDuplicateGroups(codeDocs, matchScan.referencedCodeIds);
const releasePlan = buildReleasePlan(groups, matchScan.referencedCodeIds);
const blankRiotMatchCodeIds = codeDocs
.filter(hasBlankRiotMatchId)
.map((code) => code._id);
const unsafePlanEntries = releasePlan.filter(
(entry) => entry.code.state === 'used',
);
const unsafeGroupCount = groups.filter((group) => {
const keeper = chooseKeeper(group, matchScan.referencedCodeIds);
const keeperId = stringifyId(keeper._id);
return group.codeDocs.some(
(code) => stringifyId(code._id) !== keeperId && code.state === 'used',
);
}).length;
const stats: TournamentCodeUniqueIndexMigrationStats = {
blankRiotMatchIdsToUnset: blankRiotMatchCodeIds.length,
blankRiotMatchIdsUnset: 0,
duplicateBracketMatchGroups: groups.filter(
(group) => group.kind === 'bracketMatchId',
).length,
duplicateCodesReleased: 0,
duplicateCodesToRelease: releasePlan.length,
duplicateGameNumberGroups: groups.filter(
(group) => group.kind === 'gameNumber',
).length,
duplicateRiotMatchGroups: groups.filter(
(group) => group.kind === 'riotMatchId',
).length,
indexesAlreadyCorrect: 0,
indexesCreated: 0,
indexesDropped: 0,
matchesUpdated: 0,
scannedCodes: codeDocs.length,
scannedMatches: matchScan.scannedMatches,
unsafeUsedDuplicateCodes: unsafePlanEntries.length,
unsafeUsedDuplicateGroups: unsafeGroupCount,
};
if (
!dryRun &&
unsafePlanEntries.length > 0 &&
options.allowUsedDuplicateRelease !== true
) {
throw new Error(
`Refusing to release ${unsafePlanEntries.length} used duplicate tournament codes. ` +
'Review the duplicate groups manually or re-run with --allow-used-duplicate-release.',
);
}
if (!dryRun) {
if (blankRiotMatchCodeIds.length > 0) {
emitProgress(options, 'cleanupBlankRiotMatchIds', {
total: blankRiotMatchCodeIds.length,
});
const result = await tournamentCodeCollection.updateMany(
{ _id: { $in: blankRiotMatchCodeIds } },
{ $unset: { riotMatchId: '' } },
);
stats.blankRiotMatchIdsUnset = readModifiedCount(result);
}
if (releasePlan.length > 0) {
const releaseIds = releasePlan.map((entry) => entry.code._id);
emitProgress(options, 'cleanupDuplicateCodes', {
total: releaseIds.length,
});
const releaseResult = await tournamentCodeCollection.updateMany(
{ _id: { $in: releaseIds } },
{
$set: { releasedAt: now, state: 'released' },
$unset: {
bracketMatchId: '',
gameNumber: '',
matchId: '',
reservedAt: '',
riotMatchId: '',
usedAt: '',
},
},
);
stats.duplicateCodesReleased = readModifiedCount(releaseResult);
const matchResult = await matchCollection.updateMany(
{ tournamentCodeIds: { $in: releaseIds } },
{ $pull: { tournamentCodeIds: { $in: releaseIds } } },
);
stats.matchesUpdated = readModifiedCount(matchResult);
}
if (options.createIndexes ?? true) {
emitProgress(options, 'ensureIndexes');
const indexStats = await ensureTournamentCodeUniqueIndexes(
tournamentCodeCollection,
options,
);
stats.indexesAlreadyCorrect = indexStats.indexesAlreadyCorrect;
stats.indexesCreated = indexStats.indexesCreated;
stats.indexesDropped = indexStats.indexesDropped;
}
}
return {
sampleDuplicateGroups: summarizeGroups(
groups,
matchScan.referencedCodeIds,
options.duplicateSampleLimit ?? 20,
),
stats,
};
}
async function readTournamentCodes(
collection: MigrationCollection,
options: TournamentCodeUniqueIndexMigrationOptions,
): Promise<TournamentCodeDoc[]> {
const docs: TournamentCodeDoc[] = [];
for await (const doc of collection
.find(TOURNAMENT_CODE_SCAN_FILTER, {
projection: TOURNAMENT_CODE_SCAN_PROJECTION,
})
.limit(0)) {
docs.push(doc as TournamentCodeDoc);
emitScanProgress(options, 'scanTournamentCodes', docs.length);
}
emitProgress(options, 'scanTournamentCodes', { scanned: docs.length });
return docs;
}
async function readReferencedTournamentCodeIds(
collection: MigrationCollection,
options: TournamentCodeUniqueIndexMigrationOptions,
): Promise<{ referencedCodeIds: Set<string>; scannedMatches: number }> {
const referencedCodeIds = new Set<string>();
let scannedMatches = 0;
for await (const doc of collection
.find(MATCH_SCAN_FILTER, { projection: MATCH_SCAN_PROJECTION })
.limit(0)) {
scannedMatches += 1;
emitScanProgress(options, 'scanMatches', scannedMatches);
const ids = (doc as MatchDoc).tournamentCodeIds;
if (!Array.isArray(ids)) continue;
for (const id of ids) {
const stringId = stringifyId(id);
if (stringId) referencedCodeIds.add(stringId);
}
}
emitProgress(options, 'scanMatches', { scanned: scannedMatches });
return { referencedCodeIds, scannedMatches };
}
function emitScanProgress(
options: TournamentCodeUniqueIndexMigrationOptions,
phase: TournamentCodeUniqueIndexMigrationProgress['phase'],
scanned: number,
) {
const interval = options.progressInterval ?? 5_000;
if (interval < 1 || scanned % interval !== 0) return;
emitProgress(options, phase, { scanned });
}
function emitProgress(
options: TournamentCodeUniqueIndexMigrationOptions,
phase: TournamentCodeUniqueIndexMigrationProgress['phase'],
values: Omit<TournamentCodeUniqueIndexMigrationProgress, 'phase'> = {},
) {
options.onProgress?.({ phase, ...values });
}
function findDuplicateGroups(
docs: TournamentCodeDoc[],
referencedCodeIds: Set<string>,
): DuplicateGroup[] {
return [
...duplicateGroupsFor(docs, referencedCodeIds, 'gameNumber'),
...duplicateGroupsFor(docs, referencedCodeIds, 'riotMatchId'),
];
}
function duplicateGroupsFor(
docs: TournamentCodeDoc[],
referencedCodeIds: Set<string>,
kind: TournamentCodeDuplicateKind,
): DuplicateGroup[] {
const groups = new Map<string, TournamentCodeDoc[]>();
for (const doc of docs) {
const key = duplicateKey(doc, kind);
if (!key) continue;
const group = groups.get(key) ?? [];
group.push(doc);
groups.set(key, group);
}
return [...groups.entries()]
.filter(([, groupDocs]) => groupDocs.length > 1)
.map(([key, groupDocs]) => ({
codeDocs: sortCodesByKeeperPriority(groupDocs, referencedCodeIds, kind),
key,
kind,
}));
}
function duplicateKey(
doc: TournamentCodeDoc,
kind: TournamentCodeDuplicateKind,
): string | null {
if (kind === 'riotMatchId') {
if (typeof doc.riotMatchId !== 'string') return null;
if (doc.riotMatchId.trim() === '') return null;
return `riotMatchId:${doc.riotMatchId}`;
}
if (!ACTIVE_CODE_STATES.has(String(doc.state))) return null;
if (!hasField(doc, 'matchId')) return null;
if (kind === 'gameNumber') {
if (!hasField(doc, 'gameNumber')) return null;
return `matchId:${stringifyKeyPart(doc.matchId)}:gameNumber:${stringifyKeyPart(
doc.gameNumber,
)}`;
}
if (!hasField(doc, 'bracketMatchId')) return null;
return `matchId:${stringifyKeyPart(
doc.matchId,
)}:bracketMatchId:${stringifyKeyPart(doc.bracketMatchId)}`;
}
function buildReleasePlan(
groups: DuplicateGroup[],
referencedCodeIds: Set<string>,
): ReleasePlanEntry[] {
const byCodeId = new Map<string, ReleasePlanEntry>();
for (const group of groups) {
const keeper = chooseKeeper(group, referencedCodeIds);
const keeperId = stringifyId(keeper._id);
for (const code of group.codeDocs) {
const codeId = stringifyId(code._id);
if (!codeId || codeId === keeperId) continue;
const entry = byCodeId.get(codeId) ?? { code, reasons: [] };
entry.reasons.push(`${group.kind}:${group.key}`);
byCodeId.set(codeId, entry);
}
}
return [...byCodeId.values()];
}
function summarizeGroups(
groups: DuplicateGroup[],
referencedCodeIds: Set<string>,
limit: number,
): TournamentCodeDuplicateGroupSummary[] {
return groups.slice(0, limit).map((group) => {
const keeper = chooseKeeper(group, referencedCodeIds);
const keeperId = stringifyId(keeper._id);
return {
keeper: summarizeCode(keeper),
key: group.key,
kind: group.kind,
losers: group.codeDocs
.filter((code) => stringifyId(code._id) !== keeperId)
.map(summarizeCode),
};
});
}
function summarizeCode(doc: TournamentCodeDoc): TournamentCodeDuplicateSummary {
return {
bracketMatchId:
doc.bracketMatchId === undefined ? undefined : String(doc.bracketMatchId),
code: doc.code === undefined ? undefined : String(doc.code),
gameNumber:
doc.gameNumber === undefined ? undefined : String(doc.gameNumber),
id: stringifyId(doc._id) ?? '',
matchId: doc.matchId === undefined ? undefined : stringifyId(doc.matchId),
riotMatchId:
doc.riotMatchId === undefined ? undefined : String(doc.riotMatchId),
state: doc.state === undefined ? undefined : String(doc.state),
};
}
function chooseKeeper(
group: DuplicateGroup,
referencedCodeIds: Set<string>,
): TournamentCodeDoc {
return sortCodesByKeeperPriority(
group.codeDocs,
referencedCodeIds,
group.kind,
)[0];
}
function sortCodesByKeeperPriority(
docs: TournamentCodeDoc[],
referencedCodeIds: Set<string>,
kind: TournamentCodeDuplicateKind,
): TournamentCodeDoc[] {
return [...docs].sort((left, right) =>
compareCodePriority(left, right, referencedCodeIds, kind),
);
}
function compareCodePriority(
left: TournamentCodeDoc,
right: TournamentCodeDoc,
referencedCodeIds: Set<string>,
kind: TournamentCodeDuplicateKind,
): number {
if (kind !== 'riotMatchId') {
const leftReferenced = referencedCodeIds.has(stringifyId(left._id) ?? '');
const rightReferenced = referencedCodeIds.has(stringifyId(right._id) ?? '');
if (leftReferenced !== rightReferenced) return leftReferenced ? -1 : 1;
}
const leftStateRank = stateRank(left.state);
const rightStateRank = stateRank(right.state);
if (leftStateRank !== rightStateRank) return leftStateRank - rightStateRank;
if (kind === 'riotMatchId') {
const leftReferenced = referencedCodeIds.has(stringifyId(left._id) ?? '');
const rightReferenced = referencedCodeIds.has(stringifyId(right._id) ?? '');
if (leftReferenced !== rightReferenced) return leftReferenced ? -1 : 1;
}
const leftHasRiotMatch = hasNonBlankRiotMatchId(left);
const rightHasRiotMatch = hasNonBlankRiotMatchId(right);
if (leftHasRiotMatch !== rightHasRiotMatch) {
return leftHasRiotMatch ? -1 : 1;
}
const leftDate = latestTimestamp(left);
const rightDate = latestTimestamp(right);
if (leftDate !== rightDate) return rightDate - leftDate;
return (stringifyId(left._id) ?? '').localeCompare(
stringifyId(right._id) ?? '',
);
}
function stateRank(state: unknown): number {
if (state === 'used') return 0;
if (state === 'reserved') return 1;
if (state === 'available') return 2;
if (state === 'released') return 3;
if (state === 'expired') return 4;
if (state === 'voided') return 5;
return 10;
}
function latestTimestamp(doc: TournamentCodeDoc): number {
return Math.max(
toTimestamp(doc.usedAt),
toTimestamp(doc.reservedAt),
toTimestamp(doc.updatedAt),
toTimestamp(doc.createdAt),
toTimestamp(doc.uploadedAt),
0,
);
}
function toTimestamp(value: unknown): number {
if (value instanceof Date) return value.getTime();
if (typeof value === 'number') return value;
if (typeof value !== 'string') return 0;
const parsed = Date.parse(value);
return Number.isNaN(parsed) ? 0 : parsed;
}
function hasBlankRiotMatchId(doc: TournamentCodeDoc): boolean {
return typeof doc.riotMatchId === 'string' && doc.riotMatchId.trim() === '';
}
function hasNonBlankRiotMatchId(doc: TournamentCodeDoc): boolean {
return typeof doc.riotMatchId === 'string' && doc.riotMatchId.trim() !== '';
}
async function ensureTournamentCodeUniqueIndexes(
collection: MigrationCollection,
options: TournamentCodeUniqueIndexMigrationOptions,
): Promise<{
indexesAlreadyCorrect: number;
indexesCreated: number;
indexesDropped: number;
}> {
if (!collection.indexes || !collection.dropIndex || !collection.createIndex) {
throw new Error('Migration collection does not support index operations.');
}
emitProgress(options, 'ensureIndexes', { action: 'list' });
let indexes = await listCollectionIndexes(collection);
let indexesAlreadyCorrect = 0;
let indexesCreated = 0;
let indexesDropped = 0;
for (const desired of DESIRED_TOURNAMENT_CODE_INDEXES) {
const matchingIndexes = indexes.filter(
(index) =>
index.name === desired.options.name ||
sameObject(index.key, desired.key),
);
const correctIndex = matchingIndexes.find((index) =>
sameIndex(index, desired),
);
if (correctIndex) {
emitProgress(options, 'ensureIndexes', {
action: 'alreadyCorrect',
indexName: desired.options.name,
});
indexesAlreadyCorrect += 1;
continue;
}
for (const index of matchingIndexes) {
if (index.name === '_id_') continue;
emitProgress(options, 'ensureIndexes', {
action: 'drop',
indexName: index.name,
});
await collection.dropIndex(index.name);
emitProgress(options, 'ensureIndexes', {
action: 'dropped',
indexName: index.name,
});
indexesDropped += 1;
}
emitProgress(options, 'ensureIndexes', {
action: 'create',
indexName: desired.options.name,
});
await collection.createIndex(desired.key, {
...desired.options,
...(options.indexCommitQuorum !== undefined
? { commitQuorum: options.indexCommitQuorum }
: {}),
...(options.indexMaxTimeMS !== undefined
? { maxTimeMS: options.indexMaxTimeMS }
: {}),
});
emitProgress(options, 'ensureIndexes', {
action: 'created',
indexName: desired.options.name,
});
indexesCreated += 1;
emitProgress(options, 'ensureIndexes', { action: 'list' });
indexes = await listCollectionIndexes(collection);
}
return { indexesAlreadyCorrect, indexesCreated, indexesDropped };
}
async function listCollectionIndexes(
collection: MigrationCollection,
): Promise<MigrationIndex[]> {
if (!collection.indexes) {
throw new Error('Migration collection does not support index operations.');
}
try {
return await collection.indexes();
} catch (error) {
if (isNamespaceNotFoundError(error)) return [];
throw error;
}
}
function isNamespaceNotFoundError(error: unknown): boolean {
const candidate = error as {
code?: number;
codeName?: string;
message?: string;
};
return Boolean(
candidate?.code === 26 ||
candidate?.codeName === 'NamespaceNotFound' ||
candidate?.message?.includes('ns does not exist'),
);
}
function sameIndex(index: MigrationIndex, desired: DesiredIndex): boolean {
return (
sameObject(index.key, desired.key) &&
index.unique === desired.options.unique &&
sameObject(
index.partialFilterExpression ?? {},
desired.options.partialFilterExpression ?? {},
)
);
}
function sameObject(left: unknown, right: unknown): boolean {
return JSON.stringify(left) === JSON.stringify(right);
}
function readModifiedCount(result: unknown): number {
if (!result || typeof result !== 'object') return 0;
const modifiedCount = (result as { modifiedCount?: unknown }).modifiedCount;
return typeof modifiedCount === 'number' ? modifiedCount : 0;
}
function hasField(doc: Record<string, unknown>, key: string): boolean {
return Object.prototype.hasOwnProperty.call(doc, key);
}
function stringifyKeyPart(value: unknown): string {
if (value === null) return '<null>';
if (value === undefined) return '<undefined>';
return stringifyId(value) ?? String(value);
}
function stringifyId(value: unknown): string | undefined {
if (value === undefined || value === null) return undefined;
return typeof value === 'string' ? value : String(value);
}
@@ -0,0 +1,303 @@
import { projectCompetition } from '../../../competition/domain/competition-projector';
import {
planCompetitionMigration,
type LegacyMatchInput,
type ReadyCompetitionMigrationPlan,
} from './20260712-competition-domain';
describe('planCompetitionMigration', () => {
it('produces deterministic, idempotent identities and maps legacy bracket mode explicitly', () => {
const legacy = pairedMatch({ gameMode: 'bracket' });
const first = planCompetitionMigration(legacy);
const second = planCompetitionMigration(structuredClone(legacy));
expect(first).toEqual(second);
const plan = requireReady(first);
expect(plan.competition.id).toMatch(/^[a-f0-9]{24}$/);
expect(plan.competition.teams.map((team) => team.teamId)).toEqual(
expect.arrayContaining([
expect.stringMatching(/^[a-f0-9]{24}$/),
expect.stringMatching(/^[a-f0-9]{24}$/),
]),
);
expect(plan.competition.format).toMatchObject({ type: 'paired-series' });
expect(plan.warnings).toContainEqual(
expect.objectContaining({
code: 'LEGACY_BRACKET_MAPPED_TO_PAIRED_SERIES',
}),
);
});
it('preserves Riot-backed and normalized-only games as different evidence kinds', () => {
const legacy = pairedMatch({ gameCount: 2 });
legacy.result = {
games: [
legacyGame({
gameNumber: 1,
riotMatchId: 'KR_WITH_ARCHIVE',
blueTeamIndex: 1,
redTeamIndex: 2,
winnerTeamIndex: 1,
riotArchivePresent: true,
}),
legacyGame({
gameNumber: 2,
riotMatchId: 'KR_NORMALIZED_ONLY',
blueTeamIndex: 2,
redTeamIndex: 1,
winnerTeamIndex: 2,
riotArchivePresent: false,
}),
],
seriesResults: [],
};
const plan = requireReady(planCompetitionMigration(legacy));
const games = plan.facts.filter((fact) => fact.type === 'game-accepted');
expect(games).toHaveLength(2);
expect(games[0]).toMatchObject({
evidence: {
type: 'riot',
riotMatchId: 'KR_WITH_ARCHIVE',
},
});
expect(games[1]).toMatchObject({
evidence: {
type: 'legacy',
legacyReference: expect.stringContaining('KR_NORMALIZED_ONLY'),
},
});
});
it('turns a winner-only Series into an adjudication without fabricating games', () => {
const legacy = pairedMatch({ gameCount: 3 });
legacy.result = {
games: [],
seriesResults: [
{
teamAIndex: 1,
teamBIndex: 2,
teamAWins: 0,
teamBWins: 0,
winnerTeamIndex: 2,
},
],
};
const plan = requireReady(planCompetitionMigration(legacy));
expect(plan.facts).toHaveLength(1);
expect(plan.facts[0]).toMatchObject({
type: 'series-adjudicated',
decision: {
type: 'administrative',
winnerTeamId: plan.competition.teams[1].teamId,
},
reason: 'legacy-winner-only-result',
});
expect(plan.facts).not.toContainEqual(
expect.objectContaining({ type: 'game-accepted' }),
);
});
it('quarantines an ambiguous legacy game assignment instead of guessing', () => {
const legacy = pairedMatch({
teams: [
legacyTeam(1, 'One'),
legacyTeam(2, 'Two'),
legacyTeam(3, 'Three'),
legacyTeam(4, 'Four'),
],
});
legacy.gameSchedule = [
{ gameNumber: 7, teamAIndex: 1, teamBIndex: 2 },
{ gameNumber: 7, teamAIndex: 3, teamBIndex: 4 },
];
legacy.result = {
games: [
legacyGame({
gameNumber: 7,
riotMatchId: 'KR_AMBIGUOUS',
blueTeamIndex: 1,
redTeamIndex: 2,
winnerTeamIndex: 1,
riotArchivePresent: true,
}),
],
seriesResults: [],
};
const plan = planCompetitionMigration(legacy);
expect(plan).toMatchObject({
status: 'quarantined',
reasons: expect.arrayContaining([
expect.objectContaining({ code: 'AMBIGUOUS_GAME_ASSIGNMENT' }),
]),
});
});
it('repairs the data.txt WB_R2_M2 positional bug from accepted game evidence', () => {
const legacy = loadDataTxtFixture();
const plan = requireReady(planCompetitionMigration(legacy));
const projection = projectCompetition({
competitionId: plan.competition.id,
revision: plan.competition.revision,
projectorVersion: plan.competition.projectorVersion,
teams: plan.competition.teams,
format: plan.competition.format,
seriesGraph: plan.competition.seriesGraph,
facts: plan.facts,
});
const team3 = plan.competition.teams.find(
(team) => team.legacyTeamIndex === 3,
);
const team8 = plan.competition.teams.find(
(team) => team.legacyTeamIndex === 8,
);
const series = (code: string) =>
projection.series.find((candidate) => candidate.code === code);
expect(team3).toBeDefined();
expect(team8).toBeDefined();
expect(series('WB_R2_M2')).toMatchObject({
status: 'completed',
entries: [
{ slot: 'A', teamId: team8!.teamId, gameWins: 2 },
{ slot: 'B', teamId: team3!.teamId, gameWins: 1 },
],
outcome: {
type: 'played',
winnerTeamId: team8!.teamId,
loserTeamId: team3!.teamId,
},
});
expect(series('WB_FINAL')).toMatchObject({
entries: expect.arrayContaining([
{ slot: 'B', teamId: team8!.teamId, gameWins: 0 },
]),
});
expect(series('LB_R2_M1')).toMatchObject({
entries: expect.arrayContaining([
{ slot: 'B', teamId: team3!.teamId, gameWins: 0 },
]),
});
});
});
function pairedMatch(
overrides: Partial<LegacyMatchInput> = {},
): LegacyMatchInput {
return {
_id: 'match-legacy-paired',
communityId: 'community-1',
gameMode: 'pair',
gameCount: 1,
status: 'in-progress',
teams: [legacyTeam(1, 'One'), legacyTeam(2, 'Two')],
gameSchedule: [{ gameNumber: 1, teamAIndex: 1, teamBIndex: 2 }],
createdAt: '2026-07-01T00:00:00.000Z',
updatedAt: '2026-07-02T00:00:00.000Z',
...overrides,
};
}
function legacyTeam(teamIndex: number, name: string) {
return {
teamIndex,
name,
captainUserId: `captain-${teamIndex}`,
members: [],
};
}
function legacyGame(
overrides: Partial<NonNullable<LegacyMatchInput['result']>['games'][number]>,
): NonNullable<LegacyMatchInput['result']>['games'][number] {
return {
gameNumber: 1,
riotMatchId: 'KR_DEFAULT',
blueTeamIndex: 1,
redTeamIndex: 2,
winnerTeamIndex: 1,
gameCreation: 1782864000000,
gameDuration: 1800,
participants: [],
...overrides,
};
}
function requireReady(
plan: ReturnType<typeof planCompetitionMigration>,
): ReadyCompetitionMigrationPlan {
if (plan.status !== 'ready') {
throw new Error(
`Expected ready migration plan: ${JSON.stringify(plan.reasons)}`,
);
}
return plan;
}
function loadDataTxtFixture(): LegacyMatchInput {
const seededTeamIndexes = [1, 8, 3, 4, 5, 6, 7, 2];
const games = [
['WB_R1_M3', 8, 7, 8],
['WB_R1_M3', 7, 8, 8],
['WB_R1_M4', 3, 6, 3],
['WB_R1_M4', 6, 3, 3],
['WB_R2_M2', 3, 8, 8],
['WB_R2_M2', 8, 3, 3],
['WB_R2_M2', 3, 8, 8],
] as const;
return {
_id: '6a3e0c2c8ade90b14b72f335',
communityId: '69ebe0adf627c11be2f020a1',
gameMode: 'double-elimination',
gameCount: 3,
status: 'in-progress',
teams: Array.from({ length: 8 }, (_, index) =>
legacyTeam(
index + 1,
index + 1 === 3
? '해온해줘'
: index + 1 === 8
? '똥칼라파워'
: `${index + 1}팀`,
),
),
doubleElimination: {
teamCount: 8,
resetFinalEnabled: true,
seeds: seededTeamIndexes.map((teamIndex, index) => ({
seedNumber: index + 1,
teamIndex,
})),
bracketMatches: [],
},
result: {
games: games.map(
(
[bracketMatchId, blueTeamIndex, redTeamIndex, winnerTeamIndex],
index,
) =>
legacyGame({
gameNumber: index + 1,
bracketMatchId,
riotMatchId: `KR_DATA_TXT_${index + 1}`,
riotArchivePresent: true,
blueTeamIndex,
redTeamIndex,
winnerTeamIndex,
gameCreation: 1782864000000 + index * 60_000,
}),
),
seriesResults: [],
},
createdAt: '2026-06-27T05:18:00.000Z',
updatedAt: '2026-07-12T17:17:00.000Z',
};
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,842 @@
import mongoose from 'mongoose';
import {
migrateCompetitionDomain,
type CompetitionDomainMigrationDb,
type CompetitionDomainMigrationSession,
} from './competition-domain-runner';
describe('migrateCompetitionDomain', () => {
it('defaults to a side-effect-free dry run and reports the deterministic plan', async () => {
const match = readyMatch();
const db = new MemoryMigrationDb({
match: [match],
riotMatch: [riotArchive()],
tournamentCode: [usedTournamentCode(match)],
});
const startSession = jest.fn(async () => new FakeSession());
const result = await migrateCompetitionDomain(db, { startSession });
expect(result.mode).toBe('dry-run');
expect(result.summary).toMatchObject({
scanned: 1,
ready: 1,
applied: 0,
quarantined: 0,
failed: 0,
unclassified: 0,
factsPlanned: 1,
assignmentsPlanned: 1,
});
expect(result.matches[0]).toMatchObject({
status: 'ready',
factCount: 1,
assignmentCount: 1,
});
expect(startSession).not.toHaveBeenCalled();
expect(db.writeCount).toBe(0);
expect(db.docs('competition')).toHaveLength(0);
expect(db.createdIndexes).toHaveLength(0);
});
it.each([
['absent', (match: AnyDoc) => delete match.gameMode],
['null', (match: AnyDoc) => (match.gameMode = null)],
])(
'restores the historical pair default when raw Mongo Match gameMode is %s',
async (_label, omitGameMode) => {
const match = readyMatch();
omitGameMode(match);
const before = canonical(match);
const db = new MemoryMigrationDb({
match: [match],
riotMatch: [riotArchive()],
tournamentCode: [usedTournamentCode(match)],
});
const result = await migrateCompetitionDomain(db);
expect(result.summary).toMatchObject({
scanned: 1,
ready: 1,
quarantined: 0,
failed: 0,
});
expect(result.matches[0]).toMatchObject({
status: 'ready',
factCount: 1,
assignmentCount: 1,
});
expect(canonical(db.docs('match')[0])).toBe(before);
expect(db.writeCount).toBe(0);
},
);
it('keeps an explicitly unknown raw Mongo Match gameMode quarantined', async () => {
const match = readyMatch();
match.gameMode = 'future-mode';
const db = new MemoryMigrationDb({ match: [match] });
const result = await migrateCompetitionDomain(db);
expect(result.summary).toMatchObject({
scanned: 1,
ready: 0,
quarantined: 1,
failed: 0,
});
expect(result.matches[0]).toMatchObject({
status: 'quarantined',
reasons: [
expect.objectContaining({ code: 'UNSUPPORTED_LEGACY_GAME_MODE' }),
],
});
expect(db.writeCount).toBe(0);
});
it('applies one Match atomically and converges on an already-applied replay', async () => {
const match = readyMatch();
const originalResult = canonical(match.result);
const db = new MemoryMigrationDb({
match: [match],
riotMatch: [riotArchive()],
tournamentCode: [usedTournamentCode(match)],
});
const sessions: FakeSession[] = [];
const startSession = jest.fn(async () => {
const session = new FakeSession();
sessions.push(session);
return session;
});
const first = await migrateCompetitionDomain(db, {
dryRun: false,
startSession,
});
expect(first.summary).toMatchObject({
scanned: 1,
applied: 1,
alreadyApplied: 0,
failed: 0,
});
expect(db.docs('competition')).toHaveLength(1);
expect(db.docs('competition_fact')).toHaveLength(1);
expect(db.docs('competition_fact')[0].evidence).toMatchObject({
type: 'riot',
riotMatchId: 'KR_MIGRATION_1',
payloadHash: expect.stringMatching(/^sha256:[a-f0-9]{64}$/),
});
expect(db.docs('tournament_code_assignment')).toHaveLength(1);
expect(db.docs('competition_migration_quarantine')).toHaveLength(0);
expect(String(db.docs('match')[0].competitionId)).toBe(
first.matches[0].competitionId,
);
expect(canonical(db.docs('match')[0].result)).toBe(originalResult);
expect(sessions[0]).toMatchObject({
started: 1,
committed: 1,
aborted: 0,
ended: 1,
});
const second = await migrateCompetitionDomain(db, {
dryRun: false,
startSession,
});
expect(second.summary).toMatchObject({
scanned: 1,
applied: 0,
alreadyApplied: 1,
failed: 0,
});
expect(db.docs('competition')).toHaveLength(1);
expect(db.docs('competition_fact')).toHaveLength(1);
expect(db.docs('tournament_code_assignment')).toHaveLength(1);
expect(sessions[1]).toMatchObject({ committed: 1, aborted: 0, ended: 1 });
});
it('quarantines an ambiguous Match without changing any legacy Match field', async () => {
const match = ambiguousMatch();
const before = canonical(match);
const db = new MemoryMigrationDb({ match: [match] });
const session = new FakeSession();
const result = await migrateCompetitionDomain(db, {
dryRun: false,
startSession: async () => session,
});
expect(result.summary).toMatchObject({
scanned: 1,
quarantined: 1,
applied: 0,
failed: 0,
});
expect(result.matches[0]).toMatchObject({
status: 'quarantined',
reasons: expect.arrayContaining([
expect.objectContaining({ code: 'AMBIGUOUS_GAME_ASSIGNMENT' }),
]),
});
expect(canonical(db.docs('match')[0])).toBe(before);
expect(db.docs('competition')).toHaveLength(0);
expect(db.docs('competition_fact')).toHaveLength(0);
expect(db.docs('competition_migration_quarantine')).toHaveLength(1);
expect(session).toMatchObject({ committed: 1, aborted: 0, ended: 1 });
});
it('aborts and reports a failed Match when persisted projection replay diverges', async () => {
const match = readyMatch();
const db = new MemoryMigrationDb({
match: [match],
riotMatch: [riotArchive()],
tournamentCode: [usedTournamentCode(match)],
});
await migrateCompetitionDomain(db, {
dryRun: false,
startSession: async () => new FakeSession(),
});
db.docs('competition')[0].projection = {
phase: 'completed',
corrupt: true,
};
const session = new FakeSession();
const result = await migrateCompetitionDomain(db, {
dryRun: false,
startSession: async () => session,
});
expect(result.summary).toMatchObject({
scanned: 1,
applied: 0,
alreadyApplied: 0,
failed: 1,
});
expect(result.matches[0]).toMatchObject({
status: 'failed',
error: expect.stringContaining('replay'),
});
expect(session).toMatchObject({ committed: 0, aborted: 1, ended: 1 });
});
it('reports apply failures without attempting writes when no session can be created', async () => {
const db = new MemoryMigrationDb({ match: [readyMatch()] });
const result = await migrateCompetitionDomain(db, {
dryRun: false,
startSession: async () => undefined,
});
expect(result.summary.failed).toBe(1);
expect(result.matches[0]).toMatchObject({
status: 'failed',
error: expect.stringContaining('transaction session'),
});
expect(db.writeCount).toBe(0);
});
it('ensures every Competition unique or partial index before the first apply write', async () => {
const match = readyMatch();
const db = new MemoryMigrationDb({
match: [match],
riotMatch: [riotArchive()],
tournamentCode: [usedTournamentCode(match)],
});
const result = await migrateCompetitionDomain(db, {
dryRun: false,
startSession: () => Promise.resolve(new FakeSession()),
});
expect(result.indexPreflight).toMatchObject({
status: 'ensured',
requiredIndexes: 10,
conflicts: [],
});
expect(result.indexPreflight.ensuredIndexes).toHaveLength(10);
expect(db.createdIndexes).toHaveLength(10);
expect(db.createdIndexes).toEqual(
expect.arrayContaining([
expect.objectContaining({
collection: 'match',
key: { competitionId: 1 },
options: expect.objectContaining({
unique: true,
partialFilterExpression: {
competitionId: { $type: 'objectId' },
},
}),
}),
expect.objectContaining({
collection: 'competition',
key: { matchId: 1 },
options: expect.objectContaining({ unique: true }),
}),
expect.objectContaining({
collection: 'competition_fact',
key: { 'evidence.riotMatchId': 1 },
options: expect.objectContaining({
unique: true,
partialFilterExpression: expect.any(Object),
}),
}),
expect.objectContaining({
collection: 'tournament_code_assignment',
key: { gameSlotId: 1 },
options: expect.objectContaining({
unique: true,
partialFilterExpression: expect.any(Object),
}),
}),
]),
);
expect(db.operations.indexOf('create-index')).toBeLessThan(
db.operations.indexOf('write'),
);
});
it('blocks apply with a machine-readable report when a required index cannot be created', async () => {
const match = readyMatch();
const db = new MemoryMigrationDb({ match: [match] });
db.indexCreationError = Object.assign(
new Error('E11000 duplicate key while building competitionId_1'),
{
code: 11000,
keyPattern: { competitionId: 1 },
keyValue: { competitionId: match._id },
},
);
const startSession = jest.fn(() => Promise.resolve(new FakeSession()));
const result = await migrateCompetitionDomain(db, {
dryRun: false,
startSession,
});
expect(result.indexPreflight).toMatchObject({
status: 'blocked',
conflicts: [
expect.objectContaining({
collection: 'match',
code: 11000,
keyValue: {
competitionId: (match._id as mongoose.Types.ObjectId).toHexString(),
},
}),
],
});
expect(result.matches).toEqual([]);
expect(result.summary.scanned).toBe(0);
expect(startSession).not.toHaveBeenCalled();
expect(db.writeCount).toBe(0);
});
it('quarantines a later Match that reuses an already accepted global Riot identity', async () => {
const firstMatch = readyMatch('KR_SHARED_MIGRATION');
const secondMatch = readyMatch('KR_SHARED_MIGRATION');
const db = new MemoryMigrationDb({
match: [firstMatch, secondMatch],
riotMatch: [riotArchive('KR_SHARED_MIGRATION')],
tournamentCode: [
usedTournamentCode(firstMatch, 'KR_SHARED_MIGRATION'),
usedTournamentCode(secondMatch, 'KR_SHARED_MIGRATION'),
],
});
const result = await migrateCompetitionDomain(db, {
dryRun: false,
startSession: () => Promise.resolve(new FakeSession()),
});
expect(result.summary).toMatchObject({ applied: 1, quarantined: 1 });
expect(result.matches).toContainEqual(
expect.objectContaining({
status: 'quarantined',
reasons: expect.arrayContaining([
expect.objectContaining({ code: 'GLOBAL_UNIQUE_INDEX_CONFLICT' }),
]),
}),
);
expect(db.docs('competition_fact')).toHaveLength(1);
expect(db.docs('competition_migration_quarantine')).toHaveLength(1);
});
it('resumes repeated limited apply runs after the durable Match checkpoint', async () => {
const firstMatch = readyMatch('KR_BATCH_1');
const secondMatch = readyMatch('KR_BATCH_2');
const db = new MemoryMigrationDb({
match: [firstMatch, secondMatch],
riotMatch: [riotArchive('KR_BATCH_1'), riotArchive('KR_BATCH_2')],
tournamentCode: [
usedTournamentCode(firstMatch, 'KR_BATCH_1'),
usedTournamentCode(secondMatch, 'KR_BATCH_2'),
],
});
const first = await migrateCompetitionDomain(db, {
dryRun: false,
limit: 1,
startSession: () => Promise.resolve(new FakeSession()),
});
const second = await migrateCompetitionDomain(db, {
dryRun: false,
limit: 1,
startSession: () => Promise.resolve(new FakeSession()),
});
expect(first.summary).toMatchObject({ scanned: 1, applied: 1 });
expect(first.resume).toMatchObject({
strategy: 'checkpoint',
hasMore: true,
completed: false,
});
expect(second.summary).toMatchObject({ scanned: 1, applied: 1 });
expect(second.matches[0].matchId).not.toBe(first.matches[0].matchId);
expect(second.resume).toMatchObject({
strategy: 'checkpoint',
startedAfterMatchId: first.matches[0].matchId,
hasMore: false,
completed: true,
});
expect(db.docs('competition')).toHaveLength(2);
expect(db.docs('competition_migration_checkpoint')).toHaveLength(1);
});
it('does not let an apply checkpoint silently narrow a later dry-run', async () => {
const firstMatch = readyMatch('KR_DRY_RUN_1');
const secondMatch = readyMatch('KR_DRY_RUN_2');
const db = new MemoryMigrationDb({
match: [firstMatch, secondMatch],
riotMatch: [riotArchive('KR_DRY_RUN_1'), riotArchive('KR_DRY_RUN_2')],
tournamentCode: [
usedTournamentCode(firstMatch, 'KR_DRY_RUN_1'),
usedTournamentCode(secondMatch, 'KR_DRY_RUN_2'),
],
});
const applied = await migrateCompetitionDomain(db, {
dryRun: false,
limit: 1,
startSession: () => Promise.resolve(new FakeSession()),
});
const dryRun = await migrateCompetitionDomain(db, {
dryRun: true,
limit: 1,
});
expect(dryRun.resume.strategy).toBe('none');
expect(dryRun.matches[0].matchId).toBe(applied.matches[0].matchId);
});
it('does not advance a limited-run checkpoint past a failed Match', async () => {
const match = readyMatch('KR_RETRY_AFTER_FAILURE');
const db = new MemoryMigrationDb({
match: [match],
riotMatch: [riotArchive('KR_RETRY_AFTER_FAILURE')],
tournamentCode: [usedTournamentCode(match, 'KR_RETRY_AFTER_FAILURE')],
});
const failed = await migrateCompetitionDomain(db, {
dryRun: false,
limit: 1,
startSession: () => Promise.resolve(undefined),
});
expect(failed.summary).toMatchObject({ scanned: 1, failed: 1 });
expect(failed.resume).toMatchObject({
strategy: 'checkpoint',
hasMore: true,
completed: false,
});
expect(db.docs('competition_migration_checkpoint')).toHaveLength(0);
const retried = await migrateCompetitionDomain(db, {
dryRun: false,
limit: 1,
startSession: () => Promise.resolve(new FakeSession()),
});
expect(db.docs('competition_migration_checkpoint')).toHaveLength(1);
expect(retried.matches[0].matchId).toBe(failed.matches[0].matchId);
expect(retried.summary).toMatchObject({ scanned: 1, applied: 1 });
});
it('durably overrides a later checkpoint before an explicit earlier retry can fail', async () => {
const retryMatch = readyMatch('KR_EXPLICIT_RETRY');
const laterMatch = readyMatch('KR_LATER_CHECKPOINT');
const explicitAfter = '000000000000000000000000';
const migrationRunId = '20260712-competition-domain';
const db = new MemoryMigrationDb({
match: [retryMatch, laterMatch],
riotMatch: [
riotArchive('KR_EXPLICIT_RETRY'),
riotArchive('KR_LATER_CHECKPOINT'),
],
tournamentCode: [
usedTournamentCode(retryMatch, 'KR_EXPLICIT_RETRY'),
usedTournamentCode(laterMatch, 'KR_LATER_CHECKPOINT'),
],
competition_migration_checkpoint: [
{
_id: migrationRunId,
migrationRunId,
lastMatchId: laterMatch._id,
status: 'running',
},
],
});
const failed = await migrateCompetitionDomain(db, {
dryRun: false,
limit: 1,
afterMatchId: explicitAfter,
startSession: () => Promise.resolve(undefined),
});
expect(failed.summary).toMatchObject({ scanned: 1, failed: 1 });
expect(
String(db.docs('competition_migration_checkpoint')[0].lastMatchId),
).toBe(explicitAfter);
const retried = await migrateCompetitionDomain(db, {
dryRun: false,
limit: 1,
startSession: () => Promise.resolve(new FakeSession()),
});
expect(retried.matches[0].matchId).toBe(failed.matches[0].matchId);
expect(retried.summary).toMatchObject({ scanned: 1, applied: 1 });
});
it('does not persist an explicit checkpoint override during dry-run', async () => {
const match = readyMatch('KR_DRY_EXPLICIT_CURSOR');
const migrationRunId = '20260712-competition-domain';
const persistedCheckpoint = objectId();
const db = new MemoryMigrationDb({
match: [match],
riotMatch: [riotArchive('KR_DRY_EXPLICIT_CURSOR')],
tournamentCode: [usedTournamentCode(match, 'KR_DRY_EXPLICIT_CURSOR')],
competition_migration_checkpoint: [
{
_id: migrationRunId,
migrationRunId,
lastMatchId: persistedCheckpoint,
status: 'running',
},
],
});
await migrateCompetitionDomain(db, {
dryRun: true,
limit: 1,
afterMatchId: '000000000000000000000000',
});
expect(
String(db.docs('competition_migration_checkpoint')[0].lastMatchId),
).toBe(persistedCheckpoint.toHexString());
expect(db.writeCount).toBe(0);
});
});
class FakeSession implements CompetitionDomainMigrationSession {
public started = 0;
public committed = 0;
public aborted = 0;
public ended = 0;
startTransaction(): void {
this.started += 1;
}
async commitTransaction(): Promise<void> {
this.committed += 1;
}
async abortTransaction(): Promise<void> {
this.aborted += 1;
}
async endSession(): Promise<void> {
this.ended += 1;
}
}
type AnyDoc = Record<string, any> & { _id: unknown };
class MemoryMigrationDb implements CompetitionDomainMigrationDb {
private readonly collections = new Map<string, AnyDoc[]>();
public writeCount = 0;
public readonly createdIndexes: Array<{
collection: string;
key: Record<string, unknown>;
options: Record<string, unknown>;
}> = [];
public readonly operations: string[] = [];
public indexCreationError?: Error;
constructor(seed: Record<string, AnyDoc[]> = {}) {
for (const [name, docs] of Object.entries(seed)) {
this.collections.set(name, docs);
}
}
docs(name: string): AnyDoc[] {
const docs = this.collections.get(name) ?? [];
this.collections.set(name, docs);
return docs;
}
collection(name: string) {
const owner = this;
return {
createIndex(
key: Record<string, unknown>,
options: Record<string, unknown>,
) {
owner.operations.push('create-index');
if (owner.indexCreationError) {
const error = owner.indexCreationError;
owner.indexCreationError = undefined;
return Promise.reject(error);
}
owner.createdIndexes.push({ collection: name, key, options });
return Promise.resolve(
typeof options.name === 'string'
? options.name
: Object.keys(key).join('_'),
);
},
find(filter: Record<string, unknown>) {
return new MemoryCursor(() =>
owner.docs(name).filter((doc) => matches(doc, filter)),
);
},
async findOne(filter: Record<string, unknown>) {
return owner.docs(name).find((doc) => matches(doc, filter)) ?? null;
},
async updateOne(
filter: Record<string, unknown>,
update: Record<string, Record<string, unknown>>,
options: { upsert?: boolean } = {},
) {
owner.operations.push('write');
owner.writeCount += 1;
const docs = owner.docs(name);
let doc = docs.find((candidate) => matches(candidate, filter));
const inserted = !doc && options.upsert === true;
if (inserted) {
doc = materializeEqualityFilter(filter);
docs.push(doc);
}
if (!doc) return { matchedCount: 0, modifiedCount: 0 };
if (inserted) Object.assign(doc, update.$setOnInsert ?? {});
Object.assign(doc, update.$set ?? {});
for (const field of Object.keys(update.$unset ?? {})) delete doc[field];
return {
matchedCount: inserted ? 0 : 1,
modifiedCount: 1,
upsertedCount: inserted ? 1 : 0,
};
},
async deleteOne(filter: Record<string, unknown>) {
owner.operations.push('write');
owner.writeCount += 1;
const docs = owner.docs(name);
const index = docs.findIndex((doc) => matches(doc, filter));
if (index === -1) return { deletedCount: 0 };
docs.splice(index, 1);
return { deletedCount: 1 };
},
};
}
}
class MemoryCursor {
private sortSpec: Record<string, 1 | -1> = {};
private max = 0;
constructor(private readonly read: () => AnyDoc[]) {}
sort(spec: Record<string, 1 | -1>): this {
this.sortSpec = spec;
return this;
}
limit(limit: number): this {
this.max = limit;
return this;
}
async *[Symbol.asyncIterator](): AsyncIterator<AnyDoc> {
const entries = [...this.read()].sort((left, right) => {
for (const [key, direction] of Object.entries(this.sortSpec)) {
const compared = String(readPath(left, key)).localeCompare(
String(readPath(right, key)),
);
if (compared !== 0) return compared * direction;
}
return 0;
});
for (const doc of this.max > 0 ? entries.slice(0, this.max) : entries) {
yield doc;
}
}
}
function matches(doc: AnyDoc, filter: Record<string, unknown>): boolean {
return Object.entries(filter).every(([key, expected]) => {
if (key === '$or') {
return (expected as Record<string, unknown>[]).some((candidate) =>
matches(doc, candidate),
);
}
const actual = readPath(doc, key);
if (isRecord(expected)) {
if ('$exists' in expected) {
return (actual !== undefined) === Boolean(expected.$exists);
}
if ('$in' in expected) {
return (expected.$in as unknown[]).some((candidate) =>
sameValue(actual, candidate),
);
}
if ('$gt' in expected) {
return String(actual) > String(expected.$gt);
}
}
return sameValue(actual, expected);
});
}
function readPath(value: unknown, path: string): unknown {
return path.split('.').reduce<unknown>((current, segment) => {
if (Array.isArray(current) && /^\d+$/.test(segment)) {
return current[Number(segment)];
}
return isRecord(current) ? current[segment] : undefined;
}, value);
}
function materializeEqualityFilter(filter: Record<string, unknown>): AnyDoc {
return Object.fromEntries(
Object.entries(filter).filter(
([key, value]) => !key.startsWith('$') && !isRecord(value),
),
) as AnyDoc;
}
function sameValue(left: unknown, right: unknown): boolean {
return String(left) === String(right);
}
function isRecord(value: unknown): value is Record<string, any> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function readyMatch(riotMatchId = 'KR_MIGRATION_1'): AnyDoc {
const matchId = objectId();
const codeId = objectId();
return {
_id: matchId,
communityId: objectId(),
gameMode: 'pair',
gameCount: 1,
status: 'in-progress',
participants: [],
teams: [legacyTeam(1), legacyTeam(2)],
gameSchedule: [{ gameNumber: 1, teamAIndex: 1, teamBIndex: 2 }],
tournamentCodeIds: [codeId],
result: {
riotMatchIds: [riotMatchId],
games: [
{
gameNumber: 1,
riotMatchId,
blueTeamIndex: 1,
redTeamIndex: 2,
winnerTeamIndex: 1,
winnerSide: 'blue',
gameCreation: 1_782_864_000_000,
gameDuration: 1800,
participants: [],
},
],
seriesResults: [],
},
createdAt: new Date('2026-07-01T00:00:00.000Z'),
updatedAt: new Date('2026-07-02T00:00:00.000Z'),
};
}
function usedTournamentCode(
match = readyMatch(),
riotMatchId = 'KR_MIGRATION_1',
): AnyDoc {
return {
_id: match.tournamentCodeIds[0],
matchId: match._id,
state: 'used',
gameNumber: 1,
riotMatchId,
reservedAt: new Date('2026-07-01T00:30:00.000Z'),
usedAt: new Date('2026-07-01T01:00:00.000Z'),
};
}
function riotArchive(matchId = 'KR_MIGRATION_1'): AnyDoc {
return {
_id: objectId(),
matchId,
raw: { metadata: { matchId } },
};
}
function ambiguousMatch(): AnyDoc {
const match = readyMatch();
match.teams = [legacyTeam(1), legacyTeam(2), legacyTeam(3), legacyTeam(4)];
match.gameSchedule = [
{ gameNumber: 7, teamAIndex: 1, teamBIndex: 2 },
{ gameNumber: 7, teamAIndex: 3, teamBIndex: 4 },
];
match.tournamentCodeIds = [];
match.result = {
games: [
{
gameNumber: 7,
riotMatchId: 'KR_AMBIGUOUS',
blueTeamIndex: 1,
redTeamIndex: 2,
winnerTeamIndex: 1,
winnerSide: 'blue',
participants: [],
},
],
seriesResults: [],
};
return match;
}
function legacyTeam(teamIndex: number) {
return {
teamIndex,
name: `${teamIndex}팀`,
captainUserId: objectId(),
members: [],
};
}
function objectId(): mongoose.Types.ObjectId {
return new mongoose.Types.ObjectId();
}
function canonical(value: unknown): string {
return JSON.stringify(value, (_key, child) => {
if (child instanceof mongoose.Types.ObjectId) return child.toHexString();
if (child instanceof Date) return child.toISOString();
return child;
});
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,94 @@
import mongoose from 'mongoose';
import { buildRepairPlan } from './repair-double-elimination-series-rules';
import type { MatchDocument, TournamentCodeDocument } from '../schema';
function createMatch(overrides: Partial<MatchDocument>): MatchDocument {
return {
_id: new mongoose.Types.ObjectId(),
gameCount: 3,
tournamentCodeIds: [],
doubleElimination: {
teamCount: 8,
resetFinalEnabled: false,
resetFinalCreated: false,
seeds: [],
bracketMatches: [],
placements: {},
events: [],
},
...overrides,
} as unknown as MatchDocument;
}
function createCode(
overrides: Partial<TournamentCodeDocument>,
): TournamentCodeDocument {
return {
_id: new mongoose.Types.ObjectId(),
code: 'CODE',
state: 'reserved',
...overrides,
} as unknown as TournamentCodeDocument;
}
describe('repair-double-elimination-series-rules buildRepairPlan', () => {
it('plans missing ready series slots even when result games already exist', () => {
const match = createMatch({
result: {
riotMatchIds: ['KR_1'],
games: [
{
gameNumber: 1,
bracketMatchId: 'WB_R2_M1',
},
],
seriesResults: [],
},
doubleElimination: {
teamCount: 8,
resetFinalEnabled: false,
resetFinalCreated: false,
seeds: [],
bracketMatches: [
{
bracketMatchId: 'WB_R2_M1',
gameNumber: 1,
gameCount: 3,
requiredWins: 2,
bracketSide: 'winner',
roundNumber: 2,
matchNumber: 1,
state: 'ready',
teamAIndex: 4,
teamBIndex: 6,
},
],
placements: {},
events: [],
},
});
const existingFirstSetCode = createCode({
bracketMatchId: 'WB_R2_M1',
gameNumber: 1,
});
const plan = buildRepairPlan(match, [existingFirstSetCode], 3);
expect(plan.ruleRepairSkippedReason).toBe('result-games-exist');
expect(plan.codeUpdates).toEqual([]);
expect(plan.missingReadySlots).toEqual([
{
bracketMatchId: 'WB_R2_M1',
gameNumber: 2,
seriesGameNumber: 2,
seriesGameCount: 3,
},
{
bracketMatchId: 'WB_R2_M1',
gameNumber: 3,
seriesGameNumber: 3,
seriesGameCount: 3,
},
]);
});
});
@@ -0,0 +1,470 @@
import 'reflect-metadata';
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import mongoose from 'mongoose';
import { readFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import {
buildDoubleEliminationGameSlots,
type DoubleEliminationBracketMatch,
} from '../../../double-elimination/double-elimination.util';
import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../../../tournament-code/tournament-code.constants';
import { ConnectionService } from '../connection.service';
import type { MatchDocument, TournamentCodeDocument } from '../schema';
import { SecretModule } from '../../secret/secret.module';
interface CliOptions {
dryRun: boolean;
matchId?: mongoose.Types.ObjectId;
nodeEnv: string;
winnerGameCount: number;
}
interface CodeUpdatePlan {
codeId: mongoose.Types.ObjectId;
code: string;
bracketMatchId: string;
currentGameNumber: number | undefined;
nextGameNumber: number;
}
interface MissingReadySlotPlan {
bracketMatchId: string;
gameNumber: number;
seriesGameNumber: number;
seriesGameCount: number;
}
interface MatchRepairPlan {
codeUpdates: CodeUpdatePlan[];
currentGameCount: number;
matchId: mongoose.Types.ObjectId;
missingReadySlots: MissingReadySlotPlan[];
nextGameCount: number;
nextBracketMatches: DoubleEliminationBracketMatch[];
ruleRepairSkippedReason?: string;
skippedReason?: string;
}
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: [
resolve(__dirname, '../../../../../../project.env'),
resolve(process.cwd(), '../project.env'),
resolve(process.cwd(), 'apps/project.env'),
resolve(process.cwd(), 'project.env'),
],
}),
SecretModule,
],
providers: [ConnectionService],
})
class RepairModule {}
async function loadMachineEnvFile() {
const homeDir = process.env.HOME ?? process.env.USERPROFILE;
if (!homeDir) return;
const machineEnvFile = resolve(homeDir, 'source/global-env-vars.txt');
try {
const file = await readFile(machineEnvFile, 'utf8');
for (const rawLine of file.split(/\r?\n/)) {
const line = rawLine.trim();
if (!line || line.startsWith('#')) continue;
const matched = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
if (!matched) continue;
const [, key, rawValue] = matched;
process.env[key] = rawValue.replace(/^["']|["']$/g, '');
}
} catch {
// Local machine env is optional for one-off migrations.
}
}
function parseArgs(argv: string[]): CliOptions {
let dryRun = true;
let matchId: mongoose.Types.ObjectId | undefined;
let nodeEnv = process.env.NODE_ENV ?? 'dev';
let winnerGameCount = 3;
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (arg === '--apply') {
dryRun = false;
continue;
}
if (arg === '--dry-run') {
dryRun = true;
continue;
}
if (arg === '--env') {
const value = argv[index + 1];
if (!value) throw new Error('--env requires dev, staging, or prod.');
nodeEnv = value;
index += 1;
continue;
}
if (arg.startsWith('--env=')) {
nodeEnv = arg.slice('--env='.length);
continue;
}
if (arg === '--match-id') {
matchId = parseObjectId(argv[index + 1], '--match-id');
index += 1;
continue;
}
if (arg.startsWith('--match-id=')) {
matchId = parseObjectId(arg.slice('--match-id='.length), '--match-id');
continue;
}
if (arg === '--winner-game-count') {
winnerGameCount = parseOddPositiveInteger(
argv[index + 1],
'--winner-game-count',
);
index += 1;
continue;
}
if (arg.startsWith('--winner-game-count=')) {
winnerGameCount = parseOddPositiveInteger(
arg.slice('--winner-game-count='.length),
'--winner-game-count',
);
continue;
}
if (arg === '--help' || arg === '-h') {
printHelp();
process.exit(0);
}
throw new Error(`Unknown argument: ${arg}`);
}
if (!['dev', 'staging', 'prod'].includes(nodeEnv)) {
throw new Error('--env must be dev, staging, or prod.');
}
return { dryRun, matchId, nodeEnv, winnerGameCount };
}
function parseObjectId(value: string | undefined, label: string) {
if (!value || !mongoose.isValidObjectId(value)) {
throw new Error(`${label} requires a valid ObjectId.`);
}
return new mongoose.Types.ObjectId(value);
}
function parseOddPositiveInteger(value: string | undefined, label: string) {
const parsed = Number(value);
if (!Number.isInteger(parsed) || parsed < 1 || parsed % 2 === 0) {
throw new Error(`${label} requires a positive odd integer.`);
}
return parsed;
}
function printHelp() {
console.log(`Usage:
pnpm --filter api exec ts-node src/modules/global/database/migrations/repair-double-elimination-series-rules.ts --match-id <id> --dry-run
pnpm --filter api exec ts-node src/modules/global/database/migrations/repair-double-elimination-series-rules.ts --match-id <id> --env prod --apply
Options:
--match-id <id> Optional match ObjectId. If omitted, scans all double-elimination matches.
--winner-game-count <n> Winner-bracket series size. Must be odd. Default: 3.
--dry-run Print the repair plan without writing. Default.
--apply Apply match and tournament code updates.
--env <env> dev | staging | prod. Default: NODE_ENV or dev.
`);
}
function requiredWinsFor(gameCount: number): number {
return Math.floor(gameCount / 2) + 1;
}
function codeSlotKey(
bracketMatchId: string | undefined,
gameNumber: number | undefined,
): string | undefined {
if (!bracketMatchId || typeof gameNumber !== 'number') return undefined;
return `${bracketMatchId}:${gameNumber}`;
}
function buildActiveCodeSlotKeys(
codes: TournamentCodeDocument[],
codeUpdates: CodeUpdatePlan[] = [],
): Set<string> {
const updateByCodeId = new Map(
codeUpdates.map((update) => [update.codeId.toString(), update]),
);
const activeSlotKeys = new Set<string>();
for (const code of codes) {
if (code.state !== 'reserved' && code.state !== 'used') continue;
const update = updateByCodeId.get(code._id.toString());
const key = codeSlotKey(
update?.bracketMatchId ?? code.bracketMatchId,
update?.nextGameNumber ?? code.gameNumber,
);
if (key) activeSlotKeys.add(key);
}
return activeSlotKeys;
}
function buildMissingReadySlots(
bracketMatches: DoubleEliminationBracketMatch[],
codes: TournamentCodeDocument[],
codeUpdates: CodeUpdatePlan[] = [],
): MissingReadySlotPlan[] {
const activeSlotKeys = buildActiveCodeSlotKeys(codes, codeUpdates);
return buildDoubleEliminationGameSlots(bracketMatches)
.filter((slot) => slot.bracketMatch.state === 'ready')
.filter(
(slot) =>
!activeSlotKeys.has(
`${slot.bracketMatch.bracketMatchId}:${slot.gameNumber}`,
),
)
.map((slot) => ({
bracketMatchId: slot.bracketMatch.bracketMatchId,
gameNumber: slot.gameNumber,
seriesGameNumber: slot.seriesGameNumber,
seriesGameCount: slot.seriesGameCount,
}));
}
export function buildRepairPlan(
match: MatchDocument,
codes: TournamentCodeDocument[],
winnerGameCount: number,
): MatchRepairPlan {
const currentGameCount = match.gameCount;
const resultGames = match.result?.games ?? [];
const currentBracketMatches = [
...(match.doubleElimination?.bracketMatches ?? []),
];
if (resultGames.length > 0) {
return {
codeUpdates: [],
currentGameCount,
matchId: match._id,
missingReadySlots: buildMissingReadySlots(currentBracketMatches, codes),
nextBracketMatches: currentBracketMatches,
nextGameCount: currentGameCount,
ruleRepairSkippedReason: 'result-games-exist',
};
}
const nextBracketMatches = currentBracketMatches.map((bracketMatch) => {
const gameCount =
bracketMatch.bracketSide === 'winner' ? winnerGameCount : 1;
return {
...bracketMatch,
gameCount,
requiredWins: requiredWinsFor(gameCount),
};
});
const firstSlotByBracketMatchId = new Map(
buildDoubleEliminationGameSlots(nextBracketMatches)
.filter((slot) => slot.seriesGameNumber === 1)
.map((slot) => [slot.bracketMatch.bracketMatchId, slot]),
);
const codeUpdates = codes
.filter((code) => code.bracketMatchId)
.map((code) => {
const slot = firstSlotByBracketMatchId.get(code.bracketMatchId!);
if (!slot) return null;
if (code.gameNumber === slot.gameNumber) return null;
return {
codeId: code._id,
code: code.code,
bracketMatchId: code.bracketMatchId!,
currentGameNumber: code.gameNumber,
nextGameNumber: slot.gameNumber,
} satisfies CodeUpdatePlan;
})
.filter((entry): entry is CodeUpdatePlan => Boolean(entry));
const missingReadySlots = buildMissingReadySlots(
nextBracketMatches,
codes,
codeUpdates,
);
return {
codeUpdates,
currentGameCount,
matchId: match._id,
missingReadySlots,
nextGameCount: Math.max(currentGameCount ?? 1, winnerGameCount),
nextBracketMatches,
};
}
function printPlan(plan: MatchRepairPlan) {
console.log(`match=${plan.matchId.toString()}`);
if (plan.skippedReason) {
console.log(` skipped=${plan.skippedReason}`);
return;
}
if (plan.ruleRepairSkippedReason) {
console.log(` ruleRepairSkipped=${plan.ruleRepairSkippedReason}`);
} else {
console.log(
` gameCount: ${plan.currentGameCount} -> ${plan.nextGameCount}`,
);
}
console.log(
` bracketMatches=${plan.nextBracketMatches.length} codeUpdates=${plan.codeUpdates.length} missingReadySlots=${plan.missingReadySlots.length}`,
);
for (const update of plan.codeUpdates) {
console.log(
` code ${update.code} ${update.bracketMatchId}: ${update.currentGameNumber ?? 'unset'} -> ${update.nextGameNumber}`,
);
}
for (const slot of plan.missingReadySlots) {
console.log(
` missing ${slot.bracketMatchId}: game ${slot.gameNumber} (${slot.seriesGameNumber}/${slot.seriesGameCount})`,
);
}
}
async function applyPlan(
match: MatchDocument,
plan: MatchRepairPlan,
TournamentCodeModel: mongoose.Model<any>,
session: mongoose.ClientSession,
) {
if (plan.skippedReason) return;
for (const update of plan.codeUpdates) {
await TournamentCodeModel.updateOne(
{ _id: update.codeId },
{
$set: {
gameNumber: update.nextGameNumber,
bracketMatchId: update.bracketMatchId,
},
},
{ session },
).exec();
}
const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS);
const reservedIds: mongoose.Types.ObjectId[] = [];
for (const slot of plan.missingReadySlots) {
const existingSlotCode = await TournamentCodeModel.exists({
matchId: match._id,
gameNumber: slot.gameNumber,
bracketMatchId: slot.bracketMatchId,
state: { $in: ['reserved', 'used'] },
})
.session(session)
.exec();
if (existingSlotCode) continue;
const code = await TournamentCodeModel.findOneAndUpdate(
{
state: 'available',
region: 'kr',
mapType: 'SUMMONERS_RIFT',
teamSize: 5,
expiresAt: { $gt: expiresAfter },
},
{
$set: {
state: 'reserved',
matchId: match._id,
gameNumber: slot.gameNumber,
bracketMatchId: slot.bracketMatchId,
reservedAt: new Date(),
},
$unset: { releasedAt: 1 },
},
{ sort: { expiresAt: 1 }, returnDocument: 'after', session },
).exec();
if (!code) break;
reservedIds.push(code._id);
}
if (reservedIds.length > 0) {
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
match.tournamentCodeIds.push(...reservedIds);
}
if (!plan.ruleRepairSkippedReason) {
match.gameCount = plan.nextGameCount;
if (match.doubleElimination) {
match.doubleElimination.bracketMatches = plan.nextBracketMatches;
match.markModified('doubleElimination');
}
}
if (reservedIds.length > 0 || !plan.ruleRepairSkippedReason) {
await match.save({ session });
}
}
async function main() {
const options = parseArgs(process.argv.slice(2));
process.env.NODE_ENV = options.nodeEnv;
process.env.SECRET_SOURCE = process.env.SECRET_SOURCE || 'infisical';
await loadMachineEnvFile();
const app = await NestFactory.createApplicationContext(RepairModule, {
logger: ['log', 'warn', 'error'],
});
try {
const connectionService = app.get(ConnectionService);
const MatchModel = await connectionService.getModel('match');
const TournamentCodeModel =
await connectionService.getModel('tournamentCode');
const matches = await MatchModel.find({
gameMode: 'double-elimination',
...(options.matchId ? { _id: options.matchId } : {}),
}).exec();
const plans: Array<{ match: MatchDocument; plan: MatchRepairPlan }> = [];
for (const match of matches) {
const codes = await TournamentCodeModel.find({
_id: { $in: match.tournamentCodeIds ?? [] },
}).exec();
const plan = buildRepairPlan(match, codes, options.winnerGameCount);
plans.push({ match, plan });
printPlan(plan);
}
if (options.dryRun) {
console.log(
'No writes were made. Re-run with --apply to update MongoDB.',
);
return;
}
const session = await (
await connectionService.getConnection()
).startSession();
try {
await session.withTransaction(async () => {
for (const { match, plan } of plans) {
await applyPlan(match, plan, TournamentCodeModel, session);
}
});
} finally {
await session.endSession();
}
console.log(
`Applied ${plans.filter(({ plan }) => !plan.skippedReason).length} match repairs.`,
);
} finally {
await app.close();
}
}
if (require.main === module) {
main().catch((error) => {
console.error(error);
process.exit(1);
});
}
@@ -0,0 +1,52 @@
import { parseCliOptions } from './run-competition-domain';
describe('competition domain migration CLI', () => {
const originalNodeEnv = process.env.NODE_ENV;
beforeEach(() => {
process.env.NODE_ENV = 'dev';
});
afterAll(() => {
process.env.NODE_ENV = originalNodeEnv;
});
it('ignores pnpm standalone separators before dry-run and apply options', () => {
expect(parseCliOptions(['--', '--dry-run'])).toMatchObject({
dryRun: true,
help: false,
nodeEnv: 'dev',
});
expect(parseCliOptions(['--', '--apply'])).toMatchObject({
dryRun: false,
help: false,
nodeEnv: 'dev',
});
});
it('recognizes help after a pnpm standalone separator without exiting', () => {
expect(parseCliOptions(['--', '--help'])).toMatchObject({
dryRun: true,
help: true,
nodeEnv: 'dev',
});
});
it('accepts an explicit Match cursor for limited-run recovery', () => {
expect(
parseCliOptions([
'--apply',
'--limit=25',
'--after',
'66a000000000000000000123',
]),
).toMatchObject({
dryRun: false,
limit: 25,
afterMatchId: '66a000000000000000000123',
});
expect(() => parseCliOptions(['--after', 'not-an-object-id'])).toThrow(
'--after requires a 24-character hexadecimal Match ObjectId.',
);
});
});
@@ -0,0 +1,222 @@
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 {
migrateCompetitionDomain,
type CompetitionDomainMigrationDb,
} from './competition-domain-runner';
export interface CompetitionDomainCliOptions {
dryRun: boolean;
help: boolean;
limit?: number;
afterMatchId?: string;
nodeEnv: string;
}
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: [
resolve(__dirname, '../../../../../../project.env'),
resolve(process.cwd(), '../project.env'),
resolve(process.cwd(), 'apps/project.env'),
resolve(process.cwd(), 'project.env'),
],
}),
SecretModule,
],
providers: [ConnectionService],
})
class MigrationModule {}
async function loadMachineEnvFile(): Promise<void> {
const homeDir = process.env.HOME ?? process.env.USERPROFILE;
if (!homeDir) return;
try {
const file = await readFile(
resolve(homeDir, 'source/global-env-vars.txt'),
'utf8',
);
for (const rawLine of file.split(/\r?\n/)) {
const line = rawLine.trim();
if (!line || line.startsWith('#')) continue;
const matched = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
if (!matched) continue;
const [, key, rawValue] = matched;
process.env[key] = rawValue.replace(/^["']|["']$/g, '');
}
} catch {
// A local machine env file is optional for one-off migrations.
}
}
export function parseCliOptions(argv: string[]): CompetitionDomainCliOptions {
let dryRun = true;
let help = false;
let limit: number | undefined;
let afterMatchId: string | undefined;
let nodeEnv = process.env.NODE_ENV ?? 'dev';
for (let index = 0; index < argv.length; index += 1) {
const argument = argv[index];
// pnpm preserves the conventional option separator when it forwards
// script arguments (`pnpm ... -- --apply`). It is not a CLI option.
if (argument === '--') continue;
if (argument === '--apply') {
dryRun = false;
continue;
}
if (argument === '--dry-run') {
dryRun = true;
continue;
}
if (argument === '--env') {
const value = argv[index + 1];
if (!value) throw new Error('--env requires dev, staging, or prod.');
nodeEnv = value;
index += 1;
continue;
}
if (argument.startsWith('--env=')) {
nodeEnv = argument.slice('--env='.length);
continue;
}
if (argument === '--limit') {
limit = positiveInteger(argv[index + 1], '--limit');
index += 1;
continue;
}
if (argument.startsWith('--limit=')) {
limit = positiveInteger(argument.slice('--limit='.length), '--limit');
continue;
}
if (argument === '--after') {
afterMatchId = matchObjectId(argv[index + 1]);
index += 1;
continue;
}
if (argument.startsWith('--after=')) {
afterMatchId = matchObjectId(argument.slice('--after='.length));
continue;
}
if (argument === '--help' || argument === '-h') {
help = true;
continue;
}
throw new Error(`Unknown argument: ${argument}`);
}
if (!['dev', 'staging', 'prod'].includes(nodeEnv)) {
throw new Error('--env must be dev, staging, or prod.');
}
return { dryRun, help, limit, afterMatchId, nodeEnv };
}
function positiveInteger(value: string | undefined, label: string): number {
const parsed = Number(value);
if (!Number.isInteger(parsed) || parsed < 1) {
throw new Error(`${label} requires a positive integer.`);
}
return parsed;
}
function matchObjectId(value: string | undefined): string {
if (!value || !/^[a-f\d]{24}$/i.test(value)) {
throw new Error(
'--after requires a 24-character hexadecimal Match ObjectId.',
);
}
return value.toLowerCase();
}
function printHelp(): void {
process.stdout.write(`Usage:
pnpm --silent --filter api competition:migrate
pnpm --silent --filter api competition:migrate -- --env staging --apply
Options:
--dry-run Plan and report without writes. Default.
--apply Apply one transaction per Match.
--env <env> dev | staging | prod. Default: NODE_ENV or dev.
--limit <n> Scan at most n Matches. Apply resumes from a durable checkpoint.
--after <id> Override the checkpoint with a Match ObjectId cursor.
The JSON report is written to stdout; the concise human summary is written to stderr.
`);
}
async function main(): Promise<void> {
const options = parseCliOptions(process.argv.slice(2));
if (options.help) {
printHelp();
return;
}
await loadMachineEnvFile();
process.env.NODE_ENV = options.nodeEnv;
const app = await NestFactory.createApplicationContext(MigrationModule, {
logger: false,
});
try {
const connectionService = app.get(ConnectionService);
const connection = await connectionService.getConnection();
if (!connection.db) throw new Error('MongoDB connection has no db handle.');
const result = await migrateCompetitionDomain(
connection.db as unknown as CompetitionDomainMigrationDb,
{
dryRun: options.dryRun,
limit: options.limit,
afterMatchId: options.afterMatchId,
startSession: options.dryRun
? undefined
: async () => connection.startSession(),
},
);
const { summary } = result;
process.stderr.write(
`[competition-domain migration] mode=${result.mode} env=${options.nodeEnv} ` +
`db=${resolveMongoDbName(options.nodeEnv)} scanned=${summary.scanned} ` +
`ready=${summary.ready} applied=${summary.applied} ` +
`alreadyApplied=${summary.alreadyApplied} quarantined=${summary.quarantined} ` +
`failed=${summary.failed} unclassified=${summary.unclassified} ` +
`indexPreflight=${result.indexPreflight.status} ` +
`resume=${result.resume.checkpointAfterMatchId ?? 'none'} ` +
`completed=${result.resume.completed}\n`,
);
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
if (result.indexPreflight.status === 'blocked') process.exitCode = 1;
else if (summary.failed > 0) process.exitCode = 1;
else if (summary.quarantined > 0) process.exitCode = 2;
} finally {
await app.close().catch((error: unknown) => {
const message = error instanceof Error ? error.message : String(error);
process.stderr.write(
`[competition-domain migration] context close warning: ${message}\n`,
);
});
}
}
if (require.main === module) {
void main().catch((error: unknown) => {
const message = error instanceof Error ? error.message : String(error);
process.stderr.write(`[competition-domain migration] failed: ${message}\n`);
process.stdout.write(
`${JSON.stringify({
migrationRunId: '20260712-competition-domain',
mode: process.argv.includes('--apply') ? 'apply' : 'dry-run',
error: message,
})}\n`,
);
process.exitCode = 1;
});
}
@@ -0,0 +1,318 @@
import 'reflect-metadata';
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import mongoose from 'mongoose';
import { readFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import { ConnectionService, resolveMongoDbName } from '../connection.service';
import { SecretModule } from '../../secret/secret.module';
import {
migrateTournamentCodeUniqueIndexes,
TournamentCodeDuplicateGroupSummary,
TournamentCodeUniqueIndexMigrationProgress,
} from './20260627-tournament-code-unique-indexes';
interface CliOptions {
allowUsedDuplicateRelease: boolean;
createIndexes: boolean;
dryRun: boolean;
duplicateSampleLimit: number;
indexCommitQuorum?: number | string;
indexMaxTimeMS?: number;
listDuplicates: boolean;
nodeEnv: string;
}
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: [
resolve(__dirname, '../../../../../../project.env'),
resolve(process.cwd(), '../project.env'),
resolve(process.cwd(), 'apps/project.env'),
resolve(process.cwd(), 'project.env'),
],
}),
SecretModule,
],
providers: [ConnectionService],
})
class MigrationModule {}
async function loadMachineEnvFile() {
const homeDir = process.env.HOME ?? process.env.USERPROFILE;
if (!homeDir) return;
const machineEnvFile = resolve(homeDir, 'source/global-env-vars.txt');
try {
const file = await readFile(machineEnvFile, 'utf8');
for (const rawLine of file.split(/\r?\n/)) {
const line = rawLine.trim();
if (!line || line.startsWith('#')) continue;
const matched = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
if (!matched) continue;
const [, key, rawValue] = matched;
process.env[key] = rawValue.replace(/^["']|["']$/g, '');
}
} catch {
// Local machine env is optional for one-off migrations.
}
}
function parseArgs(argv: string[]): CliOptions {
let allowUsedDuplicateRelease = false;
let createIndexes = true;
let dryRun = true;
let duplicateSampleLimit = 20;
let indexCommitQuorum: number | string | undefined;
let indexMaxTimeMS: number | undefined;
let listDuplicates = false;
let nodeEnv = process.env.NODE_ENV ?? 'dev';
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (arg === '--allow-used-duplicate-release') {
allowUsedDuplicateRelease = true;
continue;
}
if (arg === '--apply') {
dryRun = false;
continue;
}
if (arg === '--dry-run') {
dryRun = true;
continue;
}
if (arg === '--duplicate-sample-limit') {
duplicateSampleLimit = parsePositiveInteger(
argv[index + 1],
'--duplicate-sample-limit',
);
index += 1;
continue;
}
if (arg.startsWith('--duplicate-sample-limit=')) {
duplicateSampleLimit = parsePositiveInteger(
arg.slice('--duplicate-sample-limit='.length),
'--duplicate-sample-limit',
);
continue;
}
if (arg === '--env') {
const value = argv[index + 1];
if (!value) throw new Error('--env requires dev, staging, or prod.');
nodeEnv = value;
index += 1;
continue;
}
if (arg.startsWith('--env=')) {
nodeEnv = arg.slice('--env='.length);
continue;
}
if (arg === '--index-commit-quorum') {
indexCommitQuorum = parseCommitQuorum(
argv[index + 1],
'--index-commit-quorum',
);
index += 1;
continue;
}
if (arg.startsWith('--index-commit-quorum=')) {
indexCommitQuorum = parseCommitQuorum(
arg.slice('--index-commit-quorum='.length),
'--index-commit-quorum',
);
continue;
}
if (arg === '--index-max-time-ms') {
indexMaxTimeMS = parsePositiveInteger(
argv[index + 1],
'--index-max-time-ms',
);
index += 1;
continue;
}
if (arg.startsWith('--index-max-time-ms=')) {
indexMaxTimeMS = parsePositiveInteger(
arg.slice('--index-max-time-ms='.length),
'--index-max-time-ms',
);
continue;
}
if (arg === '--list-duplicates') {
listDuplicates = true;
continue;
}
if (arg === '--skip-indexes') {
createIndexes = false;
continue;
}
if (arg === '--help' || arg === '-h') {
printHelp();
process.exit(0);
}
throw new Error(`Unknown argument: ${arg}`);
}
if (!['dev', 'staging', 'prod'].includes(nodeEnv)) {
throw new Error('--env must be dev, staging, or prod.');
}
return {
allowUsedDuplicateRelease,
createIndexes,
dryRun,
duplicateSampleLimit,
indexCommitQuorum,
indexMaxTimeMS,
listDuplicates,
nodeEnv,
};
}
function parseCommitQuorum(value: string | undefined, label: string) {
if (!value) {
throw new Error(`${label} requires a positive integer, majority, or votingMembers.`);
}
if (value === 'majority' || value === 'votingMembers') return value;
return parsePositiveInteger(value, label);
}
function parsePositiveInteger(value: string | undefined, label: string) {
const parsed = Number(value);
if (!Number.isInteger(parsed) || parsed < 1) {
throw new Error(`${label} requires a positive integer.`);
}
return parsed;
}
function printHelp() {
console.log(`Usage:
pnpm --filter api exec ts-node src/modules/global/database/migrations/run-tournament-code-unique-indexes.ts [--dry-run]
pnpm --filter api exec ts-node src/modules/global/database/migrations/run-tournament-code-unique-indexes.ts --env staging --apply
Options:
--dry-run Print affected counts without writing. Default.
--apply Release duplicate losers, pull them from matches, and create unique indexes.
--env <env> dev | staging | prod. Default: NODE_ENV or dev.
--list-duplicates
Print duplicate tournamentCode group samples.
--duplicate-sample-limit <n>
Max duplicate groups to print. Default: 20.
--index-commit-quorum <n|majority|votingMembers>
Override MongoDB index build commitQuorum. Use 1 only after checking replica health.
--index-max-time-ms <n>
Abort an individual index command after n milliseconds.
--skip-indexes Apply document cleanup without creating indexes.
--allow-used-duplicate-release
Allow releasing duplicate codes whose state is used. Default refuses this.
`);
}
function printDuplicateGroups(groups: TournamentCodeDuplicateGroupSummary[]) {
if (groups.length === 0) {
console.log('No duplicate tournamentCode groups found.');
return;
}
console.log('Duplicate tournamentCode groups:');
console.table(
groups.map((group) => ({
keeperCode: group.keeper.code ?? '',
keeperId: group.keeper.id,
keeperState: group.keeper.state ?? '',
key: group.key,
kind: group.kind,
loserCodes: group.losers.map((loser) => loser.code ?? '').join(', '),
loserIds: group.losers.map((loser) => loser.id).join(', '),
loserStates: group.losers
.map((loser) => loser.state ?? '')
.join(', '),
})),
);
}
function printProgress(progress: TournamentCodeUniqueIndexMigrationProgress) {
const count =
progress.scanned !== undefined
? ` scanned=${progress.scanned}`
: progress.total !== undefined
? ` total=${progress.total}`
: '';
const index = progress.indexName ? ` index=${progress.indexName}` : '';
const action = progress.action ? ` action=${progress.action}` : '';
console.log(
`[tournament-code unique index migration] ${progress.phase}${action}${index}${count}`,
);
}
async function main() {
const options = parseArgs(process.argv.slice(2));
process.env.NODE_ENV = options.nodeEnv;
process.env.SECRET_SOURCE = process.env.SECRET_SOURCE || 'infisical';
await loadMachineEnvFile();
const app = await NestFactory.createApplicationContext(MigrationModule, {
logger: ['log', 'warn', 'error'],
});
try {
const connectionService = app.get(ConnectionService);
const connection = await connectionService.getConnection();
if (!connection.db) {
throw new Error('MongoDB connection has no db handle.');
}
const dbName = resolveMongoDbName(options.nodeEnv);
console.log(
`[tournament-code unique index migration] mode=${
options.dryRun ? 'dry-run' : 'apply'
} env=${options.nodeEnv} db=${dbName}`,
);
const result = await migrateTournamentCodeUniqueIndexes(
connection.db as Parameters<typeof migrateTournamentCodeUniqueIndexes>[0],
{
allowUsedDuplicateRelease: options.allowUsedDuplicateRelease,
createIndexes: options.createIndexes,
dryRun: options.dryRun,
duplicateSampleLimit: options.duplicateSampleLimit,
indexCommitQuorum: options.indexCommitQuorum,
indexMaxTimeMS: options.indexMaxTimeMS,
onProgress: printProgress,
},
);
console.table(result.stats);
if (options.listDuplicates) {
printDuplicateGroups(result.sampleDuplicateGroups);
}
if (result.stats.unsafeUsedDuplicateCodes > 0 && options.dryRun) {
console.log(
'Apply will refuse used duplicate cleanup unless --allow-used-duplicate-release is provided.',
);
}
if (options.dryRun) {
console.log(
'No writes were made. Re-run with --apply to clean documents and create indexes.',
);
} else if (options.createIndexes) {
console.log('Migration applied and indexes ensured.');
} else {
console.log('Migration applied without index creation.');
}
} finally {
await app.close();
await mongoose.disconnect();
}
}
void main().catch((error: unknown) => {
console.error(error instanceof Error ? error.message : error);
process.exitCode = 1;
});
+364 -4
View File
@@ -3,6 +3,14 @@ import type {
RiotPlatformRoute,
RiotRegionalRoute,
} from '../../riot/riot.types';
import {
Competition,
CompetitionFact,
CompetitionOutbox,
TournamentCodeAssignment,
applyCompetitionDomainInvariantIndexes,
competitionModelDefinitions,
} from '../../competition/competition.schema';
import { ModelDefinition } from './types';
export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
@@ -32,11 +40,16 @@ export const MATCH_STATUSES: MatchStatus[] = [
export type TeamSide = 'blue' | 'red';
export const TEAM_SIDES: TeamSide[] = ['blue', 'red'];
export type MatchGameMode = 'pair' | 'bracket' | 'round-robin';
export type MatchGameMode =
| 'pair'
| 'bracket'
| 'round-robin'
| 'double-elimination';
export const MATCH_GAME_MODES: MatchGameMode[] = [
'pair',
'bracket',
'round-robin',
'double-elimination',
];
export type CommunityRole = 'owner' | 'admin' | 'member';
@@ -47,13 +60,15 @@ export type TournamentCodeState =
| 'reserved'
| 'used'
| 'expired'
| 'released';
| 'released'
| 'voided';
export const TOURNAMENT_CODE_STATES: TournamentCodeState[] = [
'available',
'reserved',
'used',
'expired',
'released',
'voided',
];
export type TournamentMapType = 'SUMMONERS_RIFT';
export const TOURNAMENT_MAP_TYPES: TournamentMapType[] = ['SUMMONERS_RIFT'];
@@ -385,6 +400,8 @@ export interface DakaoOutboxMessage extends MongooseTimestamps {
payload: Record<string, unknown>;
state: DakaoOutboxMessageState;
publishAttempts: number;
publishLeaseOwnerIdentifier?: string;
publishLeaseExpiresAt?: Date;
publishedAt?: Date;
terminalAt?: Date;
resultEventId?: string;
@@ -445,9 +462,11 @@ export interface TournamentCode extends MongooseTimestamps {
state: TournamentCodeState;
matchId?: mongoose.Types.ObjectId;
gameNumber?: number;
bracketMatchId?: string;
reservedAt?: Date;
usedAt?: Date;
releasedAt?: Date;
voidedAt?: Date;
riotMatchId?: string;
uploadedBy: mongoose.Types.ObjectId;
uploadedAt: Date;
@@ -497,6 +516,7 @@ export interface MatchGameResultParticipant {
export interface MatchGameResult {
gameNumber: number;
bracketMatchId?: string;
riotMatchId: string;
blueTeamIndex: number;
redTeamIndex: number;
@@ -508,6 +528,7 @@ export interface MatchGameResult {
}
export interface MatchSeriesResult {
bracketMatchId?: string;
teamAIndex: number;
teamBIndex: number;
teamAWins: number;
@@ -515,6 +536,120 @@ export interface MatchSeriesResult {
winnerTeamIndex?: number;
}
export type DoubleEliminationBracketSide =
| 'winner'
| 'loser'
| 'grand-final'
| 'reset-final';
export const DOUBLE_ELIMINATION_BRACKET_SIDES: DoubleEliminationBracketSide[] =
['winner', 'loser', 'grand-final', 'reset-final'];
export type DoubleEliminationBracketMatchState =
| 'pending'
| 'ready'
| 'completed';
export const DOUBLE_ELIMINATION_BRACKET_MATCH_STATES: DoubleEliminationBracketMatchState[] =
['pending', 'ready', 'completed'];
export type DoubleEliminationCompletionType = 'riot-result' | 'walkover';
export const DOUBLE_ELIMINATION_COMPLETION_TYPES: DoubleEliminationCompletionType[] =
['riot-result', 'walkover'];
export type DoubleEliminationEventType =
| 'bracket-created'
| 'seeds-reshuffled'
| 'seeds-swapped'
| 'bracket-match-completed'
| 'bracket-match-cancelled'
| 'walkover-awarded'
| 'walkover-cancelled'
| 'reset-final-created'
| 'riot-result-cancelled';
export const DOUBLE_ELIMINATION_EVENT_TYPES: DoubleEliminationEventType[] = [
'bracket-created',
'seeds-reshuffled',
'seeds-swapped',
'bracket-match-completed',
'bracket-match-cancelled',
'walkover-awarded',
'walkover-cancelled',
'reset-final-created',
'riot-result-cancelled',
];
export interface DoubleEliminationSeed {
seedNumber: number;
teamIndex: number;
}
export interface DoubleEliminationBracketMatchSource {
type: 'seed' | 'winner' | 'loser';
seedNumber?: number;
bracketMatchId?: string;
}
export interface DoubleEliminationBracketMatchDestination {
bracketMatchId: string;
position: 'A' | 'B';
}
export interface DoubleEliminationWalkover {
winnerTeamIndex: number;
reason?: string;
awardedBy?: mongoose.Types.ObjectId;
awardedAt: Date;
cancelledBy?: mongoose.Types.ObjectId;
cancelledAt?: Date;
cancelReason?: string;
active: boolean;
}
export interface DoubleEliminationBracketMatch {
bracketMatchId: string;
gameNumber: number;
gameCount: number;
requiredWins: number;
bracketSide: DoubleEliminationBracketSide;
roundNumber: number;
matchNumber: number;
state: DoubleEliminationBracketMatchState;
teamAIndex?: number;
teamBIndex?: number;
teamASource?: DoubleEliminationBracketMatchSource;
teamBSource?: DoubleEliminationBracketMatchSource;
winnerAdvancesTo?: DoubleEliminationBracketMatchDestination;
loserAdvancesTo?: DoubleEliminationBracketMatchDestination;
winnerTeamIndex?: number;
loserTeamIndex?: number;
completedBy?: DoubleEliminationCompletionType;
completedAt?: Date;
walkover?: DoubleEliminationWalkover;
}
export interface DoubleEliminationPlacements {
firstTeamIndex?: number;
secondTeamIndex?: number;
thirdTeamIndex?: number;
}
export interface DoubleEliminationEvent {
type: DoubleEliminationEventType;
bracketMatchId?: string;
actorUserId?: mongoose.Types.ObjectId;
reason?: string;
createdAt: Date;
}
export interface DoubleEliminationBracket {
teamCount: 4 | 8;
resetFinalEnabled: boolean;
resetFinalCreated: boolean;
seeds: DoubleEliminationSeed[];
bracketMatches: DoubleEliminationBracketMatch[];
placements: DoubleEliminationPlacements;
events: DoubleEliminationEvent[];
}
export interface MatchGameAssignment {
gameNumber: number;
roundNumber?: number;
@@ -546,6 +681,7 @@ export interface MatchScheduleItem {
export interface Match extends MongooseTimestamps {
communityId: mongoose.Types.ObjectId;
competitionId?: mongoose.Types.ObjectId;
shortCode?: string;
title: string;
description: string;
@@ -564,6 +700,7 @@ export interface Match extends MongooseTimestamps {
teams: MatchTeam[];
result?: MatchResult;
resultPollState?: MatchResultPollState;
doubleElimination?: DoubleEliminationBracket;
legacyImported?: boolean;
legacyImportSource?: {
importedAt: Date;
@@ -610,6 +747,7 @@ export interface LegacyImportJob extends MongooseTimestamps {
totalSkippedDuplicate: number;
totalErrors: number;
averageMemberSeconds?: number;
completedMemberJobIds: string[];
errors?: LegacyImportJobError[];
}
@@ -893,6 +1031,9 @@ export interface MatchStatsTimelinePoint {
export interface MatchStats extends MongooseTimestamps {
matchId: mongoose.Types.ObjectId;
sourceCompetitionId?: mongoose.Types.ObjectId;
sourceRevision?: number;
projectorVersion?: number;
communityId: mongoose.Types.ObjectId;
scheduledAt: Date;
gameCreationMin: number;
@@ -1159,6 +1300,8 @@ export const DakaoOutboxMessageSchema = new Schema<DakaoOutboxMessage>(
default: 'pending',
},
publishAttempts: { type: Number, required: true, default: 0 },
publishLeaseOwnerIdentifier: { type: String },
publishLeaseExpiresAt: { type: Date },
publishedAt: { type: Date },
terminalAt: { type: Date },
resultEventId: { type: String },
@@ -1179,6 +1322,11 @@ export const DakaoOutboxMessageSchema = new Schema<DakaoOutboxMessage>(
);
DakaoOutboxMessageSchema.index({ state: 1, updatedAt: 1 });
DakaoOutboxMessageSchema.index({
state: 1,
publishLeaseExpiresAt: 1,
updatedAt: 1,
});
DakaoOutboxMessageSchema.index({ correlationId: 1 }, { sparse: true });
export const DakaoSendResultEventSchema = new Schema<DakaoSendResultEvent>(
@@ -1351,9 +1499,11 @@ export const TournamentCodeSchema = new Schema<TournamentCode>(
},
matchId: { type: Schema.Types.ObjectId, ref: 'match' },
gameNumber: { type: Number },
bracketMatchId: { type: String },
reservedAt: { type: Date },
usedAt: { type: Date },
releasedAt: { type: Date },
voidedAt: { type: Date },
riotMatchId: { type: String },
uploadedBy: { type: Schema.Types.ObjectId, ref: 'user', required: true },
uploadedAt: { type: Date, required: true, default: Date.now },
@@ -1368,9 +1518,35 @@ export const TournamentCodeSchema = new Schema<TournamentCode>(
TournamentCodeSchema.index({ code: 1 }, { unique: true });
TournamentCodeSchema.index({ state: 1, expiresAt: 1 });
TournamentCodeSchema.index({ matchId: 1, gameNumber: 1 });
TournamentCodeSchema.index(
{ matchId: 1, gameNumber: 1 },
{
unique: true,
partialFilterExpression: {
matchId: { $exists: true },
gameNumber: { $exists: true },
state: { $in: ['reserved', 'used'] },
},
},
);
TournamentCodeSchema.index(
{ matchId: 1, bracketMatchId: 1 },
{
partialFilterExpression: {
matchId: { $exists: true },
bracketMatchId: { $exists: true },
state: { $in: ['reserved', 'used'] },
},
},
);
TournamentCodeSchema.index({ state: 1, uploadedAt: -1 });
TournamentCodeSchema.index({ riotMatchId: 1 }, { sparse: true });
TournamentCodeSchema.index(
{ riotMatchId: 1 },
{
unique: true,
partialFilterExpression: { riotMatchId: { $type: 'string' } },
},
);
const MatchParticipantSubSchema = new Schema<MatchParticipant>(
{
@@ -1428,6 +1604,7 @@ const MatchGameResultParticipantSubSchema =
const MatchGameResultSubSchema = new Schema<MatchGameResult>(
{
gameNumber: { type: Number, required: true },
bracketMatchId: { type: String, required: false },
riotMatchId: { type: String, required: true },
blueTeamIndex: { type: Number, required: true, min: 1 },
redTeamIndex: { type: Number, required: true, min: 1 },
@@ -1446,6 +1623,7 @@ const MatchGameResultSubSchema = new Schema<MatchGameResult>(
const MatchSeriesResultSubSchema = new Schema<MatchSeriesResult>(
{
bracketMatchId: { type: String, required: false },
teamAIndex: { type: Number, required: true, min: 1 },
teamBIndex: { type: Number, required: true, min: 1 },
teamAWins: { type: Number, required: true, default: 0 },
@@ -1465,6 +1643,159 @@ const MatchGameAssignmentSubSchema = new Schema<MatchGameAssignment>(
{ _id: false },
);
const DoubleEliminationSeedSubSchema = new Schema<DoubleEliminationSeed>(
{
seedNumber: { type: Number, required: true, min: 1 },
teamIndex: { type: Number, required: true, min: 1 },
},
{ _id: false },
);
const DoubleEliminationBracketMatchSourceSubSchema =
new Schema<DoubleEliminationBracketMatchSource>(
{
type: {
type: String,
enum: ['seed', 'winner', 'loser'],
required: true,
},
seedNumber: { type: Number, required: false, min: 1 },
bracketMatchId: { type: String, required: false },
},
{ _id: false },
);
const DoubleEliminationBracketMatchDestinationSubSchema =
new Schema<DoubleEliminationBracketMatchDestination>(
{
bracketMatchId: { type: String, required: true },
position: { type: String, enum: ['A', 'B'], required: true },
},
{ _id: false },
);
const DoubleEliminationWalkoverSubSchema =
new Schema<DoubleEliminationWalkover>(
{
winnerTeamIndex: { type: Number, required: true, min: 1 },
reason: { type: String, required: false },
awardedBy: { type: Schema.Types.ObjectId, ref: 'user' },
awardedAt: { type: Date, required: true },
cancelledBy: { type: Schema.Types.ObjectId, ref: 'user' },
cancelledAt: { type: Date },
cancelReason: { type: String },
active: { type: Boolean, required: true, default: true },
},
{ _id: false },
);
const DoubleEliminationBracketMatchSubSchema =
new Schema<DoubleEliminationBracketMatch>(
{
bracketMatchId: { type: String, required: true },
gameNumber: { type: Number, required: true, min: 1 },
gameCount: { type: Number, required: true, min: 1, default: 1 },
requiredWins: { type: Number, required: true, min: 1, default: 1 },
bracketSide: {
type: String,
enum: DOUBLE_ELIMINATION_BRACKET_SIDES,
required: true,
},
roundNumber: { type: Number, required: true, min: 1 },
matchNumber: { type: Number, required: true, min: 1 },
state: {
type: String,
enum: DOUBLE_ELIMINATION_BRACKET_MATCH_STATES,
required: true,
},
teamAIndex: { type: Number, required: false, min: 1 },
teamBIndex: { type: Number, required: false, min: 1 },
teamASource: {
type: DoubleEliminationBracketMatchSourceSubSchema,
required: false,
},
teamBSource: {
type: DoubleEliminationBracketMatchSourceSubSchema,
required: false,
},
winnerAdvancesTo: {
type: DoubleEliminationBracketMatchDestinationSubSchema,
required: false,
},
loserAdvancesTo: {
type: DoubleEliminationBracketMatchDestinationSubSchema,
required: false,
},
winnerTeamIndex: { type: Number, required: false, min: 1 },
loserTeamIndex: { type: Number, required: false, min: 1 },
completedBy: {
type: String,
enum: DOUBLE_ELIMINATION_COMPLETION_TYPES,
required: false,
},
completedAt: { type: Date, required: false },
walkover: {
type: DoubleEliminationWalkoverSubSchema,
required: false,
},
},
{ _id: false },
);
const DoubleEliminationPlacementsSubSchema =
new Schema<DoubleEliminationPlacements>(
{
firstTeamIndex: { type: Number, required: false, min: 1 },
secondTeamIndex: { type: Number, required: false, min: 1 },
thirdTeamIndex: { type: Number, required: false, min: 1 },
},
{ _id: false },
);
const DoubleEliminationEventSubSchema = new Schema<DoubleEliminationEvent>(
{
type: {
type: String,
enum: DOUBLE_ELIMINATION_EVENT_TYPES,
required: true,
},
bracketMatchId: { type: String, required: false },
actorUserId: { type: Schema.Types.ObjectId, ref: 'user' },
reason: { type: String, required: false },
createdAt: { type: Date, required: true },
},
{ _id: false },
);
const DoubleEliminationBracketSubSchema = new Schema<DoubleEliminationBracket>(
{
teamCount: { type: Number, enum: [4, 8], required: true },
resetFinalEnabled: { type: Boolean, required: true, default: false },
resetFinalCreated: { type: Boolean, required: true, default: false },
seeds: {
type: [DoubleEliminationSeedSubSchema],
required: true,
default: [],
},
bracketMatches: {
type: [DoubleEliminationBracketMatchSubSchema],
required: true,
default: [],
},
placements: {
type: DoubleEliminationPlacementsSubSchema,
required: true,
default: () => ({}),
},
events: {
type: [DoubleEliminationEventSubSchema],
required: true,
default: [],
},
},
{ _id: false },
);
const MatchResultSubSchema = new Schema<MatchResult>(
{
winnerTeamIndex: { type: Number, required: false, min: 1 },
@@ -1528,6 +1859,11 @@ export const MatchSchema = new Schema<Match>(
ref: 'community',
required: true,
},
competitionId: {
type: Schema.Types.ObjectId,
ref: 'competition',
required: false,
},
shortCode: {
type: String,
required: false,
@@ -1595,6 +1931,10 @@ export const MatchSchema = new Schema<Match>(
type: MatchResultPollStateSubSchema,
required: false,
},
doubleElimination: {
type: DoubleEliminationBracketSubSchema,
required: false,
},
legacyImported: { type: Boolean, required: false, default: false },
legacyImportSource: {
type: MatchLegacyImportSourceSubSchema,
@@ -1615,6 +1955,7 @@ export const MatchSchema = new Schema<Match>(
);
MatchSchema.index({ communityId: 1, scheduledAt: -1 });
applyCompetitionDomainInvariantIndexes(MatchSchema, 'match');
MatchSchema.index({ communityId: 1, status: 1, scheduledAt: -1 });
MatchSchema.index(
{ communityId: 1, shortCode: 1 },
@@ -1679,6 +2020,11 @@ export const LegacyImportJobSchema = new Schema<LegacyImportJob>(
totalSkippedDuplicate: { type: Number, required: true, default: 0 },
totalErrors: { type: Number, required: true, default: 0 },
averageMemberSeconds: { type: Number },
completedMemberJobIds: {
type: [String],
required: true,
default: [],
},
errors: {
type: [LegacyImportJobErrorSubSchema],
required: true,
@@ -1694,6 +2040,7 @@ export const LegacyImportJobSchema = new Schema<LegacyImportJob>(
LegacyImportJobSchema.index({ communityId: 1, startedAt: -1 });
LegacyImportJobSchema.index({ communityId: 1, state: 1 });
LegacyImportJobSchema.index({ jobId: 1, completedMemberJobIds: 1 });
const AuctionPlayerSnapshotSubSchema = new Schema<AuctionPlayerSnapshot>(
{
@@ -2062,6 +2409,13 @@ export const MatchStatsSchema: mongoose.Schema<MatchStats> = new Schema(
required: true,
unique: true,
},
sourceCompetitionId: {
type: Schema.Types.ObjectId,
ref: 'competition',
required: false,
},
sourceRevision: { type: Number, required: false, min: 0 },
projectorVersion: { type: Number, required: false, min: 1 },
communityId: {
type: Schema.Types.ObjectId,
ref: 'community',
@@ -2088,9 +2442,11 @@ MatchStatsSchema.index({
gameCreationMax: 1,
});
MatchStatsSchema.index({ communityId: 1, userIds: 1 });
MatchStatsSchema.index({ communityId: 1, userIds: 1, scheduledAt: -1 });
MatchStatsSchema.index({ communityId: 1, championIds: 1 });
export const tournamentModelDefinitions: ModelDefinition[] = [
...competitionModelDefinitions,
{ name: 'identity', schema: IdentitySchema, schemaName: 'identity' },
{ name: 'community', schema: CommunitySchema, schemaName: 'community' },
{
@@ -2140,6 +2496,10 @@ export const tournamentModelDefinitions: ModelDefinition[] = [
];
export interface TournamentModelTypes {
competition: Competition;
competitionFact: CompetitionFact;
competitionOutbox: CompetitionOutbox;
tournamentCodeAssignment: TournamentCodeAssignment;
identity: Identity;
community: Community;
dakaoInboundMessage: DakaoInboundMessage;
@@ -56,20 +56,25 @@ export interface JetStreamConsumeOptions {
maxMessages?: number;
expiresMs?: number;
nakDelayMs?: number;
restartDelayMilliseconds?: number;
}
const JET_STREAM_CONSUMER_RESTART_DELAY_MILLISECONDS = 1_000;
@Injectable()
export class NatsService implements OnModuleDestroy {
private readonly logger = new Logger(NatsService.name);
private readonly stringCodec = StringCodec();
private readonly subscriptions = new Set<Subscription>();
private readonly jetStreamConsumers = new Set<ConsumerMessages>();
private isDestroying = false;
constructor(
@Inject(NATS_CLIENT) private readonly natsClient: NatsConnection,
) {}
async onModuleDestroy() {
this.isDestroying = true;
for (const consumer of this.jetStreamConsumers) {
try {
await consumer.close();
@@ -199,28 +204,36 @@ export class NatsService implements OnModuleDestroy {
options: JetStreamConsumeOptions,
handler: JetStreamMessageHandler<T>,
): Promise<void> {
try {
const consumer = await this.natsClient
.jetstream()
.consumers.get(options.stream, options.durable);
const messages = await consumer.consume({
max_messages: options.maxMessages ?? 10,
expires: options.expiresMs ?? 30000,
});
this.jetStreamConsumers.add(messages);
while (!this.isDestroying) {
try {
for await (const msg of messages) {
await this.dispatchJetStream(msg, handler, options);
const consumer = await this.natsClient
.jetstream()
.consumers.get(options.stream, options.durable);
const messages = await consumer.consume({
max_messages: options.maxMessages ?? 10,
expires: options.expiresMs ?? 30000,
});
this.jetStreamConsumers.add(messages);
try {
for await (const msg of messages) {
await this.dispatchJetStream(msg, handler, options);
}
} finally {
this.jetStreamConsumers.delete(messages);
}
} finally {
this.jetStreamConsumers.delete(messages);
} catch (err) {
if (this.isDestroying) return;
this.logger.error(
`JetStream consumer stream="${options.stream}" durable="${options.durable}" terminated: ${
(err as Error)?.stack ?? err
}`,
);
}
} catch (err) {
this.logger.error(
`JetStream consumer stream="${options.stream}" durable="${options.durable}" terminated: ${
(err as Error)?.stack ?? err
}`,
await this.sleep(
options.restartDelayMilliseconds ??
JET_STREAM_CONSUMER_RESTART_DELAY_MILLISECONDS,
);
}
}
@@ -313,4 +326,8 @@ export class NatsService implements OnModuleDestroy {
? RetentionPolicy.Workqueue
: RetentionPolicy.Limits;
}
private sleep(durationMilliseconds: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, durationMilliseconds));
}
}
@@ -0,0 +1,95 @@
import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
} from '@nestjs/common';
import { Observable, catchError, finalize, throwError } from 'rxjs';
import { setNewRelicTransactionName } from './new-relic';
import {
buildApiRequestPerformanceEvent,
createApiPerformanceRequestContext,
isApiPerformanceObservabilityEnabled,
recordApiRequestPerformance,
runWithApiPerformanceContext,
} from './performance-observer';
interface RequestLike {
method?: string;
originalUrl?: string;
url?: string;
path?: string;
route?: {
path?: string | RegExp | Array<string | RegExp>;
};
}
interface ResponseLike {
statusCode?: number;
}
@Injectable()
export class ApiPerformanceInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
if (!isApiPerformanceObservabilityEnabled()) {
return next.handle();
}
const http = context.switchToHttp();
const request = http.getRequest<RequestLike>();
const response = http.getResponse<ResponseLike>();
const method = request.method ?? 'UNKNOWN';
const route = resolveRouteTemplate(request);
const path = resolveRequestPath(request);
const requestContext = createApiPerformanceRequestContext({
method,
route,
path,
});
const startedAt = process.hrtime.bigint();
let thrownError: unknown;
setNewRelicTransactionName(`${method} ${route}`);
return runWithApiPerformanceContext(requestContext, () =>
next.handle().pipe(
catchError((error: unknown) => {
thrownError = error;
return throwError(() => error);
}),
finalize(() => {
const statusCode = response.statusCode ?? (thrownError ? 500 : 200);
const durationMs =
Number(process.hrtime.bigint() - startedAt) / 1_000_000;
recordApiRequestPerformance(
buildApiRequestPerformanceEvent({
context: requestContext,
statusCode,
durationMs,
isError: Boolean(thrownError) || statusCode >= 400,
}),
);
}),
),
);
}
}
export function resolveRouteTemplate(request: RequestLike): string {
const routePath = request.route?.path;
if (Array.isArray(routePath)) {
return normalizeRoute(routePath.map(String).join('|'));
}
if (routePath) return normalizeRoute(String(routePath));
return normalizeRoute(resolveRequestPath(request));
}
export function resolveRequestPath(request: RequestLike): string {
const rawPath = request.originalUrl ?? request.path ?? request.url ?? '/';
return rawPath.split('?')[0] || '/';
}
function normalizeRoute(route: string): string {
const normalized = route.startsWith('/') ? route : `/${route}`;
return normalized.replace(/\/+/g, '/').replace(/\/$/, '') || '/';
}
@@ -0,0 +1,22 @@
import {
countHydratedDocuments,
countReturnedDocuments,
} from './mongoose-performance.plugin';
describe('Mongoose performance helpers', () => {
it('counts returned documents for common query result shapes', () => {
expect(countReturnedDocuments([{ id: 1 }, { id: 2 }])).toBe(2);
expect(countReturnedDocuments({ id: 1 })).toBe(1);
expect(countReturnedDocuments(null)).toBe(0);
expect(countReturnedDocuments(7)).toBe(7);
});
it('counts hydrated documents separately from lean documents', () => {
const hydrated = { $__: {} };
const lean = { id: 1 };
expect(countHydratedDocuments([hydrated, lean, hydrated])).toBe(2);
expect(countHydratedDocuments(lean)).toBe(0);
expect(countHydratedDocuments(hydrated)).toBe(1);
});
});
@@ -0,0 +1,188 @@
import mongoose from 'mongoose';
import { recordMongooseQueryPerformance } from './performance-observer';
const QUERY_PERFORMANCE_START = Symbol('queryPerformanceStart');
const QUERY_PERFORMANCE_RECORDED = Symbol('queryPerformanceRecorded');
const PERFORMANCE_PLUGIN_APPLIED = Symbol('performancePluginApplied');
const QUERY_OPERATIONS = [
'countDocuments',
'deleteMany',
'deleteOne',
'find',
'findOne',
'findOneAndDelete',
'findOneAndReplace',
'findOneAndUpdate',
'replaceOne',
'updateMany',
'updateOne',
] as const;
const QUERY_OPERATION_REGEX = new RegExp(`^(${QUERY_OPERATIONS.join('|')})$`);
type QueryWithPerformanceState = mongoose.Query<unknown, unknown> & {
[QUERY_PERFORMANCE_START]?: bigint;
[QUERY_PERFORMANCE_RECORDED]?: boolean;
};
type AggregateWithPerformanceState = mongoose.Aggregate<unknown[]> & {
[QUERY_PERFORMANCE_START]?: bigint;
[QUERY_PERFORMANCE_RECORDED]?: boolean;
};
type SchemaWithPerformanceMarker = mongoose.Schema & {
[PERFORMANCE_PLUGIN_APPLIED]?: boolean;
};
export function applyMongoosePerformancePlugin(schema: mongoose.Schema): void {
const markedSchema = schema as SchemaWithPerformanceMarker;
if (markedSchema[PERFORMANCE_PLUGIN_APPLIED]) return;
markedSchema[PERFORMANCE_PLUGIN_APPLIED] = true;
const hookableSchema = schema as any;
hookableSchema.pre(QUERY_OPERATION_REGEX, function () {
const query = this as QueryWithPerformanceState;
query[QUERY_PERFORMANCE_START] = process.hrtime.bigint();
query[QUERY_PERFORMANCE_RECORDED] = false;
});
hookableSchema.post(
QUERY_OPERATION_REGEX,
function (result: unknown) {
recordQueryPerformance(
this as unknown as QueryWithPerformanceState,
result,
);
},
);
hookableSchema.post(
QUERY_OPERATION_REGEX,
function (error: unknown, _result: unknown, next: (error: unknown) => void) {
recordQueryPerformance(
this as unknown as QueryWithPerformanceState,
undefined,
error,
);
next(error);
},
);
hookableSchema.pre('aggregate', function () {
const aggregate = this as AggregateWithPerformanceState;
aggregate[QUERY_PERFORMANCE_START] = process.hrtime.bigint();
aggregate[QUERY_PERFORMANCE_RECORDED] = false;
});
hookableSchema.post('aggregate', function (result: unknown) {
recordAggregatePerformance(this as AggregateWithPerformanceState, result);
});
hookableSchema.post(
'aggregate',
function (error: unknown, _result: unknown, next: (error: unknown) => void) {
recordAggregatePerformance(
this as AggregateWithPerformanceState,
undefined,
error,
);
next(error);
},
);
}
function recordQueryPerformance(
query: QueryWithPerformanceState,
result: unknown,
error?: unknown,
): void {
if (query[QUERY_PERFORMANCE_RECORDED]) return;
query[QUERY_PERFORMANCE_RECORDED] = true;
const startedAt = query[QUERY_PERFORMANCE_START];
if (!startedAt) return;
const hydratedDocsReturned = countHydratedDocuments(result);
const model = query.model as mongoose.Model<unknown> | undefined;
const options = query.getOptions();
recordMongooseQueryPerformance({
operation: (query as unknown as { op?: string }).op ?? 'query',
modelName: model?.modelName ?? 'unknown',
collectionName: model?.collection?.name,
durationMs: toDurationMs(startedAt),
docsReturned: countReturnedDocuments(result),
hydratedDocsReturned,
lean: Boolean(query.mongooseOptions().lean),
limit: numberOption(options.limit),
skip: numberOption(options.skip),
filterKeys: joinObjectKeys(query.getFilter()),
projectionKeys: joinObjectKeys(query.projection()),
sortKeys: joinObjectKeys(options.sort),
errorName: errorName(error),
});
}
function recordAggregatePerformance(
aggregate: AggregateWithPerformanceState,
result: unknown,
error?: unknown,
): void {
if (aggregate[QUERY_PERFORMANCE_RECORDED]) return;
aggregate[QUERY_PERFORMANCE_RECORDED] = true;
const startedAt = aggregate[QUERY_PERFORMANCE_START];
if (!startedAt) return;
const model = aggregate.model();
recordMongooseQueryPerformance({
operation: 'aggregate',
modelName: model?.modelName ?? 'unknown',
collectionName: model?.collection?.name,
durationMs: toDurationMs(startedAt),
docsReturned: countReturnedDocuments(result),
hydratedDocsReturned: countHydratedDocuments(result),
lean: true,
errorName: errorName(error),
});
}
export function countReturnedDocuments(result: unknown): number {
if (Array.isArray(result)) return result.length;
if (result == null) return 0;
if (typeof result === 'number') return result;
return 1;
}
export function countHydratedDocuments(result: unknown): number {
if (Array.isArray(result)) {
return result.filter((item) => isHydratedDocument(item)).length;
}
return isHydratedDocument(result) ? 1 : 0;
}
function isHydratedDocument(value: unknown): boolean {
return Boolean(
value &&
typeof value === 'object' &&
'$__' in (value as Record<string, unknown>),
);
}
function toDurationMs(startedAt: bigint): number {
return Number(process.hrtime.bigint() - startedAt) / 1_000_000;
}
function numberOption(value: unknown): number | undefined {
return typeof value === 'number' ? value : undefined;
}
function joinObjectKeys(value: unknown): string | undefined {
if (!value || typeof value !== 'object') return undefined;
const keys = Object.keys(value as Record<string, unknown>).sort();
return keys.length > 0 ? keys.join(',') : undefined;
}
function errorName(error: unknown): string | undefined {
return error instanceof Error ? error.name : undefined;
}
@@ -0,0 +1,65 @@
// [AUCTION-DEBUG] 경매 "중복 멤버" 조사용 서버 계측 래퍼. 조사 종료 후 호출부와 함께
// 제거 대상(범용으로 남길 거면 이 마커만 떼면 됨).
import newrelicAgent from 'newrelic';
export type NewRelicAttributeValue = string | number | boolean | null;
// newrelic 기본 export는 타입이 느슨해 unsafe-call로 잡힌다. 우리가 쓰는 부분만
// 좁게 타입을 고정한다(에이전트는 -r newrelic로 이미 preload됨).
interface NewRelicCustomEventApi {
recordCustomEvent(
eventType: string,
attributes: Record<string, NewRelicAttributeValue>,
): void;
addCustomAttributes(
attributes: Record<string, NewRelicAttributeValue>,
): void;
setTransactionName(name: string): void;
}
const agent = newrelicAgent as unknown as NewRelicCustomEventApi;
/**
* 서버 커스텀 이벤트를 New Relic으로 보낸다(클라의 addPageAction 대응).
*
* - 에이전트는 `-r newrelic`로 이미 preload되어 있으므로 여기서 import만 하면 된다.
* - `recordCustomEvent`는 활성 트랜잭션이 없어도 동작하므로 durability 스케줄러
* tick이나 socket.io 핸들러처럼 HTTP 컨텍스트 밖에서도 그대로 호출할 수 있다.
* - 평탄한 스칼라만 받는다(중첩 객체/배열 불가). undefined 속성은 제거한다.
* - 에이전트 비활성/테스트 환경에서도 호출부가 깨지지 않도록 예외를 삼킨다.
*/
export function recordNewRelicCustomEvent(
eventType: string,
attributes: Record<string, NewRelicAttributeValue | undefined>,
): void {
try {
const flat: Record<string, NewRelicAttributeValue> = {};
for (const [key, value] of Object.entries(attributes)) {
if (value !== undefined) flat[key] = value;
}
agent.recordCustomEvent(eventType, flat);
} catch {
// 관측성 실패가 비즈니스 로직을 막아선 안 된다.
}
}
export function addNewRelicCustomAttributes(
attributes: Record<string, NewRelicAttributeValue | undefined>,
): void {
try {
const flat: Record<string, NewRelicAttributeValue> = {};
for (const [key, value] of Object.entries(attributes)) {
if (value !== undefined) flat[key] = value;
}
agent.addCustomAttributes(flat);
} catch {
// 관측성 실패가 비즈니스 로직을 막아선 안 된다.
}
}
export function setNewRelicTransactionName(name: string): void {
try {
agent.setTransactionName(name);
} catch {
// 관측성 실패가 비즈니스 로직을 막아선 안 된다.
}
}
@@ -0,0 +1,80 @@
import {
buildApiRequestPerformanceEvent,
createApiPerformanceRequestContext,
readBoolean,
recordMongooseQueryPerformance,
resolveApiPerformanceConfig,
runWithApiPerformanceContext,
} from './performance-observer';
describe('performance observer config', () => {
it('keeps observability disabled by default', () => {
expect(resolveApiPerformanceConfig({}).enabled).toBe(false);
expect(resolveApiPerformanceConfig({}).localEventsEnabled).toBe(false);
});
it('reads common boolean values', () => {
expect(readBoolean(undefined, true)).toBe(true);
expect(readBoolean('false', true)).toBe(false);
expect(readBoolean('enabled', false)).toBe(true);
});
});
describe('API performance request context', () => {
const originalEnv = process.env;
beforeEach(() => {
process.env = {
...originalEnv,
API_PERF_OBSERVABILITY_ENABLED: 'true',
API_PERF_LOCAL_EVENTS_ENABLED: 'false',
API_PERF_NEW_RELIC_QUERY_EVENTS_ENABLED: 'false',
};
});
afterEach(() => {
process.env = originalEnv;
});
it('aggregates Mongoose document-return metrics into the request event', () => {
const context = createApiPerformanceRequestContext({
method: 'GET',
route: '/communities/:communityId/internal-stats/matches',
path: '/communities/abc/internal-stats/matches',
});
const event = runWithApiPerformanceContext(context, () => {
recordMongooseQueryPerformance({
operation: 'find',
modelName: 'matchStats',
collectionName: 'match_stats',
durationMs: 12,
docsReturned: 300,
hydratedDocsReturned: 300,
lean: false,
});
recordMongooseQueryPerformance({
operation: 'find',
modelName: 'matchStats',
collectionName: 'match_stats',
durationMs: 3,
docsReturned: 20,
hydratedDocsReturned: 0,
lean: true,
});
return buildApiRequestPerformanceEvent({
context,
statusCode: 200,
durationMs: 50,
isError: false,
});
});
expect(event.queryCount).toBe(2);
expect(event.mongooseDurationMs).toBe(15);
expect(event.docsReturned).toBe(320);
expect(event.hydratedDocsReturned).toBe(300);
expect(event.leanQueryCount).toBe(1);
});
});
@@ -0,0 +1,285 @@
import { AsyncLocalStorage } from 'node:async_hooks';
import { randomUUID } from 'node:crypto';
import { appendFile } from 'node:fs/promises';
import {
addNewRelicCustomAttributes,
NewRelicAttributeValue,
recordNewRelicCustomEvent,
} from './new-relic';
export type PerformanceEventType = 'api-request' | 'mongoose-query';
export interface ApiPerformanceConfig {
enabled: boolean;
localEventsEnabled: boolean;
localEventFile: string;
newRelicRequestEventsEnabled: boolean;
newRelicQueryEventsEnabled: boolean;
appName: string;
nodeEnv: string;
}
export interface MongooseQueryPerformance {
operation: string;
modelName: string;
collectionName?: string;
durationMs: number;
docsReturned: number;
hydratedDocsReturned: number;
lean: boolean;
limit?: number;
skip?: number;
filterKeys?: string;
projectionKeys?: string;
sortKeys?: string;
errorName?: string;
}
export interface ApiRequestPerformanceEvent {
type: 'api-request';
timestamp: string;
requestId: string;
method: string;
route: string;
path: string;
statusCode: number;
durationMs: number;
isError: boolean;
queryCount: number;
mongooseDurationMs: number;
docsReturned: number;
hydratedDocsReturned: number;
leanQueryCount: number;
}
export interface MongooseQueryPerformanceEvent
extends MongooseQueryPerformance {
type: 'mongoose-query';
timestamp: string;
requestId?: string;
method?: string;
route?: string;
path?: string;
}
export type ApiPerformanceEvent =
| ApiRequestPerformanceEvent
| MongooseQueryPerformanceEvent;
export interface ApiPerformanceContext {
requestId: string;
method: string;
route: string;
path: string;
queries: MongooseQueryPerformance[];
}
const storage = new AsyncLocalStorage<ApiPerformanceContext>();
export function readBoolean(
value: string | undefined,
defaultValue: boolean,
): boolean {
if (value == null || value.trim() === '') return defaultValue;
return !['0', 'false', 'f', 'no', 'n', 'disabled', 'off'].includes(
value.trim().toLowerCase(),
);
}
export function resolveApiPerformanceConfig(
env: NodeJS.ProcessEnv = process.env,
): ApiPerformanceConfig {
const enabled = readBoolean(env.API_PERF_OBSERVABILITY_ENABLED, false);
return {
enabled,
localEventsEnabled: readBoolean(
env.API_PERF_LOCAL_EVENTS_ENABLED,
enabled,
),
localEventFile:
env.API_PERF_LOCAL_EVENT_FILE || '/tmp/lolympus-api-performance.ndjson',
newRelicRequestEventsEnabled: readBoolean(
env.API_PERF_NEW_RELIC_REQUEST_EVENTS_ENABLED,
enabled,
),
newRelicQueryEventsEnabled: readBoolean(
env.API_PERF_NEW_RELIC_QUERY_EVENTS_ENABLED,
false,
),
appName: env.NEW_RELIC_APP_NAME || 'lolympus',
nodeEnv: env.NODE_ENV || 'dev',
};
}
export function isApiPerformanceObservabilityEnabled(): boolean {
return resolveApiPerformanceConfig().enabled;
}
export function createApiPerformanceRequestContext(params: {
method: string;
route: string;
path: string;
}): ApiPerformanceContext {
return {
requestId: randomUUID(),
method: params.method,
route: params.route,
path: params.path,
queries: [],
};
}
export function runWithApiPerformanceContext<T>(
context: ApiPerformanceContext,
callback: () => T,
): T {
return storage.run(context, callback);
}
export function getCurrentApiPerformanceContext():
| ApiPerformanceContext
| undefined {
return storage.getStore();
}
export function recordMongooseQueryPerformance(
query: MongooseQueryPerformance,
): void {
if (!isApiPerformanceObservabilityEnabled()) return;
const config = resolveApiPerformanceConfig();
const context = storage.getStore();
context?.queries.push(query);
const event: MongooseQueryPerformanceEvent = {
...query,
type: 'mongoose-query',
timestamp: new Date().toISOString(),
requestId: context?.requestId,
method: context?.method,
route: context?.route,
path: context?.path,
};
if (config.localEventsEnabled) appendLocalPerformanceEvent(event, config);
if (config.newRelicQueryEventsEnabled) {
recordNewRelicCustomEvent('MongooseQueryPerformance', {
appName: config.appName,
nodeEnv: config.nodeEnv,
requestId: event.requestId,
method: event.method,
route: event.route,
operation: event.operation,
modelName: event.modelName,
collectionName: event.collectionName,
durationMs: event.durationMs,
docsReturned: event.docsReturned,
hydratedDocsReturned: event.hydratedDocsReturned,
lean: event.lean,
limit: event.limit,
skip: event.skip,
errorName: event.errorName,
});
}
}
export function buildApiRequestPerformanceEvent(params: {
context: ApiPerformanceContext;
statusCode: number;
durationMs: number;
isError: boolean;
}): ApiRequestPerformanceEvent {
const queries = params.context.queries;
return {
type: 'api-request',
timestamp: new Date().toISOString(),
requestId: params.context.requestId,
method: params.context.method,
route: params.context.route,
path: params.context.path,
statusCode: params.statusCode,
durationMs: params.durationMs,
isError: params.isError,
queryCount: queries.length,
mongooseDurationMs: sum(queries.map((query) => query.durationMs)),
docsReturned: sum(queries.map((query) => query.docsReturned)),
hydratedDocsReturned: sum(
queries.map((query) => query.hydratedDocsReturned),
),
leanQueryCount: queries.filter((query) => query.lean).length,
};
}
export function recordApiRequestPerformance(
event: ApiRequestPerformanceEvent,
): void {
if (!isApiPerformanceObservabilityEnabled()) return;
const config = resolveApiPerformanceConfig();
if (config.localEventsEnabled) appendLocalPerformanceEvent(event, config);
if (config.newRelicRequestEventsEnabled) {
recordNewRelicCustomEvent('ApiRequestPerformance', {
appName: config.appName,
nodeEnv: config.nodeEnv,
requestId: event.requestId,
method: event.method,
route: event.route,
statusCode: event.statusCode,
durationMs: event.durationMs,
isError: event.isError,
queryCount: event.queryCount,
mongooseDurationMs: event.mongooseDurationMs,
docsReturned: event.docsReturned,
hydratedDocsReturned: event.hydratedDocsReturned,
leanQueryCount: event.leanQueryCount,
});
}
addNewRelicCustomAttributes({
appName: config.appName,
nodeEnv: config.nodeEnv,
'api.request_id': event.requestId,
'api.method': event.method,
'api.route': event.route,
'api.status_code': event.statusCode,
'api.duration_ms': event.durationMs,
'api.is_error': event.isError,
'mongoose.query_count': event.queryCount,
'mongoose.duration_ms': event.mongooseDurationMs,
'mongoose.docs_returned': event.docsReturned,
'mongoose.hydrated_docs_returned': event.hydratedDocsReturned,
'mongoose.lean_query_count': event.leanQueryCount,
});
}
export function appendLocalPerformanceEvent(
event: ApiPerformanceEvent,
config: ApiPerformanceConfig = resolveApiPerformanceConfig(),
): void {
void appendFile(config.localEventFile, `${JSON.stringify(event)}\n`).catch(
() => {
// 관측성 실패가 API 응답을 막아선 안 된다.
},
);
}
export function toNewRelicAttributes(
event: ApiRequestPerformanceEvent,
): Record<string, NewRelicAttributeValue> {
return {
requestId: event.requestId,
method: event.method,
route: event.route,
statusCode: event.statusCode,
durationMs: event.durationMs,
isError: event.isError,
queryCount: event.queryCount,
mongooseDurationMs: event.mongooseDurationMs,
docsReturned: event.docsReturned,
hydratedDocsReturned: event.hydratedDocsReturned,
leanQueryCount: event.leanQueryCount,
};
}
function sum(values: number[]): number {
return values.reduce((acc, value) => acc + value, 0);
}
@@ -0,0 +1,121 @@
import { DistributedLockService } from './distributed-lock.service';
import { RedisService } from './redis.service';
function createService(sendCommand: jest.Mock) {
const redisService = {
raw: jest.fn().mockReturnValue({ sendCommand }),
} as unknown as RedisService;
return new DistributedLockService(redisService);
}
describe('DistributedLockService', () => {
it('acquires a lock with a token and millisecond expiration', async () => {
const sendCommand = jest.fn().mockResolvedValue('OK');
const service = createService(sendCommand);
const lockOwnership = await service.acquireLock({
lockKey: 'distributed-lock:test',
lockOwnershipToken: 'owner-token',
lockExpirationDurationMilliseconds: 30_000,
});
expect(lockOwnership).toEqual({
lockKey: 'distributed-lock:test',
lockOwnershipToken: 'owner-token',
lockExpirationDurationMilliseconds: 30_000,
});
expect(sendCommand).toHaveBeenCalledWith([
'SET',
'distributed-lock:test',
'owner-token',
'NX',
'PX',
'30000',
]);
});
it('returns null when another owner already holds the lock', async () => {
const sendCommand = jest.fn().mockResolvedValue(null);
const service = createService(sendCommand);
await expect(
service.acquireLock({
lockKey: 'distributed-lock:test',
lockExpirationDurationMilliseconds: 30_000,
}),
).resolves.toBeNull();
});
it('releases a lock only when the ownership token matches', async () => {
const sendCommand = jest.fn().mockResolvedValue(1);
const service = createService(sendCommand);
await expect(
service.releaseLockIfOwned({
lockKey: 'distributed-lock:test',
lockOwnershipToken: 'owner-token',
lockExpirationDurationMilliseconds: 30_000,
}),
).resolves.toBe(true);
expect(sendCommand).toHaveBeenCalledWith([
'EVAL',
expect.stringContaining('redis.call("GET", KEYS[1]) == ARGV[1]'),
'1',
'distributed-lock:test',
'owner-token',
]);
});
it('extends a lock only when the ownership token matches', async () => {
const sendCommand = jest.fn().mockResolvedValue(1);
const service = createService(sendCommand);
await expect(
service.extendLockIfOwned(
{
lockKey: 'distributed-lock:test',
lockOwnershipToken: 'owner-token',
lockExpirationDurationMilliseconds: 30_000,
},
45_000,
),
).resolves.toBe(true);
expect(sendCommand).toHaveBeenCalledWith([
'EVAL',
expect.stringContaining('PEXPIRE'),
'1',
'distributed-lock:test',
'owner-token',
'45000',
]);
});
it('runs the operation and releases the lock afterward', async () => {
const sendCommand = jest
.fn()
.mockResolvedValueOnce('OK')
.mockResolvedValueOnce(1);
const service = createService(sendCommand);
const operation = jest.fn().mockResolvedValue('done');
await expect(
service.runWithLock(
{
lockKey: 'distributed-lock:test',
lockExpirationDurationMilliseconds: 30_000,
},
operation,
),
).resolves.toBe('done');
expect(operation).toHaveBeenCalledWith(
expect.objectContaining({
lockKey: 'distributed-lock:test',
lockExpirationDurationMilliseconds: 30_000,
}),
);
expect(sendCommand).toHaveBeenCalledTimes(2);
});
});
@@ -0,0 +1,199 @@
import { Injectable, Logger } from '@nestjs/common';
import { randomUUID } from 'crypto';
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 {
lockKey: string;
lockOwnershipToken: string;
lockExpirationDurationMilliseconds: number;
}
export interface AcquireDistributedLockOptions {
lockKey: string;
lockExpirationDurationMilliseconds: number;
lockOwnershipToken?: string;
}
export interface RunWithDistributedLockOptions {
lockKey: string;
lockExpirationDurationMilliseconds: number;
lockAcquireTimeoutMilliseconds?: number;
lockRetryDelayMilliseconds?: number;
}
export interface RunWithRenewedDistributedLockOptions
extends RunWithDistributedLockOptions {
lockRenewalIntervalMilliseconds: number;
}
@Injectable()
export class DistributedLockService {
private readonly logger = new Logger(DistributedLockService.name);
constructor(private readonly redisService: RedisService) {}
public async acquireLock(
options: AcquireDistributedLockOptions,
): Promise<DistributedLockOwnership | null> {
this.assertPositiveDuration(
options.lockExpirationDurationMilliseconds,
'lockExpirationDurationMilliseconds',
);
const lockOwnershipToken = options.lockOwnershipToken ?? randomUUID();
const result = await this.redisService.raw().sendCommand([
'SET',
options.lockKey,
lockOwnershipToken,
'NX',
'PX',
String(options.lockExpirationDurationMilliseconds),
]);
if (String(result) !== 'OK') return null;
return {
lockKey: options.lockKey,
lockOwnershipToken,
lockExpirationDurationMilliseconds:
options.lockExpirationDurationMilliseconds,
};
}
public async releaseLockIfOwned(
lockOwnership: DistributedLockOwnership,
): Promise<boolean> {
const result = await this.redisService.raw().sendCommand([
'EVAL',
RELEASE_LOCK_IF_OWNED_SCRIPT,
'1',
lockOwnership.lockKey,
lockOwnership.lockOwnershipToken,
]);
return Number(result) === 1;
}
public async extendLockIfOwned(
lockOwnership: DistributedLockOwnership,
lockExpirationDurationMilliseconds =
lockOwnership.lockExpirationDurationMilliseconds,
): Promise<boolean> {
this.assertPositiveDuration(
lockExpirationDurationMilliseconds,
'lockExpirationDurationMilliseconds',
);
const result = await this.redisService.raw().sendCommand([
'EVAL',
EXTEND_LOCK_IF_OWNED_SCRIPT,
'1',
lockOwnership.lockKey,
lockOwnership.lockOwnershipToken,
String(lockExpirationDurationMilliseconds),
]);
return Number(result) === 1;
}
public async runWithLock<TResult>(
options: RunWithDistributedLockOptions,
operation: (lockOwnership: DistributedLockOwnership) => Promise<TResult>,
): Promise<TResult | null> {
const lockOwnership = await this.acquireLockWithRetry(options);
if (!lockOwnership) return null;
try {
return await operation(lockOwnership);
} finally {
await this.releaseLockIfOwned(lockOwnership).catch((error: unknown) => {
this.logger.warn(
`Failed to release distributed lock ${lockOwnership.lockKey}: ${
error instanceof Error ? error.message : error
}`,
);
});
}
}
public async runWithRenewedLock<TResult>(
options: RunWithRenewedDistributedLockOptions,
operation: (lockOwnership: DistributedLockOwnership) => Promise<TResult>,
): Promise<TResult | null> {
this.assertPositiveDuration(
options.lockRenewalIntervalMilliseconds,
'lockRenewalIntervalMilliseconds',
);
const lockOwnership = await this.acquireLockWithRetry(options);
if (!lockOwnership) return null;
let lockRenewalTimer: NodeJS.Timeout | undefined;
lockRenewalTimer = setInterval(() => {
void this.extendLockIfOwned(lockOwnership).then((wasExtended) => {
if (wasExtended) return;
this.logger.warn(
`Lost distributed lock ownership before operation finished: ${lockOwnership.lockKey}`,
);
});
}, options.lockRenewalIntervalMilliseconds);
lockRenewalTimer.unref?.();
try {
return await operation(lockOwnership);
} finally {
if (lockRenewalTimer) clearInterval(lockRenewalTimer);
await this.releaseLockIfOwned(lockOwnership).catch((error: unknown) => {
this.logger.warn(
`Failed to release distributed lock ${lockOwnership.lockKey}: ${
error instanceof Error ? error.message : error
}`,
);
});
}
}
private async acquireLockWithRetry(
options: RunWithDistributedLockOptions,
): Promise<DistributedLockOwnership | null> {
const lockAcquireTimeoutMilliseconds =
options.lockAcquireTimeoutMilliseconds ?? 0;
const lockRetryDelayMilliseconds =
options.lockRetryDelayMilliseconds ?? 100;
const acquisitionStartedAtTimestampMilliseconds = Date.now();
while (true) {
const lockOwnership = await this.acquireLock(options);
if (lockOwnership) return lockOwnership;
if (lockAcquireTimeoutMilliseconds <= 0) return null;
const elapsedMilliseconds =
Date.now() - acquisitionStartedAtTimestampMilliseconds;
if (elapsedMilliseconds >= lockAcquireTimeoutMilliseconds) return null;
await this.sleep(
Math.min(lockRetryDelayMilliseconds, lockAcquireTimeoutMilliseconds),
);
}
}
private assertPositiveDuration(value: number, fieldName: string): void {
if (Number.isFinite(value) && value > 0) return;
throw new Error(`${fieldName} must be a positive finite number.`);
}
private sleep(durationMilliseconds: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, durationMilliseconds));
}
}
@@ -4,6 +4,7 @@ import { SecretModule } from '../secret/secret.module';
import { SecretService } from '../secret/secret.service';
import { REDIS_CLIENT } from './redis.constants';
import { resolveRedisClientOptions } from './redis.config';
import { DistributedLockService } from './distributed-lock.service';
import { RedisService, type RedisClient } from './redis.service';
async function readFirstSecret(
@@ -62,7 +63,8 @@ async function readFirstSecret(
},
},
RedisService,
DistributedLockService,
],
exports: [RedisService, REDIS_CLIENT],
exports: [RedisService, DistributedLockService, REDIS_CLIENT],
})
export class RedisModule {}
@@ -0,0 +1,52 @@
import { RedisService } from './redis.service';
function createRedisService(client: Record<string, unknown>) {
return new RedisService(client as never);
}
describe('RedisService stream pending recovery', () => {
it('normalizes XAUTOCLAIM array replies into stream entries', async () => {
const sendCommand = jest.fn().mockResolvedValue([
'0-0',
[
[
'1700000000000-0',
['job', '{"kind":"poll-tournament-result"}', 'source', 'test'],
],
],
]);
const service = createRedisService({ sendCommand });
await expect(
service.claimStalePendingStreamMessages({
key: 'riot:queue:high',
group: 'riot-refresh-worker',
consumer: 'worker-1',
stalePendingMessageMinimumIdleMilliseconds: 1_800_000,
count: 1,
}),
).resolves.toEqual({
nextStartId: '0-0',
messages: [
{
id: '1700000000000-0',
message: {
job: '{"kind":"poll-tournament-result"}',
source: 'test',
},
},
],
});
expect(sendCommand).toHaveBeenCalledWith([
'XAUTOCLAIM',
'riot:queue:high',
'riot-refresh-worker',
'worker-1',
'1800000',
'0-0',
'COUNT',
'1',
]);
});
});
@@ -16,6 +16,11 @@ export interface StreamReadResult {
name: string;
}
export interface ClaimStalePendingStreamMessagesResult {
messages: StreamEntry[];
nextStartId: string;
}
interface RawStreamMessage {
deliveriesCounter?: number;
id: string;
@@ -29,6 +34,16 @@ interface RawStreamReadResult {
}
function normalizeStreamFields(fields: unknown): Record<string, string> {
if (Array.isArray(fields)) {
const normalized: Record<string, string> = {};
for (let index = 0; index < fields.length; index += 2) {
const key = fields[index];
if (key === undefined) continue;
normalized[String(key)] = String(fields[index + 1] ?? '');
}
return normalized;
}
if (fields instanceof Map) {
return Object.fromEntries(
[...fields.entries()].map(([key, value]) => [String(key), String(value)]),
@@ -188,6 +203,38 @@ export class RedisService implements OnModuleDestroy {
}));
}
public async claimStalePendingStreamMessages(options: {
key: string;
group: string;
consumer: string;
stalePendingMessageMinimumIdleMilliseconds: number;
startId?: string;
count?: number;
}): Promise<ClaimStalePendingStreamMessagesResult> {
const response = (await this.client.sendCommand([
'XAUTOCLAIM',
options.key,
options.group,
options.consumer,
String(options.stalePendingMessageMinimumIdleMilliseconds),
options.startId ?? '0-0',
'COUNT',
String(options.count ?? 1),
])) as unknown;
const responseItems = Array.isArray(response) ? response : [];
const rawMessages = Array.isArray(responseItems[1])
? responseItems[1]
: [];
return {
nextStartId: String(responseItems[0] ?? '0-0'),
messages: rawMessages
.map((rawMessage) => this.normalizeClaimedStreamMessage(rawMessage))
.filter((message): message is StreamEntry => Boolean(message)),
};
}
public async acknowledgeStream(
key: string,
group: string,
@@ -210,4 +257,37 @@ export class RedisService implements OnModuleDestroy {
public async publish(channel: string, message: string): Promise<number> {
return this.client.publish(channel, message);
}
private normalizeClaimedStreamMessage(rawMessage: unknown): StreamEntry | null {
if (Array.isArray(rawMessage)) {
const [id, fields] = rawMessage;
if (id === undefined) return null;
return {
id: String(id),
message: normalizeStreamFields(fields),
};
}
if (
typeof rawMessage === 'object' &&
rawMessage !== null &&
'id' in rawMessage
) {
const message = rawMessage as RawStreamMessage;
return {
deliveriesCounter:
typeof message.deliveriesCounter === 'number'
? message.deliveriesCounter
: undefined,
id: String(message.id),
message: normalizeStreamFields(message.message),
millisElapsedFromDelivery:
typeof message.millisElapsedFromDelivery === 'number'
? message.millisElapsedFromDelivery
: undefined,
};
}
return null;
}
}
@@ -0,0 +1,985 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/require-await, @typescript-eslint/unbound-method */
import { readFileSync } from 'node:fs';
import mongoose from 'mongoose';
import type { CompetitionBootstrapService } from '../competition/competition-bootstrap.service';
import type { CompetitionCommandService } from '../competition/competition-command.service';
import type { MatchStatsService } from '../community-stats/match-stats.service';
import type { CommunityStatsService } from '../community-stats/community-stats.service';
import type { ConnectionService } from '../global/database/connection.service';
import type { DistributedLockService } from '../global/redis/distributed-lock.service';
import type { RedisService } from '../global/redis/redis.service';
import type { RiotMatchService } from '../riot/riot-match.service';
import type { RiotMatchDto } from '../riot/riot.types';
import { LegacyImportService } from './legacy-import.service';
import type { LegacyUserSnapshot, UserByPuuidMap } from './match-builder.util';
import type { LegacyImportMemberJob } from './legacy-import.types';
const ServiceConstructor = LegacyImportService as unknown as new (
...dependencies: unknown[]
) => LegacyImportService;
describe('Legacy import Competition result cutover', () => {
it('has no production Match.result writer', () => {
const source = readFileSync(
require.resolve('./legacy-import.service'),
'utf8',
);
expect(source).not.toMatch(/\b(?:match|update)\.result\s*=/u);
expect(source).not.toMatch(/\bresult\s*:\s*\{\s*winnerTeamIndex/u);
});
it('creates a paired Competition and accepts Riot evidence without writing Match.result', async () => {
const fixture = createImportFixture();
const competitionFactModel = {
exists: jest.fn().mockResolvedValue(null),
};
const matchModel = {
findOneAndUpdate: jest.fn().mockReturnValue(execResult(fixture.match)),
updateOne: jest.fn().mockReturnValue(execResult({ modifiedCount: 1 })),
};
const connectionService = {
getModel: jest.fn(async (name: string) => {
if (name === 'competitionFact') return competitionFactModel;
if (name === 'match') return matchModel;
throw new Error(`Unexpected model ${name}`);
}),
} as unknown as ConnectionService;
const bootstrapService = {
bootstrap: jest.fn().mockResolvedValue(fixture.competition),
} as unknown as jest.Mocked<CompetitionBootstrapService>;
const commandService = {
acceptGame: jest.fn().mockResolvedValue({
competition: {
...fixture.competition,
revision: 1,
phase: 'completed',
},
commandId: 'command-1',
revision: 1,
replayed: false,
}),
} as unknown as jest.Mocked<CompetitionCommandService>;
const matchStatsService = {
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<MatchStatsService>;
const service = createService({
connectionService,
matchStatsService,
bootstrapService,
commandService,
runWithLock: async (_options, operation) => operation(),
});
jest
.spyOn(
service as unknown as {
ensureRiotMatchPersisted: (
riotMatchId: string,
region: string,
) => Promise<RiotMatchDto>;
},
'ensureRiotMatchPersisted',
)
.mockResolvedValue(fixture.detail);
const outcome = await importSingleMatch(
service,
fixture.detail.metadata.matchId,
fixture.job,
fixture.userByPuuid,
);
expect(outcome).toBe('imported');
expect(matchModel.findOneAndUpdate).toHaveBeenCalledWith(
{ _id: expect.any(mongoose.Types.ObjectId) },
{
$setOnInsert: expect.not.objectContaining({
result: expect.anything(),
doubleElimination: expect.anything(),
}),
},
expect.objectContaining({ upsert: true, returnDocument: 'after' }),
);
expect(bootstrapService.bootstrap).toHaveBeenCalledWith(
expect.objectContaining({
gameMode: 'pair',
gameCount: 1,
teams: expect.arrayContaining([
expect.objectContaining({ teamIndex: 1 }),
expect.objectContaining({ teamIndex: 2 }),
]),
}),
);
expect(commandService.acceptGame).toHaveBeenCalledWith(
expect.objectContaining({
competitionId: fixture.competition._id.toString(),
expectedRevision: 0,
evidence: expect.objectContaining({
type: 'riot',
riotMatchId: fixture.detail.metadata.matchId,
payloadHash: expect.stringMatching(/^[a-f0-9]{64}$/u),
}),
mapping: expect.objectContaining({
blueTeamId: fixture.blueTeamId.toString(),
redTeamId: fixture.redTeamId.toString(),
winnerTeamId: fixture.blueTeamId.toString(),
algorithmVersion: 'roster-overlap-v1',
mappingVersion: 1,
confidence: 1,
diagnostics: {
trustedOverlap: 10,
normalOverlap: 10,
reversedOverlap: 0,
},
participantAssignments: expect.any(Array),
snapshot: expect.any(Object),
}),
}),
);
expect(matchModel.updateOne).toHaveBeenCalledWith(
{ _id: fixture.match._id },
{ $set: { status: 'finished' } },
);
expect(matchStatsService.buildAndUpsert).toHaveBeenCalledWith(
fixture.match._id,
{ sourceRevision: 1 },
);
});
it('detects duplicates from accepted Competition fact evidence before fetching Riot data', async () => {
const fixture = createImportFixture();
const competitionFactModel = {
exists: jest
.fn()
.mockResolvedValue({ _id: new mongoose.Types.ObjectId() }),
};
const connectionService = {
getModel: jest.fn(async (name: string) => {
if (name === 'competitionFact') return competitionFactModel;
throw new Error(`Unexpected model ${name}`);
}),
} as unknown as ConnectionService;
const service = createService({
connectionService,
runWithLock: async (_options, operation) => operation(),
});
const ensureRiotMatchPersisted = jest
.spyOn(
service as unknown as {
ensureRiotMatchPersisted: () => Promise<RiotMatchDto>;
},
'ensureRiotMatchPersisted',
)
.mockResolvedValue(fixture.detail);
const outcome = await importSingleMatch(
service,
fixture.detail.metadata.matchId,
fixture.job,
fixture.userByPuuid,
);
expect(outcome).toBe('duplicate');
expect(competitionFactModel.exists).toHaveBeenCalledWith({
type: 'game-accepted',
'evidence.type': 'riot',
'evidence.riotMatchId': fixture.detail.metadata.matchId,
});
expect(ensureRiotMatchPersisted).not.toHaveBeenCalled();
});
it('lists new legacy imports from Competition projection when Match.result is absent', async () => {
const fixture = createImportFixture();
const canonicalCompetition = {
...fixture.competition,
revision: 1,
phase: 'completed',
projection: {
phase: 'completed',
series: [
{
...fixture.competition.projection.series[0],
status: 'completed',
entries: [
{
slot: 'A',
teamId: fixture.blueTeamId,
gameWins: 1,
},
{ slot: 'B', teamId: fixture.redTeamId, gameWins: 0 },
],
outcome: {
type: 'played',
winnerTeamId: fixture.blueTeamId,
loserTeamId: fixture.redTeamId,
},
},
],
gameSlots: [],
games: [
{
seriesId: fixture.competition.projection.series[0].seriesId,
winnerTeamId: fixture.blueTeamId,
evidence: {
type: 'riot',
riotMatchId: fixture.detail.metadata.matchId,
},
participants: fixture.match.participants.map(({ userId }) => ({
userId,
})),
},
],
},
};
const matchModel = {
find: jest.fn().mockReturnValue({
sort: jest.fn().mockReturnValue({
limit: jest.fn().mockReturnValue(execResult([fixture.match])),
}),
}),
};
const competitionModel = {
find: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue(execResult([canonicalCompetition])),
}),
};
const riotMatchModel = {
find: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue(
execResult([
{
matchId: fixture.detail.metadata.matchId,
raw: fixture.detail,
},
]),
),
}),
};
const connectionService = {
getModel: jest.fn((name: string) => {
if (name === 'match') return Promise.resolve(matchModel);
if (name === 'competition') return Promise.resolve(competitionModel);
if (name === 'riotMatch') return Promise.resolve(riotMatchModel);
return Promise.reject(new Error(`Unexpected model ${name}`));
}),
} as unknown as ConnectionService;
const service = createService({ connectionService });
jest
.spyOn(
service as unknown as {
buildUserByPuuidMap: () => Promise<UserByPuuidMap>;
},
'buildUserByPuuidMap',
)
.mockResolvedValue(fixture.userByPuuid);
const page = await service.listLegacyMatches({
communityId: fixture.match.communityId,
});
expect(page.matches).toEqual([
expect.objectContaining({
matchId: fixture.match._id.toString(),
riotMatchId: fixture.detail.metadata.matchId,
memberCount: 10,
externalCount: 0,
teamAIndex: 1,
teamBIndex: 2,
teamAWins: 1,
teamBWins: 0,
winnerTeamIndex: 1,
}),
]);
});
it('cascades admin deletion through Competition facts and read models', async () => {
const fixture = createImportFixture();
const session = {
startTransaction: jest.fn(),
commitTransaction: jest.fn().mockResolvedValue(undefined),
abortTransaction: jest.fn().mockResolvedValue(undefined),
endSession: jest.fn().mockResolvedValue(undefined),
};
const competitionFactModel = deleteManyModel();
const competitionOutboxModel = deleteManyModel();
const reservedCodeId = new mongoose.Types.ObjectId();
const usedCodeId = new mongoose.Types.ObjectId();
const assignmentModel = {
...deleteManyModel(),
find: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue(
execResult([
{ tournamentCodeId: reservedCodeId, state: 'reserved' },
{ tournamentCodeId: usedCodeId, state: 'used' },
]),
),
}),
}),
}),
};
const competitionModel = {
...deleteManyModel(),
find: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest
.fn()
.mockReturnValue(execResult([{ _id: fixture.competition._id }])),
}),
}),
}),
};
const matchModel = {
find: jest.fn().mockReturnValue({
select: jest
.fn()
.mockReturnValue(sessionResult([{ _id: fixture.match._id }])),
}),
deleteMany: jest.fn().mockReturnValue(sessionResult({ deletedCount: 1 })),
};
const tournamentCodeModel = {
find: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue(
execResult([
{
_id: reservedCodeId,
state: 'reserved',
matchId: fixture.match._id,
},
{
_id: usedCodeId,
state: 'used',
matchId: fixture.match._id,
},
]),
),
}),
}),
}),
updateMany: jest
.fn()
.mockReturnValue(sessionResult({ matchedCount: 1, modifiedCount: 1 })),
};
const matchStatsModel = deleteManyModel();
const quarantineCollection = {
deleteMany: jest.fn().mockResolvedValue({ deletedCount: 1 }),
};
const connectionService = {
createSession: jest.fn().mockResolvedValue(session),
getConnection: jest.fn().mockResolvedValue({
collection: jest.fn().mockReturnValue(quarantineCollection),
}),
getModel: jest.fn((name: string) => {
const models: Record<string, unknown> = {
match: matchModel,
competition: competitionModel,
competitionFact: competitionFactModel,
competitionOutbox: competitionOutboxModel,
tournamentCodeAssignment: assignmentModel,
tournamentCode: tournamentCodeModel,
matchStats: matchStatsModel,
};
const model = models[name];
return model
? Promise.resolve(model)
: Promise.reject(new Error(`Unexpected model ${name}`));
}),
} as unknown as ConnectionService;
const communityStatsService = {
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<CommunityStatsService>;
const service = createService({
connectionService,
communityStatsService,
});
const result = await service.bulkDeleteLegacyMatches({
communityId: fixture.match.communityId,
body: { matchIds: [fixture.match._id.toString()] },
});
expect(result).toEqual({ deleted: 1 });
for (const model of [
competitionFactModel,
competitionOutboxModel,
assignmentModel,
]) {
expect(model.deleteMany).toHaveBeenCalledWith({
competitionId: { $in: [fixture.competition._id] },
});
}
expect(competitionModel.deleteMany).toHaveBeenCalledWith({
_id: { $in: [fixture.competition._id] },
});
expect(tournamentCodeModel.updateMany).toHaveBeenCalledTimes(2);
expect(matchStatsModel.deleteMany).toHaveBeenCalledWith({
matchId: { $in: [fixture.match._id] },
});
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
expect(session.abortTransaction).not.toHaveBeenCalled();
expect(communityStatsService.invalidateCommunity).toHaveBeenCalledWith(
fixture.match.communityId,
);
});
it('aborts legacy deletion when an active assignment points to another Match code', async () => {
const harness = createBulkDeleteFailureHarness({
codeMatchId: new mongoose.Types.ObjectId(),
});
await expect(
harness.service.bulkDeleteLegacyMatches({
communityId: harness.fixture.match.communityId,
body: { matchIds: [harness.fixture.match._id.toString()] },
}),
).rejects.toThrow(/Tournament Code assignment/);
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).not.toHaveBeenCalled();
expect(harness.matchModel.deleteMany).not.toHaveBeenCalled();
expect(harness.competitionFactModel.deleteMany).not.toHaveBeenCalled();
});
it('aborts legacy deletion when a validated Tournament Code transition does not update exactly once', async () => {
const harness = createBulkDeleteFailureHarness({
updateResult: { matchedCount: 0, modifiedCount: 0 },
});
await expect(
harness.service.bulkDeleteLegacyMatches({
communityId: harness.fixture.match.communityId,
body: { matchIds: [harness.fixture.match._id.toString()] },
}),
).rejects.toThrow(/Tournament Code transition/);
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).not.toHaveBeenCalled();
expect(harness.matchModel.deleteMany).not.toHaveBeenCalled();
});
it('invalidates community caches again when a committed deletion is retried', async () => {
const harness = createBulkDeleteFailureHarness({});
harness.matchModel.find
.mockReset()
.mockReturnValueOnce({
select: jest
.fn()
.mockReturnValue(sessionResult([{ _id: harness.fixture.match._id }])),
})
.mockReturnValueOnce({
select: jest.fn().mockReturnValue(sessionResult([])),
});
harness.communityStatsService.invalidateCommunity
.mockRejectedValueOnce(new Error('Redis unavailable'))
.mockResolvedValueOnce(0);
await expect(
harness.service.bulkDeleteLegacyMatches({
communityId: harness.fixture.match.communityId,
body: { matchIds: [harness.fixture.match._id.toString()] },
}),
).rejects.toThrow('Redis unavailable');
await expect(
harness.service.bulkDeleteLegacyMatches({
communityId: harness.fixture.match.communityId,
body: { matchIds: [harness.fixture.match._id.toString()] },
}),
).resolves.toEqual({ deleted: 0 });
expect(
harness.communityStatsService.invalidateCommunity,
).toHaveBeenCalledTimes(2);
});
it('removes migration quarantine records in the same legacy deletion transaction', async () => {
const harness = createBulkDeleteFailureHarness({});
await harness.service.bulkDeleteLegacyMatches({
communityId: harness.fixture.match.communityId,
body: { matchIds: [harness.fixture.match._id.toString()] },
});
expect(harness.quarantineCollection.deleteMany).toHaveBeenCalledWith(
{ _id: { $in: [harness.fixture.match._id] } },
{ session: harness.session },
);
});
it('rebuilds a historical legacy Match into Competition facts without rewriting Match.result', async () => {
const fixture = createImportFixture();
const historicalMatch = {
...fixture.match,
legacyImported: true,
result: {
riotMatchIds: [fixture.detail.metadata.matchId],
games: [
{
riotMatchId: fixture.detail.metadata.matchId,
participants: [],
},
],
seriesResults: [],
},
};
const matchModel = {
find: jest.fn().mockReturnValue(execResult([historicalMatch])),
updateOne: jest.fn().mockReturnValue(execResult({ modifiedCount: 1 })),
};
const competitionModel = {
find: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue(execResult([])),
}),
};
const riotMatchModel = {
find: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue(
execResult([
{
matchId: fixture.detail.metadata.matchId,
raw: fixture.detail,
},
]),
),
}),
};
const connectionService = {
getModel: jest.fn(async (name: string) => {
if (name === 'match') return matchModel;
if (name === 'competition') return competitionModel;
if (name === 'riotMatch') return riotMatchModel;
throw new Error(`Unexpected model ${name}`);
}),
} as unknown as ConnectionService;
const bootstrapService = {
bootstrap: jest.fn().mockResolvedValue(fixture.competition),
} as unknown as jest.Mocked<CompetitionBootstrapService>;
const commandService = {
acceptGame: jest.fn().mockResolvedValue({
competition: {
...fixture.competition,
revision: 1,
phase: 'completed',
},
commandId: 'command-1',
revision: 1,
replayed: false,
}),
} as unknown as jest.Mocked<CompetitionCommandService>;
const matchStatsService = {
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<MatchStatsService>;
const service = createService({
connectionService,
matchStatsService,
bootstrapService,
commandService,
});
jest
.spyOn(
service as unknown as {
buildUserByPuuidMap: () => Promise<UserByPuuidMap>;
},
'buildUserByPuuidMap',
)
.mockResolvedValue(fixture.userByPuuid);
const result = await service.rebuildLegacyMatches({
communityId: fixture.match.communityId,
});
expect(result).toMatchObject({ scanned: 1, rebuilt: 1 });
for (const [, update] of matchModel.updateOne.mock.calls) {
expect(update).toEqual(
expect.objectContaining({
$set: expect.not.objectContaining({ result: expect.anything() }),
}),
);
}
expect(bootstrapService.bootstrap).toHaveBeenCalledTimes(1);
expect(commandService.acceptGame).toHaveBeenCalledWith(
expect.objectContaining({
actor: { type: 'system' },
evidence: expect.objectContaining({
type: 'riot',
riotMatchId: fixture.detail.metadata.matchId,
}),
}),
);
expect(matchStatsService.buildAndUpsert).toHaveBeenCalledWith(
fixture.match._id,
{ sourceRevision: 1 },
);
});
});
function createService(
options: {
connectionService?: ConnectionService;
communityStatsService?: CommunityStatsService;
matchStatsService?: MatchStatsService;
bootstrapService?: CompetitionBootstrapService;
commandService?: CompetitionCommandService;
runWithLock?: (
options: Record<string, unknown>,
operation: () => Promise<unknown>,
) => Promise<unknown>;
} = {},
): LegacyImportService {
const distributedLockService = {
runWithLock:
options.runWithLock ??
(async (
_options: Record<string, unknown>,
operation: () => Promise<unknown>,
) => operation()),
} as unknown as DistributedLockService;
return new ServiceConstructor(
options.connectionService ?? ({} as ConnectionService),
{} as RedisService,
{} as RiotMatchService,
options.communityStatsService ??
({
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
} as unknown as CommunityStatsService),
options.matchStatsService ?? ({} as MatchStatsService),
distributedLockService,
options.bootstrapService ?? ({} as CompetitionBootstrapService),
options.commandService ?? ({} as CompetitionCommandService),
);
}
async function importSingleMatch(
service: LegacyImportService,
riotMatchId: string,
job: LegacyImportMemberJob,
userByPuuid: UserByPuuidMap,
): Promise<string> {
return (
service as unknown as {
importSingleMatch: (
riotMatchId: string,
job: LegacyImportMemberJob,
userByPuuid: UserByPuuidMap,
) => Promise<string>;
}
).importSingleMatch(riotMatchId, job, userByPuuid);
}
function createImportFixture() {
const communityId = new mongoose.Types.ObjectId();
const triggeredBy = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const seriesId = new mongoose.Types.ObjectId();
const gameSlotId = new mongoose.Types.ObjectId();
const blueTeamId = new mongoose.Types.ObjectId();
const redTeamId = new mongoose.Types.ObjectId();
const users = Array.from({ length: 10 }, (_, index) => ({
userId: new mongoose.Types.ObjectId(),
puuid: `puuid-${index + 1}`,
}));
const userByPuuid: UserByPuuidMap = new Map(
users.map(({ userId, puuid }, index) => [
puuid,
{
userId,
account: {
puuid,
gameName: `player-${index + 1}`,
tagLine: 'KR1',
profileIconId: index + 1,
tiers: [],
isPrimary: true,
},
displayName: `player-${index + 1}`,
preferredPositions: [],
} as LegacyUserSnapshot,
]),
);
const participants = users.map(({ puuid }, index) => ({
puuid,
participantId: index + 1,
teamId: index < 5 ? 100 : 200,
championId: index + 1,
teamPosition: ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'][index % 5],
kills: index < 5 ? 10 : 2,
deaths: index < 5 ? 2 : 10,
assists: index < 5 ? 8 : 3,
win: index < 5,
}));
const detail = {
metadata: {
dataVersion: '2',
matchId: 'KR_legacy_1',
participants: users.map(({ puuid }) => puuid),
},
info: {
gameCreation: Date.parse('2026-07-12T10:00:00.000Z'),
gameEndTimestamp: Date.parse('2026-07-12T10:30:00.000Z'),
gameDuration: 1_800,
mapId: 11,
tournamentCode: 'LEGACY-CODE',
participants,
teams: [
{ teamId: 100, win: true },
{ teamId: 200, win: false },
],
},
} as unknown as RiotMatchDto;
const match = {
_id: matchId,
communityId,
title: 'legacy',
description: 'Legacy import (자동 생성)',
mapId: 11,
status: 'team-built',
scheduledAt: new Date(detail.info.gameCreation),
maxParticipants: 10,
gameCount: 1,
gameMode: 'pair',
tournamentCodeIds: [],
gameSchedule: [],
teamBuiltAt: new Date(detail.info.gameCreation),
hostUserId: triggeredBy,
participants: users.map(({ userId, puuid }, index) => ({
userId,
puuid,
gameName: `player-${index + 1}`,
tagLine: 'KR1',
profileIconId: index + 1,
preferredPositions: [],
joinedAt: new Date(detail.info.gameCreation),
})),
teams: [
{
teamIndex: 1,
name: '1팀',
members: users.slice(0, 5).map(({ userId }, index) => ({
userId,
assignedPosition: ['TOP', 'JGL', 'MID', 'ADC', 'SUP'][index],
})),
},
{
teamIndex: 2,
name: '2팀',
members: users.slice(5).map(({ userId }, index) => ({
userId,
assignedPosition: ['TOP', 'JGL', 'MID', 'ADC', 'SUP'][index],
})),
},
],
prizes: [],
notices: [],
schedule: [],
};
const competition = {
_id: competitionId,
matchId,
communityId,
revision: 0,
phase: 'ready',
teams: [
{
teamId: blueTeamId,
legacyTeamIndex: 1,
displayOrder: 1,
seedNumber: 1,
name: '1팀',
members: users.slice(0, 5).map(({ userId }) => ({ userId })),
},
{
teamId: redTeamId,
legacyTeamIndex: 2,
displayOrder: 2,
seedNumber: 2,
name: '2팀',
members: users.slice(5).map(({ userId }) => ({ userId })),
},
],
projection: {
phase: 'ready',
series: [
{
seriesId,
status: 'ready',
entries: [
{ slot: 'A', teamId: blueTeamId, gameWins: 0 },
{ slot: 'B', teamId: redTeamId, gameWins: 0 },
],
},
],
gameSlots: [
{
id: gameSlotId,
seriesId,
ordinal: 1,
displayNumber: 1,
status: 'ready',
},
],
games: [],
},
};
const job: LegacyImportMemberJob = {
kind: 'legacy-import-member',
jobId: 'member-job-1',
parentJobId: 'legacy-job-1',
communityId: communityId.toString(),
userId: users[0].userId.toString(),
puuid: users[0].puuid,
startTime: 1,
endTime: 2,
triggeredBy: triggeredBy.toString(),
region: 'asia',
};
return {
detail,
match,
competition,
blueTeamId,
redTeamId,
job,
userByPuuid,
};
}
function execResult<T>(value: T) {
return { exec: jest.fn().mockResolvedValue(value) };
}
function sessionResult<T>(value: T) {
const query = {
exec: jest.fn().mockResolvedValue(value),
session: jest.fn(),
};
query.session.mockReturnValue(query);
return query;
}
function deleteManyModel() {
return {
deleteMany: jest
.fn()
.mockReturnValue(sessionResult({ acknowledged: true, deletedCount: 1 })),
};
}
function createBulkDeleteFailureHarness(options: {
codeMatchId?: mongoose.Types.ObjectId;
codeState?: 'reserved' | 'used';
assignmentState?: 'reserved' | 'used';
updateResult?: { matchedCount: number; modifiedCount: number };
}) {
const fixture = createImportFixture();
const session = {
startTransaction: jest.fn(),
commitTransaction: jest.fn().mockResolvedValue(undefined),
abortTransaction: jest.fn().mockResolvedValue(undefined),
endSession: jest.fn().mockResolvedValue(undefined),
};
const tournamentCodeId = new mongoose.Types.ObjectId();
const assignmentState = options.assignmentState ?? 'reserved';
const codeState = options.codeState ?? assignmentState;
const assignmentModel = {
...deleteManyModel(),
find: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest
.fn()
.mockReturnValue(
execResult([{ tournamentCodeId, state: assignmentState }]),
),
}),
}),
}),
};
const competitionModel = {
...deleteManyModel(),
find: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest
.fn()
.mockReturnValue(execResult([{ _id: fixture.competition._id }])),
}),
}),
}),
};
const matchModel = {
find: jest.fn().mockReturnValue({
select: jest
.fn()
.mockReturnValue(sessionResult([{ _id: fixture.match._id }])),
}),
deleteMany: jest.fn().mockReturnValue(sessionResult({ deletedCount: 1 })),
};
const tournamentCodeModel = {
find: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue(
execResult([
{
_id: tournamentCodeId,
state: codeState,
matchId: options.codeMatchId ?? fixture.match._id,
},
]),
),
}),
}),
}),
updateMany: jest
.fn()
.mockReturnValue(
sessionResult(
options.updateResult ?? { matchedCount: 1, modifiedCount: 1 },
),
),
};
const competitionFactModel = deleteManyModel();
const competitionOutboxModel = deleteManyModel();
const matchStatsModel = deleteManyModel();
const quarantineCollection = {
deleteMany: jest.fn().mockResolvedValue({ deletedCount: 1 }),
};
const connectionService = {
createSession: jest.fn().mockResolvedValue(session),
getConnection: jest.fn().mockResolvedValue({
collection: jest.fn().mockReturnValue(quarantineCollection),
}),
getModel: jest.fn((name: string) => {
const models: Record<string, unknown> = {
match: matchModel,
competition: competitionModel,
competitionFact: competitionFactModel,
competitionOutbox: competitionOutboxModel,
tournamentCodeAssignment: assignmentModel,
tournamentCode: tournamentCodeModel,
matchStats: matchStatsModel,
};
const model = models[name];
return model
? Promise.resolve(model)
: Promise.reject(new Error(`Unexpected model ${name}`));
}),
} as unknown as ConnectionService;
const communityStatsService = {
invalidateCommunity: jest.fn().mockResolvedValue(0),
} as unknown as jest.Mocked<CommunityStatsService>;
const service = createService({ connectionService, communityStatsService });
return {
fixture,
session,
service,
matchModel,
competitionFactModel,
communityStatsService,
quarantineCollection,
};
}
@@ -1,11 +1,12 @@
import { Module } from '@nestjs/common';
import { CompetitionModule } from '../competition/competition.module';
import { CommunityStatsModule } from '../community-stats/community-stats.module';
import { RiotModule } from '../riot/riot.module';
import { LegacyImportController } from './legacy-import.controller';
import { LegacyImportService } from './legacy-import.service';
@Module({
imports: [RiotModule, CommunityStatsModule],
imports: [RiotModule, CommunityStatsModule, CompetitionModule],
controllers: [LegacyImportController],
providers: [LegacyImportService],
exports: [LegacyImportService],
@@ -0,0 +1,150 @@
import mongoose from 'mongoose';
import { CompetitionBootstrapService } from '../competition/competition-bootstrap.service';
import { CompetitionCommandService } from '../competition/competition-command.service';
import { MatchStatsService } from '../community-stats/match-stats.service';
import { CommunityStatsService } from '../community-stats/community-stats.service';
import { ConnectionService } from '../global/database/connection.service';
import { DistributedLockService } from '../global/redis/distributed-lock.service';
import { RedisService } from '../global/redis/redis.service';
import { RiotMatchService } from '../riot/riot-match.service';
import { LegacyImportService } from './legacy-import.service';
import type { LegacyImportMemberJob } from './legacy-import.types';
function execResult<T>(value: T) {
return { exec: jest.fn().mockResolvedValue(value) };
}
describe('LegacyImportService member job completion', () => {
it('increments aggregate counters only once for the same member job id', async () => {
const legacyImportJobModel = {
findOne: jest
.fn()
.mockReturnValueOnce(
execResult({
jobId: 'legacy-job-1',
state: 'running',
processedMembers: 0,
totalMembers: 1,
averageMemberSeconds: 60,
completedMemberJobIds: [],
}),
)
.mockReturnValueOnce({
select: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue(
execResult({
state: 'running',
processedMembers: 1,
totalMembers: 1,
}),
),
}),
})
.mockReturnValueOnce(
execResult({
jobId: 'legacy-job-1',
state: 'completed',
processedMembers: 1,
totalMembers: 1,
averageMemberSeconds: 60,
completedMemberJobIds: ['member-job-1'],
}),
),
updateOne: jest.fn().mockReturnValue(execResult({ modifiedCount: 1 })),
};
const connectionService = {
getModel: jest.fn().mockResolvedValue(legacyImportJobModel),
} as unknown as jest.Mocked<ConnectionService>;
const distributedLockService = {
releaseLockIfOwned: jest.fn().mockResolvedValue(true),
} as unknown as jest.Mocked<DistributedLockService>;
const communityStatsService = {
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<CommunityStatsService>;
const service = new LegacyImportService(
connectionService,
{} as RedisService,
{} as RiotMatchService,
communityStatsService,
{} as MatchStatsService,
distributedLockService,
{} as CompetitionBootstrapService,
{} as CompetitionCommandService,
);
const job: LegacyImportMemberJob = {
kind: 'legacy-import-member',
jobId: 'member-job-1',
parentJobId: 'legacy-job-1',
communityId: new mongoose.Types.ObjectId().toString(),
userId: new mongoose.Types.ObjectId().toString(),
puuid: 'puuid-1',
startTime: 1,
endTime: 2,
triggeredBy: new mongoose.Types.ObjectId().toString(),
region: 'asia',
};
await (
service as unknown as {
finishMemberJob: (
job: LegacyImportMemberJob,
stats: {
discovered: number;
imported: number;
duplicates: number;
errors: number;
elapsedSeconds: number;
},
) => Promise<void>;
}
).finishMemberJob(job, {
discovered: 3,
imported: 2,
duplicates: 1,
errors: 0,
elapsedSeconds: 30,
});
await (
service as unknown as {
finishMemberJob: (
job: LegacyImportMemberJob,
stats: {
discovered: number;
imported: number;
duplicates: number;
errors: number;
elapsedSeconds: number;
},
) => Promise<void>;
}
).finishMemberJob(job, {
discovered: 3,
imported: 2,
duplicates: 1,
errors: 0,
elapsedSeconds: 30,
});
expect(legacyImportJobModel.updateOne).toHaveBeenNthCalledWith(
1,
{
jobId: 'legacy-job-1',
completedMemberJobIds: { $ne: 'member-job-1' },
state: { $ne: 'cancelled' },
},
expect.objectContaining({
$addToSet: { completedMemberJobIds: 'member-job-1' },
$inc: expect.objectContaining({
processedMembers: 1,
totalDiscoveredMatchIds: 3,
totalImportedMatches: 2,
totalSkippedDuplicate: 1,
totalErrors: 0,
}),
}),
);
expect(legacyImportJobModel.updateOne).toHaveBeenCalledTimes(2);
expect(distributedLockService.releaseLockIfOwned).toHaveBeenCalledTimes(1);
expect(communityStatsService.invalidateCommunity).toHaveBeenCalledTimes(1);
});
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,140 @@
import mongoose from 'mongoose';
import { MatchHistoryService } from './match-history.service';
describe('MatchHistoryService.getChampionStats', () => {
it('aggregates champion stats in MongoDB with secondaryPreferred reads', async () => {
const communityId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
const aggregateExec = jest.fn().mockResolvedValue([
{
championId: 103,
games: 2,
wins: 1,
totalKills: 15,
totalDeaths: 5,
totalAssists: 20,
totalCs: 320,
totalGameMinutes: 62,
doubleKills: 2,
tripleKills: 1,
quadraKills: 0,
pentaKills: 0,
lastFetchedAt: new Date('2026-01-03T00:00:00.000Z'),
},
{
championId: 64,
games: 1,
wins: 1,
totalKills: 5,
totalDeaths: 0,
totalAssists: 7,
totalCs: 110,
totalGameMinutes: 25,
doubleKills: 0,
tripleKills: 0,
quadraKills: 0,
pentaKills: 0,
lastFetchedAt: new Date('2026-01-04T00:00:00.000Z'),
},
]);
const read = jest.fn().mockReturnThis();
const aggregate = jest.fn().mockReturnValue({ read, exec: aggregateExec });
const UserModel = {
findById: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({
_id: userId,
communityId,
riotAccounts: [
{
puuid: 'puuid-1',
isPrimary: true,
recentStatsFetchedAt: new Date('2026-01-05T00:00:00.000Z'),
},
],
}),
}),
};
const CommunityModel = {
findById: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({
_id: communityId,
seasonStartedAt: new Date('2026-01-01T00:00:00.000Z'),
seasons: [
{
id: 'current',
label: '현재 시즌',
startedAt: new Date('2026-01-01T00:00:00.000Z'),
},
],
}),
}),
};
const connectionService = {
getModel: jest.fn(async (name: string) => {
if (name === 'user') return UserModel;
if (name === 'community') return CommunityModel;
if (name === 'riotMatch') return { aggregate };
throw new Error(`Unexpected model: ${name}`);
}),
};
const service = new MatchHistoryService(connectionService as never);
const response = await service.getChampionStats({
communityId,
userId,
filters: { queueGroup: 'summoners-rift', rank: 'all' },
});
expect(aggregate).toHaveBeenCalledTimes(1);
expect(read).toHaveBeenCalledWith('secondaryPreferred');
expect(aggregateExec).toHaveBeenCalledTimes(1);
expect(aggregate.mock.calls[0][0]).toEqual(
expect.arrayContaining([
expect.objectContaining({
$match: expect.objectContaining({
participantPuuids: 'puuid-1',
gameCreation: {
$gte: new Date('2026-01-01T00:00:00.000Z').getTime(),
},
}),
}),
{ $limit: 500 },
expect.objectContaining({ $group: expect.any(Object) }),
]),
);
expect(response.champions).toEqual([
expect.objectContaining({
championId: 103,
games: 2,
wins: 1,
losses: 1,
winRate: 50,
avgKills: 7.5,
avgDeaths: 2.5,
avgAssists: 10,
kda: 7,
avgCs: 160,
}),
expect.objectContaining({
championId: 64,
games: 1,
wins: 1,
losses: 0,
winRate: 100,
kda: 12,
}),
]);
expect(response.totals).toEqual(
expect.objectContaining({
championId: 0,
games: 3,
wins: 2,
losses: 1,
totalKills: 20,
totalDeaths: 5,
totalAssists: 27,
}),
);
expect(response.lastFetchedAt).toBe('2026-01-03T00:00:00.000Z');
});
});
@@ -69,6 +69,10 @@ interface AggregatedChampion {
pentaKills: number;
}
interface ChampionAggregateRow extends AggregatedChampion {
lastFetchedAt?: Date;
}
@Injectable()
export class MatchHistoryService {
constructor(private readonly connectionService: ConnectionService) {}
@@ -129,29 +133,17 @@ export class MatchHistoryService {
const { queueGroup, rank, queueIds } = this.resolveQueueFilters(
params.filters,
);
const docs = await this.findStoredMatches({
const aggregates = await this.aggregateChampionStats({
context,
queueIds,
limit: MAX_AGGREGATE_MATCHES,
});
const aggregates = new Map<number, AggregatedChampion>();
for (const doc of docs) {
const dto = doc.raw as unknown as RiotMatchDto;
const participant = this.findParticipant(dto, context.account.puuid);
if (!participant) continue;
const aggregate =
aggregates.get(participant.championId) ??
this.createChampionAggregate(participant.championId);
this.addParticipantToChampionAggregate(aggregate, participant, dto);
aggregates.set(participant.championId, aggregate);
}
const champions = [...aggregates.values()]
const champions = aggregates
.map((aggregate) => this.toChampionStatsRow(aggregate))
.sort((a, b) => b.games - a.games || b.winRate - a.winRate);
const totals = this.toChampionStatsRow(
[...aggregates.values()].reduce(
aggregates.reduce(
(acc, aggregate) => this.mergeChampionAggregate(acc, aggregate),
this.createChampionAggregate(0),
),
@@ -162,7 +154,7 @@ export class MatchHistoryService {
rank,
queueIds,
season: context.season,
lastFetchedAt: this.resolveLastFetchedAt(docs, context),
lastFetchedAt: this.resolveAggregateLastFetchedAt(aggregates, context),
champions,
totals,
};
@@ -363,6 +355,101 @@ export class MatchHistoryService {
.slice(0, params.limit);
}
private async aggregateChampionStats(params: {
context: HistoryContext;
queueIds: number[];
limit: number;
}): Promise<ChampionAggregateRow[]> {
if (params.queueIds.length === 0) return [];
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const gameCreation: Record<string, number> = {};
if (params.context.seasonStartedAt) {
gameCreation.$gte = params.context.seasonStartedAt.getTime();
}
const match: Record<string, unknown> = {
participantPuuids: params.context.account.puuid,
queueId: { $in: params.queueIds },
};
if (Object.keys(gameCreation).length > 0) match.gameCreation = gameCreation;
return RiotMatchModel.aggregate<ChampionAggregateRow>([
{ $match: match },
{ $sort: { gameCreation: -1 } },
{ $limit: params.limit },
{
$project: {
fetchedAt: 1,
gameDuration: '$raw.info.gameDuration',
participant: {
$first: {
$filter: {
input: '$raw.info.participants',
as: 'participant',
cond: {
$eq: ['$$participant.puuid', params.context.account.puuid],
},
},
},
},
},
},
{ $match: { participant: { $ne: null } } },
{
$group: {
_id: '$participant.championId',
championId: { $first: '$participant.championId' },
games: { $sum: 1 },
wins: {
$sum: { $cond: ['$participant.win', 1, 0] },
},
totalKills: { $sum: { $ifNull: ['$participant.kills', 0] } },
totalDeaths: { $sum: { $ifNull: ['$participant.deaths', 0] } },
totalAssists: { $sum: { $ifNull: ['$participant.assists', 0] } },
totalCs: {
$sum: {
$add: [
{ $ifNull: ['$participant.totalMinionsKilled', 0] },
{ $ifNull: ['$participant.neutralMinionsKilled', 0] },
],
},
},
totalGameMinutes: {
$sum: {
$max: [
{
$divide: [
{
$ifNull: ['$participant.timePlayed', '$gameDuration'],
},
60,
],
},
1,
],
},
},
doubleKills: {
$sum: { $ifNull: ['$participant.doubleKills', 0] },
},
tripleKills: {
$sum: { $ifNull: ['$participant.tripleKills', 0] },
},
quadraKills: {
$sum: { $ifNull: ['$participant.quadraKills', 0] },
},
pentaKills: {
$sum: { $ifNull: ['$participant.pentaKills', 0] },
},
lastFetchedAt: { $min: '$fetchedAt' },
},
},
{ $sort: { games: -1, wins: -1, championId: 1 } },
])
.read('secondaryPreferred')
.exec();
}
private findParticipant(
match: RiotMatchDto,
puuid: string,
@@ -760,6 +847,24 @@ export class MatchHistoryService {
return oldest.toISOString();
}
private resolveAggregateLastFetchedAt(
rows: ChampionAggregateRow[],
context: HistoryContext,
): string | null {
if (rows.length === 0) {
return context.account.recentStatsFetchedAt?.toISOString() ?? null;
}
const oldest = rows
.map((row) => row.lastFetchedAt)
.filter((value): value is Date => value instanceof Date)
.reduce<Date | null>(
(acc, value) =>
!acc || value.getTime() < acc.getTime() ? value : acc,
null,
);
return oldest?.toISOString() ?? null;
}
private clampLimit(value: number | undefined, fallback: number, max: number): number {
if (!value || !Number.isFinite(value)) return fallback;
return Math.max(1, Math.min(Math.floor(value), max));
@@ -135,6 +135,8 @@ export interface RecentMatchTeamParticipantView {
export interface RecentMatchView {
matchId: string;
internalMatchId?: string;
gameNumber?: number;
queueId: number;
queueLabel: string;
gameCreation: number;
@@ -0,0 +1,63 @@
import 'reflect-metadata';
import { BadRequestException, ValidationPipe } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { validateSync } from 'class-validator';
import mongoose from 'mongoose';
import { CreateMatchDto, JoinMatchDto } from './create-match.dto';
describe('CreateMatchDto game mode cutover', () => {
it('rejects the removed live bracket mode', () => {
const dto = plainToInstance(CreateMatchDto, {
title: 'legacy bracket',
scheduledAt: '2026-07-13T10:00:00.000Z',
gameMode: 'bracket',
});
expect(validateSync(dto)).toEqual(
expect.arrayContaining([
expect.objectContaining({ property: 'gameMode' }),
]),
);
});
it.each(['pair', 'round-robin', 'double-elimination'] as const)(
'accepts the live %s mode',
(gameMode) => {
const dto = plainToInstance(CreateMatchDto, {
title: 'Competition',
scheduledAt: '2026-07-13T10:00:00.000Z',
gameMode,
});
expect(validateSync(dto)).toEqual([]);
},
);
});
describe('JoinMatchDto self-join boundary', () => {
it('rejects a caller-supplied userId', async () => {
const pipe = new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
});
try {
await pipe.transform(
{
preferredPositions: [{ position: 'MID', priority: 1 }],
userId: new mongoose.Types.ObjectId().toString(),
},
{ type: 'body', metatype: JoinMatchDto },
);
throw new Error('Expected validation to reject userId.');
} catch (error) {
expect(error).toBeInstanceOf(BadRequestException);
expect((error as BadRequestException).getResponse()).toEqual({
error: 'Bad Request',
message: ['property userId should not exist'],
statusCode: 400,
});
}
});
});
@@ -4,9 +4,11 @@ import {
ArrayMinSize,
registerDecorator,
IsArray,
IsBoolean,
IsDate,
IsEnum,
IsInt,
IsIn,
IsOptional,
IsString,
MaxLength,
@@ -16,9 +18,16 @@ import {
ValidationArguments,
ValidationOptions,
} from 'class-validator';
import { MATCH_GAME_MODES, POSITIONS } from '../../global/database/schema';
import { POSITIONS } from '../../global/database/schema';
import type { MatchGameMode, Position } from '../../global/database/schema';
const LIVE_MATCH_GAME_MODES = [
'pair',
'round-robin',
'double-elimination',
] as const;
type LiveMatchGameMode = Exclude<MatchGameMode, 'bracket'>;
function IsMultipleOf(
multiple: number,
validationOptions?: ValidationOptions,
@@ -98,14 +107,18 @@ export class CreateMatchDto {
gameCount?: number;
@IsOptional()
@IsEnum(MATCH_GAME_MODES)
gameMode?: MatchGameMode;
@IsIn(LIVE_MATCH_GAME_MODES)
gameMode?: LiveMatchGameMode;
@IsOptional()
@IsInt()
@Min(1)
roundRobinMaxRounds?: number;
@IsOptional()
@IsBoolean()
doubleEliminationResetFinalEnabled?: boolean;
@IsOptional()
@IsArray()
@IsString({ each: true })
@@ -158,14 +171,18 @@ export class UpdateMatchDto {
gameCount?: number;
@IsOptional()
@IsEnum(MATCH_GAME_MODES)
gameMode?: MatchGameMode;
@IsIn(LIVE_MATCH_GAME_MODES)
gameMode?: LiveMatchGameMode;
@IsOptional()
@IsInt()
@Min(1)
roundRobinMaxRounds?: number;
@IsOptional()
@IsBoolean()
doubleEliminationResetFinalEnabled?: boolean;
@IsOptional()
@IsArray()
@IsString({ each: true })
@@ -198,10 +215,6 @@ export class JoinMatchDto {
@ValidateNested({ each: true })
@Type(() => PositionPreferenceDto)
preferredPositions!: PositionPreferenceDto[];
@IsOptional()
@IsString()
userId?: string;
}
export class AddParticipantDto {
@@ -0,0 +1,118 @@
import { Types } from 'mongoose';
import { presentPublicMatch } from './match-public.presenter';
describe('presentPublicMatch', () => {
it('whitelists recruiting fields and excludes result/code internals', () => {
const response = presentPublicMatch({
_id: oid('1'),
communityId: oid('2'),
competitionId: oid('3'),
shortCode: '33NW',
title: '내전',
joined: false,
description: '설명',
mapId: 11,
status: 'in-progress',
scheduledAt: new Date('2026-07-12T10:00:00.000Z'),
maxParticipants: 20,
gameCount: 3,
gameMode: 'double-elimination',
roundRobinMaxRounds: undefined,
hostUserId: oid('4'),
participants: [
{
userId: oid('5'),
puuid: 'public-roster-snapshot',
gameName: '선수',
tagLine: 'KR1',
profileIconId: 1,
tier: {
queueType: 'RANKED_SOLO_5x5',
tier: 'GOLD',
rank: 'I',
leaguePoints: 42,
wins: 10,
losses: 5,
fetchedAt: new Date('2026-07-10T00:00:00.000Z'),
puuid: 'secret-tier-puuid',
},
preferredPositions: [
{ position: 'MID', priority: 1 },
{ position: 'SUP', priority: 2 },
],
joinedAt: new Date('2026-07-01T00:00:00.000Z'),
excluded: false,
},
],
teams: [
{
teamIndex: 8,
name: '똥칼라파워',
captainUserId: oid('5'),
members: [{ userId: oid('5'), assignedPosition: 'MID', cost: 42 }],
},
],
prizes: ['상품'],
notices: ['안내'],
schedule: [{ time: '20:00', label: '시작' }],
createdAt: new Date('2026-07-01T00:00:00.000Z'),
updatedAt: new Date('2026-07-12T00:00:00.000Z'),
tournamentCodeIds: [oid('6')],
tournamentCodes: [{ code: 'SECRET' }],
result: { winnerTeamIndex: 3, games: [], seriesResults: [] },
doubleElimination: { bracketMatches: [{ winnerTeamIndex: 3 }] },
resultPollState: { state: 'polling' },
legacyImportSource: { triggeringPuuid: 'secret' },
});
expect(response).toMatchObject({
_id: oid('1').toString(),
communityId: oid('2').toString(),
competitionId: oid('3').toString(),
title: '내전',
doubleEliminationResetFinalEnabled: false,
scheduledAt: '2026-07-12T10:00:00.000Z',
participants: [
expect.objectContaining({
userId: oid('5').toString(),
joinedAt: '2026-07-01T00:00:00.000Z',
tier: {
queueType: 'RANKED_SOLO_5x5',
tier: 'GOLD',
rank: 'I',
leaguePoints: 42,
wins: 10,
losses: 5,
fetchedAt: '2026-07-10T00:00:00.000Z',
},
}),
],
teams: [
{
teamIndex: 8,
name: '똥칼라파워',
captainUserId: oid('5').toString(),
members: [
{
userId: oid('5').toString(),
assignedPosition: 'MID',
cost: 42,
},
],
},
],
});
expect(response).not.toHaveProperty('tournamentCodeIds');
expect(response).not.toHaveProperty('tournamentCodes');
expect(response).not.toHaveProperty('result');
expect(response).not.toHaveProperty('doubleElimination');
expect(response).not.toHaveProperty('resultPollState');
expect(response).not.toHaveProperty('legacyImportSource');
expect(response.participants[0]).not.toHaveProperty('puuid');
expect(response.participants[0]?.tier).not.toHaveProperty('puuid');
});
});
function oid(suffix: string) {
return new Types.ObjectId(suffix.padStart(24, '0'));
}
@@ -0,0 +1,159 @@
import type { MatchDetailResponse, MatchTierView } from '@lolympus/contracts';
import type {
MatchGameMode,
MatchStatus,
Position,
} from '../global/database/schema';
type IdLike = string | { toString(): string };
interface PublicMatchSource {
_id: IdLike;
communityId: IdLike;
competitionId?: IdLike;
shortCode?: string;
title: string;
description: string;
mapId: number;
status: MatchStatus;
scheduledAt: Date | string;
maxParticipants: number;
gameCount: number;
gameMode: MatchGameMode;
roundRobinMaxRounds?: number;
doubleElimination?: { resetFinalEnabled?: boolean };
hostUserId?: IdLike;
participants: Array<{
userId: IdLike;
gameName?: string;
tagLine?: string;
profileIconId?: number;
tier?: unknown;
preferredPositions: Array<{ position: Position; priority: number }>;
joinedAt: Date | string;
excluded?: boolean;
[key: string]: unknown;
}>;
teams: Array<{
teamIndex: number;
name: string;
captainUserId?: IdLike;
members: Array<{
userId: IdLike;
assignedPosition: Position;
cost?: number;
[key: string]: unknown;
}>;
[key: string]: unknown;
}>;
prizes: string[];
notices: string[];
schedule: Array<{ time: string; label: string }>;
createdAt: Date | string;
updatedAt: Date | string;
[key: string]: unknown;
}
/** Public Match DTO. Competitive results and Tournament Codes live elsewhere. */
export function presentPublicMatch(
source: PublicMatchSource,
options: { joined?: boolean } = {},
): MatchDetailResponse {
return {
_id: source._id.toString() as never,
communityId: source.communityId.toString() as never,
...(source.competitionId
? { competitionId: source.competitionId.toString() as never }
: {}),
...(source.shortCode ? { shortCode: source.shortCode } : {}),
title: source.title,
description: source.description,
mapId: source.mapId,
status: source.status,
scheduledAt: asIso(source.scheduledAt),
maxParticipants: source.maxParticipants,
gameCount: source.gameCount,
gameMode: source.gameMode === 'bracket' ? 'pair' : source.gameMode,
...(source.roundRobinMaxRounds === undefined
? {}
: { roundRobinMaxRounds: source.roundRobinMaxRounds }),
...(source.gameMode === 'double-elimination'
? {
doubleEliminationResetFinalEnabled:
source.doubleElimination?.resetFinalEnabled ?? false,
}
: {}),
...(source.hostUserId
? { hostUserId: source.hostUserId.toString() as never }
: {}),
participants: source.participants.map((participant) => {
const tier = toPublicTier(participant.tier);
return {
userId: participant.userId.toString() as never,
...(participant.gameName ? { gameName: participant.gameName } : {}),
...(participant.tagLine ? { tagLine: participant.tagLine } : {}),
...(participant.profileIconId === undefined
? {}
: { profileIconId: participant.profileIconId }),
...(tier ? { tier } : {}),
preferredPositions: participant.preferredPositions.map(
(preference) => ({
position: preference.position,
priority: preference.priority,
}),
),
joinedAt: asIso(participant.joinedAt),
excluded: participant.excluded ?? false,
};
}),
teams: source.teams.map((team) => ({
teamIndex: team.teamIndex,
name: team.name,
...(team.captainUserId
? { captainUserId: team.captainUserId.toString() as never }
: {}),
members: team.members.map((member) => ({
userId: member.userId.toString() as never,
assignedPosition: member.assignedPosition,
...(member.cost === undefined ? {} : { cost: member.cost }),
})),
})),
prizes: [...source.prizes],
notices: [...source.notices],
schedule: source.schedule.map(({ time, label }) => ({ time, label })),
joined: options.joined ?? false,
createdAt: asIso(source.createdAt),
updatedAt: asIso(source.updatedAt),
};
}
function asIso(value: Date | string): string {
return value instanceof Date ? value.toISOString() : value;
}
function toPublicTier(value: unknown): MatchTierView | undefined {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
return undefined;
}
const tier = value as Record<string, unknown>;
if (
typeof tier.queueType !== 'string' ||
typeof tier.tier !== 'string' ||
typeof tier.rank !== 'string' ||
typeof tier.leaguePoints !== 'number' ||
typeof tier.wins !== 'number' ||
typeof tier.losses !== 'number' ||
!(typeof tier.fetchedAt === 'string' || tier.fetchedAt instanceof Date)
) {
return undefined;
}
return {
queueType: tier.queueType,
tier: tier.tier,
rank: tier.rank,
leaguePoints: tier.leaguePoints,
wins: tier.wins,
losses: tier.losses,
fetchedAt: asIso(tier.fetchedAt),
};
}
@@ -0,0 +1,42 @@
import { PATH_METADATA } from '@nestjs/common/constants';
import { MatchController } from './match.controller';
import { MatchService } from './match.service';
const LEGACY_RESULT_METHODS = [
'applyDoubleEliminationWalkover',
'cancelDoubleEliminationWalkover',
'cancelDoubleEliminationRiotResult',
] as const;
describe('Match result ownership cutover', () => {
it('does not expose legacy Match result mutation routes', () => {
const routes = Object.getOwnPropertyNames(MatchController.prototype)
.map((name) => {
const handler = Object.getOwnPropertyDescriptor(
MatchController.prototype,
name,
)?.value as unknown;
return typeof handler === 'function'
? (Reflect.getMetadata(PATH_METADATA, handler) as unknown)
: undefined;
})
.filter((path): path is string => typeof path === 'string');
expect(routes).not.toEqual(
expect.arrayContaining([
':matchId/double-elimination/bracket-matches/:bracketMatchId/walkover',
':matchId/double-elimination/bracket-matches/:bracketMatchId/walkover/cancel',
':matchId/double-elimination/bracket-matches/:bracketMatchId/result/cancel',
]),
);
});
it.each(LEGACY_RESULT_METHODS)(
'removes the legacy MatchService.%s result writer',
(methodName) => {
expect(Object.getOwnPropertyNames(MatchService.prototype)).not.toContain(
methodName,
);
},
);
});
@@ -0,0 +1,93 @@
import 'reflect-metadata';
import { GUARDS_METADATA } from '@nestjs/common/constants';
import mongoose from 'mongoose';
import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from '../auth/allow-public-access.decorator';
import { ROLES_KEY } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard';
import type { UserDocument } from '../global/database/schema';
import { MatchController } from './match.controller';
describe('MatchController participant access', () => {
function createController() {
const joinedMatch = { _id: new mongoose.Types.ObjectId() };
const response = { _id: joinedMatch._id.toString(), joined: true };
const matchService = {
join: jest.fn().mockResolvedValue(joinedMatch),
serialize: jest.fn().mockReturnValue(response),
};
return {
controller: new MatchController(matchService as never),
joinedMatch,
matchService,
response,
};
}
function createUser(communityId: mongoose.Types.ObjectId): UserDocument {
return {
_id: new mongoose.Types.ObjectId(),
communityId,
role: 'member',
} as UserDocument;
}
it('requires an authenticated community member for the self-join route', () => {
// Metadata must be read from the unbound prototype method itself.
// eslint-disable-next-line @typescript-eslint/unbound-method
const handler = MatchController.prototype.joinMatch;
const roles = Reflect.getMetadata(ROLES_KEY, handler) as
| string[]
| undefined;
const guards = Reflect.getMetadata(GUARDS_METADATA, handler) as
| unknown[]
| undefined;
expect(
Reflect.getMetadata(METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, handler),
).not.toBe(true);
expect(roles).toHaveLength(3);
expect(roles).toEqual(expect.arrayContaining(['owner', 'admin', 'member']));
expect(guards).toEqual(expect.arrayContaining([RolesGuard]));
});
it('joins only the authenticated user', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const currentUser = createUser(communityId);
const preferredPositions = [{ position: 'MID' as const, priority: 1 }];
const { controller, joinedMatch, matchService, response } =
createController();
await expect(
controller.joinMatch(currentUser, communityId, matchId, {
preferredPositions,
}),
).resolves.toBe(response);
expect(matchService.join).toHaveBeenCalledWith({
matchId,
communityId,
userId: currentUser._id,
preferredPositions,
});
expect(matchService.serialize).toHaveBeenCalledWith(joinedMatch, {
joined: true,
});
});
it('rejects a dev-auth user from a different URL community', async () => {
const currentUser = createUser(new mongoose.Types.ObjectId());
const requestedCommunityId = new mongoose.Types.ObjectId();
const { controller, matchService } = createController();
await expect(
controller.joinMatch(
currentUser,
requestedCommunityId,
new mongoose.Types.ObjectId(),
{ preferredPositions: [{ position: 'TOP', priority: 1 }] },
),
).rejects.toThrow('Different community.');
expect(matchService.join).not.toHaveBeenCalled();
});
});
+71 -49
View File
@@ -1,3 +1,7 @@
import type {
MatchDetailResponse,
MatchListResponse,
} from '@lolympus/contracts';
import {
BadRequestException,
Body,
@@ -18,11 +22,7 @@ import { CurrentUser } from '../auth/current-user.decorator';
import { Roles } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import type {
MatchDocument,
MatchStatus,
UserDocument,
} from '../global/database/schema';
import type { MatchStatus, UserDocument } from '../global/database/schema';
import {
AddParticipantDto,
CreateMatchDto,
@@ -44,9 +44,9 @@ export class MatchController {
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Body() body: CreateMatchDto,
) {
): Promise<MatchDetailResponse> {
this.assertSameCommunity(currentUser, communityId);
return this.matchService.create({
const match = await this.matchService.create({
communityId,
hostUserId: currentUser._id,
data: {
@@ -58,11 +58,14 @@ export class MatchController {
gameCount: body.gameCount,
gameMode: body.gameMode ?? 'pair',
roundRobinMaxRounds: body.roundRobinMaxRounds,
doubleEliminationResetFinalEnabled:
body.doubleEliminationResetFinalEnabled,
prizes: body.prizes ?? [],
notices: body.notices ?? [],
schedule: body.schedule ?? [],
},
});
return this.matchService.serialize(match, { joined: false });
}
// 공개 — 커뮤니티 내 매치 리스트. 로그인 시 본인 참여 여부를 함께 반환.
@@ -79,7 +82,7 @@ export class MatchController {
@Query('scheduledFrom') scheduledFrom?: string,
@Query('scheduledTo') scheduledTo?: string,
@Query('sort') sort?: 'asc' | 'desc',
) {
): Promise<MatchListResponse> {
const result = await this.matchService.listPage({
communityId,
status,
@@ -90,21 +93,39 @@ export class MatchController {
scheduledTo: this.toOptionalDate(scheduledTo),
sort,
});
if (!currentUser) return result;
const myId = currentUser._id;
return {
...result,
matches: result.matches.map((m) => this.annotateJoined(m, myId)),
matches: result.matches.map((match) =>
this.matchService.serialize(match, {
...(currentUser
? {
joined: match.participants.some((participant) =>
participant.userId.equals(currentUser._id),
),
}
: {}),
}),
),
};
}
@Get(':matchId')
@AllowPublicAccess()
public async getMatch(
@CurrentUser() currentUser: UserDocument | undefined,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) {
const match = await this.matchService.getById(matchId);
return this.matchService.serialize(match);
): Promise<MatchDetailResponse> {
const match = await this.matchService.getById(matchId, communityId);
return this.matchService.serialize(match, {
joined: Boolean(
currentUser &&
match.participants.some((participant) =>
participant.userId.equals(currentUser._id),
),
),
});
}
@Patch(':matchId')
@@ -116,9 +137,18 @@ export class MatchController {
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: UpdateMatchDto,
) {
): Promise<MatchDetailResponse> {
this.assertSameCommunity(currentUser, communityId);
return this.matchService.update({ matchId, communityId, patch: body });
const match = await this.matchService.update({
matchId,
communityId,
patch: body,
});
return this.matchService.serialize(match, {
joined: match.participants.some((participant) =>
participant.userId.equals(currentUser._id),
),
});
}
@Delete(':matchId')
@@ -135,20 +165,25 @@ export class MatchController {
await this.matchService.remove({ matchId, communityId });
}
// 공개 — 참여 (로그인된 유저는 자기 자신, 비로그인은 body.userId 사용).
// 커뮤니티 멤버 본인 참여. 다른 유저 추가는 관리자 전용 경로를 사용한다.
@Post(':matchId/participants')
@AllowPublicAccess()
@Roles('owner', 'admin', 'member')
@UseGuards(RolesGuard)
public async joinMatch(
@CurrentUser() currentUser: UserDocument | undefined,
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: JoinMatchDto,
) {
const userId = this.resolveJoinerUserId(currentUser, body.userId);
return this.matchService.join({
): Promise<MatchDetailResponse> {
this.assertSameCommunity(currentUser, communityId);
const match = await this.matchService.join({
matchId,
userId,
communityId,
userId: currentUser._id,
preferredPositions: body.preferredPositions,
});
return this.matchService.serialize(match, { joined: true });
}
// 관리자 전용 — 커뮤니티 유저를 모집중 매치에 직접 추가한다.
@@ -162,15 +197,20 @@ export class MatchController {
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
@Body() body: AddParticipantDto | undefined,
) {
): Promise<MatchDetailResponse> {
this.assertSameCommunity(currentUser, communityId);
const match = await this.matchService.join({
matchId,
communityId,
userId,
preferredPositions: body?.preferredPositions,
riotPuuid: body?.riotPuuid,
});
return this.matchService.serialize(match);
return this.matchService.serialize(match, {
joined: match.participants.some((participant) =>
participant.userId.equals(currentUser._id),
),
});
}
// 관리자 전용 — 참가자 주/부 포지션 변경.
@@ -184,7 +224,7 @@ export class MatchController {
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
@Body() body: UpdateParticipantDto,
) {
): Promise<MatchDetailResponse> {
this.assertSameCommunity(currentUser, communityId);
const match = await this.matchService.updateParticipantPositions({
matchId,
@@ -193,7 +233,11 @@ export class MatchController {
mainPosition: body.mainPosition,
subPosition: body.subPosition,
});
return this.matchService.serialize(match);
return this.matchService.serialize(match, {
joined: match.participants.some((participant) =>
participant.userId.equals(currentUser._id),
),
});
}
// 관리자 전용 — 참가자 강제 제외.
@@ -216,28 +260,6 @@ export class MatchController {
});
}
private resolveJoinerUserId(
currentUser: UserDocument | undefined,
bodyUserId?: string,
): mongoose.Types.ObjectId {
if (currentUser) return currentUser._id;
if (!bodyUserId || !mongoose.isValidObjectId(bodyUserId)) {
throw new BadRequestException(
'userId is required when not authenticated.',
);
}
return new mongoose.Types.ObjectId(bodyUserId);
}
private annotateJoined(
match: MatchDocument,
userId: mongoose.Types.ObjectId,
) {
const obj = match.toObject();
const joined = match.participants.some((p) => p.userId.equals(userId));
return { ...obj, joined };
}
private assertSameCommunity(
user: UserDocument,
communityId: mongoose.Types.ObjectId,
+424 -37
View File
@@ -2,9 +2,63 @@ import mongoose from 'mongoose';
import { MatchService } from './match.service';
describe('MatchService', () => {
function createService(match: Record<string, unknown>) {
function createServiceWithCreateModels() {
const createdPayloads: Record<string, unknown>[] = [];
const MatchModel = {
create: jest.fn().mockImplementation(async (payload) => {
createdPayloads.push(payload);
return payload;
}),
exists: jest.fn().mockResolvedValue(null),
};
const CommunityModel = {
findById: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ matchGameCount: 3 }),
}),
}),
}),
};
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') return MatchModel;
if (name === 'community') return CommunityModel;
return {};
}),
};
const tournamentCodeService = {
buildSlots: jest.fn().mockResolvedValue([]),
releaseFromMatch: jest.fn().mockResolvedValue(undefined),
};
const communityStatsService = {
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
};
const matchStatsService = {
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
removeByMatch: jest.fn().mockResolvedValue(undefined),
};
return {
service: new MatchService(
connectionService as never,
tournamentCodeService as never,
communityStatsService as never,
matchStatsService as never,
),
MatchModel,
createdPayloads,
};
}
function createService(
match: Record<string, unknown>,
updatedMatch: Record<string, unknown> | null = match,
) {
const MatchModel = {
findById: jest.fn().mockResolvedValue(match),
findOne: jest.fn().mockResolvedValue(match),
findOneAndUpdate: jest.fn().mockResolvedValue(updatedMatch),
};
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
@@ -31,6 +85,7 @@ describe('MatchService', () => {
communityStatsService as never,
matchStatsService as never,
),
MatchModel,
tournamentCodeService,
matchStatsService,
};
@@ -83,12 +138,16 @@ describe('MatchService', () => {
function createServiceWithJoinModels(params: {
user: Record<string, unknown> | null;
match: Record<string, unknown> | null;
updatedMatch?: Record<string, unknown> | null;
}) {
const UserModel = {
findById: jest.fn().mockResolvedValue(params.user),
};
const MatchModel = {
findById: jest.fn().mockResolvedValue(params.match),
findOneAndUpdate: jest
.fn()
.mockResolvedValue(params.updatedMatch ?? params.match),
};
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
@@ -145,6 +204,19 @@ describe('MatchService', () => {
});
});
it('scopes Match detail lookup to the URL community', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const match = { _id: matchId, communityId };
const { service, MatchModel } = createService(match);
await expect(service.getById(matchId, communityId)).resolves.toBe(match);
expect(MatchModel.findOne).toHaveBeenCalledWith({
_id: matchId,
communityId,
});
});
it('applies offset before page-based pagination', async () => {
const communityId = new mongoose.Types.ObjectId();
const { service, skip } = createServiceWithListModel();
@@ -233,28 +305,271 @@ describe('MatchService', () => {
participants: [],
save: jest.fn().mockResolvedValue(undefined),
};
const { service } = createServiceWithJoinModels({ user, match });
const updatedMatch = {
...match,
participants: [
{
userId,
puuid: 'puuid-1',
gameName: 'Dahyeon',
tagLine: 'KR1',
profileIconId: 7,
preferredPositions: [{ position: 'MID', priority: 1 }],
excluded: false,
},
],
};
const { service, MatchModel } = createServiceWithJoinModels({
user,
match,
updatedMatch,
});
await service.join({
const joined = await service.join({
matchId,
userId,
});
expect(match.participants).toEqual([
expect(joined).toBe(updatedMatch);
expect(MatchModel.findOneAndUpdate).toHaveBeenCalledWith(
expect.objectContaining({
userId,
puuid: 'puuid-1',
gameName: 'Dahyeon',
tagLine: 'KR1',
profileIconId: 7,
preferredPositions: [{ position: 'MID', priority: 1 }],
excluded: false,
_id: matchId,
communityId,
status: 'recruiting',
'participants.userId': { $ne: userId },
$expr: expect.any(Object),
}),
]);
expect(match.save).toHaveBeenCalledTimes(1);
{
$push: {
participants: expect.objectContaining({
userId,
puuid: 'puuid-1',
gameName: 'Dahyeon',
tagLine: 'KR1',
profileIconId: 7,
preferredPositions: [{ position: 'MID', priority: 1 }],
excluded: false,
}),
},
},
expect.objectContaining({ returnDocument: 'after', runValidators: true }),
);
expect(match.participants).toEqual([]);
expect(match.save).not.toHaveBeenCalled();
});
it('clears game schedule when a built match returns to recruiting', async () => {
it('does not join a user from a different community', async () => {
const requestedCommunityId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
const user = {
_id: userId,
communityId: new mongoose.Types.ObjectId(),
preferredPositions: [],
riotAccounts: [],
};
const match = {
_id: new mongoose.Types.ObjectId(),
communityId: requestedCommunityId,
status: 'recruiting',
participants: [],
};
const { service, MatchModel } = createServiceWithJoinModels({
user,
match,
});
await expect(
service.join({
matchId: match._id,
communityId: requestedCommunityId,
userId,
}),
).rejects.toThrow('Match not found.');
expect(MatchModel.findOneAndUpdate).not.toHaveBeenCalled();
});
it('cancels a join with an atomic participant pull', async () => {
const communityId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const user = {
_id: userId,
communityId,
riotAccounts: [],
preferredPositions: [],
};
const match = {
_id: matchId,
communityId,
status: 'recruiting',
participants: [{ userId }],
save: jest.fn(),
};
const updatedMatch = { ...match, participants: [] };
const { service, MatchModel } = createServiceWithJoinModels({
user,
match,
updatedMatch,
});
await expect(service.cancelJoin({ matchId, userId })).resolves.toBe(
updatedMatch,
);
expect(MatchModel.findOneAndUpdate).toHaveBeenCalledWith(
{
_id: matchId,
communityId,
status: 'recruiting',
'participants.userId': userId,
},
{ $pull: { participants: { userId } } },
expect.objectContaining({ returnDocument: 'after', runValidators: true }),
);
expect(match.save).not.toHaveBeenCalled();
});
it('removes a participant with an atomic participant pull', async () => {
const communityId = new mongoose.Types.ObjectId();
const targetUserId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const match = {
_id: matchId,
communityId,
status: 'recruiting',
participants: [{ userId: targetUserId }],
save: jest.fn(),
};
const updatedMatch = { ...match, participants: [] };
const { service, MatchModel } = createService(match, updatedMatch);
await expect(
service.removeParticipant({ matchId, communityId, targetUserId }),
).resolves.toBe(updatedMatch);
expect(MatchModel.findOneAndUpdate).toHaveBeenCalledWith(
{
_id: matchId,
communityId,
status: 'recruiting',
'participants.userId': targetUserId,
},
{ $pull: { participants: { userId: targetUserId } } },
expect.objectContaining({ returnDocument: 'after', runValidators: true }),
);
expect(match.save).not.toHaveBeenCalled();
});
it('updates participant positions with an array-filtered atomic update', async () => {
const communityId = new mongoose.Types.ObjectId();
const targetUserId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const match = {
_id: matchId,
communityId,
status: 'recruiting',
participants: [
{
userId: targetUserId,
preferredPositions: [
{ position: 'TOP', priority: 1 },
{ position: 'JUNGLE', priority: 2 },
{ position: 'MID', priority: 3 },
],
},
],
save: jest.fn(),
};
const updatedMatch = { ...match };
const { service, MatchModel } = createService(match, updatedMatch);
await expect(
service.updateParticipantPositions({
matchId,
communityId,
targetUserId,
mainPosition: 'MID',
subPosition: 'SUPPORT',
}),
).resolves.toBe(updatedMatch);
expect(MatchModel.findOneAndUpdate).toHaveBeenCalledWith(
{
_id: matchId,
communityId,
status: 'recruiting',
'participants.userId': targetUserId,
},
{
$set: {
'participants.$[participant].preferredPositions': [
{ position: 'MID', priority: 1 },
{ position: 'SUPPORT', priority: 2 },
{ position: 'TOP', priority: 3 },
{ position: 'JUNGLE', priority: 4 },
],
},
},
expect.objectContaining({
arrayFilters: [{ 'participant.userId': targetUserId }],
returnDocument: 'after',
runValidators: true,
}),
);
expect(match.save).not.toHaveBeenCalled();
});
it('normalizes double-elimination match creation', async () => {
const { service, createdPayloads } = createServiceWithCreateModels();
const communityId = new mongoose.Types.ObjectId();
await service.create({
communityId,
data: {
title: 'Double elimination',
scheduledAt: new Date('2026-06-01T10:00:00.000Z'),
maxParticipants: 20,
gameCount: 5,
gameMode: 'double-elimination',
doubleEliminationResetFinalEnabled: true,
},
});
expect(createdPayloads[0]).toMatchObject({
communityId,
maxParticipants: 20,
gameCount: 5,
gameMode: 'double-elimination',
roundRobinMaxRounds: undefined,
doubleElimination: {
teamCount: 4,
resetFinalEnabled: true,
resetFinalCreated: false,
seeds: [],
bracketMatches: [],
placements: {},
events: [],
},
});
});
it('rejects unsupported double-elimination participant counts', async () => {
const { service, MatchModel } = createServiceWithCreateModels();
await expect(
service.create({
communityId: new mongoose.Types.ObjectId(),
data: {
title: 'Invalid double elimination',
scheduledAt: new Date('2026-06-01T10:00:00.000Z'),
maxParticipants: 30,
gameMode: 'double-elimination',
},
}),
).rejects.toThrow(
'Double elimination supports only 20 or 40 participants.',
);
expect(MatchModel.create).not.toHaveBeenCalled();
});
it('rejects returning a finalized team build to recruiting', async () => {
const communityId = new mongoose.Types.ObjectId();
const match = {
communityId,
@@ -276,20 +591,23 @@ describe('MatchService', () => {
const { service, tournamentCodeService, matchStatsService } =
createService(match);
await service.update({
matchId: new mongoose.Types.ObjectId(),
communityId,
patch: { status: 'recruiting' },
});
await expect(
service.update({
matchId: new mongoose.Types.ObjectId(),
communityId,
patch: { status: 'recruiting' },
}),
).rejects.toThrow('cannot return to recruiting');
expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled();
expect(match.tournamentCodeIds).toEqual([]);
expect(match.gameSchedule).toEqual([]);
expect(match.teamBuiltAt).toBeUndefined();
expect(match.result).toBeUndefined();
expect(match.resultPollState).toBeUndefined();
expect(match.save).toHaveBeenCalledTimes(1);
expect(matchStatsService.removeByMatch).toHaveBeenCalledWith(match._id);
expect(match.gameSchedule).toEqual([
{ gameNumber: 1, teamAIndex: 2, teamBIndex: 4 },
]);
expect(match.teamBuiltAt).toBeInstanceOf(Date);
expect(match.result).toEqual({ games: [] });
expect(match.resultPollState).toEqual({ state: 'polling' });
expect(match.save).not.toHaveBeenCalled();
expect(matchStatsService.removeByMatch).not.toHaveBeenCalled();
});
it('rejects round-robin max round changes after recruiting', async () => {
@@ -310,12 +628,77 @@ describe('MatchService', () => {
patch: { roundRobinMaxRounds: 3 },
}),
).rejects.toThrow(
'maxParticipants, gameMode, and roundRobinMaxRounds can only be changed while recruiting.',
'maxParticipants, gameCount, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.',
);
expect(match.set).not.toHaveBeenCalled();
});
it('releases reserved codes when returning a built match to recruiting', async () => {
it('rejects game count changes after recruiting', async () => {
const communityId = new mongoose.Types.ObjectId();
const match = {
communityId,
status: 'team-built',
tournamentCodeIds: [],
set: jest.fn(),
save: jest.fn(),
};
const { service } = createService(match);
await expect(
service.update({
matchId: new mongoose.Types.ObjectId(),
communityId,
patch: { gameCount: 5 },
}),
).rejects.toThrow('gameCount');
expect(match.set).not.toHaveBeenCalled();
});
it('rejects returning to recruiting after Competition bootstrap', async () => {
const communityId = new mongoose.Types.ObjectId();
const match = {
communityId,
competitionId: new mongoose.Types.ObjectId(),
status: 'team-built',
tournamentCodeIds: [],
set: jest.fn(),
save: jest.fn(),
};
const { service, tournamentCodeService } = createService(match);
await expect(
service.update({
matchId: new mongoose.Types.ObjectId(),
communityId,
patch: { status: 'recruiting' },
}),
).rejects.toThrow('cannot return to recruiting');
expect(match.set).not.toHaveBeenCalled();
expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled();
});
it('rejects hard deletion after Competition bootstrap', async () => {
const communityId = new mongoose.Types.ObjectId();
const match = {
_id: new mongoose.Types.ObjectId(),
communityId,
competitionId: new mongoose.Types.ObjectId(),
status: 'recruiting',
tournamentCodeIds: [],
deleteOne: jest.fn(),
};
const { service, tournamentCodeService, matchStatsService } =
createService(match);
await expect(
service.remove({ matchId: match._id, communityId }),
).rejects.toThrow('cannot be hard-deleted');
expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled();
expect(matchStatsService.removeByMatch).not.toHaveBeenCalled();
expect(match.deleteOne).not.toHaveBeenCalled();
});
it('preserves reserved codes when a recruiting rollback is rejected', async () => {
const communityId = new mongoose.Types.ObjectId();
const codeId = new mongoose.Types.ObjectId();
const match = {
@@ -333,14 +716,18 @@ describe('MatchService', () => {
};
const { service, tournamentCodeService } = createService(match);
await service.update({
matchId: new mongoose.Types.ObjectId(),
communityId,
patch: { status: 'recruiting' },
});
expect(tournamentCodeService.releaseFromMatch).toHaveBeenCalledWith(match);
expect(match.tournamentCodeIds).toEqual([]);
expect(match.gameSchedule).toEqual([]);
await expect(
service.update({
matchId: new mongoose.Types.ObjectId(),
communityId,
patch: { status: 'recruiting' },
}),
).rejects.toThrow('cannot return to recruiting');
expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled();
expect(match.tournamentCodeIds).toEqual([codeId]);
expect(match.gameSchedule).toEqual([
{ gameNumber: 1, teamAIndex: 1, teamBIndex: 3 },
]);
expect(match.save).not.toHaveBeenCalled();
});
});
+281 -130
View File
@@ -1,5 +1,6 @@
import {
BadRequestException,
ConflictException,
Injectable,
InternalServerErrorException,
NotFoundException,
@@ -11,7 +12,6 @@ import { ConnectionService } from '../global/database/connection.service';
import {
Match,
MatchDocument,
MatchSeriesResult,
MatchStatus,
POSITIONS,
Position,
@@ -20,23 +20,32 @@ import {
} from '../global/database/schema';
import { DEFAULT_TOURNAMENT_GAME_COUNT } from '../tournament-code/tournament-code.constants';
import { TournamentCodeService } from '../tournament-code/tournament-code.service';
import { presentPublicMatch } from './match-public.presenter';
const MATCH_SHORT_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
const MATCH_SHORT_CODE_LENGTH = 4;
const MATCH_SHORT_CODE_GENERATION_ATTEMPTS = 20;
const DEFAULT_MATCH_LIST_LIMIT = 50;
const MAX_MATCH_LIST_LIMIT = 200;
const DOUBLE_ELIMINATION_PARTICIPANT_COUNTS = [20, 40] as const;
const DEFAULT_DOUBLE_ELIMINATION_SERIES_GAME_COUNT = 3;
interface DoubleEliminationConfigInput {
doubleEliminationResetFinalEnabled?: boolean;
}
interface CreateMatchParams {
communityId: mongoose.Types.ObjectId;
hostUserId?: mongoose.Types.ObjectId;
data: Partial<Match> & Pick<Match, 'title' | 'scheduledAt'>;
data: Partial<Match> &
Pick<Match, 'title' | 'scheduledAt'> &
DoubleEliminationConfigInput;
}
interface UpdateMatchParams {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
patch: Partial<Match>;
patch: Partial<Match> & DoubleEliminationConfigInput;
}
interface ListMatchesQuery {
@@ -64,6 +73,7 @@ interface MatchListFilter {
interface JoinMatchParams {
matchId: mongoose.Types.ObjectId;
communityId?: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
preferredPositions?: PositionPreference[];
// 특정 RiotAccount(puuid)로 참가하고 싶을 때 지정. 없으면 primary 사용.
@@ -105,15 +115,18 @@ export class MatchService {
.select({ matchGameCount: 1 })
.lean()
.exec();
return MatchModel.create({
const normalizedData = this.normalizeMatchConfig({
...params.data,
shortCode:
params.data.shortCode ??
(await this.generateUniqueShortCode(MatchModel, params.communityId)),
gameCount:
params.data.gameCount ??
community?.matchGameCount ??
DEFAULT_TOURNAMENT_GAME_COUNT,
});
return MatchModel.create({
...normalizedData,
shortCode:
normalizedData.shortCode ??
(await this.generateUniqueShortCode(MatchModel, params.communityId)),
communityId: params.communityId,
hostUserId: params.hostUserId,
});
@@ -171,37 +184,24 @@ export class MatchService {
public async getById(
matchId: mongoose.Types.ObjectId,
communityId: mongoose.Types.ObjectId,
): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findById(matchId);
const match = await MatchModel.findOne({ _id: matchId, communityId });
if (!match) throw new NotFoundException('Match not found.');
return match;
}
public async serialize(match: MatchDocument) {
public serialize(match: MatchDocument, options: { joined?: boolean } = {}) {
const obj = match.toObject();
if (obj.result?.games) {
obj.result.games = [...obj.result.games].sort(
(left, right) => left.gameNumber - right.gameNumber,
);
if (!obj.result.seriesResults?.length) {
obj.result.seriesResults = this.buildSeriesResults(obj.result.games);
}
}
return {
...obj,
gameCount: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT,
gameMode: match.gameMode ?? 'pair',
participants: (obj.participants ?? []).map((participant) => ({
...participant,
excluded: participant.excluded ?? false,
})),
teams: (obj.teams ?? []).map((team) => ({
...team,
})),
gameSchedule: obj.gameSchedule ?? [],
tournamentCodes: await this.tournamentCodeService.buildSlots(match),
};
return presentPublicMatch(
{
...obj,
gameCount: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT,
gameMode: match.gameMode ?? 'pair',
} as never,
options,
);
}
public async update(params: UpdateMatchParams): Promise<MatchDocument> {
@@ -214,30 +214,43 @@ export class MatchService {
const previousStatus = match.status;
if (
previousStatus !== 'recruiting' &&
('maxParticipants' in params.patch ||
'gameMode' in params.patch ||
'roundRobinMaxRounds' in params.patch)
params.patch.status === 'recruiting'
) {
throw new BadRequestException(
'maxParticipants, gameMode, and roundRobinMaxRounds can only be changed while recruiting.',
throw new ConflictException(
'A finalized team build cannot return to recruiting. Preserve its immutable lifecycle and create a new Match instead.',
);
}
match.set(params.patch);
if (previousStatus !== 'recruiting' && match.status === 'recruiting') {
if (match.tournamentCodeIds.length > 0) {
await this.tournamentCodeService.releaseFromMatch(match);
}
match.tournamentCodeIds = [];
match.gameSchedule = [];
match.teamBuiltAt = undefined;
match.result = undefined;
match.resultPollState = undefined;
if (
previousStatus !== 'recruiting' &&
('maxParticipants' in params.patch ||
'gameCount' in params.patch ||
'gameMode' in params.patch ||
'roundRobinMaxRounds' in params.patch ||
'doubleEliminationResetFinalEnabled' in params.patch)
) {
throw new BadRequestException(
'maxParticipants, gameCount, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.',
);
}
const patchToSet =
previousStatus === 'recruiting'
? this.normalizeMatchConfig({
...params.patch,
gameMode: params.patch.gameMode ?? match.gameMode,
maxParticipants:
params.patch.maxParticipants ?? match.maxParticipants,
gameCount: params.patch.gameCount ?? match.gameCount,
roundRobinMaxRounds:
params.patch.roundRobinMaxRounds ?? match.roundRobinMaxRounds,
doubleEliminationResetFinalEnabled:
params.patch.doubleEliminationResetFinalEnabled ??
params.patch.doubleElimination?.resetFinalEnabled ??
match.doubleElimination?.resetFinalEnabled,
})
: this.stripMatchConfigInput(params.patch);
match.set(patchToSet);
await match.save();
if (previousStatus !== 'recruiting' && match.status === 'recruiting') {
await this.matchStatsService.removeByMatch(match._id);
await this.communityStatsService.invalidateCommunity(params.communityId);
} else if (match.result?.games?.length) {
if (match.result?.games?.length) {
await this.matchStatsService.buildAndUpsert(match._id);
await this.communityStatsService.invalidateCommunity(params.communityId);
}
@@ -254,6 +267,16 @@ export class MatchService {
if (!match.communityId.equals(params.communityId)) {
throw new BadRequestException('Match does not belong to this community.');
}
if (match.status !== 'recruiting') {
throw new ConflictException(
'Only a recruiting Match can be hard-deleted. Finalized Match history must be preserved.',
);
}
if (match.competitionId) {
throw new ConflictException(
'A Match with a Competition cannot be hard-deleted. Preserve the immutable ledger and archive the Match instead.',
);
}
await this.tournamentCodeService.releaseFromMatch(match);
await this.matchStatsService.removeByMatch(match._id);
await match.deleteOne();
@@ -266,30 +289,15 @@ export class MatchService {
const user = await UserModel.findById(params.userId);
if (!user) throw new NotFoundException('User not found.');
const match = await MatchModel.findById(params.matchId);
if (!match) throw new NotFoundException('Match not found.');
if (!match.communityId.equals(user.communityId)) {
throw new BadRequestException(
'User and match belong to different communities.',
);
}
if (match.status !== 'recruiting') {
throw new BadRequestException('Match is not recruiting.');
}
if (match.participants.length >= match.maxParticipants) {
throw new BadRequestException('Match is full.');
}
const alreadyIn = match.participants.some((p) => p.userId.equals(user._id));
if (alreadyIn) {
throw new BadRequestException('User already joined this match.');
if (params.communityId && !user.communityId.equals(params.communityId)) {
throw new NotFoundException('Match not found.');
}
const selectedRiot = params.riotPuuid
? user.riotAccounts.find((a) => a.puuid === params.riotPuuid)
: user.riotAccounts.find((a) => a.isPrimary);
const selectedTier = this.selectParticipantTier(selectedRiot?.tiers ?? []);
match.participants.push({
const participant = {
userId: user._id,
puuid: selectedRiot?.puuid,
gameName: selectedRiot?.gameName,
@@ -302,9 +310,85 @@ export class MatchService {
),
joinedAt: new Date(),
excluded: false,
});
await match.save();
return match;
};
const updatedMatch = await MatchModel.findOneAndUpdate(
{
_id: params.matchId,
communityId: params.communityId ?? user.communityId,
status: 'recruiting',
'participants.userId': { $ne: user._id },
$expr: { $lt: [{ $size: '$participants' }, '$maxParticipants'] },
},
{ $push: { participants: participant } },
{ returnDocument: 'after', runValidators: true },
);
if (updatedMatch) return updatedMatch;
return await this.throwJoinFailure(MatchModel, params.matchId, user);
}
private normalizeMatchConfig<
T extends Partial<Match> & DoubleEliminationConfigInput,
>(input: T): Partial<Match> {
const patch = this.stripMatchConfigInput(input);
const gameMode = patch.gameMode ?? 'pair';
const maxParticipants = patch.maxParticipants ?? 10;
if (gameMode === 'double-elimination') {
if (
!DOUBLE_ELIMINATION_PARTICIPANT_COUNTS.includes(
maxParticipants as (typeof DOUBLE_ELIMINATION_PARTICIPANT_COUNTS)[number],
)
) {
throw new BadRequestException(
'Double elimination supports only 20 or 40 participants.',
);
}
return {
...patch,
gameMode,
maxParticipants,
gameCount: this.normalizeDoubleEliminationSeriesGameCount(
patch.gameCount ?? DEFAULT_DOUBLE_ELIMINATION_SERIES_GAME_COUNT,
),
roundRobinMaxRounds: undefined,
gameSchedule: [],
doubleElimination: {
teamCount: (maxParticipants / 5) as 4 | 8,
resetFinalEnabled:
input.doubleEliminationResetFinalEnabled ??
input.doubleElimination?.resetFinalEnabled ??
false,
resetFinalCreated: false,
seeds: [],
bracketMatches: [],
placements: {},
events: [],
},
};
}
return {
...patch,
gameMode,
doubleElimination: undefined,
};
}
private stripMatchConfigInput<
T extends Partial<Match> & DoubleEliminationConfigInput,
>(input: T): Partial<Match> {
const patch = { ...input };
delete patch.doubleEliminationResetFinalEnabled;
return patch;
}
private normalizeDoubleEliminationSeriesGameCount(gameCount: number): number {
if (!Number.isInteger(gameCount) || gameCount < 1) {
return DEFAULT_DOUBLE_ELIMINATION_SERIES_GAME_COUNT;
}
return gameCount % 2 === 0 ? gameCount + 1 : gameCount;
}
public async cancelJoin(
@@ -316,52 +400,57 @@ export class MatchService {
const user = await UserModel.findById(params.userId);
if (!user) throw new NotFoundException('User not found.');
const match = await MatchModel.findById(params.matchId);
if (!match) throw new NotFoundException('Match not found.');
if (!match.communityId.equals(user.communityId)) {
throw new BadRequestException(
'User and match belong to different communities.',
);
}
if (match.status !== 'recruiting') {
throw new BadRequestException('Match is not recruiting.');
}
const participantIndex = match.participants.findIndex((participant) =>
participant.userId.equals(user._id),
const updatedMatch = await MatchModel.findOneAndUpdate(
{
_id: params.matchId,
communityId: user.communityId,
status: 'recruiting',
'participants.userId': user._id,
},
{ $pull: { participants: { userId: user._id } } },
{ returnDocument: 'after', runValidators: true },
);
if (participantIndex === -1) {
throw new BadRequestException('User has not joined this match.');
}
if (updatedMatch) return updatedMatch;
match.participants.splice(participantIndex, 1);
await match.save();
return match;
return await this.throwCancelJoinFailure(MatchModel, params.matchId, user);
}
// 관리자 전용 — 특정 참가자를 강제로 제외한다.
public async removeParticipant(
params: RemoveParticipantParams,
): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match');
const updatedMatch = await MatchModel.findOneAndUpdate(
{
_id: params.matchId,
communityId: params.communityId,
status: 'recruiting',
'participants.userId': params.targetUserId,
},
{ $pull: { participants: { userId: params.targetUserId } } },
{ returnDocument: 'after', runValidators: true },
);
if (updatedMatch) return updatedMatch;
const match = await this.loadRecruitingMatch(
params.matchId,
params.communityId,
);
const participantIndex = match.participants.findIndex((participant) =>
participant.userId.equals(params.targetUserId),
);
if (participantIndex === -1) {
if (
!match.participants.some((participant) =>
this.sameObjectId(participant.userId, params.targetUserId),
)
) {
throw new NotFoundException('Participant not found.');
}
match.participants.splice(participantIndex, 1);
await match.save();
return match;
throw new BadRequestException('Participant could not be removed.');
}
// 관리자 전용 — 참가자의 주/부 포지션(선호 우선순위 1·2)을 교체한다.
public async updateParticipantPositions(
params: UpdateParticipantPositionsParams,
): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match');
const match = await this.loadRecruitingMatch(
params.matchId,
params.communityId,
@@ -372,14 +461,36 @@ export class MatchService {
if (!participant) {
throw new NotFoundException('Participant not found.');
}
participant.preferredPositions = this.reorderPreferredPositions(
const preferredPositions = this.reorderPreferredPositions(
params.mainPosition,
params.subPosition,
participant.preferredPositions,
);
match.markModified('participants');
await match.save();
return match;
const updatedMatch = await MatchModel.findOneAndUpdate(
{
_id: params.matchId,
communityId: params.communityId,
status: 'recruiting',
'participants.userId': params.targetUserId,
},
{
$set: {
'participants.$[participant].preferredPositions': preferredPositions,
},
},
{
arrayFilters: [{ 'participant.userId': params.targetUserId }],
returnDocument: 'after',
runValidators: true,
},
);
if (!updatedMatch) {
throw new BadRequestException(
'Participant positions could not be updated.',
);
}
return updatedMatch;
}
private async loadRecruitingMatch(
@@ -398,6 +509,75 @@ export class MatchService {
return match;
}
private async throwJoinFailure(
MatchModel: mongoose.Model<Match>,
matchId: mongoose.Types.ObjectId,
user: {
_id: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
},
): Promise<never> {
const match = await MatchModel.findById(matchId);
if (!match) throw new NotFoundException('Match not found.');
if (!this.sameObjectId(match.communityId, user.communityId)) {
throw new BadRequestException(
'User and match belong to different communities.',
);
}
if (match.status !== 'recruiting') {
throw new BadRequestException('Match is not recruiting.');
}
if (
match.participants.some((participant) =>
this.sameObjectId(participant.userId, user._id),
)
) {
throw new BadRequestException('User already joined this match.');
}
if (match.participants.length >= match.maxParticipants) {
throw new BadRequestException('Match is full.');
}
throw new BadRequestException('Unable to join this match.');
}
private async throwCancelJoinFailure(
MatchModel: mongoose.Model<Match>,
matchId: mongoose.Types.ObjectId,
user: {
_id: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
},
): Promise<never> {
const match = await MatchModel.findById(matchId);
if (!match) throw new NotFoundException('Match not found.');
if (!this.sameObjectId(match.communityId, user.communityId)) {
throw new BadRequestException(
'User and match belong to different communities.',
);
}
if (match.status !== 'recruiting') {
throw new BadRequestException('Match is not recruiting.');
}
if (
!match.participants.some((participant) =>
this.sameObjectId(participant.userId, user._id),
)
) {
throw new BadRequestException('User has not joined this match.');
}
throw new BadRequestException('Unable to cancel match join.');
}
private sameObjectId(
left: mongoose.Types.ObjectId | { toString(): string },
right: mongoose.Types.ObjectId | { toString(): string },
): boolean {
if (left instanceof mongoose.Types.ObjectId) {
return left.equals(right.toString());
}
return left.toString() === right.toString();
}
// 주/부 포지션을 priority 1·2로 올리고 기존 나머지 선호는 뒤로 보존한다.
private reorderPreferredPositions(
mainPosition: Position,
@@ -531,33 +711,4 @@ export class MatchService {
}
return code;
}
private buildSeriesResults(
games: NonNullable<Match['result']>['games'],
): MatchSeriesResult[] {
const bySeries = new Map<string, MatchSeriesResult>();
for (const game of games) {
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex);
const key = `${teamAIndex}:${teamBIndex}`;
const current =
bySeries.get(key) ??
({
teamAIndex,
teamBIndex,
teamAWins: 0,
teamBWins: 0,
} satisfies MatchSeriesResult);
if (game.winnerTeamIndex === teamAIndex) current.teamAWins += 1;
if (game.winnerTeamIndex === teamBIndex) current.teamBWins += 1;
current.winnerTeamIndex =
current.teamAWins > current.teamBWins
? teamAIndex
: current.teamBWins > current.teamAWins
? teamBIndex
: undefined;
bySeries.set(key, current);
}
return [...bySeries.values()];
}
}
@@ -1,4 +1,5 @@
import mongoose from 'mongoose';
import { DistributedLockService } from '../global/redis/distributed-lock.service';
import { RedisService } from '../global/redis/redis.service';
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
import { RiotRateLimiterService } from '../riot/riot-rate-limiter.service';
@@ -35,11 +36,18 @@ function makeScheduler() {
};
const redis = {
getString: jest.fn().mockResolvedValue(null),
setString: jest.fn().mockResolvedValue(undefined),
setStringIfAbsent: jest.fn().mockResolvedValue(true),
delete: jest.fn().mockResolvedValue(1),
raw: jest.fn().mockReturnValue(rawClient),
} as unknown as jest.Mocked<RedisService> & { raw: jest.Mock };
const distributedLockService = {
acquireLock: jest.fn().mockResolvedValue({
lockKey: 'distributed-lock:riot-background-refresh:leader',
lockOwnershipToken: 'lock-owner',
lockExpirationDurationMilliseconds: 90_000,
}),
extendLockIfOwned: jest.fn().mockResolvedValue(true),
releaseLockIfOwned: jest.fn().mockResolvedValue(true),
} as unknown as jest.Mocked<DistributedLockService>;
const rateLimiter = {
isRefreshWindowOpen: jest.fn().mockResolvedValue(true),
} as unknown as jest.Mocked<RiotRateLimiterService>;
@@ -52,6 +60,7 @@ function makeScheduler() {
} as unknown as jest.Mocked<StaleAccountRepository>;
const scheduler = new BackgroundRefreshScheduler(
redis,
distributedLockService,
rateLimiter,
enrichmentService,
staleAccountRepository,
@@ -60,6 +69,7 @@ function makeScheduler() {
return {
scheduler,
redis,
distributedLockService,
rawClient,
rateLimiter,
enrichmentService,
@@ -115,8 +125,9 @@ describe('BackgroundRefreshScheduler', () => {
it('does not query stale accounts when another leader holds the lock', async () => {
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
const { scheduler, redis, staleAccountRepository } = makeScheduler();
redis.getString.mockResolvedValue('another-consumer');
const { scheduler, distributedLockService, staleAccountRepository } =
makeScheduler();
distributedLockService.acquireLock.mockResolvedValueOnce(null);
await scheduler.tick();
@@ -9,13 +9,17 @@ import {
RiotAccountEnrichmentService,
} from '../riot/riot-account-enrichment.service';
import { RiotRateLimiterService } from '../riot/riot-rate-limiter.service';
import {
type DistributedLockOwnership,
DistributedLockService,
} from '../global/redis/distributed-lock.service';
import { RedisService } from '../global/redis/redis.service';
import { isInKstBackgroundWindow } from './kst-window.util';
import { StaleAccountRepository } from './stale-account.repository';
const TICK_INTERVAL_MS = 60_000;
const LEADER_KEY = 'riot:bg-refresh:leader';
const LEADER_TTL_SECONDS = 90;
const LEADER_LOCK_KEY = 'distributed-lock:riot-background-refresh:leader';
const LEADER_LOCK_EXPIRATION_DURATION_MILLISECONDS = 90_000;
const LEADER_RENEW_INTERVAL_MS = 30_000;
const STALE_THRESHOLD_MS = 6 * 60 * 60 * 1000;
const PER_TICK_CANDIDATE_LIMIT = 20;
@@ -38,10 +42,11 @@ export class BackgroundRefreshScheduler
private tickTimer?: NodeJS.Timeout;
private leaderRenewTimer?: NodeJS.Timeout;
private tickInProgress = false;
private readonly consumer = `${process.pid}:${Math.random().toString(36).slice(2)}`;
private leaderLockOwnership: DistributedLockOwnership | undefined;
constructor(
private readonly redis: RedisService,
private readonly distributedLockService: DistributedLockService,
private readonly rateLimiter: RiotRateLimiterService,
private readonly enrichmentService: RiotAccountEnrichmentService,
private readonly staleAccountRepository: StaleAccountRepository,
@@ -59,9 +64,20 @@ export class BackgroundRefreshScheduler
void this.safeTick();
}
public onModuleDestroy(): void {
public async onModuleDestroy(): Promise<void> {
if (this.tickTimer) clearInterval(this.tickTimer);
if (this.leaderRenewTimer) clearInterval(this.leaderRenewTimer);
if (!this.leaderLockOwnership) return;
await this.distributedLockService
.releaseLockIfOwned(this.leaderLockOwnership)
.catch((err: unknown) => {
this.logger.warn(
`Background refresh leader release failed: ${
err instanceof Error ? err.message : err
}`,
);
});
this.leaderLockOwnership = undefined;
}
private async safeTick(): Promise<void> {
@@ -158,33 +174,33 @@ export class BackgroundRefreshScheduler
}
private async tryBecomeLeader(): Promise<boolean> {
const current = await this.redis.getString(LEADER_KEY);
if (current === this.consumer) {
await this.redis.setString(
LEADER_KEY,
this.consumer,
LEADER_TTL_SECONDS,
);
return true;
if (this.leaderLockOwnership) {
const didExtendLeaderLock =
await this.distributedLockService.extendLockIfOwned(
this.leaderLockOwnership,
);
if (didExtendLeaderLock) return true;
this.leaderLockOwnership = undefined;
}
if (current) return false;
return this.redis.setStringIfAbsent(
LEADER_KEY,
this.consumer,
LEADER_TTL_SECONDS,
);
const leaderLockOwnership = await this.distributedLockService.acquireLock({
lockKey: LEADER_LOCK_KEY,
lockExpirationDurationMilliseconds:
LEADER_LOCK_EXPIRATION_DURATION_MILLISECONDS,
});
this.leaderLockOwnership = leaderLockOwnership ?? undefined;
return Boolean(leaderLockOwnership);
}
private async renewLeaderIfHeld(): Promise<void> {
try {
const current = await this.redis.getString(LEADER_KEY);
if (current !== this.consumer) return;
await this.redis.setString(
LEADER_KEY,
this.consumer,
LEADER_TTL_SECONDS,
);
if (!this.leaderLockOwnership) return;
const didExtendLeaderLock =
await this.distributedLockService.extendLockIfOwned(
this.leaderLockOwnership,
);
if (didExtendLeaderLock) return;
this.leaderLockOwnership = undefined;
} catch (err) {
this.logger.warn(
`Background refresh leader renew failed: ${
@@ -1,5 +1,6 @@
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { DistributedLockService } from '../global/redis/distributed-lock.service';
import { RedisService } from '../global/redis/redis.service';
import { LegacyImportService } from '../legacy-import/legacy-import.service';
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
@@ -19,6 +20,16 @@ function makeWorker() {
acknowledgeStream: jest.fn().mockResolvedValue(undefined),
deleteStreamEntries: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<RedisService>;
const distributedLockService = {
runWithRenewedLock: jest.fn().mockImplementation(async (options, operation) =>
operation({
lockKey: options.lockKey,
lockOwnershipToken: 'lock-owner',
lockExpirationDurationMilliseconds:
options.lockExpirationDurationMilliseconds,
}),
),
} as unknown as jest.Mocked<DistributedLockService>;
const jobQueueService = {
markProcessing: jest.fn().mockResolvedValue(undefined),
markCompleted: jest.fn().mockResolvedValue({
@@ -54,6 +65,7 @@ function makeWorker() {
const worker = new RiotJobWorkerService(
redisService,
distributedLockService,
jobQueueService,
recentMatchesService,
connectionService,
@@ -66,6 +78,7 @@ function makeWorker() {
return {
worker,
redisService,
distributedLockService,
jobQueueService,
recentMatchesService,
connectionService,
@@ -151,4 +164,37 @@ describe('RiotJobWorkerService', () => {
redisService.deleteStreamEntries.mock.invocationCallOrder[0],
);
});
it('leaves a stream entry pending when another worker owns the job processing lock', async () => {
const { worker, distributedLockService, redisService } = makeWorker();
distributedLockService.runWithRenewedLock.mockResolvedValueOnce(null);
const userId = new mongoose.Types.ObjectId().toString();
const job: RiotRefreshSubJob = {
jobId: 'job-1',
parentJobId: 'parent-1',
userId,
puuid: 'puuid-1',
region: 'asia',
platform: 'kr',
queueGroup: 'summoners-rift',
queueIds: [420],
requestedAt: Date.now(),
priority: 'high',
};
await (
worker as unknown as {
processEntry: (
stream: string,
entry: { id: string; message: Record<string, string> },
) => Promise<void>;
}
).processEntry('riot:queue:high', {
id: '1-0',
message: { job: JSON.stringify(job) },
});
expect(redisService.acknowledgeStream).not.toHaveBeenCalled();
expect(redisService.deleteStreamEntries).not.toHaveBeenCalled();
});
});
@@ -6,6 +6,10 @@ import {
} from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import {
DistributedLockOwnership,
DistributedLockService,
} from '../global/redis/distributed-lock.service';
import { RedisService, StreamEntry } from '../global/redis/redis.service';
import { LegacyImportService } from '../legacy-import/legacy-import.service';
import type { LegacyImportMemberJob } from '../legacy-import/legacy-import.types';
@@ -23,17 +27,24 @@ import {
import { RiotJobQueueService } from './riot-job-queue.service';
import { RiotRefreshGateway } from './riot-refresh.gateway';
const LEADER_KEY = 'riot:worker:leader';
const LEADER_TTL_SECONDS = 60;
const RIOT_JOB_WORKER_LEADER_LOCK_KEY =
'distributed-lock:riot-job-worker:leader';
const RIOT_JOB_WORKER_LEADER_LOCK_EXPIRATION_DURATION_MILLISECONDS = 60_000;
const RIOT_JOB_PROCESSING_LOCK_EXPIRATION_DURATION_MILLISECONDS = 30 * 60_000;
const RIOT_JOB_PROCESSING_LOCK_RENEWAL_INTERVAL_MILLISECONDS = 5 * 60_000;
const STALE_PENDING_MESSAGE_MINIMUM_IDLE_MILLISECONDS = 30 * 60_000;
const STALE_PENDING_MESSAGE_CLAIM_COUNT = 1;
@Injectable()
export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(RiotJobWorkerService.name);
private readonly consumer = `${process.pid}:${Math.random().toString(36).slice(2)}`;
private readonly consumerIdentifier = `${process.pid}:${Math.random().toString(36).slice(2)}`;
private leaderLockOwnership: DistributedLockOwnership | undefined;
private stopped = false;
constructor(
private readonly redisService: RedisService,
private readonly distributedLockService: DistributedLockService,
private readonly jobQueueService: RiotJobQueueService,
private readonly recentMatchesService: RiotRecentMatchesService,
private readonly connectionService: ConnectionService,
@@ -48,8 +59,19 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
void this.loop();
}
public onModuleDestroy() {
public async onModuleDestroy() {
this.stopped = true;
if (!this.leaderLockOwnership) return;
await this.distributedLockService
.releaseLockIfOwned(this.leaderLockOwnership)
.catch((error: unknown) => {
this.logger.warn(
`Failed to release Riot job worker leader lock: ${
error instanceof Error ? error.message : error
}`,
);
});
this.leaderLockOwnership = undefined;
}
private async loop(): Promise<void> {
@@ -63,7 +85,9 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
await this.jobQueueService.promoteDueScheduledJobs();
const entry =
(await this.readOneStalePendingMessage(RIOT_JOB_HIGH_STREAM)) ??
(await this.readOne(RIOT_JOB_HIGH_STREAM, 100)) ??
(await this.readOneStalePendingMessage(RIOT_JOB_LOW_STREAM)) ??
(await this.readOne(RIOT_JOB_LOW_STREAM, 1_000));
if (!entry) continue;
@@ -89,6 +113,31 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
return;
}
const didProcessJob = await this.distributedLockService.runWithRenewedLock(
{
lockKey: this.jobProcessingLockKey(job),
lockExpirationDurationMilliseconds:
RIOT_JOB_PROCESSING_LOCK_EXPIRATION_DURATION_MILLISECONDS,
lockRenewalIntervalMilliseconds:
RIOT_JOB_PROCESSING_LOCK_RENEWAL_INTERVAL_MILLISECONDS,
},
async () => {
await this.processJob(job);
return true;
},
);
if (!didProcessJob) {
this.logger.debug(
`Skipped Riot job ${job.jobId}; another worker still owns the processing lock.`,
);
return;
}
await this.acknowledgeAndDelete(stream, entry.id);
}
private async processJob(job: RiotJobPayload): Promise<void> {
try {
if (this.isTournamentResultJob(job)) {
await this.tournamentResultService.processPollJob(job);
@@ -136,8 +185,6 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
error instanceof Error ? error.message : error
}`,
);
} finally {
await this.acknowledgeAndDelete(stream, entry.id);
}
}
@@ -228,15 +275,30 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
): Promise<{ stream: string; message: StreamEntry } | null> {
const result = await this.redisService.readGroup(
stream,
RIOT_JOB_GROUP,
this.consumer,
'>',
{ count: 1, blockMs },
RIOT_JOB_GROUP,
this.consumerIdentifier,
'>',
{ count: 1, blockMs },
);
const message = result?.[0]?.messages[0];
return message ? { stream, message } : null;
}
private async readOneStalePendingMessage(
stream: string,
): Promise<{ stream: string; message: StreamEntry } | null> {
const result = await this.redisService.claimStalePendingStreamMessages({
key: stream,
group: RIOT_JOB_GROUP,
consumer: this.consumerIdentifier,
stalePendingMessageMinimumIdleMilliseconds:
STALE_PENDING_MESSAGE_MINIMUM_IDLE_MILLISECONDS,
count: STALE_PENDING_MESSAGE_CLAIM_COUNT,
});
const message = result.messages[0];
return message ? { stream, message } : null;
}
private async ensureConsumerGroups(): Promise<void> {
await Promise.all(
[RIOT_JOB_HIGH_STREAM, RIOT_JOB_LOW_STREAM].map(async (stream) => {
@@ -252,21 +314,26 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
}
private async tryBecomeLeader(): Promise<boolean> {
const current = await this.redisService.getString(LEADER_KEY);
if (current === this.consumer) {
await this.redisService.setString(
LEADER_KEY,
this.consumer,
LEADER_TTL_SECONDS,
);
return true;
if (this.leaderLockOwnership) {
const didExtendLeaderLock =
await this.distributedLockService.extendLockIfOwned(
this.leaderLockOwnership,
);
if (didExtendLeaderLock) return true;
this.leaderLockOwnership = undefined;
}
if (current) return false;
return this.redisService.setStringIfAbsent(
LEADER_KEY,
this.consumer,
LEADER_TTL_SECONDS,
);
const leaderLockOwnership = await this.distributedLockService.acquireLock({
lockKey: RIOT_JOB_WORKER_LEADER_LOCK_KEY,
lockExpirationDurationMilliseconds:
RIOT_JOB_WORKER_LEADER_LOCK_EXPIRATION_DURATION_MILLISECONDS,
});
this.leaderLockOwnership = leaderLockOwnership ?? undefined;
return Boolean(leaderLockOwnership);
}
private jobProcessingLockKey(job: RiotJobPayload): string {
return `distributed-lock:riot-job-worker:job:${job.kind ?? 'refresh-account'}:${job.jobId}`;
}
private sleep(ms: number): Promise<void> {
@@ -0,0 +1,171 @@
import { RedisService } from '../global/redis/redis.service';
import { RiotDdragonService } from './riot-ddragon.service';
function jsonResponse(payload: unknown): Response {
return {
ok: true,
json: jest.fn().mockResolvedValue(payload),
} as unknown as Response;
}
function makeRedisService() {
return {
getJson: jest.fn().mockResolvedValue(null),
setJson: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<RedisService>;
}
describe('RiotDdragonService', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('includes localized item, spell, and rune metadata in the manifest', async () => {
const fetchMock = jest.fn(async (url: string) => {
if (url.endsWith('/api/versions.json')) {
return jsonResponse(['15.24.1']);
}
if (url.endsWith('/champion.json')) {
return jsonResponse({
data: {
Aatrox: { key: '266', id: 'Aatrox', name: '아트록스' },
},
});
}
if (url.endsWith('/summoner.json')) {
return jsonResponse({
data: {
SummonerFlash: {
key: '4',
id: 'SummonerFlash',
name: '점멸',
description: '커서 방향으로 순간이동합니다.',
tooltip: '<span>커서 방향으로 순간이동합니다.</span>',
},
},
});
}
if (url.endsWith('/runesReforged.json')) {
return jsonResponse([
{
id: 8000,
key: 'Precision',
icon: 'perk-images/Styles/7201_Precision.png',
name: '정밀',
slots: [
{
runes: [
{
id: 8005,
key: 'PressTheAttack',
icon: 'perk-images/Styles/Precision/PressTheAttack/PressTheAttack.png',
name: '집중 공격',
shortDesc: '연속 공격 시 추가 피해',
longDesc:
'<lol-uikit-tooltipped-keyword>기본 공격</lol-uikit-tooltipped-keyword>으로 적을 약화시킵니다.',
},
],
},
],
},
]);
}
if (url.endsWith('/item.json')) {
return jsonResponse({
data: {
'1055': {
name: '도란의 검',
description:
'<mainText><stats>공격력 <attention>10</attention></stats></mainText>',
plaintext: '공격력과 체력을 올려줍니다.',
gold: {
base: 450,
total: 450,
sell: 180,
purchasable: true,
},
},
},
});
}
throw new Error(`Unexpected URL: ${url}`);
});
jest.spyOn(global, 'fetch').mockImplementation(fetchMock as typeof fetch);
const redis = makeRedisService();
const service = new RiotDdragonService(redis);
await expect(service.getManifest('ko_KR')).resolves.toMatchObject({
version: '15.24.1',
locale: 'ko_KR',
summonerSpells: {
'4': {
key: 'SummonerFlash',
name: '점멸',
description: '커서 방향으로 순간이동합니다.',
tooltip: '<span>커서 방향으로 순간이동합니다.</span>',
},
},
runesReforged: [
{
id: 8000,
name: '정밀',
slots: [
{
runes: [
{
id: 8005,
name: '집중 공격',
shortDesc: '연속 공격 시 추가 피해',
longDesc:
'<lol-uikit-tooltipped-keyword>기본 공격</lol-uikit-tooltipped-keyword>으로 적을 약화시킵니다.',
},
],
},
],
},
],
items: {
'1055': {
name: '도란의 검',
description:
'<mainText><stats>공격력 <attention>10</attention></stats></mainText>',
plaintext: '공격력과 체력을 올려줍니다.',
gold: {
base: 450,
total: 450,
sell: 180,
purchasable: true,
},
},
},
});
expect(fetchMock).toHaveBeenCalledWith(
expect.stringContaining('/15.24.1/data/ko_KR/item.json'),
expect.any(Object),
);
expect(redis.setJson).toHaveBeenCalledWith(
'ddragon:manifest:v5:ko_KR',
expect.objectContaining({
summonerSpells: expect.objectContaining({
'4': expect.objectContaining({ description: '커서 방향으로 순간이동합니다.' }),
}),
runesReforged: expect.arrayContaining([
expect.objectContaining({
slots: expect.arrayContaining([
expect.objectContaining({
runes: expect.arrayContaining([
expect.objectContaining({ longDesc: expect.stringContaining('기본 공격') }),
]),
}),
]),
}),
]),
items: expect.objectContaining({
'1055': expect.objectContaining({ name: '도란의 검' }),
}),
}),
86_400,
);
});
});
@@ -5,7 +5,7 @@ const DDRAGON_BASE = 'https://ddragon.leagueoflegends.com';
const DDRAGON_CDN = `${DDRAGON_BASE}/cdn`;
const DEFAULT_LOCALE = 'ko_KR';
const CACHE_TTL_SECONDS = 24 * 60 * 60;
const CACHE_VERSION = 'v3';
const CACHE_VERSION = 'v5';
const FETCH_TIMEOUT_MS = 10_000;
export interface DdragonChampionEntry {
@@ -16,6 +16,8 @@ export interface DdragonChampionEntry {
export interface DdragonSummonerSpellEntry {
key: string;
name: string;
description: string;
tooltip: string;
}
export interface DdragonRuneEntry {
@@ -23,12 +25,26 @@ export interface DdragonRuneEntry {
key: string;
icon: string;
name: string;
shortDesc: string;
longDesc: string;
}
export interface DdragonRuneStyleEntry extends DdragonRuneEntry {
slots: Array<{ runes: DdragonRuneEntry[] }>;
}
export interface DdragonItemEntry {
name: string;
description: string;
plaintext: string;
gold: {
base: number;
total: number;
sell: number;
purchasable: boolean;
};
}
export interface DdragonManifest {
version: string;
cdn: string;
@@ -36,6 +52,7 @@ export interface DdragonManifest {
champions: Record<string, DdragonChampionEntry>;
summonerSpells: Record<string, DdragonSummonerSpellEntry>;
runesReforged: DdragonRuneStyleEntry[];
items: Record<string, DdragonItemEntry>;
fetchedAt: string;
}
@@ -53,6 +70,8 @@ interface SummonerSpellDataEntry {
key: string;
id: string;
name: string;
description?: string;
tooltip?: string;
}
interface SummonerSpellDataResponse {
@@ -64,12 +83,30 @@ interface RuneDataEntry {
key: string;
icon: string;
name: string;
shortDesc?: string;
longDesc?: string;
}
interface RuneStyleDataEntry extends RuneDataEntry {
slots?: Array<{ runes?: RuneDataEntry[] }>;
}
interface ItemDataEntry {
name?: string;
description?: string;
plaintext?: string;
gold?: {
base?: number;
total?: number;
sell?: number;
purchasable?: boolean;
};
}
interface ItemDataResponse {
data: Record<string, ItemDataEntry>;
}
@Injectable()
export class RiotDdragonService {
private readonly logger = new Logger(RiotDdragonService.name);
@@ -102,10 +139,11 @@ export class RiotDdragonService {
private async buildManifest(locale: string): Promise<DdragonManifest> {
const version = await this.fetchLatestVersion();
const [champions, summonerSpells, runesReforged] = await Promise.all([
const [champions, summonerSpells, runesReforged, items] = await Promise.all([
this.fetchChampionMap(version, locale),
this.fetchSummonerSpellMap(version, locale),
this.fetchRuneStyles(version, locale),
this.fetchItemMap(version, locale),
]);
return {
version,
@@ -114,6 +152,7 @@ export class RiotDdragonService {
champions,
summonerSpells,
runesReforged,
items,
fetchedAt: new Date().toISOString(),
};
}
@@ -164,6 +203,9 @@ export class RiotDdragonService {
map[entry.key] = {
key: entry.id,
name: typeof entry.name === 'string' ? entry.name : entry.id,
description:
typeof entry.description === 'string' ? entry.description : '',
tooltip: typeof entry.tooltip === 'string' ? entry.tooltip : '',
};
}
}
@@ -187,6 +229,9 @@ export class RiotDdragonService {
key: style.key,
icon: style.icon,
name: style.name,
shortDesc:
typeof style.shortDesc === 'string' ? style.shortDesc : '',
longDesc: typeof style.longDesc === 'string' ? style.longDesc : '',
slots: (style.slots ?? []).map((slot) => ({
runes: (slot.runes ?? [])
.filter((rune): rune is RuneDataEntry => isRuneEntry(rune))
@@ -195,11 +240,46 @@ export class RiotDdragonService {
key: rune.key,
icon: rune.icon,
name: rune.name,
shortDesc:
typeof rune.shortDesc === 'string' ? rune.shortDesc : '',
longDesc: typeof rune.longDesc === 'string' ? rune.longDesc : '',
})),
})),
}));
}
private async fetchItemMap(
version: string,
locale: string,
): Promise<Record<string, DdragonItemEntry>> {
const url = `${DDRAGON_CDN}/${version}/data/${locale}/item.json`;
const payload = await this.fetchJson<ItemDataResponse>(url);
if (!payload || typeof payload !== 'object' || !payload.data) {
throw new Error(`ddragon item.json response is malformed (${url}).`);
}
const map: Record<string, DdragonItemEntry> = {};
for (const [itemId, entry] of Object.entries(payload.data)) {
if (!/^\d+$/.test(itemId) || typeof entry?.name !== 'string') {
continue;
}
map[itemId] = {
name: entry.name,
description:
typeof entry.description === 'string' ? entry.description : '',
plaintext: typeof entry.plaintext === 'string' ? entry.plaintext : '',
gold: {
base: numberOrZero(entry.gold?.base),
total: numberOrZero(entry.gold?.total),
sell: numberOrZero(entry.gold?.sell),
purchasable: entry.gold?.purchasable ?? false,
},
};
}
return map;
}
private async fetchJson<T>(url: string): Promise<T> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
@@ -245,6 +325,10 @@ function isRuneEntry(value: unknown): value is RuneDataEntry {
);
}
function numberOrZero(value: unknown): number {
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
}
function manifestCacheKey(locale: string): string {
return `ddragon:manifest:${CACHE_VERSION}:${locale}`;
}
@@ -4,14 +4,14 @@ import type {
RiotMatch as StoredRiotMatch,
} from '../global/database/schema';
import { ConnectionService } from '../global/database/connection.service';
import { RedisService } from '../global/redis/redis.service';
import { DistributedLockService } from '../global/redis/distributed-lock.service';
import type { RiotRegionalRoute } from './riot.types';
import { RiotMatchService } from './riot-match.service';
export const RIOT_RECENT_MATCH_LIMIT = 20;
export const RIOT_SOLO_QUEUE_ID = 420;
const MATCH_ENRICHMENT_LOCK_TTL_SECONDS = 60;
const MATCH_ENRICHMENT_LOCK_EXPIRATION_DURATION_MILLISECONDS = 60_000;
const MATCH_DETAIL_CONCURRENCY = 2;
const DEFAULT_REGION: RiotRegionalRoute = 'asia';
@@ -22,7 +22,7 @@ export class RiotRecentMatchesService {
constructor(
private readonly connectionService: ConnectionService,
private readonly matchService: RiotMatchService,
private readonly redisService: RedisService,
private readonly distributedLockService: DistributedLockService,
) {}
public async syncRecentMatches(params: {
@@ -34,83 +34,84 @@ export class RiotRecentMatchesService {
const region = params.region ?? DEFAULT_REGION;
const limit = params.limit ?? RIOT_RECENT_MATCH_LIMIT;
const queueId = params.queueId ?? RIOT_SOLO_QUEUE_ID;
const lockKey = `riot:enrich:matches:${params.puuid}`;
const lockValue = `${process.pid}:${Date.now()}`;
const acquired = await this.redisService.setStringIfAbsent(
lockKey,
lockValue,
MATCH_ENRICHMENT_LOCK_TTL_SECONDS,
);
if (!acquired) {
return this.loadFromDb({ puuid: params.puuid, limit, queueId });
}
try {
const matchIds = await this.matchService.getMatchIdsByPuuid(params.puuid, {
region,
queue: queueId,
count: limit,
});
if (matchIds.length === 0) {
return this.loadFromDb({ puuid: params.puuid, limit, queueId });
}
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const existingMatches = await RiotMatchModel.find({
matchId: { $in: matchIds },
})
.select({ matchId: 1 })
.lean()
.exec();
const existingMatchIds = new Set(existingMatches.map((match) => match.matchId));
const missingMatchIds = matchIds.filter((matchId) => !existingMatchIds.has(matchId));
await runWithConcurrency(missingMatchIds, MATCH_DETAIL_CONCURRENCY, async (matchId) => {
try {
const dto = await this.matchService.getMatch(matchId, { region });
if (dto.info.queueId !== queueId) {
this.logger.warn(
`Skipping unexpected queue ${dto.info.queueId} for ${matchId} while syncing ${params.puuid}.`,
);
return;
}
const payload: Partial<StoredRiotMatch> = {
matchId: dto.metadata.matchId,
gameCreation: dto.info.gameCreation,
gameDuration: dto.info.gameDuration,
gameVersion: dto.info.gameVersion,
queueId: dto.info.queueId,
participantPuuids: dto.metadata.participants,
raw: dto as unknown as Record<string, unknown>,
fetchedAt: new Date(),
};
await RiotMatchModel.updateOne(
{ matchId: dto.metadata.matchId },
{ $setOnInsert: payload },
{ upsert: true },
).exec();
} catch (error: unknown) {
this.logger.warn(
`Skipping Riot match ${matchId} while syncing ${params.puuid}: ${
error instanceof Error ? error.message : error
}`,
);
}
});
return this.loadFromDb({ puuid: params.puuid, limit, queueId });
} finally {
await this.redisService.delete(lockKey).catch((error: unknown) => {
this.logger.warn(
`Failed to release recent matches lock for ${params.puuid}: ${
(error as Error)?.message ?? error
}`,
const result = await this.distributedLockService.runWithLock(
{
lockKey: `distributed-lock:riot-recent-matches:sync:puuid:${params.puuid}`,
lockExpirationDurationMilliseconds:
MATCH_ENRICHMENT_LOCK_EXPIRATION_DURATION_MILLISECONDS,
},
async () => {
const matchIds = await this.matchService.getMatchIdsByPuuid(
params.puuid,
{
region,
queue: queueId,
count: limit,
},
);
});
}
if (matchIds.length === 0) {
return this.loadFromDb({ puuid: params.puuid, limit, queueId });
}
const RiotMatchModel =
await this.connectionService.getModel('riotMatch');
const existingMatches = await RiotMatchModel.find({
matchId: { $in: matchIds },
})
.select({ matchId: 1 })
.lean()
.exec();
const existingMatchIds = new Set(
existingMatches.map((match) => match.matchId),
);
const missingMatchIds = matchIds.filter(
(matchId) => !existingMatchIds.has(matchId),
);
await runWithConcurrency(
missingMatchIds,
MATCH_DETAIL_CONCURRENCY,
async (matchId) => {
try {
const dto = await this.matchService.getMatch(matchId, { region });
if (dto.info.queueId !== queueId) {
this.logger.warn(
`Skipping unexpected queue ${dto.info.queueId} for ${matchId} while syncing ${params.puuid}.`,
);
return;
}
const payload: Partial<StoredRiotMatch> = {
matchId: dto.metadata.matchId,
gameCreation: dto.info.gameCreation,
gameDuration: dto.info.gameDuration,
gameVersion: dto.info.gameVersion,
queueId: dto.info.queueId,
participantPuuids: dto.metadata.participants,
raw: dto as unknown as Record<string, unknown>,
fetchedAt: new Date(),
};
await RiotMatchModel.updateOne(
{ matchId: dto.metadata.matchId },
{ $setOnInsert: payload },
{ upsert: true },
).exec();
} catch (error: unknown) {
this.logger.warn(
`Skipping Riot match ${matchId} while syncing ${params.puuid}: ${
error instanceof Error ? error.message : error
}`,
);
}
},
);
return this.loadFromDb({ puuid: params.puuid, limit, queueId });
},
);
return result ?? this.loadFromDb({ puuid: params.puuid, limit, queueId });
}
public async ensureFreshForQueue(params: {
@@ -1,47 +0,0 @@
import mongoose from 'mongoose';
import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from '../auth/allow-public-access.decorator';
import { TournamentCodeReplacementController } from './tournament-code-replacement.controller';
import type { TournamentCodeService } from './tournament-code.service';
describe('TournamentCodeReplacementController', () => {
function createFixture() {
const service = {
replaceForMatchGame: jest.fn().mockResolvedValue({
gameNumber: 1,
code: 'NEW-CODE',
}),
} as unknown as jest.Mocked<
Pick<TournamentCodeService, 'replaceForMatchGame'>
>;
const controller = new TournamentCodeReplacementController(
service as unknown as TournamentCodeService,
);
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
return { controller, service, communityId, matchId };
}
it('allows public replacement requests', async () => {
const { controller, service, communityId, matchId } = createFixture();
await expect(
controller.replaceForMatchGame(communityId, matchId, 1),
).resolves.toEqual(expect.objectContaining({ code: 'NEW-CODE' }));
expect(service.replaceForMatchGame).toHaveBeenCalledWith({
communityId,
matchId,
gameNumber: 1,
});
});
it('marks the replacement endpoint as public access', () => {
expect(
Reflect.getMetadata(
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
TournamentCodeReplacementController.prototype.replaceForMatchGame,
),
).toBe(true);
});
});
@@ -1,30 +0,0 @@
import {
Controller,
Param,
ParseIntPipe,
Post,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import { TournamentCodeService } from './tournament-code.service';
@Controller('communities/:communityId/tournament-codes')
export class TournamentCodeReplacementController {
constructor(private readonly tournamentCodeService: TournamentCodeService) {}
@Post('matches/:matchId/games/:gameNumber/replace')
@AllowPublicAccess()
public async replaceForMatchGame(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Param('gameNumber', ParseIntPipe) gameNumber: number,
) {
return this.tournamentCodeService.replaceForMatchGame({
communityId,
matchId,
gameNumber,
});
}
}
@@ -1,13 +1,15 @@
import { Module } from '@nestjs/common';
import { AuctionRedisModule } from '../auction/redis/auction-redis.module';
import { TournamentResultModule } from '../tournament-result/tournament-result.module';
import { TournamentCodeController } from './tournament-code.controller';
import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service';
import { TournamentCodeReplacementController } from './tournament-code-replacement.controller';
import { TournamentCodeScheduler } from './tournament-code.scheduler';
import { TournamentCodeService } from './tournament-code.service';
import { TournamentCodeVendorService } from './tournament-code-vendor.service';
@Module({
controllers: [TournamentCodeController, TournamentCodeReplacementController],
imports: [TournamentResultModule, AuctionRedisModule],
controllers: [TournamentCodeController],
providers: [
TournamentCodeService,
TournamentCodeVendorService,
Loaded 100 of 173 files, more files were not shown because too many files have changed in this diff. Show more