diff --git a/.codex/config.toml b/.codex/config.toml new file mode 100644 index 00000000..392b17a5 --- /dev/null +++ b/.codex/config.toml @@ -0,0 +1,4 @@ +[mcp_servers.playwright_macos] +url = "http://100.96.0.26:8931/mcp" +tool_timeout_sec = 120 +startup_timeout_sec = 30 \ No newline at end of file diff --git a/.gitignore b/.gitignore index 18024dde..b762a4c2 100644 --- a/.gitignore +++ b/.gitignore @@ -26,6 +26,10 @@ website/LICENSE *.md !README.md !AGENTS.md +!docs/specs/internal-match-game-analysis.md +!docs/plans/internal-match-game-analysis-p0-p1.md +!docs/specs/double-elimination-connector-routing.md +!docs/plans/double-elimination-connector-routing.md !agents/**/*.md !skills/**/*.md /tmp/ diff --git a/BUILD_NUMBER b/BUILD_NUMBER index 780fea92..76a8b2b7 100644 --- a/BUILD_NUMBER +++ b/BUILD_NUMBER @@ -1 +1 @@ -77 \ No newline at end of file +83 diff --git a/Dockerfile b/Dockerfile index 00d1e559..315f68e4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -14,24 +14,27 @@ FROM pnpm-base AS deps COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ COPY apps/api/package.json apps/api/package.json COPY apps/web/package.json apps/web/package.json +COPY packages/contracts/package.json packages/contracts/package.json RUN pnpm install --frozen-lockfile --filter api... --filter lolympus-tournament-support FROM deps AS build +COPY packages/contracts packages/contracts COPY apps/api apps/api -RUN pnpm --filter api build +RUN pnpm --filter api... build FROM pnpm-base AS prod-deps COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ COPY apps/api/package.json apps/api/package.json COPY apps/web/package.json apps/web/package.json +COPY packages/contracts/package.json packages/contracts/package.json RUN pnpm install --prod --frozen-lockfile --filter api... --filter lolympus-tournament-support -FROM gcr.io/distroless/nodejs24-debian13:nonroot AS runtime +FROM gcr.io/distroless/nodejs26-debian13:nonroot AS runtime WORKDIR /app @@ -41,9 +44,18 @@ COPY --from=prod-deps --chown=nonroot:nonroot /app/package.json ./package.json COPY --from=prod-deps --chown=nonroot:nonroot /app/node_modules ./node_modules COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/package.json ./apps/api/package.json COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/node_modules ./apps/api/node_modules +COPY --from=build --chown=nonroot:nonroot /app/packages/contracts/package.json ./packages/contracts/package.json +COPY --from=build --chown=nonroot:nonroot /app/packages/contracts/dist ./packages/contracts/dist +COPY --chown=nonroot:nonroot apps/api/newrelic.cjs ./apps/api/newrelic.cjs COPY --from=build --chown=nonroot:nonroot /app/apps/api/dist ./apps/api/dist COPY --chown=nonroot:nonroot apps/project.env ./project.env -EXPOSE 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"] diff --git a/README.md b/README.md index 876df721..83acefd7 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ LOLYMPUS는 리그 오브 레전드 커뮤니티의 여러 이벤트 중 내전(

- 3초 간격 데모 영상 보기 + 3초 간격 데모 영상 보기

## 배포 주소 | Environment | Version | URL | | ----------- | ------- | -------------------------------------- | -| Production | v77 | | -| Staging | v77 | | +| Production | v84 | | +| Staging | v84 | | ## 개요 @@ -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 기반 결과 수집, 개인 전적, 리더보드 제공 @@ -91,7 +95,8 @@ LOLYMPUS는 이 반복 작업을 줄이는 데 초점을 맞췄습니다. 운영 - TanStack Query - NestJS - MongoDB -- Redis/Garnet +- Redis +- Redis 8.4 (경매 실시간 상태 전용) - NATS - Riot API - pnpm workspace @@ -113,7 +118,9 @@ scripts/ deployment and maintenance scripts - Node.js 24 이상 - pnpm 10.4.1 (`packageManager` 기준, `corepack enable`로 활성화 권장) -- MongoDB 7.0, Redis 5.0 이상, NATS 실행 환경 +- MongoDB 7.0, 일반 캐시/스트림용 Redis, 경매 실시간 상태 전용 Redis 8.4, NATS 실행 환경 + +경매 Redis는 라이브 경매 상태의 source of truth로 사용되므로 일반 캐시/스트림 Redis와 물리적으로 분리해야 합니다. API는 `REDIS_URL`/`REDIS_ENDPOINT`와 별도로 `AUCTION_REDIS_URL`/`AUCTION_REDIS_ENDPOINT`를 읽고, 두 값이 같은 호스트/포트를 가리키면 부팅을 거부합니다. ## 실행 방법 @@ -125,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 서버와 연결되어 있지 않으면 일정 조회, 내전 참가, 참가 취소, 계정 등록 같은 카카오톡 명령어는 사용할 수 없습니다. ## 커맨드 @@ -134,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 배포 | diff --git a/apps/api/newrelic.cjs b/apps/api/newrelic.cjs new file mode 100644 index 00000000..64602d6f --- /dev/null +++ b/apps/api/newrelic.cjs @@ -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*', + ], + }, +}; diff --git a/apps/api/package.json b/apps/api/package.json index cd8552e2..05377cc8 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -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", @@ -32,11 +36,13 @@ "@nestjs/platform-socket.io": "^11.1.19", "@nestjs/swagger": "^11.2.7", "@nestjs/websockets": "^11.1.19", + "@socket.io/redis-adapter": "^8.3.0", "class-transformer": "^0.5.1", "class-validator": "^0.15.1", "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", diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts index 9e8347a1..c2b13878 100644 --- a/apps/api/src/app.module.ts +++ b/apps/api/src/app.module.ts @@ -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 {} diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts index 375ab8a4..2ffb073c 100644 --- a/apps/api/src/main.ts +++ b/apps/api/src/main.ts @@ -2,6 +2,7 @@ import { ValidationPipe } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { createCorsOrigin } from './cors-origin'; +import { RedisIoAdapter } from './redis-io.adapter'; async function bootstrap() { const app = await NestFactory.create(AppModule, { @@ -10,11 +11,21 @@ async function bootstrap() { const nodeEnv = process.env.NODE_ENV; const isDev = nodeEnv === 'dev'; + const redisIoAdapter = new RedisIoAdapter(app); + await redisIoAdapter.connectToRedis(); + app.useWebSocketAdapter(redisIoAdapter); 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({ diff --git a/apps/api/src/modules/auction/auction-deadline.scheduler.spec.ts b/apps/api/src/modules/auction/auction-deadline.scheduler.spec.ts new file mode 100644 index 00000000..1e4824df --- /dev/null +++ b/apps/api/src/modules/auction/auction-deadline.scheduler.spec.ts @@ -0,0 +1,217 @@ +import { AuctionRedisService } from './redis/auction-redis.service'; +import { AuctionDeadlineScheduler } from './auction-deadline.scheduler'; +import { AuctionRedisCommandService } from './redis/auction-redis-command.service'; +import { AuctionService } from './auction.service'; +import { AuctionEventBusService } from './auction-event-bus.service'; + +function makeScheduler(params: { + dueReply?: unknown; + leaderLockAcquired?: boolean; + expireReply?: unknown; + completedState?: unknown; + currentRedisTimestampMS?: number; +}) { + const sendCommand = jest.fn().mockResolvedValue(params.dueReply ?? []); + const redis = { + acquireTokenLock: jest + .fn() + .mockResolvedValue(params.leaderLockAcquired ?? true), + getCurrentRedisTimestampMS: jest + .fn() + .mockResolvedValue(params.currentRedisTimestampMS ?? 1000), + releaseTokenLock: jest.fn().mockResolvedValue(true), + raw: jest.fn().mockReturnValue({ sendCommand }), + } as unknown as jest.Mocked; + const redisCommand = { + expirePrepare: jest.fn().mockResolvedValue( + params.expireReply ?? { + auctionStateTransitionId: 'expire-1', + bidRoundExpiryDecision: 'passed', + currentServerTimestampMS: 1000, + ok: true, + revision: 2, + }, + ), + } as unknown as jest.Mocked; + const auctionService = { + completePreparedExpiry: jest + .fn() + .mockResolvedValue(params.completedState ?? { phase: 'passed' }), + } as unknown as jest.Mocked; + const eventBus = { + broadcastState: jest.fn(), + } as unknown as jest.Mocked; + return { + auctionService, + eventBus, + redis, + redisCommand, + scheduler: new AuctionDeadlineScheduler( + redis, + redisCommand, + auctionService, + eventBus, + ), + sendCommand, + }; +} + +describe('AuctionDeadlineScheduler', () => { + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('starts and clears the deadline tick timer', () => { + const setIntervalSpy = jest.spyOn(global, 'setInterval'); + const clearIntervalSpy = jest.spyOn(global, 'clearInterval'); + const { scheduler } = makeScheduler({}); + + scheduler.onModuleInit(); + scheduler.onModuleDestroy(); + + expect(setIntervalSpy).toHaveBeenCalledWith(expect.any(Function), 1000); + expect(clearIntervalSpy).toHaveBeenCalledTimes(1); + }); + + it('processes a deadline tick only while holding the Redis leader lock', async () => { + const { redis, scheduler } = makeScheduler({}); + const processDueBidRoundDeadlinesSpy = jest + .spyOn(scheduler, 'processDueBidRoundDeadlines') + .mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 }); + + await (scheduler as unknown as { safeTick: () => Promise }).safeTick(); + + const leaderLockToken = redis.acquireTokenLock.mock.calls[0]?.[1]; + expect(redis.acquireTokenLock).toHaveBeenCalledWith( + 'auction:bidRoundDeadlineScheduler:leader', + expect.any(String), + 2500, + ); + expect(processDueBidRoundDeadlinesSpy).toHaveBeenCalledWith(20); + expect(redis.releaseTokenLock).toHaveBeenCalledWith( + 'auction:bidRoundDeadlineScheduler:leader', + leaderLockToken, + ); + }); + + it('skips deadline tick work when another instance holds the leader lock', async () => { + const { redis, scheduler } = makeScheduler({ leaderLockAcquired: false }); + const processDueBidRoundDeadlinesSpy = jest + .spyOn(scheduler, 'processDueBidRoundDeadlines') + .mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 }); + + await (scheduler as unknown as { safeTick: () => Promise }).safeTick(); + + expect(processDueBidRoundDeadlinesSpy).not.toHaveBeenCalled(); + expect(redis.releaseTokenLock).not.toHaveBeenCalled(); + }); + + it('reads due match ids from the Redis deadline queue with a batch limit', async () => { + const { redis, scheduler } = makeScheduler({ + dueReply: ['match-1', 'match-2'], + }); + + await expect(scheduler.readDueMatchIds(1_000, 2)).resolves.toEqual([ + 'match-1', + 'match-2', + ]); + expect(redis.raw().sendCommand).toHaveBeenCalledWith([ + 'ZRANGEBYSCORE', + 'auction:bidRoundDeadlineQueue', + '-inf', + '1000', + 'LIMIT', + '0', + '2', + ]); + }); + + it('prepares and completes due auction deadlines', async () => { + const matchId = '665f2f01f1f1f1f1f1f1f1f1'; + const completedState = { phase: 'passed', revision: 3 }; + const { auctionService, eventBus, redisCommand, scheduler } = makeScheduler({ + dueReply: [matchId], + completedState, + }); + + await expect(scheduler.processDueBidRoundDeadlines(10)).resolves.toEqual({ + completed: 1, + prepared: 1, + skipped: 0, + }); + expect(redisCommand.expirePrepare).toHaveBeenCalledWith( + matchId, + expect.objectContaining({ + bidRoundExpiryRetryDelayMS: 3000, + matchId, + }), + ); + expect(auctionService.completePreparedExpiry).toHaveBeenCalledTimes(1); + // 만료 확정 결과는 즉시 1차 broadcast돼야 한다(클라가 입찰 라운드에 멈춰 + // 후속 액션에서 CONFLICT가 반복되는 것을 막는 핵심 동작). + expect(eventBus.broadcastState).toHaveBeenCalledWith(matchId, completedState); + }); + + it('skips noop expiry preparations', async () => { + const { auctionService, eventBus, scheduler } = makeScheduler({ + dueReply: ['665f2f01f1f1f1f1f1f1f1f1'], + expireReply: { + code: 'NOT_DUE', + currentServerTimestampMS: 1000, + noop: true, + }, + }); + + await expect(scheduler.processDueBidRoundDeadlines(10)).resolves.toEqual({ + completed: 0, + prepared: 0, + skipped: 1, + }); + expect(auctionService.completePreparedExpiry).not.toHaveBeenCalled(); + expect(eventBus.broadcastState).not.toHaveBeenCalled(); + }); + + it('removes invalid deadline queue members', async () => { + const { scheduler, sendCommand } = makeScheduler({ + dueReply: ['not-a-match-id'], + }); + + await expect(scheduler.processDueBidRoundDeadlines(10)).resolves.toEqual({ + completed: 0, + prepared: 0, + skipped: 1, + }); + expect(sendCommand).toHaveBeenLastCalledWith([ + 'ZREM', + 'auction:bidRoundDeadlineQueue', + 'not-a-match-id', + ]); + }); + + it('continues processing later deadline items after one item fails', async () => { + const matchIds = [ + '665f2f01f1f1f1f1f1f1f1f1', + '665f2f02f1f1f1f1f1f1f1f1', + ]; + const { auctionService, redisCommand, scheduler } = makeScheduler({ + dueReply: matchIds, + }); + redisCommand.expirePrepare + .mockRejectedValueOnce(new Error('temporary redis error')) + .mockResolvedValueOnce({ + auctionStateTransitionId: 'expire-2', + bidRoundExpiryDecision: 'passed', + currentServerTimestampMS: 1000, + ok: true, + revision: 3, + }); + + await expect(scheduler.processDueBidRoundDeadlines(10)).resolves.toEqual({ + completed: 1, + prepared: 1, + skipped: 1, + }); + expect(redisCommand.expirePrepare).toHaveBeenCalledTimes(2); + expect(auctionService.completePreparedExpiry).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/api/src/modules/auction/auction-deadline.scheduler.ts b/apps/api/src/modules/auction/auction-deadline.scheduler.ts new file mode 100644 index 00000000..b68a5ca8 --- /dev/null +++ b/apps/api/src/modules/auction/auction-deadline.scheduler.ts @@ -0,0 +1,187 @@ +import { + Injectable, + Logger, + OnModuleDestroy, + OnModuleInit, +} from '@nestjs/common'; +import { randomUUID } from 'crypto'; +import mongoose from 'mongoose'; +import { AuctionService } from './auction.service'; +import { AuctionEventBusService } from './auction-event-bus.service'; +import { AuctionRedisCommandService } from './redis/auction-redis-command.service'; +import { AuctionRedisService } from './redis/auction-redis.service'; + +const BID_ROUND_DEADLINE_QUEUE_KEY = 'auction:bidRoundDeadlineQueue'; +const BID_ROUND_EXPIRY_RETRY_DELAY_MS = 3000; +const BID_ROUND_DEADLINE_TICK_INTERVAL_MS = 1000; +const BID_ROUND_DEADLINE_BATCH_LIMIT = 20; +const BID_ROUND_DEADLINE_LEADER_LOCK_KEY = + 'auction:bidRoundDeadlineScheduler:leader'; +const BID_ROUND_DEADLINE_LEADER_LOCK_TTL_MS = 2500; + +/** + * 입찰 라운드 마감(deadline)을 감시해 자동으로 만료시키는 단일 리더 스위퍼. + * + * 만료는 2단계로 처리한다(정확히-1회 + 노드 크래시 복구를 위해): + * 1) EXPIRE_PREPARE Lua: `bidding → expiring`으로 flip하고 만료 결정/컨텍스트를 + * `liveAuctionState`에 고정 + deadline ZSET에 재시도 점수 재등록. + * 2) `completePreparedExpiry`: 고정된 컨텍스트로 APPLY_TRANSITION을 돌려 + * `sold`/`passed`로 확정하고 Mongo durability outbox를 enqueue. + * + * 중요(브로드캐스트 책임): + * - 관리자 수동 전환(sold/next 등)은 게이트웨이가 응답 직후 동기로 `state`를 + * broadcast하지만, 자동 만료는 게이트웨이를 거치지 않는다. + * - 따라서 만료 확정 결과를 클라이언트에 즉시 알리는 1차 전달 책임은 이 스위퍼에 + * 있다. 여기서 broadcast하지 않으면 클라는 입찰 라운드 revision에 멈춰 있다가 + * "다음" 등 후속 액션에서 stale 관측값으로 CONFLICT를 반복하게 된다. + * - `AuctionDurabilityScheduler`의 broadcast는 Mongo 영속화 성공에 묶인 ~1초 주기의 + * "노드 크래시 복구용 백업"이지 1차 전달 경로가 아니다(중복 emit돼도 클라 + * revision 가드로 무해). + * + * 멀티 인스턴스: 리더 락을 잡은 한 인스턴스만 만료를 처리/방송하고, socket.io Redis + * adapter가 전 인스턴스 소켓으로 fanout한다. + */ +@Injectable() +export class AuctionDeadlineScheduler implements OnModuleInit, OnModuleDestroy { + private readonly logger = new Logger(AuctionDeadlineScheduler.name); + private tickTimer?: NodeJS.Timeout; + private tickInProgress = false; + + constructor( + private readonly auctionRedisService: AuctionRedisService, + private readonly auctionRedisCommandService: AuctionRedisCommandService, + private readonly auctionService: AuctionService, + // 만료 확정 결과를 클라이언트에 즉시 알리기 위한 1차 broadcast 채널. + private readonly auctionEventBusService: AuctionEventBusService, + ) {} + + public onModuleInit(): void { + this.tickTimer = setInterval( + () => void this.safeTick(), + BID_ROUND_DEADLINE_TICK_INTERVAL_MS, + ); + this.tickTimer.unref?.(); + } + + public onModuleDestroy(): void { + if (this.tickTimer) clearInterval(this.tickTimer); + } + + private async safeTick(): Promise { + if (this.tickInProgress) return; + this.tickInProgress = true; + const leaderLockToken = randomUUID(); + let leaderLockAcquired = false; + try { + leaderLockAcquired = await this.auctionRedisService.acquireTokenLock( + BID_ROUND_DEADLINE_LEADER_LOCK_KEY, + leaderLockToken, + BID_ROUND_DEADLINE_LEADER_LOCK_TTL_MS, + ); + if (!leaderLockAcquired) return; + await this.processDueBidRoundDeadlines(BID_ROUND_DEADLINE_BATCH_LIMIT); + } catch (error) { + this.logger.warn( + `Auction deadline tick failed: ${ + error instanceof Error ? error.message : error + }`, + ); + } finally { + if (leaderLockAcquired) { + await this.auctionRedisService.releaseTokenLock( + BID_ROUND_DEADLINE_LEADER_LOCK_KEY, + leaderLockToken, + ); + } + this.tickInProgress = false; + } + } + + public async readDueMatchIds( + currentRedisTimestampMS: number, + batchLimit: number, + ): Promise { + const reply = await this.auctionRedisService.raw().sendCommand([ + 'ZRANGEBYSCORE', + BID_ROUND_DEADLINE_QUEUE_KEY, + '-inf', + String(currentRedisTimestampMS), + 'LIMIT', + '0', + String(batchLimit), + ]); + return Array.isArray(reply) ? reply.map(String) : []; + } + + public async processDueBidRoundDeadlines(batchLimit: number): Promise<{ + completed: number; + prepared: number; + skipped: number; + }> { + const currentRedisTimestampMS = + await this.auctionRedisService.getCurrentRedisTimestampMS(); + const matchIds = await this.readDueMatchIds( + currentRedisTimestampMS, + batchLimit, + ); + let prepared = 0; + let completed = 0; + let skipped = 0; + + for (const matchId of matchIds) { + if (!mongoose.isValidObjectId(matchId)) { + skipped += 1; + await this.removeBidRoundDeadlineQueueEntry(matchId); + continue; + } + try { + // 1단계: 만료 결정/컨텍스트 고정(bidding → expiring). 아직 마감 전이거나 + // 이미 다른 phase면 noop으로 빠진다(stale ZSET 엔트리는 Lua가 정리). + const result = await this.auctionRedisCommandService.expirePrepare( + matchId, + { + auctionStateTransitionId: `expire:${matchId}:${randomUUID()}`, + bidRoundExpiryRetryDelayMS: BID_ROUND_EXPIRY_RETRY_DELAY_MS, + matchId, + }, + ); + if ('noop' in result) { + skipped += 1; + continue; + } + prepared += 1; + // 2단계: 고정된 컨텍스트로 sold/passed 확정. 재진입(다른 인스턴스/다음 틱)해도 + // appliedAuctionStateTransitionIds dedupe로 정확히-1회만 반영된다. + const completedState = await this.auctionService.completePreparedExpiry( + new mongoose.Types.ObjectId(matchId), + ); + if (completedState) { + completed += 1; + // 1차 전달: 만료 확정 즉시 최신 state를 방송한다. 이게 없으면 클라가 + // 입찰 라운드에 멈춰 후속 액션에서 CONFLICT가 반복된다(durability + // worker 백업 방송은 Mongo 성공 + ~1초 tick에 묶여 1차 전달로 부적합). + // 이미 처리된 전환은 completePreparedExpiry가 null을 반환하므로 중복 + // 방송되지 않고, 혹시 겹쳐도 클라 revision 가드로 무해하다. + this.auctionEventBusService.broadcastState(matchId, completedState); + } + } catch (error) { + skipped += 1; + this.logger.warn( + `Auction deadline item failed for ${matchId}: ${ + error instanceof Error ? error.message : error + }`, + ); + } + } + + return { completed, prepared, skipped }; + } + + private async removeBidRoundDeadlineQueueEntry(matchId: string): Promise { + await this.auctionRedisService.raw().sendCommand([ + 'ZREM', + BID_ROUND_DEADLINE_QUEUE_KEY, + matchId, + ]); + } +} diff --git a/apps/api/src/modules/auction/auction-durability.scheduler.spec.ts b/apps/api/src/modules/auction/auction-durability.scheduler.spec.ts new file mode 100644 index 00000000..4cceabd4 --- /dev/null +++ b/apps/api/src/modules/auction/auction-durability.scheduler.spec.ts @@ -0,0 +1,1342 @@ +import { + AuctionDurabilityScheduler, + buildAuctionHistoryUpsert, + buildAuctionProjectionGuardedUpdate, + buildSideEffectApplicationUpsert, + shouldApplyAuctionProjection, + shouldProcessAuctionDurabilityPayload, +} from './auction-durability.scheduler'; + +const payload = { + actorUserId: 'user-1', + afterAuctionMongoProjection: { phase: 'sold', revision: 9 }, + auctionActionType: 'sold', + auctionHistorySequence: 4, + auctionId: 'auction-1', + auctionLifecycleId: 'life-1', + auctionStateTransitionId: 'transition-1', + committedAtRedisTimestampMS: 1780000000000, + matchId: 'match-1', + matchSideEffectMutation: { type: 'none' }, + revision: 9, + snapshotBefore: { phase: 'bidding' }, +} as const; + +describe('auction durability projection helpers', () => { + it('builds idempotent history upsert by auction and transition id', () => { + expect(buildAuctionHistoryUpsert(payload)).toEqual({ + updateOne: { + filter: { + auctionId: 'auction-1', + auctionStateTransitionId: 'transition-1', + }, + update: { + $setOnInsert: { + action: 'sold', + actorUserId: 'user-1', + auctionId: 'auction-1', + auctionLifecycleId: 'life-1', + auctionStateTransitionId: 'transition-1', + matchId: 'match-1', + matchSideEffectMutation: { type: 'none' }, + revision: 9, + sequence: 4, + snapshotBefore: { phase: 'bidding' }, + takenAt: new Date(1780000000000), + }, + }, + upsert: true, + }, + }); + }); + + it('guards projection updates by lifecycle and lower revision', () => { + expect(buildAuctionProjectionGuardedUpdate(payload)).toEqual({ + filter: { + _id: 'auction-1', + auctionLifecycleId: 'life-1', + revision: { $lt: 9 }, + }, + update: { + $set: { phase: 'sold', revision: 9 }, + }, + }); + }); + + it('builds idempotent side-effect application upsert', () => { + expect( + buildSideEffectApplicationUpsert(payload, { + type: 'syncMatchTeamsAfterComplete', + }), + ).toEqual({ + filter: { + auctionId: 'auction-1', + auctionStateTransitionId: 'transition-1', + sideEffectType: 'syncMatchTeamsAfterComplete', + }, + update: { + $setOnInsert: expect.objectContaining({ + attempts: 0, + auctionId: 'auction-1', + auctionLifecycleId: 'life-1', + auctionStateTransitionId: 'transition-1', + matchId: 'match-1', + payload: { type: 'syncMatchTeamsAfterComplete' }, + sideEffectType: 'syncMatchTeamsAfterComplete', + state: 'pending', + }), + }, + }); + }); + + 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, + }, + ])('decides whether projection can apply %#', ({ current, expected }) => { + expect(shouldApplyAuctionProjection(current, payload)).toBe(expected); + }); + + 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: {}, expected: false }, + ])( + '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']); + const scheduler = new AuctionDurabilityScheduler( + { getModel: jest.fn(), createSession: jest.fn() } as never, + { + raw: jest.fn().mockReturnValue({ sendCommand }), + } as never, + ); + + await expect( + scheduler.readDueDurabilityPayloadKeys(1000, 10), + ).resolves.toEqual(['payload-1']); + expect(sendCommand).toHaveBeenCalledWith([ + 'ZRANGEBYSCORE', + 'auction:auctionDurabilityRetryQueue', + '-inf', + '1000', + 'LIMIT', + '0', + '10', + ]); + }); + + it('parses a durability payload hash', async () => { + const scheduler = new AuctionDurabilityScheduler( + { getModel: jest.fn(), createSession: jest.fn() } as never, + { + raw: jest.fn().mockReturnValue({ + sendCommand: jest.fn().mockResolvedValue({ + broadcastStateRevision: '9', + committedAtRedisTimestampMS: '1780000000000', + payloadJson: JSON.stringify(payload), + shouldBroadcastState: '1', + }), + }), + } as never, + ); + + await expect(scheduler.readDurabilityPayload('payload-1')).resolves.toEqual( + { + ...payload, + broadcastStateRevision: 9, + shouldBroadcastState: true, + }, + ); + }); + + it('applies history and projection updates in a session', async () => { + const session = { + abortTransaction: jest.fn().mockResolvedValue(undefined), + commitTransaction: jest.fn().mockResolvedValue(undefined), + endSession: jest.fn().mockResolvedValue(undefined), + startTransaction: jest.fn(), + }; + const historyUpdateOne = jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ upsertedCount: 1 }), + }); + const auctionUpdateOne = jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ modifiedCount: 1 }), + }); + const scheduler = new AuctionDurabilityScheduler( + { + createSession: jest.fn().mockResolvedValue(session), + getModel: jest.fn((name: string) => + name === 'auctionHistory' + ? { updateOne: historyUpdateOne } + : { updateOne: auctionUpdateOne }, + ), + } as never, + { raw: jest.fn() } as never, + ); + + await scheduler.applyDurabilityPayload(payload); + + expect(session.startTransaction).toHaveBeenCalledTimes(1); + expect(historyUpdateOne).toHaveBeenCalledWith( + { + auctionId: 'auction-1', + auctionStateTransitionId: 'transition-1', + }, + expect.objectContaining({ $setOnInsert: expect.any(Object) }), + { session, upsert: true }, + ); + expect(auctionUpdateOne).toHaveBeenCalledWith( + { + _id: 'auction-1', + auctionLifecycleId: 'life-1', + revision: { $lt: 9 }, + }, + { $set: { phase: 'sold', revision: 9 } }, + { session }, + ); + expect(session.commitTransaction).toHaveBeenCalledTimes(1); + expect(session.endSession).toHaveBeenCalledTimes(1); + }); + + it('broadcasts latest Redis state when durability payload requests it', async () => { + const session = { + abortTransaction: jest.fn().mockResolvedValue(undefined), + commitTransaction: jest.fn().mockResolvedValue(undefined), + endSession: jest.fn().mockResolvedValue(undefined), + startTransaction: jest.fn(), + }; + const historyUpdateOne = jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ upsertedCount: 1 }), + }); + const auctionUpdateOne = jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ modifiedCount: 1 }), + }); + const readAuctionStateView = jest.fn().mockResolvedValue({ + auctionLifecycleId: 'life-1', + phase: 'sold', + revision: 9, + }); + const broadcastState = jest.fn(); + const scheduler = new AuctionDurabilityScheduler( + { + createSession: jest.fn().mockResolvedValue(session), + getModel: jest.fn((name: string) => + name === 'auctionHistory' + ? { updateOne: historyUpdateOne } + : { updateOne: auctionUpdateOne }, + ), + } as never, + { raw: jest.fn() } as never, + undefined, + undefined, + undefined, + { broadcastState } as never, + { readAuctionStateView } as never, + ); + + await scheduler.applyDurabilityPayload({ + ...payload, + broadcastStateRevision: 9, + shouldBroadcastState: true, + }); + + expect(readAuctionStateView).toHaveBeenCalledWith('match-1'); + expect(broadcastState).toHaveBeenCalledWith('match-1', { + auctionLifecycleId: 'life-1', + phase: 'sold', + revision: 9, + }); + }); + + it('does not broadcast stale Redis state below requested revision', async () => { + const session = { + abortTransaction: jest.fn().mockResolvedValue(undefined), + commitTransaction: jest.fn().mockResolvedValue(undefined), + endSession: jest.fn().mockResolvedValue(undefined), + startTransaction: jest.fn(), + }; + const historyUpdateOne = jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ upsertedCount: 1 }), + }); + const auctionUpdateOne = jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ modifiedCount: 1 }), + }); + const readAuctionStateView = jest.fn().mockResolvedValue({ + auctionLifecycleId: 'life-1', + phase: 'bidding', + revision: 8, + }); + const broadcastState = jest.fn(); + const scheduler = new AuctionDurabilityScheduler( + { + createSession: jest.fn().mockResolvedValue(session), + getModel: jest.fn((name: string) => + name === 'auctionHistory' + ? { updateOne: historyUpdateOne } + : { updateOne: auctionUpdateOne }, + ), + } as never, + { raw: jest.fn() } as never, + undefined, + undefined, + undefined, + { broadcastState } as never, + { readAuctionStateView } as never, + ); + + await scheduler.applyDurabilityPayload({ + ...payload, + broadcastStateRevision: 9, + shouldBroadcastState: true, + }); + + expect(readAuctionStateView).toHaveBeenCalledWith('match-1'); + expect(broadcastState).not.toHaveBeenCalled(); + }); + + it('applies undo history mutation only when projection can advance', async () => { + const session = { + abortTransaction: jest.fn().mockResolvedValue(undefined), + commitTransaction: jest.fn().mockResolvedValue(undefined), + endSession: jest.fn().mockResolvedValue(undefined), + startTransaction: jest.fn(), + }; + const historyDeleteMany = jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ deletedCount: 2 }), + }); + const historyUpdateOne = jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ upsertedCount: 1 }), + }); + const auctionUpdateOne = jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ modifiedCount: 1 }), + }); + const projectionExec = jest.fn().mockResolvedValue({ + auctionLifecycleId: 'life-1', + revision: 8, + }); + 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 { + deleteMany: historyDeleteMany, + 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, + historyMutation: { + targetHistorySequence: 2, + type: 'deleteAfterSequenceAndAppendUndo', + }, + }); + + expect(historyDeleteMany).toHaveBeenCalledWith( + { + auctionId: 'auction-1', + sequence: { $gt: 2 }, + }, + { session }, + ); + expect(historyUpdateOne).toHaveBeenCalledWith( + { + auctionId: 'auction-1', + auctionStateTransitionId: 'transition-1', + }, + expect.objectContaining({ + $setOnInsert: expect.objectContaining({ + historyMutation: { + targetHistorySequence: 2, + type: 'deleteAfterSequenceAndAppendUndo', + }, + }), + }), + { session, upsert: true }, + ); + }); + + it('skips destructive history mutation for stale payloads', async () => { + const session = { + abortTransaction: jest.fn().mockResolvedValue(undefined), + commitTransaction: jest.fn().mockResolvedValue(undefined), + endSession: jest.fn().mockResolvedValue(undefined), + startTransaction: jest.fn(), + }; + const historyDeleteMany = jest.fn(); + const historyUpdateOne = jest.fn(); + const auctionUpdateOne = jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ matchedCount: 0, modifiedCount: 0 }), + }); + 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 { + deleteMany: historyDeleteMany, + 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, + historyMutation: { + targetHistorySequence: 2, + type: 'deleteAfterSequenceAndAppendUndo', + }, + }); + + expect(historyDeleteMany).not.toHaveBeenCalled(); + expect(historyUpdateOne).not.toHaveBeenCalled(); + 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() + .mockResolvedValueOnce(['payload-1']) + .mockResolvedValueOnce({ + committedAtRedisTimestampMS: '1780000000000', + payloadJson: JSON.stringify(payload), + }) + .mockResolvedValueOnce(1) + .mockResolvedValueOnce(1); + const scheduler = new AuctionDurabilityScheduler( + { + createSession: jest.fn().mockResolvedValue(null), + getModel: jest.fn((name: string) => + name === 'auctionHistory' + ? { + updateOne: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({}), + }), + } + : { + updateOne: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({}), + }), + }, + ), + } 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(sendCommand).toHaveBeenLastCalledWith(['DEL', 'payload-1']); + }); + + it('requeues failed durability payloads with an incremented attempt count', async () => { + const sendCommand = jest + .fn() + .mockResolvedValueOnce(['payload-1']) + .mockResolvedValueOnce({ + committedAtRedisTimestampMS: '1780000000000', + payloadJson: JSON.stringify(payload), + }) + .mockResolvedValueOnce(1) + .mockResolvedValueOnce(1) + .mockResolvedValueOnce(1); + const scheduler = new AuctionDurabilityScheduler( + { createSession: jest.fn(), getModel: jest.fn() } as never, + { + getCurrentRedisTimestampMS: jest.fn().mockResolvedValue(1000), + raw: jest.fn().mockReturnValue({ sendCommand }), + } as never, + ); + jest + .spyOn(scheduler, 'applyDurabilityPayload') + .mockRejectedValue(new Error('mongo down')); + + await expect(scheduler.processDueDurabilityPayloads(10)).resolves.toEqual({ + applied: 0, + failed: 1, + skipped: 0, + }); + expect(sendCommand).toHaveBeenNthCalledWith(3, [ + 'HINCRBY', + 'payload-1', + 'attempts', + '1', + ]); + expect(sendCommand).toHaveBeenNthCalledWith(4, [ + 'HSET', + 'payload-1', + 'lastError', + 'mongo down', + 'lastFailedAtRedisTimestampMS', + '1000', + ]); + expect(sendCommand).toHaveBeenNthCalledWith(5, [ + 'ZADD', + 'auction:auctionDurabilityRetryQueue', + '6000', + 'payload-1', + ]); + }); + + it('uses bounded exponential backoff for repeated durability failures', async () => { + const sendCommand = jest + .fn() + .mockResolvedValueOnce(['payload-1']) + .mockResolvedValueOnce({ + committedAtRedisTimestampMS: '1780000000000', + payloadJson: JSON.stringify(payload), + }) + .mockResolvedValueOnce(3) + .mockResolvedValueOnce(1) + .mockResolvedValueOnce(1); + const scheduler = new AuctionDurabilityScheduler( + { createSession: jest.fn(), getModel: jest.fn() } as never, + { + getCurrentRedisTimestampMS: jest.fn().mockResolvedValue(1000), + raw: jest.fn().mockReturnValue({ sendCommand }), + } as never, + ); + jest + .spyOn(scheduler, 'applyDurabilityPayload') + .mockRejectedValue(new Error('mongo down')); + + await expect(scheduler.processDueDurabilityPayloads(10)).resolves.toEqual({ + applied: 0, + failed: 1, + skipped: 0, + }); + expect(sendCommand).toHaveBeenNthCalledWith(5, [ + 'ZADD', + 'auction:auctionDurabilityRetryQueue', + '21000', + 'payload-1', + ]); + }); + + it('moves repeatedly failing durability payloads to the dead-letter queue', async () => { + const sendCommand = jest + .fn() + .mockResolvedValueOnce(['payload-1']) + .mockResolvedValueOnce({ + committedAtRedisTimestampMS: '1780000000000', + payloadJson: JSON.stringify(payload), + }) + .mockResolvedValueOnce(10) + .mockResolvedValueOnce(1) + .mockResolvedValueOnce(1) + .mockResolvedValueOnce(1) + .mockResolvedValueOnce(1); + const scheduler = new AuctionDurabilityScheduler( + { createSession: jest.fn(), getModel: jest.fn() } as never, + { + getCurrentRedisTimestampMS: jest.fn().mockResolvedValue(1000), + raw: jest.fn().mockReturnValue({ sendCommand }), + } as never, + ); + jest + .spyOn(scheduler, 'applyDurabilityPayload') + .mockRejectedValue(new Error('side effect down')); + + await expect(scheduler.processDueDurabilityPayloads(10)).resolves.toEqual({ + applied: 0, + failed: 1, + skipped: 0, + }); + expect(sendCommand).toHaveBeenNthCalledWith(5, [ + 'ZREM', + 'auction:auctionDurabilityRetryQueue', + 'payload-1', + ]); + expect(sendCommand).toHaveBeenNthCalledWith(6, [ + 'HSET', + 'payload-1', + 'deadLetteredAtRedisTimestampMS', + '1000', + ]); + expect(sendCommand).toHaveBeenNthCalledWith(7, [ + 'ZADD', + 'auction:auctionDurabilityDeadLetterQueue', + '1000', + 'payload-1', + ]); + }); + + it('processes durability ticks only while holding the Redis leader lock', async () => { + const scheduler = new AuctionDurabilityScheduler( + { createSession: jest.fn(), getModel: jest.fn() } as never, + { + acquireTokenLock: jest.fn().mockResolvedValue(true), + releaseTokenLock: jest.fn().mockResolvedValue(true), + } as never, + ); + const processDueDurabilityPayloadsSpy = jest + .spyOn(scheduler, 'processDueDurabilityPayloads') + .mockResolvedValue({ applied: 0, failed: 0, skipped: 0 }); + + await ( + scheduler as unknown as { safeTick: () => Promise } + ).safeTick(); + + const auctionRedisService = ( + scheduler as unknown as { + auctionRedisService: { + acquireTokenLock: jest.Mock; + releaseTokenLock: jest.Mock; + }; + } + ).auctionRedisService; + const leaderLockToken = + auctionRedisService.acquireTokenLock.mock.calls[0]?.[1]; + expect(auctionRedisService.acquireTokenLock).toHaveBeenCalledWith( + 'auction:auctionDurabilityScheduler:leader', + expect.any(String), + 2500, + ); + expect(processDueDurabilityPayloadsSpy).toHaveBeenCalledWith(20); + expect(auctionRedisService.releaseTokenLock).toHaveBeenCalledWith( + 'auction:auctionDurabilityScheduler:leader', + leaderLockToken, + ); + }); + + it('skips durability ticks when another instance holds the leader lock', async () => { + const scheduler = new AuctionDurabilityScheduler( + { createSession: jest.fn(), getModel: jest.fn() } as never, + { + acquireTokenLock: jest.fn().mockResolvedValue(false), + releaseTokenLock: jest.fn().mockResolvedValue(true), + } as never, + ); + const processDueDurabilityPayloadsSpy = jest + .spyOn(scheduler, 'processDueDurabilityPayloads') + .mockResolvedValue({ applied: 0, failed: 0, skipped: 0 }); + + await ( + scheduler as unknown as { safeTick: () => Promise } + ).safeTick(); + + const auctionRedisService = ( + scheduler as unknown as { + auctionRedisService: { + releaseTokenLock: jest.Mock; + }; + } + ).auctionRedisService; + expect(processDueDurabilityPayloadsSpy).not.toHaveBeenCalled(); + expect(auctionRedisService.releaseTokenLock).not.toHaveBeenCalled(); + }); + + it('applies sync match teams side effect after durable projection', async () => { + const completePayload = { + ...payload, + afterAuctionMongoProjection: { + auctionTeams: [ + { + teamIndex: 1, + captainUserId: 'captain-1', + members: [ + { + assignedPosition: 'ADC', + memberAcquisitionBidPointAmount: 30, + userId: 'member-1', + }, + ], + }, + ], + matchSideEffectRevision: 1, + phase: 'complete', + revision: 10, + }, + auctionActionType: 'complete', + matchSideEffectMutation: { type: 'syncMatchTeamsAfterComplete' }, + revision: 10, + } as const; + const match = { + participants: [ + { + userId: { toString: () => 'captain-1' }, + preferredPositions: [{ position: 'TOP' }], + }, + { + userId: { toString: () => 'member-1' }, + preferredPositions: [{ position: 'ADC' }], + }, + ], + save: jest.fn().mockResolvedValue(undefined), + status: 'recruiting', + 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: 'completed', + }), + }); + const sideEffectUpdateOne = jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ matchedCount: 1, modifiedCount: 1 }), + }); + 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(); + const sendCommand = jest.fn().mockResolvedValue(1); + 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 }), + } as never, + { reserveForMatch } as never, + { scheduleInitialPoll } as never, + { mirrorMatchSideEffectStatus } as never, + { broadcastMatchSideEffect } as never, + ); + + await scheduler.applyDurabilityPayload(completePayload); + + expect(match.teams).toEqual([ + { + captainUserId: 'captain-1', + members: [ + { assignedPosition: 'TOP', cost: 0, userId: 'captain-1' }, + { assignedPosition: 'ADC', cost: 30, userId: 'member-1' }, + ], + name: '1팀', + teamIndex: 1, + }, + ]); + expect(match.save).toHaveBeenCalledTimes(2); + expect(reserveForMatch).toHaveBeenCalledWith(match); + expect(scheduleInitialPoll).toHaveBeenCalledWith(match); + expect(sideEffectUpdateOne).toHaveBeenCalledWith( + expect.objectContaining({ + auctionId: 'auction-1', + auctionStateTransitionId: 'transition-1', + sideEffectType: 'syncMatchTeamsAfterComplete', + }), + expect.objectContaining({ $setOnInsert: expect.any(Object) }), + { session: null, upsert: true }, + ); + expect(auctionFindOneAndUpdate).toHaveBeenNthCalledWith( + 1, + { + _id: 'auction-1', + auctionLifecycleId: 'life-1', + matchSideEffectRevision: 1, + }, + { + $inc: { matchSideEffectRevision: 1 }, + $set: { matchSideEffectStatus: 'processing' }, + $unset: { matchSideEffectError: '' }, + }, + expect.objectContaining({ returnDocument: 'after' }), + ); + expect(auctionFindOneAndUpdate).toHaveBeenNthCalledWith( + 2, + { + _id: 'auction-1', + auctionLifecycleId: 'life-1', + matchSideEffectRevision: 2, + }, + { + $inc: { matchSideEffectRevision: 1 }, + $set: { matchSideEffectStatus: 'completed' }, + $unset: { matchSideEffectError: '' }, + }, + expect.objectContaining({ returnDocument: 'after' }), + ); + expect(mirrorMatchSideEffectStatus).toHaveBeenCalledWith({ + auctionLifecycleId: 'life-1', + matchId: 'match-1', + matchSideEffectRevision: 2, + matchSideEffectStatus: 'processing', + }); + expect(mirrorMatchSideEffectStatus).toHaveBeenLastCalledWith({ + auctionLifecycleId: 'life-1', + matchId: 'match-1', + 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'"), + '11', + 'auction:match-1:liveAuctionState', + 'auction:bidRoundDeadlineQueue', + 'auction:match-1:auctionStructureState', + 'auction:match-1:appliedAuctionStateTransitionIds', + 'auction:match-1:auctionBidHistory', + 'auction:match-1:bidRequestResults', + 'auction:match-1:bidRequestResultOrder', + 'auction:match-1:auctionActionRequestResults', + 'auction:match-1:auctionActionRequestResultOrder', + 'auction:match-1:rehydrateLock', + 'auction:match-1:auctionStateTransitionLock', + 'match-1', + 'life-1', + String(7 * 24 * 60 * 60), + ]); + }); + + 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, + afterAuctionMongoProjection: { + matchSideEffectRevision: 1, + matchSideEffectStatus: 'pending', + phase: 'waiting', + revision: 10, + }, + auctionActionType: 'reset', + historyMutation: { resetMode: 'clear-history', type: 'reset' }, + matchSideEffectMutation: { type: 'resetMatchAfterAuctionReset' }, + revision: 10, + } as const; + const match = { + gameSchedule: [{ gameNumber: 1 }], + participants: [{ excluded: true }, { excluded: false }], + result: { games: [] }, + resultPollState: { state: 'polling' }, + save: jest.fn().mockResolvedValue(undefined), + status: 'team-built', + teamBuiltAt: new Date(1780000000000), + teams: [{ teamIndex: 1 }], + tournamentCodeIds: ['code-1'], + }; + const historyDeleteMany = jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ deletedCount: 3 }), + }); + const historyUpdateOne = jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ upsertedCount: 1 }), + }); + const auctionUpdateOne = jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ modifiedCount: 1 }), + }); + const projectionExec = jest.fn().mockResolvedValue({ + auctionLifecycleId: 'life-1', + revision: 9, + }); + const auctionFindById = jest.fn().mockReturnValue({ + select: jest.fn().mockReturnValue({ + session: jest.fn().mockReturnValue({ + lean: jest.fn().mockReturnValue({ exec: projectionExec }), + }), + }), + }); + 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: 'completed', + }), + }); + const sideEffectUpdateOne = jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ matchedCount: 1, modifiedCount: 1 }), + }); + const releaseFromMatch = jest.fn().mockResolvedValue(undefined); + const cancelPolling = jest.fn().mockResolvedValue(undefined); + 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 { + deleteMany: historyDeleteMany, + updateOne: historyUpdateOne, + }; + } + if (name === 'auction') { + return { + findById: auctionFindById, + 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(), + } as never, + { releaseFromMatch } as never, + { cancelPolling } as never, + { mirrorMatchSideEffectStatus } as never, + { broadcastMatchSideEffect } as never, + ); + + await scheduler.applyDurabilityPayload(resetPayload); + + expect(releaseFromMatch).toHaveBeenCalledWith(match); + expect(cancelPolling).toHaveBeenCalledWith(match); + expect(match).toMatchObject({ + gameSchedule: [], + result: undefined, + resultPollState: undefined, + status: 'recruiting', + teamBuiltAt: undefined, + teams: [], + tournamentCodeIds: [], + }); + expect(match.participants).toEqual([ + { excluded: false }, + { excluded: false }, + ]); + expect(match.save).toHaveBeenCalledTimes(1); + expect(sideEffectUpdateOne).toHaveBeenCalledWith( + expect.objectContaining({ + auctionId: 'auction-1', + auctionStateTransitionId: 'transition-1', + sideEffectType: 'resetMatchAfterAuctionReset', + }), + expect.objectContaining({ $setOnInsert: expect.any(Object) }), + { session: null, upsert: true }, + ); + expect(mirrorMatchSideEffectStatus).toHaveBeenLastCalledWith({ + auctionLifecycleId: 'life-1', + matchId: 'match-1', + matchSideEffectRevision: 3, + matchSideEffectStatus: 'completed', + }); + expect(broadcastMatchSideEffect).toHaveBeenLastCalledWith('match-1', { + auctionLifecycleId: 'life-1', + currentServerTimestampMS: 3000, + matchSideEffectRevision: 3, + matchSideEffectStatus: 'completed', + }); + }); +}); diff --git a/apps/api/src/modules/auction/auction-durability.scheduler.ts b/apps/api/src/modules/auction/auction-durability.scheduler.ts new file mode 100644 index 00000000..7163e204 --- /dev/null +++ b/apps/api/src/modules/auction/auction-durability.scheduler.ts @@ -0,0 +1,1391 @@ +import { + Injectable, + Logger, + OnModuleDestroy, + OnModuleInit, + Optional, +} from '@nestjs/common'; +import { createHash, randomUUID } from 'crypto'; +import type mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import type { + AuctionMatchSideEffectStatus, + MatchTeamMember, + Position, +} from '../global/database/schema'; +import { TournamentCodeService } from '../tournament-code/tournament-code.service'; +import { TournamentResultService } from '../tournament-result/tournament-result.service'; +import { AuctionEventBusService } from './auction-event-bus.service'; +import { + AuctionSideEffectService, + buildMatchSideEffectDelta, + buildSideEffectLeaseAcquireUpdate, + type MatchSideEffectDelta, +} from './auction-side-effect.service'; +import { AuctionRedisService } from './redis/auction-redis.service'; +import { AuctionRedisStateReaderService } from './redis/auction-redis-state-reader.service'; +import { + AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY, + 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; +const AUCTION_DURABILITY_MAX_RETRY_DELAY_MS = 60_000; +const AUCTION_DURABILITY_MAX_ATTEMPTS = 10; +const AUCTION_DURABILITY_ERROR_MESSAGE_MAX_LENGTH = 2000; +const AUCTION_DURABILITY_LEADER_LOCK_KEY = + 'auction:auctionDurabilityScheduler:leader'; +const AUCTION_DURABILITY_LEADER_LOCK_TTL_MS = 2500; +const AUCTION_REDIS_COMPLETED_RETAIN_SECONDS = 7 * 24 * 60 * 60; +const AUCTION_SIDE_EFFECT_LEASE_DURATION_MS = 30_000; +const SYNC_MATCH_TEAMS_SIDE_EFFECT_TYPE = 'syncMatchTeamsAfterComplete'; +const RESET_MATCH_SIDE_EFFECT_TYPE = 'resetMatchAfterAuctionReset'; +const UNDO_COMPLETED_MATCH_SIDE_EFFECT_TYPE = 'undoCompletedAuctionSideEffects'; + +export interface AuctionDurabilityPayload { + actorUserId?: unknown; + afterAuctionMongoProjection: Record; + auctionActionType: string; + auctionHistorySequence: number; + auctionId: unknown; + auctionLifecycleId: string; + auctionStateTransitionId: string; + committedAtRedisTimestampMS?: number; + historyMutation?: Record; + matchId: unknown; + matchSideEffectMutation: Record; + shouldBroadcastState?: boolean; + broadcastStateRevision?: number; + revision: number; + snapshotBefore: Record; +} + +export interface AuctionProjectionIdentity { + auctionLifecycleId?: string; + revision?: number; +} + +type ParsedAuctionHistoryMutation = + | { type: 'append' } + | { targetHistorySequence: number; type: 'deleteAfterSequenceAndAppendUndo' } + | { resetMode: 'clear-history' | 'preserve-audit'; type: 'reset' }; + +type ParsedMatchSideEffectMutation = + | { type: typeof SYNC_MATCH_TEAMS_SIDE_EFFECT_TYPE } + | { type: typeof RESET_MATCH_SIDE_EFFECT_TYPE } + | { type: typeof UNDO_COMPLETED_MATCH_SIDE_EFFECT_TYPE }; + +interface CleanupSideEffectMatchDocument { + competitionId?: unknown; + gameSchedule?: unknown[]; + participants: Array<{ excluded?: boolean }>; + result?: unknown; + resultPollState?: unknown; + save(): Promise; + status: string; + teamBuiltAt?: Date; + teams?: unknown[]; + tournamentCodeIds?: unknown[]; +} + +@Injectable() +export class AuctionDurabilityScheduler + implements OnModuleInit, OnModuleDestroy +{ + private readonly logger = new Logger(AuctionDurabilityScheduler.name); + private tickTimer?: NodeJS.Timeout; + private tickInProgress = false; + + constructor( + private readonly connectionService: ConnectionService, + private readonly auctionRedisService: AuctionRedisService, + @Optional() + private readonly tournamentCodeService?: TournamentCodeService, + @Optional() + private readonly tournamentResultService?: TournamentResultService, + @Optional() + private readonly auctionSideEffectService?: AuctionSideEffectService, + @Optional() + private readonly auctionEventBusService?: AuctionEventBusService, + @Optional() + private readonly auctionRedisStateReaderService?: AuctionRedisStateReaderService, + ) {} + + public onModuleInit(): void { + this.tickTimer = setInterval( + () => void this.safeTick(), + AUCTION_DURABILITY_TICK_INTERVAL_MS, + ); + this.tickTimer.unref?.(); + } + + public onModuleDestroy(): void { + if (this.tickTimer) clearInterval(this.tickTimer); + } + + public async readDueDurabilityPayloadKeys( + currentRedisTimestampMS: number, + batchLimit: number, + ): Promise { + 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) : []; + } + + public async processDueDurabilityPayloads(batchLimit: number): Promise<{ + applied: number; + failed: number; + skipped: number; + }> { + const currentRedisTimestampMS = + await this.auctionRedisService.getCurrentRedisTimestampMS(); + const payloadKeys = await this.readDueDurabilityPayloadKeys( + currentRedisTimestampMS, + batchLimit, + ); + let applied = 0; + let failed = 0; + let skipped = 0; + + for (const payloadKey of payloadKeys) { + try { + const payload = await this.readDurabilityPayload(payloadKey); + if (!payload) { + skipped += 1; + await this.clearDurabilityPayload(payloadKey); + continue; + } + 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, + ); + this.logger.warn( + `Auction durability payload failed for ${payloadKey} (${failureDisposition}): ${ + error instanceof Error ? error.message : error + }`, + ); + } + } + + return { applied, failed, skipped }; + } + + public async readDurabilityPayload( + payloadKey: string, + ): Promise { + const reply = await this.auctionRedisService + .raw() + .sendCommand(['HGETALL', payloadKey]); + const hash = parseRedisHash(reply); + const payloadJson = hash.payloadJson; + if (!payloadJson) return null; + const payload = JSON.parse(payloadJson) as AuctionDurabilityPayload; + const committedAtRedisTimestampMS = Number( + hash.committedAtRedisTimestampMS, + ); + if (Number.isFinite(committedAtRedisTimestampMS)) { + payload.committedAtRedisTimestampMS = committedAtRedisTimestampMS; + } + payload.shouldBroadcastState = hash.shouldBroadcastState === '1'; + const broadcastStateRevision = Number(hash.broadcastStateRevision); + if (Number.isFinite(broadcastStateRevision)) { + payload.broadcastStateRevision = broadcastStateRevision; + } + return payload; + } + + public async applyDurabilityPayload( + payload: AuctionDurabilityPayload, + ): Promise { + const AuctionHistoryModel = + await this.connectionService.getModel('auctionHistory'); + const AuctionModel = await this.connectionService.getModel('auction'); + const AuctionSideEffectApplicationModel = + await this.connectionService.getModel('auctionSideEffectApplication'); + const session = await this.connectionService.createSession(); + const sideEffectMutation = parseMatchSideEffectMutation( + payload.matchSideEffectMutation, + ); + + 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) + ) { + // 뒤 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; + } + } + await this.applyAuctionHistoryMutation({ + AuctionHistoryModel, + AuctionModel, + payload, + session, + }); + const projectionOperation = buildAuctionProjectionGuardedUpdate(payload); + await execMaybe( + AuctionModel.updateOne( + projectionOperation.filter as never, + projectionOperation.update as never, + { session } as never, + ), + ); + if (sideEffectMutation) { + const sideEffectOperation = buildSideEffectApplicationUpsert( + payload, + sideEffectMutation, + ); + await execMaybe( + AuctionSideEffectApplicationModel.updateOne( + sideEffectOperation.filter as never, + sideEffectOperation.update as never, + { + session, + upsert: true, + } as never, + ), + ); + } + if (session) await session.commitTransaction(); + } catch (error) { + if (session) await session.abortTransaction(); + throw error; + } finally { + if (session) await session.endSession(); + } + + await this.broadcastLatestRedisAuctionStateIfRequested(payload); + + if (sideEffectMutation) { + await this.applyMatchSideEffect(payload, sideEffectMutation); + } + } + + /** + * 노드 크래시 복구용 백업 broadcast(1차 전달 아님). + * + * 정상 경로에서는 요청을 처리한 게이트웨이(수동 전환) 또는 + * `AuctionDeadlineScheduler`(자동 만료)가 commit 직후 동기로 `state`를 방송한다. + * 이 메서드는 "방송을 하기로 한 인스턴스가 broadcast 전에 죽은" 경우를 위해 + * outbox를 처리하면서 최신 state를 한 번 더 방송하는 안전망이다. + * 이 호출은 위 try 블록의 Mongo 트랜잭션이 성공해야(early return/throw 없이) + * 도달하므로 1차 전달로 의존해서는 안 된다. 중복 방송은 클라 revision 가드로 무해. + */ + private async broadcastLatestRedisAuctionStateIfRequested( + payload: AuctionDurabilityPayload, + ): Promise { + if (!payload.shouldBroadcastState) return; + if (!this.auctionRedisStateReaderService || !this.auctionEventBusService) { + return; + } + const matchId = String(payload.matchId); + const state = + await this.auctionRedisStateReaderService.readAuctionStateView(matchId); + if (!state) return; + const stateRevision = Number(state.revision); + if ( + Number.isFinite(payload.broadcastStateRevision) && + Number.isFinite(stateRevision) && + stateRevision < Number(payload.broadcastStateRevision) + ) { + return; + } + this.auctionEventBusService.broadcastState(matchId, state); + } + + private async applyMatchSideEffect( + payload: AuctionDurabilityPayload, + mutation: ParsedMatchSideEffectMutation, + ): Promise { + if (mutation.type === SYNC_MATCH_TEAMS_SIDE_EFFECT_TYPE) { + await this.applySyncMatchTeamsSideEffect(payload, mutation); + return; + } + if (mutation.type === RESET_MATCH_SIDE_EFFECT_TYPE) { + await this.applyResetMatchSideEffect(payload, mutation); + return; + } + if (mutation.type === UNDO_COMPLETED_MATCH_SIDE_EFFECT_TYPE) { + await this.applyUndoCompletedMatchSideEffect(payload, mutation); + } + } + + private async applySyncMatchTeamsSideEffect( + payload: AuctionDurabilityPayload, + mutation: ParsedMatchSideEffectMutation, + ): Promise { + if (!this.tournamentCodeService || !this.tournamentResultService) { + throw new Error('Auction side-effect services are not available.'); + } + + const AuctionModel = await this.connectionService.getModel('auction'); + const AuctionSideEffectApplicationModel = + await this.connectionService.getModel('auctionSideEffectApplication'); + const MatchModel = await this.connectionService.getModel('match'); + const currentRedisTimestampMS = + await this.auctionRedisService.getCurrentRedisTimestampMS(); + const ownerToken = randomUUID(); + const identity = buildSideEffectApplicationIdentityFromPayload( + payload, + mutation, + ); + const leaseResult = await execMaybe( + AuctionSideEffectApplicationModel.updateOne( + { + ...identity, + $or: [ + { state: 'pending' }, + { state: 'failed' }, + { + state: 'processing', + processingLeaseExpiresAtTimestampMS: { + $lte: currentRedisTimestampMS, + }, + }, + ], + } as never, + buildSideEffectLeaseAcquireUpdate({ + currentRedisTimestampMS, + leaseDurationMS: AUCTION_SIDE_EFFECT_LEASE_DURATION_MS, + ownerToken, + }) as never, + ), + ); + if (!hasMatchedDocument(leaseResult)) return; + + const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus( + { + AuctionModel, + currentServerTimestampMS: currentRedisTimestampMS, + expectedMatchSideEffectRevision: Number( + payload.afterAuctionMongoProjection.matchSideEffectRevision ?? 0, + ), + payload, + status: 'processing', + }, + ); + if (!processingDelta) return; + 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 }; + }>; + save(): Promise; + status: string; + teamBuiltAt?: Date; + teams: ReturnType; + } | null; + 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(); + await execMaybe( + AuctionSideEffectApplicationModel.updateOne( + identity as never, + { + $set: { + completedAtTimestampMS, + state: 'completed', + }, + $unset: { + lastError: '', + processingLeaseExpiresAtTimestampMS: '', + processingOwnerToken: '', + processingStartedAtTimestampMS: '', + }, + } as never, + ), + ); + await this.persistAndBroadcastMatchSideEffectStatus({ + AuctionModel, + currentServerTimestampMS: completedAtTimestampMS, + errorMessage: undefined, + expectedMatchSideEffectRevision, + payload, + status: 'completed', + }); + await this.expireCompletedAuctionRedisRuntime(payload); + } catch (error) { + const failureTimestampMS = + await this.auctionRedisService.getCurrentRedisTimestampMS(); + await execMaybe( + AuctionSideEffectApplicationModel.updateOne( + identity as never, + { + $set: { + lastError: error instanceof Error ? error.message : String(error), + state: 'failed', + }, + $unset: { + processingLeaseExpiresAtTimestampMS: '', + processingOwnerToken: '', + processingStartedAtTimestampMS: '', + }, + } as never, + ), + ); + await this.persistAndBroadcastMatchSideEffectStatus({ + AuctionModel, + currentServerTimestampMS: failureTimestampMS, + errorMessage: error instanceof Error ? error.message : String(error), + expectedMatchSideEffectRevision, + payload, + status: 'failed', + }); + throw error; + } + } + + private async applyStaleAppendHistoryRecovery(params: { + AuctionHistoryModel: { + findOne?: (...args: never[]) => unknown; + updateOne: (...args: never[]) => unknown; + }; + payload: AuctionDurabilityPayload; + session: mongoose.ClientSession | null | undefined; + }): Promise { + 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 | { exec(): Promise }, + ); + } + + private async isAppendHistoryInvalidatedByLaterDestructiveMutation(params: { + AuctionHistoryModel: { + findOne?: (...args: never[]) => unknown; + }; + payload: AuctionDurabilityPayload; + session: mongoose.ClientSession | null | undefined; + }): Promise { + 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 }).exec() + : await Promise.resolve(leaned); + return Boolean(result); + } + + private async applyResetMatchSideEffect( + payload: AuctionDurabilityPayload, + mutation: ParsedMatchSideEffectMutation, + ): Promise { + await this.applyMatchCleanupSideEffect({ + mutation, + payload, + updateMatch: async (match) => { + await this.tournamentCodeService?.releaseFromMatch(match as never); + await this.tournamentResultService?.cancelPolling(match as never); + match.status = 'recruiting'; + match.teams = []; + match.tournamentCodeIds = []; + match.gameSchedule = []; + match.participants.forEach((participant) => { + participant.excluded = false; + }); + match.teamBuiltAt = undefined; + match.result = undefined; + match.resultPollState = undefined; + await match.save(); + }, + }); + } + + private async applyUndoCompletedMatchSideEffect( + payload: AuctionDurabilityPayload, + mutation: ParsedMatchSideEffectMutation, + ): Promise { + await this.applyMatchCleanupSideEffect({ + mutation, + payload, + updateMatch: async (match) => { + await this.tournamentCodeService?.releaseFromMatch(match as never); + await this.tournamentResultService?.cancelPolling(match as never); + match.status = 'team-built'; + match.result = undefined; + match.resultPollState = undefined; + await match.save(); + }, + }); + } + + private async applyMatchCleanupSideEffect(params: { + mutation: ParsedMatchSideEffectMutation; + payload: AuctionDurabilityPayload; + updateMatch: (match: CleanupSideEffectMatchDocument) => Promise; + }): Promise { + if (!this.tournamentCodeService || !this.tournamentResultService) { + throw new Error('Auction side-effect services are not available.'); + } + + const AuctionModel = await this.connectionService.getModel('auction'); + const AuctionSideEffectApplicationModel = + await this.connectionService.getModel('auctionSideEffectApplication'); + const MatchModel = await this.connectionService.getModel('match'); + const currentRedisTimestampMS = + await this.auctionRedisService.getCurrentRedisTimestampMS(); + const ownerToken = randomUUID(); + const identity = buildSideEffectApplicationIdentityFromPayload( + params.payload, + params.mutation, + ); + const leaseResult = await execMaybe( + AuctionSideEffectApplicationModel.updateOne( + { + ...identity, + $or: [ + { state: 'pending' }, + { state: 'failed' }, + { + state: 'processing', + processingLeaseExpiresAtTimestampMS: { + $lte: currentRedisTimestampMS, + }, + }, + ], + } as never, + buildSideEffectLeaseAcquireUpdate({ + currentRedisTimestampMS, + leaseDurationMS: AUCTION_SIDE_EFFECT_LEASE_DURATION_MS, + ownerToken, + }) as never, + ), + ); + if (!hasMatchedDocument(leaseResult)) return; + + const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus( + { + AuctionModel, + currentServerTimestampMS: currentRedisTimestampMS, + expectedMatchSideEffectRevision: Number( + params.payload.afterAuctionMongoProjection.matchSideEffectRevision ?? + 0, + ), + payload: params.payload, + status: 'processing', + }, + ); + if (!processingDelta) return; + const expectedMatchSideEffectRevision = + processingDelta.matchSideEffectRevision; + + try { + const match = (await execMaybe( + MatchModel.findById(params.payload.matchId) as never, + )) as CleanupSideEffectMatchDocument | null; + 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 = + await this.auctionRedisService.getCurrentRedisTimestampMS(); + await execMaybe( + AuctionSideEffectApplicationModel.updateOne( + identity as never, + { + $set: { + completedAtTimestampMS, + state: 'completed', + }, + $unset: { + lastError: '', + processingLeaseExpiresAtTimestampMS: '', + processingOwnerToken: '', + processingStartedAtTimestampMS: '', + }, + } as never, + ), + ); + await this.persistAndBroadcastMatchSideEffectStatus({ + AuctionModel, + currentServerTimestampMS: completedAtTimestampMS, + errorMessage: undefined, + expectedMatchSideEffectRevision, + payload: params.payload, + status: 'completed', + }); + } catch (error) { + const failureTimestampMS = + await this.auctionRedisService.getCurrentRedisTimestampMS(); + const errorMessage = + error instanceof Error ? error.message : String(error); + await execMaybe( + AuctionSideEffectApplicationModel.updateOne( + identity as never, + { + $set: { + lastError: errorMessage, + state: 'failed', + }, + $unset: { + processingLeaseExpiresAtTimestampMS: '', + processingOwnerToken: '', + processingStartedAtTimestampMS: '', + }, + } as never, + ), + ); + await this.persistAndBroadcastMatchSideEffectStatus({ + AuctionModel, + currentServerTimestampMS: failureTimestampMS, + errorMessage, + expectedMatchSideEffectRevision, + payload: params.payload, + status: 'failed', + }); + throw error; + } + } + + private async applyAuctionHistoryMutation(params: { + AuctionHistoryModel: { + deleteMany?: (...args: never[]) => unknown; + updateOne: (...args: never[]) => unknown; + }; + AuctionModel: { + findById?: (...args: never[]) => { + lean?: () => { exec?: () => Promise }; + session?: (...args: never[]) => { + lean?: () => { exec?: () => Promise }; + select?: (...args: never[]) => { + lean?: () => { exec?: () => Promise }; + session?: (...args: never[]) => unknown; + }; + }; + select?: (...args: never[]) => { + lean?: () => { exec?: () => Promise }; + session?: (...args: never[]) => unknown; + }; + }; + }; + payload: AuctionDurabilityPayload; + session: mongoose.ClientSession | null | undefined; + }): Promise { + const mutation = parseAuctionHistoryMutation( + params.payload.historyMutation, + ); + if (isDestructiveHistoryMutation(mutation)) { + if (mutation.type === 'deleteAfterSequenceAndAppendUndo') { + if (!params.AuctionHistoryModel.deleteMany) { + throw new Error('Auction history deleteMany is not available.'); + } + await execMaybe( + params.AuctionHistoryModel.deleteMany( + { + auctionId: params.payload.auctionId, + sequence: { $gt: mutation.targetHistorySequence }, + } as never, + { session: params.session } as never, + ) as Promise | { exec(): Promise }, + ); + } + if (mutation.type === 'reset' && mutation.resetMode === 'clear-history') { + if (!params.AuctionHistoryModel.deleteMany) { + throw new Error('Auction history deleteMany is not available.'); + } + await execMaybe( + params.AuctionHistoryModel.deleteMany( + { + auctionId: params.payload.auctionId, + } as never, + { session: params.session } as never, + ) as Promise | { exec(): Promise }, + ); + } + } + + 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 | { exec(): Promise }, + ); + } + + private async persistAndBroadcastMatchSideEffectStatus(params: { + AuctionModel: { + findOneAndUpdate( + filter: never, + update: never, + options: never, + ): Promise | { exec(): Promise }; + }; + currentServerTimestampMS: number; + errorMessage?: string; + expectedMatchSideEffectRevision: number; + payload: AuctionDurabilityPayload; + status: AuctionMatchSideEffectStatus; + }): Promise { + const updatedAuction = (await execMaybe( + params.AuctionModel.findOneAndUpdate( + { + _id: params.payload.auctionId, + auctionLifecycleId: params.payload.auctionLifecycleId, + matchSideEffectRevision: params.expectedMatchSideEffectRevision, + } as never, + { + $inc: { matchSideEffectRevision: 1 }, + $set: { + ...(params.errorMessage + ? { matchSideEffectError: params.errorMessage } + : {}), + matchSideEffectStatus: params.status, + }, + ...(params.errorMessage + ? {} + : { $unset: { matchSideEffectError: '' } }), + } as never, + { + projection: { + auctionLifecycleId: 1, + matchSideEffectRevision: 1, + matchSideEffectStatus: 1, + }, + returnDocument: 'after', + } as never, + ), + )) as { + auctionLifecycleId?: string; + matchSideEffectRevision?: number; + matchSideEffectStatus?: AuctionMatchSideEffectStatus; + } | null; + if (!updatedAuction?.auctionLifecycleId) return null; + + const delta = buildMatchSideEffectDelta({ + auctionLifecycleId: updatedAuction.auctionLifecycleId, + currentServerTimestampMS: params.currentServerTimestampMS, + matchSideEffectRevision: Number( + updatedAuction.matchSideEffectRevision ?? 0, + ), + matchSideEffectStatus: + updatedAuction.matchSideEffectStatus ?? params.status, + }); + + await this.auctionSideEffectService?.mirrorMatchSideEffectStatus({ + auctionLifecycleId: delta.auctionLifecycleId, + matchId: String(params.payload.matchId), + matchSideEffectRevision: delta.matchSideEffectRevision, + matchSideEffectStatus: delta.matchSideEffectStatus, + }); + this.auctionEventBusService?.broadcastMatchSideEffect( + String(params.payload.matchId), + delta, + ); + return delta; + } + + private async safeTick(): Promise { + if (this.tickInProgress) return; + this.tickInProgress = true; + const leaderLockToken = randomUUID(); + let leaderLockAcquired = false; + try { + leaderLockAcquired = await this.auctionRedisService.acquireTokenLock( + AUCTION_DURABILITY_LEADER_LOCK_KEY, + leaderLockToken, + AUCTION_DURABILITY_LEADER_LOCK_TTL_MS, + ); + if (!leaderLockAcquired) return; + await this.processDueDurabilityPayloads(AUCTION_DURABILITY_BATCH_LIMIT); + } catch (error) { + this.logger.warn( + `Auction durability tick failed: ${ + error instanceof Error ? error.message : error + }`, + ); + } finally { + if (leaderLockAcquired) { + await this.auctionRedisService.releaseTokenLock( + AUCTION_DURABILITY_LEADER_LOCK_KEY, + leaderLockToken, + ); + } + this.tickInProgress = false; + } + } + + private async clearDurabilityPayload(payloadKey: string): Promise { + await this.auctionRedisService + .raw() + .sendCommand(['ZREM', AUCTION_DURABILITY_RETRY_QUEUE_KEY, payloadKey]); + await this.auctionRedisService.raw().sendCommand(['DEL', payloadKey]); + } + + private async requeueDurabilityPayload( + payloadKey: string, + retryAtRedisTimestampMS: number, + ): Promise { + await this.auctionRedisService + .raw() + .sendCommand([ + 'ZADD', + AUCTION_DURABILITY_RETRY_QUEUE_KEY, + String(retryAtRedisTimestampMS), + payloadKey, + ]); + } + + private async recordDurabilityPayloadFailure( + payloadKey: string, + currentRedisTimestampMS: number, + error: unknown, + ): Promise<'dead-lettered' | 'requeued'> { + const errorMessage = formatErrorMessageForRedis(error); + 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), + ]); + + 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, + ]); + return 'dead-lettered'; + } + + await this.requeueDurabilityPayload( + payloadKey, + currentRedisTimestampMS + calculateDurabilityRetryDelayMS(attempts), + ); + return 'requeued'; + } + + private async expireCompletedAuctionRedisRuntime( + payload: AuctionDurabilityPayload, + ): Promise { + 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), + ]); + } +} + +export function buildAuctionHistoryUpsert(payload: AuctionDurabilityPayload) { + return { + updateOne: { + filter: { + auctionId: payload.auctionId, + auctionStateTransitionId: payload.auctionStateTransitionId, + }, + update: { + $setOnInsert: { + action: payload.auctionActionType, + actorUserId: payload.actorUserId, + auctionId: payload.auctionId, + auctionLifecycleId: payload.auctionLifecycleId, + auctionStateTransitionId: payload.auctionStateTransitionId, + historyMutation: payload.historyMutation, + matchId: payload.matchId, + matchSideEffectMutation: payload.matchSideEffectMutation, + revision: payload.revision, + sequence: payload.auctionHistorySequence, + snapshotBefore: payload.snapshotBefore, + takenAt: new Date(payload.committedAtRedisTimestampMS ?? 0), + }, + }, + upsert: true, + }, + }; +} + +export function parseAuctionHistoryMutation( + mutation: unknown, +): ParsedAuctionHistoryMutation { + if (!mutation || typeof mutation !== 'object') return { type: 'append' }; + const record = mutation as Record; + if (record.type === 'deleteAfterSequenceAndAppendUndo') { + const targetHistorySequence = Number(record.targetHistorySequence); + if (!Number.isFinite(targetHistorySequence) || targetHistorySequence < 0) { + throw new Error('Invalid undo history mutation target sequence.'); + } + return { + targetHistorySequence, + type: 'deleteAfterSequenceAndAppendUndo', + }; + } + if (record.type === 'reset') { + const resetMode = + record.resetMode === 'preserve-audit' + ? 'preserve-audit' + : 'clear-history'; + return { resetMode, type: 'reset' }; + } + return { type: 'append' }; +} + +function isDestructiveHistoryMutation( + mutation: ParsedAuctionHistoryMutation, +): boolean { + return ( + mutation.type === 'deleteAfterSequenceAndAppendUndo' || + (mutation.type === 'reset' && mutation.resetMode === 'clear-history') + ); +} + +async function readAuctionProjectionIdentityForMutation( + AuctionModel: { + findById?: (...args: never[]) => unknown; + }, + auctionId: unknown, + session: mongoose.ClientSession | null | undefined, +): Promise { + if (!AuctionModel.findById) return {}; + const query = AuctionModel.findById(auctionId as never); + const selected = + query && typeof query === 'object' && 'select' in query + ? (query as { select: (...args: never[]) => unknown }).select({ + auctionLifecycleId: 1, + revision: 1, + } as never) + : query; + const scoped = + selected && typeof selected === 'object' && 'session' in selected + ? (selected as { session: (...args: never[]) => unknown }).session( + session as never, + ) + : selected; + const leaned = + scoped && typeof scoped === 'object' && 'lean' in scoped + ? (scoped as { lean: () => unknown }).lean() + : scoped; + const projection = + leaned && typeof leaned === 'object' && 'exec' in leaned + ? await (leaned as { exec: () => Promise }).exec() + : await Promise.resolve(leaned); + if (!projection || typeof projection !== 'object') return {}; + const record = projection as Record; + return { + auctionLifecycleId: + typeof record.auctionLifecycleId === 'string' + ? record.auctionLifecycleId + : undefined, + revision: + typeof record.revision === 'number' + ? record.revision + : Number(record.revision), + }; +} + +export function buildAuctionProjectionGuardedUpdate( + payload: AuctionDurabilityPayload, +) { + return { + filter: { + _id: payload.auctionId, + auctionLifecycleId: payload.auctionLifecycleId, + revision: { $lt: payload.revision }, + }, + update: { + $set: payload.afterAuctionMongoProjection, + }, + }; +} + +export function shouldApplyAuctionProjection( + current: AuctionProjectionIdentity, + payload: Pick, +): boolean { + if (current.auctionLifecycleId !== payload.auctionLifecycleId) return false; + return (current.revision ?? -1) < payload.revision; +} + +export function shouldProcessAuctionDurabilityPayload( + current: AuctionProjectionIdentity, + payload: Pick, +): boolean { + if (current.auctionLifecycleId !== payload.auctionLifecycleId) return false; + return (current.revision ?? -1) <= payload.revision; +} + +export function buildSideEffectApplicationUpsert( + payload: AuctionDurabilityPayload, + mutation: ParsedMatchSideEffectMutation, +) { + const identity = buildSideEffectApplicationIdentityFromPayload( + payload, + mutation, + ); + return { + filter: identity, + update: { + $setOnInsert: { + ...identity, + auctionLifecycleId: payload.auctionLifecycleId, + matchId: payload.matchId, + attempts: 0, + payload: mutation, + payloadChecksum: hashStableJson(mutation), + state: 'pending', + }, + }, + }; +} + +function parseMatchSideEffectMutation( + value: Record | undefined, +): ParsedMatchSideEffectMutation | null { + if (value?.type === SYNC_MATCH_TEAMS_SIDE_EFFECT_TYPE) { + return { type: SYNC_MATCH_TEAMS_SIDE_EFFECT_TYPE }; + } + if (value?.type === RESET_MATCH_SIDE_EFFECT_TYPE) { + return { type: RESET_MATCH_SIDE_EFFECT_TYPE }; + } + if (value?.type === UNDO_COMPLETED_MATCH_SIDE_EFFECT_TYPE) { + return { type: UNDO_COMPLETED_MATCH_SIDE_EFFECT_TYPE }; + } + return null; +} + +function buildSideEffectApplicationIdentityFromPayload( + payload: AuctionDurabilityPayload, + mutation: ParsedMatchSideEffectMutation, +) { + return { + auctionId: payload.auctionId, + auctionStateTransitionId: payload.auctionStateTransitionId, + sideEffectType: mutation.type, + }; +} + +function hashStableJson(value: unknown): string { + return createHash('sha256') + .update( + JSON.stringify( + value, + Object.keys(value as Record).sort(), + ), + ) + .digest('hex'); +} + +function hasMatchedDocument(result: unknown): boolean { + if (!result || typeof result !== 'object') return false; + const record = result as Record; + const matchedCount = Number(record.matchedCount ?? record.modifiedCount ?? 0); + return matchedCount > 0; +} + +function buildMatchTeamsFromProjection( + projection: Record, + match: { + participants: Array<{ + preferredPositions?: Array<{ position?: string }>; + userId: { toString(): string }; + }>; + }, +) { + const auctionTeams = Array.isArray(projection.auctionTeams) + ? (projection.auctionTeams as Array>) + : []; + const participantByUserId = new Map( + match.participants.map((participant) => [ + participant.userId.toString(), + participant, + ]), + ); + + return auctionTeams.map((team) => { + const teamIndex = Number(team.teamIndex); + const captainUserId = team.captainUserId as MatchTeamMember['userId']; + const captain = participantByUserId.get(captainUserId.toString()); + const rawMembers = Array.isArray(team.members) + ? (team.members as Array>) + : []; + const members: MatchTeamMember[] = [ + { + assignedPosition: + (captain?.preferredPositions?.[0]?.position as + | Position + | undefined) ?? 'MID', + cost: 0, + userId: captainUserId, + }, + ...rawMembers + .filter( + (member) => member.userId?.toString() !== captainUserId.toString(), + ) + .map((member) => ({ + assignedPosition: (member.assignedPosition ?? 'MID') as Position, + cost: Number(member.memberAcquisitionBidPointAmount ?? 0), + userId: member.userId as MatchTeamMember['userId'], + })), + ]; + + return { + captainUserId, + members, + name: `${teamIndex}팀`, + teamIndex, + }; + }); +} + +function parseRedisHash(reply: unknown): Record { + if (!reply) return {}; + if (Array.isArray(reply)) { + const result: Record = {}; + for (let index = 0; index < reply.length; index += 2) { + result[String(reply[index])] = String(reply[index + 1]); + } + return result; + } + if (typeof reply === 'object') { + return Object.fromEntries( + Object.entries(reply as Record).map(([key, value]) => [ + key, + String(value), + ]), + ); + } + return {}; +} + +function formatErrorMessageForRedis(error: unknown): string { + const message = error instanceof Error ? error.message : String(error); + return message.slice(0, AUCTION_DURABILITY_ERROR_MESSAGE_MAX_LENGTH); +} + +function calculateDurabilityRetryDelayMS(attempts: number): number { + if (!Number.isFinite(attempts) || attempts <= 1) { + return AUCTION_DURABILITY_RETRY_DELAY_MS; + } + return Math.min( + AUCTION_DURABILITY_MAX_RETRY_DELAY_MS, + AUCTION_DURABILITY_RETRY_DELAY_MS * 2 ** (attempts - 1), + ); +} + +async function execMaybe( + queryOrPromise: Promise | { exec(): Promise }, +) { + if ( + queryOrPromise && + typeof (queryOrPromise as { exec?: unknown }).exec === 'function' + ) { + return (queryOrPromise as { exec(): Promise }).exec(); + } + return queryOrPromise; +} diff --git a/apps/api/src/modules/auction/auction-event-bus.service.ts b/apps/api/src/modules/auction/auction-event-bus.service.ts new file mode 100644 index 00000000..f4032730 --- /dev/null +++ b/apps/api/src/modules/auction/auction-event-bus.service.ts @@ -0,0 +1,28 @@ +import { Injectable } from '@nestjs/common'; +import type { Namespace } from 'socket.io'; +import type { AuctionStateResponse } from './auction.service'; +import type { MatchSideEffectDelta } from './auction-side-effect.service'; +import { serializeRealtimeAuction } from './auction-realtime-serializer'; + +@Injectable() +export class AuctionEventBusService { + private auctionNamespace?: Namespace; + + public attachAuctionNamespace(namespace: Namespace): void { + this.auctionNamespace = namespace; + } + + public broadcastMatchSideEffect( + matchId: string, + delta: MatchSideEffectDelta, + ): void { + this.auctionNamespace?.to(matchId).emit('match-side-effect', delta); + } + + public broadcastState(matchId: string, state: AuctionStateResponse): void { + this.auctionNamespace?.to(matchId).emit( + 'state', + serializeRealtimeAuction(state), + ); + } +} diff --git a/apps/api/src/modules/auction/auction-realtime-serializer.ts b/apps/api/src/modules/auction/auction-realtime-serializer.ts new file mode 100644 index 00000000..2a3c75de --- /dev/null +++ b/apps/api/src/modules/auction/auction-realtime-serializer.ts @@ -0,0 +1,103 @@ +import type { AuctionStateResponse } from './auction.service'; + +export function serializeRealtimeAuction(auction: AuctionStateResponse) { + const serialized = JSON.parse(JSON.stringify(auction)) as Record< + string, + unknown + >; + const auctionPlayerOrder = getRecordArray( + serialized.auctionPlayerOrder ?? serialized.order, + ); + const currentAuctionPlayerOrderIndex = Number( + serialized.currentAuctionPlayerOrderIndex ?? serialized.currentIndex ?? 0, + ); + const currentBidRoundPlayerUserId = + typeof serialized.currentBidRoundPlayerUserId === 'string' + ? serialized.currentBidRoundPlayerUserId + : getStringField( + auctionPlayerOrder[currentAuctionPlayerOrderIndex], + 'userId', + ); + + if (Array.isArray(serialized.auctionPlayerOrder)) { + serialized.auctionPlayerOrder = auctionPlayerOrder.map((player) => + serializeRealtimeAuctionPlayer(player, currentBidRoundPlayerUserId), + ); + } else if (Array.isArray(serialized.order)) { + serialized.order = auctionPlayerOrder.map((player) => + serializeRealtimeAuctionPlayer(player, currentBidRoundPlayerUserId), + ); + } + + const passedAuctionPlayerQueue = getRecordArray( + serialized.passedAuctionPlayerQueue ?? serialized.passedQueue, + ); + if (Array.isArray(serialized.passedAuctionPlayerQueue)) { + serialized.passedAuctionPlayerQueue = passedAuctionPlayerQueue.map( + (player) => + serializeRealtimeAuctionPlayer(player, currentBidRoundPlayerUserId), + ); + } else if (Array.isArray(serialized.passedQueue)) { + serialized.passedQueue = passedAuctionPlayerQueue.map((player) => + serializeRealtimeAuctionPlayer(player, currentBidRoundPlayerUserId), + ); + } + + if ('auctionPlayerOrder' in serialized) delete serialized.order; + if ('auctionTeams' in serialized) delete serialized.teams; + if ('passedAuctionPlayerQueue' in serialized) delete serialized.passedQueue; + if ('auctionBidHistory' in serialized) delete serialized.bids; + if ('maximumBidRoundDurationSeconds' in serialized) { + delete serialized.maxTimerSeconds; + } + if ('bidRoundExtensionSeconds' in serialized) { + delete serialized.bidExtensionSeconds; + } + if ('initialTeamBidPointAmount' in serialized) { + delete serialized.initialPoints; + } + if ('topTierAuctionPriorityThreshold' in serialized) { + delete serialized.topTierThreshold; + } + if ('manualTopTierAuctionPriorityUserIds' in serialized) { + delete serialized.manualTopTierUserIds; + } + + return serialized; +} + +function serializeRealtimeAuctionPlayer( + player: Record, + currentBidRoundPlayerUserId?: string, +) { + if (getStringField(player, 'userId') === currentBidRoundPlayerUserId) { + return player; + } + + const { + masteries: _masteries, + puuid: _puuid, + recentStatsSummary: _recentStatsSummary, + tierHistory: _tierHistory, + ...lightweightPlayer + } = player; + + return lightweightPlayer; +} + +function getRecordArray(value: unknown): Array> { + return Array.isArray(value) + ? value.filter( + (item): item is Record => + typeof item === 'object' && item !== null, + ) + : []; +} + +function getStringField( + value: Record | undefined, + fieldName: string, +): string | undefined { + const fieldValue = value?.[fieldName]; + return typeof fieldValue === 'string' ? fieldValue : undefined; +} diff --git a/apps/api/src/modules/auction/auction-rejection.spec.ts b/apps/api/src/modules/auction/auction-rejection.spec.ts new file mode 100644 index 00000000..79b6316a --- /dev/null +++ b/apps/api/src/modules/auction/auction-rejection.spec.ts @@ -0,0 +1,82 @@ +import { + AUCTION_REJECTION_REASON, + isAuctionResyncRecommended, + resolveAuctionRejectionReason, +} from './auction-rejection'; + +describe('resolveAuctionRejectionReason', () => { + it('maps the internal CONFLICT code to the descriptive transition reason', () => { + expect(resolveAuctionRejectionReason('CONFLICT')).toBe( + AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_LIVE_STATE_CHANGED_BEFORE_APPLY, + ); + }); + + it('maps internal bid codes to descriptive bid reasons', () => { + expect(resolveAuctionRejectionReason('EXPIRED')).toBe( + AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_BID_ROUND_DEADLINE_PASSED, + ); + expect(resolveAuctionRejectionReason('TOO_LOW')).toBe( + AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_AMOUNT_NOT_HIGHER_THAN_CURRENT_HIGHEST, + ); + }); + + it('maps known BadRequest messages without a structured code', () => { + expect( + resolveAuctionRejectionReason(undefined, 'Cannot advance from current phase.'), + ).toBe( + AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE, + ); + }); + + it('falls back via the message when the code carries the full sentence', () => { + // 구조 전환 경로는 code 자리에 message 문장이 들어올 수 있다. + expect( + resolveAuctionRejectionReason('Auction is not in bidding phase.'), + ).toBe( + AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE, + ); + }); + + it('treats internal coordination codes as retryable', () => { + expect(resolveAuctionRejectionReason('ACTION_REQUEST_LEASE_EXPIRED')).toBe( + AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_REQUEST_COORDINATION_RETRYABLE, + ); + expect(resolveAuctionRejectionReason('INVALID_DEADLINE_MODE')).toBe( + AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_REQUEST_COORDINATION_RETRYABLE, + ); + }); + + it('falls back to the unrecognized reason for unknown input', () => { + expect(resolveAuctionRejectionReason('SOMETHING_NEW', 'weird')).toBe( + AUCTION_REJECTION_REASON.AUCTION_REQUEST_REJECTED_FOR_UNRECOGNIZED_REASON, + ); + }); +}); + +describe('isAuctionResyncRecommended', () => { + it('recommends resync for stale-view rejections', () => { + expect( + isAuctionResyncRecommended( + AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_LIVE_STATE_CHANGED_BEFORE_APPLY, + ), + ).toBe(true); + expect( + isAuctionResyncRecommended( + AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_BID_ROUND_DEADLINE_PASSED, + ), + ).toBe(true); + }); + + it('does not recommend resync for genuine constraint rejections', () => { + expect( + isAuctionResyncRecommended( + AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_TEAM_ROSTER_FULL, + ), + ).toBe(false); + expect( + isAuctionResyncRecommended( + AUCTION_REJECTION_REASON.AUCTION_REQUEST_REJECTED_FOR_UNRECOGNIZED_REASON, + ), + ).toBe(false); + }); +}); diff --git a/apps/api/src/modules/auction/auction-rejection.ts b/apps/api/src/modules/auction/auction-rejection.ts new file mode 100644 index 00000000..8a20e67c --- /dev/null +++ b/apps/api/src/modules/auction/auction-rejection.ts @@ -0,0 +1,170 @@ +/** + * 경매 거부(rejection)를 클라이언트에 알릴 때 쓰는 "설명적 거부코드" 체계. + * + * 배경: + * - 내부 Lua/서비스는 `CONFLICT`, `EXPIRED`, `TOO_LOW` 같은 짧은 코드를 쓴다. + * 이 코드들은 구현 디테일이고, 그대로 클라/운영자에게 노출하면 "무엇이 왜 + * 거부됐는지"를 알기 어렵다(특히 `CONFLICT`는 원인이 광범위하다). + * - 그래서 ack의 `code`/`message`는 그대로 두되(진단/하위호환), 별도로 + * `auctionRejectionReason`이라는 **맥락을 코드 이름에 담은 안정적 식별자**를 + * 함께 내려준다. 클라는 이 reason을 사람이 읽는 문구로 매핑한다(프론트 사전). + * + * 명명 규칙: + * - 다소 길어지더라도 "무엇이(BID/AUCTION_TRANSITION) + 왜(BECAUSE_...)"를 + * 이름만으로 알 수 있게 풀어쓴다. + * + * resync 권장 여부: + * - `AUCTION_RESYNC_RECOMMENDED_REASONS`에 속한 reason은 "클라가 본 상태가 이미 + * 바뀌었다(낙관적 동시성 충돌/만료/단계 전이)"는 신호다. 이 경우 클라는 최신 + * state로 rebaseline한 뒤 (구조 액션이라면) 1회 재시도하는 것이 안전하다. + * - 반대로 정원 초과/포인트 부족처럼 "상태를 새로고침해도 결과가 같은" 거부는 + * resync 권장 대상이 아니다(재시도해도 또 거부됨). + */ + +export const AUCTION_REJECTION_REASON = { + // === 구조 전환(낙찰/유찰/다음/입찰오픈) === + /** 내가 본 revision/phase/선수가 commit 직전 이미 바뀜(낙관적 동시성 충돌, 내부 `CONFLICT`). */ + AUCTION_TRANSITION_REJECTED_BECAUSE_LIVE_STATE_CHANGED_BEFORE_APPLY: + 'AUCTION_TRANSITION_REJECTED_BECAUSE_LIVE_STATE_CHANGED_BEFORE_APPLY', + /** 입찰 단계가 아닌데 입찰 단계 전환을 시도함(이미 sold/passed/presenting 등). */ + AUCTION_TRANSITION_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE: + 'AUCTION_TRANSITION_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE', + /** 현재 단계에서 "다음"으로 진행할 수 없음(sold/passed/presenting이 아님 — 보통 이미 진행됨). */ + AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE: + 'AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE', + /** 낙찰 처리할 유효한 최고 입찰이 없음(만료 처리로 이미 정리됐을 수 있음). */ + AUCTION_TRANSITION_REJECTED_BECAUSE_NO_WINNING_BID_TO_MARK_SOLD: + 'AUCTION_TRANSITION_REJECTED_BECAUSE_NO_WINNING_BID_TO_MARK_SOLD', + /** 진행 중인 입찰이 있는 선수를 유찰 처리하려 함. */ + AUCTION_TRANSITION_REJECTED_BECAUSE_ACTIVE_BID_PRESENT: + 'AUCTION_TRANSITION_REJECTED_BECAUSE_ACTIVE_BID_PRESENT', + /** 전환 요청 조정(예약/리스/멱등) 단계의 일시적 거부 — 최신 상태로 재시도하면 보통 해소됨. */ + AUCTION_TRANSITION_REJECTED_BECAUSE_REQUEST_COORDINATION_RETRYABLE: + 'AUCTION_TRANSITION_REJECTED_BECAUSE_REQUEST_COORDINATION_RETRYABLE', + + // === 입찰(bid) === + /** 입찰 라운드가 이미 다음 선수/다음 라운드로 넘어감(내부 `STALE_BID_ROUND`). */ + BID_REJECTED_BECAUSE_BID_ROUND_ALREADY_ADVANCED: + 'BID_REJECTED_BECAUSE_BID_ROUND_ALREADY_ADVANCED', + /** 입찰 라운드 마감 시각이 이미 지남(내부 `EXPIRED`). */ + BID_REJECTED_BECAUSE_BID_ROUND_DEADLINE_PASSED: + 'BID_REJECTED_BECAUSE_BID_ROUND_DEADLINE_PASSED', + /** 경매가 입찰 단계가 아님(내부 `PHASE`). */ + BID_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE: + 'BID_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE', + /** 입찰 금액이 현재 최고가보다 높지 않음(내부 `TOO_LOW`). */ + BID_REJECTED_BECAUSE_AMOUNT_NOT_HIGHER_THAN_CURRENT_HIGHEST: + 'BID_REJECTED_BECAUSE_AMOUNT_NOT_HIGHER_THAN_CURRENT_HIGHEST', + /** 팀 정원이 이미 가득 참(내부 `FULL`). */ + BID_REJECTED_BECAUSE_TEAM_ROSTER_FULL: + 'BID_REJECTED_BECAUSE_TEAM_ROSTER_FULL', + /** 남은 슬롯 최소 확보분을 고려하면 포인트가 부족함(내부 `INSUFFICIENT`). */ + BID_REJECTED_BECAUSE_INSUFFICIENT_REMAINING_POINTS_FOR_SLOTS: + 'BID_REJECTED_BECAUSE_INSUFFICIENT_REMAINING_POINTS_FOR_SLOTS', + /** 알 수 없는 팀 인덱스(내부 `UNKNOWN_TEAM`). */ + BID_REJECTED_BECAUSE_UNKNOWN_TEAM: 'BID_REJECTED_BECAUSE_UNKNOWN_TEAM', + /** 같은 요청 id에 다른 내용이 온 멱등성 충돌(내부 `DUPLICATE_REQUEST_CONFLICT`). */ + BID_REJECTED_BECAUSE_DUPLICATE_REQUEST_PAYLOAD_CONFLICT: + 'BID_REJECTED_BECAUSE_DUPLICATE_REQUEST_PAYLOAD_CONFLICT', + /** 짧은 시간에 너무 많은 입찰 요청(게이트웨이 rate limit). */ + BID_REJECTED_BECAUSE_RATE_LIMITED: 'BID_REJECTED_BECAUSE_RATE_LIMITED', + + // === 공통/그 외 === + /** 실시간 상태를 아직 사용할 수 없음(재접속/재조회 필요). */ + AUCTION_REQUEST_REJECTED_BECAUSE_REALTIME_STATE_UNAVAILABLE: + 'AUCTION_REQUEST_REJECTED_BECAUSE_REALTIME_STATE_UNAVAILABLE', + /** 위 어디에도 해당하지 않는 미분류 거부(원문 message로 안내). */ + AUCTION_REQUEST_REJECTED_FOR_UNRECOGNIZED_REASON: + 'AUCTION_REQUEST_REJECTED_FOR_UNRECOGNIZED_REASON', +} as const; + +export type AuctionRejectionReason = + (typeof AUCTION_REJECTION_REASON)[keyof typeof AUCTION_REJECTION_REASON]; + +/** 내부 짧은 코드 → 설명적 reason. */ +const INTERNAL_CODE_TO_REASON: Record = { + CONFLICT: + AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_LIVE_STATE_CHANGED_BEFORE_APPLY, + STALE_BID_ROUND: + AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_BID_ROUND_ALREADY_ADVANCED, + EXPIRED: + AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_BID_ROUND_DEADLINE_PASSED, + PHASE: + AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE, + TOO_LOW: + AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_AMOUNT_NOT_HIGHER_THAN_CURRENT_HIGHEST, + FULL: AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_TEAM_ROSTER_FULL, + INSUFFICIENT: + AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_INSUFFICIENT_REMAINING_POINTS_FOR_SLOTS, + UNKNOWN_TEAM: AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_UNKNOWN_TEAM, + DUPLICATE_REQUEST_CONFLICT: + AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_DUPLICATE_REQUEST_PAYLOAD_CONFLICT, + BID_RATE_LIMITED: AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_RATE_LIMITED, +}; + +/** 구조화된 code 없이 message만 던지는 BadRequest(구조 전환 검증 등) → 설명적 reason. */ +const MESSAGE_TO_REASON: Record = { + 'Auction is not in bidding phase.': + AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE, + 'Cannot advance from current phase.': + AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE, + 'No bid to mark sold.': + AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_NO_WINNING_BID_TO_MARK_SOLD, + 'Cannot pass a player with an active bid.': + AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_ACTIVE_BID_PRESENT, + 'Auction realtime state is not available.': + AUCTION_REJECTION_REASON.AUCTION_REQUEST_REJECTED_BECAUSE_REALTIME_STATE_UNAVAILABLE, +}; + +/** + * resync(최신 state로 rebaseline 후 재시도)가 권장되는 reason 집합. + * "내가 본 상태가 낡았을 뿐, 다시 보면 가능할 수 있는" 거부들이다. + */ +export const AUCTION_RESYNC_RECOMMENDED_REASONS: ReadonlySet = + new Set([ + AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_LIVE_STATE_CHANGED_BEFORE_APPLY, + AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE, + AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE, + AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_NO_WINNING_BID_TO_MARK_SOLD, + AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_ACTIVE_BID_PRESENT, + AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_REQUEST_COORDINATION_RETRYABLE, + AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_BID_ROUND_ALREADY_ADVANCED, + AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_BID_ROUND_DEADLINE_PASSED, + AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE, + AUCTION_REJECTION_REASON.BID_REJECTED_BECAUSE_AMOUNT_NOT_HIGHER_THAN_CURRENT_HIGHEST, + AUCTION_REJECTION_REASON.AUCTION_REQUEST_REJECTED_BECAUSE_REALTIME_STATE_UNAVAILABLE, + ]); + +/** + * 내부 거부 code(짧은 코드) 또는 BadRequest message로부터 설명적 reason을 해석한다. + * 둘 다 모르면 미분류 reason으로 떨어뜨린다(원문 message는 ack에 그대로 남는다). + */ +export function resolveAuctionRejectionReason( + internalCode?: string, + message?: string, +): AuctionRejectionReason { + if (internalCode && INTERNAL_CODE_TO_REASON[internalCode]) { + return INTERNAL_CODE_TO_REASON[internalCode]; + } + if (message && MESSAGE_TO_REASON[message]) { + return MESSAGE_TO_REASON[message]; + } + // 구조 전환 경로는 code 자리에 message 문장이 들어올 수 있어 한 번 더 확인한다. + if (internalCode && MESSAGE_TO_REASON[internalCode]) { + return MESSAGE_TO_REASON[internalCode]; + } + if ( + internalCode && + (internalCode.startsWith('ACTION_REQUEST_') || + internalCode.startsWith('INVALID_')) + ) { + return AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_REQUEST_COORDINATION_RETRYABLE; + } + return AUCTION_REJECTION_REASON.AUCTION_REQUEST_REJECTED_FOR_UNRECOGNIZED_REASON; +} + +export function isAuctionResyncRecommended( + reason: AuctionRejectionReason, +): boolean { + return AUCTION_RESYNC_RECOMMENDED_REASONS.has(reason); +} diff --git a/apps/api/src/modules/auction/auction-side-effect.service.spec.ts b/apps/api/src/modules/auction/auction-side-effect.service.spec.ts new file mode 100644 index 00000000..ffdac4c0 --- /dev/null +++ b/apps/api/src/modules/auction/auction-side-effect.service.spec.ts @@ -0,0 +1,101 @@ +import { + AuctionSideEffectService, + buildMatchSideEffectDelta, + buildSideEffectApplicationIdentity, + buildSideEffectLeaseAcquireUpdate, + canAcquireSideEffectLease, +} from './auction-side-effect.service'; + +describe('auction side effect helpers', () => { + it('builds idempotency identity from transition and side effect type', () => { + expect( + buildSideEffectApplicationIdentity({ + auctionId: 'auction-1', + auctionStateTransitionId: 'transition-1', + sideEffectType: 'syncMatchTeams', + }), + ).toEqual({ + auctionId: 'auction-1', + auctionStateTransitionId: 'transition-1', + sideEffectType: 'syncMatchTeams', + }); + }); + + it('allows lease acquisition for pending, failed, or stale processing items only', () => { + expect(canAcquireSideEffectLease({ state: 'pending' }, 1000)).toBe(true); + expect(canAcquireSideEffectLease({ state: 'failed' }, 1000)).toBe(true); + expect( + canAcquireSideEffectLease( + { processingLeaseExpiresAtTimestampMS: 999, state: 'processing' }, + 1000, + ), + ).toBe(true); + expect( + canAcquireSideEffectLease( + { processingLeaseExpiresAtTimestampMS: 1001, state: 'processing' }, + 1000, + ), + ).toBe(false); + expect(canAcquireSideEffectLease({ state: 'completed' }, 1000)).toBe(false); + }); + + it('builds lease acquire update with Redis TIME timestamps', () => { + expect( + buildSideEffectLeaseAcquireUpdate({ + currentRedisTimestampMS: 1000, + leaseDurationMS: 5000, + ownerToken: 'worker-1', + }), + ).toEqual({ + $inc: { attempts: 1 }, + $set: { + processingLeaseExpiresAtTimestampMS: 6000, + processingOwnerToken: 'worker-1', + processingStartedAtTimestampMS: 1000, + state: 'processing', + }, + }); + }); + + it('builds side-effect socket delta independently from auction revision', () => { + expect( + buildMatchSideEffectDelta({ + auctionLifecycleId: 'life-1', + currentServerTimestampMS: 1000, + matchSideEffectRevision: 3, + matchSideEffectStatus: 'completed', + }), + ).toEqual({ + auctionLifecycleId: 'life-1', + currentServerTimestampMS: 1000, + matchSideEffectRevision: 3, + matchSideEffectStatus: 'completed', + }); + }); + + it('mirrors side-effect status into Redis live state with lifecycle and revision guard', async () => { + const sendCommand = jest.fn().mockResolvedValue(1); + const service = new AuctionSideEffectService({ + raw: jest.fn().mockReturnValue({ sendCommand }), + } as never); + + await expect( + service.mirrorMatchSideEffectStatus({ + auctionLifecycleId: 'life-1', + matchId: 'match-1', + matchSideEffectRevision: 2, + matchSideEffectStatus: 'completed', + }), + ).resolves.toBe(true); + + expect(sendCommand).toHaveBeenCalledWith([ + 'EVAL', + expect.stringContaining('auctionLifecycleId'), + '1', + 'auction:match-1:liveAuctionState', + 'life-1', + '2', + 'completed', + ]); + }); +}); diff --git a/apps/api/src/modules/auction/auction-side-effect.service.ts b/apps/api/src/modules/auction/auction-side-effect.service.ts new file mode 100644 index 00000000..2dbc3b2e --- /dev/null +++ b/apps/api/src/modules/auction/auction-side-effect.service.ts @@ -0,0 +1,110 @@ +import { Injectable } from '@nestjs/common'; +import type { + AuctionMatchSideEffectStatus, + AuctionSideEffectApplicationState, +} from '../global/database/schema'; +import { buildAuctionRedisKeys } from './redis/auction-redis.keys'; +import { AuctionRedisService } from './redis/auction-redis.service'; + +export interface SideEffectApplicationIdentity { + auctionId: unknown; + auctionStateTransitionId: string; + sideEffectType: string; +} + +export interface SideEffectLeaseState { + processingLeaseExpiresAtTimestampMS?: number; + state: AuctionSideEffectApplicationState; +} + +export interface BuildSideEffectLeaseAcquireUpdateParams { + currentRedisTimestampMS: number; + leaseDurationMS: number; + ownerToken: string; +} + +export interface MatchSideEffectDelta { + auctionLifecycleId: string; + currentServerTimestampMS: number; + matchSideEffectRevision: number; + matchSideEffectStatus: AuctionMatchSideEffectStatus; +} + +@Injectable() +export class AuctionSideEffectService { + constructor(private readonly auctionRedisService: AuctionRedisService) {} + + public async mirrorMatchSideEffectStatus(params: { + auctionLifecycleId: string; + matchId: string; + matchSideEffectRevision: number; + matchSideEffectStatus: AuctionMatchSideEffectStatus; + }): Promise { + const keys = buildAuctionRedisKeys(params.matchId); + const result = await this.auctionRedisService.raw().sendCommand([ + 'EVAL', + [ + "if redis.call('HGET', KEYS[1], 'auctionLifecycleId') ~= ARGV[1] then return 0 end", + "local currentRevision = tonumber(redis.call('HGET', KEYS[1], 'matchSideEffectRevision') or '-1')", + 'local nextRevision = tonumber(ARGV[2])', + 'if currentRevision >= nextRevision then return 0 end', + "redis.call('HSET', KEYS[1], 'matchSideEffectRevision', ARGV[2], 'matchSideEffectStatus', ARGV[3])", + 'return 1', + ].join('\n'), + '1', + keys.liveStateKey, + params.auctionLifecycleId, + String(params.matchSideEffectRevision), + params.matchSideEffectStatus, + ]); + return Number(result) === 1; + } +} + +export function buildSideEffectApplicationIdentity( + params: SideEffectApplicationIdentity, +): SideEffectApplicationIdentity { + return { + auctionId: params.auctionId, + auctionStateTransitionId: params.auctionStateTransitionId, + sideEffectType: params.sideEffectType, + }; +} + +export function canAcquireSideEffectLease( + state: SideEffectLeaseState, + currentRedisTimestampMS: number, +): boolean { + if (state.state === 'pending' || state.state === 'failed') return true; + if (state.state !== 'processing') return false; + return ( + (state.processingLeaseExpiresAtTimestampMS ?? 0) <= + currentRedisTimestampMS + ); +} + +export function buildSideEffectLeaseAcquireUpdate( + params: BuildSideEffectLeaseAcquireUpdateParams, +) { + return { + $inc: { attempts: 1 }, + $set: { + processingLeaseExpiresAtTimestampMS: + params.currentRedisTimestampMS + params.leaseDurationMS, + processingOwnerToken: params.ownerToken, + processingStartedAtTimestampMS: params.currentRedisTimestampMS, + state: 'processing', + }, + }; +} + +export function buildMatchSideEffectDelta( + params: MatchSideEffectDelta, +): MatchSideEffectDelta { + return { + auctionLifecycleId: params.auctionLifecycleId, + currentServerTimestampMS: params.currentServerTimestampMS, + matchSideEffectRevision: params.matchSideEffectRevision, + matchSideEffectStatus: params.matchSideEffectStatus, + }; +} diff --git a/apps/api/src/modules/auction/auction.controller.ts b/apps/api/src/modules/auction/auction.controller.ts index 70fd1560..3aca5420 100644 --- a/apps/api/src/modules/auction/auction.controller.ts +++ b/apps/api/src/modules/auction/auction.controller.ts @@ -20,7 +20,11 @@ import type { UserDocument } from '../global/database/schema'; import { AuctionService } from './auction.service'; import { AuctionGateway } from './auction.gateway'; import { + NextAuctionDto, + OpenBiddingDto, + PassedAuctionDto, PlaceBidDto, + ResetAuctionDto, SoldDto, StartAuctionDto, UndoAuctionDto, @@ -47,18 +51,22 @@ export class AuctionController { return this.auctionService.start({ matchId, communityId, + startAuctionRequestId: body.startAuctionRequestId, + actorUserId: currentUser._id, captains: body.captains.map((c) => ({ teamIndex: c.teamIndex, userId: new mongoose.Types.ObjectId(c.userId), - initialPoints: c.initialPoints, + initialTeamBidPointAmount: c.initialTeamBidPointAmount, })), - initialPoints: body.initialPoints ?? 1000, - maxTimerSeconds: body.maxTimerSeconds ?? 30, - bidExtensionSeconds: body.bidExtensionSeconds ?? 5, - topTierThreshold: body.topTierThreshold ?? 'NONE', - manualTopTierUserIds: (body.manualTopTierUserIds ?? []).map( - (userId) => new mongoose.Types.ObjectId(userId), - ), + initialTeamBidPointAmount: body.initialTeamBidPointAmount ?? 1000, + maximumBidRoundDurationSeconds: + body.maximumBidRoundDurationSeconds ?? 30, + bidRoundExtensionSeconds: body.bidRoundExtensionSeconds ?? 5, + topTierAuctionPriorityThreshold: + body.topTierAuctionPriorityThreshold ?? 'NONE', + manualTopTierAuctionPriorityUserIds: ( + body.manualTopTierAuctionPriorityUserIds ?? [] + ).map((userId) => new mongoose.Types.ObjectId(userId)), }); } @@ -67,7 +75,7 @@ export class AuctionController { public async getAuction( @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, ) { - return this.auctionService.getByMatchId(matchId); + return this.auctionService.getStateByMatchId(matchId); } // 공개 — 팀장 2명만 쓸 엔드포인트(트러스트 기반, 10명 동시 관전). @@ -76,23 +84,26 @@ export class AuctionController { @HttpCode(HttpStatus.OK) public async openBidding( @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Body() body: OpenBiddingDto = {}, ) { - return this.auctionService.openBidding(matchId); + return this.auctionService.openBidding(matchId, body); } @Post('bids') @AllowPublicAccess() @HttpCode(HttpStatus.OK) public async placeBid( - @CurrentUser() currentUser: UserDocument | undefined, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, @Body() body: PlaceBidDto, ) { return this.auctionService.placeBid({ matchId, - teamIndex: body.teamIndex, - amount: body.amount, - bidderUserId: this.resolveBidder(currentUser, body.bidderUserId), + teamIndex: body.bidderTeamIndex, + amount: body.bidPointAmount, + bidRequestId: body.bidRequestId, + clientObservedAuctionLifecycleId: body.clientObservedAuctionLifecycleId, + clientObservedCurrentBidRoundPlayerUserId: + body.clientObservedCurrentBidRoundPlayerUserId, }); } @@ -106,16 +117,35 @@ export class AuctionController { return this.auctionService.markSold({ matchId, assignedPosition: body.assignedPosition, + auctionActionRequestId: body.auctionActionRequestId, + clientObservedAuctionLifecycleId: body.clientObservedAuctionLifecycleId, + clientObservedCurrentAuctionPlayerOrderIndex: + body.clientObservedCurrentAuctionPlayerOrderIndex, + clientObservedCurrentBidRoundPlayerUserId: + body.clientObservedCurrentBidRoundPlayerUserId, + clientObservedPhase: body.clientObservedPhase, + clientObservedRevision: body.clientObservedRevision, }); } + @Post('passed') + @AllowPublicAccess() + @HttpCode(HttpStatus.OK) + public async markPassed( + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Body() body: PassedAuctionDto = {}, + ) { + return this.auctionService.markPassed(matchId, body); + } + @Post('next') @AllowPublicAccess() @HttpCode(HttpStatus.OK) public async next( @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Body() body: NextAuctionDto = {}, ) { - return this.auctionService.next(matchId); + return this.auctionService.next(matchId, body); } @Get('history') @@ -147,6 +177,14 @@ export class AuctionController { matchId, communityId, sequence: body.sequence, + auctionActionRequestId: body.auctionActionRequestId, + clientObservedAuctionLifecycleId: body.clientObservedAuctionLifecycleId, + clientObservedCurrentAuctionPlayerOrderIndex: + body.clientObservedCurrentAuctionPlayerOrderIndex, + clientObservedCurrentBidRoundPlayerUserId: + body.clientObservedCurrentBidRoundPlayerUserId, + clientObservedPhase: body.clientObservedPhase, + clientObservedRevision: body.clientObservedRevision, }); this.auctionGateway.broadcastState(matchId.toString(), auction); return auction; @@ -161,24 +199,24 @@ export class AuctionController { @Param('communityId', ParseObjectIdPipe) communityId: mongoose.Types.ObjectId, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Body() body: ResetAuctionDto = {}, ) { this.assertSameCommunity(currentUser, communityId); - await this.auctionService.reset({ matchId, communityId }); + await this.auctionService.reset({ + matchId, + communityId, + auctionActionRequestId: body.auctionActionRequestId, + clientObservedAuctionLifecycleId: body.clientObservedAuctionLifecycleId, + clientObservedCurrentAuctionPlayerOrderIndex: + body.clientObservedCurrentAuctionPlayerOrderIndex, + clientObservedCurrentBidRoundPlayerUserId: + body.clientObservedCurrentBidRoundPlayerUserId, + clientObservedPhase: body.clientObservedPhase, + clientObservedRevision: body.clientObservedRevision, + }); this.auctionGateway.broadcastReset(matchId.toString()); } - private resolveBidder( - currentUser: UserDocument | undefined, - bodyBidder?: string, - ): mongoose.Types.ObjectId | undefined { - if (currentUser) return currentUser._id; - if (!bodyBidder) return undefined; - if (!mongoose.isValidObjectId(bodyBidder)) { - throw new BadRequestException('Invalid bidderUserId.'); - } - return new mongoose.Types.ObjectId(bodyBidder); - } - private assertSameCommunity( user: UserDocument, communityId: mongoose.Types.ObjectId, diff --git a/apps/api/src/modules/auction/auction.gateway.spec.ts b/apps/api/src/modules/auction/auction.gateway.spec.ts new file mode 100644 index 00000000..7a8ba603 --- /dev/null +++ b/apps/api/src/modules/auction/auction.gateway.spec.ts @@ -0,0 +1,319 @@ +import mongoose from 'mongoose'; + +jest.mock('../auth/jwt.service', () => ({ + JwtService: class JwtService {}, +})); + +import { AuctionGateway } from './auction.gateway'; + +describe('AuctionGateway', () => { + function createGateway(params?: { + getCurrentRedisTimestampMS?: jest.Mock; + placeBidDelta?: jest.Mock; + }) { + const auctionService = { + placeBidDelta: params?.placeBidDelta ?? jest.fn(), + }; + const auctionRedisService = { + getCurrentRedisTimestampMS: + params?.getCurrentRedisTimestampMS ?? + jest.fn().mockResolvedValue(1780000000000), + }; + const gateway = new AuctionGateway( + auctionService as never, + { resolveDevUserById: jest.fn() } as never, + { verify: jest.fn() } as never, + { findOrCreateByOid: jest.fn() } as never, + { getModel: jest.fn() } as never, + { attachAuctionNamespace: jest.fn() } as never, + auctionRedisService as never, + ); + const emit = jest.fn(); + const to = jest.fn().mockReturnValue({ emit }); + (gateway as unknown as { server: { to: jest.Mock } }).server = { to }; + + return { + auctionService, + emit, + gateway, + auctionRedisService, + to, + }; + } + + it('broadcasts a bid delta and acknowledges the matching bid request', async () => { + const matchId = new mongoose.Types.ObjectId().toString(); + const auctionBidHistoryEntry = { + bidderTeamIndex: 2, + bidderUserId: 'captain-2', + bidPlacedAtTimestampMS: 1780000000000, + bidPointAmount: 120, + }; + const placeBidDelta = jest.fn().mockResolvedValue({ + auctionBidHistoryEntry, + auctionLifecycleId: 'life-1', + currentBidRoundDeadlineTimestampMS: 1780000030000, + currentHighestBidderTeamIndex: 2, + currentHighestBidPointAmount: 120, + currentServerTimestampMS: 1780000000000, + revision: 9, + }); + const { emit, gateway, to } = createGateway({ placeBidDelta }); + const ack = jest.fn(); + + await gateway.handleBid( + { data: { matchId }, emit: jest.fn() } as never, + { + bidPointAmount: 120, + bidderTeamIndex: 2, + bidRequestId: 'bid-1', + clientObservedAuctionLifecycleId: 'life-1', + clientObservedCurrentBidRoundPlayerUserId: 'player-1', + }, + ack, + ); + + expect(placeBidDelta).toHaveBeenCalledWith({ + amount: 120, + bidRequestId: 'bid-1', + clientObservedAuctionLifecycleId: 'life-1', + clientObservedCurrentBidRoundPlayerUserId: 'player-1', + matchId: new mongoose.Types.ObjectId(matchId), + teamIndex: 2, + }); + expect(to).toHaveBeenCalledWith(matchId); + expect(emit).toHaveBeenCalledWith('bid', { + auctionBidHistoryEntry, + auctionLifecycleId: 'life-1', + bidRequestId: 'bid-1', + currentBidRoundDeadlineTimestampMS: 1780000030000, + currentHighestBidderTeamIndex: 2, + currentHighestBidPointAmount: 120, + currentServerTimestampMS: 1780000000000, + revision: 9, + }); + expect(ack).toHaveBeenCalledWith( + expect.objectContaining({ + bidDelta: { + auctionBidHistoryEntry, + auctionLifecycleId: 'life-1', + bidRequestId: 'bid-1', + currentBidRoundDeadlineTimestampMS: 1780000030000, + currentHighestBidderTeamIndex: 2, + currentHighestBidPointAmount: 120, + currentServerTimestampMS: 1780000000000, + revision: 9, + }, + bidRequestId: 'bid-1', + bidServerTiming: expect.objectContaining({ + gatewayTotalDurationMS: expect.any(Number), + }), + ok: true, + }), + ); + }); + + it('generates one bid request id when the client omits it', async () => { + const matchId = new mongoose.Types.ObjectId().toString(); + const placeBidDelta = jest.fn().mockResolvedValue({ + auctionBidHistoryEntry: { + bidderTeamIndex: 1, + bidPointAmount: 50, + }, + auctionLifecycleId: 'life-1', + currentHighestBidderTeamIndex: 1, + currentHighestBidPointAmount: 50, + revision: 3, + }); + const { emit, gateway } = createGateway({ placeBidDelta }); + const ack = jest.fn(); + + await gateway.handleBid( + { data: { matchId }, emit: jest.fn() } as never, + { + bidPointAmount: 50, + bidderTeamIndex: 1, + }, + ack, + ); + + const generatedBidRequestId = placeBidDelta.mock.calls[0][0].bidRequestId; + expect(generatedBidRequestId).toEqual(expect.any(String)); + expect(generatedBidRequestId).not.toHaveLength(0); + expect(emit).toHaveBeenCalledWith( + 'bid', + expect.objectContaining({ + bidRequestId: generatedBidRequestId, + }), + ); + expect(ack).toHaveBeenCalledWith( + expect.objectContaining({ + bidRequestId: generatedBidRequestId, + ok: true, + }), + ); + }); + + it('acknowledges bid failures with the request id used for the attempt', async () => { + const matchId = new mongoose.Types.ObjectId().toString(); + const placeBidDelta = jest.fn().mockRejectedValue({ + getResponse: () => ({ + bidDiagnostics: { + currentBidRoundDeadlineTimestampMS: 1780000002500, + currentServerTimestampMS: 1780000003000, + }, + bidServerTiming: { + redisBidCommandDurationMS: 2, + redisBidContextReadDurationMS: 1, + serviceTotalDurationMS: 4, + }, + code: 'EXPIRED', + message: 'Bid deadline has already expired.', + }), + }); + const socketEmit = jest.fn(); + const { gateway } = createGateway({ placeBidDelta }); + const ack = jest.fn(); + + await gateway.handleBid( + { data: { matchId }, emit: socketEmit } as never, + { + bidPointAmount: 50, + bidderTeamIndex: 1, + bidRequestId: 'bid-1', + }, + ack, + ); + + expect(socketEmit).toHaveBeenCalledWith('error', { + message: 'Bid deadline has already expired.', + }); + expect(ack).toHaveBeenCalledWith( + expect.objectContaining({ + bidDiagnostics: { + currentBidRoundDeadlineTimestampMS: 1780000002500, + currentServerTimestampMS: 1780000003000, + }, + bidRequestId: 'bid-1', + bidServerTiming: expect.objectContaining({ + gatewayTotalDurationMS: expect.any(Number), + redisBidCommandDurationMS: 2, + redisBidContextReadDurationMS: 1, + serviceTotalDurationMS: 4, + }), + code: 'EXPIRED', + message: 'Bid deadline has already expired.', + rejected: true, + }), + ); + }); + + it('acknowledges time sync with Redis server time', async () => { + const getCurrentRedisTimestampMS = jest + .fn() + .mockResolvedValue(1780000001234); + const { gateway } = createGateway({ getCurrentRedisTimestampMS }); + const ack = jest.fn(); + + await gateway.handleTimeSync( + { + clientSentAtTimestampMS: 1780000000000, + sequence: 7, + }, + ack, + ); + + expect(getCurrentRedisTimestampMS).toHaveBeenCalledTimes(1); + expect(ack).toHaveBeenCalledWith( + expect.objectContaining({ + clientSentAtTimestampMS: 1780000000000, + currentServerTimestampMS: 1780000001234, + ok: true, + sequence: 7, + }), + ); + }); + + it('rate limits excessive bid requests from the same socket', async () => { + jest.spyOn(Date, 'now').mockReturnValue(1780000000000); + const matchId = new mongoose.Types.ObjectId().toString(); + const placeBidDelta = jest.fn().mockResolvedValue({ + auctionBidHistoryEntry: { + bidderTeamIndex: 1, + bidPointAmount: 50, + }, + currentHighestBidderTeamIndex: 1, + currentHighestBidPointAmount: 50, + revision: 3, + }); + const socketEmit = jest.fn(); + const socket = { data: { matchId }, emit: socketEmit }; + const { gateway } = createGateway({ placeBidDelta }); + const acknowledgements: Array> = []; + + for (let index = 0; index < 9; index += 1) { + await gateway.handleBid( + socket as never, + { + bidPointAmount: 50, + bidderTeamIndex: 1, + bidRequestId: `bid-${index}`, + }, + (response) => acknowledgements.push(response), + ); + } + + expect(placeBidDelta).toHaveBeenCalledTimes(8); + expect(socketEmit).toHaveBeenCalledWith('error', { + message: '입찰 요청이 너무 많습니다. 잠시 후 다시 시도해주세요.', + }); + expect(acknowledgements[8]).toEqual({ + bidRequestId: 'bid-8', + code: 'BID_RATE_LIMITED', + message: '입찰 요청이 너무 많습니다. 잠시 후 다시 시도해주세요.', + rejected: true, + }); + }); + + it('allows bid requests again after the rate limit window resets', async () => { + const nowSpy = jest.spyOn(Date, 'now'); + nowSpy.mockReturnValue(1780000000000); + const matchId = new mongoose.Types.ObjectId().toString(); + const placeBidDelta = jest.fn().mockResolvedValue({ + auctionBidHistoryEntry: { + bidderTeamIndex: 1, + bidPointAmount: 50, + }, + currentHighestBidderTeamIndex: 1, + currentHighestBidPointAmount: 50, + revision: 3, + }); + const socket = { data: { matchId }, emit: jest.fn() }; + const { gateway } = createGateway({ placeBidDelta }); + + for (let index = 0; index < 8; index += 1) { + await gateway.handleBid( + socket as never, + { + bidPointAmount: 50, + bidderTeamIndex: 1, + bidRequestId: `bid-${index}`, + }, + jest.fn(), + ); + } + + nowSpy.mockReturnValue(1780000001000); + await gateway.handleBid( + socket as never, + { + bidPointAmount: 50, + bidderTeamIndex: 1, + bidRequestId: 'bid-reset', + }, + jest.fn(), + ); + + expect(placeBidDelta).toHaveBeenCalledTimes(9); + }); +}); diff --git a/apps/api/src/modules/auction/auction.gateway.ts b/apps/api/src/modules/auction/auction.gateway.ts index 91c0c613..66d4df76 100644 --- a/apps/api/src/modules/auction/auction.gateway.ts +++ b/apps/api/src/modules/auction/auction.gateway.ts @@ -1,9 +1,12 @@ import { Logger } from '@nestjs/common'; +import { randomUUID } from 'crypto'; +import { performance } from 'perf_hooks'; import { + Ack, ConnectedSocket, MessageBody, OnGatewayConnection, - OnGatewayDisconnect, + OnGatewayInit, SubscribeMessage, WebSocketGateway, WebSocketServer, @@ -23,26 +26,64 @@ import type { UserDocument, } from '../global/database/schema'; import { AuctionService } from './auction.service'; +import type { + AuctionBidDeltaResponse, + AuctionStateResponse, +} from './auction.service'; +import { AuctionEventBusService } from './auction-event-bus.service'; +import { + isAuctionResyncRecommended, + resolveAuctionRejectionReason, +} from './auction-rejection'; +import type { MatchSideEffectDelta } from './auction-side-effect.service'; +import { serializeRealtimeAuction } from './auction-realtime-serializer'; +import { AuctionRedisService } from './redis/auction-redis.service'; interface JoinAuctionPayload { matchId: string; } interface BidPayload { - teamIndex: number; - amount: number; - bidderUserId?: string; + bidderTeamIndex: number; + bidPointAmount: number; + bidRequestId?: string; + clientObservedAuctionLifecycleId?: string; + clientObservedCurrentBidRoundPlayerUserId?: string; +} + +interface TimeSyncPayload { + clientSentAtTimestampMS?: number; + sequence?: number; } interface SoldPayload { + auctionActionRequestId?: string; assignedPosition?: Position; + clientObservedAuctionLifecycleId?: string; + clientObservedCurrentAuctionPlayerOrderIndex?: number; + clientObservedCurrentBidRoundPlayerUserId?: string; + clientObservedPhase?: string; + clientObservedRevision?: number; } +type AuctionActionPayload = Omit; + interface ChatMessagePayload { message?: string; displayName?: string; } +interface BidRateLimitState { + count: number; + windowStartedAtTimestampMS: number; +} + +const BID_RATE_LIMIT_WINDOW_MS = 1000; +const BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW = 8; +const BID_RATE_LIMIT_REJECTION_CODE = 'BID_RATE_LIMITED'; +const BID_RATE_LIMIT_REJECTION_MESSAGE = + '입찰 요청이 너무 많습니다. 잠시 후 다시 시도해주세요.'; + @WebSocketGateway({ namespace: '/auction', cors: { @@ -52,13 +93,12 @@ interface ChatMessagePayload { }, }) export class AuctionGateway - implements OnGatewayConnection, OnGatewayDisconnect + implements OnGatewayConnection, OnGatewayInit { @WebSocketServer() private server!: Namespace; private readonly logger = new Logger(AuctionGateway.name); - private readonly roomTimers = new Map(); constructor( private readonly auctionService: AuctionService, @@ -66,8 +106,14 @@ export class AuctionGateway private readonly jwtService: JwtService, private readonly identityService: IdentityService, private readonly connectionService: ConnectionService, + private readonly auctionEventBusService: AuctionEventBusService, + private readonly auctionRedisService: AuctionRedisService, ) {} + public afterInit(server: Namespace): void { + this.auctionEventBusService.attachAuctionNamespace(server); + } + public async handleConnection(socket: Socket) { try { await this.authenticateSocket(socket); @@ -82,12 +128,6 @@ export class AuctionGateway } } - public handleDisconnect(socket: Socket) { - const matchId = this.getSocketMatchId(socket); - if (!matchId) return; - this.maybeClearRoomTimer(matchId); - } - @SubscribeMessage('join') public async handleJoin( @ConnectedSocket() socket: Socket, @@ -106,8 +146,11 @@ export class AuctionGateway const auction = await this.auctionService.getByMatchId( new mongoose.Types.ObjectId(payload.matchId), ); + const auctionState = await this.auctionService.getStateByMatchId( + new mongoose.Types.ObjectId(payload.matchId), + ); this.emitChatHistory(socket, auction); - this.broadcastState(payload.matchId, auction); + this.broadcastState(payload.matchId, auctionState); } catch (error) { this.emitKnownError(socket, error); } @@ -117,41 +160,133 @@ export class AuctionGateway public async handleBid( @ConnectedSocket() socket: Socket, @MessageBody() payload: BidPayload, + @Ack() ack?: (response: Record) => void, ) { + const gatewayBidStartedAtMS = performance.now(); const matchId = this.requireJoinedMatchId(socket); if (!matchId) return; - const bidderUserId = this.resolveBidderUserId(socket, payload?.bidderUserId); - if (payload?.bidderUserId && !bidderUserId) { - this.emitError(socket, 'Invalid bidderUserId.'); + const bidRequestId = payload.bidRequestId ?? randomUUID(); + if (!this.consumeBidRateLimit(socket)) { + this.emitError(socket, BID_RATE_LIMIT_REJECTION_MESSAGE); + ack?.({ + bidRequestId, + code: BID_RATE_LIMIT_REJECTION_CODE, + message: BID_RATE_LIMIT_REJECTION_MESSAGE, + rejected: true, + }); return; } try { - const auction = await this.auctionService.placeBid({ + const bidResult = await this.auctionService.placeBidDelta({ matchId: new mongoose.Types.ObjectId(matchId), - teamIndex: payload.teamIndex, - amount: payload.amount, - bidderUserId, + teamIndex: payload.bidderTeamIndex, + amount: payload.bidPointAmount, + bidRequestId, + clientObservedAuctionLifecycleId: + payload.clientObservedAuctionLifecycleId, + clientObservedCurrentBidRoundPlayerUserId: + payload.clientObservedCurrentBidRoundPlayerUserId, + }); + const bidDelta = this.isBidDeltaResponse(bidResult) + ? { + ...bidResult, + bidRequestId: bidResult.bidRequestId ?? bidRequestId, + } + : this.buildBidDeltaFromAuctionState(bidResult, bidRequestId); + const bidServerTiming = this.extractBidServerTiming(bidDelta); + const broadcastBidDelta = this.stripBidServerTiming(bidDelta); + if (broadcastBidDelta) { + this.broadcastBid(matchId, broadcastBidDelta); + } else { + this.broadcastState(matchId, bidResult as AuctionStateResponse); + } + ack?.({ + ...(bidDelta + ? {} + : { state: this.serializeAuction(bidResult as AuctionStateResponse) }), + ok: true, + bidRequestId, + bidDelta: broadcastBidDelta, + bidServerTiming: this.buildGatewayBidTiming( + gatewayBidStartedAtMS, + bidServerTiming, + ), }); - this.broadcastState(matchId, auction); } catch (error) { - this.emitKnownError(socket, error); + const rejectionAckFields = await this.resolveRejectionAckFields( + matchId, + error, + ); + const bidServerTiming = this.extractBidServerTiming(rejectionAckFields); + this.emitError(socket, String(rejectionAckFields.message ?? '')); + ack?.({ + ...rejectionAckFields, + bidRequestId, + bidServerTiming: this.buildGatewayBidTiming( + gatewayBidStartedAtMS, + bidServerTiming, + ), + rejected: true, + }); + } + } + + @SubscribeMessage('time-sync') + public async handleTimeSync( + @MessageBody() payload: TimeSyncPayload, + @Ack() ack?: (response: Record) => void, + ) { + const receivedAtMonotonicMS = performance.now(); + try { + const currentServerTimestampMS = + await this.auctionRedisService.getCurrentRedisTimestampMS(); + ack?.({ + clientSentAtTimestampMS: payload?.clientSentAtTimestampMS, + currentServerTimestampMS, + ok: true, + sequence: payload?.sequence, + serverProcessingDurationMS: + Math.round((performance.now() - receivedAtMonotonicMS) * 10) / 10, + }); + } catch (error) { + const errorPayload = this.resolveErrorPayload(error); + ack?.({ + ...errorPayload, + clientSentAtTimestampMS: payload?.clientSentAtTimestampMS, + rejected: true, + sequence: payload?.sequence, + }); } } @SubscribeMessage('open-bidding') - public async handleOpenBidding(@ConnectedSocket() socket: Socket) { + public async handleOpenBidding( + @ConnectedSocket() socket: Socket, + @MessageBody() payload: AuctionActionPayload, + @Ack() ack?: (response: Record) => void, + ) { const matchId = this.requireJoinedMatchId(socket); if (!matchId) return; try { const auction = await this.auctionService.openBidding( new mongoose.Types.ObjectId(matchId), + this.toSocketAuctionActionRequest(payload), ); this.broadcastState(matchId, auction); + ack?.({ + auctionActionRequestId: payload?.auctionActionRequestId, + ok: true, + }); } catch (error) { this.emitKnownError(socket, error); + ack?.({ + ...(await this.resolveRejectionAckFields(matchId, error)), + auctionActionRequestId: payload?.auctionActionRequestId, + rejected: true, + }); } } @@ -159,6 +294,7 @@ export class AuctionGateway public async handleSold( @ConnectedSocket() socket: Socket, @MessageBody() payload: SoldPayload, + @Ack() ack?: (response: Record) => void, ) { const matchId = this.requireJoinedMatchId(socket); if (!matchId) return; @@ -167,25 +303,78 @@ export class AuctionGateway const auction = await this.auctionService.markSold({ matchId: new mongoose.Types.ObjectId(matchId), assignedPosition: payload?.assignedPosition, + ...this.toSocketAuctionActionRequest(payload), }); this.broadcastState(matchId, auction); + ack?.({ + auctionActionRequestId: payload?.auctionActionRequestId, + ok: true, + }); } catch (error) { this.emitKnownError(socket, error); + ack?.({ + ...(await this.resolveRejectionAckFields(matchId, error)), + auctionActionRequestId: payload?.auctionActionRequestId, + rejected: true, + }); } } @SubscribeMessage('next') - public async handleNext(@ConnectedSocket() socket: Socket) { + public async handleNext( + @ConnectedSocket() socket: Socket, + @MessageBody() payload: AuctionActionPayload, + @Ack() ack?: (response: Record) => void, + ) { const matchId = this.requireJoinedMatchId(socket); if (!matchId) return; try { const auction = await this.auctionService.next( new mongoose.Types.ObjectId(matchId), + this.toSocketAuctionActionRequest(payload), ); this.broadcastState(matchId, auction); + ack?.({ + auctionActionRequestId: payload?.auctionActionRequestId, + ok: true, + }); } catch (error) { this.emitKnownError(socket, error); + ack?.({ + ...(await this.resolveRejectionAckFields(matchId, error)), + auctionActionRequestId: payload?.auctionActionRequestId, + rejected: true, + }); + } + } + + @SubscribeMessage('passed') + public async handlePassed( + @ConnectedSocket() socket: Socket, + @MessageBody() payload: AuctionActionPayload, + @Ack() ack?: (response: Record) => void, + ) { + const matchId = this.requireJoinedMatchId(socket); + if (!matchId) return; + + try { + const auction = await this.auctionService.markPassed( + new mongoose.Types.ObjectId(matchId), + this.toSocketAuctionActionRequest(payload), + ); + this.broadcastState(matchId, auction); + ack?.({ + auctionActionRequestId: payload?.auctionActionRequestId, + ok: true, + }); + } catch (error) { + this.emitKnownError(socket, error); + ack?.({ + ...(await this.resolveRejectionAckFields(matchId, error)), + auctionActionRequestId: payload?.auctionActionRequestId, + rejected: true, + }); } } @@ -226,24 +415,52 @@ export class AuctionGateway return matchId; } + private consumeBidRateLimit(socket: Socket): boolean { + const currentTimestampMS = Date.now(); + const previousState = socket.data + .auctionBidRateLimit as BidRateLimitState | undefined; + if ( + !previousState || + currentTimestampMS - previousState.windowStartedAtTimestampMS >= + BID_RATE_LIMIT_WINDOW_MS + ) { + socket.data.auctionBidRateLimit = { + count: 1, + windowStartedAtTimestampMS: currentTimestampMS, + }; + return true; + } + + previousState.count += 1; + socket.data.auctionBidRateLimit = previousState; + return previousState.count <= BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW; + } + private getSocketMatchId(socket: Socket): string | undefined { return typeof socket.data.matchId === 'string' ? socket.data.matchId : undefined; } - private resolveBidderUserId( - socket: Socket, - payloadBidderUserId?: string, - ): mongoose.Types.ObjectId | undefined { - const candidate = - payloadBidderUserId ?? - (socket.data.user as UserDocument | undefined)?._id.toString() ?? - this.readHandshakeUserId(socket); - if (!candidate || !mongoose.isValidObjectId(candidate)) { - return undefined; - } - return new mongoose.Types.ObjectId(candidate); + private toAuctionActionRequest(payload?: AuctionActionPayload) { + return { + auctionActionRequestId: payload?.auctionActionRequestId, + clientObservedAuctionLifecycleId: + payload?.clientObservedAuctionLifecycleId, + clientObservedCurrentAuctionPlayerOrderIndex: + payload?.clientObservedCurrentAuctionPlayerOrderIndex, + clientObservedCurrentBidRoundPlayerUserId: + payload?.clientObservedCurrentBidRoundPlayerUserId, + clientObservedPhase: payload?.clientObservedPhase, + clientObservedRevision: payload?.clientObservedRevision, + }; + } + + private toSocketAuctionActionRequest(payload?: AuctionActionPayload) { + return { + ...this.toAuctionActionRequest(payload), + shouldBroadcastStateAfterDurability: false, + }; } private readHandshakeUserId(socket: Socket): string | undefined { @@ -359,16 +576,25 @@ export class AuctionGateway return typeof value === 'string' && value.length > 0 ? value : undefined; } - public broadcastState(matchId: string, auction: AuctionDocument) { - this.server.to(matchId).emit('state', this.serializeAuction(auction)); - this.syncRoomTimer(matchId, auction); + public broadcastState(matchId: string, auction: AuctionStateResponse) { + this.server.to(matchId).emit('state', serializeRealtimeAuction(auction)); + } + + public broadcastBid(matchId: string, delta: Record) { + this.server.to(matchId).emit('bid', delta); } public broadcastReset(matchId: string) { - this.clearRoomTimer(matchId); this.server.to(matchId).emit('reset', { matchId }); } + public broadcastMatchSideEffect( + matchId: string, + delta: MatchSideEffectDelta, + ) { + this.server.to(matchId).emit('match-side-effect', delta); + } + private emitChatHistory(socket: Socket, auction: AuctionDocument) { socket.emit('chat-history', { messages: (auction.chatMessages ?? []).map((message) => @@ -377,90 +603,207 @@ export class AuctionGateway }); } - private syncRoomTimer(matchId: string, auction: AuctionDocument) { - this.clearRoomTimer(matchId); - if (!auction.currentDeadline) return; - - const deadline = auction.currentDeadline; - const deadlineIso = deadline.toISOString(); - if (Date.now() >= deadline.getTime()) { - void this.handleDeadlineExpiry(matchId); - return; - } - this.server.to(matchId).emit('tick', { - deadline: deadlineIso, - serverTime: new Date().toISOString(), - }); - - const timer = setInterval(() => { - this.server.to(matchId).emit('tick', { - deadline: deadlineIso, - serverTime: new Date().toISOString(), - }); - - if (Date.now() >= deadline.getTime()) { - this.clearRoomTimer(matchId); - void this.handleDeadlineExpiry(matchId); - } - }, 1000); - - this.roomTimers.set(matchId, timer); - } - - private async handleDeadlineExpiry(matchIdStr: string) { - const matchId = new mongoose.Types.ObjectId(matchIdStr); - const auction = await this.auctionService - .getByMatchId(matchId) - .catch(() => null); - if (!auction || auction.phase !== 'bidding') return; - if (!auction.currentDeadline || auction.currentDeadline.getTime() > Date.now()) { - return; - } - - try { - const nextAuction = - auction.currentBid > 0 - ? await this.auctionService.markSold({ matchId }) - : await this.auctionService.markPassed(matchId); - this.broadcastState(matchIdStr, nextAuction); - } catch (error) { - this.emitKnownErrorToRoom(matchIdStr, error); - } - } - - private maybeClearRoomTimer(matchId: string) { - const room = this.server.adapter.rooms.get(matchId); - if (room && room.size > 0) return; - this.clearRoomTimer(matchId); - } - - private clearRoomTimer(matchId: string) { - const timer = this.roomTimers.get(matchId); - if (!timer) return; - clearInterval(timer); - this.roomTimers.delete(matchId); - } - private emitKnownError(socket: Socket, error: unknown) { - const message = - error instanceof Error ? error.message : 'Unexpected auction gateway error.'; - this.emitError(socket, message); - } - - private emitKnownErrorToRoom(matchId: string, error: unknown) { - const message = - error instanceof Error ? error.message : 'Unexpected auction gateway error.'; - this.server.to(matchId).emit('error', { message }); + this.emitError(socket, this.resolveErrorPayload(error).message); } private emitError(socket: Socket, message: string) { socket.emit('error', { message }); } - private serializeAuction(auction: AuctionDocument) { + private serializeAuction(auction: AuctionStateResponse) { return JSON.parse(JSON.stringify(auction)); } + /** + * 거부 ack에 실을 공통 필드를 만든다. + * + * - `code`/`message`: 기존 내부 코드/문구(진단·하위호환). + * - `auctionRejectionReason`: 맥락을 담은 설명적 거부코드(클라가 문구로 매핑). + * - `resyncRecommended`: "내가 본 상태가 낡았다"는 신호면 true. + * - `state`: resync 권장 거부에 한해 최신 권위 state를 동봉해, 클라가 join + * 왕복 없이 즉시 rebaseline하도록 한다(후속 액션의 반복 CONFLICT 차단). + */ + private async resolveRejectionAckFields( + matchId: string, + error: unknown, + ): Promise> { + const errorPayload = this.resolveErrorPayload(error); + const auctionRejectionReason = resolveAuctionRejectionReason( + typeof errorPayload.code === 'string' ? errorPayload.code : undefined, + errorPayload.message, + ); + const resyncRecommended = isAuctionResyncRecommended(auctionRejectionReason); + const state = resyncRecommended + ? await this.fetchSerializedAuctionState(matchId) + : undefined; + return { + ...errorPayload, + auctionRejectionReason, + resyncRecommended, + ...(state ? { state } : {}), + }; + } + + private async fetchSerializedAuctionState( + matchId: string, + ): Promise | undefined> { + try { + const state = await this.auctionService.getStateByMatchId( + new mongoose.Types.ObjectId(matchId), + ); + return state ? this.serializeAuction(state) : undefined; + } catch { + return undefined; + } + } + + private resolveErrorPayload(error: unknown): Record & { + message: string; + } { + const response = + typeof (error as { getResponse?: unknown })?.getResponse === 'function' + ? (error as { getResponse: () => unknown }).getResponse() + : undefined; + if (typeof response === 'object' && response !== null) { + const record = response as Record; + const message = Array.isArray(record.message) + ? record.message.join(', ') + : typeof record.message === 'string' + ? record.message + : error instanceof Error + ? error.message + : 'Unexpected auction gateway error.'; + return { + ...record, + code: + typeof record.code === 'string' + ? record.code + : error instanceof Error + ? error.message + : 'UNKNOWN', + message, + }; + } + return { + code: error instanceof Error ? error.message : 'UNKNOWN', + message: + error instanceof Error ? error.message : 'Unexpected auction gateway error.', + }; + } + + private buildGatewayBidTiming( + gatewayBidStartedAtMS: number, + bidServerTiming?: Record, + ): Record { + return { + ...(bidServerTiming ?? {}), + gatewayTotalDurationMS: + Math.round((performance.now() - gatewayBidStartedAtMS) * 10) / 10, + }; + } + + private extractBidServerTiming( + bidDelta: Record | null, + ): Record | undefined { + const timing = bidDelta?.bidServerTiming; + return typeof timing === 'object' && timing !== null + ? (timing as Record) + : undefined; + } + + private stripBidServerTiming( + bidDelta: Record | null, + ): Record | null { + if (!bidDelta || !('bidServerTiming' in bidDelta)) return bidDelta; + const { bidServerTiming: _bidServerTiming, ...publicBidDelta } = bidDelta; + return publicBidDelta; + } + + private buildBidDeltaFromAuctionState( + auction: AuctionStateResponse, + bidRequestId?: string, + ): Record | null { + const serialized = this.serializeAuction(auction) as Record; + const revision = Number(serialized.revision); + const currentHighestBidPointAmount = Number( + serialized.currentHighestBidPointAmount ?? serialized.currentBid, + ); + const currentHighestBidderTeamIndex = Number( + serialized.currentHighestBidderTeamIndex ?? + serialized.currentBidderTeamIndex, + ); + const currentBidRoundDeadlineTimestampMS = Number( + serialized.currentBidRoundDeadlineTimestampMS ?? + (typeof serialized.currentDeadline === 'string' + ? Date.parse(serialized.currentDeadline) + : 0), + ); + const redisBidHistory = Array.isArray(serialized.auctionBidHistory) + ? serialized.auctionBidHistory + : []; + const legacyBidHistory = Array.isArray(serialized.bids) + ? serialized.bids + : []; + const auctionBidHistoryEntry = + redisBidHistory[redisBidHistory.length - 1] ?? + this.convertLegacyBidToRedisBidHistoryEntry( + legacyBidHistory[legacyBidHistory.length - 1], + ); + + if ( + !Number.isFinite(currentHighestBidPointAmount) || + !Number.isFinite(currentHighestBidderTeamIndex) || + !auctionBidHistoryEntry + ) { + return null; + } + + return { + auctionBidHistoryEntry, + auctionLifecycleId: serialized.auctionLifecycleId, + bidRequestId, + currentBidRoundDeadlineTimestampMS: Number.isFinite( + currentBidRoundDeadlineTimestampMS, + ) + ? currentBidRoundDeadlineTimestampMS + : undefined, + currentHighestBidPointAmount, + currentHighestBidderTeamIndex, + currentServerTimestampMS: serialized.currentServerTimestampMS, + revision: Number.isFinite(revision) ? revision : undefined, + }; + } + + private isBidDeltaResponse( + value: unknown, + ): value is AuctionBidDeltaResponse { + return ( + typeof value === 'object' && + value !== null && + 'auctionBidHistoryEntry' in value && + 'currentHighestBidPointAmount' in value && + 'currentHighestBidderTeamIndex' in value && + 'revision' in value + ); + } + + private convertLegacyBidToRedisBidHistoryEntry( + bid: unknown, + ): Record | null { + if (!bid || typeof bid !== 'object') return null; + const record = bid as Record; + return { + bidderTeamIndex: record.teamIndex, + bidPointAmount: record.amount, + bidderUserId: record.bidderUserId, + bidPlacedAtTimestampMS: + typeof record.timestamp === 'string' + ? Date.parse(record.timestamp) + : undefined, + }; + } + private serializeChatMessage(message: AuctionChatMessage) { return JSON.parse(JSON.stringify(message)); } diff --git a/apps/api/src/modules/auction/auction.module.ts b/apps/api/src/modules/auction/auction.module.ts index fbbb1ccd..cdf7c595 100644 --- a/apps/api/src/modules/auction/auction.module.ts +++ b/apps/api/src/modules/auction/auction.module.ts @@ -4,12 +4,29 @@ import { TournamentCodeModule } from '../tournament-code/tournament-code.module' import { TournamentResultModule } from '../tournament-result/tournament-result.module'; import { AuctionGateway } from './auction.gateway'; import { AuctionController } from './auction.controller'; +import { AuctionDeadlineScheduler } from './auction-deadline.scheduler'; +import { AuctionDurabilityScheduler } from './auction-durability.scheduler'; +import { AuctionEventBusService } from './auction-event-bus.service'; +import { AuctionRedisModule } from './redis/auction-redis.module'; +import { AuctionSideEffectService } from './auction-side-effect.service'; import { AuctionService } from './auction.service'; @Module({ - imports: [RiotModule, TournamentCodeModule, TournamentResultModule], + imports: [ + RiotModule, + TournamentCodeModule, + TournamentResultModule, + AuctionRedisModule, + ], controllers: [AuctionController], - providers: [AuctionService, AuctionGateway], + providers: [ + AuctionService, + AuctionGateway, + AuctionEventBusService, + AuctionDeadlineScheduler, + AuctionDurabilityScheduler, + AuctionSideEffectService, + ], exports: [AuctionService], }) export class AuctionModule {} diff --git a/apps/api/src/modules/auction/auction.service.spec.ts b/apps/api/src/modules/auction/auction.service.spec.ts index 82992acc..695e8b49 100644 --- a/apps/api/src/modules/auction/auction.service.spec.ts +++ b/apps/api/src/modules/auction/auction.service.spec.ts @@ -37,6 +37,63 @@ describe('AuctionService', () => { scheduleInitialPoll: jest.fn().mockResolvedValue(null), cancelPolling: jest.fn().mockResolvedValue(undefined), }; + const auctionRedisService = { + acquireTokenLock: jest.fn().mockResolvedValue(true), + getCurrentRedisTimestampMS: jest.fn().mockResolvedValue(1780000000000), + releaseTokenLock: jest.fn().mockResolvedValue(true), + raw: jest.fn().mockReturnValue({ + sendCommand: jest.fn().mockResolvedValue(1), + }), + }; + const auctionRedisCommandService = { + applyTransition: jest.fn().mockResolvedValue({ + auctionStateTransitionId: 'transition-1', + currentServerTimestampMS: 1780000000000, + ok: true, + revision: 2, + }), + reserveActionRequest: jest.fn().mockImplementation( + async ( + _matchId: string, + input: { + auctionActionRequestId: string; + auctionStateTransitionId: string; + clientObservedAuctionLifecycleId: string; + }, + ) => ({ + actionRequestScopeKey: `${input.clientObservedAuctionLifecycleId}:${input.auctionActionRequestId}`, + auctionStateTransitionId: input.auctionStateTransitionId, + currentServerTimestampMS: 1780000000000, + newAuctionLifecycleId: '', + observedProcessingLeaseVersion: 1, + reserved: true, + wasLeaseExpired: false, + }), + ), + hydrateState: jest.fn().mockResolvedValue({ + currentServerTimestampMS: 1780000000000, + hydrated: true, + revision: 1, + }), + placeBid: jest.fn().mockResolvedValue({ + auctionBidHistoryEntry: { bidPointAmount: 20 }, + bidRequestId: 'bid-1', + currentBidRoundDeadlineTimestampMS: 1780000030000, + currentHighestBidderTeamIndex: 1, + currentHighestBidPointAmount: 20, + currentServerTimestampMS: 1780000000000, + ok: true, + revision: 3, + }), + }; + const auctionRedisStateReaderService = { + readLiveStateIdentity: jest.fn().mockResolvedValue({ + auctionLifecycleId: 'life-1', + revision: 1, + }), + readBidContext: jest.fn().mockResolvedValue(null), + readAuctionStateView: jest.fn().mockResolvedValue(null), + }; return { service: new AuctionService( @@ -44,11 +101,17 @@ describe('AuctionService', () => { enrichmentService as never, tournamentCodeService as never, tournamentResultService as never, + auctionRedisService as never, + auctionRedisCommandService as never, + auctionRedisStateReaderService as never, ), connectionService, tournamentCodeService, tournamentResultService, auctionHistoryModel, + auctionRedisCommandService, + auctionRedisService, + auctionRedisStateReaderService, }; } @@ -70,6 +133,127 @@ describe('AuctionService', () => { jest.useRealTimers(); }); + it('rejects live operations for migrated legacy auctions', async () => { + const matchId = new mongoose.Types.ObjectId(); + const auction = { + auctionEngineVersion: 'legacy-renamed', + matchId, + phase: 'bidding', + }; + const { service } = createService({ + auction: { + findOne: jest.fn().mockResolvedValue(auction), + }, + }); + + await expect( + service.placeBid({ + amount: 10, + matchId, + teamIndex: 1, + }), + ).rejects.toThrow('Legacy auction live operations are not supported.'); + }); + + 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, + }, + }); + + await expect( + service.placeBid({ + amount: 0, + matchId, + teamIndex: 1, + }), + ).rejects.toThrow('Bid amount must be a positive integer.'); + await expect( + service.placeBid({ + amount: 10.5, + matchId, + teamIndex: 1, + }), + ).rejects.toThrow('Bid amount must be a positive integer.'); + expect(auctionFindOne).not.toHaveBeenCalled(); + 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(); @@ -141,24 +325,1092 @@ describe('AuctionService', () => { await service.start({ matchId, communityId, + startAuctionRequestId: '00000000-0000-4000-8000-000000000001', captains: [ { teamIndex: 1, userId: userIds[0] }, { teamIndex: 2, userId: userIds[1] }, ], - initialPoints: 1000, - maxTimerSeconds: 30, - bidExtensionSeconds: 5, - topTierThreshold: 'NONE', - manualTopTierUserIds: [], + initialTeamBidPointAmount: 1000, + maximumBidRoundDurationSeconds: 30, + bidRoundExtensionSeconds: 5, + topTierAuctionPriorityThreshold: 'NONE', + manualTopTierAuctionPriorityUserIds: [], }); 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(); }); + it('creates redis-v1 auction fields and bootstraps Redis state when starting', async () => { + const matchId = new mongoose.Types.ObjectId(); + const communityId = new mongoose.Types.ObjectId(); + const userIds = Array.from( + { length: 10 }, + () => new mongoose.Types.ObjectId(), + ); + const participants = userIds.map((userId, index) => ({ + userId, + preferredPositions: [{ position: 'MID', priority: 1 }], + joinedAt: new Date(index), + excluded: false, + })); + const match = { + _id: matchId, + communityId, + participants, + status: 'recruiting', + teamBuiltAt: undefined, + save: jest.fn().mockResolvedValue(undefined), + }; + const users = userIds.slice(2).map((userId, index) => ({ + _id: userId, + riotAccounts: [ + { + puuid: `puuid-${index}`, + gameName: `Player${index}`, + tagLine: 'KR1', + profileIconId: index, + tiers: [], + championMasteries: [], + recentStatsSummary: undefined, + lastRefreshRequestedAt: new Date(), + isPrimary: true, + }, + ], + })); + const auctionCreate = jest.fn().mockImplementation(async (payload) => ({ + _id: payload._id, + matchId, + ...payload, + toObject: jest.fn().mockReturnValue({ matchId, ...payload }), + })); + const { service, auctionRedisCommandService, auctionRedisService } = + createService({ + match: { + findById: jest.fn().mockResolvedValue(match), + }, + user: { + find: jest.fn().mockResolvedValue(users), + }, + auction: { + findOne: jest.fn().mockResolvedValue(null), + create: auctionCreate, + }, + community: { + findById: jest.fn().mockReturnValue({ + select: jest.fn().mockReturnValue({ + lean: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ + riotPlatform: 'kr', + riotRegion: 'asia', + }), + }), + }), + }), + }, + }); + + await service.start({ + matchId, + communityId, + startAuctionRequestId: '00000000-0000-4000-8000-000000000011', + captains: [ + { teamIndex: 1, userId: userIds[0] }, + { + teamIndex: 2, + userId: userIds[1], + initialTeamBidPointAmount: 1200, + }, + ], + initialTeamBidPointAmount: 1000, + maximumBidRoundDurationSeconds: 30, + bidRoundExtensionSeconds: 5, + topTierAuctionPriorityThreshold: 'NONE', + manualTopTierAuctionPriorityUserIds: [], + }); + + const createdPayload = auctionCreate.mock.calls[0][0]; + expect(auctionRedisService.getCurrentRedisTimestampMS).toHaveBeenCalled(); + expect(createdPayload).toMatchObject({ + auctionEngineVersion: 'redis-v1', + currentAuctionHistorySequence: 1, + currentAuctionPlayerOrderIndex: 0, + currentAuctionRound: 1, + currentHighestBidPointAmount: 0, + initialTeamBidPointAmount: 1000, + matchSideEffectRevision: 0, + matchSideEffectStatus: 'none', + phase: 'presenting', + revision: 1, + }); + expect(createdPayload.auctionTeams).toEqual([ + expect.objectContaining({ + remainingBidPointAmount: 1000, + teamIndex: 1, + }), + expect.objectContaining({ + remainingBidPointAmount: 1200, + teamIndex: 2, + }), + ]); + expect(createdPayload.auctionStartedAtTimestampMS).toBe(1780000000000); + expect(createdPayload.startedAt).toEqual(new Date(1780000000000)); + expect(auctionRedisCommandService.hydrateState).toHaveBeenCalledWith( + matchId.toString(), + expect.objectContaining({ + auctionHistorySequence: 1, + maximumBidRoundDurationSeconds: 30, + matchId: matchId.toString(), + phase: 'presenting', + revision: 0, + }), + ); + }); + + it('replays start when the same startAuctionRequestId already created the auction', async () => { + const matchId = new mongoose.Types.ObjectId(); + const communityId = new mongoose.Types.ObjectId(); + const existingAuction = { + _id: new mongoose.Types.ObjectId(), + matchId, + startAuctionRequestId: '00000000-0000-4000-8000-000000000010', + }; + const auctionCreate = jest.fn(); + const { service } = createService({ + match: { + findById: jest.fn().mockResolvedValue({ + _id: matchId, + communityId, + }), + }, + user: { + find: jest.fn(), + }, + auction: { + findOne: jest.fn().mockResolvedValue(existingAuction), + create: auctionCreate, + }, + community: { + findById: jest.fn(), + }, + }); + + await expect( + service.start({ + matchId, + communityId, + startAuctionRequestId: '00000000-0000-4000-8000-000000000010', + captains: [], + initialTeamBidPointAmount: 1000, + maximumBidRoundDurationSeconds: 30, + bidRoundExtensionSeconds: 5, + topTierAuctionPriorityThreshold: 'NONE', + manualTopTierAuctionPriorityUserIds: [], + }), + ).resolves.toBe(existingAuction); + expect(auctionCreate).not.toHaveBeenCalled(); + }); + + it('rejects start while a redis reset side effect is still applying', async () => { + const matchId = new mongoose.Types.ObjectId(); + const communityId = new mongoose.Types.ObjectId(); + const existingAuction = { + _id: new mongoose.Types.ObjectId(), + auctionEngineVersion: 'redis-v1', + matchSideEffectStatus: 'pending', + phase: 'waiting', + startAuctionRequestId: '00000000-0000-4000-8000-000000000020', + }; + const auctionCreate = jest.fn(); + const { service } = createService({ + match: { + findById: jest.fn().mockResolvedValue({ + _id: matchId, + communityId, + }), + }, + user: { + find: jest.fn(), + }, + auction: { + findOne: jest.fn().mockResolvedValue(existingAuction), + create: auctionCreate, + }, + community: { + findById: jest.fn(), + }, + }); + + await expect( + service.start({ + matchId, + communityId, + startAuctionRequestId: '00000000-0000-4000-8000-000000000021', + captains: [], + initialTeamBidPointAmount: 1000, + maximumBidRoundDurationSeconds: 30, + bidRoundExtensionSeconds: 5, + topTierAuctionPriorityThreshold: 'NONE', + manualTopTierAuctionPriorityUserIds: [], + }), + ).rejects.toThrow('Auction reset is still being applied.'); + expect(auctionCreate).not.toHaveBeenCalled(); + }); + + it('removes a completed redis reset auction before starting again', async () => { + const matchId = new mongoose.Types.ObjectId(); + const communityId = new mongoose.Types.ObjectId(); + const oldAuctionId = new mongoose.Types.ObjectId(); + const userIds = Array.from( + { length: 10 }, + () => new mongoose.Types.ObjectId(), + ); + const participants = userIds.map((userId, index) => ({ + userId, + preferredPositions: [{ position: 'MID', priority: 1 }], + joinedAt: new Date(index), + excluded: false, + })); + const users = userIds.slice(2).map((userId, index) => ({ + _id: userId, + riotAccounts: [ + { + puuid: `puuid-${index}`, + gameName: `Player${index}`, + tagLine: 'KR1', + profileIconId: index, + tiers: [], + championMasteries: [], + recentStatsSummary: undefined, + lastRefreshRequestedAt: new Date(), + isPrimary: true, + }, + ], + })); + const existingAuction = { + _id: oldAuctionId, + auctionEngineVersion: 'redis-v1', + auctionLifecycleId: 'old-life-1', + matchSideEffectStatus: 'completed', + phase: 'waiting', + startAuctionRequestId: '00000000-0000-4000-8000-000000000022', + }; + const match = { + _id: matchId, + communityId, + participants, + status: 'recruiting', + teamBuiltAt: undefined, + save: jest.fn().mockResolvedValue(undefined), + }; + const auctionCreate = jest.fn().mockImplementation(async (payload) => ({ + _id: payload._id, + matchId, + ...payload, + toObject: jest.fn().mockReturnValue({ matchId, ...payload }), + })); + 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({ + 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({ + riotPlatform: 'kr', + riotRegion: 'asia', + }), + }), + }), + }), + }, + }); + + await service.start({ + matchId, + communityId, + startAuctionRequestId: '00000000-0000-4000-8000-000000000023', + captains: [ + { teamIndex: 1, userId: userIds[0] }, + { teamIndex: 2, userId: userIds[1] }, + ], + initialTeamBidPointAmount: 1000, + maximumBidRoundDurationSeconds: 30, + bidRoundExtensionSeconds: 5, + topTierAuctionPriorityThreshold: 'NONE', + manualTopTierAuctionPriorityUserIds: [], + }); + + expect(historyDeleteMany).toHaveBeenCalledWith({ auctionId: oldAuctionId }); + expect(auctionDeleteOne).toHaveBeenCalledWith({ _id: oldAuctionId }); + expect(auctionRedisService.raw().sendCommand).toHaveBeenCalledWith([ + 'EVAL', + expect.stringContaining('currentAuctionLifecycleId'), + '11', + `auction:${matchId.toString()}:liveAuctionState`, + 'auction:bidRoundDeadlineQueue', + `auction:${matchId.toString()}:auctionStructureState`, + `auction:${matchId.toString()}:appliedAuctionStateTransitionIds`, + `auction:${matchId.toString()}:auctionBidHistory`, + `auction:${matchId.toString()}:bidRequestResults`, + `auction:${matchId.toString()}:bidRequestResultOrder`, + `auction:${matchId.toString()}:auctionActionRequestResults`, + `auction:${matchId.toString()}:auctionActionRequestResultOrder`, + `auction:${matchId.toString()}:rehydrateLock`, + `auction:${matchId.toString()}:auctionStateTransitionLock`, + matchId.toString(), + 'old-life-1', + ]); + expect(auctionCreate).toHaveBeenCalledTimes(1); + expect(auctionRedisCommandService.hydrateState).toHaveBeenCalled(); + }); + + it('replays start after a concurrent create wins with the same request id', async () => { + const matchId = new mongoose.Types.ObjectId(); + const communityId = new mongoose.Types.ObjectId(); + const userIds = Array.from( + { length: 10 }, + () => new mongoose.Types.ObjectId(), + ); + const participants = userIds.map((userId, index) => ({ + userId, + preferredPositions: [{ position: 'MID', priority: 1 }], + joinedAt: new Date(index), + excluded: false, + })); + const users = userIds.slice(2).map((userId, index) => ({ + _id: userId, + riotAccounts: [ + { + puuid: `puuid-${index}`, + gameName: `Player${index}`, + tagLine: 'KR1', + profileIconId: index, + tiers: [], + championMasteries: [], + recentStatsSummary: undefined, + lastRefreshRequestedAt: new Date(), + isPrimary: true, + }, + ], + })); + const raceWinner = { + _id: new mongoose.Types.ObjectId(), + matchId, + startAuctionRequestId: '00000000-0000-4000-8000-000000000012', + }; + const match = { + _id: matchId, + communityId, + participants, + status: 'recruiting', + save: jest.fn().mockResolvedValue(undefined), + }; + const auctionFindOne = jest + .fn() + .mockResolvedValueOnce(null) + .mockResolvedValueOnce(raceWinner); + const auctionCreate = jest.fn().mockRejectedValue({ code: 11000 }); + const { service, auctionRedisCommandService } = createService({ + match: { + findById: jest.fn().mockResolvedValue(match), + }, + user: { + find: jest.fn().mockResolvedValue(users), + }, + auction: { + findOne: auctionFindOne, + create: auctionCreate, + }, + community: { + findById: jest.fn().mockReturnValue({ + select: jest.fn().mockReturnValue({ + lean: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ + riotPlatform: 'kr', + riotRegion: 'asia', + }), + }), + }), + }), + }, + }); + + await expect( + service.start({ + matchId, + communityId, + startAuctionRequestId: '00000000-0000-4000-8000-000000000012', + captains: [ + { teamIndex: 1, userId: userIds[0] }, + { teamIndex: 2, userId: userIds[1] }, + ], + initialTeamBidPointAmount: 1000, + maximumBidRoundDurationSeconds: 30, + bidRoundExtensionSeconds: 5, + topTierAuctionPriorityThreshold: 'NONE', + manualTopTierAuctionPriorityUserIds: [], + }), + ).resolves.toBe(raceWinner); + + expect(auctionCreate).toHaveBeenCalledTimes(1); + expect(auctionRedisCommandService.hydrateState).not.toHaveBeenCalled(); + expect(match.save).not.toHaveBeenCalled(); + }); + + it('reads Redis state view for redis-v1 auctions', async () => { + const matchId = new mongoose.Types.ObjectId(); + const auction = { + _id: new mongoose.Types.ObjectId(), + matchId, + auctionEngineVersion: 'redis-v1', + chatMessages: [{ id: 'chat-1' }], + toObject: jest.fn().mockReturnValue({ + matchId, + phase: 'presenting', + revision: 1, + }), + }; + const { service, auctionRedisStateReaderService } = createService({ + auction: { + findOne: jest.fn().mockResolvedValue(auction), + }, + }); + auctionRedisStateReaderService.readAuctionStateView.mockResolvedValue({ + phase: 'bidding', + revision: 2, + currentServerTimestampMS: 1000, + }); + + await expect(service.getStateByMatchId(matchId)).resolves.toMatchObject({ + chatMessages: [{ id: 'chat-1' }], + currentServerTimestampMS: 1000, + phase: 'bidding', + revision: 2, + }); + expect( + auctionRedisStateReaderService.readAuctionStateView, + ).toHaveBeenCalledWith(matchId.toString()); + }); + + it('rehydrates Redis state from Mongo projection when live state is missing', async () => { + const matchId = new mongoose.Types.ObjectId(); + const playerUserId = new mongoose.Types.ObjectId(); + const captainUserId = new mongoose.Types.ObjectId(); + const auction = { + _id: new mongoose.Types.ObjectId(), + matchId, + auctionEngineVersion: 'redis-v1', + auctionLifecycleId: 'life-1', + phase: 'presenting', + revision: 4, + currentAuctionHistorySequence: 3, + auctionTeams: [ + { + teamIndex: 1, + captainUserId: captainUserId.toString(), + remainingBidPointAmount: 1000, + members: [], + }, + ], + auctionPlayerOrder: [{ userId: playerUserId.toString() }], + passedAuctionPlayerQueue: [], + currentAuctionRound: 1, + currentAuctionPlayerOrderIndex: 0, + maximumBidRoundDurationSeconds: 30, + bidRoundExtensionSeconds: 5, + initialTeamBidPointAmount: 1000, + topTierAuctionPriorityThreshold: 'NONE', + manualTopTierAuctionPriorityUserIds: [], + chatMessages: [], + toObject: jest.fn().mockReturnValue({ + matchId, + phase: 'presenting', + revision: 4, + }), + }; + const redisState = { + auctionLifecycleId: 'life-1', + phase: 'presenting', + revision: 5, + shouldForceAuctionStateResync: true, + }; + const { + service, + auctionRedisCommandService, + auctionRedisService, + auctionRedisStateReaderService, + } = createService({ + auction: { + findOne: jest.fn().mockResolvedValue(auction), + }, + }); + auctionRedisStateReaderService.readLiveStateIdentity.mockResolvedValue( + null, + ); + auctionRedisStateReaderService.readAuctionStateView.mockResolvedValue( + redisState, + ); + + await expect(service.getStateByMatchId(matchId)).resolves.toMatchObject({ + phase: 'presenting', + revision: 5, + shouldForceAuctionStateResync: true, + }); + expect(auctionRedisService.acquireTokenLock).toHaveBeenCalledWith( + `auction:${matchId.toString()}:rehydrateLock`, + expect.any(String), + 5000, + ); + expect(auctionRedisCommandService.hydrateState).toHaveBeenCalledWith( + matchId.toString(), + expect.objectContaining({ + auctionLifecycleId: 'life-1', + phase: 'presenting', + revision: 4, + }), + ); + expect( + auctionRedisStateReaderService.readAuctionStateView, + ).toHaveBeenCalledWith(matchId.toString(), { + shouldForceAuctionStateResync: true, + }); + }); + + it('opens bidding through Redis for redis-v1 auctions', async () => { + const matchId = new mongoose.Types.ObjectId(); + const auction = { + _id: new mongoose.Types.ObjectId(), + matchId, + auctionEngineVersion: 'redis-v1', + }; + const presentingState = { + auctionLifecycleId: 'life-1', + auctionTeams: [ + { + teamIndex: 1, + captainUserId: new mongoose.Types.ObjectId().toString(), + remainingBidPointAmount: 1000, + members: [], + }, + ], + auctionPlayerOrder: [ + { + userId: new mongoose.Types.ObjectId().toString(), + preferredPositions: [{ position: 'MID', priority: 1 }], + }, + ], + bidRoundExtensionSeconds: 5, + currentAuctionHistorySequence: 1, + currentAuctionPlayerOrderIndex: 0, + currentAuctionRound: 1, + initialTeamBidPointAmount: 1000, + maximumBidRoundDurationSeconds: 30, + passedAuctionPlayerQueue: [], + phase: 'presenting', + revision: 1, + topTierAuctionPriorityThreshold: 'NONE', + }; + const biddingState = { + ...presentingState, + currentBidRoundDeadlineTimestampMS: 1780000030000, + phase: 'bidding', + revision: 2, + }; + const { + service, + auctionRedisCommandService, + auctionRedisStateReaderService, + } = createService({ + auction: { + findOne: jest.fn().mockResolvedValue(auction), + }, + }); + auctionRedisStateReaderService.readAuctionStateView + .mockResolvedValueOnce(presentingState) + .mockResolvedValueOnce(biddingState); + + await expect( + service.openBidding(matchId, { + auctionActionRequestId: '00000000-0000-4000-8000-000000000060', + clientObservedAuctionLifecycleId: 'life-1', + clientObservedCurrentAuctionPlayerOrderIndex: 0, + clientObservedPhase: 'presenting', + clientObservedRevision: 1, + }), + ).resolves.toMatchObject({ + phase: 'bidding', + revision: 2, + }); + expect( + auctionRedisCommandService.reserveActionRequest, + ).toHaveBeenCalledWith( + matchId.toString(), + expect.objectContaining({ + auctionActionRequestId: '00000000-0000-4000-8000-000000000060', + auctionActionType: 'open-bidding', + auctionStateTransitionId: + 'open-bidding:life-1:00000000-0000-4000-8000-000000000060', + clientObservedAuctionLifecycleId: 'life-1', + clientObservedCurrentAuctionPlayerOrderIndex: 0, + clientObservedPhase: 'presenting', + clientObservedRevision: 1, + }), + ); + expect(auctionRedisCommandService.applyTransition).toHaveBeenCalledWith( + matchId.toString(), + expect.objectContaining({ + actionRequest: expect.objectContaining({ + observedProcessingLeaseVersion: 1, + scopeKey: 'life-1:00000000-0000-4000-8000-000000000060', + }), + auctionStateTransitionId: + 'open-bidding:life-1:00000000-0000-4000-8000-000000000060', + deadline: { durationSeconds: 30, mode: 'set-relative' }, + expectedPhase: 'presenting', + expectedRevision: 1, + liveStatePatch: expect.objectContaining({ + currentHighestBidPointAmount: 0, + currentHighestBidderTeamIndex: -1, + phase: 'bidding', + 'team:1:assignedAuctionTeamMemberCount': 1, + 'team:1:remainingBidPointAmount': 1000, + }), + }), + ); + const transitionInput = + auctionRedisCommandService.applyTransition.mock.calls[0][1]; + expect(JSON.parse(transitionInput.durabilityPayloadJson)).toMatchObject({ + afterAuctionMongoProjection: expect.objectContaining({ + phase: 'bidding', + revision: 2, + }), + auctionActionType: 'open-bidding', + historyMutation: { type: 'append' }, + matchSideEffectMutation: { type: 'none' }, + snapshotBefore: expect.objectContaining({ + phase: 'presenting', + }), + }); + }); + + it('places bids through Redis for redis-v1 auctions', 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(), + matchId, + auctionEngineVersion: 'redis-v1', + }; + const biddingState = { + auctionLifecycleId: 'life-1', + auctionTeams: [ + { + teamIndex: 1, + captainUserId: captainUserId.toString(), + remainingBidPointAmount: 1000, + members: [], + }, + ], + currentBidRoundPlayerUserId: playerUserId.toString(), + phase: 'bidding', + revision: 2, + }; + const afterBidState = { + ...biddingState, + currentHighestBidderTeamIndex: 1, + currentHighestBidPointAmount: 120, + revision: 3, + }; + const { + service, + auctionRedisCommandService, + auctionRedisStateReaderService, + } = createService({ + auction: { + findOne: jest.fn().mockResolvedValue(auction), + }, + }); + auctionRedisStateReaderService.readAuctionStateView + .mockResolvedValueOnce(biddingState) + .mockResolvedValueOnce(afterBidState); + + await expect( + service.placeBid({ + amount: 120, + bidRequestId: '00000000-0000-4000-8000-000000000050', + matchId, + teamIndex: 1, + }), + ).resolves.toMatchObject({ + currentHighestBidderTeamIndex: 1, + currentHighestBidPointAmount: 120, + revision: 3, + }); + expect(auctionRedisCommandService.placeBid).toHaveBeenCalledWith( + matchId.toString(), + expect.objectContaining({ + bidPointAmount: 120, + bidderTeamIndex: 1, + bidderUserId: captainUserId.toString(), + clientObservedAuctionLifecycleId: 'life-1', + clientObservedCurrentBidRoundPlayerUserId: playerUserId.toString(), + }), + ); + }); + + 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(); + const playerUserId = new mongoose.Types.ObjectId(); + const biddingContext = { + auctionLifecycleId: 'life-1', + bidderTeamCaptainUserId: captainUserId.toString(), + currentBidRoundPlayerUserId: playerUserId.toString(), + phase: 'bidding', + }; + const auctionBidHistoryEntry = { + bidderTeamIndex: 1, + bidderUserId: captainUserId.toString(), + bidPlacedAtTimestampMS: 1780000000000, + bidPointAmount: 120, + }; + const { + connectionService, + service, + auctionRedisCommandService, + auctionRedisStateReaderService, + } = createService({}); + auctionRedisStateReaderService.readBidContext.mockResolvedValueOnce( + biddingContext, + ); + auctionRedisCommandService.placeBid.mockResolvedValueOnce({ + auctionBidHistoryEntry, + bidRequestId: '00000000-0000-4000-8000-000000000050', + currentBidRoundDeadlineTimestampMS: 1780000030000, + currentHighestBidderTeamIndex: 1, + currentHighestBidPointAmount: 120, + currentServerTimestampMS: 1780000000000, + ok: true, + revision: 3, + }); + + await expect( + service.placeBidDelta({ + amount: 120, + bidRequestId: '00000000-0000-4000-8000-000000000050', + matchId, + teamIndex: 1, + }), + ).resolves.toEqual( + expect.objectContaining({ + auctionBidHistoryEntry, + auctionLifecycleId: 'life-1', + bidRequestId: '00000000-0000-4000-8000-000000000050', + bidServerTiming: expect.objectContaining({ + redisBidCommandDurationMS: expect.any(Number), + redisBidContextReadDurationMS: expect.any(Number), + serviceTotalDurationMS: expect.any(Number), + }), + currentBidRoundDeadlineTimestampMS: 1780000030000, + currentHighestBidderTeamIndex: 1, + currentHighestBidPointAmount: 120, + currentServerTimestampMS: 1780000000000, + revision: 3, + }), + ); + expect( + auctionRedisStateReaderService.readAuctionStateView, + ).not.toHaveBeenCalled(); + expect(connectionService.getModel).not.toHaveBeenCalledWith('auction'); + }); + + it('includes redis bid diagnostics and timing on realtime bid rejection', async () => { + const matchId = new mongoose.Types.ObjectId(); + const captainUserId = new mongoose.Types.ObjectId(); + const playerUserId = new mongoose.Types.ObjectId(); + const { + service, + auctionRedisCommandService, + auctionRedisStateReaderService, + } = createService({}); + auctionRedisStateReaderService.readBidContext.mockResolvedValueOnce({ + auctionLifecycleId: 'life-1', + bidderTeamCaptainUserId: captainUserId.toString(), + currentBidRoundPlayerUserId: playerUserId.toString(), + phase: 'bidding', + }); + auctionRedisCommandService.placeBid.mockResolvedValueOnce({ + bidRequestId: 'bid-1', + code: 'EXPIRED', + currentBidRoundDeadlineTimestampMS: 1780000002500, + currentServerTimestampMS: 1780000003000, + rejected: true, + }); + + try { + await service.placeBidDelta({ + amount: 120, + bidRequestId: 'bid-1', + matchId, + teamIndex: 1, + }); + throw new Error('Expected bid rejection.'); + } catch (error) { + const response = (error as { getResponse: () => unknown }).getResponse(); + expect(response).toEqual( + expect.objectContaining({ + bidDiagnostics: { + currentBidRoundDeadlineTimestampMS: 1780000002500, + currentServerTimestampMS: 1780000003000, + }, + bidServerTiming: expect.objectContaining({ + redisBidCommandDurationMS: expect.any(Number), + redisBidContextReadDurationMS: expect.any(Number), + serviceTotalDurationMS: expect.any(Number), + }), + code: 'EXPIRED', + message: 'Bid deadline has already expired.', + }), + ); + } + }); + + it('syncs match teams when a redis-v1 auction completes', async () => { + const matchId = new mongoose.Types.ObjectId(); + const captainUserId = new mongoose.Types.ObjectId(); + const memberUserId = new mongoose.Types.ObjectId(); + const auction = { + _id: new mongoose.Types.ObjectId(), + matchId, + auctionEngineVersion: 'redis-v1', + }; + const soldState = { + auctionLifecycleId: 'life-1', + auctionTeams: [ + { + teamIndex: 1, + captainUserId: captainUserId.toString(), + remainingBidPointAmount: 970, + members: [ + { + userId: memberUserId.toString(), + assignedPosition: 'ADC', + memberAcquisitionBidPointAmount: 30, + }, + ], + }, + ], + auctionPlayerOrder: [{ userId: memberUserId.toString() }], + bidRoundExtensionSeconds: 5, + currentAuctionHistorySequence: 2, + currentAuctionPlayerOrderIndex: 0, + currentAuctionRound: 1, + initialTeamBidPointAmount: 1000, + maximumBidRoundDurationSeconds: 30, + passedAuctionPlayerQueue: [], + phase: 'sold', + revision: 3, + topTierAuctionPriorityThreshold: 'NONE', + }; + const completeState = { + ...soldState, + auctionCompletedAtTimestampMS: 1780000100000, + phase: 'complete', + revision: 4, + }; + const match = { + participants: [ + { + userId: captainUserId, + preferredPositions: [{ position: 'TOP', priority: 1 }], + }, + { + userId: memberUserId, + preferredPositions: [{ position: 'ADC', priority: 1 }], + }, + ], + status: 'team-built', + teams: [], + teamBuiltAt: undefined, + save: jest.fn().mockResolvedValue(undefined), + }; + const { + service, + auctionRedisCommandService, + auctionRedisStateReaderService, + tournamentCodeService, + tournamentResultService, + } = createService({ + auction: { + findOne: jest.fn().mockResolvedValue(auction), + }, + match: { + findById: jest.fn().mockResolvedValue(match), + }, + }); + auctionRedisStateReaderService.readAuctionStateView + .mockResolvedValueOnce(soldState) + .mockResolvedValueOnce(completeState); + + await expect(service.next(matchId)).resolves.toMatchObject({ + phase: 'complete', + revision: 4, + }); + const [, transitionInput] = + auctionRedisCommandService.applyTransition.mock.calls.at(-1) ?? []; + expect(JSON.parse(transitionInput.durabilityPayloadJson)).toMatchObject({ + afterAuctionMongoProjection: { + matchSideEffectStatus: 'pending', + phase: 'complete', + }, + auctionActionType: 'complete', + matchSideEffectMutation: { type: 'syncMatchTeamsAfterComplete' }, + }); + expect(match.teams).toEqual([]); + expect(match.save).not.toHaveBeenCalled(); + expect(tournamentCodeService.reserveForMatch).not.toHaveBeenCalled(); + expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled(); + }); + it('appends a chat message and keeps only the latest 200 messages', async () => { const matchId = new mongoose.Types.ObjectId(); const userId = new mongoose.Types.ObjectId(); @@ -300,21 +1552,21 @@ describe('AuctionService', () => { await service.start({ matchId, communityId, + startAuctionRequestId: '00000000-0000-4000-8000-000000000002', captains: [ { teamIndex: 1, userId: userIds[0] }, { teamIndex: 2, userId: userIds[1] }, ], - initialPoints: 1000, - maxTimerSeconds: 30, - bidExtensionSeconds: 5, - topTierThreshold: 'NONE', - manualTopTierUserIds: [], + initialTeamBidPointAmount: 1000, + maximumBidRoundDurationSeconds: 30, + bidRoundExtensionSeconds: 5, + topTierAuctionPriorityThreshold: 'NONE', + manualTopTierAuctionPriorityUserIds: [], }); 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); @@ -413,15 +1665,16 @@ describe('AuctionService', () => { await service.start({ matchId, communityId, + startAuctionRequestId: '00000000-0000-4000-8000-000000000003', captains: [ { teamIndex: 1, userId: userIds[0] }, { teamIndex: 2, userId: userIds[1] }, ], - initialPoints: 1000, - maxTimerSeconds: 30, - bidExtensionSeconds: 5, - topTierThreshold: 'NONE', - manualTopTierUserIds: [], + initialTeamBidPointAmount: 1000, + maximumBidRoundDurationSeconds: 30, + bidRoundExtensionSeconds: 5, + topTierAuctionPriorityThreshold: 'NONE', + manualTopTierAuctionPriorityUserIds: [], }); const firstPlayerSnapshot = auctionCreate.mock.calls[0][0].order.find( @@ -459,6 +1712,91 @@ describe('AuctionService', () => { expect(auction.save).not.toHaveBeenCalled(); }); + it('rejects bids that do not reserve minimum points for remaining team slots', async () => { + const matchId = new mongoose.Types.ObjectId(); + const auction = { + _id: new mongoose.Types.ObjectId(), + matchId, + phase: 'bidding', + teams: [ + { + teamIndex: 1, + captainUserId: new mongoose.Types.ObjectId(), + points: 1000, + members: [], + }, + ], + currentBid: 100, + currentDeadline: new Date(), + maxTimerSeconds: 30, + bidExtensionSeconds: 5, + bids: [], + save: jest.fn().mockResolvedValue(undefined), + toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }), + }; + const { service } = createService({ + auction: { + findOne: jest.fn().mockResolvedValue(auction), + }, + }); + + await expect( + service.placeBid({ + matchId, + teamIndex: 1, + amount: 980, + }), + ).rejects.toThrow('Bid must reserve minimum points for remaining slots.'); + expect(auction.save).not.toHaveBeenCalled(); + }); + + it('allows bids up to the maximum after reserving minimum points', async () => { + const matchId = new mongoose.Types.ObjectId(); + const captainUserId = new mongoose.Types.ObjectId(); + const auction = { + _id: new mongoose.Types.ObjectId(), + matchId, + phase: 'bidding', + teams: [ + { + teamIndex: 1, + captainUserId, + points: 1000, + members: [], + }, + ], + currentBid: 100, + currentDeadline: new Date(), + maxTimerSeconds: 30, + bidExtensionSeconds: 5, + bids: [], + save: jest.fn().mockResolvedValue(undefined), + toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }), + }; + const { service } = createService({ + auction: { + findOne: jest.fn().mockResolvedValue(auction), + }, + }); + + await service.placeBid({ + matchId, + teamIndex: 1, + amount: 970, + }); + + expect(auction.currentBid).toBe(970); + expect(auction.currentBidderTeamIndex).toBe(1); + expect(auction.bids).toEqual([ + expect.objectContaining({ + teamIndex: 1, + amount: 970, + bidderUserId: captainUserId, + }), + ]); + expect(auction.save).toHaveBeenCalledTimes(1); + }); + it('extends a short bid deadline using the configured bid extension seconds', async () => { const now = new Date('2026-05-02T00:00:00.000Z'); jest.useFakeTimers().setSystemTime(now); @@ -497,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); }); @@ -736,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, @@ -838,6 +2178,163 @@ 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(); + const auctionId = new mongoose.Types.ObjectId(); + const session = { + startTransaction: jest.fn(), + commitTransaction: jest.fn().mockResolvedValue(undefined), + abortTransaction: jest.fn().mockResolvedValue(undefined), + endSession: jest.fn().mockResolvedValue(undefined), + }; + const auction = { + _id: auctionId, + auctionEngineVersion: 'redis-v1', + auctionLifecycleId: 'life-1', + matchId, + matchSideEffectRevision: 0, + deleteOne: jest.fn().mockResolvedValue(undefined), + }; + const match = { + gameSchedule: [{ gameNumber: 1, teamAIndex: 1, teamBIndex: 2 }], + communityId, + status: 'team-built', + teams: [{ teamIndex: 1 }], + tournamentCodeIds: [new mongoose.Types.ObjectId()], + participants: [{ excluded: true }, { excluded: false }], + result: { games: [] }, + resultPollState: { state: 'polling' }, + teamBuiltAt: new Date(), + save: jest.fn().mockResolvedValue(undefined), + }; + const sideEffectDeleteMany = jest.fn().mockReturnValue({ + session: jest.fn().mockResolvedValue(undefined), + }); + const { + service, + connectionService, + tournamentCodeService, + tournamentResultService, + auctionHistoryModel, + auctionRedisCommandService, + auctionRedisService, + } = createService({ + auction: { + findOne: jest.fn().mockReturnValue({ + session: jest.fn().mockResolvedValue(auction), + }), + }, + auctionSideEffectApplication: { + deleteMany: sideEffectDeleteMany, + }, + match: { + findById: jest.fn().mockReturnValue({ + session: jest.fn().mockResolvedValue(match), + }), + }, + }); + connectionService.createSession.mockResolvedValue(session); + const redisClient = auctionRedisService.raw(); + redisClient.sendCommand + .mockResolvedValueOnce(1) + .mockResolvedValueOnce(['0', []]); + + await service.reset({ + auctionActionRequestId: '00000000-0000-4000-8000-000000000080', + clientObservedAuctionLifecycleId: 'life-1', + clientObservedCurrentAuctionPlayerOrderIndex: 0, + clientObservedCurrentBidRoundPlayerUserId: 'player-1', + clientObservedPhase: 'bidding', + clientObservedRevision: 4, + matchId, + communityId, + }); + + expect( + auctionRedisCommandService.reserveActionRequest, + ).not.toHaveBeenCalled(); + expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled(); + expect(tournamentCodeService.releaseFromMatch).toHaveBeenCalledWith(match); + expect(tournamentResultService.cancelPolling).toHaveBeenCalledWith(match); + expect(match).toMatchObject({ + gameSchedule: [], + result: undefined, + resultPollState: undefined, + status: 'recruiting', + teamBuiltAt: undefined, + teams: [], + tournamentCodeIds: [], + }); + expect(match.participants).toEqual([ + { excluded: false }, + { excluded: false }, + ]); + expect(match.save).toHaveBeenCalledWith({ session }); + expect(sideEffectDeleteMany).toHaveBeenCalledWith({ auctionId }); + expect(auctionHistoryModel.deleteMany).toHaveBeenCalledWith({ + auctionId, + }); + expect(auction.deleteOne).toHaveBeenCalledWith({ session }); + expect(redisClient.sendCommand).toHaveBeenCalledWith( + expect.arrayContaining([ + 'auction:bidRoundDeadlineQueue', + matchId.toString(), + 'life-1', + ]), + ); + expect(session.commitTransaction).toHaveBeenCalledTimes(1); + }); + it('undoes to a history snapshot and releases resources when leaving complete', async () => { const matchId = new mongoose.Types.ObjectId(); const communityId = new mongoose.Types.ObjectId(); @@ -893,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( @@ -925,4 +2426,159 @@ describe('AuctionService', () => { ); expect(session.commitTransaction).toHaveBeenCalledTimes(1); }); + + it('uses Redis transition when undoing a redis-v1 auction', async () => { + const matchId = new mongoose.Types.ObjectId(); + const communityId = new mongoose.Types.ObjectId(); + const auctionId = new mongoose.Types.ObjectId(); + const session = { + startTransaction: jest.fn(), + commitTransaction: jest.fn().mockResolvedValue(undefined), + abortTransaction: jest.fn().mockResolvedValue(undefined), + endSession: jest.fn().mockResolvedValue(undefined), + }; + const auction = { + _id: auctionId, + auctionEngineVersion: 'redis-v1', + auctionLifecycleId: 'life-1', + completedAt: new Date(), + matchId, + matchSideEffectRevision: 0, + }; + const snapshot = { + _id: auctionId.toString(), + auctionLifecycleId: 'life-1', + auctionPlayerOrder: [{ userId: 'player-1', passCount: 0 }], + auctionTeams: [], + bidRoundExtensionSeconds: 5, + currentAuctionHistorySequence: 3, + currentAuctionPlayerOrderIndex: 0, + currentAuctionRound: 1, + currentHighestBidPointAmount: 0, + currentHighestBidderTeamIndex: -1, + initialTeamBidPointAmount: 1000, + matchId: matchId.toString(), + maximumBidRoundDurationSeconds: 30, + passedAuctionPlayerQueue: [], + phase: 'bidding', + revision: 4, + topTierAuctionPriorityThreshold: 'NONE', + }; + const match = { + communityId, + }; + const currentRedisState = { + auctionLifecycleId: 'life-1', + auctionPlayerOrder: [{ userId: 'player-2', passCount: 0 }], + auctionTeams: [], + bidRoundExtensionSeconds: 5, + currentAuctionHistorySequence: 5, + currentAuctionPlayerOrderIndex: 0, + currentAuctionRound: 1, + currentBidRoundPlayerUserId: 'player-2', + currentHighestBidPointAmount: 0, + currentHighestBidderTeamIndex: -1, + initialTeamBidPointAmount: 1000, + maximumBidRoundDurationSeconds: 30, + passedAuctionPlayerQueue: [], + phase: 'complete', + revision: 5, + topTierAuctionPriorityThreshold: 'NONE', + }; + const restoredRedisState = { + ...snapshot, + currentServerTimestampMS: 1780000000000, + phase: 'bidding', + revision: 6, + }; + const historyFindOneQuery = { + session: jest.fn().mockReturnValue({ + lean: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ + auctionId, + matchId, + sequence: 3, + snapshotBefore: snapshot, + }), + }), + }), + }; + 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), + }), + }, + }); + connectionService.createSession.mockResolvedValue(session); + auctionRedisStateReaderService.readAuctionStateView + .mockResolvedValueOnce(currentRedisState) + .mockResolvedValueOnce(restoredRedisState); + + await expect( + service.undoTo({ + auctionActionRequestId: '00000000-0000-4000-8000-000000000070', + clientObservedAuctionLifecycleId: 'life-1', + clientObservedCurrentAuctionPlayerOrderIndex: 0, + clientObservedCurrentBidRoundPlayerUserId: 'player-2', + clientObservedPhase: 'complete', + clientObservedRevision: 5, + matchId, + communityId, + sequence: 3, + }), + ).resolves.toBe(restoredRedisState); + + expect(auctionReplaceOne).not.toHaveBeenCalled(); + expect( + auctionRedisCommandService.reserveActionRequest, + ).toHaveBeenCalledWith( + matchId.toString(), + expect.objectContaining({ + auctionActionRequestId: '00000000-0000-4000-8000-000000000070', + auctionStateTransitionId: + 'undo:life-1:00000000-0000-4000-8000-000000000070', + clientObservedAuctionLifecycleId: 'life-1', + clientObservedCurrentAuctionPlayerOrderIndex: 0, + clientObservedCurrentBidRoundPlayerUserId: 'player-2', + clientObservedPhase: 'complete', + clientObservedRevision: 5, + }), + ); + expect(auctionRedisCommandService.applyTransition).toHaveBeenCalledTimes(1); + const transitionInput = + auctionRedisCommandService.applyTransition.mock.calls[0][1]; + expect(transitionInput.expectedPhase).toBe('complete'); + expect(transitionInput.deadline).toEqual({ + durationSeconds: 30, + mode: 'set-relative', + }); + const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson); + expect(durabilityPayload).toMatchObject({ + auctionActionType: 'undo', + historyMutation: { + targetHistorySequence: 3, + type: 'deleteAfterSequenceAndAppendUndo', + }, + matchSideEffectMutation: { + type: 'undoCompletedAuctionSideEffects', + }, + }); + expect(session.commitTransaction).toHaveBeenCalledTimes(1); + }); }); diff --git a/apps/api/src/modules/auction/auction.service.ts b/apps/api/src/modules/auction/auction.service.ts index 557bc8eb..3737ea2f 100644 --- a/apps/api/src/modules/auction/auction.service.ts +++ b/apps/api/src/modules/auction/auction.service.ts @@ -1,11 +1,13 @@ import { BadRequestException, + ConflictException, Injectable, InternalServerErrorException, Logger, NotFoundException, } from '@nestjs/common'; import { randomUUID } from 'crypto'; +import { performance } from 'perf_hooks'; import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; import { @@ -15,6 +17,7 @@ import { AuctionPlayerSnapshot, AuctionTeam, AuctionTopTierThreshold, + MatchDocument, MatchParticipant, MatchTeamMember, Position, @@ -24,41 +27,110 @@ import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.se import type { RiotPlatformRoute, RiotRegionalRoute } from '../riot/riot.types'; import { TournamentCodeService } from '../tournament-code/tournament-code.service'; import { TournamentResultService } from '../tournament-result/tournament-result.service'; +import { + AuctionRedisCommandService, + type AuctionBidCommandResult, +} from './redis/auction-redis-command.service'; +import { buildAuctionRedisKeys } from './redis/auction-redis.keys'; +import { + buildAuctionRedisLiveStatePatchFromStructure, + buildAuctionRedisStructureState, + convertLegacyAuctionTeamsToRedisTeams, + stringifyAuctionRedisStructureState, +} from './redis/auction-redis-projection'; +import { AuctionRedisService } from './redis/auction-redis.service'; +import { AuctionRedisStateReaderService } from './redis/auction-redis-state-reader.service'; +import { shouldHydrateRedisAuctionState } from './redis/auction-redis.state'; +// [AUCTION-DEBUG] 경매 "중복 멤버" 조사용 임시 계측. 조사 종료 후 제거 대상. +import { recordNewRelicCustomEvent } from '../global/observability/new-relic'; const AUCTION_MAX_TEAM_SIZE = 5; +const AUCTION_MIN_BID_POINTS = 10; const AUCTION_BACKGROUND_ENRICHMENT_CONCURRENCY = 1; const AUCTION_ENRICHMENT_COOLDOWN_MS = 3 * 60 * 60 * 1000; const AUCTION_CHAT_MAX_MESSAGES = 200; const AUCTION_CHAT_MAX_MESSAGE_LENGTH = 300; const AUCTION_CHAT_MAX_DISPLAY_NAME_LENGTH = 24; +const AUCTION_MAX_STORED_BID_HISTORY_COUNT = 1000; +const AUCTION_MAX_STORED_BID_REQUEST_RESULT_COUNT = 500; +const AUCTION_BID_REQUEST_REPLAY_WINDOW_MS = 5 * 60 * 1000; +const AUCTION_MAX_STORED_ACTION_REQUEST_RESULT_COUNT = 500; +const AUCTION_ACTION_REQUEST_REPLAY_WINDOW_MS = 5 * 60 * 1000; +const AUCTION_ACTION_REQUEST_LEASE_DURATION_MS = 15 * 1000; +const AUCTION_REHYDRATE_LOCK_TTL_MS = 5 * 1000; +const AUCTION_REHYDRATE_LOCK_WAIT_MS = 50; +const AUCTION_HISTORY_LIST_LIMIT = 100; +const AUCTION_HISTORY_LIST_CACHE_TTL_MS = 2 * 1000; +const AUCTION_HISTORY_LIST_CACHE_MAX_ENTRIES = 256; interface StartAuctionParams { matchId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; + startAuctionRequestId: string; + actorUserId?: mongoose.Types.ObjectId; captains: { teamIndex: number; userId: mongoose.Types.ObjectId; - initialPoints?: number; + initialTeamBidPointAmount?: number; }[]; - initialPoints: number; - maxTimerSeconds: number; - bidExtensionSeconds: number; - topTierThreshold: AuctionTopTierThreshold; - manualTopTierUserIds: mongoose.Types.ObjectId[]; + initialTeamBidPointAmount: number; + maximumBidRoundDurationSeconds: number; + bidRoundExtensionSeconds: number; + topTierAuctionPriorityThreshold: AuctionTopTierThreshold; + manualTopTierAuctionPriorityUserIds: mongoose.Types.ObjectId[]; } interface PlaceBidParams { matchId: mongoose.Types.ObjectId; teamIndex: number; amount: number; + bidRequestId?: string; bidderUserId?: mongoose.Types.ObjectId; + clientObservedAuctionLifecycleId?: string; + clientObservedCurrentBidRoundPlayerUserId?: string; } -interface MarkSoldParams { +interface AuctionStructureActionRequestParams { + auctionActionRequestId?: string; + clientObservedAuctionLifecycleId?: string; + clientObservedCurrentAuctionPlayerOrderIndex?: number; + clientObservedCurrentBidRoundPlayerUserId?: string; + clientObservedPhase?: string; + clientObservedRevision?: number; + shouldBroadcastStateAfterDurability?: boolean; +} + +interface MarkSoldParams extends AuctionStructureActionRequestParams { matchId: mongoose.Types.ObjectId; assignedPosition?: Position; } +interface ReservedRedisActionRequestContext { + actionRequest: { + observedProcessingLeaseVersion: number; + processingOwnerToken: string; + scopeKey: string; + }; + auctionStateTransitionId: string; + expectedAuctionLifecycleId: string; + expectedCurrentAuctionPlayerOrderIndex?: number; + expectedCurrentBidRoundPlayerUserId?: string; + expectedPhase: string; + expectedRevision: number; +} + +interface ReplayedRedisActionRequestContext { + currentServerTimestampMS: number; + replay: true; + requiresRefetch: boolean; + responseJson?: string; + revision?: number; +} + +type RedisActionRequestContext = + | ReservedRedisActionRequestContext + | ReplayedRedisActionRequestContext; + interface AppendChatMessageParams { matchId: mongoose.Types.ObjectId; userId?: mongoose.Types.ObjectId; @@ -73,26 +145,80 @@ export interface AuctionHistoryView { takenAt: Date; } +interface AuctionHistorySummaryRecord { + sequence: number; + action: AuctionActionType; + takenAt: Date; +} + +interface AuctionHistoryListCacheEntry { + entries: AuctionHistoryView[]; + expiresAtTimestampMS: number; +} + +export type AuctionStateResponse = AuctionDocument | Record; + +export interface AuctionBidDeltaResponse { + auctionBidHistoryEntry: Record; + auctionLifecycleId?: string; + bidServerTiming?: AuctionBidServerTiming; + bidRequestId: string; + currentBidRoundDeadlineTimestampMS: number; + currentHighestBidderTeamIndex: number; + currentHighestBidPointAmount: number; + currentServerTimestampMS: number; + revision: number; +} + +export interface AuctionBidServerTiming { + fallbackFullStatePath?: boolean; + redisBidCommandDurationMS?: number; + redisBidContextReadDurationMS?: number; + serviceTotalDurationMS?: number; +} + +export interface AuctionBidRejectDiagnostics { + currentBidRoundDeadlineTimestampMS?: number; + currentServerTimestampMS?: number; +} + interface AuctionEnrichmentTarget { userId: mongoose.Types.ObjectId; puuid: string; } +function isMongoDuplicateKeyError(error: unknown): boolean { + return ( + typeof error === 'object' && + error !== null && + Number((error as { code?: unknown }).code) === 11000 + ); +} + @Injectable() export class AuctionService { private readonly logger = new Logger(AuctionService.name); + private readonly auctionHistoryListCache = new Map< + string, + AuctionHistoryListCacheEntry + >(); constructor( private readonly connectionService: ConnectionService, private readonly enrichmentService: RiotAccountEnrichmentService, private readonly tournamentCodeService: TournamentCodeService, private readonly tournamentResultService: TournamentResultService, + private readonly auctionRedisService: AuctionRedisService, + private readonly auctionRedisCommandService: AuctionRedisCommandService, + private readonly auctionRedisStateReaderService: AuctionRedisStateReaderService, ) {} public async start(params: StartAuctionParams): Promise { const MatchModel = await this.connectionService.getModel('match'); const UserModel = await this.connectionService.getModel('user'); const AuctionModel = await this.connectionService.getModel('auction'); + const AuctionHistoryModel = + await this.connectionService.getModel('auctionHistory'); const CommunityModel = await this.connectionService.getModel('community'); const match = await MatchModel.findById(params.matchId); @@ -103,13 +229,31 @@ export class AuctionService { const existing = await AuctionModel.findOne({ matchId: params.matchId }); if (existing) { - throw new BadRequestException('Auction already exists for this match.'); + if (existing.startAuctionRequestId === params.startAuctionRequestId) { + return existing; + } + if (this.isRestartableResetRedisAuction(existing)) { + await this.clearRedisAuctionRuntimeForLifecycle( + params.matchId.toString(), + existing.auctionLifecycleId, + ); + await AuctionHistoryModel.deleteMany({ auctionId: existing._id }); + await AuctionModel.deleteOne({ _id: existing._id }); + } else if (this.isRedisResetStillApplying(existing)) { + throw new BadRequestException( + 'Auction reset is still being applied. Please try again shortly.', + ); + } else { + throw new BadRequestException('Auction already exists for this match.'); + } } const activeParticipants = this.applyAuctionCut(match); const desiredAuctionCount = activeParticipants.length; if (desiredAuctionCount < 10) { - throw new BadRequestException('Not enough participants (need at least 10).'); + throw new BadRequestException( + 'Not enough participants (need at least 10).', + ); } const expectedCaptainCount = desiredAuctionCount / AUCTION_MAX_TEAM_SIZE; if (params.captains.length !== expectedCaptainCount) { @@ -141,7 +285,8 @@ export class AuctionService { const enrichCooldownCutoff = Date.now() - AUCTION_ENRICHMENT_COOLDOWN_MS; const enrichTargets = basePlayerUsers.flatMap((user) => { const account = - user.riotAccounts.find((entry) => entry.isPrimary) ?? user.riotAccounts[0]; + user.riotAccounts.find((entry) => entry.isPrimary) ?? + user.riotAccounts[0]; if (!account?.puuid) return []; if (this.wasRecentlyRefreshed(account, enrichCooldownCutoff)) return []; return [{ userId: user._id, puuid: account.puuid }]; @@ -183,37 +328,116 @@ export class AuctionService { const shuffledOrder = this.shuffleAuctionPlayerOrder(order); const prioritizedOrder = this.applyTopTierPriority( shuffledOrder, - params.topTierThreshold, - params.manualTopTierUserIds, + params.topTierAuctionPriorityThreshold, + params.manualTopTierAuctionPriorityUserIds, ); - const auction = await AuctionModel.create({ - matchId: params.matchId, - phase: 'presenting', - teams: params.captains.map((c) => ({ - teamIndex: c.teamIndex, - captainUserId: c.userId, - points: c.initialPoints ?? params.initialPoints, - members: [], - })), - order: prioritizedOrder, - passedQueue: [], - auctionRound: 1, - currentIndex: 0, - bids: [], - currentBid: 0, - maxTimerSeconds: params.maxTimerSeconds, - bidExtensionSeconds: params.bidExtensionSeconds, - initialPoints: params.initialPoints, - topTierThreshold: params.topTierThreshold, - manualTopTierUserIds: - params.topTierThreshold === 'MANUAL' ? params.manualTopTierUserIds : [], - startedAt: new Date(), - }); + const auctionId = new mongoose.Types.ObjectId(); + const auctionStartedAtTimestampMS = + await this.auctionRedisService.getCurrentRedisTimestampMS(); + const startAuctionStateTransitionId = `start:${auctionId.toString()}:${params.startAuctionRequestId}`; + const auctionLifecycleId = `auction:${auctionId.toString()}:${params.startAuctionRequestId}`; + const legacyTeams = params.captains.map((c) => ({ + teamIndex: c.teamIndex, + captainUserId: c.userId, + points: c.initialTeamBidPointAmount ?? params.initialTeamBidPointAmount, + members: [], + })); + const auctionTeams = convertLegacyAuctionTeamsToRedisTeams(legacyTeams); + const redisStructureInput = { + auctionPlayerOrder: prioritizedOrder, + auctionTeams, + bidRoundExtensionSeconds: params.bidRoundExtensionSeconds, + currentAuctionPlayerOrderIndex: 0, + currentAuctionRound: 1, + initialTeamBidPointAmount: params.initialTeamBidPointAmount, + manualTopTierAuctionPriorityUserIds: + params.topTierAuctionPriorityThreshold === 'MANUAL' + ? params.manualTopTierAuctionPriorityUserIds + : [], + maximumBidRoundDurationSeconds: params.maximumBidRoundDurationSeconds, + passedAuctionPlayerQueue: [], + topTierAuctionPriorityThreshold: params.topTierAuctionPriorityThreshold, + }; + const structureStateJson = + stringifyAuctionRedisStructureState(redisStructureInput); + const liveStatePatch = + buildAuctionRedisLiveStatePatchFromStructure(redisStructureInput); + let auction: AuctionDocument; + try { + auction = await AuctionModel.create({ + _id: auctionId, + matchId: params.matchId, + phase: 'presenting', + revision: 1, + auctionEngineVersion: 'redis-v1', + auctionLifecycleId, + lastAppliedAuctionStateTransitionId: startAuctionStateTransitionId, + currentAuctionHistorySequence: 1, + startAuctionRequestId: params.startAuctionRequestId, + startAuctionStateTransitionId, + auctionStartedAtTimestampMS, + auctionStartedByUserId: params.actorUserId, + matchSideEffectStatus: 'none', + matchSideEffectRevision: 0, + teams: legacyTeams, + order: prioritizedOrder, + passedQueue: [], + auctionRound: 1, + currentIndex: 0, + bids: [], + currentBid: 0, + maxTimerSeconds: params.maximumBidRoundDurationSeconds, + bidExtensionSeconds: params.bidRoundExtensionSeconds, + initialPoints: params.initialTeamBidPointAmount, + topTierThreshold: params.topTierAuctionPriorityThreshold, + manualTopTierUserIds: + params.topTierAuctionPriorityThreshold === 'MANUAL' + ? params.manualTopTierAuctionPriorityUserIds + : [], + startedAt: new Date(auctionStartedAtTimestampMS), + auctionTeams, + auctionPlayerOrder: prioritizedOrder, + passedAuctionPlayerQueue: [], + currentAuctionRound: 1, + currentAuctionPlayerOrderIndex: 0, + auctionBidHistory: [], + currentHighestBidPointAmount: 0, + maximumBidRoundDurationSeconds: params.maximumBidRoundDurationSeconds, + bidRoundExtensionSeconds: params.bidRoundExtensionSeconds, + initialTeamBidPointAmount: params.initialTeamBidPointAmount, + topTierAuctionPriorityThreshold: params.topTierAuctionPriorityThreshold, + manualTopTierAuctionPriorityUserIds: + params.topTierAuctionPriorityThreshold === 'MANUAL' + ? params.manualTopTierAuctionPriorityUserIds + : [], + }); + } catch (error) { + if (!isMongoDuplicateKeyError(error)) throw error; + const raceWinner = await AuctionModel.findOne({ + matchId: params.matchId, + }); + if (raceWinner?.startAuctionRequestId === params.startAuctionRequestId) { + return raceWinner; + } + throw new BadRequestException('Auction already exists for this match.'); + } await this.recordSnapshot(auction, 'start'); + await this.auctionRedisCommandService.hydrateState( + params.matchId.toString(), + { + auctionHistorySequence: 1, + auctionLifecycleId, + maximumBidRoundDurationSeconds: params.maximumBidRoundDurationSeconds, + liveStatePatch, + matchId: params.matchId.toString(), + phase: 'presenting', + revision: 0, + structureStateJson, + }, + ); match.status = 'team-built'; - match.teamBuiltAt = match.teamBuiltAt ?? new Date(); await match.save(); this.enqueueBackgroundOrderEnrichment({ auctionId: auction._id, @@ -234,6 +458,78 @@ export class AuctionService { return auction; } + public async getStateByMatchId( + matchId: mongoose.Types.ObjectId, + ): Promise { + const auction = await this.getByMatchId(matchId); + if (!this.isRedisV1Auction(auction)) return auction; + + const redisState = await this.readRedisAuctionStateOrRehydrate(auction); + if (!redisState) return auction; + + const mongoState = + typeof auction.toObject === 'function' + ? auction.toObject({ depopulate: true }) + : auction; + return { + ...this.cloneJson(mongoState), + ...redisState, + chatMessages: auction.chatMessages ?? [], + }; + } + + private async readRedisAuctionStateOrRehydrate( + auction: AuctionDocument, + ): Promise | null> { + const matchId = auction.matchId.toString(); + const mongoRevision = auction.revision ?? 0; + const mongoAuctionLifecycleId = auction.auctionLifecycleId; + if (!mongoAuctionLifecycleId || auction.phase === 'complete') { + return this.auctionRedisStateReaderService.readAuctionStateView(matchId); + } + + const liveIdentity = + await this.auctionRedisStateReaderService.readLiveStateIdentity(matchId); + const shouldHydrate = shouldHydrateRedisAuctionState({ + live: liveIdentity, + mongo: { + auctionLifecycleId: mongoAuctionLifecycleId, + revision: mongoRevision, + }, + }); + + if (!shouldHydrate) { + return this.auctionRedisStateReaderService.readAuctionStateView(matchId); + } + + const keys = buildAuctionRedisKeys(matchId); + const lockToken = randomUUID(); + const lockAcquired = await this.auctionRedisService.acquireTokenLock( + keys.rehydrateLockKey, + lockToken, + AUCTION_REHYDRATE_LOCK_TTL_MS, + ); + + if (lockAcquired) { + try { + await this.hydrateRedisStateFromAuctionDocument(auction); + } finally { + await this.auctionRedisService.releaseTokenLock( + keys.rehydrateLockKey, + lockToken, + ); + } + } else { + await new Promise((resolve) => + setTimeout(resolve, AUCTION_REHYDRATE_LOCK_WAIT_MS), + ); + } + + return this.auctionRedisStateReaderService.readAuctionStateView(matchId, { + shouldForceAuctionStateResync: true, + }); + } + public async appendChatMessage(params: AppendChatMessageParams): Promise<{ auction: AuctionDocument; message: AuctionChatMessage; @@ -274,24 +570,75 @@ export class AuctionService { throw new BadRequestException('Match does not belong to this community.'); } - const entries = await AuctionHistoryModel.find({ matchId: params.matchId }) - .sort({ sequence: -1 }) - .limit(100) - .lean() - .exec(); + const cacheKey = this.buildAuctionHistoryListCacheKey(params); + const cachedHistory = this.getCachedAuctionHistoryList(cacheKey); + if (cachedHistory) return cachedHistory; - return entries.map((entry) => ({ + const entries = (await AuctionHistoryModel.find({ matchId: params.matchId }) + .select({ _id: 0, action: 1, sequence: 1, takenAt: 1 }) + .sort({ sequence: -1 }) + .limit(AUCTION_HISTORY_LIST_LIMIT) + .lean() + .exec()) as AuctionHistorySummaryRecord[]; + + const history = entries.map((entry) => ({ sequence: entry.sequence, action: entry.action, actionLabel: this.formatHistoryActionLabel(entry.action), takenAt: entry.takenAt, })); + this.setCachedAuctionHistoryList(cacheKey, history); + return history; + } + + private buildAuctionHistoryListCacheKey(params: { + matchId: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + }): string { + return `${params.communityId.toString()}:${params.matchId.toString()}`; + } + + private getCachedAuctionHistoryList( + cacheKey: string, + ): AuctionHistoryView[] | null { + const cached = this.auctionHistoryListCache.get(cacheKey); + if (!cached) return null; + if (cached.expiresAtTimestampMS <= Date.now()) { + this.auctionHistoryListCache.delete(cacheKey); + return null; + } + return cached.entries; + } + + private setCachedAuctionHistoryList( + cacheKey: string, + entries: AuctionHistoryView[], + ): void { + if ( + !this.auctionHistoryListCache.has(cacheKey) && + this.auctionHistoryListCache.size >= + AUCTION_HISTORY_LIST_CACHE_MAX_ENTRIES + ) { + const oldestKey = this.auctionHistoryListCache.keys().next().value as + | string + | undefined; + if (oldestKey) this.auctionHistoryListCache.delete(oldestKey); + } + this.auctionHistoryListCache.set(cacheKey, { + entries, + expiresAtTimestampMS: Date.now() + AUCTION_HISTORY_LIST_CACHE_TTL_MS, + }); } public async openBidding( matchId: mongoose.Types.ObjectId, - ): Promise { + actionRequest: AuctionStructureActionRequestParams = {}, + ): Promise { const auction = await this.getByMatchId(matchId); + this.assertLiveAuctionOperationSupported(auction); + if (this.isRedisV1Auction(auction)) { + return this.openRedisBidding(auction, actionRequest); + } if (auction.phase !== 'presenting') { throw new BadRequestException('Auction is not in presenting phase.'); } @@ -304,8 +651,13 @@ export class AuctionService { return auction; } - public async placeBid(params: PlaceBidParams): Promise { + public async placeBid(params: PlaceBidParams): Promise { + this.assertValidBidPointAmount(params.amount); const auction = await this.getByMatchId(params.matchId); + this.assertLiveAuctionOperationSupported(auction); + if (this.isRedisV1Auction(auction)) { + return this.placeRedisBid(auction, params); + } if (auction.phase !== 'bidding') { throw new BadRequestException('Auction is not in bidding phase.'); } @@ -318,6 +670,11 @@ export class AuctionService { throw new BadRequestException('Bid exceeds team points.'); } this.assertTeamHasSlot(team); + if (params.amount > this.calculateMaxBidForTeam(team)) { + throw new BadRequestException( + 'Bid must reserve minimum points for remaining slots.', + ); + } // 임시 운영용: 클라이언트에서 선택한 팀장 모드를 신뢰하고 실제 로그인 사용자 검증은 건너뛴다. await this.recordSnapshot(auction, 'bid', params.bidderUserId); @@ -336,8 +693,578 @@ export class AuctionService { return auction; } - public async markSold(params: MarkSoldParams): Promise { + public async placeBidDelta( + params: PlaceBidParams, + ): Promise { + this.assertValidBidPointAmount(params.amount); + const redisBidDelta = + await this.tryPlaceRedisBidDeltaFromRealtimeState(params); + if (redisBidDelta) return redisBidDelta; + const auction = await this.getByMatchId(params.matchId); + this.assertLiveAuctionOperationSupported(auction); + if (this.isRedisV1Auction(auction)) { + return this.placeRedisBidDelta(auction, params); + } + return this.placeBid(params); + } + + private async openRedisBidding( + auction: AuctionDocument, + actionRequestParams: AuctionStructureActionRequestParams, + ): Promise { + const matchId = auction.matchId.toString(); + const state = await this.requireRedisAuctionState(matchId); + if (state.phase !== 'presenting') { + throw new BadRequestException('Auction is not in presenting phase.'); + } + const actionRequest = await this.reserveRedisStructureActionRequest({ + action: 'open-bidding', + matchId, + params: actionRequestParams, + state, + }); + if (this.isReplayedRedisActionRequestContext(actionRequest)) { + return this.resolveReplayedRedisActionRequest(matchId, actionRequest); + } + + const structureInput = this.buildRedisStructureInputFromState(state); + const liveStatePatch = { + ...buildAuctionRedisLiveStatePatchFromStructure(structureInput), + currentHighestBidPointAmount: 0, + currentHighestBidderTeamIndex: -1, + phase: 'bidding', + }; + return this.applyRedisStructureTransition({ + action: 'open-bidding', + actionRequest, + auction, + deadline: { + durationSeconds: structureInput.maximumBidRoundDurationSeconds, + mode: 'set-relative', + }, + expectedPhase: 'presenting', + liveStatePatch, + shouldBroadcastStateAfterDurability: + actionRequestParams.shouldBroadcastStateAfterDurability, + state, + structureInput, + }); + } + + private async placeRedisBid( + auction: AuctionDocument, + params: PlaceBidParams, + ): Promise { + const matchId = auction.matchId.toString(); + await this.executeRedisBid(auction, params); + return this.requireRedisAuctionState(matchId); + } + + private async placeRedisBidDelta( + auction: AuctionDocument, + params: PlaceBidParams, + ): Promise { + const serviceStartedAtMS = performance.now(); + const { redisBidCommandDurationMS, result, state } = + await this.executeRedisBid(auction, params); + const bidDelta = this.buildBidDeltaFromRedisBidResult(state, result); + bidDelta.bidServerTiming = this.roundBidServerTiming({ + fallbackFullStatePath: true, + redisBidCommandDurationMS, + serviceTotalDurationMS: performance.now() - serviceStartedAtMS, + }); + this.logSlowBidTiming(auction.matchId.toString(), bidDelta.bidServerTiming); + return bidDelta; + } + + private async tryPlaceRedisBidDeltaFromRealtimeState( + params: PlaceBidParams, + ): Promise { + const serviceStartedAtMS = performance.now(); + const matchId = params.matchId.toString(); + const bidContextReadStartedAtMS = performance.now(); + const bidContext = await this.auctionRedisStateReaderService.readBidContext( + matchId, + params.teamIndex, + ); + const redisBidContextReadDurationMS = + performance.now() - bidContextReadStartedAtMS; + if (!bidContext) return null; + if (bidContext.phase !== 'bidding') { + throw new BadRequestException('Auction is not in bidding phase.'); + } + if (!bidContext.bidderTeamCaptainUserId) { + throw new BadRequestException('Unknown team.'); + } + + const auctionLifecycleId = + params.clientObservedAuctionLifecycleId ?? bidContext.auctionLifecycleId; + const currentBidRoundPlayerUserId = + params.clientObservedCurrentBidRoundPlayerUserId ?? + bidContext.currentBidRoundPlayerUserId; + if (!auctionLifecycleId || !currentBidRoundPlayerUserId) { + throw new BadRequestException('Current bid round is not available.'); + } + + const redisBidCommandStartedAtMS = performance.now(); + const result = await this.auctionRedisCommandService.placeBid(matchId, { + bidPointAmount: params.amount, + bidderTeamIndex: params.teamIndex, + bidderUserId: bidContext.bidderTeamCaptainUserId, + bidRequestId: params.bidRequestId ?? randomUUID(), + clientObservedAuctionLifecycleId: auctionLifecycleId, + clientObservedCurrentBidRoundPlayerUserId: currentBidRoundPlayerUserId, + matchId, + maximumAuctionTeamMemberCount: AUCTION_MAX_TEAM_SIZE, + maximumStoredAuctionBidHistoryCount: AUCTION_MAX_STORED_BID_HISTORY_COUNT, + maximumStoredBidRequestResultCount: + AUCTION_MAX_STORED_BID_REQUEST_RESULT_COUNT, + minimumBidPointReservePerRemainingAuctionTeamMemberSlot: + AUCTION_MIN_BID_POINTS, + minimumBidRequestResultReplayWindowMS: + AUCTION_BID_REQUEST_REPLAY_WINDOW_MS, + }); + const redisBidCommandDurationMS = + performance.now() - redisBidCommandStartedAtMS; + if ('rejected' in result) { + const bidServerTiming = this.roundBidServerTiming({ + redisBidCommandDurationMS, + redisBidContextReadDurationMS, + serviceTotalDurationMS: performance.now() - serviceStartedAtMS, + }); + this.logSlowBidTiming(matchId, bidServerTiming); + throw this.createRedisBidRejectedException(result, bidServerTiming); + } + + const bidDelta = this.buildBidDeltaFromRedisBidResult( + { auctionLifecycleId: bidContext.auctionLifecycleId }, + result, + ); + bidDelta.bidServerTiming = this.roundBidServerTiming({ + redisBidCommandDurationMS, + redisBidContextReadDurationMS, + serviceTotalDurationMS: performance.now() - serviceStartedAtMS, + }); + this.logSlowBidTiming(matchId, bidDelta.bidServerTiming); + return bidDelta; + } + + private async executeRedisBid( + auction: AuctionDocument, + params: PlaceBidParams, + ): Promise<{ + redisBidCommandDurationMS: number; + result: Extract; + state: Record; + }> { + const serviceStartedAtMS = performance.now(); + const matchId = auction.matchId.toString(); + const state = await this.requireRedisAuctionState(matchId); + if (state.phase !== 'bidding') { + throw new BadRequestException('Auction is not in bidding phase.'); + } + + const auctionTeams = this.arrayFromState>( + state.auctionTeams, + ); + const team = auctionTeams.find( + (entry) => Number(entry.teamIndex) === params.teamIndex, + ); + if (!team) throw new BadRequestException('Unknown team.'); + + const auctionLifecycleId = + params.clientObservedAuctionLifecycleId ?? + this.stringFromState(state.auctionLifecycleId); + const currentBidRoundPlayerUserId = + params.clientObservedCurrentBidRoundPlayerUserId ?? + this.stringFromState(state.currentBidRoundPlayerUserId); + if (!auctionLifecycleId || !currentBidRoundPlayerUserId) { + throw new BadRequestException('Current bid round is not available.'); + } + + const redisBidCommandStartedAtMS = performance.now(); + const result = await this.auctionRedisCommandService.placeBid(matchId, { + bidPointAmount: params.amount, + bidderTeamIndex: params.teamIndex, + bidderUserId: this.stringFromState(team.captainUserId), + bidRequestId: params.bidRequestId ?? randomUUID(), + clientObservedAuctionLifecycleId: auctionLifecycleId, + clientObservedCurrentBidRoundPlayerUserId: currentBidRoundPlayerUserId, + matchId, + maximumAuctionTeamMemberCount: AUCTION_MAX_TEAM_SIZE, + maximumStoredAuctionBidHistoryCount: AUCTION_MAX_STORED_BID_HISTORY_COUNT, + maximumStoredBidRequestResultCount: + AUCTION_MAX_STORED_BID_REQUEST_RESULT_COUNT, + minimumBidPointReservePerRemainingAuctionTeamMemberSlot: + AUCTION_MIN_BID_POINTS, + minimumBidRequestResultReplayWindowMS: + AUCTION_BID_REQUEST_REPLAY_WINDOW_MS, + }); + const redisBidCommandDurationMS = + performance.now() - redisBidCommandStartedAtMS; + if ('rejected' in result) { + const bidServerTiming = this.roundBidServerTiming({ + fallbackFullStatePath: true, + redisBidCommandDurationMS, + serviceTotalDurationMS: performance.now() - serviceStartedAtMS, + }); + this.logSlowBidTiming(matchId, bidServerTiming); + throw this.createRedisBidRejectedException(result, bidServerTiming); + } + + return { redisBidCommandDurationMS, result, state }; + } + + private buildBidDeltaFromRedisBidResult( + state: Record, + result: Extract, + ): AuctionBidDeltaResponse { + return { + auctionBidHistoryEntry: result.auctionBidHistoryEntry, + auctionLifecycleId: this.stringFromState(state.auctionLifecycleId), + bidRequestId: result.bidRequestId, + currentBidRoundDeadlineTimestampMS: + result.currentBidRoundDeadlineTimestampMS, + currentHighestBidderTeamIndex: result.currentHighestBidderTeamIndex, + currentHighestBidPointAmount: result.currentHighestBidPointAmount, + currentServerTimestampMS: result.currentServerTimestampMS, + revision: result.revision, + }; + } + + private async markRedisSold( + auction: AuctionDocument, + params: MarkSoldParams, + ): Promise { + const matchId = auction.matchId.toString(); + const state = await this.requireRedisAuctionState(matchId); + if (state.phase !== 'bidding') { + throw new BadRequestException('Auction is not in bidding phase.'); + } + + const currentBidPointAmount = this.numberFromState( + state.currentHighestBidPointAmount, + ); + const winningTeamIndex = this.numberFromState( + state.currentHighestBidderTeamIndex, + -1, + ); + if (winningTeamIndex < 1 || currentBidPointAmount <= 0) { + throw new BadRequestException('No bid to mark sold.'); + } + + const structureInput = this.buildRedisStructureInputFromState(state); + const currentPlayer = + structureInput.auctionPlayerOrder[ + structureInput.currentAuctionPlayerOrderIndex + ]; + if (!currentPlayer) throw new BadRequestException('No current player.'); + + const team = structureInput.auctionTeams.find( + (entry) => Number(entry.teamIndex) === winningTeamIndex, + ); + if (!team) throw new BadRequestException('Winning team not found.'); + + const actionRequest = await this.reserveRedisStructureActionRequest({ + action: 'sold', + matchId, + params, + state, + }); + if (this.isReplayedRedisActionRequestContext(actionRequest)) { + return this.resolveReplayedRedisActionRequest(matchId, actionRequest); + } + + // [AUCTION-DEBUG] 중복 멤버 버그 스모킹건: 낙찰 직전, 이 선수가 이미 어느 팀에 + // 들어있는지. (markRedisSold는 검사 없이 append하므로 true면 그대로 중복) — 제거 대상 + const soldUserId = String(currentPlayer.userId); + const existingTeamIndex = structureInput.auctionTeams.find((entry) => + (entry.members ?? []).some( + (member) => String(member.userId) === soldUserId, + ), + )?.teamIndex; + recordNewRelicCustomEvent('AuctionServerSold', { + matchId, + auctionActionRequestId: params.auctionActionRequestId ?? null, + auctionLifecycleId: this.stringFromState(state.auctionLifecycleId), + revision: this.numberFromState(state.revision), + currentAuctionPlayerOrderIndex: + structureInput.currentAuctionPlayerOrderIndex, + soldUserId, + winningTeamIndex, + currentBidPointAmount, + playerAlreadyInTeam: existingTeamIndex !== undefined, + existingTeamIndex: + existingTeamIndex !== undefined ? Number(existingTeamIndex) : -1, + totalAssignedMemberCount: structureInput.auctionTeams.reduce( + (sum, entry) => sum + (entry.members?.length ?? 0), + 0, + ), + }); + + const preferredPrimary = currentPlayer.preferredPositions?.[0]?.position; + team.members = [ + ...(team.members ?? []), + { + userId: currentPlayer.userId, + assignedPosition: params.assignedPosition ?? preferredPrimary ?? 'MID', + memberAcquisitionBidPointAmount: currentBidPointAmount, + }, + ]; + team.remainingBidPointAmount = + Number(team.remainingBidPointAmount ?? 0) - currentBidPointAmount; + + return this.applyRedisStructureTransition({ + action: 'sold', + actionRequest, + auction, + deadline: { mode: 'remove' }, + expectedPhase: 'bidding', + liveStatePatch: { + ...buildAuctionRedisLiveStatePatchFromStructure(structureInput), + phase: 'sold', + }, + shouldBroadcastStateAfterDurability: + params.shouldBroadcastStateAfterDurability, + state, + structureInput, + }); + } + + private async markRedisPassed( + auction: AuctionDocument, + actionRequestParams: AuctionStructureActionRequestParams, + ): Promise { + const matchId = auction.matchId.toString(); + const state = await this.requireRedisAuctionState(matchId); + if (state.phase !== 'bidding') { + throw new BadRequestException('Auction is not in bidding phase.'); + } + if (this.numberFromState(state.currentHighestBidPointAmount) > 0) { + throw new BadRequestException('Cannot pass a player with an active bid.'); + } + + const structureInput = this.buildRedisStructureInputFromState(state); + const currentPlayer = + structureInput.auctionPlayerOrder[ + structureInput.currentAuctionPlayerOrderIndex + ]; + if (!currentPlayer) throw new BadRequestException('No current player.'); + + const actionRequest = await this.reserveRedisStructureActionRequest({ + action: 'passed', + matchId, + params: actionRequestParams, + state, + }); + if (this.isReplayedRedisActionRequestContext(actionRequest)) { + return this.resolveReplayedRedisActionRequest(matchId, actionRequest); + } + + const passedPlayer: AuctionPlayerSnapshot = { + ...this.cloneAuctionPlayerSnapshot(currentPlayer), + passCount: this.numberFromState(currentPlayer.passCount) + 1, + }; + structureInput.auctionPlayerOrder[ + structureInput.currentAuctionPlayerOrderIndex + ] = passedPlayer; + structureInput.passedAuctionPlayerQueue = [ + ...structureInput.passedAuctionPlayerQueue, + passedPlayer, + ]; + + return this.applyRedisStructureTransition({ + action: 'passed', + actionRequest, + auction, + deadline: { mode: 'remove' }, + expectedPhase: 'bidding', + liveStatePatch: { + ...buildAuctionRedisLiveStatePatchFromStructure(structureInput), + phase: 'passed', + }, + shouldBroadcastStateAfterDurability: + actionRequestParams.shouldBroadcastStateAfterDurability, + state, + structureInput, + }); + } + + private async completeRedisExpirySold( + auction: AuctionDocument, + state: Record, + ): Promise { + const currentBidPointAmount = this.numberFromState( + state.bidRoundExpiryWinningBidPointAmount, + ); + const winningTeamIndex = this.numberFromState( + state.bidRoundExpiryWinningBidderTeamIndex, + -1, + ); + if (winningTeamIndex < 1 || currentBidPointAmount <= 0) { + throw new BadRequestException('Prepared expiry has no winning bid.'); + } + + const structureInput = this.buildRedisStructureInputFromState(state); + const currentPlayer = + structureInput.auctionPlayerOrder[ + structureInput.currentAuctionPlayerOrderIndex + ]; + if (!currentPlayer) throw new BadRequestException('No current player.'); + + const team = structureInput.auctionTeams.find( + (entry) => Number(entry.teamIndex) === winningTeamIndex, + ); + if (!team) throw new BadRequestException('Winning team not found.'); + + const preferredPrimary = currentPlayer.preferredPositions?.[0]?.position; + team.members = [ + ...(team.members ?? []), + { + userId: currentPlayer.userId, + assignedPosition: preferredPrimary ?? 'MID', + memberAcquisitionBidPointAmount: currentBidPointAmount, + }, + ]; + team.remainingBidPointAmount = + Number(team.remainingBidPointAmount ?? 0) - currentBidPointAmount; + + return this.applyRedisStructureTransition({ + action: 'sold', + auction, + auctionStateTransitionId: this.stringFromState( + state.bidRoundExpiryAuctionStateTransitionId, + ), + deadline: { mode: 'remove' }, + expectedPhase: 'expiring', + liveStatePatch: { + ...buildAuctionRedisLiveStatePatchFromStructure(structureInput), + phase: 'sold', + }, + state, + structureInput, + }); + } + + private async completeRedisExpiryPassed( + auction: AuctionDocument, + state: Record, + ): Promise { + const structureInput = this.buildRedisStructureInputFromState(state); + const currentPlayer = + structureInput.auctionPlayerOrder[ + structureInput.currentAuctionPlayerOrderIndex + ]; + if (!currentPlayer) throw new BadRequestException('No current player.'); + + const passedPlayer: AuctionPlayerSnapshot = { + ...this.cloneAuctionPlayerSnapshot(currentPlayer), + passCount: this.numberFromState(currentPlayer.passCount) + 1, + }; + structureInput.auctionPlayerOrder[ + structureInput.currentAuctionPlayerOrderIndex + ] = passedPlayer; + structureInput.passedAuctionPlayerQueue = [ + ...structureInput.passedAuctionPlayerQueue, + passedPlayer, + ]; + + return this.applyRedisStructureTransition({ + action: 'passed', + auction, + auctionStateTransitionId: this.stringFromState( + state.bidRoundExpiryAuctionStateTransitionId, + ), + deadline: { mode: 'remove' }, + expectedPhase: 'expiring', + liveStatePatch: { + ...buildAuctionRedisLiveStatePatchFromStructure(structureInput), + phase: 'passed', + }, + state, + structureInput, + }); + } + + private async advanceRedisAuction( + auction: AuctionDocument, + actionRequestParams: AuctionStructureActionRequestParams, + ): Promise { + const matchId = auction.matchId.toString(); + const state = await this.requireRedisAuctionState(matchId); + if ( + state.phase !== 'sold' && + state.phase !== 'presenting' && + state.phase !== 'passed' + ) { + throw new BadRequestException('Cannot advance from current phase.'); + } + + const structureInput = this.buildRedisStructureInputFromState(state); + const nextIndex = structureInput.currentAuctionPlayerOrderIndex + 1; + let action: AuctionActionType = 'next'; + let nextPhase = 'presenting'; + + if (nextIndex >= structureInput.auctionPlayerOrder.length) { + if (structureInput.passedAuctionPlayerQueue.length > 0) { + structureInput.auctionPlayerOrder = [ + ...structureInput.auctionPlayerOrder, + ...structureInput.passedAuctionPlayerQueue.map((player) => + this.cloneAuctionPlayerSnapshot(player), + ), + ]; + structureInput.passedAuctionPlayerQueue = []; + structureInput.currentAuctionRound += 1; + structureInput.currentAuctionPlayerOrderIndex = nextIndex; + } else { + action = 'complete'; + nextPhase = 'complete'; + } + } else { + structureInput.currentAuctionPlayerOrderIndex = nextIndex; + } + + const actionRequest = await this.reserveRedisStructureActionRequest({ + action, + matchId, + params: actionRequestParams, + state, + }); + if (this.isReplayedRedisActionRequestContext(actionRequest)) { + return this.resolveReplayedRedisActionRequest(matchId, actionRequest); + } + + const completionTimestampMS = + action === 'complete' + ? await this.auctionRedisService.getCurrentRedisTimestampMS() + : undefined; + return this.applyRedisStructureTransition({ + action, + actionRequest, + auction, + deadline: { mode: 'remove' }, + expectedPhase: String(state.phase), + liveStatePatch: { + ...buildAuctionRedisLiveStatePatchFromStructure(structureInput), + auctionCompletedAtTimestampMS: completionTimestampMS, + currentHighestBidPointAmount: 0, + currentHighestBidderTeamIndex: -1, + phase: nextPhase, + }, + shouldBroadcastStateAfterDurability: + actionRequestParams.shouldBroadcastStateAfterDurability, + state, + structureInput, + }); + } + + public async markSold(params: MarkSoldParams): Promise { + const auction = await this.getByMatchId(params.matchId); + this.assertLiveAuctionOperationSupported(auction); + if (this.isRedisV1Auction(auction)) { + return this.markRedisSold(auction, params); + } if (auction.phase !== 'bidding') { throw new BadRequestException('Auction is not in bidding phase.'); } @@ -370,8 +1297,13 @@ export class AuctionService { public async markPassed( matchId: mongoose.Types.ObjectId, - ): Promise { + actionRequest: AuctionStructureActionRequestParams = {}, + ): Promise { const auction = await this.getByMatchId(matchId); + this.assertLiveAuctionOperationSupported(auction); + if (this.isRedisV1Auction(auction)) { + return this.markRedisPassed(auction, actionRequest); + } if (auction.phase !== 'bidding') { throw new BadRequestException('Auction is not in bidding phase.'); } @@ -393,8 +1325,13 @@ export class AuctionService { public async next( matchId: mongoose.Types.ObjectId, - ): Promise { + actionRequest: AuctionStructureActionRequestParams = {}, + ): Promise { const auction = await this.getByMatchId(matchId); + this.assertLiveAuctionOperationSupported(auction); + if (this.isRedisV1Auction(auction)) { + return this.advanceRedisAuction(auction, actionRequest); + } if ( auction.phase !== 'sold' && auction.phase !== 'presenting' && @@ -438,19 +1375,54 @@ export class AuctionService { return auction; } + public async completePreparedExpiry( + matchId: mongoose.Types.ObjectId, + ): Promise { + const auction = await this.getByMatchId(matchId); + if (!this.isRedisV1Auction(auction)) return null; + + const state = + await this.auctionRedisStateReaderService.readAuctionStateView( + matchId.toString(), + { includeInternalLiveStateFields: true }, + ); + if (!state || state.redisInternalPhase !== 'expiring') return null; + + const decision = this.stringFromState(state.bidRoundExpiryDecision); + if (decision === 'sold') { + return this.completeRedisExpirySold(auction, state); + } + if (decision === 'passed') { + return this.completeRedisExpiryPassed(auction, state); + } + return null; + } + public async reset(params: { + auctionActionRequestId?: string; + clientObservedAuctionLifecycleId?: string; + clientObservedCurrentAuctionPlayerOrderIndex?: number; + clientObservedCurrentBidRoundPlayerUserId?: string; + clientObservedPhase?: string; + clientObservedRevision?: number; matchId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; }): Promise { const AuctionModel = await this.connectionService.getModel('auction'); const AuctionHistoryModel = await this.connectionService.getModel('auctionHistory'); + const AuctionSideEffectApplicationModel = + await this.connectionService.getModel('auctionSideEffectApplication'); const MatchModel = await this.connectionService.getModel('match'); const session = await this.connectionService.createSession(); if (!session) { throw new InternalServerErrorException('Failed to start DB session.'); } + let redisRuntimeToClear: { + auctionLifecycleId?: string; + matchId: string; + } | null = null; try { session.startTransaction(); const auction = await AuctionModel.findOne({ @@ -463,24 +1435,40 @@ export class AuctionService { if (!match.communityId.equals(params.communityId)) { throw new BadRequestException('Community mismatch.'); } + this.assertCompetitionLifecycleMutable(match, 'reset the auction'); - await auction.deleteOne({ session }); - await AuctionHistoryModel.deleteMany({ auctionId: auction._id }).session( - session, - ); - if (match.status === 'team-built') { - await this.tournamentCodeService.releaseFromMatch(match); - match.status = 'recruiting'; - match.teams = []; - match.tournamentCodeIds = []; - match.gameSchedule = []; - match.participants.forEach((participant) => { - participant.excluded = false; - }); - match.teamBuiltAt = undefined; - match.result = undefined; - match.resultPollState = undefined; - await match.save({ session }); + if (this.isRedisV1Auction(auction)) { + redisRuntimeToClear = { + auctionLifecycleId: auction.auctionLifecycleId, + matchId: params.matchId.toString(), + }; + await this.resetMatchAfterAuctionCancellation(match, session); + await AuctionSideEffectApplicationModel.deleteMany({ + auctionId: auction._id, + }).session(session); + await AuctionHistoryModel.deleteMany({ + auctionId: auction._id, + }).session(session); + await auction.deleteOne({ session }); + } else { + await auction.deleteOne({ session }); + await AuctionHistoryModel.deleteMany({ + auctionId: auction._id, + }).session(session); + if (match.status === 'team-built') { + await this.tournamentCodeService.releaseFromMatch(match); + match.status = 'recruiting'; + match.teams = []; + match.tournamentCodeIds = []; + match.gameSchedule = []; + match.participants.forEach((participant) => { + participant.excluded = false; + }); + match.teamBuiltAt = undefined; + match.result = undefined; + match.resultPollState = undefined; + await match.save({ session }); + } } await session.commitTransaction(); } catch (err) { @@ -489,13 +1477,26 @@ export class AuctionService { } finally { await session.endSession(); } + + if (redisRuntimeToClear) { + await this.clearRedisAuctionRuntimeForLifecycle( + redisRuntimeToClear.matchId, + redisRuntimeToClear.auctionLifecycleId, + ); + } } public async undoTo(params: { + auctionActionRequestId?: string; + clientObservedAuctionLifecycleId?: string; + clientObservedCurrentAuctionPlayerOrderIndex?: number; + clientObservedCurrentBidRoundPlayerUserId?: string; + clientObservedPhase?: string; + clientObservedRevision?: number; matchId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; sequence: number; - }): Promise { + }): Promise { const AuctionModel = await this.connectionService.getModel('auction'); const AuctionHistoryModel = await this.connectionService.getModel('auctionHistory'); @@ -506,6 +1507,15 @@ export class AuctionService { throw new InternalServerErrorException('Failed to start DB session.'); } + let redisUndoContext: { + actionRequestParams?: AuctionStructureActionRequestParams; + auction: AuctionDocument; + snapshot: Record; + targetHistorySequence: number; + undoingCompletedAuction: boolean; + } | null = null; + let restored: AuctionDocument | null = null; + try { session.startTransaction(); const auction = await AuctionModel.findOne({ @@ -536,33 +1546,804 @@ export class AuctionService { const undoingCompletedAuction = Boolean(auction.completedAt) && !('completedAt' in snapshot); if (undoingCompletedAuction) { - await this.tournamentCodeService.releaseFromMatch(match); - await this.tournamentResultService.cancelPolling(match); - match.status = 'team-built'; - match.result = undefined; - await match.save({ session }); + this.assertCompetitionLifecycleMutable( + match, + 'undo a completed auction', + ); } + if (this.isRedisV1Auction(auction)) { + redisUndoContext = { + auction, + actionRequestParams: params, + snapshot: snapshot, + targetHistorySequence: params.sequence, + undoingCompletedAuction, + }; + await session.commitTransaction(); + } else { + if (undoingCompletedAuction) { + await this.tournamentCodeService.releaseFromMatch(match); + await this.tournamentResultService.cancelPolling(match); + match.status = 'team-built'; + match.result = undefined; + await match.save({ session }); + } - await AuctionModel.replaceOne({ _id: auction._id }, snapshot, { - session, - }).exec(); - await AuctionHistoryModel.deleteMany({ - auctionId: auction._id, - sequence: { $gt: params.sequence }, - }) - .session(session) - .exec(); + await AuctionModel.replaceOne({ _id: auction._id }, snapshot, { + session, + }).exec(); + await AuctionHistoryModel.deleteMany({ + auctionId: auction._id, + sequence: { $gt: params.sequence }, + }) + .session(session) + .exec(); - await session.commitTransaction(); - const restored = await AuctionModel.findById(auction._id); - if (!restored) throw new NotFoundException('Auction not found.'); - return restored; + await session.commitTransaction(); + restored = await AuctionModel.findById(auction._id); + if (!restored) throw new NotFoundException('Auction not found.'); + } } catch (err) { await session.abortTransaction(); throw err; } finally { await session.endSession(); } + + if (redisUndoContext) { + return this.undoRedisAuction(redisUndoContext); + } + if (!restored) throw new NotFoundException('Auction not found.'); + return restored; + } + + private async requireRedisAuctionState( + matchId: string, + ): Promise> { + const state = + await this.auctionRedisStateReaderService.readAuctionStateView(matchId); + if (!state) { + throw new BadRequestException('Auction realtime state is not available.'); + } + return state; + } + + private async reserveRedisStructureActionRequest(params: { + action: AuctionActionType; + matchId: string; + params: AuctionStructureActionRequestParams; + state: Record; + }): Promise { + const auctionActionRequestId = + params.params.auctionActionRequestId ?? randomUUID(); + const expectedAuctionLifecycleId = + params.params.clientObservedAuctionLifecycleId ?? + this.stringFromState(params.state.auctionLifecycleId); + const expectedRevision = + params.params.clientObservedRevision ?? + this.numberFromState(params.state.revision); + const expectedPhase = + params.params.clientObservedPhase ?? + this.stringFromState(params.state.phase); + const expectedCurrentBidRoundPlayerUserId = + params.params.clientObservedCurrentBidRoundPlayerUserId ?? + this.stringFromState(params.state.currentBidRoundPlayerUserId) ?? + undefined; + const expectedCurrentAuctionPlayerOrderIndex = + params.params.clientObservedCurrentAuctionPlayerOrderIndex ?? + this.numberFromState(params.state.currentAuctionPlayerOrderIndex); + const processingOwnerToken = randomUUID(); + const auctionStateTransitionId = `${params.action}:${expectedAuctionLifecycleId}:${auctionActionRequestId}`; + + const reserved = await this.auctionRedisCommandService.reserveActionRequest( + params.matchId, + { + auctionActionRequestId, + auctionActionType: params.action, + auctionStateTransitionId, + clientObservedAuctionLifecycleId: expectedAuctionLifecycleId, + clientObservedCurrentAuctionPlayerOrderIndex: + expectedCurrentAuctionPlayerOrderIndex, + clientObservedCurrentBidRoundPlayerUserId: + expectedCurrentBidRoundPlayerUserId, + clientObservedPhase: expectedPhase, + clientObservedRevision: expectedRevision, + leaseDurationMS: AUCTION_ACTION_REQUEST_LEASE_DURATION_MS, + maximumStoredAuctionActionRequestResultCount: + AUCTION_MAX_STORED_ACTION_REQUEST_RESULT_COUNT, + minimumAuctionActionRequestResultReplayWindowMS: + AUCTION_ACTION_REQUEST_REPLAY_WINDOW_MS, + processingOwnerToken, + }, + ); + + if ('rejected' in reserved) { + throw new BadRequestException( + `Auction action request was rejected: ${reserved.code}.`, + ); + } + if ('isReplay' in reserved) { + if (reserved.replayStatus === 'applied') { + return { + currentServerTimestampMS: reserved.currentServerTimestampMS, + replay: true, + requiresRefetch: reserved.requiresRefetch ?? true, + responseJson: reserved.responseJson, + revision: reserved.revision, + }; + } + throw new BadRequestException( + `Auction action request was replayed as ${reserved.replayStatus}.`, + ); + } + + return { + actionRequest: { + observedProcessingLeaseVersion: reserved.observedProcessingLeaseVersion, + processingOwnerToken, + scopeKey: reserved.actionRequestScopeKey, + }, + auctionStateTransitionId: reserved.auctionStateTransitionId, + expectedAuctionLifecycleId, + expectedCurrentAuctionPlayerOrderIndex, + expectedCurrentBidRoundPlayerUserId, + expectedPhase, + expectedRevision, + }; + } + + private isReplayedRedisActionRequestContext( + actionRequest: RedisActionRequestContext, + ): actionRequest is ReplayedRedisActionRequestContext { + return 'replay' in actionRequest; + } + + private async resolveReplayedRedisActionRequest( + matchId: string, + actionRequest: ReplayedRedisActionRequestContext, + ): Promise { + if (actionRequest.responseJson && !actionRequest.requiresRefetch) { + try { + return JSON.parse(actionRequest.responseJson) as Record< + string, + unknown + >; + } catch { + // Fall through to a full Redis read if a stored response is malformed. + } + } + return this.requireRedisAuctionState(matchId); + } + + private async applyRedisStructureTransition(params: { + action: AuctionActionType; + auction: AuctionDocument; + actionRequest?: ReservedRedisActionRequestContext; + auctionStateTransitionId?: string; + deadline: + | { mode: 'none' } + | { mode: 'remove' } + | { durationSeconds: number; mode: 'set-relative' }; + expectedPhase: string; + historyMutation?: Record; + liveStatePatch: Record< + string, + string | number | boolean | null | undefined + >; + matchSideEffectMutation?: Record; + shouldBroadcastStateAfterDurability?: boolean; + shouldResetBidRuntime?: boolean; + state: Record; + structureInput: Parameters[0]; + }): Promise { + const matchId = params.auction.matchId.toString(); + const auctionLifecycleId = this.stringFromState( + params.state.auctionLifecycleId, + ); + const expectedRevision = + params.actionRequest?.expectedRevision ?? + this.numberFromState(params.state.revision); + const expectedAuctionHistorySequence = this.numberFromState( + params.state.currentAuctionHistorySequence, + ); + const auctionHistorySequence = expectedAuctionHistorySequence + 1; + const auctionStateTransitionId = + params.actionRequest?.auctionStateTransitionId || + params.auctionStateTransitionId || + `${params.action}:${auctionLifecycleId}:${randomUUID()}`; + const afterState = { + ...params.state, + ...buildAuctionRedisStructureState(params.structureInput), + ...params.liveStatePatch, + currentAuctionHistorySequence: auctionHistorySequence, + lastAppliedAuctionStateTransitionId: auctionStateTransitionId, + revision: expectedRevision + 1, + }; + const afterAuctionMongoProjection = + this.buildAuctionMongoProjectionFromState(params.auction, afterState); + const matchSideEffectMutation = + params.matchSideEffectMutation ?? + (params.action === 'complete' + ? { type: 'syncMatchTeamsAfterComplete' } + : { type: 'none' }); + if (matchSideEffectMutation.type !== 'none') { + afterAuctionMongoProjection.matchSideEffectStatus = 'pending'; + afterAuctionMongoProjection.matchSideEffectRevision = + (params.auction.matchSideEffectRevision ?? 0) + 1; + afterAuctionMongoProjection.matchSideEffectError = undefined; + } + + const durabilityPayload = { + afterAuctionMongoProjection, + auctionActionType: params.action, + auctionHistorySequence, + auctionId: params.auction._id.toString(), + auctionLifecycleId, + auctionStateTransitionId, + historyMutation: params.historyMutation ?? { type: 'append' }, + matchId, + matchSideEffectMutation, + revision: expectedRevision + 1, + snapshotBefore: this.buildAuctionSnapshotFromRedisState( + params.auction, + params.state, + ), + }; + const result = await this.auctionRedisCommandService.applyTransition( + matchId, + { + afterAuctionStructureStateJson: stringifyAuctionRedisStructureState( + params.structureInput, + ), + auctionHistorySequence, + auctionLifecycleId: + params.actionRequest?.expectedAuctionLifecycleId ?? + auctionLifecycleId, + auctionStateTransitionId, + broadcastStateRevision: expectedRevision + 1, + deadline: params.deadline, + durabilityPayloadJson: JSON.stringify(durabilityPayload), + expectedCurrentAuctionPlayerOrderIndex: + params.actionRequest?.expectedCurrentAuctionPlayerOrderIndex ?? + params.structureInput.currentAuctionPlayerOrderIndex, + expectedCurrentBidRoundPlayerUserId: + params.actionRequest?.expectedCurrentBidRoundPlayerUserId ?? + (params.expectedPhase === 'bidding' + ? this.stringFromState(params.state.currentBidRoundPlayerUserId) + : undefined), + expectedAuctionHistorySequence, + expectedPhase: + params.actionRequest?.expectedPhase ?? params.expectedPhase, + expectedRevision, + liveStatePatch: params.liveStatePatch, + matchId, + shouldBroadcastState: + params.shouldBroadcastStateAfterDurability ?? true, + shouldResetBidRuntime: params.shouldResetBidRuntime, + actionRequest: params.actionRequest?.actionRequest, + }, + ); + // [AUCTION-DEBUG] 제거 대상. 모든 redis 전환(sold/undo/next/open-bidding/complete)의 백본 타임라인. + // auctionStateTransitionId = `${action}:${lifecycleId}:${auctionActionRequestId}` + // 라서 클라의 auctionActionRequestId와 조인된다. + recordNewRelicCustomEvent('AuctionServerTransition', { + matchId, + action: params.action, + auctionStateTransitionId, + auctionLifecycleId, + expectedRevision, + newRevision: 'rejected' in result ? -1 : expectedRevision + 1, + auctionHistorySequence, + currentAuctionPlayerOrderIndex: + params.structureInput.currentAuctionPlayerOrderIndex, + totalAssignedMemberCount: params.structureInput.auctionTeams.reduce( + (sum, entry) => sum + (entry.members?.length ?? 0), + 0, + ), + rejected: 'rejected' in result, + rejectionCode: 'rejected' in result ? result.code : null, + }); + + if ('rejected' in result) { + // 게이트웨이가 설명적 거부코드로 변환할 수 있도록 내부 code(예: CONFLICT)를 + // 구조화해 던진다(message만 던지면 code 자리에 풀 문장이 들어가 매핑이 어렵다). + throw new BadRequestException({ + code: result.code, + message: `Auction transition was rejected: ${result.code}.`, + }); + } + + return this.requireRedisAuctionState(matchId); + } + + private async resetRedisAuction(params: { + actionRequestParams?: AuctionStructureActionRequestParams; + auction: AuctionDocument; + }): Promise { + const matchId = params.auction.matchId.toString(); + const state = await this.requireRedisAuctionState(matchId); + const actionRequest = await this.reserveRedisStructureActionRequest({ + action: 'reset', + matchId, + params: params.actionRequestParams ?? {}, + state, + }); + if (this.isReplayedRedisActionRequestContext(actionRequest)) { + return this.resolveReplayedRedisActionRequest(matchId, actionRequest); + } + + const currentStructureInput = this.buildRedisStructureInputFromState(state); + const resetStructureInput = { + ...currentStructureInput, + auctionPlayerOrder: [], + auctionTeams: [], + currentAuctionPlayerOrderIndex: 0, + currentAuctionRound: 1, + passedAuctionPlayerQueue: [], + }; + const clearedTeamLiveStatePatch: Record = {}; + for (const team of this.arrayFromState>( + state.auctionTeams, + )) { + const teamIndex = this.numberFromState(team.teamIndex); + if (teamIndex < 1) continue; + clearedTeamLiveStatePatch[`team:${teamIndex}:remainingBidPointAmount`] = + 0; + clearedTeamLiveStatePatch[ + `team:${teamIndex}:assignedAuctionTeamMemberCount` + ] = 0; + } + + return this.applyRedisStructureTransition({ + action: 'reset', + actionRequest, + auction: params.auction, + deadline: { mode: 'remove' }, + expectedPhase: String(state.phase), + historyMutation: { + resetMode: 'clear-history', + type: 'reset', + }, + liveStatePatch: { + ...buildAuctionRedisLiveStatePatchFromStructure(resetStructureInput), + ...clearedTeamLiveStatePatch, + auctionCompletedAtTimestampMS: 0, + currentBidRoundDeadlineTimestampMS: 0, + currentBidRoundPlayerUserId: '', + currentHighestBidPointAmount: 0, + currentHighestBidderTeamIndex: -1, + matchSideEffectRevision: + Number(params.auction.matchSideEffectRevision ?? 0) + 1, + matchSideEffectStatus: 'pending', + phase: 'waiting', + }, + matchSideEffectMutation: { type: 'resetMatchAfterAuctionReset' }, + shouldResetBidRuntime: true, + state, + structureInput: resetStructureInput, + }); + } + + private async undoRedisAuction(params: { + actionRequestParams?: AuctionStructureActionRequestParams; + auction: AuctionDocument; + snapshot: Record; + targetHistorySequence: number; + undoingCompletedAuction: boolean; + }): Promise { + const matchId = params.auction.matchId.toString(); + const state = await this.requireRedisAuctionState(matchId); + const actionRequest = await this.reserveRedisStructureActionRequest({ + action: 'undo', + matchId, + params: params.actionRequestParams ?? {}, + state, + }); + if (this.isReplayedRedisActionRequestContext(actionRequest)) { + return this.resolveReplayedRedisActionRequest(matchId, actionRequest); + } + + const structureInput = this.buildRedisStructureInputFromAuctionSnapshot( + params.snapshot, + ); + const phase = this.stringFromState(params.snapshot.phase) || 'presenting'; + const currentHighestBidderTeamIndex = this.numberFromState( + params.snapshot.currentHighestBidderTeamIndex ?? + params.snapshot.currentBidderTeamIndex, + -1, + ); + const currentHighestBidPointAmount = this.numberFromState( + params.snapshot.currentHighestBidPointAmount ?? + params.snapshot.currentBid, + 0, + ); + + // [AUCTION-DEBUG] 제거 대상. undo가 "어느 시점으로" 복원하는지 + 복원된 팀 구성. 라이브 revision과 + // 복원 스냅샷 revision의 간격(restoredRevisionLag)이 사용자가 본 "2~3 뒤처짐". + // 이 이벤트 직후의 AuctionServerSold가 playerAlreadyInTeam:true면 "undo가 선수를 + // 안 지운 채 재낙찰 → 중복"이 한 타임라인으로 증명된다. + const liveRevisionBeforeUndo = this.numberFromState(state.revision); + const restoredRevision = this.numberFromState(params.snapshot.revision); + const restoredMemberUserIds = structureInput.auctionTeams.flatMap((entry) => + (entry.members ?? []).map((member) => String(member.userId)), + ); + recordNewRelicCustomEvent('AuctionServerUndo', { + matchId, + auctionActionRequestId: + params.actionRequestParams?.auctionActionRequestId ?? null, + auctionLifecycleId: this.stringFromState(state.auctionLifecycleId), + targetHistorySequence: params.targetHistorySequence, + liveRevisionBeforeUndo, + restoredRevision, + restoredRevisionLag: liveRevisionBeforeUndo - restoredRevision, + restoredHistorySequence: this.numberFromState( + params.snapshot.currentAuctionHistorySequence, + ), + restoredPhase: phase, + restoredOrderIndex: structureInput.currentAuctionPlayerOrderIndex, + restoredAssignedMemberCount: restoredMemberUserIds.length, + restoredHasDuplicateMember: + restoredMemberUserIds.length !== new Set(restoredMemberUserIds).size, + undoingCompletedAuction: params.undoingCompletedAuction, + }); + + return this.applyRedisStructureTransition({ + action: 'undo', + actionRequest, + auction: params.auction, + deadline: + phase === 'bidding' + ? { + durationSeconds: structureInput.maximumBidRoundDurationSeconds, + mode: 'set-relative', + } + : { mode: 'remove' }, + expectedPhase: String(state.phase), + historyMutation: { + targetHistorySequence: params.targetHistorySequence, + type: 'deleteAfterSequenceAndAppendUndo', + }, + liveStatePatch: { + ...buildAuctionRedisLiveStatePatchFromStructure(structureInput), + auctionCompletedAtTimestampMS: + phase === 'complete' + ? this.numberFromState( + params.snapshot.auctionCompletedAtTimestampMS ?? + params.snapshot.completedAt, + ) + : 0, + currentHighestBidPointAmount, + currentHighestBidderTeamIndex, + phase, + }, + matchSideEffectMutation: params.undoingCompletedAuction + ? { type: 'undoCompletedAuctionSideEffects' } + : { type: 'none' }, + state, + structureInput, + }); + } + + private buildRedisStructureInputFromState( + state: Record, + ): Parameters[0] { + return { + auctionPlayerOrder: this.cloneRedisStructureArray( + state.auctionPlayerOrder, + ), + auctionTeams: this.cloneRedisStructureArray(state.auctionTeams), + bidRoundExtensionSeconds: this.numberFromState( + state.bidRoundExtensionSeconds, + 5, + ), + currentAuctionPlayerOrderIndex: this.numberFromState( + state.currentAuctionPlayerOrderIndex, + ), + currentAuctionRound: this.numberFromState(state.currentAuctionRound, 1), + initialTeamBidPointAmount: this.numberFromState( + state.initialTeamBidPointAmount, + 1000, + ), + manualTopTierAuctionPriorityUserIds: this.cloneRedisStructureArray( + state.manualTopTierAuctionPriorityUserIds, + ), + maximumBidRoundDurationSeconds: this.numberFromState( + state.maximumBidRoundDurationSeconds, + 30, + ), + passedAuctionPlayerQueue: this.cloneRedisStructureArray( + state.passedAuctionPlayerQueue, + ), + topTierAuctionPriorityThreshold: this.isAuctionTopTierThreshold( + state.topTierAuctionPriorityThreshold, + ) + ? state.topTierAuctionPriorityThreshold + : 'NONE', + }; + } + + private buildRedisStructureInputFromAuctionSnapshot( + snapshot: Record, + ): Parameters[0] { + const legacyTeams = this.cloneRedisStructureArray(snapshot.teams); + const auctionTeams = this.cloneRedisStructureArray(snapshot.auctionTeams); + return { + auctionPlayerOrder: this.cloneRedisStructureArray( + snapshot.auctionPlayerOrder ?? snapshot.order, + ), + auctionTeams: + auctionTeams.length > 0 + ? auctionTeams + : convertLegacyAuctionTeamsToRedisTeams(legacyTeams as never), + bidRoundExtensionSeconds: this.numberFromState( + snapshot.bidRoundExtensionSeconds ?? snapshot.bidExtensionSeconds, + 5, + ), + currentAuctionPlayerOrderIndex: this.numberFromState( + snapshot.currentAuctionPlayerOrderIndex ?? snapshot.currentIndex, + ), + currentAuctionRound: this.numberFromState( + snapshot.currentAuctionRound ?? snapshot.auctionRound, + 1, + ), + initialTeamBidPointAmount: this.numberFromState( + snapshot.initialTeamBidPointAmount ?? snapshot.initialPoints, + 1000, + ), + manualTopTierAuctionPriorityUserIds: this.cloneRedisStructureArray( + snapshot.manualTopTierAuctionPriorityUserIds ?? + snapshot.manualTopTierUserIds, + ), + maximumBidRoundDurationSeconds: this.numberFromState( + snapshot.maximumBidRoundDurationSeconds ?? snapshot.maxTimerSeconds, + 30, + ), + passedAuctionPlayerQueue: this.cloneRedisStructureArray( + snapshot.passedAuctionPlayerQueue ?? snapshot.passedQueue, + ), + topTierAuctionPriorityThreshold: this.isAuctionTopTierThreshold( + snapshot.topTierAuctionPriorityThreshold ?? snapshot.topTierThreshold, + ) + ? ((snapshot.topTierAuctionPriorityThreshold ?? + snapshot.topTierThreshold) as never) + : 'NONE', + }; + } + + private buildAuctionSnapshotFromRedisState( + auction: AuctionDocument, + state: Record, + ): Record { + const base = + typeof auction.toObject === 'function' + ? (auction.toObject({ depopulate: true }) as Record) + : (auction as unknown as Record); + return { + ...this.cloneJson(base), + ...this.buildAuctionMongoProjectionFromState(auction, state), + _id: auction._id, + matchId: auction.matchId, + chatMessages: auction.chatMessages ?? [], + }; + } + + private buildAuctionMongoProjectionFromState( + auction: AuctionDocument, + state: Record, + ): Record { + const structureInput = this.buildRedisStructureInputFromState(state); + const currentHighestBidderTeamIndex = this.numberFromState( + state.currentHighestBidderTeamIndex, + -1, + ); + const currentBidRoundDeadlineTimestampMS = this.numberFromState( + state.currentBidRoundDeadlineTimestampMS, + 0, + ); + const auctionBidHistory = this.arrayFromState>( + state.auctionBidHistory, + ); + const phase = this.stringFromState(state.phase) || 'presenting'; + const projection: Record = { + auctionBidHistory, + auctionCompletedAtTimestampMS: + phase === 'complete' && + this.numberFromState(state.auctionCompletedAtTimestampMS) > 0 + ? this.numberFromState(state.auctionCompletedAtTimestampMS) + : undefined, + auctionEngineVersion: 'redis-v1', + auctionLifecycleId: this.stringFromState(state.auctionLifecycleId), + auctionPlayerOrder: structureInput.auctionPlayerOrder, + auctionRound: structureInput.currentAuctionRound, + auctionTeams: structureInput.auctionTeams, + bidExtensionSeconds: structureInput.bidRoundExtensionSeconds, + bidRoundExtensionSeconds: structureInput.bidRoundExtensionSeconds, + bids: auctionBidHistory.map((bid) => ({ + amount: this.numberFromState(bid.bidPointAmount), + bidderUserId: bid.bidderUserId, + teamIndex: this.numberFromState(bid.bidderTeamIndex), + timestamp: new Date(this.numberFromState(bid.bidPlacedAtTimestampMS)), + })), + completedAt: + phase === 'complete' && + this.numberFromState(state.auctionCompletedAtTimestampMS) > 0 + ? new Date(this.numberFromState(state.auctionCompletedAtTimestampMS)) + : undefined, + currentAuctionHistorySequence: this.numberFromState( + state.currentAuctionHistorySequence, + ), + currentAuctionPlayerOrderIndex: + structureInput.currentAuctionPlayerOrderIndex, + currentAuctionRound: structureInput.currentAuctionRound, + currentBid: this.numberFromState(state.currentHighestBidPointAmount), + currentBidRoundDeadlineTimestampMS: + currentBidRoundDeadlineTimestampMS > 0 + ? currentBidRoundDeadlineTimestampMS + : undefined, + currentBidderTeamIndex: + currentHighestBidderTeamIndex > 0 + ? currentHighestBidderTeamIndex + : undefined, + currentDeadline: + currentBidRoundDeadlineTimestampMS > 0 + ? new Date(currentBidRoundDeadlineTimestampMS) + : undefined, + currentHighestBidPointAmount: this.numberFromState( + state.currentHighestBidPointAmount, + ), + currentHighestBidderTeamIndex: + currentHighestBidderTeamIndex > 0 + ? currentHighestBidderTeamIndex + : undefined, + currentIndex: structureInput.currentAuctionPlayerOrderIndex, + initialPoints: structureInput.initialTeamBidPointAmount, + initialTeamBidPointAmount: structureInput.initialTeamBidPointAmount, + lastAppliedAuctionStateTransitionId: this.stringFromState( + state.lastAppliedAuctionStateTransitionId, + ), + manualTopTierAuctionPriorityUserIds: + structureInput.manualTopTierAuctionPriorityUserIds, + manualTopTierUserIds: structureInput.manualTopTierAuctionPriorityUserIds, + matchId: auction.matchId, + maxTimerSeconds: structureInput.maximumBidRoundDurationSeconds, + maximumBidRoundDurationSeconds: + structureInput.maximumBidRoundDurationSeconds, + order: structureInput.auctionPlayerOrder, + passedAuctionPlayerQueue: structureInput.passedAuctionPlayerQueue, + passedQueue: structureInput.passedAuctionPlayerQueue, + phase, + revision: this.numberFromState(state.revision), + teams: this.convertRedisTeamsToLegacyTeams(structureInput.auctionTeams), + topTierAuctionPriorityThreshold: + structureInput.topTierAuctionPriorityThreshold, + topTierThreshold: structureInput.topTierAuctionPriorityThreshold, + }; + + return this.dropUndefinedProjectionFields(projection); + } + + private convertRedisTeamsToLegacyTeams( + auctionTeams: Parameters< + typeof stringifyAuctionRedisStructureState + >[0]['auctionTeams'], + ): AuctionTeam[] { + return auctionTeams.map((team) => ({ + captainUserId: team.captainUserId, + members: (team.members ?? []).map((member) => ({ + assignedPosition: member.assignedPosition, + cost: member.memberAcquisitionBidPointAmount, + userId: member.userId, + })), + points: team.remainingBidPointAmount, + teamIndex: team.teamIndex, + })); + } + + private dropUndefinedProjectionFields( + projection: Record, + ): Record { + return Object.fromEntries( + Object.entries(projection).filter(([, value]) => value !== undefined), + ); + } + + private arrayFromState(value: unknown): T[] { + return Array.isArray(value) ? (value as T[]) : []; + } + + private cloneRedisStructureArray(value: unknown): T[] { + // 구조 전환 핸들러가 이 작업본을 변이하므로 snapshotBefore 원본과 참조를 공유하면 안 된다. + // structuredClone은 ObjectId를 [object Object]로 망가뜨리므로, 코드베이스 관행대로 + // JSON 클론으로 깊은 복사 + ObjectId/Date 정규화를 함께 수행한다. + return this.cloneJson(this.arrayFromState(value)); + } + + private cloneJson(value: T): T { + return JSON.parse(JSON.stringify(value)) as T; + } + + private numberFromState(value: unknown, fallback = 0): number { + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : fallback; + } + + private stringFromState(value: unknown): string { + return typeof value === 'string' ? value : (value?.toString() ?? ''); + } + + private isAuctionTopTierThreshold( + value: unknown, + ): value is AuctionTopTierThreshold { + return ( + value === 'NONE' || + value === 'EMERALD' || + value === 'DIAMOND' || + value === 'MASTER' || + value === 'MANUAL' + ); + } + + private formatRedisBidRejectCode(code: string): string { + switch (code) { + case 'PHASE': + return 'Auction is not in bidding phase.'; + case 'STALE_BID_ROUND': + return 'Bid round has already changed.'; + case 'EXPIRED': + return 'Bid deadline has already expired.'; + case 'TOO_LOW': + return 'Bid must exceed current bid.'; + case 'UNKNOWN_TEAM': + return 'Unknown team.'; + case 'FULL': + return 'Team already has maximum members.'; + case 'INSUFFICIENT': + return 'Bid must reserve minimum points for remaining slots.'; + case 'DUPLICATE_REQUEST_CONFLICT': + return 'Bid request conflicts with an earlier request.'; + default: + return `Bid was rejected: ${code}.`; + } + } + + private createRedisBidRejectedException( + result: Extract, + bidServerTiming?: AuctionBidServerTiming, + ): BadRequestException { + const message = this.formatRedisBidRejectCode(result.code); + const bidDiagnostics: AuctionBidRejectDiagnostics = { + currentBidRoundDeadlineTimestampMS: + result.currentBidRoundDeadlineTimestampMS, + currentServerTimestampMS: result.currentServerTimestampMS, + }; + return new BadRequestException({ + bidDiagnostics, + ...(bidServerTiming ? { bidServerTiming } : {}), + code: result.code, + message, + }); + } + + private roundBidServerTiming( + timing: AuctionBidServerTiming, + ): AuctionBidServerTiming { + return Object.fromEntries( + Object.entries(timing).map(([key, value]) => [ + key, + typeof value === 'number' ? Math.round(value * 10) / 10 : value, + ]), + ) as AuctionBidServerTiming; + } + + private logSlowBidTiming( + matchId: string, + timing: AuctionBidServerTiming, + ): void { + const serviceTotalDurationMS = timing.serviceTotalDurationMS ?? 0; + if (serviceTotalDurationMS < 250) return; + this.logger.warn( + `Auction bid latency match=${matchId} service=${serviceTotalDurationMS}ms context=${timing.redisBidContextReadDurationMS ?? 0}ms redisBid=${timing.redisBidCommandDurationMS ?? 0}ms fallback=${timing.fallbackFullStatePath ? '1' : '0'}`, + ); } private applyTopTierPriority( @@ -609,7 +2390,9 @@ export class AuctionService { ({ I: 4, II: 3, III: 2, IV: 1, '': 0 } as Record)[ solo.rank ] ?? 0; - return tierIdx * 1000 + rankBonus * 100 + (solo.leaguePoints ?? 0) * 0.001; + return ( + tierIdx * 1000 + rankBonus * 100 + (solo.leaguePoints ?? 0) * 0.001 + ); }; const top = order @@ -684,7 +2467,7 @@ export class AuctionService { sequence: (latest?.sequence ?? 0) + 1, action, actorUserId, - snapshotBefore: JSON.parse(JSON.stringify(snapshotBefore)), + snapshotBefore: this.cloneJson(snapshotBefore), takenAt: new Date(), }); } @@ -705,6 +2488,10 @@ export class AuctionService { return '다음 선수'; case 'complete': return '경매 완료'; + case 'reset': + return '경매 초기화'; + case 'undo': + return '되돌리기'; default: return action; } @@ -809,6 +2596,22 @@ export class AuctionService { } } + private assertValidBidPointAmount(amount: number): void { + if (!Number.isInteger(amount) || amount <= 0) { + throw new BadRequestException('Bid amount must be a positive integer.'); + } + } + + private calculateMaxBidForTeam(team: AuctionTeam): number { + const remainingSlotsAfterCurrentBid = Math.max( + 0, + AUCTION_MAX_TEAM_SIZE - this.countTeamMembersIncludingCaptain(team) - 1, + ); + const reservedPoints = + remainingSlotsAfterCurrentBid * AUCTION_MIN_BID_POINTS; + return Math.max(0, team.points - reservedPoints); + } + private countTeamMembersIncludingCaptain(team: AuctionTeam): number { const userIds = new Set([team.captainUserId.toString()]); for (const member of team.members) { @@ -817,12 +2620,74 @@ export class AuctionService { return userIds.size; } + private isRedisV1Auction(auction: AuctionDocument): boolean { + return auction.auctionEngineVersion === 'redis-v1'; + } + + private assertCompetitionLifecycleMutable( + match: Pick, + action: string, + ): void { + if (match.competitionId) { + throw new ConflictException( + `Cannot ${action} after the immutable Competition has been created. Create a new Match instead.`, + ); + } + } + + private isRestartableResetRedisAuction(auction: AuctionDocument): boolean { + return ( + this.isRedisV1Auction(auction) && + auction.phase === 'waiting' && + auction.matchSideEffectStatus === 'completed' + ); + } + + private isRedisResetStillApplying(auction: AuctionDocument): boolean { + return ( + this.isRedisV1Auction(auction) && + auction.phase === 'waiting' && + auction.matchSideEffectStatus !== 'completed' + ); + } + + private async resetMatchAfterAuctionCancellation( + match: MatchDocument, + session: mongoose.ClientSession, + ): Promise { + await this.tournamentCodeService.releaseFromMatch(match); + await this.tournamentResultService.cancelPolling(match); + match.status = 'recruiting'; + match.teams = []; + match.tournamentCodeIds = []; + match.gameSchedule = []; + match.participants.forEach((participant) => { + participant.excluded = false; + }); + match.teamBuiltAt = undefined; + match.result = undefined; + match.resultPollState = undefined; + await match.save({ session }); + } + + private assertLiveAuctionOperationSupported(auction: AuctionDocument): void { + if (auction.auctionEngineVersion && !this.isRedisV1Auction(auction)) { + throw new BadRequestException( + 'Legacy auction live operations are not supported.', + ); + } + } + private async syncMatchTeamsFromAuction( auction: AuctionDocument, ): Promise { const MatchModel = await this.connectionService.getModel('match'); const match = await MatchModel.findById(auction.matchId); if (!match) throw new NotFoundException('Match not found.'); + if (match.competitionId) { + await this.tournamentResultService.scheduleInitialPoll(match); + return; + } const participantByUserId = new Map( match.participants.map((participant) => [ @@ -831,7 +2696,7 @@ export class AuctionService { ]), ); - match.teams = auction.teams.map((team) => { + const matchTeams = auction.teams.map((team) => { const captain = participantByUserId.get(team.captainUserId.toString()); const members: MatchTeamMember[] = [ { @@ -855,11 +2720,259 @@ export class AuctionService { members, }; }); + if (matchTeams.length === 0) { + throw new Error( + `Auction completed without teams for match ${match._id.toString()}.`, + ); + } + const finalizedAt = match.teamBuiltAt ?? new Date(); + match.teams = matchTeams; match.status = 'team-built'; - match.teamBuiltAt = match.teamBuiltAt ?? new Date(); + match.teamBuiltAt = undefined; await match.save(); - await this.tournamentCodeService.reserveForMatch(match); - await this.tournamentResultService.scheduleInitialPoll(match); + const preparedMatch = + (await this.tournamentCodeService.reserveForMatch(match)) ?? match; + preparedMatch.teamBuiltAt = finalizedAt; + await preparedMatch.save(); + await this.tournamentResultService.scheduleInitialPoll(preparedMatch); + } + + private async syncMatchTeamsFromRedisAuctionState( + auction: AuctionDocument, + state: Record, + ): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const match = await MatchModel.findById(auction.matchId); + if (!match) throw new NotFoundException('Match not found.'); + if (match.competitionId) { + await this.tournamentResultService.scheduleInitialPoll(match); + return; + } + + const participantByUserId = new Map( + match.participants.map((participant) => [ + participant.userId.toString(), + participant, + ]), + ); + const structureInput = this.buildRedisStructureInputFromState(state); + const teams = this.convertRedisTeamsToLegacyTeams( + structureInput.auctionTeams, + ); + + const matchTeams = teams.map((team) => { + const captain = participantByUserId.get(team.captainUserId.toString()); + const members: MatchTeamMember[] = [ + { + userId: team.captainUserId, + assignedPosition: captain?.preferredPositions[0]?.position ?? 'MID', + cost: 0, + }, + ...team.members + .filter( + (member) => + member.userId.toString() !== team.captainUserId.toString(), + ) + .map((member) => ({ + userId: member.userId, + assignedPosition: member.assignedPosition, + cost: member.cost, + })), + ]; + + return { + teamIndex: team.teamIndex, + name: this.resolveTeamName(team.teamIndex), + captainUserId: team.captainUserId, + members, + }; + }); + if (matchTeams.length === 0) { + throw new Error( + `Redis auction completed without teams for match ${match._id.toString()}.`, + ); + } + 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)) ?? match; + preparedMatch.teamBuiltAt = finalizedAt; + await preparedMatch.save(); + await this.tournamentResultService.scheduleInitialPoll(preparedMatch); + } + + private async hydrateRedisStateFromAuctionDocument( + auction: AuctionDocument, + ): Promise { + const auctionTeams = + auction.auctionTeams && auction.auctionTeams.length > 0 + ? auction.auctionTeams + : convertLegacyAuctionTeamsToRedisTeams(auction.teams ?? []); + const structureInput = { + auctionPlayerOrder: auction.auctionPlayerOrder ?? auction.order ?? [], + auctionTeams, + bidRoundExtensionSeconds: + auction.bidRoundExtensionSeconds ?? auction.bidExtensionSeconds ?? 5, + currentAuctionPlayerOrderIndex: + auction.currentAuctionPlayerOrderIndex ?? auction.currentIndex ?? 0, + currentAuctionRound: + auction.currentAuctionRound ?? auction.auctionRound ?? 1, + initialTeamBidPointAmount: + auction.initialTeamBidPointAmount ?? auction.initialPoints ?? 1000, + manualTopTierAuctionPriorityUserIds: + auction.manualTopTierAuctionPriorityUserIds ?? + auction.manualTopTierUserIds ?? + [], + maximumBidRoundDurationSeconds: + auction.maximumBidRoundDurationSeconds ?? auction.maxTimerSeconds ?? 30, + passedAuctionPlayerQueue: + auction.passedAuctionPlayerQueue ?? auction.passedQueue ?? [], + topTierAuctionPriorityThreshold: + auction.topTierAuctionPriorityThreshold ?? + auction.topTierThreshold ?? + 'NONE', + }; + await this.auctionRedisCommandService.hydrateState( + auction.matchId.toString(), + { + auctionHistorySequence: auction.currentAuctionHistorySequence ?? 0, + auctionLifecycleId: + auction.auctionLifecycleId ?? + `auction:${auction._id.toString()}:rehydrated`, + liveStatePatch: { + ...buildAuctionRedisLiveStatePatchFromStructure(structureInput), + currentHighestBidPointAmount: + auction.currentHighestBidPointAmount ?? auction.currentBid ?? 0, + currentHighestBidderTeamIndex: + auction.currentHighestBidderTeamIndex ?? + auction.currentBidderTeamIndex ?? + -1, + }, + maximumBidRoundDurationSeconds: + structureInput.maximumBidRoundDurationSeconds, + matchId: auction.matchId.toString(), + phase: auction.phase, + revision: auction.revision ?? 0, + structureStateJson: stringifyAuctionRedisStructureState(structureInput), + }, + ); + } + + private async clearRedisAuctionRuntimeForLifecycle( + matchId: string, + expectedAuctionLifecycleId?: string, + ): Promise { + const keys = buildAuctionRedisKeys(matchId); + const cleared = await this.auctionRedisService + .raw() + .sendCommand([ + 'EVAL', + [ + 'local expectedAuctionLifecycleId = ARGV[2]', + "if expectedAuctionLifecycleId ~= '' then", + " local currentAuctionLifecycleId = redis.call('HGET', KEYS[1], 'auctionLifecycleId')", + ' if currentAuctionLifecycleId and currentAuctionLifecycleId ~= expectedAuctionLifecycleId then', + ' return 0', + ' end', + 'end', + "redis.call('ZREM', KEYS[2], ARGV[1])", + "redis.call('DEL', KEYS[1], KEYS[3], KEYS[4], KEYS[5], KEYS[6], KEYS[7], KEYS[8], KEYS[9], KEYS[10], KEYS[11])", + '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, + expectedAuctionLifecycleId ?? '', + ]); + if (Number(cleared) !== 1) return; + await this.clearRedisDurabilityPayloadsForLifecycle( + keys, + expectedAuctionLifecycleId, + ); + } + + private async clearRedisDurabilityPayloadsForLifecycle( + keys: ReturnType, + expectedAuctionLifecycleId?: string, + ): Promise { + let cursor = '0'; + do { + const reply = await this.auctionRedisService + .raw() + .sendCommand([ + 'SCAN', + cursor, + 'MATCH', + `${keys.durabilityPayloadKeyPrefix}*`, + 'COUNT', + '100', + ]); + if (!Array.isArray(reply) || reply.length < 2) return; + cursor = String(reply[0]); + const payloadKeys = Array.isArray(reply[1]) ? reply[1].map(String) : []; + if (payloadKeys.length === 0) continue; + + const values = await this.auctionRedisService + .raw() + .sendCommand(['MGET', ...payloadKeys]); + const payloadKeysToDelete = payloadKeys.filter((payloadKey, index) => + this.shouldDeleteRedisDurabilityPayload( + Array.isArray(values) ? values[index] : undefined, + expectedAuctionLifecycleId, + payloadKey, + ), + ); + if (payloadKeysToDelete.length === 0) continue; + + await this.auctionRedisService + .raw() + .sendCommand([ + 'ZREM', + keys.durabilityRetryQueueKey, + ...payloadKeysToDelete, + ]); + await this.auctionRedisService + .raw() + .sendCommand([ + 'ZREM', + keys.durabilityDeadLetterQueueKey, + ...payloadKeysToDelete, + ]); + await this.auctionRedisService + .raw() + .sendCommand(['DEL', ...payloadKeysToDelete]); + } while (cursor !== '0'); + } + + private shouldDeleteRedisDurabilityPayload( + payloadValue: unknown, + expectedAuctionLifecycleId: string | undefined, + payloadKey: string, + ): boolean { + if (!expectedAuctionLifecycleId) return true; + if (typeof payloadValue !== 'string') return false; + try { + const payload = JSON.parse(payloadValue) as Record; + return payload.auctionLifecycleId === expectedAuctionLifecycleId; + } catch { + this.logger.warn( + `Failed to parse auction durability payload ${payloadKey}.`, + ); + return false; + } } private enqueueBackgroundOrderEnrichment(params: { @@ -874,7 +2987,7 @@ export class AuctionService { void this.refreshOrderSnapshotsFromRiot(params).catch((error: unknown) => { this.logger.warn( `Auction background Riot refresh failed for ${params.auctionId.toString()}: ${ - error instanceof Error ? error.message : error + error instanceof Error ? error.message : String(error) }`, ); }); @@ -930,7 +3043,7 @@ export class AuctionService { } catch (error: unknown) { this.logger.warn( `Failed to refresh auction Riot snapshot for ${target.puuid}: ${ - error instanceof Error ? error.message : error + error instanceof Error ? error.message : String(error) }`, ); } @@ -970,13 +3083,16 @@ async function runWithConcurrency( if (items.length === 0) return; const queue = [...items]; - const runners = Array.from({ length: Math.min(concurrency, queue.length) }, async () => { - while (queue.length > 0) { - const item = queue.shift(); - if (item === undefined) return; - await worker(item); - } - }); + const runners = Array.from( + { length: Math.min(concurrency, queue.length) }, + async () => { + while (queue.length > 0) { + const item = queue.shift(); + if (item === undefined) return; + await worker(item); + } + }, + ); await Promise.allSettled(runners); } diff --git a/apps/api/src/modules/auction/dto/auction.dto.ts b/apps/api/src/modules/auction/dto/auction.dto.ts index 9c4e4b8e..d7a58e7f 100644 --- a/apps/api/src/modules/auction/dto/auction.dto.ts +++ b/apps/api/src/modules/auction/dto/auction.dto.ts @@ -7,6 +7,8 @@ import { IsInt, IsMongoId, IsOptional, + IsString, + IsUUID, Max, Min, ValidateNested, @@ -28,10 +30,13 @@ class CaptainAssignmentDto { @IsInt() @Min(100) @Max(100000) - initialPoints?: number; + initialTeamBidPointAmount?: number; } export class StartAuctionDto { + @IsUUID() + startAuctionRequestId!: string; + @IsArray() @ArrayMinSize(2) @ArrayMaxSize(16) @@ -43,50 +48,92 @@ export class StartAuctionDto { @IsInt() @Min(100) @Max(100000) - initialPoints?: number; + initialTeamBidPointAmount?: number; @IsOptional() @IsEnum(AUCTION_TOP_TIER_THRESHOLDS) - topTierThreshold?: AuctionTopTierThreshold; + topTierAuctionPriorityThreshold?: AuctionTopTierThreshold; @IsOptional() @IsArray() @ArrayMaxSize(100) @IsMongoId({ each: true }) - manualTopTierUserIds?: string[]; + manualTopTierAuctionPriorityUserIds?: string[]; @IsOptional() @IsInt() @Min(5) - maxTimerSeconds?: number; + maximumBidRoundDurationSeconds?: number; @IsOptional() @IsInt() @Min(0) - bidExtensionSeconds?: number; + bidRoundExtensionSeconds?: number; } export class PlaceBidDto { - @IsInt() - @Min(1) - teamIndex!: number; + @IsOptional() + @IsUUID() + bidRequestId?: string; @IsInt() @Min(1) - amount!: number; + bidderTeamIndex!: number; + + @IsInt() + @Min(1) + bidPointAmount!: number; @IsOptional() - @IsMongoId() - bidderUserId?: string; + clientObservedAuctionLifecycleId?: string; + + @IsOptional() + clientObservedCurrentBidRoundPlayerUserId?: string; } -export class SoldDto { +export class AuctionActionRequestDto { + @IsOptional() + @IsUUID() + auctionActionRequestId?: string; + + @IsOptional() + @IsString() + clientObservedAuctionLifecycleId?: string; + + @IsOptional() + @IsInt() + @Min(0) + clientObservedRevision?: number; + + @IsOptional() + @IsString() + clientObservedPhase?: string; + + @IsOptional() + @IsString() + clientObservedCurrentBidRoundPlayerUserId?: string; + + @IsOptional() + @IsInt() + @Min(0) + clientObservedCurrentAuctionPlayerOrderIndex?: number; +} + +export class SoldDto extends AuctionActionRequestDto { @IsOptional() @IsEnum(['TOP', 'JGL', 'MID', 'ADC', 'SUP']) assignedPosition?: 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP'; } -export class UndoAuctionDto { +export class OpenBiddingDto extends AuctionActionRequestDto {} + +export class NextAuctionDto extends AuctionActionRequestDto {} + +export class PassedAuctionDto extends AuctionActionRequestDto {} + +export class ResetAuctionDto extends AuctionActionRequestDto {} + +export class UndoAuctionDto extends AuctionActionRequestDto { @IsInt() @Min(1) sequence!: number; diff --git a/apps/api/src/modules/auction/redis/auction-redis-command.service.spec.ts b/apps/api/src/modules/auction/redis/auction-redis-command.service.spec.ts new file mode 100644 index 00000000..515cdb51 --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis-command.service.spec.ts @@ -0,0 +1,379 @@ +import { AuctionRedisService } from './auction-redis.service'; +import { AuctionRedisCommandService } from './auction-redis-command.service'; +import { AUCTION_APPLY_TRANSITION_SCRIPT } from './auction-redis.apply-transition'; +import { AUCTION_BID_SCRIPT } from './auction-redis.bid'; +import { AUCTION_EXPIRE_PREPARE_SCRIPT } from './auction-redis.expire-prepare'; +import { AUCTION_RESERVE_ACTION_REQUEST_SCRIPT } from './auction-redis.reserve-action'; +import { AUCTION_HYDRATE_STATE_SCRIPT } from './auction-redis.state'; + +function makeService(reply: unknown) { + const auctionRedisService = { + evalScript: jest.fn().mockResolvedValue(reply), + } as unknown as jest.Mocked; + return { + auctionRedisService, + service: new AuctionRedisCommandService(auctionRedisService), + }; +} + +describe('AuctionRedisCommandService', () => { + it('executes BID script and parses successful reply', async () => { + const { service, auctionRedisService } = makeService([ + 'OK', + 'bid-1', + '9', + '1000', + '120', + '2', + '31000', + '{"bidPointAmount":120}', + ]); + + await expect( + service.placeBid('match-1', { + bidderTeamIndex: 2, + bidPointAmount: 120, + bidRequestId: 'bid-1', + bidderUserId: 'captain-2', + clientObservedAuctionLifecycleId: 'life-1', + clientObservedCurrentBidRoundPlayerUserId: 'player-1', + maximumAuctionTeamMemberCount: 5, + maximumStoredAuctionBidHistoryCount: 200, + maximumStoredBidRequestResultCount: 100, + matchId: 'match-1', + minimumBidPointReservePerRemainingAuctionTeamMemberSlot: 10, + minimumBidRequestResultReplayWindowMS: 60_000, + }), + ).resolves.toEqual({ + auctionBidHistoryEntry: { bidPointAmount: 120 }, + bidRequestId: 'bid-1', + currentHighestBidderTeamIndex: 2, + currentHighestBidPointAmount: 120, + currentBidRoundDeadlineTimestampMS: 31_000, + currentServerTimestampMS: 1_000, + ok: true, + revision: 9, + }); + expect(auctionRedisService.evalScript).toHaveBeenCalledWith( + AUCTION_BID_SCRIPT, + expect.arrayContaining(['auction:match-1:liveAuctionState']), + expect.arrayContaining(['match-1', '2', '120']), + ); + }); + + it('parses BID rejected reply', async () => { + const { service } = makeService([ + 'REJECTED', + 'TOO_LOW', + 'bid-1', + '1000', + '31000', + ]); + + await expect( + service.placeBid('match-1', { + bidderTeamIndex: 2, + bidPointAmount: 120, + bidRequestId: 'bid-1', + bidderUserId: 'captain-2', + clientObservedAuctionLifecycleId: 'life-1', + clientObservedCurrentBidRoundPlayerUserId: 'player-1', + maximumAuctionTeamMemberCount: 5, + maximumStoredAuctionBidHistoryCount: 200, + maximumStoredBidRequestResultCount: 100, + matchId: 'match-1', + minimumBidPointReservePerRemainingAuctionTeamMemberSlot: 10, + minimumBidRequestResultReplayWindowMS: 60_000, + }), + ).resolves.toEqual({ + bidRequestId: 'bid-1', + code: 'TOO_LOW', + currentBidRoundDeadlineTimestampMS: 31_000, + currentServerTimestampMS: 1000, + rejected: true, + }); + }); + + it('executes reserve action request and parses lease metadata', async () => { + const { service, auctionRedisService } = makeService([ + 'RESERVED', + 'life-1:request-1', + 'transition-1', + '', + '2', + '1', + '1000', + ]); + + await expect( + service.reserveActionRequest('match-1', { + auctionActionRequestId: 'request-1', + auctionActionType: 'sold', + auctionStateTransitionId: 'transition-1', + clientObservedAuctionLifecycleId: 'life-1', + clientObservedPhase: 'bidding', + clientObservedRevision: 8, + leaseDurationMS: 10_000, + maximumStoredAuctionActionRequestResultCount: 100, + minimumAuctionActionRequestResultReplayWindowMS: 60_000, + processingOwnerToken: 'owner-1', + }), + ).resolves.toEqual({ + actionRequestScopeKey: 'life-1:request-1', + auctionStateTransitionId: 'transition-1', + currentServerTimestampMS: 1000, + newAuctionLifecycleId: '', + observedProcessingLeaseVersion: 2, + reserved: true, + wasLeaseExpired: true, + }); + expect(auctionRedisService.evalScript).toHaveBeenCalledWith( + AUCTION_RESERVE_ACTION_REQUEST_SCRIPT, + expect.arrayContaining(['auction:match-1:auctionActionRequestResults']), + expect.arrayContaining(['life-1', 'request-1', 'sold']), + ); + }); + + it('parses reserve action request replay refetch metadata', async () => { + const { service } = makeService([ + 'REPLAY', + 'applied', + 'life-1:request-1', + '11', + '', + 'transition-1', + '', + '2', + '3000', + '', + '1', + ]); + + await expect( + service.reserveActionRequest('match-1', { + auctionActionRequestId: 'request-1', + auctionActionType: 'sold', + auctionStateTransitionId: 'transition-1', + clientObservedAuctionLifecycleId: 'life-1', + clientObservedPhase: 'bidding', + clientObservedRevision: 8, + leaseDurationMS: 10_000, + maximumStoredAuctionActionRequestResultCount: 100, + minimumAuctionActionRequestResultReplayWindowMS: 60_000, + processingOwnerToken: 'owner-1', + }), + ).resolves.toEqual({ + actionRequestScopeKey: 'life-1:request-1', + currentServerTimestampMS: 3000, + isReplay: true, + requiresRefetch: true, + replayStatus: 'applied', + revision: 11, + }); + }); + + it('executes apply transition and parses successful reply', async () => { + const { service, auctionRedisService } = makeService([ + 'OK', + 'transition-1', + '11', + '2000', + ]); + + await expect( + service.applyTransition('match-1', { + afterAuctionStructureStateJson: '{"auctionTeams":[]}', + auctionHistorySequence: 5, + auctionLifecycleId: 'life-1', + auctionStateTransitionId: 'transition-1', + broadcastStateRevision: 11, + deadline: { mode: 'remove' }, + durabilityPayloadJson: '{"auctionStateTransitionId":"transition-1"}', + expectedPhase: 'bidding', + expectedRevision: 10, + liveStatePatch: { phase: 'sold' }, + matchId: 'match-1', + shouldBroadcastState: true, + }), + ).resolves.toEqual({ + auctionStateTransitionId: 'transition-1', + currentServerTimestampMS: 2000, + ok: true, + revision: 11, + }); + expect(auctionRedisService.evalScript).toHaveBeenCalledWith( + AUCTION_APPLY_TRANSITION_SCRIPT, + expect.arrayContaining(['auction:match-1:liveAuctionState']), + expect.arrayContaining(['match-1', 'life-1', 'transition-1']), + ); + }); + + it('parses apply transition replay and rejected replies', async () => { + await expect( + makeService(['REPLAY', 'APPLIED', 'transition-1', '2100']) + .service.applyTransition('match-1', { + afterAuctionStructureStateJson: '{}', + auctionHistorySequence: 5, + auctionLifecycleId: 'life-1', + auctionStateTransitionId: 'transition-1', + broadcastStateRevision: 11, + deadline: { mode: 'none' }, + durabilityPayloadJson: '{}', + expectedPhase: 'sold', + expectedRevision: 10, + liveStatePatch: {}, + matchId: 'match-1', + shouldBroadcastState: false, + }), + ).resolves.toEqual({ + auctionStateTransitionId: 'transition-1', + currentServerTimestampMS: 2100, + isReplay: true, + replayStatus: 'APPLIED', + }); + + await expect( + makeService(['REJECTED', 'CONFLICT', 'transition-1', '2200']) + .service.applyTransition('match-1', { + afterAuctionStructureStateJson: '{}', + auctionHistorySequence: 5, + auctionLifecycleId: 'life-1', + auctionStateTransitionId: 'transition-1', + broadcastStateRevision: 11, + deadline: { mode: 'none' }, + durabilityPayloadJson: '{}', + expectedPhase: 'sold', + expectedRevision: 10, + liveStatePatch: {}, + matchId: 'match-1', + shouldBroadcastState: false, + }), + ).resolves.toEqual({ + auctionStateTransitionId: 'transition-1', + code: 'CONFLICT', + currentServerTimestampMS: 2200, + rejected: true, + }); + }); + + it('executes expire prepare and parses expiry decisions', async () => { + const { service, auctionRedisService } = makeService([ + 'OK', + 'sold', + 'expire-1', + '12', + '3000', + ]); + + await expect( + service.expirePrepare('match-1', { + auctionStateTransitionId: 'expire-1', + bidRoundExpiryRetryDelayMS: 3000, + matchId: 'match-1', + }), + ).resolves.toEqual({ + auctionStateTransitionId: 'expire-1', + bidRoundExpiryDecision: 'sold', + currentServerTimestampMS: 3000, + isReplay: undefined, + ok: true, + revision: 12, + }); + expect(auctionRedisService.evalScript).toHaveBeenCalledWith( + AUCTION_EXPIRE_PREPARE_SCRIPT, + expect.arrayContaining(['auction:match-1:liveAuctionState']), + expect.arrayContaining(['match-1', 'expire-1']), + ); + }); + + it('parses expire prepare replay and noop replies', async () => { + await expect( + makeService(['REPLAY', 'passed', 'expire-1', '12', '3100']) + .service.expirePrepare('match-1', { + auctionStateTransitionId: 'expire-1', + bidRoundExpiryRetryDelayMS: 3000, + matchId: 'match-1', + }), + ).resolves.toMatchObject({ + auctionStateTransitionId: 'expire-1', + bidRoundExpiryDecision: 'passed', + currentServerTimestampMS: 3100, + isReplay: true, + ok: true, + revision: 12, + }); + + await expect( + makeService(['NOOP', 'NOT_DUE', '3200']).service.expirePrepare( + 'match-1', + { + auctionStateTransitionId: 'expire-1', + bidRoundExpiryRetryDelayMS: 3000, + matchId: 'match-1', + }, + ), + ).resolves.toEqual({ + code: 'NOT_DUE', + currentServerTimestampMS: 3200, + noop: true, + }); + }); + + it('executes hydrate state and parses hydrate/noop replies', async () => { + const { service, auctionRedisService } = makeService(['OK', '7', '4000']); + + await expect( + service.hydrateState('match-1', { + auctionHistorySequence: 3, + auctionLifecycleId: 'life-1', + maximumBidRoundDurationSeconds: 30, + matchId: 'match-1', + phase: 'presenting', + revision: 6, + structureStateJson: '{"auctionTeams":[]}', + }), + ).resolves.toEqual({ + currentServerTimestampMS: 4000, + hydrated: true, + revision: 7, + }); + expect(auctionRedisService.evalScript).toHaveBeenCalledWith( + AUCTION_HYDRATE_STATE_SCRIPT, + expect.arrayContaining(['auction:match-1:liveAuctionState']), + expect.arrayContaining(['match-1', 'life-1', '6']), + ); + + await expect( + makeService(['NOOP', '8', '4100']).service.hydrateState('match-1', { + auctionHistorySequence: 3, + auctionLifecycleId: 'life-1', + maximumBidRoundDurationSeconds: 30, + matchId: 'match-1', + phase: 'presenting', + revision: 6, + structureStateJson: '{}', + }), + ).resolves.toEqual({ + currentServerTimestampMS: 4100, + noop: true, + revision: 8, + }); + + await expect( + makeService(['REJECTED', 'INVALID_PATCH_ARITY', '4200']) + .service.hydrateState('match-1', { + auctionHistorySequence: 3, + auctionLifecycleId: 'life-1', + maximumBidRoundDurationSeconds: 30, + matchId: 'match-1', + phase: 'presenting', + revision: 6, + structureStateJson: '{}', + }), + ).resolves.toEqual({ + code: 'INVALID_PATCH_ARITY', + currentServerTimestampMS: 4200, + rejected: true, + }); + }); +}); diff --git a/apps/api/src/modules/auction/redis/auction-redis-command.service.ts b/apps/api/src/modules/auction/redis/auction-redis-command.service.ts new file mode 100644 index 00000000..0c9d7e75 --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis-command.service.ts @@ -0,0 +1,384 @@ +import { Injectable } from '@nestjs/common'; +import { + type AuctionApplyTransitionScriptInput, + buildAuctionApplyTransitionScriptInvocation, +} from './auction-redis.apply-transition'; +import { + type AuctionBidScriptInput, + buildAuctionBidScriptInvocation, +} from './auction-redis.bid'; +import { + type AuctionExpirePrepareScriptInput, + buildAuctionExpirePrepareScriptInvocation, +} from './auction-redis.expire-prepare'; +import { buildAuctionRedisKeys } from './auction-redis.keys'; +import { AuctionRedisService } from './auction-redis.service'; +import { + type AuctionReserveActionRequestScriptInput, + buildAuctionReserveActionRequestScriptInvocation, +} from './auction-redis.reserve-action'; +import { + type HydrateAuctionStateScriptInput, + buildHydrateAuctionStateScriptInvocation, +} from './auction-redis.state'; + +export type AuctionBidCommandResult = + | { + auctionBidHistoryEntry: Record; + bidRequestId: string; + currentBidRoundDeadlineTimestampMS: number; + currentHighestBidderTeamIndex: number; + currentHighestBidPointAmount: number; + currentServerTimestampMS: number; + isReplay?: boolean; + ok: true; + revision: number; + } + | { + bidRequestId: string; + code: string; + currentBidRoundDeadlineTimestampMS?: number; + currentServerTimestampMS: number; + isReplay?: boolean; + rejected: true; + }; + +export type AuctionReserveActionRequestCommandResult = + | { + actionRequestScopeKey: string; + auctionStateTransitionId: string; + currentServerTimestampMS: number; + newAuctionLifecycleId: string; + observedProcessingLeaseVersion: number; + reserved: true; + wasLeaseExpired: boolean; + } + | { + actionRequestScopeKey: string; + code: string; + currentServerTimestampMS: number; + rejected: true; + } + | { + actionRequestScopeKey: string; + currentServerTimestampMS: number; + isReplay: true; + requiresRefetch?: boolean; + replayStatus: string; + responseJson?: string; + revision?: number; + }; + +export type AuctionApplyTransitionCommandResult = + | { + auctionStateTransitionId: string; + currentServerTimestampMS: number; + ok: true; + revision: number; + } + | { + auctionStateTransitionId: string; + currentServerTimestampMS: number; + isReplay: true; + replayStatus: string; + } + | { + auctionStateTransitionId: string; + code: string; + currentServerTimestampMS: number; + rejected: true; + }; + +export type AuctionExpirePrepareCommandResult = + | { + auctionStateTransitionId: string; + bidRoundExpiryDecision: 'passed' | 'sold'; + currentServerTimestampMS: number; + isReplay?: boolean; + ok: true; + revision: number; + } + | { + code: string; + currentServerTimestampMS: number; + noop: true; + }; + +export type AuctionHydrateStateCommandResult = + | { + currentServerTimestampMS: number; + hydrated: true; + revision: number; + } + | { + currentServerTimestampMS: number; + noop: true; + revision: number; + } + | { + code: string; + currentServerTimestampMS: number; + rejected: true; + }; + +@Injectable() +export class AuctionRedisCommandService { + constructor(private readonly auctionRedisService: AuctionRedisService) {} + + public async placeBid( + matchId: string, + input: AuctionBidScriptInput, + ): Promise { + const invocation = buildAuctionBidScriptInvocation( + buildAuctionRedisKeys(matchId), + input, + ); + const reply = await this.auctionRedisService.evalScript( + invocation.script, + invocation.keys, + invocation.values, + ); + return parseBidCommandReply(reply); + } + + public async reserveActionRequest( + matchId: string, + input: AuctionReserveActionRequestScriptInput, + ): Promise { + const invocation = buildAuctionReserveActionRequestScriptInvocation( + buildAuctionRedisKeys(matchId), + input, + ); + const reply = await this.auctionRedisService.evalScript( + invocation.script, + invocation.keys, + invocation.values, + ); + return parseReserveActionRequestReply(reply); + } + + public async applyTransition( + matchId: string, + input: AuctionApplyTransitionScriptInput, + ): Promise { + const invocation = buildAuctionApplyTransitionScriptInvocation( + buildAuctionRedisKeys(matchId), + input, + ); + const reply = await this.auctionRedisService.evalScript( + invocation.script, + invocation.keys, + invocation.values, + ); + return parseApplyTransitionReply(reply); + } + + public async expirePrepare( + matchId: string, + input: AuctionExpirePrepareScriptInput, + ): Promise { + const invocation = buildAuctionExpirePrepareScriptInvocation( + buildAuctionRedisKeys(matchId), + input, + ); + const reply = await this.auctionRedisService.evalScript( + invocation.script, + invocation.keys, + invocation.values, + ); + return parseExpirePrepareReply(reply); + } + + public async hydrateState( + matchId: string, + input: HydrateAuctionStateScriptInput, + ): Promise { + const invocation = buildHydrateAuctionStateScriptInvocation( + buildAuctionRedisKeys(matchId), + input, + ); + const reply = await this.auctionRedisService.evalScript( + invocation.script, + invocation.keys, + invocation.values, + ); + return parseHydrateStateReply(reply); + } +} + +function parseBidCommandReply(reply: unknown[]): AuctionBidCommandResult { + const values = reply.map(String); + const kind = values[0]; + if (kind === 'OK') { + return { + auctionBidHistoryEntry: JSON.parse(values[7] || '{}') as Record< + string, + unknown + >, + bidRequestId: values[1], + currentBidRoundDeadlineTimestampMS: numberValue(values[6]), + currentHighestBidderTeamIndex: numberValue(values[5]), + currentHighestBidPointAmount: numberValue(values[4]), + currentServerTimestampMS: numberValue(values[3]), + ok: true, + revision: numberValue(values[2]), + }; + } + if (kind === 'REPLAY') { + const status = values[1]; + if (status === 'ok') { + return { + auctionBidHistoryEntry: JSON.parse(values[8] || '{}') as Record< + string, + unknown + >, + bidRequestId: values[2], + currentBidRoundDeadlineTimestampMS: numberValue(values[7]), + currentHighestBidderTeamIndex: numberValue(values[6]), + currentHighestBidPointAmount: numberValue(values[5]), + currentServerTimestampMS: numberValue(values[9]), + isReplay: true, + ok: true, + revision: numberValue(values[3]), + }; + } + return { + bidRequestId: values[2], + code: values[4] || status, + currentBidRoundDeadlineTimestampMS: optionalNumberValue(values[7]), + currentServerTimestampMS: numberValue(values[9]), + isReplay: true, + rejected: true, + }; + } + return { + bidRequestId: values[2] ?? '', + code: values[1] ?? 'UNKNOWN', + currentBidRoundDeadlineTimestampMS: optionalNumberValue(values[4]), + currentServerTimestampMS: numberValue(values[3]), + rejected: true, + }; +} + +function parseReserveActionRequestReply( + reply: unknown[], +): AuctionReserveActionRequestCommandResult { + const values = reply.map(String); + const kind = values[0]; + if (kind === 'RESERVED') { + return { + actionRequestScopeKey: values[1], + auctionStateTransitionId: values[2], + currentServerTimestampMS: numberValue(values[6]), + newAuctionLifecycleId: values[3], + observedProcessingLeaseVersion: numberValue(values[4]), + reserved: true, + wasLeaseExpired: values[5] === '1', + }; + } + if (kind === 'REPLAY') { + return { + actionRequestScopeKey: values[2], + currentServerTimestampMS: numberValue(values[8]), + isReplay: true, + requiresRefetch: values[10] === '1' || undefined, + replayStatus: values[1], + responseJson: values[9] || undefined, + revision: values[3] ? numberValue(values[3]) : undefined, + }; + } + return { + actionRequestScopeKey: values[2] ?? '', + code: values[1] ?? 'UNKNOWN', + currentServerTimestampMS: numberValue(values[3]), + rejected: true, + }; +} + +function parseApplyTransitionReply( + reply: unknown[], +): AuctionApplyTransitionCommandResult { + const values = reply.map(String); + const kind = values[0]; + if (kind === 'OK') { + return { + auctionStateTransitionId: values[1], + currentServerTimestampMS: numberValue(values[3]), + ok: true, + revision: numberValue(values[2]), + }; + } + if (kind === 'REPLAY') { + return { + auctionStateTransitionId: values[2], + currentServerTimestampMS: numberValue(values[3]), + isReplay: true, + replayStatus: values[1], + }; + } + return { + auctionStateTransitionId: values[2] ?? '', + code: values[1] ?? 'UNKNOWN', + currentServerTimestampMS: numberValue(values[3]), + rejected: true, + }; +} + +function parseExpirePrepareReply( + reply: unknown[], +): AuctionExpirePrepareCommandResult { + const values = reply.map(String); + const kind = values[0]; + if (kind === 'OK' || kind === 'REPLAY') { + return { + auctionStateTransitionId: values[2], + bidRoundExpiryDecision: + values[1] === 'sold' || values[1] === 'passed' ? values[1] : 'passed', + currentServerTimestampMS: numberValue(values[4]), + isReplay: kind === 'REPLAY' || undefined, + ok: true, + revision: numberValue(values[3]), + }; + } + return { + code: values[1] ?? 'UNKNOWN', + currentServerTimestampMS: numberValue(values[2]), + noop: true, + }; +} + +function parseHydrateStateReply( + reply: unknown[], +): AuctionHydrateStateCommandResult { + const values = reply.map(String); + if (values[0] === 'OK') { + return { + currentServerTimestampMS: numberValue(values[2]), + hydrated: true, + revision: numberValue(values[1]), + }; + } + if (values[0] === 'REJECTED') { + return { + code: values[1] ?? 'UNKNOWN', + currentServerTimestampMS: numberValue(values[2]), + rejected: true, + }; + } + return { + currentServerTimestampMS: numberValue(values[2]), + noop: true, + revision: numberValue(values[1]), + }; +} + +function numberValue(value: string | undefined): number { + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : 0; +} + +function optionalNumberValue(value: string | undefined): number | undefined { + if (value === undefined || value === '') return undefined; + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : undefined; +} diff --git a/apps/api/src/modules/auction/redis/auction-redis-projection.spec.ts b/apps/api/src/modules/auction/redis/auction-redis-projection.spec.ts new file mode 100644 index 00000000..4bedf58a --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis-projection.spec.ts @@ -0,0 +1,153 @@ +import mongoose from 'mongoose'; +import { + buildAuctionRedisLiveStatePatchFromStructure, + buildAuctionRedisStructureState, + convertLegacyAuctionTeamsToRedisTeams, +} from './auction-redis-projection'; + +describe('auction redis projection helpers', () => { + it('converts legacy auction team fields to redis-v1 names', () => { + const captainUserId = new mongoose.Types.ObjectId(); + const memberUserId = new mongoose.Types.ObjectId(); + + expect( + convertLegacyAuctionTeamsToRedisTeams([ + { + teamIndex: 1, + captainUserId, + points: 970, + members: [ + { + userId: memberUserId, + assignedPosition: 'ADC', + cost: 30, + }, + ], + }, + ]), + ).toEqual([ + { + teamIndex: 1, + captainUserId, + remainingBidPointAmount: 970, + members: [ + { + userId: memberUserId, + assignedPosition: 'ADC', + memberAcquisitionBidPointAmount: 30, + }, + ], + }, + ]); + }); + + it('builds the redis structure state with only structure/config fields', () => { + const captainUserId = new mongoose.Types.ObjectId(); + const playerUserId = new mongoose.Types.ObjectId(); + + expect( + buildAuctionRedisStructureState({ + auctionPlayerOrder: [ + { + userId: playerUserId, + puuid: 'puuid', + gameName: 'Player', + tagLine: 'KR1', + profileIconId: 1, + preferredPositions: [{ position: 'MID', priority: 1 }], + tiers: [], + tierHistory: [], + masteries: [], + passCount: 0, + }, + ], + auctionTeams: [ + { + teamIndex: 1, + captainUserId, + remainingBidPointAmount: 1000, + members: [], + }, + ], + bidRoundExtensionSeconds: 5, + currentAuctionPlayerOrderIndex: 0, + currentAuctionRound: 1, + initialTeamBidPointAmount: 1000, + manualTopTierAuctionPriorityUserIds: [], + maximumBidRoundDurationSeconds: 30, + passedAuctionPlayerQueue: [], + topTierAuctionPriorityThreshold: 'NONE', + }), + ).toMatchObject({ + auctionPlayerOrder: [expect.objectContaining({ userId: playerUserId })], + auctionTeams: [ + expect.objectContaining({ + captainUserId, + remainingBidPointAmount: 1000, + teamIndex: 1, + }), + ], + bidRoundExtensionSeconds: 5, + currentAuctionPlayerOrderIndex: 0, + currentAuctionRound: 1, + initialTeamBidPointAmount: 1000, + maximumBidRoundDurationSeconds: 30, + passedAuctionPlayerQueue: [], + topTierAuctionPriorityThreshold: 'NONE', + }); + }); + + it('builds live state patch required by BID Lua', () => { + const captainUserId = new mongoose.Types.ObjectId(); + const playerUserId = new mongoose.Types.ObjectId(); + + expect( + buildAuctionRedisLiveStatePatchFromStructure({ + auctionPlayerOrder: [ + { + userId: playerUserId, + puuid: 'puuid', + gameName: 'Player', + tagLine: 'KR1', + profileIconId: 1, + preferredPositions: [{ position: 'MID', priority: 1 }], + tiers: [], + tierHistory: [], + masteries: [], + passCount: 0, + }, + ], + auctionTeams: [ + { + teamIndex: 2, + captainUserId, + remainingBidPointAmount: 970, + members: [ + { + userId: new mongoose.Types.ObjectId(), + assignedPosition: 'ADC', + memberAcquisitionBidPointAmount: 30, + }, + ], + }, + ], + bidRoundExtensionSeconds: 5, + currentAuctionPlayerOrderIndex: 0, + currentAuctionRound: 1, + initialTeamBidPointAmount: 1000, + manualTopTierAuctionPriorityUserIds: [], + maximumBidRoundDurationSeconds: 30, + passedAuctionPlayerQueue: [], + topTierAuctionPriorityThreshold: 'NONE', + }), + ).toEqual({ + bidRoundExtensionSeconds: 5, + currentAuctionPlayerOrderIndex: 0, + currentBidRoundPlayerUserId: playerUserId.toString(), + maximumBidRoundDurationSeconds: 30, + 'team:2:assignedAuctionTeamMemberCount': 2, + 'team:2:captainUserId': captainUserId.toString(), + 'team:2:remainingBidPointAmount': 970, + }); + }); +}); diff --git a/apps/api/src/modules/auction/redis/auction-redis-projection.ts b/apps/api/src/modules/auction/redis/auction-redis-projection.ts new file mode 100644 index 00000000..3993a4a9 --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis-projection.ts @@ -0,0 +1,94 @@ +import type { + AuctionPlayerSnapshot, + AuctionTeam, + AuctionTopTierThreshold, + RedisAuctionTeam, +} from '../../global/database/schema'; +import type mongoose from 'mongoose'; + +export interface AuctionRedisStructureStateInput { + auctionPlayerOrder: AuctionPlayerSnapshot[]; + auctionTeams: RedisAuctionTeam[]; + bidRoundExtensionSeconds: number; + currentAuctionPlayerOrderIndex: number; + currentAuctionRound: number; + initialTeamBidPointAmount: number; + manualTopTierAuctionPriorityUserIds: mongoose.Types.ObjectId[]; + maximumBidRoundDurationSeconds: number; + passedAuctionPlayerQueue: AuctionPlayerSnapshot[]; + topTierAuctionPriorityThreshold: AuctionTopTierThreshold; +} + +export function convertLegacyAuctionTeamsToRedisTeams( + teams: AuctionTeam[], +): RedisAuctionTeam[] { + return teams.map((team) => ({ + teamIndex: team.teamIndex, + captainUserId: team.captainUserId, + remainingBidPointAmount: team.points, + members: team.members.map((member) => ({ + userId: member.userId, + assignedPosition: member.assignedPosition, + memberAcquisitionBidPointAmount: member.cost, + })), + })); +} + +export function buildAuctionRedisStructureState( + input: AuctionRedisStructureStateInput, +): Record { + return { + auctionPlayerOrder: input.auctionPlayerOrder, + auctionTeams: input.auctionTeams, + bidRoundExtensionSeconds: input.bidRoundExtensionSeconds, + currentAuctionPlayerOrderIndex: input.currentAuctionPlayerOrderIndex, + currentAuctionRound: input.currentAuctionRound, + initialTeamBidPointAmount: input.initialTeamBidPointAmount, + manualTopTierAuctionPriorityUserIds: + input.manualTopTierAuctionPriorityUserIds, + maximumBidRoundDurationSeconds: input.maximumBidRoundDurationSeconds, + passedAuctionPlayerQueue: input.passedAuctionPlayerQueue, + topTierAuctionPriorityThreshold: input.topTierAuctionPriorityThreshold, + }; +} + +export function buildAuctionRedisLiveStatePatchFromStructure( + input: AuctionRedisStructureStateInput, +): Record { + const patch: Record = { + bidRoundExtensionSeconds: input.bidRoundExtensionSeconds, + currentAuctionPlayerOrderIndex: input.currentAuctionPlayerOrderIndex, + maximumBidRoundDurationSeconds: input.maximumBidRoundDurationSeconds, + }; + + const currentPlayer = + input.auctionPlayerOrder[input.currentAuctionPlayerOrderIndex]; + if (currentPlayer) { + patch.currentBidRoundPlayerUserId = currentPlayer.userId.toString(); + } + + for (const team of input.auctionTeams) { + patch[`team:${team.teamIndex}:captainUserId`] = + team.captainUserId.toString(); + patch[`team:${team.teamIndex}:remainingBidPointAmount`] = + team.remainingBidPointAmount; + patch[`team:${team.teamIndex}:assignedAuctionTeamMemberCount`] = + countAuctionTeamMembersIncludingCaptain(team); + } + + return patch; +} + +export function stringifyAuctionRedisStructureState( + input: AuctionRedisStructureStateInput, +): string { + return JSON.stringify(buildAuctionRedisStructureState(input)); +} + +function countAuctionTeamMembersIncludingCaptain(team: RedisAuctionTeam): number { + const userIds = new Set([team.captainUserId.toString()]); + for (const member of team.members) { + userIds.add(member.userId.toString()); + } + return userIds.size; +} diff --git a/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.spec.ts b/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.spec.ts new file mode 100644 index 00000000..ed81edfe --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.spec.ts @@ -0,0 +1,200 @@ +import { AuctionRedisService } from './auction-redis.service'; +import { AuctionRedisStateReaderService } from './auction-redis-state-reader.service'; + +function makeService(commandReplies: unknown[], currentServerTimestampMS = 1000) { + const sendCommand = jest + .fn() + .mockImplementation(() => Promise.resolve(commandReplies.shift())); + const auctionRedisService = { + getCurrentRedisTimestampMS: jest + .fn() + .mockResolvedValue(currentServerTimestampMS), + raw: jest.fn().mockReturnValue({ sendCommand }), + } as unknown as jest.Mocked; + + return { + auctionRedisService, + sendCommand, + service: new AuctionRedisStateReaderService(auctionRedisService), + }; +} + +describe('AuctionRedisStateReaderService', () => { + it('reads live state identity', async () => { + const { service, sendCommand } = makeService([['life-1', '7']]); + + await expect(service.readLiveStateIdentity('match-1')).resolves.toEqual({ + auctionLifecycleId: 'life-1', + revision: 7, + }); + expect(sendCommand).toHaveBeenCalledWith([ + 'HMGET', + 'auction:match-1:liveAuctionState', + 'auctionLifecycleId', + 'revision', + ]); + }); + + it('returns null when live state identity is missing', async () => { + const { service } = makeService([[null, null]]); + + await expect(service.readLiveStateIdentity('match-1')).resolves.toBeNull(); + }); + + it('reads bid context from the live state hot path fields', async () => { + const { service, sendCommand } = makeService([ + ['bidding', 'life-1', 'player-1', 'captain-2'], + ]); + + await expect(service.readBidContext('match-1', 2)).resolves.toEqual({ + auctionLifecycleId: 'life-1', + bidderTeamCaptainUserId: 'captain-2', + currentBidRoundPlayerUserId: 'player-1', + phase: 'bidding', + }); + expect(sendCommand).toHaveBeenCalledTimes(1); + expect(sendCommand).toHaveBeenCalledWith([ + 'HMGET', + 'auction:match-1:liveAuctionState', + 'phase', + 'auctionLifecycleId', + 'currentBidRoundPlayerUserId', + 'team:2:captainUserId', + ]); + }); + + it('falls back to structure state when bid context has no live captain field', async () => { + const { service, sendCommand } = makeService([ + ['bidding', 'life-1', 'player-1', null], + '{"auctionTeams":[{"teamIndex":2,"captainUserId":"captain-2"}]}', + ]); + + await expect(service.readBidContext('match-1', 2)).resolves.toEqual({ + auctionLifecycleId: 'life-1', + bidderTeamCaptainUserId: 'captain-2', + currentBidRoundPlayerUserId: 'player-1', + phase: 'bidding', + }); + expect(sendCommand).toHaveBeenNthCalledWith(2, [ + 'GET', + 'auction:match-1:auctionStructureState', + ]); + }); + + it('assembles a public auction view from Redis state', async () => { + const { service, sendCommand } = makeService([ + [ + 'auctionLifecycleId', + 'life-1', + 'phase', + 'expiring', + 'revision', + '8', + 'currentHighestBidPointAmount', + '100', + 'currentHighestBidderTeamIndex', + '2', + 'team:2:remainingBidPointAmount', + '900', + 'bidRoundExpiryDecision', + 'sold', + ], + '{"auctionTeams":[{"teamIndex":1}]}', + ['{"bidPointAmount":100,"bidderTeamIndex":2}'], + ]); + + const view = await service.readAuctionStateView('match-1', { + shouldForceAuctionStateResync: true, + }); + + expect(view).toMatchObject({ + auctionBidHistory: [{ bidPointAmount: 100, bidderTeamIndex: 2 }], + auctionLifecycleId: 'life-1', + auctionTeams: [{ teamIndex: 1 }], + canPlaceBidInCurrentBidRound: false, + currentHighestBidderTeamIndex: 2, + currentHighestBidPointAmount: 100, + currentServerTimestampMS: 1000, + isAuctionStateTransitionInProgress: true, + phase: 'bidding', + revision: 8, + shouldForceAuctionStateResync: true, + }); + expect(view).not.toHaveProperty('team:2:remainingBidPointAmount'); + expect(view).not.toHaveProperty('bidRoundExpiryDecision'); + expect(sendCommand).toHaveBeenNthCalledWith(1, [ + 'HGETALL', + 'auction:match-1:liveAuctionState', + ]); + expect(sendCommand).toHaveBeenNthCalledWith(2, [ + 'GET', + 'auction:match-1:auctionStructureState', + ]); + expect(sendCommand).toHaveBeenNthCalledWith(3, [ + 'LRANGE', + 'auction:match-1:auctionBidHistory', + '0', + '-1', + ]); + }); + + it('assembles state when HGETALL returns an object', async () => { + const { service } = makeService([ + { + auctionLifecycleId: 'life-1', + phase: 'presenting', + revision: '3', + }, + '{"auctionTeams":[]}', + [], + ]); + + await expect(service.readAuctionStateView('match-1')).resolves.toMatchObject({ + auctionLifecycleId: 'life-1', + auctionTeams: [], + phase: 'presenting', + revision: 3, + }); + }); + + it('can expose internal live fields for server-side expiry completion', async () => { + const { service } = makeService([ + { + auctionLifecycleId: 'life-1', + bidRoundExpiryDecision: 'sold', + phase: 'expiring', + revision: '4', + 'team:1:remainingBidPointAmount': '900', + }, + '{"auctionTeams":[]}', + [], + ]); + + await expect( + service.readAuctionStateView('match-1', { + includeInternalLiveStateFields: true, + }), + ).resolves.toMatchObject({ + bidRoundExpiryDecision: 'sold', + redisInternalPhase: 'expiring', + 'team:1:remainingBidPointAmount': '900', + }); + }); + + + it('returns null when live or structure state is absent', async () => { + await expect( + makeService([[], '{"auctionTeams":[]}', []]).service.readAuctionStateView( + 'match-1', + ), + ).resolves.toBeNull(); + + await expect( + makeService([ + { auctionLifecycleId: 'life-1', phase: 'presenting', revision: '1' }, + null, + [], + ]).service.readAuctionStateView('match-1'), + ).resolves.toBeNull(); + }); +}); diff --git a/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.ts b/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.ts new file mode 100644 index 00000000..fc0b5384 --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.ts @@ -0,0 +1,229 @@ +import { Injectable } from '@nestjs/common'; +import { buildAuctionRedisKeys } from './auction-redis.keys'; +import { AuctionRedisService } from './auction-redis.service'; +import { assembleAuctionViewFromRedisState } from './auction-redis.state'; + +const NUMERIC_LIVE_STATE_FIELDS = new Set([ + 'bidRoundExpiryPlayerOrderIndex', + 'bidRoundExpiryRevision', + 'bidRoundExpiryWinningBidPointAmount', + 'bidRoundExpiryWinningBidderTeamIndex', + 'currentAuctionHistorySequence', + 'currentAuctionPlayerOrderIndex', + 'currentBidRoundDeadlineTimestampMS', + 'currentHighestBidPointAmount', + 'currentHighestBidderTeamIndex', + 'matchSideEffectRevision', + 'revision', +]); + +export interface AuctionRedisLiveStateIdentity { + auctionLifecycleId?: string; + revision?: number; +} + +export interface AuctionRedisBidContext { + auctionLifecycleId: string; + bidderTeamCaptainUserId?: string; + currentBidRoundPlayerUserId?: string; + phase: string; +} + +export interface AuctionRedisStateViewReadOptions { + includeInternalLiveStateFields?: boolean; + shouldForceAuctionStateResync?: boolean; +} + +@Injectable() +export class AuctionRedisStateReaderService { + constructor(private readonly auctionRedisService: AuctionRedisService) {} + + public async readLiveStateIdentity( + matchId: string, + ): Promise { + const keys = buildAuctionRedisKeys(matchId); + const reply = await this.auctionRedisService.raw().sendCommand([ + 'HMGET', + keys.liveStateKey, + 'auctionLifecycleId', + 'revision', + ]); + if (!Array.isArray(reply)) return null; + const auctionLifecycleId = + typeof reply[0] === 'string' && reply[0] ? reply[0] : undefined; + const revision = + typeof reply[1] === 'string' || typeof reply[1] === 'number' + ? Number(reply[1]) + : Number.NaN; + if (!auctionLifecycleId && !Number.isFinite(revision)) return null; + return { + auctionLifecycleId, + revision: Number.isFinite(revision) ? revision : undefined, + }; + } + + public async readBidContext( + matchId: string, + bidderTeamIndex: number, + ): Promise { + const keys = buildAuctionRedisKeys(matchId); + const bidderTeamCaptainUserIdField = `team:${bidderTeamIndex}:captainUserId`; + const liveReply = await this.auctionRedisService.raw().sendCommand([ + 'HMGET', + keys.liveStateKey, + 'phase', + 'auctionLifecycleId', + 'currentBidRoundPlayerUserId', + bidderTeamCaptainUserIdField, + ]); + if (!Array.isArray(liveReply)) return null; + + const phase = stringValue(liveReply[0]); + const auctionLifecycleId = stringValue(liveReply[1]); + const currentBidRoundPlayerUserId = stringValue(liveReply[2]); + const liveCaptainUserId = stringValue(liveReply[3]); + if (!phase || !auctionLifecycleId) return null; + + return { + auctionLifecycleId, + bidderTeamCaptainUserId: + liveCaptainUserId ?? + (await this.readBidderTeamCaptainUserIdFromStructure( + keys.structureStateKey, + bidderTeamIndex, + )), + currentBidRoundPlayerUserId, + phase, + }; + } + + public async readAuctionStateView( + matchId: string, + options: AuctionRedisStateViewReadOptions = {}, + ): Promise | null> { + const keys = buildAuctionRedisKeys(matchId); + const [currentServerTimestampMS, liveReply, structureStateJson, bidEntries] = + await Promise.all([ + this.auctionRedisService.getCurrentRedisTimestampMS(), + this.auctionRedisService.raw().sendCommand(['HGETALL', keys.liveStateKey]), + this.auctionRedisService.raw().sendCommand(['GET', keys.structureStateKey]), + this.auctionRedisService.raw().sendCommand([ + 'LRANGE', + keys.bidHistoryKey, + '0', + '-1', + ]), + ]); + + const liveState = parseHashReply(liveReply, { + includeInternalLiveStateFields: + options.includeInternalLiveStateFields ?? false, + }); + if (!liveState) return null; + if ( + typeof liveState.auctionLifecycleId !== 'string' || + typeof liveState.phase !== 'string' || + typeof liveState.revision !== 'number' + ) { + return null; + } + if (typeof structureStateJson !== 'string' || !structureStateJson) { + return null; + } + + const view = assembleAuctionViewFromRedisState({ + auctionBidHistoryEntries: Array.isArray(bidEntries) + ? bidEntries.map(String) + : [], + currentServerTimestampMS, + liveState: liveState as Record & { + auctionLifecycleId: string; + phase: string; + revision: number; + }, + shouldForceAuctionStateResync: options.shouldForceAuctionStateResync, + structureState: JSON.parse(structureStateJson) as Record, + }); + view.matchId = matchId; + if (options.includeInternalLiveStateFields) { + view.redisInternalPhase = liveState.phase; + } + return view; + } + + private async readBidderTeamCaptainUserIdFromStructure( + structureStateKey: string, + bidderTeamIndex: number, + ): Promise { + const structureStateJson = await this.auctionRedisService + .raw() + .sendCommand(['GET', structureStateKey]); + if (typeof structureStateJson !== 'string' || !structureStateJson) { + return undefined; + } + const structureState = JSON.parse(structureStateJson) as Record< + string, + unknown + >; + const auctionTeams = Array.isArray(structureState.auctionTeams) + ? structureState.auctionTeams + : []; + const bidderTeam = auctionTeams.find((entry) => { + if (!entry || typeof entry !== 'object') return false; + return ( + Number((entry as Record).teamIndex) === bidderTeamIndex + ); + }); + if (!bidderTeam || typeof bidderTeam !== 'object') return undefined; + return stringValue((bidderTeam as Record).captainUserId); + } +} + +function stringValue(value: unknown): string | undefined { + return typeof value === 'string' && value ? value : undefined; +} + +function parseHashReply( + reply: unknown, + options: { includeInternalLiveStateFields?: boolean } = {}, +): Record | null { + if (!reply) return null; + if (Array.isArray(reply)) { + if (reply.length === 0) return null; + const entries: [string, unknown][] = []; + for (let index = 0; index < reply.length; index += 2) { + entries.push([String(reply[index]), reply[index + 1]]); + } + return parseHashEntries(entries, options); + } + if (typeof reply === 'object') { + const entries = Object.entries(reply as Record); + if (entries.length === 0) return null; + return parseHashEntries(entries, options); + } + return null; +} + +function parseHashEntries( + entries: [string, unknown][], + options: { includeInternalLiveStateFields?: boolean } = {}, +): Record { + const result: Record = {}; + for (const [field, rawValue] of entries) { + if (!options.includeInternalLiveStateFields && isInternalLiveStateField(field)) { + continue; + } + const value = String(rawValue); + if (NUMERIC_LIVE_STATE_FIELDS.has(field)) { + const parsed = Number(value); + result[field] = Number.isFinite(parsed) ? parsed : 0; + continue; + } + result[field] = value; + } + return result; +} + +function isInternalLiveStateField(field: string): boolean { + return field.startsWith('team:') || field.startsWith('bidRoundExpiry'); +} diff --git a/apps/api/src/modules/auction/redis/auction-redis.apply-transition.spec.ts b/apps/api/src/modules/auction/redis/auction-redis.apply-transition.spec.ts new file mode 100644 index 00000000..90dd2586 --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis.apply-transition.spec.ts @@ -0,0 +1,113 @@ +import { buildAuctionRedisKeys } from './auction-redis.keys'; +import { + AUCTION_APPLY_TRANSITION_SCRIPT, + buildAuctionApplyTransitionScriptInvocation, +} from './auction-redis.apply-transition'; + +describe('auction apply transition redis script contract', () => { + it('builds APPLY_TRANSITION keys and values in a stable order', () => { + const keys = buildAuctionRedisKeys('match-1'); + const invocation = buildAuctionApplyTransitionScriptInvocation(keys, { + actionRequest: { + observedProcessingLeaseVersion: 3, + processingOwnerToken: 'owner-1', + scopeKey: 'life-1:request-1', + }, + afterAuctionStructureStateJson: '{"auctionTeams":[]}', + auctionHistorySequence: 4, + auctionLifecycleId: 'life-1', + auctionStateTransitionId: 'transition-1', + broadcastStateRevision: 9, + deadline: { durationSeconds: 30, mode: 'set-relative' }, + durabilityPayloadJson: '{"revision":9}', + expectedCurrentAuctionPlayerOrderIndex: 2, + expectedCurrentBidRoundPlayerUserId: 'player-1', + expectedAuctionHistorySequence: 3, + expectedPhase: 'bidding', + expectedRevision: 8, + liveStatePatch: { + currentAuctionHistorySequence: 4, + phase: 'sold', + }, + matchId: 'match-1', + shouldBroadcastState: true, + }); + + expect(invocation.script).toBe(AUCTION_APPLY_TRANSITION_SCRIPT); + expect(invocation.keys).toEqual([ + 'auction:match-1:liveAuctionState', + 'auction:match-1:auctionStructureState', + 'auction:match-1:appliedAuctionStateTransitionIds', + 'auction:match-1:durability:transition-1', + 'auction:auctionDurabilityRetryQueue', + 'auction:match-1:auctionActionRequestResults', + 'auction:match-1:auctionActionRequestResultOrder', + 'auction:match-1:auctionBidHistory', + 'auction:match-1:bidRequestResults', + 'auction:match-1:bidRequestResultOrder', + 'auction:bidRoundDeadlineQueue', + ]); + expect(invocation.values.slice(0, 19)).toEqual([ + 'match-1', + 'life-1', + 'transition-1', + '8', + '3', + 'bidding', + 'player-1', + '2', + '{"auctionTeams":[]}', + '4', + '{"revision":9}', + '1', + '9', + 'set-relative', + '30', + '0', + 'life-1:request-1', + 'owner-1', + '3', + ]); + expect(invocation.values.slice(19)).toEqual([ + '2', + 'currentAuctionHistorySequence', + '4', + 'phase', + 'sold', + ]); + }); + + it('keeps critical atomicity guards in Lua', () => { + expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain("redis.call('TIME')"); + expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain( + 'ACTION_REQUEST_LEASE_VERSION_MISMATCH', + ); + expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain( + 'ACTION_REQUEST_TRANSITION_MISMATCH', + ); + expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain( + 'INVALID_PATCH_ARITY', + ); + expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain( + 'shouldBroadcastState', + ); + expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain( + "redis.call('SADD'", + ); + expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain( + "redis.call('HINCRBY'", + ); + expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain( + 'currentAuctionHistorySequence', + ); + expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain( + 'storeValidatedActionRequestRejection', + ); + expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain( + "actionRequestPrefix .. 'status'", + ); + expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain( + "actionRequestPrefix .. 'requiresRefetch'", + ); + }); +}); diff --git a/apps/api/src/modules/auction/redis/auction-redis.apply-transition.ts b/apps/api/src/modules/auction/redis/auction-redis.apply-transition.ts new file mode 100644 index 00000000..9650592e --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis.apply-transition.ts @@ -0,0 +1,325 @@ +import type { AuctionRedisKeys } from './auction-redis.keys'; +import { defineAuctionRedisScript } from './auction-redis.scripts'; + +export type ApplyTransitionDeadlineInput = + | { mode: 'none' } + | { mode: 'remove' } + | { durationSeconds: number; mode: 'set-relative' }; + +export interface ApplyTransitionActionRequestInput { + observedProcessingLeaseVersion: number; + processingOwnerToken: string; + scopeKey: string; +} + +export interface AuctionApplyTransitionScriptInput { + actionRequest?: ApplyTransitionActionRequestInput; + afterAuctionStructureStateJson: string; + auctionHistorySequence: number; + auctionLifecycleId: string; + auctionStateTransitionId: string; + broadcastStateRevision: number; + deadline: ApplyTransitionDeadlineInput; + durabilityPayloadJson: string; + expectedCurrentAuctionPlayerOrderIndex?: number; + expectedCurrentBidRoundPlayerUserId?: string; + expectedAuctionHistorySequence?: number; + expectedPhase: string; + expectedRevision: number; + liveStatePatch: Record; + matchId: string; + shouldBroadcastState: boolean; + shouldResetBidRuntime?: boolean; +} + +export interface AuctionApplyTransitionScriptInvocation { + keys: string[]; + script: typeof AUCTION_APPLY_TRANSITION_SCRIPT; + values: string[]; +} + +function stringifyRedisValue(value: string | number | boolean | null): string { + if (typeof value === 'boolean') return value ? '1' : '0'; + if (value === null) return ''; + return String(value); +} + +function flattenLiveStatePatch( + liveStatePatch: AuctionApplyTransitionScriptInput['liveStatePatch'], +): string[] { + return Object.entries(liveStatePatch) + .filter(([, value]) => value !== undefined) + .sort(([a], [b]) => a.localeCompare(b)) + .flatMap(([key, value]) => [ + key, + stringifyRedisValue(value as string | number | boolean | null), + ]); +} + +export function buildAuctionApplyTransitionScriptInvocation( + keys: AuctionRedisKeys, + input: AuctionApplyTransitionScriptInput, +): AuctionApplyTransitionScriptInvocation { + const liveStatePatchPairs = flattenLiveStatePatch(input.liveStatePatch); + const deadlineDurationSeconds = + input.deadline.mode === 'set-relative' + ? String(input.deadline.durationSeconds) + : '0'; + + return { + keys: [ + keys.liveStateKey, + keys.structureStateKey, + keys.appliedTransitionIdsKey, + keys.durabilityPayloadKey(input.auctionStateTransitionId), + keys.durabilityRetryQueueKey, + keys.actionRequestResultsKey, + keys.actionRequestResultOrderKey, + keys.bidHistoryKey, + keys.bidRequestResultsKey, + keys.bidRequestResultOrderKey, + keys.deadlineQueueKey, + ], + script: AUCTION_APPLY_TRANSITION_SCRIPT, + values: [ + input.matchId, + input.auctionLifecycleId, + input.auctionStateTransitionId, + String(input.expectedRevision), + String( + input.expectedAuctionHistorySequence ?? + input.auctionHistorySequence - 1, + ), + input.expectedPhase, + input.expectedCurrentBidRoundPlayerUserId ?? '', + input.expectedCurrentAuctionPlayerOrderIndex === undefined + ? '' + : String(input.expectedCurrentAuctionPlayerOrderIndex), + input.afterAuctionStructureStateJson, + String(input.auctionHistorySequence), + input.durabilityPayloadJson, + input.shouldBroadcastState ? '1' : '0', + String(input.broadcastStateRevision), + input.deadline.mode, + deadlineDurationSeconds, + input.shouldResetBidRuntime ? '1' : '0', + input.actionRequest?.scopeKey ?? '', + input.actionRequest?.processingOwnerToken ?? '', + input.actionRequest?.observedProcessingLeaseVersion === undefined + ? '' + : String(input.actionRequest.observedProcessingLeaseVersion), + String(liveStatePatchPairs.length / 2), + ...liveStatePatchPairs, + ], + }; +} + +export const AUCTION_APPLY_TRANSITION_SCRIPT = defineAuctionRedisScript( + 'auction.applyTransition', + ` +local liveAuctionStateKey = KEYS[1] +local auctionStructureStateKey = KEYS[2] +local appliedAuctionStateTransitionIdsKey = KEYS[3] +local durabilityPayloadKey = KEYS[4] +local durabilityRetryQueueKey = KEYS[5] +local auctionActionRequestResultsKey = KEYS[6] +local auctionActionRequestResultOrderKey = KEYS[7] +local auctionBidHistoryKey = KEYS[8] +local bidRequestResultsKey = KEYS[9] +local bidRequestResultOrderKey = KEYS[10] +local bidRoundDeadlineQueueKey = KEYS[11] + +local matchId = ARGV[1] +local auctionLifecycleId = ARGV[2] +local auctionStateTransitionId = ARGV[3] +local expectedRevision = tonumber(ARGV[4]) +local expectedAuctionHistorySequence = tonumber(ARGV[5]) +local expectedPhase = ARGV[6] +local expectedCurrentBidRoundPlayerUserId = ARGV[7] +local expectedCurrentAuctionPlayerOrderIndex = ARGV[8] +local afterAuctionStructureStateJson = ARGV[9] +local auctionHistorySequence = tonumber(ARGV[10]) +local durabilityPayloadJson = ARGV[11] +local shouldBroadcastState = ARGV[12] +local broadcastStateRevision = tonumber(ARGV[13]) +local deadlineMode = ARGV[14] +local deadlineDurationSeconds = tonumber(ARGV[15]) +local shouldResetBidRuntime = ARGV[16] +local actionRequestScopeKey = ARGV[17] +local processingOwnerToken = ARGV[18] +local observedProcessingLeaseVersion = ARGV[19] +local liveStatePatchPairCount = tonumber(ARGV[20]) + +local redisTime = redis.call('TIME') +local currentRedisTimestampMS = (tonumber(redisTime[1]) * 1000) + math.floor(tonumber(redisTime[2]) / 1000) +local validatedActionRequestScopeKey = '' + +local function storeValidatedActionRequestRejection(code) + if validatedActionRequestScopeKey == '' then + return + end + local actionRequestPrefix = validatedActionRequestScopeKey .. ':' + redis.call( + 'HSET', + auctionActionRequestResultsKey, + actionRequestPrefix .. 'status', + 'rejected', + actionRequestPrefix .. 'rejectCode', + code, + actionRequestPrefix .. 'requiresRefetch', + '1', + actionRequestPrefix .. 'responseServerTimestampMS', + tostring(currentRedisTimestampMS) + ) +end + +local function reject(code) + storeValidatedActionRequestRejection(code) + return {'REJECTED', code, auctionStateTransitionId, tostring(currentRedisTimestampMS)} +end + +if not liveStatePatchPairCount then + return reject('INVALID_PATCH_ARITY') +end +if #ARGV ~= 20 + (liveStatePatchPairCount * 2) then + return reject('INVALID_PATCH_ARITY') +end +if not durabilityPayloadJson or durabilityPayloadJson == '' then + return reject('MISSING_DURABILITY_PAYLOAD') +end +if shouldBroadcastState ~= '0' and shouldBroadcastState ~= '1' then + return reject('INVALID_SHOULD_BROADCAST_STATE') +end +if shouldBroadcastState == '1' and not broadcastStateRevision then + return reject('INVALID_BROADCAST_STATE_REVISION') +end +if deadlineMode ~= 'none' and deadlineMode ~= 'remove' and deadlineMode ~= 'set-relative' then + return reject('INVALID_DEADLINE_MODE') +end +if deadlineMode == 'set-relative' and (not deadlineDurationSeconds or deadlineDurationSeconds <= 0) then + return reject('INVALID_DEADLINE_DURATION') +end + +if actionRequestScopeKey ~= '' then + local actionRequestPrefix = actionRequestScopeKey .. ':' + local storedTransitionId = redis.call('HGET', auctionActionRequestResultsKey, actionRequestPrefix .. 'auctionStateTransitionId') + if not storedTransitionId then + return reject('ACTION_REQUEST_NOT_RESERVED') + end + if storedTransitionId ~= auctionStateTransitionId then + return reject('ACTION_REQUEST_TRANSITION_MISMATCH') + end + local storedOwnerToken = redis.call('HGET', auctionActionRequestResultsKey, actionRequestPrefix .. 'processingOwnerToken') + local leaseExpiresAtTimestampMS = tonumber(redis.call('HGET', auctionActionRequestResultsKey, actionRequestPrefix .. 'processingLeaseExpiresAtTimestampMS') or '0') + if leaseExpiresAtTimestampMS <= currentRedisTimestampMS then + return reject('ACTION_REQUEST_LEASE_EXPIRED') + end + if storedOwnerToken ~= processingOwnerToken then + return reject('ACTION_REQUEST_IN_PROGRESS') + end + local storedLeaseVersion = redis.call('HGET', auctionActionRequestResultsKey, actionRequestPrefix .. 'processingLeaseVersion') or '' + if storedLeaseVersion ~= observedProcessingLeaseVersion then + return reject('ACTION_REQUEST_LEASE_VERSION_MISMATCH') + end + validatedActionRequestScopeKey = actionRequestScopeKey +end + +local currentRevision = tonumber(redis.call('HGET', liveAuctionStateKey, 'revision') or '-1') +if currentRevision ~= expectedRevision then + return reject('CONFLICT') +end +local currentAuctionHistorySequence = tonumber(redis.call('HGET', liveAuctionStateKey, 'currentAuctionHistorySequence') or '-1') +if currentAuctionHistorySequence ~= expectedAuctionHistorySequence then + return reject('CONFLICT') +end +if redis.call('HGET', liveAuctionStateKey, 'auctionLifecycleId') ~= auctionLifecycleId then + return reject('CONFLICT') +end +if redis.call('HGET', liveAuctionStateKey, 'phase') ~= expectedPhase then + return reject('CONFLICT') +end +if expectedCurrentBidRoundPlayerUserId ~= '' and redis.call('HGET', liveAuctionStateKey, 'currentBidRoundPlayerUserId') ~= expectedCurrentBidRoundPlayerUserId then + return reject('CONFLICT') +end +if expectedCurrentAuctionPlayerOrderIndex ~= '' and redis.call('HGET', liveAuctionStateKey, 'currentAuctionPlayerOrderIndex') ~= expectedCurrentAuctionPlayerOrderIndex then + return reject('CONFLICT') +end + +local transitionDedupeMember = auctionLifecycleId .. ':' .. auctionStateTransitionId +if redis.call('SISMEMBER', appliedAuctionStateTransitionIdsKey, transitionDedupeMember) == 1 then + return {'REPLAY', 'APPLIED', auctionStateTransitionId, tostring(currentRedisTimestampMS)} +end + +local newRevision = redis.call('HINCRBY', liveAuctionStateKey, 'revision', 1) +redis.call('SET', auctionStructureStateKey, afterAuctionStructureStateJson) + +local hsetArgs = { + liveAuctionStateKey, + 'auctionLifecycleId', + auctionLifecycleId, + 'currentAuctionHistorySequence', + tostring(auctionHistorySequence), + 'lastAppliedAuctionStateTransitionId', + auctionStateTransitionId +} +local patchIndex = 21 +for i = 1, liveStatePatchPairCount do + table.insert(hsetArgs, ARGV[patchIndex]) + table.insert(hsetArgs, ARGV[patchIndex + 1]) + patchIndex = patchIndex + 2 +end +redis.call('HSET', unpack(hsetArgs)) + +if deadlineMode == 'set-relative' then + local currentBidRoundDeadlineTimestampMS = currentRedisTimestampMS + (deadlineDurationSeconds * 1000) + redis.call('HSET', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS', tostring(currentBidRoundDeadlineTimestampMS)) + redis.call('ZADD', bidRoundDeadlineQueueKey, currentBidRoundDeadlineTimestampMS, matchId) +elseif deadlineMode == 'remove' then + redis.call('ZREM', bidRoundDeadlineQueueKey, matchId) +end + +if shouldResetBidRuntime == '1' then + redis.call('DEL', auctionBidHistoryKey, bidRequestResultsKey, bidRequestResultOrderKey) +end + +redis.call('SADD', appliedAuctionStateTransitionIdsKey, transitionDedupeMember) +redis.call( + 'HSET', + durabilityPayloadKey, + 'payloadJson', + durabilityPayloadJson, + 'preparedAtRedisTimestampMS', + tostring(currentRedisTimestampMS), + 'committedAtRedisTimestampMS', + tostring(currentRedisTimestampMS), + 'auctionLifecycleId', + auctionLifecycleId, + 'revision', + tostring(newRevision), + 'shouldBroadcastState', + shouldBroadcastState, + 'broadcastStateRevision', + tostring(broadcastStateRevision) +) +redis.call('ZADD', durabilityRetryQueueKey, currentRedisTimestampMS, durabilityPayloadKey) + +if actionRequestScopeKey ~= '' then + local actionRequestPrefix = actionRequestScopeKey .. ':' + redis.call( + 'HSET', + auctionActionRequestResultsKey, + actionRequestPrefix .. 'status', + 'applied', + actionRequestPrefix .. 'revision', + tostring(newRevision), + actionRequestPrefix .. 'requiresRefetch', + '1', + actionRequestPrefix .. 'responseServerTimestampMS', + tostring(currentRedisTimestampMS) + ) + redis.call('RPUSH', auctionActionRequestResultOrderKey, actionRequestScopeKey) +end + +return {'OK', auctionStateTransitionId, tostring(newRevision), tostring(currentRedisTimestampMS)} +`, +); diff --git a/apps/api/src/modules/auction/redis/auction-redis.bid.spec.ts b/apps/api/src/modules/auction/redis/auction-redis.bid.spec.ts new file mode 100644 index 00000000..fe0a5c7a --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis.bid.spec.ts @@ -0,0 +1,72 @@ +import { buildAuctionRedisKeys } from './auction-redis.keys'; +import { + AUCTION_BID_SCRIPT, + buildAuctionBidScriptInvocation, + buildBidRequestPayloadFingerprint, +} from './auction-redis.bid'; + +describe('auction bid redis script contract', () => { + it('builds the BID script KEYS and ARGV in the documented order', () => { + const keys = buildAuctionRedisKeys('match-1'); + const invocation = buildAuctionBidScriptInvocation(keys, { + bidderTeamIndex: 2, + bidPointAmount: 120, + bidRequestId: 'bid-1', + bidderUserId: 'captain-2', + clientObservedAuctionLifecycleId: 'life-1', + clientObservedCurrentBidRoundPlayerUserId: 'player-1', + maximumAuctionTeamMemberCount: 5, + maximumStoredAuctionBidHistoryCount: 200, + maximumStoredBidRequestResultCount: 100, + matchId: 'match-1', + minimumBidPointReservePerRemainingAuctionTeamMemberSlot: 10, + minimumBidRequestResultReplayWindowMS: 60_000, + }); + + expect(invocation.script).toBe(AUCTION_BID_SCRIPT); + expect(invocation.keys).toEqual([ + 'auction:match-1:liveAuctionState', + 'auction:match-1:auctionBidHistory', + 'auction:match-1:bidRequestResults', + 'auction:match-1:bidRequestResultOrder', + 'auction:bidRoundDeadlineQueue', + ]); + expect(invocation.values).toEqual([ + 'match-1', + '2', + '120', + '5', + '10', + 'bid-1', + 'captain-2', + 'life-1', + 'player-1', + 'match-1|life-1|player-1|2|120', + '100', + '60000', + '200', + ]); + }); + + it('keeps bid fingerprints stable and timestamp-free', () => { + expect( + buildBidRequestPayloadFingerprint({ + bidderTeamIndex: 2, + bidPointAmount: 120, + clientObservedAuctionLifecycleId: 'life-1', + clientObservedCurrentBidRoundPlayerUserId: 'player-1', + matchId: 'match-1', + }), + ).toBe('match-1|life-1|player-1|2|120'); + }); + + it('uses Redis TIME and scalar hash fields rather than JSON parsing', () => { + expect(AUCTION_BID_SCRIPT.lua).toContain("redis.call('TIME')"); + expect(AUCTION_BID_SCRIPT.lua).toContain("redis.call('HINCRBY'"); + expect(AUCTION_BID_SCRIPT.lua).toContain('BID_REQUEST_RESULT_LIMIT'); + expect(AUCTION_BID_SCRIPT.lua).toContain( + 'currentHighestBidPointAmount', + ); + expect(AUCTION_BID_SCRIPT.lua).not.toContain('cjson.decode'); + }); +}); diff --git a/apps/api/src/modules/auction/redis/auction-redis.bid.ts b/apps/api/src/modules/auction/redis/auction-redis.bid.ts new file mode 100644 index 00000000..882fce34 --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis.bid.ts @@ -0,0 +1,313 @@ +import type { AuctionRedisKeys } from './auction-redis.keys'; +import { defineAuctionRedisScript } from './auction-redis.scripts'; + +export interface AuctionBidScriptInput { + bidderTeamIndex: number; + bidPointAmount: number; + bidRequestId: string; + bidderUserId: string; + clientObservedAuctionLifecycleId: string; + clientObservedCurrentBidRoundPlayerUserId: string; + maximumAuctionTeamMemberCount: number; + maximumStoredAuctionBidHistoryCount: number; + maximumStoredBidRequestResultCount: number; + matchId: string; + minimumBidPointReservePerRemainingAuctionTeamMemberSlot: number; + minimumBidRequestResultReplayWindowMS: number; +} + +export interface AuctionBidScriptInvocation { + keys: string[]; + script: typeof AUCTION_BID_SCRIPT; + values: string[]; +} + +const BID_RESULT_HASH_SUFFIXES = [ + 'fingerprint', + 'status', + 'revision', + 'rejectCode', + 'currentHighestBidPointAmount', + 'currentHighestBidderTeamIndex', + 'currentBidRoundDeadlineTimestampMS', + 'auctionBidHistoryEntryJson', + 'responseServerTimestampMS', + 'createdAtTimestampMS', +] as const; + +export function buildBidRequestPayloadFingerprint(params: { + bidderTeamIndex: number; + bidPointAmount: number; + clientObservedAuctionLifecycleId: string; + clientObservedCurrentBidRoundPlayerUserId: string; + matchId: string; +}): string { + return [ + params.matchId, + params.clientObservedAuctionLifecycleId, + params.clientObservedCurrentBidRoundPlayerUserId, + params.bidderTeamIndex, + params.bidPointAmount, + ].join('|'); +} + +export function buildAuctionBidScriptInvocation( + keys: AuctionRedisKeys, + input: AuctionBidScriptInput, +): AuctionBidScriptInvocation { + return { + keys: [ + keys.liveStateKey, + keys.bidHistoryKey, + keys.bidRequestResultsKey, + keys.bidRequestResultOrderKey, + keys.deadlineQueueKey, + ], + script: AUCTION_BID_SCRIPT, + values: [ + input.matchId, + String(input.bidderTeamIndex), + String(input.bidPointAmount), + String(input.maximumAuctionTeamMemberCount), + String(input.minimumBidPointReservePerRemainingAuctionTeamMemberSlot), + input.bidRequestId, + input.bidderUserId, + input.clientObservedAuctionLifecycleId, + input.clientObservedCurrentBidRoundPlayerUserId, + buildBidRequestPayloadFingerprint(input), + String(input.maximumStoredBidRequestResultCount), + String(input.minimumBidRequestResultReplayWindowMS), + String(input.maximumStoredAuctionBidHistoryCount), + ], + }; +} + +export const AUCTION_BID_SCRIPT = defineAuctionRedisScript( + 'auction.bid', + ` +local liveAuctionStateKey = KEYS[1] +local auctionBidHistoryKey = KEYS[2] +local bidRequestResultsKey = KEYS[3] +local bidRequestResultOrderKey = KEYS[4] +local bidRoundDeadlineQueueKey = KEYS[5] + +local matchId = ARGV[1] +local bidderTeamIndex = ARGV[2] +local bidPointAmount = tonumber(ARGV[3]) +local maximumAuctionTeamMemberCount = tonumber(ARGV[4]) +local minimumBidPointReservePerRemainingAuctionTeamMemberSlot = tonumber(ARGV[5]) +local bidRequestId = ARGV[6] +local bidderUserId = ARGV[7] +local clientObservedAuctionLifecycleId = ARGV[8] +local clientObservedCurrentBidRoundPlayerUserId = ARGV[9] +local bidRequestPayloadFingerprint = ARGV[10] +local maximumStoredBidRequestResultCount = tonumber(ARGV[11]) +local minimumBidRequestResultReplayWindowMS = tonumber(ARGV[12]) +local maximumStoredAuctionBidHistoryCount = tonumber(ARGV[13]) + +local redisTime = redis.call('TIME') +local currentRedisTimestampMS = (tonumber(redisTime[1]) * 1000) + math.floor(tonumber(redisTime[2]) / 1000) + +local function requestField(suffix) + return bidRequestId .. ':' .. suffix +end + +local function hdelBidRequest(requestId) + redis.call( + 'HDEL', + bidRequestResultsKey, + requestId .. ':fingerprint', + requestId .. ':status', + requestId .. ':revision', + requestId .. ':rejectCode', + requestId .. ':currentHighestBidPointAmount', + requestId .. ':currentHighestBidderTeamIndex', + requestId .. ':currentBidRoundDeadlineTimestampMS', + requestId .. ':auctionBidHistoryEntryJson', + requestId .. ':responseServerTimestampMS', + requestId .. ':createdAtTimestampMS' + ) +end + +local function trimOldBidRequestResults() + while redis.call('LLEN', bidRequestResultOrderKey) >= maximumStoredBidRequestResultCount do + local oldestBidRequestId = redis.call('LINDEX', bidRequestResultOrderKey, 0) + if not oldestBidRequestId then + return + end + local createdAtTimestampMS = tonumber(redis.call('HGET', bidRequestResultsKey, oldestBidRequestId .. ':createdAtTimestampMS') or '0') + if createdAtTimestampMS > currentRedisTimestampMS - minimumBidRequestResultReplayWindowMS then + return + end + redis.call('LPOP', bidRequestResultOrderKey) + hdelBidRequest(oldestBidRequestId) + end +end + +local function replayExistingRequest() + local status = redis.call('HGET', bidRequestResultsKey, requestField('status')) or '' + return { + 'REPLAY', + status, + bidRequestId, + redis.call('HGET', bidRequestResultsKey, requestField('revision')) or '', + redis.call('HGET', bidRequestResultsKey, requestField('rejectCode')) or '', + redis.call('HGET', bidRequestResultsKey, requestField('currentHighestBidPointAmount')) or '', + redis.call('HGET', bidRequestResultsKey, requestField('currentHighestBidderTeamIndex')) or '', + redis.call('HGET', bidRequestResultsKey, requestField('currentBidRoundDeadlineTimestampMS')) or '', + redis.call('HGET', bidRequestResultsKey, requestField('auctionBidHistoryEntryJson')) or '', + redis.call('HGET', bidRequestResultsKey, requestField('responseServerTimestampMS')) or tostring(currentRedisTimestampMS) + } +end + +local existingFingerprint = redis.call('HGET', bidRequestResultsKey, requestField('fingerprint')) +if existingFingerprint then + if existingFingerprint ~= bidRequestPayloadFingerprint then + return {'REJECTED', 'DUPLICATE_REQUEST_CONFLICT', bidRequestId, tostring(currentRedisTimestampMS)} + end + return replayExistingRequest() +end + +trimOldBidRequestResults() +if redis.call('LLEN', bidRequestResultOrderKey) >= maximumStoredBidRequestResultCount then + return {'REJECTED', 'BID_REQUEST_RESULT_LIMIT', bidRequestId, tostring(currentRedisTimestampMS)} +end + +local function storeRejectedRequest(rejectCode) + local rejectedCurrentBidRoundDeadlineTimestampMS = redis.call('HGET', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS') or '' + redis.call( + 'HSET', + bidRequestResultsKey, + requestField('fingerprint'), + bidRequestPayloadFingerprint, + requestField('status'), + 'rejected', + requestField('rejectCode'), + rejectCode, + requestField('currentBidRoundDeadlineTimestampMS'), + rejectedCurrentBidRoundDeadlineTimestampMS, + requestField('responseServerTimestampMS'), + tostring(currentRedisTimestampMS), + requestField('createdAtTimestampMS'), + tostring(currentRedisTimestampMS) + ) + redis.call('RPUSH', bidRequestResultOrderKey, bidRequestId) + return {'REJECTED', rejectCode, bidRequestId, tostring(currentRedisTimestampMS), rejectedCurrentBidRoundDeadlineTimestampMS} +end + +local phase = redis.call('HGET', liveAuctionStateKey, 'phase') +if phase ~= 'bidding' then + return storeRejectedRequest('PHASE') +end + +local auctionLifecycleId = redis.call('HGET', liveAuctionStateKey, 'auctionLifecycleId') +local currentBidRoundPlayerUserId = redis.call('HGET', liveAuctionStateKey, 'currentBidRoundPlayerUserId') +if auctionLifecycleId ~= clientObservedAuctionLifecycleId or currentBidRoundPlayerUserId ~= clientObservedCurrentBidRoundPlayerUserId then + return storeRejectedRequest('STALE_BID_ROUND') +end + +local currentBidRoundDeadlineTimestampMS = tonumber(redis.call('HGET', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS') or '0') +if currentBidRoundDeadlineTimestampMS <= currentRedisTimestampMS then + return storeRejectedRequest('EXPIRED') +end + +local currentHighestBidPointAmount = tonumber(redis.call('HGET', liveAuctionStateKey, 'currentHighestBidPointAmount') or '0') +if bidPointAmount <= currentHighestBidPointAmount then + return storeRejectedRequest('TOO_LOW') +end + +local remainingBidPointAmountField = 'team:' .. bidderTeamIndex .. ':remainingBidPointAmount' +local assignedAuctionTeamMemberCountField = 'team:' .. bidderTeamIndex .. ':assignedAuctionTeamMemberCount' +local remainingBidPointAmountRaw = redis.call('HGET', liveAuctionStateKey, remainingBidPointAmountField) +if not remainingBidPointAmountRaw then + return storeRejectedRequest('UNKNOWN_TEAM') +end + +local assignedAuctionTeamMemberCount = tonumber(redis.call('HGET', liveAuctionStateKey, assignedAuctionTeamMemberCountField) or '0') +if assignedAuctionTeamMemberCount >= maximumAuctionTeamMemberCount then + return storeRejectedRequest('FULL') +end + +local remainingBidPointAmount = tonumber(remainingBidPointAmountRaw) +local remainingSlotsAfterBid = maximumAuctionTeamMemberCount - assignedAuctionTeamMemberCount - 1 +local requiredReserveAfterBid = remainingSlotsAfterBid * minimumBidPointReservePerRemainingAuctionTeamMemberSlot +if bidPointAmount + requiredReserveAfterBid > remainingBidPointAmount then + return storeRejectedRequest('INSUFFICIENT') +end + +if redis.call('LLEN', auctionBidHistoryKey) >= maximumStoredAuctionBidHistoryCount then + return storeRejectedRequest('BID_HISTORY_LIMIT') +end + +local maximumBidRoundDurationSeconds = tonumber(redis.call('HGET', liveAuctionStateKey, 'maximumBidRoundDurationSeconds') or '0') +local bidRoundExtensionSeconds = tonumber(redis.call('HGET', liveAuctionStateKey, 'bidRoundExtensionSeconds') or '0') +local remainingBidRoundTimeMS = currentBidRoundDeadlineTimestampMS - currentRedisTimestampMS +local nextRemainingBidRoundTimeMS = remainingBidRoundTimeMS +local bidRoundExtensionMS = bidRoundExtensionSeconds * 1000 +local maximumBidRoundDurationMS = maximumBidRoundDurationSeconds * 1000 +if nextRemainingBidRoundTimeMS < bidRoundExtensionMS then + nextRemainingBidRoundTimeMS = bidRoundExtensionMS +end +if nextRemainingBidRoundTimeMS > maximumBidRoundDurationMS then + nextRemainingBidRoundTimeMS = maximumBidRoundDurationMS +end +local nextBidRoundDeadlineTimestampMS = currentRedisTimestampMS + nextRemainingBidRoundTimeMS + +local revision = redis.call('HINCRBY', liveAuctionStateKey, 'revision', 1) +local auctionBidHistoryEntryJson = + '{"bidderTeamIndex":' .. bidderTeamIndex .. + ',"bidPointAmount":' .. tostring(bidPointAmount) .. + ',"bidderUserId":"' .. bidderUserId .. + '","bidPlacedAtTimestampMS":' .. tostring(currentRedisTimestampMS) .. + '}' + +redis.call('RPUSH', auctionBidHistoryKey, auctionBidHistoryEntryJson) +redis.call( + 'HSET', + liveAuctionStateKey, + 'currentHighestBidPointAmount', + tostring(bidPointAmount), + 'currentHighestBidderTeamIndex', + bidderTeamIndex, + 'currentBidRoundDeadlineTimestampMS', + tostring(nextBidRoundDeadlineTimestampMS) +) +redis.call('ZADD', bidRoundDeadlineQueueKey, nextBidRoundDeadlineTimestampMS, matchId) +redis.call( + 'HSET', + bidRequestResultsKey, + requestField('fingerprint'), + bidRequestPayloadFingerprint, + requestField('status'), + 'ok', + requestField('revision'), + tostring(revision), + requestField('currentHighestBidPointAmount'), + tostring(bidPointAmount), + requestField('currentHighestBidderTeamIndex'), + bidderTeamIndex, + requestField('currentBidRoundDeadlineTimestampMS'), + tostring(nextBidRoundDeadlineTimestampMS), + requestField('auctionBidHistoryEntryJson'), + auctionBidHistoryEntryJson, + requestField('responseServerTimestampMS'), + tostring(currentRedisTimestampMS), + requestField('createdAtTimestampMS'), + tostring(currentRedisTimestampMS) +) +redis.call('RPUSH', bidRequestResultOrderKey, bidRequestId) + +return { + 'OK', + bidRequestId, + tostring(revision), + tostring(currentRedisTimestampMS), + tostring(bidPointAmount), + bidderTeamIndex, + tostring(nextBidRoundDeadlineTimestampMS), + auctionBidHistoryEntryJson +} +`, +); + +export const BID_RESULT_HASH_FIELD_SUFFIXES = BID_RESULT_HASH_SUFFIXES; diff --git a/apps/api/src/modules/auction/redis/auction-redis.constants.ts b/apps/api/src/modules/auction/redis/auction-redis.constants.ts new file mode 100644 index 00000000..4a565349 --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis.constants.ts @@ -0,0 +1 @@ +export const AUCTION_REDIS_CLIENT = Symbol('AUCTION_REDIS_CLIENT'); diff --git a/apps/api/src/modules/auction/redis/auction-redis.expire-prepare.spec.ts b/apps/api/src/modules/auction/redis/auction-redis.expire-prepare.spec.ts new file mode 100644 index 00000000..6936d578 --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis.expire-prepare.spec.ts @@ -0,0 +1,38 @@ +import { buildAuctionRedisKeys } from './auction-redis.keys'; +import { + AUCTION_EXPIRE_PREPARE_SCRIPT, + buildAuctionExpirePrepareScriptInvocation, +} from './auction-redis.expire-prepare'; + +describe('auction expire prepare redis script contract', () => { + it('builds EXPIRE_PREPARE keys and values', () => { + const invocation = buildAuctionExpirePrepareScriptInvocation( + buildAuctionRedisKeys('match-1'), + { + auctionStateTransitionId: 'expire-1', + bidRoundExpiryRetryDelayMS: 3_000, + matchId: 'match-1', + }, + ); + + expect(invocation.script).toBe(AUCTION_EXPIRE_PREPARE_SCRIPT); + expect(invocation.keys).toEqual([ + 'auction:match-1:liveAuctionState', + 'auction:bidRoundDeadlineQueue', + ]); + expect(invocation.values).toEqual(['match-1', 'expire-1', '3000']); + }); + + it('freezes expiry context with Redis TIME and expiring phase', () => { + expect(AUCTION_EXPIRE_PREPARE_SCRIPT.lua).toContain("redis.call('TIME')"); + expect(AUCTION_EXPIRE_PREPARE_SCRIPT.lua).toContain("'phase'"); + expect(AUCTION_EXPIRE_PREPARE_SCRIPT.lua).toContain("'expiring'"); + expect(AUCTION_EXPIRE_PREPARE_SCRIPT.lua).toContain( + 'bidRoundExpiryRevision', + ); + expect(AUCTION_EXPIRE_PREPARE_SCRIPT.lua).toContain( + 'bidRoundExpiryWinningBidderTeamIndex', + ); + expect(AUCTION_EXPIRE_PREPARE_SCRIPT.lua).toContain("'ZADD'"); + }); +}); diff --git a/apps/api/src/modules/auction/redis/auction-redis.expire-prepare.ts b/apps/api/src/modules/auction/redis/auction-redis.expire-prepare.ts new file mode 100644 index 00000000..29cd6999 --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis.expire-prepare.ts @@ -0,0 +1,107 @@ +import type { AuctionRedisKeys } from './auction-redis.keys'; +import { defineAuctionRedisScript } from './auction-redis.scripts'; + +export interface AuctionExpirePrepareScriptInput { + auctionStateTransitionId: string; + bidRoundExpiryRetryDelayMS: number; + matchId: string; +} + +export interface AuctionExpirePrepareScriptInvocation { + keys: string[]; + script: typeof AUCTION_EXPIRE_PREPARE_SCRIPT; + values: string[]; +} + +export function buildAuctionExpirePrepareScriptInvocation( + keys: AuctionRedisKeys, + input: AuctionExpirePrepareScriptInput, +): AuctionExpirePrepareScriptInvocation { + return { + keys: [keys.liveStateKey, keys.deadlineQueueKey], + script: AUCTION_EXPIRE_PREPARE_SCRIPT, + values: [ + input.matchId, + input.auctionStateTransitionId, + String(input.bidRoundExpiryRetryDelayMS), + ], + }; +} + +export const AUCTION_EXPIRE_PREPARE_SCRIPT = defineAuctionRedisScript( + 'auction.expirePrepare', + ` +local liveAuctionStateKey = KEYS[1] +local bidRoundDeadlineQueueKey = KEYS[2] + +local matchId = ARGV[1] +local auctionStateTransitionId = ARGV[2] +local bidRoundExpiryRetryDelayMS = tonumber(ARGV[3]) + +local redisTime = redis.call('TIME') +local currentRedisTimestampMS = (tonumber(redisTime[1]) * 1000) + math.floor(tonumber(redisTime[2]) / 1000) + +local phase = redis.call('HGET', liveAuctionStateKey, 'phase') +if phase == 'expiring' then + return { + 'REPLAY', + redis.call('HGET', liveAuctionStateKey, 'bidRoundExpiryDecision') or '', + redis.call('HGET', liveAuctionStateKey, 'bidRoundExpiryAuctionStateTransitionId') or '', + redis.call('HGET', liveAuctionStateKey, 'bidRoundExpiryRevision') or '', + tostring(currentRedisTimestampMS) + } +end +if phase ~= 'bidding' then + redis.call('ZREM', bidRoundDeadlineQueueKey, matchId) + return {'NOOP', 'PHASE', tostring(currentRedisTimestampMS)} +end + +local currentBidRoundDeadlineTimestampMS = tonumber(redis.call('HGET', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS') or '0') +if currentBidRoundDeadlineTimestampMS > currentRedisTimestampMS then + return {'NOOP', 'NOT_DUE', tostring(currentRedisTimestampMS)} +end + +local currentHighestBidPointAmount = tonumber(redis.call('HGET', liveAuctionStateKey, 'currentHighestBidPointAmount') or '0') +local currentHighestBidderTeamIndex = redis.call('HGET', liveAuctionStateKey, 'currentHighestBidderTeamIndex') or '-1' +local bidRoundExpiryDecision = 'passed' +if currentHighestBidPointAmount > 0 then + bidRoundExpiryDecision = 'sold' +end + +local revision = redis.call('HINCRBY', liveAuctionStateKey, 'revision', 1) +redis.call( + 'HSET', + liveAuctionStateKey, + 'phase', + 'expiring', + 'bidRoundExpiryDecision', + bidRoundExpiryDecision, + 'bidRoundExpiryAuctionStateTransitionId', + auctionStateTransitionId, + 'bidRoundExpiryPlayerUserId', + redis.call('HGET', liveAuctionStateKey, 'currentBidRoundPlayerUserId') or '', + 'bidRoundExpiryPlayerOrderIndex', + redis.call('HGET', liveAuctionStateKey, 'currentAuctionPlayerOrderIndex') or '', + 'bidRoundExpiryWinningBidPointAmount', + tostring(currentHighestBidPointAmount), + 'bidRoundExpiryWinningBidderTeamIndex', + currentHighestBidderTeamIndex, + 'bidRoundExpiryRevision', + tostring(revision) +) +redis.call( + 'ZADD', + bidRoundDeadlineQueueKey, + currentRedisTimestampMS + bidRoundExpiryRetryDelayMS, + matchId +) + +return { + 'OK', + bidRoundExpiryDecision, + auctionStateTransitionId, + tostring(revision), + tostring(currentRedisTimestampMS) +} +`, +); diff --git a/apps/api/src/modules/auction/redis/auction-redis.keys.spec.ts b/apps/api/src/modules/auction/redis/auction-redis.keys.spec.ts new file mode 100644 index 00000000..b03377b1 --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis.keys.spec.ts @@ -0,0 +1,29 @@ +import { buildAuctionRedisKeys } from './auction-redis.keys'; + +describe('auction redis keys', () => { + it('builds lifecycle-safe key names from match id', () => { + expect(buildAuctionRedisKeys('match-1')).toMatchObject({ + actionRequestResultOrderKey: 'auction:match-1:auctionActionRequestResultOrder', + actionRequestResultsKey: 'auction:match-1:auctionActionRequestResults', + appliedTransitionIdsKey: 'auction:match-1:appliedAuctionStateTransitionIds', + bidHistoryKey: 'auction:match-1:auctionBidHistory', + bidRequestResultOrderKey: 'auction:match-1:bidRequestResultOrder', + bidRequestResultsKey: 'auction:match-1:bidRequestResults', + deadlineQueueKey: 'auction:bidRoundDeadlineQueue', + durabilityDeadLetterQueueKey: 'auction:auctionDurabilityDeadLetterQueue', + durabilityPayloadKeyPrefix: 'auction:match-1:durability:', + durabilityRetryQueueKey: 'auction:auctionDurabilityRetryQueue', + liveStateKey: 'auction:match-1:liveAuctionState', + rehydrateLockKey: 'auction:match-1:rehydrateLock', + stateTransitionLockKey: 'auction:match-1:auctionStateTransitionLock', + structureStateKey: 'auction:match-1:auctionStructureState', + }); + }); + + it('builds transition durability payload keys', () => { + const keys = buildAuctionRedisKeys('match-1'); + expect(keys.durabilityPayloadKey('transition-1')).toBe( + 'auction:match-1:durability:transition-1', + ); + }); +}); diff --git a/apps/api/src/modules/auction/redis/auction-redis.keys.ts b/apps/api/src/modules/auction/redis/auction-redis.keys.ts new file mode 100644 index 00000000..0ef9a636 --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis.keys.ts @@ -0,0 +1,47 @@ +export const AUCTION_BID_ROUND_DEADLINE_QUEUE_KEY = + 'auction:bidRoundDeadlineQueue'; +export const AUCTION_DURABILITY_RETRY_QUEUE_KEY = + 'auction:auctionDurabilityRetryQueue'; +export const AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY = + 'auction:auctionDurabilityDeadLetterQueue'; + +export interface AuctionRedisKeys { + actionRequestResultOrderKey: string; + actionRequestResultsKey: string; + appliedTransitionIdsKey: string; + bidHistoryKey: string; + bidRequestResultOrderKey: string; + bidRequestResultsKey: string; + deadlineQueueKey: string; + durabilityDeadLetterQueueKey: string; + durabilityPayloadKey: (auctionStateTransitionId: string) => string; + durabilityPayloadKeyPrefix: string; + durabilityRetryQueueKey: string; + liveStateKey: string; + rehydrateLockKey: string; + stateTransitionLockKey: string; + structureStateKey: string; +} + +export function buildAuctionRedisKeys(matchId: string): AuctionRedisKeys { + const prefix = `auction:${matchId}`; + const durabilityPayloadKeyPrefix = `${prefix}:durability:`; + return { + actionRequestResultOrderKey: `${prefix}:auctionActionRequestResultOrder`, + actionRequestResultsKey: `${prefix}:auctionActionRequestResults`, + appliedTransitionIdsKey: `${prefix}:appliedAuctionStateTransitionIds`, + bidHistoryKey: `${prefix}:auctionBidHistory`, + bidRequestResultOrderKey: `${prefix}:bidRequestResultOrder`, + bidRequestResultsKey: `${prefix}:bidRequestResults`, + deadlineQueueKey: AUCTION_BID_ROUND_DEADLINE_QUEUE_KEY, + durabilityDeadLetterQueueKey: AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY, + durabilityPayloadKey: (auctionStateTransitionId: string) => + `${durabilityPayloadKeyPrefix}${auctionStateTransitionId}`, + durabilityPayloadKeyPrefix, + durabilityRetryQueueKey: AUCTION_DURABILITY_RETRY_QUEUE_KEY, + liveStateKey: `${prefix}:liveAuctionState`, + rehydrateLockKey: `${prefix}:rehydrateLock`, + stateTransitionLockKey: `${prefix}:auctionStateTransitionLock`, + structureStateKey: `${prefix}:auctionStructureState`, + }; +} diff --git a/apps/api/src/modules/auction/redis/auction-redis.module.ts b/apps/api/src/modules/auction/redis/auction-redis.module.ts new file mode 100644 index 00000000..d3b1b3a9 --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis.module.ts @@ -0,0 +1,100 @@ +import { Logger, Module } from '@nestjs/common'; +import { createClient } from 'redis'; +import { SecretModule } from '../../global/secret/secret.module'; +import { SecretService } from '../../global/secret/secret.service'; +import { + assertDistinctRedisInstances, + resolveRedisClientOptions, +} from '../../global/redis/redis.config'; +import { AUCTION_REDIS_CLIENT } from './auction-redis.constants'; +import { + AuctionRedisService, + type AuctionRedisClient, +} from './auction-redis.service'; +import { AuctionRedisCommandService } from './auction-redis-command.service'; +import { AuctionRedisStateReaderService } from './auction-redis-state-reader.service'; + +async function readFirstSecret( + secretService: SecretService, + keys: string[], +): Promise { + for (const key of keys) { + const value = await secretService.get(key, ''); + const trimmed = value.trim(); + if (trimmed) return trimmed; + } + return undefined; +} + +@Module({ + imports: [SecretModule], + providers: [ + { + provide: AUCTION_REDIS_CLIENT, + inject: [SecretService], + useFactory: async ( + secretService: SecretService, + ): Promise => { + await secretService.ready(); + + const [ + redisUrl, + redisEndpoint, + auctionRedisUrl, + auctionRedisEndpoint, + auctionRedisUsername, + auctionRedisPassword, + ] = await Promise.all([ + readFirstSecret(secretService, ['REDIS_URL', 'GARNET_URL']), + readFirstSecret(secretService, ['REDIS_ENDPOINT', 'GARNET_ENDPOINT']), + readFirstSecret(secretService, ['AUCTION_REDIS_URL']), + readFirstSecret(secretService, ['AUCTION_REDIS_ENDPOINT']), + readFirstSecret(secretService, [ + 'AUCTION_REDIS_USERNAME', + 'AUCTION_REDIS_USERID', + ]), + readFirstSecret(secretService, ['AUCTION_REDIS_PASSWORD']), + ]); + + const redisOptions = resolveRedisClientOptions({ + endpoint: redisEndpoint, + endpointEnvName: 'REDIS_ENDPOINT', + url: redisUrl, + urlEnvName: 'REDIS_URL', + }); + const auctionRedisOptions = resolveRedisClientOptions({ + endpoint: auctionRedisEndpoint, + endpointEnvName: 'AUCTION_REDIS_ENDPOINT', + password: auctionRedisPassword, + url: auctionRedisUrl, + urlEnvName: 'AUCTION_REDIS_URL', + username: auctionRedisUsername, + }); + assertDistinctRedisInstances(redisOptions.url, auctionRedisOptions.url); + + const logger = new Logger('AuctionRedisClient'); + const client = createClient(auctionRedisOptions); + client.on('error', (error) => { + logger.error( + `Auction Redis client error: ${error?.message ?? error}`, + ); + }); + + await client.connect(); + logger.log('Auction Redis connected'); + + return client; + }, + }, + AuctionRedisService, + AuctionRedisCommandService, + AuctionRedisStateReaderService, + ], + exports: [ + AuctionRedisService, + AuctionRedisCommandService, + AuctionRedisStateReaderService, + AUCTION_REDIS_CLIENT, + ], +}) +export class AuctionRedisModule {} diff --git a/apps/api/src/modules/auction/redis/auction-redis.reserve-action.spec.ts b/apps/api/src/modules/auction/redis/auction-redis.reserve-action.spec.ts new file mode 100644 index 00000000..ec16743c --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis.reserve-action.spec.ts @@ -0,0 +1,77 @@ +import { buildAuctionRedisKeys } from './auction-redis.keys'; +import { + AUCTION_RESERVE_ACTION_REQUEST_SCRIPT, + buildActionRequestPayloadFingerprint, + buildAuctionReserveActionRequestScriptInvocation, +} from './auction-redis.reserve-action'; + +describe('auction reserve action request redis script contract', () => { + it('builds RESERVE_AUCTION_ACTION_REQUEST keys and values', () => { + const invocation = buildAuctionReserveActionRequestScriptInvocation( + buildAuctionRedisKeys('match-1'), + { + auctionActionRequestId: 'request-1', + auctionActionType: 'sold', + auctionStateTransitionId: 'transition-1', + clientObservedAuctionLifecycleId: 'life-1', + clientObservedPhase: 'bidding', + clientObservedRevision: 8, + leaseDurationMS: 10_000, + maximumStoredAuctionActionRequestResultCount: 100, + minimumAuctionActionRequestResultReplayWindowMS: 60_000, + newAuctionLifecycleId: undefined, + processingOwnerToken: 'owner-1', + }, + ); + + expect(invocation.script).toBe(AUCTION_RESERVE_ACTION_REQUEST_SCRIPT); + expect(invocation.keys).toEqual([ + 'auction:match-1:auctionActionRequestResults', + 'auction:match-1:auctionActionRequestResultOrder', + ]); + expect(invocation.values).toEqual([ + 'life-1', + 'request-1', + 'sold', + 'transition-1', + '', + 'owner-1', + '10000', + '100', + '60000', + 'life-1|request-1|sold|8|bidding||', + ]); + }); + + it('builds stable action request fingerprints', () => { + expect( + buildActionRequestPayloadFingerprint({ + auctionActionRequestId: 'request-1', + auctionActionType: 'next', + clientObservedAuctionLifecycleId: 'life-1', + clientObservedCurrentAuctionPlayerOrderIndex: 3, + clientObservedCurrentBidRoundPlayerUserId: 'player-1', + clientObservedPhase: 'sold', + clientObservedRevision: 9, + }), + ).toBe('life-1|request-1|next|9|sold|player-1|3'); + }); + + it('keeps lease version and replay guards in Lua', () => { + expect(AUCTION_RESERVE_ACTION_REQUEST_SCRIPT.lua).toContain( + "redis.call('TIME')", + ); + expect(AUCTION_RESERVE_ACTION_REQUEST_SCRIPT.lua).toContain( + 'processingLeaseVersion', + ); + expect(AUCTION_RESERVE_ACTION_REQUEST_SCRIPT.lua).toContain( + 'ACTION_REQUEST_IN_PROGRESS', + ); + expect(AUCTION_RESERVE_ACTION_REQUEST_SCRIPT.lua).toContain( + 'ACTION_REQUEST_RESULT_LIMIT', + ); + expect(AUCTION_RESERVE_ACTION_REQUEST_SCRIPT.lua).toContain( + 'DUPLICATE_ACTION_REQUEST_CONFLICT', + ); + }); +}); diff --git a/apps/api/src/modules/auction/redis/auction-redis.reserve-action.ts b/apps/api/src/modules/auction/redis/auction-redis.reserve-action.ts new file mode 100644 index 00000000..fcd16690 --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis.reserve-action.ts @@ -0,0 +1,233 @@ +import type { AuctionRedisKeys } from './auction-redis.keys'; +import { defineAuctionRedisScript } from './auction-redis.scripts'; + +export interface AuctionReserveActionRequestScriptInput { + auctionActionRequestId: string; + auctionActionType: string; + auctionStateTransitionId: string; + clientObservedAuctionLifecycleId: string; + clientObservedCurrentAuctionPlayerOrderIndex?: number; + clientObservedCurrentBidRoundPlayerUserId?: string; + clientObservedPhase: string; + clientObservedRevision: number; + leaseDurationMS: number; + maximumStoredAuctionActionRequestResultCount: number; + minimumAuctionActionRequestResultReplayWindowMS: number; + newAuctionLifecycleId?: string; + processingOwnerToken: string; +} + +export interface AuctionReserveActionRequestScriptInvocation { + keys: string[]; + script: typeof AUCTION_RESERVE_ACTION_REQUEST_SCRIPT; + values: string[]; +} + +export function buildActionRequestPayloadFingerprint(params: { + auctionActionRequestId: string; + auctionActionType: string; + clientObservedAuctionLifecycleId: string; + clientObservedCurrentAuctionPlayerOrderIndex?: number; + clientObservedCurrentBidRoundPlayerUserId?: string; + clientObservedPhase: string; + clientObservedRevision: number; +}): string { + return [ + params.clientObservedAuctionLifecycleId, + params.auctionActionRequestId, + params.auctionActionType, + params.clientObservedRevision, + params.clientObservedPhase, + params.clientObservedCurrentBidRoundPlayerUserId ?? '', + params.clientObservedCurrentAuctionPlayerOrderIndex ?? '', + ].join('|'); +} + +export function buildAuctionReserveActionRequestScriptInvocation( + keys: AuctionRedisKeys, + input: AuctionReserveActionRequestScriptInput, +): AuctionReserveActionRequestScriptInvocation { + return { + keys: [keys.actionRequestResultsKey, keys.actionRequestResultOrderKey], + script: AUCTION_RESERVE_ACTION_REQUEST_SCRIPT, + values: [ + input.clientObservedAuctionLifecycleId, + input.auctionActionRequestId, + input.auctionActionType, + input.auctionStateTransitionId, + input.newAuctionLifecycleId ?? '', + input.processingOwnerToken, + String(input.leaseDurationMS), + String(input.maximumStoredAuctionActionRequestResultCount), + String(input.minimumAuctionActionRequestResultReplayWindowMS), + buildActionRequestPayloadFingerprint(input), + ], + }; +} + +export const AUCTION_RESERVE_ACTION_REQUEST_SCRIPT = defineAuctionRedisScript( + 'auction.reserveActionRequest', + ` +local auctionActionRequestResultsKey = KEYS[1] +local auctionActionRequestResultOrderKey = KEYS[2] + +local clientObservedAuctionLifecycleId = ARGV[1] +local auctionActionRequestId = ARGV[2] +local auctionActionType = ARGV[3] +local auctionStateTransitionId = ARGV[4] +local newAuctionLifecycleId = ARGV[5] +local processingOwnerToken = ARGV[6] +local leaseDurationMS = tonumber(ARGV[7]) +local maximumStoredAuctionActionRequestResultCount = tonumber(ARGV[8]) +local minimumAuctionActionRequestResultReplayWindowMS = tonumber(ARGV[9]) +local actionRequestPayloadFingerprint = ARGV[10] + +local redisTime = redis.call('TIME') +local currentRedisTimestampMS = (tonumber(redisTime[1]) * 1000) + math.floor(tonumber(redisTime[2]) / 1000) +local actionRequestScopeKey = clientObservedAuctionLifecycleId .. ':' .. auctionActionRequestId + +local function requestField(suffix) + return actionRequestScopeKey .. ':' .. suffix +end + +local function hdelActionRequest(scopeKey) + redis.call( + 'HDEL', + auctionActionRequestResultsKey, + scopeKey .. ':fingerprint', + scopeKey .. ':status', + scopeKey .. ':revision', + scopeKey .. ':rejectCode', + scopeKey .. ':auctionActionType', + scopeKey .. ':auctionStateTransitionId', + scopeKey .. ':newAuctionLifecycleId', + scopeKey .. ':processingOwnerToken', + scopeKey .. ':processingLeaseExpiresAtTimestampMS', + scopeKey .. ':processingLeaseVersion', + scopeKey .. ':responseServerTimestampMS', + scopeKey .. ':responseJson', + scopeKey .. ':requiresRefetch', + scopeKey .. ':createdAtTimestampMS' + ) +end + +local function trimOldActionRequestResults() + while redis.call('LLEN', auctionActionRequestResultOrderKey) >= maximumStoredAuctionActionRequestResultCount do + local oldestActionRequestScopeKey = redis.call('LINDEX', auctionActionRequestResultOrderKey, 0) + if not oldestActionRequestScopeKey then + return + end + local createdAtTimestampMS = tonumber(redis.call('HGET', auctionActionRequestResultsKey, oldestActionRequestScopeKey .. ':createdAtTimestampMS') or '0') + if createdAtTimestampMS > currentRedisTimestampMS - minimumAuctionActionRequestResultReplayWindowMS then + return + end + redis.call('LPOP', auctionActionRequestResultOrderKey) + hdelActionRequest(oldestActionRequestScopeKey) + end +end + +local existingFingerprint = redis.call('HGET', auctionActionRequestResultsKey, requestField('fingerprint')) +if existingFingerprint then + if existingFingerprint ~= actionRequestPayloadFingerprint then + return {'REJECTED', 'DUPLICATE_ACTION_REQUEST_CONFLICT', actionRequestScopeKey, tostring(currentRedisTimestampMS)} + end + + local status = redis.call('HGET', auctionActionRequestResultsKey, requestField('status')) or '' + if status == 'applied' or status == 'rejected' then + return { + 'REPLAY', + status, + actionRequestScopeKey, + redis.call('HGET', auctionActionRequestResultsKey, requestField('revision')) or '', + redis.call('HGET', auctionActionRequestResultsKey, requestField('rejectCode')) or '', + redis.call('HGET', auctionActionRequestResultsKey, requestField('auctionStateTransitionId')) or '', + redis.call('HGET', auctionActionRequestResultsKey, requestField('newAuctionLifecycleId')) or '', + redis.call('HGET', auctionActionRequestResultsKey, requestField('processingLeaseVersion')) or '', + redis.call('HGET', auctionActionRequestResultsKey, requestField('responseServerTimestampMS')) or tostring(currentRedisTimestampMS), + redis.call('HGET', auctionActionRequestResultsKey, requestField('responseJson')) or '', + redis.call('HGET', auctionActionRequestResultsKey, requestField('requiresRefetch')) or '' + } + end + + local leaseExpiresAtTimestampMS = tonumber(redis.call('HGET', auctionActionRequestResultsKey, requestField('processingLeaseExpiresAtTimestampMS')) or '0') + local storedOwnerToken = redis.call('HGET', auctionActionRequestResultsKey, requestField('processingOwnerToken')) or '' + local storedLeaseVersion = tonumber(redis.call('HGET', auctionActionRequestResultsKey, requestField('processingLeaseVersion')) or '1') + if leaseExpiresAtTimestampMS > currentRedisTimestampMS and storedOwnerToken ~= processingOwnerToken then + return {'REJECTED', 'ACTION_REQUEST_IN_PROGRESS', actionRequestScopeKey, tostring(currentRedisTimestampMS)} + end + + local nextLeaseVersion = storedLeaseVersion + local wasLeaseExpired = '0' + if leaseExpiresAtTimestampMS <= currentRedisTimestampMS then + nextLeaseVersion = storedLeaseVersion + 1 + wasLeaseExpired = '1' + end + + redis.call( + 'HSET', + auctionActionRequestResultsKey, + requestField('status'), + 'processing', + requestField('processingOwnerToken'), + processingOwnerToken, + requestField('processingLeaseExpiresAtTimestampMS'), + tostring(currentRedisTimestampMS + leaseDurationMS), + requestField('processingLeaseVersion'), + tostring(nextLeaseVersion), + requestField('responseServerTimestampMS'), + tostring(currentRedisTimestampMS) + ) + + return { + 'RESERVED', + actionRequestScopeKey, + redis.call('HGET', auctionActionRequestResultsKey, requestField('auctionStateTransitionId')) or auctionStateTransitionId, + redis.call('HGET', auctionActionRequestResultsKey, requestField('newAuctionLifecycleId')) or '', + tostring(nextLeaseVersion), + wasLeaseExpired, + tostring(currentRedisTimestampMS) + } +end + +trimOldActionRequestResults() +if redis.call('LLEN', auctionActionRequestResultOrderKey) >= maximumStoredAuctionActionRequestResultCount then + return {'REJECTED', 'ACTION_REQUEST_RESULT_LIMIT', actionRequestScopeKey, tostring(currentRedisTimestampMS)} +end + +redis.call( + 'HSET', + auctionActionRequestResultsKey, + requestField('fingerprint'), + actionRequestPayloadFingerprint, + requestField('status'), + 'processing', + requestField('auctionActionType'), + auctionActionType, + requestField('auctionStateTransitionId'), + auctionStateTransitionId, + requestField('newAuctionLifecycleId'), + newAuctionLifecycleId, + requestField('processingOwnerToken'), + processingOwnerToken, + requestField('processingLeaseExpiresAtTimestampMS'), + tostring(currentRedisTimestampMS + leaseDurationMS), + requestField('processingLeaseVersion'), + '1', + requestField('responseServerTimestampMS'), + tostring(currentRedisTimestampMS), + requestField('createdAtTimestampMS'), + tostring(currentRedisTimestampMS) +) +redis.call('RPUSH', auctionActionRequestResultOrderKey, actionRequestScopeKey) + +return { + 'RESERVED', + actionRequestScopeKey, + auctionStateTransitionId, + newAuctionLifecycleId, + '1', + '0', + tostring(currentRedisTimestampMS) +} +`, +); diff --git a/apps/api/src/modules/auction/redis/auction-redis.scripts.spec.ts b/apps/api/src/modules/auction/redis/auction-redis.scripts.spec.ts new file mode 100644 index 00000000..258eb643 --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis.scripts.spec.ts @@ -0,0 +1,14 @@ +import { createHash } from 'crypto'; +import { defineAuctionRedisScript } from './auction-redis.scripts'; + +describe('auction redis scripts', () => { + it('stores normalized Lua and its SHA1', () => { + const script = defineAuctionRedisScript('test', 'return 1\n'); + + expect(script).toEqual({ + lua: 'return 1\n', + name: 'test', + sha: createHash('sha1').update('return 1\n').digest('hex'), + }); + }); +}); diff --git a/apps/api/src/modules/auction/redis/auction-redis.scripts.ts b/apps/api/src/modules/auction/redis/auction-redis.scripts.ts new file mode 100644 index 00000000..ad8656be --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis.scripts.ts @@ -0,0 +1,18 @@ +import { createHash } from 'crypto'; + +export interface AuctionRedisScriptDefinition { + lua: string; + name: string; + sha: string; +} + +export function defineAuctionRedisScript( + name: string, + lua: string, +): AuctionRedisScriptDefinition { + return { + lua, + name, + sha: createHash('sha1').update(lua).digest('hex'), + }; +} diff --git a/apps/api/src/modules/auction/redis/auction-redis.service.spec.ts b/apps/api/src/modules/auction/redis/auction-redis.service.spec.ts new file mode 100644 index 00000000..9098dec1 --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis.service.spec.ts @@ -0,0 +1,64 @@ +import { + AuctionRedisNoscriptError, + AuctionRedisService, +} from './auction-redis.service'; + +function makeService(sendCommand: jest.Mock) { + const client = { + destroy: jest.fn(), + quit: jest.fn().mockResolvedValue(undefined), + sendCommand, + }; + + return new AuctionRedisService(client as never); +} + +describe('AuctionRedisService', () => { + it('uses Redis TIME as the timestamp source', async () => { + const service = makeService(jest.fn().mockResolvedValue(['1781700000', '123000'])); + + await expect(service.getCurrentRedisTimestampMS()).resolves.toBe( + 1_781_700_000_123, + ); + }); + + it('loads and retries a script once when EVALSHA returns NOSCRIPT', async () => { + const sendCommand = jest + .fn() + .mockRejectedValueOnce(new AuctionRedisNoscriptError()) + .mockResolvedValueOnce('sha-from-redis') + .mockResolvedValueOnce(['ok']); + const service = makeService(sendCommand); + + await expect( + service.evalShaWithReload({ + keys: ['auction:state:1'], + script: 'return 1', + scriptSha: 'old-sha', + values: ['v1'], + }), + ).resolves.toEqual(['ok']); + + expect(sendCommand.mock.calls).toEqual([ + [['EVALSHA', 'old-sha', '1', 'auction:state:1', 'v1']], + [['SCRIPT', 'LOAD', 'return 1']], + [['EVALSHA', 'sha-from-redis', '1', 'auction:state:1', 'v1']], + ]); + }); + + it('does not reload scripts for non-NOSCRIPT errors', async () => { + const error = new Error('OOM command not allowed'); + const sendCommand = jest.fn().mockRejectedValue(error); + const service = makeService(sendCommand); + + await expect( + service.evalShaWithReload({ + keys: [], + script: 'return 1', + scriptSha: 'sha', + values: [], + }), + ).rejects.toBe(error); + expect(sendCommand).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/api/src/modules/auction/redis/auction-redis.service.ts b/apps/api/src/modules/auction/redis/auction-redis.service.ts new file mode 100644 index 00000000..571787cd --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis.service.ts @@ -0,0 +1,131 @@ +import { Inject, Injectable, OnModuleDestroy } from '@nestjs/common'; +import type { createClient } from 'redis'; +import { AUCTION_REDIS_CLIENT } from './auction-redis.constants'; +import type { AuctionRedisScriptDefinition } from './auction-redis.scripts'; + +export type AuctionRedisClient = ReturnType; + +export interface EvalShaWithReloadParams { + keys: string[]; + script: string; + scriptSha: string; + values: string[]; +} + +export class AuctionRedisNoscriptError extends Error { + constructor(message = 'NOSCRIPT No matching script. Please use EVAL.') { + super(message); + this.name = 'AuctionRedisNoscriptError'; + } +} + +function isNoscriptError(error: unknown): boolean { + if (error instanceof AuctionRedisNoscriptError) return true; + const message = + error instanceof Error ? error.message : typeof error === 'string' ? error : ''; + return /\bNOSCRIPT\b/iu.test(message); +} + +function buildEvalShaCommand( + scriptSha: string, + keys: string[], + values: string[], +): string[] { + return ['EVALSHA', scriptSha, String(keys.length), ...keys, ...values]; +} + +function parseRedisTimeReply(reply: unknown): number { + if (Array.isArray(reply) && reply.length >= 2) { + const seconds = Number(reply[0]); + const microseconds = Number(reply[1]); + if (Number.isFinite(seconds) && Number.isFinite(microseconds)) { + return seconds * 1000 + Math.floor(microseconds / 1000); + } + } + + throw new Error(`Unexpected Redis TIME reply: ${JSON.stringify(reply)}`); +} + +@Injectable() +export class AuctionRedisService implements OnModuleDestroy { + constructor( + @Inject(AUCTION_REDIS_CLIENT) + private readonly client: AuctionRedisClient, + ) {} + + async onModuleDestroy() { + try { + await this.client.quit(); + } catch { + this.client.destroy(); + } + } + + public raw(): AuctionRedisClient { + return this.client; + } + + public async getCurrentRedisTimestampMS(): Promise { + const reply = await this.client.sendCommand(['TIME']); + return parseRedisTimeReply(reply); + } + + public async evalShaWithReload( + params: EvalShaWithReloadParams, + ): Promise { + try { + return (await this.client.sendCommand( + buildEvalShaCommand(params.scriptSha, params.keys, params.values), + )) as T; + } catch (error) { + if (!isNoscriptError(error)) throw error; + } + + const loadedSha = String( + await this.client.sendCommand(['SCRIPT', 'LOAD', params.script]), + ); + return (await this.client.sendCommand( + buildEvalShaCommand(loadedSha, params.keys, params.values), + )) as T; + } + + public async evalScript( + script: AuctionRedisScriptDefinition, + keys: string[], + values: string[], + ): Promise { + return this.evalShaWithReload({ + keys, + script: script.lua, + scriptSha: script.sha, + values, + }); + } + + public async acquireTokenLock( + key: string, + token: string, + ttlMS: number, + ): Promise { + const result = await this.client.sendCommand([ + 'SET', + key, + token, + 'PX', + String(ttlMS), + 'NX', + ]); + return String(result) === 'OK'; + } + + public async releaseTokenLock(key: string, token: string): Promise { + const result = await this.client.sendCommand([ + 'EVAL', + 'if redis.call("GET", KEYS[1]) == ARGV[1] then return redis.call("DEL", KEYS[1]) else return 0 end', + '1', + key, + token, + ]); + return Number(result) === 1; + } +} diff --git a/apps/api/src/modules/auction/redis/auction-redis.state.spec.ts b/apps/api/src/modules/auction/redis/auction-redis.state.spec.ts new file mode 100644 index 00000000..810b77d0 --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis.state.spec.ts @@ -0,0 +1,111 @@ +import { buildAuctionRedisKeys } from './auction-redis.keys'; +import { + AUCTION_HYDRATE_STATE_SCRIPT, + assembleAuctionViewFromRedisState, + buildHydrateAuctionStateScriptInvocation, + shouldHydrateRedisAuctionState, +} from './auction-redis.state'; + +describe('auction redis state assembly', () => { + it.each([ + { + expected: true, + live: null, + mongo: { auctionLifecycleId: 'life-1', revision: 1 }, + }, + { + expected: true, + live: { auctionLifecycleId: 'life-1', revision: 1 }, + mongo: { auctionLifecycleId: 'life-1', revision: 2 }, + }, + { + expected: true, + live: { auctionLifecycleId: 'old-life', revision: 2 }, + mongo: { auctionLifecycleId: 'new-life', revision: 2 }, + }, + { + expected: false, + live: { auctionLifecycleId: 'redis-life', revision: 3 }, + mongo: { auctionLifecycleId: 'mongo-life', revision: 2 }, + }, + ])('decides rehydrate need: %#', ({ live, mongo, expected }) => { + expect(shouldHydrateRedisAuctionState({ live, mongo })).toBe(expected); + }); + + it('assembles public view and maps internal expiring phase to bidding', () => { + expect( + assembleAuctionViewFromRedisState({ + auctionBidHistoryEntries: ['{"bidPointAmount":100}'], + currentServerTimestampMS: 1_000, + liveState: { + auctionLifecycleId: 'life-1', + currentBidRoundPlayerUserId: 'player-1', + phase: 'expiring', + revision: 3, + }, + shouldForceAuctionStateResync: true, + structureState: { + auctionTeams: [], + }, + }), + ).toMatchObject({ + auctionBidHistory: [{ bidPointAmount: 100 }], + auctionLifecycleId: 'life-1', + canPlaceBidInCurrentBidRound: false, + currentBidRoundPlayerUserId: 'player-1', + currentServerTimestampMS: 1000, + isAuctionStateTransitionInProgress: true, + phase: 'bidding', + revision: 3, + shouldForceAuctionStateResync: true, + }); + }); + + it('builds HYDRATE invocation and keeps CAS conditions in Lua', () => { + const invocation = buildHydrateAuctionStateScriptInvocation( + buildAuctionRedisKeys('match-1'), + { + auctionHistorySequence: 4, + auctionLifecycleId: 'life-1', + liveStatePatch: { + 'team:1:assignedAuctionTeamMemberCount': 1, + 'team:1:remainingBidPointAmount': 1000, + }, + maximumBidRoundDurationSeconds: 30, + matchId: 'match-1', + phase: 'bidding', + revision: 7, + structureStateJson: '{"auctionTeams":[]}', + }, + ); + + expect(invocation.script).toBe(AUCTION_HYDRATE_STATE_SCRIPT); + expect(invocation.keys).toEqual([ + 'auction:match-1:liveAuctionState', + 'auction:match-1:auctionStructureState', + 'auction:bidRoundDeadlineQueue', + ]); + expect(invocation.values).toEqual([ + 'match-1', + 'life-1', + '7', + 'bidding', + '4', + '30', + '{"auctionTeams":[]}', + '2', + 'team:1:assignedAuctionTeamMemberCount', + '1', + 'team:1:remainingBidPointAmount', + '1000', + ]); + expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain("redis.call('TIME')"); + expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain( + 'INVALID_PATCH_ARITY', + ); + expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain( + 'mongoRevision > redisRevision', + ); + expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain("redis.call('ZADD'"); + }); +}); diff --git a/apps/api/src/modules/auction/redis/auction-redis.state.ts b/apps/api/src/modules/auction/redis/auction-redis.state.ts new file mode 100644 index 00000000..477a7396 --- /dev/null +++ b/apps/api/src/modules/auction/redis/auction-redis.state.ts @@ -0,0 +1,188 @@ +import type { AuctionRedisKeys } from './auction-redis.keys'; +import { defineAuctionRedisScript } from './auction-redis.scripts'; + +export interface AuctionRedisRevisionIdentity { + auctionLifecycleId?: string; + revision?: number; +} + +export interface ShouldHydrateRedisAuctionStateParams { + live: AuctionRedisRevisionIdentity | null; + mongo: Required; +} + +export interface AssembleAuctionViewParams { + auctionBidHistoryEntries: string[]; + currentServerTimestampMS: number; + liveState: Record & { + auctionLifecycleId: string; + phase: string; + revision: number; + }; + shouldForceAuctionStateResync?: boolean; + structureState: Record; +} + +export interface HydrateAuctionStateScriptInput { + auctionHistorySequence: number; + auctionLifecycleId: string; + liveStatePatch?: Record; + maximumBidRoundDurationSeconds: number; + matchId: string; + phase: string; + revision: number; + structureStateJson: string; +} + +export interface HydrateAuctionStateScriptInvocation { + keys: string[]; + script: typeof AUCTION_HYDRATE_STATE_SCRIPT; + values: string[]; +} + +function stringifyRedisValue(value: string | number | boolean | null): string { + if (typeof value === 'boolean') return value ? '1' : '0'; + if (value === null) return ''; + return String(value); +} + +function flattenLiveStatePatch( + liveStatePatch: HydrateAuctionStateScriptInput['liveStatePatch'], +): string[] { + return Object.entries(liveStatePatch ?? {}) + .filter(([, value]) => value !== undefined) + .sort(([a], [b]) => a.localeCompare(b)) + .flatMap(([key, value]) => [ + key, + stringifyRedisValue(value as string | number | boolean | null), + ]); +} + +export function shouldHydrateRedisAuctionState( + params: ShouldHydrateRedisAuctionStateParams, +): boolean { + if (!params.live) return true; + const redisRevision = params.live.revision ?? -1; + const mongoRevision = params.mongo.revision; + if (mongoRevision > redisRevision) return true; + return ( + mongoRevision === redisRevision && + params.mongo.auctionLifecycleId !== params.live.auctionLifecycleId + ); +} + +export function assembleAuctionViewFromRedisState( + params: AssembleAuctionViewParams, +): Record { + const isExpiring = params.liveState.phase === 'expiring'; + return { + ...params.structureState, + ...params.liveState, + auctionBidHistory: params.auctionBidHistoryEntries.map((entry) => + JSON.parse(entry), + ), + canPlaceBidInCurrentBidRound: !isExpiring, + currentServerTimestampMS: params.currentServerTimestampMS, + isAuctionStateTransitionInProgress: isExpiring, + phase: isExpiring ? 'bidding' : params.liveState.phase, + shouldForceAuctionStateResync: + params.shouldForceAuctionStateResync || undefined, + }; +} + +export function buildHydrateAuctionStateScriptInvocation( + keys: AuctionRedisKeys, + input: HydrateAuctionStateScriptInput, +): HydrateAuctionStateScriptInvocation { + const liveStatePatchPairs = flattenLiveStatePatch(input.liveStatePatch); + return { + keys: [keys.liveStateKey, keys.structureStateKey, keys.deadlineQueueKey], + script: AUCTION_HYDRATE_STATE_SCRIPT, + values: [ + input.matchId, + input.auctionLifecycleId, + String(input.revision), + input.phase, + String(input.auctionHistorySequence), + String(input.maximumBidRoundDurationSeconds), + input.structureStateJson, + String(liveStatePatchPairs.length / 2), + ...liveStatePatchPairs, + ], + }; +} + +export const AUCTION_HYDRATE_STATE_SCRIPT = defineAuctionRedisScript( + 'auction.hydrateState', + ` +local liveAuctionStateKey = KEYS[1] +local auctionStructureStateKey = KEYS[2] +local bidRoundDeadlineQueueKey = KEYS[3] + +local matchId = ARGV[1] +local mongoAuctionLifecycleId = ARGV[2] +local mongoRevision = tonumber(ARGV[3]) +local phase = ARGV[4] +local auctionHistorySequence = ARGV[5] +local maximumBidRoundDurationSeconds = tonumber(ARGV[6]) +local structureStateJson = ARGV[7] +local liveStatePatchPairCount = tonumber(ARGV[8]) + +local redisTime = redis.call('TIME') +local currentRedisTimestampMS = (tonumber(redisTime[1]) * 1000) + math.floor(tonumber(redisTime[2]) / 1000) +local redisRevision = tonumber(redis.call('HGET', liveAuctionStateKey, 'revision') or '-1') +local redisAuctionLifecycleId = redis.call('HGET', liveAuctionStateKey, 'auctionLifecycleId') + +if not liveStatePatchPairCount or #ARGV ~= 8 + (liveStatePatchPairCount * 2) then + return {'REJECTED', 'INVALID_PATCH_ARITY', tostring(currentRedisTimestampMS)} +end + +local shouldHydrate = false +if redisRevision < 0 then + shouldHydrate = true +elseif mongoRevision > redisRevision then + shouldHydrate = true +elseif mongoRevision == redisRevision and mongoAuctionLifecycleId ~= redisAuctionLifecycleId then + shouldHydrate = true +end + +if not shouldHydrate then + return {'NOOP', tostring(redisRevision), tostring(currentRedisTimestampMS)} +end + +local hydratedRevision = mongoRevision + 1 +redis.call('SET', auctionStructureStateKey, structureStateJson) +local hsetArgs = { + liveAuctionStateKey, + 'auctionLifecycleId', + mongoAuctionLifecycleId, + 'revision', + tostring(hydratedRevision), + 'phase', + phase, + 'currentAuctionHistorySequence', + auctionHistorySequence, + 'currentHighestBidPointAmount', + '0', + 'currentHighestBidderTeamIndex', + '-1' +} +local patchIndex = 9 +for i = 1, liveStatePatchPairCount do + table.insert(hsetArgs, ARGV[patchIndex]) + table.insert(hsetArgs, ARGV[patchIndex + 1]) + patchIndex = patchIndex + 2 +end +redis.call('HSET', unpack(hsetArgs)) + +if phase == 'bidding' then + local currentBidRoundDeadlineTimestampMS = currentRedisTimestampMS + (maximumBidRoundDurationSeconds * 1000) + redis.call('HSET', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS', tostring(currentBidRoundDeadlineTimestampMS)) + redis.call('ZADD', bidRoundDeadlineQueueKey, currentBidRoundDeadlineTimestampMS, matchId) +else + redis.call('ZREM', bidRoundDeadlineQueueKey, matchId) +end + +return {'OK', tostring(hydratedRevision), tostring(currentRedisTimestampMS)} +`, +); diff --git a/apps/api/src/modules/community-stats/community-stats-cache.service.ts b/apps/api/src/modules/community-stats/community-stats-cache.service.ts index 6f3c26f2..2d50765a 100644 --- a/apps/api/src/modules/community-stats/community-stats-cache.service.ts +++ b/apps/api/src/modules/community-stats/community-stats-cache.service.ts @@ -1,5 +1,5 @@ import { Injectable, Logger } from '@nestjs/common'; -import { GarnetService } from '../global/garnet/garnet.service'; +import { RedisService } from '../global/redis/redis.service'; const COMMUNITY_STATS_TTL_SECONDS = 5 * 60; const COMMUNITY_STATS_DETAIL_TTL_SECONDS = 24 * 60 * 60; @@ -8,10 +8,10 @@ const COMMUNITY_STATS_DETAIL_TTL_SECONDS = 24 * 60 * 60; export class CommunityStatsCacheService { private readonly logger = new Logger(CommunityStatsCacheService.name); - constructor(private readonly garnetService: GarnetService) {} + constructor(private readonly redisService: RedisService) {} public get(key: string): Promise { - return this.garnetService.getJson(key); + return this.redisService.getJson(key); } public set( @@ -19,7 +19,7 @@ export class CommunityStatsCacheService { value: unknown, ttlSeconds = COMMUNITY_STATS_TTL_SECONDS, ): Promise { - return this.garnetService.setJson(key, value, ttlSeconds); + return this.redisService.setJson(key, value, ttlSeconds); } public setDetail(key: string, value: unknown): Promise { @@ -29,7 +29,7 @@ export class CommunityStatsCacheService { public async invalidateCommunity(communityId: string): Promise { const prefix = `riot:communitystats:`; const match = `${prefix}*${communityId}*`; - const client = this.garnetService.raw(); + const client = this.redisService.raw(); let cursor = '0'; let deleted = 0; diff --git a/apps/api/src/modules/community-stats/community-stats.module.ts b/apps/api/src/modules/community-stats/community-stats.module.ts index 4be3ae42..9b19a740 100644 --- a/apps/api/src/modules/community-stats/community-stats.module.ts +++ b/apps/api/src/modules/community-stats/community-stats.module.ts @@ -1,4 +1,5 @@ import { Module } from '@nestjs/common'; +import { RiotModule } from '../riot/riot.module'; import { CommunityStatsCacheService } from './community-stats-cache.service'; import { CommunityStatsController } from './community-stats.controller'; import { CommunityStatsService } from './community-stats.service'; @@ -7,6 +8,7 @@ import { MatchStatsRepository } from './match-stats.repository'; import { MatchStatsService } from './match-stats.service'; @Module({ + imports: [RiotModule], controllers: [CommunityStatsController], providers: [ CommunityStatsService, diff --git a/apps/api/src/modules/community-stats/community-stats.service.spec.ts b/apps/api/src/modules/community-stats/community-stats.service.spec.ts new file mode 100644 index 00000000..ba53125b --- /dev/null +++ b/apps/api/src/modules/community-stats/community-stats.service.spec.ts @@ -0,0 +1,702 @@ +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import { CommunityStatsCacheService } from './community-stats-cache.service'; +import { CommunityStatsService } from './community-stats.service'; +import type { + InternalMatchCardView, + InternalMatchDetailResponse, +} from './community-stats.types'; +import { MatchStatsRepository } from './match-stats.repository'; +import { MatchStatsService } from './match-stats.service'; +import { + MATCH_STATS_BUILDER_VERSION, + type InternalGameDetail, + type InternalRecord, +} from './match-stats.types'; + +function objectives() { + return { + tower: 1, + dragon: 0, + inhibitor: 0, + baron: 0, + riftHerald: 0, + voidGrub: 0, + elderDragon: 0, + }; +} + +function record(matchId: mongoose.Types.ObjectId): InternalRecord { + return { + matchId: matchId.toString(), + title: '내전', + scheduledAt: new Date('2026-06-18T12:00:00.000Z'), + gameNumber: 1, + riotMatchId: 'KR_1', + gameCreation: 1_000, + gameDuration: 1_800, + userId: new mongoose.Types.ObjectId().toString(), + summonerName: 'Player', + tagLine: 'KR1', + profileIconId: 1, + teamIndex: 1, + side: 'blue', + championId: 266, + championLevel: 15, + teamPosition: 'TOP', + kills: 5, + deaths: 1, + assists: 7, + win: true, + cs: 200, + csPerMin: 6.7, + gold: 12_000, + gpm: 400, + damageDealtToChampions: 18_000, + damageTaken: 20_000, + damageShare: 30, + killParticipation: 60, + visionScore: 18, + controlWardsBought: 1, + wardsPlaced: 8, + wardsKilled: 2, + firstBloodKill: false, + firstBloodAssist: false, + items: [1054, 3071, 0, 0, 0, 0], + trinket: 3340, + summonerSpells: [4, 12], + perks: { + primaryStyle: 8000, + subStyle: 8400, + keystone: 8010, + selectedPerkIds: [8010, 9111, 9105, 8299, 8444, 8451], + styles: [ + { styleId: 8000, perkIds: [8010, 9111, 9105, 8299] }, + { styleId: 8400, perkIds: [8444, 8451] }, + ], + statPerks: { defense: 5001, flex: 5008, offense: 5005 }, + }, + itemBuild: [{ timestamp: 10, itemId: 1054, type: 'purchased' }], + skillBuild: [{ timestamp: 11, skillSlot: 1, level: 1 }], + rating: 8.5, + }; +} + +describe('CommunityStatsService', () => { + it('ignores detail caches missing unified events or containing invalid checkpoints', async () => { + const communityId = new mongoose.Types.ObjectId(); + const matchId = new mongoose.Types.ObjectId(); + const match: InternalMatchCardView = { + matchId: matchId.toString(), + title: '내전', + scheduledAt: '2026-06-18T12:00:00.000Z', + status: 'finished', + gameCount: 1, + games: [], + teams: [], + seriesResults: [], + }; + const participant = record(matchId); + Object.assign(participant, { + participantId: 1, + checkpoints: { + at10: { + timestamp: 590, + gold: 5_200, + cs: 90, + xp: 4_200, + kills: 1, + deaths: 1, + assists: 1, + }, + }, + }); + const gameDetail: InternalGameDetail = { + gameNumber: 1, + riotMatchId: 'KR_1', + gameCreation: 1_000, + gameDuration: 1_800, + winnerSide: 'blue', + timelineLoaded: true, + timeline: [ + { + timestamp: 0, + blue: { gold: 500, xp: 0 }, + red: { gold: 500, xp: 0 }, + goldDiff: 0, + xpDiff: 0, + }, + ], + objectiveEvents: [], + teams: [ + { + teamIndex: 1, + side: 'blue', + win: true, + objectives: objectives(), + bans: [], + participants: [participant], + }, + ], + }; + Object.assign(gameDetail, { + timelineEvents: [ + { + timestamp: 300, + side: 'blue', + type: 'championKill', + killerParticipantId: 1, + victimParticipantId: 2, + assistingParticipantIds: [], + }, + ], + }); + const otherwiseCompleteCachedGame = { + gameNumber: 1, + riotMatchId: 'KR_1', + gameCreation: 1_000, + gameDuration: 1_800, + timeline: [], + objectiveEvents: [], + teams: [ + { + teamIndex: 1, + side: 'blue' as const, + win: true, + objectives: objectives(), + bans: [], + participants: [ + { + summonerName: 'Cached Player', + tagLine: 'KR1', + itemBuild: [], + skillBuild: [], + }, + ], + }, + ], + }; + const missingTimelineEventsCache = { + match, + games: [otherwiseCompleteCachedGame], + } as unknown as InternalMatchDetailResponse; + const invalidCheckpointCache = { + match, + games: [ + { + ...otherwiseCompleteCachedGame, + timelineEvents: [], + teams: otherwiseCompleteCachedGame.teams.map((team) => ({ + ...team, + participants: team.participants.map((cachedParticipant) => ({ + ...cachedParticipant, + participantId: 1, + checkpoints: { + at10: { + timestamp: '590', + gold: 5_200, + cs: 90, + xp: 4_200, + kills: 1, + deaths: 1, + assists: 1, + }, + }, + })), + })), + }, + ], + } as unknown as InternalMatchDetailResponse; + const setDetail = jest.fn().mockResolvedValue(undefined); + const cacheService = { + get: jest + .fn() + .mockResolvedValueOnce(missingTimelineEventsCache) + .mockResolvedValueOnce(invalidCheckpointCache), + setDetail, + } as unknown as jest.Mocked; + const matchStatsService = { + buildAndUpsert: jest.fn().mockResolvedValue(undefined), + } as unknown as jest.Mocked; + const service = new CommunityStatsService( + {} as ConnectionService, + cacheService, + {} as MatchStatsRepository, + matchStatsService, + ); + (service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset = + jest.fn().mockResolvedValue({ + season: { + id: 'all', + label: '전체', + startTime: null, + endTime: null, + }, + matches: [match], + records: [participant], + detailsByMatchId: new Map([[matchId.toString(), [gameDetail]]]), + }); + + const missingEventsResponse = await service.getMatchDetail({ + communityId, + matchId, + }); + const invalidCheckpointResponse = await service.getMatchDetail({ + communityId, + matchId, + }); + + expect(missingEventsResponse.games[0].timeline).toHaveLength(1); + expect(invalidCheckpointResponse.games[0].timeline).toHaveLength(1); + expect(invalidCheckpointResponse.games[0]).toMatchObject({ + timelineEvents: [ + { + timestamp: 300, + side: 'blue', + type: 'championKill', + }, + ], + }); + expect( + invalidCheckpointResponse.games[0].teams[0].participants[0], + ).toMatchObject({ + participantId: 1, + checkpoints: { + at10: { + timestamp: 590, + gold: 5_200, + cs: 90, + xp: 4_200, + kills: 1, + deaths: 1, + assists: 1, + }, + }, + itemBuild: [{ timestamp: 10, itemId: 1054, type: 'purchased' }], + perks: { + selectedPerkIds: [8010, 9111, 9105, 8299, 8444, 8451], + }, + }); + expect(matchStatsService.buildAndUpsert).not.toHaveBeenCalled(); + expect(setDetail).toHaveBeenCalledTimes(2); + expect(setDetail).toHaveBeenNthCalledWith( + 2, + expect.stringContaining(':r4:'), + invalidCheckpointResponse, + ); + }); + + it('backs off failed timeline hydration and retries after the short cache expires', async () => { + const communityId = new mongoose.Types.ObjectId(); + const matchId = new mongoose.Types.ObjectId(); + const match: InternalMatchCardView = { + matchId: matchId.toString(), + title: '내전', + scheduledAt: '2026-06-18T12:00:00.000Z', + status: 'finished', + gameCount: 1, + games: [], + teams: [], + seriesResults: [], + }; + const participant = record(matchId); + const gameDetail: InternalGameDetail = { + gameNumber: 1, + riotMatchId: 'KR_1', + gameCreation: 1_000, + gameDuration: 1_800, + winnerSide: 'blue', + timelineLoaded: false, + timeline: [], + objectiveEvents: [], + timelineEvents: [], + teams: [ + { + teamIndex: 1, + side: 'blue', + win: true, + objectives: objectives(), + bans: [], + participants: [participant], + }, + ], + }; + const dataset = (timelineLoaded: boolean) => ({ + season: { + id: 'all', + label: '전체', + startTime: null, + endTime: null, + }, + matches: [match], + records: [participant], + detailsByMatchId: new Map([ + [matchId.toString(), [{ ...gameDetail, timelineLoaded }]], + ]), + }); + let cachedResponse: InternalMatchDetailResponse | null = null; + const set = jest + .fn() + .mockImplementation( + (_key: string, value: InternalMatchDetailResponse) => { + cachedResponse = value; + return Promise.resolve(); + }, + ); + const setDetail = jest + .fn() + .mockImplementation( + (_key: string, value: InternalMatchDetailResponse) => { + cachedResponse = value; + return Promise.resolve(); + }, + ); + const cacheService = { + get: jest.fn().mockImplementation(() => Promise.resolve(cachedResponse)), + set, + setDetail, + } as unknown as jest.Mocked; + const buildAndUpsert = jest.fn().mockResolvedValue(undefined); + const service = new CommunityStatsService( + {} as ConnectionService, + cacheService, + {} as MatchStatsRepository, + { buildAndUpsert } as unknown as MatchStatsService, + ); + (service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset = + jest + .fn() + .mockResolvedValueOnce(dataset(false)) + .mockResolvedValueOnce(dataset(false)) + .mockResolvedValueOnce(dataset(false)) + .mockResolvedValueOnce(dataset(true)); + + const fallback = await service.getMatchDetail({ communityId, matchId }); + const backedOff = await service.getMatchDetail({ communityId, matchId }); + + expect(backedOff).toBe(fallback); + expect(buildAndUpsert).toHaveBeenCalledTimes(1); + expect(set).toHaveBeenCalledWith( + expect.stringContaining(':r4:'), + fallback, + 60, + ); + expect(setDetail).not.toHaveBeenCalled(); + + cachedResponse = null; + const recovered = await service.getMatchDetail({ communityId, matchId }); + + expect(buildAndUpsert).toHaveBeenCalledTimes(2); + expect(setDetail).toHaveBeenCalledTimes(1); + expect(setDetail).toHaveBeenCalledWith( + expect.stringContaining(':r4:'), + recovered, + ); + }); + + it('coalesces concurrent internal match detail cache misses', async () => { + const communityId = new mongoose.Types.ObjectId(); + const matchId = new mongoose.Types.ObjectId(); + const match: InternalMatchCardView = { + matchId: matchId.toString(), + title: '내전', + scheduledAt: '2026-06-18T12:00:00.000Z', + status: 'finished', + gameCount: 1, + games: [], + teams: [], + seriesResults: [], + }; + const participant = record(matchId); + const dataset = { + season: { + id: 'all', + label: '전체', + startTime: null, + endTime: null, + }, + matches: [match], + records: [participant], + detailsByMatchId: new Map([ + [ + matchId.toString(), + [ + { + gameNumber: 1, + riotMatchId: 'KR_1', + gameCreation: 1_000, + gameDuration: 1_800, + winnerSide: 'blue' as const, + timelineLoaded: true, + timeline: [], + objectiveEvents: [], + timelineEvents: [], + teams: [ + { + teamIndex: 1, + side: 'blue' as const, + win: true, + objectives: objectives(), + bans: [], + participants: [participant], + }, + ], + }, + ], + ], + ]), + }; + let resolveDataset: ((value: typeof dataset) => void) | undefined; + const datasetPromise = new Promise((resolve) => { + resolveDataset = resolve; + }); + const setDetail = jest.fn().mockResolvedValue(undefined); + const cacheService = { + get: jest.fn().mockResolvedValue(null), + setDetail, + } as unknown as jest.Mocked; + const service = new CommunityStatsService( + {} as ConnectionService, + cacheService, + {} as MatchStatsRepository, + {} as MatchStatsService, + ); + const buildBaseDataset = jest.fn().mockReturnValue(datasetPromise); + (service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset = + buildBaseDataset; + + const first = service.getMatchDetail({ communityId, matchId }); + const second = service.getMatchDetail({ communityId, matchId }); + await Promise.resolve(); + resolveDataset?.(dataset); + const [firstResponse, secondResponse] = await Promise.all([first, second]); + + expect(firstResponse).toBe(secondResponse); + expect(buildBaseDataset).toHaveBeenCalledTimes(1); + expect(setDetail).toHaveBeenCalledTimes(1); + }); + + it('includes internal match route fields in user internal history matches', async () => { + const communityId = new mongoose.Types.ObjectId(); + const matchId = new mongoose.Types.ObjectId(); + const userId = new mongoose.Types.ObjectId(); + const participant = record(matchId); + participant.userId = userId.toString(); + participant.gameNumber = 2; + participant.riotMatchId = 'KR_1234'; + + const cacheService = { + get: jest.fn().mockResolvedValue(null), + set: jest.fn().mockResolvedValue(undefined), + } as unknown as jest.Mocked; + const matchStatsRepository = { + findUserRecordFragments: jest + .fn() + .mockResolvedValue([{ matchId, records: [participant] }]), + findDetailsByMatches: jest + .fn() + .mockResolvedValue([{ matchId, gameDetails: [] }]), + } as unknown as jest.Mocked; + 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; + const matchStatsRepository = { + findUserRecordFragments: jest.fn().mockReturnValue(fragmentsPromise), + findDetailsByMatches: jest.fn().mockResolvedValue([]), + } as unknown as jest.Mocked; + 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; + const matchStatsService = { + buildAndUpsert: jest.fn().mockResolvedValue(undefined), + } as unknown as jest.Mocked; + const service = new CommunityStatsService( + connectionService, + {} as CommunityStatsCacheService, + matchStatsRepository, + matchStatsService, + ); + + const rebuilt = await ( + service as unknown as { + rebuildMissingOrStaleFragments( + communityId: mongoose.Types.ObjectId, + ): Promise; + } + ).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); + }); +}); diff --git a/apps/api/src/modules/community-stats/community-stats.service.ts b/apps/api/src/modules/community-stats/community-stats.service.ts index df89ea56..9c605fa3 100644 --- a/apps/api/src/modules/community-stats/community-stats.service.ts +++ b/apps/api/src/modules/community-stats/community-stats.service.ts @@ -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, @@ -36,6 +40,8 @@ const DEFAULT_LIST_LIMIT = 20; const MAX_LIST_LIMIT = 50; const MAX_MATCH_SCAN = 300; const MIN_HIGHLIGHT_GAMES = 5; +const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 4; +const INCOMPLETE_MATCH_DETAIL_TTL_SECONDS = 60; interface CommunityStatsContext { community: CommunityDocument; @@ -54,6 +60,14 @@ interface BaseDataset { @Injectable() export class CommunityStatsService { private readonly logger = new Logger(CommunityStatsService.name); + private readonly matchDetailInFlight = new Map< + string, + Promise + >(); + private readonly userInternalHistoryInFlight = new Map< + string, + Promise + >(); constructor( private readonly connectionService: ConnectionService, @@ -205,11 +219,32 @@ export class CommunityStatsService { communityId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId; }): Promise { - const key = `riot:communitystats:matchDetail:${params.communityId.toString()}:${params.matchId.toString()}`; + const key = `riot:communitystats:matchDetail:v${MATCH_STATS_BUILDER_VERSION}:r${MATCH_DETAIL_RESPONSE_CACHE_VERSION}:${params.communityId.toString()}:${params.matchId.toString()}`; const cached = await this.cacheService.get(key); - if (cached) return cached; + if (cached && isCompleteMatchDetailResponse(cached)) return cached; + const inFlight = this.matchDetailInFlight.get(key); + if (inFlight) return inFlight; + + const promise = this.buildMatchDetailResponse(params, key); + this.matchDetailInFlight.set(key, promise); + try { + return await promise; + } finally { + if (this.matchDetailInFlight.get(key) === promise) { + this.matchDetailInFlight.delete(key); + } + } + } + + private async buildMatchDetailResponse( + params: { + communityId: mongoose.Types.ObjectId; + matchId: mongoose.Types.ObjectId; + }, + key: string, + ): Promise { const dataset = await this.buildBaseDataset(params.communityId, { seasonId: 'all', }); @@ -217,48 +252,81 @@ export class CommunityStatsService { (item) => item.matchId === params.matchId.toString(), ); if (!match) throw new NotFoundException('Internal match not found.'); + let gameDetails = dataset.detailsByMatchId.get(match.matchId) ?? []; + if (gameDetails.some((game) => game.timelineLoaded !== true)) { + await this.matchStatsService.buildAndUpsert(params.matchId, { + includeTimeline: true, + }); + const refreshedDataset = await this.buildBaseDataset(params.communityId, { + seasonId: 'all', + }); + gameDetails = refreshedDataset.detailsByMatchId.get(match.matchId) ?? []; + } const response: InternalMatchDetailResponse = { match, - games: (dataset.detailsByMatchId.get(match.matchId) ?? []).map( - (game) => ({ - gameNumber: game.gameNumber, - riotMatchId: game.riotMatchId, - gameCreation: game.gameCreation, - gameDuration: game.gameDuration, - teams: game.teams.map((team) => ({ - teamIndex: team.teamIndex, - side: team.side, - win: team.win, - objectives: team.objectives, - participants: team.participants.map((record) => ({ - userId: record.userId, - summonerName: record.summonerName, - teamIndex: record.teamIndex, - side: record.side, - teamPosition: record.teamPosition, - championId: record.championId, - kills: record.kills, - deaths: record.deaths, - assists: record.assists, - cs: record.cs, - csPerMin: record.csPerMin, - gold: record.gold, - gpm: record.gpm, - damageDealtToChampions: record.damageDealtToChampions, - damageShare: record.damageShare, - killParticipation: record.killParticipation, - visionScore: record.visionScore, - items: record.items, - trinket: record.trinket, - summonerSpells: record.summonerSpells, - perks: record.perks, - 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 ?? [], + timelineEvents: game.timelineEvents ?? 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) => ({ + participantId: record.participantId, + checkpoints: record.checkpoints, + 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); + if (gameDetails.every((game) => game.timelineLoaded === true)) { + await this.cacheService.setDetail(key, response); + } else { + await this.cacheService.set( + key, + response, + INCOMPLETE_MATCH_DETAIL_TTL_SECONDS, + ); + } return response; } @@ -268,7 +336,7 @@ export class CommunityStatsService { filters: CommunityStatsFilters; }): Promise { const key = this.cacheKey( - `userInternal:${params.userId.toString()}`, + `userInternal:v3:${params.userId.toString()}`, params.communityId, params.filters, ); @@ -276,38 +344,20 @@ export class CommunityStatsService { await this.cacheService.get(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( @@ -342,7 +392,7 @@ export class CommunityStatsService { const detailsByMatchId = new Map(); 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; @@ -358,7 +408,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), ), ); @@ -372,6 +422,116 @@ export class CommunityStatsService { }; } + private async buildUserInternalHistoryResponse( + params: { + communityId: mongoose.Types.ObjectId; + userId: mongoose.Types.ObjectId; + filters: CommunityStatsFilters; + }, + cacheKey: string, + ): Promise { + 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> { + 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 { + const detailsByMatchId = new Map(); + 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 { @@ -380,11 +540,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, @@ -394,11 +557,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; } @@ -764,6 +961,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, @@ -990,3 +1189,57 @@ export class CommunityStatsService { return Math.round(value * 10) / 10; } } + +function isCompleteMatchDetailResponse( + response: InternalMatchDetailResponse, +): boolean { + return response.games.every( + (game) => + Array.isArray(game.timeline) && + Array.isArray(game.objectiveEvents) && + Array.isArray(game.timelineEvents) && + game.teams.every( + (team) => + Array.isArray(team.bans) && + team.participants.every( + (participant) => + typeof participant.tagLine === 'string' && + Array.isArray(participant.itemBuild) && + Array.isArray(participant.skillBuild) && + isOptionalFiniteNumber(participant.participantId) && + isCompleteParticipantCheckpoints(participant.checkpoints), + ), + ), + ); +} + +function isCompleteParticipantCheckpoints(value: unknown): boolean { + if (value === undefined) return true; + if (!isRecord(value)) return false; + return ['at10', 'at15'].every((key) => { + const checkpoint = value[key]; + if (checkpoint === undefined) return true; + if (!isRecord(checkpoint)) return false; + return [ + 'timestamp', + 'gold', + 'cs', + 'xp', + 'kills', + 'deaths', + 'assists', + ].every((field) => isFiniteNumber(checkpoint[field])); + }); +} + +function isOptionalFiniteNumber(value: unknown): boolean { + return value === undefined || isFiniteNumber(value); +} + +function isFiniteNumber(value: unknown): value is number { + return typeof value === 'number' && Number.isFinite(value); +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} diff --git a/apps/api/src/modules/community-stats/community-stats.types.ts b/apps/api/src/modules/community-stats/community-stats.types.ts index ec381dea..e6824841 100644 --- a/apps/api/src/modules/community-stats/community-stats.types.ts +++ b/apps/api/src/modules/community-stats/community-stats.types.ts @@ -1,4 +1,12 @@ -import type { RiotLane, TeamSide } from '../global/database/schema'; +import type { + MatchStatsParticipantCheckpoints, + MatchStatsItemBuildEvent, + MatchStatsRunePerks, + MatchStatsSkillBuildEvent, + MatchStatsTimelineEvent, + RiotLane, + TeamSide, +} from '../global/database/schema'; import type { RecentMatchView, HistorySeasonDto } from '../match-history/match-history.types'; export interface CommunityStatsFilters { @@ -108,18 +116,46 @@ export interface InternalMatchDetailResponse { riotMatchId: string; gameCreation: number; gameDuration: number; + gameVersion?: string; + timeline: Array<{ + timestamp: number; + blue: { gold: number; xp: number }; + red: { gold: number; xp: number }; + goldDiff: number; + xpDiff: number; + }>; + objectiveEvents: Array<{ + timestamp: number; + side: TeamSide; + type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub'; + monsterSubType?: string; + }>; + timelineEvents: MatchStatsTimelineEvent[]; teams: Array<{ teamIndex: number; side: TeamSide; win: boolean; - objectives: { baron: number; dragon: number; tower: number }; + objectives: { + tower: number; + dragon: number; + inhibitor: number; + baron: number; + riftHerald: number; + voidGrub: number; + elderDragon: number; + }; + bans: Array<{ championId: number; pickTurn: number }>; participants: Array<{ + participantId?: number; + checkpoints?: MatchStatsParticipantCheckpoints; userId: string | null; summonerName: string; + tagLine: string; teamIndex: number; side: TeamSide; teamPosition: string; championId: number; + championLevel: number; kills: number; deaths: number; assists: number; @@ -128,13 +164,21 @@ export interface InternalMatchDetailResponse { gold: number; gpm: number; damageDealtToChampions: number; + damageTaken: number; damageShare: number; killParticipation: number; visionScore: number; + wardsPlaced: number; + wardsKilled: number; + controlWardsBought: number; + firstBloodKill: boolean; + firstBloodAssist: boolean; items: number[]; trinket: number; summonerSpells: [number, number]; - perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + perks: MatchStatsRunePerks; + itemBuild: MatchStatsItemBuildEvent[]; + skillBuild: MatchStatsSkillBuildEvent[]; win: boolean; }>; }>; diff --git a/apps/api/src/modules/community-stats/match-stats-fragment.builder.spec.ts b/apps/api/src/modules/community-stats/match-stats-fragment.builder.spec.ts index 3f5c9b1f..a805b23f 100644 --- a/apps/api/src/modules/community-stats/match-stats-fragment.builder.spec.ts +++ b/apps/api/src/modules/community-stats/match-stats-fragment.builder.spec.ts @@ -1,5 +1,6 @@ import mongoose from 'mongoose'; import type { MatchDocument } from '../global/database/schema'; +import type { RiotMatchDto, RiotMatchTimelineDto } from '../riot/riot.types'; import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder'; function makeMatch(): MatchDocument { @@ -95,4 +96,727 @@ describe('MatchStatsFragmentBuilder', () => { }); expect(fragment.gameDetails[0].teams[0].participants).toHaveLength(1); }); + + it('builds rich set detail from raw Riot match data', () => { + const builder = new MatchStatsFragmentBuilder(); + const match = makeMatch(); + const redUserId = new mongoose.Types.ObjectId(); + match.participants.push({ + userId: redUserId, + puuid: 'puuid-2', + gameName: 'Opponent', + profileIconId: 8, + }); + match.teams[1].members.push({ userId: redUserId, assignedPosition: 'TOP' }); + match.result?.games[0].participants.push({ + userId: redUserId, + teamIndex: 2, + side: 'red', + championId: 24, + kills: 1, + deaths: 3, + assists: 0, + win: false, + }); + const raw = { + metadata: { + dataVersion: '2', + matchId: 'KR_1', + participants: ['puuid-1'], + }, + info: { + gameCreation: 1_000, + gameDuration: 1_800, + gameId: 1, + gameMode: 'CLASSIC', + gameName: 'teambuilder-match-1', + gameStartTimestamp: 1_000, + gameType: 'CUSTOM_GAME', + gameVersion: '16.11.1.1234', + mapId: 11, + participants: [ + { + assists: 7, + champExperience: 15_000, + champLevel: 15, + championId: 266, + championName: 'Aatrox', + deaths: 1, + firstBloodAssist: false, + firstBloodKill: true, + goldEarned: 12_345, + goldSpent: 11_000, + individualPosition: 'TOP', + item0: 1054, + item1: 3071, + item2: 0, + item3: 0, + item4: 0, + item5: 0, + item6: 3340, + kills: 5, + neutralMinionsKilled: 8, + participantId: 1, + perks: { + statPerks: { defense: 5001, flex: 5008, offense: 5005 }, + styles: [ + { + description: 'primaryStyle', + style: 8000, + selections: [ + { perk: 8010, var1: 0, var2: 0, var3: 0 }, + { perk: 9111, var1: 0, var2: 0, var3: 0 }, + { perk: 9105, var1: 0, var2: 0, var3: 0 }, + { perk: 8299, var1: 0, var2: 0, var3: 0 }, + ], + }, + { + description: 'subStyle', + style: 8400, + selections: [ + { perk: 8444, var1: 0, var2: 0, var3: 0 }, + { perk: 8451, var1: 0, var2: 0, var3: 0 }, + ], + }, + ], + }, + puuid: 'puuid-1', + riotIdGameName: 'Player', + riotIdTagLine: 'KR1', + summoner1Id: 4, + summoner2Id: 12, + summonerId: 'summoner-1', + summonerLevel: 100, + summonerName: 'Player', + teamId: 100, + teamPosition: 'TOP', + timePlayed: 1_800, + totalDamageDealtToChampions: 18_765, + totalDamageTaken: 24_321, + totalMinionsKilled: 220, + visionScore: 18, + visionWardsBoughtInGame: 2, + wardsKilled: 3, + wardsPlaced: 11, + win: true, + }, + ], + platformId: 'KR', + queueId: 0, + teams: [ + { + bans: [ + { championId: 14, pickTurn: 1 }, + { championId: 43, pickTurn: 2 }, + ], + objectives: { + baron: { first: true, kills: 1 }, + champion: { first: true, kills: 5 }, + dragon: { first: true, kills: 2 }, + horde: { first: false, kills: 3 }, + inhibitor: { first: false, kills: 0 }, + riftHerald: { first: false, kills: 0 }, + tower: { first: true, kills: 7 }, + }, + teamId: 100, + win: true, + }, + ], + }, + }; + raw.info.participants.push( + { + ...raw.info.participants[0], + assists: 0, + championId: 24, + championName: 'Jax', + deaths: 3, + kills: 1, + participantId: 2, + puuid: 'puuid-2', + riotIdGameName: 'Opponent', + summonerId: 'summoner-2', + summonerName: 'Opponent', + teamId: 200, + win: false, + }, + { + ...raw.info.participants[0], + assists: 2, + championId: 64, + championName: 'LeeSin', + deaths: 0, + kills: 1, + participantId: 3, + puuid: 'puuid-3', + riotIdGameName: 'Jungler', + summonerId: 'summoner-3', + summonerName: 'Jungler', + teamId: 100, + }, + ); + raw.info.teams.push({ + bans: [], + objectives: { + baron: { first: false, kills: 0 }, + champion: { first: false, kills: 3 }, + dragon: { first: false, kills: 0 }, + horde: { first: false, kills: 0 }, + inhibitor: { first: false, kills: 0 }, + riftHerald: { first: false, kills: 0 }, + tower: { first: false, kills: 0 }, + }, + teamId: 200, + win: false, + }); + const timeline = { + metadata: { + dataVersion: '2', + matchId: 'KR_1', + participants: ['puuid-1'], + }, + info: { + frameInterval: 60_000, + frames: [ + { + timestamp: 0, + participantFrames: { + '1': { + participantId: 1, + totalGold: 500, + xp: 0, + minionsKilled: 0, + jungleMinionsKilled: 0, + }, + '2': { + participantId: 2, + totalGold: 500, + xp: 0, + minionsKilled: 0, + jungleMinionsKilled: 0, + }, + }, + }, + { + timestamp: 60_000, + events: [ + { + type: 'ITEM_PURCHASED', + timestamp: 10_000, + participantId: 1, + itemId: 1054, + }, + { + type: 'SKILL_LEVEL_UP', + timestamp: 11_000, + participantId: 1, + skillSlot: 1, + levelUpType: 'NORMAL', + }, + { + type: 'ITEM_DESTROYED', + timestamp: 12_000, + participantId: 1, + itemId: 2003, + }, + { + type: 'ITEM_UNDO', + timestamp: 13_000, + participantId: 1, + beforeId: 1054, + afterId: 3071, + }, + { + type: 'ELITE_MONSTER_KILL', + timestamp: 20_000, + killerTeamId: 100, + monsterType: 'DRAGON', + monsterSubType: 'FIRE_DRAGON', + }, + { + type: 'ELITE_MONSTER_KILL', + timestamp: 30_000, + killerTeamId: 100, + monsterType: 'DRAGON', + monsterSubType: 'ELDER_DRAGON', + }, + { + type: 'ELITE_MONSTER_KILL', + timestamp: 40_000, + killerId: 1, + monsterType: 'HORDE', + }, + { + type: 'SKILL_LEVEL_UP', + timestamp: 45_000, + participantId: 1, + skillSlot: 3, + levelUpType: 'NORMAL', + }, + { + type: 'ELITE_MONSTER_KILL', + timestamp: 50_000, + killerTeamId: 100, + monsterType: 'BARON_NASHOR', + }, + { + type: 'ELITE_MONSTER_KILL', + timestamp: 55_000, + killerTeamId: 100, + monsterType: 'RIFTHERALD', + }, + ], + participantFrames: { + '1': { + participantId: 1, + totalGold: 1_150, + xp: 550, + minionsKilled: 5, + jungleMinionsKilled: 1, + }, + '2': { + participantId: 2, + totalGold: 1_050, + xp: 500, + minionsKilled: 4, + jungleMinionsKilled: 0, + }, + }, + }, + { + timestamp: 540_000, + events: [ + { + type: 'CHAMPION_KILL', + timestamp: 300_000, + killerId: 1, + victimId: 2, + assistingParticipantIds: [3], + }, + { + type: 'CHAMPION_KILL', + timestamp: 400_000, + killerId: 0, + victimId: 1, + }, + { + type: 'BUILDING_KILL', + timestamp: 450_000, + killerId: 0, + teamId: 200, + buildingType: 'TOWER_BUILDING', + towerType: 'OUTER_TURRET', + }, + { + type: 'BUILDING_KILL', + timestamp: 450_000, + killerId: 1, + teamId: 200, + buildingType: 'INHIBITOR_BUILDING', + }, + { + type: 'CHAMPION_KILL', + timestamp: 500_000, + killerId: 3, + victimId: 2, + assistingParticipantIds: [1], + }, + ], + participantFrames: { + '1': { + participantId: 1, + totalGold: 4_900, + xp: 3_900, + minionsKilled: 72, + jungleMinionsKilled: 8, + }, + '2': { + participantId: 2, + totalGold: 4_300, + xp: 3_500, + minionsKilled: 68, + jungleMinionsKilled: 2, + }, + }, + }, + { + timestamp: 590_000, + events: [], + participantFrames: { + '1': { + participantId: 1, + totalGold: 5_200, + xp: 4_200, + minionsKilled: 80, + jungleMinionsKilled: 10, + }, + }, + }, + { + timestamp: 900_000, + events: [ + { + type: 'CHAMPION_KILL', + timestamp: 900_000, + killerId: 1, + victimId: 2, + assistingParticipantIds: [3], + }, + ], + participantFrames: { + '1': { + participantId: 1, + totalGold: 8_100, + xp: 7_300, + minionsKilled: 130, + jungleMinionsKilled: 15, + }, + '2': { + participantId: 2, + totalGold: 6_700, + xp: 6_100, + minionsKilled: 115, + jungleMinionsKilled: 5, + }, + }, + }, + { + timestamp: 1_800_000, + events: [], + participantFrames: { + '1': { + participantId: 1, + totalGold: 12_500, + xp: 14_000, + minionsKilled: 205, + jungleMinionsKilled: 23, + }, + '2': { + participantId: 2, + totalGold: 10_200, + xp: 12_700, + minionsKilled: 190, + jungleMinionsKilled: 10, + }, + }, + }, + ], + }, + }; + + const fragment = builder.buildFragment({ + match, + rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]), + timelineByRiotMatchId: new Map([ + ['KR_1', timeline as RiotMatchTimelineDto], + ]), + }); + + expect(fragment.gameDetails[0]).toMatchObject({ + gameVersion: '16.11.1.1234', + objectiveEvents: [ + { + timestamp: 20, + side: 'blue', + type: 'dragon', + monsterSubType: 'FIRE_DRAGON', + }, + { + timestamp: 30, + side: 'blue', + type: 'elderDragon', + monsterSubType: 'ELDER_DRAGON', + }, + { timestamp: 40, side: 'blue', type: 'voidGrub' }, + { timestamp: 50, side: 'blue', type: 'baron' }, + { timestamp: 55, side: 'blue', type: 'riftHerald' }, + ], + timeline: [ + { + timestamp: 0, + blue: { gold: 500, xp: 0 }, + red: { gold: 500, xp: 0 }, + goldDiff: 0, + xpDiff: 0, + }, + { + timestamp: 60, + blue: { gold: 1_150, xp: 550 }, + red: { gold: 1_050, xp: 500 }, + goldDiff: 100, + xpDiff: 50, + }, + { + timestamp: 540, + blue: { gold: 4_900, xp: 3_900 }, + red: { gold: 4_300, xp: 3_500 }, + goldDiff: 600, + xpDiff: 400, + }, + { + timestamp: 590, + blue: { gold: 5_200, xp: 4_200 }, + red: { gold: 0, xp: 0 }, + goldDiff: 5_200, + xpDiff: 4_200, + }, + { + timestamp: 900, + blue: { gold: 8_100, xp: 7_300 }, + red: { gold: 6_700, xp: 6_100 }, + goldDiff: 1_400, + xpDiff: 1_200, + }, + { + timestamp: 1_800, + blue: { gold: 12_500, xp: 14_000 }, + red: { gold: 10_200, xp: 12_700 }, + goldDiff: 2_300, + xpDiff: 1_300, + }, + ], + }); + expect(fragment.gameDetails[0].timelineEvents).toEqual([ + { + timestamp: 20, + side: 'blue', + type: 'dragon', + monsterSubType: 'FIRE_DRAGON', + }, + { + timestamp: 30, + side: 'blue', + type: 'elderDragon', + monsterSubType: 'ELDER_DRAGON', + }, + { timestamp: 40, side: 'blue', type: 'voidGrub' }, + { timestamp: 50, side: 'blue', type: 'baron' }, + { timestamp: 55, side: 'blue', type: 'riftHerald' }, + { + timestamp: 300, + side: 'blue', + type: 'championKill', + killerParticipantId: 1, + victimParticipantId: 2, + assistingParticipantIds: [3], + }, + { + timestamp: 400, + type: 'championKill', + victimParticipantId: 1, + }, + { + timestamp: 450, + side: 'blue', + type: 'tower', + towerType: 'OUTER_TURRET', + }, + { + timestamp: 450, + side: 'blue', + type: 'inhibitor', + killerParticipantId: 1, + }, + { + timestamp: 500, + side: 'blue', + type: 'championKill', + killerParticipantId: 3, + victimParticipantId: 2, + assistingParticipantIds: [1], + }, + { + timestamp: 900, + side: 'blue', + type: 'championKill', + killerParticipantId: 1, + victimParticipantId: 2, + assistingParticipantIds: [3], + }, + ]); + expect(fragment.gameDetails[0].teams[0].bans).toEqual([ + { championId: 14, pickTurn: 1 }, + { championId: 43, pickTurn: 2 }, + ]); + expect(fragment.gameDetails[0].teams[0].objectives).toMatchObject({ + baron: 1, + dragon: 1, + elderDragon: 1, + inhibitor: 0, + riftHerald: 1, + tower: 7, + voidGrub: 1, + }); + expect(fragment.records[0]).toMatchObject({ + participantId: 1, + checkpoints: { + at10: { + timestamp: 590, + gold: 5_200, + cs: 90, + xp: 4_200, + kills: 1, + deaths: 1, + assists: 1, + }, + at15: { + timestamp: 900, + gold: 8_100, + cs: 145, + xp: 7_300, + kills: 2, + deaths: 1, + assists: 1, + }, + }, + championLevel: 15, + cs: 228, + damageDealtToChampions: 18_765, + damageTaken: 24_321, + firstBloodKill: true, + firstBloodAssist: false, + controlWardsBought: 2, + wardsKilled: 3, + wardsPlaced: 11, + perks: { + primaryStyle: 8000, + subStyle: 8400, + keystone: 8010, + selectedPerkIds: [8010, 9111, 9105, 8299, 8444, 8451], + styles: [ + { styleId: 8000, perkIds: [8010, 9111, 9105, 8299] }, + { styleId: 8400, perkIds: [8444, 8451] }, + ], + statPerks: { defense: 5001, flex: 5008, offense: 5005 }, + }, + itemBuild: [ + { timestamp: 10, itemId: 1054, type: 'purchased' }, + { timestamp: 12, itemId: 2003, type: 'destroyed' }, + { + timestamp: 13, + itemId: 3071, + type: 'undo', + beforeId: 1054, + afterId: 3071, + }, + ], + skillBuild: [ + { timestamp: 11, skillSlot: 1, level: 1, levelUpType: 'NORMAL' }, + { timestamp: 45, skillSlot: 3, level: 2, levelUpType: 'NORMAL' }, + ], + }); + expect(fragment.records[1]).toMatchObject({ + participantId: 2, + checkpoints: { + at15: { + timestamp: 900, + gold: 6_700, + cs: 120, + xp: 6_100, + kills: 0, + deaths: 3, + assists: 0, + }, + }, + }); + expect(fragment.records[1].checkpoints).not.toHaveProperty('at10'); + + const timelineWithoutEvents = { + ...timeline, + info: { + ...timeline.info, + frames: timeline.info.frames.map((frame) => ({ + ...frame, + events: [], + })), + }, + } as RiotMatchTimelineDto; + const objectiveFallback = builder.buildFragment({ + match, + rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]), + timelineByRiotMatchId: new Map([['KR_1', timelineWithoutEvents]]), + }); + expect(objectiveFallback.gameDetails[0].teams[0].objectives).toMatchObject({ + baron: 1, + dragon: 2, + elderDragon: 0, + riftHerald: 0, + voidGrub: 3, + }); + + const dragonOnlyTimeline = { + ...timeline, + info: { + ...timeline.info, + frames: timeline.info.frames.map((frame) => ({ + ...frame, + events: (frame.events ?? []).filter( + (event) => + event.type !== 'ELITE_MONSTER_KILL' || + event.monsterType === 'DRAGON', + ), + })), + }, + } as RiotMatchTimelineDto; + const partialObjectiveFallback = builder.buildFragment({ + match, + rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]), + timelineByRiotMatchId: new Map([['KR_1', dragonOnlyTimeline]]), + }); + expect( + partialObjectiveFallback.gameDetails[0].teams[0].objectives, + ).toMatchObject({ + baron: 1, + dragon: 1, + elderDragon: 1, + riftHerald: 0, + voidGrub: 3, + }); + + const shortMatch = { + ...match, + result: { + ...match.result!, + games: match.result!.games.map((game) => ({ + ...game, + gameDuration: 599, + })), + }, + } as MatchDocument; + const shortFragment = builder.buildFragment({ + match: shortMatch, + rawByRiotMatchId: new Map([ + [ + 'KR_1', + { + ...raw, + info: { ...raw.info, gameDuration: 599 }, + } as RiotMatchDto, + ], + ]), + timelineByRiotMatchId: new Map([ + ['KR_1', timeline as RiotMatchTimelineDto], + ]), + }); + expect( + shortFragment.records.every((record) => record.checkpoints === undefined), + ).toBe(true); + + const invalidIntervalTimeline = { + ...timeline, + info: { ...timeline.info, frameInterval: Number.NaN }, + } as RiotMatchTimelineDto; + const invalidIntervalFragment = builder.buildFragment({ + match, + rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]), + timelineByRiotMatchId: new Map([['KR_1', invalidIntervalTimeline]]), + }); + expect(invalidIntervalFragment.gameDetails[0].timelineLoaded).toBe(false); + expect(invalidIntervalFragment.gameDetails[0].timeline).toEqual([]); + expect( + invalidIntervalFragment.records.every( + (record) => record.checkpoints === undefined, + ), + ).toBe(true); + }); }); diff --git a/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts b/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts index b4a10c0d..c91a5d77 100644 --- a/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts +++ b/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts @@ -3,9 +3,21 @@ import mongoose from 'mongoose'; import type { MatchDocument, MatchGameResultParticipant, + MatchStatsCheckpoint, + MatchStatsItemBuildEvent, + MatchStatsObjectiveEvent, + MatchStatsObjectiveSummary, + MatchStatsParticipantCheckpoints, + MatchStatsSkillBuildEvent, + MatchStatsTimelineEvent, + MatchStatsTimelinePoint, TeamSide, } from '../global/database/schema'; -import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types'; +import type { + RiotMatchDto, + RiotMatchParticipantDto, + RiotMatchTimelineDto, +} from '../riot/riot.types'; import type { InternalMatchCardView } from './community-stats.types'; import type { InternalGameDetail, @@ -13,11 +25,22 @@ import type { MatchStatsFragment, } from './match-stats.types'; +interface ParticipantBuildEvents { + items: MatchStatsItemBuildEvent[]; + skills: MatchStatsSkillBuildEvent[]; +} + +interface TimelineProjection { + objectiveEvents: MatchStatsObjectiveEvent[]; + timelineEvents: MatchStatsTimelineEvent[]; +} + @Injectable() export class MatchStatsFragmentBuilder { public buildFragment(params: { match: MatchDocument; rawByRiotMatchId: Map; + timelineByRiotMatchId?: Map; }): MatchStatsFragment { const games = [...(params.match.result?.games ?? [])].sort( (left, right) => left.gameNumber - right.gameNumber, @@ -25,8 +48,9 @@ export class MatchStatsFragmentBuilder { const matchCard = this.toMatchCard(params.match, games); const gameDetails = games.map((game) => { const raw = params.rawByRiotMatchId.get(game.riotMatchId); + const timeline = params.timelineByRiotMatchId?.get(game.riotMatchId); return raw - ? this.toGameDetail(params.match, game, raw) + ? this.toGameDetail(params.match, game, raw, timeline) : this.toFallbackGameDetail(params.match, game); }); const records = gameDetails.flatMap((detail) => @@ -106,7 +130,11 @@ export class MatchStatsFragmentBuilder { match: MatchDocument, game: NonNullable['games'][number], raw: RiotMatchDto, + timeline?: RiotMatchTimelineDto, ): InternalGameDetail { + const usableTimeline = isUsableTimeline(timeline, raw.info.gameDuration) + ? timeline + : undefined; const puuidByUserId = new Map( match.participants .filter((participant) => participant.puuid) @@ -129,13 +157,34 @@ export class MatchStatsFragmentBuilder { rawTeamIdBySide.set(participant.side, rawParticipant.teamId); } } + const sideByParticipantId = this.toSideByParticipantId( + raw, + rawTeamIdBySide, + ); + const { objectiveEvents, timelineEvents } = this.toTimelineEvents( + usableTimeline, + rawTeamIdBySide, + sideByParticipantId, + ); + const timelineObjectives = this.toTimelineObjectives(objectiveEvents); + const buildEventsByParticipantId = + this.toBuildEventsByParticipantId(usableTimeline); + const checkpointsByParticipantId = this.toCheckpointsByParticipantId( + usableTimeline, + raw.info.gameDuration, + ); return { gameNumber: game.gameNumber, riotMatchId: game.riotMatchId, gameCreation: game.gameCreation, gameDuration: game.gameDuration, + gameVersion: raw.info.gameVersion, winnerSide: game.winnerSide, + timeline: this.toTimeline(raw, rawTeamIdBySide, usableTimeline), + timelineLoaded: Boolean(usableTimeline), + objectiveEvents, + timelineEvents, teams: (['blue', 'red'] as TeamSide[]).map((side) => { const teamIndex = side === 'blue' ? game.blueTeamIndex : game.redTeamIndex; @@ -158,25 +207,37 @@ export class MatchStatsFragmentBuilder { teamIndex, side, win: game.winnerSide === side, - objectives: { - baron: rawTeam?.objectives?.baron?.kills ?? 0, - dragon: rawTeam?.objectives?.dragon?.kills ?? 0, - tower: rawTeam?.objectives?.tower?.kills ?? 0, - }, + objectives: this.toObjectiveSummary( + rawTeam, + timelineObjectives.get(side), + ), + bans: (rawTeam?.bans ?? []).map((ban) => ({ + championId: ban.championId, + pickTurn: ban.pickTurn, + })), participants: game.participants .filter((participant) => participant.side === side) - .map((participant) => - this.toRecord({ + .map((participant) => { + const rawParticipant = rawByPuuid.get( + puuidByUserId.get(participant.userId.toString()) ?? '', + ); + return this.toRecord({ match, game, participant, - rawParticipant: rawByPuuid.get( - puuidByUserId.get(participant.userId.toString()) ?? '', - ), + rawParticipant, + buildEvents: rawParticipant + ? buildEventsByParticipantId.get( + rawParticipant.participantId, + ) + : undefined, + checkpoints: rawParticipant + ? checkpointsByParticipantId.get(rawParticipant.participantId) + : undefined, teamKills, teamDamage, - }), - ), + }); + }), }; }), }; @@ -192,11 +253,16 @@ export class MatchStatsFragmentBuilder { gameCreation: game.gameCreation, gameDuration: game.gameDuration, winnerSide: game.winnerSide, + timeline: [], + timelineLoaded: false, + objectiveEvents: [], + timelineEvents: [], teams: (['blue', 'red'] as TeamSide[]).map((side) => ({ teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex, side, win: game.winnerSide === side, - objectives: { baron: 0, dragon: 0, tower: 0 }, + objectives: emptyObjectives(), + bans: [], participants: game.participants .filter((participant) => participant.side === side) .map((participant) => @@ -217,11 +283,21 @@ export class MatchStatsFragmentBuilder { game: NonNullable['games'][number]; participant: MatchGameResultParticipant; rawParticipant?: RiotMatchParticipantDto; + buildEvents?: ParticipantBuildEvents; + checkpoints?: MatchStatsParticipantCheckpoints; teamKills: number; teamDamage: number; }): InternalRecord { - const { match, game, participant, rawParticipant, teamKills, teamDamage } = - params; + const { + match, + game, + participant, + rawParticipant, + buildEvents, + checkpoints, + teamKills, + teamDamage, + } = params; const snapshot = match.participants.find((item) => item.userId.equals(participant.userId), ); @@ -256,12 +332,15 @@ export class MatchStatsFragmentBuilder { riotMatchId: game.riotMatchId, gameCreation: game.gameCreation, gameDuration: game.gameDuration, + participantId: rawParticipant?.participantId, + checkpoints, userId: participant.userId.toString(), summonerName: snapshot?.gameName ?? rawParticipant?.riotIdGameName ?? rawParticipant?.summonerName ?? 'Unknown', + tagLine: snapshot?.tagLine ?? rawParticipant?.riotIdTagLine ?? '', profileIconId: snapshot?.profileIconId ?? 0, teamIndex: participant.teamIndex, side: participant.side, @@ -290,6 +369,8 @@ export class MatchStatsFragmentBuilder { ), wardsPlaced: rawParticipant?.wardsPlaced ?? 0, wardsKilled: rawParticipant?.wardsKilled ?? 0, + firstBloodKill: booleanField(rawParticipant, 'firstBloodKill'), + firstBloodAssist: booleanField(rawParticipant, 'firstBloodAssist'), items: [ rawParticipant?.item0 ?? 0, rawParticipant?.item1 ?? 0, @@ -304,6 +385,8 @@ export class MatchStatsFragmentBuilder { rawParticipant?.summoner2Id ?? 0, ], perks: rawParticipant ? this.resolvePerks(rawParticipant) : {}, + itemBuild: buildEvents?.items ?? [], + skillBuild: buildEvents?.skills ?? [], rating, }; } @@ -319,6 +402,410 @@ export class MatchStatsFragmentBuilder { primaryStyle: primary?.style, subStyle: sub?.style, keystone: primary?.selections[0]?.perk, + selectedPerkIds: participant.perks.styles.flatMap((style) => + style.selections.map((selection) => selection.perk), + ), + styles: participant.perks.styles.map((style) => ({ + styleId: style.style, + perkIds: style.selections.map((selection) => selection.perk), + })), + statPerks: { + offense: participant.perks.statPerks.offense, + flex: participant.perks.statPerks.flex, + defense: participant.perks.statPerks.defense, + }, + }; + } + + private toBuildEventsByParticipantId( + timeline?: RiotMatchTimelineDto, + ): Map { + const buildEventsByParticipantId = new Map(); + if (!timeline?.info.frames.length) return buildEventsByParticipantId; + + const getEvents = (participantId: number): ParticipantBuildEvents => { + const current = buildEventsByParticipantId.get(participantId); + if (current) return current; + const created: ParticipantBuildEvents = { items: [], skills: [] }; + buildEventsByParticipantId.set(participantId, created); + return created; + }; + + for (const frame of timeline.info.frames) { + for (const event of frame.events ?? []) { + const participantId = event.participantId; + if (!participantId) continue; + const timestamp = Math.max(0, Math.round(event.timestamp / 1000)); + + if (event.type === 'SKILL_LEVEL_UP' && isSkillSlot(event.skillSlot)) { + const skills = getEvents(participantId).skills; + skills.push({ + timestamp, + skillSlot: event.skillSlot, + level: skills.length + 1, + levelUpType: event.levelUpType, + }); + continue; + } + + const itemType = toItemBuildType(event.type); + if (!itemType) continue; + const itemId = event.itemId ?? event.afterId ?? event.beforeId ?? 0; + if (itemId <= 0) continue; + getEvents(participantId).items.push({ + timestamp, + itemId, + type: itemType, + beforeId: event.beforeId, + afterId: event.afterId, + }); + } + } + + for (const events of buildEventsByParticipantId.values()) { + events.items.sort((left, right) => left.timestamp - right.timestamp); + events.skills.sort((left, right) => left.timestamp - right.timestamp); + } + + return buildEventsByParticipantId; + } + + private toCheckpointsByParticipantId( + timeline: RiotMatchTimelineDto | undefined, + gameDurationSeconds: number, + ): Map { + const checkpointsByParticipantId = new Map< + number, + MatchStatsParticipantCheckpoints + >(); + if ( + !timeline?.info.frames.length || + !Number.isFinite(timeline.info.frameInterval) || + timeline.info.frameInterval <= 0 + ) { + return checkpointsByParticipantId; + } + + const participantIds = new Set(); + const championKillEvents = timeline.info.frames.flatMap((frame) => + (frame.events ?? []).filter((event) => event.type === 'CHAMPION_KILL'), + ); + for (const frame of timeline.info.frames) { + for (const participantFrame of Object.values(frame.participantFrames)) { + participantIds.add(participantFrame.participantId); + } + } + + const targets = [ + ['at10', 600_000], + ['at15', 900_000], + ] as const; + for (const participantId of participantIds) { + const checkpoints: MatchStatsParticipantCheckpoints = {}; + for (const [key, targetTimestamp] of targets) { + if (gameDurationSeconds * 1_000 < targetTimestamp) continue; + + const selectedFrame = timeline.info.frames.reduce< + RiotMatchTimelineDto['info']['frames'][number] | undefined + >((latest, frame) => { + if ( + frame.timestamp > targetTimestamp || + !Object.values(frame.participantFrames).some( + (participantFrame) => + participantFrame.participantId === participantId, + ) + ) { + return latest; + } + return !latest || frame.timestamp > latest.timestamp ? frame : latest; + }, undefined); + if ( + !selectedFrame || + targetTimestamp - selectedFrame.timestamp >= + timeline.info.frameInterval + ) { + continue; + } + + const participantFrame = Object.values( + selectedFrame.participantFrames, + ).find((frame) => frame.participantId === participantId); + if ( + !participantFrame || + typeof participantFrame.minionsKilled !== 'number' || + !Number.isFinite(participantFrame.minionsKilled) || + typeof participantFrame.jungleMinionsKilled !== 'number' || + !Number.isFinite(participantFrame.jungleMinionsKilled) + ) { + continue; + } + + const checkpoint: MatchStatsCheckpoint = { + timestamp: Math.max(0, Math.round(selectedFrame.timestamp / 1_000)), + gold: participantFrame.totalGold, + cs: + participantFrame.minionsKilled + + participantFrame.jungleMinionsKilled, + xp: participantFrame.xp, + kills: 0, + deaths: 0, + assists: 0, + }; + for (const event of championKillEvents) { + if (event.timestamp > selectedFrame.timestamp) continue; + if (event.killerId === participantId && event.killerId > 0) { + checkpoint.kills += 1; + } + if (event.victimId === participantId) checkpoint.deaths += 1; + if (event.assistingParticipantIds?.includes(participantId)) { + checkpoint.assists += 1; + } + } + checkpoints[key] = checkpoint; + } + if (checkpoints.at10 || checkpoints.at15) { + checkpointsByParticipantId.set(participantId, checkpoints); + } + } + + return checkpointsByParticipantId; + } + + private toTimeline( + raw: RiotMatchDto, + rawTeamIdBySide: Map, + timeline?: RiotMatchTimelineDto, + ): MatchStatsTimelinePoint[] { + if (!timeline?.info.frames.length) return []; + + const sideByParticipantId = this.toSideByParticipantId( + raw, + rawTeamIdBySide, + ); + + const points = timeline.info.frames.map((frame) => { + const point: MatchStatsTimelinePoint = { + timestamp: Math.max(0, Math.round(frame.timestamp / 1000)), + blue: { gold: 0, xp: 0 }, + red: { gold: 0, xp: 0 }, + goldDiff: 0, + xpDiff: 0, + }; + + for (const participantFrame of Object.values(frame.participantFrames)) { + const side = sideByParticipantId.get(participantFrame.participantId); + if (!side) continue; + point[side].gold += participantFrame.totalGold; + point[side].xp += participantFrame.xp; + } + point.goldDiff = point.blue.gold - point.red.gold; + point.xpDiff = point.blue.xp - point.red.xp; + return point; + }); + + return points.filter( + (point, index) => + index === 0 || point.timestamp !== points[index - 1].timestamp, + ); + } + + private toSideByParticipantId( + raw: RiotMatchDto, + rawTeamIdBySide: Map, + ): Map { + const blueTeamId = rawTeamIdBySide.get('blue') ?? 100; + const redTeamId = rawTeamIdBySide.get('red') ?? 200; + const sideByParticipantId = new Map(); + for (const participant of raw.info.participants) { + if (participant.teamId === blueTeamId) { + sideByParticipantId.set(participant.participantId, 'blue'); + } + if (participant.teamId === redTeamId) { + sideByParticipantId.set(participant.participantId, 'red'); + } + } + return sideByParticipantId; + } + + private toTimelineEvents( + timeline: RiotMatchTimelineDto | undefined, + rawTeamIdBySide: Map, + sideByParticipantId: Map, + ): TimelineProjection { + if (!timeline?.info.frames.length) { + return { objectiveEvents: [], timelineEvents: [] }; + } + + const sideByTeamId = new Map(); + for (const [side, teamId] of rawTeamIdBySide.entries()) { + sideByTeamId.set(teamId, side); + } + + const projected: Array<{ + sourceSequence: number; + event: MatchStatsTimelineEvent; + }> = []; + let sourceSequence = 0; + for (const frame of timeline.info.frames) { + for (const event of frame.events ?? []) { + const currentSequence = sourceSequence; + sourceSequence += 1; + const timestamp = Math.max(0, Math.round(event.timestamp / 1000)); + if (event.type === 'ELITE_MONSTER_KILL') { + const side = + (typeof event.killerTeamId === 'number' + ? sideByTeamId.get(event.killerTeamId) + : undefined) ?? + (typeof event.killerId === 'number' + ? sideByParticipantId.get(event.killerId) + : undefined); + if (!side) continue; + const objectiveEvent = toObjectiveTimelineEvent({ + timestamp, + side, + monsterType: event.monsterType, + monsterSubType: event.monsterSubType, + }); + if (objectiveEvent) { + projected.push({ + sourceSequence: currentSequence, + event: objectiveEvent, + }); + } + continue; + } + + if (event.type === 'CHAMPION_KILL') { + const side = + typeof event.killerId === 'number' && event.killerId > 0 + ? sideByParticipantId.get(event.killerId) + : undefined; + projected.push({ + sourceSequence: currentSequence, + event: { + timestamp, + type: 'championKill', + ...(side ? { side } : {}), + ...(typeof event.killerId === 'number' && event.killerId > 0 + ? { killerParticipantId: event.killerId } + : {}), + ...(typeof event.victimId === 'number' && event.victimId > 0 + ? { victimParticipantId: event.victimId } + : {}), + ...(event.assistingParticipantIds + ? { assistingParticipantIds: event.assistingParticipantIds } + : {}), + }, + }); + continue; + } + + if (event.type !== 'BUILDING_KILL') continue; + const destroyedSide = + typeof event.teamId === 'number' + ? sideByTeamId.get(event.teamId) + : undefined; + const side = + (typeof event.killerId === 'number' && event.killerId > 0 + ? sideByParticipantId.get(event.killerId) + : undefined) ?? + (destroyedSide ? oppositeSide(destroyedSide) : undefined); + const type = + event.buildingType === 'TOWER_BUILDING' + ? 'tower' + : event.buildingType === 'INHIBITOR_BUILDING' + ? 'inhibitor' + : undefined; + if (!side || !type) continue; + projected.push({ + sourceSequence: currentSequence, + event: { + timestamp, + side, + type, + ...(typeof event.killerId === 'number' && event.killerId > 0 + ? { killerParticipantId: event.killerId } + : {}), + ...(type === 'tower' && event.towerType + ? { towerType: event.towerType } + : {}), + }, + }); + } + } + + const timelineEvents = projected + .sort( + (left, right) => + left.event.timestamp - right.event.timestamp || + left.sourceSequence - right.sourceSequence, + ) + .map(({ event }) => event); + return { + timelineEvents, + objectiveEvents: timelineEvents.filter(isObjectiveTimelineEvent), + }; + } + + private toTimelineObjectives( + objectiveEvents: MatchStatsObjectiveEvent[], + ): Map { + const objectives = new Map([ + ['blue', emptyObjectives()], + ['red', emptyObjectives()], + ]); + + for (const event of objectiveEvents) { + const current = objectives.get(event.side) ?? emptyObjectives(); + switch (event.type) { + case 'baron': + current.baron += 1; + break; + case 'riftHerald': + current.riftHerald += 1; + break; + case 'voidGrub': + current.voidGrub += 1; + break; + case 'dragon': + current.dragon += 1; + break; + case 'elderDragon': + current.elderDragon += 1; + break; + default: + break; + } + objectives.set(event.side, current); + } + + return objectives; + } + + private toObjectiveSummary( + rawTeam: RiotMatchDto['info']['teams'][number] | undefined, + timelineObjectives: MatchStatsObjectiveSummary | undefined, + ): MatchStatsObjectiveSummary { + const rawObjectives = rawTeam?.objectives; + const timelineDragon = timelineObjectives?.dragon ?? 0; + const timelineElder = timelineObjectives?.elderDragon ?? 0; + const hasProjectedDragon = timelineDragon + timelineElder > 0; + return { + tower: rawObjectives?.tower?.kills ?? 0, + dragon: hasProjectedDragon + ? timelineDragon + : (rawObjectives?.dragon?.kills ?? 0), + inhibitor: rawObjectives?.inhibitor?.kills ?? 0, + baron: (timelineObjectives?.baron ?? 0) > 0 + ? (timelineObjectives?.baron ?? 0) + : (rawObjectives?.baron?.kills ?? 0), + riftHerald: (timelineObjectives?.riftHerald ?? 0) > 0 + ? (timelineObjectives?.riftHerald ?? 0) + : (rawObjectives?.riftHerald?.kills ?? 0), + voidGrub: (timelineObjectives?.voidGrub ?? 0) > 0 + ? (timelineObjectives?.voidGrub ?? 0) + : (rawObjectives?.horde?.kills ?? 0), + elderDragon: hasProjectedDragon ? timelineElder : 0, }; } @@ -354,6 +841,100 @@ function average(value: number, total: number): number { return total > 0 ? round(value / total) : 0; } +function isSkillSlot(value: number | undefined): value is 1 | 2 | 3 | 4 { + return value === 1 || value === 2 || value === 3 || value === 4; +} + +function toItemBuildType( + value: string, +): MatchStatsItemBuildEvent['type'] | null { + switch (value) { + case 'ITEM_PURCHASED': + return 'purchased'; + case 'ITEM_SOLD': + return 'sold'; + case 'ITEM_DESTROYED': + return 'destroyed'; + case 'ITEM_UNDO': + return 'undo'; + default: + return null; + } +} + +function toObjectiveTimelineEvent(params: { + timestamp: number; + side: TeamSide; + monsterType?: string; + monsterSubType?: string; +}): MatchStatsObjectiveEvent | null { + switch (params.monsterType) { + case 'BARON_NASHOR': + return { timestamp: params.timestamp, side: params.side, type: 'baron' }; + case 'RIFTHERALD': + return { + timestamp: params.timestamp, + side: params.side, + type: 'riftHerald', + }; + case 'HORDE': + return { + timestamp: params.timestamp, + side: params.side, + type: 'voidGrub', + }; + case 'DRAGON': + return { + timestamp: params.timestamp, + side: params.side, + type: + params.monsterSubType === 'ELDER_DRAGON' ? 'elderDragon' : 'dragon', + monsterSubType: params.monsterSubType, + }; + default: + return null; + } +} + +function isObjectiveTimelineEvent( + event: MatchStatsTimelineEvent, +): event is MatchStatsObjectiveEvent { + return ( + event.type === 'dragon' || + event.type === 'elderDragon' || + event.type === 'baron' || + event.type === 'riftHerald' || + event.type === 'voidGrub' + ); +} + +function oppositeSide(side: TeamSide): TeamSide { + return side === 'blue' ? 'red' : 'blue'; +} + +function isUsableTimeline( + timeline: RiotMatchTimelineDto | undefined, + gameDurationSeconds: number, +): timeline is RiotMatchTimelineDto { + if ( + !timeline || + !Number.isFinite(timeline.info.frameInterval) || + timeline.info.frameInterval <= 0 || + !Array.isArray(timeline.info.frames) || + timeline.info.frames.length === 0 + ) { + return false; + } + const finalTimestamp = Math.max( + ...timeline.info.frames.map((frame) => frame.timestamp), + ); + return ( + Number.isFinite(finalTimestamp) && + Math.abs(gameDurationSeconds * 1_000 - finalTimestamp) < + timeline.info.frameInterval + ); +} + function round(value: number): number { return Math.round(value * 10) / 10; } @@ -365,3 +946,22 @@ function numberField( const value = participant?.[key]; return typeof value === 'number' && Number.isFinite(value) ? value : 0; } + +function booleanField( + participant: RiotMatchParticipantDto | undefined, + key: string, +): boolean { + return participant?.[key] === true; +} + +function emptyObjectives(): MatchStatsObjectiveSummary { + return { + tower: 0, + dragon: 0, + inhibitor: 0, + baron: 0, + riftHerald: 0, + voidGrub: 0, + elderDragon: 0, + }; +} diff --git a/apps/api/src/modules/community-stats/match-stats.repository.spec.ts b/apps/api/src/modules/community-stats/match-stats.repository.spec.ts new file mode 100644 index 00000000..b9a8c6ef --- /dev/null +++ b/apps/api/src/modules/community-stats/match-stats.repository.spec.ts @@ -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 | undefined; + let initialGuardCount = 0; + let releaseInitialGuards!: () => void; + const initialGuardsReady = new Promise((resolve) => { + releaseInitialGuards = resolve; + }); + let releaseOlderInsert!: () => void; + const olderInserted = new Promise((resolve) => { + releaseOlderInsert = resolve; + }); + const updateOne = jest.fn( + ( + _filter: Record, + update: { + $set?: ReturnType; + $setOnInsert?: ReturnType; + }, + ) => ({ + 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; +} diff --git a/apps/api/src/modules/community-stats/match-stats.repository.ts b/apps/api/src/modules/community-stats/match-stats.repository.ts index 21b35acf..f56a3baa 100644 --- a/apps/api/src/modules/community-stats/match-stats.repository.ts +++ b/apps/api/src/modules/community-stats/match-stats.repository.ts @@ -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, ): Promise { 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 { + public async deleteByMatch( + matchId: mongoose.Types.ObjectId, + guard?: MatchStatsDeleteGuard, + ): Promise { 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 { + const MatchStatsModel = await this.connectionService.getModel('matchStats'); + await MatchStatsModel.deleteOne({ + matchId, + sourceCompetitionId: { $exists: false }, + }).exec(); + } + public async findByMatch( matchId: mongoose.Types.ObjectId, ): Promise { @@ -68,6 +163,53 @@ export class MatchStatsRepository { toGameCreation?: number; }): Promise { 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 { + 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() + .exec(); + } + + public async findDetailsByMatches(params: { + communityId: mongoose.Types.ObjectId; + matchIds: mongoose.Types.ObjectId[]; + }): Promise { + 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() + .exec(); + } + + private buildUserFilter(params: { + communityId: mongoose.Types.ObjectId; + userId: mongoose.Types.ObjectId; + fromGameCreation?: number; + toGameCreation?: number; + }): Record { const filter: Record = { 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, +) { + 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 + ); +} diff --git a/apps/api/src/modules/community-stats/match-stats.service.spec.ts b/apps/api/src/modules/community-stats/match-stats.service.spec.ts index 552cca15..a2e6e5e3 100644 --- a/apps/api/src/modules/community-stats/match-stats.service.spec.ts +++ b/apps/api/src/modules/community-stats/match-stats.service.spec.ts @@ -3,6 +3,7 @@ import { ConnectionService } from '../global/database/connection.service'; import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder'; import { MatchStatsRepository } from './match-stats.repository'; import { MatchStatsService } from './match-stats.service'; +import { MATCH_STATS_BUILDER_VERSION } from './match-stats.types'; describe('MatchStatsService', () => { it('deletes an existing fragment when the match is no longer eligible', async () => { @@ -17,6 +18,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}`); }), @@ -29,6 +31,7 @@ describe('MatchStatsService', () => { connectionService, repository, {} as MatchStatsFragmentBuilder, + { getMatchTimeline: jest.fn() } as never, ); await service.buildAndUpsert(matchId); @@ -37,6 +40,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; + 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(); @@ -53,12 +107,26 @@ describe('MatchStatsService', () => { }); const riotFind = jest.fn().mockReturnValue({ lean: () => ({ - exec: jest.fn().mockResolvedValue([{ matchId: 'KR_1', raw: {} }]), + exec: jest.fn().mockResolvedValue([ + { + matchId: 'KR_1', + raw: {}, + timeline: { + metadata: { + dataVersion: '2', + matchId: 'KR_1', + participants: [], + }, + info: { frameInterval: 60_000, frames: [] }, + }, + }, + ]), }), }); const connectionService = { getModel: jest.fn().mockImplementation(async (name: string) => { if (name === 'match') return { findById }; + if (name === 'competition') return { findOne: () => queryResult(null) }; if (name === 'riotMatch') return { find: riotFind }; throw new Error(`Unexpected model: ${name}`); }), @@ -82,6 +150,7 @@ describe('MatchStatsService', () => { connectionService, repository, builder, + { getMatchTimeline: jest.fn() } as never, ); await service.buildAndUpsert(matchId); @@ -89,7 +158,11 @@ describe('MatchStatsService', () => { expect(builder.buildFragment).toHaveBeenCalledWith({ match, rawByRiotMatchId: expect.any(Map), + timelineByRiotMatchId: expect.any(Map), }); + expect( + builder.buildFragment.mock.calls[0][0].timelineByRiotMatchId, + ).toHaveProperty('size', 0); expect(repository.upsert).toHaveBeenCalledWith( expect.objectContaining({ matchId, @@ -97,8 +170,461 @@ describe('MatchStatsService', () => { scheduledAt, gameCreationMin: 1_000, gameCreationMax: 2_000, - builderVersion: 1, + builderVersion: MATCH_STATS_BUILDER_VERSION, }), ); }); + + it('retries unusable timeline caches and stores a later usable fetch', async () => { + const matchId = new mongoose.Types.ObjectId(); + const communityId = new mongoose.Types.ObjectId(); + const match = { + _id: matchId, + communityId, + scheduledAt: new Date('2026-05-03T00:00:00.000Z'), + status: 'finished', + result: { games: [{ riotMatchId: 'KR_1' }] }, + }; + const emptyTimeline = { + info: { frameInterval: 60_000, frames: [] }, + }; + const partialTimeline = { + info: { + frameInterval: 60_000, + frames: [{ timestamp: 0, events: [] }], + }, + }; + const nonPositiveTimeline = { + info: { + frameInterval: 0, + frames: [timelineFrame(120_000)], + }, + }; + const truncatedTimeline = { + info: { + frameInterval: 60_000, + frames: [timelineFrame()], + }, + }; + const usableTimeline = { + metadata: { + dataVersion: '2', + matchId: 'KR_1', + participants: ['puuid-1'], + }, + info: { + frameInterval: 60_000, + frames: [timelineFrame(120_000)], + }, + }; + const cachedTimelines = [ + emptyTimeline, + partialTimeline, + nonPositiveTimeline, + truncatedTimeline, + ]; + let buildIndex = 0; + const riotFind = jest.fn().mockImplementation(() => ({ + lean: () => ({ + exec: jest.fn().mockResolvedValue([ + { + matchId: 'KR_1', + raw: { info: { gameDuration: 120 } }, + timeline: cachedTimelines[Math.min(buildIndex++, 3)], + }, + ]), + }), + })); + const updateExec = jest.fn().mockResolvedValue(undefined); + let storedUpdate: + | { + filter: unknown; + update: { $set: { timeline: unknown; timelineFetchedAt: Date } }; + } + | undefined; + const updateOne = jest.fn( + ( + filter: unknown, + update: { $set: { timeline: unknown; timelineFetchedAt: Date } }, + ) => { + storedUpdate = { filter, update }; + return { exec: updateExec }; + }, + ); + const connectionService = { + getModel: jest.fn().mockImplementation((name: string) => { + if (name === 'match') { + return Promise.resolve({ findById: () => queryResult(match, false) }); + } + if (name === 'competition') { + return Promise.resolve({ findOne: () => queryResult(null) }); + } + if (name === 'riotMatch') { + return Promise.resolve({ find: riotFind, updateOne }); + } + if (name === 'community') { + return Promise.resolve({ + findById: () => ({ + select: () => queryResult({ riotRegion: 'asia' }), + }), + }); + } + return Promise.reject(new Error(`Unexpected model: ${name}`)); + }), + } as unknown as ConnectionService; + const repository = { + upsert: jest.fn().mockResolvedValue(undefined), + deleteByMatch: jest.fn(), + deleteLegacyByMatch: jest.fn(), + } as unknown as jest.Mocked; + type BuildParams = Parameters< + MatchStatsFragmentBuilder['buildFragment'] + >[0]; + const buildCalls: BuildParams[] = []; + const builtFragment = { + matchCard: { matchId: matchId.toString() }, + records: [], + gameDetails: [], + userIds: [], + championIds: [], + gameCreationMin: 1_000, + gameCreationMax: 2_000, + } as ReturnType; + const buildFragment = jest.fn((params: BuildParams) => { + buildCalls.push(params); + return builtFragment; + }); + const builder = { + buildFragment, + } as unknown as jest.Mocked; + const getMatchTimeline = jest + .fn() + .mockRejectedValueOnce(new Error('temporary Riot failure')) + .mockRejectedValueOnce(new Error('temporary Riot failure')) + .mockRejectedValueOnce(new Error('temporary Riot failure')) + .mockResolvedValueOnce(usableTimeline); + const service = new MatchStatsService( + connectionService, + repository, + builder, + { getMatchTimeline } as never, + ); + + await service.buildAndUpsert(matchId, { includeTimeline: true }); + await service.buildAndUpsert(matchId, { includeTimeline: true }); + await service.buildAndUpsert(matchId, { includeTimeline: true }); + await service.buildAndUpsert(matchId, { includeTimeline: true }); + + expect(getMatchTimeline).toHaveBeenCalledTimes(4); + expect(buildFragment).toHaveBeenCalledTimes(4); + expect(buildCalls[0].timelineByRiotMatchId).toHaveProperty('size', 0); + expect(buildCalls[1].timelineByRiotMatchId).toHaveProperty('size', 0); + expect(buildCalls[2].timelineByRiotMatchId?.get('KR_1')).toBeUndefined(); + expect(buildCalls[3].timelineByRiotMatchId?.get('KR_1')).toBe( + usableTimeline, + ); + for (const call of buildCalls) { + expect(call).not.toHaveProperty('timelineLoadAttempted'); + } + expect(updateOne).toHaveBeenCalledTimes(1); + expect(storedUpdate?.filter).toEqual({ matchId: 'KR_1' }); + expect(storedUpdate?.update.$set.timeline).toBe(usableTimeline); + expect(storedUpdate?.update.$set.timelineFetchedAt).toBeInstanceOf(Date); + expect(updateExec).toHaveBeenCalledTimes(1); + }); + + it('builds from the Competition projection and records its source revision', async () => { + const matchId = new mongoose.Types.ObjectId(); + const communityId = new mongoose.Types.ObjectId(); + const competitionId = new mongoose.Types.ObjectId(); + const teamAId = new mongoose.Types.ObjectId(); + const teamBId = new mongoose.Types.ObjectId(); + const userAId = new mongoose.Types.ObjectId(); + const userBId = new mongoose.Types.ObjectId(); + const match = { + _id: matchId, + communityId, + scheduledAt: new Date('2026-07-12T10:00:00.000Z'), + status: 'in-progress', + teams: [], + result: { games: [{ riotMatchId: 'KR_LEGACY_MUST_NOT_BE_USED' }] }, + }; + const competition = { + _id: competitionId, + revision: 12, + projectorVersion: 3, + teams: [ + { teamId: teamAId, legacyTeamIndex: 8, displayOrder: 1 }, + { teamId: teamBId, legacyTeamIndex: 3, displayOrder: 2 }, + ], + projection: { + phase: 'running', + games: [ + { + displayNumber: 4, + evidence: { type: 'riot', riotMatchId: 'KR_COMPETITION' }, + teams: { + blue: { teamId: teamAId.toString() }, + red: { teamId: teamBId.toString() }, + }, + winnerTeamId: teamAId.toString(), + startedAt: '2026-07-12T10:00:00.000Z', + durationSeconds: 1800, + participants: [ + participant(userAId, teamAId, 'blue', true), + participant(userBId, teamBId, 'red', false), + ], + }, + ], + }, + }; + const riotFind = jest.fn().mockReturnValue({ + lean: () => ({ + exec: jest + .fn() + .mockResolvedValue([{ matchId: 'KR_COMPETITION', raw: {} }]), + }), + }); + const connectionService = { + getModel: jest.fn().mockImplementation(async (name: string) => { + if (name === 'match') + return { findById: () => queryResult(match, false) }; + if (name === 'competition') { + return { findOne: () => queryResult(competition) }; + } + if (name === 'riotMatch') return { find: riotFind }; + throw new Error(`Unexpected model: ${name}`); + }), + } as unknown as ConnectionService; + const repository = { + upsert: jest.fn().mockResolvedValue(undefined), + deleteByMatch: jest.fn(), + } as unknown as jest.Mocked; + const builder = { + buildFragment: jest.fn().mockReturnValue({ + matchCard: {}, + records: [], + gameDetails: [], + userIds: [], + championIds: [], + gameCreationMin: 1, + gameCreationMax: 2, + }), + } as unknown as jest.Mocked; + 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; + const builder = { + buildFragment: jest.fn().mockReturnValue({ + matchCard: {}, + records: [], + gameDetails: [], + userIds: [], + championIds: [], + gameCreationMin: 1, + gameCreationMax: 2, + }), + } as unknown as jest.Mocked; + 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; + const builder = { + buildFragment: jest.fn(), + } as unknown as jest.Mocked; + 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(value: T, lean = true) { + const query = { + lean: jest.fn(), + exec: jest.fn().mockResolvedValue(value), + }; + query.lean.mockReturnValue(query); + return lean ? query : { exec: query.exec }; +} + +function timelineFrame(timestamp = 0) { + return { + timestamp, + events: [], + participantFrames: { + '1': { + participantId: 1, + totalGold: 500, + xp: 0, + minionsKilled: 0, + jungleMinionsKilled: 0, + }, + }, + }; +} diff --git a/apps/api/src/modules/community-stats/match-stats.service.ts b/apps/api/src/modules/community-stats/match-stats.service.ts index 00381a9d..6978276a 100644 --- a/apps/api/src/modules/community-stats/match-stats.service.ts +++ b/apps/api/src/modules/community-stats/match-stats.service.ts @@ -1,31 +1,65 @@ -import { Injectable } from '@nestjs/common'; +import { Injectable, Logger } from '@nestjs/common'; import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; import type { MatchDocument } from '../global/database/schema'; -import type { RiotMatchDto } from '../riot/riot.types'; +import { RiotMatchService } from '../riot/riot-match.service'; +import { + RIOT_REGIONAL_ROUTES, + type RiotMatchDto, + type RiotMatchTimelineDto, + type RiotRegionalRoute, +} from '../riot/riot.types'; import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder'; import { MatchStatsRepository } from './match-stats.repository'; import { MATCH_STATS_BUILDER_VERSION } from './match-stats.types'; @Injectable() export class MatchStatsService { + private readonly logger = new Logger(MatchStatsService.name); + constructor( private readonly connectionService: ConnectionService, private readonly repository: MatchStatsRepository, private readonly builder: MatchStatsFragmentBuilder, + private readonly riotMatchService: RiotMatchService, ) {} - public async buildAndUpsert(matchId: mongoose.Types.ObjectId): Promise { + public async buildAndUpsert( + matchId: mongoose.Types.ObjectId, + options: { includeTimeline?: boolean; sourceRevision?: number } = {}, + ): Promise { 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) @@ -41,7 +75,56 @@ export class MatchStatsService { const rawByRiotMatchId = new Map( riotDocs.map((doc) => [doc.matchId, doc.raw as unknown as RiotMatchDto]), ); - const fragment = this.builder.buildFragment({ match, rawByRiotMatchId }); + const timelineByRiotMatchId = new Map(); + for (const doc of riotDocs) { + if (isUsableRiotMatchTimeline(doc.timeline, doc.raw)) { + timelineByRiotMatchId.set(doc.matchId, doc.timeline); + } + } + if ( + options.includeTimeline && + riotDocs.length > 0 && + timelineByRiotMatchId.size < riotDocs.length + ) { + const region = await this.resolveRiotRegion(match.communityId); + for (const doc of riotDocs) { + if (timelineByRiotMatchId.has(doc.matchId)) continue; + try { + const timeline = await this.riotMatchService.getMatchTimeline( + doc.matchId, + { region }, + ); + if (!isUsableRiotMatchTimeline(timeline, doc.raw)) { + this.logger.warn( + `Ignored unusable match timeline for ${doc.matchId}.`, + ); + continue; + } + await RiotMatchModel.updateOne( + { matchId: doc.matchId }, + { + $set: { + timeline: timeline as unknown as Record, + timelineFetchedAt: new Date(), + }, + }, + ).exec(); + timelineByRiotMatchId.set(doc.matchId, timeline); + } catch (error) { + this.logger.warn( + `Failed to fetch match timeline for ${doc.matchId}: ${ + error instanceof Error ? error.message : error + }`, + ); + } + } + } + + const fragment = this.builder.buildFragment({ + match: sourceMatch, + rawByRiotMatchId, + timelineByRiotMatchId, + }); await this.repository.upsert({ matchId: match._id, @@ -56,7 +139,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 { @@ -76,7 +171,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 }) @@ -101,4 +199,276 @@ export class MatchStatsService { Boolean(match.result?.games?.length) ); } + + private async resolveRiotRegion( + communityId: mongoose.Types.ObjectId, + ): Promise { + const CommunityModel = await this.connectionService.getModel('community'); + const community = await CommunityModel.findById(communityId) + .select({ riotRegion: 1 }) + .lean() + .exec(); + const region = community?.riotRegion; + return RIOT_REGIONAL_ROUTES.includes(region as RiotRegionalRoute) + ? (region as RiotRegionalRoute) + : 'asia'; + } + + private async removeFragmentIfSourceChanged( + matchId: mongoose.Types.ObjectId, + source: + | { + sourceCompetitionId: mongoose.Types.ObjectId; + sourceRevision: number; + } + | undefined, + ): Promise { + const [MatchModel, CompetitionModel] = await Promise.all([ + this.connectionService.getModel('match'), + this.connectionService.getModel('competition'), + ]); + const [currentMatch, currentCompetition] = await Promise.all([ + MatchModel.findById(matchId).exec(), + CompetitionModel.findOne({ + matchId, + ...(source + ? { + _id: source.sourceCompetitionId, + revision: source.sourceRevision, + } + : {}), + }) + .lean() + .exec(), + ]); + + if (source) { + if (!currentMatch || !currentCompetition) { + await this.repository.deleteByMatch(matchId, { + sourceCompetitionId: source.sourceCompetitionId, + sourceRevision: source.sourceRevision, + }); + } + return; + } + + if (!currentMatch || currentCompetition) { + await this.repository.deleteLegacyByMatch(matchId); + } + } +} + +function isUsableRiotMatchTimeline( + value: unknown, + rawMatch: unknown, +): value is RiotMatchTimelineDto { + if ( + !isRecord(value) || + !isRecord(value.info) || + !isRecord(rawMatch) || + !isRecord(rawMatch.info) + ) { + return false; + } + const frameInterval = finiteNumber(value.info.frameInterval); + const gameDuration = finiteNumber(rawMatch.info.gameDuration); + const frames = value.info.frames; + if ( + frameInterval === undefined || + frameInterval <= 0 || + gameDuration === undefined || + gameDuration < 0 || + !Array.isArray(frames) || + frames.length === 0 || + !frames.every(isUsableTimelineFrame) + ) { + return false; + } + + const lastTimestamp = Math.max( + ...frames.map((frame) => (frame as { timestamp: number }).timestamp), + ); + return Math.abs(gameDuration * 1_000 - lastTimestamp) < frameInterval; +} + +function isUsableTimelineFrame(value: unknown): boolean { + if ( + !isRecord(value) || + finiteNumber(value.timestamp) === undefined || + !Array.isArray(value.events) || + !value.events.every( + (event) => + isRecord(event) && + typeof event.type === 'string' && + finiteNumber(event.timestamp) !== undefined, + ) || + !isRecord(value.participantFrames) + ) { + return false; + } + const participantFrames = Object.values(value.participantFrames); + return ( + participantFrames.length > 0 && + participantFrames.every( + (participantFrame) => + isRecord(participantFrame) && + finiteNumber(participantFrame.participantId) !== undefined && + finiteNumber(participantFrame.totalGold) !== undefined && + finiteNumber(participantFrame.xp) !== undefined, + ) + ); +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} + +function competitionStatsSource( + match: MatchDocument, + competition: { + _id: mongoose.Types.ObjectId; + revision: number; + projectorVersion: number; + teams: unknown[]; + projection: Record; + }, +): { + match: MatchDocument; + riotMatchIds: string[]; + sourceCompetitionId: mongoose.Types.ObjectId; + sourceRevision: number; + projectorVersion: number; +} { + const teamIndexById = new Map(); + 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(); + 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; } diff --git a/apps/api/src/modules/community-stats/match-stats.types.ts b/apps/api/src/modules/community-stats/match-stats.types.ts index ed0901e3..a864c124 100644 --- a/apps/api/src/modules/community-stats/match-stats.types.ts +++ b/apps/api/src/modules/community-stats/match-stats.types.ts @@ -4,7 +4,7 @@ import type { } from '../global/database/schema'; import type { InternalMatchCardView } from './community-stats.types'; -export const MATCH_STATS_BUILDER_VERSION = 1; +export const MATCH_STATS_BUILDER_VERSION = 10; export type InternalRecord = MatchStatsRecord; export type InternalGameDetail = MatchStatsGameDetail; diff --git a/apps/api/src/modules/competition/competition-bootstrap.service.spec.ts b/apps/api/src/modules/competition/competition-bootstrap.service.spec.ts new file mode 100644 index 00000000..5a26cdf3 --- /dev/null +++ b/apps/api/src/modules/competition/competition-bootstrap.service.spec.ts @@ -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>({ + 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; + competitionResults?: Array | 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 = { + 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(value: T) { + return { exec: jest.fn().mockResolvedValue(value) }; +} + +function rejectedQuery(error: Error) { + return { exec: jest.fn().mockRejectedValue(error) }; +} diff --git a/apps/api/src/modules/competition/competition-bootstrap.service.ts b/apps/api/src/modules/competition/competition-bootstrap.service.ts new file mode 100644 index 00000000..3304b8b3 --- /dev/null +++ b/apps/api/src/modules/competition/competition-bootstrap.service.ts @@ -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>, + ) { + 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 { + 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, +): 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(); + 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(); + const assignedUserIds = new Set(); + const memberCounts = new Set(); + 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(); + const seedNumbers = new Set(); + 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, +): 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 { + 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'), + ); +} diff --git a/apps/api/src/modules/competition/competition-command.service.spec.ts b/apps/api/src/modules/competition/competition-command.service.spec.ts new file mode 100644 index 00000000..1db0db1e --- /dev/null +++ b/apps/api/src/modules/competition/competition-command.service.spec.ts @@ -0,0 +1,787 @@ +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, + { $inc: Record; $set: Record }, + Record, + ]; + expect(casFilter).toEqual({ _id: COMPETITION_ID, revision: 7 }); + expect(casUpdate).toMatchObject({ + $inc: { revision: 1 }, + $set: { projection: PROJECTION }, + }); + expect(casOptions).toMatchObject({ + returnDocument: 'after', + session: harness.session, + }); + expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1); + expect(harness.session.commitTransaction).not.toHaveBeenCalled(); + }); + + it('replays an exact Idempotency-Key request without appending a second fact', async () => { + const harness = createHarness(); + let storedReceipt: Record | null = null; + harness.outboxModel.findOne.mockImplementation(() => + queryResult(storedReceipt), + ); + harness.outboxModel.insertMany.mockImplementation( + ([receipt]: Array>) => { + 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 | null = null; + harness.outboxModel.findOne.mockImplementation(() => + queryResult(committedReceipt), + ); + harness.factModel.insertMany.mockImplementationOnce( + async ([fact]: Array>) => { + 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, + ]; + 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; + const projectedMapping = projectedFact.mapping as Record; + 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, + { $set: Record }, + Record, + ]; + 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, + { $set: Record }, + Record, + ]; + 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, + ]; + 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, + Array>, + ]; + 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 | null; + competition?: Record; + facts?: Array>; + assignments?: Array>; + } = {}, +) { + 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 = { + 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(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, + sourceB: Record, + ) => ({ + 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', + }, + ], + }; +} diff --git a/apps/api/src/modules/competition/competition-command.service.ts b/apps/api/src/modules/competition/competition-command.service.ts new file mode 100644 index 00000000..9a7c86fc --- /dev/null +++ b/apps/api/src/modules/competition/competition-command.service.ts @@ -0,0 +1,1062 @@ +import { Injectable } from '@nestjs/common'; +import { createHash } from 'node:crypto'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import type { Competition, CompetitionOutbox } from './competition.schema'; +import { CompetitionCommandError } from './competition.errors'; +import { projectCompetition } from './domain/competition-projector'; +import { + assertReversalPreview, + buildReversalFacts, + previewSeriesReversal as planSeriesReversal, + type SeriesReversalMode, + type SeriesReversalPreview, +} from './domain/competition-reversal'; + +type PersistenceId = string | mongoose.Types.ObjectId; +const COMMAND_TRANSACTION_ATTEMPTS = 3; + +export type CompetitionCommandActor = + | { type: 'system' } + | { type: 'user'; userId: PersistenceId } + | { type: 'migration'; migrationRunId: string }; + +export interface AcceptGameCommand { + competitionId: PersistenceId; + expectedRevision: number; + idempotencyKey: string; + actor: CompetitionCommandActor; + occurredAt?: Date; + gameId: PersistenceId; + seriesId: PersistenceId; + gameSlotId: PersistenceId; + ordinal: number; + evidence: Readonly>; + mapping: Readonly>; + startedAt?: Date; + durationSeconds?: number; + participants?: readonly Readonly>[]; + tournamentCode?: { + tournamentCodeId: PersistenceId; + riotMatchId: string; + }; +} + +export type SeriesAdjudicationDecision = + | { + type: 'walkover' | 'forfeit' | 'administrative'; + winnerTeamId: PersistenceId; + } + | { type: 'administrative-draw' }; + +export interface AdjudicateSeriesCommand { + competitionId: PersistenceId; + expectedRevision: number; + idempotencyKey: string; + actor: CompetitionCommandActor; + occurredAt?: Date; + seriesId: PersistenceId; + decision: SeriesAdjudicationDecision; + reason: string; +} + +export interface PreviewSeriesReversalCommand { + competitionId: PersistenceId; + expectedRevision: number; + seriesId: PersistenceId; + mode: SeriesReversalMode; +} + +export interface ReverseSeriesCommand extends PreviewSeriesReversalCommand { + idempotencyKey: string; + actor: CompetitionCommandActor; + occurredAt?: Date; + reason: string; + impactHash: string; +} + +export interface CompetitionCommandResult { + competition: unknown; + commandId: string; + revision: number; + replayed: boolean; +} + +interface CommandEnvelope { + type: 'accept-game' | 'adjudicate-series' | 'reverse-series'; + competitionId: PersistenceId; + expectedRevision: number; + idempotencyKey: string; + actor: CompetitionCommandActor; + occurredAt?: Date; + payload: Readonly>; +} + +interface AssignmentRecord { + seriesId: PersistenceId; + gameSlotId: PersistenceId; + tournamentCodeId: PersistenceId; + state: string; +} + +@Injectable() +export class CompetitionCommandService { + constructor(private readonly connectionService: ConnectionService) {} + + public acceptGame( + command: AcceptGameCommand, + ): Promise { + return this.runCommand({ + type: 'accept-game', + competitionId: command.competitionId, + expectedRevision: command.expectedRevision, + idempotencyKey: command.idempotencyKey, + actor: command.actor, + occurredAt: command.occurredAt, + payload: { + gameId: command.gameId, + seriesId: command.seriesId, + gameSlotId: command.gameSlotId, + ordinal: command.ordinal, + evidence: command.evidence, + mapping: command.mapping, + ...(command.startedAt ? { startedAt: command.startedAt } : {}), + ...(command.durationSeconds === undefined + ? {} + : { durationSeconds: command.durationSeconds }), + ...(command.participants ? { participants: command.participants } : {}), + ...(command.tournamentCode + ? { tournamentCode: command.tournamentCode } + : {}), + }, + }); + } + + public adjudicateSeries( + command: AdjudicateSeriesCommand, + ): Promise { + return this.runCommand({ + type: 'adjudicate-series', + competitionId: command.competitionId, + expectedRevision: command.expectedRevision, + idempotencyKey: command.idempotencyKey, + actor: command.actor, + occurredAt: command.occurredAt, + payload: { + seriesId: command.seriesId, + decision: command.decision, + reason: command.reason.trim(), + }, + }); + } + + public async previewSeriesReversal( + command: PreviewSeriesReversalCommand, + ): Promise { + if ( + !Number.isInteger(command.expectedRevision) || + command.expectedRevision < 0 + ) { + throw invalidCommandError(); + } + const CompetitionModel = + await this.connectionService.getModel('competition'); + const competition = await CompetitionModel.findById(command.competitionId) + .lean() + .exec(); + if (!competition) throw competitionNotFound(command.competitionId); + assertExpectedRevision(competition.revision, command.expectedRevision); + + const [FactModel, AssignmentModel] = await Promise.all([ + this.connectionService.getModel('competitionFact'), + this.connectionService.getModel('tournamentCodeAssignment'), + ]); + const [facts, assignments] = await Promise.all([ + FactModel.find({ competitionId: command.competitionId }) + .sort({ revision: 1, ordinalWithinRevision: 1 }) + .lean() + .exec(), + AssignmentModel.find({ competitionId: command.competitionId }) + .lean() + .exec() as Promise, + ]); + const revisionCheck = await CompetitionModel.findById(command.competitionId) + .lean() + .exec(); + if (!revisionCheck) throw competitionNotFound(command.competitionId); + assertExpectedRevision(revisionCheck.revision, command.expectedRevision); + return planSeriesReversal( + reversalInput(competition, command, facts, assignments), + ); + } + + public async reverseSeries( + command: ReverseSeriesCommand, + ): Promise { + const envelope: CommandEnvelope = { + type: 'reverse-series', + competitionId: command.competitionId, + expectedRevision: command.expectedRevision, + idempotencyKey: command.idempotencyKey, + actor: command.actor, + occurredAt: command.occurredAt, + payload: { + seriesId: command.seriesId, + mode: command.mode, + reason: command.reason.trim(), + impactHash: command.impactHash, + }, + }; + validateEnvelope(envelope); + if (!/^[a-f0-9]{64}$/.test(command.impactHash)) { + throw invalidCommandError(); + } + + let lastRetryableError: unknown; + for ( + let attempt = 1; + attempt <= COMMAND_TRANSACTION_ATTEMPTS; + attempt += 1 + ) { + const session = await this.connectionService.createSession(); + if (!session) { + throw new CompetitionCommandError( + 'COMPETITION_TRANSACTION_UNAVAILABLE', + 'A MongoDB transaction is required for Competition commands.', + 500, + ); + } + + try { + session.startTransaction(); + const [CompetitionModel, FactModel, OutboxModel, AssignmentModel] = + await Promise.all([ + this.connectionService.getModel('competition'), + this.connectionService.getModel('competitionFact'), + this.connectionService.getModel('competitionOutbox'), + this.connectionService.getModel('tournamentCodeAssignment'), + ]); + const requestHash = requestHashFor(envelope); + const commandId = commandIdFor(envelope); + const receipt = await OutboxModel.findOne({ + competitionId: command.competitionId, + idempotencyKey: command.idempotencyKey, + }) + .session(session) + .lean() + .exec(); + if (receipt) { + const replay = await this.replay( + CompetitionModel, + command.competitionId, + requestHash, + receipt, + session, + ); + await session.commitTransaction(); + return replay; + } + + const competition = await CompetitionModel.findById( + command.competitionId, + ) + .session(session) + .lean() + .exec(); + if (!competition) throw competitionNotFound(command.competitionId); + assertExpectedRevision(competition.revision, command.expectedRevision); + + const [existingFacts, assignments] = await Promise.all([ + FactModel.find({ competitionId: command.competitionId }) + .sort({ revision: 1, ordinalWithinRevision: 1 }) + .session(session) + .lean() + .exec(), + AssignmentModel.find({ competitionId: command.competitionId }) + .session(session) + .lean() + .exec() as Promise, + ]); + const input = reversalInput( + competition, + command, + existingFacts, + assignments, + ); + const preview = assertReversalPreview(input, command.impactHash); + const nextRevision = command.expectedRevision + 1; + const recordedAt = new Date(); + const occurredAt = command.occurredAt ?? recordedAt; + const rawFacts = buildReversalFacts({ + preview, + facts: input.facts, + competitionId: idString(command.competitionId), + commandId, + nextRevision, + actor: toPlain(command.actor) as Readonly>, + reason: command.reason.trim(), + occurredAt, + }); + const reversalFacts = rawFacts.map((rawFact) => + persistenceReversalFact(rawFact, command, commandId, requestHash), + ); + const projection = projectCompetition({ + competitionId: idString(command.competitionId), + revision: nextRevision, + projectorVersion: competition.projectorVersion, + teams: toPlain(competition.teams) as never, + format: toPlain(competition.format) as never, + seriesGraph: toPlain(competition.seriesGraph) as never, + facts: [...existingFacts, ...reversalFacts].map(factForProjection), + }); + + await FactModel.insertMany(reversalFacts, { session }); + const updated = await CompetitionModel.findOneAndUpdate( + { _id: command.competitionId, revision: command.expectedRevision }, + { + $inc: { revision: 1 }, + $set: { + projection, + projectorVersion: competition.projectorVersion, + phase: projection.phase, + }, + }, + { returnDocument: 'after', runValidators: true, session }, + ) + .lean() + .exec(); + if (!updated) throw staleRevisionError(command.expectedRevision); + + await this.applyReversalAssignments( + command.competitionId, + competition.matchId, + preview, + assignments, + commandId, + recordedAt, + session, + ); + await OutboxModel.insertMany( + [ + buildOutbox( + command.competitionId, + envelope, + commandId, + requestHash, + nextRevision, + reversalFacts, + projection, + updated, + recordedAt, + ), + ], + { session }, + ); + await session.commitTransaction(); + return { + competition: updated, + commandId, + revision: nextRevision, + replayed: false, + }; + } catch (error) { + await session.abortTransaction().catch(() => undefined); + if ( + attempt < COMMAND_TRANSACTION_ATTEMPTS && + isRetryableCommandTransactionError(error) + ) { + lastRetryableError = error; + continue; + } + throw error; + } finally { + await session.endSession(); + } + } + throw lastRetryableError; + } + + private async runCommand( + command: CommandEnvelope, + ): Promise { + validateEnvelope(command); + let lastRetryableError: unknown; + for ( + let attempt = 1; + attempt <= COMMAND_TRANSACTION_ATTEMPTS; + attempt += 1 + ) { + const session = await this.connectionService.createSession(); + if (!session) { + throw new CompetitionCommandError( + 'COMPETITION_TRANSACTION_UNAVAILABLE', + 'A MongoDB transaction is required for Competition commands.', + 500, + ); + } + + try { + session.startTransaction(); + const CompetitionModel = + await this.connectionService.getModel('competition'); + const FactModel = + await this.connectionService.getModel('competitionFact'); + const OutboxModel = + await this.connectionService.getModel('competitionOutbox'); + const requestHash = requestHashFor(command); + const commandId = commandIdFor(command); + const competitionId = command.competitionId; + + const receipt = await OutboxModel.findOne({ + competitionId, + idempotencyKey: command.idempotencyKey, + }) + .session(session) + .lean() + .exec(); + if (receipt) { + const replay = await this.replay( + CompetitionModel, + competitionId, + requestHash, + receipt, + session, + ); + await session.commitTransaction(); + return replay; + } + + const competition = await CompetitionModel.findById(competitionId) + .session(session) + .lean() + .exec(); + if (!competition) { + throw new CompetitionCommandError( + 'COMPETITION_NOT_FOUND', + 'Competition not found.', + 404, + { competitionId: idString(competitionId) }, + ); + } + assertExpectedRevision(competition.revision, command.expectedRevision); + + const existingFacts = await FactModel.find({ competitionId }) + .sort({ revision: 1, ordinalWithinRevision: 1 }) + .session(session) + .lean() + .exec(); + const nextRevision = command.expectedRevision + 1; + const recordedAt = new Date(); + const fact = buildFact( + command, + commandId, + requestHash, + nextRevision, + recordedAt, + ); + const projection = projectCompetition({ + competitionId: idString(competitionId), + revision: nextRevision, + projectorVersion: competition.projectorVersion, + teams: toPlain(competition.teams) as never, + format: toPlain(competition.format) as never, + seriesGraph: toPlain(competition.seriesGraph) as never, + facts: [...existingFacts, fact].map(factForProjection), + }); + + await FactModel.insertMany([fact], { session }); + const updated = await CompetitionModel.findOneAndUpdate( + { _id: competitionId, revision: command.expectedRevision }, + { + $inc: { revision: 1 }, + $set: { + projection, + projectorVersion: competition.projectorVersion, + phase: projection.phase, + }, + }, + { returnDocument: 'after', runValidators: true, session }, + ) + .lean() + .exec(); + if (!updated) { + throw staleRevisionError(command.expectedRevision); + } + + await this.applyTournamentCode(command, commandId, recordedAt, session); + await OutboxModel.insertMany( + [ + buildOutbox( + competitionId, + command, + commandId, + requestHash, + nextRevision, + fact, + projection, + updated, + recordedAt, + ), + ], + { session }, + ); + await session.commitTransaction(); + return { + competition: updated, + commandId, + revision: nextRevision, + replayed: false, + }; + } catch (error) { + await session.abortTransaction().catch(() => undefined); + if ( + attempt < COMMAND_TRANSACTION_ATTEMPTS && + isRetryableCommandTransactionError(error) + ) { + lastRetryableError = error; + continue; + } + throw error; + } finally { + await session.endSession(); + } + } + throw lastRetryableError; + } + + private async replay( + CompetitionModel: mongoose.Model, + competitionId: PersistenceId, + requestHash: string, + receipt: Pick< + CompetitionOutbox, + 'requestHash' | 'idempotencyKey' | 'commandId' | 'revision' | 'payload' + >, + session: mongoose.ClientSession, + ): Promise { + if (receipt.requestHash !== requestHash) { + throw new CompetitionCommandError( + 'IDEMPOTENCY_KEY_CONFLICT', + 'The Idempotency-Key was already used for a different command payload.', + 409, + { idempotencyKey: receipt.idempotencyKey }, + ); + } + const competition = await CompetitionModel.findById(competitionId) + .session(session) + .lean() + .exec(); + if (!competition) { + throw new CompetitionCommandError( + 'COMPETITION_NOT_FOUND', + 'Competition not found.', + 404, + { competitionId: idString(competitionId) }, + ); + } + const responseSnapshot = receipt.payload; + const replayCompetition = { + ...competition, + revision: receipt.revision, + projection: responseSnapshot.projection, + phase: responseSnapshot.phase, + ...(responseSnapshot.updatedAt === undefined + ? {} + : { updatedAt: responseSnapshot.updatedAt }), + }; + return { + competition: replayCompetition, + commandId: receipt.commandId, + revision: receipt.revision, + replayed: true, + }; + } + + private async applyTournamentCode( + command: CommandEnvelope, + commandId: string, + recordedAt: Date, + session: mongoose.ClientSession, + ): Promise { + const tournamentCode = command.payload.tournamentCode as + | { tournamentCodeId: PersistenceId; riotMatchId: string } + | undefined; + if (!tournamentCode) return; + + const AssignmentModel = (await this.connectionService.getModel( + 'tournamentCodeAssignment', + )) as mongoose.Model; + const assignmentResult = await AssignmentModel.updateOne( + { + competitionId: command.competitionId, + seriesId: command.payload.seriesId, + gameSlotId: command.payload.gameSlotId, + tournamentCodeId: tournamentCode.tournamentCodeId, + state: 'reserved', + }, + { + $set: { + state: 'used', + usedAt: recordedAt, + riotMatchId: tournamentCode.riotMatchId, + commandId, + }, + }, + { session }, + ); + if (assignmentResult.modifiedCount !== 1) { + throw tournamentCodeConflict(command, tournamentCode.tournamentCodeId); + } + + const TournamentCodeModel = (await this.connectionService.getModel( + 'tournamentCode', + )) as mongoose.Model; + const codeResult = await TournamentCodeModel.updateOne( + { _id: tournamentCode.tournamentCodeId, state: 'reserved' }, + { + $set: { + state: 'used', + usedAt: recordedAt, + riotMatchId: tournamentCode.riotMatchId, + }, + }, + { session }, + ); + if (codeResult.modifiedCount !== 1) { + throw tournamentCodeConflict(command, tournamentCode.tournamentCodeId); + } + } + + private async applyReversalAssignments( + competitionId: PersistenceId, + matchId: PersistenceId, + preview: SeriesReversalPreview, + assignments: AssignmentRecord[], + commandId: string, + recordedAt: Date, + session: mongoose.ClientSession, + ): Promise { + const impactedSlotIds = new Set(preview.impact.gameSlotIds); + const impacted = assignments.filter( + (assignment) => + impactedSlotIds.has(idString(assignment.gameSlotId)) && + (assignment.state === 'reserved' || assignment.state === 'used'), + ); + if (impacted.length === 0) return; + + const gameSlotIds = impacted.map(({ gameSlotId }) => + persistenceObjectId(gameSlotId), + ); + const codeIds = impacted.map(({ tournamentCodeId }) => + persistenceObjectId(tournamentCodeId), + ); + const AssignmentModel = (await this.connectionService.getModel( + 'tournamentCodeAssignment', + )) as mongoose.Model; + await AssignmentModel.updateMany( + { + competitionId, + gameSlotId: { $in: gameSlotIds }, + state: { $in: ['reserved', 'used'] }, + }, + reversalStatePipeline(recordedAt, commandId), + { session }, + ); + const TournamentCodeModel = (await this.connectionService.getModel( + 'tournamentCode', + )) as mongoose.Model; + await TournamentCodeModel.updateMany( + { + _id: { $in: codeIds }, + state: { $in: ['reserved', 'used'] }, + }, + tournamentCodeReversalStatePipeline(recordedAt), + { session }, + ); + const MatchModel = (await this.connectionService.getModel( + 'match', + )) as mongoose.Model; + await MatchModel.updateOne( + { _id: matchId }, + { $pull: { tournamentCodeIds: { $in: codeIds } } }, + { session }, + ); + } +} + +function validateEnvelope(command: CommandEnvelope): void { + if ( + !Number.isInteger(command.expectedRevision) || + command.expectedRevision < 0 || + command.idempotencyKey.trim().length === 0 || + command.idempotencyKey.length > 200 || + ((command.type === 'adjudicate-series' || + command.type === 'reverse-series') && + String(command.payload.reason).trim().length === 0) + ) { + throw invalidCommandError(); + } +} + +function assertExpectedRevision(actual: number, expected: number): void { + if (actual !== expected) { + throw staleRevisionError(expected, actual); + } +} + +function staleRevisionError( + expectedRevision: number, + actualRevision?: number, +): CompetitionCommandError { + return new CompetitionCommandError( + 'STALE_COMPETITION_REVISION', + 'Competition changed after the caller read it.', + 412, + { + expectedRevision, + ...(actualRevision === undefined ? {} : { actualRevision }), + }, + ); +} + +function buildFact( + command: CommandEnvelope, + commandId: string, + requestHash: string, + revision: number, + recordedAt: Date, +): Readonly> { + const factId = deterministicObjectId(commandId, 'fact', 1); + const common = { + _id: factId, + competitionId: command.competitionId, + revision, + ordinalWithinRevision: 1, + commandId, + idempotencyKey: command.idempotencyKey, + requestHash, + schemaVersion: 1, + actor: command.actor, + occurredAt: command.occurredAt ?? recordedAt, + recordedAt, + }; + + if (command.type === 'accept-game') { + return { + ...common, + type: 'game-accepted', + gameId: command.payload.gameId, + seriesId: command.payload.seriesId, + gameSlotId: command.payload.gameSlotId, + ordinal: command.payload.ordinal, + evidence: command.payload.evidence, + mapping: command.payload.mapping, + ...(command.payload.startedAt === undefined + ? {} + : { startedAt: command.payload.startedAt }), + ...(command.payload.durationSeconds === undefined + ? {} + : { durationSeconds: command.payload.durationSeconds }), + ...(command.payload.participants === undefined + ? {} + : { participants: command.payload.participants }), + }; + } + + if (command.type === 'adjudicate-series') { + return { + ...common, + type: 'series-adjudicated', + seriesId: command.payload.seriesId, + decision: command.payload.decision, + reason: command.payload.reason, + }; + } + + throw invalidCommandError(); +} + +function buildOutbox( + competitionId: PersistenceId, + command: CommandEnvelope, + commandId: string, + requestHash: string, + revision: number, + fact: + | Readonly> + | readonly Readonly>[], + projection: unknown, + updatedCompetition: unknown, + recordedAt: Date, +): Readonly> { + const facts: readonly Readonly>[] = Array.isArray( + fact, + ) + ? fact + : [fact]; + return { + eventId: `${commandId}:competition-projected`, + competitionId, + revision, + commandId, + idempotencyKey: command.idempotencyKey, + requestHash, + type: 'competition.projection-updated', + payload: { + competitionId: idString(competitionId), + sourceRevision: revision, + factIds: facts.map((entry) => idString(entry._id as PersistenceId)), + projection, + phase: + isRecord(projection) && typeof projection.phase === 'string' + ? projection.phase + : undefined, + updatedAt: isRecord(updatedCompetition) + ? updatedCompetition.updatedAt + : undefined, + }, + state: 'pending', + attemptCount: 0, + availableAt: recordedAt, + }; +} + +function factForProjection( + fact: Readonly>, +): Readonly> { + const plain = toPlain(fact) as Readonly>; + const sourceId = fact.id ?? fact._id; + return { + ...plain, + id: idString(sourceId as PersistenceId), + }; +} + +function requestHashFor(command: CommandEnvelope): string { + return sha256({ + type: command.type, + competitionId: command.competitionId, + actor: command.actor, + payload: command.payload, + }); +} + +function commandIdFor(command: CommandEnvelope): string { + return `cmpcmd_${sha256({ + competitionId: command.competitionId, + idempotencyKey: command.idempotencyKey, + }).slice(0, 32)}`; +} + +function deterministicObjectId( + commandId: string, + entity: string, + ordinal: number, +): mongoose.Types.ObjectId { + return new mongoose.Types.ObjectId( + sha256([commandId, entity, ordinal]).slice(0, 24), + ); +} + +function sha256(value: unknown): string { + return createHash('sha256').update(canonicalJson(value)).digest('hex'); +} + +function canonicalJson(value: unknown): string { + return JSON.stringify(toCanonical(value)); +} + +function toCanonical(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(toCanonical); + if (value && typeof value === 'object') { + return Object.fromEntries( + Object.entries(value as Readonly>) + .filter(([, child]) => child !== undefined) + .sort(([left], [right]) => left.localeCompare(right)) + .map(([key, child]) => [key, toCanonical(child)]), + ); + } + return value; +} + +function toPlain(value: unknown): unknown { + return toCanonical(value); +} + +function isRecord(value: unknown): value is Readonly> { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function idString(value: PersistenceId): string { + return value instanceof mongoose.Types.ObjectId + ? value.toHexString() + : String(value); +} + +function tournamentCodeConflict( + command: CommandEnvelope, + tournamentCodeId: PersistenceId, +): CompetitionCommandError { + return new CompetitionCommandError( + 'TOURNAMENT_CODE_ASSIGNMENT_CONFLICT', + 'The Tournament Code assignment is no longer reserved for this GameSlot.', + 409, + { + competitionId: idString(command.competitionId), + gameSlotId: idString(command.payload.gameSlotId as PersistenceId), + tournamentCodeId: idString(tournamentCodeId), + }, + ); +} + +function reversalInput( + competition: Pick, + command: PreviewSeriesReversalCommand, + facts: readonly unknown[], + assignments: readonly AssignmentRecord[], +) { + return { + competitionId: idString(command.competitionId), + revision: competition.revision, + seriesId: idString(command.seriesId), + mode: command.mode, + graph: toPlain(competition.seriesGraph) as never, + facts: facts.map((fact) => + factForProjection(fact as Readonly>), + ), + assignments: assignments.map((assignment) => ({ + seriesId: idString(assignment.seriesId), + gameSlotId: idString(assignment.gameSlotId), + state: String(assignment.state), + })), + }; +} + +function persistenceReversalFact( + rawFact: Record, + command: ReverseSeriesCommand, + commandId: string, + requestHash: string, +): Readonly> { + const { id, ...fields } = rawFact; + return { + ...fields, + _id: persistenceObjectId(id as PersistenceId), + competitionId: command.competitionId, + commandId, + idempotencyKey: command.idempotencyKey, + requestHash, + ...(fields.gameAcceptedFactId === undefined + ? {} + : { + gameAcceptedFactId: persistenceObjectId( + fields.gameAcceptedFactId as PersistenceId, + ), + }), + ...(fields.adjudicationFactId === undefined + ? {} + : { + adjudicationFactId: persistenceObjectId( + fields.adjudicationFactId as PersistenceId, + ), + }), + }; +} + +function reversalStatePipeline( + recordedAt: Date, + commandId?: string, +): mongoose.PipelineStage[] { + return [ + { + $set: { + state: { + $cond: [{ $eq: ['$state', 'reserved'] }, 'released', 'voided'], + }, + releasedAt: { + $cond: [{ $eq: ['$state', 'reserved'] }, recordedAt, '$$REMOVE'], + }, + voidedAt: { + $cond: [{ $eq: ['$state', 'used'] }, recordedAt, '$$REMOVE'], + }, + ...(commandId ? { commandId } : {}), + }, + }, + ]; +} + +function tournamentCodeReversalStatePipeline( + recordedAt: Date, +): mongoose.PipelineStage[] { + return [ + { + $set: { + state: { + $cond: [{ $eq: ['$state', 'reserved'] }, 'released', 'voided'], + }, + releasedAt: { + $cond: [{ $eq: ['$state', 'reserved'] }, recordedAt, '$releasedAt'], + }, + 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'], + }, + }, + }, + ]; +} + +function persistenceObjectId(value: PersistenceId): PersistenceId { + if (value instanceof mongoose.Types.ObjectId) return value; + return mongoose.isValidObjectId(value) + ? new mongoose.Types.ObjectId(value) + : value; +} + +function isRetryableCommandTransactionError(error: unknown): boolean { + const candidate = error as { + code?: number; + codeName?: string; + hasErrorLabel?: (label: string) => boolean; + }; + return Boolean( + candidate?.code === 11_000 || + candidate?.code === 112 || + candidate?.codeName === 'WriteConflict' || + candidate?.hasErrorLabel?.('TransientTransactionError') || + candidate?.hasErrorLabel?.('UnknownTransactionCommitResult'), + ); +} + +function competitionNotFound( + competitionId: PersistenceId, +): CompetitionCommandError { + return new CompetitionCommandError( + 'COMPETITION_NOT_FOUND', + 'Competition not found.', + 404, + { competitionId: idString(competitionId) }, + ); +} + +function invalidCommandError(): CompetitionCommandError { + return new CompetitionCommandError( + 'INVALID_COMPETITION_COMMAND', + 'Expected revision, valid payload, and a non-empty Idempotency-Key are required.', + 422, + ); +} diff --git a/apps/api/src/modules/competition/competition-query.service.spec.ts b/apps/api/src/modules/competition/competition-query.service.spec.ts new file mode 100644 index 00000000..37f21c07 --- /dev/null +++ b/apps/api/src/modules/competition/competition-query.service.spec.ts @@ -0,0 +1,367 @@ +import { + ConflictException, + ForbiddenException, + NotFoundException, +} from '@nestjs/common'; +import { Types } from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import { CompetitionQueryService } from './competition-query.service'; + +describe('CompetitionQueryService', () => { + it('does not let a public read race the team-build bootstrap workflow', async () => { + const harness = createHarness({ competition: null }); + const service = createService(harness); + + await expect( + service.getCompetition({ + communityId: COMMUNITY_ID, + matchId: MATCH_ID, + }), + ).rejects.toBeInstanceOf(ConflictException); + + expect(harness.matchModel.findOne).toHaveBeenCalledWith({ + _id: MATCH_ID, + communityId: COMMUNITY_ID, + }); + }); + + it('returns an explicit team view with codes only for the callers team', async () => { + const harness = createHarness(); + const service = createService(harness); + + const result = await service.getTeamView({ + communityId: COMMUNITY_ID, + matchId: MATCH_ID, + userId: TEAM_A_USER_ID, + }); + + expect(result).toMatchObject({ + competitionId: COMPETITION_ID.toHexString(), + revision: 4, + teamId: TEAM_A_ID.toHexString(), + activeSeries: [expect.objectContaining({ seriesId: SERIES_ID })], + tournamentCodes: [ + { + gameSlotId: GAME_SLOT_ID, + seriesId: SERIES_ID, + ordinal: 1, + displayNumber: 1, + state: 'reserved', + code: 'TEAM-A-SECRET-CODE', + expiresAt: '2026-07-13T00:00:00.000Z', + }, + ], + }); + expect(JSON.stringify(result)).not.toContain('OPPONENT-SECRET-CODE'); + expect(harness.tournamentCodeModel.find).toHaveBeenCalledWith({ + _id: { $in: [TEAM_A_CODE_ID] }, + state: { $in: ['reserved', 'used'] }, + }); + }); + + it('resolves a team view from an explicit team id without a caller identity', async () => { + const harness = createHarness(); + const service = createService(harness); + + const result = await service.getTeamView({ + communityId: COMMUNITY_ID, + matchId: MATCH_ID, + teamId: TEAM_A_ID, + }); + + expect(result).toMatchObject({ + teamId: TEAM_A_ID.toHexString(), + activeSeries: [expect.objectContaining({ seriesId: SERIES_ID })], + tournamentCodes: [ + expect.objectContaining({ code: 'TEAM-A-SECRET-CODE' }), + ], + }); + expect(JSON.stringify(result)).not.toContain('OPPONENT-SECRET-CODE'); + }); + + it('does not resolve a team view for an unknown team id', async () => { + const service = createService(createHarness()); + + await expect( + service.getTeamView({ + communityId: COMMUNITY_ID, + matchId: MATCH_ID, + teamId: new Types.ObjectId('64c000000000000000000098'), + }), + ).rejects.toBeInstanceOf(NotFoundException); + }); + + it('does not reveal a team view to an authenticated non-participant', async () => { + const service = createService(createHarness()); + + await expect( + service.getTeamView({ + communityId: COMMUNITY_ID, + matchId: MATCH_ID, + userId: new Types.ObjectId('64c000000000000000000099'), + }), + ).rejects.toBeInstanceOf(ForbiddenException); + }); + + it('does not expose a stale code whose active assignment no longer matches', async () => { + const harness = createHarness(); + harness.tournamentCodeModel.find.mockReturnValueOnce(queryResult([])); + const service = createService(harness); + + await expect( + service.getTeamView({ + communityId: COMMUNITY_ID, + matchId: MATCH_ID, + userId: TEAM_A_USER_ID, + }), + ).rejects.toBeInstanceOf(ConflictException); + }); + + it('pages facts in immutable revision order using an opaque cursor', async () => { + const harness = createHarness(); + harness.factModel.find.mockReturnValueOnce( + queryResult([ + factDocument('64c000000000000000000031', 1, 1), + factDocument('64c000000000000000000032', 2, 1), + factDocument('64c000000000000000000033', 3, 1), + ]), + ); + const service = createService(harness); + + const first = await service.listFacts({ + communityId: COMMUNITY_ID, + matchId: MATCH_ID, + limit: 2, + }); + + expect(first.facts).toHaveLength(2); + expect(first.nextCursor).toEqual(expect.any(String)); + expect(first.facts[0]).toMatchObject({ + id: '64c000000000000000000031', + competitionId: COMPETITION_ID.toHexString(), + type: 'game-accepted', + revision: 1, + }); + expect(first.facts[0]).not.toHaveProperty('requestHash'); + expect(first.facts[0]).not.toHaveProperty('idempotencyKey'); + }); +}); + +const COMMUNITY_ID = new Types.ObjectId('64c000000000000000000001'); +const MATCH_ID = new Types.ObjectId('64c000000000000000000002'); +const COMPETITION_ID = new Types.ObjectId('64c000000000000000000003'); +const TEAM_A_ID = new Types.ObjectId('64c000000000000000000004'); +const TEAM_B_ID = new Types.ObjectId('64c000000000000000000005'); +const TEAM_A_USER_ID = new Types.ObjectId('64c000000000000000000006'); +const TEAM_B_USER_ID = new Types.ObjectId('64c000000000000000000007'); +const TEAM_A_CODE_ID = new Types.ObjectId('64c000000000000000000008'); +const TEAM_B_CODE_ID = new Types.ObjectId('64c000000000000000000009'); +const SERIES_ID = 'series-1'; +const GAME_SLOT_ID = 'slot-1'; + +function createService(harness: ReturnType) { + 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 = { + 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(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; +} diff --git a/apps/api/src/modules/competition/competition-query.service.ts b/apps/api/src/modules/competition/competition-query.service.ts new file mode 100644 index 00000000..d5fc5b05 --- /dev/null +++ b/apps/api/src/modules/competition/competition-query.service.ts @@ -0,0 +1,407 @@ +import type { + CompetitionFactView, + CompetitionFactsResponse, + TeamCompetitionViewResponse, +} from '@lolympus/contracts'; +import { + ConflictException, + ForbiddenException, + Injectable, + NotFoundException, + UnprocessableEntityException, +} from '@nestjs/common'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import type { Competition, CompetitionFact } from './competition.schema'; + +type PersistenceId = string | mongoose.Types.ObjectId; +type CompetitionRecord = Competition & { _id: mongoose.Types.ObjectId }; + +export interface CompetitionScope { + communityId: mongoose.Types.ObjectId; + matchId: mongoose.Types.ObjectId; +} + +/** + * A team view is addressed either by the caller's membership (signed-in) or by + * an explicit team id. The explicit form exists so that the team progress page + * stays usable while community members have not all signed in yet. + */ +export type TeamViewScope = CompetitionScope & + ( + | { userId: mongoose.Types.ObjectId; teamId?: undefined } + | { teamId: mongoose.Types.ObjectId; userId?: undefined } + ); + +interface CompetitionProjectionSource { + series?: Array>; + gameSlots?: Array>; +} + +@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 { + const MatchModel = await this.connectionService.getModel('match'); + const match = await MatchModel.findOne({ + _id: scope.matchId, + communityId: scope.communityId, + }) + .lean() + .exec(); + if (!match) throw new NotFoundException('Match not found.'); + if ( + match.status === 'recruiting' || + !Array.isArray(match.teams) || + match.teams.length < 2 + ) { + throw new ConflictException( + 'Competition is unavailable until team building is complete.', + ); + } + + const CompetitionModel = + await this.connectionService.getModel('competition'); + const existing = await CompetitionModel.findOne({ + matchId: scope.matchId, + communityId: scope.communityId, + }) + .lean() + .exec(); + if (existing) return existing as CompetitionRecord; + throw new ConflictException( + 'Competition is still being initialized by the team-build workflow.', + ); + } + + public async getTeamView( + scope: TeamViewScope, + ): Promise { + const competition = (await this.getCompetition(scope)) as Competition & { + _id: PersistenceId; + }; + const requestedTeamId = scope.teamId; + const team = requestedTeamId + ? competition.teams.find(({ teamId }) => sameId(teamId, requestedTeamId)) + : competition.teams.find(({ members }) => + members.some(({ userId }) => sameId(userId, scope.userId)), + ); + if (!team) { + if (requestedTeamId) { + throw new NotFoundException('Competition team not found.'); + } + throw new ForbiddenException( + 'Only a Competition team member may access the team view.', + ); + } + + const projection = competition.projection as CompetitionProjectionSource; + const allSeries = Array.isArray(projection.series) ? projection.series : []; + const teamId = idString(team.teamId); + const activeSeries = allSeries.filter( + (series) => + series.status !== 'completed' && + series.status !== 'inactive' && + Array.isArray(series.entries) && + series.entries.some( + (entry) => + isRecord(entry) && + idString(entry.teamId as PersistenceId) === teamId, + ), + ); + const activeSeriesIds = new Set( + activeSeries.map((series) => idString(series.seriesId as PersistenceId)), + ); + const gameSlots = ( + Array.isArray(projection.gameSlots) ? projection.gameSlots : [] + ).filter((slot) => + activeSeriesIds.has(idString(slot.seriesId as PersistenceId)), + ); + + const AssignmentModel = await this.connectionService.getModel( + 'tournamentCodeAssignment', + ); + const queriedAssignments = await AssignmentModel.find({ + competitionId: competition._id, + seriesId: { $in: [...activeSeriesIds] }, + state: { $in: ['reserved', 'used'] }, + }) + .lean() + .exec(); + // Keep this defensive filter even when the persistence query is mocked or + // changed: an opponent-only assignment must never cross this boundary. + const assignments = queriedAssignments.filter((assignment) => + activeSeriesIds.has(idString(assignment.seriesId)), + ); + const codeIds = assignments.map(({ tournamentCodeId }) => tournamentCodeId); + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const codes = codeIds.length + ? await TournamentCodeModel.find({ + _id: { $in: codeIds }, + state: { $in: ['reserved', 'used'] }, + }) + .lean() + .exec() + : []; + const codeById = new Map(codes.map((code) => [idString(code._id), code])); + const assignmentBySlot = new Map( + assignments.map((assignment) => [ + idString(assignment.gameSlotId), + assignment, + ]), + ); + + return { + competitionId: idString(competition._id) as never, + revision: competition.revision, + phase: competition.phase, + teamId: teamId as never, + activeSeries: toWire(activeSeries) as never, + tournamentCodes: gameSlots.map((slot) => { + const gameSlotId = idString(slot.id as PersistenceId); + const assignment = assignmentBySlot.get(gameSlotId); + const code = assignment + ? codeById.get(idString(assignment.tournamentCodeId)) + : undefined; + if ( + assignment && + (!code || + code.state !== assignment.state || + !code.matchId || + !sameId(code.matchId, competition.matchId)) + ) { + throw new ConflictException( + 'Tournament Code assignment is inconsistent and cannot be exposed.', + ); + } + return { + gameSlotId: gameSlotId as never, + seriesId: idString(slot.seriesId as PersistenceId) as never, + ordinal: numberValue(slot.ordinal), + displayNumber: numberValue(slot.displayNumber), + state: + assignment?.state === 'reserved' || assignment?.state === 'used' + ? assignment.state + : 'pending', + code: typeof code?.code === 'string' ? code.code : null, + expiresAt: code?.expiresAt ? isoDate(code.expiresAt) : null, + }; + }), + }; + } + + public async listFacts( + scope: CompetitionScope & { cursor?: string; limit?: number }, + ): Promise { + 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 { + 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}.`); +} diff --git a/apps/api/src/modules/competition/competition.controller.spec.ts b/apps/api/src/modules/competition/competition.controller.spec.ts new file mode 100644 index 00000000..9b98e109 --- /dev/null +++ b/apps/api/src/modules/competition/competition.controller.spec.ts @@ -0,0 +1,411 @@ +import { HttpException } from '@nestjs/common'; +import { Types } from 'mongoose'; +import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from '../auth/allow-public-access.decorator'; +import { ROLES_KEY } from '../auth/roles.decorator'; +import { CompetitionCommandService } from './competition-command.service'; +import { CompetitionController } from './competition.controller'; +import { CompetitionQueryService } from './competition-query.service'; + +describe('CompetitionController', () => { + it('marks the read endpoints public and writes a revision ETag', async () => { + const { controller, queryService } = createHarness(); + const response = { setHeader: jest.fn() }; + + const result = await controller.getDetail( + COMMUNITY_ID, + MATCH_ID, + response as never, + ); + + for (const method of ['getDetail', 'getTeamView'] as const) { + expect( + Reflect.getMetadata( + METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, + CompetitionController.prototype[method], + ), + ).toBe(true); + } + expect(response.setHeader).toHaveBeenCalledWith('ETag', '"7"'); + expect(result).toMatchObject({ revision: 7 }); + expect(queryService.getCompetition).toHaveBeenCalledWith({ + communityId: COMMUNITY_ID, + matchId: MATCH_ID, + }); + }); + + it('reads a team view by explicit team id without an authenticated caller', async () => { + const { controller, queryService } = createHarness(); + queryService.getTeamView.mockResolvedValue({ revision: 7 }); + const response = { setHeader: jest.fn() }; + + const result = await controller.getTeamView( + undefined, + COMMUNITY_ID, + MATCH_ID, + TEAM_A_ID.toHexString(), + response as never, + ); + + expect(queryService.getTeamView).toHaveBeenCalledWith({ + communityId: COMMUNITY_ID, + matchId: MATCH_ID, + teamId: TEAM_A_ID, + }); + expect(response.setHeader).toHaveBeenCalledWith('ETag', '"7"'); + expect(result).toMatchObject({ revision: 7 }); + }); + + it('falls back to the membership-scoped team view for a signed-in caller', async () => { + const { controller, queryService } = createHarness(); + queryService.getTeamView.mockResolvedValue({ revision: 7 }); + + await controller.getTeamView(adminUser(), COMMUNITY_ID, MATCH_ID); + + expect(queryService.getTeamView).toHaveBeenCalledWith({ + communityId: COMMUNITY_ID, + matchId: MATCH_ID, + userId: ADMIN_ID, + }); + }); + + it('rejects an anonymous team view request that names no team', async () => { + const { controller, queryService } = createHarness(); + + await expect( + controller.getTeamView(undefined, COMMUNITY_ID, MATCH_ID), + ).rejects.toMatchObject({ + status: 401, + response: { error: { code: 'COMPETITION_TEAM_UNIDENTIFIED' } }, + }); + expect(queryService.getTeamView).not.toHaveBeenCalled(); + }); + + it('rejects a malformed team id', async () => { + const { controller, queryService } = createHarness(); + + await expect( + controller.getTeamView(undefined, COMMUNITY_ID, MATCH_ID, 'not-an-id'), + ).rejects.toMatchObject({ + status: 422, + response: { error: { code: 'INVALID_COMPETITION_REQUEST' } }, + }); + expect(queryService.getTeamView).not.toHaveBeenCalled(); + }); + + it('protects audit and mutation endpoints with admin roles', () => { + for (const method of [ + 'listFacts', + 'acceptGame', + 'adjudicateSeries', + 'previewReversal', + 'reverseSeries', + ] as const) { + expect( + Reflect.getMetadata(ROLES_KEY, CompetitionController.prototype[method]), + ).toEqual(['owner', 'admin']); + } + }); + + it('requires If-Match and Idempotency-Key for a mutation', async () => { + const { controller } = createHarness(); + + await expect( + controller.acceptGame( + adminUser(), + COMMUNITY_ID, + MATCH_ID, + undefined, + undefined, + acceptGameBody(), + ), + ).rejects.toMatchObject({ + status: 422, + response: { + error: { code: 'INVALID_COMPETITION_COMMAND_HEADERS' }, + }, + }); + }); + + it('passes revision, idempotency and the authenticated actor to accept-game', async () => { + const { controller, commandService } = createHarness(); + + await controller.acceptGame( + adminUser(), + COMMUNITY_ID, + MATCH_ID, + 'W/"7"', + 'operator:accept:1', + acceptGameBody(), + ); + + expect(commandService.acceptGame).toHaveBeenCalledWith( + expect.objectContaining({ + expectedRevision: 7, + idempotencyKey: 'operator:accept:1', + }), + ); + const accepted = commandService.acceptGame.mock.calls[0][0]; + expect(accepted.competitionId.toHexString()).toBe( + COMPETITION_ID.toHexString(), + ); + expect(accepted.actor.userId.toHexString()).toBe(ADMIN_ID.toHexString()); + expect(accepted.gameId.toHexString()).toBe(GAME_ID.toHexString()); + expect(accepted.seriesId.toHexString()).toBe(SERIES_ID); + expect(accepted.gameSlotId.toHexString()).toBe(GAME_SLOT_ID.toHexString()); + }); + + it('maps command conflicts to the explicit error envelope', async () => { + const { controller, commandService } = createHarness(); + commandService.adjudicateSeries.mockRejectedValue({ + code: 'IDEMPOTENCY_KEY_CONFLICT', + message: 'duplicate key with another payload', + httpStatus: 409, + details: { idempotencyKey: 'same-key' }, + }); + + let thrown: unknown; + try { + await controller.adjudicateSeries( + adminUser(), + COMMUNITY_ID, + MATCH_ID, + new Types.ObjectId(SERIES_ID), + '"7"', + 'same-key', + { + decision: { type: 'administrative-draw' }, + reason: '운영 판단', + }, + ); + } catch (error) { + thrown = error; + } + + expect(thrown).toBeInstanceOf(HttpException); + expect(thrown).toMatchObject({ + status: 409, + response: { + error: { + code: 'IDEMPOTENCY_KEY_CONFLICT', + details: { idempotencyKey: 'same-key' }, + }, + }, + }); + }); + + it.each([ + { + source: { + code: 'STALE_COMPETITION_REVISION', + message: 'stale', + httpStatus: 412, + }, + status: 412, + }, + { + source: { + code: 'GAME_TEAM_MISMATCH', + message: 'invalid evidence mapping', + }, + status: 422, + }, + ])('maps $source.code to HTTP $status', async ({ source, status }) => { + const { controller, commandService } = createHarness(); + commandService.acceptGame.mockRejectedValue(source); + + await expect( + controller.acceptGame( + adminUser(), + COMMUNITY_ID, + MATCH_ID, + '"7"', + `operator:error:${status}`, + acceptGameBody(), + ), + ).rejects.toMatchObject({ + status, + response: { error: { code: source.code } }, + }); + }); + + it('returns an explicit 422 envelope for an invalid command body', async () => { + const { controller, commandService } = createHarness(); + + await expect( + controller.adjudicateSeries( + adminUser(), + COMMUNITY_ID, + MATCH_ID, + new Types.ObjectId(SERIES_ID), + '"7"', + 'operator:invalid-body:1', + { + decision: { type: 'walkover' }, + reason: '', + }, + ), + ).rejects.toMatchObject({ + status: 422, + response: { + error: { code: 'INVALID_COMPETITION_REQUEST' }, + }, + }); + expect(commandService.adjudicateSeries).not.toHaveBeenCalled(); + }); + + it('rejects malformed game evidence before it reaches the ledger', async () => { + const { controller, commandService } = createHarness(); + + await expect( + controller.acceptGame( + adminUser(), + COMMUNITY_ID, + MATCH_ID, + '"7"', + 'operator:bad-evidence:1', + { + ...acceptGameBody(), + evidence: { type: 'invented-evidence' }, + }, + ), + ).rejects.toMatchObject({ + status: 422, + response: { + error: { code: 'INVALID_COMPETITION_REQUEST' }, + }, + }); + expect(commandService.acceptGame).not.toHaveBeenCalled(); + }); + + it('requires the same revision for preview and hash-confirmed reversal', async () => { + const { controller, commandService } = createHarness(); + + await controller.previewReversal( + adminUser(), + COMMUNITY_ID, + MATCH_ID, + new Types.ObjectId(SERIES_ID), + '"7"', + { mode: 'cascade', reason: '잘못 수집됨' }, + ); + await controller.reverseSeries( + adminUser(), + COMMUNITY_ID, + MATCH_ID, + new Types.ObjectId(SERIES_ID), + '"7"', + 'operator:reverse:1', + { + mode: 'cascade', + reason: '잘못 수집됨', + impactHash: 'a'.repeat(64), + }, + ); + + expect(commandService.previewSeriesReversal).toHaveBeenCalledWith({ + competitionId: COMPETITION_ID, + expectedRevision: 7, + seriesId: new Types.ObjectId(SERIES_ID), + mode: 'cascade', + }); + expect(commandService.reverseSeries).toHaveBeenCalledWith( + expect.objectContaining({ + competitionId: COMPETITION_ID, + expectedRevision: 7, + idempotencyKey: 'operator:reverse:1', + impactHash: 'a'.repeat(64), + }), + ); + }); +}); + +const COMMUNITY_ID = new Types.ObjectId('64d000000000000000000001'); +const MATCH_ID = new Types.ObjectId('64d000000000000000000002'); +const COMPETITION_ID = new Types.ObjectId('64d000000000000000000003'); +const ADMIN_ID = new Types.ObjectId('64d000000000000000000004'); +const GAME_ID = new Types.ObjectId('64d000000000000000000005'); +const SERIES_ID = '64d000000000000000000006'; +const GAME_SLOT_ID = new Types.ObjectId('64d000000000000000000007'); +const TEAM_A_ID = new Types.ObjectId('64d000000000000000000008'); +const TEAM_B_ID = new Types.ObjectId('64d000000000000000000009'); + +function createHarness() { + const competition = { + _id: COMPETITION_ID, + matchId: MATCH_ID, + communityId: COMMUNITY_ID, + schemaVersion: 1, + revision: 7, + phase: 'running', + teams: [], + format: { + type: 'paired-series', + rule: { type: 'fixed-games', gameCount: 3, drawPolicy: 'allow' }, + }, + projection: { + sourceRevision: 7, + projectorVersion: 1, + phase: 'running', + formatType: 'paired-series', + series: [], + games: [], + gameSlots: [], + rounds: [], + connectors: [], + }, + createdAt: new Date('2026-07-11T00:00:00.000Z'), + updatedAt: new Date('2026-07-12T00:00:00.000Z'), + }; + const queryService = { + getCompetition: jest.fn().mockResolvedValue(competition), + getTeamView: jest.fn(), + listFacts: jest.fn(), + }; + const commandService = { + acceptGame: jest.fn().mockResolvedValue({ competition, revision: 8 }), + adjudicateSeries: jest.fn().mockResolvedValue({ competition, revision: 8 }), + previewSeriesReversal: jest.fn().mockResolvedValue({ + sourceRevision: 7, + impactHash: 'a'.repeat(64), + impact: {}, + }), + reverseSeries: jest.fn().mockResolvedValue({ competition, revision: 8 }), + }; + return { + queryService, + commandService, + controller: new CompetitionController( + queryService as unknown as CompetitionQueryService, + commandService as unknown as CompetitionCommandService, + ), + }; +} + +function adminUser() { + return { + _id: ADMIN_ID, + communityId: COMMUNITY_ID, + role: 'admin', + } as never; +} + +function acceptGameBody() { + return { + gameId: GAME_ID.toHexString(), + seriesId: SERIES_ID, + gameSlotId: GAME_SLOT_ID.toHexString(), + ordinal: 1, + evidence: { + type: 'riot', + riotMatchId: 'KR_1', + payloadHash: 'sha256:value', + }, + mapping: { + mappingVersion: 1, + confidence: 1, + blueTeamId: TEAM_A_ID.toHexString(), + redTeamId: TEAM_B_ID.toHexString(), + winnerTeamId: TEAM_A_ID.toHexString(), + }, + }; +} diff --git a/apps/api/src/modules/competition/competition.controller.ts b/apps/api/src/modules/competition/competition.controller.ts new file mode 100644 index 00000000..d717357a --- /dev/null +++ b/apps/api/src/modules/competition/competition.controller.ts @@ -0,0 +1,530 @@ +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 { + return this.translate(async () => { + const competition = await this.queryService.getCompetition({ + communityId, + matchId, + }); + response.setHeader('ETag', revisionEtag(competition.revision)); + return presentCompetitionDetail(competition as never); + }); + } + + // Temporarily public: community members are not all signed in yet, so the + // team progress page addresses a team through an explicit `teamId` instead of + // the caller's identity. A signed-in caller with no `teamId` keeps the + // membership-scoped behaviour. + @Get('team') + @AllowPublicAccess() + public async getTeamView( + @CurrentUser() currentUser: UserDocument | undefined, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Query('teamId') requestedTeamId?: string, + @Res({ passthrough: true }) response?: Response, + ): Promise { + return this.translate(async () => { + const teamId = parseOptionalObjectId(requestedTeamId, 'teamId'); + if (!teamId) { + if (!currentUser) { + throw apiHttpError( + 401, + 'COMPETITION_TEAM_UNIDENTIFIED', + 'Sign in or provide a teamId query parameter to read a team view.', + ); + } + assertSameCommunity(currentUser, communityId); + } + const result = await this.queryService.getTeamView({ + communityId, + matchId, + ...(teamId ? { teamId } : { userId: currentUser!._id }), + }); + response?.setHeader('ETag', revisionEtag(result.revision)); + return result; + }); + } + + @Get('facts') + @Roles('owner', 'admin') + @UseGuards(RolesGuard) + public async listFacts( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Query() rawQuery: unknown, + ): Promise { + 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 { + 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 { + 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 { + 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 { + 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(operation: () => Promise): Promise { + try { + return await operation(); + } catch (error) { + throw explicitHttpError(error); + } + } +} + +function requireCommandHeaders( + ifMatch: string | undefined, + idempotencyKey: string | undefined, +): number { + const revision = parseRevision(ifMatch); + if ( + revision === undefined || + typeof idempotencyKey !== 'string' || + idempotencyKey.trim().length === 0 || + idempotencyKey.length > 200 + ) { + throw apiHttpError( + 422, + 'INVALID_COMPETITION_COMMAND_HEADERS', + 'A numeric If-Match revision and non-empty Idempotency-Key are required.', + ); + } + return revision; +} + +function parseOptionalObjectId( + value: string | undefined, + field: string, +): mongoose.Types.ObjectId | undefined { + if (value === undefined || value.trim().length === 0) return undefined; + if (!mongoose.isValidObjectId(value)) { + throw apiHttpError( + 422, + 'INVALID_COMPETITION_REQUEST', + `The ${field} query parameter must be a valid ObjectId.`, + ); + } + return new mongoose.Types.ObjectId(value); +} + +function requireRevisionHeader(ifMatch: string | undefined): number { + const revision = parseRevision(ifMatch); + if (revision === undefined) { + throw apiHttpError( + 422, + 'INVALID_COMPETITION_COMMAND_HEADERS', + 'A numeric If-Match revision is required.', + ); + } + return revision; +} + +function parseRevision(value: string | undefined): number | undefined { + if (!value) return undefined; + const match = /^(?:W\/)?"?(\d+)"?$/.exec(value.trim()); + if (!match) return undefined; + const revision = Number(match[1]); + return Number.isSafeInteger(revision) ? revision : undefined; +} + +function revisionEtag(revision: number): string { + return `"${revision}"`; +} + +function assertSameCommunity( + user: UserDocument, + communityId: mongoose.Types.ObjectId, +): void { + if (!user?.communityId?.equals(communityId)) { + throw apiHttpError( + 403, + 'COMPETITION_COMMUNITY_FORBIDDEN', + 'The authenticated user does not belong to this community.', + ); + } +} + +function explicitHttpError(error: unknown): HttpException { + if (error instanceof HttpException) { + const response = error.getResponse(); + if ( + typeof response === 'object' && + response !== null && + 'error' in response + ) { + return error; + } + return apiHttpError( + error.getStatus(), + statusCodeName(error.getStatus()), + typeof response === 'string' + ? response + : error.message || 'Competition request failed.', + ); + } + if (isCodedError(error)) { + return apiHttpError( + error.httpStatus ?? codedErrorStatus(error.code), + error.code, + error.message, + error.details, + ); + } + return apiHttpError( + 500, + 'COMPETITION_INTERNAL_ERROR', + 'Competition request failed.', + ); +} + +function codedErrorStatus(code: string): number { + switch (code) { + case 'REVERSAL_SERIES_NOT_FOUND': + case 'REVERSAL_REASON_REQUIRED': + return 422; + case 'REVERSAL_DESCENDANT_ACTIVITY': + case 'REVERSAL_NO_ACTIVE_RESULT': + case 'REVERSAL_PREVIEW_STALE': + case 'DUPLICATE_FACT_ID': + case 'DUPLICATE_GAME_ID': + case 'DUPLICATE_RIOT_MATCH_ID': + case 'DUPLICATE_GAME_SLOT': + case 'DUPLICATE_GAME_ORDINAL': + case 'DUPLICATE_ADJUDICATION': + case 'FACT_ALREADY_REVERSED': + case 'SERIES_ALREADY_COMPLETED': + case 'WALKOVER_HAS_ACTIVE_GAMES': + return 409; + case 'FACT_REFERENCE_NOT_FOUND': + case 'FACT_TYPE_INVALID': + case 'GAME_SLOT_INVALID': + case 'GAME_ORDINAL_INVALID': + case 'GAME_SERIES_MISMATCH': + case 'GAME_TEAM_MISMATCH': + case 'GAME_WINNER_INVALID': + case 'SERIES_DEFINITION_INVALID': + case 'SERIES_PARTICIPANTS_INVALID': + case 'ADJUDICATION_INVALID': + case 'ADJUDICATION_DRAW_NOT_ALLOWED': + return 422; + default: + return 500; + } +} + +function statusCodeName(status: number): string { + switch (status) { + case 403: + return 'COMPETITION_FORBIDDEN'; + case 404: + return 'COMPETITION_NOT_FOUND'; + case 409: + return 'COMPETITION_CONFLICT'; + case 412: + return 'STALE_COMPETITION_REVISION'; + case 422: + return 'INVALID_COMPETITION_REQUEST'; + default: + return 'COMPETITION_REQUEST_FAILED'; + } +} + +function apiHttpError( + status: number, + code: string, + message: string, + details?: unknown, +): HttpException { + return new HttpException( + { + error: { + code, + message, + ...(details === undefined ? {} : { details }), + }, + }, + status, + ); +} + +function isCodedError(error: unknown): error is { + code: string; + message: string; + httpStatus?: number; + details?: unknown; +} { + return ( + typeof error === 'object' && + error !== null && + typeof (error as { code?: unknown }).code === 'string' && + typeof (error as { message?: unknown }).message === 'string' + ); +} + +type DtoConstructor = new () => T; + +function validateDto( + constructor: DtoConstructor, + 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), + ]; + }); +} diff --git a/apps/api/src/modules/competition/competition.errors.ts b/apps/api/src/modules/competition/competition.errors.ts new file mode 100644 index 00000000..f78398fb --- /dev/null +++ b/apps/api/src/modules/competition/competition.errors.ts @@ -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>, + ) { + super(message); + this.name = 'CompetitionCommandError'; + } +} diff --git a/apps/api/src/modules/competition/competition.module.spec.ts b/apps/api/src/modules/competition/competition.module.spec.ts new file mode 100644 index 00000000..4c4d7765 --- /dev/null +++ b/apps/api/src/modules/competition/competition.module.spec.ts @@ -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, + ]), + ); + }); +}); diff --git a/apps/api/src/modules/competition/competition.module.ts b/apps/api/src/modules/competition/competition.module.ts new file mode 100644 index 00000000..6a70df74 --- /dev/null +++ b/apps/api/src/modules/competition/competition.module.ts @@ -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 {} diff --git a/apps/api/src/modules/competition/competition.presenter.spec.ts b/apps/api/src/modules/competition/competition.presenter.spec.ts new file mode 100644 index 00000000..958046bf --- /dev/null +++ b/apps/api/src/modules/competition/competition.presenter.spec.ts @@ -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 }; +} diff --git a/apps/api/src/modules/competition/competition.presenter.ts b/apps/api/src/modules/competition/competition.presenter.ts new file mode 100644 index 00000000..925a38c7 --- /dev/null +++ b/apps/api/src/modules/competition/competition.presenter.ts @@ -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; + projection: Record; + 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(source._id), + matchId: asId(source.matchId), + communityId: asId(source.communityId), + schemaVersion: source.schemaVersion, + revision: source.revision, + phase: source.phase, + teams: source.teams.map((team) => ({ + teamId: asId(team.teamId), + displayOrder: team.displayOrder, + name: team.name, + ...(team.captainUserId + ? { captainUserId: asId(team.captainUserId) } + : {}), + members: team.members.map((member) => ({ + userId: asId(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(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 { + return ( + typeof value === 'object' && + value !== null && + Object.getPrototypeOf(value) === Object.prototype + ); +} diff --git a/apps/api/src/modules/competition/competition.schema.spec.ts b/apps/api/src/modules/competition/competition.schema.spec.ts new file mode 100644 index 00000000..c65a0cc5 --- /dev/null +++ b/apps/api/src/modules/competition/competition.schema.spec.ts @@ -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, Record]>; + }, + expected: Array<{ + keys: Record; + options?: Record; + }>, +) { + const indexes = schema.indexes(); + for (const candidate of expected) { + expect(indexes).toEqual( + expect.arrayContaining([ + [candidate.keys, expect.objectContaining(candidate.options ?? {})], + ]), + ); + } +} diff --git a/apps/api/src/modules/competition/competition.schema.ts b/apps/api/src/modules/competition/competition.schema.ts new file mode 100644 index 00000000..849ebae5 --- /dev/null +++ b/apps/api/src/modules/competition/competition.schema.ts @@ -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; + seriesGraph: Array>; + projection: Record; + createdAt: Date; + updatedAt: Date; +} + +export type CompetitionDocument = HydratedDocument; + +export interface CompetitionFact { + competitionId: mongoose.Types.ObjectId; + type: CompetitionFactType; + revision: number; + ordinalWithinRevision: number; + commandId: string; + idempotencyKey: string; + requestHash: string; + schemaVersion: number; + actor: Record; + 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>; + evidence?: Record; + mapping?: Record; + gameAcceptedFactId?: mongoose.Types.ObjectId; + adjudicationFactId?: mongoose.Types.ObjectId; + decision?: Record; + reason?: string; + createdAt: Date; + updatedAt: Date; +} + +export type CompetitionFactDocument = HydratedDocument; + +export interface CompetitionOutbox { + eventId: string; + competitionId: mongoose.Types.ObjectId; + revision: number; + commandId: string; + idempotencyKey: string; + requestHash: string; + type: string; + payload: Record; + state: CompetitionOutboxState; + attemptCount: number; + availableAt: Date; + publishedAt?: Date; + lastError?: string; + createdAt: Date; + updatedAt: Date; +} + +export type CompetitionOutboxDocument = HydratedDocument; + +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; + +const CompetitionTeamMemberSchema = new Schema( + { + 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( + { + 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 = + new Schema( + { + 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( + { + 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( + { + 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( + { + 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', + }, +]; diff --git a/apps/api/src/modules/competition/domain/competition-projector.spec.ts b/apps/api/src/modules/competition/domain/competition-projector.spec.ts new file mode 100644 index 00000000..c83a66ea --- /dev/null +++ b/apps/api/src/modules/competition/domain/competition-projector.spec.ts @@ -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[] = []; + 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 }, +>(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; + 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 }>( + 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; +} diff --git a/apps/api/src/modules/competition/domain/competition-projector.ts b/apps/api/src/modules/competition/domain/competition-projector.ts new file mode 100644 index 00000000..4e431d3a --- /dev/null +++ b/apps/api/src/modules/competition/domain/competition-projector.ts @@ -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(); + const knownTeams = new Set(); + 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(); + 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, +): '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, + teamBySeed: ReadonlyMap, + projections: ReadonlyMap, +): Array { + return definition.slots.map( + ({ source }) => + resolveParticipant(source, knownTeams, teamBySeed, projections) ?? null, + ); +} + +function resolveParticipant( + source: ParticipantSource, + knownTeams: ReadonlySet, + teamBySeed: ReadonlyMap, + projections: ReadonlyMap, +): 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 + | 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, + 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, + 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 + | 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 = + 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(); + + 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(); + const activeBySlotId = new Map(); + + 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(); + 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 { + 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(); + 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 { + 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, +): 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 + ); +} diff --git a/apps/api/src/modules/competition/domain/competition-reversal.spec.ts b/apps/api/src/modules/competition/domain/competition-reversal.spec.ts new file mode 100644 index 00000000..c7688e79 --- /dev/null +++ b/apps/api/src/modules/competition/domain/competition-reversal.spec.ts @@ -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>) { + 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 }; +} diff --git a/apps/api/src/modules/competition/domain/competition-reversal.ts b/apps/api/src/modules/competition/domain/competition-reversal.ts new file mode 100644 index 00000000..f1a38ef5 --- /dev/null +++ b/apps/api/src/modules/competition/domain/competition-reversal.ts @@ -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>, + ) { + 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(); + const gameSlotIds = new Set(); + 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>; + reason: string; + occurredAt: Date; +}): Array> { + 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 { + 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 { + return typeof value === 'object' && value !== null; +} diff --git a/apps/api/src/modules/competition/domain/domain-error.ts b/apps/api/src/modules/competition/domain/domain-error.ts new file mode 100644 index 00000000..62eb3578 --- /dev/null +++ b/apps/api/src/modules/competition/domain/domain-error.ts @@ -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>, + ) { + super(message); + this.name = 'CompetitionDomainError'; + } +} + +export function assertCompetitionInvariant( + condition: unknown, + code: CompetitionDomainErrorCode, + message: string, + details?: Readonly>, +): asserts condition { + if (!condition) { + throw new CompetitionDomainError(code, message, details); + } +} diff --git a/apps/api/src/modules/competition/domain/series-graph.spec.ts b/apps/api/src/modules/competition/domain/series-graph.spec.ts new file mode 100644 index 00000000..57e5c34e --- /dev/null +++ b/apps/api/src/modules/competition/domain/series-graph.spec.ts @@ -0,0 +1,378 @@ +import { generateSeriesGraph } from './series-graph'; + +type GraphInput = Parameters[0]; +type ExplicitRoundRobinPairing = { + roundNumber: number; + matchNumber: number; + teamAId: string; + teamBId: string; +}; +type ExplicitRoundRobinGraphInput = Omit & { + format: Extract & { + pairings: readonly ExplicitRoundRobinPairing[]; + }; +}; + +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' }); + } + }); + + it('reproduces an explicit persisted round-robin schedule by TeamId and pairing position', () => { + const input: ExplicitRoundRobinGraphInput = { + competitionId: 'competition-persisted-round-robin', + teams: Array.from({ length: 8 }, (_, index) => ({ + teamId: `team-${index + 1}`, + displayOrder: 8 - index, + seedNumber: index + 1, + })), + format: { + type: 'round-robin', + rule: fixedGames(1), + maxRounds: 3, + tieBreakers: ['series-wins', 'game-diff', 'head-to-head'], + // Persisted schedules need not arrive in display order. Their explicit + // round/match positions, rather than array position, define identity. + pairings: [ + pairing(3, 4, 'team-6', 'team-7'), + pairing(1, 2, 'team-3', 'team-4'), + pairing(2, 1, 'team-1', 'team-3'), + pairing(1, 4, 'team-7', 'team-8'), + pairing(3, 1, 'team-1', 'team-4'), + pairing(2, 3, 'team-5', 'team-7'), + pairing(1, 1, 'team-1', 'team-2'), + pairing(3, 3, 'team-5', 'team-8'), + pairing(2, 4, 'team-6', 'team-8'), + pairing(1, 3, 'team-5', 'team-6'), + pairing(3, 2, 'team-2', 'team-3'), + pairing(2, 2, 'team-2', 'team-4'), + ], + }, + }; + + const first = generateSeriesGraph(input); + const second = generateSeriesGraph({ + ...input, + format: { + ...input.format, + pairings: [...input.format.pairings].reverse(), + }, + }); + + expect(second).toEqual(first); + expect( + first.map((series) => ({ + code: series.code, + roundNumber: series.stage.roundNumber, + displayOrder: series.stage.displayOrder, + sources: series.slots.map((slot) => slot.source), + })), + ).toEqual([ + roundRobinSeries('RR_R1_M1', 1, 1, 'team-1', 'team-2'), + roundRobinSeries('RR_R1_M2', 1, 2, 'team-3', 'team-4'), + roundRobinSeries('RR_R1_M3', 1, 3, 'team-5', 'team-6'), + roundRobinSeries('RR_R1_M4', 1, 4, 'team-7', 'team-8'), + roundRobinSeries('RR_R2_M1', 2, 5, 'team-1', 'team-3'), + roundRobinSeries('RR_R2_M2', 2, 6, 'team-2', 'team-4'), + roundRobinSeries('RR_R2_M3', 2, 7, 'team-5', 'team-7'), + roundRobinSeries('RR_R2_M4', 2, 8, 'team-6', 'team-8'), + roundRobinSeries('RR_R3_M1', 3, 9, 'team-1', 'team-4'), + roundRobinSeries('RR_R3_M2', 3, 10, 'team-2', 'team-3'), + roundRobinSeries('RR_R3_M3', 3, 11, 'team-5', 'team-8'), + roundRobinSeries('RR_R3_M4', 3, 12, 'team-6', 'team-7'), + ]); + }); + + it.each([ + { + name: 'a TeamId that is absent from the Competition', + replacement: pairing(1, 1, 'team-1', 'team-9'), + }, + { + name: 'the same TeamId in both slots', + replacement: pairing(1, 1, 'team-1', 'team-1'), + }, + { + name: 'a non-positive round number', + replacement: pairing(0, 1, 'team-1', 'team-2'), + }, + { + name: 'a non-positive match number', + replacement: pairing(1, 0, 'team-1', 'team-2'), + }, + ])( + 'rejects an explicit round-robin pairing with $name', + ({ replacement }) => { + const input = explicitRoundRobinInput([ + replacement, + pairing(1, 2, 'team-3', 'team-4'), + ]); + + expectGraphError(input, 'INVALID_ROUND_ROBIN_PAIRING'); + }, + ); + + it.each([ + { + name: 'round and match position', + pairings: [ + pairing(1, 1, 'team-1', 'team-2'), + pairing(1, 1, 'team-3', 'team-4'), + ], + code: 'DUPLICATE_ROUND_ROBIN_PAIRING_POSITION', + }, + { + name: 'opponents with reversed slots', + pairings: [ + pairing(1, 1, 'team-1', 'team-2'), + pairing(2, 1, 'team-2', 'team-1'), + ], + code: 'DUPLICATE_ROUND_ROBIN_OPPONENTS', + }, + ])('rejects a duplicate explicit $name', ({ pairings, code }) => { + expectGraphError(explicitRoundRobinInput(pairings), code); + }); + + it('keeps distinct opponent pairs when opaque TeamIds contain delimiters', () => { + const input = explicitRoundRobinInput([ + pairing(1, 1, 'a', 'b:c'), + pairing(1, 2, 'a:b', 'c'), + ]); + input.format.maxRounds = 1; + input.teams = ['a', 'b:c', 'a:b', 'c'].map((teamId, index) => ({ + teamId, + displayOrder: index + 1, + seedNumber: index + 1, + })); + + expect(generateSeriesGraph(input)).toHaveLength(2); + }); + + it('validates complete odd-team rounds and clamps maxRounds to the full schedule', () => { + const pairings = [ + pairing(1, 1, 'team-2', 'team-5'), + pairing(1, 2, 'team-3', 'team-4'), + pairing(2, 1, 'team-1', 'team-5'), + pairing(2, 2, 'team-2', 'team-3'), + pairing(3, 1, 'team-1', 'team-4'), + pairing(3, 2, 'team-3', 'team-5'), + pairing(4, 1, 'team-1', 'team-3'), + pairing(4, 2, 'team-2', 'team-4'), + pairing(5, 1, 'team-1', 'team-2'), + pairing(5, 2, 'team-4', 'team-5'), + ]; + const input = explicitRoundRobinInput(pairings); + input.teams = Array.from({ length: 5 }, (_, index) => ({ + teamId: `team-${index + 1}`, + displayOrder: index + 1, + seedNumber: index + 1, + })); + input.format.maxRounds = 10; + + expect(generateSeriesGraph(input)).toHaveLength(10); + }); + + it.each([ + { + name: 'an expected round', + pairings: [ + pairing(1, 1, 'team-1', 'team-2'), + pairing(1, 2, 'team-3', 'team-4'), + ], + }, + { + name: 'a match from an expected round', + pairings: [ + pairing(1, 1, 'team-1', 'team-2'), + pairing(1, 2, 'team-3', 'team-4'), + pairing(2, 1, 'team-1', 'team-3'), + ], + }, + ])('rejects explicit pairings missing $name', ({ pairings }) => { + expectGraphError( + explicitRoundRobinInput(pairings), + 'INCOMPLETE_ROUND_ROBIN_PAIRINGS', + ); + }); +}); + +function firstTo(winsRequired: number, maxGames: number) { + return { type: 'first-to' as const, winsRequired, maxGames }; +} + +function expectGraphError(input: GraphInput, code: string): void { + try { + generateSeriesGraph(input); + throw new Error(`Expected graph error ${code}.`); + } catch (error) { + expect(error).toMatchObject({ code }); + } +} + +function fixedGames(gameCount: number) { + return { + type: 'fixed-games' as const, + gameCount, + drawPolicy: 'allow' as const, + }; +} + +function pairing( + roundNumber: number, + matchNumber: number, + teamAId: string, + teamBId: string, +): ExplicitRoundRobinPairing { + return { + roundNumber, + matchNumber, + teamAId, + teamBId, + }; +} + +function explicitRoundRobinInput( + pairings: readonly ExplicitRoundRobinPairing[], +): ExplicitRoundRobinGraphInput { + return { + competitionId: 'competition-explicit-round-robin-validation', + teams: Array.from({ length: 4 }, (_, index) => ({ + teamId: `team-${index + 1}`, + displayOrder: index + 1, + seedNumber: index + 1, + })), + format: { + type: 'round-robin', + rule: fixedGames(1), + maxRounds: 2, + tieBreakers: ['series-wins', 'game-diff', 'head-to-head'], + pairings, + }, + }; +} + +function roundRobinSeries( + code: string, + roundNumber: number, + displayOrder: number, + teamAId: string, + teamBId: string, +) { + return { + code, + roundNumber, + displayOrder, + sources: [ + { type: 'team', teamId: teamAId }, + { type: 'team', teamId: teamBId }, + ], + }; +} diff --git a/apps/api/src/modules/competition/domain/series-graph.ts b/apps/api/src/modules/competition/domain/series-graph.ts new file mode 100644 index 00000000..288de088 --- /dev/null +++ b/apps/api/src/modules/competition/domain/series-graph.ts @@ -0,0 +1,786 @@ +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; + schedule?: { + date: string; + time: string | null; + timeZone: 'Asia/Seoul'; + }; + 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 interface RoundRobinPairing { + roundNumber: number; + matchNumber: number; + teamAId: string; + teamBId: string; +} + +export type CompetitionGraphFormat = + | { + type: 'paired-series'; + rule: FixedGamesSeriesRule; + } + | { + type: 'round-robin'; + rule: FixedGamesSeriesRule; + maxRounds?: number; + pairings?: readonly RoundRobinPairing[]; + 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 CanonicalRoundRobinPairing { + 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); + 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[], + format: Extract, +): SeriesDefinition[] { + assertFixedGamesRule(format.rule); + if (teams.length < 2) { + throw graphError( + 'INVALID_ROUND_ROBIN_TEAM_COUNT', + 'Round robin requires at least two teams.', + ); + } + + const pairings = format.pairings + ? validateExplicitRoundRobinPairings( + teams, + format.pairings, + format.maxRounds, + ) + : canonicalRoundRobinPairings(teams, format.maxRounds); + + return pairings.map((pairing, index) => { + const code = `RR_R${pairing.roundNumber}_M${pairing.matchNumber}`; + return createSeriesDefinition({ + competitionId, + code, + stage: 'round-robin', + roundNumber: pairing.roundNumber, + displayOrder: index + 1, + sources: [ + { type: 'team', teamId: pairing.teamAId }, + { type: 'team', teamId: pairing.teamBId }, + ], + rule: format.rule, + }); + }); +} + +function canonicalRoundRobinPairings( + teams: CompetitionGraphTeam[], + maxRounds?: number, +): RoundRobinPairing[] { + const matchNumberByRound = new Map(); + return roundRobinPairings(teams.length, maxRounds).map((pairing) => { + const matchNumber = (matchNumberByRound.get(pairing.roundNumber) ?? 0) + 1; + matchNumberByRound.set(pairing.roundNumber, matchNumber); + return { + roundNumber: pairing.roundNumber, + matchNumber, + teamAId: teams[pairing.teamAIndex].teamId, + teamBId: teams[pairing.teamBIndex].teamId, + }; + }); +} + +function validateExplicitRoundRobinPairings( + teams: CompetitionGraphTeam[], + pairings: readonly RoundRobinPairing[], + maxRounds?: number, +): RoundRobinPairing[] { + if (pairings.length === 0) { + throw graphError( + 'INVALID_ROUND_ROBIN_PAIRING', + 'Explicit round-robin pairings cannot be empty.', + ); + } + const teamIds = new Set(teams.map(({ teamId }) => teamId)); + const positions = new Set(); + const opponentPairs = new Set(); + const teamsByRound = new Map>(); + const sorted = pairings + .map((pairing) => ({ ...pairing })) + .sort( + (left, right) => + left.roundNumber - right.roundNumber || + left.matchNumber - right.matchNumber, + ); + + for (const pairing of sorted) { + if ( + !Number.isInteger(pairing.roundNumber) || + pairing.roundNumber < 1 || + !Number.isInteger(pairing.matchNumber) || + pairing.matchNumber < 1 || + (maxRounds !== undefined && pairing.roundNumber > maxRounds) || + !teamIds.has(pairing.teamAId) || + !teamIds.has(pairing.teamBId) || + pairing.teamAId === pairing.teamBId + ) { + throw graphError( + 'INVALID_ROUND_ROBIN_PAIRING', + 'Every explicit round-robin pairing needs a valid position and two known, distinct teams.', + ); + } + + const position = `${pairing.roundNumber}:${pairing.matchNumber}`; + if (positions.has(position)) { + throw graphError( + 'DUPLICATE_ROUND_ROBIN_PAIRING_POSITION', + `Round-robin pairing position ${position} occurs more than once.`, + ); + } + positions.add(position); + + const opponents = JSON.stringify([pairing.teamAId, pairing.teamBId].sort()); + if (opponentPairs.has(opponents)) { + throw graphError( + 'DUPLICATE_ROUND_ROBIN_OPPONENTS', + 'A round-robin opponent pair occurs more than once.', + ); + } + opponentPairs.add(opponents); + + const roundTeams = teamsByRound.get(pairing.roundNumber) ?? new Set(); + if (roundTeams.has(pairing.teamAId) || roundTeams.has(pairing.teamBId)) { + throw graphError( + 'INVALID_ROUND_ROBIN_PAIRING', + 'A team cannot appear in multiple Series in the same round.', + ); + } + roundTeams.add(pairing.teamAId); + roundTeams.add(pairing.teamBId); + teamsByRound.set(pairing.roundNumber, roundTeams); + } + + for (const roundNumber of new Set( + sorted.map((pairing) => pairing.roundNumber), + )) { + const matches = sorted.filter( + (pairing) => pairing.roundNumber === roundNumber, + ); + if (matches.some((pairing, index) => pairing.matchNumber !== index + 1)) { + throw graphError( + 'INVALID_ROUND_ROBIN_PAIRING', + `Round ${roundNumber} match numbers must be contiguous from one.`, + ); + } + } + + const expectedRoundCount = roundRobinRoundCount(teams.length, maxRounds); + const expectedMatchesPerRound = Math.floor(teams.length / 2); + for ( + let roundNumber = 1; + roundNumber <= expectedRoundCount; + roundNumber += 1 + ) { + const matchCount = (teamsByRound.get(roundNumber)?.size ?? 0) / 2; + if (matchCount !== expectedMatchesPerRound) { + throw graphError( + 'INCOMPLETE_ROUND_ROBIN_PAIRINGS', + `Round ${roundNumber} must contain ${expectedMatchesPerRound} Series.`, + ); + } + } + if (teamsByRound.size !== expectedRoundCount) { + throw graphError( + 'INCOMPLETE_ROUND_ROBIN_PAIRINGS', + `Explicit round-robin pairings must contain rounds 1 through ${expectedRoundCount}.`, + ); + } + return sorted; +} + +function generateDoubleEliminationGraph( + competitionId: string, + teams: CompetitionGraphTeam[], + format: Extract, +): 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, +): CanonicalRoundRobinPairing[] { + const bye = -1; + const rotating = Array.from({ length: teamCount }, (_, index) => index); + if (rotating.length % 2 === 1) rotating.push(bye); + + const roundCount = roundRobinRoundCount(teamCount, maxRounds); + const pairings: CanonicalRoundRobinPairing[] = []; + + 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 roundRobinRoundCount(teamCount: number, maxRounds?: number): number { + const fullRoundCount = teamCount % 2 === 0 ? teamCount - 1 : teamCount; + const requestedRounds = + maxRounds === undefined + ? fullRoundCount + : Number.isFinite(maxRounds) + ? Math.floor(maxRounds) + : fullRoundCount; + return Math.max(0, Math.min(fullRoundCount, requestedRounds)); +} + +function normalizeTeams( + teams: readonly CompetitionGraphTeam[], +): CompetitionGraphTeam[] { + const normalized = teams.map((team) => ({ ...team })); + const teamIds = new Set(); + const displayOrders = new Set(); + + 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(); + const gameSlotIds = new Set(); + + 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 { + 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 }); +} diff --git a/apps/api/src/modules/competition/domain/series-projector.spec.ts b/apps/api/src/modules/competition/domain/series-projector.spec.ts new file mode 100644 index 00000000..bf414edc --- /dev/null +++ b/apps/api/src/modules/competition/domain/series-projector.spec.ts @@ -0,0 +1,458 @@ +import { projectSeries } from './series-projector'; + +describe('projectSeries', () => { + it.each([ + ['a known local time', '21:30'], + ['an unknown local time', null], + ] as const)('preserves an optional Series schedule with %s', (_, time) => { + const schedule = { + date: '2026-07-15', + time, + timeZone: 'Asia/Seoul' as const, + }; + const definition = { + ...seriesDefinition({ + id: `series-scheduled-${time ?? 'unknown'}`, + stage: 'upper', + rule: { type: 'first-to' as const, winsRequired: 1, maxGames: 1 }, + }), + schedule, + }; + + const projection = projectSeries({ + definition, + participants: ['team-8', 'team-3'], + facts: [], + }); + + expect(projection).toMatchObject({ + status: 'ready', + schedule, + }); + }); + + it('keeps an existing definition without a schedule explicitly unscheduled', () => { + const definition = seriesDefinition({ + id: 'series-unscheduled', + stage: 'upper', + rule: { type: 'first-to', winsRequired: 1, maxGames: 1 }, + }); + + const projection = projectSeries({ + definition, + participants: ['team-8', 'team-3'], + facts: [], + }); + + expect(projection).not.toHaveProperty('schedule'); + }); + + it.each([ + [ + 'an impossible calendar date', + { date: '2026-02-30', time: '21:30', timeZone: 'Asia/Seoul' }, + ], + [ + 'an out-of-range local time', + { date: '2026-07-15', time: '24:00', timeZone: 'Asia/Seoul' }, + ], + [ + 'a non-canonical time zone', + { date: '2026-07-15', time: '21:30', timeZone: 'UTC' }, + ], + ])('rejects a Series schedule with %s', (_, schedule) => { + const definition = { + ...seriesDefinition({ + id: `series-invalid-schedule-${schedule.date}-${schedule.time}`, + stage: 'upper', + rule: { type: 'first-to' as const, winsRequired: 1, maxGames: 1 }, + }), + schedule, + } as unknown as Parameters[0]['definition']; + + expectInvariant( + () => + projectSeries({ + definition, + participants: ['team-8', 'team-3'], + facts: [], + }), + 'SERIES_DEFINITION_INVALID', + ); + }); + + it.each([null, false, ''])( + 'rejects a non-object Series schedule value %p', + (schedule) => { + const definition = { + ...seriesDefinition({ + id: 'series-invalid-schedule-shape', + stage: 'upper', + rule: { type: 'first-to' as const, winsRequired: 1, maxGames: 1 }, + }), + schedule, + } as unknown as Parameters[0]['definition']; + + expectInvariant( + () => + projectSeries({ + definition, + participants: ['team-8', 'team-3'], + facts: [], + }), + 'SERIES_DEFINITION_INVALID', + ); + }, + ); + + 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; + 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 }); + } +} diff --git a/apps/api/src/modules/competition/domain/series-projector.ts b/apps/api/src/modules/competition/domain/series-projector.ts new file mode 100644 index 00000000..5b207f48 --- /dev/null +++ b/apps/api/src/modules/competition/domain/series-projector.ts @@ -0,0 +1,866 @@ +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 SeriesSchedule { + date: string; + time: string | null; + timeZone: 'Asia/Seoul'; +} + +export interface SeriesDefinitionLike { + id: string; + code?: string; + stage: { + type: string; + roundNumber?: number; + displayOrder: number; + }; + slots: ReadonlyArray<{ + position: SeriesSlot; + source: Readonly>; + }>; + rule: SeriesRule; + schedule?: SeriesSchedule; + 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; + schedule?: SeriesSchedule; + 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; + 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(); + const voidedGameFacts = new Set(); + const adjudications = new Map(); + const reversedAdjudications = new Set(); + 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 schedule: unknown = definition.schedule; + if (schedule !== undefined) { + assertCompetitionInvariant( + isSeriesSchedule(schedule), + 'SERIES_DEFINITION_INVALID', + `Series ${definition.id} has an invalid schedule`, + ); + } + + 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(); + const ordinals = new Set(); + 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(); + const gameIds = new Set(); + const riotMatchIds = new Set(); + + 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(); + const activeAdjudications = new Set(); + + 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, + 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, +): 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, + ...(definition.schedule ? { schedule: { ...definition.schedule } } : {}), + entries: [ + { slot: 'A', teamId: participants[0], gameWins: 0 }, + { slot: 'B', teamId: participants[1], gameWins: 0 }, + ], + }; +} + +function isValidLocalDate(value: string): boolean { + const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value); + if (!match) return false; + const year = Number(match[1]); + const month = Number(match[2]); + const day = Number(match[3]); + const date = new Date(Date.UTC(year, month - 1, day)); + return ( + date.getUTCFullYear() === year && + date.getUTCMonth() === month - 1 && + date.getUTCDate() === day + ); +} + +function isSeriesSchedule(value: unknown): value is SeriesSchedule { + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + return false; + } + const schedule = value as Record; + return ( + typeof schedule.date === 'string' && + isValidLocalDate(schedule.date) && + (schedule.time === null || + (typeof schedule.time === 'string' && + /^(?:[01]\d|2[0-3]):[0-5]\d$/.test(schedule.time))) && + schedule.timeZone === 'Asia/Seoul' + ); +} + +function entriesFor( + participants: [string, string], + winsByTeam: Map, +): [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 | 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 { + return typeof value === 'object' && value !== null; +} diff --git a/apps/api/src/modules/competition/dto/competition-command.dto.ts b/apps/api/src/modules/competition/dto/competition-command.dto.ts new file mode 100644 index 00000000..25ba1743 --- /dev/null +++ b/apps/api/src/modules/competition/dto/competition-command.dto.ts @@ -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>; +} + +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>; + + @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; +} diff --git a/apps/api/src/modules/dakao/dakao-outbox-sweeper.service.ts b/apps/api/src/modules/dakao/dakao-outbox-sweeper.service.ts index ab2c3ebb..e060242f 100644 --- a/apps/api/src/modules/dakao/dakao-outbox-sweeper.service.ts +++ b/apps/api/src/modules/dakao/dakao-outbox-sweeper.service.ts @@ -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 { 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( diff --git a/apps/api/src/modules/dakao/dakao-outbox.service.spec.ts b/apps/api/src/modules/dakao/dakao-outbox.service.spec.ts index 97b6c264..fc07ea5f 100644 --- a/apps/api/src/modules/dakao/dakao-outbox.service.spec.ts +++ b/apps/api/src/modules/dakao/dakao-outbox.service.spec.ts @@ -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; diff --git a/apps/api/src/modules/dakao/dakao-outbox.service.ts b/apps/api/src/modules/dakao/dakao-outbox.service.ts index 21fb7cda..1662c6a6 100644 --- a/apps/api/src/modules/dakao/dakao-outbox.service.ts +++ b/apps/api/src/modules/dakao/dakao-outbox.service.ts @@ -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(params: { + subject: string; + eventId: string; + envelope: DakaoCommandEnvelope; + publishLeaseOwnerIdentifier?: string; + }): Promise { + 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 { 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( diff --git a/apps/api/src/modules/dakao/dakao.subscriber.spec.ts b/apps/api/src/modules/dakao/dakao.subscriber.spec.ts index ebf8e425..fa97773d 100644 --- a/apps/api/src/modules/dakao/dakao.subscriber.spec.ts +++ b/apps/api/src/modules/dakao/dakao.subscriber.spec.ts @@ -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: '스타' }, { diff --git a/apps/api/src/modules/double-elimination/double-elimination.util.spec.ts b/apps/api/src/modules/double-elimination/double-elimination.util.spec.ts new file mode 100644 index 00000000..e943b40f --- /dev/null +++ b/apps/api/src/modules/double-elimination/double-elimination.util.spec.ts @@ -0,0 +1,306 @@ +import { + buildDoubleEliminationGameSlots, + buildDoubleEliminationBracket, + cancelDoubleEliminationBracketMatch, + completeDoubleEliminationBracketMatch, + resolveDoubleEliminationSeriesWinner, + reshuffleDoubleEliminationSeeds, + swapDoubleEliminationSeeds, +} from './double-elimination.util'; + +function mongooseSubdocumentLike(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]); + }); +}); diff --git a/apps/api/src/modules/double-elimination/double-elimination.util.ts b/apps/api/src/modules/double-elimination/double-elimination.util.ts new file mode 100644 index 00000000..73dd5c58 --- /dev/null +++ b/apps/api/src/modules/double-elimination/double-elimination.util.ts @@ -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 { + 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 { + const descendants = new Set(); + 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(value: T): T { + const candidate = value as { toObject?: () => T }; + if (candidate && typeof candidate.toObject === 'function') { + return candidate.toObject(); + } + return value; +} + +function shuffleInPlace(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; +} diff --git a/apps/api/src/modules/global/database/auction-redis-schema.spec.ts b/apps/api/src/modules/global/database/auction-redis-schema.spec.ts new file mode 100644 index 00000000..c984c8cd --- /dev/null +++ b/apps/api/src/modules/global/database/auction-redis-schema.spec.ts @@ -0,0 +1,94 @@ +import { + AuctionHistoryEntrySchema, + AuctionSchema, + AuctionSideEffectApplicationSchema, + tournamentModelDefinitions, +} from './schema'; + +function indexWithKeys( + schemaIndexes: ReturnType, + expectedKeys: Record, +) { + return schemaIndexes.find(([keys]) => { + return JSON.stringify(keys) === JSON.stringify(expectedKeys); + }); +} + +describe('auction Redis schema foundation', () => { + it('defines Redis v1 projection metadata on auction documents', () => { + expect(AuctionSchema.path('revision')).toBeDefined(); + expect(AuctionSchema.path('auctionEngineVersion')).toBeDefined(); + expect(AuctionSchema.path('auctionLifecycleId')).toBeDefined(); + expect(AuctionSchema.path('lastAppliedAuctionStateTransitionId')).toBeDefined(); + expect(AuctionSchema.path('currentAuctionHistorySequence')).toBeDefined(); + expect(AuctionSchema.path('startAuctionRequestId')).toBeDefined(); + expect(AuctionSchema.path('startAuctionStateTransitionId')).toBeDefined(); + expect(AuctionSchema.path('matchSideEffectStatus')).toBeDefined(); + expect(AuctionSchema.path('matchSideEffectRevision')).toBeDefined(); + }); + + it('defines the new auction state field names for migration targets', () => { + expect(AuctionSchema.path('auctionTeams')).toBeDefined(); + expect(AuctionSchema.path('auctionPlayerOrder')).toBeDefined(); + expect(AuctionSchema.path('passedAuctionPlayerQueue')).toBeDefined(); + expect(AuctionSchema.path('currentAuctionRound')).toBeDefined(); + expect(AuctionSchema.path('currentAuctionPlayerOrderIndex')).toBeDefined(); + expect(AuctionSchema.path('auctionBidHistory')).toBeDefined(); + expect(AuctionSchema.path('currentHighestBidPointAmount')).toBeDefined(); + expect(AuctionSchema.path('currentHighestBidderTeamIndex')).toBeDefined(); + expect(AuctionSchema.path('currentBidRoundDeadlineTimestampMS')).toBeDefined(); + expect(AuctionSchema.path('maximumBidRoundDurationSeconds')).toBeDefined(); + expect(AuctionSchema.path('bidRoundExtensionSeconds')).toBeDefined(); + expect(AuctionSchema.path('initialTeamBidPointAmount')).toBeDefined(); + expect(AuctionSchema.path('topTierAuctionPriorityThreshold')).toBeDefined(); + expect(AuctionSchema.path('manualTopTierAuctionPriorityUserIds')).toBeDefined(); + expect(AuctionSchema.path('auctionStartedAtTimestampMS')).toBeDefined(); + expect(AuctionSchema.path('auctionCompletedAtTimestampMS')).toBeDefined(); + }); + + it('adds history transition fields and reset/undo action enum values', () => { + expect(AuctionHistoryEntrySchema.path('auctionStateTransitionId')).toBeDefined(); + expect(AuctionHistoryEntrySchema.path('auctionLifecycleId')).toBeDefined(); + expect(AuctionHistoryEntrySchema.path('revision')).toBeDefined(); + expect(AuctionHistoryEntrySchema.path('historyMutation')).toBeDefined(); + expect(AuctionHistoryEntrySchema.path('matchSideEffectMutation')).toBeDefined(); + expect( + AuctionHistoryEntrySchema.path('action').options.enum, + ).toEqual( + expect.arrayContaining(['start', 'open-bidding', 'bid', 'sold', 'passed', 'next', 'complete', 'reset', 'undo']), + ); + }); + + it('adds unique history indexes for sequence and transition idempotency', () => { + const indexes = AuctionHistoryEntrySchema.indexes(); + + expect(indexWithKeys(indexes, { auctionId: 1, sequence: 1 })?.[1]).toMatchObject({ + unique: true, + }); + expect( + indexWithKeys(indexes, { auctionId: 1, auctionStateTransitionId: 1 })?.[1], + ).toMatchObject({ unique: true, sparse: true }); + }); + + it('registers auction side effect application model with lease fields and unique idempotency index', () => { + expect(AuctionSideEffectApplicationSchema.path('processingOwnerToken')).toBeDefined(); + expect( + AuctionSideEffectApplicationSchema.path('processingLeaseExpiresAtTimestampMS'), + ).toBeDefined(); + expect(AuctionSideEffectApplicationSchema.path('payloadChecksum')).toBeDefined(); + + const indexes = AuctionSideEffectApplicationSchema.indexes(); + expect( + indexWithKeys(indexes, { + auctionId: 1, + auctionStateTransitionId: 1, + sideEffectType: 1, + })?.[1], + ).toMatchObject({ unique: true }); + expect( + tournamentModelDefinitions.some( + (definition) => definition.name === 'auctionSideEffectApplication', + ), + ).toBe(true); + }); +}); diff --git a/apps/api/src/modules/global/database/connection.service.spec.ts b/apps/api/src/modules/global/database/connection.service.spec.ts index e48d72b0..8bbd9a59 100644 --- a/apps/api/src/modules/global/database/connection.service.spec.ts +++ b/apps/api/src/modules/global/database/connection.service.spec.ts @@ -1,4 +1,74 @@ -import { resolveMongoDbName } from './connection.service'; +import mongoose from 'mongoose'; +import { + ConnectionService, + resolveMongoAppName, + resolveMongoConnectionOptions, + resolveMongoDbName, +} from './connection.service'; + +function createFakeConnection(connectionId: string) { + const models: Record = {}; + return { + readyState: mongoose.ConnectionStates.connected, + models, + model: jest.fn((name: string) => { + const model = { connectionId, modelName: name }; + models[name] = model; + return model; + }), + }; +} + +describe('ConnectionService', () => { + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('shares one MongoDB connection across concurrent initialization calls', async () => { + const connection = createFakeConnection('shared'); + const createConnection = jest + .spyOn(mongoose, 'createConnection') + .mockReturnValue({ + asPromise: jest.fn().mockResolvedValue(connection), + } as never); + const service = new ConnectionService({ + get: jest.fn().mockResolvedValue('mongodb://localhost/test'), + } as never); + + const [first, second] = await Promise.all([ + service.getConnection(), + service.getConnection(), + ]); + + expect(first).toBe(connection); + expect(second).toBe(connection); + expect(createConnection).toHaveBeenCalledTimes(1); + }); + + it('rebuilds models from the replacement connection after disconnect', async () => { + const firstConnection = createFakeConnection('first'); + const secondConnection = createFakeConnection('second'); + jest + .spyOn(mongoose, 'createConnection') + .mockReturnValueOnce({ + asPromise: jest.fn().mockResolvedValue(firstConnection), + } as never) + .mockReturnValueOnce({ + asPromise: jest.fn().mockResolvedValue(secondConnection), + } as never); + const service = new ConnectionService({ + get: jest.fn().mockResolvedValue('mongodb://localhost/test'), + } as never); + + const firstModel = await service.getModel('match'); + firstConnection.readyState = mongoose.ConnectionStates.disconnected; + const secondModel = await service.getModel('match'); + + expect(firstModel).toMatchObject({ connectionId: 'first' }); + expect(secondModel).toMatchObject({ connectionId: 'second' }); + expect(secondModel).not.toBe(firstModel); + }); +}); describe('resolveMongoDbName', () => { it('uses production database only for prod', () => { @@ -12,3 +82,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, + }); + }); +}); diff --git a/apps/api/src/modules/global/database/connection.service.ts b/apps/api/src/modules/global/database/connection.service.ts index 6d46b340..f9981d9f 100644 --- a/apps/api/src/modules/global/database/connection.service.ts +++ b/apps/api/src/modules/global/database/connection.service.ts @@ -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,47 +10,94 @@ 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; + private connectionPromise: Promise | null = null; constructor(private readonly secretService: SecretService) {} private tournamentModels: Map> | null = null; public async getConnection(): Promise { - if (this.connection !== null && this.connection.readyState === 1) { + if ( + this.connection !== null && + this.connection.readyState === mongoose.ConnectionStates.connected + ) { return this.connection; } + const pendingConnection = this.connectionPromise ?? this.openConnection(); + this.connectionPromise = pendingConnection; + try { + return await pendingConnection; + } finally { + if (this.connectionPromise === pendingConnection) { + this.connectionPromise = null; + } + } + } + + private async openConnection(): Promise { const connectionString = await this.secretService.get( 'MONGODB_CONNECTION_STRING', ); const dbName = resolveMongoDbName(); - const defaultConnection = await mongoose - .createConnection(connectionString, { - dbName, - minPoolSize: 10, - maxPoolSize: 20, - }) + const appName = resolveMongoAppName(); + const connectionOptions = resolveMongoConnectionOptions(dbName, appName); + const connection = await mongoose + .createConnection(connectionString, connectionOptions) .asPromise(); - this.connection = defaultConnection; - console.log(`Default Connection이 새로 생성됨. dbName=${dbName}`); - return this.connection; + this.connection = connection; + this.tournamentModels = null; + this.logger.log( + `MongoDB connection created. dbName=${dbName} appName=${appName} autoIndex=${ + connectionOptions.autoIndex === true + }`, + ); + + return connection; } public async getModel( modelKey: K, ): Promise> { + const connection = await this.getConnection(); if (this.tournamentModels) return this.tournamentModels.get(modelKey) as mongoose.Model< TournamentModelTypes[K] >; const models = new Map>(); - const connection = await this.getConnection(); tournamentModelDefinitions.forEach((modelDefinition) => { + applyMongoosePerformancePlugin(modelDefinition.schema); // 이미 생성된 경우 컴파일 스킵. if ( Object.prototype.hasOwnProperty.call( @@ -86,15 +134,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() { - this.connection?.close(); + 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, + ); } } diff --git a/apps/api/src/modules/global/database/migrations/20260622-auction-redis-field-rename.spec.ts b/apps/api/src/modules/global/database/migrations/20260622-auction-redis-field-rename.spec.ts new file mode 100644 index 00000000..7d4e92dc --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/20260622-auction-redis-field-rename.spec.ts @@ -0,0 +1,219 @@ +import { migrateAuctionRedisFieldRename } from './20260622-auction-redis-field-rename'; + +type Doc = Record & { _id: string }; + +function createDb(params: { auctions?: Doc[]; history?: Doc[] }) { + const collections = { + auction: params.auctions ?? [], + auctionHistory: params.history ?? [], + }; + + return { + collections, + db: { + collection(name: string) { + const docs = + name === 'auction' + ? collections.auction + : name === 'auctionHistory' + ? collections.auctionHistory + : []; + return { + find() { + return { + limit() { + return { + async *[Symbol.asyncIterator]() { + for (const doc of docs) yield doc; + }, + }; + }, + }; + }, + async bulkWrite(writes: Array<{ + updateOne: { + filter: { _id: unknown }; + update: { + $set?: Record; + $unset?: Record; + }; + }; + }>) { + for (const write of writes) { + const doc = docs.find((item) => item._id === write.updateOne.filter._id); + if (!doc) continue; + Object.assign(doc, write.updateOne.update.$set ?? {}); + for (const key of Object.keys(write.updateOne.update.$unset ?? {})) { + delete doc[key]; + } + } + }, + }; + }, + }, + }; +} + +describe('migrateAuctionRedisFieldRename', () => { + it('renames auction fields and nested bid/team fields', async () => { + const deadline = new Date('2026-06-22T01:02:03.004Z'); + const { db, collections } = createDb({ + auctions: [ + { + _id: 'auction-1', + teams: [ + { + teamIndex: 1, + captainUserId: 'u1', + points: 900, + members: [{ userId: 'u1', assignedPosition: 'TOP', cost: 100 }], + }, + ], + order: [{ userId: 'p1', passCount: 0 }], + passedQueue: [{ userId: 'p2', passCount: 1 }], + auctionRound: 2, + currentIndex: 3, + bids: [ + { + teamIndex: 1, + amount: 120, + bidderUserId: 'u1', + timestamp: deadline, + }, + ], + currentBid: 120, + currentBidderTeamIndex: 1, + currentDeadline: deadline, + maxTimerSeconds: 30, + bidExtensionSeconds: 5, + initialPoints: 1000, + topTierThreshold: 'DIAMOND', + manualTopTierUserIds: ['u2'], + startedAt: deadline, + completedAt: deadline, + }, + ], + }); + + const dryRunStats = await migrateAuctionRedisFieldRename(db, { + dryRun: true, + }); + expect(dryRunStats.changedAuctions).toBe(1); + expect(collections.auction[0]).toHaveProperty('teams'); + + const stats = await migrateAuctionRedisFieldRename(db, { dryRun: false }); + + expect(stats.changedAuctions).toBe(1); + expect(collections.auction[0]).toMatchObject({ + auctionEngineVersion: 'legacy-renamed', + auctionLifecycleId: 'legacy-auction:auction-1', + revision: 0, + currentAuctionHistorySequence: 0, + matchSideEffectStatus: 'none', + matchSideEffectRevision: 0, + auctionTeams: [ + { + teamIndex: 1, + captainUserId: 'u1', + remainingBidPointAmount: 900, + members: [ + { + userId: 'u1', + assignedPosition: 'TOP', + memberAcquisitionBidPointAmount: 100, + }, + ], + }, + ], + auctionPlayerOrder: [{ userId: 'p1', passCount: 0 }], + passedAuctionPlayerQueue: [{ userId: 'p2', passCount: 1 }], + currentAuctionRound: 2, + currentAuctionPlayerOrderIndex: 3, + auctionBidHistory: [ + { + bidderTeamIndex: 1, + bidPointAmount: 120, + bidderUserId: 'u1', + bidPlacedAtTimestampMS: deadline.getTime(), + }, + ], + currentHighestBidPointAmount: 120, + currentHighestBidderTeamIndex: 1, + currentBidRoundDeadlineTimestampMS: deadline.getTime(), + maximumBidRoundDurationSeconds: 30, + bidRoundExtensionSeconds: 5, + initialTeamBidPointAmount: 1000, + topTierAuctionPriorityThreshold: 'DIAMOND', + manualTopTierAuctionPriorityUserIds: ['u2'], + auctionStartedAtTimestampMS: deadline.getTime(), + auctionCompletedAtTimestampMS: deadline.getTime(), + }); + expect(collections.auction[0]).not.toHaveProperty('teams'); + expect(collections.auction[0]).not.toHaveProperty('bids'); + expect(collections.auction[0]).not.toHaveProperty('currentDeadline'); + }); + + it('renames history snapshots and adds transition metadata', async () => { + const { db, collections } = createDb({ + history: [ + { + _id: 'history-1', + auctionId: 'auction-1', + matchId: 'match-1', + sequence: 2, + action: 'sold', + snapshotBefore: { + currentBid: 100, + bids: [{ teamIndex: 1, amount: 100, timestamp: 123 }], + }, + }, + ], + }); + + await migrateAuctionRedisFieldRename(db, { dryRun: false }); + + expect(collections.auctionHistory[0]).toMatchObject({ + auctionLifecycleId: 'legacy-auction:auction-1', + auctionStateTransitionId: 'legacy-history:auction-1:2', + revision: 2, + historyMutation: { type: 'append' }, + matchSideEffectMutation: { type: 'none' }, + snapshotBefore: { + currentHighestBidPointAmount: 100, + auctionBidHistory: [ + { + bidderTeamIndex: 1, + bidPointAmount: 100, + bidPlacedAtTimestampMS: 123, + }, + ], + }, + }); + }); + + it('is idempotent after applying updates', async () => { + const { db } = createDb({ + auctions: [{ _id: 'auction-1', teams: [] }], + history: [{ _id: 'history-1', auctionId: 'auction-1', sequence: 1 }], + }); + + await migrateAuctionRedisFieldRename(db, { dryRun: false }); + const stats = await migrateAuctionRedisFieldRename(db, { dryRun: false }); + + expect(stats.changedAuctions).toBe(0); + expect(stats.changedHistoryEntries).toBe(0); + }); + + it('fails apply when duplicate history sequences would break unique indexes', async () => { + const { db } = createDb({ + history: [ + { _id: 'h1', auctionId: 'auction-1', sequence: 1 }, + { _id: 'h2', auctionId: 'auction-1', sequence: 1 }, + ], + }); + + await expect( + migrateAuctionRedisFieldRename(db, { dryRun: false }), + ).rejects.toThrow('Duplicate auctionHistory sequence'); + }); +}); diff --git a/apps/api/src/modules/global/database/migrations/20260622-auction-redis-field-rename.ts b/apps/api/src/modules/global/database/migrations/20260622-auction-redis-field-rename.ts new file mode 100644 index 00000000..a1a0d67c --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/20260622-auction-redis-field-rename.ts @@ -0,0 +1,336 @@ +interface MigrationCollection { + find(filter: Record): { + limit(limit: number): AsyncIterable; + }; + bulkWrite( + writes: Array<{ + updateOne: { + filter: { _id: unknown }; + update: { $set?: Record; $unset?: Record }; + }; + }>, + options: { ordered: boolean }, + ): Promise; +} + +interface MigrationDb { + collection(name: string): MigrationCollection; +} + +interface MigrationOptions { + dryRun?: boolean; + limit?: number; +} + +interface MigrationStats { + changedAuctions: number; + changedHistoryEntries: number; + duplicateHistorySequences: number; + scannedAuctions: number; + scannedHistoryEntries: number; +} + +type AnyDoc = Record & { _id: unknown }; +type UpdateDoc = { $set?: Record; $unset?: Record }; + +const AUCTION_FIELD_RENAMES: Array<{ + from: string; + to: string; + transform?: (value: unknown) => unknown; +}> = [ + { from: 'teams', to: 'auctionTeams', transform: transformAuctionTeams }, + { from: 'order', to: 'auctionPlayerOrder' }, + { from: 'passedQueue', to: 'passedAuctionPlayerQueue' }, + { from: 'auctionRound', to: 'currentAuctionRound' }, + { from: 'currentIndex', to: 'currentAuctionPlayerOrderIndex' }, + { from: 'bids', to: 'auctionBidHistory', transform: transformAuctionBidHistory }, + { from: 'currentBid', to: 'currentHighestBidPointAmount' }, + { from: 'currentBidderTeamIndex', to: 'currentHighestBidderTeamIndex' }, + { + from: 'currentDeadline', + to: 'currentBidRoundDeadlineTimestampMS', + transform: toTimestampMS, + }, + { from: 'maxTimerSeconds', to: 'maximumBidRoundDurationSeconds' }, + { from: 'bidExtensionSeconds', to: 'bidRoundExtensionSeconds' }, + { from: 'initialPoints', to: 'initialTeamBidPointAmount' }, + { from: 'topTierThreshold', to: 'topTierAuctionPriorityThreshold' }, + { + from: 'manualTopTierUserIds', + to: 'manualTopTierAuctionPriorityUserIds', + }, + { + from: 'startedAt', + to: 'auctionStartedAtTimestampMS', + transform: toTimestampMS, + }, + { + from: 'completedAt', + to: 'auctionCompletedAtTimestampMS', + transform: toTimestampMS, + }, +]; + +export async function migrateAuctionRedisFieldRename( + db: MigrationDb, + options: MigrationOptions = {}, +): Promise { + const dryRun = options.dryRun ?? true; + const stats: MigrationStats = { + changedAuctions: 0, + changedHistoryEntries: 0, + duplicateHistorySequences: 0, + scannedAuctions: 0, + scannedHistoryEntries: 0, + }; + + stats.duplicateHistorySequences = await countDuplicateHistorySequences( + db.collection('auctionHistory'), + options.limit, + ); + if (!dryRun && stats.duplicateHistorySequences > 0) { + throw new Error( + `Duplicate auctionHistory sequence entries found: ${stats.duplicateHistorySequences}`, + ); + } + + await migrateCollection( + db.collection('auction'), + options.limit, + dryRun, + stats, + 'auction', + ); + await migrateCollection( + db.collection('auctionHistory'), + options.limit, + dryRun, + stats, + 'auctionHistory', + ); + + return stats; +} + +async function migrateCollection( + collection: MigrationCollection, + limit: number | undefined, + dryRun: boolean, + stats: MigrationStats, + kind: 'auction' | 'auctionHistory', +) { + const writes: Array<{ + updateOne: { + filter: { _id: unknown }; + update: UpdateDoc; + }; + }> = []; + + for await (const doc of collection.find({}).limit(limit ?? 0)) { + if (kind === 'auction') stats.scannedAuctions += 1; + if (kind === 'auctionHistory') stats.scannedHistoryEntries += 1; + + const update = + kind === 'auction' ? migrateAuctionDoc(doc) : migrateHistoryDoc(doc); + if (!update) continue; + + if (kind === 'auction') stats.changedAuctions += 1; + if (kind === 'auctionHistory') stats.changedHistoryEntries += 1; + writes.push({ + updateOne: { + filter: { _id: doc._id }, + update, + }, + }); + } + + if (!dryRun && writes.length > 0) { + await collection.bulkWrite(writes, { ordered: false }); + } +} + +async function countDuplicateHistorySequences( + collection: MigrationCollection, + limit: number | undefined, +): Promise { + const seen = new Set(); + const duplicates = new Set(); + for await (const doc of collection.find({}).limit(limit ?? 0)) { + const auctionId = stringifyId(doc.auctionId); + const sequence = typeof doc.sequence === 'number' ? doc.sequence : undefined; + if (!auctionId || sequence === undefined) continue; + + const key = `${auctionId}:${sequence}`; + if (seen.has(key)) duplicates.add(key); + seen.add(key); + } + return duplicates.size; +} + +function migrateAuctionDoc(doc: AnyDoc): UpdateDoc | null { + const set: Record = {}; + const unset: Record = {}; + + for (const rename of AUCTION_FIELD_RENAMES) { + renameField(doc, rename.from, rename.to, set, unset, rename.transform); + } + + setDefault(doc, set, 'revision', 0); + setDefault(doc, set, 'currentAuctionHistorySequence', 0); + setDefault(doc, set, 'auctionEngineVersion', 'legacy-renamed'); + setDefault(doc, set, 'auctionLifecycleId', legacyAuctionLifecycleId(doc._id)); + setDefault(doc, set, 'matchSideEffectStatus', 'none'); + setDefault(doc, set, 'matchSideEffectRevision', 0); + + return buildUpdate(set, unset); +} + +function migrateHistoryDoc(doc: AnyDoc): UpdateDoc | null { + const set: Record = {}; + const unset: Record = {}; + const auctionId = stringifyId(doc.auctionId); + const sequence = typeof doc.sequence === 'number' ? doc.sequence : 0; + + setDefault( + doc, + set, + 'auctionLifecycleId', + auctionId ? legacyAuctionLifecycleId(auctionId) : undefined, + ); + setDefault( + doc, + set, + 'auctionStateTransitionId', + auctionId ? `legacy-history:${auctionId}:${sequence}` : undefined, + ); + setDefault(doc, set, 'revision', sequence); + setDefault(doc, set, 'historyMutation', { type: 'append' }); + setDefault(doc, set, 'matchSideEffectMutation', { type: 'none' }); + + const snapshotBefore = isRecord(doc.snapshotBefore) + ? migrateAuctionSnapshot(doc.snapshotBefore) + : undefined; + if (snapshotBefore?.changed) { + set.snapshotBefore = snapshotBefore.value; + } + + return buildUpdate(set, unset); +} + +function migrateAuctionSnapshot(snapshot: Record): { + changed: boolean; + value: Record; +} { + const value = { ...snapshot }; + let changed = false; + for (const rename of AUCTION_FIELD_RENAMES) { + if (!(rename.from in value)) continue; + if (!(rename.to in value)) { + value[rename.to] = rename.transform + ? rename.transform(value[rename.from]) + : value[rename.from]; + } + delete value[rename.from]; + changed = true; + } + return { changed, value }; +} + +function renameField( + doc: Record, + from: string, + to: string, + set: Record, + unset: Record, + transform?: (value: unknown) => unknown, +) { + if (!(from in doc)) return; + if (!(to in doc)) { + set[to] = transform ? transform(doc[from]) : doc[from]; + } + unset[from] = ''; +} + +function setDefault( + doc: Record, + set: Record, + key: string, + value: unknown, +) { + if (value === undefined || key in doc || key in set) return; + set[key] = value; +} + +function buildUpdate( + set: Record, + unset: Record, +): UpdateDoc | null { + const update: UpdateDoc = {}; + if (Object.keys(set).length > 0) update.$set = set; + if (Object.keys(unset).length > 0) update.$unset = unset; + return update.$set || update.$unset ? update : null; +} + +function transformAuctionTeams(value: unknown): unknown[] { + return asArray(value).map((team) => { + const next = { ...team }; + if ('points' in next && !('remainingBidPointAmount' in next)) { + next.remainingBidPointAmount = next.points; + } + delete next.points; + next.members = asArray(next.members).map((member) => { + const migratedMember = { ...member }; + if ( + 'cost' in migratedMember && + !('memberAcquisitionBidPointAmount' in migratedMember) + ) { + migratedMember.memberAcquisitionBidPointAmount = migratedMember.cost; + } + delete migratedMember.cost; + return migratedMember; + }); + return next; + }); +} + +function transformAuctionBidHistory(value: unknown): unknown[] { + return asArray(value).map((bid) => { + const next: Record = {}; + if ('teamIndex' in bid) next.bidderTeamIndex = bid.teamIndex; + if ('amount' in bid) next.bidPointAmount = bid.amount; + if ('bidderUserId' in bid) next.bidderUserId = bid.bidderUserId; + if ('timestamp' in bid) { + next.bidPlacedAtTimestampMS = toTimestampMS(bid.timestamp); + } + return next; + }); +} + +function toTimestampMS(value: unknown): unknown { + if (value instanceof Date) return value.getTime(); + if (typeof value === 'number') return value; + if (typeof value === 'string') { + const parsed = Date.parse(value); + return Number.isNaN(parsed) ? value : parsed; + } + return value; +} + +function legacyAuctionLifecycleId(value: unknown): string { + return `legacy-auction:${stringifyId(value) ?? 'unknown'}`; +} + +function stringifyId(value: unknown): string | undefined { + if (value === undefined || value === null) return undefined; + return typeof value === 'string' ? value : String(value); +} + +function asArray(value: unknown): Record[] { + return Array.isArray(value) + ? value.filter(isRecord).map((item) => ({ ...item })) + : []; +} + +function isRecord(value: unknown): value is Record { + return Boolean(value && typeof value === 'object' && !Array.isArray(value)); +} diff --git a/apps/api/src/modules/global/database/migrations/20260627-tournament-code-unique-indexes.spec.ts b/apps/api/src/modules/global/database/migrations/20260627-tournament-code-unique-indexes.spec.ts new file mode 100644 index 00000000..19473cd7 --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/20260627-tournament-code-unique-indexes.spec.ts @@ -0,0 +1,618 @@ +import { migrateTournamentCodeUniqueIndexes } from './20260627-tournament-code-unique-indexes'; + +type Doc = Record & { _id: string }; +type FakeIndex = { + commitQuorum?: number | string; + key: Record; + maxTimeMS?: number; + name: string; + partialFilterExpression?: Record; + unique?: boolean; +}; +type Projection = Record; + +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 = {}, + 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, + update: { + $pull?: Record; + $set?: Record; + $unset?: Record; + }, + ) { + 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, + options: { + name: string; + partialFilterExpression?: Record; + unique?: boolean; + }, + ) { + if (name === 'tournamentCode') { + tournamentCodeNamespaceMissing = false; + } + indexes.push({ key, ...options }); + return options.name; + }, + }; + }, + }, + }; +} + +function matchesFilter(doc: Doc, filter: Record): 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; + $set?: Record; + $unset?: Record; + }, +) { + 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, 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 { + 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']); + }); +}); diff --git a/apps/api/src/modules/global/database/migrations/20260627-tournament-code-unique-indexes.ts b/apps/api/src/modules/global/database/migrations/20260627-tournament-code-unique-indexes.ts new file mode 100644 index 00000000..b8e457af --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/20260627-tournament-code-unique-indexes.ts @@ -0,0 +1,764 @@ +type TournamentCodeState = + | 'available' + | 'reserved' + | 'used' + | 'released' + | 'expired' + | 'voided' + | string; + +type AnyDoc = Record & { _id: unknown }; +type IndexKey = Record; +type PartialFilterExpression = Record; +type Projection = Record; + +interface MigrationCursor { + limit(limit: number): AsyncIterable; +} + +interface MigrationIndex { + key: IndexKey; + name: string; + partialFilterExpression?: PartialFilterExpression; + unique?: boolean; +} + +interface MigrationCollection { + find( + filter: Record, + options?: { projection?: Projection }, + ): MigrationCursor; + updateMany( + filter: Record, + update: { + $pull?: Record; + $set?: Record; + $unset?: Record; + }, + options?: { ordered?: boolean }, + ): Promise<{ matchedCount?: number; modifiedCount?: number } | unknown>; + indexes?(): Promise; + dropIndex?(name: string): Promise; + createIndex?( + key: IndexKey, + options: { + commitQuorum?: number | string; + maxTimeMS?: number; + name: string; + partialFilterExpression?: PartialFilterExpression; + unique?: boolean; + }, + ): Promise; +} + +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 { + 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 { + 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; scannedMatches: number }> { + const referencedCodeIds = new Set(); + 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 = {}, +) { + options.onProgress?.({ phase, ...values }); +} + +function findDuplicateGroups( + docs: TournamentCodeDoc[], + referencedCodeIds: Set, +): DuplicateGroup[] { + return [ + ...duplicateGroupsFor(docs, referencedCodeIds, 'gameNumber'), + ...duplicateGroupsFor(docs, referencedCodeIds, 'riotMatchId'), + ]; +} + +function duplicateGroupsFor( + docs: TournamentCodeDoc[], + referencedCodeIds: Set, + kind: TournamentCodeDuplicateKind, +): DuplicateGroup[] { + const groups = new Map(); + + 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, +): ReleasePlanEntry[] { + const byCodeId = new Map(); + + 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, + 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, +): TournamentCodeDoc { + return sortCodesByKeeperPriority( + group.codeDocs, + referencedCodeIds, + group.kind, + )[0]; +} + +function sortCodesByKeeperPriority( + docs: TournamentCodeDoc[], + referencedCodeIds: Set, + kind: TournamentCodeDuplicateKind, +): TournamentCodeDoc[] { + return [...docs].sort((left, right) => + compareCodePriority(left, right, referencedCodeIds, kind), + ); +} + +function compareCodePriority( + left: TournamentCodeDoc, + right: TournamentCodeDoc, + referencedCodeIds: Set, + 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 { + 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, key: string): boolean { + return Object.prototype.hasOwnProperty.call(doc, key); +} + +function stringifyKeyPart(value: unknown): string { + if (value === null) return ''; + if (value === undefined) return ''; + 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); +} diff --git a/apps/api/src/modules/global/database/migrations/20260712-competition-domain.spec.ts b/apps/api/src/modules/global/database/migrations/20260712-competition-domain.spec.ts new file mode 100644 index 00000000..8c8cb05e --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/20260712-competition-domain.spec.ts @@ -0,0 +1,1569 @@ +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].evidence.type).toBe('legacy'); + if (games[1].evidence.type !== 'legacy') { + throw new Error('Expected normalized-only legacy evidence.'); + } + expect(games[1].evidence.legacyReference).toContain('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); + + expectQuarantineReason(plan, 'AMBIGUOUS_GAME_ASSIGNMENT'); + }); + + it('preserves a persisted non-canonical round-robin schedule', () => { + const schedule = [ + [1, 1, 1, 2], + [2, 1, 3, 4], + [3, 1, 5, 6], + [4, 1, 7, 8], + [5, 2, 1, 3], + [6, 2, 2, 4], + [7, 2, 5, 7], + [8, 2, 6, 8], + [9, 3, 1, 4], + [10, 3, 2, 3], + [11, 3, 5, 8], + [12, 3, 6, 7], + ] as const; + const legacy = pairedMatch({ + _id: 'match-persisted-round-robin-schedule', + gameMode: 'round-robin', + gameCount: 1, + roundRobinMaxRounds: 3, + teams: Array.from({ length: 8 }, (_, index) => + legacyTeam(index + 1, `${index + 1}팀`), + ), + gameSchedule: schedule.map( + ([gameNumber, roundNumber, teamAIndex, teamBIndex]) => ({ + gameNumber, + roundNumber, + teamAIndex, + teamBIndex, + }), + ), + result: { + games: schedule.map(([gameNumber, , teamAIndex, teamBIndex]) => + legacyGame({ + gameNumber, + riotMatchId: `KR_PERSISTED_RR_${gameNumber}`, + blueTeamIndex: teamAIndex, + redTeamIndex: teamBIndex, + winnerTeamIndex: teamAIndex, + riotArchivePresent: true, + }), + ), + seriesResults: [], + }, + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + + expect(plan.competition.format.type).toBe('round-robin'); + if (plan.competition.format.type !== 'round-robin') { + throw new Error('Expected a round-robin format.'); + } + expect( + plan.competition.format.pairings?.some( + (pairing) => + pairing.roundNumber === 3 && + pairing.matchNumber === 4 && + pairing.teamAId === plan.competition.teams[5].teamId && + pairing.teamBId === plan.competition.teams[6].teamId, + ), + ).toBe(true); + expect( + plan.facts.filter(({ type }) => type === 'game-accepted'), + ).toHaveLength(12); + }); + + it('maps a result-less code through an interleaved persisted round-robin schedule', () => { + const legacy = pairedMatch({ + _id: 'match-persisted-round-robin-code', + gameMode: 'round-robin', + gameCount: 2, + roundRobinMaxRounds: 1, + teams: [ + legacyTeam(1, 'One'), + legacyTeam(2, 'Two'), + legacyTeam(3, 'Three'), + legacyTeam(4, 'Four'), + ], + gameSchedule: [ + { gameNumber: 1, roundNumber: 1, teamAIndex: 1, teamBIndex: 3 }, + { gameNumber: 2, roundNumber: 1, teamAIndex: 2, teamBIndex: 4 }, + { gameNumber: 3, roundNumber: 1, teamAIndex: 1, teamBIndex: 3 }, + { gameNumber: 4, roundNumber: 1, teamAIndex: 2, teamBIndex: 4 }, + ], + result: { games: [], seriesResults: [] }, + tournamentCodes: [ + { + _id: 'persisted-round-robin-code-game-3', + state: 'reserved', + gameNumber: 3, + }, + ], + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + const expectedSeries = plan.competition.seriesGraph.find( + (series) => series.code === 'RR_R1_M1', + ); + + expect(expectedSeries).toBeDefined(); + expect(plan.assignments).toContainEqual( + expect.objectContaining({ + seriesId: expectedSeries!.id, + gameSlotId: expectedSeries!.gameSlots[1].id, + }), + ); + }); + + it('quarantines an incomplete persisted round-robin schedule', () => { + const legacy = pairedMatch({ + _id: 'match-incomplete-round-robin-schedule', + gameMode: 'round-robin', + gameCount: 1, + roundRobinMaxRounds: 2, + teams: [ + legacyTeam(1, 'One'), + legacyTeam(2, 'Two'), + legacyTeam(3, 'Three'), + legacyTeam(4, 'Four'), + ], + gameSchedule: [ + { gameNumber: 1, roundNumber: 1, teamAIndex: 1, teamBIndex: 2 }, + { gameNumber: 2, roundNumber: 1, teamAIndex: 3, teamBIndex: 4 }, + { gameNumber: 3, roundNumber: 2, teamAIndex: 1, teamBIndex: 3 }, + ], + result: { games: [], seriesResults: [] }, + }); + + const plan = planCompetitionMigration(legacy); + + expectQuarantineReason(plan, 'SERIES_GRAPH_GENERATION_FAILED'); + if (plan.status === 'quarantined') { + expect(plan.reasons).toContainEqual( + expect.objectContaining({ + code: 'SERIES_GRAPH_GENERATION_FAILED', + details: { + projectorCode: 'INCOMPLETE_ROUND_ROBIN_PAIRINGS', + }, + }), + ); + } + }); + + it('reconstructs playable rounds for a complete legacy schedule without round numbers', () => { + const schedule = [ + [2, 5], + [1, 2], + [4, 5], + [1, 6], + [5, 6], + [4, 6], + [2, 6], + [3, 5], + [2, 3], + [1, 4], + [3, 6], + [1, 3], + [3, 4], + [1, 5], + [2, 4], + ] as const; + const legacy = pairedMatch({ + _id: 'match-legacy-round-robin-without-rounds', + gameMode: 'round-robin', + gameCount: 1, + roundRobinMaxRounds: undefined, + teams: Array.from({ length: 6 }, (_, index) => + legacyTeam(index + 1, `${index + 1}팀`), + ), + gameSchedule: schedule.map(([teamAIndex, teamBIndex], index) => ({ + gameNumber: index + 1, + teamAIndex, + teamBIndex, + })), + result: { games: [], seriesResults: [] }, + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + + expect(plan.competition.seriesGraph).toHaveLength(15); + expect( + new Set( + plan.competition.seriesGraph.map((series) => series.stage.roundNumber), + ), + ).toHaveProperty('size', 5); + expect(plan.warnings).toContainEqual( + expect.objectContaining({ + code: 'LEGACY_ROUND_ROBIN_ROUNDS_RECONSTRUCTED', + }), + ); + }); + + it('reconstructs a large complete opponent-only schedule without combinatorial search', () => { + const teamCount = 14; + const pairs = Array.from({ length: teamCount }, (_, left) => + Array.from( + { length: teamCount - left - 1 }, + (_, offset) => [left + 1, left + offset + 2] as const, + ), + ).flat(); + const legacy = pairedMatch({ + _id: 'match-large-complete-round-robin-without-rounds', + gameMode: 'round-robin', + gameCount: 1, + teams: Array.from({ length: teamCount }, (_, index) => + legacyTeam(index + 1, `${index + 1}팀`), + ), + gameSchedule: pairs.map(([teamAIndex, teamBIndex], index) => ({ + gameNumber: index + 1, + teamAIndex, + teamBIndex, + })), + result: { games: [], seriesResults: [] }, + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + + expect(plan.competition.seriesGraph).toHaveLength(91); + }); + + it('rejects a large infeasible partial opponent schedule during degree preflight', () => { + const teamCount = 14; + const pairs = Array.from({ length: teamCount }, (_, left) => + Array.from( + { length: teamCount - left - 1 }, + (_, offset) => [left + 1, left + offset + 2] as const, + ), + ) + .flat() + .slice(0, 49); + const legacy = pairedMatch({ + _id: 'match-large-infeasible-round-robin-without-rounds', + gameMode: 'round-robin', + gameCount: 1, + roundRobinMaxRounds: 7, + teams: Array.from({ length: teamCount }, (_, index) => + legacyTeam(index + 1, `${index + 1}팀`), + ), + gameSchedule: pairs.map(([teamAIndex, teamBIndex], index) => ({ + gameNumber: index + 1, + teamAIndex, + teamBIndex, + })), + result: { games: [], seriesResults: [] }, + }); + + const plan = planCompetitionMigration(legacy); + + expectQuarantineReason(plan, 'INVALID_ROUND_ROBIN_SCHEDULE'); + }); + + it('uses a dedicated quarantine code for unsupported large partial round reconstruction', () => { + const teamCount = 20; + const rotating = Array.from({ length: teamCount }, (_, index) => index + 1); + const pairs: Array = []; + for (let round = 0; round < 10; round += 1) { + for (let index = 0; index < teamCount / 2; index += 1) { + pairs.push([rotating[index], rotating[teamCount - 1 - index]]); + } + const fixed = rotating[0]; + const tail = rotating.slice(1); + tail.unshift(tail.pop()!); + rotating.splice(0, rotating.length, fixed, ...tail); + } + const legacy = pairedMatch({ + _id: 'match-unsupported-large-partial-round-reconstruction', + gameMode: 'round-robin', + gameCount: 1, + roundRobinMaxRounds: 10, + teams: Array.from({ length: teamCount }, (_, index) => + legacyTeam(index + 1, `${index + 1}팀`), + ), + gameSchedule: pairs.reverse().map(([teamAIndex, teamBIndex], index) => ({ + gameNumber: index + 1, + teamAIndex, + teamBIndex, + })), + result: { games: [], seriesResults: [] }, + }); + + const plan = planCompetitionMigration(legacy); + + expectQuarantineReason( + plan, + 'ROUND_ROBIN_ROUND_RECONSTRUCTION_UNSUPPORTED', + ); + }); + + it('preserves a sparse global game number as the exact paired-Series slot', () => { + const legacy = pairedMatch({ + _id: 'match-sparse-paired-game-number', + gameCount: 3, + teams: [legacyTeam(1, 'One'), legacyTeam(2, 'Two')], + gameSchedule: undefined, + result: { + games: [ + legacyGame({ + gameNumber: 2, + riotMatchId: 'KR_SPARSE_PAIR_GAME_2', + riotArchivePresent: true, + blueTeamIndex: 1, + redTeamIndex: 2, + winnerTeamIndex: 1, + }), + ], + seriesResults: [], + }, + tournamentCodes: [ + { + _id: 'sparse-pair-code-game-2', + state: 'used', + gameNumber: 2, + riotMatchId: 'KR_SPARSE_PAIR_GAME_2', + }, + ], + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + const series = plan.competition.seriesGraph[0]; + const gameFact = plan.facts.find((fact) => fact.type === 'game-accepted'); + + expect(gameFact).toMatchObject({ + type: 'game-accepted', + seriesId: series.id, + gameSlotId: series.gameSlots[1].id, + ordinal: 2, + }); + expect(plan.assignments).toContainEqual( + expect.objectContaining({ + seriesId: series.id, + gameSlotId: series.gameSlots[1].id, + }), + ); + }); + + it('preserves a sparse double-elimination global game number and binds its used code to the same slot', () => { + const legacy = sparseDoubleEliminationWbFinalMatch(); + + const plan = requireReady(planCompetitionMigration(legacy)); + const wbFinal = plan.competition.seriesGraph.find( + (series) => series.code === 'WB_FINAL', + ); + + expect(wbFinal).toBeDefined(); + const wbFinalFact = plan.facts.find( + (fact) => fact.type === 'game-accepted' && fact.seriesId === wbFinal!.id, + ); + expect(wbFinalFact).toMatchObject({ + type: 'game-accepted', + seriesId: wbFinal!.id, + gameSlotId: wbFinal!.gameSlots[1].id, + ordinal: 2, + evidence: { + type: 'riot', + riotMatchId: 'KR_SPARSE_WB_FINAL_GAME_2', + }, + }); + expect(plan.assignments).toContainEqual( + expect.objectContaining({ + tournamentCodeId: 'sparse-wb-final-code-game-2', + state: 'used', + seriesId: wbFinal!.id, + gameSlotId: wbFinal!.gameSlots[1].id, + riotMatchId: 'KR_SPARSE_WB_FINAL_GAME_2', + }), + ); + }); + + it('quarantines a used TournamentCode when its slot has no accepted game', () => { + const legacy = pairedMatch({ + _id: 'match-used-code-without-game', + gameCount: 1, + gameSchedule: undefined, + result: { games: [], seriesResults: [] }, + tournamentCodes: [ + { + _id: 'used-code-without-game', + state: 'used', + gameNumber: 1, + usedAt: '2026-07-02T00:00:00.000Z', + }, + ], + }); + + const plan = planCompetitionMigration(legacy); + + expectQuarantineReason(plan, 'USED_CODE_WITHOUT_ACCEPTED_GAME'); + }); + + it('binds a used code without Riot identity to the accepted game in its exact slot', () => { + const legacy = pairedMatch({ + _id: 'match-used-code-by-slot', + gameCount: 1, + gameSchedule: undefined, + result: { + games: [ + legacyGame({ + gameNumber: 1, + riotMatchId: 'KR_USED_CODE_BY_SLOT', + riotArchivePresent: true, + }), + ], + seriesResults: [], + }, + tournamentCodes: [ + { + _id: 'used-code-by-slot', + state: 'used', + gameNumber: 1, + reservedAt: '2026-07-01T00:00:00.000Z', + usedAt: '2026-07-02T00:00:00.000Z', + releasedAt: '2026-07-01T12:00:00.000Z', + voidedAt: '2026-07-01T18:00:00.000Z', + }, + ], + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + + expect(plan.assignments).toHaveLength(1); + expect(plan.assignments[0]).toMatchObject({ + state: 'used', + usedAt: '2026-07-02T00:00:00.000Z', + }); + expect(plan.assignments[0]).not.toHaveProperty('releasedAt'); + expect(plan.assignments[0]).not.toHaveProperty('voidedAt'); + expect(plan.warnings).toEqual([]); + }); + + it('preserves the actual voided lifecycle timestamp', () => { + const legacy = pairedMatch({ + _id: 'match-voided-code-timestamp', + gameCount: 1, + gameSchedule: undefined, + tournamentCodes: [ + { + _id: 'voided-code-with-timestamp', + state: 'voided', + gameNumber: 1, + reservedAt: '2026-07-01T00:00:00.000Z', + usedAt: '2026-07-02T00:00:00.000Z', + releasedAt: '2026-07-04T00:00:00.000Z', + voidedAt: '2026-07-03T00:00:00.000Z', + }, + ], + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + + expect(plan.assignments).toContainEqual( + expect.objectContaining({ + state: 'voided', + voidedAt: '2026-07-03T00:00:00.000Z', + }), + ); + expect(plan.assignments[0]).not.toHaveProperty('releasedAt'); + }); + + it('ignores stale terminal timestamps from an earlier lifecycle when a code is reserved again', () => { + const legacy = pairedMatch({ + _id: 'match-reused-reserved-code-timeline', + gameCount: 1, + gameSchedule: undefined, + result: { games: [], seriesResults: [] }, + tournamentCodes: [ + { + _id: 'reused-reserved-code', + state: 'reserved', + gameNumber: 1, + reservedAt: '2026-07-03T00:00:00.000Z', + usedAt: '2026-07-01T00:00:00.000Z', + releasedAt: '2026-07-02T00:00:00.000Z', + voidedAt: '2026-07-02T00:00:00.000Z', + riotMatchId: 'KR_STALE_RESERVED_LIFECYCLE', + }, + ], + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + + expect(plan.assignments).toContainEqual( + expect.objectContaining({ + state: 'reserved', + reservedAt: '2026-07-03T00:00:00.000Z', + }), + ); + expect(plan.assignments[0]).not.toHaveProperty('usedAt'); + expect(plan.assignments[0]).not.toHaveProperty('releasedAt'); + expect(plan.assignments[0]).not.toHaveProperty('voidedAt'); + expect(plan.assignments[0]).not.toHaveProperty('riotMatchId'); + }); + + it('preserves only the applicable lifecycle for a released code', () => { + const legacy = pairedMatch({ + _id: 'match-released-code-timeline', + gameCount: 1, + gameSchedule: undefined, + result: { games: [], seriesResults: [] }, + tournamentCodes: [ + { + _id: 'released-code-with-stale-terminal-fields', + state: 'released', + gameNumber: 1, + reservedAt: '2026-07-03T00:00:00.000Z', + usedAt: '2026-07-01T00:00:00.000Z', + releasedAt: '2026-07-04T00:00:00.000Z', + voidedAt: '2026-07-02T00:00:00.000Z', + riotMatchId: 'KR_STALE_RELEASED_LIFECYCLE', + }, + ], + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + + expect(plan.assignments[0]).toMatchObject({ + state: 'released', + reservedAt: '2026-07-03T00:00:00.000Z', + releasedAt: '2026-07-04T00:00:00.000Z', + }); + expect(plan.assignments[0]).not.toHaveProperty('usedAt'); + expect(plan.assignments[0]).not.toHaveProperty('voidedAt'); + expect(plan.assignments[0]).not.toHaveProperty('riotMatchId'); + }); + + it('uses updatedAt as voidedAt for the production reversal document shape', () => { + const legacy = pairedMatch({ + _id: 'match-voided-code-updated-at-fallback', + gameCount: 1, + gameSchedule: undefined, + result: { games: [], seriesResults: [] }, + tournamentCodes: [ + { + _id: 'voided-code-updated-at-fallback', + state: 'voided', + gameNumber: 1, + reservedAt: '2026-07-01T00:00:00.000Z', + usedAt: '2026-07-02T00:00:00.000Z', + updatedAt: '2026-07-03T00:00:00.000Z', + }, + ], + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + + expect(plan.assignments[0]).toMatchObject({ + state: 'voided', + voidedAt: '2026-07-03T00:00:00.000Z', + }); + }); + + it('normalizes a post-game reservation timestamp for an accepted used code', () => { + const legacy = pairedMatch({ + _id: 'match-post-game-used-code-reservation', + gameCount: 1, + gameSchedule: undefined, + updatedAt: '2026-07-03T00:06:00.000Z', + result: { + games: [ + legacyGame({ + gameNumber: 1, + riotMatchId: 'KR_POST_GAME_CODE_RESERVATION', + riotArchivePresent: true, + riotGameEndedAt: '2026-07-02T00:00:00.000Z', + riotGameEndedAtSource: 'gameEndTimestamp', + }), + ], + seriesResults: [], + }, + tournamentCodes: [ + { + _id: 'used-code-reserved-after-game', + state: 'used', + gameNumber: 1, + reservedAt: '2026-07-03T00:00:00.000Z', + usedAt: '2026-07-02T00:00:00.000Z', + updatedAt: '2026-07-03T00:05:00.000Z', + riotMatchId: 'KR_POST_GAME_CODE_RESERVATION', + }, + ], + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + + expect(plan.assignments[0]).toMatchObject({ + state: 'used', + reservedAt: '2026-07-03T00:00:00.000Z', + usedAt: '2026-07-03T00:05:00.000Z', + }); + expect(plan.warnings).toContainEqual({ + code: 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED', + message: + 'Legacy used TournamentCode usedAt represented Riot game time and was normalized to its persisted transition time.', + details: { + tournamentCodeId: 'used-code-reserved-after-game', + originalReservedAt: '2026-07-03T00:00:00.000Z', + originalUsedAt: '2026-07-02T00:00:00.000Z', + sourceUpdatedAt: '2026-07-03T00:05:00.000Z', + normalizedUsedAt: '2026-07-03T00:05:00.000Z', + factRecordedAt: '2026-07-03T00:06:00.000Z', + legacyOccurrenceSource: 'riot-archive-gameEndTimestamp', + riotMatchId: 'KR_POST_GAME_CODE_RESERVATION', + gameSlotId: plan.assignments[0].gameSlotId, + strategy: 'use-persisted-transition-time', + }, + }); + }); + + it('normalizes a chronological legacy Riot occurrence to the persisted used transition', () => { + const legacy = pairedMatch({ + _id: 'match-chronological-legacy-used-occurrence', + gameCount: 1, + gameSchedule: undefined, + updatedAt: '2026-07-02T00:06:00.000Z', + result: { + games: [ + legacyGame({ + gameNumber: 1, + riotMatchId: 'KR_CHRONOLOGICAL_LEGACY_USED_OCCURRENCE', + riotArchivePresent: true, + riotGameEndedAt: '2026-07-02T00:00:00.000Z', + riotGameEndedAtSource: 'gameEndTimestamp', + }), + ], + seriesResults: [], + }, + tournamentCodes: [ + { + _id: 'chronological-legacy-used-occurrence', + state: 'used', + gameNumber: 1, + reservedAt: '2026-07-01T00:00:00.000Z', + usedAt: '2026-07-02T00:00:00.000Z', + updatedAt: '2026-07-02T00:05:00.000Z', + riotMatchId: 'KR_CHRONOLOGICAL_LEGACY_USED_OCCURRENCE', + }, + ], + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + + expect(plan.assignments[0]).toMatchObject({ + reservedAt: '2026-07-01T00:00:00.000Z', + usedAt: '2026-07-02T00:05:00.000Z', + }); + expect(plan.warnings).toContainEqual( + expect.objectContaining({ + code: 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED', + }), + ); + }); + + it('recognizes the legacy Riot gameCreation fallback occurrence path', () => { + const legacy = pairedMatch({ + _id: 'match-legacy-game-creation-used-occurrence', + gameCount: 1, + gameSchedule: undefined, + updatedAt: '2026-07-02T00:06:00.000Z', + result: { + games: [ + legacyGame({ + gameNumber: 1, + riotMatchId: 'KR_LEGACY_GAME_CREATION_USED_OCCURRENCE', + riotArchivePresent: true, + riotGameEndedAt: '2026-07-02T00:00:00.000Z', + riotGameEndedAtSource: 'gameCreation', + }), + ], + seriesResults: [], + }, + tournamentCodes: [ + { + _id: 'legacy-game-creation-used-occurrence', + state: 'used', + gameNumber: 1, + reservedAt: '2026-07-01T00:00:00.000Z', + usedAt: '2026-07-02T00:00:00.000Z', + updatedAt: '2026-07-02T00:05:00.000Z', + riotMatchId: 'KR_LEGACY_GAME_CREATION_USED_OCCURRENCE', + }, + ], + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + + expect(plan.assignments[0].usedAt).toBe('2026-07-02T00:05:00.000Z'); + const warning = plan.warnings.find( + ({ code }) => code === 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED', + ); + expect(warning?.details).toMatchObject({ + legacyOccurrenceSource: 'riot-archive-gameCreation', + }); + }); + + it('recognizes the legacy repair gameCreation plus duration occurrence path', () => { + const legacy = pairedMatch({ + _id: 'match-repaired-legacy-used-occurrence', + gameCount: 1, + gameSchedule: undefined, + updatedAt: '2026-07-03T00:06:00.000Z', + result: { + games: [ + legacyGame({ + gameNumber: 1, + riotMatchId: 'KR_REPAIRED_LEGACY_USED_OCCURRENCE', + riotArchivePresent: true, + gameCreation: '2026-07-02T00:00:00.000Z', + gameDuration: 1800, + riotGameEndedAt: '2026-07-02T00:30:17.000Z', + riotGameEndedAtSource: 'gameEndTimestamp', + }), + ], + seriesResults: [], + }, + tournamentCodes: [ + { + _id: 'repaired-legacy-used-occurrence', + state: 'used', + gameNumber: 1, + reservedAt: '2026-07-01T00:00:00.000Z', + usedAt: '2026-07-02T00:30:00.000Z', + updatedAt: '2026-07-03T00:05:00.000Z', + riotMatchId: 'KR_REPAIRED_LEGACY_USED_OCCURRENCE', + }, + ], + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + + expect(plan.assignments[0]).toMatchObject({ + reservedAt: '2026-07-01T00:00:00.000Z', + usedAt: '2026-07-03T00:05:00.000Z', + }); + const warning = plan.warnings.find( + ({ code }) => code === 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED', + ); + expect(warning?.details).toMatchObject({ + legacyOccurrenceSource: 'legacy-gameCreation-plus-duration', + }); + }); + + it('does not normalize an inverted used-code lifecycle without Riot archive evidence', () => { + const legacy = pairedMatch({ + _id: 'match-unverified-used-code-transition', + gameCount: 1, + gameSchedule: undefined, + updatedAt: '2026-07-03T00:06:00.000Z', + result: { + games: [ + legacyGame({ + gameNumber: 1, + riotMatchId: 'KR_UNVERIFIED_USED_CODE_TRANSITION', + riotArchivePresent: false, + }), + ], + seriesResults: [], + }, + tournamentCodes: [ + { + _id: 'unverified-used-code-transition', + state: 'used', + gameNumber: 1, + reservedAt: '2026-07-03T00:00:00.000Z', + usedAt: '2026-07-02T00:00:00.000Z', + updatedAt: '2026-07-03T00:05:00.000Z', + riotMatchId: 'KR_UNVERIFIED_USED_CODE_TRANSITION', + }, + ], + }); + + const plan = planCompetitionMigration(legacy); + + expectQuarantineReason(plan, 'INVALID_TOURNAMENT_CODE_TIMELINE'); + }); + + it('preserves a chronological usedAt that does not match a known occurrence encoding', () => { + const legacy = pairedMatch({ + _id: 'match-current-used-transition-semantics', + gameCount: 1, + gameSchedule: undefined, + updatedAt: '2026-07-02T00:10:00.000Z', + result: { + games: [ + legacyGame({ + gameNumber: 1, + riotMatchId: 'KR_CURRENT_USED_TRANSITION_SEMANTICS', + riotArchivePresent: true, + riotGameEndedAt: '2026-07-02T00:00:00.000Z', + riotGameEndedAtSource: 'gameEndTimestamp', + }), + ], + seriesResults: [], + }, + tournamentCodes: [ + { + _id: 'current-used-transition-semantics', + state: 'used', + gameNumber: 1, + reservedAt: '2026-07-01T00:00:00.000Z', + usedAt: '2026-07-02T00:10:00.000Z', + updatedAt: '2026-07-02T00:10:00.000Z', + riotMatchId: 'KR_CURRENT_USED_TRANSITION_SEMANTICS', + }, + ], + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + + expect(plan.assignments[0].usedAt).toBe('2026-07-02T00:10:00.000Z'); + expect( + plan.warnings.some( + ({ code }) => code === 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED', + ), + ).toBe(false); + }); + + it('quarantines an inverted used timeline with an out-of-range legacy duration without throwing', () => { + const legacy = pairedMatch({ + _id: 'match-out-of-range-legacy-duration', + gameCount: 1, + gameSchedule: undefined, + updatedAt: '2026-07-03T00:06:00.000Z', + result: { + games: [ + legacyGame({ + gameNumber: 1, + riotMatchId: 'KR_OUT_OF_RANGE_LEGACY_DURATION', + riotArchivePresent: true, + gameCreation: '2026-07-02T00:00:00.000Z', + gameDuration: Number.MAX_VALUE, + }), + ], + seriesResults: [], + }, + tournamentCodes: [ + { + _id: 'out-of-range-legacy-duration', + state: 'used', + gameNumber: 1, + reservedAt: '2026-07-03T00:00:00.000Z', + usedAt: '2026-07-02T00:00:00.000Z', + updatedAt: '2026-07-03T00:05:00.000Z', + riotMatchId: 'KR_OUT_OF_RANGE_LEGACY_DURATION', + }, + ], + }); + + const plan = planCompetitionMigration(legacy); + + expectQuarantineReason(plan, 'INVALID_TOURNAMENT_CODE_TIMELINE'); + }); + + it('does not normalize an inverted used-code lifecycle with an invalid transition time', () => { + const legacy = pairedMatch({ + _id: 'match-invalid-used-code-transition-time', + gameCount: 1, + gameSchedule: undefined, + updatedAt: '2026-07-03T00:06:00.000Z', + result: { + games: [ + legacyGame({ + gameNumber: 1, + riotMatchId: 'KR_INVALID_USED_CODE_TRANSITION_TIME', + riotArchivePresent: true, + riotGameEndedAt: '2026-07-02T00:00:00.000Z', + riotGameEndedAtSource: 'gameEndTimestamp', + }), + ], + seriesResults: [], + }, + tournamentCodes: [ + { + _id: 'invalid-used-code-transition-time', + state: 'used', + gameNumber: 1, + reservedAt: '2026-07-03T00:00:00.000Z', + usedAt: '2026-07-02T00:00:00.000Z', + updatedAt: '2026-07-02T12:00:00.000Z', + riotMatchId: 'KR_INVALID_USED_CODE_TRANSITION_TIME', + }, + ], + }); + + const plan = planCompetitionMigration(legacy); + + expectQuarantineReason(plan, 'INVALID_TOURNAMENT_CODE_TIMELINE'); + }); + + it.each<[string, string | undefined]>([ + ['missing', undefined], + ['earlier than the Riot occurrence', '2026-07-01T12:00:00.000Z'], + ])( + 'quarantines a recognized legacy occurrence when persisted transition time is %s', + (_label, updatedAt) => { + const legacy = pairedMatch({ + _id: `match-invalid-persisted-transition-${_label}`, + gameCount: 1, + gameSchedule: undefined, + updatedAt: '2026-07-03T00:06:00.000Z', + result: { + games: [ + legacyGame({ + gameNumber: 1, + riotMatchId: 'KR_INVALID_PERSISTED_TRANSITION', + riotArchivePresent: true, + riotGameEndedAt: '2026-07-02T00:00:00.000Z', + riotGameEndedAtSource: 'gameEndTimestamp', + }), + ], + seriesResults: [], + }, + tournamentCodes: [ + { + _id: `invalid-persisted-transition-${_label}`, + state: 'used', + gameNumber: 1, + reservedAt: '2026-07-01T00:00:00.000Z', + usedAt: '2026-07-02T00:00:00.000Z', + ...(updatedAt ? { updatedAt } : {}), + riotMatchId: 'KR_INVALID_PERSISTED_TRANSITION', + }, + ], + }); + + const plan = planCompetitionMigration(legacy); + + expectQuarantineReason(plan, 'INVALID_TOURNAMENT_CODE_TIMELINE'); + }, + ); + + it('does not normalize a used-code transition recorded after the accepted fact', () => { + const legacy = pairedMatch({ + _id: 'match-used-code-transition-after-fact', + gameCount: 1, + gameSchedule: undefined, + updatedAt: '2026-07-03T00:04:00.000Z', + result: { + games: [ + legacyGame({ + gameNumber: 1, + riotMatchId: 'KR_USED_CODE_TRANSITION_AFTER_FACT', + riotArchivePresent: true, + riotGameEndedAt: '2026-07-02T00:00:00.000Z', + riotGameEndedAtSource: 'gameEndTimestamp', + }), + ], + seriesResults: [], + }, + tournamentCodes: [ + { + _id: 'used-code-transition-after-fact', + state: 'used', + gameNumber: 1, + reservedAt: '2026-07-03T00:00:00.000Z', + usedAt: '2026-07-02T00:00:00.000Z', + updatedAt: '2026-07-03T00:05:00.000Z', + riotMatchId: 'KR_USED_CODE_TRANSITION_AFTER_FACT', + }, + ], + }); + + const plan = planCompetitionMigration(legacy); + + expectQuarantineReason(plan, 'INVALID_TOURNAMENT_CODE_TIMELINE'); + }); + + it('still quarantines an inverted released-code lifecycle', () => { + const legacy = pairedMatch({ + _id: 'match-inverted-released-code-timeline', + gameCount: 1, + gameSchedule: undefined, + result: { games: [], seriesResults: [] }, + tournamentCodes: [ + { + _id: 'released-code-inverted-current-timeline', + state: 'released', + gameNumber: 1, + reservedAt: '2026-07-03T00:00:00.000Z', + releasedAt: '2026-07-02T00:00:00.000Z', + }, + ], + }); + + const plan = planCompetitionMigration(legacy); + + expectQuarantineReason(plan, 'INVALID_TOURNAMENT_CODE_TIMELINE'); + }); + + it('maps a result-less reserved TournamentCode by its global game number', () => { + const legacy = pairedMatch({ + _id: 'match-future-reserved-code', + gameCount: 2, + teams: [ + legacyTeam(1, 'One'), + legacyTeam(2, 'Two'), + legacyTeam(3, 'Three'), + legacyTeam(4, 'Four'), + ], + gameSchedule: undefined, + result: { games: [], seriesResults: [] }, + tournamentCodes: [ + { + _id: 'future-code-for-global-game-3', + state: 'reserved', + gameNumber: 3, + }, + ], + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + const expectedSeries = plan.competition.seriesGraph.find( + (series) => series.code === 'PAIR_M2', + ); + + expect(expectedSeries).toBeDefined(); + expect(plan.assignments).toContainEqual( + expect.objectContaining({ + tournamentCodeId: 'future-code-for-global-game-3', + seriesId: expectedSeries!.id, + gameSlotId: expectedSeries!.gameSlots[0].id, + }), + ); + }); + + it('maps persisted WB_FINAL global game numbers to distinct stable slots', () => { + const legacy = loadDataTxtFixture(); + legacy.result = { games: [], seriesResults: [] }; + legacy.doubleElimination!.bracketMatches = dataTxtUpperBracketTopology(); + legacy.tournamentCodes = [19, 20, 21].map((gameNumber, index) => ({ + _id: `wb-final-code-${index + 1}`, + state: 'reserved' as const, + bracketMatchId: 'WB_FINAL', + gameNumber, + })); + + const plan = requireReady(planCompetitionMigration(legacy)); + const wbFinal = plan.competition.seriesGraph.find( + (series) => series.code === 'WB_FINAL', + ); + + expect(wbFinal).toBeDefined(); + expect(wbFinal!.gameSlots).toHaveLength(3); + expect(plan.assignments).toHaveLength(3); + for (const [index, slot] of wbFinal!.gameSlots.entries()) { + expect(plan.assignments).toContainEqual( + expect.objectContaining({ + tournamentCodeId: `wb-final-code-${index + 1}`, + seriesId: wbFinal!.id, + gameSlotId: slot.id, + }), + ); + } + }); + + it('quarantines a TournamentCode whose bracket identity conflicts with its global game number', () => { + const legacy = loadDataTxtFixture(); + legacy.result = { games: [], seriesResults: [] }; + legacy.doubleElimination!.bracketMatches = dataTxtUpperBracketTopology(); + legacy.tournamentCodes = [ + { + _id: 'conflicting-wb-final-code', + state: 'reserved', + bracketMatchId: 'WB_FINAL', + gameNumber: 1, + }, + ]; + + const plan = planCompetitionMigration(legacy); + + expectQuarantineReason(plan, 'TOURNAMENT_CODE_ASSIGNMENT_CONFLICT'); + }); + + it('quarantines conflicting Riot evidence and global game number', () => { + const legacy = pairedMatch({ + _id: 'match-conflicting-code-evidence', + gameCount: 2, + gameSchedule: undefined, + result: { + games: [ + legacyGame({ + gameNumber: 1, + riotMatchId: 'KR_CONFLICTING_CODE_EVIDENCE', + blueTeamIndex: 1, + redTeamIndex: 2, + winnerTeamIndex: 1, + riotArchivePresent: true, + }), + ], + seriesResults: [], + }, + tournamentCodes: [ + { + _id: 'code-with-conflicting-evidence', + state: 'used', + gameNumber: 2, + riotMatchId: 'KR_CONFLICTING_CODE_EVIDENCE', + }, + ], + }); + + expectQuarantineReason( + planCompetitionMigration(legacy), + 'TOURNAMENT_CODE_ASSIGNMENT_CONFLICT', + ); + }); + + it('quarantines a TournamentCode game number outside the Competition topology', () => { + const legacy = pairedMatch({ + _id: 'match-out-of-range-code', + gameSchedule: undefined, + result: { games: [], seriesResults: [] }, + tournamentCodes: [ + { + _id: 'out-of-range-code', + state: 'reserved', + gameNumber: 99, + }, + ], + }); + + expectQuarantineReason( + planCompetitionMigration(legacy), + 'TOURNAMENT_CODE_ASSIGNMENT_MAPPING_NOT_FOUND', + ); + }); + + it('does not guess the first slot of a multi-slot Series without exact slot evidence', () => { + const legacy = pairedMatch({ + _id: 'match-multi-slot-code-without-evidence', + gameCount: 3, + result: { games: [], seriesResults: [] }, + tournamentCodes: [ + { + _id: 'code-with-series-only', + state: 'reserved', + bracketMatchId: 'PAIR_M1', + }, + ], + }); + + const plan = planCompetitionMigration(legacy); + + expectQuarantineReason( + plan, + 'TOURNAMENT_CODE_ASSIGNMENT_MAPPING_NOT_FOUND', + ); + }); + + 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')?.entries.some( + (entry) => + entry.slot === 'B' && + entry.teamId === team8!.teamId && + entry.gameWins === 0, + ), + ).toBe(true); + expect( + series('LB_R2_M1')?.entries.some( + (entry) => + entry.slot === 'B' && + entry.teamId === team3!.teamId && + entry.gameWins === 0, + ), + ).toBe(true); + }); +}); + +function pairedMatch( + overrides: Partial = {}, +): 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['games'][number]>, +): NonNullable['games'][number] { + return { + gameNumber: 1, + riotMatchId: 'KR_DEFAULT', + blueTeamIndex: 1, + redTeamIndex: 2, + winnerTeamIndex: 1, + gameCreation: 1782864000000, + gameDuration: 1800, + participants: [], + ...overrides, + }; +} + +function requireReady( + plan: ReturnType, +): ReadyCompetitionMigrationPlan { + if (plan.status !== 'ready') { + throw new Error( + `Expected ready migration plan: ${JSON.stringify(plan.reasons)}`, + ); + } + return plan; +} + +function expectQuarantineReason( + plan: ReturnType, + code: string, +): void { + expect(plan.status).toBe('quarantined'); + if (plan.status !== 'quarantined') { + throw new Error( + `Expected a quarantined migration plan, got ${plan.status}.`, + ); + } + expect(plan.reasons.some((reason) => reason.code === code)).toBe(true); +} + +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', + }; +} + +function dataTxtUpperBracketTopology() { + return [ + 'WB_R1_M1', + 'WB_R1_M2', + 'WB_R1_M3', + 'WB_R1_M4', + 'WB_R2_M1', + 'WB_R2_M2', + 'WB_FINAL', + ].map((bracketMatchId, index) => ({ + bracketMatchId, + gameNumber: index + 1, + gameCount: 3, + requiredWins: 2, + bracketSide: 'winner' as const, + })); +} + +function sparseDoubleEliminationWbFinalMatch(): LegacyMatchInput { + const completedSeries = [ + ['WB_R1_M1', 1, 2, 1, 8, 1], + ['WB_R1_M2', 4, 5, 4, 5, 4], + ['WB_R1_M3', 7, 8, 2, 7, 2], + ['WB_R1_M4', 10, 11, 3, 6, 3], + ['WB_R2_M1', 13, 14, 1, 4, 1], + ['WB_R2_M2', 16, 17, 2, 3, 2], + ] as const; + const games = completedSeries.flatMap( + ([ + bracketMatchId, + firstGameNumber, + secondGameNumber, + teamA, + teamB, + winner, + ]) => [ + legacyGame({ + bracketMatchId, + gameNumber: firstGameNumber, + riotMatchId: `KR_${bracketMatchId}_1`, + riotArchivePresent: true, + blueTeamIndex: teamA, + redTeamIndex: teamB, + winnerTeamIndex: winner, + gameCreation: 1782864000000 + firstGameNumber * 60_000, + }), + legacyGame({ + bracketMatchId, + gameNumber: secondGameNumber, + riotMatchId: `KR_${bracketMatchId}_2`, + riotArchivePresent: true, + blueTeamIndex: teamB, + redTeamIndex: teamA, + winnerTeamIndex: winner, + gameCreation: 1782864000000 + secondGameNumber * 60_000, + }), + ], + ); + games.push( + legacyGame({ + bracketMatchId: 'WB_FINAL', + gameNumber: 20, + riotMatchId: 'KR_SPARSE_WB_FINAL_GAME_2', + riotArchivePresent: true, + blueTeamIndex: 1, + redTeamIndex: 2, + winnerTeamIndex: 1, + gameCreation: 1782864000000 + 20 * 60_000, + }), + ); + + return { + _id: 'match-sparse-double-elimination-game-number', + communityId: 'community-1', + gameMode: 'double-elimination', + gameCount: 3, + status: 'in-progress', + teams: Array.from({ length: 8 }, (_, index) => + legacyTeam(index + 1, `${index + 1}팀`), + ), + doubleElimination: { + teamCount: 8, + resetFinalEnabled: true, + seeds: Array.from({ length: 8 }, (_, index) => ({ + seedNumber: index + 1, + teamIndex: index + 1, + })), + bracketMatches: dataTxtUpperBracketTopology(), + }, + result: { games, seriesResults: [] }, + tournamentCodes: [ + { + _id: 'sparse-wb-final-code-game-2', + state: 'used', + bracketMatchId: 'WB_FINAL', + gameNumber: 20, + riotMatchId: 'KR_SPARSE_WB_FINAL_GAME_2', + reservedAt: '2026-07-01T00:00:00.000Z', + usedAt: '2026-07-02T00:00:00.000Z', + }, + ], + createdAt: '2026-07-01T00:00:00.000Z', + updatedAt: '2026-07-03T00:00:00.000Z', + }; +} diff --git a/apps/api/src/modules/global/database/migrations/20260712-competition-domain.ts b/apps/api/src/modules/global/database/migrations/20260712-competition-domain.ts new file mode 100644 index 00000000..26a41ed5 --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/20260712-competition-domain.ts @@ -0,0 +1,2557 @@ +import { createHash } from 'node:crypto'; +import { projectCompetition } from '../../../competition/domain/competition-projector'; +import { + generateSeriesGraph, + type CompetitionGraphFormat, + type RoundRobinPairing, + type SeriesDefinition, +} from '../../../competition/domain/series-graph'; + +const MIGRATION_RUN_ID = '20260712-competition-domain'; +const SCHEMA_VERSION = 1; +const PROJECTOR_VERSION = 1; +const EPOCH = '1970-01-01T00:00:00.000Z'; + +type LegacyGameMode = 'pair' | 'bracket' | 'round-robin' | 'double-elimination'; + +interface LegacyTeamMemberInput { + userId: unknown; + assignedPosition?: string; + cost?: number; +} + +interface LegacyTeamInput { + teamIndex: number; + name?: string; + captainUserId?: unknown; + members?: LegacyTeamMemberInput[]; +} + +interface LegacyParticipantInput { + userId: unknown; + gameName?: string; + tagLine?: string; + profileIconId?: number; +} + +interface LegacyGameInput { + gameNumber: number; + bracketMatchId?: string; + riotMatchId?: string; + riotArchivePresent?: boolean; + payloadHash?: string; + blueTeamIndex: number; + redTeamIndex: number; + winnerTeamIndex: number; + winnerSide?: 'blue' | 'red'; + gameCreation?: number | string | Date; + gameDuration?: number; + riotGameEndedAt?: number | string | Date; + riotGameEndedAtSource?: 'gameEndTimestamp' | 'gameCreation'; + participants?: Array<{ + userId?: unknown; + teamIndex?: number; + side?: 'blue' | 'red'; + [key: string]: unknown; + }>; +} + +type LegacyUsedOccurrenceSource = + | 'riot-archive-gameEndTimestamp' + | 'riot-archive-gameCreation' + | 'legacy-gameCreation-plus-duration'; + +interface LegacyUsedOccurrenceEvidence { + at: string; + source: LegacyUsedOccurrenceSource; +} + +interface LegacySeriesResultInput { + bracketMatchId?: string; + teamAIndex: number; + teamBIndex: number; + teamAWins?: number; + teamBWins?: number; + winnerTeamIndex?: number; +} + +interface LegacyBracketMatchInput { + bracketMatchId: string; + gameNumber?: number; + gameCount?: number; + requiredWins?: number; + bracketSide?: 'winner' | 'loser' | 'grand-final' | 'reset-final'; + state?: 'pending' | 'ready' | 'completed'; + winnerTeamIndex?: number; + completedAt?: Date | string; + completedBy?: 'riot-result' | 'walkover'; + walkover?: { + winnerTeamIndex: number; + reason?: string; + awardedBy?: unknown; + awardedAt?: Date | string; + active: boolean; + }; +} + +interface LegacyTournamentCodeInput { + _id: unknown; + state?: 'available' | 'reserved' | 'used' | 'expired' | 'released' | 'voided'; + gameNumber?: number; + bracketMatchId?: string; + riotMatchId?: string; + reservedAt?: Date | string; + usedAt?: Date | string; + releasedAt?: Date | string; + voidedAt?: Date | string; + createdAt?: Date | string; + updatedAt?: Date | string; +} + +export interface LegacyMatchInput { + _id: unknown; + communityId: unknown; + gameMode: LegacyGameMode; + gameCount: number; + roundRobinMaxRounds?: number; + status?: string; + participants?: LegacyParticipantInput[]; + teams: LegacyTeamInput[]; + gameSchedule?: Array<{ + gameNumber: number; + roundNumber?: number; + teamAIndex: number; + teamBIndex: number; + }>; + result?: { + winnerTeamIndex?: number; + riotMatchIds?: string[]; + games: LegacyGameInput[]; + seriesResults?: LegacySeriesResultInput[]; + }; + doubleElimination?: { + teamCount?: 4 | 8; + resetFinalEnabled?: boolean; + seeds?: Array<{ seedNumber: number; teamIndex: number }>; + bracketMatches?: LegacyBracketMatchInput[]; + }; + tournamentCodes?: LegacyTournamentCodeInput[]; + riotMatchArchiveIds?: string[]; + createdAt?: Date | string; + updatedAt?: Date | string; +} + +export interface CompetitionMigrationIssue { + code: string; + message: string; + details?: Record; +} + +export interface CompetitionMigrationTeamSnapshot { + teamId: string; + legacyTeamIndex: number; + displayOrder: number; + seedNumber: number; + name: string; + captainUserId?: string; + members: Array<{ + userId: string; + displayName: string; + gameName?: string; + tagLine?: string; + profileIconId?: number; + assignedPosition?: string; + cost?: number; + }>; +} + +interface MigrationFactBase { + id: string; + competitionId: string; + revision: number; + ordinalWithinRevision: 1; + commandId: string; + idempotencyKey: string; + requestHash: string; + schemaVersion: 1; + actor: { type: 'migration'; migrationRunId: string }; + occurredAt: string; + recordedAt: string; +} + +export interface MigrationGameAcceptedFact extends MigrationFactBase { + type: 'game-accepted'; + gameId: string; + seriesId: string; + gameSlotId: string; + ordinal: number; + startedAt: string; + durationSeconds: number; + participants: Array<{ + userId: string; + teamId: string; + side: 'blue' | 'red'; + summonerName: string; + tagLine: string; + championId: number; + kills: number; + deaths: number; + assists: number; + }>; + evidence: + | { type: 'riot'; riotMatchId: string; payloadHash: string } + | { type: 'legacy'; legacyReference: string }; + mapping: { + mappingVersion: 1; + confidence: number; + blueTeamId: string; + redTeamId: string; + winnerTeamId: string; + participantAssignments: Array<{ + userId: string; + teamId: string; + side: 'blue' | 'red'; + }>; + }; +} + +export interface MigrationSeriesAdjudicatedFact extends MigrationFactBase { + type: 'series-adjudicated'; + seriesId: string; + decision: + | { + type: 'walkover' | 'administrative'; + winnerTeamId: string; + } + | { type: 'administrative-draw' }; + reason: string; +} + +export type CompetitionMigrationFact = + | MigrationGameAcceptedFact + | MigrationSeriesAdjudicatedFact; + +export interface CompetitionMigrationAssignment { + id: string; + competitionId: string; + seriesId: string; + gameSlotId: string; + tournamentCodeId: string; + state: 'reserved' | 'used' | 'released' | 'voided'; + reservedAt: string; + usedAt?: string; + releasedAt?: string; + voidedAt?: string; + riotMatchId?: string; + commandId: string; +} + +export interface CompetitionMigrationSnapshot { + id: string; + matchId: string; + communityId: string; + schemaVersion: 1; + projectorVersion: 1; + revision: number; + phase: 'ready' | 'running' | 'completed' | 'cancelled'; + teams: CompetitionMigrationTeamSnapshot[]; + format: CompetitionGraphFormat; + seriesGraph: SeriesDefinition[]; + projection: ReturnType; + createdAt: string; + updatedAt: string; +} + +export interface ReadyCompetitionMigrationPlan { + status: 'ready'; + competition: CompetitionMigrationSnapshot; + facts: CompetitionMigrationFact[]; + assignments: CompetitionMigrationAssignment[]; + warnings: CompetitionMigrationIssue[]; +} + +export interface QuarantinedCompetitionMigrationPlan { + status: 'quarantined'; + matchId: string; + reasons: CompetitionMigrationIssue[]; + warnings: CompetitionMigrationIssue[]; +} + +export type CompetitionMigrationPlan = + | ReadyCompetitionMigrationPlan + | QuarantinedCompetitionMigrationPlan; + +interface PlannedGame { + legacy: LegacyGameInput; + series: SeriesDefinition; + confidence: number; + ordinal: number; +} + +interface PendingFact { + kind: CompetitionMigrationFact['type']; + seriesOrder: number; + occurredAt: string; + logicalKey: string; + build(base: MigrationFactBase): CompetitionMigrationFact; +} + +/** + * Builds an entirely deterministic write plan from one legacy Match snapshot. + * It performs no I/O and deliberately quarantines uncertainty instead of + * guessing a Series or team identity. + */ +export function planCompetitionMigration( + input: LegacyMatchInput, + options: { migrationRunId?: string } = {}, +): CompetitionMigrationPlan { + const migrationRunId = options.migrationRunId ?? MIGRATION_RUN_ID; + const warnings: CompetitionMigrationIssue[] = []; + const reasons: CompetitionMigrationIssue[] = []; + const matchId = opaqueString(input?._id); + const communityId = opaqueString(input?.communityId); + + if (!matchId) { + reasons.push( + issue('MATCH_ID_MISSING', 'The legacy Match has no identity.'), + ); + } + if (!communityId) { + reasons.push( + issue( + 'COMMUNITY_ID_MISSING', + 'The legacy Match has no Community identity.', + ), + ); + } + + const competitionId = stableId(matchId || 'missing-match', 'competition'); + const teamBuild = buildTeamSnapshots(input, competitionId, reasons); + if (reasons.length > 0) { + return quarantined(matchId, reasons, warnings); + } + + const format = buildFormat( + input, + teamBuild.teamIdByLegacyIndex, + warnings, + reasons, + ); + if (!format) return quarantined(matchId, reasons, warnings); + + let seriesGraph: SeriesDefinition[]; + try { + seriesGraph = generateSeriesGraph({ + competitionId, + teams: teamBuild.teams, + format, + }); + } catch (error) { + reasons.push( + issue( + 'SERIES_GRAPH_GENERATION_FAILED', + errorMessage(error), + errorCodeDetails(error), + ), + ); + return quarantined(matchId, reasons, warnings); + } + + const plannedGames = mapGames( + input, + seriesGraph, + teamBuild.teamIdByLegacyIndex, + reasons, + ); + const pendingFacts: PendingFact[] = []; + addGameFacts( + input, + competitionId, + plannedGames, + teamBuild.teamIdByLegacyIndex, + seriesGraph, + pendingFacts, + reasons, + ); + addAdjudicationFacts( + input, + competitionId, + plannedGames, + teamBuild.teamIdByLegacyIndex, + seriesGraph, + pendingFacts, + reasons, + ); + if (reasons.length > 0) { + return quarantined(matchId, reasons, warnings); + } + + const facts = materializeFacts( + competitionId, + migrationRunId, + normalizeDate(input.updatedAt, normalizeDate(input.createdAt, EPOCH)), + pendingFacts, + ); + + let projection: ReturnType; + try { + projection = projectCompetition({ + competitionId, + revision: facts.length, + projectorVersion: PROJECTOR_VERSION, + teams: teamBuild.teams, + format, + seriesGraph, + facts, + }); + } catch (error) { + reasons.push( + issue( + 'MIGRATION_PROJECTION_REJECTED', + errorMessage(error), + errorCodeDetails(error), + ), + ); + return quarantined(matchId, reasons, warnings); + } + + const assignments = buildAssignments( + input, + competitionId, + facts, + seriesGraph, + teamBuild.teamIdByLegacyIndex, + reasons, + warnings, + ); + if (reasons.length > 0) { + return quarantined(matchId, reasons, warnings); + } + + const createdAt = normalizeDate(input.createdAt, EPOCH); + const updatedAt = normalizeDate(input.updatedAt, createdAt); + return { + status: 'ready', + competition: { + id: competitionId, + matchId, + communityId, + schemaVersion: SCHEMA_VERSION, + projectorVersion: PROJECTOR_VERSION, + revision: facts.length, + phase: projection.phase, + teams: teamBuild.teams, + format, + seriesGraph, + projection, + createdAt, + updatedAt, + }, + facts, + assignments, + warnings: sortedIssues(warnings), + }; +} + +function buildTeamSnapshots( + input: LegacyMatchInput, + competitionId: string, + reasons: CompetitionMigrationIssue[], +): { + teams: CompetitionMigrationTeamSnapshot[]; + teamIdByLegacyIndex: Map; +} { + const legacyTeams = Array.isArray(input?.teams) ? input.teams : []; + if (legacyTeams.length < 2) { + reasons.push( + issue('TEAMS_MISSING', 'At least two legacy teams are required.'), + ); + } + + const indexes = new Set(); + for (const team of legacyTeams) { + if (!Number.isInteger(team.teamIndex) || team.teamIndex < 1) { + reasons.push( + issue('INVALID_LEGACY_TEAM_INDEX', 'A legacy team index is invalid.', { + teamIndex: team.teamIndex, + }), + ); + continue; + } + if (indexes.has(team.teamIndex)) { + reasons.push( + issue( + 'DUPLICATE_LEGACY_TEAM_INDEX', + `Legacy team index ${team.teamIndex} occurs more than once.`, + { teamIndex: team.teamIndex }, + ), + ); + } + indexes.add(team.teamIndex); + } + + const sorted = [...legacyTeams].sort( + (left, right) => left.teamIndex - right.teamIndex, + ); + const displayOrderByIndex = new Map( + sorted.map((team, index) => [team.teamIndex, index + 1]), + ); + const seedByTeamIndex = seedMap(input, sorted, reasons); + const participantByUserId = new Map( + (input.participants ?? []).map((participant) => [ + opaqueString(participant.userId), + participant, + ]), + ); + const teamIdByLegacyIndex = new Map(); + const teams = sorted.map((team) => { + const teamId = stableId(competitionId, 'team', team.teamIndex); + teamIdByLegacyIndex.set(team.teamIndex, teamId); + const members = (team.members ?? []).map((member) => { + const userId = opaqueString(member.userId); + const participant = participantByUserId.get(userId); + return { + userId, + displayName: + participant?.gameName || + (userId ? `legacy-user:${userId}` : 'legacy-user'), + ...(participant?.gameName ? { gameName: participant.gameName } : {}), + ...(participant?.tagLine ? { tagLine: participant.tagLine } : {}), + ...(typeof participant?.profileIconId === 'number' + ? { profileIconId: participant.profileIconId } + : {}), + ...(member.assignedPosition + ? { assignedPosition: member.assignedPosition } + : {}), + ...(typeof member.cost === 'number' ? { cost: member.cost } : {}), + }; + }); + const captainUserId = opaqueString(team.captainUserId); + return { + teamId, + legacyTeamIndex: team.teamIndex, + displayOrder: displayOrderByIndex.get(team.teamIndex)!, + seedNumber: seedByTeamIndex.get(team.teamIndex)!, + name: team.name?.trim() || `${team.teamIndex}팀`, + ...(captainUserId ? { captainUserId } : {}), + members, + }; + }); + + return { teams, teamIdByLegacyIndex }; +} + +function seedMap( + input: LegacyMatchInput, + sortedTeams: LegacyTeamInput[], + reasons: CompetitionMigrationIssue[], +): Map { + if (input.gameMode !== 'double-elimination') { + return new Map( + sortedTeams.map((team, index) => [team.teamIndex, index + 1]), + ); + } + + const seeds = input.doubleElimination?.seeds ?? []; + if (seeds.length !== sortedTeams.length) { + reasons.push( + issue( + 'INVALID_DOUBLE_ELIMINATION_SEEDS', + 'Every double-elimination team must have exactly one seed.', + ), + ); + } + const result = new Map(); + const seenSeeds = new Set(); + for (const seed of seeds) { + if ( + !Number.isInteger(seed.seedNumber) || + seed.seedNumber < 1 || + seenSeeds.has(seed.seedNumber) || + !sortedTeams.some((team) => team.teamIndex === seed.teamIndex) || + result.has(seed.teamIndex) + ) { + reasons.push( + issue( + 'INVALID_DOUBLE_ELIMINATION_SEEDS', + 'Double-elimination seeds are duplicate, non-contiguous, or reference an unknown team.', + { seedNumber: seed.seedNumber, teamIndex: seed.teamIndex }, + ), + ); + continue; + } + seenSeeds.add(seed.seedNumber); + result.set(seed.teamIndex, seed.seedNumber); + } + for (let seedNumber = 1; seedNumber <= sortedTeams.length; seedNumber += 1) { + if (!seenSeeds.has(seedNumber)) { + reasons.push( + issue( + 'INVALID_DOUBLE_ELIMINATION_SEEDS', + 'Double-elimination seeds must be contiguous from one.', + { missingSeedNumber: seedNumber }, + ), + ); + } + } + return result; +} + +function buildFormat( + input: LegacyMatchInput, + teamIds: Map, + warnings: CompetitionMigrationIssue[], + reasons: CompetitionMigrationIssue[], +): CompetitionGraphFormat | undefined { + const gameCount = positiveInteger(input.gameCount); + if (!gameCount) { + reasons.push( + issue( + 'INVALID_GAME_COUNT', + 'Legacy gameCount must be a positive integer.', + ), + ); + return undefined; + } + + switch (input.gameMode) { + case 'pair': + return fixedFormat('paired-series', gameCount); + case 'bracket': + warnings.push( + issue( + 'LEGACY_BRACKET_MAPPED_TO_PAIRED_SERIES', + 'The unused legacy bracket mode was executed as paired Series and is migrated accordingly.', + ), + ); + return fixedFormat('paired-series', gameCount); + case 'round-robin': { + const pairings = normalizeLegacyRoundRobinPairings( + input, + teamIds, + gameCount, + warnings, + reasons, + ); + if (pairings === null) return undefined; + return { + type: 'round-robin', + rule: fixedRule(gameCount), + ...(positiveInteger(input.roundRobinMaxRounds) + ? { maxRounds: input.roundRobinMaxRounds } + : {}), + ...(pairings ? { pairings } : {}), + tieBreakers: ['series-wins', 'game-diff', 'head-to-head'], + }; + } + case 'double-elimination': { + const teamCount = input.teams.length; + if (teamCount !== 4 && teamCount !== 8) { + reasons.push( + issue( + 'UNSUPPORTED_DOUBLE_ELIMINATION_TEAM_COUNT', + 'Only four- and eight-team double elimination can be migrated.', + { teamCount }, + ), + ); + return undefined; + } + const bracketMatches = input.doubleElimination?.bracketMatches ?? []; + return { + type: 'double-elimination', + teamCount, + resetFinalEnabled: input.doubleElimination?.resetFinalEnabled ?? false, + rules: { + upper: legacyFirstToRule(bracketMatches, 'winner', gameCount), + lower: legacyFirstToRule(bracketMatches, 'loser', 1), + grandFinal: legacyFirstToRule(bracketMatches, 'grand-final', 1), + resetFinal: legacyFirstToRule(bracketMatches, 'reset-final', 1), + }, + }; + } + default: + reasons.push( + issue( + 'UNSUPPORTED_LEGACY_GAME_MODE', + `Unsupported legacy game mode: ${String(input.gameMode)}`, + ), + ); + return undefined; + } +} + +function normalizeLegacyRoundRobinPairings( + input: LegacyMatchInput, + teamIds: ReadonlyMap, + gameCount: number, + warnings: CompetitionMigrationIssue[], + reasons: CompetitionMigrationIssue[], +): RoundRobinPairing[] | undefined | null { + const schedule = input.gameSchedule ?? []; + if (schedule.length === 0) return undefined; + + const seenGameNumbers = new Set(); + const groups = new Map< + string, + { + roundNumber?: number; + teamAId: string; + teamBId: string; + gameNumbers: number[]; + } + >(); + const hasRoundNumbers = schedule.some( + (assignment) => assignment.roundNumber !== undefined, + ); + if ( + hasRoundNumbers && + schedule.some((assignment) => assignment.roundNumber === undefined) + ) { + reasons.push( + issue( + 'INVALID_ROUND_ROBIN_SCHEDULE', + 'Persisted round-robin round numbers must be present for every game or absent from every game.', + ), + ); + return null; + } + + for (const assignment of schedule) { + const teamAId = teamIds.get(assignment.teamAIndex); + const teamBId = teamIds.get(assignment.teamBIndex); + const roundNumber = + assignment.roundNumber === undefined + ? undefined + : positiveInteger(assignment.roundNumber); + if ( + !positiveInteger(assignment.gameNumber) || + seenGameNumbers.has(assignment.gameNumber) || + !teamAId || + !teamBId || + teamAId === teamBId || + (hasRoundNumbers && !roundNumber) || + (positiveInteger(input.roundRobinMaxRounds) !== undefined && + roundNumber !== undefined && + roundNumber > input.roundRobinMaxRounds!) + ) { + reasons.push( + issue( + 'INVALID_ROUND_ROBIN_SCHEDULE', + 'The persisted round-robin schedule has an invalid game, round, or team identity.', + { gameNumber: assignment.gameNumber }, + ), + ); + return null; + } + seenGameNumbers.add(assignment.gameNumber); + + const opponents = [teamAId, teamBId].sort(); + const key = JSON.stringify(opponents); + const existing = groups.get(key); + if (existing && existing.roundNumber !== roundNumber) { + reasons.push( + issue( + 'INVALID_ROUND_ROBIN_SCHEDULE', + 'A persisted round-robin opponent pair occurs in multiple rounds.', + { gameNumber: assignment.gameNumber }, + ), + ); + return null; + } + const group = + existing ?? + ({ + roundNumber, + teamAId, + teamBId, + gameNumbers: [], + } satisfies { + roundNumber?: number; + teamAId: string; + teamBId: string; + gameNumbers: number[]; + }); + group.gameNumbers.push(assignment.gameNumber); + groups.set(key, group); + } + + const groupedSeries = [...groups.values()]; + if (!hasRoundNumbers) { + const reconstruction = assignLegacyRoundRobinRounds( + groupedSeries, + [...teamIds.values()], + input.roundRobinMaxRounds, + ); + if (reconstruction !== 'assigned') { + const [code, message] = + reconstruction === 'unsupported-size' + ? [ + 'ROUND_ROBIN_ROUND_RECONSTRUCTION_UNSUPPORTED', + 'Opponent-only partial round-robin reconstruction supports at most 16 teams.', + ] + : reconstruction === 'search-limit-exceeded' + ? [ + 'ROUND_ROBIN_ROUND_RECONSTRUCTION_LIMIT_EXCEEDED', + 'Opponent-only round-robin reconstruction exceeded its deterministic search limit.', + ] + : [ + 'INVALID_ROUND_ROBIN_SCHEDULE', + 'The persisted round-robin opponent pairs cannot be reconstructed as complete playable rounds.', + ]; + reasons.push(issue(code, message, { teamCount: teamIds.size })); + return null; + } + } + if (!hasRoundNumbers) { + warnings.push( + issue( + 'LEGACY_ROUND_ROBIN_ROUNDS_RECONSTRUCTED', + 'Playable round numbers were reconstructed deterministically from a legacy opponent-only schedule.', + ), + ); + } + + const orderedGroups = groupedSeries.sort( + (left, right) => + left.roundNumber! - right.roundNumber! || + Math.min(...left.gameNumbers) - Math.min(...right.gameNumbers), + ); + const teamsByRound = new Map>(); + const matchNumberByRound = new Map(); + const pairings: RoundRobinPairing[] = []; + for (const group of orderedGroups) { + const roundNumber = group.roundNumber!; + if (group.gameNumbers.length !== gameCount) { + reasons.push( + issue( + 'INVALID_ROUND_ROBIN_SCHEDULE', + 'Every persisted round-robin Series must contain exactly gameCount scheduled games.', + { + roundNumber, + scheduledGameCount: group.gameNumbers.length, + expectedGameCount: gameCount, + }, + ), + ); + return null; + } + const roundTeams = teamsByRound.get(roundNumber) ?? new Set(); + if (roundTeams.has(group.teamAId) || roundTeams.has(group.teamBId)) { + reasons.push( + issue( + 'INVALID_ROUND_ROBIN_SCHEDULE', + 'A team appears in multiple persisted Series in the same round.', + { roundNumber }, + ), + ); + return null; + } + roundTeams.add(group.teamAId); + roundTeams.add(group.teamBId); + teamsByRound.set(roundNumber, roundTeams); + + const matchNumber = (matchNumberByRound.get(roundNumber) ?? 0) + 1; + matchNumberByRound.set(roundNumber, matchNumber); + pairings.push({ + roundNumber, + matchNumber, + teamAId: group.teamAId, + teamBId: group.teamBId, + }); + } + return pairings; +} + +function assignLegacyRoundRobinRounds( + groups: Array<{ + roundNumber?: number; + teamAId: string; + teamBId: string; + gameNumbers: number[]; + }>, + teamIds: readonly string[], + maxRounds?: number, +): 'assigned' | 'invalid' | 'unsupported-size' | 'search-limit-exceeded' { + const teamCount = teamIds.length; + const fullRoundCount = teamCount % 2 === 0 ? teamCount - 1 : teamCount; + const roundCount = Math.min( + fullRoundCount, + positiveInteger(maxRounds) ?? fullRoundCount, + ); + const matchesPerRound = Math.floor(teamCount / 2); + if (groups.length !== roundCount * matchesPerRound) return 'invalid'; + + if (roundCount === fullRoundCount) { + return assignCompleteLegacyRoundRobinRounds(groups, teamIds) + ? 'assigned' + : 'invalid'; + } + if (teamCount > 16) return 'unsupported-size'; + + const degreeByTeam = new Map(teamIds.map((teamId) => [teamId, 0])); + for (const group of groups) { + degreeByTeam.set(group.teamAId, degreeByTeam.get(group.teamAId)! + 1); + degreeByTeam.set(group.teamBId, degreeByTeam.get(group.teamBId)! + 1); + } + if ( + [...degreeByTeam.values()].some( + (degree) => + degree > roundCount || (teamCount % 2 === 0 && degree !== roundCount), + ) + ) { + return 'invalid'; + } + + const ordered = [...groups] + .sort( + (left, right) => + Math.min(...left.gameNumbers) - Math.min(...right.gameNumbers), + ) + .map((group, index) => ({ group, index })); + const failedPartitions = new Set(); + let searchBudget = 1_000_000; + + const partition = ( + roundNumber: number, + remaining: typeof ordered, + ): boolean => { + if (roundNumber > roundCount) return remaining.length === 0; + if (remaining.length < matchesPerRound) return false; + const partitionKey = remaining.map(({ index }) => index).join(','); + if (failedPartitions.has(partitionKey) || searchBudget <= 0) return false; + + const selectedIndexes: number[] = [0]; + const usedTeams = new Set([ + remaining[0].group.teamAId, + remaining[0].group.teamBId, + ]); + + const fillRound = (candidateIndex: number): boolean => { + searchBudget -= 1; + if (searchBudget < 0) return false; + if (selectedIndexes.length === matchesPerRound) { + const selected = new Set(selectedIndexes); + const nextRemaining = remaining.filter( + (_group, index) => !selected.has(index), + ); + if (!partition(roundNumber + 1, nextRemaining)) return false; + for (const index of selectedIndexes) { + remaining[index].group.roundNumber = roundNumber; + } + return true; + } + + for (let index = candidateIndex; index < remaining.length; index += 1) { + if (searchBudget <= 0) return false; + const candidate = remaining[index].group; + if ( + usedTeams.has(candidate.teamAId) || + usedTeams.has(candidate.teamBId) + ) { + continue; + } + selectedIndexes.push(index); + usedTeams.add(candidate.teamAId); + usedTeams.add(candidate.teamBId); + if (fillRound(index + 1)) return true; + selectedIndexes.pop(); + usedTeams.delete(candidate.teamAId); + usedTeams.delete(candidate.teamBId); + } + return false; + }; + + const found = fillRound(1); + if (!found) failedPartitions.add(partitionKey); + return found; + }; + + const assigned = partition(1, ordered); + if (assigned) return 'assigned'; + return searchBudget <= 0 ? 'search-limit-exceeded' : 'invalid'; +} + +function assignCompleteLegacyRoundRobinRounds( + groups: Array<{ + roundNumber?: number; + teamAId: string; + teamBId: string; + }>, + teamIds: readonly string[], +): boolean { + const byOpponents = new Map( + groups.map((group) => [ + JSON.stringify([group.teamAId, group.teamBId].sort()), + group, + ]), + ); + const bye = Symbol('round-robin-bye'); + const rotating: Array = [...teamIds].sort(); + if (rotating.length % 2 === 1) rotating.push(bye); + + for (let roundIndex = 0; roundIndex < rotating.length - 1; 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; + const group = byOpponents.get(JSON.stringify([left, right].sort())); + if (!group) return false; + group.roundNumber = roundIndex + 1; + } + const fixed = rotating[0]; + const tail = rotating.slice(1); + tail.unshift(tail.pop()!); + rotating.splice(0, rotating.length, fixed, ...tail); + } + return groups.every((group) => group.roundNumber !== undefined); +} + +function fixedFormat(type: 'paired-series', gameCount: number) { + return { type, rule: fixedRule(gameCount) } as const; +} + +function fixedRule(gameCount: number) { + return { + type: 'fixed-games' as const, + gameCount, + drawPolicy: 'allow' as const, + }; +} + +function legacyFirstToRule( + bracketMatches: LegacyBracketMatchInput[], + bracketSide: NonNullable, + fallbackGameCount: number, +) { + const matching = bracketMatches.filter( + (bracketMatch) => bracketMatch.bracketSide === bracketSide, + ); + const maxGames = Math.max( + ...matching.map( + (bracketMatch) => positiveInteger(bracketMatch.gameCount) ?? 0, + ), + fallbackGameCount, + ); + const configuredWins = matching + .map((bracketMatch) => positiveInteger(bracketMatch.requiredWins)) + .filter((value): value is number => value !== undefined); + const winsRequired = configuredWins[0] ?? Math.floor(maxGames / 2) + 1; + return { type: 'first-to' as const, winsRequired, maxGames }; +} + +function mapGames( + input: LegacyMatchInput, + graph: SeriesDefinition[], + teamIds: Map, + reasons: CompetitionMigrationIssue[], +): PlannedGame[] { + const mapped: Array & { ordinal?: number }> = []; + const games = input.result?.games ?? []; + for (const game of games) { + const blueTeamId = teamIds.get(game.blueTeamIndex); + const redTeamId = teamIds.get(game.redTeamIndex); + const winnerTeamId = teamIds.get(game.winnerTeamIndex); + if (!blueTeamId || !redTeamId || !winnerTeamId) { + reasons.push( + issue( + 'GAME_REFERENCES_UNKNOWN_TEAM', + `Legacy game ${game.gameNumber} references an unknown team.`, + { + gameNumber: game.gameNumber, + blueTeamIndex: game.blueTeamIndex, + redTeamIndex: game.redTeamIndex, + winnerTeamIndex: game.winnerTeamIndex, + }, + ), + ); + continue; + } + if ( + blueTeamId === redTeamId || + (winnerTeamId !== blueTeamId && winnerTeamId !== redTeamId) + ) { + reasons.push( + issue( + 'INCONSISTENT_GAME_TEAM_EVIDENCE', + `Legacy game ${game.gameNumber} has an invalid team or winner set.`, + { gameNumber: game.gameNumber }, + ), + ); + continue; + } + + const resolution = resolveGameSeries( + input, + graph, + game, + blueTeamId, + redTeamId, + ); + if ('issue' in resolution) { + reasons.push(resolution.issue); + continue; + } + mapped.push({ + legacy: game, + series: resolution.series, + confidence: resolution.confidence, + ...(resolution.ordinal ? { ordinal: resolution.ordinal } : {}), + }); + } + + const grouped = new Map< + string, + Array & { ordinal?: number }> + >(); + for (const game of mapped) { + const group = grouped.get(game.series.id) ?? []; + group.push(game); + grouped.set(game.series.id, group); + } + + const result: PlannedGame[] = []; + for (const [seriesId, seriesGames] of grouped) { + seriesGames.sort(compareLegacyGames); + const series = graph.find((candidate) => candidate.id === seriesId)!; + if (seriesGames.length > series.gameSlots.length) { + reasons.push( + issue( + 'TOO_MANY_GAMES_FOR_SERIES', + `Series ${series.code ?? series.id} has more legacy games than stable slots.`, + { + seriesId, + gameCount: seriesGames.length, + slotCount: series.gameSlots.length, + }, + ), + ); + continue; + } + const occupiedOrdinals = new Set(); + for (const game of seriesGames) { + if (game.ordinal === undefined) continue; + if ( + game.ordinal < 1 || + game.ordinal > series.gameSlots.length || + occupiedOrdinals.has(game.ordinal) + ) { + reasons.push( + issue( + 'AMBIGUOUS_GAME_SLOT_MAPPING', + `Series ${series.code ?? series.id} has conflicting exact GameSlot evidence.`, + { seriesId, ordinal: game.ordinal }, + ), + ); + continue; + } + occupiedOrdinals.add(game.ordinal); + } + const availableOrdinals = series.gameSlots + .map(({ ordinal }) => ordinal) + .filter((ordinal) => !occupiedOrdinals.has(ordinal)); + for (const game of seriesGames) { + const ordinal = game.ordinal ?? availableOrdinals.shift(); + if (ordinal === undefined) { + reasons.push( + issue( + 'GAME_SLOT_MAPPING_NOT_FOUND', + `Series ${series.code ?? series.id} has no remaining stable GameSlot.`, + { seriesId, gameNumber: game.legacy.gameNumber }, + ), + ); + continue; + } + result.push({ ...game, ordinal }); + } + } + return result.sort( + (left, right) => + graph.indexOf(left.series) - graph.indexOf(right.series) || + left.ordinal - right.ordinal, + ); +} + +function resolveGameSeries( + input: LegacyMatchInput, + graph: SeriesDefinition[], + game: LegacyGameInput, + blueTeamId: string, + redTeamId: string, +): + | { series: SeriesDefinition; confidence: number; ordinal?: number } + | { issue: CompetitionMigrationIssue } { + if (game.bracketMatchId) { + const series = graph.find( + (candidate) => candidate.code === game.bracketMatchId, + ); + if (!series) { + return { + issue: issue( + 'GAME_SERIES_MAPPING_NOT_FOUND', + `Legacy bracket code ${game.bracketMatchId} has no Series.`, + { + gameNumber: game.gameNumber, + bracketMatchId: game.bracketMatchId, + }, + ), + }; + } + const exactSlot = resolveLegacyGameNumberTarget(input, graph, game, series); + if ('issue' in exactSlot) return exactSlot; + return { + series, + confidence: 1, + ...(exactSlot.ordinal ? { ordinal: exactSlot.ordinal } : {}), + }; + } + + const assignments = (input.gameSchedule ?? []).filter( + (assignment) => assignment.gameNumber === game.gameNumber, + ); + if (assignments.length > 1) { + return { + issue: issue( + 'AMBIGUOUS_GAME_ASSIGNMENT', + `Legacy game number ${game.gameNumber} maps to multiple schedule entries.`, + { gameNumber: game.gameNumber, assignmentCount: assignments.length }, + ), + }; + } + if (assignments.length === 1) { + const assignment = assignments[0]; + const expected = new Set([assignment.teamAIndex, assignment.teamBIndex]); + if (!expected.has(game.blueTeamIndex) || !expected.has(game.redTeamIndex)) { + return { + issue: issue( + 'GAME_ASSIGNMENT_TEAM_MISMATCH', + `Legacy game ${game.gameNumber} conflicts with its schedule entry.`, + { gameNumber: game.gameNumber }, + ), + }; + } + } + + const candidates = graph.filter((series) => + staticSeriesHasTeamSet(series, blueTeamId, redTeamId), + ); + if (candidates.length === 1) { + const exactSlot = resolveLegacyGameNumberTarget( + input, + graph, + game, + candidates[0], + ); + if ('issue' in exactSlot) return exactSlot; + return { + series: candidates[0], + confidence: assignments.length === 1 ? 0.95 : 0.8, + ...(exactSlot.ordinal ? { ordinal: exactSlot.ordinal } : {}), + }; + } + return { + issue: issue( + candidates.length > 1 + ? 'AMBIGUOUS_GAME_SERIES_MAPPING' + : 'GAME_SERIES_MAPPING_NOT_FOUND', + candidates.length > 1 + ? `Legacy game ${game.gameNumber} matches multiple Series.` + : `Legacy game ${game.gameNumber} cannot be mapped to a Series.`, + { + gameNumber: game.gameNumber, + candidateSeriesIds: candidates.map((series) => series.id), + }, + ), + }; +} + +function resolveLegacyGameNumberTarget( + input: LegacyMatchInput, + graph: SeriesDefinition[], + game: LegacyGameInput, + series: SeriesDefinition, +): { ordinal?: number } | { issue: CompetitionMigrationIssue } { + if (input.gameMode === 'double-elimination') { + if ((input.doubleElimination?.bracketMatches?.length ?? 0) === 0) return {}; + const target = resolvePersistedDoubleEliminationGameNumberTarget( + input, + graph, + game.gameNumber, + ); + if ('error' in target) { + return { + issue: issue('GAME_SLOT_MAPPING_NOT_FOUND', target.error, { + gameNumber: game.gameNumber, + bracketMatchId: game.bracketMatchId, + seriesId: series.id, + }), + }; + } + if (target.series.id !== series.id) { + return { + issue: issue( + 'GAME_SLOT_MAPPING_CONFLICT', + `Legacy game ${game.gameNumber} conflicts with its persisted double-elimination topology.`, + { + gameNumber: game.gameNumber, + bracketMatchId: game.bracketMatchId, + seriesId: series.id, + targetSeriesId: target.series.id, + }, + ), + }; + } + return { ordinal: target.slot.ordinal }; + } + + if ( + input.gameMode === 'round-robin' && + (input.gameSchedule?.length ?? 0) > 0 + ) { + const assignment = input.gameSchedule!.find( + (candidate) => candidate.gameNumber === game.gameNumber, + ); + if (!assignment) { + return { + issue: issue( + 'GAME_SLOT_MAPPING_NOT_FOUND', + `Legacy round-robin game ${game.gameNumber} is absent from its persisted schedule.`, + { gameNumber: game.gameNumber, seriesId: series.id }, + ), + }; + } + const samePair = input + .gameSchedule!.filter( + (candidate) => + unorderedNumberPair(candidate.teamAIndex, candidate.teamBIndex) === + unorderedNumberPair(assignment.teamAIndex, assignment.teamBIndex), + ) + .sort((left, right) => left.gameNumber - right.gameNumber); + const ordinal = + samePair.findIndex( + (candidate) => candidate.gameNumber === game.gameNumber, + ) + 1; + if (!series.gameSlots.some((slot) => slot.ordinal === ordinal)) { + return { + issue: issue( + 'GAME_SLOT_MAPPING_NOT_FOUND', + `Legacy round-robin game ${game.gameNumber} has no stable GameSlot ordinal.`, + { gameNumber: game.gameNumber, seriesId: series.id, ordinal }, + ), + }; + } + return { ordinal }; + } + + const flattened = graph.flatMap((candidateSeries) => + candidateSeries.gameSlots.map((slot) => ({ + series: candidateSeries, + ordinal: slot.ordinal, + })), + ); + const target = flattened[game.gameNumber - 1]; + if (!target || target.series.id !== series.id) { + return { + issue: issue( + 'GAME_SLOT_MAPPING_CONFLICT', + `Legacy game ${game.gameNumber} conflicts with the canonical global GameSlot topology.`, + { + gameNumber: game.gameNumber, + seriesId: series.id, + targetSeriesId: target?.series.id, + }, + ), + }; + } + return { ordinal: target.ordinal }; +} + +function staticSeriesHasTeamSet( + series: SeriesDefinition, + leftTeamId: string, + rightTeamId: string, +): boolean { + const sourceTeamIds = series.slots.map((slot) => + slot.source.type === 'team' ? slot.source.teamId : undefined, + ); + return ( + sourceTeamIds.every((teamId) => teamId !== undefined) && + new Set(sourceTeamIds).size === 2 && + sourceTeamIds.includes(leftTeamId) && + sourceTeamIds.includes(rightTeamId) + ); +} + +function addGameFacts( + input: LegacyMatchInput, + competitionId: string, + plannedGames: PlannedGame[], + teamIds: Map, + graph: SeriesDefinition[], + pending: PendingFact[], + reasons: CompetitionMigrationIssue[], +): void { + const riotIds = new Set(); + for (const planned of plannedGames) { + const game = planned.legacy; + const riotMatchId = game.riotMatchId?.trim(); + if (riotMatchId && riotIds.has(riotMatchId)) { + reasons.push( + issue( + 'DUPLICATE_RIOT_MATCH_EVIDENCE', + `Riot match ${riotMatchId} appears more than once.`, + { riotMatchId }, + ), + ); + continue; + } + if (riotMatchId) riotIds.add(riotMatchId); + + const slot = planned.series.gameSlots.find( + (candidate) => candidate.ordinal === planned.ordinal, + )!; + const blueTeamId = teamIds.get(game.blueTeamIndex)!; + const redTeamId = teamIds.get(game.redTeamIndex)!; + const winnerTeamId = teamIds.get(game.winnerTeamIndex)!; + const occurredAt = gameOccurrence(game, input); + const evidence = gameEvidence(input, competitionId, planned); + const logicalKey = `game:${planned.series.id}:${planned.ordinal}:${riotMatchId ?? game.gameNumber}`; + pending.push({ + kind: 'game-accepted', + seriesOrder: graph.indexOf(planned.series), + occurredAt, + logicalKey, + build: (base) => ({ + ...base, + type: 'game-accepted', + gameId: stableId( + competitionId, + 'game', + planned.series.id, + planned.ordinal, + riotMatchId ?? game.gameNumber, + ), + seriesId: planned.series.id, + gameSlotId: slot.id, + ordinal: planned.ordinal, + startedAt: occurredAt, + durationSeconds: + typeof game.gameDuration === 'number' ? game.gameDuration : 0, + participants: (game.participants ?? []).flatMap((participant) => { + const userId = opaqueString(participant.userId); + const teamId = teamIds.get(participant.teamIndex ?? -1); + if ( + !userId || + !teamId || + (participant.side !== 'blue' && participant.side !== 'red') + ) { + return []; + } + return [ + { + userId, + teamId, + side: participant.side, + summonerName: + typeof participant.summonerName === 'string' + ? participant.summonerName + : '', + tagLine: + typeof participant.tagLine === 'string' + ? participant.tagLine + : '', + championId: numericValue(participant.championId), + kills: numericValue(participant.kills), + deaths: numericValue(participant.deaths), + assists: numericValue(participant.assists), + }, + ]; + }), + evidence, + mapping: { + mappingVersion: 1, + confidence: planned.confidence, + blueTeamId, + redTeamId, + winnerTeamId, + participantAssignments: (game.participants ?? []) + .filter( + (participant) => + opaqueString(participant.userId) && + (participant.side === 'blue' || participant.side === 'red') && + teamIds.has(participant.teamIndex ?? -1), + ) + .map((participant) => ({ + userId: opaqueString(participant.userId), + teamId: teamIds.get(participant.teamIndex!)!, + side: participant.side!, + })), + }, + }), + }); + } +} + +function gameEvidence( + input: LegacyMatchInput, + competitionId: string, + planned: PlannedGame, +): MigrationGameAcceptedFact['evidence'] { + const game = planned.legacy; + const riotMatchId = game.riotMatchId?.trim(); + const archiveKnown = + game.riotArchivePresent === true || + (riotMatchId !== undefined && + input.riotMatchArchiveIds?.includes(riotMatchId)); + if (riotMatchId && archiveKnown) { + return { + type: 'riot', + riotMatchId, + payloadHash: + game.payloadHash ?? `sha256:${stableHash(canonicalize(game))}`, + }; + } + return { + type: 'legacy', + legacyReference: [ + 'match', + opaqueString(input._id), + 'result.games', + String(game.gameNumber), + riotMatchId ?? + stableId( + competitionId, + 'legacy-game', + planned.series.id, + planned.ordinal, + ), + ].join(':'), + }; +} + +function addAdjudicationFacts( + input: LegacyMatchInput, + competitionId: string, + plannedGames: PlannedGame[], + teamIds: Map, + graph: SeriesDefinition[], + pending: PendingFact[], + reasons: CompetitionMigrationIssue[], +): void { + const gameSeriesIds = new Set(plannedGames.map((game) => game.series.id)); + const adjudicatedSeriesIds = new Set(); + + for (const bracketMatch of input.doubleElimination?.bracketMatches ?? []) { + const walkover = bracketMatch.walkover; + if (!walkover?.active) continue; + const series = graph.find( + (candidate) => candidate.code === bracketMatch.bracketMatchId, + ); + const winnerTeamId = teamIds.get(walkover.winnerTeamIndex); + if (!series || !winnerTeamId) { + reasons.push( + issue( + 'WALKOVER_MAPPING_NOT_FOUND', + `Active walkover ${bracketMatch.bracketMatchId} cannot be mapped.`, + { bracketMatchId: bracketMatch.bracketMatchId }, + ), + ); + continue; + } + if (gameSeriesIds.has(series.id)) { + reasons.push( + issue( + 'WALKOVER_CONFLICTS_WITH_GAMES', + `Series ${bracketMatch.bracketMatchId} has both active games and a walkover.`, + { seriesId: series.id }, + ), + ); + continue; + } + addAdjudication({ + competitionId, + series, + winnerTeamId, + decisionType: 'walkover', + reason: walkover.reason?.trim() || 'legacy-walkover', + occurredAt: normalizeDate(walkover.awardedAt, sourceFallbackDate(input)), + graph, + pending, + logicalSuffix: 'walkover', + }); + adjudicatedSeriesIds.add(series.id); + } + + for (const result of input.result?.seriesResults ?? []) { + if (!result.winnerTeamIndex) continue; + const resolution = resolveSeriesResult(graph, result, teamIds); + if ('issue' in resolution) { + reasons.push(resolution.issue); + continue; + } + const { series } = resolution; + if (gameSeriesIds.has(series.id) || adjudicatedSeriesIds.has(series.id)) + continue; + const winnerTeamId = teamIds.get(result.winnerTeamIndex); + if (!winnerTeamId) { + reasons.push( + issue( + 'WINNER_ONLY_RESULT_REFERENCES_UNKNOWN_TEAM', + 'A winner-only Series references an unknown team.', + { winnerTeamIndex: result.winnerTeamIndex, seriesId: series.id }, + ), + ); + continue; + } + addAdjudication({ + competitionId, + series, + winnerTeamId, + decisionType: 'administrative', + reason: 'legacy-winner-only-result', + occurredAt: seriesCompletionDate(input, series.code), + graph, + pending, + logicalSuffix: 'winner-only', + }); + adjudicatedSeriesIds.add(series.id); + } + + if ( + input.result?.winnerTeamIndex && + graph.length === 1 && + !gameSeriesIds.has(graph[0].id) && + !adjudicatedSeriesIds.has(graph[0].id) + ) { + const winnerTeamId = teamIds.get(input.result.winnerTeamIndex); + if (!winnerTeamId) { + reasons.push( + issue( + 'WINNER_ONLY_RESULT_REFERENCES_UNKNOWN_TEAM', + 'The Match winner references an unknown team.', + { winnerTeamIndex: input.result.winnerTeamIndex }, + ), + ); + } else { + addAdjudication({ + competitionId, + series: graph[0], + winnerTeamId, + decisionType: 'administrative', + reason: 'legacy-winner-only-result', + occurredAt: sourceFallbackDate(input), + graph, + pending, + logicalSuffix: 'match-winner-only', + }); + } + } +} + +function resolveSeriesResult( + graph: SeriesDefinition[], + result: LegacySeriesResultInput, + teamIds: Map, +): { series: SeriesDefinition } | { issue: CompetitionMigrationIssue } { + if (result.bracketMatchId) { + const series = graph.find( + (candidate) => candidate.code === result.bracketMatchId, + ); + return series + ? { series } + : { + issue: issue( + 'WINNER_ONLY_SERIES_MAPPING_NOT_FOUND', + `Winner-only bracket code ${result.bracketMatchId} has no Series.`, + ), + }; + } + const left = teamIds.get(result.teamAIndex); + const right = teamIds.get(result.teamBIndex); + if (!left || !right) { + return { + issue: issue( + 'WINNER_ONLY_RESULT_REFERENCES_UNKNOWN_TEAM', + 'A winner-only Series references an unknown team.', + ), + }; + } + const candidates = graph.filter((series) => + staticSeriesHasTeamSet(series, left, right), + ); + if (candidates.length !== 1) { + return { + issue: issue( + candidates.length > 1 + ? 'AMBIGUOUS_WINNER_ONLY_SERIES_MAPPING' + : 'WINNER_ONLY_SERIES_MAPPING_NOT_FOUND', + 'A winner-only Series cannot be mapped without guessing.', + { candidateSeriesIds: candidates.map((series) => series.id) }, + ), + }; + } + return { series: candidates[0] }; +} + +function addAdjudication(params: { + competitionId: string; + series: SeriesDefinition; + winnerTeamId: string; + decisionType: 'walkover' | 'administrative'; + reason: string; + occurredAt: string; + graph: SeriesDefinition[]; + pending: PendingFact[]; + logicalSuffix: string; +}): void { + params.pending.push({ + kind: 'series-adjudicated', + seriesOrder: params.graph.indexOf(params.series), + occurredAt: params.occurredAt, + logicalKey: `adjudication:${params.series.id}:${params.logicalSuffix}`, + build: (base) => ({ + ...base, + type: 'series-adjudicated', + seriesId: params.series.id, + decision: { + type: params.decisionType, + winnerTeamId: params.winnerTeamId, + }, + reason: params.reason, + }), + }); +} + +function materializeFacts( + competitionId: string, + migrationRunId: string, + recordedAt: string, + pending: PendingFact[], +): CompetitionMigrationFact[] { + const sorted = [...pending].sort( + (left, right) => + left.occurredAt.localeCompare(right.occurredAt) || + left.seriesOrder - right.seriesOrder || + left.logicalKey.localeCompare(right.logicalKey), + ); + return sorted.map((fact, index) => { + const revision = index + 1; + const id = stableId(competitionId, 'fact', fact.logicalKey); + const commandId = stableId( + competitionId, + 'migration-command', + fact.logicalKey, + ); + const base: MigrationFactBase = { + id, + competitionId, + revision, + ordinalWithinRevision: 1, + commandId, + idempotencyKey: `${migrationRunId}:${fact.logicalKey}`, + requestHash: `sha256:${stableHash(fact.logicalKey)}`, + schemaVersion: SCHEMA_VERSION, + actor: { type: 'migration', migrationRunId }, + occurredAt: fact.occurredAt, + recordedAt, + }; + return fact.build(base); + }); +} + +interface TournamentCodeAssignmentTarget { + series: SeriesDefinition; + slot: SeriesDefinition['gameSlots'][number]; +} + +function resolveTournamentCodeAssignmentTarget(params: { + input: LegacyMatchInput; + code: LegacyTournamentCodeInput; + tournamentCodeId: string; + gameFact: MigrationGameAcceptedFact | undefined; + graph: SeriesDefinition[]; + teamIds: ReadonlyMap; +}): TournamentCodeAssignmentTarget | { issue: CompetitionMigrationIssue } { + let target: TournamentCodeAssignmentTarget | undefined; + if (params.gameFact) { + const series = params.graph.find( + (candidate) => candidate.id === params.gameFact!.seriesId, + ); + const slot = series?.gameSlots.find( + (candidate) => candidate.id === params.gameFact!.gameSlotId, + ); + if (!series || !slot) { + return assignmentMappingNotFound( + params, + 'Accepted TournamentCode evidence does not target a stable GameSlot.', + ); + } + target = { series, slot }; + } + + if (params.code.gameNumber !== undefined) { + const numbered = resolveGlobalGameNumberTarget(params); + if ('issue' in numbered) return numbered; + if (target && !sameAssignmentTarget(target, numbered)) { + return assignmentConflict( + params, + [target, numbered], + 'TournamentCode Riot evidence conflicts with its global game number.', + ); + } + target = numbered; + } + + if (params.code.bracketMatchId) { + const bracketSeries = params.graph.find( + (candidate) => candidate.code === params.code.bracketMatchId, + ); + if (!bracketSeries) { + return assignmentMappingNotFound( + params, + 'The TournamentCode bracket identity has no stable Series.', + ); + } + if (target && target.series.id !== bracketSeries.id) { + return assignmentConflict( + params, + [target], + 'TournamentCode bracket identity conflicts with its exact GameSlot evidence.', + ); + } + if (!target) { + if (bracketSeries.gameSlots.length !== 1) { + return assignmentMappingNotFound( + params, + 'A multi-slot TournamentCode Series needs exact GameSlot evidence.', + ); + } + target = { series: bracketSeries, slot: bracketSeries.gameSlots[0] }; + } + } + + return ( + target ?? + assignmentMappingNotFound( + params, + 'A non-available TournamentCode cannot be mapped to a stable GameSlot.', + ) + ); +} + +function resolveGlobalGameNumberTarget(params: { + input: LegacyMatchInput; + code: LegacyTournamentCodeInput; + tournamentCodeId: string; + graph: SeriesDefinition[]; + teamIds: ReadonlyMap; +}): TournamentCodeAssignmentTarget | { issue: CompetitionMigrationIssue } { + const gameNumber = positiveInteger(params.code.gameNumber); + if (!gameNumber) { + return assignmentMappingNotFound( + params, + 'TournamentCode gameNumber must be a positive integer.', + ); + } + + const bracketMatches = params.input.doubleElimination?.bracketMatches ?? []; + if ( + params.input.gameMode === 'double-elimination' && + bracketMatches.length > 0 + ) { + const target = resolvePersistedDoubleEliminationGameNumberTarget( + params.input, + params.graph, + gameNumber, + ); + return 'error' in target + ? assignmentMappingNotFound(params, target.error) + : target; + } + + const schedule = params.input.gameSchedule ?? []; + if (schedule.length > 0) { + const matches = schedule.filter( + (assignment) => assignment.gameNumber === gameNumber, + ); + if (matches.length !== 1) { + return assignmentMappingNotFound( + params, + matches.length > 1 + ? 'TournamentCode gameNumber maps to multiple persisted schedule entries.' + : 'TournamentCode gameNumber is absent from the persisted schedule.', + ); + } + const [assignment] = matches; + const teamAId = params.teamIds.get(assignment.teamAIndex); + const teamBId = params.teamIds.get(assignment.teamBIndex); + if (!teamAId || !teamBId || teamAId === teamBId) { + return assignmentMappingNotFound( + params, + 'TournamentCode schedule entry references an invalid team set.', + ); + } + const candidates = params.graph.filter((series) => + staticSeriesHasTeamSet(series, teamAId, teamBId), + ); + if (candidates.length !== 1) { + return assignmentMappingNotFound( + params, + 'TournamentCode schedule entry does not identify one stable Series.', + ); + } + const samePair = schedule + .filter( + (candidate) => + unorderedNumberPair(candidate.teamAIndex, candidate.teamBIndex) === + unorderedNumberPair(assignment.teamAIndex, assignment.teamBIndex), + ) + .sort((left, right) => left.gameNumber - right.gameNumber); + const ordinal = samePair.findIndex( + (candidate) => candidate.gameNumber === gameNumber, + ); + const series = candidates[0]; + const slot = series.gameSlots.find( + (candidate) => candidate.ordinal === ordinal + 1, + ); + if (!slot) { + return assignmentMappingNotFound( + params, + 'TournamentCode schedule ordinal has no stable GameSlot.', + ); + } + return { series, slot }; + } + + const flattened = params.graph.flatMap((series) => + series.gameSlots.map((slot) => ({ series, slot })), + ); + const target = flattened[gameNumber - 1]; + return ( + target ?? + assignmentMappingNotFound( + params, + 'TournamentCode gameNumber is outside the canonical Competition topology.', + ) + ); +} + +function resolvePersistedDoubleEliminationGameNumberTarget( + input: LegacyMatchInput, + graph: SeriesDefinition[], + gameNumber: number, +): TournamentCodeAssignmentTarget | { error: string } { + const seenBracketNumbers = new Set(); + const ordered = [...(input.doubleElimination?.bracketMatches ?? [])].sort( + (left, right) => + (positiveInteger(left.gameNumber) ?? Number.MAX_SAFE_INTEGER) - + (positiveInteger(right.gameNumber) ?? Number.MAX_SAFE_INTEGER) || + left.bracketMatchId.localeCompare(right.bracketMatchId), + ); + let nextGameNumber = 1; + for (const bracketMatch of ordered) { + const bracketNumber = positiveInteger(bracketMatch.gameNumber); + if ( + !bracketNumber || + seenBracketNumbers.has(bracketNumber) || + bracketNumber !== seenBracketNumbers.size + 1 + ) { + return { + error: + 'The persisted double-elimination topology has ambiguous Series numbering.', + }; + } + seenBracketNumbers.add(bracketNumber); + const gameCount = positiveInteger(bracketMatch.gameCount) ?? 1; + if ( + gameNumber >= nextGameNumber && + gameNumber < nextGameNumber + gameCount + ) { + const series = graph.find( + (candidate) => candidate.code === bracketMatch.bracketMatchId, + ); + const ordinal = gameNumber - nextGameNumber + 1; + const slot = series?.gameSlots.find( + (candidate) => candidate.ordinal === ordinal, + ); + return series && slot + ? { series, slot } + : { + error: + 'The persisted double-elimination GameSlot has no Competition target.', + }; + } + nextGameNumber += gameCount; + } + return { + error: + 'The global game number is outside the persisted double-elimination topology.', + }; +} + +function assignmentMappingNotFound( + params: { + code: LegacyTournamentCodeInput; + tournamentCodeId: string; + }, + message: string, +): { issue: CompetitionMigrationIssue } { + return { + issue: issue('TOURNAMENT_CODE_ASSIGNMENT_MAPPING_NOT_FOUND', message, { + tournamentCodeId: params.tournamentCodeId, + bracketMatchId: params.code.bracketMatchId, + gameNumber: params.code.gameNumber, + }), + }; +} + +function assignmentConflict( + params: { + code: LegacyTournamentCodeInput; + tournamentCodeId: string; + }, + targets: TournamentCodeAssignmentTarget[], + message: string, +): { issue: CompetitionMigrationIssue } { + return { + issue: issue('TOURNAMENT_CODE_ASSIGNMENT_CONFLICT', message, { + tournamentCodeId: params.tournamentCodeId, + bracketMatchId: params.code.bracketMatchId, + gameNumber: params.code.gameNumber, + targets: targets.map(({ series, slot }) => ({ + seriesId: series.id, + gameSlotId: slot.id, + })), + }), + }; +} + +function sameAssignmentTarget( + left: TournamentCodeAssignmentTarget, + right: TournamentCodeAssignmentTarget, +): boolean { + return left.series.id === right.series.id && left.slot.id === right.slot.id; +} + +function unorderedNumberPair(left: number, right: number): string { + return left < right ? `${left}:${right}` : `${right}:${left}`; +} + +function buildAssignments( + input: LegacyMatchInput, + competitionId: string, + facts: CompetitionMigrationFact[], + graph: SeriesDefinition[], + teamIds: ReadonlyMap, + reasons: CompetitionMigrationIssue[], + warnings: CompetitionMigrationIssue[], +): CompetitionMigrationAssignment[] { + const result: CompetitionMigrationAssignment[] = []; + for (const code of input.tournamentCodes ?? []) { + if ( + code.state !== 'reserved' && + code.state !== 'used' && + code.state !== 'released' && + code.state !== 'voided' + ) { + continue; + } + const tournamentCodeId = opaqueString(code._id); + const riotMatchId = + code.state === 'used' || code.state === 'voided' + ? code.riotMatchId + : undefined; + const gameFact = facts.find( + (fact): fact is MigrationGameAcceptedFact => + fact.type === 'game-accepted' && + riotMatchId !== undefined && + ((fact.evidence.type === 'riot' && + fact.evidence.riotMatchId === riotMatchId) || + (fact.evidence.type === 'legacy' && + fact.evidence.legacyReference.endsWith(`:${riotMatchId}`))), + ); + const resolution = resolveTournamentCodeAssignmentTarget({ + input, + code, + tournamentCodeId, + gameFact, + graph, + teamIds, + }); + if ('issue' in resolution) { + reasons.push(resolution.issue); + continue; + } + const { series, slot } = resolution; + const acceptedGame = + gameFact ?? + facts.find( + (fact): fact is MigrationGameAcceptedFact => + fact.type === 'game-accepted' && fact.gameSlotId === slot.id, + ); + if (code.state === 'used' && !acceptedGame) { + reasons.push( + issue( + 'USED_CODE_WITHOUT_ACCEPTED_GAME', + 'A used TournamentCode must target an accepted legacy game.', + { tournamentCodeId, gameSlotId: slot.id }, + ), + ); + continue; + } + if ( + riotMatchId && + acceptedGame && + !acceptedGameHasRiotIdentity(acceptedGame, riotMatchId) + ) { + reasons.push( + issue( + 'TOURNAMENT_CODE_RIOT_EVIDENCE_CONFLICT', + 'TournamentCode Riot identity conflicts with the accepted game in its target slot.', + { + tournamentCodeId, + gameSlotId: slot.id, + riotMatchId, + }, + ), + ); + continue; + } + const legacyGame = riotMatchId + ? input.result?.games.find( + (game) => game.riotMatchId?.trim() === riotMatchId, + ) + : undefined; + const timestamps = tournamentCodeTimestamps( + input, + code, + tournamentCodeId, + reasons, + warnings, + riotMatchId && + acceptedGame?.evidence.type === 'riot' && + acceptedGame.evidence.riotMatchId === riotMatchId && + legacyGame + ? { + riotMatchId, + gameSlotId: slot.id, + factRecordedAt: acceptedGame.recordedAt, + legacyOccurrences: legacyUsedOccurrenceEvidence(legacyGame), + } + : undefined, + ); + if (!timestamps) continue; + result.push({ + id: stableId( + competitionId, + 'tournament-code-assignment', + tournamentCodeId, + ), + competitionId, + seriesId: series.id, + gameSlotId: slot.id, + tournamentCodeId, + state: code.state, + ...timestamps, + ...(riotMatchId ? { riotMatchId } : {}), + commandId: stableId( + competitionId, + 'migration-code-command', + tournamentCodeId, + ), + }); + } + + const activeSlots = new Set(); + const activeCodes = new Set(); + for (const assignment of result) { + if (assignment.state !== 'reserved' && assignment.state !== 'used') + continue; + if ( + activeSlots.has(assignment.gameSlotId) || + activeCodes.has(assignment.tournamentCodeId) + ) { + reasons.push( + issue( + 'AMBIGUOUS_TOURNAMENT_CODE_ASSIGNMENT', + 'Active TournamentCode assignments collide on identity or GameSlot.', + { + tournamentCodeId: assignment.tournamentCodeId, + gameSlotId: assignment.gameSlotId, + }, + ), + ); + } + activeSlots.add(assignment.gameSlotId); + activeCodes.add(assignment.tournamentCodeId); + } + return result.sort((left, right) => left.id.localeCompare(right.id)); +} + +function acceptedGameHasRiotIdentity( + fact: MigrationGameAcceptedFact, + riotMatchId: string, +): boolean { + return ( + (fact.evidence.type === 'riot' && + fact.evidence.riotMatchId === riotMatchId) || + (fact.evidence.type === 'legacy' && + fact.evidence.legacyReference.endsWith(`:${riotMatchId}`)) + ); +} + +function tournamentCodeTimestamps( + input: LegacyMatchInput, + code: LegacyTournamentCodeInput, + tournamentCodeId: string, + reasons: CompetitionMigrationIssue[], + warnings: CompetitionMigrationIssue[], + corroboratedRiotTransition?: { + riotMatchId: string; + gameSlotId: string; + factRecordedAt: string; + legacyOccurrences: LegacyUsedOccurrenceEvidence[]; + }, +): Pick< + CompetitionMigrationAssignment, + 'reservedAt' | 'usedAt' | 'releasedAt' | 'voidedAt' +> | null { + const raw = { + createdAt: optionalDate(code.createdAt), + reservedAt: optionalDate(code.reservedAt), + usedAt: + code.state === 'used' || code.state === 'voided' + ? optionalDate(code.usedAt) + : undefined, + releasedAt: + code.state === 'released' ? optionalDate(code.releasedAt) : undefined, + voidedAt: code.state === 'voided' ? optionalDate(code.voidedAt) : undefined, + updatedAt: + code.state === 'voided' && code.voidedAt == null + ? optionalDate(code.updatedAt) + : undefined, + }; + if (Object.values(raw).some((value) => value === null)) { + reasons.push( + issue( + 'INVALID_TOURNAMENT_CODE_TIMELINE', + 'TournamentCode lifecycle contains an invalid timestamp.', + { tournamentCodeId }, + ), + ); + return null; + } + + // TournamentCode pool documents can be restored and reserved again while + // terminal timestamps from a previous binding remain on the document. A + // Competition assignment represents only the current binding, so preserve + // the lifecycle fields that are reachable for its current state. + const reservedAt = + raw.reservedAt ?? + raw.createdAt ?? + (code.state === 'used' || code.state === 'voided' + ? raw.usedAt + : undefined) ?? + (code.state === 'released' ? raw.releasedAt : undefined) ?? + (code.state === 'voided' ? raw.voidedAt : undefined) ?? + sourceFallbackDate(input); + let usedAt = + code.state === 'used' || code.state === 'voided' + ? (raw.usedAt ?? undefined) + : undefined; + const releasedAt = + code.state === 'released' ? (raw.releasedAt ?? undefined) : undefined; + const voidedAt = + code.state === 'voided' + ? (raw.voidedAt ?? raw.updatedAt ?? usedAt ?? reservedAt) + : undefined; + + // Legacy result collection and repair paths recorded usedAt from Riot game + // occurrence, while updatedAt captured the persisted state transition. Keep + // target lifecycle meaning uniform by using that transition only when an + // archived Riot fact, exact identity, and source occurrence all corroborate. + const occurrenceEvidence = corroboratedRiotTransition?.legacyOccurrences.find( + (candidate) => candidate.at === raw.usedAt, + ); + if ( + code.state === 'used' && + raw.reservedAt && + raw.usedAt && + occurrenceEvidence && + corroboratedRiotTransition + ) { + const persistedTransitionAt = optionalDate(code.updatedAt); + if ( + !persistedTransitionAt || + persistedTransitionAt < reservedAt || + persistedTransitionAt < raw.usedAt || + persistedTransitionAt > corroboratedRiotTransition.factRecordedAt + ) { + reasons.push( + issue( + 'INVALID_TOURNAMENT_CODE_TIMELINE', + 'Legacy used TournamentCode has no valid persisted transition time.', + { + tournamentCodeId, + state: code.state, + reservedAt, + originalUsedAt: raw.usedAt, + sourceUpdatedAt: persistedTransitionAt, + factRecordedAt: corroboratedRiotTransition.factRecordedAt, + }, + ), + ); + return null; + } + const originalUsedAt = raw.usedAt; + usedAt = persistedTransitionAt; + if (originalUsedAt !== usedAt) { + warnings.push( + issue( + 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED', + 'Legacy used TournamentCode usedAt represented Riot game time and was normalized to its persisted transition time.', + { + tournamentCodeId, + originalReservedAt: reservedAt, + originalUsedAt, + sourceUpdatedAt: persistedTransitionAt, + normalizedUsedAt: usedAt, + factRecordedAt: corroboratedRiotTransition.factRecordedAt, + legacyOccurrenceSource: occurrenceEvidence.source, + riotMatchId: corroboratedRiotTransition.riotMatchId, + gameSlotId: corroboratedRiotTransition.gameSlotId, + strategy: 'use-persisted-transition-time', + }, + ), + ); + } + } + const ordered = [reservedAt, usedAt, releasedAt, voidedAt].filter( + (value): value is string => value !== undefined, + ); + if (ordered.some((value, index) => index > 0 && value < ordered[index - 1])) { + reasons.push( + issue( + 'INVALID_TOURNAMENT_CODE_TIMELINE', + 'TournamentCode lifecycle timestamps are not chronological.', + { + tournamentCodeId, + state: code.state, + reservedAt, + ...(usedAt ? { usedAt } : {}), + ...(releasedAt ? { releasedAt } : {}), + ...(voidedAt ? { voidedAt } : {}), + }, + ), + ); + return null; + } + return { + reservedAt, + ...(usedAt ? { usedAt } : {}), + ...(releasedAt ? { releasedAt } : {}), + ...(voidedAt ? { voidedAt } : {}), + }; +} + +function optionalDate(value: unknown): string | undefined | null { + if (value === undefined || value === null || value === '') return undefined; + const date = + value instanceof Date ? value : new Date(value as string | number); + return Number.isNaN(date.getTime()) ? null : date.toISOString(); +} + +function seriesCompletionDate(input: LegacyMatchInput, code?: string): string { + const completedAt = input.doubleElimination?.bracketMatches?.find( + (bracketMatch) => bracketMatch.bracketMatchId === code, + )?.completedAt; + return normalizeDate(completedAt, sourceFallbackDate(input)); +} + +function gameOccurrence( + game: LegacyGameInput, + input: LegacyMatchInput, +): string { + if (typeof game.gameCreation === 'number') { + const milliseconds = + game.gameCreation < 10_000_000_000 + ? game.gameCreation * 1000 + : game.gameCreation; + return normalizeDate(milliseconds, sourceFallbackDate(input)); + } + return normalizeDate(game.gameCreation, sourceFallbackDate(input)); +} + +function legacyUsedOccurrenceEvidence( + game: LegacyGameInput, +): LegacyUsedOccurrenceEvidence[] { + const candidates: LegacyUsedOccurrenceEvidence[] = []; + const archivedGameEnd = optionalRiotDate(game.riotGameEndedAt); + if (archivedGameEnd && game.riotGameEndedAtSource) { + candidates.push({ + at: archivedGameEnd, + source: + game.riotGameEndedAtSource === 'gameEndTimestamp' + ? 'riot-archive-gameEndTimestamp' + : 'riot-archive-gameCreation', + }); + } + + const gameCreation = optionalRiotDate(game.gameCreation); + if ( + gameCreation && + typeof game.gameDuration === 'number' && + Number.isFinite(game.gameDuration) && + game.gameDuration >= 0 + ) { + const computedGameEnd = optionalDate( + Date.parse(gameCreation) + game.gameDuration * 1000, + ); + if (computedGameEnd) { + candidates.push({ + at: computedGameEnd, + source: 'legacy-gameCreation-plus-duration', + }); + } + } + + return candidates.filter( + (candidate, index) => + candidates.findIndex((other) => other.at === candidate.at) === index, + ); +} + +function optionalRiotDate(value: unknown): string | null | undefined { + if (typeof value !== 'number') return optionalDate(value); + return optionalDate(value < 10_000_000_000 ? value * 1000 : value); +} + +function compareLegacyGames( + left: Omit, + right: Omit, +) { + return ( + gameOccurrence(left.legacy, { + createdAt: EPOCH, + } as LegacyMatchInput).localeCompare( + gameOccurrence(right.legacy, { createdAt: EPOCH } as LegacyMatchInput), + ) || + left.legacy.gameNumber - right.legacy.gameNumber || + (left.legacy.riotMatchId ?? '').localeCompare( + right.legacy.riotMatchId ?? '', + ) + ); +} + +function sourceFallbackDate(input: LegacyMatchInput): string { + return normalizeDate(input.updatedAt, normalizeDate(input.createdAt, EPOCH)); +} + +function normalizeDate(value: unknown, fallback: string): string { + if (value === undefined || value === null || value === '') return fallback; + const date = + value instanceof Date ? value : new Date(value as string | number); + return Number.isNaN(date.getTime()) ? fallback : date.toISOString(); +} + +function stableId(...parts: Array): string { + return createHash('sha256') + .update(JSON.stringify(parts)) + .digest('hex') + .slice(0, 24); +} + +function stableHash(value: string): string { + return createHash('sha256').update(value).digest('hex'); +} + +function canonicalize(value: unknown): string { + if (Array.isArray(value)) { + return `[${value.map(canonicalize).join(',')}]`; + } + if (value instanceof Date) return JSON.stringify(value.toISOString()); + if (value && typeof value === 'object') { + const record = value as Record; + return `{${Object.keys(record) + .sort() + .map((key) => `${JSON.stringify(key)}:${canonicalize(record[key])}`) + .join(',')}}`; + } + return JSON.stringify(value); +} + +function opaqueString(value: unknown): string { + if (typeof value === 'string') return value.trim(); + if (hasHexString(value)) { + const rendered = value.toHexString(); + if (typeof rendered === 'string') return rendered.trim(); + } + if (typeof value === 'number' || typeof value === 'boolean') { + return String(value); + } + if (value === undefined || value === null) return ''; + return ''; +} + +function hasHexString(value: unknown): value is { toHexString(): unknown } { + return ( + value !== null && + typeof value === 'object' && + 'toHexString' in value && + typeof value.toHexString === 'function' + ); +} + +function positiveInteger(value: unknown): number | undefined { + return typeof value === 'number' && Number.isInteger(value) && value > 0 + ? value + : undefined; +} + +function numericValue(value: unknown): number { + return typeof value === 'number' && Number.isFinite(value) ? value : 0; +} + +function issue( + code: string, + message: string, + details?: Record, +): CompetitionMigrationIssue { + return { + code, + message, + ...(details && Object.keys(details).length > 0 ? { details } : {}), + }; +} + +function quarantined( + matchId: string, + reasons: CompetitionMigrationIssue[], + warnings: CompetitionMigrationIssue[], +): QuarantinedCompetitionMigrationPlan { + return { + status: 'quarantined', + matchId, + reasons: sortedIssues(reasons), + warnings: sortedIssues(warnings), + }; +} + +function sortedIssues( + issues: CompetitionMigrationIssue[], +): CompetitionMigrationIssue[] { + return [...issues].sort( + (left, right) => + left.code.localeCompare(right.code) || + canonicalize(left.details).localeCompare(canonicalize(right.details)), + ); +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +function errorCodeDetails(error: unknown): Record | undefined { + if (!error || typeof error !== 'object' || !('code' in error)) + return undefined; + return { projectorCode: String((error as { code: unknown }).code) }; +} diff --git a/apps/api/src/modules/global/database/migrations/competition-domain-runner.spec.ts b/apps/api/src/modules/global/database/migrations/competition-domain-runner.spec.ts new file mode 100644 index 00000000..fc045b90 --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/competition-domain-runner.spec.ts @@ -0,0 +1,1125 @@ +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, + }); + if (result.matches[0].status !== 'ready') { + throw new Error('Expected a ready dry-run result.'); + } + expect(result.matches[0].planHash).toMatch(/^sha256:[a-f0-9]{64}$/); + const repeated = await migrateCompetitionDomain(db); + expect(repeated.matches[0]).toMatchObject({ status: 'ready' }); + if (repeated.matches[0].status !== 'ready') { + throw new Error('Expected a repeated ready dry-run result.'); + } + expect(repeated.matches[0].planHash).toBe(result.matches[0].planHash); + expect(startSession).not.toHaveBeenCalled(); + expect(db.writeCount).toBe(0); + expect(db.docs('competition')).toHaveLength(0); + expect(db.createdIndexes).toHaveLength(0); + }); + + it('reports apply-time global identity conflicts during dry-run without writes', async () => { + const riotMatchId = 'KR_DRY_RUN_GLOBAL_CONFLICT'; + const match = readyMatch(riotMatchId); + const conflictingFactId = objectId(); + const db = new MemoryMigrationDb({ + match: [match], + riotMatch: [riotArchive(riotMatchId)], + tournamentCode: [usedTournamentCode(match, riotMatchId)], + competition_fact: [ + { + _id: conflictingFactId, + competitionId: objectId(), + type: 'game-accepted', + evidence: { type: 'riot', riotMatchId }, + }, + ], + }); + + const dryRun = await migrateCompetitionDomain(db); + + expect(dryRun.summary).toMatchObject({ + scanned: 1, + ready: 0, + applied: 0, + quarantined: 1, + failed: 0, + }); + expect(dryRun.matches[0]).toMatchObject({ status: 'quarantined' }); + if (dryRun.matches[0].status !== 'quarantined') { + throw new Error('Expected a quarantined dry-run result.'); + } + const conflict = dryRun.matches[0].reasons.find( + ({ code }) => code === 'GLOBAL_UNIQUE_INDEX_CONFLICT', + ); + expect(conflict?.details?.collection).toBe('competition_fact'); + expect(conflict?.details?.indexName).toBe('evidence.riotMatchId_1'); + expect(conflict?.details?.conflictingDocumentId).toBe( + conflictingFactId.toHexString(), + ); + expect(db.writeCount).toBe(0); + expect(db.createdIndexes).toHaveLength(0); + + const applied = await migrateCompetitionDomain(db, { + dryRun: false, + startSession: () => Promise.resolve(new FakeSession()), + }); + + expect(applied.summary).toMatchObject({ applied: 0, quarantined: 1 }); + expect(applied.matches[0]).toEqual(dryRun.matches[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('persists the source voidedAt timestamp without synthesizing it from usedAt', async () => { + const match = readyMatch('KR_VOIDED_TIMESTAMP'); + const code = usedTournamentCode(match, 'KR_VOIDED_TIMESTAMP'); + code.state = 'voided'; + code.voidedAt = new Date('2026-07-03T00:00:00.000Z'); + const db = new MemoryMigrationDb({ + match: [match], + riotMatch: [riotArchive('KR_VOIDED_TIMESTAMP')], + tournamentCode: [code], + }); + + const result = await migrateCompetitionDomain(db, { + dryRun: false, + startSession: () => Promise.resolve(new FakeSession()), + }); + + expect(result.summary).toMatchObject({ applied: 1, failed: 0 }); + expect(db.docs('tournament_code_assignment')).toContainEqual( + expect.objectContaining({ + state: 'voided', + voidedAt: new Date('2026-07-03T00:00:00.000Z'), + updatedAt: new Date('2026-07-03T00:00:00.000Z'), + }), + ); + }); + + it('hydrates Riot occurrence evidence and persists the normalized used transition idempotently', async () => { + const riotMatchId = 'KR_LEGACY_USED_TRANSITION'; + const match = readyMatch(riotMatchId); + match.updatedAt = new Date('2026-07-03T00:06:00.000Z'); + const legacyOccurrenceAt = new Date(1_782_864_000_000 + 1800 * 1000); + const code = usedTournamentCode(match, riotMatchId); + code.reservedAt = new Date('2026-07-03T00:00:00.000Z'); + code.usedAt = legacyOccurrenceAt; + code.updatedAt = new Date('2026-07-03T00:05:00.000Z'); + const originalCode = canonical(code); + const archive = riotArchive(riotMatchId); + archive.raw = { + info: { + gameCreation: 1_782_864_000_000, + gameEndTimestamp: legacyOccurrenceAt.getTime(), + }, + }; + const db = new MemoryMigrationDb({ + match: [match], + riotMatch: [archive], + tournamentCode: [code], + }); + + const dryRun = await migrateCompetitionDomain(db); + + expect(dryRun.summary).toMatchObject({ + ready: 1, + quarantined: 0, + warnings: 1, + }); + const warning = dryRun.matches[0].warnings.find( + ({ code: warningCode }) => + warningCode === 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED', + ); + expect(warning?.details).toMatchObject({ + originalReservedAt: '2026-07-03T00:00:00.000Z', + originalUsedAt: legacyOccurrenceAt.toISOString(), + sourceUpdatedAt: '2026-07-03T00:05:00.000Z', + normalizedUsedAt: '2026-07-03T00:05:00.000Z', + legacyOccurrenceSource: 'riot-archive-gameEndTimestamp', + riotMatchId, + strategy: 'use-persisted-transition-time', + }); + expect(db.writeCount).toBe(0); + + const firstApply = await migrateCompetitionDomain(db, { + dryRun: false, + startSession: () => Promise.resolve(new FakeSession()), + }); + + expect(firstApply.summary).toMatchObject({ applied: 1, failed: 0 }); + expect(db.docs('tournament_code_assignment')).toContainEqual( + expect.objectContaining({ + state: 'used', + reservedAt: new Date('2026-07-03T00:00:00.000Z'), + usedAt: new Date('2026-07-03T00:05:00.000Z'), + createdAt: new Date('2026-07-03T00:00:00.000Z'), + updatedAt: new Date('2026-07-03T00:05:00.000Z'), + }), + ); + expect(canonical(db.docs('tournamentCode')[0])).toBe(originalCode); + + const replay = await migrateCompetitionDomain(db, { + dryRun: false, + startSession: () => Promise.resolve(new FakeSession()), + }); + + expect(replay.summary).toMatchObject({ + applied: 0, + alreadyApplied: 1, + failed: 0, + }); + }); + + it.each([ + [ + 'raw.info.gameCreation', + { raw: { info: { gameCreation: 1_782_864_000_000 } } }, + ], + [ + 'top-level gameCreation', + { + gameCreation: 1_782_864_000_000, + raw: { metadata: { matchId: 'KR_GAME_CREATION_FALLBACK' } }, + }, + ], + ])( + 'hydrates the %s Riot occurrence fallback', + async (_label, archiveFields) => { + const riotMatchId = 'KR_GAME_CREATION_FALLBACK'; + const match = readyMatch(riotMatchId); + const code = usedTournamentCode(match, riotMatchId); + code.reservedAt = new Date('2026-07-01T00:10:00.000Z'); + code.usedAt = new Date('2026-07-01T00:00:00.000Z'); + code.updatedAt = new Date('2026-07-01T00:20:00.000Z'); + const archive = Object.assign(riotArchive(riotMatchId), archiveFields); + const db = new MemoryMigrationDb({ + match: [match], + riotMatch: [archive], + tournamentCode: [code], + }); + + const result = await migrateCompetitionDomain(db); + + expect(result.summary).toMatchObject({ ready: 1, quarantined: 0 }); + const warning = result.matches[0].warnings.find( + ({ code: warningCode }) => + warningCode === 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED', + ); + expect(warning?.details).toMatchObject({ + originalUsedAt: '2026-07-01T00:00:00.000Z', + normalizedUsedAt: '2026-07-01T00:20:00.000Z', + legacyOccurrenceSource: 'riot-archive-gameCreation', + }); + }, + ); + + it.each([ + ['null', null], + ['blank', ''], + ['invalid', 'not-a-date'], + ])( + 'falls back to archive gameCreation when gameEndTimestamp is %s', + async (_label, invalidGameEnd) => { + const riotMatchId = 'KR_INVALID_ARCHIVE_GAME_END'; + const match = readyMatch(riotMatchId); + const code = usedTournamentCode(match, riotMatchId); + code.reservedAt = new Date('2026-07-01T00:10:00.000Z'); + code.usedAt = new Date('2026-07-01T00:00:00.000Z'); + code.updatedAt = new Date('2026-07-01T00:20:00.000Z'); + const archive = riotArchive(riotMatchId); + archive.raw = { + info: { + gameEndTimestamp: invalidGameEnd, + gameCreation: 1_782_864_000_000, + }, + }; + const db = new MemoryMigrationDb({ + match: [match], + riotMatch: [archive], + tournamentCode: [code], + }); + + const result = await migrateCompetitionDomain(db); + + expect(result.summary).toMatchObject({ ready: 1, quarantined: 0 }); + const warning = result.matches[0].warnings.find( + ({ code: warningCode }) => + warningCode === 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED', + ); + expect(warning?.details).toMatchObject({ + legacyOccurrenceSource: 'riot-archive-gameCreation', + }); + }, + ); + + 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('detects the same global identity collision between dry-run plans as sequential apply', async () => { + const riotMatchId = 'KR_SHARED_DRY_RUN_MIGRATION'; + const firstMatch = readyMatch(riotMatchId); + const secondMatch = readyMatch(riotMatchId); + const db = new MemoryMigrationDb({ + match: [firstMatch, secondMatch], + riotMatch: [riotArchive(riotMatchId)], + tournamentCode: [ + usedTournamentCode(firstMatch, riotMatchId), + usedTournamentCode(secondMatch, riotMatchId), + ], + }); + + const dryRun = await migrateCompetitionDomain(db); + + expect(dryRun.summary).toMatchObject({ ready: 1, quarantined: 1 }); + expect(dryRun.matches.map(({ status }) => status)).toEqual([ + 'ready', + 'quarantined', + ]); + expect(dryRun.matches[1]).toMatchObject({ status: 'quarantined' }); + if (dryRun.matches[1].status !== 'quarantined') { + throw new Error('Expected the second dry-run result to be quarantined.'); + } + expect( + dryRun.matches[1].reasons.some( + ({ code }) => code === 'GLOBAL_UNIQUE_INDEX_CONFLICT', + ), + ).toBe(true); + expect(db.writeCount).toBe(0); + + const applied = await migrateCompetitionDomain(db, { + dryRun: false, + startSession: () => Promise.resolve(new FakeSession()), + }); + + expect(applied.summary).toMatchObject({ applied: 1, quarantined: 1 }); + expect(applied.matches[1]).toEqual(dryRun.matches[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 { + this.committed += 1; + } + + async abortTransaction(): Promise { + this.aborted += 1; + } + + async endSession(): Promise { + this.ended += 1; + } +} + +type AnyDoc = Record & { _id: unknown }; + +class MemoryMigrationDb implements CompetitionDomainMigrationDb { + private readonly collections = new Map(); + public writeCount = 0; + public readonly createdIndexes: Array<{ + collection: string; + key: Record; + options: Record; + }> = []; + public readonly operations: string[] = []; + public indexCreationError?: Error; + + constructor(seed: Record = {}) { + 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, + options: Record, + ) { + 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) { + return new MemoryCursor(() => + owner.docs(name).filter((doc) => matches(doc, filter)), + ); + }, + async findOne(filter: Record) { + return owner.docs(name).find((doc) => matches(doc, filter)) ?? null; + }, + async updateOne( + filter: Record, + update: Record>, + 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) { + 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 = {}; + private max = 0; + + constructor(private readonly read: () => AnyDoc[]) {} + + sort(spec: Record): this { + this.sortSpec = spec; + return this; + } + + limit(limit: number): this { + this.max = limit; + return this; + } + + async *[Symbol.asyncIterator](): AsyncIterator { + 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): boolean { + return Object.entries(filter).every(([key, expected]) => { + if (key === '$or') { + return (expected as Record[]).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((current, segment) => { + if (Array.isArray(current) && /^\d+$/.test(segment)) { + return current[Number(segment)]; + } + return isRecord(current) ? current[segment] : undefined; + }, value); +} + +function materializeEqualityFilter(filter: Record): 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 { + 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; + }); +} diff --git a/apps/api/src/modules/global/database/migrations/competition-domain-runner.ts b/apps/api/src/modules/global/database/migrations/competition-domain-runner.ts new file mode 100644 index 00000000..2aee988b --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/competition-domain-runner.ts @@ -0,0 +1,1488 @@ +import { createHash } from 'node:crypto'; +import mongoose from 'mongoose'; +import { projectCompetition } from '../../../competition/domain/competition-projector'; +import { + COMPETITION_DOMAIN_INVARIANT_INDEXES, + type CompetitionDomainInvariantIndex, +} from '../../../competition/competition.schema'; +import { + planCompetitionMigration, + type CompetitionMigrationAssignment, + type CompetitionMigrationFact, + type CompetitionMigrationIssue, + type LegacyMatchInput, + type ReadyCompetitionMigrationPlan, +} from './20260712-competition-domain'; + +const DEFAULT_MIGRATION_RUN_ID = '20260712-competition-domain'; +const MATCH_SCAN_FILTER = { 'teams.1': { $exists: true } }; + +type AnyDocument = Record & { _id: unknown }; + +export interface CompetitionDomainMigrationCursor extends AsyncIterable { + sort(specification: Record): CompetitionDomainMigrationCursor; + limit(limit: number): CompetitionDomainMigrationCursor; +} + +export interface CompetitionDomainMigrationCollection { + createIndex( + key: mongoose.IndexDefinition, + options: mongoose.IndexOptions, + ): Promise; + find( + filter: Record, + options?: { session?: CompetitionDomainMigrationSession }, + ): CompetitionDomainMigrationCursor; + findOne( + filter: Record, + options?: { session?: CompetitionDomainMigrationSession }, + ): Promise; + updateOne( + filter: Record, + update: { + $set?: Record; + $setOnInsert?: Record; + $unset?: Record; + }, + options?: { + session?: CompetitionDomainMigrationSession; + upsert?: boolean; + }, + ): Promise<{ + matchedCount?: number; + modifiedCount?: number; + upsertedCount?: number; + }>; + deleteOne( + filter: Record, + options?: { session?: CompetitionDomainMigrationSession }, + ): Promise<{ deletedCount?: number }>; +} + +export interface CompetitionDomainMigrationDb { + collection(name: string): CompetitionDomainMigrationCollection; +} + +export interface CompetitionDomainMigrationSession { + startTransaction(): void; + commitTransaction(): Promise; + abortTransaction(): Promise; + endSession(): Promise; +} + +export interface CompetitionDomainMigrationOptions { + dryRun?: boolean; + limit?: number; + afterMatchId?: string; + migrationRunId?: string; + now?: Date; + startSession?: () => Promise; + onProgress?: (progress: CompetitionDomainMigrationProgress) => void; +} + +export interface CompetitionDomainMigrationProgress { + index: number; + matchId: string; + status: CompetitionDomainMigrationMatchResult['status']; + total: number; +} + +interface CompetitionDomainMigrationMatchBase { + matchId: string; + competitionId?: string; + warnings: CompetitionMigrationIssue[]; +} + +export type CompetitionDomainMigrationMatchResult = + | (CompetitionDomainMigrationMatchBase & { + status: 'ready' | 'applied'; + factCount: number; + assignmentCount: number; + planHash: string; + }) + | (CompetitionDomainMigrationMatchBase & { + status: 'already-applied'; + }) + | (CompetitionDomainMigrationMatchBase & { + status: 'quarantined'; + reasons: CompetitionMigrationIssue[]; + }) + | (CompetitionDomainMigrationMatchBase & { + status: 'failed'; + error: string; + }); + +export interface CompetitionDomainMigrationSummary { + scanned: number; + ready: number; + applied: number; + alreadyApplied: number; + quarantined: number; + failed: number; + /** Planner/runtime failures that were neither ready nor explicitly quarantined. */ + unclassified: number; + factsPlanned: number; + assignmentsPlanned: number; + warnings: number; +} + +export interface CompetitionDomainMigrationResult { + migrationRunId: string; + mode: 'dry-run' | 'apply'; + indexPreflight: CompetitionDomainIndexPreflight; + resume: CompetitionDomainMigrationResume; + summary: CompetitionDomainMigrationSummary; + matches: CompetitionDomainMigrationMatchResult[]; +} + +export interface CompetitionDomainMigrationResume { + strategy: 'none' | 'cursor' | 'checkpoint'; + startedAfterMatchId?: string; + checkpointAfterMatchId?: string; + hasMore: boolean; + completed: boolean; +} + +export interface CompetitionDomainIndexConflict { + collection: CompetitionDomainInvariantIndex['collection']; + indexName: string; + key: Record; + code?: number; + keyPattern?: Record; + keyValue?: unknown; + message: string; +} + +export interface CompetitionDomainIndexPreflight { + status: 'dry-run' | 'ensured' | 'blocked'; + requiredIndexes: number; + ensuredIndexes: string[]; + conflicts: CompetitionDomainIndexConflict[]; +} + +/** + * Plans or applies the clean-break Competition migration. Apply mode owns one + * Mongo transaction per Match so a process can be stopped and safely resumed. + */ +export async function migrateCompetitionDomain( + db: CompetitionDomainMigrationDb, + options: CompetitionDomainMigrationOptions = {}, +): Promise { + const dryRun = options.dryRun ?? true; + const migrationRunId = + options.migrationRunId?.trim() || DEFAULT_MIGRATION_RUN_ID; + assertOptions(options); + + const resumeStart = await resolveResumeStart( + db, + migrationRunId, + options, + dryRun, + ); + + const indexPreflight = await ensureCompetitionDomainIndexes(db, dryRun); + if (indexPreflight.status === 'blocked') { + return { + migrationRunId, + mode: 'apply', + indexPreflight, + resume: resumeReport(resumeStart, undefined, true, false), + summary: summarize([]), + matches: [], + }; + } + if (!dryRun && options.limit !== undefined && options.afterMatchId) { + await persistMigrationCheckpoint(db, { + migrationRunId, + matchId: options.afterMatchId, + completed: false, + resetMatchStatus: true, + observedAt: options.now ?? new Date(), + }); + } + + const scan = await scanMatches( + db, + options.limit, + resumeStart.startedAfterMatchId, + ); + const matches: CompetitionDomainMigrationMatchResult[] = []; + const dryRunUniquenessClaims = new Map(); + let checkpointAfterMatchId = resumeStart.startedAfterMatchId; + let haltedOnFailure = false; + for (const [index, scannedMatch] of scan.matches.entries()) { + const result = dryRun + ? await inspectMatch( + db, + scannedMatch, + migrationRunId, + dryRunUniquenessClaims, + ) + : await applyMatch(db, scannedMatch, migrationRunId, options); + matches.push(result); + options.onProgress?.({ + index: index + 1, + matchId: result.matchId, + status: result.status, + total: scan.matches.length, + }); + if (!dryRun && options.limit !== undefined) { + if (result.status === 'failed') { + haltedOnFailure = true; + break; + } + await persistMigrationCheckpoint(db, { + migrationRunId, + matchId: result.matchId, + matchStatus: result.status, + completed: false, + observedAt: options.now ?? new Date(), + }); + checkpointAfterMatchId = result.matchId; + } + } + + const hasMore = + scan.hasMore || haltedOnFailure || matches.length < scan.matches.length; + const completed = + !hasMore && !matches.some(({ status }) => status === 'failed'); + if (!dryRun && options.limit !== undefined && completed) { + await persistMigrationCheckpoint(db, { + migrationRunId, + matchId: checkpointAfterMatchId, + completed: true, + observedAt: options.now ?? new Date(), + }); + } + + return { + migrationRunId, + mode: dryRun ? 'dry-run' : 'apply', + indexPreflight, + resume: resumeReport( + resumeStart, + checkpointAfterMatchId, + hasMore, + completed, + ), + summary: summarize(matches), + matches, + }; +} + +interface ResumeStart { + strategy: CompetitionDomainMigrationResume['strategy']; + startedAfterMatchId?: string; +} + +async function resolveResumeStart( + db: CompetitionDomainMigrationDb, + migrationRunId: string, + options: CompetitionDomainMigrationOptions, + dryRun: boolean, +): Promise { + if (dryRun || options.limit === undefined) { + return { + strategy: options.afterMatchId ? 'cursor' : 'none', + ...(options.afterMatchId + ? { startedAfterMatchId: options.afterMatchId } + : {}), + }; + } + if (options.afterMatchId) { + return { + strategy: 'cursor', + startedAfterMatchId: options.afterMatchId, + }; + } + const checkpoint = await db + .collection('competition_migration_checkpoint') + .findOne({ _id: migrationRunId }); + const checkpointMatchId = optionalIdString(checkpoint?.lastMatchId); + if (checkpointMatchId) assertMatchCursor(checkpointMatchId); + return { + strategy: 'checkpoint', + ...(checkpointMatchId ? { startedAfterMatchId: checkpointMatchId } : {}), + }; +} + +function resumeReport( + start: ResumeStart, + checkpointAfterMatchId: string | undefined, + hasMore: boolean, + completed: boolean, +): CompetitionDomainMigrationResume { + return { + strategy: start.strategy, + ...(start.startedAfterMatchId + ? { startedAfterMatchId: start.startedAfterMatchId } + : {}), + ...(checkpointAfterMatchId ? { checkpointAfterMatchId } : {}), + hasMore, + completed, + }; +} + +async function persistMigrationCheckpoint( + db: CompetitionDomainMigrationDb, + params: { + migrationRunId: string; + matchId?: string; + matchStatus?: CompetitionDomainMigrationMatchResult['status']; + completed: boolean; + resetMatchStatus?: boolean; + observedAt: Date; + }, +): Promise { + await db.collection('competition_migration_checkpoint').updateOne( + { _id: params.migrationRunId }, + { + $set: { + migrationRunId: params.migrationRunId, + status: params.completed ? 'completed' : 'running', + ...(params.matchId + ? { lastMatchId: persistenceId(params.matchId) } + : {}), + ...(params.matchStatus ? { lastMatchStatus: params.matchStatus } : {}), + updatedAt: params.observedAt, + }, + $setOnInsert: { + _id: params.migrationRunId, + createdAt: params.observedAt, + }, + ...(params.resetMatchStatus ? { $unset: { lastMatchStatus: 1 } } : {}), + }, + { upsert: true }, + ); +} + +async function ensureCompetitionDomainIndexes( + db: CompetitionDomainMigrationDb, + dryRun: boolean, +): Promise { + if (dryRun) { + return { + status: 'dry-run', + requiredIndexes: COMPETITION_DOMAIN_INVARIANT_INDEXES.length, + ensuredIndexes: [], + conflicts: [], + }; + } + + const ensuredIndexes: string[] = []; + const conflicts: CompetitionDomainIndexConflict[] = []; + for (const index of COMPETITION_DOMAIN_INVARIANT_INDEXES) { + try { + const createdName = await db + .collection(index.collection) + .createIndex(index.key, index.options); + ensuredIndexes.push(createdName); + } catch (error) { + conflicts.push(indexConflict(index, error)); + } + } + return { + status: conflicts.length > 0 ? 'blocked' : 'ensured', + requiredIndexes: COMPETITION_DOMAIN_INVARIANT_INDEXES.length, + ensuredIndexes, + conflicts, + }; +} + +function indexConflict( + index: CompetitionDomainInvariantIndex, + error: unknown, +): CompetitionDomainIndexConflict { + const record = isRecord(error) ? error : {}; + const code = + typeof record.code === 'number' && Number.isInteger(record.code) + ? record.code + : undefined; + const keyPattern = isRecord(record.keyPattern) + ? (canonicalValue(record.keyPattern) as Record) + : undefined; + const keyValue = + record.keyValue === undefined ? undefined : canonicalValue(record.keyValue); + return { + collection: index.collection, + indexName: index.options.name, + key: canonicalValue(index.key) as Record, + ...(code === undefined ? {} : { code }), + ...(keyPattern ? { keyPattern } : {}), + ...(keyValue === undefined ? {} : { keyValue }), + message: error instanceof Error ? error.message : String(error), + }; +} + +async function scanMatches( + db: CompetitionDomainMigrationDb, + limit: number | undefined, + afterMatchId: string | undefined, +): Promise<{ matches: AnyDocument[]; hasMore: boolean }> { + const scanned = await readCursor( + db + .collection('match') + .find({ + ...MATCH_SCAN_FILTER, + ...(afterMatchId ? { _id: { $gt: persistenceId(afterMatchId) } } : {}), + }) + .sort({ _id: 1 }) + .limit(limit === undefined ? 0 : limit + 1), + ); + if (limit === undefined) return { matches: scanned, hasMore: false }; + return { + matches: scanned.slice(0, limit), + hasMore: scanned.length > limit, + }; +} + +async function inspectMatch( + db: CompetitionDomainMigrationDb, + scannedMatch: AnyDocument, + migrationRunId: string, + uniquenessClaims: Map, +): Promise { + const matchId = idString(scannedMatch._id); + try { + const linkedCompetitionId = optionalIdString(scannedMatch.competitionId); + if (linkedCompetitionId) { + assertExpectedCompetitionId(matchId, linkedCompetitionId); + await verifyProjectionReplay(db, linkedCompetitionId); + return { + status: 'already-applied', + matchId, + competitionId: linkedCompetitionId, + warnings: [], + }; + } + + const legacy = await hydrateLegacyMatch(db, scannedMatch); + const plan = planCompetitionMigration(legacy, { migrationRunId }); + if (plan.status === 'ready') { + const uniquenessConflicts = await findReadyPlanUniquenessConflicts( + db, + plan, + { claims: uniquenessClaims }, + ); + if (uniquenessConflicts.length > 0) { + return { + status: 'quarantined', + matchId, + warnings: plan.warnings, + reasons: uniquenessConflicts, + }; + } + } + return planResult(matchId, plan); + } catch (error) { + return failedResult(matchId, error); + } +} + +async function applyMatch( + db: CompetitionDomainMigrationDb, + scannedMatch: AnyDocument, + migrationRunId: string, + options: CompetitionDomainMigrationOptions, +): Promise { + const matchId = idString(scannedMatch._id); + let session: CompetitionDomainMigrationSession | undefined; + try { + session = await options.startSession?.(); + if (!session) { + throw new Error( + 'Apply mode requires a MongoDB transaction session for every Match.', + ); + } + session.startTransaction(); + + const currentMatch = await db + .collection('match') + .findOne({ _id: scannedMatch._id }, { session }); + if (!currentMatch) throw new Error(`Match ${matchId} no longer exists.`); + + const linkedCompetitionId = optionalIdString(currentMatch.competitionId); + if (linkedCompetitionId) { + assertExpectedCompetitionId(matchId, linkedCompetitionId); + await verifyProjectionReplay(db, linkedCompetitionId, session); + await db + .collection('competition_migration_quarantine') + .deleteOne({ _id: currentMatch._id }, { session }); + await verifyProjectionReplay(db, linkedCompetitionId, session); + await session.commitTransaction(); + return { + status: 'already-applied', + matchId, + competitionId: linkedCompetitionId, + warnings: [], + }; + } + + // Re-read all evidence inside the transaction. The scan is only a work + // list; it is never treated as the source snapshot for an apply. + const legacy = await hydrateLegacyMatch(db, currentMatch, session); + const plan = planCompetitionMigration(legacy, { migrationRunId }); + if (plan.status === 'quarantined') { + await persistQuarantine( + db, + currentMatch, + plan.reasons, + plan.warnings, + migrationRunId, + options.now ?? new Date(), + session, + ); + await session.commitTransaction(); + return { + status: 'quarantined', + matchId, + warnings: plan.warnings, + reasons: plan.reasons, + }; + } + + const uniquenessConflicts = await findReadyPlanUniquenessConflicts( + db, + plan, + { session }, + ); + if (uniquenessConflicts.length > 0) { + await persistQuarantine( + db, + currentMatch, + uniquenessConflicts, + plan.warnings, + migrationRunId, + options.now ?? new Date(), + session, + ); + await session.commitTransaction(); + return { + status: 'quarantined', + matchId, + warnings: plan.warnings, + reasons: uniquenessConflicts, + }; + } + + await upsertReadyPlan(db, plan, session); + await verifyReadyPlan(db, plan, session); + + const competitionId = plan.competition.id; + const linkResult = await db.collection('match').updateOne( + { + _id: currentMatch._id, + $or: [ + { competitionId: { $exists: false } }, + { competitionId: null }, + { competitionId: persistenceId(competitionId) }, + ], + }, + { $set: { competitionId: persistenceId(competitionId) } }, + { session }, + ); + if (linkResult.matchedCount !== 1) { + throw new Error( + `Match ${matchId} was concurrently linked to another Competition.`, + ); + } + + await db + .collection('competition_migration_quarantine') + .deleteOne({ _id: currentMatch._id }, { session }); + // Verify again after the final Match/quarantine writes, immediately before + // committing, so every applied Match ends with a replay-equal aggregate. + await verifyProjectionReplay(db, competitionId, session); + await session.commitTransaction(); + return { + status: 'applied', + matchId, + competitionId, + factCount: plan.facts.length, + assignmentCount: plan.assignments.length, + planHash: readyPlanHash(plan), + warnings: plan.warnings, + }; + } catch (error) { + if (session) await session.abortTransaction().catch(() => undefined); + return failedResult(matchId, error); + } finally { + if (session) await session.endSession().catch(() => undefined); + } +} + +interface UniqueIdentityCheck { + collection: 'competition' | 'competition_fact' | 'tournament_code_assignment'; + indexName: string; + filter: Record; + expectedDocumentId: string; + expectedCompetitionId?: string; +} + +interface ClaimedUniqueIdentity { + documentId: string; + competitionId?: string; +} + +async function findReadyPlanUniquenessConflicts( + db: CompetitionDomainMigrationDb, + plan: ReadyCompetitionMigrationPlan, + options: { + session?: CompetitionDomainMigrationSession; + claims?: Map; + } = {}, +): Promise { + const checks: UniqueIdentityCheck[] = [ + { + collection: 'competition', + indexName: 'matchId_1', + filter: { matchId: persistenceId(plan.competition.matchId) }, + expectedDocumentId: plan.competition.id, + }, + ]; + + for (const fact of plan.facts) { + checks.push( + { + collection: 'competition_fact', + indexName: 'competitionId_1_revision_1_ordinalWithinRevision_1', + filter: { + competitionId: persistenceId(fact.competitionId), + revision: fact.revision, + ordinalWithinRevision: fact.ordinalWithinRevision, + }, + expectedDocumentId: fact.id, + expectedCompetitionId: fact.competitionId, + }, + { + collection: 'competition_fact', + indexName: 'competitionId_1_commandId_1_ordinalWithinRevision_1', + filter: { + competitionId: persistenceId(fact.competitionId), + commandId: fact.commandId, + ordinalWithinRevision: fact.ordinalWithinRevision, + }, + expectedDocumentId: fact.id, + expectedCompetitionId: fact.competitionId, + }, + ); + if (fact.type === 'game-accepted' && fact.evidence.type === 'riot') { + checks.push({ + collection: 'competition_fact', + indexName: 'evidence.riotMatchId_1', + filter: { + type: 'game-accepted', + 'evidence.riotMatchId': fact.evidence.riotMatchId, + }, + expectedDocumentId: fact.id, + expectedCompetitionId: fact.competitionId, + }); + } + } + + for (const assignment of plan.assignments) { + if (assignment.state === 'reserved' || assignment.state === 'used') { + checks.push( + { + collection: 'tournament_code_assignment', + indexName: 'gameSlotId_1', + filter: { + gameSlotId: persistenceId(assignment.gameSlotId), + state: { $in: ['reserved', 'used'] }, + }, + expectedDocumentId: assignment.id, + expectedCompetitionId: assignment.competitionId, + }, + { + collection: 'tournament_code_assignment', + indexName: 'tournamentCodeId_1', + filter: { + tournamentCodeId: persistenceId(assignment.tournamentCodeId), + state: { $in: ['reserved', 'used'] }, + }, + expectedDocumentId: assignment.id, + expectedCompetitionId: assignment.competitionId, + }, + ); + } + if (assignment.riotMatchId) { + checks.push({ + collection: 'tournament_code_assignment', + indexName: 'riotMatchId_1', + filter: { riotMatchId: assignment.riotMatchId }, + expectedDocumentId: assignment.id, + expectedCompetitionId: assignment.competitionId, + }); + } + } + + const conflicts: CompetitionMigrationIssue[] = []; + // Mongo sessions do not support parallel operations inside one transaction. + for (const check of checks) { + const claim = options.claims?.get(uniqueIdentityKey(check)); + if (claim && claim.documentId !== check.expectedDocumentId) { + conflicts.push( + uniqueIdentityConflict(check, { + _id: persistenceId(claim.documentId), + ...(claim.competitionId + ? { competitionId: persistenceId(claim.competitionId) } + : {}), + }), + ); + continue; + } + const existing = await db + .collection(check.collection) + .findOne( + check.filter, + options.session ? { session: options.session } : undefined, + ); + if (!existing || idString(existing._id) === check.expectedDocumentId) { + continue; + } + conflicts.push(uniqueIdentityConflict(check, existing)); + } + if (conflicts.length === 0 && options.claims) { + for (const check of checks) { + options.claims.set(uniqueIdentityKey(check), { + documentId: check.expectedDocumentId, + ...(check.expectedCompetitionId + ? { competitionId: check.expectedCompetitionId } + : {}), + }); + } + } + return conflicts; +} + +function uniqueIdentityKey(check: UniqueIdentityCheck): string { + return `${check.collection}:${check.indexName}:${canonicalJson(check.filter)}`; +} + +function uniqueIdentityConflict( + check: UniqueIdentityCheck, + existing: AnyDocument, +): CompetitionMigrationIssue { + return { + code: 'GLOBAL_UNIQUE_INDEX_CONFLICT', + message: `Migration input conflicts with ${check.collection}.${check.indexName}.`, + details: { + collection: check.collection, + indexName: check.indexName, + key: canonicalValue(check.filter) as Record, + expectedDocumentId: check.expectedDocumentId, + conflictingDocumentId: idString(existing._id), + ...(existing.competitionId + ? { conflictingCompetitionId: idString(existing.competitionId) } + : {}), + }, + }; +} + +async function hydrateLegacyMatch( + db: CompetitionDomainMigrationDb, + match: AnyDocument, + session?: CompetitionDomainMigrationSession, +): Promise { + const tournamentCodeIds = arrayOf(match.tournamentCodeIds); + const tournamentCodes = await readCursor( + db + .collection('tournamentCode') + .find( + { + $or: [ + ...(tournamentCodeIds.length > 0 + ? [{ _id: { $in: tournamentCodeIds } }] + : []), + { matchId: match._id }, + ], + }, + { session }, + ) + .sort({ _id: 1 }) + .limit(0), + ); + const result = isRecord(match.result) ? match.result : undefined; + const games = arrayOf(result?.games); + const riotMatchIds = uniqueStrings( + games.map((game) => (isRecord(game) ? game.riotMatchId : undefined)), + ); + const archives = + riotMatchIds.length === 0 + ? [] + : await readCursor( + db + .collection('riotMatch') + .find({ matchId: { $in: riotMatchIds } }, { session }) + .sort({ matchId: 1 }) + .limit(0), + ); + const archiveByMatchId = new Map( + archives.map((archive) => [String(archive.matchId), archive]), + ); + const archivedIds = new Set(archiveByMatchId.keys()); + const hydratedResult = result + ? { + ...result, + games: games.map((game) => + isRecord(game) + ? hydrateLegacyGameEvidence(game, archiveByMatchId) + : game, + ), + } + : undefined; + + return { + ...match, + // Native collection reads bypass the MatchSchema default. Historical + // documents without a persisted gameMode still executed as pair mode via + // the runtime fallback. + gameMode: match.gameMode ?? 'pair', + ...(hydratedResult ? { result: hydratedResult } : {}), + tournamentCodes, + riotMatchArchiveIds: [...archivedIds].sort(), + } as unknown as LegacyMatchInput; +} + +function hydrateLegacyGameEvidence( + game: Record, + archiveByMatchId: ReadonlyMap, +): Record { + const riotMatchId = + typeof game.riotMatchId === 'string' ? game.riotMatchId : undefined; + const archive = riotMatchId ? archiveByMatchId.get(riotMatchId) : undefined; + if (!archive) return { ...game, riotArchivePresent: false }; + const existingPayloadHash = + typeof game.payloadHash === 'string' && game.payloadHash.trim().length > 0 + ? game.payloadHash + : undefined; + const archiveRaw = isRecord(archive.raw) ? archive.raw : undefined; + const archiveInfo = isRecord(archiveRaw?.info) ? archiveRaw.info : undefined; + const riotGameEndEvidence = resolveRiotGameEndEvidence( + archiveInfo, + archive.gameCreation, + ); + return { + ...game, + riotArchivePresent: true, + ...(riotGameEndEvidence === undefined + ? {} + : { + riotGameEndedAt: riotGameEndEvidence.value, + riotGameEndedAtSource: riotGameEndEvidence.source, + }), + payloadHash: + existingPayloadHash ?? + `sha256:${createNodeHash(canonicalJson(archive.raw ?? archive))}`, + }; +} + +function resolveRiotGameEndEvidence( + archiveInfo: Record | undefined, + archiveGameCreation: unknown, +): + | { + value: unknown; + source: 'gameEndTimestamp' | 'gameCreation'; + } + | undefined { + const candidates = [ + { + value: archiveInfo?.gameEndTimestamp, + source: 'gameEndTimestamp' as const, + }, + { + value: archiveInfo?.gameCreation, + source: 'gameCreation' as const, + }, + { value: archiveGameCreation, source: 'gameCreation' as const }, + ]; + return candidates.find(({ value }) => isValidRiotTimestamp(value)); +} + +function isValidRiotTimestamp(value: unknown): boolean { + if (value === undefined || value === null || value === '') return false; + if (typeof value === 'string' && value.trim() === '') return false; + if (typeof value === 'number' && !Number.isFinite(value)) return false; + const normalized = + typeof value === 'number' && value < 10_000_000_000 ? value * 1000 : value; + try { + const date = + normalized instanceof Date + ? normalized + : new Date(normalized as string | number); + return !Number.isNaN(date.getTime()); + } catch { + return false; + } +} + +async function upsertReadyPlan( + db: CompetitionDomainMigrationDb, + plan: ReadyCompetitionMigrationPlan, + session: CompetitionDomainMigrationSession, +): Promise { + const competition = competitionForPersistence(plan); + await db + .collection('competition') + .updateOne( + { _id: competition._id }, + { $setOnInsert: competition }, + { upsert: true, session }, + ); + for (const fact of plan.facts) { + const persisted = factForPersistence(fact); + await db + .collection('competition_fact') + .updateOne( + { _id: persisted._id }, + { $setOnInsert: persisted }, + { upsert: true, session }, + ); + } + for (const assignment of plan.assignments) { + const persisted = assignmentForPersistence(assignment); + await db + .collection('tournament_code_assignment') + .updateOne( + { _id: persisted._id }, + { $setOnInsert: persisted }, + { upsert: true, session }, + ); + } +} + +async function verifyReadyPlan( + db: CompetitionDomainMigrationDb, + plan: ReadyCompetitionMigrationPlan, + session: CompetitionDomainMigrationSession, +): Promise { + const competition = await db + .collection('competition') + .findOne({ _id: persistenceId(plan.competition.id) }, { session }); + if (!competition) { + throw new Error( + `Competition ${plan.competition.id} is missing after deterministic upsert.`, + ); + } + assertFieldsEqual( + competition, + competitionForPersistence(plan), + [ + '_id', + 'matchId', + 'communityId', + 'schemaVersion', + 'projectorVersion', + 'teams', + 'format', + 'seriesGraph', + ], + `Competition ${plan.competition.id}`, + ); + + for (const fact of plan.facts) { + const expected = factForPersistence(fact); + const actual = await db + .collection('competition_fact') + .findOne({ _id: expected._id }, { session }); + if (!actual) throw new Error(`Migration fact ${fact.id} is missing.`); + assertFieldsEqual( + actual, + expected, + Object.keys(expected).filter( + (key) => key !== 'createdAt' && key !== 'updatedAt', + ), + `Migration fact ${fact.id}`, + ); + } + + for (const assignment of plan.assignments) { + const expected = assignmentForPersistence(assignment); + const actual = await db + .collection('tournament_code_assignment') + .findOne({ _id: expected._id }, { session }); + if (!actual) { + throw new Error(`TournamentCode assignment ${assignment.id} is missing.`); + } + assertFieldsEqual( + actual, + expected, + Object.keys(expected).filter( + (key) => key !== 'createdAt' && key !== 'updatedAt', + ), + `TournamentCode assignment ${assignment.id}`, + ); + } + + await verifyProjectionReplay(db, plan.competition.id, session); +} + +async function verifyProjectionReplay( + db: CompetitionDomainMigrationDb, + competitionId: string, + session?: CompetitionDomainMigrationSession, +): Promise { + const competition = await db + .collection('competition') + .findOne({ _id: persistenceId(competitionId) }, { session }); + if (!competition) { + throw new Error(`Linked Competition ${competitionId} does not exist.`); + } + const facts = await readCursor( + db + .collection('competition_fact') + .find({ competitionId: persistenceId(competitionId) }, { session }) + .sort({ revision: 1, ordinalWithinRevision: 1 }) + .limit(0), + ); + const revision = numberField(competition, 'revision'); + const projectorVersion = numberField(competition, 'projectorVersion'); + assertLedgerRevision(facts, revision, competitionId); + const replay = projectCompetition({ + competitionId, + revision, + projectorVersion, + teams: canonicalValue(competition.teams) as never, + format: canonicalValue(competition.format) as never, + seriesGraph: canonicalValue(competition.seriesGraph) as never, + facts: facts.map(factForProjection), + }); + if (canonicalJson(replay) !== canonicalJson(competition.projection)) { + throw new Error( + `Competition ${competitionId} projection replay does not equal the persisted projection.`, + ); + } + if (replay.phase !== competition.phase) { + throw new Error( + `Competition ${competitionId} replay phase does not equal the persisted phase.`, + ); + } +} + +function assertLedgerRevision( + facts: ReadonlyArray>, + competitionRevision: number, + competitionId: string, +): void { + const positions = new Set(); + const revisions = new Set(); + let maximumRevision = 0; + for (const fact of facts) { + const revision = numberField(fact, 'revision'); + const ordinal = numberField(fact, 'ordinalWithinRevision'); + if (revision < 1 || ordinal < 1) { + throw new Error( + `Competition ${competitionId} has an invalid fact ledger position.`, + ); + } + const position = `${revision}:${ordinal}`; + if (positions.has(position)) { + throw new Error( + `Competition ${competitionId} has duplicate fact ledger position ${position}.`, + ); + } + positions.add(position); + revisions.add(revision); + maximumRevision = Math.max(maximumRevision, revision); + } + if (maximumRevision !== competitionRevision) { + throw new Error( + `Competition ${competitionId} revision ${competitionRevision} does not match fact ledger revision ${maximumRevision}.`, + ); + } + if (revisions.size !== maximumRevision) { + throw new Error( + `Competition ${competitionId} fact ledger has a revision gap.`, + ); + } +} + +async function persistQuarantine( + db: CompetitionDomainMigrationDb, + match: AnyDocument, + reasons: CompetitionMigrationIssue[], + warnings: CompetitionMigrationIssue[], + migrationRunId: string, + observedAt: Date, + session: CompetitionDomainMigrationSession, +): Promise { + const sourceUpdatedAt = dateOrUndefined(match.updatedAt); + const payload = { + matchId: match._id, + migrationRunId, + status: 'quarantined', + reasons, + warnings, + sourceUpdatedAt, + planHash: canonicalHash({ + matchId: idString(match._id), + sourceUpdatedAt, + reasons, + warnings, + }), + observedAt, + updatedAt: observedAt, + }; + await db.collection('competition_migration_quarantine').updateOne( + { _id: match._id }, + { + $set: payload, + $setOnInsert: { _id: match._id, createdAt: observedAt }, + }, + { upsert: true, session }, + ); +} + +function competitionForPersistence( + plan: ReadyCompetitionMigrationPlan, +): AnyDocument { + const source = plan.competition; + return { + _id: persistenceId(source.id), + matchId: persistenceId(source.matchId), + communityId: persistenceId(source.communityId), + schemaVersion: source.schemaVersion, + projectorVersion: source.projectorVersion, + revision: source.revision, + phase: source.phase, + teams: source.teams.map((team) => ({ + ...team, + teamId: persistenceId(team.teamId), + ...(team.captainUserId + ? { captainUserId: persistenceId(team.captainUserId) } + : {}), + members: team.members.map((member) => ({ + ...member, + userId: persistenceId(member.userId), + })), + })), + format: source.format, + seriesGraph: source.seriesGraph, + projection: source.projection, + createdAt: new Date(source.createdAt), + updatedAt: new Date(source.updatedAt), + }; +} + +function factForPersistence(fact: CompetitionMigrationFact): AnyDocument { + const recordedAt = new Date(fact.recordedAt); + const common: AnyDocument = { + ...fact, + _id: persistenceId(fact.id), + competitionId: persistenceId(fact.competitionId), + occurredAt: new Date(fact.occurredAt), + recordedAt, + createdAt: recordedAt, + updatedAt: recordedAt, + }; + delete common.id; + if (fact.type === 'game-accepted') { + common.gameId = persistenceId(fact.gameId); + common.seriesId = persistenceId(fact.seriesId); + common.gameSlotId = persistenceId(fact.gameSlotId); + common.mapping = { + ...fact.mapping, + blueTeamId: persistenceId(fact.mapping.blueTeamId), + redTeamId: persistenceId(fact.mapping.redTeamId), + winnerTeamId: persistenceId(fact.mapping.winnerTeamId), + participantAssignments: fact.mapping.participantAssignments.map( + (assignment) => ({ + ...assignment, + userId: persistenceId(assignment.userId), + teamId: persistenceId(assignment.teamId), + }), + ), + }; + } else { + common.seriesId = persistenceId(fact.seriesId); + common.decision = + 'winnerTeamId' in fact.decision + ? { + ...fact.decision, + winnerTeamId: persistenceId(fact.decision.winnerTeamId), + } + : fact.decision; + } + return common; +} + +function assignmentForPersistence( + assignment: CompetitionMigrationAssignment, +): AnyDocument { + const reservedAt = new Date(assignment.reservedAt); + const updatedAt = new Date( + assignment.voidedAt ?? + assignment.releasedAt ?? + assignment.usedAt ?? + assignment.reservedAt, + ); + const voidedAt = + assignment.state === 'voided' + ? new Date( + assignment.voidedAt ?? + assignment.releasedAt ?? + assignment.usedAt ?? + assignment.reservedAt, + ) + : undefined; + return { + _id: persistenceId(assignment.id), + competitionId: persistenceId(assignment.competitionId), + seriesId: persistenceId(assignment.seriesId), + gameSlotId: persistenceId(assignment.gameSlotId), + tournamentCodeId: persistenceId(assignment.tournamentCodeId), + state: assignment.state, + reservedAt, + ...(assignment.usedAt ? { usedAt: new Date(assignment.usedAt) } : {}), + ...(assignment.releasedAt + ? { releasedAt: new Date(assignment.releasedAt) } + : {}), + ...(voidedAt ? { voidedAt } : {}), + ...(assignment.riotMatchId ? { riotMatchId: assignment.riotMatchId } : {}), + commandId: assignment.commandId, + createdAt: reservedAt, + updatedAt, + }; +} + +function factForProjection( + fact: Readonly>, +): Readonly> { + const canonical = canonicalValue(fact) as Readonly>; + return { ...canonical, id: idString(fact.id ?? fact._id) }; +} + +function planResult( + matchId: string, + plan: ReturnType, +): CompetitionDomainMigrationMatchResult { + if (plan.status === 'quarantined') { + return { + status: 'quarantined', + matchId, + warnings: plan.warnings, + reasons: plan.reasons, + }; + } + return { + status: 'ready', + matchId, + competitionId: plan.competition.id, + factCount: plan.facts.length, + assignmentCount: plan.assignments.length, + planHash: readyPlanHash(plan), + warnings: plan.warnings, + }; +} + +function readyPlanHash(plan: ReadyCompetitionMigrationPlan): string { + return `sha256:${createHash('sha256') + .update( + canonicalJson({ + competition: plan.competition, + facts: plan.facts, + assignments: plan.assignments, + }), + ) + .digest('hex')}`; +} + +function failedResult( + matchId: string, + error: unknown, +): CompetitionDomainMigrationMatchResult { + return { + status: 'failed', + matchId, + warnings: [], + error: error instanceof Error ? error.message : String(error), + }; +} + +function summarize( + matches: CompetitionDomainMigrationMatchResult[], +): CompetitionDomainMigrationSummary { + const count = (status: CompetitionDomainMigrationMatchResult['status']) => + matches.filter((match) => match.status === status).length; + return { + scanned: matches.length, + ready: count('ready'), + applied: count('applied'), + alreadyApplied: count('already-applied'), + quarantined: count('quarantined'), + failed: count('failed'), + unclassified: count('failed'), + factsPlanned: matches.reduce( + (sum, match) => sum + ('factCount' in match ? match.factCount : 0), + 0, + ), + assignmentsPlanned: matches.reduce( + (sum, match) => + sum + ('assignmentCount' in match ? match.assignmentCount : 0), + 0, + ), + warnings: matches.reduce((sum, match) => sum + match.warnings.length, 0), + }; +} + +function assertExpectedCompetitionId( + matchId: string, + linkedCompetitionId: string, +): void { + const expected = deterministicCompetitionId(matchId); + if (linkedCompetitionId !== expected) { + throw new Error( + `Match ${matchId} links Competition ${linkedCompetitionId}; expected deterministic Competition ${expected}.`, + ); + } +} + +function deterministicCompetitionId(matchId: string): string { + return createHash('sha256') + .update(JSON.stringify([matchId, 'competition'])) + .digest('hex') + .slice(0, 24); +} + +function assertFieldsEqual( + actual: Record, + expected: Record, + fields: string[], + label: string, +): void { + for (const field of fields) { + if (canonicalJson(actual[field]) !== canonicalJson(expected[field])) { + throw new Error(`${label} has conflicting persisted field ${field}.`); + } + } +} + +function assertOptions(options: CompetitionDomainMigrationOptions): void { + if ( + options.limit !== undefined && + (!Number.isInteger(options.limit) || options.limit < 1) + ) { + throw new Error('Competition migration limit must be a positive integer.'); + } + if (options.dryRun === false && !options.startSession) { + throw new Error('Apply mode requires a transaction session factory.'); + } + if (options.afterMatchId !== undefined) { + assertMatchCursor(options.afterMatchId); + } +} + +function assertMatchCursor(value: string): void { + if (!/^[a-f\d]{24}$/i.test(value)) { + throw new Error( + 'Competition migration afterMatchId must be a 24-character hexadecimal Match ObjectId.', + ); + } +} + +async function readCursor( + cursor: CompetitionDomainMigrationCursor, +): Promise { + const result: AnyDocument[] = []; + for await (const document of cursor) result.push(document); + return result; +} + +function numberField(document: Record, field: string): number { + const value = document[field]; + if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) { + throw new Error(`Competition has invalid ${field}.`); + } + return value; +} + +function persistenceId(value: unknown): unknown { + if (value instanceof mongoose.Types.ObjectId) return value; + const stringValue = idString(value); + return mongoose.Types.ObjectId.isValid(stringValue) && + /^[a-f\d]{24}$/i.test(stringValue) + ? new mongoose.Types.ObjectId(stringValue) + : value; +} + +function optionalIdString(value: unknown): string | undefined { + return value === undefined || value === null || value === '' + ? undefined + : idString(value); +} + +function idString(value: unknown): string { + if (value instanceof mongoose.Types.ObjectId) return value.toHexString(); + if (hasHexString(value)) { + const rendered = value.toHexString(); + if (typeof rendered === 'string') return rendered; + } + return String(value); +} + +function arrayOf(value: unknown): unknown[] { + return Array.isArray(value) ? value : []; +} + +function uniqueStrings(values: unknown[]): string[] { + return [ + ...new Set( + values.filter( + (value): value is string => + typeof value === 'string' && value.trim().length > 0, + ), + ), + ].sort(); +} + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function dateOrUndefined(value: unknown): Date | undefined { + if (value === undefined || value === null || value === '') return undefined; + const date = value instanceof Date ? value : new Date(value as string); + return Number.isNaN(date.getTime()) ? undefined : date; +} + +function canonicalHash(value: unknown): string { + return `sha256:${createNodeHash(canonicalJson(value))}`; +} + +function createNodeHash(value: string): string { + // Kept in one helper so canonical hashes use exactly one encoding. + return createHash('sha256').update(value).digest('hex'); +} + +function canonicalJson(value: unknown): string { + return JSON.stringify(canonicalValue(value)); +} + +function canonicalValue(value: unknown): unknown { + if (value instanceof mongoose.Types.ObjectId) return value.toHexString(); + if (value instanceof Date) return value.toISOString(); + if (hasHexString(value)) { + const rendered = value.toHexString(); + if (typeof rendered === 'string') return rendered; + } + if (Array.isArray(value)) return value.map(canonicalValue); + if (isRecord(value)) { + return Object.fromEntries( + Object.entries(value) + .filter(([, child]) => child !== undefined) + .sort(([left], [right]) => left.localeCompare(right)) + .map(([key, child]) => [key, canonicalValue(child)]), + ); + } + return value; +} + +function hasHexString(value: unknown): value is { toHexString(): unknown } { + return ( + value !== null && + typeof value === 'object' && + 'toHexString' in value && + typeof value.toHexString === 'function' + ); +} diff --git a/apps/api/src/modules/global/database/migrations/repair-double-elimination-series-rules.spec.ts b/apps/api/src/modules/global/database/migrations/repair-double-elimination-series-rules.spec.ts new file mode 100644 index 00000000..c9111b13 --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/repair-double-elimination-series-rules.spec.ts @@ -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 { + 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 { + 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, + }, + ]); + }); +}); diff --git a/apps/api/src/modules/global/database/migrations/repair-double-elimination-series-rules.ts b/apps/api/src/modules/global/database/migrations/repair-double-elimination-series-rules.ts new file mode 100644 index 00000000..15f163b9 --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/repair-double-elimination-series-rules.ts @@ -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 --dry-run + pnpm --filter api exec ts-node src/modules/global/database/migrations/repair-double-elimination-series-rules.ts --match-id --env prod --apply + +Options: + --match-id Optional match ObjectId. If omitted, scans all double-elimination matches. + --winner-game-count 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 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 { + const updateByCodeId = new Map( + codeUpdates.map((update) => [update.codeId.toString(), update]), + ); + const activeSlotKeys = new Set(); + + 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, + 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); + }); +} diff --git a/apps/api/src/modules/global/database/migrations/repair-limited-round-robin-finished-match.ts b/apps/api/src/modules/global/database/migrations/repair-limited-round-robin-finished-match.ts new file mode 100644 index 00000000..24108c05 --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/repair-limited-round-robin-finished-match.ts @@ -0,0 +1,680 @@ +import 'reflect-metadata'; +import { Module } from '@nestjs/common'; +import { ConfigModule } from '@nestjs/config'; +import { NestFactory } from '@nestjs/core'; +import mongoose from 'mongoose'; +import { readFile } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import { + ConnectionService, + resolveMongoDbName, +} from '../connection.service'; +import type { + MatchDocument, + MatchGameAssignment, + MatchGameResult, + MatchSeriesResult, + TournamentCodeDocument, +} from '../schema'; +import { SecretModule } from '../../secret/secret.module'; +import { MatchStatsFragmentBuilder } from '../../../community-stats/match-stats-fragment.builder'; +import { MatchStatsRepository } from '../../../community-stats/match-stats.repository'; +import { MatchStatsService } from '../../../community-stats/match-stats.service'; + +interface CliOptions { + dryRun: boolean; + matchId: mongoose.Types.ObjectId; + maxRounds: number; + nodeEnv: string; +} + +interface ResultGamePlan { + oldGameNumber: number; + newGameNumber: number; + roundNumber: number; + teamAIndex: number; + teamBIndex: number; + game: MatchGameResult; +} + +interface RepairPlan { + schedule: MatchGameAssignment[]; + gamePlans: ResultGamePlan[]; + seriesResults: MatchSeriesResult[]; + winnerTeamIndex?: number; + usedCodeByOldGameNumber: Map; + releasedCodes: TournamentCodeDocument[]; +} + +@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, + MatchStatsFragmentBuilder, + MatchStatsRepository, + MatchStatsService, + ], +}) +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 { + // 로컬 machine env 파일이 없으면 그냥 지나간다. + } +} + +function parseArgs(argv: string[]): CliOptions { + let dryRun = true; + let matchId: mongoose.Types.ObjectId | undefined; + let maxRounds = 3; + let nodeEnv = process.env.NODE_ENV ?? 'dev'; + + for (let index = 0; index < argv.length; index += 1) { + const arg = argv[index]; + if (arg === '--apply') { + dryRun = false; + continue; + } + if (arg === '--dry-run') { + dryRun = true; + continue; + } + if (arg === '--match-id') { + const value = argv[index + 1]; + if (!value || !mongoose.isValidObjectId(value)) { + throw new Error('--match-id requires a valid ObjectId.'); + } + matchId = new mongoose.Types.ObjectId(value); + index += 1; + continue; + } + if (arg.startsWith('--match-id=')) { + const value = arg.slice('--match-id='.length); + if (!mongoose.isValidObjectId(value)) { + throw new Error('--match-id requires a valid ObjectId.'); + } + matchId = new mongoose.Types.ObjectId(value); + continue; + } + if (arg === '--max-rounds') { + maxRounds = parsePositiveInteger(argv[index + 1], '--max-rounds'); + index += 1; + continue; + } + if (arg.startsWith('--max-rounds=')) { + maxRounds = parsePositiveInteger( + arg.slice('--max-rounds='.length), + '--max-rounds', + ); + 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 === '--help' || arg === '-h') { + printHelp(); + process.exit(0); + } + throw new Error(`Unknown argument: ${arg}`); + } + + if (!matchId) throw new Error('--match-id is required.'); + if (!['dev', 'staging', 'prod'].includes(nodeEnv)) { + throw new Error('--env must be dev, staging, or prod.'); + } + + return { dryRun, matchId, maxRounds, nodeEnv }; +} + +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/repair-limited-round-robin-finished-match.ts --match-id --max-rounds 3 --dry-run + pnpm --filter api exec ts-node src/modules/global/database/migrations/repair-limited-round-robin-finished-match.ts --match-id --max-rounds 3 --env prod --apply + +Options: + --match-id Match ObjectId to repair. + --max-rounds Number of round-robin rounds to keep. Default: 3. + --dry-run Print the repair plan without writing. Default. + --apply Apply match, tournament code, and stats updates. + --env dev | staging | prod. Default: NODE_ENV or dev. +`); +} + +async function main() { + const options = parseArgs(process.argv.slice(2)); + process.env.NODE_ENV = options.nodeEnv; + await loadMachineEnvFile(); + + const app = await NestFactory.createApplicationContext(RepairModule, { + logger: ['log', 'warn', 'error'], + }); + + try { + const connectionService = app.get(ConnectionService); + const matchStatsService = app.get(MatchStatsService); + const MatchModel = await connectionService.getModel('match'); + const TournamentCodeModel = + await connectionService.getModel('tournamentCode'); + const match = await MatchModel.findById(options.matchId).exec(); + if (!match) { + throw new Error(`Match not found: ${options.matchId.toString()}`); + } + + const codes = await TournamentCodeModel.find({ + _id: { $in: match.tournamentCodeIds ?? [] }, + }) + .sort({ gameNumber: 1, reservedAt: 1, _id: 1 }) + .exec(); + const plan = buildRepairPlan(match, codes, options.maxRounds); + + printPlan(options, match, codes, plan); + + if (options.dryRun) { + console.log('No writes were made. Re-run with --apply to update MongoDB.'); + return; + } + + const now = new Date(); + const session = await (await connectionService.getConnection()).startSession(); + try { + await session.withTransaction(async () => { + await applyTournamentCodeUpdates(plan, now, session); + await MatchModel.updateOne( + { _id: match._id }, + { + $set: { + status: 'finished', + roundRobinMaxRounds: options.maxRounds, + gameSchedule: plan.schedule, + tournamentCodeIds: [ + ...plan.usedCodeByOldGameNumber.values(), + ].map((code) => code._id), + resultPollState: { + startedAt: match.resultPollState?.startedAt ?? now, + lastPolledAt: now, + lastPollOutcome: 'matched', + matchedCount: plan.gamePlans.length, + expandedToAllPuuids: true, + state: 'complete', + }, + result: { + winnerTeamIndex: plan.winnerTeamIndex, + mvpUserId: match.result?.mvpUserId, + riotMatchIds: plan.gamePlans.map( + (gamePlan) => gamePlan.game.riotMatchId, + ), + games: plan.gamePlans.map((gamePlan) => ({ + ...toPlainGame(gamePlan.game), + gameNumber: gamePlan.newGameNumber, + })), + seriesResults: plan.seriesResults, + }, + }, + }, + { session }, + ).exec(); + }); + } finally { + await session.endSession(); + } + + await matchStatsService.buildAndUpsert(match._id); + console.log('Repair applied and match stats rebuilt.'); + } finally { + await app.close(); + await mongoose.disconnect(); + } +} + +function buildRepairPlan( + match: MatchDocument, + codes: TournamentCodeDocument[], + maxRounds: number, +): RepairPlan { + if (match.gameMode !== 'round-robin') { + throw new Error(`Expected round-robin match, got ${match.gameMode}.`); + } + + const games = [...(match.result?.games ?? [])] + .map(toPlainGame) + .sort((left, right) => left.gameNumber - right.gameNumber); + if (games.length === 0) { + throw new Error('Match has no result games to preserve.'); + } + + const teamIndexes = [...new Set(match.teams.map((team) => team.teamIndex))] + .filter((teamIndex) => Number.isInteger(teamIndex) && teamIndex > 0) + .sort((left, right) => left - right); + if (teamIndexes.length < 2) { + throw new Error('Match needs at least two teams.'); + } + if (teamIndexes.length % 2 !== 0) { + throw new Error('This repair script currently expects an even team count.'); + } + + const gamesPerRound = teamIndexes.length / 2; + const requiredGames = gamesPerRound * maxRounds; + if (games.length !== requiredGames) { + throw new Error( + `Expected ${requiredGames} result games for ${maxRounds} rounds and ${teamIndexes.length} teams, got ${games.length}.`, + ); + } + + validateResultGames(games, teamIndexes); + const rounds = partitionIntoRounds(games, teamIndexes, maxRounds); + const gamePlans = rounds.flatMap((roundGames, roundIndex) => + sortRoundGames(roundGames).map((game, gameIndex) => ({ + oldGameNumber: game.gameNumber, + newGameNumber: roundIndex * gamesPerRound + gameIndex + 1, + roundNumber: roundIndex + 1, + teamAIndex: Math.min(game.blueTeamIndex, game.redTeamIndex), + teamBIndex: Math.max(game.blueTeamIndex, game.redTeamIndex), + game, + })), + ); + + const schedule = gamePlans.map( + ({ newGameNumber, roundNumber, teamAIndex, teamBIndex }) => ({ + gameNumber: newGameNumber, + roundNumber, + teamAIndex, + teamBIndex, + }), + ); + + const usedOldGameNumbers = new Set( + gamePlans.map((gamePlan) => gamePlan.oldGameNumber), + ); + const usedCodeByOldGameNumber = resolveUsedCodesByOldGameNumber( + codes, + gamePlans, + ); + const releasedCodes = codes.filter( + (code) => !usedOldGameNumbers.has(code.gameNumber ?? 0), + ); + const unsafeReleased = releasedCodes.filter((code) => code.state === 'used'); + if (unsafeReleased.length > 0) { + throw new Error( + `Refusing to release used tournament codes without matching result games: ${unsafeReleased + .map((code) => formatCode(code)) + .join(', ')}`, + ); + } + + const updatedGames = gamePlans.map((gamePlan) => ({ + ...toPlainGame(gamePlan.game), + gameNumber: gamePlan.newGameNumber, + })); + const seriesResults = buildSeriesResults(updatedGames); + + return { + schedule, + gamePlans, + seriesResults, + winnerTeamIndex: resolveMatchWinnerTeamIndex(seriesResults), + usedCodeByOldGameNumber, + releasedCodes, + }; +} + +function validateResultGames(games: MatchGameResult[], teamIndexes: number[]) { + const validTeamIndexes = new Set(teamIndexes); + const pairKeys = new Set(); + const gameNumbers = new Set(); + + for (const game of games) { + if (gameNumbers.has(game.gameNumber)) { + throw new Error(`Duplicate result gameNumber: ${game.gameNumber}.`); + } + gameNumbers.add(game.gameNumber); + + if (!validTeamIndexes.has(game.blueTeamIndex)) { + throw new Error(`Invalid blueTeamIndex ${game.blueTeamIndex}.`); + } + if (!validTeamIndexes.has(game.redTeamIndex)) { + throw new Error(`Invalid redTeamIndex ${game.redTeamIndex}.`); + } + if (game.blueTeamIndex === game.redTeamIndex) { + throw new Error(`Game ${game.gameNumber} has the same team twice.`); + } + + const key = pairKey(game); + if (pairKeys.has(key)) { + throw new Error(`Duplicate team pair in results: ${key}.`); + } + pairKeys.add(key); + } +} + +function partitionIntoRounds( + games: MatchGameResult[], + teamIndexes: number[], + maxRounds: number, +): MatchGameResult[][] { + const targetPerRound = teamIndexes.length / 2; + const unused = new Set(games.map((game) => game.gameNumber)); + const byGameNumber = new Map(games.map((game) => [game.gameNumber, game])); + const rounds: MatchGameResult[][] = []; + + function fillRound(roundIndex: number): boolean { + if (roundIndex === maxRounds) return unused.size === 0; + + const candidates = enumerateRoundCandidates( + [...unused] + .map((gameNumber) => byGameNumber.get(gameNumber)) + .filter((game): game is MatchGameResult => Boolean(game)), + teamIndexes, + targetPerRound, + ); + + for (const candidate of candidates) { + for (const game of candidate) unused.delete(game.gameNumber); + rounds[roundIndex] = candidate; + if (fillRound(roundIndex + 1)) return true; + for (const game of candidate) unused.add(game.gameNumber); + } + + rounds.length = roundIndex; + return false; + } + + if (!fillRound(0)) { + throw new Error('Could not partition result games into simultaneous rounds.'); + } + + return rounds; +} + +function enumerateRoundCandidates( + availableGames: MatchGameResult[], + teamIndexes: number[], + targetPerRound: number, +): MatchGameResult[][] { + const candidates: MatchGameResult[][] = []; + + function visit(usedTeams: Set, chosen: MatchGameResult[]) { + if (chosen.length === targetPerRound) { + candidates.push([...chosen]); + return; + } + + const nextTeam = teamIndexes.find((teamIndex) => !usedTeams.has(teamIndex)); + if (!nextTeam) return; + + const nextGames = availableGames + .filter((game) => { + if (!includesTeam(game, nextTeam)) return false; + return ( + !usedTeams.has(game.blueTeamIndex) && + !usedTeams.has(game.redTeamIndex) + ); + }) + .sort((left, right) => left.gameNumber - right.gameNumber); + + for (const game of nextGames) { + chosen.push(game); + usedTeams.add(game.blueTeamIndex); + usedTeams.add(game.redTeamIndex); + visit(usedTeams, chosen); + usedTeams.delete(game.blueTeamIndex); + usedTeams.delete(game.redTeamIndex); + chosen.pop(); + } + } + + visit(new Set(), []); + return candidates; +} + +function sortRoundGames(games: MatchGameResult[]) { + return [...games].sort( + (left, right) => + Math.min(left.blueTeamIndex, left.redTeamIndex) - + Math.min(right.blueTeamIndex, right.redTeamIndex) || + Math.max(left.blueTeamIndex, left.redTeamIndex) - + Math.max(right.blueTeamIndex, right.redTeamIndex), + ); +} + +function resolveUsedCodesByOldGameNumber( + codes: TournamentCodeDocument[], + gamePlans: ResultGamePlan[], +): Map { + const byGameNumber = new Map(); + for (const code of codes) { + if (!code.gameNumber) continue; + const existing = byGameNumber.get(code.gameNumber) ?? []; + existing.push(code); + byGameNumber.set(code.gameNumber, existing); + } + + const result = new Map(); + for (const gamePlan of gamePlans) { + const candidates = byGameNumber.get(gamePlan.oldGameNumber) ?? []; + if (candidates.length !== 1) { + throw new Error( + `Expected exactly one tournament code for old game ${gamePlan.oldGameNumber}, got ${candidates.length}.`, + ); + } + const [code] = candidates; + if (code.riotMatchId && code.riotMatchId !== gamePlan.game.riotMatchId) { + throw new Error( + `Tournament code ${formatCode(code)} has riotMatchId ${code.riotMatchId}, expected ${gamePlan.game.riotMatchId}.`, + ); + } + result.set(gamePlan.oldGameNumber, code); + } + + return result; +} + +async function applyTournamentCodeUpdates( + plan: RepairPlan, + now: Date, + session: mongoose.ClientSession, +) { + const usedOperations = plan.gamePlans.map((gamePlan) => { + const code = plan.usedCodeByOldGameNumber.get(gamePlan.oldGameNumber); + if (!code) { + throw new Error(`Missing tournament code for ${gamePlan.oldGameNumber}.`); + } + return code.updateOne( + { + $set: { + state: 'used', + gameNumber: gamePlan.newGameNumber, + riotMatchId: gamePlan.game.riotMatchId, + usedAt: resolveGameEndedAt(gamePlan.game), + }, + $unset: { + releasedAt: '', + }, + }, + { session }, + ); + }); + + const releasedOperations = plan.releasedCodes.map((code) => + code.updateOne( + { + $set: { + state: 'released', + releasedAt: now, + }, + $unset: { + matchId: '', + gameNumber: '', + reservedAt: '', + usedAt: '', + riotMatchId: '', + }, + }, + { session }, + ), + ); + + await Promise.all([...usedOperations, ...releasedOperations]); +} + +function buildSeriesResults(games: MatchGameResult[]): MatchSeriesResult[] { + const bySeries = new Map(); + 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()].sort( + (left, right) => + left.teamAIndex - right.teamAIndex || + left.teamBIndex - right.teamBIndex, + ); +} + +function resolveMatchWinnerTeamIndex(seriesResults: MatchSeriesResult[]) { + const winsByTeam = new Map(); + for (const series of seriesResults) { + if (!series.winnerTeamIndex) continue; + winsByTeam.set( + series.winnerTeamIndex, + (winsByTeam.get(series.winnerTeamIndex) ?? 0) + 1, + ); + } + + const sorted = [...winsByTeam.entries()].sort( + (left, right) => right[1] - left[1], + ); + if (sorted.length === 0) return undefined; + if (sorted.length > 1 && sorted[0][1] === sorted[1][1]) return undefined; + return sorted[0][0]; +} + +function printPlan( + options: CliOptions, + match: MatchDocument, + codes: TournamentCodeDocument[], + plan: RepairPlan, +) { + console.log( + `[limited round-robin repair] mode=${options.dryRun ? 'dry-run' : 'apply'} env=${options.nodeEnv} db=${resolveMongoDbName(options.nodeEnv)}`, + ); + console.log( + `[limited round-robin repair] match=${match._id.toString()} title="${match.title}"`, + ); + console.log( + `[limited round-robin repair] status ${match.status} -> finished, maxRounds=${options.maxRounds}`, + ); + console.log( + `[limited round-robin repair] resultGames=${plan.gamePlans.length} codes kept=${plan.usedCodeByOldGameNumber.size} codes released=${plan.releasedCodes.length} previousCodeIds=${codes.length}`, + ); + console.log( + `[limited round-robin repair] winnerTeamIndex=${plan.winnerTeamIndex ?? '(tie)'}`, + ); + + for (const gamePlan of plan.gamePlans) { + console.log( + ` R${gamePlan.roundNumber} G${gamePlan.newGameNumber}: ${gamePlan.teamAIndex}팀 vs ${gamePlan.teamBIndex}팀 (old G${gamePlan.oldGameNumber}, riot=${gamePlan.game.riotMatchId})`, + ); + } +} + +function toPlainGame(game: MatchGameResult): MatchGameResult { + const maybeSubdocument = game as unknown as { + toObject?: () => MatchGameResult; + }; + const objectValue = + typeof maybeSubdocument.toObject === 'function' + ? maybeSubdocument.toObject() + : game; + return { + ...objectValue, + participants: [...(objectValue.participants ?? [])], + }; +} + +function includesTeam(game: MatchGameResult, teamIndex: number) { + return game.blueTeamIndex === teamIndex || game.redTeamIndex === teamIndex; +} + +function pairKey(game: MatchGameResult) { + const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex); + const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex); + return `${teamAIndex}:${teamBIndex}`; +} + +function resolveGameEndedAt(game: MatchGameResult) { + return new Date(game.gameCreation + game.gameDuration * 1000); +} + +function formatCode(code: TournamentCodeDocument) { + return `${code._id.toString()}(gameNumber=${code.gameNumber ?? 'none'}, state=${code.state})`; +} + +void main() + .then(() => { + process.exit(0); + }) + .catch((error: unknown) => { + console.error(error instanceof Error ? error.message : error); + process.exit(1); + }); diff --git a/apps/api/src/modules/global/database/migrations/run-auction-redis-field-rename.ts b/apps/api/src/modules/global/database/migrations/run-auction-redis-field-rename.ts new file mode 100644 index 00000000..afba5e10 --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/run-auction-redis-field-rename.ts @@ -0,0 +1,363 @@ +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 { migrateAuctionRedisFieldRename } from './20260622-auction-redis-field-rename'; + +interface CliOptions { + duplicateSampleLimit: number; + dryRun: boolean; + limit?: number; + listDuplicates: boolean; + nodeEnv: string; + repairDuplicateSequences: boolean; +} + +interface DuplicateSequenceRepairStats { + affectedAuctions: number; + changedAuctionSequenceFields: number; + changedHistoryEntries: number; + scannedHistoryEntries: number; +} + +@Module({ + imports: [ + ConfigModule.forRoot({ + isGlobal: true, + envFilePath: [ + resolve(__dirname, '../../../../../../project.env'), + resolve(process.cwd(), '../project.env'), + resolve(process.cwd(), 'apps/project.env'), + resolve(process.cwd(), 'project.env'), + ], + }), + SecretModule, + ], + providers: [ConnectionService], +}) +class MigrationModule {} + +async function loadMachineEnvFile() { + const homeDir = process.env.HOME ?? process.env.USERPROFILE; + if (!homeDir) return; + + const machineEnvFile = resolve(homeDir, 'source/global-env-vars.txt'); + + try { + const file = await readFile(machineEnvFile, 'utf8'); + for (const rawLine of file.split(/\r?\n/)) { + const line = rawLine.trim(); + if (!line || line.startsWith('#')) continue; + + const matched = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/); + if (!matched) continue; + + const [, key, rawValue] = matched; + process.env[key] = rawValue.replace(/^["']|["']$/g, ''); + } + } catch { + // 로컬 machine env 파일이 없으면 그냥 지나간다. + } +} + +function parseArgs(argv: string[]): CliOptions { + let dryRun = true; + let duplicateSampleLimit = 20; + let limit: number | undefined; + let listDuplicates = false; + let nodeEnv = process.env.NODE_ENV ?? 'dev'; + let repairDuplicateSequences = false; + + 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 === '--list-duplicates') { + listDuplicates = true; + continue; + } + if (arg === '--repair-duplicate-sequences') { + repairDuplicateSequences = 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 === '--limit') { + limit = parsePositiveInteger(argv[index + 1], '--limit'); + index += 1; + continue; + } + if (arg.startsWith('--limit=')) { + limit = parsePositiveInteger(arg.slice('--limit='.length), '--limit'); + 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 { + duplicateSampleLimit, + dryRun, + limit, + listDuplicates, + nodeEnv, + repairDuplicateSequences, + }; +} + +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-auction-redis-field-rename.ts [--dry-run] + pnpm --filter api exec ts-node src/modules/global/database/migrations/run-auction-redis-field-rename.ts --env staging --apply + +Options: + --dry-run Print affected counts without writing. Default. + --apply Apply auction and auctionHistory field updates. + --env dev | staging | prod. Default: NODE_ENV or dev. + --limit Only scan first n documents per collection. + --list-duplicates + Print duplicate auctionHistory auctionId+sequence samples. + --duplicate-sample-limit + Max duplicate groups to print. Default: 20. + --repair-duplicate-sequences + Resequence affected auctionHistory rows by takenAt/createdAt/_id before migration. +`); +} + +async function findAuctionIdsWithDuplicateHistorySequences( + db: NonNullable, +): Promise { + const groups = await db + .collection('auctionHistory') + .aggregate([ + { + $group: { + _id: { auctionId: '$auctionId', sequence: '$sequence' }, + count: { $sum: 1 }, + }, + }, + { $match: { count: { $gt: 1 } } }, + { $group: { _id: '$_id.auctionId' } }, + ]) + .toArray(); + + return groups.map((group) => group._id).filter(Boolean); +} + +async function listDuplicateHistorySequences( + db: NonNullable, + sampleLimit: number, +) { + return db + .collection('auctionHistory') + .aggregate([ + { + $group: { + _id: { auctionId: '$auctionId', sequence: '$sequence' }, + actions: { $push: '$action' }, + count: { $sum: 1 }, + createdAtValues: { $push: '$createdAt' }, + historyIds: { $push: '$_id' }, + matchIds: { $addToSet: '$matchId' }, + takenAtValues: { $push: '$takenAt' }, + }, + }, + { $match: { count: { $gt: 1 } } }, + { $sort: { count: -1, '_id.sequence': 1 } }, + { $limit: sampleLimit }, + ]) + .toArray(); +} + +function printDuplicateHistorySequences(groups: Awaited< + ReturnType +>) { + if (groups.length === 0) { + console.log('No duplicate auctionHistory auctionId+sequence groups found.'); + return; + } + + console.log('Duplicate auctionHistory auctionId+sequence groups:'); + console.table( + groups.map((group) => ({ + actions: (group.actions as unknown[]).map(String).join(', '), + auctionId: String(group._id?.auctionId ?? ''), + count: group.count, + createdAt: (group.createdAtValues as unknown[]).map(String).join(', '), + historyIds: (group.historyIds as unknown[]).map(String).join(', '), + matchIds: (group.matchIds as unknown[]).map(String).join(', '), + sequence: group._id?.sequence, + takenAt: (group.takenAtValues as unknown[]).map(String).join(', '), + })), + ); +} + +async function repairDuplicateHistorySequences( + db: NonNullable, + dryRun: boolean, +): Promise { + const historyCollection = db.collection('auctionHistory'); + const auctionCollection = db.collection('auction'); + const affectedAuctionIds = await findAuctionIdsWithDuplicateHistorySequences(db); + const stats: DuplicateSequenceRepairStats = { + affectedAuctions: affectedAuctionIds.length, + changedAuctionSequenceFields: 0, + changedHistoryEntries: 0, + scannedHistoryEntries: 0, + }; + + for (const auctionId of affectedAuctionIds) { + const histories = await historyCollection + .find({ auctionId }) + .project({ _id: 1, createdAt: 1, sequence: 1, takenAt: 1 }) + .sort({ takenAt: 1, createdAt: 1, _id: 1 }) + .toArray(); + stats.scannedHistoryEntries += histories.length; + + const writes = histories + .map((history, index) => ({ + history, + nextSequence: index + 1, + })) + .filter(({ history, nextSequence }) => history.sequence !== nextSequence); + + stats.changedHistoryEntries += writes.length; + stats.changedAuctionSequenceFields += 1; + + if (dryRun) continue; + if (writes.length > 0) { + await historyCollection.bulkWrite( + writes.map(({ history, nextSequence }) => ({ + updateOne: { + filter: { _id: history._id }, + update: { $set: { sequence: nextSequence } }, + }, + })), + { ordered: true }, + ); + } + await auctionCollection.updateOne( + { _id: auctionId } as Record, + { $set: { currentAuctionHistorySequence: histories.length } }, + ); + } + + return stats; +} + +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( + `[auction redis field rename migration] mode=${ + options.dryRun ? 'dry-run' : 'apply' + } env=${options.nodeEnv} db=${dbName}`, + ); + + if (options.repairDuplicateSequences) { + const repairStats = await repairDuplicateHistorySequences( + connection.db, + options.dryRun, + ); + console.log('Duplicate auctionHistory sequence repair:'); + console.table(repairStats); + } + + const stats = await migrateAuctionRedisFieldRename( + connection.db as Parameters[0], + { + dryRun: options.dryRun, + limit: options.limit, + }, + ); + + console.table(stats); + if (options.listDuplicates && stats.duplicateHistorySequences > 0) { + const duplicateGroups = await listDuplicateHistorySequences( + connection.db, + options.duplicateSampleLimit, + ); + printDuplicateHistorySequences(duplicateGroups); + } + if (options.dryRun) { + console.log( + 'No writes were made. Re-run with --apply to update documents.', + ); + } else { + console.log('Migration applied.'); + } + } finally { + await app.close(); + await mongoose.disconnect(); + } +} + +void main().catch((error: unknown) => { + console.error(error instanceof Error ? error.message : error); + process.exitCode = 1; +}); diff --git a/apps/api/src/modules/global/database/migrations/run-competition-domain.spec.ts b/apps/api/src/modules/global/database/migrations/run-competition-domain.spec.ts new file mode 100644 index 00000000..ed69f1aa --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/run-competition-domain.spec.ts @@ -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.', + ); + }); +}); diff --git a/apps/api/src/modules/global/database/migrations/run-competition-domain.ts b/apps/api/src/modules/global/database/migrations/run-competition-domain.ts new file mode 100644 index 00000000..9c9d954f --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/run-competition-domain.ts @@ -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 { + 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 dev | staging | prod. Default: NODE_ENV or dev. + --limit Scan at most n Matches. Apply resumes from a durable checkpoint. + --after 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 { + 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; + }); +} diff --git a/apps/api/src/modules/global/database/migrations/run-tournament-code-unique-indexes.ts b/apps/api/src/modules/global/database/migrations/run-tournament-code-unique-indexes.ts new file mode 100644 index 00000000..48754a6d --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/run-tournament-code-unique-indexes.ts @@ -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 dev | staging | prod. Default: NODE_ENV or dev. + --list-duplicates + Print duplicate tournamentCode group samples. + --duplicate-sample-limit + Max duplicate groups to print. Default: 20. + --index-commit-quorum + Override MongoDB index build commitQuorum. Use 1 only after checking replica health. + --index-max-time-ms + 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[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; +}); diff --git a/apps/api/src/modules/global/database/schema.ts b/apps/api/src/modules/global/database/schema.ts index e7a0807b..f42da202 100644 --- a/apps/api/src/modules/global/database/schema.ts +++ b/apps/api/src/modules/global/database/schema.ts @@ -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']; @@ -153,14 +168,42 @@ export const AUCTION_TOP_TIER_THRESHOLDS = [ ] as const; export type AuctionTopTierThreshold = (typeof AUCTION_TOP_TIER_THRESHOLDS)[number]; -export type AuctionActionType = - | 'start' - | 'open-bidding' - | 'bid' - | 'sold' - | 'passed' - | 'next' - | 'complete'; +export const AUCTION_ACTION_TYPES = [ + 'start', + 'open-bidding', + 'bid', + 'sold', + 'passed', + 'next', + 'complete', + 'reset', + 'undo', +] as const; +export type AuctionActionType = (typeof AUCTION_ACTION_TYPES)[number]; +export const AUCTION_ENGINE_VERSIONS = ['redis-v1', 'legacy-renamed'] as const; +export type AuctionEngineVersion = (typeof AUCTION_ENGINE_VERSIONS)[number]; +export const AUCTION_MATCH_SIDE_EFFECT_STATUSES = [ + 'none', + 'pending', + 'processing', + 'completed', + 'failed', +] as const; +export type AuctionMatchSideEffectStatus = + (typeof AUCTION_MATCH_SIDE_EFFECT_STATUSES)[number]; +export const AUCTION_SIDE_EFFECT_APPLICATION_STATES = [ + 'pending', + 'processing', + 'completed', + 'failed', +] as const; +export type AuctionSideEffectApplicationState = + (typeof AUCTION_SIDE_EFFECT_APPLICATION_STATES)[number]; + +export type AuctionHistoryMutation = + | { type: 'append' } + | { targetHistorySequence: number; type: 'deleteAfterSequenceAndAppendUndo' } + | { resetMode: 'clear-history' | 'preserve-audit'; type: 'reset' }; export interface MongooseTimestamps { createdAt: Date; @@ -357,6 +400,8 @@ export interface DakaoOutboxMessage extends MongooseTimestamps { payload: Record; state: DakaoOutboxMessageState; publishAttempts: number; + publishLeaseOwnerIdentifier?: string; + publishLeaseExpiresAt?: Date; publishedAt?: Date; terminalAt?: Date; resultEventId?: string; @@ -398,6 +443,8 @@ export interface RiotMatch extends MongooseTimestamps { queueId?: number; participantPuuids: string[]; raw: Record; // Riot API Match-V5 원본 응답 전체 + timeline?: Record; // Riot API Match-V5 timeline 원본 응답 전체 + timelineFetchedAt?: Date; fetchedAt: Date; } @@ -415,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; @@ -467,6 +516,7 @@ export interface MatchGameResultParticipant { export interface MatchGameResult { gameNumber: number; + bracketMatchId?: string; riotMatchId: string; blueTeamIndex: number; redTeamIndex: number; @@ -478,6 +528,7 @@ export interface MatchGameResult { } export interface MatchSeriesResult { + bracketMatchId?: string; teamAIndex: number; teamBIndex: number; teamAWins: number; @@ -485,8 +536,123 @@ 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; teamAIndex: number; teamBIndex: number; } @@ -515,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; @@ -524,6 +691,7 @@ export interface Match extends MongooseTimestamps { maxParticipants: number; gameCount: number; gameMode: MatchGameMode; + roundRobinMaxRounds?: number; tournamentCodeIds: mongoose.Types.ObjectId[]; gameSchedule: MatchGameAssignment[]; teamBuiltAt?: Date; @@ -532,6 +700,7 @@ export interface Match extends MongooseTimestamps { teams: MatchTeam[]; result?: MatchResult; resultPollState?: MatchResultPollState; + doubleElimination?: DoubleEliminationBracket; legacyImported?: boolean; legacyImportSource?: { importedAt: Date; @@ -578,6 +747,7 @@ export interface LegacyImportJob extends MongooseTimestamps { totalSkippedDuplicate: number; totalErrors: number; averageMemberSeconds?: number; + completedMemberJobIds: string[]; errors?: LegacyImportJobError[]; } @@ -612,6 +782,20 @@ export interface AuctionTeam { members: AuctionTeamMember[]; } +export interface RedisAuctionTeamMember { + userId: mongoose.Types.ObjectId; + assignedPosition: Position; + memberAcquisitionBidPointAmount: number; +} + +export interface RedisAuctionTeam { + teamIndex: number; + name?: string; + captainUserId: mongoose.Types.ObjectId; + remainingBidPointAmount: number; + members: RedisAuctionTeamMember[]; +} + export interface AuctionBid { teamIndex: number; amount: number; @@ -619,6 +803,13 @@ export interface AuctionBid { timestamp: Date; } +export interface AuctionBidHistoryEntry { + bidderTeamIndex: number; + bidPointAmount: number; + bidderUserId: mongoose.Types.ObjectId; + bidPlacedAtTimestampMS: number; +} + export interface AuctionChatMessage { id: string; userId?: mongoose.Types.ObjectId; @@ -630,6 +821,17 @@ export interface AuctionChatMessage { export interface Auction extends MongooseTimestamps { matchId: mongoose.Types.ObjectId; phase: AuctionPhase; + revision: number; + auctionEngineVersion?: AuctionEngineVersion; + auctionLifecycleId?: string; + lastAppliedAuctionStateTransitionId?: string; + currentAuctionHistorySequence: number; + startAuctionRequestId?: string; + startAuctionStateTransitionId?: string; + auctionStartedByUserId?: mongoose.Types.ObjectId; + matchSideEffectStatus: AuctionMatchSideEffectStatus; + matchSideEffectRevision: number; + matchSideEffectError?: string; teams: AuctionTeam[]; order: AuctionPlayerSnapshot[]; passedQueue: AuctionPlayerSnapshot[]; @@ -647,6 +849,22 @@ export interface Auction extends MongooseTimestamps { chatMessages: AuctionChatMessage[]; startedAt?: Date; completedAt?: Date; + auctionTeams?: RedisAuctionTeam[]; + auctionPlayerOrder?: AuctionPlayerSnapshot[]; + passedAuctionPlayerQueue?: AuctionPlayerSnapshot[]; + currentAuctionRound?: number; + currentAuctionPlayerOrderIndex?: number; + auctionBidHistory?: AuctionBidHistoryEntry[]; + currentHighestBidPointAmount?: number; + currentHighestBidderTeamIndex?: number; + currentBidRoundDeadlineTimestampMS?: number; + maximumBidRoundDurationSeconds?: number; + bidRoundExtensionSeconds?: number; + initialTeamBidPointAmount?: number; + topTierAuctionPriorityThreshold?: AuctionTopTierThreshold; + manualTopTierAuctionPriorityUserIds?: mongoose.Types.ObjectId[]; + auctionStartedAtTimestampMS?: number; + auctionCompletedAtTimestampMS?: number; } export type AuctionDocument = HydratedDocument; @@ -656,14 +874,87 @@ export interface AuctionHistoryEntry extends MongooseTimestamps { matchId: mongoose.Types.ObjectId; sequence: number; action: AuctionActionType; + auctionStateTransitionId?: string; + auctionLifecycleId?: string; + revision?: number; actorUserId?: mongoose.Types.ObjectId; snapshotBefore: Record; + historyMutation?: AuctionHistoryMutation; + matchSideEffectMutation?: Record; takenAt: Date; } export type AuctionHistoryEntryDocument = HydratedDocument; +export interface AuctionSideEffectApplication extends MongooseTimestamps { + auctionId: mongoose.Types.ObjectId; + matchId: mongoose.Types.ObjectId; + auctionStateTransitionId: string; + auctionLifecycleId: string; + sideEffectType: string; + state: AuctionSideEffectApplicationState; + payload: Record; + payloadChecksum: string; + attempts: number; + processingStartedAtTimestampMS?: number; + processingLeaseExpiresAtTimestampMS?: number; + processingOwnerToken?: string; + completedAtTimestampMS?: number; + lastError?: string; +} + +export type AuctionSideEffectApplicationDocument = + HydratedDocument; + // ===== MatchStats (precomputed internal stats fragment) ===== +export interface MatchStatsRuneStyleSelection { + styleId: number; + perkIds: number[]; +} + +export interface MatchStatsRunePerks { + primaryStyle?: number; + subStyle?: number; + keystone?: number; + selectedPerkIds?: number[]; + styles?: MatchStatsRuneStyleSelection[]; + statPerks?: { + offense?: number; + flex?: number; + defense?: number; + }; +} + +export interface MatchStatsItemBuildEvent { + timestamp: number; + itemId: number; + type: 'purchased' | 'sold' | 'destroyed' | 'undo'; + beforeId?: number; + afterId?: number; +} + +export interface MatchStatsSkillBuildEvent { + timestamp: number; + skillSlot: 1 | 2 | 3 | 4; + level: number; + levelUpType?: string; +} + +export interface MatchStatsCheckpoint { + timestamp: number; + gold: number; + cs: number; + xp: number; + kills: number; + deaths: number; + assists: number; +} + +export interface MatchStatsParticipantCheckpoints { + at10?: MatchStatsCheckpoint; + at15?: MatchStatsCheckpoint; +} + export interface MatchStatsRecord { matchId: string; title: string; @@ -672,8 +963,11 @@ export interface MatchStatsRecord { riotMatchId: string; gameCreation: number; gameDuration: number; + participantId?: number; + checkpoints?: MatchStatsParticipantCheckpoints; userId: string; summonerName: string; + tagLine: string; profileIconId: number; teamIndex: number; side: TeamSide; @@ -696,10 +990,14 @@ export interface MatchStatsRecord { controlWardsBought: number; wardsPlaced: number; wardsKilled: number; + firstBloodKill: boolean; + firstBloodAssist: boolean; items: number[]; trinket: number; summonerSpells: [number, number]; - perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + perks: MatchStatsRunePerks; + itemBuild: MatchStatsItemBuildEvent[]; + skillBuild: MatchStatsSkillBuildEvent[]; rating: number; } @@ -708,18 +1006,74 @@ export interface MatchStatsGameDetail { riotMatchId: string; gameCreation: number; gameDuration: number; + gameVersion?: string; winnerSide: TeamSide; + timeline: MatchStatsTimelinePoint[]; + timelineLoaded?: boolean; + objectiveEvents: MatchStatsObjectiveEvent[]; + timelineEvents?: MatchStatsTimelineEvent[]; teams: Array<{ teamIndex: number; side: TeamSide; win: boolean; - objectives: { baron: number; dragon: number; tower: number }; + objectives: MatchStatsObjectiveSummary; + bans: Array<{ championId: number; pickTurn: number }>; participants: MatchStatsRecord[]; }>; } +export interface MatchStatsObjectiveSummary { + tower: number; + dragon: number; + inhibitor: number; + baron: number; + riftHerald: number; + voidGrub: number; + elderDragon: number; +} + +export interface MatchStatsObjectiveEvent { + timestamp: number; + side: TeamSide; + type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub'; + monsterSubType?: string; +} + +export interface MatchStatsChampionKillEvent { + timestamp: number; + side?: TeamSide; + type: 'championKill'; + killerParticipantId?: number; + victimParticipantId?: number; + assistingParticipantIds?: number[]; +} + +export interface MatchStatsBuildingEvent { + timestamp: number; + side: TeamSide; + type: 'tower' | 'inhibitor'; + killerParticipantId?: number; + towerType?: string; +} + +export type MatchStatsTimelineEvent = + | MatchStatsObjectiveEvent + | MatchStatsChampionKillEvent + | MatchStatsBuildingEvent; + +export interface MatchStatsTimelinePoint { + timestamp: number; + blue: { gold: number; xp: number }; + red: { gold: number; xp: number }; + goldDiff: number; + xpDiff: number; +} + 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; @@ -986,6 +1340,8 @@ export const DakaoOutboxMessageSchema = new Schema( default: 'pending', }, publishAttempts: { type: Number, required: true, default: 0 }, + publishLeaseOwnerIdentifier: { type: String }, + publishLeaseExpiresAt: { type: Date }, publishedAt: { type: Date }, terminalAt: { type: Date }, resultEventId: { type: String }, @@ -1006,6 +1362,11 @@ export const DakaoOutboxMessageSchema = new Schema( ); 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( @@ -1133,6 +1494,8 @@ export const RiotMatchSchema = new Schema( queueId: { type: Number }, participantPuuids: { type: [String], required: true, default: [] }, raw: { type: Schema.Types.Mixed, required: true, default: () => ({}) }, + timeline: { type: Schema.Types.Mixed }, + timelineFetchedAt: { type: Date }, fetchedAt: { type: Date, required: true, default: Date.now }, }, { @@ -1151,7 +1514,6 @@ export const TournamentCodeSchema = new Schema( type: String, required: true, trim: true, - uppercase: true, }, region: { type: String, required: true, default: 'kr' }, mapType: { @@ -1177,9 +1539,11 @@ export const TournamentCodeSchema = new Schema( }, 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 }, @@ -1194,9 +1558,35 @@ export const TournamentCodeSchema = new Schema( 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( { @@ -1254,6 +1644,7 @@ const MatchGameResultParticipantSubSchema = const MatchGameResultSubSchema = new Schema( { 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 }, @@ -1272,6 +1663,7 @@ const MatchGameResultSubSchema = new Schema( const MatchSeriesResultSubSchema = new Schema( { + 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 }, @@ -1284,12 +1676,166 @@ const MatchSeriesResultSubSchema = new Schema( const MatchGameAssignmentSubSchema = new Schema( { gameNumber: { type: Number, required: true, min: 1 }, + roundNumber: { type: Number, required: false, min: 1 }, teamAIndex: { type: Number, required: true, min: 1 }, teamBIndex: { type: Number, required: true, min: 1 }, }, { _id: false }, ); +const DoubleEliminationSeedSubSchema = new Schema( + { + seedNumber: { type: Number, required: true, min: 1 }, + teamIndex: { type: Number, required: true, min: 1 }, + }, + { _id: false }, +); + +const DoubleEliminationBracketMatchSourceSubSchema = + new Schema( + { + 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( + { + bracketMatchId: { type: String, required: true }, + position: { type: String, enum: ['A', 'B'], required: true }, + }, + { _id: false }, + ); + +const DoubleEliminationWalkoverSubSchema = + new Schema( + { + 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( + { + 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( + { + 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( + { + 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( + { + 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( { winnerTeamIndex: { type: Number, required: false, min: 1 }, @@ -1353,6 +1899,11 @@ export const MatchSchema = new Schema( ref: 'community', required: true, }, + competitionId: { + type: Schema.Types.ObjectId, + ref: 'competition', + required: false, + }, shortCode: { type: String, required: false, @@ -1389,6 +1940,7 @@ export const MatchSchema = new Schema( required: true, default: 'pair', }, + roundRobinMaxRounds: { type: Number, required: false, min: 1 }, tournamentCodeIds: { type: [{ type: Schema.Types.ObjectId, ref: 'tournamentCode' }], required: true, @@ -1419,6 +1971,10 @@ export const MatchSchema = new Schema( type: MatchResultPollStateSubSchema, required: false, }, + doubleElimination: { + type: DoubleEliminationBracketSubSchema, + required: false, + }, legacyImported: { type: Boolean, required: false, default: false }, legacyImportSource: { type: MatchLegacyImportSourceSubSchema, @@ -1439,6 +1995,7 @@ export const MatchSchema = new Schema( ); MatchSchema.index({ communityId: 1, scheduledAt: -1 }); +applyCompetitionDomainInvariantIndexes(MatchSchema, 'match'); MatchSchema.index({ communityId: 1, status: 1, scheduledAt: -1 }); MatchSchema.index( { communityId: 1, shortCode: 1 }, @@ -1503,6 +2060,11 @@ export const LegacyImportJobSchema = new Schema( 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, @@ -1518,6 +2080,7 @@ export const LegacyImportJobSchema = new Schema( LegacyImportJobSchema.index({ communityId: 1, startedAt: -1 }); LegacyImportJobSchema.index({ communityId: 1, state: 1 }); +LegacyImportJobSchema.index({ jobId: 1, completedMemberJobIds: 1 }); const AuctionPlayerSnapshotSubSchema = new Schema( { @@ -1571,6 +2134,34 @@ const AuctionTeamSubSchema = new Schema( { _id: false }, ); +const RedisAuctionTeamMemberSubSchema = new Schema( + { + userId: { type: Schema.Types.ObjectId, ref: 'user', required: true }, + assignedPosition: { type: String, enum: POSITIONS, required: true }, + memberAcquisitionBidPointAmount: { + type: Number, + required: true, + default: 0, + }, + }, + { _id: false }, +); + +const RedisAuctionTeamSubSchema = new Schema( + { + teamIndex: { type: Number, required: true, min: 1 }, + name: { type: String, required: false }, + captainUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true }, + remainingBidPointAmount: { type: Number, required: true, default: 0 }, + members: { + type: [RedisAuctionTeamMemberSubSchema], + required: true, + default: [], + }, + }, + { _id: false }, +); + const AuctionBidSubSchema = new Schema( { teamIndex: { type: Number, required: true, min: 1 }, @@ -1581,6 +2172,16 @@ const AuctionBidSubSchema = new Schema( { _id: false }, ); +const AuctionBidHistoryEntrySubSchema = new Schema( + { + bidderTeamIndex: { type: Number, required: true, min: 1 }, + bidPointAmount: { type: Number, required: true }, + bidderUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true }, + bidPlacedAtTimestampMS: { type: Number, required: true }, + }, + { _id: false }, +); + const AuctionChatMessageSubSchema = new Schema( { id: { type: String, required: true }, @@ -1606,6 +2207,40 @@ export const AuctionSchema = new Schema( required: true, default: 'waiting', }, + revision: { type: Number, required: true, default: 0, min: 0 }, + auctionEngineVersion: { + type: String, + enum: AUCTION_ENGINE_VERSIONS, + required: false, + }, + auctionLifecycleId: { type: String, required: false }, + lastAppliedAuctionStateTransitionId: { type: String, required: false }, + currentAuctionHistorySequence: { + type: Number, + required: true, + default: 0, + min: 0, + }, + startAuctionRequestId: { type: String, required: false }, + startAuctionStateTransitionId: { type: String, required: false }, + auctionStartedByUserId: { + type: Schema.Types.ObjectId, + ref: 'user', + required: false, + }, + matchSideEffectStatus: { + type: String, + enum: AUCTION_MATCH_SIDE_EFFECT_STATUSES, + required: true, + default: 'none', + }, + matchSideEffectRevision: { + type: Number, + required: true, + default: 0, + min: 0, + }, + matchSideEffectError: { type: String, required: false }, teams: { type: [AuctionTeamSubSchema], required: true, default: [] }, order: { type: [AuctionPlayerSnapshotSubSchema], @@ -1645,6 +2280,55 @@ export const AuctionSchema = new Schema( }, startedAt: { type: Date, required: false }, completedAt: { type: Date, required: false }, + auctionTeams: { + type: [RedisAuctionTeamSubSchema], + required: false, + default: undefined, + }, + auctionPlayerOrder: { + type: [AuctionPlayerSnapshotSubSchema], + required: false, + default: undefined, + }, + passedAuctionPlayerQueue: { + type: [AuctionPlayerSnapshotSubSchema], + required: false, + default: undefined, + }, + currentAuctionRound: { type: Number, required: false, min: 1 }, + currentAuctionPlayerOrderIndex: { type: Number, required: false, min: 0 }, + auctionBidHistory: { + type: [AuctionBidHistoryEntrySubSchema], + required: false, + default: undefined, + }, + currentHighestBidPointAmount: { type: Number, required: false, min: 0 }, + currentHighestBidderTeamIndex: { type: Number, required: false, min: 1 }, + currentBidRoundDeadlineTimestampMS: { + type: Number, + required: false, + min: 0, + }, + maximumBidRoundDurationSeconds: { + type: Number, + required: false, + min: 1, + }, + bidRoundExtensionSeconds: { type: Number, required: false, min: 0 }, + initialTeamBidPointAmount: { type: Number, required: false, min: 0 }, + topTierAuctionPriorityThreshold: { + type: String, + enum: AUCTION_TOP_TIER_THRESHOLDS, + required: false, + }, + manualTopTierAuctionPriorityUserIds: { + type: [Schema.Types.ObjectId], + ref: 'user', + required: false, + default: undefined, + }, + auctionStartedAtTimestampMS: { type: Number, required: false, min: 0 }, + auctionCompletedAtTimestampMS: { type: Number, required: false, min: 0 }, }, { timestamps: true, @@ -1652,7 +2336,7 @@ export const AuctionSchema = new Schema( }, ); -const AuctionHistoryEntrySchema = new Schema( +export const AuctionHistoryEntrySchema = new Schema( { auctionId: { type: Schema.Types.ObjectId, @@ -1669,19 +2353,16 @@ const AuctionHistoryEntrySchema = new Schema( sequence: { type: Number, required: true, min: 1 }, action: { type: String, - enum: [ - 'start', - 'open-bidding', - 'bid', - 'sold', - 'passed', - 'next', - 'complete', - ], + enum: AUCTION_ACTION_TYPES, required: true, }, + auctionStateTransitionId: { type: String, required: false }, + auctionLifecycleId: { type: String, required: false }, + revision: { type: Number, required: false, min: 0 }, actorUserId: { type: Schema.Types.ObjectId, ref: 'user', required: false }, snapshotBefore: { type: Schema.Types.Mixed, required: true }, + historyMutation: { type: Schema.Types.Mixed, required: false }, + matchSideEffectMutation: { type: Schema.Types.Mixed, required: false }, takenAt: { type: Date, required: true, default: Date.now }, }, { @@ -1691,6 +2372,74 @@ const AuctionHistoryEntrySchema = new Schema( ); AuctionHistoryEntrySchema.index({ auctionId: 1, sequence: -1 }); +AuctionHistoryEntrySchema.index( + { auctionId: 1, sequence: 1 }, + { unique: true }, +); +AuctionHistoryEntrySchema.index( + { auctionId: 1, auctionStateTransitionId: 1 }, + { sparse: true, unique: true }, +); + +export const AuctionSideEffectApplicationSchema = + new Schema( + { + auctionId: { + type: Schema.Types.ObjectId, + ref: 'auction', + required: true, + index: true, + }, + matchId: { + type: Schema.Types.ObjectId, + ref: 'match', + required: true, + index: true, + }, + auctionStateTransitionId: { type: String, required: true }, + auctionLifecycleId: { type: String, required: true }, + sideEffectType: { type: String, required: true }, + state: { + type: String, + enum: AUCTION_SIDE_EFFECT_APPLICATION_STATES, + required: true, + default: 'pending', + }, + payload: { type: Schema.Types.Mixed, required: true, default: {} }, + payloadChecksum: { type: String, required: true }, + attempts: { type: Number, required: true, default: 0, min: 0 }, + processingStartedAtTimestampMS: { + type: Number, + required: false, + min: 0, + }, + processingLeaseExpiresAtTimestampMS: { + type: Number, + required: false, + min: 0, + }, + processingOwnerToken: { type: String, required: false }, + completedAtTimestampMS: { type: Number, required: false, min: 0 }, + lastError: { type: String, required: false }, + }, + { + timestamps: true, + collection: 'auctionSideEffectApplications', + }, + ); + +AuctionSideEffectApplicationSchema.index( + { + auctionId: 1, + auctionStateTransitionId: 1, + sideEffectType: 1, + }, + { unique: true }, +); +AuctionSideEffectApplicationSchema.index({ + state: 1, + processingLeaseExpiresAtTimestampMS: 1, +}); export const MatchStatsSchema: mongoose.Schema = new Schema( { @@ -1700,6 +2449,13 @@ export const MatchStatsSchema: mongoose.Schema = 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', @@ -1726,9 +2482,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' }, { @@ -1765,6 +2523,11 @@ export const tournamentModelDefinitions: ModelDefinition[] = [ schema: AuctionHistoryEntrySchema, schemaName: 'auctionHistory', }, + { + name: 'auctionSideEffectApplication', + schema: AuctionSideEffectApplicationSchema, + schemaName: 'auctionSideEffectApplication', + }, { name: 'matchStats', schema: MatchStatsSchema, @@ -1773,6 +2536,10 @@ export const tournamentModelDefinitions: ModelDefinition[] = [ ]; export interface TournamentModelTypes { + competition: Competition; + competitionFact: CompetitionFact; + competitionOutbox: CompetitionOutbox; + tournamentCodeAssignment: TournamentCodeAssignment; identity: Identity; community: Community; dakaoInboundMessage: DakaoInboundMessage; @@ -1785,5 +2552,6 @@ export interface TournamentModelTypes { match: Match; auction: Auction; auctionHistory: AuctionHistoryEntry; + auctionSideEffectApplication: AuctionSideEffectApplication; matchStats: MatchStats; } diff --git a/apps/api/src/modules/global/garnet/garnet.constants.ts b/apps/api/src/modules/global/garnet/garnet.constants.ts deleted file mode 100644 index 842616cb..00000000 --- a/apps/api/src/modules/global/garnet/garnet.constants.ts +++ /dev/null @@ -1 +0,0 @@ -export const GARNET_CLIENT = Symbol('GARNET_CLIENT'); diff --git a/apps/api/src/modules/global/garnet/garnet.module.ts b/apps/api/src/modules/global/garnet/garnet.module.ts deleted file mode 100644 index 8bc9ec66..00000000 --- a/apps/api/src/modules/global/garnet/garnet.module.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { Logger, Module } from '@nestjs/common'; -import { createClient } from 'redis'; -import { SecretModule } from '../secret/secret.module'; -import { SecretService } from '../secret/secret.service'; -import { GARNET_CLIENT } from './garnet.constants'; -import { GarnetService, type GarnetRedisClient } from './garnet.service'; - -function normalizeGarnetUrl(endpoint: string): string { - const trimmed = endpoint.trim(); - if (!trimmed) { - throw new Error('GARNET_ENDPOINT cannot be empty'); - } - if (/^redis(s)?:\/\//iu.test(trimmed)) { - return trimmed; - } - return `redis://${trimmed}`; -} - -@Module({ - imports: [SecretModule], - providers: [ - { - provide: GARNET_CLIENT, - inject: [SecretService], - useFactory: async ( - secretService: SecretService, - ): Promise => { - await secretService.ready(); - - const [endpoint, username, password] = await Promise.all([ - secretService.get('GARNET_ENDPOINT'), - secretService.get('GARNET_USERID'), - secretService.get('GARNET_PASSWORD'), - ]); - - const logger = new Logger('GarnetClient'); - const client = createClient({ - url: normalizeGarnetUrl(endpoint), - username, - password, - }); - - client.on('error', (error) => { - logger.error(`Garnet client error: ${error?.message ?? error}`); - }); - - await client.connect(); - logger.log('Garnet connected'); - - return client; - }, - }, - GarnetService, - ], - exports: [GarnetService, GARNET_CLIENT], -}) -export class GarnetModule {} diff --git a/apps/api/src/modules/global/global.module.ts b/apps/api/src/modules/global/global.module.ts index ba3ea479..55af9336 100644 --- a/apps/api/src/modules/global/global.module.ts +++ b/apps/api/src/modules/global/global.module.ts @@ -2,12 +2,12 @@ import { Module, Global } from '@nestjs/common'; import { SecretModule } from './secret/secret.module'; import { NatsModule } from './nats/nats.module'; import { DatabaseModule } from './database/database.module'; -import { GarnetModule } from './garnet/garnet.module'; +import { RedisModule } from './redis/redis.module'; @Global() @Module({ - imports: [SecretModule, NatsModule, DatabaseModule, GarnetModule], + imports: [SecretModule, NatsModule, DatabaseModule, RedisModule], providers: [], - exports: [SecretModule, NatsModule, DatabaseModule, GarnetModule], + exports: [SecretModule, NatsModule, DatabaseModule, RedisModule], }) export class GlobalModule {} diff --git a/apps/api/src/modules/global/nats/nats.service.ts b/apps/api/src/modules/global/nats/nats.service.ts index acbc2b3b..5b58c6ef 100644 --- a/apps/api/src/modules/global/nats/nats.service.ts +++ b/apps/api/src/modules/global/nats/nats.service.ts @@ -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(); private readonly jetStreamConsumers = new Set(); + 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, ): Promise { - 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 { + return new Promise((resolve) => setTimeout(resolve, durationMilliseconds)); + } } diff --git a/apps/api/src/modules/global/observability/api-performance.interceptor.ts b/apps/api/src/modules/global/observability/api-performance.interceptor.ts new file mode 100644 index 00000000..f7b72d72 --- /dev/null +++ b/apps/api/src/modules/global/observability/api-performance.interceptor.ts @@ -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; + }; +} + +interface ResponseLike { + statusCode?: number; +} + +@Injectable() +export class ApiPerformanceInterceptor implements NestInterceptor { + intercept(context: ExecutionContext, next: CallHandler): Observable { + if (!isApiPerformanceObservabilityEnabled()) { + return next.handle(); + } + + const http = context.switchToHttp(); + const request = http.getRequest(); + const response = http.getResponse(); + 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(/\/$/, '') || '/'; +} diff --git a/apps/api/src/modules/global/observability/mongoose-performance.plugin.spec.ts b/apps/api/src/modules/global/observability/mongoose-performance.plugin.spec.ts new file mode 100644 index 00000000..79b9dc44 --- /dev/null +++ b/apps/api/src/modules/global/observability/mongoose-performance.plugin.spec.ts @@ -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); + }); +}); diff --git a/apps/api/src/modules/global/observability/mongoose-performance.plugin.ts b/apps/api/src/modules/global/observability/mongoose-performance.plugin.ts new file mode 100644 index 00000000..2016f542 --- /dev/null +++ b/apps/api/src/modules/global/observability/mongoose-performance.plugin.ts @@ -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 & { + [QUERY_PERFORMANCE_START]?: bigint; + [QUERY_PERFORMANCE_RECORDED]?: boolean; +}; + +type AggregateWithPerformanceState = mongoose.Aggregate & { + [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 | 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), + ); +} + +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).sort(); + return keys.length > 0 ? keys.join(',') : undefined; +} + +function errorName(error: unknown): string | undefined { + return error instanceof Error ? error.name : undefined; +} diff --git a/apps/api/src/modules/global/observability/new-relic.ts b/apps/api/src/modules/global/observability/new-relic.ts new file mode 100644 index 00000000..5d773976 --- /dev/null +++ b/apps/api/src/modules/global/observability/new-relic.ts @@ -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, + ): void; + addCustomAttributes( + attributes: Record, + ): 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, +): void { + try { + const flat: Record = {}; + for (const [key, value] of Object.entries(attributes)) { + if (value !== undefined) flat[key] = value; + } + agent.recordCustomEvent(eventType, flat); + } catch { + // 관측성 실패가 비즈니스 로직을 막아선 안 된다. + } +} + +export function addNewRelicCustomAttributes( + attributes: Record, +): void { + try { + const flat: Record = {}; + 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 { + // 관측성 실패가 비즈니스 로직을 막아선 안 된다. + } +} diff --git a/apps/api/src/modules/global/observability/performance-observer.spec.ts b/apps/api/src/modules/global/observability/performance-observer.spec.ts new file mode 100644 index 00000000..52fe056f --- /dev/null +++ b/apps/api/src/modules/global/observability/performance-observer.spec.ts @@ -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); + }); +}); diff --git a/apps/api/src/modules/global/observability/performance-observer.ts b/apps/api/src/modules/global/observability/performance-observer.ts new file mode 100644 index 00000000..a41a256d --- /dev/null +++ b/apps/api/src/modules/global/observability/performance-observer.ts @@ -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(); + +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( + 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 { + 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); +} diff --git a/apps/api/src/modules/global/redis/distributed-lock.service.spec.ts b/apps/api/src/modules/global/redis/distributed-lock.service.spec.ts new file mode 100644 index 00000000..1b99bb42 --- /dev/null +++ b/apps/api/src/modules/global/redis/distributed-lock.service.spec.ts @@ -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); + }); +}); diff --git a/apps/api/src/modules/global/redis/distributed-lock.service.ts b/apps/api/src/modules/global/redis/distributed-lock.service.ts new file mode 100644 index 00000000..fbaa2ccd --- /dev/null +++ b/apps/api/src/modules/global/redis/distributed-lock.service.ts @@ -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 { + 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 { + 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 { + 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( + options: RunWithDistributedLockOptions, + operation: (lockOwnership: DistributedLockOwnership) => Promise, + ): Promise { + 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( + options: RunWithRenewedDistributedLockOptions, + operation: (lockOwnership: DistributedLockOwnership) => Promise, + ): Promise { + 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 { + 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 { + return new Promise((resolve) => setTimeout(resolve, durationMilliseconds)); + } +} diff --git a/apps/api/src/modules/global/redis/redis.config.spec.ts b/apps/api/src/modules/global/redis/redis.config.spec.ts new file mode 100644 index 00000000..a3e50e66 --- /dev/null +++ b/apps/api/src/modules/global/redis/redis.config.spec.ts @@ -0,0 +1,59 @@ +import { + assertDistinctRedisInstances, + normalizeRedisUrl, + resolveRedisClientOptions, +} from './redis.config'; + +describe('redis.config', () => { + it('normalizes host:port endpoints into redis URLs', () => { + expect(normalizeRedisUrl('127.0.0.1:6379', 'REDIS_ENDPOINT')).toBe( + 'redis://127.0.0.1:6379', + ); + expect(normalizeRedisUrl('rediss://cache.example.com:6380')).toBe( + 'rediss://cache.example.com:6380', + ); + }); + + it('throws a clear error for empty endpoints', () => { + expect(() => normalizeRedisUrl(' ', 'REDIS_ENDPOINT')).toThrow( + 'REDIS_ENDPOINT cannot be empty', + ); + }); + + it('keeps credentials optional when resolving client options', () => { + expect( + resolveRedisClientOptions({ + endpoint: 'redis.internal:6379', + username: '', + password: undefined, + endpointEnvName: 'REDIS_ENDPOINT', + }), + ).toEqual({ + url: 'redis://redis.internal:6379', + }); + }); + + it('rejects auction Redis when it points at the same physical Redis instance', () => { + expect(() => + assertDistinctRedisInstances( + 'redis://cache.internal:6379/0', + 'redis://cache.internal:6379/1', + ), + ).toThrow('AUCTION_REDIS must use a separate Redis instance'); + }); + + it('allows different Redis hosts or ports', () => { + expect(() => + assertDistinctRedisInstances( + 'redis://cache.internal:6379', + 'redis://auction.internal:6379', + ), + ).not.toThrow(); + expect(() => + assertDistinctRedisInstances( + 'redis://cache.internal:6379', + 'redis://cache.internal:6380', + ), + ).not.toThrow(); + }); +}); diff --git a/apps/api/src/modules/global/redis/redis.config.ts b/apps/api/src/modules/global/redis/redis.config.ts new file mode 100644 index 00000000..e98a9c8c --- /dev/null +++ b/apps/api/src/modules/global/redis/redis.config.ts @@ -0,0 +1,77 @@ +export interface RedisClientOptions { + password?: string; + url: string; + username?: string; +} + +export interface ResolveRedisClientOptionsParams { + endpoint?: string; + endpointEnvName?: string; + password?: string; + url?: string; + urlEnvName?: string; + username?: string; +} + +function trimOptional(value: string | undefined): string | undefined { + const trimmed = value?.trim(); + return trimmed ? trimmed : undefined; +} + +export function normalizeRedisUrl( + endpointOrUrl: string, + envName = 'REDIS_URL', +): string { + const trimmed = endpointOrUrl.trim(); + if (!trimmed) { + throw new Error(`${envName} cannot be empty`); + } + if (/^redis(s)?:\/\//iu.test(trimmed)) { + return trimmed; + } + return `redis://${trimmed}`; +} + +export function resolveRedisClientOptions( + params: ResolveRedisClientOptionsParams, +): RedisClientOptions { + const url = trimOptional(params.url); + const endpoint = trimOptional(params.endpoint); + const selectedEndpoint = url ?? endpoint; + const selectedEnvName = url + ? (params.urlEnvName ?? 'REDIS_URL') + : (params.endpointEnvName ?? 'REDIS_ENDPOINT'); + + if (!selectedEndpoint) { + throw new Error(`${selectedEnvName} cannot be empty`); + } + + const options: RedisClientOptions = { + url: normalizeRedisUrl(selectedEndpoint, selectedEnvName), + }; + const username = trimOptional(params.username); + const password = trimOptional(params.password); + if (username) options.username = username; + if (password) options.password = password; + return options; +} + +function parseRedisInstanceIdentity(redisUrl: string): string { + const url = new URL(normalizeRedisUrl(redisUrl)); + const hostname = url.hostname.toLowerCase(); + const port = url.port || '6379'; + return `${hostname}:${port}`; +} + +export function assertDistinctRedisInstances( + redisUrl: string, + auctionRedisUrl: string, +): void { + const redisIdentity = parseRedisInstanceIdentity(redisUrl); + const auctionRedisIdentity = parseRedisInstanceIdentity(auctionRedisUrl); + if (redisIdentity === auctionRedisIdentity) { + throw new Error( + 'AUCTION_REDIS must use a separate Redis instance from REDIS because auction Redis is a live state source of truth.', + ); + } +} diff --git a/apps/api/src/modules/global/redis/redis.constants.ts b/apps/api/src/modules/global/redis/redis.constants.ts new file mode 100644 index 00000000..8f1a24b2 --- /dev/null +++ b/apps/api/src/modules/global/redis/redis.constants.ts @@ -0,0 +1 @@ +export const REDIS_CLIENT = Symbol('REDIS_CLIENT'); diff --git a/apps/api/src/modules/global/redis/redis.module.ts b/apps/api/src/modules/global/redis/redis.module.ts new file mode 100644 index 00000000..205dd4e7 --- /dev/null +++ b/apps/api/src/modules/global/redis/redis.module.ts @@ -0,0 +1,70 @@ +import { Logger, Module } from '@nestjs/common'; +import { createClient } from 'redis'; +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( + secretService: SecretService, + keys: string[], +): Promise { + for (const key of keys) { + const value = await secretService.get(key, ''); + const trimmed = value.trim(); + if (trimmed) return trimmed; + } + return undefined; +} + +@Module({ + imports: [SecretModule], + providers: [ + { + provide: REDIS_CLIENT, + inject: [SecretService], + useFactory: async (secretService: SecretService): Promise => { + await secretService.ready(); + + const [url, endpoint, username, password] = await Promise.all([ + readFirstSecret(secretService, ['REDIS_URL', 'GARNET_URL']), + readFirstSecret(secretService, ['REDIS_ENDPOINT', 'GARNET_ENDPOINT']), + readFirstSecret(secretService, [ + 'REDIS_USERNAME', + 'REDIS_USERID', + 'GARNET_USERNAME', + 'GARNET_USERID', + ]), + readFirstSecret(secretService, ['REDIS_PASSWORD', 'GARNET_PASSWORD']), + ]); + + const logger = new Logger('RedisClient'); + const client = createClient( + resolveRedisClientOptions({ + endpoint, + endpointEnvName: 'REDIS_ENDPOINT', + password, + url, + urlEnvName: 'REDIS_URL', + username, + }), + ); + + client.on('error', (error) => { + logger.error(`Redis client error: ${error?.message ?? error}`); + }); + + await client.connect(); + logger.log('Redis connected'); + + return client; + }, + }, + RedisService, + DistributedLockService, + ], + exports: [RedisService, DistributedLockService, REDIS_CLIENT], +}) +export class RedisModule {} diff --git a/apps/api/src/modules/global/redis/redis.service.spec.ts b/apps/api/src/modules/global/redis/redis.service.spec.ts new file mode 100644 index 00000000..46aa02cf --- /dev/null +++ b/apps/api/src/modules/global/redis/redis.service.spec.ts @@ -0,0 +1,52 @@ +import { RedisService } from './redis.service'; + +function createRedisService(client: Record) { + 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', + ]); + }); +}); diff --git a/apps/api/src/modules/global/garnet/garnet.service.ts b/apps/api/src/modules/global/redis/redis.service.ts similarity index 65% rename from apps/api/src/modules/global/garnet/garnet.service.ts rename to apps/api/src/modules/global/redis/redis.service.ts index 2b50df91..71f1169a 100644 --- a/apps/api/src/modules/global/garnet/garnet.service.ts +++ b/apps/api/src/modules/global/redis/redis.service.ts @@ -1,8 +1,8 @@ import { Inject, Injectable, Logger, OnModuleDestroy } from '@nestjs/common'; import type { createClient } from 'redis'; -import { GARNET_CLIENT } from './garnet.constants'; +import { REDIS_CLIENT } from './redis.constants'; -export type GarnetRedisClient = ReturnType; +export type RedisClient = ReturnType; export interface StreamEntry { deliveriesCounter?: number; @@ -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 { + if (Array.isArray(fields)) { + const normalized: Record = {}; + 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)]), @@ -48,12 +63,10 @@ function normalizeStreamFields(fields: unknown): Record { } @Injectable() -export class GarnetService implements OnModuleDestroy { - private readonly logger = new Logger(GarnetService.name); +export class RedisService implements OnModuleDestroy { + private readonly logger = new Logger(RedisService.name); - constructor( - @Inject(GARNET_CLIENT) private readonly client: GarnetRedisClient, - ) {} + constructor(@Inject(REDIS_CLIENT) private readonly client: RedisClient) {} async onModuleDestroy() { try { @@ -63,7 +76,7 @@ export class GarnetService implements OnModuleDestroy { } } - public raw(): GarnetRedisClient { + public raw(): RedisClient { return this.client; } @@ -190,6 +203,38 @@ export class GarnetService implements OnModuleDestroy { })); } + public async claimStalePendingStreamMessages(options: { + key: string; + group: string; + consumer: string; + stalePendingMessageMinimumIdleMilliseconds: number; + startId?: string; + count?: number; + }): Promise { + 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, @@ -212,4 +257,37 @@ export class GarnetService implements OnModuleDestroy { public async publish(channel: string, message: string): Promise { 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; + } } diff --git a/apps/api/src/modules/legacy-import/legacy-import-result-cutover.spec.ts b/apps/api/src/modules/legacy-import/legacy-import-result-cutover.spec.ts new file mode 100644 index 00000000..4619fa50 --- /dev/null +++ b/apps/api/src/modules/legacy-import/legacy-import-result-cutover.spec.ts @@ -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; + 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; + const matchStatsService = { + buildAndUpsert: jest.fn().mockResolvedValue(undefined), + } as unknown as jest.Mocked; + const service = createService({ + connectionService, + matchStatsService, + bootstrapService, + commandService, + runWithLock: async (_options, operation) => operation(), + }); + jest + .spyOn( + service as unknown as { + ensureRiotMatchPersisted: ( + riotMatchId: string, + region: string, + ) => Promise; + }, + '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; + }, + '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; + }, + '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 = { + 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; + 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; + 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; + const matchStatsService = { + buildAndUpsert: jest.fn().mockResolvedValue(undefined), + } as unknown as jest.Mocked; + const service = createService({ + connectionService, + matchStatsService, + bootstrapService, + commandService, + }); + jest + .spyOn( + service as unknown as { + buildUserByPuuidMap: () => Promise; + }, + '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, + operation: () => Promise, + ) => Promise; + } = {}, +): LegacyImportService { + const distributedLockService = { + runWithLock: + options.runWithLock ?? + (async ( + _options: Record, + operation: () => Promise, + ) => 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 { + return ( + service as unknown as { + importSingleMatch: ( + riotMatchId: string, + job: LegacyImportMemberJob, + userByPuuid: UserByPuuidMap, + ) => Promise; + } + ).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(value: T) { + return { exec: jest.fn().mockResolvedValue(value) }; +} + +function sessionResult(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 = { + 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; + const service = createService({ connectionService, communityStatsService }); + return { + fixture, + session, + service, + matchModel, + competitionFactModel, + communityStatsService, + quarantineCollection, + }; +} diff --git a/apps/api/src/modules/legacy-import/legacy-import.module.ts b/apps/api/src/modules/legacy-import/legacy-import.module.ts index 9bd9ad80..cead3f9f 100644 --- a/apps/api/src/modules/legacy-import/legacy-import.module.ts +++ b/apps/api/src/modules/legacy-import/legacy-import.module.ts @@ -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], diff --git a/apps/api/src/modules/legacy-import/legacy-import.service.spec.ts b/apps/api/src/modules/legacy-import/legacy-import.service.spec.ts new file mode 100644 index 00000000..231d6cb9 --- /dev/null +++ b/apps/api/src/modules/legacy-import/legacy-import.service.spec.ts @@ -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(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; + const distributedLockService = { + releaseLockIfOwned: jest.fn().mockResolvedValue(true), + } as unknown as jest.Mocked; + const communityStatsService = { + invalidateCommunity: jest.fn().mockResolvedValue(undefined), + } as unknown as jest.Mocked; + 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; + } + ).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; + } + ).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); + }); +}); diff --git a/apps/api/src/modules/legacy-import/legacy-import.service.ts b/apps/api/src/modules/legacy-import/legacy-import.service.ts index 9f6a9244..5b320bed 100644 --- a/apps/api/src/modules/legacy-import/legacy-import.service.ts +++ b/apps/api/src/modules/legacy-import/legacy-import.service.ts @@ -2,26 +2,44 @@ import { BadRequestException, ConflictException, Injectable, + InternalServerErrorException, Logger, NotFoundException, } from '@nestjs/common'; -import { randomUUID } from 'crypto'; +import { createHash, randomUUID } from 'node:crypto'; import mongoose from 'mongoose'; +import { + CompetitionBootstrapService, + type CompetitionBootstrapMatch, +} from '../competition/competition-bootstrap.service'; +import { + CompetitionCommandService, + type CompetitionCommandActor, +} 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 { + type DistributedLockOwnership, + DistributedLockService, +} from '../global/redis/distributed-lock.service'; import type { LegacyImportJobDocument, Match, + MatchDocument, RiotMatch as StoredRiotMatch, UserDocument, } from '../global/database/schema'; -import { GarnetService } from '../global/garnet/garnet.service'; +import { RedisService } from '../global/redis/redis.service'; import { RIOT_JOB_LOW_STREAM } from '../riot-job-queue/riot-job-queue.types'; import { RiotMatchService } from '../riot/riot-match.service'; import type { RiotMatchDto, RiotRegionalRoute } from '../riot/riot.types'; import { - buildGameResult, + resolveReadyCompetitionSlot, + type CompetitionResultSnapshot, +} from '../tournament-result/competition-result.adapter'; +import type { MatchPuuidLookup } from '../tournament-result/team-mapping.util'; +import { buildParticipantsSnapshot, buildTeams, buildUserByPuuidMap, @@ -46,6 +64,10 @@ const MATCH_IMPORT_LOCK_TTL_SECONDS = 60; const MATCH_ID_PAGE_SIZE = 100; type ImportOutcome = 'imported' | 'duplicate' | 'skipped' | 'error'; +type ResultlessMatchPatch = Omit< + Partial, + 'result' | 'doubleElimination' +>; @Injectable() export class LegacyImportService { @@ -53,10 +75,13 @@ export class LegacyImportService { constructor( private readonly connectionService: ConnectionService, - private readonly garnetService: GarnetService, + private readonly redisService: RedisService, private readonly riotMatchService: RiotMatchService, private readonly communityStatsService: CommunityStatsService, private readonly matchStatsService: MatchStatsService, + private readonly distributedLockService: DistributedLockService, + private readonly competitionBootstrapService: CompetitionBootstrapService, + private readonly competitionCommandService: CompetitionCommandService, ) {} public async previewMembers(params: { @@ -80,12 +105,14 @@ export class LegacyImportService { }): Promise { const lockKey = this.communityLockKey(params.communityId); const jobId = randomUUID(); - const acquired = await this.garnetService.setStringIfAbsent( - lockKey, - jobId, - LEGACY_IMPORT_LOCK_TTL_SECONDS, - ); - if (!acquired) { + const communityImportLockOwnership = + await this.distributedLockService.acquireLock({ + lockKey, + lockOwnershipToken: jobId, + lockExpirationDurationMilliseconds: + LEGACY_IMPORT_LOCK_TTL_SECONDS * 1000, + }); + if (!communityImportLockOwnership) { throw new ConflictException('Legacy import is already running.'); } @@ -133,6 +160,7 @@ export class LegacyImportService { totalSkippedDuplicate: 0, totalErrors: 0, averageMemberSeconds: LEGACY_IMPORT_MEMBER_AVG_SECONDS, + completedMemberJobIds: [], }); for (const window of windows) { @@ -146,9 +174,9 @@ export class LegacyImportService { startTime: Math.floor(window.startTime.getTime() / 1000), endTime: Math.floor(window.endTime.getTime() / 1000), triggeredBy: params.triggeredBy.toString(), - region: (community.riotRegion ?? 'asia') as RiotRegionalRoute, + region: community.riotRegion ?? 'asia', }; - await this.garnetService.appendStream( + await this.redisService.appendStream( RIOT_JOB_LOW_STREAM, { job: JSON.stringify(job) }, { maxLen: 10_000 }, @@ -160,7 +188,7 @@ export class LegacyImportService { { jobId }, { $set: { state: 'completed', completedAt: new Date() } }, ).exec(); - await this.garnetService.delete(lockKey); + await this.releaseDistributedLockSafely(communityImportLockOwnership); } return { @@ -169,7 +197,7 @@ export class LegacyImportService { etaSeconds: windows.length * LEGACY_IMPORT_MEMBER_AVG_SECONDS, }; } catch (error) { - await this.garnetService.delete(lockKey); + await this.releaseDistributedLockSafely(communityImportLockOwnership); throw error; } } @@ -220,7 +248,11 @@ export class LegacyImportService { ).exec(); if (!job) throw new NotFoundException('Running legacy import job not found.'); - await this.garnetService.delete(this.communityLockKey(params.communityId)); + await this.distributedLockService.releaseLockIfOwned({ + lockKey: this.communityLockKey(params.communityId), + lockOwnershipToken: job.jobId, + lockExpirationDurationMilliseconds: LEGACY_IMPORT_LOCK_TTL_SECONDS * 1000, + }); return job; } @@ -228,6 +260,7 @@ export class LegacyImportService { const started = Date.now(); const legacyJob = await this.getRunnableJob(job); if (!legacyJob) return; + if (legacyJob.completedMemberJobIds?.includes(job.jobId)) return; let discovered = 0; let imported = 0; @@ -289,8 +322,19 @@ export class LegacyImportService { .limit(limit + 1) .exec(); const visible = matches.slice(0, limit); - const riotMatchIds = visible - .map((match) => match.result?.games[0]?.riotMatchId) + const competitionByMatchId = await this.loadCompetitionByMatchId( + visible.map(({ _id }) => _id), + ); + const summaryByMatchId = new Map( + visible.map((match) => [ + match._id.toString(), + summarizeCompetitionResult( + competitionByMatchId.get(match._id.toString()), + ) ?? summarizeLegacyMatchResult(match), + ]), + ); + const riotMatchIds = [...summaryByMatchId.values()] + .map(({ riotMatchId }) => riotMatchId) .filter((matchId): matchId is string => Boolean(matchId)); const RiotMatchModel = await this.connectionService.getModel('riotMatch'); const rawDocs = await RiotMatchModel.find({ @@ -304,23 +348,23 @@ export class LegacyImportService { const userByPuuid = await this.buildUserByPuuidMap(params.communityId); return { matches: visible.map((match) => { - const riotMatchId = match.result?.games[0]?.riotMatchId ?? null; + const summary = summaryByMatchId.get(match._id.toString())!; + const riotMatchId = summary.riotMatchId; const raw = riotMatchId ? rawById.get(riotMatchId) : undefined; - const memberCount = match.result?.games[0]?.participants.length ?? 0; return { matchId: match._id.toString(), title: match.title, scheduledAt: match.scheduledAt.toISOString(), riotMatchId, - memberCount, + memberCount: summary.memberCount, externalCount: raw ? resolveExternalCount(raw, userByPuuid) - : Math.max(0, 10 - memberCount), - teamAIndex: match.result?.seriesResults?.[0]?.teamAIndex ?? 1, - teamBIndex: match.result?.seriesResults?.[0]?.teamBIndex ?? 2, - teamAWins: match.result?.seriesResults?.[0]?.teamAWins ?? 0, - teamBWins: match.result?.seriesResults?.[0]?.teamBWins ?? 0, - winnerTeamIndex: match.result?.winnerTeamIndex, + : Math.max(0, 10 - summary.memberCount), + teamAIndex: summary.teamAIndex, + teamBIndex: summary.teamBIndex, + teamAWins: summary.teamAWins, + teamBWins: summary.teamBWins, + winnerTeamIndex: summary.winnerTeamIndex, }; }), nextCursor: @@ -338,25 +382,194 @@ export class LegacyImportService { .filter((id) => mongoose.isValidObjectId(id)) .map((id) => new mongoose.Types.ObjectId(id)); if (ids.length === 0) return { deleted: 0 }; - const MatchModel = await this.connectionService.getModel('match'); - const targets = await MatchModel.find({ - _id: { $in: ids }, - communityId: params.communityId, - legacyImported: true, - }) - .select({ _id: 1 }) - .exec(); - const targetIds = targets.map((match) => match._id); - if (targetIds.length === 0) return { deleted: 0 }; + const [ + MatchModel, + CompetitionModel, + CompetitionFactModel, + CompetitionOutboxModel, + AssignmentModel, + TournamentCodeModel, + MatchStatsModel, + connection, + ] = await Promise.all([ + this.connectionService.getModel('match'), + this.connectionService.getModel('competition'), + this.connectionService.getModel('competitionFact'), + this.connectionService.getModel('competitionOutbox'), + this.connectionService.getModel('tournamentCodeAssignment'), + this.connectionService.getModel('tournamentCode'), + this.connectionService.getModel('matchStats'), + this.connectionService.getConnection(), + ]); + const session = await this.connectionService.createSession(); + if (!session) { + throw new InternalServerErrorException( + 'A MongoDB transaction is required to delete legacy Matches.', + ); + } + + let deleted = 0; + try { + session.startTransaction(); + const targets = await MatchModel.find({ + _id: { $in: ids }, + communityId: params.communityId, + legacyImported: true, + }) + .select({ _id: 1 }) + .session(session) + .exec(); + const targetIds = targets.map((match) => match._id); + if (targetIds.length === 0) { + await session.commitTransaction(); + } else { + const competitions = await CompetitionModel.find({ + matchId: { $in: targetIds }, + }) + .select({ _id: 1 }) + .session(session) + .lean() + .exec(); + const competitionIds = competitions.map(({ _id }) => _id); + if (competitionIds.length > 0) { + const assignments = await AssignmentModel.find({ + competitionId: { $in: competitionIds }, + state: { $in: ['reserved', 'used'] }, + }) + .select({ tournamentCodeId: 1, state: 1 }) + .session(session) + .lean() + .exec(); + const assignmentCodeIds = assignments.map( + ({ tournamentCodeId }) => tournamentCodeId, + ); + const uniqueAssignmentCodeIds = new Set( + assignmentCodeIds.map((id) => id.toString()), + ); + if (uniqueAssignmentCodeIds.size !== assignmentCodeIds.length) { + throw new ConflictException( + 'Tournament Code assignments contain a duplicate active code identity.', + ); + } + const tournamentCodes = + assignmentCodeIds.length === 0 + ? [] + : await TournamentCodeModel.find({ + _id: { $in: assignmentCodeIds }, + }) + .select({ _id: 1, state: 1, matchId: 1 }) + .session(session) + .lean() + .exec(); + const tournamentCodeById = new Map( + tournamentCodes.map((code) => [code._id.toString(), code]), + ); + const targetIdSet = new Set(targetIds.map((id) => id.toString())); + for (const assignment of assignments) { + const code = tournamentCodeById.get( + assignment.tournamentCodeId.toString(), + ); + if ( + !code || + code.state !== assignment.state || + !code.matchId || + !targetIdSet.has(code.matchId.toString()) + ) { + throw new ConflictException( + 'Tournament Code assignment ownership or state does not match the target legacy Match.', + ); + } + } + const releasedCodeIds = assignments + .filter(({ state }) => state === 'reserved') + .map(({ tournamentCodeId }) => tournamentCodeId); + const voidedCodeIds = assignments + .filter(({ state }) => state === 'used') + .map(({ tournamentCodeId }) => tournamentCodeId); + const terminalAt = new Date(); + if (releasedCodeIds.length > 0) { + const released = await TournamentCodeModel.updateMany( + { + _id: { $in: releasedCodeIds }, + matchId: { $in: targetIds }, + state: 'reserved', + }, + { + $set: { state: 'released', releasedAt: terminalAt }, + $unset: legacyTournamentCodeBindingUnset(), + }, + ) + .session(session) + .exec(); + assertExactTournamentCodeTransition( + released, + releasedCodeIds.length, + ); + } + if (voidedCodeIds.length > 0) { + const voided = await TournamentCodeModel.updateMany( + { + _id: { $in: voidedCodeIds }, + matchId: { $in: targetIds }, + state: 'used', + }, + { + $set: { state: 'voided', voidedAt: terminalAt }, + $unset: legacyTournamentCodeBindingUnset(), + }, + ) + .session(session) + .exec(); + assertExactTournamentCodeTransition(voided, voidedCodeIds.length); + } + + await CompetitionFactModel.deleteMany({ + competitionId: { $in: competitionIds }, + }) + .session(session) + .exec(); + await CompetitionOutboxModel.deleteMany({ + competitionId: { $in: competitionIds }, + }) + .session(session) + .exec(); + await AssignmentModel.deleteMany({ + competitionId: { $in: competitionIds }, + }) + .session(session) + .exec(); + await CompetitionModel.deleteMany({ + _id: { $in: competitionIds }, + }) + .session(session) + .exec(); + } + + await connection + .collection('competition_migration_quarantine') + .deleteMany({ _id: { $in: targetIds } }, { session }); + const result = await MatchModel.deleteMany({ + _id: { $in: targetIds }, + communityId: params.communityId, + legacyImported: true, + }) + .session(session) + .exec(); + await MatchStatsModel.deleteMany({ matchId: { $in: targetIds } }) + .session(session) + .exec(); + deleted = result.deletedCount ?? 0; + await session.commitTransaction(); + } + } catch (error) { + await session.abortTransaction().catch(() => undefined); + throw error; + } finally { + await session.endSession().catch(() => undefined); + } - const result = await MatchModel.deleteMany({ - _id: { $in: targetIds }, - communityId: params.communityId, - legacyImported: true, - }).exec(); - await this.matchStatsService.removeByMatches(targetIds); await this.communityStatsService.invalidateCommunity(params.communityId); - return { deleted: result.deletedCount ?? 0 }; + return { deleted }; } public async rebuildLegacyMatches(params: { @@ -367,12 +580,19 @@ export class LegacyImportService { communityId: params.communityId, legacyImported: true, }).exec(); - const riotMatchIds = matches - .map( - (match) => - match.result?.games[0]?.riotMatchId ?? - match.result?.riotMatchIds?.[0], - ) + const competitionByMatchId = await this.loadCompetitionByMatchId( + matches.map(({ _id }) => _id), + ); + const summaryByMatchId = new Map( + matches.map((match) => [ + match._id.toString(), + summarizeCompetitionResult( + competitionByMatchId.get(match._id.toString()), + ) ?? summarizeLegacyMatchResult(match), + ]), + ); + const riotMatchIds = [...summaryByMatchId.values()] + .map(({ riotMatchId }) => riotMatchId) .filter((matchId): matchId is string => Boolean(matchId)); const RiotMatchModel = await this.connectionService.getModel('riotMatch'); @@ -396,14 +616,17 @@ export class LegacyImportService { }; for (const match of matches) { - const riotMatchId = - match.result?.games[0]?.riotMatchId ?? match.result?.riotMatchIds?.[0]; + const existingCompetition = competitionByMatchId.get( + match._id.toString(), + ); + const summary = summaryByMatchId.get(match._id.toString())!; + const riotMatchId = summary.riotMatchId; const raw = riotMatchId ? rawById.get(riotMatchId) : undefined; const title = this.normalizeLegacyTitle( match.title, raw?.info.gameCreation ?? match.scheduledAt.getTime(), ); - const update: Partial = {}; + const update: ResultlessMatchPatch = {}; if (title !== match.title) { update.title = title; result.normalizedTitles += 1; @@ -416,43 +639,41 @@ export class LegacyImportService { { _id: match._id }, { $set: update }, ).exec(); - await this.matchStatsService.buildAndUpsert(match._id); + await this.rebuildMatchStats( + match._id, + competitionRevision(existingCompetition), + ); } continue; } const participants = buildParticipantsSnapshot(raw, userByPuuid); - const gameResult = buildGameResult(raw, userByPuuid, 1); - if (!gameResult || participants.length === 0) { + const teams = buildTeams(raw, userByPuuid); + const counts = countKnownParticipants(raw, userByPuuid); + if ( + !hasDecisiveRiotWinner(raw) || + !hasTrustedCompetitionRoster(counts, participants, teams) + ) { result.skippedNoKnownParticipants += 1; if (Object.keys(update).length > 0) { await MatchModel.updateOne( { _id: match._id }, { $set: update }, ).exec(); - await this.matchStatsService.buildAndUpsert(match._id); + await this.rebuildMatchStats( + match._id, + competitionRevision(existingCompetition), + ); } continue; } - const winnerTeamIndex = gameResult.winnerTeamIndex; update.mapId = raw.info.mapId ?? match.mapId; update.participants = participants; - update.teams = buildTeams(raw, userByPuuid); - update.result = { - winnerTeamIndex, - riotMatchIds: [riotMatchId], - games: [gameResult], - seriesResults: [ - { - teamAIndex: 1, - teamBIndex: 2, - teamAWins: winnerTeamIndex === 1 ? 1 : 0, - teamBWins: winnerTeamIndex === 2 ? 1 : 0, - winnerTeamIndex, - }, - ], - }; + update.teams = teams; + update.gameMode = 'pair'; + update.gameCount = 1; + update.teamBuiltAt = match.teamBuiltAt ?? new Date(raw.info.gameCreation); await MatchModel.updateOne( { @@ -462,7 +683,30 @@ export class LegacyImportService { }, { $set: update }, ).exec(); - await this.matchStatsService.buildAndUpsert(match._id); + let sourceRevision = competitionRevision(existingCompetition); + if (!summarizeCompetitionResult(existingCompetition)) { + const updatedMatch = { + ...toPlainRecord(match), + ...update, + _id: match._id, + communityId: match.communityId, + } as unknown as MatchDocument; + sourceRevision = + (await this.acceptRiotCompetitionFact({ + match: updatedMatch, + detail: raw, + actor: { type: 'system' }, + })) ?? undefined; + } + if (sourceRevision === undefined) { + result.skippedNoKnownParticipants += 1; + continue; + } + await MatchModel.updateOne( + { _id: match._id }, + { $set: { status: 'finished' } }, + ).exec(); + await this.rebuildMatchStats(match._id, sourceRevision); result.rebuilt += 1; } @@ -473,6 +717,44 @@ export class LegacyImportService { return result; } + private async loadCompetitionByMatchId( + matchIds: mongoose.Types.ObjectId[], + ): Promise> { + if (matchIds.length === 0) return new Map(); + const CompetitionModel = + await this.connectionService.getModel('competition'); + const competitions = await CompetitionModel.find({ + matchId: { $in: matchIds }, + }) + .lean() + .exec(); + return new Map( + competitions.map((competition) => [ + competition.matchId.toString(), + competition, + ]), + ); + } + + private rebuildMatchStats( + matchId: mongoose.Types.ObjectId, + sourceRevision?: number, + ): Promise { + return this.matchStatsService + .buildAndUpsert(matchId, { + ...(sourceRevision === undefined ? {} : { sourceRevision }), + }) + .catch((error: unknown) => { + this.logger.warn( + `Failed to rebuild legacy Match stats ${matchId.toString()}${ + sourceRevision === undefined + ? '' + : ` at Competition revision ${sourceRevision}` + }: ${error instanceof Error ? error.message : String(error)}`, + ); + }); + } + private async collectMatchIds( job: LegacyImportMemberJob, ): Promise> { @@ -500,75 +782,100 @@ export class LegacyImportService { userByPuuid: UserByPuuidMap, ): Promise { const lockKey = `legacy-import:match:${riotMatchId}`; - const acquired = await this.garnetService.setStringIfAbsent( - lockKey, - job.parentJobId, - MATCH_IMPORT_LOCK_TTL_SECONDS, - ); - if (!acquired) return 'duplicate'; - try { - const MatchModel = await this.connectionService.getModel('match'); - const existing = await MatchModel.exists({ - 'result.games.riotMatchId': riotMatchId, - }); - if (existing) return 'duplicate'; + const importOutcome = await this.distributedLockService.runWithLock( + { + lockKey, + lockExpirationDurationMilliseconds: + MATCH_IMPORT_LOCK_TTL_SECONDS * 1000, + }, + async () => { + const CompetitionFactModel = + await this.connectionService.getModel('competitionFact'); + const existing = await CompetitionFactModel.exists({ + type: 'game-accepted', + 'evidence.type': 'riot', + 'evidence.riotMatchId': riotMatchId, + }); + if (existing) return 'duplicate'; - const detail = await this.ensureRiotMatchPersisted( - riotMatchId, - job.region, - ); - if (!detail.info.tournamentCode) return 'skipped'; - const counts = countKnownParticipants(detail, userByPuuid); - if (counts.total === 0) return 'skipped'; + const detail = await this.ensureRiotMatchPersisted( + riotMatchId, + job.region, + ); + if (!detail.info.tournamentCode) return 'skipped'; + const counts = countKnownParticipants(detail, userByPuuid); + const participants = buildParticipantsSnapshot(detail, userByPuuid); + const teams = buildTeams(detail, userByPuuid); + if ( + !hasDecisiveRiotWinner(detail) || + !hasTrustedCompetitionRoster(counts, participants, teams) + ) { + return 'skipped'; + } - const gameResult = buildGameResult(detail, userByPuuid, 1); - if (!gameResult || gameResult.participants.length === 0) return 'skipped'; - - const winnerTeamIndex = gameResult.winnerTeamIndex; - const matchPayload: Partial = { - communityId: new mongoose.Types.ObjectId(job.communityId), - title: this.formatLegacyDate(detail.info.gameCreation), - description: 'Legacy import (자동 생성)', - mapId: detail.info.mapId ?? 11, - status: 'finished', - scheduledAt: new Date(detail.info.gameCreation), - maxParticipants: 10, - gameCount: 1, - gameMode: 'pair', - tournamentCodeIds: [], - teamBuiltAt: new Date(detail.info.gameCreation), - hostUserId: new mongoose.Types.ObjectId(job.triggeredBy), - participants: buildParticipantsSnapshot(detail, userByPuuid), - teams: buildTeams(detail, userByPuuid), - result: { - winnerTeamIndex, - riotMatchIds: [riotMatchId], - games: [gameResult], - seriesResults: [ - { - teamAIndex: 1, - teamBIndex: 2, - teamAWins: winnerTeamIndex === 1 ? 1 : 0, - teamBWins: winnerTeamIndex === 2 ? 1 : 0, - winnerTeamIndex, + const matchPayload: ResultlessMatchPatch = { + communityId: new mongoose.Types.ObjectId(job.communityId), + title: this.formatLegacyDate(detail.info.gameCreation), + description: 'Legacy import (자동 생성)', + mapId: detail.info.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: new mongoose.Types.ObjectId(job.triggeredBy), + participants, + teams, + legacyImported: true, + legacyImportSource: { + importedAt: new Date(), + importedBy: new mongoose.Types.ObjectId(job.triggeredBy), + triggeringPuuid: job.puuid, + jobId: job.parentJobId, }, - ], + prizes: [], + notices: [], + schedule: [], + }; + const MatchModel = await this.connectionService.getModel('match'); + const match = await MatchModel.findOneAndUpdate( + { + _id: deterministicObjectId(`legacy-import:match:${riotMatchId}`), + }, + { $setOnInsert: matchPayload }, + { + upsert: true, + returnDocument: 'after', + setDefaultsOnInsert: true, + runValidators: true, + }, + ).exec(); + if (!match) + throw new Error('Legacy Match upsert returned no document.'); + + const sourceRevision = await this.acceptRiotCompetitionFact({ + match, + detail, + actor: { + type: 'migration', + migrationRunId: job.parentJobId, + }, + }); + if (sourceRevision === null) return 'skipped'; + await MatchModel.updateOne( + { _id: match._id }, + { $set: { status: 'finished' } }, + ).exec(); + await this.rebuildMatchStats(match._id, sourceRevision); + return 'imported'; }, - legacyImported: true, - legacyImportSource: { - importedAt: new Date(), - importedBy: new mongoose.Types.ObjectId(job.triggeredBy), - triggeringPuuid: job.puuid, - jobId: job.parentJobId, - }, - prizes: [], - notices: [], - schedule: [], - }; - const match = await MatchModel.create(matchPayload); - await this.matchStatsService.buildAndUpsert(match._id); - return 'imported'; + ); + if (importOutcome === null) return 'duplicate'; + return importOutcome; } catch (error) { await this.recordError(job.parentJobId, { puuid: job.puuid, @@ -576,11 +883,45 @@ export class LegacyImportService { reason: error instanceof Error ? error.message : String(error), }); return 'error'; - } finally { - await this.garnetService.delete(lockKey); } } + private async acceptRiotCompetitionFact(params: { + match: MatchDocument; + detail: RiotMatchDto; + actor: CompetitionCommandActor; + }): Promise { + const competitionDocument = + await this.competitionBootstrapService.bootstrap( + params.match as unknown as CompetitionBootstrapMatch, + ); + const competition = toCompetitionResultSnapshot(competitionDocument); + const mapped = resolveReadyCompetitionSlot({ + competition, + detail: params.detail, + lookup: buildMatchPuuidLookup(params.match), + }); + if (!mapped) return null; + + const accepted = await this.competitionCommandService.acceptGame({ + competitionId: competition.competitionId, + expectedRevision: competition.revision, + idempotencyKey: `legacy-import:riot:${params.detail.metadata.matchId}`, + actor: params.actor, + occurredAt: mapped.occurredAt, + gameId: mapped.gameId, + seriesId: mapped.seriesId, + gameSlotId: mapped.gameSlotId, + ordinal: mapped.ordinal, + evidence: mapped.evidence, + mapping: mapped.mapping, + startedAt: mapped.startedAt, + durationSeconds: mapped.durationSeconds, + participants: mapped.normalizedParticipants, + }); + return accepted.revision; + } + private async ensureRiotMatchPersisted( riotMatchId: string, region: RiotRegionalRoute, @@ -626,6 +967,7 @@ export class LegacyImportService { jobId: job.parentJobId, }).exec(); if (!current || current.state === 'cancelled') return; + if (current.completedMemberJobIds?.includes(job.jobId)) return; const average = current.averageMemberSeconds === undefined @@ -634,14 +976,14 @@ export class LegacyImportService { current.averageMemberSeconds * 0.7 + stats.elapsedSeconds * 0.3, ); - const nextProcessed = current.processedMembers + 1; - const completed = nextProcessed >= current.totalMembers; - await LegacyImportJobModel.updateOne( - { jobId: job.parentJobId }, + const updateResult = await LegacyImportJobModel.updateOne( + { + jobId: job.parentJobId, + completedMemberJobIds: { $ne: job.jobId }, + state: { $ne: 'cancelled' }, + }, { $set: { - state: completed ? 'completed' : current.state, - completedAt: completed ? new Date() : current.completedAt, averageMemberSeconds: average, }, $inc: { @@ -651,14 +993,54 @@ export class LegacyImportService { totalSkippedDuplicate: stats.duplicates, totalErrors: stats.errors, }, + $addToSet: { + completedMemberJobIds: job.jobId, + }, }, ).exec(); + if (updateResult.modifiedCount === 0) return; + + const updated = await LegacyImportJobModel.findOne({ + jobId: job.parentJobId, + }) + .select({ + processedMembers: 1, + totalMembers: 1, + state: 1, + completedAt: 1, + }) + .lean() + .exec(); + const completed = Boolean( + updated && + updated.state !== 'cancelled' && + updated.processedMembers >= updated.totalMembers, + ); + if (completed) { + await LegacyImportJobModel.updateOne( + { + jobId: job.parentJobId, + state: { $ne: 'cancelled' }, + }, + { + $set: { + state: 'completed', + completedAt: updated?.completedAt ?? new Date(), + }, + }, + ).exec(); + } if (completed) { await Promise.all([ - this.garnetService.delete( - this.communityLockKey(new mongoose.Types.ObjectId(job.communityId)), - ), + this.distributedLockService.releaseLockIfOwned({ + lockKey: this.communityLockKey( + new mongoose.Types.ObjectId(job.communityId), + ), + lockOwnershipToken: job.parentJobId, + lockExpirationDurationMilliseconds: + LEGACY_IMPORT_LOCK_TTL_SECONDS * 1000, + }), this.communityStatsService.invalidateCommunity( new mongoose.Types.ObjectId(job.communityId), ), @@ -680,6 +1062,20 @@ export class LegacyImportService { return legacyJob; } + private async releaseDistributedLockSafely( + lockOwnership: DistributedLockOwnership, + ): Promise { + await this.distributedLockService + .releaseLockIfOwned(lockOwnership) + .catch((error: unknown) => { + this.logger.warn( + `Failed to release legacy import lock ${lockOwnership.lockKey}: ${ + error instanceof Error ? error.message : String(error) + }`, + ); + }); + } + private async isCancelled(parentJobId: string): Promise { const LegacyImportJobModel = await this.connectionService.getModel('legacyImportJob'); @@ -836,3 +1232,256 @@ function isRiotMatchDto(value: unknown): value is RiotMatchDto { 'info' in value, ); } + +interface LegacyResultSummary { + riotMatchId: string | null; + memberCount: number; + teamAIndex: number; + teamBIndex: number; + teamAWins: number; + teamBWins: number; + winnerTeamIndex?: number; +} + +function summarizeCompetitionResult( + value: unknown, +): LegacyResultSummary | null { + if (!value) return null; + const competition = toPlainRecord(value); + const projection = toRecord(competition.projection); + const games = toArray(projection.games).map(toRecord); + const game = games.find((candidate) => { + const evidence = toRecord(candidate.evidence); + return evidence.type === 'riot' && typeof evidence.riotMatchId === 'string'; + }); + if (!game) return null; + const evidence = toRecord(game.evidence); + const series = toArray(projection.series) + .map(toRecord) + .find( + (candidate) => idString(candidate.seriesId) === idString(game.seriesId), + ); + const entries = toArray(series?.entries).map(toRecord); + const teamIndexById = new Map( + toArray(competition.teams).map((teamValue) => { + const team = toRecord(teamValue); + return [ + idString(team.teamId), + optionalNumber(team.legacyTeamIndex) ?? numberValue(team.displayOrder), + ]; + }), + ); + const teamA = entries.find((entry) => entry.slot === 'A'); + const teamB = entries.find((entry) => entry.slot === 'B'); + const teamAId = idString(teamA?.teamId); + const teamBId = idString(teamB?.teamId); + const winnerTeamId = + idString(toRecord(series?.outcome).winnerTeamId) || + idString(game.winnerTeamId); + return { + riotMatchId: String(evidence.riotMatchId), + memberCount: toArray(game.participants).filter( + (participant) => idString(toRecord(participant).userId).length > 0, + ).length, + teamAIndex: teamIndexById.get(teamAId) ?? 1, + teamBIndex: teamIndexById.get(teamBId) ?? 2, + teamAWins: numberValue(teamA?.gameWins), + teamBWins: numberValue(teamB?.gameWins), + ...(teamIndexById.has(winnerTeamId) + ? { winnerTeamIndex: teamIndexById.get(winnerTeamId) } + : {}), + }; +} + +function summarizeLegacyMatchResult(match: MatchDocument): LegacyResultSummary { + const series = match.result?.seriesResults?.[0]; + const game = match.result?.games?.[0]; + return { + riotMatchId: game?.riotMatchId ?? match.result?.riotMatchIds?.[0] ?? null, + memberCount: game?.participants.length ?? 0, + teamAIndex: series?.teamAIndex ?? 1, + teamBIndex: series?.teamBIndex ?? 2, + teamAWins: series?.teamAWins ?? 0, + teamBWins: series?.teamBWins ?? 0, + ...(match.result?.winnerTeamIndex === undefined + ? {} + : { winnerTeamIndex: match.result.winnerTeamIndex }), + }; +} + +function competitionRevision(value: unknown): number | undefined { + return value ? optionalNumber(toPlainRecord(value).revision) : undefined; +} + +function hasDecisiveRiotWinner(detail: RiotMatchDto): boolean { + return ( + detail.info.teams.filter( + ({ teamId, win }) => win && (teamId === 100 || teamId === 200), + ).length === 1 + ); +} + +function hasTrustedCompetitionRoster( + counts: { team100: number; team200: number; total: number }, + participants: Match['participants'], + teams: Match['teams'], +): boolean { + if ( + counts.total < 6 || + counts.team100 !== counts.team200 || + counts.team100 === 0 || + teams.length !== 2 || + teams.some((team) => team.members.length !== counts.team100) + ) { + return false; + } + const userIds = participants.map(({ userId }) => userId.toString()); + return ( + userIds.length === counts.total && new Set(userIds).size === userIds.length + ); +} + +function buildMatchPuuidLookup(match: MatchDocument): MatchPuuidLookup { + const puuidByUserId = new Map(); + const userIdByPuuid = new Map(); + for (const participant of match.participants) { + if (!participant.puuid) continue; + puuidByUserId.set(participant.userId.toString(), participant.puuid); + userIdByPuuid.set(participant.puuid, participant.userId); + } + return { puuidByUserId, userIdByPuuid }; +} + +function toCompetitionResultSnapshot( + value: unknown, +): CompetitionResultSnapshot { + const raw = toPlainRecord(value); + const projection = toRecord(raw.projection); + return { + competitionId: idString(raw._id), + revision: numberValue(raw.revision), + phase: String(raw.phase) as CompetitionResultSnapshot['phase'], + teams: toArray(raw.teams).map((teamValue) => { + const team = toRecord(teamValue); + return { + teamId: idString(team.teamId), + members: toArray(team.members).map((memberValue) => ({ + userId: idString(toRecord(memberValue).userId), + })), + }; + }), + projection: { + phase: String( + projection.phase, + ) as CompetitionResultSnapshot['projection']['phase'], + series: toArray(projection.series).map((seriesValue) => { + const series = toRecord(seriesValue); + return { + seriesId: idString(series.seriesId), + status: String( + series.status, + ) as CompetitionResultSnapshot['projection']['series'][number]['status'], + entries: toArray(series.entries).map((entryValue) => { + const entry = toRecord(entryValue); + return { + slot: String(entry.slot) as 'A' | 'B', + teamId: entry.teamId == null ? null : idString(entry.teamId), + gameWins: numberValue(entry.gameWins), + }; + }), + }; + }), + gameSlots: toArray(projection.gameSlots).map((slotValue) => { + const slot = toRecord(slotValue); + return { + id: idString(slot.id), + seriesId: idString(slot.seriesId), + ordinal: numberValue(slot.ordinal), + displayNumber: numberValue(slot.displayNumber), + status: String( + slot.status, + ) as CompetitionResultSnapshot['projection']['gameSlots'][number]['status'], + }; + }), + games: toArray(projection.games).map((gameValue) => { + const evidence = toRecord(toRecord(gameValue).evidence); + return { + evidence: { + type: typeof evidence.type === 'string' ? evidence.type : undefined, + riotMatchId: + typeof evidence.riotMatchId === 'string' + ? evidence.riotMatchId + : undefined, + }, + }; + }), + }, + }; +} + +function toPlainRecord(value: unknown): Record { + if ( + value && + typeof value === 'object' && + 'toObject' in value && + typeof value.toObject === 'function' + ) { + const document = value as { toObject: () => unknown }; + return toRecord(document.toObject()); + } + return toRecord(value); +} + +function toRecord(value: unknown): Record { + return value !== null && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : {}; +} + +function toArray(value: unknown): unknown[] { + return Array.isArray(value) ? value : []; +} + +function idString(value: unknown): string { + if (value instanceof mongoose.Types.ObjectId) return value.toString(); + return typeof value === 'string' ? value : ''; +} + +function numberValue(value: unknown): number { + return typeof value === 'number' && Number.isFinite(value) ? value : 0; +} + +function optionalNumber(value: unknown): number | undefined { + return typeof value === 'number' && Number.isFinite(value) + ? value + : undefined; +} + +function legacyTournamentCodeBindingUnset(): Record { + return { + matchId: 1, + gameNumber: 1, + bracketMatchId: 1, + reservedAt: 1, + }; +} + +function assertExactTournamentCodeTransition( + result: { matchedCount?: number; modifiedCount?: number }, + expectedCount: number, +): void { + if ( + result.matchedCount !== expectedCount || + result.modifiedCount !== expectedCount + ) { + throw new ConflictException( + 'Tournament Code transition did not update every validated assignment.', + ); + } +} + +function deterministicObjectId(key: string): mongoose.Types.ObjectId { + return new mongoose.Types.ObjectId( + createHash('sha256').update(key).digest('hex').slice(0, 24), + ); +} diff --git a/apps/api/src/modules/match-history/match-history.service.spec.ts b/apps/api/src/modules/match-history/match-history.service.spec.ts new file mode 100644 index 00000000..2c059e0e --- /dev/null +++ b/apps/api/src/modules/match-history/match-history.service.spec.ts @@ -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'); + }); +}); diff --git a/apps/api/src/modules/match-history/match-history.service.ts b/apps/api/src/modules/match-history/match-history.service.ts index 895689f8..c70900cd 100644 --- a/apps/api/src/modules/match-history/match-history.service.ts +++ b/apps/api/src/modules/match-history/match-history.service.ts @@ -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(); - 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 { + if (params.queueIds.length === 0) return []; + const RiotMatchModel = await this.connectionService.getModel('riotMatch'); + const gameCreation: Record = {}; + if (params.context.seasonStartedAt) { + gameCreation.$gte = params.context.seasonStartedAt.getTime(); + } + + const match: Record = { + participantPuuids: params.context.account.puuid, + queueId: { $in: params.queueIds }, + }; + if (Object.keys(gameCreation).length > 0) match.gameCreation = gameCreation; + + return RiotMatchModel.aggregate([ + { $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( + (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)); diff --git a/apps/api/src/modules/match-history/match-history.types.ts b/apps/api/src/modules/match-history/match-history.types.ts index 92727c11..29d7393d 100644 --- a/apps/api/src/modules/match-history/match-history.types.ts +++ b/apps/api/src/modules/match-history/match-history.types.ts @@ -1,4 +1,4 @@ -import type { RiotLane } from '../global/database/schema'; +import type { MatchStatsRunePerks, RiotLane } from '../global/database/schema'; import type { RiotQueueGroup, RiotRankFilter, @@ -121,7 +121,7 @@ export interface RecentMatchTeamParticipantView { items: number[]; trinket: number; summonerSpells: [number, number]; - perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + perks: MatchStatsRunePerks; totalCs: number; csPerMin: number; goldEarned: number; @@ -135,6 +135,8 @@ export interface RecentMatchTeamParticipantView { export interface RecentMatchView { matchId: string; + internalMatchId?: string; + gameNumber?: number; queueId: number; queueLabel: string; gameCreation: number; @@ -162,7 +164,7 @@ export interface RecentMatchView { items: number[]; trinket: number; summonerSpells: [number, number]; - perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + perks: MatchStatsRunePerks; teams: Array<{ side: 100 | 200; win: boolean; diff --git a/apps/api/src/modules/match/dto/create-match.dto.spec.ts b/apps/api/src/modules/match/dto/create-match.dto.spec.ts new file mode 100644 index 00000000..2b77dc13 --- /dev/null +++ b/apps/api/src/modules/match/dto/create-match.dto.spec.ts @@ -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, + }); + } + }); +}); diff --git a/apps/api/src/modules/match/dto/create-match.dto.ts b/apps/api/src/modules/match/dto/create-match.dto.ts index 7fe6ee55..5f60725d 100644 --- a/apps/api/src/modules/match/dto/create-match.dto.ts +++ b/apps/api/src/modules/match/dto/create-match.dto.ts @@ -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; + function IsMultipleOf( multiple: number, validationOptions?: ValidationOptions, @@ -98,8 +107,17 @@ 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() @@ -153,8 +171,17 @@ 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() @@ -188,8 +215,18 @@ export class JoinMatchDto { @ValidateNested({ each: true }) @Type(() => PositionPreferenceDto) preferredPositions!: PositionPreferenceDto[]; +} + +export class AddParticipantDto { + @IsOptional() + @IsArray() + @ArrayMinSize(1) + @ArrayMaxSize(5) + @ValidateNested({ each: true }) + @Type(() => PositionPreferenceDto) + preferredPositions?: PositionPreferenceDto[]; @IsOptional() @IsString() - userId?: string; + riotPuuid?: string; } diff --git a/apps/api/src/modules/match/match-public.presenter.spec.ts b/apps/api/src/modules/match/match-public.presenter.spec.ts new file mode 100644 index 00000000..de26841c --- /dev/null +++ b/apps/api/src/modules/match/match-public.presenter.spec.ts @@ -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')); +} diff --git a/apps/api/src/modules/match/match-public.presenter.ts b/apps/api/src/modules/match/match-public.presenter.ts new file mode 100644 index 00000000..42572f7e --- /dev/null +++ b/apps/api/src/modules/match/match-public.presenter.ts @@ -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; + 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), + }; +} diff --git a/apps/api/src/modules/match/match-result-cutover.spec.ts b/apps/api/src/modules/match/match-result-cutover.spec.ts new file mode 100644 index 00000000..7c6385e9 --- /dev/null +++ b/apps/api/src/modules/match/match-result-cutover.spec.ts @@ -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, + ); + }, + ); +}); diff --git a/apps/api/src/modules/match/match.controller.spec.ts b/apps/api/src/modules/match/match.controller.spec.ts new file mode 100644 index 00000000..36d85ea7 --- /dev/null +++ b/apps/api/src/modules/match/match.controller.spec.ts @@ -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(); + }); +}); diff --git a/apps/api/src/modules/match/match.controller.ts b/apps/api/src/modules/match/match.controller.ts index 81e2a985..aa13b292 100644 --- a/apps/api/src/modules/match/match.controller.ts +++ b/apps/api/src/modules/match/match.controller.ts @@ -1,3 +1,7 @@ +import type { + MatchDetailResponse, + MatchListResponse, +} from '@lolympus/contracts'; import { BadRequestException, Body, @@ -18,12 +22,9 @@ 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, JoinMatchDto, UpdateMatchDto, @@ -43,9 +44,9 @@ export class MatchController { @Param('communityId', ParseObjectIdPipe) communityId: mongoose.Types.ObjectId, @Body() body: CreateMatchDto, - ) { + ): Promise { this.assertSameCommunity(currentUser, communityId); - return this.matchService.create({ + const match = await this.matchService.create({ communityId, hostUserId: currentUser._id, data: { @@ -56,11 +57,15 @@ export class MatchController { maxParticipants: body.maxParticipants ?? 10, 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 }); } // 공개 — 커뮤니티 내 매치 리스트. 로그인 시 본인 참여 여부를 함께 반환. @@ -77,7 +82,7 @@ export class MatchController { @Query('scheduledFrom') scheduledFrom?: string, @Query('scheduledTo') scheduledTo?: string, @Query('sort') sort?: 'asc' | 'desc', - ) { + ): Promise { const result = await this.matchService.listPage({ communityId, status, @@ -88,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 { + 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') @@ -114,9 +137,18 @@ export class MatchController { communityId: mongoose.Types.ObjectId, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, @Body() body: UpdateMatchDto, - ) { + ): Promise { 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') @@ -133,20 +165,52 @@ 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 { + 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 }); + } + + // 관리자 전용 — 커뮤니티 유저를 모집중 매치에 직접 추가한다. + @Post(':matchId/participants/:userId') + @Roles('admin', 'owner') + @UseGuards(RolesGuard) + public async addParticipant( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId, + @Body() body: AddParticipantDto | undefined, + ): Promise { + this.assertSameCommunity(currentUser, communityId); + const match = await this.matchService.join({ + matchId, + communityId, + userId, + preferredPositions: body?.preferredPositions, + riotPuuid: body?.riotPuuid, + }); + return this.matchService.serialize(match, { + joined: match.participants.some((participant) => + participant.userId.equals(currentUser._id), + ), + }); } // 관리자 전용 — 참가자 주/부 포지션 변경. @@ -160,7 +224,7 @@ export class MatchController { @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, @Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId, @Body() body: UpdateParticipantDto, - ) { + ): Promise { this.assertSameCommunity(currentUser, communityId); const match = await this.matchService.updateParticipantPositions({ matchId, @@ -169,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), + ), + }); } // 관리자 전용 — 참가자 강제 제외. @@ -192,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, diff --git a/apps/api/src/modules/match/match.service.spec.ts b/apps/api/src/modules/match/match.service.spec.ts index 337f8599..e06d039c 100644 --- a/apps/api/src/modules/match/match.service.spec.ts +++ b/apps/api/src/modules/match/match.service.spec.ts @@ -2,9 +2,63 @@ import mongoose from 'mongoose'; import { MatchService } from './match.service'; describe('MatchService', () => { - function createService(match: Record) { + function createServiceWithCreateModels() { + const createdPayloads: Record[] = []; + 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, + updatedMatch: Record | 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, }; @@ -80,6 +135,51 @@ describe('MatchService', () => { }; } + function createServiceWithJoinModels(params: { + user: Record | null; + match: Record | null; + updatedMatch?: Record | 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) => { + if (name === 'user') return UserModel; + if (name === 'match') return MatchModel; + return {}; + }), + }; + const tournamentCodeService = { + buildSlots: jest.fn().mockResolvedValue([]), + releaseFromMatch: jest.fn().mockResolvedValue(undefined), + }; + const communityStatsService = { + invalidateCommunity: jest.fn().mockResolvedValue(undefined), + }; + const matchStatsService = { + buildAndUpsert: jest.fn().mockResolvedValue(undefined), + removeByMatch: jest.fn().mockResolvedValue(undefined), + }; + + return { + service: new MatchService( + connectionService as never, + tournamentCodeService as never, + communityStatsService as never, + matchStatsService as never, + ), + UserModel, + MatchModel, + }; + } + it('returns a paginated match list with total count', async () => { const communityId = new mongoose.Types.ObjectId(); const { service, MatchModel, sort, skip, limit } = @@ -104,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(); @@ -165,7 +278,298 @@ describe('MatchService', () => { expect(sort).toHaveBeenCalledWith({ scheduledAt: -1 }); }); - it('clears game schedule when a built match returns to recruiting', async () => { + it('uses saved user preferences when joining without explicit positions', async () => { + const communityId = new mongoose.Types.ObjectId(); + const userId = new mongoose.Types.ObjectId(); + const matchId = new mongoose.Types.ObjectId(); + const user = { + _id: userId, + communityId, + preferredPositions: [{ position: 'MID', priority: 1 }], + riotAccounts: [ + { + puuid: 'puuid-1', + gameName: 'Dahyeon', + tagLine: 'KR1', + profileIconId: 7, + isPrimary: true, + tiers: [], + }, + ], + }; + const match = { + _id: matchId, + communityId, + status: 'recruiting', + maxParticipants: 10, + participants: [], + save: jest.fn().mockResolvedValue(undefined), + }; + 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, + }); + + const joined = await service.join({ + matchId, + userId, + }); + + expect(joined).toBe(updatedMatch); + expect(MatchModel.findOneAndUpdate).toHaveBeenCalledWith( + expect.objectContaining({ + _id: matchId, + communityId, + status: 'recruiting', + 'participants.userId': { $ne: userId }, + $expr: expect.any(Object), + }), + { + $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('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, @@ -187,23 +591,114 @@ 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('releases reserved codes when returning a built match to recruiting', async () => { + it('rejects round-robin max round changes after recruiting', async () => { + const communityId = new mongoose.Types.ObjectId(); + const match = { + communityId, + status: 'team-built', + tournamentCodeIds: [], + set: jest.fn(), + save: jest.fn().mockResolvedValue(undefined), + }; + const { service } = createService(match); + + await expect( + service.update({ + matchId: new mongoose.Types.ObjectId(), + communityId, + patch: { roundRobinMaxRounds: 3 }, + }), + ).rejects.toThrow( + 'maxParticipants, gameCount, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.', + ); + expect(match.set).not.toHaveBeenCalled(); + }); + + 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 = { @@ -221,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(); }); }); diff --git a/apps/api/src/modules/match/match.service.ts b/apps/api/src/modules/match/match.service.ts index a3db4a51..37037459 100644 --- a/apps/api/src/modules/match/match.service.ts +++ b/apps/api/src/modules/match/match.service.ts @@ -1,5 +1,6 @@ import { BadRequestException, + ConflictException, Injectable, InternalServerErrorException, NotFoundException, @@ -11,31 +12,40 @@ import { ConnectionService } from '../global/database/connection.service'; import { Match, MatchDocument, - MatchSeriesResult, MatchStatus, + POSITIONS, Position, PositionPreference, TierInfo, } from '../global/database/schema'; import { DEFAULT_TOURNAMENT_GAME_COUNT } from '../tournament-code/tournament-code.constants'; import { TournamentCodeService } from '../tournament-code/tournament-code.service'; +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 & Pick; + data: Partial & + Pick & + DoubleEliminationConfigInput; } interface UpdateMatchParams { matchId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; - patch: Partial; + patch: Partial & DoubleEliminationConfigInput; } interface ListMatchesQuery { @@ -63,8 +73,9 @@ interface MatchListFilter { interface JoinMatchParams { matchId: mongoose.Types.ObjectId; + communityId?: mongoose.Types.ObjectId; userId: mongoose.Types.ObjectId; - preferredPositions: PositionPreference[]; + preferredPositions?: PositionPreference[]; // 특정 RiotAccount(puuid)로 참가하고 싶을 때 지정. 없으면 primary 사용. riotPuuid?: string; } @@ -104,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, }); @@ -170,37 +184,24 @@ export class MatchService { public async getById( matchId: mongoose.Types.ObjectId, + communityId: mongoose.Types.ObjectId, ): Promise { 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 { @@ -213,28 +214,43 @@ export class MatchService { const previousStatus = match.status; if ( previousStatus !== 'recruiting' && - ('maxParticipants' in params.patch || 'gameMode' in params.patch) + params.patch.status === 'recruiting' ) { - throw new BadRequestException( - 'maxParticipants and gameMode 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); } @@ -251,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(); @@ -263,42 +289,106 @@ 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, tagLine: selectedRiot?.tagLine, profileIconId: selectedRiot?.profileIconId, tier: selectedTier, - preferredPositions: params.preferredPositions, + preferredPositions: this.resolveJoinPreferredPositions( + params.preferredPositions, + user.preferredPositions, + ), 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 & DoubleEliminationConfigInput, + >(input: T): Partial { + 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 & DoubleEliminationConfigInput, + >(input: T): Partial { + 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( @@ -310,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 { + 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 { + const MatchModel = await this.connectionService.getModel('match'); const match = await this.loadRecruitingMatch( params.matchId, params.communityId, @@ -366,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( @@ -392,6 +509,75 @@ export class MatchService { return match; } + private async throwJoinFailure( + MatchModel: mongoose.Model, + matchId: mongoose.Types.ObjectId, + user: { + _id: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + }, + ): Promise { + 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, + matchId: mongoose.Types.ObjectId, + user: { + _id: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + }, + ): Promise { + 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, @@ -436,6 +622,28 @@ export class MatchService { }; } + private resolveJoinPreferredPositions( + requested: PositionPreference[] | undefined, + saved: PositionPreference[] | undefined, + ): PositionPreference[] { + const source = requested?.length + ? requested + : saved?.length + ? saved + : POSITIONS.map((position, index) => ({ + position, + priority: index + 1, + })); + + return [...source] + .sort((left, right) => left.priority - right.priority) + .slice(0, 5) + .map((preference, index) => ({ + position: preference.position, + priority: index + 1, + })); + } + private buildListFilter(query: ListMatchesQuery): MatchListFilter { const filter: MatchListFilter = { communityId: query.communityId, @@ -503,33 +711,4 @@ export class MatchService { } return code; } - - private buildSeriesResults( - games: NonNullable['games'], - ): MatchSeriesResult[] { - const bySeries = new Map(); - 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()]; - } } diff --git a/apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.spec.ts b/apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.spec.ts index fa0d8196..9c642af0 100644 --- a/apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.spec.ts +++ b/apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.spec.ts @@ -1,5 +1,6 @@ import mongoose from 'mongoose'; -import { GarnetService } from '../global/garnet/garnet.service'; +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'; import { BackgroundRefreshScheduler } from './background-refresh.scheduler'; @@ -33,13 +34,20 @@ function makeScheduler() { const rawClient = { sendCommand: jest.fn().mockResolvedValue(1), }; - const garnet = { + 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 & { raw: jest.Mock }; + } as unknown as jest.Mocked & { 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; const rateLimiter = { isRefreshWindowOpen: jest.fn().mockResolvedValue(true), } as unknown as jest.Mocked; @@ -51,7 +59,8 @@ function makeScheduler() { findStaleAccounts: jest.fn().mockResolvedValue([]), } as unknown as jest.Mocked; const scheduler = new BackgroundRefreshScheduler( - garnet, + redis, + distributedLockService, rateLimiter, enrichmentService, staleAccountRepository, @@ -59,7 +68,8 @@ function makeScheduler() { return { scheduler, - garnet, + 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, garnet, staleAccountRepository } = makeScheduler(); - garnet.getString.mockResolvedValue('another-consumer'); + const { scheduler, distributedLockService, staleAccountRepository } = + makeScheduler(); + distributedLockService.acquireLock.mockResolvedValueOnce(null); await scheduler.tick(); @@ -193,12 +204,12 @@ describe('BackgroundRefreshScheduler', () => { it('skips candidates already in failure backoff', async () => { jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z')); - const { scheduler, garnet, enrichmentService, staleAccountRepository } = + const { scheduler, redis, enrichmentService, staleAccountRepository } = makeScheduler(); staleAccountRepository.findStaleAccounts.mockResolvedValue([ candidate('skip-me'), ]); - garnet.getString.mockImplementation(async (key: string) => { + redis.getString.mockImplementation(async (key: string) => { if (key.includes('riot:bg:fail:skip-me')) return '3'; return null; }); diff --git a/apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.ts b/apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.ts index 82dc3936..bbb9a940 100644 --- a/apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.ts +++ b/apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.ts @@ -9,13 +9,17 @@ import { RiotAccountEnrichmentService, } from '../riot/riot-account-enrichment.service'; import { RiotRateLimiterService } from '../riot/riot-rate-limiter.service'; -import { GarnetService } from '../global/garnet/garnet.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 garnet: GarnetService, + 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 { 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 { @@ -158,33 +174,33 @@ export class BackgroundRefreshScheduler } private async tryBecomeLeader(): Promise { - const current = await this.garnet.getString(LEADER_KEY); - if (current === this.consumer) { - await this.garnet.setString( - LEADER_KEY, - this.consumer, - LEADER_TTL_SECONDS, - ); - return true; + if (this.leaderLockOwnership) { + const didExtendLeaderLock = + await this.distributedLockService.extendLockIfOwned( + this.leaderLockOwnership, + ); + if (didExtendLeaderLock) return true; + this.leaderLockOwnership = undefined; } - if (current) return false; - return this.garnet.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 { try { - const current = await this.garnet.getString(LEADER_KEY); - if (current !== this.consumer) return; - await this.garnet.setString( - LEADER_KEY, - this.consumer, - LEADER_TTL_SECONDS, - ); + 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: ${ @@ -200,7 +216,7 @@ export class BackgroundRefreshScheduler } private async getFailureCount(puuid: string): Promise { - const raw = await this.garnet.getString(this.failureBackoffKey(puuid)); + const raw = await this.redis.getString(this.failureBackoffKey(puuid)); const count = Number(raw ?? 0); if (!Number.isFinite(count) || count < 0) return 0; return count; @@ -208,7 +224,7 @@ export class BackgroundRefreshScheduler private async bumpFailureCounter(puuid: string): Promise { const key = this.failureBackoffKey(puuid); - const client = this.garnet.raw(); + const client = this.redis.raw(); const response = await client.sendCommand(['INCR', key]); await client.sendCommand([ 'EXPIRE', @@ -225,7 +241,7 @@ export class BackgroundRefreshScheduler } private async clearFailureCounter(puuid: string): Promise { - await this.garnet.delete(this.failureBackoffKey(puuid)); + await this.redis.delete(this.failureBackoffKey(puuid)); } private isFailedEnrichment(result: EnrichResult): boolean { diff --git a/apps/api/src/modules/riot-job-queue/riot-job-queue.service.ts b/apps/api/src/modules/riot-job-queue/riot-job-queue.service.ts index ecacef15..3c416113 100644 --- a/apps/api/src/modules/riot-job-queue/riot-job-queue.service.ts +++ b/apps/api/src/modules/riot-job-queue/riot-job-queue.service.ts @@ -13,7 +13,7 @@ import type { RiotAccount, UserDocument, } from '../global/database/schema'; -import { GarnetService } from '../global/garnet/garnet.service'; +import { RedisService } from '../global/redis/redis.service'; import { isRiotQueueGroup, resolveRiotQueueIds, @@ -51,7 +51,7 @@ interface RefreshContext { export class RiotJobQueueService { constructor( private readonly connectionService: ConnectionService, - private readonly garnetService: GarnetService, + private readonly redisService: RedisService, ) {} public async enqueueRefresh(params: { @@ -64,12 +64,12 @@ export class RiotJobQueueService { const context = await this.resolveContext(params); const queueGroups = this.normalizeQueueGroups(params.queueGroups); const stream = this.resolveStream(params.priority); - const streamLength = await this.garnetService.streamLength(stream); + const streamLength = await this.redisService.streamLength(stream); const dedupKeys = queueGroups.map((queueGroup) => this.dedupKey(context.account.puuid, queueGroup), ); const existingJobIds = await Promise.all( - dedupKeys.map((key) => this.garnetService.getString(key)), + dedupKeys.map((key) => this.redisService.getString(key)), ); const needsNewJob = existingJobIds.some((jobId) => !jobId); @@ -114,13 +114,13 @@ export class RiotJobQueueService { requestedBy: params.requestedBy, priority: params.priority, }; - const acquired = await this.garnetService.setStringIfAbsent( + const acquired = await this.redisService.setStringIfAbsent( dedupKeys[index], job.jobId, RIOT_JOB_DEDUP_TTL_SECONDS, ); if (!acquired) { - const jobId = await this.garnetService.getString(dedupKeys[index]); + const jobId = await this.redisService.getString(dedupKeys[index]); if (!jobId) continue; const status = await this.getStatus(jobId); subJobs.push({ @@ -149,7 +149,7 @@ export class RiotJobQueueService { await Promise.all([ this.setStatus(status), - this.garnetService.appendStream( + this.redisService.appendStream( stream, { job: JSON.stringify(job) }, { maxLen: 10_000 }, @@ -209,7 +209,7 @@ export class RiotJobQueueService { } public async promoteDueScheduledJobs(limit = 100): Promise { - const client = this.garnetService.raw(); + const client = this.redisService.raw(); const raw = (await client.sendCommand([ 'ZRANGEBYSCORE', RIOT_JOB_SCHEDULED_ZSET, @@ -239,13 +239,13 @@ export class RiotJobQueueService { } public async getStatus(jobId: string): Promise { - return this.garnetService.getJson(this.statusKey(jobId)); + return this.redisService.getJson(this.statusKey(jobId)); } public async getParentStatus( parentJobId: string, ): Promise { - const jobIds = await this.garnetService.getJson( + const jobIds = await this.redisService.getJson( this.parentKey(parentJobId), ); if (!jobIds) return null; @@ -296,7 +296,7 @@ export class RiotJobQueueService { }; await Promise.all([ this.setStatus(next), - this.garnetService.delete(this.dedupKey(job.puuid, job.queueGroup)), + this.redisService.delete(this.dedupKey(job.puuid, job.queueGroup)), ]); return this.toEvent(next); } @@ -317,7 +317,7 @@ export class RiotJobQueueService { }; await Promise.all([ this.setStatus(next), - this.garnetService.delete(this.dedupKey(job.puuid, job.queueGroup)), + this.redisService.delete(this.dedupKey(job.puuid, job.queueGroup)), ]); return this.toEvent(next); } @@ -400,7 +400,7 @@ export class RiotJobQueueService { } private async appendJob(job: RiotRefreshSubJob | PollTournamentResultJob) { - await this.garnetService.appendStream( + await this.redisService.appendStream( this.resolveStream(job.priority), { job: JSON.stringify(job) }, { maxLen: 10_000 }, @@ -411,7 +411,7 @@ export class RiotJobQueueService { job: PollTournamentResultJob, deferUntilMs: number, ): Promise { - await this.garnetService.raw().sendCommand([ + await this.redisService.raw().sendCommand([ 'ZADD', RIOT_JOB_SCHEDULED_ZSET, String(deferUntilMs), @@ -442,7 +442,7 @@ export class RiotJobQueueService { } private async setStatus(status: RiotJobStatus): Promise { - await this.garnetService.setJson( + await this.redisService.setJson( this.statusKey(status.jobId), status, RIOT_JOB_STATUS_TTL_SECONDS, @@ -450,7 +450,7 @@ export class RiotJobQueueService { } private async setParent(parentJobId: string, jobIds: string[]): Promise { - await this.garnetService.setJson( + await this.redisService.setJson( this.parentKey(parentJobId), jobIds, RIOT_JOB_STATUS_TTL_SECONDS, diff --git a/apps/api/src/modules/riot-job-queue/riot-job-worker.service.spec.ts b/apps/api/src/modules/riot-job-queue/riot-job-worker.service.spec.ts index cca7bc82..9f9c866b 100644 --- a/apps/api/src/modules/riot-job-queue/riot-job-worker.service.spec.ts +++ b/apps/api/src/modules/riot-job-queue/riot-job-worker.service.spec.ts @@ -1,6 +1,7 @@ import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; -import { GarnetService } from '../global/garnet/garnet.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'; import { RiotRecentMatchesService } from '../riot/riot-recent-matches.service'; @@ -15,10 +16,20 @@ function execResult(value: T) { } function makeWorker() { - const garnetService = { + const redisService = { acknowledgeStream: jest.fn().mockResolvedValue(undefined), deleteStreamEntries: jest.fn().mockResolvedValue(undefined), - } as unknown as jest.Mocked; + } as unknown as jest.Mocked; + const distributedLockService = { + runWithRenewedLock: jest.fn().mockImplementation(async (options, operation) => + operation({ + lockKey: options.lockKey, + lockOwnershipToken: 'lock-owner', + lockExpirationDurationMilliseconds: + options.lockExpirationDurationMilliseconds, + }), + ), + } as unknown as jest.Mocked; const jobQueueService = { markProcessing: jest.fn().mockResolvedValue(undefined), markCompleted: jest.fn().mockResolvedValue({ @@ -53,7 +64,8 @@ function makeWorker() { } as unknown as jest.Mocked; const worker = new RiotJobWorkerService( - garnetService, + redisService, + distributedLockService, jobQueueService, recentMatchesService, connectionService, @@ -65,7 +77,8 @@ function makeWorker() { return { worker, - garnetService, + redisService, + distributedLockService, jobQueueService, recentMatchesService, connectionService, @@ -76,7 +89,7 @@ function makeWorker() { describe('RiotJobWorkerService', () => { it('acknowledges and deletes invalid stream entries', async () => { - const { worker, garnetService } = makeWorker(); + const { worker, redisService } = makeWorker(); await ( worker as unknown as { @@ -90,19 +103,19 @@ describe('RiotJobWorkerService', () => { message: { job: 'not-json' }, }); - expect(garnetService.acknowledgeStream).toHaveBeenCalledWith( + expect(redisService.acknowledgeStream).toHaveBeenCalledWith( 'riot:queue:high', RIOT_JOB_GROUP, 'bad-1', ); - expect(garnetService.deleteStreamEntries).toHaveBeenCalledWith( + expect(redisService.deleteStreamEntries).toHaveBeenCalledWith( 'riot:queue:high', 'bad-1', ); }); it('refreshes league entries while processing user history refresh jobs', async () => { - const { worker, enrichmentService, recentMatchesService, garnetService } = + const { worker, enrichmentService, recentMatchesService, redisService } = makeWorker(); const userId = new mongoose.Types.ObjectId().toString(); const job: RiotRefreshSubJob = { @@ -136,19 +149,52 @@ describe('RiotJobWorkerService', () => { puuid: 'puuid-1', platform: 'kr', }); - expect(garnetService.acknowledgeStream).toHaveBeenCalledWith( + expect(redisService.acknowledgeStream).toHaveBeenCalledWith( 'riot:queue:high', RIOT_JOB_GROUP, '1-0', ); - expect(garnetService.deleteStreamEntries).toHaveBeenCalledWith( + expect(redisService.deleteStreamEntries).toHaveBeenCalledWith( 'riot:queue:high', '1-0', ); expect( - garnetService.acknowledgeStream.mock.invocationCallOrder[0], + redisService.acknowledgeStream.mock.invocationCallOrder[0], ).toBeLessThan( - garnetService.deleteStreamEntries.mock.invocationCallOrder[0], + 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 }, + ) => Promise; + } + ).processEntry('riot:queue:high', { + id: '1-0', + message: { job: JSON.stringify(job) }, + }); + + expect(redisService.acknowledgeStream).not.toHaveBeenCalled(); + expect(redisService.deleteStreamEntries).not.toHaveBeenCalled(); + }); }); diff --git a/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts b/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts index 8ed9ebc6..02185c56 100644 --- a/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts +++ b/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts @@ -6,7 +6,11 @@ import { } from '@nestjs/common'; import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; -import { GarnetService, StreamEntry } from '../global/garnet/garnet.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'; import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service'; @@ -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 garnetService: GarnetService, + 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 { @@ -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 { 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); } } @@ -145,7 +192,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy { stream: string, id: string, ): Promise { - await this.garnetService.acknowledgeStream(stream, RIOT_JOB_GROUP, id); + await this.redisService.acknowledgeStream(stream, RIOT_JOB_GROUP, id); await this.deleteAcknowledgedEntry(stream, id); } @@ -154,7 +201,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy { id: string, ): Promise { try { - await this.garnetService.deleteStreamEntries(stream, id); + await this.redisService.deleteStreamEntries(stream, id); } catch (error) { this.logger.warn( `Failed to delete acknowledged Riot job stream entry ${stream} ${id}: ${ @@ -226,22 +273,37 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy { stream: string, blockMs: number, ): Promise<{ stream: string; message: StreamEntry } | null> { - const result = await this.garnetService.readGroup( + 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 { await Promise.all( [RIOT_JOB_HIGH_STREAM, RIOT_JOB_LOW_STREAM].map(async (stream) => { try { - await this.garnetService.createConsumerGroup(stream, RIOT_JOB_GROUP); + await this.redisService.createConsumerGroup(stream, RIOT_JOB_GROUP); } catch (error) { const message = error instanceof Error ? error.message : String(error); @@ -252,21 +314,26 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy { } private async tryBecomeLeader(): Promise { - const current = await this.garnetService.getString(LEADER_KEY); - if (current === this.consumer) { - await this.garnetService.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.garnetService.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 { diff --git a/apps/api/src/modules/riot/riot-ddragon.service.spec.ts b/apps/api/src/modules/riot/riot-ddragon.service.spec.ts new file mode 100644 index 00000000..be6e3c7a --- /dev/null +++ b/apps/api/src/modules/riot/riot-ddragon.service.spec.ts @@ -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; +} + +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: '커서 방향으로 순간이동합니다.', + }, + }, + }); + } + 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: + '기본 공격으로 적을 약화시킵니다.', + }, + ], + }, + ], + }, + ]); + } + if (url.endsWith('/item.json')) { + return jsonResponse({ + data: { + '1055': { + name: '도란의 검', + description: + '공격력 10', + 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: '커서 방향으로 순간이동합니다.', + }, + }, + runesReforged: [ + { + id: 8000, + name: '정밀', + slots: [ + { + runes: [ + { + id: 8005, + name: '집중 공격', + shortDesc: '연속 공격 시 추가 피해', + longDesc: + '기본 공격으로 적을 약화시킵니다.', + }, + ], + }, + ], + }, + ], + items: { + '1055': { + name: '도란의 검', + description: + '공격력 10', + 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, + ); + }); +}); diff --git a/apps/api/src/modules/riot/riot-ddragon.service.ts b/apps/api/src/modules/riot/riot-ddragon.service.ts index a66d65fb..cff9ab2c 100644 --- a/apps/api/src/modules/riot/riot-ddragon.service.ts +++ b/apps/api/src/modules/riot/riot-ddragon.service.ts @@ -1,11 +1,11 @@ import { Injectable, Logger } from '@nestjs/common'; -import { GarnetService } from '../global/garnet/garnet.service'; +import { RedisService } from '../global/redis/redis.service'; 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; summonerSpells: Record; runesReforged: DdragonRuneStyleEntry[]; + items: Record; fetchedAt: string; } @@ -53,6 +70,8 @@ interface SummonerSpellDataEntry { key: string; id: string; name: string; + description?: string; + tooltip?: string; } interface SummonerSpellDataResponse { @@ -64,24 +83,42 @@ 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; +} + @Injectable() export class RiotDdragonService { private readonly logger = new Logger(RiotDdragonService.name); private inflight = new Map>(); - constructor(private readonly garnetService: GarnetService) {} + constructor(private readonly redisService: RedisService) {} public async getManifest(locale: string = DEFAULT_LOCALE): Promise { const normalizedLocale = normalizeLocale(locale); const cacheKey = manifestCacheKey(normalizedLocale); - const cached = await this.garnetService.getJson(cacheKey); + const cached = await this.redisService.getJson(cacheKey); if (cached) return cached; const pending = this.inflight.get(cacheKey); @@ -89,7 +126,7 @@ export class RiotDdragonService { const promise = this.buildManifest(normalizedLocale) .then(async (manifest) => { - await this.garnetService.setJson(cacheKey, manifest, CACHE_TTL_SECONDS); + await this.redisService.setJson(cacheKey, manifest, CACHE_TTL_SECONDS); return manifest; }) .finally(() => { @@ -102,10 +139,11 @@ export class RiotDdragonService { private async buildManifest(locale: string): Promise { 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> { + const url = `${DDRAGON_CDN}/${version}/data/${locale}/item.json`; + const payload = await this.fetchJson(url); + if (!payload || typeof payload !== 'object' || !payload.data) { + throw new Error(`ddragon item.json response is malformed (${url}).`); + } + + const map: Record = {}; + 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(url: string): Promise { 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}`; } diff --git a/apps/api/src/modules/riot/riot-match.service.spec.ts b/apps/api/src/modules/riot/riot-match.service.spec.ts index 6aef710b..84475301 100644 --- a/apps/api/src/modules/riot/riot-match.service.spec.ts +++ b/apps/api/src/modules/riot/riot-match.service.spec.ts @@ -106,4 +106,160 @@ describe('RiotMatchService', () => { expect(match.info.participants[0].teamPosition).toBe(''); expect(match.info.participants[0].individualPosition).toBe(''); }); + + it('fetches and parses match timeline frames', async () => { + const payload = { + metadata: { + dataVersion: '2', + matchId: 'KR_8188913502', + participants: ['puuid-1'], + }, + info: { + frameInterval: 60_000, + gameId: 8188913502, + participants: [{ participantId: 1, puuid: 'puuid-1' }], + frames: [ + { + timestamp: 60_000, + events: [ + { + type: 'ELITE_MONSTER_KILL', + timestamp: 30_000, + killerTeamId: 100, + monsterType: 'DRAGON', + monsterSubType: 'ELDER_DRAGON', + }, + { + type: 'ITEM_PURCHASED', + timestamp: 40_000, + participantId: 1, + itemId: 1054, + }, + { + type: 'ITEM_UNDO', + timestamp: 45_000, + participantId: 1, + beforeId: 1054, + afterId: 3071, + }, + { + type: 'SKILL_LEVEL_UP', + timestamp: 50_000, + participantId: 1, + skillSlot: 3, + levelUpType: 'NORMAL', + }, + ], + participantFrames: { + '1': { + currentGold: 650, + jungleMinionsKilled: 0, + level: 2, + minionsKilled: 6, + participantId: 1, + totalGold: 1_150, + xp: 550, + }, + }, + }, + ], + }, + }; + const riotClientService = { + get: jest.fn( + async ( + _path: string, + _options: unknown, + parser?: RiotResponseParser, + ) => (parser ? parser(payload) : (payload as T)), + ), + } as unknown as RiotClientService; + const service = new RiotMatchService(riotClientService); + + const timeline = await service.getMatchTimeline('KR_8188913502', { + region: 'asia', + }); + + expect(riotClientService.get).toHaveBeenCalledWith( + '/lol/match/v5/matches/KR_8188913502/timeline', + expect.objectContaining({ region: 'asia' }), + expect.any(Function), + ); + expect(timeline.info.frames[0].participantFrames['1']).toMatchObject({ + participantId: 1, + totalGold: 1_150, + xp: 550, + }); + expect(timeline.info.frames[0].events[0]).toMatchObject({ + type: 'ELITE_MONSTER_KILL', + killerTeamId: 100, + monsterType: 'DRAGON', + monsterSubType: 'ELDER_DRAGON', + }); + expect(timeline.info.frames[0].events[1]).toMatchObject({ + type: 'ITEM_PURCHASED', + participantId: 1, + itemId: 1054, + }); + expect(timeline.info.frames[0].events[2]).toMatchObject({ + type: 'ITEM_UNDO', + participantId: 1, + beforeId: 1054, + afterId: 3071, + }); + expect(timeline.info.frames[0].events[3]).toMatchObject({ + type: 'SKILL_LEVEL_UP', + participantId: 1, + skillSlot: 3, + levelUpType: 'NORMAL', + }); + }); + + it('rejects non-numeric champion kill victim ids', async () => { + const payload = { + metadata: { + dataVersion: '2', + matchId: 'KR_8188913502', + participants: ['puuid-1'], + }, + info: { + frameInterval: 60_000, + frames: [ + { + timestamp: 60_000, + events: [ + { + type: 'CHAMPION_KILL', + timestamp: 30_000, + killerId: 1, + victimId: '2', + }, + ], + participantFrames: { + '1': { + participantId: 1, + totalGold: 1_150, + xp: 550, + }, + }, + }, + ], + }, + }; + const riotClientService = { + get: jest.fn( + (_path: string, _options: unknown, parser?: RiotResponseParser) => + Promise.resolve().then(() => + parser ? parser(payload) : (payload as T), + ), + ), + } as unknown as RiotClientService; + const service = new RiotMatchService(riotClientService); + + await expect( + service.getMatchTimeline('KR_8188913502', { region: 'asia' }), + ).rejects.toThrow( + 'timeline.info.frames[0].events[0].victimId must be a finite number when present.', + ); + }); }); diff --git a/apps/api/src/modules/riot/riot-match.service.ts b/apps/api/src/modules/riot/riot-match.service.ts index 33aaeb86..7dfb0020 100644 --- a/apps/api/src/modules/riot/riot-match.service.ts +++ b/apps/api/src/modules/riot/riot-match.service.ts @@ -15,6 +15,12 @@ import { RiotMatchPerkStyleSelectionDto, RiotMatchStatPerksDto, RiotMatchTeamDto, + RiotMatchTimelineDto, + RiotMatchTimelineEventDto, + RiotMatchTimelineFrameDto, + RiotMatchTimelineInfoDto, + RiotMatchTimelineParticipantDto, + RiotMatchTimelineParticipantFrameDto, RiotMatchType, } from './riot.types'; @@ -66,6 +72,20 @@ export class RiotMatchService { parseMatchResponse, ); } + + public async getMatchTimeline( + matchId: string, + options: RiotMatchLookupOptions = {}, + ): Promise { + return this.riotClientService.get( + `/lol/match/v5/matches/${encodeURIComponent(matchId)}/timeline`, + { + region: options.region, + signal: options.signal, + }, + parseMatchTimelineResponse, + ); + } } function validateMatchIdsLookupOptions( @@ -115,6 +135,48 @@ function parseMatchResponse(value: unknown): RiotMatchDto { }; } +function parseMatchTimelineResponse(value: unknown): RiotMatchTimelineDto { + if (!isRecord(value)) { + throw new TypeError('Riot match timeline response must be an object.'); + } + + return { + metadata: parseMatchMetadata(value.metadata), + info: parseMatchTimelineInfo(value.info), + }; +} + +function parseMatchTimelineInfo(value: unknown): RiotMatchTimelineInfoDto { + if (!isRecord(value)) { + throw new TypeError('Riot match timeline info must be an object.'); + } + + const frames = value.frames; + if (!Array.isArray(frames)) { + throw new TypeError('Riot match timeline info.frames must be an array.'); + } + + const participants = value.participants; + if (participants !== undefined && !Array.isArray(participants)) { + throw new TypeError( + 'Riot match timeline info.participants must be an array when present.', + ); + } + + return { + ...value, + frameInterval: requireNumber( + value.frameInterval, + 'timeline.info.frameInterval', + ), + frames: frames.map((frame, index) => parseTimelineFrame(frame, index)), + gameId: optionalNumber(value.gameId, 'timeline.info.gameId'), + participants: participants?.map((participant, index) => + parseTimelineParticipant(participant, index), + ), + }; +} + function parseMatchMetadata(value: unknown): RiotMatchMetadataDto { if (!isRecord(value)) { throw new TypeError('Riot match metadata must be an object.'); @@ -211,6 +273,199 @@ function parseMatchInfo(value: unknown): RiotMatchInfoDto { }; } +function parseTimelineParticipant( + value: unknown, + index: number, +): RiotMatchTimelineParticipantDto { + if (!isRecord(value)) { + throw new TypeError(`timeline.info.participants[${index}] must be an object.`); + } + + return { + ...value, + participantId: requireNumber( + value.participantId, + `timeline.info.participants[${index}].participantId`, + ), + puuid: requireString(value.puuid, `timeline.info.participants[${index}].puuid`), + }; +} + +function parseTimelineFrame( + value: unknown, + index: number, +): RiotMatchTimelineFrameDto { + if (!isRecord(value)) { + throw new TypeError(`timeline.info.frames[${index}] must be an object.`); + } + + const participantFrames = value.participantFrames; + if (!isRecord(participantFrames)) { + throw new TypeError( + `timeline.info.frames[${index}].participantFrames must be an object.`, + ); + } + const events = value.events; + if (events !== undefined && !Array.isArray(events)) { + throw new TypeError( + `timeline.info.frames[${index}].events must be an array when present.`, + ); + } + + return { + ...value, + events: (events ?? []).map((event, eventIndex) => + parseTimelineEvent(event, index, eventIndex), + ), + timestamp: requireNumber( + value.timestamp, + `timeline.info.frames[${index}].timestamp`, + ), + participantFrames: Object.fromEntries( + Object.entries(participantFrames).map(([key, participantFrame]) => [ + key, + parseTimelineParticipantFrame(participantFrame, index, key), + ]), + ), + }; +} + +function parseTimelineEvent( + value: unknown, + frameIndex: number, + eventIndex: number, +): RiotMatchTimelineEventDto { + if (!isRecord(value)) { + throw new TypeError( + `timeline.info.frames[${frameIndex}].events[${eventIndex}] must be an object.`, + ); + } + + const assistingParticipantIds = value.assistingParticipantIds; + if ( + assistingParticipantIds !== undefined && + (!Array.isArray(assistingParticipantIds) || + !assistingParticipantIds.every(isFiniteNumber)) + ) { + throw new TypeError( + `timeline.info.frames[${frameIndex}].events[${eventIndex}].assistingParticipantIds must be an array of numbers when present.`, + ); + } + + return { + ...value, + afterId: optionalNumber( + value.afterId, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].afterId`, + ), + assistingParticipantIds, + beforeId: optionalNumber( + value.beforeId, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].beforeId`, + ), + buildingType: optionalString( + value.buildingType, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].buildingType`, + ), + itemId: optionalNumber( + value.itemId, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].itemId`, + ), + killerId: optionalNumber( + value.killerId, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].killerId`, + ), + killerTeamId: optionalNumber( + value.killerTeamId, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].killerTeamId`, + ), + levelUpType: optionalString( + value.levelUpType, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].levelUpType`, + ), + monsterSubType: optionalString( + value.monsterSubType, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].monsterSubType`, + ), + monsterType: optionalString( + value.monsterType, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].monsterType`, + ), + participantId: optionalNumber( + value.participantId, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].participantId`, + ), + skillSlot: optionalNumber( + value.skillSlot, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].skillSlot`, + ), + teamId: optionalNumber( + value.teamId, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].teamId`, + ), + timestamp: requireNumber( + value.timestamp, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].timestamp`, + ), + towerType: optionalString( + value.towerType, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].towerType`, + ), + type: requireString( + value.type, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].type`, + ), + victimId: optionalNumber( + value.victimId, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].victimId`, + ), + }; +} + +function parseTimelineParticipantFrame( + value: unknown, + frameIndex: number, + key: string, +): RiotMatchTimelineParticipantFrameDto { + if (!isRecord(value)) { + throw new TypeError( + `timeline.info.frames[${frameIndex}].participantFrames.${key} must be an object.`, + ); + } + + return { + ...value, + currentGold: optionalNumber( + value.currentGold, + `timeline.info.frames[${frameIndex}].participantFrames.${key}.currentGold`, + ), + jungleMinionsKilled: optionalNumber( + value.jungleMinionsKilled, + `timeline.info.frames[${frameIndex}].participantFrames.${key}.jungleMinionsKilled`, + ), + level: optionalNumber( + value.level, + `timeline.info.frames[${frameIndex}].participantFrames.${key}.level`, + ), + minionsKilled: optionalNumber( + value.minionsKilled, + `timeline.info.frames[${frameIndex}].participantFrames.${key}.minionsKilled`, + ), + participantId: requireNumber( + value.participantId, + `timeline.info.frames[${frameIndex}].participantFrames.${key}.participantId`, + ), + totalGold: requireNumber( + value.totalGold, + `timeline.info.frames[${frameIndex}].participantFrames.${key}.totalGold`, + ), + xp: requireNumber( + value.xp, + `timeline.info.frames[${frameIndex}].participantFrames.${key}.xp`, + ), + }; +} + function parseParticipant( value: unknown, index: number, @@ -504,12 +759,22 @@ function parseObjectives( baron: parseObjective(value.baron, teamIndex, 'baron'), champion: parseObjective(value.champion, teamIndex, 'champion'), dragon: parseObjective(value.dragon, teamIndex, 'dragon'), + horde: optionalObjective(value.horde, teamIndex, 'horde'), inhibitor: parseObjective(value.inhibitor, teamIndex, 'inhibitor'), riftHerald: parseObjective(value.riftHerald, teamIndex, 'riftHerald'), tower: parseObjective(value.tower, teamIndex, 'tower'), }; } +function optionalObjective( + value: unknown, + teamIndex: number, + key: keyof RiotMatchObjectivesDto, +): RiotMatchObjectiveDto | undefined { + if (value === undefined || value === null) return undefined; + return parseObjective(value, teamIndex, key); +} + function parseObjective( value: unknown, teamIndex: number, diff --git a/apps/api/src/modules/riot/riot-rate-limiter.service.spec.ts b/apps/api/src/modules/riot/riot-rate-limiter.service.spec.ts index 67023ba6..d753bb98 100644 --- a/apps/api/src/modules/riot/riot-rate-limiter.service.spec.ts +++ b/apps/api/src/modules/riot/riot-rate-limiter.service.spec.ts @@ -1,15 +1,15 @@ -import { GarnetService } from '../global/garnet/garnet.service'; +import { RedisService } from '../global/redis/redis.service'; import { RiotRateLimiterService } from './riot-rate-limiter.service'; function makeService(sendCommand = jest.fn().mockResolvedValue(0)) { - const garnet = { + const redis = { getString: jest.fn().mockResolvedValue(null), raw: jest.fn().mockReturnValue({ sendCommand }), setString: jest.fn().mockResolvedValue(undefined), - } as unknown as jest.Mocked; + } as unknown as jest.Mocked; return { - service: new RiotRateLimiterService(garnet), - garnet, + service: new RiotRateLimiterService(redis), + redis, sendCommand, }; } @@ -51,12 +51,12 @@ describe('RiotRateLimiterService', () => { it('records the 120 second app rate observation from Riot headers', async () => { jest.spyOn(Date, 'now').mockReturnValue(1_000_000); - const { service, garnet } = makeService(); + const { service, redis } = makeService(); await service.recordAppRateLimitObservation('47:120,3:1', '100:120,20:1'); - expect(garnet.setString).toHaveBeenCalledTimes(1); - const [key, raw, ttl] = garnet.setString.mock.calls[0]; + expect(redis.setString).toHaveBeenCalledTimes(1); + const [key, raw, ttl] = redis.setString.mock.calls[0]; expect(key).toBe('riot:app:rl:observed'); expect(ttl).toBe(300); expect(JSON.parse(raw)).toEqual({ @@ -68,10 +68,10 @@ describe('RiotRateLimiterService', () => { }); it('resets the inferred window when Riot count decreases or observation is stale', async () => { - const { service, garnet } = makeService(); + const { service, redis } = makeService(); jest.spyOn(Date, 'now').mockReturnValue(1_060_000); - garnet.getString.mockResolvedValueOnce( + redis.getString.mockResolvedValueOnce( observedState({ count120: 80, observedAt: 1_050_000, @@ -81,13 +81,13 @@ describe('RiotRateLimiterService', () => { await service.recordAppRateLimitObservation('2:120', null); - expect(JSON.parse(garnet.setString.mock.calls[0][1])).toMatchObject({ + expect(JSON.parse(redis.setString.mock.calls[0][1])).toMatchObject({ count120: 2, windowStartAt: 1_060_000, }); jest.spyOn(Date, 'now').mockReturnValue(1_240_000); - garnet.getString.mockResolvedValueOnce( + redis.getString.mockResolvedValueOnce( observedState({ count120: 20, observedAt: 1_120_000, @@ -97,18 +97,18 @@ describe('RiotRateLimiterService', () => { await service.recordAppRateLimitObservation('25:120', null); - expect(JSON.parse(garnet.setString.mock.calls[1][1])).toMatchObject({ + expect(JSON.parse(redis.setString.mock.calls[1][1])).toMatchObject({ count120: 25, windowStartAt: 1_240_000, }); }); it('opens the refresh gate when there is no active observation', async () => { - const { service, garnet } = makeService(); + const { service, redis } = makeService(); await expect(service.isRefreshWindowOpen(0.5)).resolves.toBe(true); - garnet.getString.mockResolvedValueOnce( + redis.getString.mockResolvedValueOnce( observedState({ count120: 90, observedAt: 1_000_000, @@ -129,8 +129,8 @@ describe('RiotRateLimiterService', () => { 'checks tail headroom for refresh gate ratio=$ratio count=$count120', async ({ ratio, count120, expected }) => { jest.spyOn(Date, 'now').mockReturnValue(1_070_000); - const { service, garnet } = makeService(); - garnet.getString.mockResolvedValue( + const { service, redis } = makeService(); + redis.getString.mockResolvedValue( observedState({ count120, observedAt: 1_069_000, @@ -144,8 +144,8 @@ describe('RiotRateLimiterService', () => { it('keeps the refresh gate closed before the 120 second window tail', async () => { jest.spyOn(Date, 'now').mockReturnValue(1_050_000); - const { service, garnet } = makeService(); - garnet.getString.mockResolvedValue( + const { service, redis } = makeService(); + redis.getString.mockResolvedValue( observedState({ count120: 10, observedAt: 1_049_000, diff --git a/apps/api/src/modules/riot/riot-rate-limiter.service.ts b/apps/api/src/modules/riot/riot-rate-limiter.service.ts index a7d39e99..6b1f8f12 100644 --- a/apps/api/src/modules/riot/riot-rate-limiter.service.ts +++ b/apps/api/src/modules/riot/riot-rate-limiter.service.ts @@ -1,6 +1,6 @@ import { Injectable, Logger } from '@nestjs/common'; import type { RiotPlatformRoute, RiotRegionalRoute } from './riot.types'; -import { GarnetService } from '../global/garnet/garnet.service'; +import { RedisService } from '../global/redis/redis.service'; const APP_LIMITS = [ { windowMs: 1_000, max: 15 }, @@ -85,7 +85,7 @@ return 0 export class RiotRateLimiterService { private readonly logger = new Logger(RiotRateLimiterService.name); - constructor(private readonly garnet: GarnetService) {} + constructor(private readonly redis: RedisService) {} public async acquire( route: RiotRegionalRoute | RiotPlatformRoute, @@ -133,7 +133,7 @@ export class RiotRateLimiterService { // Concurrent responses can race here. This observation is advisory, so // last-writer-wins is acceptable and self-corrects on the next Riot header. - await this.garnet.setString( + await this.redis.setString( APP_OBSERVED_KEY, JSON.stringify(observation), APP_OBSERVED_TTL_SECONDS, @@ -167,7 +167,7 @@ export class RiotRateLimiterService { now: number, cost: number, ): Promise { - const client = this.garnet.raw(); + const client = this.redis.raw(); const member = `${process.pid}:${now}:${Math.random().toString(36).slice(2)}`; const argumentsList = [ String(now), @@ -190,7 +190,7 @@ export class RiotRateLimiterService { } private async getAppRateObservation(): Promise { - const raw = await this.garnet.getString(APP_OBSERVED_KEY); + const raw = await this.redis.getString(APP_OBSERVED_KEY); if (!raw) return null; try { diff --git a/apps/api/src/modules/riot/riot-recent-matches.service.ts b/apps/api/src/modules/riot/riot-recent-matches.service.ts index 704550e9..9dd6112e 100644 --- a/apps/api/src/modules/riot/riot-recent-matches.service.ts +++ b/apps/api/src/modules/riot/riot-recent-matches.service.ts @@ -4,14 +4,14 @@ import type { RiotMatch as StoredRiotMatch, } from '../global/database/schema'; import { ConnectionService } from '../global/database/connection.service'; -import { GarnetService } from '../global/garnet/garnet.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 garnetService: GarnetService, + 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.garnetService.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 = { - 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, - 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.garnetService.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 = { + 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, + 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: { diff --git a/apps/api/src/modules/riot/riot.types.ts b/apps/api/src/modules/riot/riot.types.ts index fa890349..7119c6a3 100644 --- a/apps/api/src/modules/riot/riot.types.ts +++ b/apps/api/src/modules/riot/riot.types.ts @@ -134,6 +134,11 @@ export interface RiotMatchDto { info: RiotMatchInfoDto; } +export interface RiotMatchTimelineDto { + metadata: RiotMatchMetadataDto; + info: RiotMatchTimelineInfoDto; +} + export interface RiotMatchMetadataDto { dataVersion: string; matchId: string; @@ -240,6 +245,7 @@ export interface RiotMatchObjectivesDto { baron: RiotMatchObjectiveDto; champion: RiotMatchObjectiveDto; dragon: RiotMatchObjectiveDto; + horde?: RiotMatchObjectiveDto; inhibitor: RiotMatchObjectiveDto; riftHerald: RiotMatchObjectiveDto; tower: RiotMatchObjectiveDto; @@ -249,3 +255,52 @@ export interface RiotMatchObjectiveDto { first: boolean; kills: number; } + +export interface RiotMatchTimelineInfoDto extends Record { + frameInterval: number; + frames: RiotMatchTimelineFrameDto[]; + gameId?: number; + participants?: RiotMatchTimelineParticipantDto[]; +} + +export interface RiotMatchTimelineParticipantDto extends Record { + participantId: number; + puuid: string; +} + +export interface RiotMatchTimelineFrameDto extends Record { + timestamp: number; + events: RiotMatchTimelineEventDto[]; + participantFrames: Record; +} + +export interface RiotMatchTimelineEventDto extends Record { + type: string; + timestamp: number; + afterId?: number; + assistingParticipantIds?: number[]; + beforeId?: number; + buildingType?: string; + itemId?: number; + killerId?: number; + killerTeamId?: number; + levelUpType?: string; + monsterSubType?: string; + monsterType?: string; + participantId?: number; + skillSlot?: number; + teamId?: number; + towerType?: string; + victimId?: number; +} + +export interface RiotMatchTimelineParticipantFrameDto + extends Record { + participantId: number; + totalGold: number; + xp: number; + currentGold?: number; + jungleMinionsKilled?: number; + level?: number; + minionsKilled?: number; +} diff --git a/apps/api/src/modules/tournament-code/round-robin.util.spec.ts b/apps/api/src/modules/tournament-code/round-robin.util.spec.ts index 77691089..50705065 100644 --- a/apps/api/src/modules/tournament-code/round-robin.util.spec.ts +++ b/apps/api/src/modules/tournament-code/round-robin.util.spec.ts @@ -1,5 +1,6 @@ import { resolveRoundRobinTeamCount, + roundRobinGameSchedule, roundRobinPairCount, roundRobinPairs, shuffleInPlace, @@ -25,6 +26,30 @@ describe('round-robin util', () => { expect(roundRobinPairCount(6)).toBe(15); }); + it('builds round-robin games grouped into simultaneously playable rounds', () => { + const schedule = roundRobinGameSchedule(6, { gamesPerPair: 1 }); + + expect(schedule).toHaveLength(15); + for (const roundNumber of [1, 2, 3, 4, 5]) { + const round = schedule.filter((game) => game.roundNumber === roundNumber); + expect(round).toHaveLength(3); + expect(new Set(round.flatMap((game) => [game.teamAIndex, game.teamBIndex]))) + .toHaveProperty('size', 6); + } + }); + + it('limits round-robin games by max rounds', () => { + const schedule = roundRobinGameSchedule(8, { + gamesPerPair: 1, + maxRounds: 3, + }); + + expect(schedule).toHaveLength(12); + expect(new Set(schedule.map((game) => game.roundNumber))).toEqual( + new Set([1, 2, 3]), + ); + }); + it('resolves team count from teams first, then active participants', () => { expect( resolveRoundRobinTeamCount({ diff --git a/apps/api/src/modules/tournament-code/round-robin.util.ts b/apps/api/src/modules/tournament-code/round-robin.util.ts index 4d928f50..3068fd7a 100644 --- a/apps/api/src/modules/tournament-code/round-robin.util.ts +++ b/apps/api/src/modules/tournament-code/round-robin.util.ts @@ -3,11 +3,23 @@ export interface RoundRobinPair { teamBIndex: number; } +export interface RoundRobinGameAssignment extends RoundRobinPair { + gameNumber: number; + roundNumber: number; +} + export interface RoundRobinTeamCountInput { teams?: Array<{ teamIndex: number }>; participants: Array<{ excluded?: boolean }>; } +export interface RoundRobinGameScheduleOptions { + gamesPerPair?: number; + maxRounds?: number; + rng?: () => number; + shuffleTeams?: boolean; +} + export function roundRobinPairs(teamCount: number): RoundRobinPair[] { const pairs: RoundRobinPair[] = []; for (let teamAIndex = 1; teamAIndex <= teamCount; teamAIndex += 1) { @@ -27,6 +39,70 @@ export function roundRobinPairCount(teamCount: number): number { return (teamCount * (teamCount - 1)) / 2; } +export function roundRobinRoundCount(teamCount: number): number { + if (teamCount < 2) return 0; + return teamCount % 2 === 0 ? teamCount - 1 : teamCount; +} + +export function roundRobinGameSchedule( + teamCount: number, + options: RoundRobinGameScheduleOptions = {}, +): RoundRobinGameAssignment[] { + if (teamCount < 2) return []; + + const rawGamesPerPair = options.gamesPerPair ?? 1; + const gamesPerPair = Number.isFinite(rawGamesPerPair) + ? Math.max(1, Math.floor(rawGamesPerPair)) + : 1; + const fullRoundCount = roundRobinRoundCount(teamCount); + const requestedRoundCount = + typeof options.maxRounds === 'number' && Number.isFinite(options.maxRounds) + ? Math.floor(options.maxRounds) + : fullRoundCount; + const roundLimit = Math.max( + 0, + Math.min(fullRoundCount, requestedRoundCount), + ); + if (roundLimit === 0) return []; + + const bye = 0; + const teams = Array.from({ length: teamCount }, (_, index) => index + 1); + if (options.shuffleTeams) shuffleInPlace(teams, options.rng); + if (teams.length % 2 === 1) teams.push(bye); + + const rotating = [...teams]; + const schedule: RoundRobinGameAssignment[] = []; + let gameNumber = 1; + + for (let roundIndex = 0; roundIndex < roundLimit; roundIndex += 1) { + const roundNumber = 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; + + const teamAIndex = Math.min(left, right); + const teamBIndex = Math.max(left, right); + for (let gameIndex = 0; gameIndex < gamesPerPair; gameIndex += 1) { + schedule.push({ + gameNumber, + roundNumber, + teamAIndex, + teamBIndex, + }); + gameNumber += 1; + } + } + + const fixed = rotating[0]; + const tail = rotating.slice(1); + tail.unshift(tail.pop() as number); + rotating.splice(0, rotating.length, fixed, ...tail); + } + + return schedule; +} + export function resolveRoundRobinTeamCount( match: RoundRobinTeamCountInput, ): number { diff --git a/apps/api/src/modules/tournament-code/tournament-code-auto-provision.service.spec.ts b/apps/api/src/modules/tournament-code/tournament-code-auto-provision.service.spec.ts new file mode 100644 index 00000000..e840da7d --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code-auto-provision.service.spec.ts @@ -0,0 +1,111 @@ +import { + SYSTEM_TOURNAMENT_CODE_UPLOADED_BY, + TournamentCodeAutoProvisionService, +} from './tournament-code-auto-provision.service'; +import { TournamentCodeService } from './tournament-code.service'; +import { TournamentCodeVendorService } from './tournament-code-vendor.service'; + +describe('TournamentCodeAutoProvisionService', () => { + function createFixture(params?: { + availableCounts?: number[]; + vendorCodes?: string[]; + }) { + const availableCounts = [...(params?.availableCounts ?? [30])]; + const vendorCodes = [...(params?.vendorCodes ?? [])]; + const tournamentCodeService = { + countUsableAvailable: jest.fn().mockImplementation(async () => { + return availableCounts.shift() ?? 30; + }), + bulkUpload: jest.fn().mockResolvedValue({ + inserted: 1, + duplicates: [], + invalid: [], + }), + } as unknown as jest.Mocked; + const vendorService = { + fetchTournamentCode: jest.fn().mockImplementation(async () => { + const code = vendorCodes.shift(); + if (!code) throw new Error('No vendor code'); + return code; + }), + } as unknown as jest.Mocked; + const service = new TournamentCodeAutoProvisionService( + tournamentCodeService, + vendorService, + ); + jest + .spyOn( + service as unknown as { sleepBeforeVendorRequest(): Promise }, + 'sleepBeforeVendorRequest', + ) + .mockResolvedValue(undefined); + + return { service, tournamentCodeService, vendorService }; + } + + it('does nothing when the usable pool already meets the target', async () => { + const { service, tournamentCodeService, vendorService } = createFixture({ + availableCounts: [30], + }); + + await expect(service.ensurePool()).resolves.toMatchObject({ + target: 30, + before: 30, + after: 30, + requested: 0, + inserted: 0, + }); + expect(vendorService.fetchTournamentCode).not.toHaveBeenCalled(); + expect(tournamentCodeService.bulkUpload).not.toHaveBeenCalled(); + }); + + it('requests vendor codes until the pool reaches 30', async () => { + const { service, tournamentCodeService, vendorService } = createFixture({ + availableCounts: [28, 29, 30], + vendorCodes: ['KR05090-aBc', 'KR05090-dEf'], + }); + + const result = await service.ensurePool(); + + expect(result).toMatchObject({ + target: 30, + before: 28, + after: 30, + requested: 2, + inserted: 2, + }); + expect(vendorService.fetchTournamentCode).toHaveBeenCalledTimes(2); + expect( + ( + service as unknown as { + sleepBeforeVendorRequest: jest.Mock; + } + ).sleepBeforeVendorRequest, + ).toHaveBeenCalledTimes(2); + expect(tournamentCodeService.bulkUpload).toHaveBeenCalledWith({ + uploadedBy: SYSTEM_TOURNAMENT_CODE_UPLOADED_BY, + codes: [ + expect.objectContaining({ + code: 'KR05090-aBc', + source: 'deeplol-vendor', + spectatorType: 'ALL', + }), + ], + }); + }); + + it('shares an in-flight refill instead of starting overlapping vendor loops', async () => { + const { service, vendorService } = createFixture({ + availableCounts: [29, 30], + vendorCodes: ['KR05090-aBc'], + }); + + const [left, right] = await Promise.all([ + service.ensurePool(), + service.ensurePool(), + ]); + + expect(left).toBe(right); + expect(vendorService.fetchTournamentCode).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/api/src/modules/tournament-code/tournament-code-auto-provision.service.ts b/apps/api/src/modules/tournament-code/tournament-code-auto-provision.service.ts new file mode 100644 index 00000000..af304dd2 --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code-auto-provision.service.ts @@ -0,0 +1,128 @@ +import { Injectable, Logger } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from './tournament-code.constants'; +import { TournamentCodeService } from './tournament-code.service'; +import { + resolveVendorRequestDelayMs, + TournamentCodeVendorService, +} from './tournament-code-vendor.service'; + +const DEFAULT_POOL_TARGET = 30; +const DEFAULT_VENDOR_CODE_EXPIRES_IN_MS = 14 * 24 * 60 * 60 * 1000; +const MAX_REFILL_ATTEMPTS_MULTIPLIER = 2; + +export const SYSTEM_TOURNAMENT_CODE_UPLOADED_BY = new mongoose.Types.ObjectId( + '000000000000000000000000', +); + +export interface TournamentCodeAutoProvisionResult { + target: number; + before: number; + after: number; + requested: number; + inserted: number; + duplicates: number; + invalid: number; +} + +@Injectable() +export class TournamentCodeAutoProvisionService { + private readonly logger = new Logger(TournamentCodeAutoProvisionService.name); + private inFlight?: Promise; + + constructor( + private readonly tournamentCodeService: TournamentCodeService, + private readonly vendorService: TournamentCodeVendorService, + ) {} + + public async ensurePool(): Promise { + if (this.inFlight) return this.inFlight; + + this.inFlight = this.refillPool().finally(() => { + this.inFlight = undefined; + }); + return this.inFlight; + } + + public async sleepBeforeVendorRequest(): Promise { + await sleep(resolveVendorRequestDelayMs()); + } + + private async refillPool(): Promise { + const target = resolvePoolTarget(); + const before = await this.tournamentCodeService.countUsableAvailable(); + let after = before; + let requested = 0; + let inserted = 0; + let duplicates = 0; + let invalid = 0; + + const maxAttempts = Math.max( + 1, + (target - before) * MAX_REFILL_ATTEMPTS_MULTIPLIER, + ); + + while (after < target && requested < maxAttempts) { + await this.sleepBeforeVendorRequest(); + const code = await this.vendorService.fetchTournamentCode(); + requested += 1; + + const uploadResult = await this.tournamentCodeService.bulkUpload({ + uploadedBy: SYSTEM_TOURNAMENT_CODE_UPLOADED_BY, + codes: [ + { + code, + expiresAt: resolveVendorCodeExpiresAt().toISOString(), + spectatorType: 'ALL', + source: 'deeplol-vendor', + notes: 'auto-provisioned from Deeplol vendor', + }, + ], + }); + inserted += uploadResult.inserted; + duplicates += uploadResult.duplicates.length; + invalid += uploadResult.invalid.length; + after = await this.tournamentCodeService.countUsableAvailable(); + } + + if (inserted > 0 || before < target) { + this.logger.log( + `Tournament code pool refill: before=${before} after=${after} target=${target} requested=${requested} inserted=${inserted} duplicates=${duplicates} invalid=${invalid}`, + ); + } + + return { + target, + before, + after, + requested, + inserted, + duplicates, + invalid, + }; + } +} + +function resolvePoolTarget(): number { + const configured = Number(process.env.TOURNAMENT_CODE_POOL_TARGET); + return Number.isInteger(configured) && configured > 0 + ? configured + : DEFAULT_POOL_TARGET; +} + +function resolveVendorCodeExpiresAt(): Date { + const configuredHours = Number( + process.env.TOURNAMENT_CODE_VENDOR_EXPIRES_IN_HOURS, + ); + const expiresInMs = + Number.isFinite(configuredHours) && configuredHours > 0 + ? configuredHours * 60 * 60 * 1000 + : DEFAULT_VENDOR_CODE_EXPIRES_IN_MS; + return new Date( + Date.now() + Math.max(expiresInMs, TOURNAMENT_CODE_EXPIRY_MARGIN_MS), + ); +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/apps/api/src/modules/tournament-code/tournament-code-vendor.service.spec.ts b/apps/api/src/modules/tournament-code/tournament-code-vendor.service.spec.ts new file mode 100644 index 00000000..9db7e042 --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code-vendor.service.spec.ts @@ -0,0 +1,95 @@ +import { + buildDeeplolTournamentCodeRequest, + resolveVendorRequestDelayMs, + TournamentCodeVendorService, +} from './tournament-code-vendor.service'; + +describe('TournamentCodeVendorService', () => { + const originalFetch = global.fetch; + + afterEach(() => { + global.fetch = originalFetch; + jest.restoreAllMocks(); + }); + + it('builds the Deeplol request URL and browser-like headers', () => { + const request = buildDeeplolTournamentCodeRequest(); + + expect(request.url.toString()).toBe( + 'https://b2c-api.deeplol.gg/tournament/tournament_code?server_id=212&server_name=%EB%A1%A4%EB%A6%BC%ED%91%B8%EC%8A%A4&server_comment=LPS_%EB%82%B4%EC%A0%84&spectator_type=ALL&pick_type=TOURNAMENT_DRAFT&map_name=SUMMONERS_RIFT&platform_id=KR', + ); + expect(request.headers).toMatchObject({ + accept: '*/*', + 'accept-encoding': 'gzip, deflate, br, zstd', + 'accept-language': 'ko,en;q=0.9,en-US;q=0.8', + 'cache-control': 'no-cache', + host: 'b2c-api.deeplol.gg', + origin: 'https://clash.deeplol.gg', + pragma: 'no-cache', + priority: 'u=1, i', + referer: 'https://clash.deeplol.gg/', + 'sec-ch-ua': + '"Microsoft Edge";v="149", "Chromium";v="149", "Not)A;Brand";v="24"', + 'sec-ch-ua-mobile': '?0', + 'sec-ch-ua-platform': '"Windows"', + 'sec-fetch-dest': 'empty', + 'sec-fetch-mode': 'cors', + 'sec-fetch-site': 'same-site', + 'user-agent': + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36 Edg/149.0.0.0', + }); + expect(Object.keys(request.headers)).not.toContain(':authority'); + }); + + it('fetches the first tournament code from the vendor response', async () => { + global.fetch = jest.fn().mockResolvedValue({ + ok: true, + status: 200, + json: jest.fn().mockResolvedValue({ + tournament_code_list: [ + 'KR05090-85d64e26-0a7d-438b-9ada-11784e46add3', + ], + }), + }); + const service = new TournamentCodeVendorService(); + + await expect(service.fetchTournamentCode()).resolves.toBe( + 'KR05090-85d64e26-0a7d-438b-9ada-11784e46add3', + ); + expect(global.fetch).toHaveBeenCalledWith( + expect.stringContaining( + 'https://b2c-api.deeplol.gg/tournament/tournament_code?', + ), + expect.objectContaining({ + method: 'GET', + headers: expect.objectContaining({ + origin: 'https://clash.deeplol.gg', + referer: 'https://clash.deeplol.gg/', + }), + signal: expect.any(AbortSignal), + }), + ); + }); + + it('rejects malformed vendor responses', async () => { + global.fetch = jest.fn().mockResolvedValue({ + ok: true, + status: 200, + json: jest.fn().mockResolvedValue({ + tournament_code_list: [null], + }), + }); + const service = new TournamentCodeVendorService(); + + await expect(service.fetchTournamentCode()).rejects.toThrow( + 'Vendor tournament code response is malformed.', + ); + }); + + it('generates mostly near-5-second delays with occasional extra delay', () => { + expect(resolveVendorRequestDelayMs(() => 0.1)).toBe(5_050); + expect(resolveVendorRequestDelayMs(() => 0.84)).toBe(5_420); + expect(resolveVendorRequestDelayMs(() => 0.9)).toBe(8_700); + expect(resolveVendorRequestDelayMs(() => 0)).toBeGreaterThanOrEqual(5_000); + }); +}); diff --git a/apps/api/src/modules/tournament-code/tournament-code-vendor.service.ts b/apps/api/src/modules/tournament-code/tournament-code-vendor.service.ts new file mode 100644 index 00000000..8828f742 --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code-vendor.service.ts @@ -0,0 +1,152 @@ +import { Injectable } from '@nestjs/common'; + +const DEFAULT_VENDOR_URL = + 'https://b2c-api.deeplol.gg/tournament/tournament_code'; +const DEFAULT_FETCH_TIMEOUT_MS = 10_000; +const MIN_REQUEST_DELAY_MS = 5_000; + +const DEFAULT_QUERY_PARAMS = { + server_id: '212', + server_name: '롤림푸스', + server_comment: 'LPS_내전', + spectator_type: 'ALL', + pick_type: 'TOURNAMENT_DRAFT', + map_name: 'SUMMONERS_RIFT', + platform_id: 'KR', +} as const; + +const BROWSER_LIKE_HEADERS = { + accept: '*/*', + 'accept-encoding': 'gzip, deflate, br, zstd', + 'accept-language': 'ko,en;q=0.9,en-US;q=0.8', + 'cache-control': 'no-cache', + host: 'b2c-api.deeplol.gg', + origin: 'https://clash.deeplol.gg', + pragma: 'no-cache', + priority: 'u=1, i', + referer: 'https://clash.deeplol.gg/', + 'sec-ch-ua': + '"Microsoft Edge";v="149", "Chromium";v="149", "Not)A;Brand";v="24"', + 'sec-ch-ua-mobile': '?0', + 'sec-ch-ua-platform': '"Windows"', + 'sec-fetch-dest': 'empty', + 'sec-fetch-mode': 'cors', + 'sec-fetch-site': 'same-site', + 'user-agent': + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36 Edg/149.0.0.0', +} as const; + +interface DeeplolTournamentCodeResponse { + tournament_code_list?: unknown; +} + +export interface DeeplolTournamentCodeRequest { + url: URL; + headers: Record; +} + +@Injectable() +export class TournamentCodeVendorService { + public async fetchTournamentCode(): Promise { + const request = buildDeeplolTournamentCodeRequest(); + const controller = new AbortController(); + const timeout = setTimeout(() => { + controller.abort(); + }, resolveFetchTimeoutMs()); + + try { + const response = await fetch(request.url.toString(), { + method: 'GET', + headers: request.headers, + signal: controller.signal, + }); + + if (!response.ok) { + throw new Error( + `Vendor tournament code request failed (${response.status}).`, + ); + } + + const payload = (await response.json()) as DeeplolTournamentCodeResponse; + return parseVendorTournamentCode(payload); + } finally { + clearTimeout(timeout); + } + } +} + +export function buildDeeplolTournamentCodeRequest( + env: NodeJS.ProcessEnv = process.env, +): DeeplolTournamentCodeRequest { + const url = new URL( + env.TOURNAMENT_CODE_VENDOR_URL?.trim() || DEFAULT_VENDOR_URL, + ); + const params = { + server_id: + env.TOURNAMENT_CODE_VENDOR_SERVER_ID ?? DEFAULT_QUERY_PARAMS.server_id, + server_name: + env.TOURNAMENT_CODE_VENDOR_SERVER_NAME ?? + DEFAULT_QUERY_PARAMS.server_name, + server_comment: + env.TOURNAMENT_CODE_VENDOR_SERVER_COMMENT ?? + DEFAULT_QUERY_PARAMS.server_comment, + spectator_type: + env.TOURNAMENT_CODE_VENDOR_SPECTATOR_TYPE ?? + DEFAULT_QUERY_PARAMS.spectator_type, + pick_type: + env.TOURNAMENT_CODE_VENDOR_PICK_TYPE ?? DEFAULT_QUERY_PARAMS.pick_type, + map_name: + env.TOURNAMENT_CODE_VENDOR_MAP_NAME ?? DEFAULT_QUERY_PARAMS.map_name, + platform_id: + env.TOURNAMENT_CODE_VENDOR_PLATFORM_ID ?? + DEFAULT_QUERY_PARAMS.platform_id, + }; + + for (const [key, value] of Object.entries(params)) { + url.searchParams.set(key, value); + } + + return { + url, + headers: { + ...BROWSER_LIKE_HEADERS, + host: url.host, + }, + }; +} + +export function resolveVendorRequestDelayMs( + random: () => number = Math.random, +): number { + const roll = clampRandom(random()); + if (roll < 0.85) { + return MIN_REQUEST_DELAY_MS + Math.round(roll * 500); + } + return MIN_REQUEST_DELAY_MS + 100 + Math.round(roll * 4_000); +} + +function parseVendorTournamentCode( + payload: DeeplolTournamentCodeResponse, +): string { + const codes = payload.tournament_code_list; + if ( + !Array.isArray(codes) || + typeof codes[0] !== 'string' || + !codes[0].trim() + ) { + throw new Error('Vendor tournament code response is malformed.'); + } + return codes[0].trim(); +} + +function resolveFetchTimeoutMs(): number { + const configured = Number(process.env.TOURNAMENT_CODE_VENDOR_TIMEOUT_MS); + return Number.isFinite(configured) && configured > 0 + ? configured + : DEFAULT_FETCH_TIMEOUT_MS; +} + +function clampRandom(value: number): number { + if (!Number.isFinite(value)) return 0; + return Math.min(1, Math.max(0, value)); +} diff --git a/apps/api/src/modules/tournament-code/tournament-code.module.ts b/apps/api/src/modules/tournament-code/tournament-code.module.ts index f41cc726..1cad459a 100644 --- a/apps/api/src/modules/tournament-code/tournament-code.module.ts +++ b/apps/api/src/modules/tournament-code/tournament-code.module.ts @@ -1,11 +1,21 @@ 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 { TournamentCodeScheduler } from './tournament-code.scheduler'; import { TournamentCodeService } from './tournament-code.service'; +import { TournamentCodeVendorService } from './tournament-code-vendor.service'; @Module({ + imports: [TournamentResultModule, AuctionRedisModule], controllers: [TournamentCodeController], - providers: [TournamentCodeService, TournamentCodeScheduler], + providers: [ + TournamentCodeService, + TournamentCodeVendorService, + TournamentCodeAutoProvisionService, + TournamentCodeScheduler, + ], exports: [TournamentCodeService], }) export class TournamentCodeModule {} diff --git a/apps/api/src/modules/tournament-code/tournament-code.scheduler.spec.ts b/apps/api/src/modules/tournament-code/tournament-code.scheduler.spec.ts new file mode 100644 index 00000000..e12d11d4 --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code.scheduler.spec.ts @@ -0,0 +1,121 @@ +import mongoose from 'mongoose'; +import { DistributedLockService } from '../global/redis/distributed-lock.service'; +import { TournamentCodeScheduler } from './tournament-code.scheduler'; + +describe('TournamentCodeScheduler', () => { + function createScheduler(params?: { + attachedMatches?: unknown[]; + expirationResult?: { + affectedMatchIds: unknown[]; + expiredCount: number; + failedCount: number; + }; + scheduleInitialPoll?: jest.Mock; + }) { + const tournamentCodeService = { + attachPendingMatchDocuments: jest + .fn() + .mockResolvedValue(params?.attachedMatches ?? []), + markExpired: jest.fn().mockResolvedValue( + params?.expirationResult ?? { + affectedMatchIds: [], + expiredCount: 0, + failedCount: 0, + }, + ), + }; + const autoProvisionService = { + ensurePool: jest.fn().mockResolvedValue(undefined), + }; + const tournamentResultService = { + scheduleInitialPoll: + params?.scheduleInitialPoll ?? jest.fn().mockResolvedValue(null), + }; + const distributedLockService = { + runWithRenewedLock: jest + .fn() + .mockImplementation(async (options, operation) => + operation({ + lockKey: options.lockKey, + lockOwnershipToken: 'lock-owner', + lockExpirationDurationMilliseconds: + options.lockExpirationDurationMilliseconds, + }), + ), + } as unknown as jest.Mocked; + const scheduler = new TournamentCodeScheduler( + tournamentCodeService as never, + autoProvisionService as never, + tournamentResultService as never, + distributedLockService as never, + ) as unknown as { + attachPending(): Promise; + markExpired(): Promise; + }; + + return { + scheduler, + tournamentCodeService, + tournamentResultService, + distributedLockService, + }; + } + + it('starts result polling after attaching delayed tournament codes', async () => { + const attachedMatches = [{ _id: 'match-1' }, { _id: 'match-2' }]; + const { scheduler, tournamentResultService } = createScheduler({ + attachedMatches, + }); + + await scheduler.attachPending(); + + expect(tournamentResultService.scheduleInitialPoll).toHaveBeenCalledTimes( + 2, + ); + expect(tournamentResultService.scheduleInitialPoll).toHaveBeenNthCalledWith( + 1, + attachedMatches[0], + ); + expect(tournamentResultService.scheduleInitialPoll).toHaveBeenNthCalledWith( + 2, + attachedMatches[1], + ); + }); + + it('does not schedule result polling when no match received new codes', async () => { + const { scheduler, tournamentResultService } = createScheduler(); + + await scheduler.attachPending(); + + expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled(); + }); + + it('does not attach pending tournament codes when another instance owns the scheduler lock', async () => { + const { scheduler, tournamentCodeService, distributedLockService } = + createScheduler(); + distributedLockService.runWithRenewedLock.mockResolvedValueOnce(null); + + await scheduler.attachPending(); + + expect( + tournamentCodeService.attachPendingMatchDocuments, + ).not.toHaveBeenCalled(); + }); + + it('reconciles Competition assignments after expiring Match-bound codes', async () => { + const matchId = new mongoose.Types.ObjectId(); + const { scheduler, tournamentResultService } = createScheduler({ + expirationResult: { + affectedMatchIds: [matchId], + expiredCount: 1, + failedCount: 0, + }, + }); + + await scheduler.markExpired(); + + expect(tournamentResultService.scheduleInitialPoll).toHaveBeenCalledWith( + matchId, + ); + }); +}); diff --git a/apps/api/src/modules/tournament-code/tournament-code.scheduler.ts b/apps/api/src/modules/tournament-code/tournament-code.scheduler.ts index 9f73d297..16740842 100644 --- a/apps/api/src/modules/tournament-code/tournament-code.scheduler.ts +++ b/apps/api/src/modules/tournament-code/tournament-code.scheduler.ts @@ -1,39 +1,95 @@ -import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common'; +import { + Injectable, + Logger, + OnModuleDestroy, + OnModuleInit, +} from '@nestjs/common'; +import { DistributedLockService } from '../global/redis/distributed-lock.service'; +import { TournamentResultService } from '../tournament-result/tournament-result.service'; +import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service'; import { TournamentCodeService } from './tournament-code.service'; +const ATTACH_PENDING_CODES_TO_MATCHES_LOCK_KEY = + 'distributed-lock:tournament-code:scheduler:attach-pending-codes-to-matches'; +const MARK_EXPIRED_ASSIGNED_CODES_LOCK_KEY = + 'distributed-lock:tournament-code:scheduler:mark-expired-assigned-codes'; +const ENSURE_VENDOR_CODE_POOL_LOCK_KEY = + 'distributed-lock:tournament-code:scheduler:ensure-vendor-code-pool'; +const SCHEDULER_LOCK_EXPIRATION_DURATION_MILLISECONDS = 10 * 60_000; +const SCHEDULER_LOCK_RENEWAL_INTERVAL_MILLISECONDS = 2 * 60_000; + @Injectable() export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy { private readonly logger = new Logger(TournamentCodeScheduler.name); private attachTimer?: NodeJS.Timeout; private expireTimer?: NodeJS.Timeout; + private refillTimer?: NodeJS.Timeout; - constructor(private readonly tournamentCodeService: TournamentCodeService) {} + constructor( + private readonly tournamentCodeService: TournamentCodeService, + private readonly autoProvisionService: TournamentCodeAutoProvisionService, + private readonly tournamentResultService: TournamentResultService, + private readonly distributedLockService: DistributedLockService, + ) {} public onModuleInit() { this.attachTimer = setInterval(() => { void this.attachPending(); }, 30_000); - this.expireTimer = setInterval(() => { - void this.markExpired(); - }, 60 * 60 * 1000); + this.expireTimer = setInterval( + () => { + void this.markExpired(); + }, + 60 * 60 * 1000, + ); + if (isAutoProvisionEnabled()) { + this.refillTimer = setInterval( + () => { + void this.ensureVendorPool(); + }, + 5 * 60 * 1000, + ); + } this.attachTimer.unref?.(); this.expireTimer.unref?.(); + this.refillTimer?.unref?.(); void this.attachPending(); void this.markExpired(); + if (isAutoProvisionEnabled()) { + void this.ensureVendorPool(); + } } public onModuleDestroy() { if (this.attachTimer) clearInterval(this.attachTimer); if (this.expireTimer) clearInterval(this.expireTimer); + if (this.refillTimer) clearInterval(this.refillTimer); } private async attachPending() { try { - const touched = await this.tournamentCodeService.attachPendingMatches(); - if (touched > 0) { - this.logger.debug(`Attached tournament codes for ${touched} matches.`); - } + await this.distributedLockService.runWithRenewedLock( + { + lockKey: ATTACH_PENDING_CODES_TO_MATCHES_LOCK_KEY, + lockExpirationDurationMilliseconds: + SCHEDULER_LOCK_EXPIRATION_DURATION_MILLISECONDS, + lockRenewalIntervalMilliseconds: + SCHEDULER_LOCK_RENEWAL_INTERVAL_MILLISECONDS, + }, + async () => { + const matches = + await this.tournamentCodeService.attachPendingMatchDocuments(); + if (matches.length > 0) { + this.logger.debug( + `Attached tournament codes for ${matches.length} matches.`, + ); + for (const match of matches) { + await this.tournamentResultService.scheduleInitialPoll(match); + } + } + }, + ); } catch (error) { this.logger.warn( `Failed to attach pending tournament codes: ${ @@ -45,7 +101,29 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy { private async markExpired() { try { - await this.tournamentCodeService.markExpired(); + await this.distributedLockService.runWithRenewedLock( + { + lockKey: MARK_EXPIRED_ASSIGNED_CODES_LOCK_KEY, + lockExpirationDurationMilliseconds: + SCHEDULER_LOCK_EXPIRATION_DURATION_MILLISECONDS, + lockRenewalIntervalMilliseconds: + SCHEDULER_LOCK_RENEWAL_INTERVAL_MILLISECONDS, + }, + async () => { + const result = await this.tournamentCodeService.markExpired(); + for (const matchId of result.affectedMatchIds) { + try { + await this.tournamentResultService.scheduleInitialPoll(matchId); + } catch (error) { + this.logger.warn( + `Failed to reconcile Competition codes after expiring a code for Match ${matchId.toString()}: ${ + error instanceof Error ? error.message : error + }`, + ); + } + } + }, + ); } catch (error) { this.logger.warn( `Failed to mark expired tournament codes: ${ @@ -54,4 +132,33 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy { ); } } + + private async ensureVendorPool() { + try { + await this.distributedLockService.runWithRenewedLock( + { + lockKey: ENSURE_VENDOR_CODE_POOL_LOCK_KEY, + lockExpirationDurationMilliseconds: + SCHEDULER_LOCK_EXPIRATION_DURATION_MILLISECONDS, + lockRenewalIntervalMilliseconds: + SCHEDULER_LOCK_RENEWAL_INTERVAL_MILLISECONDS, + }, + async () => { + await this.autoProvisionService.ensurePool(); + }, + ); + } catch (error) { + this.logger.warn( + `Failed to auto-provision tournament codes: ${ + error instanceof Error ? error.message : error + }`, + ); + } + } +} + +function isAutoProvisionEnabled(): boolean { + const raw = + process.env.TOURNAMENT_CODE_AUTO_PROVISION_ENABLED?.trim().toLowerCase(); + return raw !== 'false' && raw !== '0' && raw !== 'off'; } diff --git a/apps/api/src/modules/tournament-code/tournament-code.service.spec.ts b/apps/api/src/modules/tournament-code/tournament-code.service.spec.ts index 0e2c03e2..49eed573 100644 --- a/apps/api/src/modules/tournament-code/tournament-code.service.spec.ts +++ b/apps/api/src/modules/tournament-code/tournament-code.service.spec.ts @@ -1,5 +1,11 @@ -import type { MatchDocument } from '../global/database/schema'; +import { + TournamentCodeSchema, + type MatchDocument, +} from '../global/database/schema'; +import { Logger } from '@nestjs/common'; +import mongoose from 'mongoose'; import { TournamentCodeService } from './tournament-code.service'; +import { buildDoubleEliminationBracket } from '../double-elimination/double-elimination.util'; type TournamentCodeServiceInternals = TournamentCodeService & { resolveRequiredSlots(match: MatchDocument): number; @@ -8,21 +14,58 @@ type TournamentCodeServiceInternals = TournamentCodeService & { gameNumber: number, ): { teamAIndex: number; teamBIndex: number }; ensureGameSchedule(match: MatchDocument): void; + attachPendingMatches(communityId?: mongoose.Types.ObjectId): Promise; }; +function createAuctionRedisService() { + return { + acquireTokenLock: jest.fn().mockResolvedValue(true), + releaseTokenLock: jest.fn().mockResolvedValue(true), + }; +} + +function createSession() { + return { + startTransaction: jest.fn(), + commitTransaction: jest.fn().mockResolvedValue(undefined), + abortTransaction: jest.fn().mockResolvedValue(undefined), + endSession: jest.fn().mockResolvedValue(undefined), + }; +} + +function mongoQuery(value: T) { + const query = { + exec: jest.fn().mockResolvedValue(value), + lean: jest.fn(), + limit: jest.fn(), + select: jest.fn(), + session: jest.fn(), + }; + query.lean.mockReturnValue(query); + query.limit.mockReturnValue(query); + query.select.mockReturnValue(query); + query.session.mockReturnValue(query); + return query; +} + function createService() { return new TournamentCodeService( {} as never, + createAuctionRedisService() as never, ) as unknown as TournamentCodeServiceInternals; } interface MatchOverrides { gameCount?: number; - gameMode?: 'pair' | 'bracket' | 'round-robin'; + gameMode?: 'pair' | 'bracket' | 'round-robin' | 'double-elimination'; + roundRobinMaxRounds?: number; participants?: Array<{ excluded?: boolean }>; teams?: Array<{ teamIndex: number }>; + doubleElimination?: MatchDocument['doubleElimination']; + tournamentCodeIds?: mongoose.Types.ObjectId[]; gameSchedule?: Array<{ gameNumber: number; + roundNumber?: number; teamAIndex: number; teamBIndex: number; }>; @@ -30,11 +73,16 @@ interface MatchOverrides { function createMatch(overrides: MatchOverrides): MatchDocument { return { + _id: new mongoose.Types.ObjectId(), + status: 'in-progress', gameCount: 1, gameMode: 'pair', participants: [], teams: [], + tournamentCodeIds: [], gameSchedule: [], + save: jest.fn().mockResolvedValue(undefined), + markModified: jest.fn(), ...overrides, } as unknown as MatchDocument; } @@ -102,15 +150,32 @@ describe('TournamentCodeService round-robin scheduling', () => { ).toBe(15); }); + it('calculates limited round-robin slots from max rounds', () => { + const service = createService(); + + expect( + service.resolveRequiredSlots( + createMatch({ + gameMode: 'round-robin', + gameCount: 1, + roundRobinMaxRounds: 3, + teams: Array.from({ length: 8 }, (_, index) => ({ + teamIndex: index + 1, + })), + }), + ), + ).toBe(12); + }); + it('uses persisted round-robin game schedule for game refs', () => { const service = createService(); const match = createMatch({ gameMode: 'round-robin', gameCount: 2, gameSchedule: [ - { gameNumber: 1, teamAIndex: 2, teamBIndex: 5 }, - { gameNumber: 2, teamAIndex: 2, teamBIndex: 5 }, - { gameNumber: 3, teamAIndex: 1, teamBIndex: 4 }, + { gameNumber: 1, roundNumber: 1, teamAIndex: 2, teamBIndex: 5 }, + { gameNumber: 2, roundNumber: 1, teamAIndex: 2, teamBIndex: 5 }, + { gameNumber: 3, roundNumber: 2, teamAIndex: 1, teamBIndex: 4 }, ], }); @@ -124,7 +189,7 @@ describe('TournamentCodeService round-robin scheduling', () => { }); }); - it('falls back to lexicographic round-robin pairs before schedule is persisted', () => { + it('falls back to round-based pairs before schedule is persisted', () => { const service = createService(); const match = createMatch({ gameMode: 'round-robin', @@ -137,10 +202,10 @@ describe('TournamentCodeService round-robin scheduling', () => { expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({ teamAIndex: 1, - teamBIndex: 2, + teamBIndex: 4, }); expect(service.resolveSeriesRefForGameNumber(match, 2)).toEqual({ - teamAIndex: 1, + teamAIndex: 2, teamBIndex: 3, }); }); @@ -173,6 +238,239 @@ describe('TournamentCodeService round-robin scheduling', () => { expect(pair.gameSchedule).toEqual([]); }); + it('creates a double-elimination bracket from built teams', () => { + const service = createService(); + const match = createMatch({ + gameMode: 'double-elimination', + gameCount: 3, + teams: Array.from({ length: 4 }, (_, index) => ({ + teamIndex: index + 1, + })), + doubleElimination: { + teamCount: 4, + resetFinalEnabled: true, + resetFinalCreated: false, + seeds: [], + bracketMatches: [], + placements: {}, + events: [], + }, + }); + + service.ensureGameSchedule(match); + + expect(match.doubleElimination?.seeds).toHaveLength(4); + expect(match.doubleElimination?.bracketMatches).toHaveLength(6); + expect( + match.doubleElimination?.bracketMatches.filter( + (bracketMatch) => bracketMatch.state === 'ready', + ), + ).toHaveLength(2); + expect( + match.doubleElimination?.bracketMatches.find( + (bracketMatch) => bracketMatch.bracketMatchId === 'WB_R1_M1', + ), + ).toMatchObject({ gameCount: 3, requiredWins: 2 }); + }); + + it('builds a missing bracket from already-persisted authoritative seeds', () => { + const service = createService(); + const match = createMatch({ + gameMode: 'double-elimination', + gameCount: 3, + teams: Array.from({ length: 4 }, (_, index) => ({ + teamIndex: index + 1, + })), + doubleElimination: { + teamCount: 4, + resetFinalEnabled: true, + resetFinalCreated: false, + seeds: [ + { seedNumber: 1, teamIndex: 3 }, + { seedNumber: 2, teamIndex: 1 }, + { seedNumber: 3, teamIndex: 4 }, + { seedNumber: 4, teamIndex: 2 }, + ], + bracketMatches: [], + placements: {}, + events: [], + }, + }); + const random = jest.spyOn(Math, 'random').mockReturnValue(0); + + service.ensureGameSchedule(match); + + expect(match.doubleElimination?.seeds).toEqual([ + { seedNumber: 1, teamIndex: 3 }, + { seedNumber: 2, teamIndex: 1 }, + { seedNumber: 3, teamIndex: 4 }, + { seedNumber: 4, teamIndex: 2 }, + ]); + expect(random).not.toHaveBeenCalled(); + random.mockRestore(); + }); + + it('expands double-elimination winner bracket series into code slots', async () => { + const TournamentCodeModel = { + find: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue([]), + }), + }; + const service = new TournamentCodeService( + { getModel: jest.fn().mockResolvedValue(TournamentCodeModel) } as never, + createAuctionRedisService() as never, + ) as unknown as TournamentCodeServiceInternals; + const match = createMatch({ + gameMode: 'double-elimination', + gameCount: 3, + teams: Array.from({ length: 4 }, (_, index) => ({ + teamIndex: index + 1, + })), + doubleElimination: buildDoubleEliminationBracket([1, 2, 3, 4], { + resetFinalEnabled: true, + }), + }); + + const slots = await service.buildSlots(match); + + expect(slots.slice(0, 6)).toEqual([ + expect.objectContaining({ + gameNumber: 1, + seriesGameNumber: 1, + seriesGameCount: 3, + seriesRequiredWins: 2, + bracketMatchId: 'WB_R1_M1', + }), + expect.objectContaining({ + gameNumber: 2, + seriesGameNumber: 2, + bracketMatchId: 'WB_R1_M1', + }), + expect.objectContaining({ + gameNumber: 3, + seriesGameNumber: 3, + bracketMatchId: 'WB_R1_M1', + }), + expect.objectContaining({ + gameNumber: 4, + seriesGameNumber: 1, + bracketMatchId: 'WB_R1_M2', + }), + expect.objectContaining({ + gameNumber: 5, + seriesGameNumber: 2, + bracketMatchId: 'WB_R1_M2', + }), + expect.objectContaining({ + gameNumber: 6, + seriesGameNumber: 3, + bracketMatchId: 'WB_R1_M2', + }), + ]); + }); + + it('creates a limited round-robin schedule grouped by playable rounds', () => { + const service = createService(); + const roundRobin = createMatch({ + gameMode: 'round-robin', + gameCount: 1, + roundRobinMaxRounds: 3, + teams: Array.from({ length: 8 }, (_, index) => ({ + teamIndex: index + 1, + })), + gameSchedule: [], + }); + + service.ensureGameSchedule(roundRobin); + + expect(roundRobin.gameSchedule).toHaveLength(12); + for (const roundNumber of [1, 2, 3]) { + const round = roundRobin.gameSchedule.filter( + (game) => game.roundNumber === roundNumber, + ); + expect(round).toHaveLength(4); + expect( + new Set(round.flatMap((game) => [game.teamAIndex, game.teamBIndex])) + .size, + ).toBe(8); + } + }); + + it('leaves legacy round-robin schedules without round numbers unchanged', () => { + const service = createService(); + const roundRobin = createMatch({ + gameMode: 'round-robin', + gameCount: 1, + teams: Array.from({ length: 6 }, (_, index) => ({ + teamIndex: index + 1, + })), + gameSchedule: [ + { gameNumber: 1, teamAIndex: 2, teamBIndex: 5 }, + { gameNumber: 2, teamAIndex: 1, teamBIndex: 2 }, + { gameNumber: 3, teamAIndex: 4, teamBIndex: 5 }, + { gameNumber: 4, teamAIndex: 1, teamBIndex: 6 }, + { gameNumber: 5, teamAIndex: 5, teamBIndex: 6 }, + { gameNumber: 6, teamAIndex: 4, teamBIndex: 6 }, + ], + }); + + const persisted = [...roundRobin.gameSchedule]; + service.ensureGameSchedule(roundRobin); + + expect(roundRobin.gameSchedule).toEqual(persisted); + }); + + it('does not expose round numbers for legacy round-robin slots', async () => { + const codeFindExec = jest.fn().mockResolvedValue([]); + const connectionService = { + getModel: jest.fn().mockResolvedValue({ + find: jest.fn().mockReturnValue({ exec: codeFindExec }), + }), + }; + const service = new TournamentCodeService( + connectionService as never, + createAuctionRedisService() as never, + ) as unknown as TournamentCodeServiceInternals; + + const slots = await service.buildSlots( + createMatch({ + gameMode: 'round-robin', + gameCount: 1, + teams: Array.from({ length: 6 }, (_, index) => ({ + teamIndex: index + 1, + })), + gameSchedule: [ + { gameNumber: 1, teamAIndex: 2, teamBIndex: 5 }, + { gameNumber: 2, teamAIndex: 1, teamBIndex: 2 }, + { gameNumber: 3, teamAIndex: 4, teamBIndex: 5 }, + { gameNumber: 4, teamAIndex: 1, teamBIndex: 6 }, + { gameNumber: 5, teamAIndex: 5, teamBIndex: 6 }, + { gameNumber: 6, teamAIndex: 4, teamBIndex: 6 }, + { gameNumber: 7, teamAIndex: 2, teamBIndex: 6 }, + { gameNumber: 8, teamAIndex: 3, teamBIndex: 5 }, + { gameNumber: 9, teamAIndex: 2, teamBIndex: 3 }, + { gameNumber: 10, teamAIndex: 1, teamBIndex: 4 }, + { gameNumber: 11, teamAIndex: 3, teamBIndex: 6 }, + { gameNumber: 12, teamAIndex: 1, teamBIndex: 3 }, + { gameNumber: 13, teamAIndex: 3, teamBIndex: 4 }, + { gameNumber: 14, teamAIndex: 1, teamBIndex: 5 }, + { gameNumber: 15, teamAIndex: 2, teamBIndex: 4 }, + ], + }), + ); + + expect(slots).toHaveLength(15); + expect(slots[0]).toEqual( + expect.objectContaining({ + gameNumber: 1, + roundNumber: undefined, + teamAIndex: 2, + teamBIndex: 5, + }), + ); + expect(slots.every((slot) => slot.roundNumber === undefined)).toBe(true); + }); + it('does not expose fallback round-robin slots before the schedule is persisted', async () => { const service = createService(); const slots = await service.buildSlots( @@ -188,4 +486,524 @@ describe('TournamentCodeService round-robin scheduling', () => { expect(slots).toEqual([]); }); + + it('shows the active replacement when a reversed terminal code shares its game number', async () => { + const oldCodeId = new mongoose.Types.ObjectId(); + const replacementCodeId = new mongoose.Types.ObjectId(); + const TournamentCodeModel = { + find: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue([ + { + _id: replacementCodeId, + code: 'NEW-CODE', + gameNumber: 1, + state: 'reserved', + expiresAt: new Date('2026-07-13T00:00:00.000Z'), + }, + { + _id: oldCodeId, + code: 'OLD-CODE', + gameNumber: 1, + state: 'released', + expiresAt: new Date('2026-07-13T00:00:00.000Z'), + }, + ]), + }), + }; + const service = new TournamentCodeService( + { getModel: jest.fn().mockResolvedValue(TournamentCodeModel) } as never, + createAuctionRedisService() as never, + ) as unknown as TournamentCodeServiceInternals; + const match = createMatch({ + gameCount: 1, + teams: [{ teamIndex: 1 }, { teamIndex: 2 }], + tournamentCodeIds: [oldCodeId, replacementCodeId], + }); + + const slots = await service.buildSlots(match); + + expect(slots[0]).toEqual( + expect.objectContaining({ + gameNumber: 1, + code: 'NEW-CODE', + state: 'reserved', + }), + ); + }); +}); + +describe('TournamentCodeService bulk upload', () => { + it('defines slot and riot match indexes for multi-instance safety', () => { + const indexes = TournamentCodeSchema.indexes(); + + expect(indexes).toContainEqual([ + { matchId: 1, gameNumber: 1 }, + expect.objectContaining({ + unique: true, + partialFilterExpression: { + matchId: { $exists: true }, + gameNumber: { $exists: true }, + state: { $in: ['reserved', 'used'] }, + }, + }), + ]); + expect(indexes).toContainEqual([ + { matchId: 1, bracketMatchId: 1 }, + expect.objectContaining({ + partialFilterExpression: { + matchId: { $exists: true }, + bracketMatchId: { $exists: true }, + state: { $in: ['reserved', 'used'] }, + }, + }), + ]); + expect(indexes).toContainEqual([ + { riotMatchId: 1 }, + expect.objectContaining({ + unique: true, + partialFilterExpression: { riotMatchId: { $type: 'string' } }, + }), + ]); + }); + + it('preserves tournament code casing at the schema layer', async () => { + const connection = mongoose.createConnection(); + try { + const TournamentCodeModel = connection.model( + 'TournamentCodeCasingSpec', + TournamentCodeSchema, + ); + + const code = new TournamentCodeModel({ + code: ' AbC-12345 ', + expiresAt: new Date(Date.now() + 60 * 60 * 1000), + uploadedBy: new mongoose.Types.ObjectId(), + }); + + expect(code.code).toBe('AbC-12345'); + } finally { + await connection.close(); + } + }); + + it('stores tournament codes with the exact casing from input', async () => { + const insertMany = jest.fn().mockResolvedValue(undefined); + const TournamentCodeModel = { + find: jest.fn().mockReturnValue({ + select: jest.fn().mockReturnValue({ + lean: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue([]), + }), + }), + }), + insertMany, + }; + const connectionService = { + getModel: jest.fn().mockResolvedValue(TournamentCodeModel), + }; + const service = new TournamentCodeService( + connectionService as never, + createAuctionRedisService() as never, + ) as unknown as TournamentCodeServiceInternals; + service.attachPendingMatches = jest.fn().mockResolvedValue(0); + + await service.bulkUpload({ + communityId: new mongoose.Types.ObjectId(), + uploadedBy: new mongoose.Types.ObjectId(), + codes: [ + { + code: ' AbC-12345 ', + expiresAt: new Date(Date.now() + 60 * 60 * 1000).toISOString(), + }, + ], + }); + + expect(insertMany).toHaveBeenCalledWith( + [ + expect.objectContaining({ + code: 'AbC-12345', + }), + ], + { ordered: false }, + ); + }); +}); + +describe('TournamentCodeService pool stats', () => { + it('counts only available codes that are usable beyond the expiry margin', async () => { + const countDocuments = jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue(12), + }); + const connectionService = { + getModel: jest.fn().mockResolvedValue({ countDocuments }), + }; + const service = new TournamentCodeService( + connectionService as never, + createAuctionRedisService() as never, + ); + + await expect(service.countUsableAvailable()).resolves.toBe(12); + expect(countDocuments).toHaveBeenCalledWith({ + state: 'available', + expiresAt: { + $gt: expect.any(Date), + }, + }); + }); +}); + +describe('TournamentCodeService pending match attachment', () => { + it('does not attach tournament codes before match teams are built', async () => { + const invalidMatch = { + ...createMatch({ + status: 'team-built', + teams: [], + tournamentCodeIds: [], + } as unknown as MatchOverrides), + isModified: jest.fn().mockReturnValue(false), + }; + const validMatch = { + ...createMatch({ + status: 'team-built', + teams: [ + { + teamIndex: 1, + members: [{ userId: new mongoose.Types.ObjectId() }], + }, + { + teamIndex: 2, + members: [{ userId: new mongoose.Types.ObjectId() }], + }, + ], + tournamentCodeIds: [], + } as unknown as MatchOverrides), + isModified: jest.fn().mockReturnValue(false), + }; + const codeId = new mongoose.Types.ObjectId(); + const MatchModel = { + find: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue([invalidMatch, validMatch]), + }), + findById: jest.fn().mockResolvedValue(validMatch), + }; + const TournamentCodeModel = { + findOneAndUpdate: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ _id: codeId }), + }), + }; + const session = createSession(); + const connectionService = { + createSession: jest.fn().mockResolvedValue(session), + getModel: jest.fn().mockImplementation((modelName: string) => { + if (modelName === 'match') return Promise.resolve(MatchModel); + if (modelName === 'tournamentCode') { + return Promise.resolve(TournamentCodeModel); + } + throw new Error(`Unexpected model: ${modelName}`); + }), + }; + const auctionRedisService = createAuctionRedisService(); + const service = new TournamentCodeService( + connectionService as never, + auctionRedisService as never, + ); + + const matches = await service.attachPendingMatchDocuments(); + + expect(matches).toEqual([validMatch]); + expect(MatchModel.findById).toHaveBeenCalledTimes(1); + expect(MatchModel.findById).toHaveBeenCalledWith(validMatch._id); + expect(TournamentCodeModel.findOneAndUpdate).toHaveBeenCalledTimes(1); + expect(auctionRedisService.acquireTokenLock).toHaveBeenCalledWith( + `tournament-code:match:${validMatch._id.toString()}:lock`, + expect.any(String), + expect.any(Number), + ); + expect(session.startTransaction).toHaveBeenCalledTimes(1); + expect(session.commitTransaction).toHaveBeenCalledTimes(1); + expect(auctionRedisService.releaseTokenLock).toHaveBeenCalledWith( + `tournament-code:match:${validMatch._id.toString()}:lock`, + expect.any(String), + ); + expect(validMatch.tournamentCodeIds.map((id) => id.toString())).toEqual([ + codeId.toString(), + ]); + expect(invalidMatch.tournamentCodeIds).toEqual([]); + }); +}); + +describe('TournamentCodeService Competition assignment safety', () => { + it('does not restore an actively reserved code outside Competition commands', async () => { + const code = { + _id: new mongoose.Types.ObjectId(), + state: 'reserved', + save: jest.fn(), + }; + const connectionService = { + getModel: jest.fn().mockImplementation((name: string) => { + if (name === 'tournamentCode') { + return Promise.resolve({ + findById: jest.fn().mockResolvedValue(code), + }); + } + if (name === 'match') return Promise.resolve({}); + throw new Error(`Unexpected model ${name}`); + }), + }; + const service = new TournamentCodeService( + connectionService as never, + createAuctionRedisService() as never, + ); + + await expect(service.restoreToAvailable(code._id)).rejects.toThrow( + 'Active Competition assignments', + ); + expect(code.save).not.toHaveBeenCalled(); + }); + + it('expires a reserved code and releases its assignment and Match binding atomically', async () => { + const codeId = new mongoose.Types.ObjectId(); + const matchId = new mongoose.Types.ObjectId(); + const competitionId = new mongoose.Types.ObjectId(); + const assignmentId = new mongoose.Types.ObjectId(); + const session = createSession(); + const code = { _id: codeId, state: 'reserved', matchId }; + const codeUpdate = jest.fn().mockReturnValue(mongoQuery(code)); + const assignmentUpdate = jest + .fn() + .mockReturnValue(mongoQuery({ matchedCount: 1, modifiedCount: 1 })); + const matchUpdate = jest + .fn() + .mockReturnValue(mongoQuery({ matchedCount: 1, modifiedCount: 1 })); + const models = { + tournamentCode: { + find: jest.fn().mockReturnValue(mongoQuery([{ _id: codeId }])), + findOne: jest.fn().mockReturnValue(mongoQuery(code)), + findOneAndUpdate: codeUpdate, + }, + tournamentCodeAssignment: { + find: jest.fn().mockReturnValue( + mongoQuery([ + { + _id: assignmentId, + competitionId, + state: 'reserved', + }, + ]), + ), + updateOne: assignmentUpdate, + }, + competition: { + findById: jest.fn().mockReturnValue(mongoQuery({ matchId })), + }, + match: { updateOne: matchUpdate }, + }; + const service = new TournamentCodeService( + { + createSession: jest.fn().mockResolvedValue(session), + getModel: jest.fn((name: keyof typeof models) => + Promise.resolve(models[name]), + ), + } as never, + createAuctionRedisService() as never, + ); + + await expect(service.markExpired()).resolves.toEqual({ + affectedMatchIds: [matchId], + expiredCount: 1, + failedCount: 0, + }); + + expect(codeUpdate).toHaveBeenCalledWith( + { + _id: codeId, + expiresAt: { $lte: expect.any(Date) as Date }, + state: 'reserved', + }, + { + $set: { state: 'expired' }, + $unset: { + bracketMatchId: 1, + gameNumber: 1, + matchId: 1, + reservedAt: 1, + }, + }, + { returnDocument: 'before', session }, + ); + expect(assignmentUpdate).toHaveBeenCalledWith( + { _id: assignmentId, state: 'reserved' }, + { + $set: { releasedAt: expect.any(Date) as Date, state: 'released' }, + }, + { session }, + ); + expect(matchUpdate).toHaveBeenCalledWith( + { _id: matchId }, + { $pull: { tournamentCodeIds: codeId } }, + { session }, + ); + expect(session.commitTransaction).toHaveBeenCalledTimes(1); + }); + + it('isolates a used-assignment corruption and still expires the next valid candidate', async () => { + const corruptCodeId = new mongoose.Types.ObjectId(); + const validCodeId = new mongoose.Types.ObjectId(); + const corruptMatchId = new mongoose.Types.ObjectId(); + const validMatchId = new mongoose.Types.ObjectId(); + const competitionId = new mongoose.Types.ObjectId(); + const validAssignmentId = new mongoose.Types.ObjectId(); + const sessions = [createSession(), createSession()]; + const codeById = new Map([ + [ + corruptCodeId.toString(), + { _id: corruptCodeId, state: 'reserved', matchId: corruptMatchId }, + ], + [ + validCodeId.toString(), + { _id: validCodeId, state: 'reserved', matchId: validMatchId }, + ], + ]); + const codeUpdate = jest.fn((filter: { _id: mongoose.Types.ObjectId }) => + mongoQuery(codeById.get(filter._id.toString())), + ); + const assignmentUpdate = jest + .fn() + .mockReturnValue(mongoQuery({ matchedCount: 1, modifiedCount: 1 })); + const matchUpdate = jest + .fn() + .mockReturnValue(mongoQuery({ matchedCount: 1, modifiedCount: 1 })); + const models = { + tournamentCode: { + find: jest + .fn() + .mockReturnValue( + mongoQuery([{ _id: corruptCodeId }, { _id: validCodeId }]), + ), + findOne: jest.fn((filter: { _id: mongoose.Types.ObjectId }) => + mongoQuery(codeById.get(filter._id.toString())), + ), + findOneAndUpdate: codeUpdate, + }, + tournamentCodeAssignment: { + find: jest.fn((filter: { tournamentCodeId: mongoose.Types.ObjectId }) => + mongoQuery( + filter.tournamentCodeId.equals(corruptCodeId) + ? [ + { + _id: new mongoose.Types.ObjectId(), + competitionId, + state: 'used', + }, + ] + : [ + { + _id: validAssignmentId, + competitionId, + state: 'reserved', + }, + ], + ), + ), + updateOne: assignmentUpdate, + }, + competition: { + findById: jest + .fn() + .mockReturnValue(mongoQuery({ matchId: validMatchId })), + }, + match: { updateOne: matchUpdate }, + }; + const errorLog = jest + .spyOn(Logger.prototype, 'error') + .mockImplementation(() => undefined); + const service = new TournamentCodeService( + { + createSession: jest + .fn() + .mockImplementation(() => Promise.resolve(sessions.shift())), + getModel: jest.fn((name: keyof typeof models) => + Promise.resolve(models[name]), + ), + } as never, + createAuctionRedisService() as never, + ); + + await expect(service.markExpired()).resolves.toEqual({ + affectedMatchIds: [validMatchId], + expiredCount: 1, + failedCount: 1, + }); + + expect(codeUpdate).toHaveBeenCalledTimes(1); + expect(codeUpdate.mock.calls[0][0]).toMatchObject({ _id: validCodeId }); + expect(assignmentUpdate).toHaveBeenCalledWith( + { _id: validAssignmentId, state: 'reserved' }, + expect.any(Object), + expect.any(Object), + ); + expect(errorLog).toHaveBeenCalledWith( + expect.stringContaining('used Competition assignment'), + ); + errorLog.mockRestore(); + }); + + it('leaves a foreign Competition assignment unchanged and reports the candidate failure', async () => { + const codeId = new mongoose.Types.ObjectId(); + const matchId = new mongoose.Types.ObjectId(); + const foreignMatchId = new mongoose.Types.ObjectId(); + const competitionId = new mongoose.Types.ObjectId(); + const code = { _id: codeId, state: 'reserved', matchId }; + const codeUpdate = jest.fn(); + const session = createSession(); + const models = { + tournamentCode: { + find: jest.fn().mockReturnValue(mongoQuery([{ _id: codeId }])), + findOne: jest.fn().mockReturnValue(mongoQuery(code)), + findOneAndUpdate: codeUpdate, + }, + tournamentCodeAssignment: { + find: jest.fn().mockReturnValue( + mongoQuery([ + { + _id: new mongoose.Types.ObjectId(), + competitionId, + state: 'reserved', + }, + ]), + ), + updateOne: jest.fn(), + }, + competition: { + findById: jest + .fn() + .mockReturnValue(mongoQuery({ matchId: foreignMatchId })), + }, + match: { updateOne: jest.fn() }, + }; + const errorLog = jest + .spyOn(Logger.prototype, 'error') + .mockImplementation(() => undefined); + const service = new TournamentCodeService( + { + createSession: jest.fn().mockResolvedValue(session), + getModel: jest.fn((name: keyof typeof models) => + Promise.resolve(models[name]), + ), + } as never, + createAuctionRedisService() as never, + ); + + await expect(service.markExpired()).resolves.toEqual({ + affectedMatchIds: [], + expiredCount: 0, + failedCount: 1, + }); + expect(codeUpdate).not.toHaveBeenCalled(); + expect(session.abortTransaction).toHaveBeenCalledTimes(1); + expect(errorLog).toHaveBeenCalledWith( + expect.stringContaining('ownership does not match'), + ); + errorLog.mockRestore(); + }); }); diff --git a/apps/api/src/modules/tournament-code/tournament-code.service.ts b/apps/api/src/modules/tournament-code/tournament-code.service.ts index 8801f7df..45c677b8 100644 --- a/apps/api/src/modules/tournament-code/tournament-code.service.ts +++ b/apps/api/src/modules/tournament-code/tournament-code.service.ts @@ -1,9 +1,19 @@ import { BadRequestException, + ConflictException, Injectable, + InternalServerErrorException, + Logger, NotFoundException, } from '@nestjs/common'; +import { randomUUID } from 'crypto'; import mongoose from 'mongoose'; +import { + buildDoubleEliminationGameSlots, + buildDoubleEliminationBracket, + type DoubleEliminationGameSlot, +} from '../double-elimination/double-elimination.util'; +import { AuctionRedisService } from '../auction/redis/auction-redis.service'; import { ConnectionService } from '../global/database/connection.service'; import type { MatchGameAssignment, @@ -25,21 +35,32 @@ import type { TournamentCodeUploadItem, } from './tournament-code.types'; import { + roundRobinGameSchedule, resolveRoundRobinTeamCount, - roundRobinPairCount, - roundRobinPairs, - shuffleInPlace, } from './round-robin.util'; const DEFAULT_REGION = 'kr'; const DEFAULT_SPECTATOR_TYPE: TournamentSpectatorType = 'ALL'; +const TOURNAMENT_CODE_MATCH_LOCK_TTL_MS = 30_000; +const TOURNAMENT_CODE_TRANSACTION_ATTEMPTS = 3; + +export interface TournamentCodeExpirationResult { + expiredCount: number; + failedCount: number; + affectedMatchIds: mongoose.Types.ObjectId[]; +} @Injectable() export class TournamentCodeService { - constructor(private readonly connectionService: ConnectionService) {} + private readonly logger = new Logger(TournamentCodeService.name); + + constructor( + private readonly connectionService: ConnectionService, + private readonly auctionRedisService: AuctionRedisService, + ) {} public async bulkUpload(params: { - communityId: mongoose.Types.ObjectId; + communityId?: mongoose.Types.ObjectId; uploadedBy: mongoose.Types.ObjectId; codes: TournamentCodeUploadItem[]; }): Promise { @@ -123,6 +144,17 @@ export class TournamentCodeService { }; } + public async countUsableAvailable(): Promise { + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + return TournamentCodeModel.countDocuments({ + state: 'available', + expiresAt: { + $gt: new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS), + }, + }).exec(); + } + public async list(params: { state?: TournamentCodeState; limit?: number; @@ -155,10 +187,9 @@ export class TournamentCodeService { _id: TournamentCodeState; count: number; }>([{ $group: { _id: '$state', count: { $sum: 1 } } }]).exec(); - const byState = Object.fromEntries(states.map((state) => [state, 0])) as Record< - TournamentCodeState, - number - >; + const byState = Object.fromEntries( + states.map((state) => [state, 0]), + ) as Record; for (const entry of counts) byState[entry._id] = entry.count; const expiringSoon = await TournamentCodeModel.countDocuments({ @@ -180,7 +211,9 @@ export class TournamentCodeService { state: 'available', }).exec(); if (result.deletedCount === 0) { - throw new BadRequestException('Only available tournament codes can be deleted.'); + throw new BadRequestException( + 'Only available tournament codes can be deleted.', + ); } } @@ -192,9 +225,9 @@ export class TournamentCodeService { const MatchModel = await this.connectionService.getModel('match'); const code = await TournamentCodeModel.findById(id); if (!code) throw new NotFoundException('Tournament code not found.'); - if (code.state !== 'released' && code.state !== 'reserved') { + if (code.state !== 'released') { throw new BadRequestException( - 'Only released or reserved tournament codes can be restored.', + 'Only released tournament codes can be restored. Active Competition assignments must be reversed through Competition commands.', ); } const previousMatchId = code.matchId; @@ -216,21 +249,38 @@ export class TournamentCodeService { public async reserveForMatch( matchOrId: MatchDocument | mongoose.Types.ObjectId, + ): Promise { + const matchId = this.resolveMatchId(matchOrId); + return this.withLockedMatchTransaction(matchId, (session) => + this.reserveForMatchInTransaction(matchId, session), + ); + } + + private async reserveForMatchInTransaction( + matchId: mongoose.Types.ObjectId, + session: mongoose.ClientSession, ): Promise { const MatchModel = await this.connectionService.getModel('match'); const TournamentCodeModel = await this.connectionService.getModel('tournamentCode'); - const match = - matchOrId instanceof mongoose.Types.ObjectId - ? await MatchModel.findById(matchOrId) - : await MatchModel.findById(matchOrId._id); + const match = await this.execQuery( + this.withQuerySession(MatchModel.findById(matchId), session), + ); if (!match) throw new NotFoundException('Match not found.'); match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; match.tournamentCodeIds = match.tournamentCodeIds ?? []; this.ensureGameSchedule(match); + if ((match.gameMode ?? 'pair') === 'double-elimination') { + return this.reserveForDoubleEliminationMatch( + match, + TournamentCodeModel, + session, + ); + } const shouldSaveMetadata = - match.isModified('gameCount') || match.isModified('gameSchedule'); + this.isMatchModified(match, 'gameCount') || + this.isMatchModified(match, 'gameSchedule'); const requiredSlots = this.resolveRequiredSlots(match); const need = requiredSlots - match.tournamentCodeIds.length; if (need <= 0) { @@ -240,7 +290,9 @@ export class TournamentCodeService { const reservedIds: mongoose.Types.ObjectId[] = []; const startGameNumber = match.tournamentCodeIds.length + 1; - const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS); + const expiresAfter = new Date( + Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS, + ); for (let index = 0; index < need; index += 1) { const code = await TournamentCodeModel.findOneAndUpdate( @@ -260,7 +312,7 @@ export class TournamentCodeService { }, $unset: { releasedAt: 1 }, }, - { sort: { expiresAt: 1 }, returnDocument: 'after' }, + { sort: { expiresAt: 1 }, returnDocument: 'after', session }, ).exec(); if (!code) break; reservedIds.push(code._id); @@ -270,52 +322,214 @@ export class TournamentCodeService { match.tournamentCodeIds.push(...reservedIds); } if (reservedIds.length > 0 || shouldSaveMetadata) { - await match.save(); + await match.save({ session }); } return match; } public async releaseFromMatch( matchOrId: MatchDocument | mongoose.Types.ObjectId, + ): Promise { + const matchId = this.resolveMatchId(matchOrId); + await this.withLockedMatchTransaction(matchId, (session) => + this.releaseFromMatchInTransaction(matchId, session), + ); + } + + private async releaseFromMatchInTransaction( + matchId: mongoose.Types.ObjectId, + session: mongoose.ClientSession, ): Promise { const MatchModel = await this.connectionService.getModel('match'); const TournamentCodeModel = await this.connectionService.getModel('tournamentCode'); - const match = - matchOrId instanceof mongoose.Types.ObjectId - ? await MatchModel.findById(matchOrId) - : await MatchModel.findById(matchOrId._id); + const match = await this.execQuery( + this.withQuerySession(MatchModel.findById(matchId), session), + ); if (!match) return; if (match.tournamentCodeIds.length === 0) return; - await TournamentCodeModel.updateMany( - { _id: { $in: match.tournamentCodeIds }, state: 'reserved' }, - { - $set: { state: 'released', releasedAt: new Date() }, - $unset: { matchId: 1, gameNumber: 1, reservedAt: 1 }, - }, - ).exec(); + await this.execQuery( + this.withQuerySession( + TournamentCodeModel.updateMany( + { _id: { $in: match.tournamentCodeIds }, state: 'reserved' }, + { + $set: { state: 'released', releasedAt: new Date() }, + $unset: { + matchId: 1, + gameNumber: 1, + bracketMatchId: 1, + reservedAt: 1, + }, + }, + ), + session, + ), + ); match.tournamentCodeIds = []; - await match.save(); + await match.save({ session }); } - public async markExpired(): Promise { - const TournamentCodeModel = - await this.connectionService.getModel('tournamentCode'); - const result = await TournamentCodeModel.updateMany( - { - state: { $in: ['available', 'reserved', 'released'] }, - expiresAt: { $lte: new Date() }, - }, - { $set: { state: 'expired' } }, - ).exec(); - return result.modifiedCount; + public async markExpired(): Promise { + const [TournamentCodeModel, AssignmentModel, CompetitionModel, MatchModel] = + await Promise.all([ + this.connectionService.getModel('tournamentCode'), + this.connectionService.getModel('tournamentCodeAssignment'), + this.connectionService.getModel('competition'), + this.connectionService.getModel('match'), + ]); + const expiredAt = new Date(); + const candidates = await TournamentCodeModel.find({ + state: { $in: ['available', 'reserved', 'released'] }, + expiresAt: { $lte: expiredAt }, + }) + .select({ _id: 1 }) + .lean() + .exec(); + const affectedMatchIds = new Map(); + let expiredCount = 0; + let failedCount = 0; + + for (const candidate of candidates) { + try { + const expired = await this.runTransactionWithRetry(async (session) => { + const code = await TournamentCodeModel.findOne( + { + _id: candidate._id, + expiresAt: { $lte: expiredAt }, + state: { $in: ['available', 'reserved', 'released'] }, + }, + null, + { session }, + ) + .lean() + .exec(); + if (!code) return null; + + const activeAssignments = await AssignmentModel.find({ + tournamentCodeId: code._id, + state: { $in: ['reserved', 'used'] }, + }) + .session(session) + .limit(2) + .lean() + .exec(); + if (activeAssignments.length > 1) { + throw new Error( + `Tournament Code ${code._id.toString()} has multiple active Competition assignments.`, + ); + } + const assignment = activeAssignments[0]; + if (assignment?.state === 'used') { + throw new Error( + `Tournament Code ${code._id.toString()} has a used Competition assignment and cannot expire as reserved.`, + ); + } + if (assignment) { + if (!code.matchId) { + throw new Error( + `Tournament Code ${code._id.toString()} has an active Competition assignment without a Match binding.`, + ); + } + const competition = await CompetitionModel.findById( + assignment.competitionId, + ) + .session(session) + .select({ matchId: 1 }) + .lean() + .exec(); + if ( + !competition || + competition.matchId.toString() !== code.matchId.toString() + ) { + throw new Error( + `Tournament Code ${code._id.toString()} Competition ownership does not match its Match binding.`, + ); + } + } + + const expiredCode = await TournamentCodeModel.findOneAndUpdate( + { + _id: code._id, + expiresAt: { $lte: expiredAt }, + state: code.state, + }, + { + $set: { state: 'expired' }, + $unset: { + bracketMatchId: 1, + gameNumber: 1, + matchId: 1, + reservedAt: 1, + }, + }, + { returnDocument: 'before', session }, + ).exec(); + if (!expiredCode) return null; + + if (assignment) { + const assignmentResult = await AssignmentModel.updateOne( + { _id: assignment._id, state: 'reserved' }, + { $set: { releasedAt: expiredAt, state: 'released' } }, + { session }, + ).exec(); + if (assignmentResult.modifiedCount !== 1) { + throw new Error( + `Tournament Code ${code._id.toString()} assignment did not transition to released.`, + ); + } + } + if (code.matchId) { + const matchResult = await MatchModel.updateOne( + { _id: code.matchId }, + { $pull: { tournamentCodeIds: code._id } }, + { session }, + ).exec(); + if ( + assignment && + (matchResult.matchedCount !== 1 || + matchResult.modifiedCount !== 1) + ) { + throw new Error( + `Tournament Code ${code._id.toString()} Match binding did not transition atomically.`, + ); + } + } + return code; + }); + if (!expired) continue; + expiredCount += 1; + if (expired.matchId) { + affectedMatchIds.set(expired.matchId.toString(), expired.matchId); + } + } catch (error) { + failedCount += 1; + this.logger.error( + `Failed to expire Tournament Code ${candidate._id.toString()}; candidate was left unchanged: ${ + error instanceof Error ? error.message : String(error) + }`, + ); + } + } + + return { + expiredCount, + failedCount, + affectedMatchIds: [...affectedMatchIds.values()], + }; } public async attachPendingMatches( communityId?: mongoose.Types.ObjectId, ): Promise { + const matches = await this.attachPendingMatchDocuments(communityId); + return matches.length; + } + + public async attachPendingMatchDocuments( + communityId?: mongoose.Types.ObjectId, + ): Promise { const MatchModel = await this.connectionService.getModel('match'); const filter: { status: { $in: string[] }; @@ -326,20 +540,36 @@ export class TournamentCodeService { if (communityId) filter.communityId = communityId; const matches = await MatchModel.find(filter).exec(); - let touched = 0; + const touched: MatchDocument[] = []; for (const match of matches) { - if ((match.tournamentCodeIds?.length ?? 0) >= this.resolveRequiredSlots(match)) { + if (!this.hasBuiltTeams(match)) continue; + if ( + (match.tournamentCodeIds?.length ?? 0) >= + this.resolveRequiredSlots(match) + ) { continue; } const before = match.tournamentCodeIds?.length ?? 0; - await this.reserveForMatch(match); - const after = match.tournamentCodeIds?.length ?? 0; - if (after > before) touched += 1; + const updatedMatch = await this.reserveForMatch(match); + const after = updatedMatch.tournamentCodeIds?.length ?? 0; + if (after > before) touched.push(updatedMatch); } return touched; } - public async buildSlots(match: MatchDocument): Promise { + private hasBuiltTeams(match: MatchDocument): boolean { + return Boolean( + match.teams.length >= 2 && + match.teams.every((team) => team.members.length > 0), + ); + } + + public async buildSlots( + match: MatchDocument, + ): Promise { + if ((match.gameMode ?? 'pair') === 'double-elimination') { + return this.buildDoubleEliminationSlots(match); + } if ( (match.gameMode ?? 'pair') === 'round-robin' && (match.gameSchedule?.length ?? 0) === 0 && @@ -357,7 +587,11 @@ export class TournamentCodeService { : []; const byGameNumber = new Map( codes - .filter((code) => typeof code.gameNumber === 'number') + .filter( + (code) => + typeof code.gameNumber === 'number' && + (code.state === 'reserved' || code.state === 'used'), + ) .map((code) => [code.gameNumber as number, code]), ); @@ -368,6 +602,7 @@ export class TournamentCodeService { const seriesRef = this.resolveSeriesRefForGameNumber(match, gameNumber); return { gameNumber, + roundNumber: this.resolveRoundNumberForGameNumber(match, gameNumber), ...seriesRef, code: null, expiresAt: null, @@ -377,6 +612,7 @@ export class TournamentCodeService { } return { gameNumber, + roundNumber: this.resolveRoundNumberForGameNumber(match, gameNumber), ...this.resolveSeriesRefForGameNumber(match, gameNumber), code: code.code, expiresAt: code.expiresAt.toISOString(), @@ -387,16 +623,258 @@ export class TournamentCodeService { } private normalizeCode(code: string | undefined): string { - return (code ?? '').trim().toUpperCase(); + return (code ?? '').trim(); + } + + private resolveMatchId( + matchOrId: MatchDocument | mongoose.Types.ObjectId, + ): mongoose.Types.ObjectId { + return matchOrId instanceof mongoose.Types.ObjectId + ? matchOrId + : matchOrId._id; + } + + private async withLockedMatchTransaction( + matchId: mongoose.Types.ObjectId, + operation: (session: mongoose.ClientSession) => Promise, + ): Promise { + const lockKey = this.matchCodeLockKey(matchId); + const token = randomUUID(); + const acquired = await this.auctionRedisService.acquireTokenLock( + lockKey, + token, + TOURNAMENT_CODE_MATCH_LOCK_TTL_MS, + ); + if (!acquired) { + throw new ConflictException( + 'Tournament code operation is already running for this match.', + ); + } + + try { + return await this.runTransactionWithRetry(operation); + } finally { + await this.auctionRedisService.releaseTokenLock(lockKey, token); + } + } + + private async runTransactionWithRetry( + operation: (session: mongoose.ClientSession) => Promise, + ): Promise { + let lastError: unknown; + for ( + let attempt = 1; + attempt <= TOURNAMENT_CODE_TRANSACTION_ATTEMPTS; + attempt += 1 + ) { + const session = await this.connectionService.createSession(); + if (!session) { + throw new InternalServerErrorException('Failed to start DB session.'); + } + + try { + session.startTransaction(); + const result = await operation(session); + await session.commitTransaction(); + return result; + } catch (error) { + lastError = error; + await session.abortTransaction().catch(() => undefined); + if ( + attempt >= TOURNAMENT_CODE_TRANSACTION_ATTEMPTS || + !this.isRetryableTransactionError(error) + ) { + throw error; + } + } finally { + await session.endSession().catch(() => undefined); + } + } + + throw lastError; + } + + private isRetryableTransactionError(error: unknown): boolean { + const candidate = error as { + code?: number; + codeName?: string; + hasErrorLabel?: (label: string) => boolean; + }; + return Boolean( + candidate?.hasErrorLabel?.('TransientTransactionError') || + candidate?.hasErrorLabel?.('UnknownTransactionCommitResult') || + candidate?.code === 112 || + candidate?.codeName === 'WriteConflict', + ); + } + + private matchCodeLockKey(matchId: mongoose.Types.ObjectId): string { + return `tournament-code:match:${matchId.toString()}:lock`; + } + + private withQuerySession(query: T, session: mongoose.ClientSession): T { + const maybeQuery = query as { + session?: (session: mongoose.ClientSession) => T; + }; + if (maybeQuery && typeof maybeQuery.session === 'function') { + return maybeQuery.session(session); + } + return query; + } + + private async execQuery(query: unknown): Promise { + const maybeQuery = query as { exec?: () => Promise }; + if (maybeQuery && typeof maybeQuery.exec === 'function') { + return maybeQuery.exec(); + } + return query as Promise; + } + + private async reserveForDoubleEliminationMatch( + match: MatchDocument, + TournamentCodeModel: mongoose.Model, + session: mongoose.ClientSession, + ): Promise { + const readySlots = buildDoubleEliminationGameSlots( + match.doubleElimination?.bracketMatches ?? [], + ).filter((slot) => slot.bracketMatch.state === 'ready'); + const existingCodes = + match.tournamentCodeIds.length > 0 + ? await this.execQuery( + this.withQuerySession( + TournamentCodeModel.find({ + _id: { $in: match.tournamentCodeIds }, + }), + session, + ), + ) + : []; + const byGameNumber = new Map( + existingCodes + .filter( + (code) => + typeof code.gameNumber === 'number' && + (code.state === 'reserved' || code.state === 'used'), + ) + .map((code) => [code.gameNumber as number, code]), + ); + const expiresAfter = new Date( + Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS, + ); + const reservedIds: mongoose.Types.ObjectId[] = []; + + for (const slot of readySlots) { + if (byGameNumber.has(slot.gameNumber)) continue; + const code = await TournamentCodeModel.findOneAndUpdate( + { + state: 'available', + region: DEFAULT_REGION, + mapType: 'SUMMONERS_RIFT', + teamSize: 5, + expiresAt: { $gt: expiresAfter }, + }, + { + $set: { + state: 'reserved', + matchId: match._id, + gameNumber: slot.gameNumber, + bracketMatchId: slot.bracketMatch.bracketMatchId, + reservedAt: new Date(), + }, + $unset: { releasedAt: 1 }, + }, + { sort: { expiresAt: 1 }, returnDocument: 'after', session }, + ).exec(); + if (!code) break; + reservedIds.push(code._id); + byGameNumber.set(slot.gameNumber, code); + } + + if (reservedIds.length > 0) { + match.tournamentCodeIds.push(...reservedIds); + } + if ( + reservedIds.length > 0 || + this.isMatchModified(match, 'doubleElimination') + ) { + await match.save({ session }); + } + return match; + } + + private async buildDoubleEliminationSlots( + match: MatchDocument, + ): Promise { + this.ensureGameSchedule(match); + const bracketMatches = match.doubleElimination?.bracketMatches ?? []; + if (bracketMatches.length === 0) return []; + const slots = buildDoubleEliminationGameSlots(bracketMatches); + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const ids = match.tournamentCodeIds ?? []; + const codes = + ids.length > 0 + ? await TournamentCodeModel.find({ _id: { $in: ids } }).exec() + : []; + const byGameNumber = new Map( + codes + .filter( + (code) => + typeof code.gameNumber === 'number' && + code.state !== 'released' && + code.state !== 'voided', + ) + .map((code) => [code.gameNumber as number, code]), + ); + + return slots.map((slot) => { + const code = byGameNumber.get(slot.gameNumber); + return { + ...this.toDoubleEliminationSlotBase(slot), + code: code?.code ?? null, + expiresAt: code?.expiresAt.toISOString() ?? null, + state: code?.state ?? 'pending', + riotMatchId: code?.riotMatchId ?? null, + }; + }); + } + + private toDoubleEliminationSlotBase( + slot: DoubleEliminationGameSlot, + ): Omit< + TournamentCodeSlotView, + 'code' | 'expiresAt' | 'state' | 'riotMatchId' + > { + const bracketMatch = slot.bracketMatch; + return { + gameNumber: slot.gameNumber, + seriesGameNumber: slot.seriesGameNumber, + seriesGameCount: slot.seriesGameCount, + seriesRequiredWins: slot.seriesRequiredWins, + bracketMatchId: bracketMatch.bracketMatchId, + bracketSide: bracketMatch.bracketSide, + roundNumber: bracketMatch.roundNumber, + matchNumber: bracketMatch.matchNumber, + teamAIndex: bracketMatch.teamAIndex, + teamBIndex: bracketMatch.teamBIndex, + }; } private resolveRequiredSlots(match: MatchDocument): number { const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; const gameMode = match.gameMode ?? 'pair'; + if (gameMode === 'double-elimination') { + return buildDoubleEliminationGameSlots( + match.doubleElimination?.bracketMatches ?? [], + ).length; + } + if (gameMode === 'round-robin') { - const teamCount = resolveRoundRobinTeamCount(match); - return roundRobinPairCount(teamCount) * gameCount; + if ((match.gameSchedule?.length ?? 0) > 0) { + return match.gameSchedule.length; + } + return this.buildRoundRobinGameSchedule(match).length; } const teamCount = (match.teams ?? []).length; @@ -415,6 +893,17 @@ export class TournamentCodeService { ): { teamAIndex: number; teamBIndex: number } { const gameMode = match.gameMode ?? 'pair'; + if (gameMode === 'double-elimination') { + const slot = this.resolveDoubleEliminationGameSlotByGameNumber( + match, + gameNumber, + ); + return { + teamAIndex: slot?.bracketMatch.teamAIndex ?? 1, + teamBIndex: slot?.bracketMatch.teamBIndex ?? 2, + }; + } + if (gameMode === 'round-robin') { const persisted = match.gameSchedule?.find( (entry) => entry.gameNumber === gameNumber, @@ -426,13 +915,18 @@ export class TournamentCodeService { }; } - const teamCount = resolveRoundRobinTeamCount(match); - const perSeries = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; - const pairIndex = Math.max(0, Math.ceil(gameNumber / perSeries) - 1); - return roundRobinPairs(teamCount)[pairIndex] ?? { - teamAIndex: 1, - teamBIndex: 2, - }; + const fallback = this.buildRoundRobinGameSchedule(match).find( + (entry) => entry.gameNumber === gameNumber, + ); + return fallback + ? { + teamAIndex: fallback.teamAIndex, + teamBIndex: fallback.teamBIndex, + } + : { + teamAIndex: 1, + teamBIndex: 2, + }; } const perSeries = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; @@ -444,27 +938,119 @@ export class TournamentCodeService { } private ensureGameSchedule(match: MatchDocument): void { + if ((match.gameMode ?? 'pair') === 'double-elimination') { + this.ensureDoubleEliminationBracket(match); + return; + } if ((match.gameMode ?? 'pair') !== 'round-robin') return; if ((match.gameSchedule?.length ?? 0) > 0) return; const teamCount = resolveRoundRobinTeamCount(match); if (teamCount < 2) return; - const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; - const pairs = shuffleInPlace([...roundRobinPairs(teamCount)]); - const schedule: MatchGameAssignment[] = []; + match.gameSchedule = this.buildRoundRobinGameSchedule(match); + } - for (let pairIndex = 0; pairIndex < pairs.length; pairIndex += 1) { - const pair = pairs[pairIndex]; - for (let gameIndex = 0; gameIndex < gameCount; gameIndex += 1) { - schedule.push({ - gameNumber: pairIndex * gameCount + gameIndex + 1, - teamAIndex: pair.teamAIndex, - teamBIndex: pair.teamBIndex, - }); + private ensureDoubleEliminationBracket(match: MatchDocument): void { + if ((match.doubleElimination?.bracketMatches.length ?? 0) > 0) return; + const teamIndexes = [...(match.teams ?? [])] + .map((team) => team.teamIndex) + .sort((left, right) => left - right); + if (teamIndexes.length !== 4 && teamIndexes.length !== 8) return; + const seededTeamIndexes = this.configuredDoubleEliminationSeedOrder( + match, + teamIndexes, + ); + const shuffledTeamIndexes = + seededTeamIndexes ?? this.shuffleTeamIndexes(teamIndexes); + match.doubleElimination = buildDoubleEliminationBracket( + shuffledTeamIndexes, + { + resetFinalEnabled: match.doubleElimination?.resetFinalEnabled ?? false, + winnerBracketGameCount: + match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT, + }, + ); + match.markModified?.('doubleElimination'); + } + + private configuredDoubleEliminationSeedOrder( + match: MatchDocument, + teamIndexes: number[], + ): number[] | undefined { + const seeds = match.doubleElimination?.seeds ?? []; + if (seeds.length !== teamIndexes.length) return undefined; + const validTeamIndexes = new Set(teamIndexes); + const seedNumbers = new Set(); + const seededTeamIndexes = new Set(); + for (const seed of seeds) { + if ( + !Number.isInteger(seed.seedNumber) || + seed.seedNumber < 1 || + seed.seedNumber > teamIndexes.length || + seedNumbers.has(seed.seedNumber) || + !validTeamIndexes.has(seed.teamIndex) || + seededTeamIndexes.has(seed.teamIndex) + ) { + return undefined; } + seedNumbers.add(seed.seedNumber); + seededTeamIndexes.add(seed.teamIndex); } + return [...seeds] + .sort((left, right) => left.seedNumber - right.seedNumber) + .map(({ teamIndex }) => teamIndex); + } - match.gameSchedule = schedule; + private resolveDoubleEliminationGameSlotByGameNumber( + match: MatchDocument, + gameNumber: number, + ): DoubleEliminationGameSlot | undefined { + return buildDoubleEliminationGameSlots( + match.doubleElimination?.bracketMatches ?? [], + ).find((slot) => slot.gameNumber === gameNumber); + } + + private shuffleTeamIndexes(teamIndexes: number[]): number[] { + const shuffled = [...teamIndexes]; + for (let index = shuffled.length - 1; index > 0; index -= 1) { + const swapIndex = Math.floor(Math.random() * (index + 1)); + [shuffled[index], shuffled[swapIndex]] = [ + shuffled[swapIndex], + shuffled[index], + ]; + } + return shuffled; + } + + private isMatchModified(match: MatchDocument, path: string): boolean { + return typeof match.isModified === 'function' && match.isModified(path); + } + + private resolveRoundNumberForGameNumber( + match: MatchDocument, + gameNumber: number, + ): number | undefined { + if ((match.gameMode ?? 'pair') !== 'round-robin') return undefined; + + const persisted = match.gameSchedule?.find( + (entry) => entry.gameNumber === gameNumber, + ); + if (persisted) return persisted.roundNumber; + + return this.buildRoundRobinGameSchedule(match).find( + (entry) => entry.gameNumber === gameNumber, + )?.roundNumber; + } + + private buildRoundRobinGameSchedule( + match: MatchDocument, + shuffleTeams = false, + ): MatchGameAssignment[] { + return roundRobinGameSchedule(resolveRoundRobinTeamCount(match), { + gamesPerPair: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT, + maxRounds: match.roundRobinMaxRounds, + shuffleTeams, + }); } } diff --git a/apps/api/src/modules/tournament-code/tournament-code.types.ts b/apps/api/src/modules/tournament-code/tournament-code.types.ts index 207f5b0c..f3b9a59f 100644 --- a/apps/api/src/modules/tournament-code/tournament-code.types.ts +++ b/apps/api/src/modules/tournament-code/tournament-code.types.ts @@ -24,8 +24,15 @@ export interface BulkUploadTournamentCodesResponse { export interface TournamentCodeSlotView { gameNumber: number; - teamAIndex: number; - teamBIndex: number; + seriesGameNumber?: number; + seriesGameCount?: number; + seriesRequiredWins?: number; + bracketMatchId?: string; + bracketSide?: string; + roundNumber?: number; + matchNumber?: number; + teamAIndex?: number; + teamBIndex?: number; code: string | null; expiresAt: string | null; state: TournamentCodeState | 'pending'; diff --git a/apps/api/src/modules/tournament-result/competition-assignment.provisioner.spec.ts b/apps/api/src/modules/tournament-result/competition-assignment.provisioner.spec.ts new file mode 100644 index 00000000..c903a0d8 --- /dev/null +++ b/apps/api/src/modules/tournament-result/competition-assignment.provisioner.spec.ts @@ -0,0 +1,281 @@ +/* eslint-disable @typescript-eslint/no-unsafe-assignment */ +import mongoose from 'mongoose'; +import type { CompetitionResultSnapshot } from './competition-result.adapter'; +import { CompetitionAssignmentProvisioner } from './competition-assignment.provisioner'; + +describe('CompetitionAssignmentProvisioner', () => { + it('reserves an available code and creates the stable GameSlot assignment in one transaction', async () => { + const harness = createHarness(); + const provisioner = new CompetitionAssignmentProvisioner( + harness.connectionService as never, + ); + + const result = await provisioner.provisionReadyAssignments({ + matchId: harness.matchId, + competition: harness.competition, + }); + + expect(result).toMatchObject({ + requested: 1, + reserved: 1, + existing: 0, + unavailable: 0, + }); + expect(harness.competitionModel.updateOne).toHaveBeenCalledWith( + { _id: harness.competitionId, revision: 2 }, + { $set: { revision: 2 } }, + { session: harness.session, timestamps: false }, + ); + expect(harness.codeModel.findOneAndUpdate).toHaveBeenCalledWith( + expect.objectContaining({ state: 'available' }), + { + $set: expect.objectContaining({ + state: 'reserved', + matchId: harness.matchId, + gameNumber: 1, + }), + }, + expect.objectContaining({ + returnDocument: 'after', + session: harness.session, + sort: { expiresAt: 1 }, + }), + ); + expect(harness.assignmentModel.insertMany).toHaveBeenCalledWith( + [ + expect.objectContaining({ + competitionId: harness.competitionId, + seriesId: harness.seriesId, + gameSlotId: harness.gameSlotId, + tournamentCodeId: harness.codeId, + state: 'reserved', + commandId: `provision-code:${harness.competitionId.toString()}:${harness.gameSlotId.toString()}:2:${harness.codeId.toString()}`, + }), + ], + { session: harness.session }, + ); + expect(harness.matchModel.updateOne).toHaveBeenCalledWith( + { _id: harness.matchId }, + { $addToSet: { tournamentCodeIds: harness.codeId } }, + { session: harness.session }, + ); + expect(harness.session.commitTransaction).toHaveBeenCalledTimes(1); + }); + + it('converges after a unique-index race by rereading the active GameSlot assignment', async () => { + const harness = createHarness({ + assignmentInsertError: duplicateKeyError(), + }); + const activeAssignment = { + competitionId: harness.competitionId, + seriesId: harness.seriesId, + gameSlotId: harness.gameSlotId, + tournamentCodeId: harness.codeId, + state: 'reserved', + }; + harness.assignmentModel.findOne + .mockReturnValueOnce(queryResult(null)) + .mockReturnValueOnce(queryResult(activeAssignment)); + const provisioner = new CompetitionAssignmentProvisioner( + harness.connectionService as never, + ); + + const result = await provisioner.provisionReadyAssignments({ + matchId: harness.matchId, + competition: harness.competition, + }); + + expect(result).toMatchObject({ reserved: 0, existing: 1, unavailable: 0 }); + expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1); + expect(harness.session.endSession).toHaveBeenCalledTimes(1); + }); + + it('releases a reserved code when an early Series outcome makes its GameSlot inactive', async () => { + const harness = createHarness(); + harness.competition.projection.gameSlots[0].status = 'inactive'; + const assignmentId = new mongoose.Types.ObjectId(); + harness.assignmentModel.find.mockReturnValue( + queryResult([ + { + _id: assignmentId, + competitionId: harness.competitionId, + seriesId: harness.seriesId, + gameSlotId: harness.gameSlotId, + tournamentCodeId: harness.codeId, + state: 'reserved', + }, + ]), + ); + harness.assignmentModel.findOneAndUpdate.mockReturnValue( + queryResult({ _id: assignmentId, state: 'released' }), + ); + const provisioner = new CompetitionAssignmentProvisioner( + harness.connectionService as never, + ); + + const result = await provisioner.provisionReadyAssignments({ + matchId: harness.matchId, + competition: harness.competition, + }); + + expect(result).toMatchObject({ requested: 0, released: 1 }); + expect(harness.assignmentModel.findOneAndUpdate).toHaveBeenCalledWith( + { _id: assignmentId, state: 'reserved' }, + { $set: expect.objectContaining({ state: 'released' }) }, + { returnDocument: 'after', session: harness.session }, + ); + expect(harness.codeModel.findOneAndUpdate).toHaveBeenCalledWith( + { _id: harness.codeId, state: 'reserved' }, + expect.objectContaining({ + $set: expect.objectContaining({ state: 'released' }), + }), + { returnDocument: 'after', session: harness.session }, + ); + expect(harness.matchModel.updateOne).toHaveBeenCalledWith( + { _id: harness.matchId }, + { $pull: { tournamentCodeIds: harness.codeId } }, + { session: harness.session }, + ); + }); + + it('refuses to reserve without a MongoDB transaction', async () => { + const harness = createHarness(); + harness.connectionService.createSession.mockResolvedValue(undefined); + const provisioner = new CompetitionAssignmentProvisioner( + harness.connectionService as never, + ); + + await expect( + provisioner.provisionReadyAssignments({ + matchId: harness.matchId, + competition: harness.competition, + }), + ).rejects.toMatchObject({ + code: 'COMPETITION_ASSIGNMENT_TRANSACTION_UNAVAILABLE', + }); + expect(harness.codeModel.findOneAndUpdate).not.toHaveBeenCalled(); + }); + + it('rejects a stale projection revision before reserving a code', async () => { + const harness = createHarness(); + harness.competitionModel.updateOne.mockResolvedValue({ matchedCount: 0 }); + const provisioner = new CompetitionAssignmentProvisioner( + harness.connectionService as never, + ); + + await expect( + provisioner.provisionReadyAssignments({ + matchId: harness.matchId, + competition: harness.competition, + }), + ).rejects.toMatchObject({ + code: 'COMPETITION_ASSIGNMENT_STALE_REVISION', + }); + expect(harness.codeModel.findOneAndUpdate).not.toHaveBeenCalled(); + }); +}); + +function createHarness(options: { assignmentInsertError?: Error } = {}) { + 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 codeId = new mongoose.Types.ObjectId(); + const competition: CompetitionResultSnapshot = { + competitionId: competitionId.toString(), + revision: 2, + phase: 'running', + teams: [], + projection: { + phase: 'running', + series: [], + games: [], + gameSlots: [ + { + id: gameSlotId.toString(), + seriesId: seriesId.toString(), + ordinal: 1, + displayNumber: 1, + status: 'ready', + }, + ], + }, + }; + const session = { + startTransaction: jest.fn(), + commitTransaction: jest.fn().mockResolvedValue(undefined), + abortTransaction: jest.fn().mockResolvedValue(undefined), + endSession: jest.fn().mockResolvedValue(undefined), + }; + const assignmentModel = { + find: jest.fn().mockReturnValue(queryResult([])), + findOne: jest.fn().mockReturnValue(queryResult(null)), + findOneAndUpdate: jest.fn().mockReturnValue(queryResult(null)), + insertMany: options.assignmentInsertError + ? jest.fn().mockRejectedValue(options.assignmentInsertError) + : jest.fn().mockResolvedValue([]), + }; + const code = { + _id: codeId, + state: 'reserved', + reservedAt: new Date('2026-07-12T10:00:00.000Z'), + }; + const codeModel = { + find: jest.fn().mockReturnValue(queryResult([])), + findOneAndUpdate: jest.fn().mockReturnValue(queryResult(code)), + }; + const matchModel = { + updateOne: jest.fn().mockReturnValue(execResult(undefined)), + }; + const competitionModel = { + findOne: jest.fn().mockReturnValue(queryResult({ _id: competitionId })), + updateOne: jest.fn().mockResolvedValue({ matchedCount: 1 }), + }; + const models: Record = { + tournamentCodeAssignment: assignmentModel, + tournamentCode: codeModel, + match: matchModel, + competition: competitionModel, + }; + const connectionService = { + createSession: jest.fn().mockResolvedValue(session), + getModel: jest + .fn() + .mockImplementation((name: string) => Promise.resolve(models[name])), + }; + return { + connectionService, + session, + assignmentModel, + codeModel, + matchModel, + competitionModel, + matchId, + competitionId, + seriesId, + gameSlotId, + codeId, + competition, + }; +} + +function queryResult(value: T) { + const query = { + sort: jest.fn(), + session: jest.fn(), + lean: jest.fn(), + exec: jest.fn().mockResolvedValue(value), + }; + query.sort.mockReturnValue(query); + query.session.mockReturnValue(query); + query.lean.mockReturnValue(query); + return query; +} + +function execResult(value: T) { + return { exec: jest.fn().mockResolvedValue(value) }; +} + +function duplicateKeyError(): Error & { code: number } { + return Object.assign(new Error('E11000 duplicate key'), { code: 11000 }); +} diff --git a/apps/api/src/modules/tournament-result/competition-assignment.provisioner.ts b/apps/api/src/modules/tournament-result/competition-assignment.provisioner.ts new file mode 100644 index 00000000..2eb3304a --- /dev/null +++ b/apps/api/src/modules/tournament-result/competition-assignment.provisioner.ts @@ -0,0 +1,475 @@ +import { Injectable } from '@nestjs/common'; +import { createHash } from 'node:crypto'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../tournament-code/tournament-code.constants'; +import type { + CompetitionResultGameSlotProjection, + CompetitionResultSnapshot, +} from './competition-result.adapter'; + +const PROVISION_ATTEMPTS = 3; +const ACTIVE_ASSIGNMENT_STATES = ['reserved', 'used'] as const; + +export type CompetitionAssignmentProvisionErrorCode = + | 'COMPETITION_ASSIGNMENT_TRANSACTION_UNAVAILABLE' + | 'COMPETITION_ASSIGNMENT_STALE_REVISION' + | 'COMPETITION_ASSIGNMENT_PROVISION_FAILED'; + +export class CompetitionAssignmentProvisionError extends Error { + constructor( + public readonly code: CompetitionAssignmentProvisionErrorCode, + message: string, + public readonly cause?: unknown, + ) { + super(message); + this.name = 'CompetitionAssignmentProvisionError'; + } +} + +export interface CompetitionAssignmentProvisionResult { + requested: number; + reserved: number; + existing: number; + unavailable: number; + released: number; +} + +type ReservationOutcome = 'reserved' | 'existing' | 'unavailable'; + +interface AssignmentRecord { + _id: mongoose.Types.ObjectId; + competitionId: mongoose.Types.ObjectId; + seriesId: mongoose.Types.ObjectId; + gameSlotId: mongoose.Types.ObjectId; + tournamentCodeId: mongoose.Types.ObjectId; + state: 'reserved' | 'used' | 'released' | 'voided'; +} + +interface CodeRecord { + _id: mongoose.Types.ObjectId; + state: string; + reservedAt?: Date; +} + +@Injectable() +export class CompetitionAssignmentProvisioner { + constructor(private readonly connectionService: ConnectionService) {} + + public async provisionReadyAssignments(params: { + matchId: mongoose.Types.ObjectId; + competition: CompetitionResultSnapshot; + }): Promise { + const targets = uniqueReadyTargets(params.competition); + const released = await this.releaseInactiveAssignments({ + ...params, + readyGameSlotIds: new Set(targets.map(({ id }) => id)), + }); + const result: CompetitionAssignmentProvisionResult = { + requested: targets.length, + reserved: 0, + existing: 0, + unavailable: 0, + released, + }; + + for (const target of targets) { + const outcome = await this.reserveTarget({ ...params, target }); + result[outcome] += 1; + } + return result; + } + + private async releaseInactiveAssignments(params: { + matchId: mongoose.Types.ObjectId; + competition: CompetitionResultSnapshot; + readyGameSlotIds: ReadonlySet; + }): Promise { + const competitionId = objectId( + params.competition.competitionId, + 'Competition', + ); + const [AssignmentModel, TournamentCodeModel, MatchModel, CompetitionModel] = + await Promise.all([ + this.connectionService.getModel('tournamentCodeAssignment'), + this.connectionService.getModel('tournamentCode'), + this.connectionService.getModel('match'), + this.connectionService.getModel('competition'), + ]); + const reserved = (await AssignmentModel.find({ + competitionId, + state: 'reserved', + gameSlotId: { + $nin: [...params.readyGameSlotIds].map((id) => + objectId(id, 'GameSlot'), + ), + }, + }) + .sort({ reservedAt: 1, _id: 1 }) + .lean() + .exec()) as AssignmentRecord[]; + + let released = 0; + for (const assignment of reserved) { + const didRelease = await this.releaseAssignment({ + matchId: params.matchId, + assignment, + AssignmentModel, + TournamentCodeModel, + MatchModel, + CompetitionModel, + competitionId, + expectedRevision: params.competition.revision, + }); + if (didRelease) released += 1; + } + return released; + } + + private async releaseAssignment(params: { + matchId: mongoose.Types.ObjectId; + assignment: AssignmentRecord; + AssignmentModel: mongoose.Model; + TournamentCodeModel: mongoose.Model; + MatchModel: mongoose.Model; + CompetitionModel: mongoose.Model; + competitionId: mongoose.Types.ObjectId; + expectedRevision: number; + }): Promise { + for (let attempt = 1; attempt <= PROVISION_ATTEMPTS; attempt += 1) { + const session = await this.connectionService.createSession(); + if (!session) { + throw new CompetitionAssignmentProvisionError( + 'COMPETITION_ASSIGNMENT_TRANSACTION_UNAVAILABLE', + 'A MongoDB transaction is required to release Competition GameSlot codes.', + ); + } + try { + session.startTransaction(); + await assertCurrentRevision({ + CompetitionModel: params.CompetitionModel, + competitionId: params.competitionId, + expectedRevision: params.expectedRevision, + session, + }); + const releasedAt = new Date(); + const assignment = (await params.AssignmentModel.findOneAndUpdate( + { _id: params.assignment._id, state: 'reserved' }, + { $set: { state: 'released', releasedAt } }, + { returnDocument: 'after', session }, + ).exec()) as AssignmentRecord | null; + if (!assignment) { + await session.commitTransaction(); + return false; + } + const code = (await params.TournamentCodeModel.findOneAndUpdate( + { _id: params.assignment.tournamentCodeId, state: 'reserved' }, + { + $set: { state: 'released', releasedAt }, + $unset: { + matchId: 1, + gameNumber: 1, + bracketMatchId: 1, + reservedAt: 1, + }, + }, + { returnDocument: 'after', session }, + ).exec()) as CodeRecord | null; + if (!code) { + throw new Error( + 'Reserved assignment points to a Tournament Code that is not reserved.', + ); + } + await params.MatchModel.updateOne( + { _id: params.matchId }, + { $pull: { tournamentCodeIds: params.assignment.tournamentCodeId } }, + { session }, + ).exec(); + await session.commitTransaction(); + return true; + } catch (error) { + await session.abortTransaction().catch(() => undefined); + if (isStaleRevisionError(error)) throw error; + const current = (await params.AssignmentModel.findById( + params.assignment._id, + ) + .lean() + .exec()) as AssignmentRecord | null; + if (current && current.state !== 'reserved') return false; + if (attempt < PROVISION_ATTEMPTS && isRetryable(error)) continue; + throw new CompetitionAssignmentProvisionError( + 'COMPETITION_ASSIGNMENT_PROVISION_FAILED', + `Failed to release Tournament Code assignment ${params.assignment._id.toString()}.`, + error, + ); + } finally { + await session.endSession().catch(() => undefined); + } + } + return false; + } + + private async reserveTarget(params: { + matchId: mongoose.Types.ObjectId; + competition: CompetitionResultSnapshot; + target: CompetitionResultGameSlotProjection; + }): Promise { + const competitionId = objectId( + params.competition.competitionId, + 'Competition', + ); + const seriesId = objectId(params.target.seriesId, 'Series'); + const gameSlotId = objectId(params.target.id, 'GameSlot'); + const [AssignmentModel, TournamentCodeModel, MatchModel, CompetitionModel] = + await Promise.all([ + this.connectionService.getModel('tournamentCodeAssignment'), + this.connectionService.getModel('tournamentCode'), + this.connectionService.getModel('match'), + this.connectionService.getModel('competition'), + ]); + + for (let attempt = 1; attempt <= PROVISION_ATTEMPTS; attempt += 1) { + const session = await this.connectionService.createSession(); + if (!session) { + throw new CompetitionAssignmentProvisionError( + 'COMPETITION_ASSIGNMENT_TRANSACTION_UNAVAILABLE', + 'A MongoDB transaction is required to reserve Competition GameSlot codes.', + ); + } + + try { + session.startTransaction(); + await assertCurrentRevision({ + CompetitionModel, + competitionId, + expectedRevision: params.competition.revision, + session, + }); + const existing = (await AssignmentModel.findOne({ + competitionId, + gameSlotId, + state: { $in: ACTIVE_ASSIGNMENT_STATES }, + }) + .session(session) + .lean() + .exec()) as AssignmentRecord | null; + if (existing) { + await session.commitTransaction(); + return 'existing'; + } + + const code = await this.claimCode({ + matchId: params.matchId, + competitionId, + displayNumber: params.target.displayNumber, + AssignmentModel, + TournamentCodeModel, + session, + }); + if (!code) { + await session.commitTransaction(); + return 'unavailable'; + } + + const commandId = `provision-code:${params.competition.competitionId}:${params.target.id}:${params.competition.revision}:${code._id.toString()}`; + await AssignmentModel.insertMany( + [ + { + _id: deterministicObjectId(commandId), + competitionId, + seriesId, + gameSlotId, + tournamentCodeId: code._id, + state: 'reserved', + reservedAt: code.reservedAt ?? new Date(), + commandId, + }, + ], + { session }, + ); + await MatchModel.updateOne( + { _id: params.matchId }, + { $addToSet: { tournamentCodeIds: code._id } }, + { session }, + ).exec(); + await session.commitTransaction(); + return 'reserved'; + } catch (error) { + await session.abortTransaction().catch(() => undefined); + if (isStaleRevisionError(error)) throw error; + const converged = await this.findActiveAssignment( + AssignmentModel, + competitionId, + gameSlotId, + ); + if (converged) return 'existing'; + if (attempt < PROVISION_ATTEMPTS && isRetryable(error)) continue; + throw new CompetitionAssignmentProvisionError( + 'COMPETITION_ASSIGNMENT_PROVISION_FAILED', + `Failed to reserve a Tournament Code for GameSlot ${params.target.id}.`, + error, + ); + } finally { + await session.endSession().catch(() => undefined); + } + } + + throw new CompetitionAssignmentProvisionError( + 'COMPETITION_ASSIGNMENT_PROVISION_FAILED', + `Reservation retry budget was exhausted for GameSlot ${params.target.id}.`, + ); + } + + private async claimCode(params: { + matchId: mongoose.Types.ObjectId; + competitionId: mongoose.Types.ObjectId; + displayNumber: number; + AssignmentModel: mongoose.Model; + TournamentCodeModel: mongoose.Model; + session: mongoose.ClientSession; + }): Promise { + const legacyCandidates = (await params.TournamentCodeModel.find({ + matchId: params.matchId, + state: 'reserved', + gameNumber: params.displayNumber, + }) + .sort({ reservedAt: 1, _id: 1 }) + .session(params.session) + .exec()) as CodeRecord[]; + + for (const candidate of legacyCandidates) { + const assigned = (await params.AssignmentModel.findOne({ + tournamentCodeId: candidate._id, + state: { $in: ACTIVE_ASSIGNMENT_STATES }, + }) + .session(params.session) + .lean() + .exec()) as AssignmentRecord | null; + if (assigned) continue; + const promoted = (await params.TournamentCodeModel.findOneAndUpdate( + { + _id: candidate._id, + matchId: params.matchId, + state: 'reserved', + gameNumber: params.displayNumber, + }, + { $set: { gameNumber: params.displayNumber } }, + { returnDocument: 'after', session: params.session }, + ).exec()) as CodeRecord | null; + if (promoted) return promoted; + } + + return (await params.TournamentCodeModel.findOneAndUpdate( + { + state: 'available', + region: 'kr', + mapType: 'SUMMONERS_RIFT', + teamSize: 5, + expiresAt: { + $gt: new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS), + }, + }, + { + $set: { + state: 'reserved', + matchId: params.matchId, + gameNumber: params.displayNumber, + reservedAt: new Date(), + }, + }, + { + returnDocument: 'after', + session: params.session, + sort: { expiresAt: 1 }, + }, + ).exec()) as CodeRecord | null; + } + + private async findActiveAssignment( + AssignmentModel: mongoose.Model, + competitionId: mongoose.Types.ObjectId, + gameSlotId: mongoose.Types.ObjectId, + ): Promise { + return (await AssignmentModel.findOne({ + competitionId, + gameSlotId, + state: { $in: ACTIVE_ASSIGNMENT_STATES }, + }) + .lean() + .exec()) as AssignmentRecord | null; + } +} + +function uniqueReadyTargets( + competition: CompetitionResultSnapshot, +): CompetitionResultGameSlotProjection[] { + const byId = new Map(); + for (const slot of competition.projection.gameSlots) { + if (slot.status === 'ready') byId.set(slot.id, slot); + } + return [...byId.values()].sort( + (left, right) => + left.displayNumber - right.displayNumber || left.ordinal - right.ordinal, + ); +} + +function objectId(value: string, label: string): mongoose.Types.ObjectId { + if (!mongoose.Types.ObjectId.isValid(value)) { + throw new CompetitionAssignmentProvisionError( + 'COMPETITION_ASSIGNMENT_PROVISION_FAILED', + `${label} id is not a valid ObjectId.`, + ); + } + return new mongoose.Types.ObjectId(value); +} + +function deterministicObjectId(key: string): mongoose.Types.ObjectId { + return new mongoose.Types.ObjectId( + createHash('sha256').update(key).digest('hex').slice(0, 24), + ); +} + +async function assertCurrentRevision(params: { + CompetitionModel: mongoose.Model; + competitionId: mongoose.Types.ObjectId; + expectedRevision: number; + session: mongoose.ClientSession; +}): Promise { + const current = await params.CompetitionModel.updateOne( + { + _id: params.competitionId, + revision: params.expectedRevision, + }, + { $set: { revision: params.expectedRevision } }, + { session: params.session, timestamps: false }, + ); + if (current.matchedCount === 1) return; + throw new CompetitionAssignmentProvisionError( + 'COMPETITION_ASSIGNMENT_STALE_REVISION', + 'Competition changed before Tournament Code assignments were reconciled.', + ); +} + +function isStaleRevisionError( + error: unknown, +): error is CompetitionAssignmentProvisionError { + return ( + error instanceof CompetitionAssignmentProvisionError && + error.code === 'COMPETITION_ASSIGNMENT_STALE_REVISION' + ); +} + +function isRetryable(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'), + ); +} diff --git a/apps/api/src/modules/tournament-result/competition-outbox.processor.spec.ts b/apps/api/src/modules/tournament-result/competition-outbox.processor.spec.ts new file mode 100644 index 00000000..c4c4d816 --- /dev/null +++ b/apps/api/src/modules/tournament-result/competition-outbox.processor.spec.ts @@ -0,0 +1,232 @@ +/* eslint-disable @typescript-eslint/no-unsafe-assignment */ +import mongoose from 'mongoose'; +import { Logger } from '@nestjs/common'; +import { CommunityStatsService } from '../community-stats/community-stats.service'; +import { MatchStatsService } from '../community-stats/match-stats.service'; +import { ConnectionService } from '../global/database/connection.service'; +import { CompetitionAssignmentProvisioner } from './competition-assignment.provisioner'; +import { CompetitionOutboxProcessor } from './competition-outbox.processor'; + +describe('CompetitionOutboxProcessor', () => { + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('leases a projection event and applies idempotent downstream effects', async () => { + const competitionId = new mongoose.Types.ObjectId(); + const matchId = new mongoose.Types.ObjectId(); + const communityId = new mongoose.Types.ObjectId(); + const eventId = new mongoose.Types.ObjectId(); + const event = { + _id: eventId, + competitionId, + revision: 7, + type: 'competition.projection-updated', + state: 'pending', + attemptCount: 1, + }; + const publish = jest.fn(() => executable({ matchedCount: 1 })); + const claim = jest + .fn() + .mockReturnValueOnce(leanExecutable(event)) + .mockReturnValueOnce(leanExecutable(null)); + const matchUpdate = jest.fn(() => executable({ matchedCount: 1 })); + const models = { + competitionOutbox: { + findOneAndUpdate: claim, + updateOne: publish, + }, + competition: { + findById: jest.fn(() => + leanExecutable({ + _id: competitionId, + matchId, + communityId, + revision: 8, + phase: 'completed', + teams: [], + projection: { + phase: 'completed', + series: [], + gameSlots: [], + games: [{ evidence: { type: 'riot', riotMatchId: 'KR_1' } }], + }, + }), + ), + }, + match: { + findById: jest.fn(() => + leanExecutable({ status: 'in-progress', resultPollState: {} }), + ), + updateOne: matchUpdate, + }, + }; + const connection = { + getModel: jest.fn((name: keyof typeof models) => + Promise.resolve(models[name]), + ), + } as unknown as ConnectionService; + const provisionReadyAssignments = jest.fn().mockResolvedValue({}); + const provisioner = { + provisionReadyAssignments, + } as unknown as jest.Mocked; + const buildAndUpsert = jest.fn().mockResolvedValue(undefined); + const stats = { + buildAndUpsert, + } as unknown as jest.Mocked; + const invalidateCommunity = jest.fn().mockResolvedValue(undefined); + const communityStats = { + invalidateCommunity, + } as unknown as jest.Mocked; + const processor = new CompetitionOutboxProcessor( + connection, + provisioner, + stats, + communityStats, + ); + + await expect(processor.drainOnce()).resolves.toBe(1); + + expect(provisionReadyAssignments).toHaveBeenCalledWith({ + matchId, + competition: expect.objectContaining({ + competitionId: competitionId.toString(), + revision: 8, + }), + }); + expect(matchUpdate).toHaveBeenCalledWith( + { _id: matchId }, + { + $set: expect.objectContaining({ + status: 'finished', + 'resultPollState.matchedCount': 1, + 'resultPollState.state': 'complete', + }), + }, + ); + expect(buildAndUpsert).toHaveBeenCalledWith(matchId, { + sourceRevision: 8, + }); + expect(invalidateCommunity).toHaveBeenCalledWith(communityId); + expect(publish).toHaveBeenCalledWith( + { _id: eventId, state: 'pending', attemptCount: 1 }, + expect.objectContaining({ + $set: expect.objectContaining({ state: 'published' }), + }), + ); + }); + + it('marks a leased event failed and retryable when effects cannot run', async () => { + const event = { + _id: new mongoose.Types.ObjectId(), + competitionId: new mongoose.Types.ObjectId(), + revision: 2, + type: 'competition.projection-updated', + state: 'pending', + attemptCount: 3, + }; + const updateOne = jest.fn(() => executable({ matchedCount: 1 })); + const models = { + competitionOutbox: { + findOneAndUpdate: jest + .fn() + .mockReturnValueOnce(leanExecutable(event)) + .mockReturnValueOnce(leanExecutable(null)), + updateOne, + }, + competition: { + findById: jest.fn(() => leanExecutable(null)), + }, + match: {}, + }; + const processor = new CompetitionOutboxProcessor( + { + getModel: jest.fn((name: keyof typeof models) => + Promise.resolve(models[name]), + ), + } as unknown as ConnectionService, + { provisionReadyAssignments: jest.fn() } as never, + { buildAndUpsert: jest.fn() } as never, + { invalidateCommunity: jest.fn() } as never, + ); + + await expect(processor.drainOnce()).resolves.toBe(1); + + expect(updateOne).toHaveBeenCalledWith( + { _id: event._id, state: 'pending', attemptCount: 3 }, + { + $set: expect.objectContaining({ + state: 'failed', + lastError: 'Competition no longer exists.', + availableAt: expect.any(Date), + }), + }, + ); + }); + + it('dead-letters a poison event after the delivery attempt limit', async () => { + const event = { + _id: new mongoose.Types.ObjectId(), + competitionId: new mongoose.Types.ObjectId(), + revision: 2, + type: 'competition.projection-updated', + state: 'pending', + attemptCount: 10, + }; + const updateOne = jest.fn(() => executable({ matchedCount: 1 })); + const models = { + competitionOutbox: { + findOneAndUpdate: jest + .fn() + .mockReturnValueOnce(leanExecutable(event)) + .mockReturnValueOnce(leanExecutable(null)), + updateOne, + }, + competition: { + findById: jest.fn(() => leanExecutable(null)), + }, + match: {}, + }; + const errorLog = jest + .spyOn(Logger.prototype, 'error') + .mockImplementation(() => undefined); + const processor = new CompetitionOutboxProcessor( + { + getModel: jest.fn((name: keyof typeof models) => + Promise.resolve(models[name]), + ), + } as unknown as ConnectionService, + { provisionReadyAssignments: jest.fn() } as never, + { buildAndUpsert: jest.fn() } as never, + { invalidateCommunity: jest.fn() } as never, + ); + + await expect(processor.drainOnce()).resolves.toBe(1); + + expect(updateOne).toHaveBeenCalledWith( + { _id: event._id, state: 'pending', attemptCount: 10 }, + { + $set: { + state: 'dead-letter', + lastError: 'Competition no longer exists.', + }, + }, + ); + expect(errorLog).toHaveBeenCalledWith( + expect.stringContaining('moved to dead-letter after 10 attempts'), + ); + }); +}); + +function leanExecutable(value: T) { + const query = { + lean: jest.fn(), + exec: jest.fn().mockResolvedValue(value), + }; + query.lean.mockReturnValue(query); + return query; +} + +function executable(value: T) { + return { exec: jest.fn().mockResolvedValue(value) }; +} diff --git a/apps/api/src/modules/tournament-result/competition-outbox.processor.ts b/apps/api/src/modules/tournament-result/competition-outbox.processor.ts new file mode 100644 index 00000000..c515c650 --- /dev/null +++ b/apps/api/src/modules/tournament-result/competition-outbox.processor.ts @@ -0,0 +1,333 @@ +import { + Injectable, + Logger, + OnModuleDestroy, + OnModuleInit, +} from '@nestjs/common'; +import mongoose from 'mongoose'; +import { CommunityStatsService } from '../community-stats/community-stats.service'; +import { MatchStatsService } from '../community-stats/match-stats.service'; +import { ConnectionService } from '../global/database/connection.service'; +import { CompetitionAssignmentProvisioner } from './competition-assignment.provisioner'; +import type { CompetitionResultSnapshot } from './competition-result.adapter'; + +const DRAIN_INTERVAL_MS = 5_000; +const PROCESSING_LEASE_MS = 60_000; +const MAX_EVENTS_PER_DRAIN = 20; +const MAX_RETRY_DELAY_MS = 5 * 60_000; +const MAX_DELIVERY_ATTEMPTS = 10; + +interface ClaimedOutboxEvent { + _id: mongoose.Types.ObjectId; + competitionId: mongoose.Types.ObjectId; + revision: number; + type: string; + state: 'pending' | 'failed'; + attemptCount: number; +} + +interface CompetitionEffectDocument { + _id: mongoose.Types.ObjectId; + matchId: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + revision: number; + phase: string; + teams: unknown[]; + projection: Record; +} + +/** + * Delivers durable Competition projection effects. The Mongo outbox lease is + * the retry boundary; every downstream effect is intentionally idempotent so + * an expired lease can be processed safely by another API instance. + */ +@Injectable() +export class CompetitionOutboxProcessor + implements OnModuleInit, OnModuleDestroy +{ + private readonly logger = new Logger(CompetitionOutboxProcessor.name); + private timer?: NodeJS.Timeout; + private draining = false; + + constructor( + private readonly connectionService: ConnectionService, + private readonly assignmentProvisioner: CompetitionAssignmentProvisioner, + private readonly matchStatsService: MatchStatsService, + private readonly communityStatsService: CommunityStatsService, + ) {} + + public onModuleInit(): void { + this.timer = setInterval(() => void this.drainSafely(), DRAIN_INTERVAL_MS); + this.timer.unref?.(); + void this.drainSafely(); + } + + public onModuleDestroy(): void { + if (this.timer) clearInterval(this.timer); + } + + public async drainOnce(limit = MAX_EVENTS_PER_DRAIN): Promise { + if (!Number.isInteger(limit) || limit < 1) return 0; + let processed = 0; + while (processed < limit) { + const event = await this.claimNextEvent(); + if (!event) break; + await this.deliver(event); + processed += 1; + } + return processed; + } + + private async drainSafely(): Promise { + if (this.draining) return; + this.draining = true; + try { + await this.drainOnce(); + } catch (error) { + this.logger.warn( + `Competition outbox drain failed: ${errorMessage(error)}`, + ); + } finally { + this.draining = false; + } + } + + private async claimNextEvent(): Promise { + const OutboxModel = + await this.connectionService.getModel('competitionOutbox'); + const now = new Date(); + return OutboxModel.findOneAndUpdate( + { + state: { $in: ['pending', 'failed'] }, + availableAt: { $lte: now }, + }, + { + $set: { + state: 'pending', + availableAt: new Date(now.getTime() + PROCESSING_LEASE_MS), + }, + $inc: { attemptCount: 1 }, + $unset: { lastError: 1 }, + }, + { + returnDocument: 'after', + sort: { availableAt: 1, revision: 1, _id: 1 }, + }, + ) + .lean() + .exec() as Promise; + } + + private async deliver(event: ClaimedOutboxEvent): Promise { + const OutboxModel = + await this.connectionService.getModel('competitionOutbox'); + try { + if (event.type !== 'competition.projection-updated') { + throw new Error(`Unsupported Competition outbox type ${event.type}.`); + } + await this.applyProjectionEffects(event); + await OutboxModel.updateOne(leaseFilter(event), { + $set: { state: 'published', publishedAt: new Date() }, + $unset: { lastError: 1 }, + }).exec(); + } catch (error) { + const lastError = errorMessage(error).slice(0, 2_000); + if (event.attemptCount >= MAX_DELIVERY_ATTEMPTS) { + const terminal = await OutboxModel.updateOne(leaseFilter(event), { + $set: { + state: 'dead-letter', + lastError, + }, + }).exec(); + if (terminal.matchedCount > 0) { + this.logger.error( + `Competition outbox event ${event._id.toString()} moved to dead-letter after ${event.attemptCount} attempts: ${lastError}`, + ); + } + return; + } + const availableAt = new Date( + Date.now() + retryDelayMilliseconds(event.attemptCount), + ); + await OutboxModel.updateOne(leaseFilter(event), { + $set: { + state: 'failed', + lastError, + availableAt, + }, + }).exec(); + this.logger.warn( + `Competition outbox event ${event._id.toString()} failed: ${lastError}`, + ); + } + } + + private async applyProjectionEffects( + event: ClaimedOutboxEvent, + ): Promise { + const [CompetitionModel, MatchModel] = await Promise.all([ + this.connectionService.getModel('competition'), + this.connectionService.getModel('match'), + ]); + const competition = (await CompetitionModel.findById(event.competitionId) + .lean() + .exec()) as CompetitionEffectDocument | null; + if (!competition) throw new Error('Competition no longer exists.'); + if (competition.revision < event.revision) { + throw new Error( + `Competition revision ${competition.revision} is behind outbox revision ${event.revision}.`, + ); + } + + const snapshot = toResultSnapshot(competition); + await this.assignmentProvisioner.provisionReadyAssignments({ + matchId: competition.matchId, + competition: snapshot, + }); + + const match = await MatchModel.findById(competition.matchId).lean().exec(); + if (!match) throw new Error('Competition Match no longer exists.'); + const phase = projectionPhase(competition.projection); + const gameCount = projectionGames(competition.projection).length; + const status = + phase === 'completed' + ? 'finished' + : gameCount > 0 || match.status === 'finished' + ? 'in-progress' + : match.status; + const set: Record = { status }; + if (match.resultPollState) { + set['resultPollState.matchedCount'] = gameCount; + set['resultPollState.state'] = + phase === 'completed' ? 'complete' : 'polling'; + } + await MatchModel.updateOne( + { _id: competition.matchId }, + { $set: set }, + ).exec(); + + await this.matchStatsService.buildAndUpsert(competition.matchId, { + sourceRevision: competition.revision, + }); + await this.communityStatsService.invalidateCommunity( + competition.communityId, + ); + } +} + +function leaseFilter(event: ClaimedOutboxEvent) { + return { + _id: event._id, + state: 'pending', + attemptCount: event.attemptCount, + }; +} + +function retryDelayMilliseconds(attemptCount: number): number { + return Math.min( + Math.max(1, 2 ** Math.min(attemptCount, 8)) * 1_000, + MAX_RETRY_DELAY_MS, + ); +} + +function toResultSnapshot( + competition: CompetitionEffectDocument, +): CompetitionResultSnapshot { + const projection = competition.projection; + return { + competitionId: competition._id.toString(), + revision: competition.revision, + phase: String(competition.phase) as CompetitionResultSnapshot['phase'], + teams: arrayValue(competition.teams).map((team) => ({ + teamId: idValue(recordValue(team).teamId), + members: arrayValue(recordValue(team).members).map((member) => ({ + userId: idValue(recordValue(member).userId), + })), + })), + projection: { + phase: projectionPhase(projection), + series: arrayValue(projection.series).map((series) => { + const source = recordValue(series); + return { + seriesId: idValue(source.seriesId), + status: String( + source.status, + ) as CompetitionResultSnapshot['projection']['series'][number]['status'], + entries: arrayValue(source.entries).map((entry) => { + const row = recordValue(entry); + return { + slot: String(row.slot) as 'A' | 'B', + teamId: row.teamId == null ? null : idValue(row.teamId), + gameWins: numberValue(row.gameWins), + }; + }), + }; + }), + gameSlots: arrayValue(projection.gameSlots).map((slot) => { + const source = recordValue(slot); + return { + id: idValue(source.id), + seriesId: idValue(source.seriesId), + ordinal: numberValue(source.ordinal), + displayNumber: numberValue(source.displayNumber), + status: String( + source.status, + ) as CompetitionResultSnapshot['projection']['gameSlots'][number]['status'], + }; + }), + games: projectionGames(projection).map((game) => { + const evidence = recordValue(recordValue(game).evidence); + return { + evidence: { + type: typeof evidence.type === 'string' ? evidence.type : undefined, + riotMatchId: + typeof evidence.riotMatchId === 'string' + ? evidence.riotMatchId + : undefined, + }, + }; + }), + }, + }; +} + +function projectionPhase( + projection: Record, +): CompetitionResultSnapshot['projection']['phase'] { + const phase = projection.phase; + if (phase !== 'ready' && phase !== 'running' && phase !== 'completed') { + throw new Error('Competition projection phase is invalid.'); + } + return phase; +} + +function projectionGames(projection: Record): unknown[] { + return arrayValue(projection.games); +} + +function recordValue(value: unknown): Record { + return value !== null && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : {}; +} + +function arrayValue(value: unknown): unknown[] { + return Array.isArray(value) ? value : []; +} + +function idValue(value: unknown): string { + if (value instanceof mongoose.Types.ObjectId) return value.toString(); + if (typeof value === 'string') return value; + if (typeof value === 'number' || typeof value === 'bigint') { + return String(value); + } + return ''; +} + +function numberValue(value: unknown): number { + return typeof value === 'number' ? value : Number(value); +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} diff --git a/apps/api/src/modules/tournament-result/competition-result.adapter.spec.ts b/apps/api/src/modules/tournament-result/competition-result.adapter.spec.ts new file mode 100644 index 00000000..08e3bedc --- /dev/null +++ b/apps/api/src/modules/tournament-result/competition-result.adapter.spec.ts @@ -0,0 +1,244 @@ +import mongoose from 'mongoose'; +import type { RiotMatchDto } from '../riot/riot.types'; +import type { MatchPuuidLookup } from './team-mapping.util'; +import { + compareRiotGameChronology, + mapRiotGameToCompetitionSlot, + resolveReadyCompetitionSlot, + type CompetitionResultSnapshot, +} from './competition-result.adapter'; + +const competitionId = new mongoose.Types.ObjectId().toString(); +const seriesId = new mongoose.Types.ObjectId().toString(); +const gameSlotId = new mongoose.Types.ObjectId().toString(); +const teamAId = new mongoose.Types.ObjectId().toString(); +const teamBId = new mongoose.Types.ObjectId().toString(); + +function fixture(): { + competition: CompetitionResultSnapshot; + detail: RiotMatchDto; + lookup: MatchPuuidLookup; +} { + const users = Array.from({ length: 10 }, (_, index) => ({ + userId: new mongoose.Types.ObjectId(), + puuid: `puuid-${index + 1}`, + })); + const lookup: MatchPuuidLookup = { + puuidByUserId: new Map( + users.map(({ userId, puuid }) => [userId.toString(), puuid]), + ), + userIdByPuuid: new Map(users.map(({ userId, puuid }) => [puuid, userId])), + }; + const competition: CompetitionResultSnapshot = { + competitionId, + revision: 4, + phase: 'running', + teams: [ + { + teamId: teamAId, + members: users.slice(0, 5).map(({ userId }) => ({ + userId: userId.toString(), + })), + }, + { + teamId: teamBId, + members: users.slice(5).map(({ userId }) => ({ + userId: userId.toString(), + })), + }, + ], + projection: { + phase: 'running', + series: [ + { + seriesId, + status: 'ready', + entries: [ + { slot: 'A', teamId: teamAId, gameWins: 0 }, + { slot: 'B', teamId: teamBId, gameWins: 0 }, + ], + }, + ], + gameSlots: [ + { + id: gameSlotId, + seriesId, + ordinal: 1, + displayNumber: 17, + status: 'ready', + }, + ], + games: [], + }, + }; + const participants = [ + ...users.slice(5).map(({ puuid }, index) => ({ + puuid, + participantId: index + 1, + teamId: 100, + championId: index + 1, + kills: 10, + deaths: 2, + assists: 8, + win: true, + })), + ...users.slice(0, 5).map(({ puuid }, index) => ({ + puuid, + participantId: index + 6, + teamId: 200, + championId: index + 6, + kills: 2, + deaths: 10, + assists: 3, + win: false, + })), + ]; + const detail = { + metadata: { + dataVersion: '2', + matchId: 'KR_123456789', + participants: participants.map(({ puuid }) => puuid), + }, + info: { + gameCreation: Date.parse('2026-07-12T10:00:00.000Z'), + gameEndTimestamp: Date.parse('2026-07-12T10:30:00.000Z'), + gameDuration: 1800, + participants, + teams: [ + { teamId: 100, win: true }, + { teamId: 200, win: false }, + ], + }, + } as unknown as RiotMatchDto; + return { competition, detail, lookup }; +} + +describe('Competition result Riot mapping', () => { + it('maps Riot sides to stable team ids using the frozen roster snapshot', () => { + const { competition, detail, lookup } = fixture(); + + const accepted = mapRiotGameToCompetitionSlot({ + competition, + target: competition.projection.gameSlots[0], + detail, + lookup, + }); + + expect(accepted).toMatchObject({ + seriesId, + gameSlotId, + ordinal: 1, + displayNumber: 17, + mapping: { + mappingVersion: 1, + blueTeamId: teamBId, + redTeamId: teamAId, + winnerTeamId: teamBId, + algorithmVersion: 'roster-overlap-v1', + confidence: 1, + diagnostics: { + trustedOverlap: 10, + normalOverlap: 0, + reversedOverlap: 10, + }, + }, + evidence: { + type: 'riot', + riotMatchId: 'KR_123456789', + normalizedSnapshot: { + startedAt: '2026-07-12T10:00:00.000Z', + durationSeconds: 1800, + }, + }, + }); + expect(accepted?.evidence.payloadHash).toMatch(/^[a-f0-9]{64}$/); + expect(accepted?.normalizedParticipants).toHaveLength(10); + expect(typeof accepted?.normalizedParticipants[0]?.userId).toBe('string'); + expect(accepted?.normalizedParticipants[0]).toMatchObject({ + teamId: teamBId, + side: 'blue', + summonerName: '', + tagLine: '', + }); + }); + + it('retains unknown Riot participants as normalized evidence with a null user id', () => { + const { competition, detail, lookup } = fixture(); + detail.info.participants[0].puuid = 'unknown-substitute'; + + const accepted = mapRiotGameToCompetitionSlot({ + competition, + target: competition.projection.gameSlots[0], + detail, + lookup, + }); + + expect(accepted?.mapping.confidence).toBe(0.9); + expect(accepted?.normalizedParticipants).toHaveLength(10); + expect(accepted?.normalizedParticipants[0]).toMatchObject({ + userId: null, + teamId: teamBId, + side: 'blue', + }); + expect(accepted?.mapping.participantAssignments).toHaveLength(9); + }); + + it('resolves a manual result from ready stable GameSlots, not display codes', () => { + const { competition, detail, lookup } = fixture(); + + const accepted = resolveReadyCompetitionSlot({ + competition, + detail, + lookup, + }); + + expect(accepted).toMatchObject({ seriesId, gameSlotId, displayNumber: 17 }); + }); + + it('rejects an untrusted roster overlap instead of guessing a team', () => { + const { competition, detail, lookup } = fixture(); + detail.info.participants.forEach((participant, index) => { + participant.puuid = `unknown-${index}`; + }); + + expect( + mapRiotGameToCompetitionSlot({ + competition, + target: competition.projection.gameSlots[0], + detail, + lookup, + }), + ).toBeNull(); + }); + + it('rejects inconsistent Riot evidence with more than one winning team', () => { + const { competition, detail, lookup } = fixture(); + detail.info.teams.forEach((team) => { + team.win = true; + }); + + expect( + mapRiotGameToCompetitionSlot({ + competition, + target: competition.projection.gameSlots[0], + detail, + lookup, + }), + ).toBeNull(); + }); + + it('orders collected Riot games by occurrence before first-to projection', () => { + const { detail } = fixture(); + const later = { + ...detail, + metadata: { ...detail.metadata, matchId: 'KR_LATER' }, + info: { ...detail.info, gameCreation: detail.info.gameCreation + 60_000 }, + }; + + expect( + [later, detail] + .sort(compareRiotGameChronology) + .map((game) => game.metadata.matchId), + ).toEqual(['KR_123456789', 'KR_LATER']); + }); +}); diff --git a/apps/api/src/modules/tournament-result/competition-result.adapter.ts b/apps/api/src/modules/tournament-result/competition-result.adapter.ts new file mode 100644 index 00000000..8630b188 --- /dev/null +++ b/apps/api/src/modules/tournament-result/competition-result.adapter.ts @@ -0,0 +1,365 @@ +import { createHash } from 'node:crypto'; +import type { RiotMatchDto } from '../riot/riot.types'; +import type { MatchPuuidLookup } from './team-mapping.util'; + +const RIOT_BLUE_TEAM_ID = 100; +const RIOT_RED_TEAM_ID = 200; +const MINIMUM_TRUSTED_OVERLAP = 6; +const MAPPING_ALGORITHM_VERSION = 'roster-overlap-v1'; + +type CompetitionPhase = 'ready' | 'running' | 'completed' | 'cancelled'; + +export interface CompetitionResultTeamSnapshot { + teamId: string; + members: Array<{ userId: string }>; +} + +export interface CompetitionResultSeriesProjection { + seriesId: string; + status: 'inactive' | 'waiting' | 'ready' | 'in-progress' | 'completed'; + entries: Array<{ + slot: 'A' | 'B'; + teamId: string | null; + gameWins: number; + }>; +} + +export interface CompetitionResultGameSlotProjection { + id: string; + seriesId: string; + ordinal: number; + displayNumber: number; + status: 'inactive' | 'waiting' | 'ready' | 'completed' | 'voided'; +} + +export interface CompetitionResultSnapshot { + competitionId: string; + revision: number; + phase: CompetitionPhase; + teams: CompetitionResultTeamSnapshot[]; + projection: { + phase: Exclude; + series: CompetitionResultSeriesProjection[]; + gameSlots: CompetitionResultGameSlotProjection[]; + games: Array<{ + evidence?: { type?: string; riotMatchId?: string }; + }>; + }; +} + +export interface MappedCompetitionRiotGame { + gameId: string; + seriesId: string; + gameSlotId: string; + ordinal: number; + displayNumber: number; + occurredAt: Date; + startedAt: Date; + durationSeconds: number; + normalizedParticipants: Array>; + evidence: { + type: 'riot'; + riotMatchId: string; + payloadHash: string; + normalizedSnapshot: { + startedAt: string; + durationSeconds: number; + participantCount: number; + }; + }; + mapping: { + mappingVersion: 1; + blueTeamId: string; + redTeamId: string; + winnerTeamId: string; + algorithmVersion: typeof MAPPING_ALGORITHM_VERSION; + confidence: number; + diagnostics: { + trustedOverlap: number; + normalOverlap: number; + reversedOverlap: number; + }; + participantAssignments: Array<{ + userId: string; + teamId: string; + side: 'blue' | 'red'; + }>; + snapshot: { + slotATeamId: string; + slotBTeamId: string; + slotAPuuids: string[]; + slotBPuuids: string[]; + bluePuuids: string[]; + redPuuids: string[]; + }; + }; +} + +export function compareRiotGameChronology( + left: RiotMatchDto, + right: RiotMatchDto, +): number { + return ( + left.info.gameCreation - right.info.gameCreation || + left.metadata.matchId.localeCompare(right.metadata.matchId) + ); +} + +export function mapRiotGameToCompetitionSlot(params: { + competition: CompetitionResultSnapshot; + target: CompetitionResultGameSlotProjection; + detail: RiotMatchDto; + lookup: MatchPuuidLookup; +}): MappedCompetitionRiotGame | null { + const { competition, target, detail, lookup } = params; + if (target.status !== 'ready') return null; + const series = competition.projection.series.find( + (candidate) => candidate.seriesId === target.seriesId, + ); + if ( + !series || + (series.status !== 'ready' && series.status !== 'in-progress') + ) { + return null; + } + + const slotATeamId = series.entries.find(({ slot }) => slot === 'A')?.teamId; + const slotBTeamId = series.entries.find(({ slot }) => slot === 'B')?.teamId; + if (!slotATeamId || !slotBTeamId || slotATeamId === slotBTeamId) return null; + const slotATeam = competition.teams.find( + ({ teamId }) => teamId === slotATeamId, + ); + const slotBTeam = competition.teams.find( + ({ teamId }) => teamId === slotBTeamId, + ); + if (!slotATeam || !slotBTeam) return null; + + const slotAPuuids = rosterPuuids(slotATeam, lookup); + const slotBPuuids = rosterPuuids(slotBTeam, lookup); + const bluePuuids = participantPuuids(detail, RIOT_BLUE_TEAM_ID); + const redPuuids = participantPuuids(detail, RIOT_RED_TEAM_ID); + const normalOverlap = + countOverlap(bluePuuids, slotAPuuids) + + countOverlap(redPuuids, slotBPuuids); + const reversedOverlap = + countOverlap(bluePuuids, slotBPuuids) + + countOverlap(redPuuids, slotAPuuids); + const trustedOverlap = Math.max(normalOverlap, reversedOverlap); + if ( + trustedOverlap < MINIMUM_TRUSTED_OVERLAP || + normalOverlap === reversedOverlap + ) { + return null; + } + + const blueTeamId = + normalOverlap > reversedOverlap ? slotATeamId : slotBTeamId; + const redTeamId = normalOverlap > reversedOverlap ? slotBTeamId : slotATeamId; + const winningRiotTeams = detail.info.teams.filter( + ({ teamId, win }) => + win && (teamId === RIOT_BLUE_TEAM_ID || teamId === RIOT_RED_TEAM_ID), + ); + if (winningRiotTeams.length !== 1) return null; + const winningRiotTeam = winningRiotTeams[0]; + const winnerTeamId = + winningRiotTeam?.teamId === RIOT_BLUE_TEAM_ID + ? blueTeamId + : winningRiotTeam?.teamId === RIOT_RED_TEAM_ID + ? redTeamId + : undefined; + if (!winnerTeamId) return null; + + const startedAt = new Date(detail.info.gameCreation); + const durationSeconds = detail.info.gameDuration; + const occurredAt = new Date( + detail.info.gameEndTimestamp ?? + detail.info.gameCreation + durationSeconds * 1_000, + ); + const normalizedParticipants = detail.info.participants.flatMap( + (participant) => { + const userId = lookup.userIdByPuuid.get(participant.puuid); + const teamId = + participant.teamId === RIOT_BLUE_TEAM_ID + ? blueTeamId + : participant.teamId === RIOT_RED_TEAM_ID + ? redTeamId + : undefined; + const side = + participant.teamId === RIOT_BLUE_TEAM_ID + ? 'blue' + : participant.teamId === RIOT_RED_TEAM_ID + ? 'red' + : undefined; + if (!teamId || !side) return []; + return [ + { + userId: userId?.toString() ?? null, + teamId, + side, + summonerName: + participant.riotIdGameName ?? participant.summonerName ?? '', + tagLine: participant.riotIdTagLine ?? '', + championId: participant.championId, + kills: participant.kills, + deaths: participant.deaths, + assists: participant.assists, + }, + ]; + }, + ); + + return { + gameId: deterministicGameId( + competition.competitionId, + detail.metadata.matchId, + ), + seriesId: target.seriesId, + gameSlotId: target.id, + ordinal: target.ordinal, + displayNumber: target.displayNumber, + occurredAt, + startedAt, + durationSeconds, + normalizedParticipants, + evidence: { + type: 'riot', + riotMatchId: detail.metadata.matchId, + payloadHash: sha256(detail), + normalizedSnapshot: { + startedAt: startedAt.toISOString(), + durationSeconds, + participantCount: normalizedParticipants.length, + }, + }, + mapping: { + mappingVersion: 1, + blueTeamId, + redTeamId, + winnerTeamId, + algorithmVersion: MAPPING_ALGORITHM_VERSION, + confidence: + trustedOverlap / Math.max(slotAPuuids.length + slotBPuuids.length, 1), + diagnostics: { trustedOverlap, normalOverlap, reversedOverlap }, + participantAssignments: normalizedParticipants.flatMap((participant) => + typeof participant.userId === 'string' + ? [ + { + userId: participant.userId, + teamId: String(participant.teamId), + side: participant.side as 'blue' | 'red', + }, + ] + : [], + ), + snapshot: { + slotATeamId, + slotBTeamId, + slotAPuuids, + slotBPuuids, + bluePuuids, + redPuuids, + }, + }, + }; +} + +export function resolveReadyCompetitionSlot(params: { + competition: CompetitionResultSnapshot; + detail: RiotMatchDto; + lookup: MatchPuuidLookup; +}): MappedCompetitionRiotGame | null { + const firstReadySlotBySeries = new Map< + string, + CompetitionResultGameSlotProjection + >(); + for (const slot of [...params.competition.projection.gameSlots].sort( + (left, right) => + left.displayNumber - right.displayNumber || left.ordinal - right.ordinal, + )) { + if (slot.status !== 'ready' || firstReadySlotBySeries.has(slot.seriesId)) { + continue; + } + firstReadySlotBySeries.set(slot.seriesId, slot); + } + + const candidates = [...firstReadySlotBySeries.values()] + .map((target) => mapRiotGameToCompetitionSlot({ ...params, target })) + .filter((candidate): candidate is MappedCompetitionRiotGame => + Boolean(candidate), + ) + .sort( + (left, right) => + right.mapping.diagnostics.trustedOverlap - + left.mapping.diagnostics.trustedOverlap || + left.displayNumber - right.displayNumber, + ); + if (candidates.length === 0) return null; + if ( + candidates.length > 1 && + candidates[0].mapping.diagnostics.trustedOverlap === + candidates[1].mapping.diagnostics.trustedOverlap + ) { + return null; + } + return candidates[0]; +} + +export function hasAcceptedRiotMatch( + competition: CompetitionResultSnapshot, + riotMatchId: string, +): boolean { + return competition.projection.games.some( + ({ evidence }) => + evidence?.type === 'riot' && evidence.riotMatchId === riotMatchId, + ); +} + +function rosterPuuids( + team: CompetitionResultTeamSnapshot, + lookup: MatchPuuidLookup, +): string[] { + return team.members.flatMap(({ userId }) => { + const puuid = lookup.puuidByUserId.get(userId); + return puuid ? [puuid] : []; + }); +} + +function participantPuuids(detail: RiotMatchDto, riotTeamId: number): string[] { + return detail.info.participants + .filter(({ teamId }) => teamId === riotTeamId) + .map(({ puuid }) => puuid); +} + +function countOverlap(left: string[], right: string[]): number { + const rightSet = new Set(right); + return left.filter((item) => rightSet.has(item)).length; +} + +function deterministicGameId( + competitionId: string, + riotMatchId: string, +): string { + return sha256([competitionId, 'riot-game', riotMatchId]).slice(0, 24); +} + +function sha256(value: unknown): string { + return createHash('sha256').update(canonicalJson(value)).digest('hex'); +} + +function canonicalJson(value: unknown): string { + return JSON.stringify(canonicalize(value)); +} + +function canonicalize(value: unknown): unknown { + if (value instanceof Date) return value.toISOString(); + if (Array.isArray(value)) return value.map(canonicalize); + if (value && typeof value === 'object') { + return Object.fromEntries( + Object.entries(value as Record) + .filter(([, child]) => child !== undefined) + .sort(([left], [right]) => left.localeCompare(right)) + .map(([key, child]) => [key, canonicalize(child)]), + ); + } + return value; +} diff --git a/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts b/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts index 4a254382..5002840f 100644 --- a/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts +++ b/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts @@ -1,156 +1,44 @@ import mongoose from 'mongoose'; import type { MatchDocument } from '../global/database/schema'; -import type { RiotMatchDto } from '../riot/riot.types'; -import { computeGameResult, type MatchPuuidLookup } from './team-mapping.util'; +import { collectCaptainAndLimitedTeamMemberUserIds } from './team-mapping.util'; -function makeMatch(): { - match: MatchDocument; - lookup: MatchPuuidLookup; - blueUserIds: mongoose.Types.ObjectId[]; - redUserIds: mongoose.Types.ObjectId[]; -} { - const blueUserIds = Array.from({ length: 5 }, () => new mongoose.Types.ObjectId()); - const redUserIds = Array.from({ length: 5 }, () => new mongoose.Types.ObjectId()); - const puuidByUserId = new Map(); - const userIdByPuuid = new Map(); - - for (const [index, userId] of [...blueUserIds, ...redUserIds].entries()) { - const puuid = `puuid-${index}`; - puuidByUserId.set(userId.toString(), puuid); - userIdByPuuid.set(puuid, userId); - } - - const match = { - teams: [ - { - teamIndex: 1, - name: '1팀', - members: blueUserIds.map((userId) => ({ - userId, - assignedPosition: 'MID', - })), - }, - { - teamIndex: 2, - name: '2팀', - members: redUserIds.map((userId) => ({ - userId, - assignedPosition: 'MID', - })), - }, - ], - participants: [...blueUserIds, ...redUserIds].map((userId, index) => ({ - userId, - puuid: `puuid-${index}`, - preferredPositions: [], - joinedAt: new Date(), - })), - } as unknown as MatchDocument; - - return { match, lookup: { puuidByUserId, userIdByPuuid }, blueUserIds, redUserIds }; -} - -function makeRiotMatch(params: { - team100Puuids: string[]; - team200Puuids: string[]; - winningTeamId: 100 | 200; -}): RiotMatchDto { - const participants = [ - ...params.team100Puuids.map((puuid, index) => ({ - puuid, - participantId: index + 1, - teamId: 100, - championId: 10 + index, - kills: index, - deaths: 1, - assists: 2, - win: params.winningTeamId === 100, - })), - ...params.team200Puuids.map((puuid, index) => ({ - puuid, - participantId: index + 6, - teamId: 200, - championId: 20 + index, - kills: index, - deaths: 2, - assists: 3, - win: params.winningTeamId === 200, - })), - ]; - - return { - metadata: { - dataVersion: '2', - matchId: 'KR_1', - participants: participants.map((participant) => participant.puuid), - }, - info: { - gameCreation: 1, - gameDuration: 1800, - participants, +describe('collectCaptainAndLimitedTeamMemberUserIds', () => { + it('keeps captains and caps extra members per team', () => { + const blueUserIds = Array.from( + { length: 5 }, + () => new mongoose.Types.ObjectId(), + ); + const redUserIds = Array.from( + { length: 5 }, + () => new mongoose.Types.ObjectId(), + ); + const match = { teams: [ - { teamId: 100, win: params.winningTeamId === 100 }, - { teamId: 200, win: params.winningTeamId === 200 }, + { + teamIndex: 1, + captainUserId: blueUserIds[0], + members: blueUserIds.map((userId) => ({ userId })), + }, + { + teamIndex: 2, + captainUserId: redUserIds[0], + members: redUserIds.map((userId) => ({ userId })), + }, ], - }, - } as unknown as RiotMatchDto; -} + participants: [], + } as unknown as MatchDocument; -describe('computeGameResult', () => { - it('maps Riot teams to local blue/red by overlap', () => { - const { match, lookup } = makeMatch(); - const detail = makeRiotMatch({ - team100Puuids: ['puuid-0', 'puuid-1', 'puuid-2', 'puuid-3', 'puuid-4'], - team200Puuids: ['puuid-5', 'puuid-6', 'puuid-7', 'puuid-8', 'puuid-9'], - winningTeamId: 100, - }); + const userIds = collectCaptainAndLimitedTeamMemberUserIds(match, 2).map( + (userId) => userId.toString(), + ); - const result = computeGameResult({ match, lookup, detail, gameNumber: 1 }); - - expect(result).toMatchObject({ - gameNumber: 1, - riotMatchId: 'KR_1', - winnerSide: 'blue', - blueTeamIndex: 1, - redTeamIndex: 2, - winnerTeamIndex: 1, - gameDuration: 1800, - }); - expect(result?.participants).toHaveLength(10); - expect(result?.participants[0]).toMatchObject({ - teamIndex: 1, - side: 'blue', - }); - }); - - it('handles reversed Riot side assignment', () => { - const { match, lookup } = makeMatch(); - const detail = makeRiotMatch({ - team100Puuids: ['puuid-5', 'puuid-6', 'puuid-7', 'puuid-8', 'puuid-9'], - team200Puuids: ['puuid-0', 'puuid-1', 'puuid-2', 'puuid-3', 'puuid-4'], - winningTeamId: 100, - }); - - const result = computeGameResult({ match, lookup, detail, gameNumber: 2 }); - - expect(result).toMatchObject({ - blueTeamIndex: 2, - redTeamIndex: 1, - winnerSide: 'blue', - winnerTeamIndex: 2, - }); - }); - - it('rejects matches with too little overlap', () => { - const { match, lookup } = makeMatch(); - const detail = makeRiotMatch({ - team100Puuids: ['other-1', 'other-2', 'other-3', 'other-4', 'other-5'], - team200Puuids: ['other-6', 'other-7', 'other-8', 'other-9', 'other-10'], - winningTeamId: 100, - }); - - const result = computeGameResult({ match, lookup, detail, gameNumber: 3 }); - - expect(result).toBeNull(); + expect(userIds).toEqual([ + blueUserIds[0].toString(), + blueUserIds[1].toString(), + blueUserIds[2].toString(), + redUserIds[0].toString(), + redUserIds[1].toString(), + redUserIds[2].toString(), + ]); }); }); diff --git a/apps/api/src/modules/tournament-result/team-mapping.util.ts b/apps/api/src/modules/tournament-result/team-mapping.util.ts index 8f463365..5bfcab03 100644 --- a/apps/api/src/modules/tournament-result/team-mapping.util.ts +++ b/apps/api/src/modules/tournament-result/team-mapping.util.ts @@ -1,140 +1,54 @@ import mongoose from 'mongoose'; -import type { MatchDocument, MatchGameResult, TeamSide } from '../global/database/schema'; -import type { RiotMatchDto } from '../riot/riot.types'; - -const RIOT_BLUE_TEAM_ID = 100; -const RIOT_RED_TEAM_ID = 200; -const MINIMUM_TRUSTED_OVERLAP = 6; +import type { MatchDocument } from '../global/database/schema'; export interface MatchPuuidLookup { puuidByUserId: Map; userIdByPuuid: Map; } -export function collectCaptainUserIds(match: MatchDocument): mongoose.Types.ObjectId[] { +export function collectCaptainUserIds( + match: MatchDocument, +): mongoose.Types.ObjectId[] { return match.teams .map((team) => team.captainUserId) .filter((userId): userId is mongoose.Types.ObjectId => Boolean(userId)); } -export function collectMatchUserIds(match: MatchDocument): mongoose.Types.ObjectId[] { +export function collectCaptainAndLimitedTeamMemberUserIds( + match: MatchDocument, + memberLimitPerTeam: number, +): mongoose.Types.ObjectId[] { + const ids = new Map(); + for (const team of match.teams) { + if (team.captainUserId) { + ids.set(team.captainUserId.toString(), team.captainUserId); + } + let memberCount = 0; + for (const member of team.members) { + if (team.captainUserId?.toString() === member.userId.toString()) { + continue; + } + if (memberCount >= memberLimitPerTeam) break; + ids.set(member.userId.toString(), member.userId); + memberCount += 1; + } + } + return [...ids.values()]; +} + +export function collectMatchUserIds( + match: MatchDocument, +): mongoose.Types.ObjectId[] { const ids = new Map(); for (const participant of match.participants) { ids.set(participant.userId.toString(), participant.userId); } for (const team of match.teams) { - if (team.captainUserId) ids.set(team.captainUserId.toString(), team.captainUserId); + if (team.captainUserId) + ids.set(team.captainUserId.toString(), team.captainUserId); for (const member of team.members) { ids.set(member.userId.toString(), member.userId); } } return [...ids.values()]; } - -export function collectTeamPuuids( - match: MatchDocument, - teamIndex: number, - lookup: MatchPuuidLookup, -): string[] { - const team = match.teams.find((item) => item.teamIndex === teamIndex); - if (!team) return []; - const userIds = [ - ...(team.captainUserId ? [team.captainUserId] : []), - ...team.members.map((member) => member.userId), - ]; - return userIds - .map((userId) => lookup.puuidByUserId.get(userId.toString())) - .filter((puuid): puuid is string => Boolean(puuid)); -} - -export function computeGameResult(params: { - match: MatchDocument; - detail: RiotMatchDto; - gameNumber: number; - lookup: MatchPuuidLookup; - teamAIndex?: number; - teamBIndex?: number; -}): MatchGameResult | null { - const { - match, - detail, - gameNumber, - lookup, - teamAIndex = 1, - teamBIndex = 2, - } = params; - const teamAPuuids = collectTeamPuuids(match, teamAIndex, lookup); - const teamBPuuids = collectTeamPuuids(match, teamBIndex, lookup); - const team100Puuids = detail.info.participants - .filter((participant) => participant.teamId === RIOT_BLUE_TEAM_ID) - .map((participant) => participant.puuid); - const team200Puuids = detail.info.participants - .filter((participant) => participant.teamId === RIOT_RED_TEAM_ID) - .map((participant) => participant.puuid); - - const normalOverlap = - countOverlap(team100Puuids, teamAPuuids) + - countOverlap(team200Puuids, teamBPuuids); - const reversedOverlap = - countOverlap(team100Puuids, teamBPuuids) + - countOverlap(team200Puuids, teamAPuuids); - const blueTeamIndex = normalOverlap >= reversedOverlap ? teamAIndex : teamBIndex; - const redTeamIndex = normalOverlap >= reversedOverlap ? teamBIndex : teamAIndex; - const teamIndexByRiotTeamId: Record = { - [RIOT_BLUE_TEAM_ID]: blueTeamIndex, - [RIOT_RED_TEAM_ID]: redTeamIndex, - }; - const sideByRiotTeamId: Record = { - [RIOT_BLUE_TEAM_ID]: 'blue', - [RIOT_RED_TEAM_ID]: 'red', - }; - - if (Math.max(normalOverlap, reversedOverlap) < MINIMUM_TRUSTED_OVERLAP) { - return null; - } - - const winningTeam = detail.info.teams.find((team) => team.win); - if (!winningTeam) return null; - const winnerSide = sideByRiotTeamId[winningTeam.teamId]; - if (!winnerSide) return null; - const winnerTeamIndex = teamIndexByRiotTeamId[winningTeam.teamId]; - if (!winnerTeamIndex) return null; - - const participants = detail.info.participants - .map((participant) => { - const userId = lookup.userIdByPuuid.get(participant.puuid); - const side = sideByRiotTeamId[participant.teamId]; - const teamIndex = teamIndexByRiotTeamId[participant.teamId]; - if (!userId || !side || !teamIndex) return null; - return { - userId, - teamIndex, - side, - championId: participant.championId, - kills: participant.kills, - deaths: participant.deaths, - assists: participant.assists, - win: participant.win, - }; - }) - .filter((participant): participant is NonNullable => - Boolean(participant), - ); - - return { - gameNumber, - riotMatchId: detail.metadata.matchId, - blueTeamIndex, - redTeamIndex, - winnerTeamIndex, - winnerSide, - gameCreation: detail.info.gameCreation, - gameDuration: detail.info.gameDuration, - participants, - }; -} - -export function countOverlap(left: string[], right: string[]): number { - const rightSet = new Set(right); - return left.filter((item) => rightSet.has(item)).length; -} diff --git a/apps/api/src/modules/tournament-result/tournament-result.cutover.spec.ts b/apps/api/src/modules/tournament-result/tournament-result.cutover.spec.ts new file mode 100644 index 00000000..514867d4 --- /dev/null +++ b/apps/api/src/modules/tournament-result/tournament-result.cutover.spec.ts @@ -0,0 +1,294 @@ +/* eslint-disable @typescript-eslint/no-unsafe-assignment */ +import mongoose from 'mongoose'; +import type { MatchDocument } from '../global/database/schema'; +import type { RiotMatchDto } from '../riot/riot.types'; +import { TournamentResultService } from './tournament-result.service'; + +describe('TournamentResultService Competition cutover', () => { + it('accepts a manually collected Riot game through Competition without mutating legacy result state', async () => { + const communityId = new mongoose.Types.ObjectId(); + const matchId = new mongoose.Types.ObjectId(); + const competitionId = new mongoose.Types.ObjectId(); + const seriesId = new mongoose.Types.ObjectId(); + const earlierGameSlotId = new mongoose.Types.ObjectId(); + const gameSlotId = new mongoose.Types.ObjectId(); + const tournamentCodeId = new mongoose.Types.ObjectId(); + const teamAId = new mongoose.Types.ObjectId(); + const teamBId = new mongoose.Types.ObjectId(); + const users = Array.from({ length: 10 }, (_, index) => ({ + userId: new mongoose.Types.ObjectId(), + puuid: `cutover-puuid-${index + 1}`, + })); + const legacyResult = { + winnerTeamIndex: 2, + riotMatchIds: ['legacy'], + games: [], + seriesResults: [], + }; + const legacyBracket = { marker: 'must-not-change' }; + const match = { + _id: matchId, + communityId, + status: 'team-built', + gameCount: 1, + gameMode: 'pair', + teamBuiltAt: new Date('2026-07-12T09:00:00.000Z'), + tournamentCodeIds: [tournamentCodeId], + participants: users.map(({ userId, puuid }) => ({ + userId, + puuid, + excluded: false, + })), + teams: [ + { + teamIndex: 1, + name: 'Team A', + members: users.slice(0, 5).map(({ userId }) => ({ userId })), + }, + { + teamIndex: 2, + name: 'Team B', + members: users.slice(5).map(({ userId }) => ({ userId })), + }, + ], + result: legacyResult, + doubleElimination: legacyBracket, + save: jest.fn().mockResolvedValue(undefined), + } as unknown as MatchDocument & { save: jest.Mock }; + const readyCompetition = { + _id: competitionId, + revision: 0, + phase: 'ready', + teams: [ + { + teamId: teamAId, + members: users.slice(0, 5).map(({ userId }) => ({ userId })), + }, + { + teamId: teamBId, + members: users.slice(5).map(({ userId }) => ({ userId })), + }, + ], + projection: { + phase: 'ready', + series: [ + { + seriesId: seriesId.toString(), + status: 'ready', + entries: [ + { slot: 'A', teamId: teamAId.toString(), gameWins: 0 }, + { slot: 'B', teamId: teamBId.toString(), gameWins: 0 }, + ], + }, + ], + gameSlots: [ + { + id: earlierGameSlotId.toString(), + seriesId: seriesId.toString(), + ordinal: 1, + displayNumber: 16, + status: 'ready', + }, + { + id: gameSlotId.toString(), + seriesId: seriesId.toString(), + ordinal: 2, + displayNumber: 17, + status: 'ready', + }, + ], + games: [], + }, + }; + const completedCompetition = { + ...readyCompetition, + revision: 1, + phase: 'completed', + projection: { + ...readyCompetition.projection, + phase: 'completed', + games: [ + { + evidence: { type: 'riot', riotMatchId: 'KR_CUTOVER_1' }, + }, + ], + }, + }; + const detail = riotDetail(users.map(({ puuid }) => puuid)); + const connectionService = { + getModel: jest.fn().mockImplementation((name: string) => { + if (name === 'match') { + return Promise.resolve({ + findById: jest.fn().mockResolvedValue(match), + }); + } + if (name === 'community') { + return Promise.resolve({ + findById: jest.fn().mockReturnValue({ + select: jest.fn().mockReturnValue({ + lean: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ riotRegion: 'asia' }), + }), + }), + }), + }); + } + if (name === 'riotMatch') { + return Promise.resolve({ + findOne: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue(null), + }), + updateOne: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue(undefined), + }), + }); + } + if (name === 'competition') { + return Promise.resolve({ + findById: jest.fn().mockReturnValue({ + lean: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue(readyCompetition), + }), + }), + }); + } + if (name === 'tournamentCode') { + return Promise.resolve({ + findOne: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ + _id: tournamentCodeId, + code: 'CUTOVER-CODE', + state: 'reserved', + gameNumber: 17, + }), + }), + }); + } + if (name === 'tournamentCodeAssignment') { + return Promise.resolve({ + findOne: jest.fn().mockReturnValue({ + lean: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ + competitionId, + seriesId, + gameSlotId, + tournamentCodeId, + state: 'reserved', + }), + }), + }), + updateOne: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue(undefined), + }), + }); + } + throw new Error(`Unexpected model ${name}`); + }), + }; + const commandService = { + acceptGame: jest.fn().mockResolvedValue({ + competition: completedCompetition, + commandId: 'cmpcmd-result', + revision: 1, + replayed: false, + }), + }; + const matchStatsService = { + buildAndUpsert: jest.fn().mockResolvedValue(undefined), + }; + const service = new TournamentResultService( + connectionService as never, + { getMatch: jest.fn().mockResolvedValue(detail) } as never, + {} as never, + { invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never, + matchStatsService as never, + { + runWithLock: jest.fn(), + runWithRenewedLock: jest.fn(), + } as never, + { bootstrap: jest.fn().mockResolvedValue(readyCompetition) } as never, + commandService as never, + { + provisionReadyAssignments: jest.fn().mockResolvedValue({ + requested: 1, + reserved: 0, + existing: 1, + unavailable: 0, + }), + } as never, + ); + + const response = await service.collectManualByRiotMatch({ + matchId, + communityId, + riotMatchId: ' KR_CUTOVER_1 ', + }); + + expect(response).toMatchObject({ + scanned: 1, + matched: 1, + skipped: 0, + riotMatchIds: ['KR_CUTOVER_1'], + gameNumbers: [17], + }); + expect(commandService.acceptGame).toHaveBeenCalledWith( + expect.objectContaining({ + competitionId, + expectedRevision: 0, + idempotencyKey: 'riot-result:KR_CUTOVER_1', + seriesId, + gameSlotId, + ordinal: 2, + mapping: expect.objectContaining({ + blueTeamId: teamAId.toString(), + redTeamId: teamBId.toString(), + winnerTeamId: teamAId.toString(), + }), + startedAt: new Date('2026-07-12T10:00:00.000Z'), + durationSeconds: 1800, + participants: expect.any(Array), + tournamentCode: { + tournamentCodeId, + riotMatchId: 'KR_CUTOVER_1', + }, + }), + ); + expect(match.result).toBe(legacyResult); + expect(match.doubleElimination).toBe(legacyBracket); + expect(match.status).toBe('finished'); + expect(matchStatsService.buildAndUpsert).toHaveBeenCalledWith(matchId, { + sourceRevision: 1, + }); + }); +}); + +function riotDetail(puuids: string[]): RiotMatchDto { + const participants = puuids.map((puuid, index) => ({ + puuid, + participantId: index + 1, + teamId: index < 5 ? 100 : 200, + championId: index + 1, + kills: 1, + deaths: 1, + assists: 1, + win: index < 5, + })); + return { + metadata: { + dataVersion: '2', + matchId: 'KR_CUTOVER_1', + participants: puuids, + }, + info: { + tournamentCode: 'CUTOVER-CODE', + gameCreation: Date.parse('2026-07-12T10:00:00.000Z'), + gameEndTimestamp: Date.parse('2026-07-12T10:30:00.000Z'), + gameDuration: 1800, + participants, + teams: [ + { teamId: 100, win: true }, + { teamId: 200, win: false }, + ], + }, + } as unknown as RiotMatchDto; +} diff --git a/apps/api/src/modules/tournament-result/tournament-result.module.ts b/apps/api/src/modules/tournament-result/tournament-result.module.ts index b9281ad0..89db0a0d 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.module.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.module.ts @@ -1,14 +1,26 @@ import { forwardRef, Module } from '@nestjs/common'; import { CommunityStatsModule } from '../community-stats/community-stats.module'; +import { CompetitionModule } from '../competition/competition.module'; import { RiotJobQueueModule } from '../riot-job-queue/riot-job-queue.module'; import { RiotModule } from '../riot/riot.module'; +import { CompetitionAssignmentProvisioner } from './competition-assignment.provisioner'; +import { CompetitionOutboxProcessor } from './competition-outbox.processor'; import { TournamentResultController } from './tournament-result.controller'; import { TournamentResultService } from './tournament-result.service'; @Module({ - imports: [RiotModule, CommunityStatsModule, forwardRef(() => RiotJobQueueModule)], + imports: [ + RiotModule, + CommunityStatsModule, + CompetitionModule, + forwardRef(() => RiotJobQueueModule), + ], controllers: [TournamentResultController], - providers: [TournamentResultService], + providers: [ + CompetitionAssignmentProvisioner, + CompetitionOutboxProcessor, + TournamentResultService, + ], exports: [TournamentResultService], }) export class TournamentResultModule {} diff --git a/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts b/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts index 7c181090..3884231d 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts @@ -1,263 +1,426 @@ +/* eslint-disable @typescript-eslint/no-unsafe-assignment */ import mongoose from 'mongoose'; import type { MatchDocument } from '../global/database/schema'; import type { RiotMatchDto } from '../riot/riot.types'; import { TournamentResultService } from './tournament-result.service'; -type TournamentResultServiceInternals = TournamentResultService & { - resolveRequiredGameSlots(match: MatchDocument): number; - resolveSeriesRefForGameNumber( - match: MatchDocument, - gameNumber: number, - ): { teamAIndex: number; teamBIndex: number }; -}; - -function createService() { - return new TournamentResultService( - {} as never, - {} as never, - {} as never, - {} as never, - {} as never, - ) as unknown as TournamentResultServiceInternals; -} - -interface MatchOverrides { - gameCount?: number; - gameMode?: 'pair' | 'bracket' | 'round-robin'; - participants?: Array<{ excluded?: boolean }>; - teams?: Array<{ teamIndex: number }>; - gameSchedule?: Array<{ - gameNumber: number; - teamAIndex: number; - teamBIndex: number; - }>; -} - -function createMatch(overrides: MatchOverrides): MatchDocument { - return { - gameCount: 1, - gameMode: 'pair', - participants: [], - teams: [], - gameSchedule: [], - ...overrides, - } as unknown as MatchDocument; -} - -describe('TournamentResultService round-robin scheduling', () => { - it('calculates required slots for round-robin polling', () => { - const service = createService(); - const match = createMatch({ - gameMode: 'round-robin', - gameCount: 1, - teams: Array.from({ length: 6 }, (_, index) => ({ - teamIndex: index + 1, - })), +describe('TournamentResultService Competition polling', () => { + it('promotes a reserved legacy code to a stable GameSlot assignment and accepts through Competition', async () => { + const harness = pollHarness({ + storedCode: 'AbC-12345', + riotTournamentCode: 'AbC-12345', }); - expect(service.resolveRequiredGameSlots(match)).toBe(15); - }); - - it('uses persisted round-robin schedule when mapping a game number', () => { - const service = createService(); - const match = createMatch({ - gameMode: 'round-robin', - gameSchedule: [ - { gameNumber: 1, teamAIndex: 3, teamBIndex: 6 }, - { gameNumber: 2, teamAIndex: 1, teamBIndex: 5 }, - ], + await harness.service.processPollJob({ + matchId: harness.match._id.toString(), + attempt: 1, + expandedToAllPuuids: true, }); - expect(service.resolveSeriesRefForGameNumber(match, 2)).toEqual({ - teamAIndex: 1, - teamBIndex: 5, + expect( + harness.assignmentProvisioner.provisionReadyAssignments, + ).toHaveBeenCalledWith({ + matchId: harness.match._id, + competition: expect.objectContaining({ + competitionId: harness.competitionId.toString(), + }), }); - }); - - it('keeps pair game number mapping unchanged', () => { - const service = createService(); - const match = createMatch({ gameCount: 3 }); - - expect(service.resolveSeriesRefForGameNumber(match, 4)).toEqual({ - teamAIndex: 3, - teamBIndex: 4, - }); - }); -}); - -describe('TournamentResultService manual result collection', () => { - function createManualFixture() { - const communityId = new mongoose.Types.ObjectId(); - const matchId = new mongoose.Types.ObjectId(); - const users = Array.from({ length: 10 }, (_, index) => ({ - userId: new mongoose.Types.ObjectId(), - puuid: `puuid-${index + 1}`, - })); - const match = { - _id: matchId, - communityId, - gameCount: 1, - gameMode: 'pair', - teamBuiltAt: new Date('2026-05-03T10:00:00.000Z'), - status: 'team-built', - tournamentCodeIds: [], - gameSchedule: [], - participants: users.map((user) => ({ - userId: user.userId, - puuid: user.puuid, - excluded: false, - })), - teams: [ - { - teamIndex: 1, - members: users.slice(0, 5).map((user) => ({ userId: user.userId })), - }, - { - teamIndex: 2, - members: users.slice(5).map((user) => ({ userId: user.userId })), - }, - ], - save: jest.fn().mockResolvedValue(undefined), - } as unknown as MatchDocument & { - save: jest.Mock; - result?: MatchDocument['result']; - }; - const detail = { - metadata: { - matchId: 'KR_1234567890', - participants: users.map((user) => user.puuid), - }, - info: { - gameCreation: Date.parse('2026-05-03T10:30:00.000Z'), - gameDuration: 1800, - participants: users.map((user, index) => ({ - puuid: user.puuid, - teamId: index < 5 ? 100 : 200, - championId: 1, - kills: 1, - deaths: 1, - assists: 1, - win: index < 5, - })), - teams: [ - { teamId: 100, win: true }, - { teamId: 200, win: false }, - ], - }, - } as unknown as RiotMatchDto; - const communityFindById = jest.fn().mockReturnValue({ - select: jest.fn().mockReturnValue({ - lean: jest.fn().mockReturnValue({ - exec: jest.fn().mockResolvedValue({ riotRegion: 'asia' }), + expect(harness.assignmentModel.updateOne).toHaveBeenCalledWith( + expect.objectContaining({ + competitionId: harness.competitionId, + tournamentCodeId: harness.codeId, + }), + expect.objectContaining({ + $setOnInsert: expect.objectContaining({ + seriesId: harness.seriesId, + gameSlotId: harness.gameSlotId, + state: 'reserved', }), }), - }); - const riotMatchFindOne = jest.fn().mockReturnValue({ - exec: jest.fn().mockResolvedValue(null), - }); - const riotMatchUpdateOne = jest.fn().mockReturnValue({ - exec: jest.fn().mockResolvedValue(undefined), - }); - const tournamentCodeUpdateOne = jest.fn().mockReturnValue({ - exec: jest.fn().mockResolvedValue(undefined), - }); - const connectionService = { - getModel: jest.fn().mockImplementation(async (name: string) => { - if (name === 'match') { - return { findById: jest.fn().mockResolvedValue(match) }; - } - if (name === 'community') { - return { findById: communityFindById }; - } - if (name === 'riotMatch') { - return { - findOne: riotMatchFindOne, - updateOne: riotMatchUpdateOne, - }; - } - if (name === 'tournamentCode') { - return { updateOne: tournamentCodeUpdateOne }; - } - return {}; - }), - }; - const riotMatchService = { - getMatchIdsByPuuid: jest.fn().mockResolvedValue(['KR_1234567890']), - getMatch: jest.fn().mockResolvedValue(detail), - }; - const service = new TournamentResultService( - connectionService as never, - riotMatchService as never, - {} as never, - { invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never, - { buildAndUpsert: jest.fn().mockResolvedValue(undefined) } as never, + { upsert: true }, ); + expect(harness.commandService.acceptGame).toHaveBeenCalledWith( + expect.objectContaining({ + competitionId: harness.competitionId, + seriesId: harness.seriesId, + gameSlotId: harness.gameSlotId, + tournamentCode: { + tournamentCodeId: harness.codeId, + riotMatchId: 'KR_POLL_1', + }, + }), + ); + expect(harness.code.save).not.toHaveBeenCalled(); + expect(harness.match.result).toBeUndefined(); + expect(harness.match.doubleElimination).toBeUndefined(); + expect(harness.match.status).toBe('finished'); + }); - return { - service, - match, - communityId, - matchId, - riotMatchService, - tournamentCodeUpdateOne, - }; - } - - it('collects by time window without setting Riot match type', async () => { - const { service, match, communityId, matchId, riotMatchService } = - createManualFixture(); - - const result = await service.collectManualByWindow({ - matchId, - communityId, - startTime: new Date('2026-05-03T10:00:00.000Z'), - endTime: new Date('2026-05-03T11:00:00.000Z'), + it('keeps tournament-code matching case-sensitive and caps expanded polling members', async () => { + const harness = pollHarness({ + storedCode: 'ABC-12345', + riotTournamentCode: 'abc-12345', }); + await harness.service.processPollJob({ + matchId: harness.match._id.toString(), + attempt: 1, + expandedToAllPuuids: true, + }); + + const polledPuuids = + harness.riotMatchService.getMatchIdsByPuuid.mock.calls.map( + ([puuid]: [string]) => puuid, + ); + expect(polledPuuids).toEqual([ + 'poll-puuid-1', + 'poll-puuid-2', + 'poll-puuid-6', + 'poll-puuid-7', + ]); + expect(harness.commandService.acceptGame).not.toHaveBeenCalled(); + expect(harness.assignmentModel.updateOne).not.toHaveBeenCalled(); + }); + + it('reloads Competition once when assignment provisioning loses the revision CAS', async () => { + const harness = pollHarness({ + storedCode: 'AbC-12345', + riotTournamentCode: 'AbC-12345', + }); + harness.assignmentProvisioner.provisionReadyAssignments + .mockRejectedValueOnce({ + code: 'COMPETITION_ASSIGNMENT_STALE_REVISION', + }) + .mockResolvedValue({ + requested: 1, + reserved: 0, + existing: 1, + unavailable: 0, + released: 0, + }); + + await harness.service.processPollJob({ + matchId: harness.match._id.toString(), + attempt: 1, + expandedToAllPuuids: true, + }); + + expect( + harness.assignmentProvisioner.provisionReadyAssignments, + ).toHaveBeenCalledTimes(3); + expect(harness.commandService.acceptGame).toHaveBeenCalledTimes(1); + }); + + it('resumes polling when a reversal reopens a Competition whose Match was finished', async () => { + const harness = pollHarness({ + storedCode: 'AbC-12345', + riotTournamentCode: 'AbC-12345', + }); + harness.match.status = 'finished'; + + const result = await harness.service.scheduleInitialPoll( + harness.match._id, + 'high', + ); + expect(result).toMatchObject({ - scanned: 1, - matched: 1, - gameNumbers: [1], - riotMatchIds: ['KR_1234567890'], + matchId: harness.match._id.toString(), + attempt: 1, }); - expect(riotMatchService.getMatchIdsByPuuid).toHaveBeenCalledWith( - 'puuid-1', - expect.not.objectContaining({ type: expect.anything() }), - ); - expect(match.result?.games).toHaveLength(1); - expect(match.status).toBe('finished'); - }); - - it('collects directly by Riot match id', async () => { - const { - service, - match, - communityId, - matchId, - riotMatchService, - tournamentCodeUpdateOne, - } = createManualFixture(); - - const result = await service.collectManualByRiotMatch({ - matchId, - communityId, - riotMatchId: ' KR_1234567890 ', - }); - - expect(result.matched).toBe(1); - expect(riotMatchService.getMatchIdsByPuuid).not.toHaveBeenCalled(); - expect(riotMatchService.getMatch).toHaveBeenCalledWith('KR_1234567890', { - region: 'asia', - }); - expect(tournamentCodeUpdateOne).toHaveBeenCalledWith( - expect.objectContaining({ - matchId, - gameNumber: 1, - }), - expect.objectContaining({ - $set: expect.objectContaining({ riotMatchId: 'KR_1234567890' }), - }), - ); - expect(match.result?.games[0].winnerTeamIndex).toBe(1); + expect(harness.match.status).toBe('in-progress'); + expect( + harness.riotJobQueueService.enqueueTournamentResultPoll, + ).toHaveBeenCalledTimes(1); }); }); + +function pollHarness(params: { + storedCode: string; + riotTournamentCode: string; +}) { + const communityId = 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 codeId = new mongoose.Types.ObjectId(); + const teamAId = new mongoose.Types.ObjectId(); + const teamBId = new mongoose.Types.ObjectId(); + const users = Array.from({ length: 10 }, (_, index) => ({ + userId: new mongoose.Types.ObjectId(), + puuid: `poll-puuid-${index + 1}`, + })); + const match = { + _id: matchId, + communityId, + status: 'team-built', + teamBuiltAt: new Date('2026-07-12T09:00:00.000Z'), + gameCount: 1, + gameMode: 'pair', + tournamentCodeIds: [codeId], + resultPollState: { + startedAt: new Date(), + matchedCount: 0, + expandedToAllPuuids: true, + state: 'polling', + }, + participants: users.map(({ userId, puuid }) => ({ + userId, + puuid, + excluded: false, + })), + teams: [ + { + teamIndex: 1, + name: 'Team A', + members: users.slice(0, 5).map(({ userId }) => ({ userId })), + }, + { + teamIndex: 2, + name: 'Team B', + members: users.slice(5).map(({ userId }) => ({ userId })), + }, + ], + save: jest.fn().mockResolvedValue(undefined), + } as unknown as MatchDocument & { save: jest.Mock }; + const code = { + _id: codeId, + code: params.storedCode, + state: 'reserved', + gameNumber: 1, + reservedAt: new Date('2026-07-12T09:00:00.000Z'), + save: jest.fn().mockResolvedValue(undefined), + }; + const readyCompetition = competitionDocument({ + competitionId, + seriesId, + gameSlotId, + teamAId, + teamBId, + users, + completed: false, + }); + const completedCompetition = competitionDocument({ + competitionId, + seriesId, + gameSlotId, + teamAId, + teamBId, + users, + completed: true, + }); + const detail = riotDetail( + users.map(({ puuid }) => puuid), + params.riotTournamentCode, + ); + const assignmentModel = { + findOne: jest.fn().mockReturnValue(queryResult(null)), + updateOne: jest.fn().mockReturnValue(execResult(undefined)), + }; + const connectionService = { + getModel: jest.fn().mockImplementation((name: string) => { + switch (name) { + case 'match': + return Promise.resolve({ + findById: jest.fn().mockResolvedValue(match), + }); + case 'tournamentCode': + return Promise.resolve({ + find: jest.fn().mockReturnValue(sortedResult([code])), + }); + case 'tournamentCodeAssignment': + return Promise.resolve(assignmentModel); + case 'community': + return Promise.resolve({ + findById: jest.fn().mockReturnValue({ + select: jest.fn().mockReturnValue({ + lean: jest + .fn() + .mockReturnValue(execResult({ riotRegion: 'asia' })), + }), + }), + }); + case 'riotMatch': + return Promise.resolve({ + findOne: jest.fn().mockReturnValue(execResult(null)), + updateOne: jest.fn().mockReturnValue(execResult(undefined)), + }); + case 'competition': + return Promise.resolve({ + findById: jest.fn().mockReturnValue(queryResult(readyCompetition)), + }); + default: + throw new Error(`Unexpected model ${name}`); + } + }), + }; + const riotMatchService = { + getMatchIdsByPuuid: jest.fn().mockResolvedValue(['KR_POLL_1']), + getMatch: jest.fn().mockResolvedValue(detail), + }; + const commandService = { + acceptGame: jest.fn().mockResolvedValue({ + competition: completedCompetition, + commandId: 'cmpcmd-poll', + revision: 1, + replayed: false, + }), + }; + const assignmentProvisioner = { + provisionReadyAssignments: jest.fn().mockResolvedValue({ + requested: 1, + reserved: 0, + existing: 1, + unavailable: 0, + }), + }; + const distributedLockService = { + runWithRenewedLock: jest + .fn() + .mockImplementation( + (_options: unknown, operation: (context: object) => Promise) => + operation({}), + ), + runWithLock: jest + .fn() + .mockImplementation( + (_options: unknown, operation: (context: object) => Promise) => + operation({}), + ), + }; + const riotJobQueueService = { + enqueueTournamentResultPoll: jest.fn().mockResolvedValue({ + jobId: 'poll-job-1', + matchId: matchId.toString(), + priority: 'high', + attempt: 1, + expandedToAllPuuids: false, + }), + }; + const service = new TournamentResultService( + connectionService as never, + riotMatchService as never, + riotJobQueueService as never, + { invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never, + { buildAndUpsert: jest.fn().mockResolvedValue(undefined) } as never, + distributedLockService as never, + { bootstrap: jest.fn().mockResolvedValue(readyCompetition) } as never, + commandService as never, + assignmentProvisioner as never, + ); + + return { + service, + match, + code, + competitionId, + seriesId, + gameSlotId, + codeId, + assignmentModel, + commandService, + assignmentProvisioner, + riotMatchService, + riotJobQueueService, + }; +} + +function competitionDocument(params: { + competitionId: mongoose.Types.ObjectId; + seriesId: mongoose.Types.ObjectId; + gameSlotId: mongoose.Types.ObjectId; + teamAId: mongoose.Types.ObjectId; + teamBId: mongoose.Types.ObjectId; + users: Array<{ userId: mongoose.Types.ObjectId }>; + completed: boolean; +}) { + const phase = params.completed ? 'completed' : 'ready'; + return { + _id: params.competitionId, + revision: params.completed ? 1 : 0, + phase, + teams: [ + { + teamId: params.teamAId, + members: params.users.slice(0, 5).map(({ userId }) => ({ userId })), + }, + { + teamId: params.teamBId, + members: params.users.slice(5).map(({ userId }) => ({ userId })), + }, + ], + projection: { + phase, + series: [ + { + seriesId: params.seriesId.toString(), + status: params.completed ? 'completed' : 'ready', + entries: [ + { + slot: 'A', + teamId: params.teamAId.toString(), + gameWins: params.completed ? 1 : 0, + }, + { slot: 'B', teamId: params.teamBId.toString(), gameWins: 0 }, + ], + }, + ], + gameSlots: [ + { + id: params.gameSlotId.toString(), + seriesId: params.seriesId.toString(), + ordinal: 1, + displayNumber: 1, + status: params.completed ? 'completed' : 'ready', + }, + ], + games: params.completed + ? [{ evidence: { type: 'riot', riotMatchId: 'KR_POLL_1' } }] + : [], + }, + }; +} + +function riotDetail(puuids: string[], tournamentCode: string): RiotMatchDto { + const participants = puuids.map((puuid, index) => ({ + puuid, + participantId: index + 1, + teamId: index < 5 ? 100 : 200, + championId: index + 1, + kills: 1, + deaths: 1, + assists: 1, + win: index < 5, + })); + return { + metadata: { dataVersion: '2', matchId: 'KR_POLL_1', participants: puuids }, + info: { + tournamentCode, + gameCreation: Date.parse('2026-07-12T10:00:00.000Z'), + gameEndTimestamp: Date.parse('2026-07-12T10:30:00.000Z'), + gameDuration: 1800, + participants, + teams: [ + { teamId: 100, win: true }, + { teamId: 200, win: false }, + ], + }, + } as unknown as RiotMatchDto; +} + +function execResult(value: T) { + return { exec: jest.fn().mockResolvedValue(value) }; +} + +function sortedResult(value: T) { + return { sort: jest.fn().mockReturnValue(execResult(value)) }; +} + +function queryResult(value: T) { + const query = { + lean: jest.fn(), + exec: jest.fn().mockResolvedValue(value), + }; + query.lean.mockReturnValue(query); + return query; +} diff --git a/apps/api/src/modules/tournament-result/tournament-result.service.ts b/apps/api/src/modules/tournament-result/tournament-result.service.ts index c6f8bb7a..a3fdcb31 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.service.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.service.ts @@ -4,29 +4,40 @@ import { Logger, NotFoundException, } from '@nestjs/common'; +import { createHash } from 'node:crypto'; import mongoose from 'mongoose'; -import { MatchStatsService } from '../community-stats/match-stats.service'; import { CommunityStatsService } from '../community-stats/community-stats.service'; +import { MatchStatsService } from '../community-stats/match-stats.service'; +import { + CompetitionBootstrapService, + type CompetitionBootstrapMatch, +} from '../competition/competition-bootstrap.service'; +import { CompetitionCommandService } from '../competition/competition-command.service'; import { ConnectionService } from '../global/database/connection.service'; import type { MatchDocument, - MatchGameResult, RiotMatch as StoredRiotMatch, TournamentCodeDocument, } from '../global/database/schema'; +import { DistributedLockService } from '../global/redis/distributed-lock.service'; import { RiotJobQueueService } from '../riot-job-queue/riot-job-queue.service'; import type { RiotJobPriority } from '../riot-job-queue/riot-job-queue.types'; import { RiotMatchService } from '../riot/riot-match.service'; import type { RiotMatchDto, RiotRegionalRoute } from '../riot/riot.types'; +import { CompetitionAssignmentProvisioner } from './competition-assignment.provisioner'; import { - resolveRoundRobinTeamCount, - roundRobinPairCount, - roundRobinPairs, -} from '../tournament-code/round-robin.util'; + compareRiotGameChronology, + hasAcceptedRiotMatch, + mapRiotGameToCompetitionSlot, + resolveReadyCompetitionSlot, + type CompetitionResultGameSlotProjection, + type CompetitionResultSnapshot, + type MappedCompetitionRiotGame, +} from './competition-result.adapter'; import { + collectCaptainAndLimitedTeamMemberUserIds, collectCaptainUserIds, collectMatchUserIds, - computeGameResult, type MatchPuuidLookup, } from './team-mapping.util'; import type { @@ -35,17 +46,45 @@ import type { PollTournamentResultJob, } from './tournament-result.types'; -const FIRST_HOUR_POLL_DELAY_MS = 5 * 60_000; +const FIRST_HOUR_POLL_DELAY_MS = 2 * 60_000; const LATER_POLL_DELAY_MS = 60 * 60_000; const POLL_EXPIRY_MS = 24 * 60 * 60_000; const EXPAND_AFTER_MS = 60 * 60_000; +const EXPANDED_MEMBER_LIMIT_PER_TEAM = 2; const TOURNAMENT_LOOKUP_START_MARGIN_SECONDS = 60; +const RESULT_ACCEPT_ATTEMPTS = 2; +const TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_EXPIRATION_DURATION_MILLISECONDS = + 30 * 60_000; +const TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_RENEWAL_INTERVAL_MILLISECONDS = + 5 * 60_000; +const TOURNAMENT_RESULT_POLL_SCHEDULING_LOCK_EXPIRATION_DURATION_MILLISECONDS = + 5 * 60_000; -interface ManualGameAssignment { - gameNumber: number; - teamAIndex: number; - teamBIndex: number; -} +type CompetitionPersistenceDocument = { + _id: mongoose.Types.ObjectId; + revision: number; + phase: string; + teams: unknown[]; + projection: Record; + toObject?: () => unknown; +}; + +type CodeAssignmentRecord = { + competitionId: mongoose.Types.ObjectId; + seriesId: mongoose.Types.ObjectId; + gameSlotId: mongoose.Types.ObjectId; + tournamentCodeId: mongoose.Types.ObjectId; + state: 'reserved' | 'used' | 'released' | 'voided'; +}; + +type AcceptanceOutcome = + | { + kind: 'accepted'; + displayNumber: number; + competition: CompetitionResultSnapshot; + } + | { kind: 'duplicate'; competition: CompetitionResultSnapshot } + | { kind: 'unmatched'; competition: CompetitionResultSnapshot }; @Injectable() export class TournamentResultService { @@ -57,21 +96,48 @@ export class TournamentResultService { private readonly riotJobQueueService: RiotJobQueueService, private readonly communityStatsService: CommunityStatsService, private readonly matchStatsService: MatchStatsService, + private readonly distributedLockService: DistributedLockService, + private readonly competitionBootstrapService: CompetitionBootstrapService, + private readonly competitionCommandService: CompetitionCommandService, + private readonly competitionAssignmentProvisioner: CompetitionAssignmentProvisioner, ) {} public async scheduleInitialPoll( matchOrId: MatchDocument | mongoose.Types.ObjectId, priority: RiotJobPriority = 'high', + ): Promise { + const matchIdentifier = this.resolveMatchIdentifier(matchOrId); + return this.distributedLockService.runWithLock( + { + lockKey: this.tournamentResultPollProcessingLockKey(matchIdentifier), + lockExpirationDurationMilliseconds: + TOURNAMENT_RESULT_POLL_SCHEDULING_LOCK_EXPIRATION_DURATION_MILLISECONDS, + lockAcquireTimeoutMilliseconds: 1_000, + lockRetryDelayMilliseconds: 100, + }, + async () => this.scheduleInitialPollWhileLockOwned(matchOrId, priority), + ); + } + + private async scheduleInitialPollWhileLockOwned( + matchOrId: MatchDocument | mongoose.Types.ObjectId, + priority: RiotJobPriority, ): Promise { const match = await this.loadMatch(matchOrId); - if (match.status === 'finished') return null; if (!this.isReadyToPoll(match)) return null; + let competition = await this.ensureCompetition(match); + competition = await this.provisionCompetitionAssignments( + match, + competition, + ); + if (competition.projection.phase === 'completed') return null; + if (match.status === 'finished') match.status = 'in-progress'; match.resultPollState = { startedAt: match.resultPollState?.startedAt ?? new Date(), lastPolledAt: match.resultPollState?.lastPolledAt, lastPollOutcome: match.resultPollState?.lastPollOutcome, - matchedCount: match.result?.games?.length ?? 0, + matchedCount: competition.projection.games.length, expandedToAllPuuids: false, state: 'polling', }; @@ -95,7 +161,7 @@ export class TournamentResultService { } if (!this.isReadyToPoll(match)) { throw new BadRequestException( - 'Match needs built teams, teamBuiltAt, and tournament codes before polling.', + 'Match needs built teams and teamBuiltAt before polling.', ); } const result = await this.scheduleInitialPoll(match, 'high'); @@ -127,8 +193,8 @@ export class TournamentResultService { collectMatchUserIds(match), lookup, ); - const startTime = Math.floor(params.startTime.getTime() / 1000); - const endTime = Math.floor(params.endTime.getTime() / 1000); + const startTime = Math.floor(params.startTime.getTime() / 1_000); + const endTime = Math.floor(params.endTime.getTime() / 1_000); const riotMatchIds = new Set(); for (const puuid of puuids) { @@ -142,9 +208,7 @@ export class TournamentResultService { ids.forEach((id) => riotMatchIds.add(id)); } catch (error) { this.logger.warn( - `Manual result match id lookup failed for ${puuid}: ${ - error instanceof Error ? error.message : error - }`, + `Manual result match id lookup failed for ${puuid}: ${errorMessage(error)}`, ); } } @@ -164,18 +228,12 @@ export class TournamentResultService { }): Promise { const match = await this.loadMatch(params.matchId); this.assertManualCollectionAllowed(match, params.communityId); - - const normalizedRiotMatchId = params.riotMatchId.trim(); - if (!normalizedRiotMatchId) { - throw new BadRequestException('riotMatchId is required.'); - } + const riotMatchId = params.riotMatchId.trim(); + if (!riotMatchId) throw new BadRequestException('riotMatchId is required.'); const region = await this.resolveRiotRegion(match); const lookup = await this.buildPuuidLookup(match); - const detail = await this.ensureRiotMatchPersisted( - normalizedRiotMatchId, - region, - ); + const detail = await this.ensureRiotMatchPersisted(riotMatchId, region); return this.applyManualRiotMatches(match, [detail], lookup); } @@ -188,149 +246,147 @@ export class TournamentResultService { } public async processPollJob(job: PollTournamentResultJob): Promise { + const didProcess = await this.distributedLockService.runWithRenewedLock( + { + lockKey: this.tournamentResultPollProcessingLockKey(job.matchId), + lockExpirationDurationMilliseconds: + TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_EXPIRATION_DURATION_MILLISECONDS, + lockRenewalIntervalMilliseconds: + TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_RENEWAL_INTERVAL_MILLISECONDS, + }, + async () => { + await this.processPollJobWhileLockOwned(job); + return true; + }, + ); + if (didProcess) return; + this.logger.debug( + `Skipped tournament result poll job ${job.jobId}; another worker is processing match ${job.matchId}.`, + ); + } + + private async processPollJobWhileLockOwned( + job: PollTournamentResultJob, + ): Promise { const MatchModel = await this.connectionService.getModel('match'); const TournamentCodeModel = await this.connectionService.getModel('tournamentCode'); - const CommunityModel = await this.connectionService.getModel('community'); const match = await MatchModel.findById(job.matchId); - if (!match || match.status === 'finished') return; + if (!match) return; if (!this.isReadyToPoll(match)) { await this.updatePollState(match, 'failed', job.expandedToAllPuuids); return; } + let competition = await this.ensureCompetition(match); + competition = await this.provisionCompetitionAssignments( + match, + competition, + ); const codes = await TournamentCodeModel.find({ matchId: match._id }) .sort({ gameNumber: 1 }) .exec(); - const unmatched = codes.filter( + const unmatchedCodes = codes.filter( (code) => code.state === 'reserved' && !code.riotMatchId, ); - if (unmatched.length === 0) { - await this.advanceMatchIfReady(match, codes); + if (unmatchedCodes.length === 0) { + await this.syncMatchLifecycle(match, competition); + if (competition.projection.phase !== 'completed') { + await this.scheduleNextPoll(match, competition, job); + } return; } - const community = await CommunityModel.findById(match.communityId) - .select({ riotRegion: 1 }) - .lean() - .exec(); - const region = community?.riotRegion ?? 'asia'; + const region = await this.resolveRiotRegion(match); const lookup = await this.buildPuuidLookup(match); const puuids = job.expandedToAllPuuids - ? this.collectPollingPuuids(collectMatchUserIds(match), lookup) + ? this.collectPollingPuuids( + collectCaptainAndLimitedTeamMemberUserIds( + match, + EXPANDED_MEMBER_LIMIT_PER_TEAM, + ), + lookup, + ) : this.collectPollingPuuids(collectCaptainUserIds(match), lookup); - - const matchedGameNumbers = new Set(); const checkedRiotMatchIds = new Set(); - const unmatchedByCode = new Map(unmatched.map((code) => [code.code, code])); + const unmatchedByCode = new Map( + unmatchedCodes.map((code) => [code.code, code]), + ); + const collected: Array<{ + detail: RiotMatchDto; + code: TournamentCodeDocument; + tournamentCode: string; + }> = []; + let matched = 0; for (const puuid of puuids) { - let ids: string[]; + let riotMatchIds: string[]; try { - ids = await this.riotMatchService.getMatchIdsByPuuid(puuid, { + riotMatchIds = await this.riotMatchService.getMatchIdsByPuuid(puuid, { region, type: 'tourney', startTime: this.resolveStartTime(match), - endTime: Math.floor(Date.now() / 1000), + endTime: Math.floor(Date.now() / 1_000), count: 100, }); } catch (error) { this.logger.warn( - `Tournament result match id lookup failed for ${puuid}: ${ - error instanceof Error ? error.message : error - }`, + `Tournament result match id lookup failed for ${puuid}: ${errorMessage(error)}`, ); continue; } - for (const riotMatchId of ids) { + for (const riotMatchId of riotMatchIds) { if (checkedRiotMatchIds.has(riotMatchId)) continue; checkedRiotMatchIds.add(riotMatchId); - - const alreadyMatched = await TournamentCodeModel.exists({ - riotMatchId, - }); - if (alreadyMatched) continue; - let detail: RiotMatchDto; try { detail = await this.ensureRiotMatchPersisted(riotMatchId, region); } catch (error) { this.logger.warn( - `Tournament result detail fetch failed for ${riotMatchId}: ${ - error instanceof Error ? error.message : error - }`, + `Tournament result detail fetch failed for ${riotMatchId}: ${errorMessage(error)}`, ); continue; } - const tournamentCode = detail.info.tournamentCode?.trim().toUpperCase(); + const tournamentCode = detail.info.tournamentCode?.trim(); if (!tournamentCode) continue; - const code = unmatchedByCode.get(tournamentCode); if (!code) continue; - - const applied = await this.applyMatchToGameSlot({ - match, - code, - detail, - lookup, - }); - if (applied) { - matchedGameNumbers.add(code.gameNumber ?? 0); - unmatchedByCode.delete(tournamentCode); - } + collected.push({ detail, code, tournamentCode }); } } - const reloadedCodes = await TournamentCodeModel.find({ matchId: match._id }) - .sort({ gameNumber: 1 }) - .exec(); - const outcome = matchedGameNumbers.size > 0 ? 'matched' : 'not-found'; - await this.updatePollState(match, outcome, job.expandedToAllPuuids); - const completed = await this.advanceMatchIfReady(match, reloadedCodes); - if (!completed) { - await this.scheduleNextPoll(match, job); - } - } - - private async applyMatchToGameSlot(params: { - match: MatchDocument; - code: TournamentCodeDocument; - detail: RiotMatchDto; - lookup: MatchPuuidLookup; - }): Promise { - const { match, code, detail, lookup } = params; - if (code.state !== 'reserved' || code.riotMatchId) return false; - if (!code.gameNumber) return false; - - const gameResult = computeGameResult({ - match, - detail, - gameNumber: code.gameNumber, - lookup, - ...this.resolveSeriesRefForGameNumber(match, code.gameNumber), - }); - if (!gameResult) { - this.logger.warn( - `Skipped tournament result ${detail.metadata.matchId}; team mapping was not trusted for match ${match._id.toString()}.`, - ); - return false; - } - - code.state = 'used'; - code.usedAt = new Date( - detail.info.gameEndTimestamp ?? detail.info.gameCreation, + collected.sort((left, right) => + compareRiotGameChronology(left.detail, right.detail), ); - code.riotMatchId = detail.metadata.matchId; - await code.save(); + for (const candidate of collected) { + if (unmatchedByCode.get(candidate.tournamentCode) !== candidate.code) { + continue; + } + const outcome = await this.acceptRiotGame({ + match, + initialCompetition: competition, + detail: candidate.detail, + lookup, + code: candidate.code, + }); + competition = outcome.competition; + if (outcome.kind === 'accepted') matched += 1; + if (outcome.kind !== 'unmatched') { + unmatchedByCode.delete(candidate.tournamentCode); + } + } - this.upsertGameResult(match, gameResult); - if (match.status === 'team-built') { - match.status = 'in-progress'; + await this.updatePollState( + match, + matched > 0 ? 'matched' : 'not-found', + job.expandedToAllPuuids, + competition, + ); + await this.syncMatchLifecycle(match, competition); + if (competition.projection.phase !== 'completed') { + await this.scheduleNextPoll(match, competition, job); } - await match.save(); - await this.rebuildMatchStatsSafe(match); - return true; } private async applyManualRiotMatches( @@ -338,129 +394,330 @@ export class TournamentResultService { details: RiotMatchDto[], lookup: MatchPuuidLookup, ): Promise { - const sortedDetails = [...details].sort( - (left, right) => left.info.gameCreation - right.info.gameCreation, - ); - const appliedRiotMatchIds: string[] = []; - const appliedGameNumbers: number[] = []; + const sortedDetails = [...details].sort(compareRiotGameChronology); + let competition = await this.ensureCompetition(match); + const riotMatchIds: string[] = []; + const gameNumbers: number[] = []; let skipped = 0; for (const detail of sortedDetails) { - if (this.hasResultForRiotMatch(match, detail.metadata.matchId)) { - skipped += 1; - continue; - } - - const gameResult = this.computeManualGameResult(match, detail, lookup); - if (!gameResult) { - skipped += 1; - continue; - } - - this.upsertGameResult(match, gameResult); - await this.markTournamentCodeUsedForManualResult( + const outcome = await this.acceptRiotGame({ match, - gameResult, + initialCompetition: competition, detail, - ); - appliedRiotMatchIds.push(detail.metadata.matchId); - appliedGameNumbers.push(gameResult.gameNumber); + lookup, + }); + competition = outcome.competition; + if (outcome.kind !== 'accepted') { + skipped += 1; + continue; + } + riotMatchIds.push(detail.metadata.matchId); + gameNumbers.push(outcome.displayNumber); } - if (appliedRiotMatchIds.length > 0 && match.status === 'team-built') { - match.status = 'in-progress'; - } - this.updateManualCollectionState(match, appliedRiotMatchIds.length); - await match.save(); - if (appliedRiotMatchIds.length > 0) { - await this.rebuildMatchStatsSafe(match); - } - if (this.hasAllRequiredGameResults(match)) { - await this.finishMatchFromManualResults(match); - } + match.resultPollState = { + startedAt: match.resultPollState?.startedAt ?? new Date(), + lastPolledAt: new Date(), + lastPollOutcome: riotMatchIds.length > 0 ? 'matched' : 'not-found', + matchedCount: competition.projection.games.length, + expandedToAllPuuids: true, + state: + competition.projection.phase === 'completed' ? 'complete' : 'polling', + }; + await this.syncMatchLifecycle(match, competition); return { scanned: sortedDetails.length, - matched: appliedRiotMatchIds.length, + matched: riotMatchIds.length, skipped, - riotMatchIds: appliedRiotMatchIds, - gameNumbers: appliedGameNumbers, + riotMatchIds, + gameNumbers, }; } - private async advanceMatchIfReady( - match: MatchDocument, - codes: TournamentCodeDocument[], - ): Promise { - if (codes.length < this.resolveRequiredGameSlots(match)) return false; - if (!codes.every((code) => code.state === 'used' && code.riotMatchId)) { - return false; - } + private async acceptRiotGame(params: { + match: MatchDocument; + initialCompetition: CompetitionResultSnapshot; + detail: RiotMatchDto; + lookup: MatchPuuidLookup; + code?: TournamentCodeDocument; + }): Promise { + let competition = params.initialCompetition; + for (let attempt = 1; attempt <= RESULT_ACCEPT_ATTEMPTS; attempt += 1) { + if (hasAcceptedRiotMatch(competition, params.detail.metadata.matchId)) { + return { kind: 'duplicate', competition }; + } - match.status = 'finished'; - if (match.result) { - match.result.winnerTeamIndex = this.resolveMatchWinnerTeamIndex( - match.result.seriesResults ?? [], - ); - } - match.resultPollState = { - startedAt: match.resultPollState?.startedAt ?? new Date(), - lastPolledAt: match.resultPollState?.lastPolledAt, - lastPollOutcome: match.resultPollState?.lastPollOutcome, - matchedCount: match.result?.games?.length ?? 0, - expandedToAllPuuids: match.resultPollState?.expandedToAllPuuids ?? false, - state: 'complete', - }; - await match.save(); - await this.rebuildMatchStatsSafe(match); - void this.communityStatsService - .invalidateCommunity(match.communityId) - .catch((error) => { - this.logger.warn( - `Failed to invalidate community stats cache for ${match.communityId.toString()}: ${ - error instanceof Error ? error.message : error - }`, + const declaredCode = + params.code ?? + (await this.findDeclaredTournamentCode(params.match, params.detail)); + const target = declaredCode + ? await this.resolveCodeTarget(competition, declaredCode) + : undefined; + const mapped = target + ? mapRiotGameToCompetitionSlot({ + competition, + target, + detail: params.detail, + lookup: params.lookup, + }) + : declaredCode + ? null + : resolveReadyCompetitionSlot({ + competition, + detail: params.detail, + lookup: params.lookup, + }); + if (!mapped) return { kind: 'unmatched', competition }; + + const manualCode = + declaredCode ?? + (await this.findCodeForMappedSlot(params.match, mapped)); + if (manualCode && !params.code) { + await this.ensureCodeAssignment(competition, manualCode, { + id: mapped.gameSlotId, + seriesId: mapped.seriesId, + ordinal: mapped.ordinal, + displayNumber: mapped.displayNumber, + }); + } + + try { + const result = await this.competitionCommandService.acceptGame({ + competitionId: objectId(competition.competitionId, 'Competition'), + expectedRevision: competition.revision, + idempotencyKey: `riot-result:${params.detail.metadata.matchId}`, + actor: { type: 'system' }, + occurredAt: mapped.occurredAt, + gameId: objectId(mapped.gameId, 'Game'), + seriesId: objectId(mapped.seriesId, 'Series'), + gameSlotId: objectId(mapped.gameSlotId, 'GameSlot'), + ordinal: mapped.ordinal, + evidence: mapped.evidence, + mapping: mapped.mapping, + startedAt: mapped.startedAt, + durationSeconds: mapped.durationSeconds, + participants: mapped.normalizedParticipants, + ...(manualCode + ? { + tournamentCode: { + tournamentCodeId: manualCode._id, + riotMatchId: params.detail.metadata.matchId, + }, + } + : {}), + }); + competition = competitionSnapshot(result.competition); + competition = await this.provisionCompetitionAssignments( + params.match, + competition, ); - }); - return true; + if (!result.replayed) { + await this.rebuildMatchStatsSafe(params.match, result.revision); + } + return { + kind: 'accepted', + displayNumber: mapped.displayNumber, + competition, + }; + } catch (error) { + if (attempt < RESULT_ACCEPT_ATTEMPTS && isStaleRevision(error)) { + competition = await this.loadCompetition(competition.competitionId); + continue; + } + throw error; + } + } + return { kind: 'unmatched', competition }; } - private async scheduleNextPoll( - match: MatchDocument, - job: PollTournamentResultJob, - ): Promise { - const pollState = match.resultPollState; - const startedAt = pollState?.startedAt ?? new Date(); - const elapsedMs = Date.now() - startedAt.getTime(); - const delayMs = this.nextPollDelayMs(elapsedMs); - if (delayMs === null) { - match.resultPollState = { - startedAt, - lastPolledAt: pollState?.lastPolledAt, - lastPollOutcome: pollState?.lastPollOutcome, - matchedCount: match.result?.games?.length ?? 0, - expandedToAllPuuids: - pollState?.expandedToAllPuuids ?? job.expandedToAllPuuids, - state: 'expired', - }; - await match.save(); - this.logger.warn( - `Tournament result polling expired for match ${match._id.toString()}.`, + private async resolveCodeTarget( + competition: CompetitionResultSnapshot, + code: TournamentCodeDocument, + ): Promise { + const AssignmentModel = await this.connectionService.getModel( + 'tournamentCodeAssignment', + ); + const existing = (await AssignmentModel.findOne({ + competitionId: objectId(competition.competitionId, 'Competition'), + tournamentCodeId: code._id, + }) + .lean() + .exec()) as CodeAssignmentRecord | null; + if (existing) { + if (existing.state !== 'reserved') return undefined; + return competition.projection.gameSlots.find( + (slot) => + slot.id === existing.gameSlotId.toString() && slot.status === 'ready', ); - return; } - const expandedToAllPuuids = - job.expandedToAllPuuids || - (elapsedMs >= EXPAND_AFTER_MS && - (match.result?.games?.length ?? 0) === 0); - await this.riotJobQueueService.enqueueTournamentResultPoll({ - matchId: match._id.toString(), - attempt: job.attempt + 1, - expandedToAllPuuids, - priority: 'low', - deferUntilMs: Date.now() + delayMs, - }); + if (!code.gameNumber) return undefined; + const target = competition.projection.gameSlots.find( + (slot) => + slot.displayNumber === code.gameNumber && slot.status === 'ready', + ); + if (!target) return undefined; + await this.ensureCodeAssignment(competition, code, target); + return target; + } + + private async ensureCodeAssignment( + competition: CompetitionResultSnapshot, + code: TournamentCodeDocument, + target: Pick< + CompetitionResultGameSlotProjection, + 'id' | 'seriesId' | 'ordinal' | 'displayNumber' + >, + ): Promise { + const AssignmentModel = await this.connectionService.getModel( + 'tournamentCodeAssignment', + ); + const competitionId = objectId(competition.competitionId, 'Competition'); + const seriesId = objectId(target.seriesId, 'Series'); + const gameSlotId = objectId(target.id, 'GameSlot'); + const commandId = `cutover-assignment:${code._id.toString()}:${target.id}:${competition.revision}`; + await AssignmentModel.updateOne( + { + competitionId, + tournamentCodeId: code._id, + state: { $in: ['reserved', 'used'] }, + }, + { + $setOnInsert: { + _id: deterministicObjectId(commandId), + competitionId, + seriesId, + gameSlotId, + tournamentCodeId: code._id, + state: 'reserved', + reservedAt: code.reservedAt ?? new Date(), + commandId, + }, + }, + { upsert: true }, + ).exec(); + } + + private async findDeclaredTournamentCode( + match: MatchDocument, + detail: RiotMatchDto, + ): Promise { + const tournamentCode = detail.info.tournamentCode?.trim(); + if (!tournamentCode) return undefined; + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const code = await TournamentCodeModel.findOne({ + matchId: match._id, + state: 'reserved', + code: tournamentCode, + }).exec(); + return code ?? undefined; + } + + private async findCodeForMappedSlot( + match: MatchDocument, + mapped: MappedCompetitionRiotGame, + ): Promise { + if (match.tournamentCodeIds.length === 0) return undefined; + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const code = await TournamentCodeModel.findOne({ + _id: { $in: match.tournamentCodeIds }, + matchId: match._id, + state: 'reserved', + gameNumber: mapped.displayNumber, + }).exec(); + return code ?? undefined; + } + + private async ensureCompetition( + match: MatchDocument, + ): Promise { + const document = await this.competitionBootstrapService.bootstrap( + match as unknown as CompetitionBootstrapMatch, + ); + const snapshot = competitionSnapshot(document); + match.competitionId = objectId(snapshot.competitionId, 'Competition'); + return snapshot; + } + + private async provisionCompetitionAssignments( + match: MatchDocument, + competition: CompetitionResultSnapshot, + ): Promise { + try { + await this.competitionAssignmentProvisioner.provisionReadyAssignments({ + matchId: match._id, + competition, + }); + return competition; + } catch (error) { + if (!isAssignmentStaleRevision(error)) throw error; + const current = await this.loadCompetition(competition.competitionId); + await this.competitionAssignmentProvisioner.provisionReadyAssignments({ + matchId: match._id, + competition: current, + }); + return current; + } + } + + private async loadCompetition( + competitionId: string, + ): Promise { + const CompetitionModel = + await this.connectionService.getModel('competition'); + const competition = await CompetitionModel.findById(competitionId) + .lean() + .exec(); + if (!competition) throw new NotFoundException('Competition not found.'); + return competitionSnapshot(competition); + } + + private async syncMatchLifecycle( + match: MatchDocument, + competition: CompetitionResultSnapshot, + ): Promise { + if (competition.projection.phase === 'completed') { + match.status = 'finished'; + if (match.resultPollState) match.resultPollState.state = 'complete'; + } else if ( + (competition.projection.phase === 'running' && + match.status === 'team-built') || + match.status === 'finished' + ) { + match.status = 'in-progress'; + } + if (match.resultPollState) { + match.resultPollState.matchedCount = competition.projection.games.length; + } + await match.save(); + if (competition.projection.phase === 'completed') { + void this.communityStatsService + .invalidateCommunity(match.communityId) + .catch((error) => { + this.logger.warn( + `Failed to invalidate community stats cache for ${match.communityId.toString()}: ${errorMessage(error)}`, + ); + }); + } + } + + private async rebuildMatchStatsSafe( + match: MatchDocument, + sourceRevision: number, + ): Promise { + try { + await this.matchStatsService.buildAndUpsert(match._id, { + sourceRevision, + }); + } catch (error) { + this.logger.warn( + `Failed to rebuild match stats for ${match._id.toString()} at Competition revision ${sourceRevision}: ${errorMessage(error)}`, + ); + } } private async ensureRiotMatchPersisted( @@ -505,11 +762,7 @@ export class TournamentResultService { try { details.push(await this.ensureRiotMatchPersisted(riotMatchId, region)); } catch (error) { - this.logger.warn( - `${logPrefix} ${riotMatchId}: ${ - error instanceof Error ? error.message : error - }`, - ); + this.logger.warn(`${logPrefix} ${riotMatchId}: ${errorMessage(error)}`); } } return details; @@ -520,11 +773,9 @@ export class TournamentResultService { ): Promise { const puuidByUserId = new Map(); const userIdByPuuid = new Map(); - for (const participant of match.participants) { if (!participant.puuid) continue; - const userId = participant.userId.toString(); - puuidByUserId.set(userId, participant.puuid); + puuidByUserId.set(participant.userId.toString(), participant.puuid); userIdByPuuid.set(participant.puuid, participant.userId); } @@ -545,7 +796,6 @@ export class TournamentResultService { userIdByPuuid.set(primary.puuid, user._id); } } - return { puuidByUserId, userIdByPuuid }; } @@ -555,305 +805,72 @@ export class TournamentResultService { ): string[] { return [ ...new Set( - userIds - .map((userId) => lookup.puuidByUserId.get(userId.toString())) - .filter((puuid): puuid is string => Boolean(puuid)), + userIds.flatMap((userId) => { + const puuid = lookup.puuidByUserId.get(userId.toString()); + return puuid ? [puuid] : []; + }), ), ]; } - private upsertGameResult( - match: MatchDocument, - gameResult: MatchGameResult, - ): void { - const currentGames = match.result?.games ?? []; - const games = [ - ...currentGames.filter( - (game) => - game.gameNumber !== gameResult.gameNumber && - game.riotMatchId !== gameResult.riotMatchId, - ), - gameResult, - ].sort((left, right) => left.gameNumber - right.gameNumber); - const seriesResults = this.buildSeriesResults(games); - - match.result = { - winnerTeamIndex: this.resolveMatchWinnerTeamIndex(seriesResults), - mvpUserId: match.result?.mvpUserId, - riotMatchIds: [...new Set(games.map((game) => game.riotMatchId))], - games, - seriesResults, - }; - } - - private computeManualGameResult( - match: MatchDocument, - detail: RiotMatchDto, - lookup: MatchPuuidLookup, - ): MatchGameResult | null { - for (const assignment of this.resolveOpenManualGameAssignments(match)) { - const gameResult = computeGameResult({ - match, - detail, - gameNumber: assignment.gameNumber, - lookup, - teamAIndex: assignment.teamAIndex, - teamBIndex: assignment.teamBIndex, - }); - if (gameResult) return gameResult; - } - return null; - } - - private resolveOpenManualGameAssignments( - match: MatchDocument, - ): ManualGameAssignment[] { - const usedGameNumbers = new Set( - (match.result?.games ?? []).map((game) => game.gameNumber), - ); - const assignments: ManualGameAssignment[] = []; - const requiredSlots = this.resolveRequiredGameSlots(match); - - for (let gameNumber = 1; gameNumber <= requiredSlots; gameNumber += 1) { - if (usedGameNumbers.has(gameNumber)) continue; - assignments.push({ - gameNumber, - ...this.resolveSeriesRefForGameNumber(match, gameNumber), - }); - } - return assignments; - } - - private hasResultForRiotMatch( - match: MatchDocument, - riotMatchId: string, - ): boolean { - return Boolean( - match.result?.games?.some((game) => game.riotMatchId === riotMatchId), - ); - } - - private hasAllRequiredGameResults(match: MatchDocument): boolean { - const requiredSlots = this.resolveRequiredGameSlots(match); - if (requiredSlots <= 0) return false; - const resultGameNumbers = new Set( - (match.result?.games ?? []).map((game) => game.gameNumber), - ); - for (let gameNumber = 1; gameNumber <= requiredSlots; gameNumber += 1) { - if (!resultGameNumbers.has(gameNumber)) return false; - } - return true; - } - - private updateManualCollectionState( - match: MatchDocument, - matchedCount: number, - ): void { - match.resultPollState = { - startedAt: match.resultPollState?.startedAt ?? new Date(), - lastPolledAt: new Date(), - lastPollOutcome: matchedCount > 0 ? 'matched' : 'not-found', - matchedCount: match.result?.games?.length ?? 0, - expandedToAllPuuids: true, - state: 'polling', - }; - } - - private async finishMatchFromManualResults( - match: MatchDocument, - ): Promise { - match.status = 'finished'; - if (match.result) { - match.result.winnerTeamIndex = this.resolveMatchWinnerTeamIndex( - match.result.seriesResults ?? [], - ); - } - match.resultPollState = { - startedAt: match.resultPollState?.startedAt ?? new Date(), - lastPolledAt: new Date(), - lastPollOutcome: 'matched', - matchedCount: match.result?.games?.length ?? 0, - expandedToAllPuuids: true, - state: 'complete', - }; - await match.save(); - await this.rebuildMatchStatsSafe(match); - void this.communityStatsService - .invalidateCommunity(match.communityId) - .catch((error) => { - this.logger.warn( - `Failed to invalidate community stats cache for ${match.communityId.toString()}: ${ - error instanceof Error ? error.message : error - }`, - ); - }); - } - - private async rebuildMatchStatsSafe(match: MatchDocument): Promise { - try { - await this.matchStatsService.buildAndUpsert(match._id); - } catch (error) { - this.logger.warn( - `Failed to rebuild match stats for ${match._id.toString()}: ${ - error instanceof Error ? error.message : error - }`, - ); - } - } - - private async markTournamentCodeUsedForManualResult( - match: MatchDocument, - gameResult: MatchGameResult, - detail: RiotMatchDto, - ): Promise { - const TournamentCodeModel = - await this.connectionService.getModel('tournamentCode'); - await TournamentCodeModel.updateOne( - { - matchId: match._id, - gameNumber: gameResult.gameNumber, - state: { $in: ['reserved', 'released'] }, - }, - { - $set: { - state: 'used', - usedAt: new Date( - detail.info.gameEndTimestamp ?? detail.info.gameCreation, - ), - riotMatchId: detail.metadata.matchId, - }, - }, - ).exec(); - } - - private buildSeriesResults( - games: MatchGameResult[], - ): NonNullable['seriesResults'] { - const bySeries = new Map< - string, - { - teamAIndex: number; - teamBIndex: number; - teamAWins: number; - teamBWins: number; - winnerTeamIndex?: number; - } - >(); - - 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, - }; - 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()].sort( - (left, right) => - left.teamAIndex - right.teamAIndex || - left.teamBIndex - right.teamBIndex, - ); - } - - private resolveSeriesRefForGameNumber( - match: MatchDocument, - gameNumber: number, - ): { teamAIndex: number; teamBIndex: number } { - const gameMode = match.gameMode ?? 'pair'; - - if (gameMode === 'round-robin') { - const persisted = match.gameSchedule?.find( - (entry) => entry.gameNumber === gameNumber, - ); - if (persisted) { - return { - teamAIndex: persisted.teamAIndex, - teamBIndex: persisted.teamBIndex, - }; - } - - const perSeries = match.gameCount || 1; - const pairIndex = Math.max(0, Math.ceil(gameNumber / perSeries) - 1); - return ( - roundRobinPairs(resolveRoundRobinTeamCount(match))[pairIndex] ?? { - teamAIndex: 1, - teamBIndex: 2, - } - ); - } - - const perSeries = match.gameCount || 1; - const seriesIndex = Math.max(1, Math.ceil(gameNumber / perSeries)); - return { - teamAIndex: (seriesIndex - 1) * 2 + 1, - teamBIndex: (seriesIndex - 1) * 2 + 2, - }; - } - - private resolveRequiredGameSlots(match: MatchDocument): number { - const gameMode = match.gameMode ?? 'pair'; - if (gameMode === 'round-robin') { - const teamCount = resolveRoundRobinTeamCount(match); - return roundRobinPairCount(teamCount) * (match.gameCount || 1); - } - - const activeParticipantCount = match.participants.filter( - (participant) => !participant.excluded, - ).length; - const participantSeriesCount = Math.floor(activeParticipantCount / 10); - const teamSeriesCount = Math.ceil(match.teams.length / 2); - const seriesCount = Math.max(1, participantSeriesCount, teamSeriesCount); - return seriesCount * (match.gameCount || 1); - } - - private resolveMatchWinnerTeamIndex( - seriesResults: NonNullable['seriesResults'], - ): number | undefined { - const winsByTeam = new Map(); - for (const series of seriesResults ?? []) { - if (!series.winnerTeamIndex) continue; - winsByTeam.set( - series.winnerTeamIndex, - (winsByTeam.get(series.winnerTeamIndex) ?? 0) + 1, - ); - } - const sorted = [...winsByTeam.entries()].sort( - (left, right) => right[1] - left[1], - ); - if (sorted.length === 0) return undefined; - if (sorted.length > 1 && sorted[0][1] === sorted[1][1]) return undefined; - return sorted[0][0]; - } - private async updatePollState( match: MatchDocument, outcome: 'matched' | 'not-found' | 'failed', expandedToAllPuuids: boolean, + competition?: CompetitionResultSnapshot, ): Promise { match.resultPollState = { startedAt: match.resultPollState?.startedAt ?? new Date(), lastPolledAt: new Date(), lastPollOutcome: outcome, - matchedCount: match.result?.games?.length ?? 0, + matchedCount: + competition?.projection.games.length ?? + match.resultPollState?.matchedCount ?? + 0, expandedToAllPuuids, state: outcome === 'failed' ? 'failed' : 'polling', }; await match.save(); } + private async scheduleNextPoll( + match: MatchDocument, + competition: CompetitionResultSnapshot, + job: PollTournamentResultJob, + ): Promise { + const pollState = match.resultPollState; + const startedAt = pollState?.startedAt ?? new Date(); + const elapsedMs = Date.now() - startedAt.getTime(); + const delayMs = this.nextPollDelayMs(elapsedMs); + if (delayMs === null) { + match.resultPollState = { + startedAt, + lastPolledAt: pollState?.lastPolledAt, + lastPollOutcome: pollState?.lastPollOutcome, + matchedCount: competition.projection.games.length, + expandedToAllPuuids: + pollState?.expandedToAllPuuids ?? job.expandedToAllPuuids, + state: 'expired', + }; + await match.save(); + this.logger.warn( + `Tournament result polling expired for match ${match._id.toString()}.`, + ); + return; + } + const expandedToAllPuuids = + job.expandedToAllPuuids || + (elapsedMs >= EXPAND_AFTER_MS && + competition.projection.games.length === 0); + await this.riotJobQueueService.enqueueTournamentResultPoll({ + matchId: match._id.toString(), + attempt: job.attempt + 1, + expandedToAllPuuids, + priority: 'low', + deferUntilMs: Date.now() + delayMs, + }); + } + private nextPollDelayMs(elapsedMs: number): number | null { if (elapsedMs >= POLL_EXPIRY_MS) return null; if (elapsedMs <= EXPAND_AFTER_MS) return FIRST_HOUR_POLL_DELAY_MS; @@ -863,18 +880,13 @@ export class TournamentResultService { private resolveStartTime(match: MatchDocument): number { return Math.max( 0, - Math.floor(match.teamBuiltAt!.getTime() / 1000) - + Math.floor(match.teamBuiltAt!.getTime() / 1_000) - TOURNAMENT_LOOKUP_START_MARGIN_SECONDS, ); } private isReadyToPoll(match: MatchDocument): boolean { - return Boolean( - match.teamBuiltAt && - match.tournamentCodeIds.length > 0 && - match.teams.length >= 2 && - match.teams.every((team) => team.members.length > 0), - ); + return this.hasBuiltTeams(match); } private assertManualCollectionAllowed( @@ -921,6 +933,116 @@ export class TournamentResultService { if (!match) throw new NotFoundException('Match not found.'); return match; } + + private resolveMatchIdentifier( + matchOrId: MatchDocument | mongoose.Types.ObjectId, + ): string { + return matchOrId instanceof mongoose.Types.ObjectId + ? matchOrId.toString() + : matchOrId._id.toString(); + } + + private tournamentResultPollProcessingLockKey( + matchIdentifier: string, + ): string { + return `distributed-lock:tournament-result:process-poll-job:match:${matchIdentifier}`; + } +} + +function competitionSnapshot(value: unknown): CompetitionResultSnapshot { + const raw = + value && typeof value === 'object' && 'toObject' in value + ? ((value as CompetitionPersistenceDocument).toObject?.() ?? value) + : value; + if (!isRecord(raw)) throw new Error('Competition snapshot is missing.'); + const projection = raw.projection; + if (!isRecord(projection)) + throw new Error('Competition projection is missing.'); + const competitionId = idString(raw._id); + const revision = raw.revision; + if (!competitionId || typeof revision !== 'number') { + throw new Error('Competition identity or revision is invalid.'); + } + return { + competitionId, + revision, + phase: String(raw.phase) as CompetitionResultSnapshot['phase'], + teams: asArray(raw.teams).map((team) => ({ + teamId: idString(asRecord(team).teamId), + members: asArray(asRecord(team).members).map((member) => ({ + userId: idString(asRecord(member).userId), + })), + })), + projection: { + phase: String( + projection.phase, + ) as CompetitionResultSnapshot['projection']['phase'], + series: asArray(projection.series).map((series) => { + const record = asRecord(series); + return { + seriesId: idString(record.seriesId), + status: String( + record.status, + ) as CompetitionResultSnapshot['projection']['series'][number]['status'], + entries: asArray(record.entries).map((entry) => { + const row = asRecord(entry); + return { + slot: String(row.slot) as 'A' | 'B', + teamId: row.teamId == null ? null : idString(row.teamId), + gameWins: typeof row.gameWins === 'number' ? row.gameWins : 0, + }; + }), + }; + }), + gameSlots: asArray(projection.gameSlots).map((slot) => { + const record = asRecord(slot); + return { + id: idString(record.id), + seriesId: idString(record.seriesId), + ordinal: Number(record.ordinal), + displayNumber: Number(record.displayNumber), + status: String( + record.status, + ) as CompetitionResultGameSlotProjection['status'], + }; + }), + games: asArray(projection.games).map((game) => { + const evidence = asRecord(asRecord(game).evidence); + return { + evidence: { + type: typeof evidence.type === 'string' ? evidence.type : undefined, + riotMatchId: + typeof evidence.riotMatchId === 'string' + ? evidence.riotMatchId + : undefined, + }, + }; + }), + }, + }; +} + +function objectId(value: string, label: string): mongoose.Types.ObjectId { + if (!mongoose.Types.ObjectId.isValid(value)) { + throw new Error(`${label} id is not a valid ObjectId.`); + } + return new mongoose.Types.ObjectId(value); +} + +function deterministicObjectId(key: string): mongoose.Types.ObjectId { + return new mongoose.Types.ObjectId( + createHash('sha256').update(key).digest('hex').slice(0, 24), + ); +} + +function isStaleRevision(error: unknown): boolean { + return isRecord(error) && error.code === 'STALE_COMPETITION_REVISION'; +} + +function isAssignmentStaleRevision(error: unknown): boolean { + return ( + isRecord(error) && error.code === 'COMPETITION_ASSIGNMENT_STALE_REVISION' + ); } function isRiotMatchDto(value: unknown): value is RiotMatchDto { @@ -931,3 +1053,28 @@ function isRiotMatchDto(value: unknown): value is RiotMatchDto { 'info' in value, ); } + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function asRecord(value: unknown): Record { + return isRecord(value) ? value : {}; +} + +function asArray(value: unknown): unknown[] { + return Array.isArray(value) ? value : []; +} + +function idString(value: unknown): string { + if (value instanceof mongoose.Types.ObjectId) return value.toString(); + if (typeof value === 'string') return value; + if (typeof value === 'number' || typeof value === 'bigint') { + return String(value); + } + return ''; +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} diff --git a/apps/api/src/modules/tournament-result/tournament-result.types.ts b/apps/api/src/modules/tournament-result/tournament-result.types.ts index 687b9910..9669827f 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.types.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.types.ts @@ -1,4 +1,3 @@ -import type { TeamSide } from '../global/database/schema'; import type { RiotJobPriority } from '../riot-job-queue/riot-job-queue.types'; export interface PollTournamentResultJob { @@ -26,14 +25,3 @@ export interface ManualTournamentResultCollectResponse { riotMatchIds: string[]; gameNumbers: number[]; } - -export interface ComputedGameParticipant { - userId: string; - teamIndex: number; - side: TeamSide; - championId: number; - kills: number; - deaths: number; - assists: number; - win: boolean; -} diff --git a/apps/api/src/modules/user/community-user.controller.ts b/apps/api/src/modules/user/community-user.controller.ts new file mode 100644 index 00000000..e078b6d2 --- /dev/null +++ b/apps/api/src/modules/user/community-user.controller.ts @@ -0,0 +1,61 @@ +import { + BadRequestException, + Controller, + Get, + Param, + Query, + UseGuards, +} from '@nestjs/common'; +import { Type } from 'class-transformer'; +import { + IsInt, + IsOptional, + IsString, + Max, + MaxLength, + Min, +} from 'class-validator'; +import mongoose from 'mongoose'; +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 { UserSearchService } from './user-search.service'; + +class SearchCommunityUsersQueryDto { + @IsString() + @MaxLength(80) + query!: string; + + @IsOptional() + @Type(() => Number) + @IsInt() + @Min(1) + @Max(20) + limit?: number; +} + +@Controller('communities/:communityId/users') +@Roles('admin', 'owner') +@UseGuards(RolesGuard) +export class CommunityUserController { + constructor(private readonly userSearchService: UserSearchService) {} + + @Get('search') + public async searchUsers( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Query() query: SearchCommunityUsersQueryDto, + ) { + if (!currentUser.communityId.equals(communityId)) { + throw new BadRequestException('Different community.'); + } + return this.userSearchService.search({ + communityId, + query: query.query, + limit: query.limit, + }); + } +} diff --git a/apps/api/src/modules/user/user-search.service.spec.ts b/apps/api/src/modules/user/user-search.service.spec.ts new file mode 100644 index 00000000..be8b8753 --- /dev/null +++ b/apps/api/src/modules/user/user-search.service.spec.ts @@ -0,0 +1,143 @@ +import mongoose from 'mongoose'; +import { UserSearchService } from './user-search.service'; + +describe('UserSearchService', () => { + function createService(users: Record[] = []) { + const exec = jest.fn().mockResolvedValue(users); + const limit = jest.fn().mockReturnValue({ exec }); + const find = jest.fn().mockReturnValue({ limit }); + const UserModel = { find }; + const connectionService = { + getModel: jest.fn().mockImplementation(async (name: string) => { + if (name === 'user') return UserModel; + return {}; + }), + }; + + return { + service: new UserSearchService(connectionService as never), + UserModel, + limit, + }; + } + + it('returns no results for short queries', async () => { + const communityId = new mongoose.Types.ObjectId(); + const { service, UserModel } = createService(); + + const results = await service.search({ communityId, query: 'a' }); + + expect(results).toEqual([]); + expect(UserModel.find).not.toHaveBeenCalled(); + }); + + it('searches by kakao nickname and Riot ID parts', async () => { + const communityId = new mongoose.Types.ObjectId(); + const { service, UserModel, limit } = createService(); + + await service.search({ communityId, query: 'Hide on bush#KR1', limit: 50 }); + + expect(UserModel.find).toHaveBeenCalledWith({ + communityId, + $or: expect.arrayContaining([ + { kakaoTalkNickname: expect.any(RegExp) }, + { + riotAccounts: { + $elemMatch: { + gameName: expect.any(RegExp), + tagLine: expect.any(RegExp), + }, + }, + }, + ]), + }); + expect(limit).toHaveBeenCalledWith(20); + }); + + it('serializes limited candidate fields', async () => { + const communityId = new mongoose.Types.ObjectId(); + const userId = new mongoose.Types.ObjectId(); + const { service } = createService([ + { + _id: userId, + kakaoTalkNickname: '다혜', + isActivated: true, + preferredPositions: [{ position: 'MID', priority: 1 }], + riotAccounts: [ + { + puuid: 'puuid-1', + gameName: 'Dahyeon', + tagLine: 'KR1', + profileIconId: 7, + isPrimary: true, + tiers: [{ queueType: 'RANKED_SOLO_5x5', tier: 'GOLD' }], + matchIds: ['private-extra-field'], + }, + ], + }, + ]); + + const results = await service.search({ communityId, query: '다혜' }); + + expect(results).toEqual([ + { + userId: userId.toString(), + kakaoTalkNickname: '다혜', + isActivated: true, + preferredPositions: [{ position: 'MID', priority: 1 }], + matchedRiotPuuid: undefined, + riotAccounts: [ + { + puuid: 'puuid-1', + gameName: 'Dahyeon', + tagLine: 'KR1', + profileIconId: 7, + isPrimary: true, + tiers: [{ queueType: 'RANKED_SOLO_5x5', tier: 'GOLD' }], + }, + ], + }, + ]); + }); + + it('returns the matching secondary Riot account as a selection hint', async () => { + const communityId = new mongoose.Types.ObjectId(); + const userId = new mongoose.Types.ObjectId(); + const { service } = createService([ + { + _id: userId, + kakaoTalkNickname: '다혜', + isActivated: true, + preferredPositions: [], + riotAccounts: [ + { + puuid: 'main-puuid', + gameName: 'MainDahyeon', + tagLine: 'KR1', + profileIconId: 7, + isPrimary: true, + tiers: [], + }, + { + puuid: 'smurf-puuid', + gameName: 'PracticeDahyeon', + tagLine: 'KR2', + profileIconId: 8, + isPrimary: false, + tiers: [], + }, + ], + }, + ]); + + const results = await service.search({ + communityId, + query: 'Practice#KR2', + }); + + expect(results[0]).toMatchObject({ + userId: userId.toString(), + matchedRiotPuuid: 'smurf-puuid', + }); + }); +}); diff --git a/apps/api/src/modules/user/user-search.service.ts b/apps/api/src/modules/user/user-search.service.ts new file mode 100644 index 00000000..0b927f67 --- /dev/null +++ b/apps/api/src/modules/user/user-search.service.ts @@ -0,0 +1,164 @@ +import { Injectable } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import type { + PositionPreference, + RiotAccount, + TierInfo, + UserDocument, +} from '../global/database/schema'; + +const DEFAULT_SEARCH_LIMIT = 10; +const MAX_SEARCH_LIMIT = 20; +const MIN_QUERY_LENGTH = 2; + +export interface UserSearchRiotAccountResult { + puuid: string; + gameName: string; + tagLine: string; + profileIconId: number; + isPrimary: boolean; + tiers: TierInfo[]; +} + +export interface UserSearchResult { + userId: string; + kakaoTalkNickname?: string; + isActivated: boolean; + preferredPositions: PositionPreference[]; + matchedRiotPuuid?: string; + riotAccounts: UserSearchRiotAccountResult[]; +} + +export interface SearchCommunityUsersParams { + communityId: mongoose.Types.ObjectId; + query: string; + limit?: number; +} + +@Injectable() +export class UserSearchService { + constructor(private readonly connectionService: ConnectionService) {} + + public async search( + params: SearchCommunityUsersParams, + ): Promise { + const query = params.query.trim(); + if (query.length < MIN_QUERY_LENGTH) return []; + + const UserModel = await this.connectionService.getModel('user'); + const users = await UserModel.find( + this.buildFilter(params.communityId, query), + ) + .limit(this.resolveLimit(params.limit)) + .exec(); + + return users.map((user) => this.serializeUser(user, query)); + } + + private buildFilter(communityId: mongoose.Types.ObjectId, query: string) { + const [gameName, tagLine] = this.splitRiotId(query); + const generalRegex = this.toContainsRegex(query); + const filters: Record[] = [ + { kakaoTalkNickname: generalRegex }, + { 'riotAccounts.gameName': generalRegex }, + { 'riotAccounts.tagLine': generalRegex }, + ]; + + if (gameName && tagLine) { + filters.push({ + riotAccounts: { + $elemMatch: { + gameName: this.toContainsRegex(gameName), + tagLine: this.toContainsRegex(tagLine), + }, + }, + }); + } + + return { communityId, $or: filters }; + } + + private splitRiotId(query: string): [string | null, string | null] { + const hashIndex = query.lastIndexOf('#'); + if (hashIndex <= 0 || hashIndex === query.length - 1) { + return [null, null]; + } + return [ + query.slice(0, hashIndex).trim(), + query.slice(hashIndex + 1).trim(), + ]; + } + + private toContainsRegex(value: string): RegExp { + return new RegExp(escapeRegex(value.trim()), 'i'); + } + + private resolveLimit(limit: number | undefined): number { + if (typeof limit !== 'number' || !Number.isFinite(limit)) { + return DEFAULT_SEARCH_LIMIT; + } + return Math.min(MAX_SEARCH_LIMIT, Math.max(1, Math.trunc(limit))); + } + + private serializeUser(user: UserDocument, query: string): UserSearchResult { + return { + userId: user._id.toString(), + kakaoTalkNickname: user.kakaoTalkNickname, + isActivated: user.isActivated, + preferredPositions: user.preferredPositions ?? [], + matchedRiotPuuid: this.findMatchingRiotAccount( + user.riotAccounts ?? [], + query, + )?.puuid, + riotAccounts: (user.riotAccounts ?? []).map((account) => + this.serializeRiotAccount(account), + ), + }; + } + + private serializeRiotAccount( + account: RiotAccount, + ): UserSearchRiotAccountResult { + return { + puuid: account.puuid, + gameName: account.gameName, + tagLine: account.tagLine, + profileIconId: account.profileIconId, + isPrimary: account.isPrimary, + tiers: account.tiers ?? [], + }; + } + + private findMatchingRiotAccount( + accounts: RiotAccount[], + query: string, + ): RiotAccount | undefined { + const [gameName, tagLine] = this.splitRiotId(query); + if (gameName && tagLine) { + return accounts.find( + (account) => + includesNormalized(account.gameName, gameName) && + includesNormalized(account.tagLine, tagLine), + ); + } + + return accounts.find( + (account) => + includesNormalized(account.gameName, query) || + includesNormalized(account.tagLine, query), + ); + } +} + +function escapeRegex(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function includesNormalized(value: string | undefined, query: string): boolean { + return normalizeForSearch(value).includes(normalizeForSearch(query)); +} + +function normalizeForSearch(value: string | undefined): string { + return (value ?? '').trim().toLowerCase(); +} diff --git a/apps/api/src/modules/user/user.module.ts b/apps/api/src/modules/user/user.module.ts index 66ca9ce0..5b559c3b 100644 --- a/apps/api/src/modules/user/user.module.ts +++ b/apps/api/src/modules/user/user.module.ts @@ -1,9 +1,12 @@ import { Module } from '@nestjs/common'; import { RiotModule } from '../riot/riot.module'; +import { CommunityUserController } from './community-user.controller'; import { UserController } from './user.controller'; +import { UserSearchService } from './user-search.service'; @Module({ imports: [RiotModule], - controllers: [UserController], + controllers: [UserController, CommunityUserController], + providers: [UserSearchService], }) export class UserModule {} diff --git a/apps/api/src/newrelic-config.spec.ts b/apps/api/src/newrelic-config.spec.ts new file mode 100644 index 00000000..caa400f7 --- /dev/null +++ b/apps/api/src/newrelic-config.spec.ts @@ -0,0 +1,90 @@ +import { createRequire } from 'node:module'; + +const CONFIG_PATH = '../newrelic.cjs'; +const requireConfig = createRequire(__filename); + +interface NewRelicConfig { + app_name: string[]; + license_key: string; + agent_enabled: boolean; + ai_monitoring: { + enabled: boolean; + }; + custom_insights_events: { + max_samples_stored: number; + }; + span_events: { + max_samples_stored: number; + }; +} + +interface NewRelicConfigModule { + config: NewRelicConfig; +} + +function loadConfig(): NewRelicConfig { + jest.resetModules(); + const module = requireConfig(CONFIG_PATH) as unknown as NewRelicConfigModule; + return module.config; +} + +describe('New Relic config', () => { + let originalEnv: NodeJS.ProcessEnv; + + beforeEach(() => { + originalEnv = { ...process.env }; + delete process.env.NEW_RELIC_ENABLED; + delete process.env.NEW_RELIC_LICENSE_KEY; + delete process.env.NEW_RELIC_APP_NAME; + delete process.env.NEW_RELIC_AI_MONITORING_ENABLED; + delete process.env.NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED; + delete process.env.NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED; + jest.resetModules(); + }); + + afterEach(() => { + process.env = originalEnv; + jest.resetModules(); + }); + + it('uses safe defaults and stays disabled without a license key', () => { + const config = loadConfig(); + + expect(config.app_name).toEqual(['lolympus']); + expect(config.agent_enabled).toBe(false); + expect(config.ai_monitoring.enabled).toBe(true); + expect(config.custom_insights_events.max_samples_stored).toBe(100000); + expect(config.span_events.max_samples_stored).toBe(10000); + }); + + it('enables the agent when a license key exists and honors runtime overrides', () => { + process.env.NEW_RELIC_LICENSE_KEY = 'test-license'; + process.env.NEW_RELIC_APP_NAME = 'lolympus-api-test'; + process.env.NEW_RELIC_AI_MONITORING_ENABLED = 'false'; + process.env.NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED = '5000'; + process.env.NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED = '4000'; + + const config = loadConfig(); + + expect(config.app_name).toEqual(['lolympus-api-test']); + expect(config.license_key).toBe('test-license'); + expect(config.agent_enabled).toBe(true); + expect(config.ai_monitoring.enabled).toBe(false); + expect(config.custom_insights_events.max_samples_stored).toBe(5000); + expect(config.span_events.max_samples_stored).toBe(4000); + }); + + it('normalizes shorthand sample sizes before New Relic applies env overrides', () => { + process.env.NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED = '100k'; + process.env.NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED = '10k'; + + const config = loadConfig(); + + expect(config.custom_insights_events.max_samples_stored).toBe(100000); + expect(config.span_events.max_samples_stored).toBe(10000); + expect( + process.env.NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED, + ).toBe('100000'); + expect(process.env.NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED).toBe('10000'); + }); +}); diff --git a/apps/api/src/redis-io.adapter.ts b/apps/api/src/redis-io.adapter.ts new file mode 100644 index 00000000..8b0a0bfa --- /dev/null +++ b/apps/api/src/redis-io.adapter.ts @@ -0,0 +1,46 @@ +import { INestApplicationContext } from '@nestjs/common'; +import { IoAdapter } from '@nestjs/platform-socket.io'; +import { createAdapter } from '@socket.io/redis-adapter'; +import type { Server, ServerOptions } from 'socket.io'; +import { + AuctionRedisService, + type AuctionRedisClient, +} from './modules/auction/redis/auction-redis.service'; + +type RedisAdapterConstructor = ReturnType; +type DuplicatedRedisClient = ReturnType; + +export class RedisIoAdapter extends IoAdapter { + private adapterConstructor?: RedisAdapterConstructor; + private subClient?: DuplicatedRedisClient; + + constructor(private readonly app: INestApplicationContext) { + super(app); + } + + public async connectToRedis(): Promise { + const auctionRedisService = this.app.get(AuctionRedisService); + const pubClient = auctionRedisService.raw(); + this.subClient = pubClient.duplicate(); + await this.subClient.connect(); + this.adapterConstructor = createAdapter(pubClient, this.subClient); + } + + override createIOServer(port: number, options?: ServerOptions): Server { + const server = super.createIOServer(port, options) as Server; + if (this.adapterConstructor) { + server.adapter(this.adapterConstructor); + } + return server; + } + + override close(server: unknown) { + const closeResult = super.close(server as never); + if (this.subClient) { + void this.subClient.quit().catch(() => { + this.subClient?.destroy(); + }); + } + return closeResult; + } +} diff --git a/apps/api/src/scripts/api-performance-report.spec.ts b/apps/api/src/scripts/api-performance-report.spec.ts new file mode 100644 index 00000000..78220a8b --- /dev/null +++ b/apps/api/src/scripts/api-performance-report.spec.ts @@ -0,0 +1,218 @@ +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { + buildEndpointReportFromLocalEvents, + buildNewRelicCustomEventNrql, + buildNewRelicTransactionNrql, + discoverApiRoutes, + formatMarkdownReport, + mergeRowsWithManifest, +} from './api-performance-report'; +import type { ApiPerformanceEvent } from '../modules/global/observability/performance-observer'; + +describe('api performance route discovery', () => { + let rootDir: string; + + beforeEach(async () => { + rootDir = await mkdtemp(path.join(os.tmpdir(), 'api-performance-routes-')); + await mkdir(path.join(rootDir, 'modules', 'match'), { recursive: true }); + }); + + afterEach(async () => { + await rm(rootDir, { recursive: true, force: true }); + }); + + it('discovers controller routes including multiline decorators', async () => { + await writeFile( + path.join(rootDir, 'modules', 'match', 'match.controller.ts'), + ` + import { Controller, Get, Post } from '@nestjs/common'; + + @Controller('communities/:communityId/matches') + export class MatchController { + @Get() + list() {} + + @Post( + ':matchId/participants' + ) + join() {} + } + `, + ); + + await writeFile( + path.join(rootDir, 'app.controller.ts'), + ` + import { Controller, Get } from '@nestjs/common'; + + @Controller() + export class AppController { + @Get() + root() {} + } + `, + ); + + await expect(discoverApiRoutes(rootDir)).resolves.toEqual([ + { + method: 'GET', + route: '/', + controllerFile: 'app.controller.ts', + }, + { + method: 'GET', + route: '/communities/:communityId/matches', + controllerFile: 'modules/match/match.controller.ts', + }, + { + method: 'POST', + route: '/communities/:communityId/matches/:matchId/participants', + controllerFile: 'modules/match/match.controller.ts', + }, + ]); + }); +}); + +describe('api performance report generation', () => { + it('reports every manifest route, including routes with no samples', () => { + const routes = [ + { + method: 'GET', + route: '/communities/:communityId/matches', + controllerFile: 'match.controller.ts', + }, + { + method: 'POST', + route: '/communities/:communityId/matches', + controllerFile: 'match.controller.ts', + }, + { + method: 'GET', + route: '/communities/:communityId/internal-stats/matches', + controllerFile: 'community-stats.controller.ts', + }, + ]; + const events: ApiPerformanceEvent[] = [ + { + type: 'api-request', + timestamp: '2026-06-28T00:00:00.000Z', + requestId: 'request-1', + method: 'GET', + route: '/communities/:communityId/matches', + path: '/communities/abc/matches', + statusCode: 200, + durationMs: 100, + isError: false, + queryCount: 2, + mongooseDurationMs: 40, + docsReturned: 50, + hydratedDocsReturned: 50, + leanQueryCount: 0, + }, + ]; + + const rows = buildEndpointReportFromLocalEvents({ + routes, + events, + p95BudgetMs: 300, + docsReturnedP95Budget: 500, + hydratedDocsReturnedP95Budget: 0, + }); + + expect(rows).toHaveLength(3); + expect( + rows.find( + (row) => row.route === '/communities/:communityId/matches', + )?.status, + ).toBe('document-heavy'); + expect(rows.filter((row) => row.status === 'no-samples')).toHaveLength(2); + }); + + it('keeps observed-only New Relic rows while adding no-sample manifest routes', () => { + const rows = mergeRowsWithManifest({ + routes: [ + { + method: 'GET', + route: '/known', + controllerFile: 'known.controller.ts', + }, + ], + measuredRows: [ + { + method: 'GET', + route: '/observed-only', + source: 'newrelic-transaction', + samples: 10, + avgMs: 40, + p50Ms: 35, + p95Ms: 80, + p99Ms: 120, + maxMs: 130, + errorRatePercentage: 0, + queryCountP95: null, + mongooseDurationP95Ms: null, + docsReturnedP95: null, + hydratedDocsReturnedP95: null, + status: 'ok', + }, + ], + fallbackSource: 'newrelic-transaction', + p95BudgetMs: 300, + docsReturnedP95Budget: 500, + hydratedDocsReturnedP95Budget: 0, + }); + + expect(rows.map((row) => `${row.method} ${row.route}`)).toEqual([ + 'GET /known', + 'GET /observed-only', + ]); + expect(rows[0].status).toBe('no-samples'); + expect(rows[1].samples).toBe(10); + }); + + it('formats all rows instead of truncating to a top list', () => { + const rows = Array.from({ length: 12 }, (_, index) => ({ + method: 'GET', + route: `/route-${index}`, + source: 'local' as const, + samples: 1, + avgMs: 10, + p50Ms: 10, + p95Ms: 10, + p99Ms: 10, + maxMs: 10, + errorRatePercentage: 0, + queryCountP95: 1, + mongooseDurationP95Ms: 1, + docsReturnedP95: 1, + hydratedDocsReturnedP95: 0, + status: 'ok' as const, + })); + + const report = formatMarkdownReport({ + rows, + source: 'local', + since: 'fixture', + }); + + expect(report).toContain('/route-0'); + expect(report).toContain('/route-11'); + }); + + it('builds New Relic queries for custom events and transaction duration data', () => { + expect(buildNewRelicCustomEventNrql('lolympus-api', '1 day ago')).toContain( + 'FROM ApiRequestPerformance', + ); + expect(buildNewRelicCustomEventNrql('lolympus-api', '1 day ago')).toContain( + 'FACET method, route', + ); + expect( + buildNewRelicTransactionNrql('lolympus-api', '1 day ago'), + ).toContain('FROM Transaction'); + expect( + buildNewRelicTransactionNrql('lolympus-api', '1 day ago'), + ).toContain('FACET name'); + }); +}); diff --git a/apps/api/src/scripts/api-performance-report.ts b/apps/api/src/scripts/api-performance-report.ts new file mode 100644 index 00000000..ce47931a --- /dev/null +++ b/apps/api/src/scripts/api-performance-report.ts @@ -0,0 +1,808 @@ +import { existsSync } from 'node:fs'; +import { readdir, readFile, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import process from 'node:process'; +import type { + ApiPerformanceEvent, + ApiRequestPerformanceEvent, +} from '../modules/global/observability/performance-observer'; + +export type ReportSource = + | 'local' + | 'newrelic-custom' + | 'newrelic-transaction'; + +export interface ApiRoute { + method: string; + route: string; + controllerFile: string; +} + +export interface EndpointReportRow { + method: string; + route: string; + controllerFile?: string; + source: ReportSource | 'none'; + samples: number; + avgMs: number | null; + p50Ms: number | null; + p95Ms: number | null; + p99Ms: number | null; + maxMs: number | null; + errorRatePercentage: number | null; + queryCountP95: number | null; + mongooseDurationP95Ms: number | null; + docsReturnedP95: number | null; + hydratedDocsReturnedP95: number | null; + status: 'ok' | 'slow' | 'document-heavy' | 'no-samples'; +} + +interface ReportOptions { + source: ReportSource; + rootDir: string; + inputFile: string; + outputFile?: string; + format: 'markdown' | 'json'; + p95BudgetMs: number; + docsReturnedP95Budget: number; + hydratedDocsReturnedP95Budget: number; + since: string; + newRelicAccountId?: string; + newRelicApiKey?: string; + newRelicAppName: string; + routesOnly: boolean; +} + +interface NewRelicNrqlResponse { + data?: { + actor?: { + account?: { + nrql?: { + results?: Record[]; + }; + }; + }; + }; + errors?: Array<{ message?: string }>; +} + +const HTTP_DECORATOR_TO_METHOD: Record = { + All: 'ALL', + Delete: 'DELETE', + Get: 'GET', + Head: 'HEAD', + Options: 'OPTIONS', + Patch: 'PATCH', + Post: 'POST', + Put: 'PUT', +}; + +export async function discoverApiRoutes(rootDir: string): Promise { + const files = await listControllerFiles(rootDir); + const routes = new Map(); + + for (const file of files) { + const source = await readFile(file, 'utf8'); + const basePath = extractDecoratorStringArgument(source, 'Controller'); + if (basePath === undefined) continue; + + const methodDecoratorRegex = + /@(Get|Post|Patch|Put|Delete|Head|Options|All)\s*\(([\s\S]*?)\)/g; + for (const match of source.matchAll(methodDecoratorRegex)) { + const method = HTTP_DECORATOR_TO_METHOD[match[1]]; + const route = normalizeRoute( + joinRouteParts(basePath, extractFirstStringLiteral(match[2]) ?? ''), + ); + const key = routeKey(method, route); + routes.set(key, { + method, + route, + controllerFile: path.relative(rootDir, file), + }); + } + } + + return [...routes.values()].sort( + (left, right) => + left.route.localeCompare(right.route) || + left.method.localeCompare(right.method), + ); +} + +export async function readLocalPerformanceEvents( + inputFile: string, +): Promise { + if (!existsSync(inputFile)) return []; + + const content = await readFile(inputFile, 'utf8'); + return content + .split(/\r?\n/) + .filter(Boolean) + .flatMap((line) => { + try { + return [JSON.parse(line) as ApiPerformanceEvent]; + } catch { + return []; + } + }); +} + +export function buildEndpointReportFromLocalEvents(params: { + routes: ApiRoute[]; + events: ApiPerformanceEvent[]; + p95BudgetMs: number; + docsReturnedP95Budget: number; + hydratedDocsReturnedP95Budget: number; +}): EndpointReportRow[] { + const requestsByRoute = new Map(); + for (const event of params.events) { + if (event.type !== 'api-request') continue; + const key = routeKey(event.method, event.route); + requestsByRoute.set(key, [...(requestsByRoute.get(key) ?? []), event]); + } + + const rowsByKey = new Map(); + for (const route of params.routes) { + const events = requestsByRoute.get(routeKey(route.method, route.route)) ?? []; + rowsByKey.set( + routeKey(route.method, route.route), + summarizeRequestEvents(route, events, { + source: 'local', + p95BudgetMs: params.p95BudgetMs, + docsReturnedP95Budget: params.docsReturnedP95Budget, + hydratedDocsReturnedP95Budget: params.hydratedDocsReturnedP95Budget, + }), + ); + } + + for (const [key, events] of requestsByRoute.entries()) { + if (rowsByKey.has(key)) continue; + const first = events[0]; + rowsByKey.set( + key, + summarizeRequestEvents( + { + method: first.method, + route: first.route, + controllerFile: 'observed-only', + }, + events, + { + source: 'local', + p95BudgetMs: params.p95BudgetMs, + docsReturnedP95Budget: params.docsReturnedP95Budget, + hydratedDocsReturnedP95Budget: params.hydratedDocsReturnedP95Budget, + }, + ), + ); + } + + return [...rowsByKey.values()].sort(compareReportRows); +} + +export async function fetchNewRelicEndpointRows(params: { + source: Exclude; + accountId: string; + apiKey: string; + appName: string; + since: string; + p95BudgetMs: number; + docsReturnedP95Budget: number; + hydratedDocsReturnedP95Budget: number; +}): Promise { + const nrql = + params.source === 'newrelic-custom' + ? buildNewRelicCustomEventNrql(params.appName, params.since) + : buildNewRelicTransactionNrql(params.appName, params.since); + const response = await fetch('https://api.newrelic.com/graphql', { + method: 'POST', + headers: { + 'Api-Key': params.apiKey, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + query: `{ + actor { + account(id: ${Number(params.accountId)}) { + nrql(query: ${JSON.stringify(nrql)}) { + results + } + } + } + }`, + }), + }); + + if (!response.ok) { + throw new Error( + `New Relic query failed: ${response.status} ${response.statusText}`, + ); + } + + const json = (await response.json()) as NewRelicNrqlResponse; + if (json.errors?.length) { + throw new Error( + `New Relic query failed: ${json.errors + .map((error) => error.message ?? 'unknown error') + .join('; ')}`, + ); + } + + const results = json.data?.actor?.account?.nrql?.results ?? []; + return results + .map((result) => + params.source === 'newrelic-custom' + ? newRelicCustomResultToRow(result, params) + : newRelicTransactionResultToRow(result, params), + ) + .filter((row): row is EndpointReportRow => row !== null) + .sort(compareReportRows); +} + +export function mergeRowsWithManifest(params: { + routes: ApiRoute[]; + measuredRows: EndpointReportRow[]; + fallbackSource: ReportSource; + p95BudgetMs: number; + docsReturnedP95Budget: number; + hydratedDocsReturnedP95Budget: number; +}): EndpointReportRow[] { + const rowsByKey = new Map( + params.measuredRows.map((row) => [routeKey(row.method, row.route), row]), + ); + + for (const route of params.routes) { + const key = routeKey(route.method, route.route); + if (rowsByKey.has(key)) { + rowsByKey.set(key, { + ...rowsByKey.get(key)!, + controllerFile: route.controllerFile, + }); + continue; + } + + rowsByKey.set(key, { + method: route.method, + route: route.route, + controllerFile: route.controllerFile, + source: 'none', + samples: 0, + avgMs: null, + p50Ms: null, + p95Ms: null, + p99Ms: null, + maxMs: null, + errorRatePercentage: null, + queryCountP95: null, + mongooseDurationP95Ms: null, + docsReturnedP95: null, + hydratedDocsReturnedP95: null, + status: 'no-samples', + }); + } + + return [...rowsByKey.values()].sort(compareReportRows); +} + +export function formatMarkdownReport(params: { + rows: EndpointReportRow[]; + source: ReportSource; + since: string; + notes?: string[]; +}): string { + const sampled = params.rows.filter((row) => row.samples > 0); + const noSamples = params.rows.length - sampled.length; + const slow = sampled.filter((row) => row.status === 'slow').length; + const documentHeavy = sampled.filter( + (row) => row.status === 'document-heavy', + ).length; + + const lines = [ + '# API Performance Report', + '', + `- Source: ${params.source}`, + `- Window: ${params.since}`, + `- Routes: ${params.rows.length}`, + `- Sampled routes: ${sampled.length}`, + `- No-sample routes: ${noSamples}`, + `- Slow routes: ${slow}`, + `- Document-heavy routes: ${documentHeavy}`, + ]; + + if (params.notes?.length) { + lines.push('', '## Notes', ''); + for (const note of params.notes) lines.push(`- ${note}`); + } + + lines.push( + '', + '| Method | Route | Samples | p95 ms | p99 ms | Avg ms | Error % | Query p95 | Docs p95 | Hydrated p95 | Status |', + '|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---|', + ); + + for (const row of params.rows) { + lines.push( + [ + `| ${row.method}`, + markdownCell(row.route), + String(row.samples), + formatNumber(row.p95Ms), + formatNumber(row.p99Ms), + formatNumber(row.avgMs), + formatNumber(row.errorRatePercentage), + formatNumber(row.queryCountP95), + formatNumber(row.docsReturnedP95), + formatNumber(row.hydratedDocsReturnedP95), + `${row.status} |`, + ].join(' | '), + ); + } + + return `${lines.join('\n')}\n`; +} + +export function buildNewRelicCustomEventNrql( + appName: string, + since: string, +): string { + return [ + 'FROM ApiRequestPerformance', + 'SELECT count(*) AS samples,', + 'average(durationMs) AS avgDurationMs,', + 'percentile(durationMs, 50, 95, 99) AS durationPercentilesMs,', + 'max(durationMs) AS maxDurationMs,', + 'percentage(count(*), WHERE isError IS true) AS errorRatePercentage,', + 'percentile(queryCount, 95) AS queryCountPercentiles,', + 'percentile(docsReturned, 95) AS docsReturnedPercentiles,', + 'percentile(hydratedDocsReturned, 95) AS hydratedDocsReturnedPercentiles,', + 'percentile(mongooseDurationMs, 95) AS mongooseDurationPercentiles', + `WHERE appName = '${escapeNrqlString(appName)}'`, + 'FACET method, route', + `SINCE ${since}`, + 'LIMIT MAX', + ].join(' '); +} + +export function buildNewRelicTransactionNrql( + appName: string, + since: string, +): string { + return [ + 'FROM Transaction', + 'SELECT count(*) AS samples,', + 'average(duration) AS avgDurationSec,', + 'percentile(duration, 50, 95, 99) AS durationPercentilesSec,', + 'max(duration) AS maxDurationSec,', + 'percentage(count(*), WHERE error IS true) AS errorRatePercentage', + `WHERE appName = '${escapeNrqlString(appName)}'`, + 'FACET name', + `SINCE ${since}`, + 'LIMIT MAX', + ].join(' '); +} + +function summarizeRequestEvents( + route: ApiRoute, + events: ApiRequestPerformanceEvent[], + options: { + source: ReportSource; + p95BudgetMs: number; + docsReturnedP95Budget: number; + hydratedDocsReturnedP95Budget: number; + }, +): EndpointReportRow { + const row: EndpointReportRow = { + method: route.method, + route: route.route, + controllerFile: route.controllerFile, + source: events.length > 0 ? options.source : 'none', + samples: events.length, + avgMs: average(events.map((event) => event.durationMs)), + p50Ms: percentile( + events.map((event) => event.durationMs), + 50, + ), + p95Ms: percentile( + events.map((event) => event.durationMs), + 95, + ), + p99Ms: percentile( + events.map((event) => event.durationMs), + 99, + ), + maxMs: max(events.map((event) => event.durationMs)), + errorRatePercentage: + events.length > 0 + ? (events.filter((event) => event.isError).length / events.length) * 100 + : null, + queryCountP95: percentile( + events.map((event) => event.queryCount), + 95, + ), + mongooseDurationP95Ms: percentile( + events.map((event) => event.mongooseDurationMs), + 95, + ), + docsReturnedP95: percentile( + events.map((event) => event.docsReturned), + 95, + ), + hydratedDocsReturnedP95: percentile( + events.map((event) => event.hydratedDocsReturned), + 95, + ), + status: 'ok', + }; + row.status = classifyRow(row, options); + return row; +} + +function newRelicCustomResultToRow( + result: Record, + options: { + source: ReportSource; + p95BudgetMs: number; + docsReturnedP95Budget: number; + hydratedDocsReturnedP95Budget: number; + }, +): EndpointReportRow | null { + const facet = result.facet; + const method = Array.isArray(facet) ? String(facet[0] ?? '') : undefined; + const route = Array.isArray(facet) ? String(facet[1] ?? '') : undefined; + if (!method || !route) return null; + + const row: EndpointReportRow = { + method, + route: normalizeRoute(route), + source: 'newrelic-custom', + samples: numberField(result.samples), + avgMs: numberOrNull(result.avgDurationMs), + p50Ms: percentileField(result.durationPercentilesMs, 50), + p95Ms: percentileField(result.durationPercentilesMs, 95), + p99Ms: percentileField(result.durationPercentilesMs, 99), + maxMs: numberOrNull(result.maxDurationMs), + errorRatePercentage: numberOrNull(result.errorRatePercentage), + queryCountP95: percentileField(result.queryCountPercentiles, 95), + mongooseDurationP95Ms: percentileField( + result.mongooseDurationPercentiles, + 95, + ), + docsReturnedP95: percentileField(result.docsReturnedPercentiles, 95), + hydratedDocsReturnedP95: percentileField( + result.hydratedDocsReturnedPercentiles, + 95, + ), + status: 'ok', + }; + row.status = classifyRow(row, options); + return row; +} + +function newRelicTransactionResultToRow( + result: Record, + options: { + source: ReportSource; + p95BudgetMs: number; + docsReturnedP95Budget: number; + hydratedDocsReturnedP95Budget: number; + }, +): EndpointReportRow | null { + const parsed = parseTransactionName(String(result.facet ?? '')); + if (!parsed) return null; + + const row: EndpointReportRow = { + method: parsed.method, + route: parsed.route, + source: 'newrelic-transaction', + samples: numberField(result.samples), + avgMs: secondsToMs(result.avgDurationSec), + p50Ms: secondsToMs(percentileField(result.durationPercentilesSec, 50)), + p95Ms: secondsToMs(percentileField(result.durationPercentilesSec, 95)), + p99Ms: secondsToMs(percentileField(result.durationPercentilesSec, 99)), + maxMs: secondsToMs(result.maxDurationSec), + errorRatePercentage: numberOrNull(result.errorRatePercentage), + queryCountP95: null, + mongooseDurationP95Ms: null, + docsReturnedP95: null, + hydratedDocsReturnedP95: null, + status: 'ok', + }; + row.status = classifyRow(row, options); + return row; +} + +function parseTransactionName( + name: string, +): { method: string; route: string } | null { + const match = name.match( + /\b(GET|POST|PATCH|PUT|DELETE|HEAD|OPTIONS|ALL)[\s/]+(\/.*)$/i, + ); + if (!match) return null; + return { + method: match[1].toUpperCase(), + route: normalizeRoute(match[2]), + }; +} + +function classifyRow( + row: EndpointReportRow, + options: { + p95BudgetMs: number; + docsReturnedP95Budget: number; + hydratedDocsReturnedP95Budget: number; + }, +): EndpointReportRow['status'] { + if (row.samples === 0) return 'no-samples'; + if (row.p95Ms !== null && row.p95Ms > options.p95BudgetMs) return 'slow'; + if ( + (row.docsReturnedP95 !== null && + row.docsReturnedP95 > options.docsReturnedP95Budget) || + (row.hydratedDocsReturnedP95 !== null && + row.hydratedDocsReturnedP95 > + options.hydratedDocsReturnedP95Budget) + ) { + return 'document-heavy'; + } + return 'ok'; +} + +async function listControllerFiles(rootDir: string): Promise { + const entries = await readdir(rootDir, { withFileTypes: true }); + const files = await Promise.all( + entries.map(async (entry) => { + const fullPath = path.join(rootDir, entry.name); + if (entry.isDirectory()) return listControllerFiles(fullPath); + return entry.isFile() && entry.name.endsWith('.controller.ts') + ? [fullPath] + : []; + }), + ); + return files.flat(); +} + +function extractDecoratorStringArgument( + source: string, + decoratorName: string, +): string | undefined { + const regex = new RegExp(`@${decoratorName}\\s*\\(([\\s\\S]*?)\\)`); + const match = source.match(regex); + if (!match) return undefined; + return extractFirstStringLiteral(match[1]) ?? ''; +} + +function extractFirstStringLiteral(input: string): string | undefined { + const match = input.match(/['"`]([^'"`]*)['"`]/); + return match?.[1]; +} + +function joinRouteParts(basePath: string, routePath: string): string { + return [basePath, routePath] + .filter((part) => part !== '') + .join('/') + .replace(/\/+/g, '/'); +} + +function normalizeRoute(route: string): string { + const normalized = route.startsWith('/') ? route : `/${route}`; + return normalized.replace(/\/+/g, '/').replace(/\/$/, '') || '/'; +} + +function routeKey(method: string, route: string): string { + return `${method.toUpperCase()} ${normalizeRoute(route)}`; +} + +function compareReportRows(left: EndpointReportRow, right: EndpointReportRow) { + return ( + left.route.localeCompare(right.route) || + left.method.localeCompare(right.method) + ); +} + +function percentile(values: number[], percentileValue: number): number | null { + if (values.length === 0) return null; + const sorted = [...values].sort((left, right) => left - right); + const index = Math.ceil((percentileValue / 100) * sorted.length) - 1; + return sorted[Math.max(0, Math.min(sorted.length - 1, index))]; +} + +function average(values: number[]): number | null { + if (values.length === 0) return null; + return values.reduce((acc, value) => acc + value, 0) / values.length; +} + +function max(values: number[]): number | null { + if (values.length === 0) return null; + return Math.max(...values); +} + +function percentileField(value: unknown, percentileValue: number): number | null { + if (!value || typeof value !== 'object') return null; + const map = value as Record; + return numberOrNull(map[String(percentileValue)] ?? map[percentileValue]); +} + +function numberField(value: unknown): number { + return numberOrNull(value) ?? 0; +} + +function numberOrNull(value: unknown): number | null { + return typeof value === 'number' && Number.isFinite(value) ? value : null; +} + +function secondsToMs(value: unknown): number | null { + const seconds = numberOrNull(value); + return seconds === null ? null : seconds * 1000; +} + +function formatNumber(value: number | null): string { + return value === null ? '-' : value.toFixed(value >= 100 ? 0 : 1); +} + +function markdownCell(value: string): string { + return value.replace(/\|/g, '\\|'); +} + +function escapeNrqlString(value: string): string { + return value.replace(/'/g, "\\'"); +} + +function parseArgs(argv: string[]): ReportOptions { + const args = new Map(); + for (const arg of argv) { + if (!arg.startsWith('--')) continue; + const [key, rawValue] = arg.slice(2).split('=', 2); + args.set(key, rawValue ?? true); + } + + const source = stringArg(args, 'source', defaultReportSource()) as ReportSource; + return { + source, + rootDir: path.resolve( + stringArg(args, 'root-dir', path.join(process.cwd(), 'src')), + ), + inputFile: path.resolve( + stringArg( + args, + 'input', + process.env.API_PERF_LOCAL_EVENT_FILE ?? + '/tmp/lolympus-api-performance.ndjson', + ), + ), + outputFile: optionalStringArg(args, 'output'), + format: stringArg(args, 'format', 'markdown') as 'markdown' | 'json', + p95BudgetMs: numberArg(args, 'p95-budget-ms', 300), + docsReturnedP95Budget: numberArg(args, 'docs-returned-p95-budget', 500), + hydratedDocsReturnedP95Budget: numberArg( + args, + 'hydrated-docs-returned-p95-budget', + 0, + ), + since: stringArg(args, 'since', '1 day ago'), + newRelicAccountId: + optionalStringArg(args, 'new-relic-account-id') ?? + process.env.NEW_RELIC_ACCOUNT_ID, + newRelicApiKey: + optionalStringArg(args, 'new-relic-api-key') ?? + process.env.NEW_RELIC_USER_API_KEY ?? + process.env.NEW_RELIC_API_KEY, + newRelicAppName: + optionalStringArg(args, 'new-relic-app-name') ?? + process.env.NEW_RELIC_APP_NAME ?? + 'lolympus', + routesOnly: args.has('routes-only'), + }; +} + +function defaultReportSource(): ReportSource { + return process.env.NEW_RELIC_ACCOUNT_ID && + (process.env.NEW_RELIC_USER_API_KEY || process.env.NEW_RELIC_API_KEY) + ? 'newrelic-custom' + : 'local'; +} + +function stringArg( + args: Map, + name: string, + defaultValue: string, +): string { + const value = args.get(name); + return typeof value === 'string' && value !== '' ? value : defaultValue; +} + +function optionalStringArg( + args: Map, + name: string, +): string | undefined { + const value = args.get(name); + return typeof value === 'string' && value !== '' ? value : undefined; +} + +function numberArg( + args: Map, + name: string, + defaultValue: number, +): number { + const value = Number(stringArg(args, name, String(defaultValue))); + return Number.isFinite(value) ? value : defaultValue; +} + +async function buildReport(options: ReportOptions): Promise { + const routes = await discoverApiRoutes(options.rootDir); + if (options.routesOnly) { + return `${JSON.stringify(routes, null, 2)}\n`; + } + + const measuredRows = + options.source === 'local' + ? buildEndpointReportFromLocalEvents({ + routes, + events: await readLocalPerformanceEvents(options.inputFile), + p95BudgetMs: options.p95BudgetMs, + docsReturnedP95Budget: options.docsReturnedP95Budget, + hydratedDocsReturnedP95Budget: + options.hydratedDocsReturnedP95Budget, + }) + : await fetchNewRelicEndpointRows({ + source: options.source, + accountId: requireOption( + options.newRelicAccountId, + 'NEW_RELIC_ACCOUNT_ID', + ), + apiKey: requireOption(options.newRelicApiKey, 'NEW_RELIC_API_KEY'), + appName: options.newRelicAppName, + since: options.since, + p95BudgetMs: options.p95BudgetMs, + docsReturnedP95Budget: options.docsReturnedP95Budget, + hydratedDocsReturnedP95Budget: + options.hydratedDocsReturnedP95Budget, + }); + const notes = + options.source === 'newrelic-custom' && measuredRows.length === 0 + ? [ + 'No ApiRequestPerformance custom events were found for this window and appName.', + 'Custom events are created only after the API runs with API_PERF_OBSERVABILITY_ENABLED=true and API_PERF_NEW_RELIC_REQUEST_EVENTS_ENABLED=true.', + 'Use --source=newrelic-transaction for historical latency before custom instrumentation was enabled.', + ] + : []; + const rows = mergeRowsWithManifest({ + routes, + measuredRows, + fallbackSource: options.source, + p95BudgetMs: options.p95BudgetMs, + docsReturnedP95Budget: options.docsReturnedP95Budget, + hydratedDocsReturnedP95Budget: options.hydratedDocsReturnedP95Budget, + }); + + return options.format === 'json' + ? `${JSON.stringify(rows, null, 2)}\n` + : formatMarkdownReport({ + rows, + source: options.source, + since: options.since, + notes, + }); +} + +function requireOption(value: string | undefined, name: string): string { + if (value) return value; + throw new Error(`${name} is required for New Relic report sources.`); +} + +async function main() { + const options = parseArgs(process.argv.slice(2)); + const report = await buildReport(options); + if (options.outputFile) { + await writeFile(path.resolve(options.outputFile), report); + return; + } + process.stdout.write(report); +} + +if (require.main === module) { + void main().catch((error: unknown) => { + process.stderr.write( + `${error instanceof Error ? error.message : String(error)}\n`, + ); + process.exitCode = 1; + }); +} diff --git a/apps/api/src/scripts/auction-redis-rehearsal.ts b/apps/api/src/scripts/auction-redis-rehearsal.ts new file mode 100644 index 00000000..3364099e --- /dev/null +++ b/apps/api/src/scripts/auction-redis-rehearsal.ts @@ -0,0 +1,643 @@ +import { ConfigService } from '@nestjs/config'; +import { randomUUID } from 'crypto'; +import fs from 'fs'; +import mongoose from 'mongoose'; +import path from 'path'; +import { createClient } from 'redis'; +import { AuctionDeadlineScheduler } from '../modules/auction/auction-deadline.scheduler'; +import { AuctionDurabilityScheduler } from '../modules/auction/auction-durability.scheduler'; +import { AuctionService } from '../modules/auction/auction.service'; +import { AuctionRedisCommandService } from '../modules/auction/redis/auction-redis-command.service'; +import { buildAuctionRedisKeys } from '../modules/auction/redis/auction-redis.keys'; +import { AuctionRedisService } from '../modules/auction/redis/auction-redis.service'; +import { AuctionRedisStateReaderService } from '../modules/auction/redis/auction-redis-state-reader.service'; +import { ConnectionService, resolveMongoDbName } from '../modules/global/database/connection.service'; +import { + assertDistinctRedisInstances, + resolveRedisClientOptions, +} from '../modules/global/redis/redis.config'; +import { SecretService } from '../modules/global/secret/secret.service'; + +type RedisClient = ReturnType; + +const REHEARSAL_PREFIX = 'redis-sot-rehearsal'; +const WAIT_FOR_EXPIRY_POLL_INTERVAL_MS = 1000; +const WAIT_FOR_EXPIRY_TIMEOUT_MS = 20_000; + +interface RehearsalResources { + auctionIds: mongoose.Types.ObjectId[]; + communityId?: mongoose.Types.ObjectId; + matchId?: mongoose.Types.ObjectId; + userIds: mongoose.Types.ObjectId[]; +} + +function loadProjectEnv(): void { + const candidates = [ + path.resolve(process.cwd(), 'project.env'), + path.resolve(process.cwd(), '../project.env'), + path.resolve(process.cwd(), 'apps/project.env'), + ]; + for (const candidate of candidates) { + if (!fs.existsSync(candidate)) continue; + for (const line of fs.readFileSync(candidate, 'utf8').split(/\r?\n/u)) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith('#')) continue; + const separatorIndex = trimmed.indexOf('='); + if (separatorIndex < 0) continue; + const key = trimmed.slice(0, separatorIndex).trim(); + const value = trimmed + .slice(separatorIndex + 1) + .trim() + .replace(/^['"]|['"]$/gu, ''); + if (key && process.env[key] === undefined) { + process.env[key] = value; + } + } + } +} + +async function readFirstSecret( + secretService: SecretService, + keys: string[], +): Promise { + for (const key of keys) { + const value = await secretService.get(key, ''); + const trimmed = value.trim(); + if (trimmed) return trimmed; + } + return undefined; +} + +function requireSafeNodeEnv(): void { + if (process.env.NODE_ENV === 'prod' && process.env.ALLOW_PROD_AUCTION_REHEARSAL !== 'true') { + throw new Error( + 'Refusing to run auction Redis rehearsal against prod. Set ALLOW_PROD_AUCTION_REHEARSAL=true only for an explicit production drill.', + ); + } +} + +function logStep(message: string): void { + console.log(`[auction-rehearsal] ${message}`); +} + +async function createRedisClientFromSecrets( + secretService: SecretService, + kind: 'common' | 'auction', +): Promise { + const prefix = kind === 'auction' ? 'AUCTION_REDIS' : 'REDIS'; + const urlKeys = kind === 'auction' ? [`${prefix}_URL`] : ['REDIS_URL', 'GARNET_URL']; + const endpointKeys = + kind === 'auction' ? [`${prefix}_ENDPOINT`] : ['REDIS_ENDPOINT', 'GARNET_ENDPOINT']; + const usernameKeys = + kind === 'auction' + ? [`${prefix}_USERNAME`, `${prefix}_USERID`] + : ['REDIS_USERNAME', 'REDIS_USERID', 'GARNET_USERNAME', 'GARNET_USERID']; + const passwordKeys = + kind === 'auction' ? [`${prefix}_PASSWORD`] : ['REDIS_PASSWORD', 'GARNET_PASSWORD']; + const [url, endpoint, username, password] = await Promise.all([ + readFirstSecret(secretService, urlKeys), + readFirstSecret(secretService, endpointKeys), + readFirstSecret(secretService, usernameKeys), + readFirstSecret(secretService, passwordKeys), + ]); + const client = createClient( + resolveRedisClientOptions({ + endpoint, + endpointEnvName: `${prefix}_ENDPOINT`, + password, + url, + urlEnvName: `${prefix}_URL`, + username, + }), + ); + client.on('error', (error) => { + console.error(`[auction-rehearsal] ${kind} Redis error:`, error); + }); + await client.connect(); + return client; +} + +async function assertRedisTopology( + secretService: SecretService, +): Promise<{ auctionRedisClient: RedisClient; commonRedisClient: RedisClient }> { + const [ + redisUrl, + redisEndpoint, + auctionRedisUrl, + auctionRedisEndpoint, + ] = await Promise.all([ + readFirstSecret(secretService, ['REDIS_URL', 'GARNET_URL']), + readFirstSecret(secretService, ['REDIS_ENDPOINT', 'GARNET_ENDPOINT']), + readFirstSecret(secretService, ['AUCTION_REDIS_URL']), + readFirstSecret(secretService, ['AUCTION_REDIS_ENDPOINT']), + ]); + const redisOptions = resolveRedisClientOptions({ + endpoint: redisEndpoint, + endpointEnvName: 'REDIS_ENDPOINT', + url: redisUrl, + urlEnvName: 'REDIS_URL', + }); + const auctionRedisOptions = resolveRedisClientOptions({ + endpoint: auctionRedisEndpoint, + endpointEnvName: 'AUCTION_REDIS_ENDPOINT', + url: auctionRedisUrl, + urlEnvName: 'AUCTION_REDIS_URL', + }); + assertDistinctRedisInstances(redisOptions.url, auctionRedisOptions.url); + + const [commonRedisClient, auctionRedisClient] = await Promise.all([ + createRedisClientFromSecrets(secretService, 'common'), + createRedisClientFromSecrets(secretService, 'auction'), + ]); + await Promise.all([ + commonRedisClient.sendCommand(['PING']), + auctionRedisClient.sendCommand(['PING']), + auctionRedisClient.sendCommand(['TIME']), + ]); + return { auctionRedisClient, commonRedisClient }; +} + +async function cleanupRedis( + auctionRedisService: AuctionRedisService, + matchId: mongoose.Types.ObjectId, +): Promise { + const keys = buildAuctionRedisKeys(matchId.toString()); + await auctionRedisService.raw().sendCommand([ + 'DEL', + keys.liveStateKey, + keys.structureStateKey, + keys.appliedTransitionIdsKey, + keys.bidHistoryKey, + keys.bidRequestResultsKey, + keys.bidRequestResultOrderKey, + keys.actionRequestResultsKey, + keys.actionRequestResultOrderKey, + keys.rehydrateLockKey, + keys.stateTransitionLockKey, + ]); + await auctionRedisService.raw().sendCommand([ + 'ZREM', + keys.deadlineQueueKey, + matchId.toString(), + ]); + + let cursor = '0'; + do { + const reply = await auctionRedisService.raw().sendCommand([ + 'SCAN', + cursor, + 'MATCH', + `${keys.durabilityPayloadKeyPrefix}*`, + 'COUNT', + '100', + ]); + if (!Array.isArray(reply) || reply.length < 2) return; + cursor = String(reply[0]); + const payloadKeys = Array.isArray(reply[1]) ? reply[1].map(String) : []; + if (payloadKeys.length > 0) { + await auctionRedisService.raw().sendCommand([ + 'ZREM', + keys.durabilityRetryQueueKey, + ...payloadKeys, + ]); + await auctionRedisService.raw().sendCommand([ + 'ZREM', + keys.durabilityDeadLetterQueueKey, + ...payloadKeys, + ]); + await auctionRedisService.raw().sendCommand(['DEL', ...payloadKeys]); + } + } while (cursor !== '0'); +} + +async function closeRedisClient( + client: RedisClient, + label: 'auction' | 'common', +): Promise { + try { + const result = await Promise.race([ + client.quit().then(() => 'closed' as const), + new Promise<'timeout'>((resolve) => { + setTimeout(() => resolve('timeout'), 3_000); + }), + ]); + if (result === 'timeout') { + client.destroy(); + logStep(`${label} Redis quit timed out; destroyed client`); + } + } catch { + client.destroy(); + logStep(`${label} Redis quit failed; destroyed client`); + } +} + +async function cleanupMongo( + connectionService: ConnectionService, + resources: RehearsalResources, +): Promise { + const AuctionModel = await connectionService.getModel('auction'); + const AuctionHistoryModel = await connectionService.getModel('auctionHistory'); + const SideEffectModel = await connectionService.getModel( + 'auctionSideEffectApplication', + ); + const MatchModel = await connectionService.getModel('match'); + const UserModel = await connectionService.getModel('user'); + const CommunityModel = await connectionService.getModel('community'); + const auctionIds = new Set(resources.auctionIds.map((id) => id.toString())); + if (resources.matchId) { + const existingAuctions = await AuctionModel.find({ + matchId: resources.matchId, + }) + .select({ _id: 1 }) + .lean() + .exec(); + for (const auction of existingAuctions) { + auctionIds.add(String(auction._id)); + } + await SideEffectModel.deleteMany({ matchId: resources.matchId }).exec(); + await MatchModel.deleteOne({ _id: resources.matchId }).exec(); + } + if (auctionIds.size > 0) { + const ids = [...auctionIds].map((id) => new mongoose.Types.ObjectId(id)); + await AuctionHistoryModel.deleteMany({ auctionId: { $in: ids } }).exec(); + await AuctionModel.deleteMany({ _id: { $in: ids } }).exec(); + } + if (resources.userIds.length > 0) { + await UserModel.deleteMany({ _id: { $in: resources.userIds } }).exec(); + } + if (resources.communityId) { + await CommunityModel.deleteOne({ _id: resources.communityId }).exec(); + } +} + +async function seedMatch( + connectionService: ConnectionService, +): Promise { + const CommunityModel = await connectionService.getModel('community'); + const UserModel = await connectionService.getModel('user'); + const MatchModel = await connectionService.getModel('match'); + const suffix = `${Date.now()}-${randomUUID().slice(0, 8)}`; + const communityId = new mongoose.Types.ObjectId(); + const ownerUserId = new mongoose.Types.ObjectId(); + const community = await CommunityModel.create({ + _id: communityId, + description: 'Temporary auction Redis rehearsal community', + name: `${REHEARSAL_PREFIX}-${suffix}`, + ownerUserId, + riotPlatform: 'kr', + riotRegion: 'asia', + }); + const userIds = Array.from({ length: 10 }, (_, index) => + index === 0 ? ownerUserId : new mongoose.Types.ObjectId(), + ); + await UserModel.insertMany( + userIds.map((userId, index) => ({ + _id: userId, + communityId: community._id, + preferredPositions: [{ position: 'MID', priority: 1 }], + riotAccounts: [ + { + championMasteries: [], + championRecords: {}, + gameName: `Rehearsal${index + 1}`, + isPrimary: true, + lastRefreshRequestedAt: new Date(), + profileIconId: 1, + puuid: `${REHEARSAL_PREFIX}-puuid-${suffix}-${index + 1}`, + tagLine: 'TEST', + tierHistory: [], + tiers: [], + }, + ], + role: index === 0 ? 'owner' : 'member', + })), + ); + const match = await MatchModel.create({ + communityId: community._id, + description: 'Temporary Redis SoT rehearsal match', + gameCount: 1, + gameMode: 'pair', + maxParticipants: 10, + participants: userIds.map((userId, index) => ({ + excluded: false, + joinedAt: new Date(Date.now() + index), + preferredPositions: [{ position: 'MID', priority: 1 }], + userId, + })), + scheduledAt: new Date(Date.now() + 60_000), + shortCode: `R${Math.random().toString(36).slice(2, 6)}`.slice(0, 6).toUpperCase(), + status: 'recruiting', + title: `${REHEARSAL_PREFIX}-${suffix}`, + }); + return { + auctionIds: [], + communityId: community._id, + matchId: match._id, + userIds, + }; +} + +async function flushDurability( + durabilityScheduler: AuctionDurabilityScheduler, +): Promise { + for (let attempt = 0; attempt < 5; attempt += 1) { + const result = await durabilityScheduler.processDueDurabilityPayloads(50); + if (result.applied === 0 && result.failed === 0) return; + } +} + +async function waitForDeadlineCompletion( + deadlineScheduler: AuctionDeadlineScheduler, +): Promise { + const startedAt = Date.now(); + let lastResult: Awaited< + ReturnType + > | null = null; + + while (Date.now() - startedAt < WAIT_FOR_EXPIRY_TIMEOUT_MS) { + await new Promise((resolve) => + setTimeout(resolve, WAIT_FOR_EXPIRY_POLL_INTERVAL_MS), + ); + lastResult = await deadlineScheduler.processDueBidRoundDeadlines(20); + if (lastResult.completed >= 1) return; + } + + throw new Error( + `Expected deadline completion, got ${JSON.stringify(lastResult)}`, + ); +} + +function assertState( + state: Record | null, + expectedPhase: string, +): Record { + if (!state) throw new Error(`Expected auction state phase=${expectedPhase}, got null`); + if (state.phase !== expectedPhase) { + throw new Error( + `Expected auction phase=${expectedPhase}, got ${String(state.phase)}`, + ); + } + return state; +} + +async function main(): Promise { + loadProjectEnv(); + process.env.NODE_ENV = process.env.NODE_ENV || 'staging'; + process.env.SECRET_SOURCE = process.env.SECRET_SOURCE || 'infisical'; + requireSafeNodeEnv(); + + const keep = process.argv.includes('--keep'); + const configService = new ConfigService(process.env); + const secretService = new SecretService(configService); + await secretService.ready(); + logStep(`secrets loaded, nodeEnv=${process.env.NODE_ENV}, db=${resolveMongoDbName()}`); + + const { auctionRedisClient, commonRedisClient } = + await assertRedisTopology(secretService); + const connectionService = new ConnectionService(secretService); + const auctionRedisService = new AuctionRedisService(auctionRedisClient); + const auctionRedisCommandService = new AuctionRedisCommandService( + auctionRedisService, + ); + const auctionRedisStateReaderService = new AuctionRedisStateReaderService( + auctionRedisService, + ); + const dummyTournamentCodeService = { + releaseFromMatch: async () => undefined, + reserveForMatch: async () => undefined, + }; + const dummyTournamentResultService = { + cancelPolling: async () => undefined, + scheduleInitialPoll: async () => undefined, + }; + const dummySideEffectService = { + mirrorMatchSideEffectStatus: async () => true, + }; + const dummyEventBus = { + broadcastMatchSideEffect: () => undefined, + broadcastState: () => undefined, + }; + const auctionService = new AuctionService( + connectionService, + { + enrichRiotAccount: async () => ({ + account: null, + league: 'fresh', + masteries: 'fresh', + recentMatches: 'fresh', + summoner: 'fresh', + }), + } as never, + dummyTournamentCodeService as never, + dummyTournamentResultService as never, + auctionRedisService, + auctionRedisCommandService, + auctionRedisStateReaderService, + ); + const durabilityScheduler = new AuctionDurabilityScheduler( + connectionService, + auctionRedisService, + dummyTournamentCodeService as never, + dummyTournamentResultService as never, + dummySideEffectService as never, + dummyEventBus as never, + ); + const deadlineScheduler = new AuctionDeadlineScheduler( + auctionRedisService, + auctionRedisCommandService, + auctionService, + dummyEventBus as never, + ); + + const resources: RehearsalResources = { auctionIds: [], userIds: [] }; + try { + Object.assign(resources, await seedMatch(connectionService)); + if (!resources.matchId || !resources.communityId) { + throw new Error('Failed to seed rehearsal match.'); + } + logStep(`seeded match=${resources.matchId.toString()}`); + + const auction = await auctionService.start({ + bidRoundExtensionSeconds: 1, + captains: [ + { teamIndex: 1, userId: resources.userIds[0] }, + { teamIndex: 2, userId: resources.userIds[1] }, + ], + communityId: resources.communityId, + initialTeamBidPointAmount: 100, + manualTopTierAuctionPriorityUserIds: [], + matchId: resources.matchId, + maximumBidRoundDurationSeconds: 5, + startAuctionRequestId: randomUUID(), + topTierAuctionPriorityThreshold: 'NONE', + }); + resources.auctionIds.push(auction._id); + assertState( + await auctionRedisStateReaderService.readAuctionStateView( + resources.matchId.toString(), + ), + 'presenting', + ); + logStep('start -> presenting OK'); + + await auctionService.openBidding(resources.matchId, { + auctionActionRequestId: randomUUID(), + }); + await flushDurability(durabilityScheduler); + assertState( + await auctionRedisStateReaderService.readAuctionStateView( + resources.matchId.toString(), + ), + 'bidding', + ); + logStep('open-bidding -> bidding OK'); + + const bidResult = await auctionService.placeBid({ + amount: 10, + bidRequestId: randomUUID(), + matchId: resources.matchId, + teamIndex: 1, + }); + if (!('revision' in bidResult)) throw new Error('Bid did not return state.'); + logStep('bid OK'); + + await auctionService.markSold({ + assignedPosition: 'MID', + auctionActionRequestId: randomUUID(), + matchId: resources.matchId, + }); + await flushDurability(durabilityScheduler); + assertState( + await auctionRedisStateReaderService.readAuctionStateView( + resources.matchId.toString(), + ), + 'sold', + ); + logStep('sold transition OK'); + + await auctionService.next(resources.matchId, { + auctionActionRequestId: randomUUID(), + }); + await flushDurability(durabilityScheduler); + assertState( + await auctionRedisStateReaderService.readAuctionStateView( + resources.matchId.toString(), + ), + 'presenting', + ); + logStep('next -> presenting OK'); + + await auctionService.openBidding(resources.matchId, { + auctionActionRequestId: randomUUID(), + }); + await flushDurability(durabilityScheduler); + const secondBiddingState = assertState( + await auctionRedisStateReaderService.readAuctionStateView( + resources.matchId.toString(), + ), + 'bidding', + ); + const secondBiddingKeys = buildAuctionRedisKeys(resources.matchId.toString()); + const queuedDeadlineScore = await auctionRedisService.raw().sendCommand([ + 'ZSCORE', + secondBiddingKeys.deadlineQueueKey, + resources.matchId.toString(), + ]); + if (!queuedDeadlineScore) { + throw new Error( + `Expected deadline queue item after second open-bidding, state deadline=${String( + secondBiddingState.currentBidRoundDeadlineTimestampMS, + )}`, + ); + } + logStep( + `waiting up to ${WAIT_FOR_EXPIRY_TIMEOUT_MS}ms for Redis TIME deadline`, + ); + await waitForDeadlineCompletion(deadlineScheduler); + await flushDurability(durabilityScheduler); + assertState( + await auctionRedisStateReaderService.readAuctionStateView( + resources.matchId.toString(), + ), + 'passed', + ); + logStep('automatic expiry -> passed OK'); + + const historyBeforeUndo = await auctionService.listHistory({ + communityId: resources.communityId, + matchId: resources.matchId, + }); + const undoTarget = historyBeforeUndo[historyBeforeUndo.length - 1]?.sequence; + if (!undoTarget) throw new Error('No history sequence to undo.'); + await auctionService.undoTo({ + auctionActionRequestId: randomUUID(), + communityId: resources.communityId, + matchId: resources.matchId, + sequence: undoTarget, + }); + await flushDurability(durabilityScheduler); + logStep(`undo to sequence=${undoTarget} OK`); + + await auctionService.reset({ + auctionActionRequestId: randomUUID(), + communityId: resources.communityId, + matchId: resources.matchId, + }); + await flushDurability(durabilityScheduler); + const resetState = await auctionRedisStateReaderService.readAuctionStateView( + resources.matchId.toString(), + ); + if (resetState) { + throw new Error( + `Expected reset to clear Redis state, got phase=${String(resetState.phase)}`, + ); + } + logStep('reset -> auction data cleared OK'); + + const restartedAuction = await auctionService.start({ + bidRoundExtensionSeconds: 1, + captains: [ + { teamIndex: 1, userId: resources.userIds[0] }, + { teamIndex: 2, userId: resources.userIds[1] }, + ], + communityId: resources.communityId, + initialTeamBidPointAmount: 100, + manualTopTierAuctionPriorityUserIds: [], + matchId: resources.matchId, + maximumBidRoundDurationSeconds: 5, + startAuctionRequestId: randomUUID(), + topTierAuctionPriorityThreshold: 'NONE', + }); + resources.auctionIds.push(restartedAuction._id); + assertState( + await auctionRedisStateReaderService.readAuctionStateView( + resources.matchId.toString(), + ), + 'presenting', + ); + logStep('restart after reset OK'); + logStep('REHEARSAL PASSED'); + } finally { + if (!keep) { + if (resources.matchId) { + await cleanupRedis(auctionRedisService, resources.matchId); + } + await cleanupMongo(connectionService, resources); + logStep('cleanup complete'); + } else { + logStep('kept rehearsal data because --keep was provided'); + } + await closeRedisClient(auctionRedisClient, 'auction'); + await closeRedisClient(commonRedisClient, 'common'); + await connectionService.onModuleDestroy(); + await mongoose.disconnect().catch(() => undefined); + logStep('connections closed'); + } +} + +void main().then(() => { + process.exit(0); +}).catch((error) => { + console.error('[auction-rehearsal] FAILED:', error); + process.exit(1); +}); diff --git a/apps/web/.env.development b/apps/web/.env.development index cd55dbf3..aa7767e6 100644 --- a/apps/web/.env.development +++ b/apps/web/.env.development @@ -1,7 +1,15 @@ -VITE_API_BASE_URL=http://localhost:3000 +VITE_API_BASE_URL=http://126.dahyeon.us:3000 VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1 VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3 VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863 VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback VITE_MSAL_SILENT_REDIRECT_URI=http://localhost:5173/auth/silent-callback.html +VITE_NEW_RELIC_ENABLED=false +VITE_NEW_RELIC_APPLICATION_ID=601654991 +VITE_NEW_RELIC_ACCOUNT_ID=8100154 +VITE_NEW_RELIC_AGENT_ID=601654991 +VITE_NEW_RELIC_LICENSE_KEY=NRJS-caad7f6e90b92fe88de +VITE_NEW_RELIC_TRUST_KEY=8100154 +VITE_NEW_RELIC_BEACON=bam.nr-data.net +VITE_NEW_RELIC_RELEASE_NAME=lolympus-web diff --git a/apps/web/.env.example b/apps/web/.env.example index 969d2d5c..ba1c2137 100644 --- a/apps/web/.env.example +++ b/apps/web/.env.example @@ -5,3 +5,13 @@ VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/ VITE_MSAL_API_SCOPE=api://lolympus-api/access_as_user VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback VITE_MSAL_SILENT_REDIRECT_URI=http://localhost:5173/auth/silent-callback.html +VITE_NEW_RELIC_ENABLED=false +VITE_NEW_RELIC_APPLICATION_ID= +VITE_NEW_RELIC_ACCOUNT_ID= +VITE_NEW_RELIC_AGENT_ID= +VITE_NEW_RELIC_LICENSE_KEY= +VITE_NEW_RELIC_TRUST_KEY= +VITE_NEW_RELIC_BEACON=bam.nr-data.net +VITE_NEW_RELIC_APPLICATION_VERSION= +VITE_NEW_RELIC_RELEASE_ID= +VITE_NEW_RELIC_RELEASE_NAME=lolympus-web diff --git a/apps/web/.env.production b/apps/web/.env.production index 64d88a8a..b64e84d1 100644 --- a/apps/web/.env.production +++ b/apps/web/.env.production @@ -5,4 +5,13 @@ VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64 VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev VITE_MSAL_REDIRECT_URI=https://lolympus.dahyeon.us/auth/callback VITE_MSAL_SILENT_REDIRECT_URI=https://lolympus.dahyeon.us/auth/silent-callback.html - +VITE_NEW_RELIC_ENABLED=true +VITE_NEW_RELIC_APPLICATION_ID=601654991 +VITE_NEW_RELIC_ACCOUNT_ID=8100154 +VITE_NEW_RELIC_AGENT_ID=601654991 +VITE_NEW_RELIC_LICENSE_KEY=NRJS-caad7f6e90b92fe88de +VITE_NEW_RELIC_TRUST_KEY=8100154 +VITE_NEW_RELIC_BEACON=bam.nr-data.net +VITE_NEW_RELIC_APPLICATION_VERSION=83 +VITE_NEW_RELIC_RELEASE_ID=release-83 +VITE_NEW_RELIC_RELEASE_NAME=lolympus-web diff --git a/apps/web/.env.staging b/apps/web/.env.staging index 8d308d67..0ddcecba 100644 --- a/apps/web/.env.staging +++ b/apps/web/.env.staging @@ -1,6 +1,16 @@ VITE_API_BASE_URL=https://lolympus-api-staging.dahyeon.us VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1 -VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3 +VITE_MSAL_CLIENT_ID=66dadf46-418c-43c8-a908-3c15dcc0465d VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863 VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev -VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback +VITE_MSAL_REDIRECT_URI=https://release-83.lolympus.pages.dev/auth/callback +VITE_NEW_RELIC_ENABLED=true +VITE_NEW_RELIC_APPLICATION_ID=601654991 +VITE_NEW_RELIC_ACCOUNT_ID=8100154 +VITE_NEW_RELIC_AGENT_ID=601654991 +VITE_NEW_RELIC_LICENSE_KEY=NRJS-caad7f6e90b92fe88de +VITE_NEW_RELIC_TRUST_KEY=8100154 +VITE_NEW_RELIC_BEACON=bam.nr-data.net +VITE_NEW_RELIC_APPLICATION_VERSION=83 +VITE_NEW_RELIC_RELEASE_ID=release-83 +VITE_NEW_RELIC_RELEASE_NAME=lolympus-web diff --git a/apps/web/package.json b/apps/web/package.json index 8d9b78b5..881c1aec 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -7,6 +7,7 @@ "dev": "vite", "start:dev": "vite --mode development", "start:staging": "vite --mode staging", + "test": "node --test --experimental-strip-types test/*.test.ts", "build": "tsc -b && vite build", "build:staging": "tsc -b && vite build --mode staging", "build:prod": "tsc -b && vite build --mode production", @@ -18,8 +19,10 @@ "preview": "vite preview" }, "dependencies": { + "@lolympus/contracts": "workspace:*", "@azure/msal-browser": "^5.8.0", "@azure/msal-react": "^5.3.1", + "@newrelic/browser-agent": "^1.316.0", "@tanstack/react-query": "^5.100.1", "lucide-react": "^1.14.0", "react": "^19.2.4", diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index ed8d4b43..b1fb1527 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -10,6 +10,7 @@ import AuthCallbackPage from "./pages/AuthCallback"; import HomePage from "./pages/HomePage"; import LoginPage from "./pages/Login"; import MatchDetailPage from "./pages/MatchDetailPage"; +import MatchGameDetailPage from "./pages/MatchGameDetailPage"; import MatchTeamProgressPage from "./pages/MatchTeamProgressPage"; import AuctionPage from "./pages/AuctionPage"; import UserHistoryPage from "./pages/UserHistoryPage"; @@ -50,7 +51,8 @@ function MsalHeaderActions() { function ThemeToggle() { const theme = useTheme(); const nextTheme = theme === "light" ? "dark" : "light"; - const label = nextTheme === "dark" ? "다크 테마로 전환" : "라이트 테마로 전환"; + const label = + nextTheme === "dark" ? "다크 테마로 전환" : "라이트 테마로 전환"; const Icon = nextTheme === "dark" ? Moon : Sun; return ( @@ -80,11 +82,11 @@ function AppFooter() {

- © 2026 LOLYMPUS. LOLYMPUS is not endorsed by Riot Games and - does not reflect the views or opinions of Riot Games or anyone - officially involved in producing or managing League of Legends. - League of Legends and Riot Games are trademarks or registered - trademarks of Riot Games, Inc. League of Legends © Riot Games, Inc. + © 2026 LOLYMPUS. LOLYMPUS is not endorsed by Riot Games and does not + reflect the views or opinions of Riot Games or anyone officially + involved in producing or managing League of Legends. League of Legends + and Riot Games are trademarks or registered trademarks of Riot Games, + Inc. League of Legends © Riot Games, Inc.

@@ -152,11 +154,15 @@ function App() { } /> } /> } + path="/match/:id/game/:gameNumber" + element={} /> + } /> } /> - } /> + } + /> } @@ -165,6 +171,10 @@ function App() { path="/communities/:cid/internal-stats/match/:matchId" element={} /> + } + /> } diff --git a/apps/web/src/api/auctionRejectionMessages.ts b/apps/web/src/api/auctionRejectionMessages.ts new file mode 100644 index 00000000..cdbee3a9 --- /dev/null +++ b/apps/web/src/api/auctionRejectionMessages.ts @@ -0,0 +1,101 @@ +/** + * 경매 거부코드 → 사용자 문구 매핑(프론트 전용). + * + * 서버(`apps/api/.../auction-rejection.ts`)가 ack에 실어주는 설명적 거부코드 + * `auctionRejectionReason`를 사람이 읽는 한국어 문구로 바꾼다. reason 문자열은 + * 서버와의 계약이므로 양쪽을 함께 바꿔야 한다(서버는 영문 message도 함께 보내므로, + * 매핑이 빠진 reason은 message로 폴백된다). + * + * 또한 ack가 없는 `error` 이벤트 채널(영문 message만 옴)도 같은 톤의 한국어로 + * 바꿀 수 있도록 영문 message → 한국어 매핑을 함께 둔다. + */ + +/** 서버 `AUCTION_REJECTION_REASON`와 1:1로 맞춘 사용자 문구. */ +const REASON_TO_USER_MESSAGE: Record = { + // 구조 전환 + AUCTION_TRANSITION_REJECTED_BECAUSE_LIVE_STATE_CHANGED_BEFORE_APPLY: + '경매 상태가 바뀌어 최신 상태로 맞췄어요. 다시 시도해 주세요.', + AUCTION_TRANSITION_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE: + '이미 입찰 단계가 아니에요. 최신 상태로 맞췄어요.', + AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE: + '이미 다음 단계로 넘어간 상태예요. 최신 상태로 맞췄어요.', + AUCTION_TRANSITION_REJECTED_BECAUSE_NO_WINNING_BID_TO_MARK_SOLD: + '낙찰할 입찰이 없어요. 최신 상태로 맞췄어요.', + AUCTION_TRANSITION_REJECTED_BECAUSE_ACTIVE_BID_PRESENT: + '진행 중인 입찰이 있어 유찰할 수 없어요.', + AUCTION_TRANSITION_REJECTED_BECAUSE_REQUEST_COORDINATION_RETRYABLE: + '잠시 처리 중이라 반영되지 않았어요. 다시 시도해 주세요.', + // 입찰 + BID_REJECTED_BECAUSE_BID_ROUND_ALREADY_ADVANCED: '이미 다음 선수로 넘어갔어요.', + BID_REJECTED_BECAUSE_BID_ROUND_DEADLINE_PASSED: '마감되어 반영되지 않았어요.', + BID_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE: + '지금은 입찰할 수 없는 단계예요.', + BID_REJECTED_BECAUSE_AMOUNT_NOT_HIGHER_THAN_CURRENT_HIGHEST: + '더 높은 입찰이 있었어요.', + BID_REJECTED_BECAUSE_TEAM_ROSTER_FULL: '팀 정원이 가득 찼어요.', + BID_REJECTED_BECAUSE_INSUFFICIENT_REMAINING_POINTS_FOR_SLOTS: + '남은 슬롯을 고려하면 포인트가 부족해요.', + BID_REJECTED_BECAUSE_UNKNOWN_TEAM: '알 수 없는 팀이에요.', + BID_REJECTED_BECAUSE_DUPLICATE_REQUEST_PAYLOAD_CONFLICT: '중복된 요청이에요.', + BID_REJECTED_BECAUSE_RATE_LIMITED: + '요청이 너무 많아요. 잠시 후 다시 시도해 주세요.', + // 공통 + AUCTION_REQUEST_REJECTED_BECAUSE_REALTIME_STATE_UNAVAILABLE: + '실시간 상태를 불러오는 중이에요. 잠시 후 다시 시도해 주세요.', +}; + +/** ack 없이 `error` 이벤트로만 오는 영문 message → 한국어. */ +const ENGLISH_MESSAGE_TO_USER_MESSAGE: Record = { + 'Bid deadline has already expired.': '마감되어 반영되지 않았어요.', + 'Bid must exceed current bid.': '더 높은 입찰이 있었어요.', + 'Bid round has already changed.': '이미 다음 선수로 넘어갔어요.', + 'Auction is not in bidding phase.': '지금은 입찰할 수 없는 단계예요.', + 'Team already has maximum members.': '팀 정원이 가득 찼어요.', + 'Bid must reserve minimum points for remaining slots.': + '남은 슬롯을 고려하면 포인트가 부족해요.', + 'Unknown team.': '알 수 없는 팀이에요.', + 'Bid request conflicts with an earlier request.': '중복된 요청이에요.', + 'Cannot advance from current phase.': + '이미 다음 단계로 넘어간 상태예요. 최신 상태로 맞췄어요.', + 'No bid to mark sold.': '낙찰할 입찰이 없어요. 최신 상태로 맞췄어요.', + 'Cannot pass a player with an active bid.': + '진행 중인 입찰이 있어 유찰할 수 없어요.', +}; + +const DEFAULT_REJECTION_MESSAGE = '요청이 반영되지 않았어요.'; +const DEFAULT_ERROR_MESSAGE = '실시간 경매 연결 중 오류가 발생했습니다.'; + +export interface AuctionRejectionAckLike { + auctionRejectionReason?: string; + code?: string; + message?: string; + resyncRecommended?: boolean; +} + +/** 거부 ack → 사용자 문구. reason 매핑 우선, 없으면 영문 message 매핑, 그래도 없으면 원문/기본값. */ +export function resolveAuctionRejectionMessage( + ack: AuctionRejectionAckLike, +): string { + if (ack.auctionRejectionReason) { + const mapped = REASON_TO_USER_MESSAGE[ack.auctionRejectionReason]; + if (mapped) return mapped; + } + if (ack.message) { + const mapped = ENGLISH_MESSAGE_TO_USER_MESSAGE[ack.message]; + if (mapped) return mapped; + } + return ack.message ?? ack.code ?? DEFAULT_REJECTION_MESSAGE; +} + +/** `error` 이벤트(영문 message) → 사용자 문구. */ +export function resolveAuctionErrorMessage(message?: string): string { + if (message && ENGLISH_MESSAGE_TO_USER_MESSAGE[message]) { + return ENGLISH_MESSAGE_TO_USER_MESSAGE[message]; + } + return message ?? DEFAULT_ERROR_MESSAGE; +} + +/** 최신 상태로 rebaseline 후 재시도가 권장되는 거부인지. */ +export function isAuctionResyncRecommended(ack: AuctionRejectionAckLike): boolean { + return ack.resyncRecommended === true; +} diff --git a/apps/web/src/api/auth-query-scope.ts b/apps/web/src/api/auth-query-scope.ts new file mode 100644 index 00000000..916986f0 --- /dev/null +++ b/apps/web/src/api/auth-query-scope.ts @@ -0,0 +1,35 @@ +export interface AuthQueryScopeInput { + authUserId: string | null; + accountKey: string | null; + msalConfigured: boolean; + msalReady: boolean; +} + +interface ExecuteAuthScopedQueryInput { + accountKey: string | null; + acquireAccessToken: () => Promise; + request: (authorizationHeader: string | null) => Promise; +} + +export function resolveAuthQueryScope({ + authUserId, + accountKey, + msalConfigured, + msalReady, +}: AuthQueryScopeInput) { + return { + cacheKey: [authUserId, accountKey] as const, + ready: Boolean(authUserId || !msalConfigured || msalReady), + }; +} + +export async function executeAuthScopedQuery({ + accountKey, + acquireAccessToken, + request, +}: ExecuteAuthScopedQueryInput): Promise { + if (!accountKey) return request(null); + + const accessToken = await acquireAccessToken(); + return request(`Bearer ${accessToken}`); +} diff --git a/apps/web/src/api/hooks.ts b/apps/web/src/api/hooks.ts index 6857fd41..d434d5cf 100644 --- a/apps/web/src/api/hooks.ts +++ b/apps/web/src/api/hooks.ts @@ -1,6 +1,19 @@ import { InteractionStatus } from '@azure/msal-browser'; import { useMsal } from '@azure/msal-react'; import { useInfiniteQuery, useMutation, useQuery } from '@tanstack/react-query'; +import type { + CompetitionCommandResponse, + CompetitionDetailResponse, + CreateSeriesAdjudicationRequest, + MatchDetailResponse, + MatchLifecycleStatus, + MatchListResponse, + ReverseSeriesResultRequest, + SeriesId, + SeriesReversalPreviewRequest, + SeriesReversalPreviewResponse, + TeamCompetitionViewResponse, +} from '@lolympus/contracts'; import { DEFAULT_COMMUNITY_ID, useAuthUserId } from '../config'; import { apiFetch } from '../lib/api'; import { @@ -8,11 +21,16 @@ import { MSAL_API_SCOPE, MSAL_SILENT_REDIRECT_URI, } from '../lib/auth/msal.config'; +import { + executeAuthScopedQuery, + resolveAuthQueryScope, +} from './auth-query-scope'; import type { ApiAuction, ApiAuctionHistoryEntry, ApiChampionStatsResponse, ApiCommunity, + ApiCommunityUserSearchCandidate, ApiEnqueueRefreshResult, ApiInternalMatchDetailResponse, ApiInternalMatchListResponse, @@ -20,7 +38,6 @@ import type { LegacyImportJobsResponse, LegacyImportMembersResponse, LegacyMatchListResponse, - ApiMatch, ApiRecentMatchesResponse, ApiRecentSummaryResponse, ApiTeamInsightsResponse, @@ -30,9 +47,7 @@ import type { DdragonManifest, StartLegacyImportRequest, StartLegacyImportResponse, - MatchStatus, MatchMutationRequest, - MatchesResponse, ManualTournamentResultCollectResponse, MeResponse, RiotQueueGroup, @@ -48,7 +63,7 @@ import type { const DDRAGON_MANIFEST_STALE_MS = 24 * 60 * 60 * 1000; interface MatchesQueryOptions { - status?: MatchStatus; + status?: MatchLifecycleStatus; limit?: number; page?: number; offset?: number; @@ -81,7 +96,8 @@ function createMatchesPath( if (options.limit) searchParams.set('limit', String(options.limit)); if (options.page) searchParams.set('page', String(options.page)); if (options.offset) searchParams.set('offset', String(options.offset)); - if (options.scheduledFrom) searchParams.set('scheduledFrom', options.scheduledFrom); + if (options.scheduledFrom) + searchParams.set('scheduledFrom', options.scheduledFrom); if (options.scheduledTo) searchParams.set('scheduledTo', options.scheduledTo); if (options.sort) searchParams.set('sort', options.sort); @@ -89,6 +105,45 @@ function createMatchesPath( return `/communities/${communityId}/matches${queryString ? `?${queryString}` : ''}`; } +function useOptionalAuthQueryScope() { + const authUserId = useAuthUserId(); + const { accounts, inProgress, instance } = useMsal(); + const account = isMsalConfigured + ? (instance.getActiveAccount() ?? accounts[0] ?? null) + : null; + const scope = resolveAuthQueryScope({ + authUserId, + accountKey: account?.homeAccountId ?? null, + msalConfigured: isMsalConfigured, + msalReady: inProgress === InteractionStatus.None, + }); + + const fetch = (path: string) => + executeAuthScopedQuery({ + accountKey: account?.homeAccountId ?? null, + acquireAccessToken: async () => { + if (!account) { + throw new Error('MSAL account is unavailable.'); + } + const response = await instance.acquireTokenSilent({ + account, + scopes: [MSAL_API_SCOPE], + redirectUri: MSAL_SILENT_REDIRECT_URI, + }); + return response.accessToken; + }, + request: (authorizationHeader) => + apiFetch( + path, + authorizationHeader + ? { headers: { Authorization: authorizationHeader } } + : undefined, + ), + }); + + return { ...scope, fetch }; +} + export function useCommunity(communityId = DEFAULT_COMMUNITY_ID) { return useQuery({ queryKey: ['community', communityId], @@ -102,10 +157,13 @@ export function useMatches( options: MatchesQueryOptions, communityId = DEFAULT_COMMUNITY_ID, ) { + const authScope = useOptionalAuthQueryScope(); + return useQuery({ queryKey: [ 'matches', communityId, + ...authScope.cacheKey, options.status ?? null, options.limit ?? null, options.page ?? null, @@ -115,13 +173,12 @@ export function useMatches( options.sort ?? null, ], queryFn: async () => { - const response = await apiFetch( + const response = await authScope.fetch( createMatchesPath(communityId, options), - { auth: 'none' }, ); return response.matches; }, - enabled: Boolean(communityId), + enabled: Boolean(communityId && authScope.ready), }); } @@ -129,10 +186,13 @@ export function useMatchesPage( options: MatchesQueryOptions, communityId = DEFAULT_COMMUNITY_ID, ) { + const authScope = useOptionalAuthQueryScope(); + return useQuery({ queryKey: [ 'matches-page', communityId, + ...authScope.cacheKey, options.status ?? null, options.limit ?? null, options.page ?? null, @@ -142,26 +202,181 @@ export function useMatchesPage( options.sort ?? null, ], queryFn: () => - apiFetch(createMatchesPath(communityId, options), { - auth: 'none', - }), - enabled: Boolean(communityId), + authScope.fetch( + createMatchesPath(communityId, options), + ), + enabled: Boolean(communityId && authScope.ready), placeholderData: (previousData) => previousData, }); } -export function useMatch(matchId: string | undefined, communityId = DEFAULT_COMMUNITY_ID) { - return useQuery({ - queryKey: ['match', communityId, matchId ?? null], +export function useMatch( + matchId: string | undefined, + communityId = DEFAULT_COMMUNITY_ID, +) { + const authScope = useOptionalAuthQueryScope(); + const queryKey = [ + 'match', + communityId, + matchId ?? null, + ...authScope.cacheKey, + ] as const; + + const query = useQuery({ + queryKey, queryFn: () => - apiFetch(`/communities/${communityId}/matches/${matchId}`, { - auth: 'none', - }), + authScope.fetch( + `/communities/${communityId}/matches/${matchId}`, + ), + enabled: Boolean(communityId && matchId && authScope.ready), + retry: false, + }); + + return { ...query, queryKey }; +} + +export function useCompetition( + matchId: string | undefined, + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useQuery({ + queryKey: ['competition', communityId, matchId ?? null], + queryFn: () => + apiFetch( + `/communities/${communityId}/matches/${matchId}/competition`, + { + auth: 'none', + }, + ), + enabled: enabled && Boolean(communityId && matchId), + retry: false, + }); +} + +export function useTeamCompetition( + matchId: string | undefined, + communityId = DEFAULT_COMMUNITY_ID, + teamId?: string, +) { + return useQuery({ + queryKey: ['competition-team', communityId, matchId ?? null, teamId ?? null], + queryFn: () => + apiFetch( + `/communities/${communityId}/matches/${matchId}/competition/team${ + teamId ? `?teamId=${encodeURIComponent(teamId)}` : '' + }`, + ), enabled: Boolean(communityId && matchId), retry: false, }); } +type CompetitionMutationScope = { + matchId: string; + seriesId: SeriesId; + revision: number; +}; + +type IdempotentCompetitionMutationScope = CompetitionMutationScope & { + idempotencyKey: string; +}; + +function competitionCommandHeaders(revision: number, idempotencyKey?: string) { + return { + 'If-Match': `"${revision}"`, + ...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}), + }; +} + +export function useAdjudicateCompetitionSeries( + communityId = DEFAULT_COMMUNITY_ID, +) { + return useMutation({ + mutationFn: ( + params: IdempotentCompetitionMutationScope & { + request: CreateSeriesAdjudicationRequest; + }, + ) => + apiFetch( + `/communities/${communityId}/matches/${params.matchId}/competition/series/${params.seriesId}/adjudications`, + { + method: 'POST', + headers: competitionCommandHeaders( + params.revision, + params.idempotencyKey, + ), + body: JSON.stringify(params.request), + }, + ), + retry: false, + }); +} + +export function usePreviewCompetitionSeriesReversal( + communityId = DEFAULT_COMMUNITY_ID, +) { + return useMutation({ + mutationFn: ( + params: CompetitionMutationScope & { + request: SeriesReversalPreviewRequest; + }, + ) => + apiFetch( + `/communities/${communityId}/matches/${params.matchId}/competition/series/${params.seriesId}/reversal-preview`, + { + method: 'POST', + headers: competitionCommandHeaders(params.revision), + body: JSON.stringify(params.request), + }, + ), + retry: false, + }); +} + +export function useReverseCompetitionSeries( + communityId = DEFAULT_COMMUNITY_ID, +) { + return useMutation({ + mutationFn: ( + params: IdempotentCompetitionMutationScope & { + request: ReverseSeriesResultRequest; + }, + ) => + apiFetch( + `/communities/${communityId}/matches/${params.matchId}/competition/series/${params.seriesId}/reverse`, + { + method: 'POST', + headers: competitionCommandHeaders( + params.revision, + params.idempotencyKey, + ), + body: JSON.stringify(params.request), + }, + ), + retry: false, + }); +} + +export function useCommunityUserSearch( + query: string, + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useQuery({ + queryKey: ['community-user-search', communityId, query], + queryFn: () => { + const searchParams = new URLSearchParams(); + searchParams.set('query', query); + searchParams.set('limit', '10'); + return apiFetch( + `/communities/${communityId}/users/search?${searchParams.toString()}`, + ); + }, + enabled: Boolean(communityId && enabled && query.trim().length >= 2), + }); +} + export function useAuction( matchId: string | undefined, communityId = DEFAULT_COMMUNITY_ID, @@ -200,9 +415,21 @@ export function useAuctionHistory( export function useUndoAuction(communityId = DEFAULT_COMMUNITY_ID) { return useMutation({ mutationFn: ({ + auctionActionRequestId, + clientObservedAuctionLifecycleId, + clientObservedCurrentAuctionPlayerOrderIndex, + clientObservedCurrentBidRoundPlayerUserId, + clientObservedPhase, + clientObservedRevision, matchId, sequence, }: { + auctionActionRequestId?: string; + clientObservedAuctionLifecycleId?: string; + clientObservedCurrentAuctionPlayerOrderIndex?: number; + clientObservedCurrentBidRoundPlayerUserId?: string; + clientObservedPhase?: string; + clientObservedRevision?: number; matchId: string; sequence: number; }) => @@ -210,7 +437,15 @@ export function useUndoAuction(communityId = DEFAULT_COMMUNITY_ID) { `/communities/${communityId}/matches/${matchId}/auction/undo`, { method: 'POST', - body: JSON.stringify({ sequence }), + body: JSON.stringify({ + auctionActionRequestId, + clientObservedAuctionLifecycleId, + clientObservedCurrentAuctionPlayerOrderIndex, + clientObservedCurrentBidRoundPlayerUserId, + clientObservedPhase, + clientObservedRevision, + sequence, + }), }, ), }); @@ -218,9 +453,33 @@ export function useUndoAuction(communityId = DEFAULT_COMMUNITY_ID) { export function useResetAuction(communityId = DEFAULT_COMMUNITY_ID) { return useMutation({ - mutationFn: ({ matchId }: { matchId: string }) => + mutationFn: ({ + auctionActionRequestId, + clientObservedAuctionLifecycleId, + clientObservedCurrentAuctionPlayerOrderIndex, + clientObservedCurrentBidRoundPlayerUserId, + clientObservedPhase, + clientObservedRevision, + matchId, + }: { + auctionActionRequestId?: string; + clientObservedAuctionLifecycleId?: string; + clientObservedCurrentAuctionPlayerOrderIndex?: number; + clientObservedCurrentBidRoundPlayerUserId?: string; + clientObservedPhase?: string; + clientObservedRevision?: number; + matchId: string; + }) => apiFetch(`/communities/${communityId}/matches/${matchId}/auction`, { method: 'DELETE', + body: JSON.stringify({ + auctionActionRequestId, + clientObservedAuctionLifecycleId, + clientObservedCurrentAuctionPlayerOrderIndex, + clientObservedCurrentBidRoundPlayerUserId, + clientObservedPhase, + clientObservedRevision, + }), }), }); } @@ -228,7 +487,7 @@ export function useResetAuction(communityId = DEFAULT_COMMUNITY_ID) { export function useCreateMatch(communityId = DEFAULT_COMMUNITY_ID) { return useMutation({ mutationFn: (body: MatchMutationRequest) => - apiFetch(`/communities/${communityId}/matches`, { + apiFetch(`/communities/${communityId}/matches`, { method: 'POST', body: JSON.stringify(body), }), @@ -237,11 +496,20 @@ export function useCreateMatch(communityId = DEFAULT_COMMUNITY_ID) { export function useUpdateMatch(communityId = DEFAULT_COMMUNITY_ID) { return useMutation({ - mutationFn: ({ matchId, body }: { matchId: string; body: Partial }) => - apiFetch(`/communities/${communityId}/matches/${matchId}`, { - method: 'PATCH', - body: JSON.stringify(body), - }), + mutationFn: ({ + matchId, + body, + }: { + matchId: string; + body: Partial; + }) => + apiFetch( + `/communities/${communityId}/matches/${matchId}`, + { + method: 'PATCH', + body: JSON.stringify(body), + }, + ), }); } @@ -256,7 +524,8 @@ function createUserHistoryPath( if (filters.queueGroup) searchParams.set('queueGroup', filters.queueGroup); if (filters.rank) searchParams.set('rank', filters.rank); if (filters.seasonId) searchParams.set('seasonId', filters.seasonId); - if (filters.championId) searchParams.set('championId', String(filters.championId)); + if (filters.championId) + searchParams.set('championId', String(filters.championId)); for (const [key, value] of Object.entries(extra)) { if (value !== null && value !== undefined && value !== '') { searchParams.set(key, String(value)); @@ -301,8 +570,15 @@ export function useChampionStats( ], queryFn: () => apiFetch( - createUserHistoryPath(communityId, userId ?? '', 'champion-stats', filters), - { auth: 'none' }, + createUserHistoryPath( + communityId, + userId ?? '', + 'champion-stats', + filters, + ), + { + auth: 'none', + }, ), enabled: Boolean(communityId && userId && enabled), }); @@ -326,8 +602,15 @@ export function useRecentSummary( ], queryFn: () => apiFetch( - createUserHistoryPath(communityId, userId ?? '', 'recent-summary', filters), - { auth: 'none' }, + createUserHistoryPath( + communityId, + userId ?? '', + 'recent-summary', + filters, + ), + { + auth: 'none', + }, ), enabled: Boolean(communityId && userId && enabled), }); @@ -351,10 +634,16 @@ export function useRecentMatches( ], queryFn: ({ pageParam }) => apiFetch( - createUserHistoryPath(communityId, userId ?? '', 'recent-matches', filters, { - cursor: pageParam, - limit: 10, - }), + createUserHistoryPath( + communityId, + userId ?? '', + 'recent-matches', + filters, + { + cursor: pageParam, + limit: 10, + }, + ), { auth: 'none' }, ), initialPageParam: null as number | null, @@ -373,7 +662,8 @@ function createCommunityInternalStatsPath( if (filters.seasonId) searchParams.set('seasonId', filters.seasonId); if (filters.from) searchParams.set('from', filters.from); if (filters.to) searchParams.set('to', filters.to); - if (filters.championId) searchParams.set('championId', String(filters.championId)); + if (filters.championId) + searchParams.set('championId', String(filters.championId)); if (filters.limit) searchParams.set('limit', String(filters.limit)); for (const [key, value] of Object.entries(extra)) { if (value !== null && value !== undefined && value !== '') { @@ -430,7 +720,9 @@ export function useCommunityLeaderboard( queryFn: () => apiFetch( createCommunityInternalStatsPath(communityId, 'leaderboard', filters), - { auth: 'none' }, + { + auth: 'none', + }, ), enabled: Boolean(communityId && enabled), }); @@ -453,7 +745,9 @@ export function useTeamInsights( queryFn: () => apiFetch( createCommunityInternalStatsPath(communityId, 'team-insights', filters), - { auth: 'none' }, + { + auth: 'none', + }, ), enabled: Boolean(communityId && enabled), }); @@ -468,7 +762,9 @@ export function useInternalMatchDetail( queryFn: () => apiFetch( `/communities/${communityId}/internal-stats/match/${matchId}`, - { auth: 'none' }, + { + auth: 'none', + }, ), enabled: Boolean(communityId && matchId), retry: false, @@ -491,10 +787,16 @@ export function useUserInternalHistory( ], queryFn: ({ pageParam }) => apiFetch( - createUserHistoryPath(communityId, userId ?? '', 'internal-history', filters, { - cursor: pageParam, - limit: 10, - }), + createUserHistoryPath( + communityId, + userId ?? '', + 'internal-history', + filters, + { + cursor: pageParam, + limit: 10, + }, + ), { auth: 'none' }, ), initialPageParam: null as number | null, @@ -580,7 +882,9 @@ export function useTournamentCodes( }); } -export function useBulkUploadTournamentCodes(communityId = DEFAULT_COMMUNITY_ID) { +export function useBulkUploadTournamentCodes( + communityId = DEFAULT_COMMUNITY_ID, +) { return useMutation({ mutationFn: (codes: TournamentCodeUploadItem[]) => apiFetch( @@ -621,9 +925,12 @@ export function usePollTournamentResult(communityId = DEFAULT_COMMUNITY_ID) { priority: 'high' | 'low'; attempt: number; expandedToAllPuuids: boolean; - }>(`/communities/${communityId}/matches/${matchId}/poll-tournament-result`, { - method: 'POST', - }), + }>( + `/communities/${communityId}/matches/${matchId}/poll-tournament-result`, + { + method: 'POST', + }, + ), }); } @@ -678,7 +985,8 @@ export function useLegacyImportMembers( ], queryFn: () => { const searchParams = new URLSearchParams(); - if (options.windowStart) searchParams.set('windowStart', options.windowStart); + if (options.windowStart) + searchParams.set('windowStart', options.windowStart); if (options.windowEnd) searchParams.set('windowEnd', options.windowEnd); const queryString = searchParams.toString(); return apiFetch( @@ -784,34 +1092,12 @@ export function useRebuildLegacyMatches(communityId = DEFAULT_COMMUNITY_ID) { } export function useMe() { - const authUserId = useAuthUserId(); - const { accounts, inProgress, instance } = useMsal(); - const account = isMsalConfigured - ? (instance.getActiveAccount() ?? accounts[0] ?? null) - : null; - const accountKey = account?.homeAccountId ?? null; - const isMsalReady = - !isMsalConfigured || inProgress === InteractionStatus.None; + const authScope = useOptionalAuthQueryScope(); return useQuery({ - queryKey: ['me', authUserId, accountKey], - queryFn: async () => { - if (!account) { - return apiFetch('/me'); - } - - const response = await instance.acquireTokenSilent({ - account, - scopes: [MSAL_API_SCOPE], - redirectUri: MSAL_SILENT_REDIRECT_URI, - }); - return apiFetch('/me', { - headers: { - Authorization: `Bearer ${response.accessToken}`, - }, - }); - }, - enabled: Boolean(authUserId || isMsalReady), + queryKey: ['me', ...authScope.cacheKey], + queryFn: () => authScope.fetch('/me'), + enabled: authScope.ready, retry: false, }); } diff --git a/apps/web/src/api/mappers.ts b/apps/web/src/api/mappers.ts index 98710038..0e768888 100644 --- a/apps/web/src/api/mappers.ts +++ b/apps/web/src/api/mappers.ts @@ -1,18 +1,19 @@ +import type { + MatchDetailResponse, + MatchLifecycleStatus, + MatchParticipantView, +} from "@lolympus/contracts"; import type { ApiAuction, ApiAuctionPlayerSnapshot, ApiAuctionTeam, - ApiMatch, - ApiMatchParticipant, ApiPositionPreference, ApiRiotLaneStats, ApiRiotRecentStatsSummary, ApiTierHistoryEntry, ApiTierInfo, - MatchStatus, Position, RiotLane, - TournamentCodeSlotView, } from "./types"; import { POSITION_ORDER, teamIndexLabel } from "../lib/league"; @@ -36,6 +37,9 @@ export interface TeamParticipantView extends ParticipantView { export interface TeamView { teamIndex: number; name: string; + captainUserId?: string; + captainName?: string; + captainTag?: string; participants: TeamParticipantView[]; } @@ -44,42 +48,13 @@ export interface MatchDetailView { title: string; date: string; time: string; - status: MatchStatus; + status: MatchLifecycleStatus; description: string; map: string; maxParticipants: number; - gameCount: number; - gameMode: ApiMatch["gameMode"]; - tournamentCodes: TournamentCodeSlotView[]; joined: boolean; participants: ParticipantView[]; teams: TeamView[]; - result?: { - winner?: string; - winnerTeamIndex?: number; - riotMatchIds: string[]; - games: Array<{ - gameNumber: number; - riotMatchId: string; - blueTeamIndex: number; - redTeamIndex: number; - winnerTeamIndex: number; - winnerSide: "blue" | "red"; - gameCreation: number; - gameDuration: number; - participants: Array<{ - userId: string; - teamIndex: number; - side: "blue" | "red"; - championId: number; - kills: number; - deaths: number; - assists: number; - win: boolean; - }>; - }>; - seriesResults: NonNullable["seriesResults"]; - }; prizes: string[]; notices: string[]; schedule: { time: string; label: string }[]; @@ -116,6 +91,8 @@ export interface AuctionTeamView { export interface AuctionStateView { matchId: string; phase: ApiAuction["phase"]; + matchSideEffectRevision?: number; + matchSideEffectStatus?: ApiAuction["matchSideEffectStatus"]; teams: AuctionTeamView[]; currentPlayer: AuctionPlayerView | null; currentPlayerIndex: number; @@ -130,6 +107,7 @@ export interface AuctionStateView { }[]; currentBid: number; currentBidder: { teamIndex: number } | null; + remainingMs: number; timer: number; maxTimer: number; bidExtensionSeconds: number; @@ -204,7 +182,7 @@ function resolveMainAndSubPosition( } function mapMatchParticipantToView( - participant: ApiMatchParticipant, + participant: MatchParticipantView, ): ParticipantView { const { mainPosition, subPosition } = resolveMainAndSubPosition( participant.preferredPositions, @@ -227,10 +205,11 @@ function mapAuctionPlayerToView( player: ApiAuctionPlayerSnapshot, ): AuctionPlayerView { const { mainPosition, subPosition } = resolveMainAndSubPosition( - player.preferredPositions, + player.preferredPositions ?? [], ); const summary = player.recentStatsSummary; const primary = pickPrimary(summary, mainPosition); + const masteries = player.masteries ?? []; return { id: player.userId, @@ -241,9 +220,9 @@ function mapAuctionPlayerToView( tierHistory: player.tierHistory ?? [], mainPosition, subPosition, - profileIconId: player.profileIconId, + profileIconId: player.profileIconId ?? 0, passCount: player.passCount ?? 0, - masteries: player.masteries.slice(0, 5).map((mastery) => ({ + masteries: masteries.slice(0, 5).map((mastery) => ({ championId: mastery.championId, level: mastery.championLevel, points: mastery.championPoints, @@ -270,7 +249,7 @@ function createFallbackParticipant(userId: string): ParticipantView { } function mapAuctionTeamToView( - team: ApiAuctionTeam, + team: NormalizedApiAuctionTeam, playerLookup: Map, participantLookup: Map, ): AuctionTeamView { @@ -406,32 +385,43 @@ export function buildDefaultPreferredPositions() { })); } -export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView { +export function mapApiMatchToMatchDetail( + match: MatchDetailResponse, +): MatchDetailView { const formattedDate = formatKoreanDate(match.scheduledAt); const participants = match.participants.map(mapMatchParticipantToView); const participantLookup = new Map( participants.map((participant) => [participant.userId, participant]), ); - const teams = match.teams.map((team) => ({ - teamIndex: team.teamIndex, - name: teamIndexLabel(team.teamIndex, team.name), - participants: team.members.map((member) => { - const participant = - participantLookup.get(member.userId) ?? - createFallbackParticipant(member.userId); + const teams = match.teams.map((team) => { + const captain = team.captainUserId + ? participantLookup.get(team.captainUserId) + : undefined; - return { - ...participant, - assignedPosition: member.assignedPosition, - cost: member.cost, - }; - }), - })); + return { + teamIndex: team.teamIndex, + name: teamIndexLabel(team.teamIndex, team.name), + captainUserId: team.captainUserId, + captainName: + captain?.summonerName ?? + (team.captainUserId + ? `User ${team.captainUserId.slice(-4)}` + : undefined), + captainTag: captain?.tag, + participants: team.members.map((member) => { + const participant = + participantLookup.get(member.userId) ?? + createFallbackParticipant(member.userId); - const winnerTeam = match.result?.winnerTeamIndex - ? teams.find((team) => team.teamIndex === match.result?.winnerTeamIndex) - : undefined; + return { + ...participant, + assignedPosition: member.assignedPosition, + cost: member.cost, + }; + }), + }; + }); return { id: match._id, @@ -442,23 +432,9 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView { description: match.description, map: mapIdToLabel(match.mapId), maxParticipants: match.maxParticipants, - gameCount: match.gameCount ?? 3, - gameMode: match.gameMode ?? "pair", - tournamentCodes: match.tournamentCodes ?? [], joined: Boolean(match.joined), participants, teams, - result: match.result - ? { - winner: match.result.winnerTeamIndex ? winnerTeam?.name : undefined, - winnerTeamIndex: match.result.winnerTeamIndex, - riotMatchIds: match.result.riotMatchIds, - games: [...(match.result.games ?? [])].sort( - (left, right) => left.gameNumber - right.gameNumber, - ), - seriesResults: match.result.seriesResults ?? [], - } - : undefined, prizes: match.prizes, notices: match.notices, schedule: match.schedule, @@ -467,7 +443,7 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView { export function mapApiAuctionToAuctionState( auction: ApiAuction, - match: ApiMatch, + match: MatchDetailResponse, now = new Date(), ): AuctionStateView { const participantLookup = new Map( @@ -475,36 +451,57 @@ export function mapApiAuctionToAuctionState( .map(mapMatchParticipantToView) .map((participant) => [participant.userId, participant]), ); - const auctionOrder = auction.order.map(mapAuctionPlayerToView); - const passedQueue = (auction.passedQueue ?? []).map(mapAuctionPlayerToView); + const rawAuctionOrder = auction.auctionPlayerOrder ?? auction.order ?? []; + const rawPassedQueue = + auction.passedAuctionPlayerQueue ?? auction.passedQueue ?? []; + const rawAuctionTeams = auction.auctionTeams ?? auction.teams ?? []; + const currentAuctionPlayerOrderIndex = + auction.currentAuctionPlayerOrderIndex ?? auction.currentIndex ?? 0; + const currentBid = + auction.currentHighestBidPointAmount ?? auction.currentBid ?? 0; + const rawCurrentBidderTeamIndex = + auction.currentHighestBidderTeamIndex ?? auction.currentBidderTeamIndex; + const currentBidderTeamIndex = + rawCurrentBidderTeamIndex !== undefined && rawCurrentBidderTeamIndex > 0 + ? rawCurrentBidderTeamIndex + : undefined; + const maximumBidRoundDurationSeconds = + auction.maximumBidRoundDurationSeconds ?? auction.maxTimerSeconds ?? 30; + const bidRoundExtensionSeconds = + auction.bidRoundExtensionSeconds ?? auction.bidExtensionSeconds ?? 5; + const currentBidRoundDeadlineTimestampMS = + auction.currentBidRoundDeadlineTimestampMS ?? + (auction.currentDeadline ? Date.parse(auction.currentDeadline) : undefined); + const auctionOrder = rawAuctionOrder.map(mapAuctionPlayerToView); + const passedQueue = rawPassedQueue.map(mapAuctionPlayerToView); const auctionPlayerLookup = new Map( auctionOrder.map((player) => [player.userId, player]), ); - const teams = [...auction.teams].sort( - (left, right) => left.teamIndex - right.teamIndex, - ); + const teams = rawAuctionTeams + .map(normalizeApiAuctionTeam) + .sort((left, right) => left.teamIndex - right.teamIndex); const totalPlayers = auctionOrder.length; const currentPlayer = auction.phase === "complete" ? null : (auctionPlayerLookup.get( - auction.order[auction.currentIndex]?.userId ?? "", + rawAuctionOrder[currentAuctionPlayerOrderIndex]?.userId ?? "", ) ?? null); const currentPlayerIndex = - auction.phase === "complete" ? totalPlayers : auction.currentIndex; - const timer = auction.currentDeadline - ? Math.max( - 0, - Math.ceil( - (new Date(auction.currentDeadline).getTime() - now.getTime()) / 1000, - ), - ) + auction.phase === "complete" + ? totalPlayers + : currentAuctionPlayerOrderIndex; + const remainingMs = currentBidRoundDeadlineTimestampMS + ? Math.max(0, currentBidRoundDeadlineTimestampMS - now.getTime()) : 0; + const timer = Math.floor(remainingMs / 1000); return { matchId: auction.matchId, phase: auction.phase, + matchSideEffectRevision: auction.matchSideEffectRevision, + matchSideEffectStatus: auction.matchSideEffectStatus, teams: teams.map((team) => mapAuctionTeamToView(team, auctionPlayerLookup, participantLookup), ), @@ -513,21 +510,51 @@ export function mapApiAuctionToAuctionState( totalPlayers, auctionOrder, passedQueue, - auctionRound: auction.auctionRound ?? 1, - bids: auction.bids.map((bid) => ({ - teamIndex: bid.teamIndex, - amount: bid.amount, - timestamp: bid.timestamp, - })), - currentBid: auction.currentBid, - currentBidder: auction.currentBidderTeamIndex - ? { - teamIndex: auction.currentBidderTeamIndex, - } - : null, + auctionRound: auction.currentAuctionRound ?? auction.auctionRound ?? 1, + bids: normalizeApiAuctionBids(auction), + currentBid, + currentBidder: + currentBidderTeamIndex !== undefined + ? { + teamIndex: currentBidderTeamIndex, + } + : null, + remainingMs, timer, - maxTimer: auction.maxTimerSeconds, - bidExtensionSeconds: auction.bidExtensionSeconds ?? 5, - deadline: auction.currentDeadline, + maxTimer: maximumBidRoundDurationSeconds, + bidExtensionSeconds: bidRoundExtensionSeconds, + deadline: currentBidRoundDeadlineTimestampMS + ? new Date(currentBidRoundDeadlineTimestampMS).toISOString() + : undefined, }; } + +type NormalizedApiAuctionTeam = ApiAuctionTeam & { points: number }; + +function normalizeApiAuctionTeam( + team: ApiAuctionTeam, +): NormalizedApiAuctionTeam { + return { + ...team, + points: team.points ?? team.remainingBidPointAmount ?? 0, + members: (team.members ?? []).map((member) => ({ + ...member, + cost: member.cost ?? member.memberAcquisitionBidPointAmount ?? 0, + })), + }; +} + +function normalizeApiAuctionBids(auction: ApiAuction) { + if (auction.auctionBidHistory) { + return auction.auctionBidHistory.map((bid) => ({ + amount: bid.bidPointAmount, + teamIndex: bid.bidderTeamIndex, + timestamp: new Date(bid.bidPlacedAtTimestampMS).toISOString(), + })); + } + return (auction.bids ?? []).map((bid) => ({ + teamIndex: bid.teamIndex, + amount: bid.amount, + timestamp: bid.timestamp, + })); +} diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index d65f0211..96a337b1 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -1,12 +1,14 @@ -export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP'; +import type { + MatchGameMode, + MatchPosition, + MatchPositionPreferenceView, + MatchScheduleItemView, + MatchTierView, +} from '@lolympus/contracts'; + +export type Position = MatchPosition; export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY'; export type TeamSide = 'blue' | 'red'; -export type MatchGameMode = 'pair' | 'bracket' | 'round-robin'; -export type MatchStatus = - | 'recruiting' - | 'team-built' - | 'in-progress' - | 'finished'; export type AuctionPhase = | 'waiting' | 'presenting' @@ -22,20 +24,8 @@ export type AuctionTopTierThreshold = | 'MANUAL'; export type CommunityRole = 'owner' | 'admin' | 'member'; -export interface ApiPositionPreference { - position: Position; - priority: number; -} - -export interface ApiTierInfo { - queueType: string; - tier: string; - rank: string; - leaguePoints: number; - wins: number; - losses: number; - fetchedAt: string; -} +export type ApiPositionPreference = MatchPositionPreferenceView; +export type ApiTierInfo = MatchTierView; export interface ApiChampionMasteryEntry { puuid?: string; @@ -103,6 +93,24 @@ export interface ApiUser { updatedAt: string; } +export interface ApiCommunityUserSearchRiotAccount { + puuid: string; + gameName: string; + tagLine: string; + profileIconId: number; + isPrimary: boolean; + tiers: ApiTierInfo[]; +} + +export interface ApiCommunityUserSearchCandidate { + userId: string; + kakaoTalkNickname?: string; + isActivated: boolean; + preferredPositions: ApiPositionPreference[]; + matchedRiotPuuid?: string; + riotAccounts: ApiCommunityUserSearchRiotAccount[]; +} + export interface ApiCommunity { _id: string; name: string; @@ -118,92 +126,8 @@ export type TournamentCodeState = | 'reserved' | 'used' | 'expired' - | 'released'; - -export type TournamentCodeSlotState = TournamentCodeState | 'pending'; - -export interface TournamentCodeSlotView { - gameNumber: number; - teamAIndex: number; - teamBIndex: number; - code: string | null; - expiresAt: string | null; - state: TournamentCodeSlotState; - riotMatchId: string | null; -} - -export interface ApiMatchParticipant { - userId: string; - puuid?: string; - gameName?: string; - tagLine?: string; - profileIconId?: number; - tier?: ApiTierInfo; - preferredPositions: ApiPositionPreference[]; - joinedAt: string; - excluded?: boolean; -} - -export interface ApiMatchTeamMember { - userId: string; - assignedPosition: Position; - cost?: number; -} - -export interface ApiMatchTeam { - teamIndex: number; - name: string; - captainUserId?: string; - members: ApiMatchTeamMember[]; -} - -export interface ApiMatchGameResultParticipant { - userId: string; - teamIndex: number; - side: TeamSide; - championId: number; - kills: number; - deaths: number; - assists: number; - win: boolean; -} - -export interface ApiMatchGameResult { - gameNumber: number; - riotMatchId: string; - blueTeamIndex: number; - redTeamIndex: number; - winnerTeamIndex: number; - winnerSide: TeamSide; - gameCreation: number; - gameDuration: number; - participants: ApiMatchGameResultParticipant[]; -} - -export interface ApiMatchResult { - winnerTeamIndex?: number; - mvpUserId?: string; - riotMatchIds: string[]; - games: ApiMatchGameResult[]; - seriesResults?: Array<{ - teamAIndex: number; - teamBIndex: number; - teamAWins: number; - teamBWins: number; - winnerTeamIndex?: number; - }>; -} - -export interface ApiMatchScheduleItem { - time: string; - label: string; -} - -export interface ApiMatchGameAssignment { - gameNumber: number; - teamAIndex: number; - teamBIndex: number; -} + | 'released' + | 'voided'; export interface ManualTournamentResultCollectResponse { scanned: number; @@ -213,32 +137,6 @@ export interface ManualTournamentResultCollectResponse { gameNumbers: number[]; } -export interface ApiMatch { - _id: string; - communityId: string; - shortCode?: string; - title: string; - description: string; - mapId: number; - status: MatchStatus; - scheduledAt: string; - maxParticipants: number; - gameCount: number; - gameMode: MatchGameMode; - gameSchedule?: ApiMatchGameAssignment[]; - tournamentCodes?: TournamentCodeSlotView[]; - hostUserId?: string; - participants: ApiMatchParticipant[]; - teams: ApiMatchTeam[]; - result?: ApiMatchResult; - prizes: string[]; - notices: string[]; - schedule: ApiMatchScheduleItem[]; - joined?: boolean; - createdAt: string; - updatedAt: string; -} - export interface ApiAuctionPlayerSnapshot { userId: string; puuid: string; @@ -257,12 +155,14 @@ export interface ApiAuctionTeamMember { userId: string; assignedPosition: Position; cost: number; + memberAcquisitionBidPointAmount?: number; } export interface ApiAuctionTeam { teamIndex: number; captainUserId: string; - points: number; + points?: number; + remainingBidPointAmount?: number; members: ApiAuctionTeamMember[]; } @@ -285,20 +185,48 @@ export interface ApiAuction { _id: string; matchId: string; phase: AuctionPhase; - teams: ApiAuctionTeam[]; - order: ApiAuctionPlayerSnapshot[]; - passedQueue: ApiAuctionPlayerSnapshot[]; - auctionRound: number; - currentIndex: number; - bids: ApiAuctionBid[]; - currentBid: number; + teams?: ApiAuctionTeam[]; + auctionTeams: ApiAuctionTeam[]; + order?: ApiAuctionPlayerSnapshot[]; + auctionPlayerOrder: ApiAuctionPlayerSnapshot[]; + passedQueue?: ApiAuctionPlayerSnapshot[]; + passedAuctionPlayerQueue: ApiAuctionPlayerSnapshot[]; + auctionRound?: number; + currentAuctionRound: number; + currentIndex?: number; + currentAuctionPlayerOrderIndex: number; + bids?: ApiAuctionBid[]; + auctionBidHistory?: Array<{ + bidderTeamIndex: number; + bidPointAmount: number; + bidderUserId: string; + bidPlacedAtTimestampMS: number; + }>; + currentBid?: number; + currentHighestBidPointAmount: number; currentBidderTeamIndex?: number; - maxTimerSeconds: number; - bidExtensionSeconds: number; + currentHighestBidderTeamIndex?: number; + maxTimerSeconds?: number; + maximumBidRoundDurationSeconds: number; + bidExtensionSeconds?: number; + bidRoundExtensionSeconds: number; currentDeadline?: string; - initialPoints: number; - topTierThreshold: AuctionTopTierThreshold; - manualTopTierUserIds: string[]; + currentBidRoundDeadlineTimestampMS?: number; + currentBidRoundPlayerUserId?: string; + currentServerTimestampMS?: number; + initialPoints?: number; + initialTeamBidPointAmount: number; + topTierThreshold?: AuctionTopTierThreshold; + topTierAuctionPriorityThreshold: AuctionTopTierThreshold; + manualTopTierUserIds?: string[]; + manualTopTierAuctionPriorityUserIds: string[]; + revision?: number; + auctionLifecycleId?: string; + matchSideEffectRevision?: number; + matchSideEffectStatus?: 'none' | 'pending' | 'processing' | 'completed' | 'failed'; + canPlaceBidInCurrentBidRound?: boolean; + isAuctionStateTransitionInProgress?: boolean; + shouldForceAuctionStateResync?: boolean; chatMessages?: ApiAuctionChatMessage[]; startedAt?: string; completedAt?: string; @@ -315,7 +243,9 @@ export interface ApiAuctionHistoryEntry { | 'sold' | 'passed' | 'next' - | 'complete'; + | 'complete' + | 'undo' + | 'reset'; actionLabel: string; takenAt: string; } @@ -338,13 +268,6 @@ export interface MeResponse { memberships: ApiMembership[]; } -export interface MatchesResponse { - matches: ApiMatch[]; - total: number; - page: number; - limit: number; -} - export interface MatchMutationRequest { title: string; description?: string; @@ -353,9 +276,11 @@ export interface MatchMutationRequest { maxParticipants?: number; gameCount?: number; gameMode?: MatchGameMode; + roundRobinMaxRounds?: number; + doubleEliminationResetFinalEnabled?: boolean; prizes?: string[]; notices?: string[]; - schedule?: ApiMatchScheduleItem[]; + schedule?: MatchScheduleItemView[]; } export interface DdragonChampionEntry { @@ -366,6 +291,8 @@ export interface DdragonChampionEntry { export interface DdragonSummonerSpellEntry { key: string; name: string; + description: string; + tooltip: string; } export interface DdragonRuneEntry { @@ -373,12 +300,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; @@ -386,6 +327,7 @@ export interface DdragonManifest { champions: Record; summonerSpells: Record; runesReforged: DdragonRuneStyleEntry[]; + items: Record; fetchedAt: string; } @@ -540,6 +482,39 @@ export interface ApiRecentSummaryResponse { lastFetchedAt: string | null; } +export interface ApiRuneStyleSelection { + styleId: number; + perkIds: number[]; +} + +export interface ApiRunePerks { + primaryStyle?: number; + subStyle?: number; + keystone?: number; + selectedPerkIds?: number[]; + styles?: ApiRuneStyleSelection[]; + statPerks?: { + offense?: number; + flex?: number; + defense?: number; + }; +} + +export interface ApiItemBuildEvent { + timestamp: number; + itemId: number; + type: 'purchased' | 'sold' | 'destroyed' | 'undo'; + beforeId?: number; + afterId?: number; +} + +export interface ApiSkillBuildEvent { + timestamp: number; + skillSlot: 1 | 2 | 3 | 4; + level: number; + levelUpType?: string; +} + export interface ApiRecentMatchTeamParticipant { puuid: string; gameName: string; @@ -553,7 +528,7 @@ export interface ApiRecentMatchTeamParticipant { items: number[]; trinket: number; summonerSpells: [number, number]; - perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + perks: ApiRunePerks; totalCs: number; csPerMin: number; goldEarned: number; @@ -574,6 +549,8 @@ export interface ApiRecentMatchTeam { export interface ApiRecentMatchView { matchId: string; + internalMatchId?: string; + gameNumber?: number; queueId: number; queueLabel: string; gameCreation: number; @@ -601,7 +578,7 @@ export interface ApiRecentMatchView { items: number[]; trinket: number; summonerSpells: [number, number]; - perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + perks: ApiRunePerks; teams: ApiRecentMatchTeam[]; } @@ -710,18 +687,82 @@ export interface ApiInternalMatchDetailResponse { riotMatchId: string; gameCreation: number; gameDuration: number; + gameVersion?: string; + timeline: Array<{ + timestamp: number; + blue: { gold: number; xp: number }; + red: { gold: number; xp: number }; + goldDiff: number; + xpDiff: number; + }>; + objectiveEvents: Array<{ + timestamp: number; + side: TeamSide; + type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub'; + monsterSubType?: string; + }>; + timelineEvents?: Array<{ + timestamp: number; + side?: TeamSide; + type: + | 'dragon' + | 'elderDragon' + | 'baron' + | 'riftHerald' + | 'voidGrub' + | 'championKill' + | 'tower' + | 'inhibitor'; + monsterSubType?: string; + killerParticipantId?: number; + victimParticipantId?: number; + assistingParticipantIds?: number[]; + towerType?: string; + }>; teams: Array<{ teamIndex: number; side: TeamSide; win: boolean; - objectives: { baron: number; dragon: number; tower: number }; + objectives: { + tower: number; + dragon: number; + inhibitor: number; + baron: number; + riftHerald: number; + voidGrub: number; + elderDragon: number; + }; + bans: Array<{ championId: number; pickTurn: number }>; participants: Array<{ + participantId?: number; + checkpoints?: { + at10?: { + timestamp: number; + gold: number; + cs: number; + xp: number; + kills: number; + deaths: number; + assists: number; + }; + at15?: { + timestamp: number; + gold: number; + cs: number; + xp: number; + kills: number; + deaths: number; + assists: number; + }; + }; userId: string | null; summonerName: string; + tagLine: string; teamIndex: number; side: TeamSide; teamPosition: string; championId: number; + championLevel: number; kills: number; deaths: number; assists: number; @@ -730,13 +771,21 @@ export interface ApiInternalMatchDetailResponse { gold: number; gpm: number; damageDealtToChampions: number; + damageTaken: number; damageShare: number; killParticipation: number; visionScore: number; + wardsPlaced: number; + wardsKilled: number; + controlWardsBought: number; + firstBloodKill: boolean; + firstBloodAssist: boolean; items: number[]; trinket: number; summonerSpells: [number, number]; - perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + perks: ApiRunePerks; + itemBuild: ApiItemBuildEvent[]; + skillBuild: ApiSkillBuildEvent[]; win: boolean; }>; }>; diff --git a/apps/web/src/api/useAuctionSocket.ts b/apps/web/src/api/useAuctionSocket.ts index 6bc32f9f..d411f43a 100644 --- a/apps/web/src/api/useAuctionSocket.ts +++ b/apps/web/src/api/useAuctionSocket.ts @@ -3,6 +3,14 @@ import { io, type Socket } from 'socket.io-client'; import { API_BASE_URL, useAuthUserId } from '../config'; import { acquireAccessToken } from '../lib/auth/token-provider'; import type { ApiAuction, ApiAuctionChatMessage, Position } from './types'; +import { + isAuctionResyncRecommended, + resolveAuctionErrorMessage, + resolveAuctionRejectionMessage, +} from './auctionRejectionMessages'; +// [AUCTION-DEBUG] 경매 "중복 멤버" 조사용 임시 계측. 조사 종료 후 제거 대상 +// (호출부는 전부 addNewRelicPageAction / describeAuctionForTelemetry 로 grep 가능). +import { addNewRelicPageAction } from '../lib/observability/new-relic'; type ConnectionStatus = | 'idle' @@ -12,9 +20,11 @@ type ConnectionStatus = | 'error'; interface BidPayload { - teamIndex: number; - amount: number; - bidderUserId?: string; + bidderTeamIndex: number; + bidPointAmount: number; + bidRequestId?: string; + clientObservedAuctionLifecycleId?: string; + clientObservedCurrentBidRoundPlayerUserId?: string; } interface ChatMessagePayload { @@ -22,6 +32,19 @@ interface ChatMessagePayload { message: string; } +interface AuctionActionPayload { + auctionActionRequestId?: string; + clientObservedAuctionLifecycleId?: string; + clientObservedCurrentAuctionPlayerOrderIndex?: number; + clientObservedCurrentBidRoundPlayerUserId?: string; + clientObservedPhase?: string; + clientObservedRevision?: number; +} + +interface SoldPayload extends AuctionActionPayload { + assignedPosition?: Position; +} + interface ChatHistoryPayload { messages?: ApiAuctionChatMessage[]; } @@ -30,7 +53,76 @@ interface ResetPayload { matchId?: string; } +type MatchSideEffectStatus = NonNullable; + +interface MatchSideEffectPayload { + auctionLifecycleId?: string; + currentServerTimestampMS?: number; + matchSideEffectRevision?: number; + matchSideEffectStatus?: MatchSideEffectStatus; +} + +interface BidDeltaPayload { + auctionBidHistoryEntry?: { + bidderTeamIndex?: number; + bidPointAmount?: number; + bidderUserId?: string; + bidPlacedAtTimestampMS?: number; + }; + auctionLifecycleId?: string; + bidRequestId?: string; + currentBidRoundDeadlineTimestampMS?: number; + currentHighestBidderTeamIndex?: number; + currentHighestBidPointAmount?: number; + currentServerTimestampMS?: number; + revision?: number; +} + +interface BidServerTimingPayload { + fallbackFullStatePath?: boolean; + gatewayTotalDurationMS?: number; + redisBidCommandDurationMS?: number; + redisBidContextReadDurationMS?: number; + serviceTotalDurationMS?: number; +} + +interface BidDiagnosticsPayload { + currentBidRoundDeadlineTimestampMS?: number; + currentServerTimestampMS?: number; +} + +interface BidAckPayload { + auctionRejectionReason?: string; + bidDelta?: BidDeltaPayload | null; + bidDiagnostics?: BidDiagnosticsPayload; + bidServerTiming?: BidServerTimingPayload; + code?: string; + message?: string; + rejected?: boolean; + resyncRecommended?: boolean; + state?: ApiAuction; +} + +interface TimeSyncAckPayload { + clientSentAtTimestampMS?: number; + currentServerTimestampMS?: number; + ok?: boolean; + rejected?: boolean; + sequence?: number; + serverProcessingDurationMS?: number; +} + +export interface BidLatencyDiagnostics { + bidDiagnostics?: BidDiagnosticsPayload; + bidServerTiming?: BidServerTimingPayload; + clientObservedRemainingBidRoundTimeMS?: number; + serverObservedRemainingBidRoundTimeMS?: number; + serverRoundTripDurationMS?: number; +} + const MAX_CHAT_MESSAGES = 200; +const TIME_SYNC_INTERVAL_MS = 5000; +const TIME_SYNC_TIMEOUT_MS = 3000; function mergeChatMessages( current: ApiAuctionChatMessage[], @@ -49,12 +141,209 @@ function mergeChatMessages( export function useAuctionSocket(matchId: string | undefined) { const authUserId = useAuthUserId(); const socketRef = useRef(null); + const pendingBidTimeoutsRef = useRef< + Record> + >({}); + const pendingActionTimeoutsRef = useRef< + Record> + >({}); + const timeSyncIntervalRef = useRef | null>( + null, + ); + const timeSyncTimeoutsRef = useRef< + Record> + >({}); + const timeSyncSequenceRef = useRef(0); + const hasSyncedServerTimeRef = useRef(false); + const latestAuctionRef = useRef(null); + const latestConfirmedBidPointAmountRef = useRef(0); const [auction, setAuction] = useState(null); const [chatMessages, setChatMessages] = useState([]); + const [pendingBidRequests, setPendingBidRequests] = useState< + Record + >({}); + const [pendingActionRequests, setPendingActionRequests] = useState< + Record + >({}); const [resetAt, setResetAt] = useState(null); const [connectionStatus, setConnectionStatus] = useState('idle'); const [error, setError] = useState(null); + const [serverTimeOffsetMs, setServerTimeOffsetMs] = useState(0); + const [serverRoundTripMs, setServerRoundTripMs] = useState( + null, + ); + const [bidLatencyDiagnostics, setBidLatencyDiagnostics] = + useState(null); + + function syncLatestConfirmedBidPointAmountFromAuction( + nextAuction: ApiAuction, + ) { + latestConfirmedBidPointAmountRef.current = + resolveCurrentBidPointAmount(nextAuction); + } + + function commitAuctionState( + nextAuction: ApiAuction, + source = 'socket-state', + ): boolean { + const currentAuction = latestAuctionRef.current; + const applied = shouldApplyIncomingAuctionState(currentAuction, nextAuction); + const currentRevision = + typeof currentAuction?.revision === 'number' + ? currentAuction.revision + : -1; + const incomingRevision = + typeof nextAuction?.revision === 'number' ? nextAuction.revision : -1; + // 단조성을 깨고 적용되는 경우(=revision이 같거나 뒤로 가는데도 반영됨). + // force-resync/lifecycle 교체로만 발생하며, "2~3 버전 롤백"의 직접 증거가 된다. + const isBackwardApply = + applied && + currentRevision >= 0 && + incomingRevision >= 0 && + incomingRevision <= currentRevision; + addNewRelicPageAction('AuctionClientStateApply', { + matchId: matchId ?? 'none', + source, + applied, + isBackwardApply, + revisionDelta: incomingRevision - currentRevision, + ...describeAuctionForTelemetry('current', currentAuction), + ...describeAuctionForTelemetry('incoming', nextAuction), + }); + + if (!applied) { + return false; + } + + latestAuctionRef.current = nextAuction; + syncLatestConfirmedBidPointAmountFromAuction(nextAuction); + setAuction(nextAuction); + return true; + } + + function commitBidDelta(payload: BidDeltaPayload): boolean { + const currentAuction = latestAuctionRef.current; + const nextAuction = applyBidDelta(currentAuction, payload); + if (!nextAuction || nextAuction === currentAuction) { + return false; + } + + latestAuctionRef.current = nextAuction; + syncLatestConfirmedBidPointAmountFromAuction(nextAuction); + setAuction(nextAuction); + return true; + } + + function applyFallbackServerTimestamp(currentServerTimestampMS?: number) { + if (hasSyncedServerTimeRef.current) return; + if (typeof currentServerTimestampMS !== 'number') return; + setServerTimeOffsetMs(currentServerTimestampMS - Date.now()); + } + + function clearTimeSyncTimers() { + if (timeSyncIntervalRef.current) { + clearInterval(timeSyncIntervalRef.current); + timeSyncIntervalRef.current = null; + } + Object.values(timeSyncTimeoutsRef.current).forEach((timeoutId) => + clearTimeout(timeoutId), + ); + timeSyncTimeoutsRef.current = {}; + } + + function requestServerTimeSync(socket: Socket) { + if (!socket.connected) return; + + const sequence = timeSyncSequenceRef.current + 1; + timeSyncSequenceRef.current = sequence; + const clientSentAtTimestampMS = Date.now(); + + timeSyncTimeoutsRef.current[sequence] = setTimeout(() => { + delete timeSyncTimeoutsRef.current[sequence]; + }, TIME_SYNC_TIMEOUT_MS); + + socket.emit( + 'time-sync', + { clientSentAtTimestampMS, sequence }, + (ack?: TimeSyncAckPayload) => { + const clientReceivedAtTimestampMS = Date.now(); + const timeoutId = timeSyncTimeoutsRef.current[sequence]; + if (!timeoutId) return; + clearTimeout(timeoutId); + delete timeSyncTimeoutsRef.current[sequence]; + + if ( + !ack?.ok || + ack.sequence !== sequence || + typeof ack.currentServerTimestampMS !== 'number' + ) { + return; + } + + const totalRoundTripDurationMS = Math.max( + 0, + clientReceivedAtTimestampMS - clientSentAtTimestampMS, + ); + const serverProcessingDurationMS = Number( + ack.serverProcessingDurationMS, + ); + const estimatedNetworkOneWayDurationMS = + Math.max( + 0, + totalRoundTripDurationMS - + (Number.isFinite(serverProcessingDurationMS) + ? serverProcessingDurationMS + : 0), + ) / 2; + const estimatedServerTimestampAtClientReceiveMS = + ack.currentServerTimestampMS + estimatedNetworkOneWayDurationMS; + + hasSyncedServerTimeRef.current = true; + setServerRoundTripMs(Math.round(totalRoundTripDurationMS)); + setServerTimeOffsetMs( + Math.round( + estimatedServerTimestampAtClientReceiveMS - + clientReceivedAtTimestampMS, + ), + ); + }, + ); + } + + function captureBidLatencyDiagnostics(ack?: BidAckPayload) { + if (!ack?.bidDiagnostics && !ack?.bidServerTiming) return; + + const currentAuction = latestAuctionRef.current; + const currentDeadlineTimestampMS = + currentAuction?.currentBidRoundDeadlineTimestampMS ?? + (currentAuction?.currentDeadline + ? Date.parse(currentAuction.currentDeadline) + : undefined); + const clientObservedRemainingBidRoundTimeMS = + typeof currentDeadlineTimestampMS === 'number' + ? Math.max(0, currentDeadlineTimestampMS - (Date.now() + serverTimeOffsetMs)) + : undefined; + const serverDeadlineTimestampMS = + ack.bidDiagnostics?.currentBidRoundDeadlineTimestampMS ?? + ack.bidDelta?.currentBidRoundDeadlineTimestampMS; + const serverTimestampMS = + ack.bidDiagnostics?.currentServerTimestampMS ?? + ack.bidDelta?.currentServerTimestampMS; + const serverObservedRemainingBidRoundTimeMS = + typeof serverDeadlineTimestampMS === 'number' && + typeof serverTimestampMS === 'number' + ? serverDeadlineTimestampMS - serverTimestampMS + : undefined; + + setBidLatencyDiagnostics({ + bidDiagnostics: ack?.bidDiagnostics, + bidServerTiming: ack?.bidServerTiming, + clientObservedRemainingBidRoundTimeMS, + serverObservedRemainingBidRoundTimeMS, + serverRoundTripDurationMS: serverRoundTripMs ?? undefined, + }); + } useEffect(() => { if (!matchId) { @@ -86,18 +375,33 @@ export function useAuctionSocket(matchId: string | undefined) { socket.on('connect', () => { setConnectionStatus('connected'); socket.emit('join', { matchId }); + requestServerTimeSync(socket); + if (timeSyncIntervalRef.current) { + clearInterval(timeSyncIntervalRef.current); + } + timeSyncIntervalRef.current = setInterval( + () => requestServerTimeSync(socket), + TIME_SYNC_INTERVAL_MS, + ); }); socket.on('disconnect', () => { + clearTimeSyncTimers(); setConnectionStatus('disconnected'); }); socket.on('state', (nextAuction: ApiAuction) => { - setAuction(nextAuction); + const didApplyState = commitAuctionState(nextAuction, 'socket-state'); + if (didApplyState) { + clearPendingActionRequests(); + } + applyFallbackServerTimestamp(nextAuction.currentServerTimestampMS); if (nextAuction.chatMessages) { setChatMessages(mergeChatMessages([], nextAuction.chatMessages)); } - setError(null); + if (didApplyState) { + setError(null); + } }); socket.on('chat-history', (payload: ChatHistoryPayload) => { @@ -108,8 +412,82 @@ export function useAuctionSocket(matchId: string | undefined) { setChatMessages((current) => mergeChatMessages(current, [message])); }); + socket.on('bid', (payload: BidDeltaPayload) => { + applyFallbackServerTimestamp(payload?.currentServerTimestampMS); + const beforeBid = latestAuctionRef.current; + const didApplyBidDelta = commitBidDelta(payload); + addNewRelicPageAction('AuctionClientBidDelta', { + matchId: matchId ?? 'none', + applied: didApplyBidDelta, + deltaRevision: + typeof payload?.revision === 'number' ? payload.revision : -1, + deltaBidAmount: Number(payload?.currentHighestBidPointAmount ?? -1), + deltaBidderTeamIndex: Number( + payload?.currentHighestBidderTeamIndex ?? -1, + ), + beforeRevision: + typeof beforeBid?.revision === 'number' ? beforeBid.revision : -1, + beforeBidAmount: beforeBid + ? resolveCurrentBidPointAmount(beforeBid) + : -1, + beforePlayerUserId: beforeBid?.currentBidRoundPlayerUserId ?? 'none', + }); + if (payload?.bidRequestId) { + if ( + didApplyBidDelta || + pendingBidTimeoutsRef.current[payload.bidRequestId] + ) { + clearPendingBidRequest(payload.bidRequestId); + } + } + }); + + socket.on('match-side-effect', (payload: MatchSideEffectPayload) => { + applyFallbackServerTimestamp(payload?.currentServerTimestampMS); + if ( + !payload?.matchSideEffectStatus || + typeof payload.matchSideEffectRevision !== 'number' + ) { + return; + } + const matchSideEffectRevision = payload.matchSideEffectRevision; + const matchSideEffectStatus = payload.matchSideEffectStatus; + + const currentAuction = latestAuctionRef.current; + if (!currentAuction) return; + if ( + payload.auctionLifecycleId && + currentAuction.auctionLifecycleId && + payload.auctionLifecycleId !== currentAuction.auctionLifecycleId + ) { + return; + } + if ( + matchSideEffectRevision <= + (currentAuction.matchSideEffectRevision ?? -1) + ) { + return; + } + + const nextAuction = { + ...currentAuction, + matchSideEffectRevision, + matchSideEffectStatus, + }; + latestAuctionRef.current = nextAuction; + setAuction(nextAuction); + addNewRelicPageAction('AuctionClientSideEffect', { + matchId: matchId ?? 'none', + matchSideEffectStatus: matchSideEffectStatus ?? 'unknown', + matchSideEffectRevision, + ...describeAuctionForTelemetry('current', currentAuction), + }); + }); + socket.on('reset', (payload: ResetPayload) => { if (payload.matchId && payload.matchId !== matchId) return; + latestAuctionRef.current = null; + latestConfirmedBidPointAmountRef.current = 0; setAuction(null); setChatMessages([]); setResetAt(Date.now()); @@ -117,8 +495,8 @@ export function useAuctionSocket(matchId: string | undefined) { }); socket.on('error', (payload: { message?: string }) => { - setConnectionStatus('error'); - setError(payload.message ?? '실시간 경매 연결 중 오류가 발생했습니다.'); + // ack 없는 error 채널(영문 message만)도 같은 톤의 한국어로 매핑한다. + setError(resolveAuctionErrorMessage(payload.message)); }); })(); @@ -128,10 +506,57 @@ export function useAuctionSocket(matchId: string | undefined) { socket?.removeAllListeners(); socket?.disconnect(); socketRef.current = null; + clearTimeSyncTimers(); + Object.values(pendingBidTimeoutsRef.current).forEach((timeoutId) => + clearTimeout(timeoutId), + ); + Object.values(pendingActionTimeoutsRef.current).forEach((timeoutId) => + clearTimeout(timeoutId), + ); + pendingBidTimeoutsRef.current = {}; + pendingActionTimeoutsRef.current = {}; + latestAuctionRef.current = null; + latestConfirmedBidPointAmountRef.current = 0; + hasSyncedServerTimeRef.current = false; + setPendingBidRequests({}); + setPendingActionRequests({}); setConnectionStatus('idle'); + setServerTimeOffsetMs(0); + setServerRoundTripMs(null); + setBidLatencyDiagnostics(null); }; }, [authUserId, matchId]); + function clearPendingBidRequest(bidRequestId: string) { + const timeoutId = pendingBidTimeoutsRef.current[bidRequestId]; + if (timeoutId) clearTimeout(timeoutId); + delete pendingBidTimeoutsRef.current[bidRequestId]; + setPendingBidRequests((current) => { + const next = { ...current }; + delete next[bidRequestId]; + return next; + }); + } + + function clearPendingActionRequest(auctionActionRequestId: string) { + const timeoutId = pendingActionTimeoutsRef.current[auctionActionRequestId]; + if (timeoutId) clearTimeout(timeoutId); + delete pendingActionTimeoutsRef.current[auctionActionRequestId]; + setPendingActionRequests((current) => { + const next = { ...current }; + delete next[auctionActionRequestId]; + return next; + }); + } + + function clearPendingActionRequests() { + Object.values(pendingActionTimeoutsRef.current).forEach((timeoutId) => + clearTimeout(timeoutId), + ); + pendingActionTimeoutsRef.current = {}; + setPendingActionRequests({}); + } + function emit(eventName: string, payload?: unknown) { const socket = socketRef.current; if (!socket || !socket.connected) { @@ -149,7 +574,169 @@ export function useAuctionSocket(matchId: string | undefined) { socket.emit(eventName, payload); } - const visibleAuction = auction?.matchId === matchId ? auction : null; + function buildAuctionActionPayload(): AuctionActionPayload { + const currentAuction = latestAuctionRef.current ?? auction; + return { + auctionActionRequestId: createClientRequestId(), + clientObservedAuctionLifecycleId: currentAuction?.auctionLifecycleId, + clientObservedCurrentAuctionPlayerOrderIndex: + currentAuction?.currentAuctionPlayerOrderIndex, + clientObservedCurrentBidRoundPlayerUserId: + currentAuction?.currentBidRoundPlayerUserId, + clientObservedPhase: currentAuction?.phase, + clientObservedRevision: currentAuction?.revision, + }; + } + + // 거부 등으로 클라 상태가 낡았을 때 서버 최신 state를 다시 받아 rebaseline한다. + // join 핸들러가 getStateByMatchId → broadcastState로 fresh state를 내려주고, + // revision 가드상 더 높은 revision이라 정상 적용된다(force-resync 아님). + function resyncAuctionState() { + const socket = socketRef.current; + if (!socket || !socket.connected || !matchId) return; + socket.emit('join', { matchId }); + } + + // retryAttempt: 거부 후 자동 재시도 횟수(루프 방지를 위해 1회로 제한). + function emitAuctionAction( + eventName: string, + payload: AuctionActionPayload, + retryAttempt = 0, + ) { + const socket = socketRef.current; + if (!socket || !socket.connected) { + setError('소켓이 아직 연결되지 않았습니다.'); + return; + } + if (Object.keys(pendingActionTimeoutsRef.current).length > 0) { + return; + } + + const auctionActionRequestId = + payload.auctionActionRequestId ?? createClientRequestId(); + const actionPayload = { + ...payload, + auctionActionRequestId, + }; + setError(null); + setPendingActionRequests((current) => ({ + ...current, + [auctionActionRequestId]: { action: eventName }, + })); + pendingActionTimeoutsRef.current[auctionActionRequestId] = setTimeout(() => { + clearPendingActionRequest(auctionActionRequestId); + setError('경매 진행 응답이 지연되어 최신 상태를 다시 확인해주세요.'); + }, 10_000); + addNewRelicPageAction('AuctionClientActionSent', { + matchId: matchId ?? 'none', + action: eventName, + retryAttempt, + sentRevision: + typeof payload.clientObservedRevision === 'number' + ? payload.clientObservedRevision + : -1, + sentOrderIndex: + typeof payload.clientObservedCurrentAuctionPlayerOrderIndex === 'number' + ? payload.clientObservedCurrentAuctionPlayerOrderIndex + : -1, + sentPlayerUserId: + payload.clientObservedCurrentBidRoundPlayerUserId ?? 'none', + sentPhase: payload.clientObservedPhase ?? 'none', + ...describeAuctionForTelemetry('observed', latestAuctionRef.current), + }); + socket.emit( + eventName, + actionPayload, + (ack?: { + auctionActionRequestId?: string; + auctionRejectionReason?: string; + code?: string; + message?: string; + rejected?: boolean; + resyncRecommended?: boolean; + state?: ApiAuction; + }) => { + if (ack?.rejected) { + clearPendingActionRequest( + ack?.auctionActionRequestId ?? auctionActionRequestId, + ); + // 2) 자동 재시도: "낡은 화면 때문에 거부"였고 동기 rebaseline 소스(state)가 + // 있을 때만 1회. assignedPosition 등 원래 payload는 유지하고 관측값/요청 + // id만 새로 만든다. 재시도 시에는 중간 에러 문구를 띄우지 않는다(무음 복구). + const canAutoRetry = + Boolean(ack.state) && + isAuctionResyncRecommended(ack) && + retryAttempt < 1; + // 거부 시 "클라가 보낸 관측 revision"과 "서버가 동봉한 진짜 state"를 함께 + // 기록한다. observedRevision < serverRevision 이면 stale-client CONFLICT 확정. + addNewRelicPageAction('AuctionClientActionRejected', { + matchId: matchId ?? 'none', + action: eventName, + retryAttempt, + rejectionReason: + ack?.auctionRejectionReason ?? ack?.code ?? 'unknown', + rejectionCode: ack?.code ?? 'none', + resyncRecommended: isAuctionResyncRecommended(ack), + hasAckState: Boolean(ack?.state), + willAutoRetry: canAutoRetry, + sentRevision: + typeof payload.clientObservedRevision === 'number' + ? payload.clientObservedRevision + : -1, + sentOrderIndex: + typeof payload.clientObservedCurrentAuctionPlayerOrderIndex === + 'number' + ? payload.clientObservedCurrentAuctionPlayerOrderIndex + : -1, + sentPlayerUserId: + payload.clientObservedCurrentBidRoundPlayerUserId ?? 'none', + sentPhase: payload.clientObservedPhase ?? 'none', + ...describeAuctionForTelemetry('observed', latestAuctionRef.current), + ...describeAuctionForTelemetry('server', ack?.state ?? null), + }); + // 1) rebaseline: 서버가 동봉한 최신 state를 즉시 반영(없으면 join으로 재요청). + // commitAuctionState는 latestAuctionRef를 동기로 갱신하므로, 이후 + // buildAuctionActionPayload는 최신 관측값(revision/phase/선수)을 읽는다. + if (ack.state) { + commitAuctionState(ack.state, 'action-reject-rebaseline'); + } else if (isAuctionResyncRecommended(ack)) { + resyncAuctionState(); + } + if (canAutoRetry) { + emitAuctionAction( + eventName, + { ...payload, ...buildAuctionActionPayload() }, + retryAttempt + 1, + ); + } else { + setError(resolveAuctionRejectionMessage(ack)); + } + return; + } + const ackState = ack?.state; + if (ackState) { + clearPendingActionRequest( + ack.auctionActionRequestId ?? auctionActionRequestId, + ); + addNewRelicPageAction('AuctionClientActionAck', { + matchId: matchId ?? 'none', + action: eventName, + retryAttempt, + sentRevision: + typeof payload.clientObservedRevision === 'number' + ? payload.clientObservedRevision + : -1, + ...describeAuctionForTelemetry('server', ackState), + }); + commitAuctionState(ackState, 'action-ack'); + } + }, + ); + } + + const currentAuction = auction; + const visibleAuction = + currentAuction && currentAuction.matchId === matchId ? currentAuction : null; const visibleConnectionStatus: ConnectionStatus = matchId ? connectionStatus : 'idle'; @@ -157,23 +744,312 @@ export function useAuctionSocket(matchId: string | undefined) { return { auction: visibleAuction, chatMessages: visibleAuction ? chatMessages : [], + isAuctionActionPending: Object.keys(pendingActionRequests).length > 0, + isBidPending: Object.keys(pendingBidRequests).length > 0, + pendingActionRequests, + pendingBidRequests, resetAt, connectionStatus: visibleConnectionStatus, error, + bidLatencyDiagnostics, + serverRoundTripMs: matchId ? serverRoundTripMs : null, + serverTimeOffsetMs: matchId ? serverTimeOffsetMs : 0, placeBid(payload: BidPayload) { - emit('bid', payload); + const socket = socketRef.current; + if (!socket || !socket.connected) { + setError('소켓이 아직 연결되지 않았습니다.'); + return; + } + if (Object.keys(pendingBidTimeoutsRef.current).length > 0) { + return; + } + if (payload.bidPointAmount <= latestConfirmedBidPointAmountRef.current) { + return; + } + + const bidRequestId = payload.bidRequestId ?? createClientRequestId(); + const currentAuction = latestAuctionRef.current ?? auction; + const bidPayload: BidPayload = { + ...payload, + bidRequestId, + clientObservedAuctionLifecycleId: + payload.clientObservedAuctionLifecycleId ?? + currentAuction?.auctionLifecycleId, + clientObservedCurrentBidRoundPlayerUserId: + payload.clientObservedCurrentBidRoundPlayerUserId ?? + currentAuction?.currentBidRoundPlayerUserId, + }; + + setError(null); + setPendingBidRequests((current) => ({ + ...current, + [bidRequestId]: { + amount: bidPayload.bidPointAmount, + teamIndex: bidPayload.bidderTeamIndex, + }, + })); + pendingBidTimeoutsRef.current[bidRequestId] = setTimeout(() => { + clearPendingBidRequest(bidRequestId); + setError('입찰 응답이 지연되어 최신 상태를 다시 확인해주세요.'); + }, 10_000); + socket.emit( + 'bid', + bidPayload, + (ack?: BidAckPayload) => { + captureBidLatencyDiagnostics(ack); + if (ack?.rejected) { + clearPendingBidRequest(bidRequestId); + // 입찰 거부도 최신 state로 rebaseline(예: 0초 입찰 EXPIRED → 만료된 + // 라운드 화면에서 벗어나게). 단 입찰은 자동 재시도하지 않는다(의도치 + // 않은 금액 재입찰 방지). + if (ack.state) { + commitAuctionState(ack.state); + } else if (isAuctionResyncRecommended(ack)) { + resyncAuctionState(); + } + setError(resolveAuctionRejectionMessage(ack)); + return; + } + if (ack?.bidDelta) { + clearPendingBidRequest(bidRequestId); + commitBidDelta(ack.bidDelta); + return; + } + const ackState = ack?.state; + if (ackState) { + clearPendingBidRequest(bidRequestId); + commitAuctionState(ackState); + } + }, + ); }, openBidding() { - emit('open-bidding', {}); + emitAuctionAction('open-bidding', buildAuctionActionPayload()); }, markSold(assignedPosition?: Position) { - emit('sold', assignedPosition ? { assignedPosition } : {}); + const payload: SoldPayload = { + ...buildAuctionActionPayload(), + assignedPosition, + }; + emitAuctionAction('sold', payload); + }, + markPassed() { + emitAuctionAction('passed', buildAuctionActionPayload()); }, next() { - emit('next', {}); + emitAuctionAction('next', buildAuctionActionPayload()); }, sendChatMessage(payload: ChatMessagePayload) { emit('chat-message', payload); }, }; } + +function createClientRequestId(): string { + if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) { + return crypto.randomUUID(); + } + return `${Date.now()}-${Math.random().toString(16).slice(2)}`; +} + +function resolveCurrentBidPointAmount(auction: ApiAuction): number { + const bidPointAmount = Math.max( + Number(auction.currentHighestBidPointAmount), + Number(auction.currentBid), + 0, + ); + return Number.isFinite(bidPointAmount) ? bidPointAmount : 0; +} + +// [AUCTION-DEBUG] 아래 텔레메트리 헬퍼들과 호출부는 조사 종료 후 제거 대상. +type AuctionTelemetryAttributes = Record; + +function readAuctionHistorySequence(auction: ApiAuction | null | undefined) { + const value = (auction as { currentAuctionHistorySequence?: unknown } | null) + ?.currentAuctionHistorySequence; + return typeof value === 'number' ? value : -1; +} + +function summarizeAuctionTeams(auction: ApiAuction | null | undefined) { + const teams = Array.isArray(auction?.auctionTeams) ? auction.auctionTeams : []; + let assignedMemberCount = 0; + for (const team of teams) { + const members = (team as { members?: unknown[] }).members; + if (Array.isArray(members)) assignedMemberCount += members.length; + } + return { teamCount: teams.length, assignedMemberCount }; +} + +// New Relic로 보내기 위해 경매 상태를 평탄한 속성 집합으로 요약한다. +// prefix로 두 상태(예: 현재 vs 수신)를 한 이벤트에 같이 실어 revision 어긋남을 +// 한눈에 비교할 수 있게 한다. +function describeAuctionForTelemetry( + prefix: string, + auction: ApiAuction | null | undefined, +): AuctionTelemetryAttributes { + const teamSummary = summarizeAuctionTeams(auction); + return { + [`${prefix}Revision`]: + typeof auction?.revision === 'number' ? auction.revision : -1, + [`${prefix}HistorySequence`]: readAuctionHistorySequence(auction), + [`${prefix}Phase`]: auction?.phase ?? 'unknown', + [`${prefix}LifecycleId`]: auction?.auctionLifecycleId ?? 'none', + [`${prefix}OrderIndex`]: + typeof auction?.currentAuctionPlayerOrderIndex === 'number' + ? auction.currentAuctionPlayerOrderIndex + : -1, + [`${prefix}PlayerUserId`]: auction?.currentBidRoundPlayerUserId ?? 'none', + [`${prefix}BidAmount`]: auction + ? resolveCurrentBidPointAmount(auction) + : -1, + [`${prefix}BidderTeamIndex`]: + typeof auction?.currentHighestBidderTeamIndex === 'number' + ? auction.currentHighestBidderTeamIndex + : typeof auction?.currentBidderTeamIndex === 'number' + ? auction.currentBidderTeamIndex + : -1, + [`${prefix}TeamCount`]: teamSummary.teamCount, + [`${prefix}AssignedMemberCount`]: teamSummary.assignedMemberCount, + [`${prefix}ForceResync`]: Boolean(auction?.shouldForceAuctionStateResync), + }; +} + +function shouldApplyIncomingAuctionState( + current: ApiAuction | null, + incoming: ApiAuction, +): boolean { + if (!current) return true; + if (incoming.shouldForceAuctionStateResync) return true; + if ( + current.auctionLifecycleId && + incoming.auctionLifecycleId && + current.auctionLifecycleId !== incoming.auctionLifecycleId + ) { + return true; + } + if ( + typeof current.revision === 'number' && + typeof incoming.revision === 'number' && + incoming.revision <= current.revision + ) { + return false; + } + return true; +} + +function applyBidDelta( + current: ApiAuction | null, + payload: BidDeltaPayload, +): ApiAuction | null { + if (!current) return current; + if ( + payload.auctionLifecycleId && + current.auctionLifecycleId && + payload.auctionLifecycleId !== current.auctionLifecycleId + ) { + return current; + } + if ( + typeof current.revision === 'number' && + typeof payload.revision === 'number' && + payload.revision <= current.revision + ) { + return current; + } + + const bidPointAmount = Number(payload.currentHighestBidPointAmount); + const bidderTeamIndex = Number(payload.currentHighestBidderTeamIndex); + if (!Number.isFinite(bidPointAmount) || !Number.isFinite(bidderTeamIndex)) { + return current; + } + + const bidHistoryEntry = normalizeBidHistoryEntry(payload.auctionBidHistoryEntry); + const currentBidRoundDeadlineTimestampMS = + typeof payload.currentBidRoundDeadlineTimestampMS === 'number' + ? payload.currentBidRoundDeadlineTimestampMS + : current.currentBidRoundDeadlineTimestampMS; + + return { + ...current, + auctionBidHistory: appendUniqueAuctionBidHistoryEntry( + current.auctionBidHistory ?? [], + bidHistoryEntry, + ), + bids: bidHistoryEntry + ? appendUniqueLegacyBidEntry(current.bids ?? [], bidHistoryEntry) + : current.bids, + currentBid: bidPointAmount, + currentBidderTeamIndex: bidderTeamIndex, + currentDeadline: currentBidRoundDeadlineTimestampMS + ? new Date(currentBidRoundDeadlineTimestampMS).toISOString() + : current.currentDeadline, + currentHighestBidPointAmount: bidPointAmount, + currentHighestBidderTeamIndex: bidderTeamIndex, + currentBidRoundDeadlineTimestampMS, + currentServerTimestampMS: + payload.currentServerTimestampMS ?? current.currentServerTimestampMS, + revision: payload.revision ?? current.revision, + }; +} + +function normalizeBidHistoryEntry( + entry: BidDeltaPayload['auctionBidHistoryEntry'], +): NonNullable[number] | null { + if (!entry) return null; + const bidderTeamIndex = Number(entry.bidderTeamIndex); + const bidPointAmount = Number(entry.bidPointAmount); + const bidPlacedAtTimestampMS = Number(entry.bidPlacedAtTimestampMS); + if (!Number.isFinite(bidderTeamIndex) || !Number.isFinite(bidPointAmount)) { + return null; + } + return { + bidderTeamIndex, + bidPointAmount, + bidderUserId: entry.bidderUserId ?? '', + bidPlacedAtTimestampMS: Number.isFinite(bidPlacedAtTimestampMS) + ? bidPlacedAtTimestampMS + : Date.now(), + }; +} + +function appendUniqueAuctionBidHistoryEntry( + current: NonNullable, + entry: NonNullable[number] | null, +) { + if (!entry) return current; + if ( + current.some( + (existing) => + existing.bidderTeamIndex === entry.bidderTeamIndex && + existing.bidPointAmount === entry.bidPointAmount && + existing.bidPlacedAtTimestampMS === entry.bidPlacedAtTimestampMS, + ) + ) { + return current; + } + return [...current, entry]; +} + +function appendUniqueLegacyBidEntry( + current: ApiAuction['bids'], + entry: NonNullable[number], +) { + const currentBids = current ?? []; + const legacyBid = { + amount: entry.bidPointAmount, + bidderUserId: entry.bidderUserId, + teamIndex: entry.bidderTeamIndex, + timestamp: new Date(entry.bidPlacedAtTimestampMS).toISOString(), + }; + if ( + currentBids.some( + (existing) => + existing.teamIndex === legacyBid.teamIndex && + existing.amount === legacyBid.amount && + existing.timestamp === legacyBid.timestamp, + ) + ) { + return currentBids; + } + return [...currentBids, legacyBid]; +} diff --git a/apps/web/src/components/InternalGameAnalysisTabs.tsx b/apps/web/src/components/InternalGameAnalysisTabs.tsx new file mode 100644 index 00000000..54d9594b --- /dev/null +++ b/apps/web/src/components/InternalGameAnalysisTabs.tsx @@ -0,0 +1,1021 @@ +import { useState, type ReactNode } from "react"; +import type { ApiInternalMatchDetailResponse, DdragonManifest, TeamSide } from "../api/types"; +import { + championDisplayName, + championIconUrl, +} from "../lib/ddragon"; +import { teamIndexLabel } from "../lib/league"; +import { LANE_LABELS } from "../lib/riot-history"; +import { + DEFAULT_LANE_CHECKPOINT, + pairLaneParticipants, + resolveCheckpointComparison, + type LaneCheckpointKey, + type LaneParticipantLike, + type NormalizedLanePosition, +} from "../lib/internal-game-matchups"; +import { ItemIcon, RuneIcon, RuneStyleIcon } from "./ItemTooltip"; + +export type InternalGameDetailTab = "scoreboard" | "matchup" | "build"; + +type InternalGameDetail = ApiInternalMatchDetailResponse["games"][number]; +type InternalGameTeam = InternalGameDetail["teams"][number]; +type InternalGameParticipant = InternalGameTeam["participants"][number]; +type CheckpointParticipant = InternalGameParticipant & LaneParticipantLike; +type DdragonManifestData = DdragonManifest | null | undefined; +type RuneStyleEntry = DdragonManifest["runesReforged"][number]; + +const DETAIL_TABS: Array<{ id: InternalGameDetailTab; label: string }> = [ + { id: "scoreboard", label: "스코어보드" }, + { id: "matchup", label: "라인전" }, + { id: "build", label: "룬 / 빌드" }, +]; + +const SKILL_ROWS: Array<{ + slot: 1 | 2 | 3 | 4; + label: string; + className: string; +}> = [ + { slot: 1, label: "Q", className: "bg-blue-500 text-white" }, + { slot: 2, label: "W", className: "bg-cyan-500 text-white" }, + { slot: 3, label: "E", className: "bg-amber-500 text-black" }, + { slot: 4, label: "R", className: "bg-red-500 text-white" }, +]; + +const STAT_PERK_LABELS: Record = { + 5001: "체력", + 5002: "방어", + 5003: "마저", + 5005: "공속", + 5007: "가속", + 5008: "적응", + 5010: "이속", + 5011: "체력", +}; + +function formatDuration(seconds: number) { + const minutes = Math.floor(seconds / 60); + const rest = seconds % 60; + return `${minutes}:${String(rest).padStart(2, "0")}`; +} + +function formatNumber(value: number) { + return new Intl.NumberFormat("ko-KR").format(value); +} + +function formatSignedNumber(value: number) { + if (value === 0) return "0"; + return `${value > 0 ? "+" : "-"}${formatNumber(Math.abs(value))}`; +} + +function sideTone(side: TeamSide) { + return side === "blue" + ? { + border: "border-blue-500/20", + bg: "bg-blue-500/5", + text: "text-blue-400", + bar: "bg-blue-500", + } + : { + border: "border-red-500/20", + bg: "bg-red-500/5", + text: "text-red-400", + bar: "bg-red-500", + }; +} + +function getTeamName( + detail: ApiInternalMatchDetailResponse, + teamIndex: number, +) { + return teamIndexLabel( + teamIndex, + detail.match.teams.find((team) => team.teamIndex === teamIndex)?.name, + ); +} + +function participantBuildKey(participant: InternalGameParticipant) { + return `${participant.side}-${participant.userId ?? participant.summonerName}-${participant.championId}`; +} + +function findRuneStyle( + manifest: DdragonManifestData, + styleId: number | undefined, +) { + return manifest?.runesReforged.find((style) => style.id === styleId) ?? null; +} + +function selectedRuneIds(participant: InternalGameParticipant) { + const explicit = participant.perks.selectedPerkIds ?? []; + const fromStyles = + participant.perks.styles?.flatMap((style) => style.perkIds) ?? []; + return new Set([ + ...explicit, + ...fromStyles, + ...(participant.perks.keystone ? [participant.perks.keystone] : []), + ]); +} + +function runeStyleSelection( + participant: InternalGameParticipant, + styleId: number | undefined, +) { + return participant.perks.styles?.find((style) => style.styleId === styleId); +} + +function ChampionCell({ + participant, + manifest, +}: { + participant: InternalGameParticipant; + manifest: DdragonManifestData; +}) { + const icon = championIconUrl(manifest, participant.championId); + const name = + championDisplayName(manifest, participant.championId) ?? + String(participant.championId); + + return ( +
+ + {icon ? ( + {name} + ) : null} + {participant.championLevel > 0 && ( + + {participant.championLevel} + + )} + +
+ + {name} + + + {LANE_LABELS[participant.teamPosition] ?? + participant.teamPosition ?? + "-"} + +
+
+ ); +} + +function ChampionAvatar({ + participant, + manifest, + size = "h-9 w-9", +}: { + participant: InternalGameParticipant; + manifest: DdragonManifestData; + size?: string; +}) { + const icon = championIconUrl(manifest, participant.championId); + const name = + championDisplayName(manifest, participant.championId) ?? + String(participant.championId); + return ( + + {icon ? ( + {name} + ) : null} + {participant.championLevel > 0 ? ( + + {participant.championLevel} + + ) : null} + + ); +} + +function RuneBuildPanel({ + selectedGame, + detail, + manifest, +}: { + selectedGame: InternalGameDetail; + detail: ApiInternalMatchDetailResponse; + manifest: DdragonManifestData; +}) { + const orderedTeams = [...selectedGame.teams].sort((left, right) => + left.side === right.side ? 0 : left.side === "blue" ? -1 : 1, + ); + const participants = orderedTeams.flatMap((team) => team.participants); + const defaultKey = participants[0] + ? participantBuildKey(participants[0]) + : ""; + const [selectedKey, setSelectedKey] = useState(defaultKey); + const effectiveSelectedKey = participants.some( + (participant) => participantBuildKey(participant) === selectedKey, + ) + ? selectedKey + : defaultKey; + const selectedParticipant = + participants.find( + (participant) => + participantBuildKey(participant) === effectiveSelectedKey, + ) ?? participants[0]; + + if (!selectedParticipant) { + return ( +
+ 빌드 데이터가 없습니다 +
+ ); + } + + return ( +
+ +
+ +
+ + +
+
+
+ ); +} + +function BuildChampionSelector({ + selectedGame, + detail, + manifest, + selectedKey, + onSelect, +}: { + selectedGame: InternalGameDetail; + detail: ApiInternalMatchDetailResponse; + manifest: DdragonManifestData; + selectedKey: string; + onSelect: (key: string) => void; +}) { + const orderedTeams = [...selectedGame.teams].sort((left, right) => + left.side === right.side ? 0 : left.side === "blue" ? -1 : 1, + ); + + return ( +
+ {orderedTeams.map((team) => { + const tone = sideTone(team.side); + return ( +
+
+
+ {team.side === "blue" ? "블루" : "레드"} +
+
+ {getTeamName(detail, team.teamIndex)} +
+
+
+ {team.participants.map((participant) => ( + onSelect(participantBuildKey(participant))} + /> + ))} +
+
+ ); + })} +
+ ); +} + +function BuildChampionButton({ + participant, + manifest, + selected, + onClick, +}: { + participant: InternalGameParticipant; + manifest: DdragonManifestData; + selected: boolean; + onClick: () => void; +}) { + const icon = championIconUrl(manifest, participant.championId); + const championName = + championDisplayName(manifest, participant.championId) ?? + String(participant.championId); + const tone = sideTone(participant.side); + + return ( + + ); +} + +function RunesPanel({ + participant, + manifest, +}: { + participant: InternalGameParticipant; + manifest: DdragonManifestData; +}) { + const selectedIds = selectedRuneIds(participant); + const primaryStyleId = + participant.perks.primaryStyle ?? participant.perks.styles?.[0]?.styleId; + const subStyleId = + participant.perks.subStyle ?? participant.perks.styles?.[1]?.styleId; + const primaryStyle = findRuneStyle(manifest, primaryStyleId); + const subStyle = findRuneStyle(manifest, subStyleId); + + return ( +
+
+
+
+ 룬 +
+
+ {participant.summonerName} +
+
+ +
+
+ + +
+ +
+ ); +} + +function RuneTreeColumn({ + label, + isPrimary, + runeStyle, + selection, + selectedIds, + manifest, +}: { + label: string; + isPrimary: boolean; + runeStyle: RuneStyleEntry | null; + selection: ReturnType; + selectedIds: Set; + manifest: DdragonManifestData; +}) { + if (!runeStyle) { + return ( +
+
+ {label} +
+
+ 룬 데이터 없음 +
+
+ ); + } + + const selectionIds = new Set(selection?.perkIds ?? []); + + return ( +
+
+ +
+
+ {label} +
+
+ {runeStyle.name} +
+
+
+
+ {runeStyle.slots.map((slot, slotIndex) => { + // 보조 룬 트리는 핵심 룬(0번 행)을 선택하지 않으므로 숨긴다. + if (!isPrimary && slotIndex === 0) return null; + const isKeystoneRow = isPrimary && slotIndex === 0; + const cell = isKeystoneRow ? "2.5rem" : "2.25rem"; + const iconSize = isKeystoneRow ? "h-10 w-10" : "h-9 w-9"; + return ( +
+ {slot.runes.map((rune) => { + const selected = + selectedIds.has(rune.id) || selectionIds.has(rune.id); + return ( + + ); + })} +
+ ); + })} +
+
+ ); +} + +function RuneShardRows({ participant }: { participant: InternalGameParticipant }) { + const statPerks = participant.perks.statPerks; + const shards = [ + { label: "공격", value: statPerks?.offense }, + { label: "보조", value: statPerks?.flex }, + { label: "방어", value: statPerks?.defense }, + ].filter((shard) => typeof shard.value === "number" && shard.value > 0); + + if (shards.length === 0) return null; + + return ( +
+ + 스탯 파편 + + {shards.map((shard) => ( + + {shard.label} + + {STAT_PERK_LABELS[shard.value ?? 0] ?? shard.value} + + + ))} +
+ ); +} + +function ItemBuildPanel({ + participant, + manifest, +}: { + participant: InternalGameParticipant; + manifest: DdragonManifestData; +}) { + const buildEvents = (participant.itemBuild ?? []).filter( + (event) => event.itemId > 0 && event.type === "purchased", + ); + const fallbackItems = [ + ...participant.items + .filter((itemId) => itemId > 0) + .map((itemId) => ({ itemId, trinket: false })), + ...(participant.trinket > 0 + ? [{ itemId: participant.trinket, trinket: true }] + : []), + ]; + + return ( +
+
+ 아이템 빌드 +
+ {buildEvents.length > 0 ? ( +
+ {buildEvents.map((event, index) => ( +
+ + {index < buildEvents.length - 1 ? ( + + > + + ) : null} +
+ ))} +
+ ) : fallbackItems.length > 0 ? ( +
+ {fallbackItems.map((item, index) => ( + + ))} +
+ ) : ( +
+ 아이템 빌드 데이터 없음 +
+ )} +
+ ); +} + +function ItemBuildNode({ + itemId, + timestamp, + manifest, +}: { + itemId: number; + timestamp: number; + manifest: DdragonManifestData; +}) { + return ( +
+ + + {formatDuration(timestamp)} + +
+ ); +} + +function SkillBuildPanel({ + participant, +}: { + participant: InternalGameParticipant; +}) { + const skillEvents = participant.skillBuild ?? []; + const skillByLevel = new Map( + skillEvents.map((event) => [event.level, event]), + ); + + return ( +
+
+
+ 스킬 빌드 +
+
+ Lv. {skillEvents.length || participant.championLevel || "-"} +
+
+ {skillEvents.length > 0 ? ( +
+
+ {SKILL_ROWS.map((row) => ( +
+
+ {row.label} +
+ {Array.from({ length: 18 }, (_, index) => index + 1).map( + (level) => { + const event = skillByLevel.get(level); + const active = event?.skillSlot === row.slot; + return ( +
+ {active ? level : ""} +
+ ); + }, + )} +
+ ))} +
+
+ ) : ( +
+ 스킬 빌드 데이터 없음 +
+ )} +
+ ); +} + +function MatchupMetricRow({ + label, + difference, + blueLead, + redLead, + blueText, + redText, +}: { + label: string; + difference?: string; + blueLead: boolean; + redLead: boolean; + blueText: string; + redText: string; +}) { + return ( +
+ + {blueText} + + + {label} + {difference ? ( + + {difference} + + ) : null} + + + {redText} + +
+ ); +} + +function checkpointKda(kills: number, deaths: number, assists: number) { + return deaths === 0 ? kills + assists : (kills + assists) / deaths; +} + +function LaneParticipantIdentity({ + participant, + manifest, + align, + ambiguous, +}: { + participant: CheckpointParticipant | null; + manifest: DdragonManifestData; + align: "left" | "right"; + ambiguous: boolean; +}) { + if (!participant) { + return ( +
+ {ambiguous ? "포지션 중복" : "선수 없음"} +
+ ); + } + + const championName = + championDisplayName(manifest, participant.championId) ?? + String(participant.championId); + const details = ( +
+
+ {participant.summonerName} +
+
+ {championName} +
+
+ ); + + return ( +
+ {align === "right" ? details : null} + + {align === "left" ? details : null} +
+ ); +} + +function LaneMatchupCard({ + position, + blue, + red, + ambiguousBlue, + ambiguousRed, + checkpointKey, + manifest, +}: { + position: NormalizedLanePosition; + blue: CheckpointParticipant | null; + red: CheckpointParticipant | null; + ambiguousBlue: boolean; + ambiguousRed: boolean; + checkpointKey: LaneCheckpointKey; + manifest: DdragonManifestData; +}) { + const laneLabel = LANE_LABELS[position] ?? position; + const comparison = resolveCheckpointComparison(blue, red, checkpointKey); + const metrics = comparison + ? [ + { + key: "gold", + label: "골드", + difference: `GD ${formatSignedNumber(comparison.goldDiff)}`, + blueValue: comparison.blue.gold, + redValue: comparison.red.gold, + blueText: formatNumber(comparison.blue.gold), + redText: formatNumber(comparison.red.gold), + }, + { + key: "cs", + label: "CS", + difference: `CSD ${formatSignedNumber(comparison.csDiff)}`, + blueValue: comparison.blue.cs, + redValue: comparison.red.cs, + blueText: formatNumber(comparison.blue.cs), + redText: formatNumber(comparison.red.cs), + }, + { + key: "xp", + label: "경험치", + difference: `XPD ${formatSignedNumber(comparison.xpDiff)}`, + blueValue: comparison.blue.xp, + redValue: comparison.red.xp, + blueText: formatNumber(comparison.blue.xp), + redText: formatNumber(comparison.red.xp), + }, + { + key: "kda", + label: "K / D / A", + blueValue: checkpointKda( + comparison.blue.kills, + comparison.blue.deaths, + comparison.blue.assists, + ), + redValue: checkpointKda( + comparison.red.kills, + comparison.red.deaths, + comparison.red.assists, + ), + blueText: `${comparison.blue.kills}/${comparison.blue.deaths}/${comparison.blue.assists}`, + redText: `${comparison.red.kills}/${comparison.red.deaths}/${comparison.red.assists}`, + }, + ] + : []; + + return ( +
+
+ + + {laneLabel} + + +
+ {comparison ? ( + <> +
+ {metrics.map((metric) => ( + metric.redValue} + redLead={metric.redValue > metric.blueValue} + blueText={metric.blueText} + redText={metric.redText} + /> + ))} +
+
+ 실제 기준 {formatDuration(comparison.blue.timestamp)} · {formatDuration(comparison.red.timestamp)} +
+ + ) : ( +
+ {ambiguousBlue || ambiguousRed + ? "포지션이 중복되어 상대를 확정할 수 없습니다" + : "선택한 시점의 라인전 데이터가 없습니다"} +
+ )} +
+ ); +} + +function LaneMatchupPanel({ + selectedGame, + detail, + manifest, +}: { + selectedGame: InternalGameDetail; + detail: ApiInternalMatchDetailResponse; + manifest: DdragonManifestData; +}) { + const [checkpointKey, setCheckpointKey] = + useState(DEFAULT_LANE_CHECKPOINT); + const blueTeam = selectedGame.teams.find((team) => team.side === "blue"); + const redTeam = selectedGame.teams.find((team) => team.side === "red"); + + if (!blueTeam || !redTeam) { + return ( +
+ 라인전 비교 데이터가 없습니다 +
+ ); + } + + const matchups = pairLaneParticipants( + blueTeam.participants as CheckpointParticipant[], + redTeam.participants as CheckpointParticipant[], + ); + const blueTeamName = getTeamName(detail, blueTeam.teamIndex); + const redTeamName = getTeamName(detail, redTeam.teamIndex); + + return ( +
+
+
+ + {blueTeamName} + + VS + {redTeamName} +
+
+ {(["at10", "at15"] as const).map((key) => ( + + ))} +
+
+
+ {matchups.length > 0 ? ( + matchups.map((matchup) => ( + + )) + ) : ( +
+ 비교 가능한 포지션 정보가 없습니다 +
+ )} +
+
+ ); +} + +export function InternalGameDetailTabBar({ + activeTab, + onChange, +}: { + activeTab: InternalGameDetailTab; + onChange: (tab: InternalGameDetailTab) => void; +}) { + return ( +
+ {DETAIL_TABS.map((tab) => ( + + ))} +
+ ); +} + +export function InternalGameAnalysisPanel({ + activeTab, + selectedGame, + detail, + manifest, + scoreboard, +}: { + activeTab: InternalGameDetailTab; + selectedGame: InternalGameDetail; + detail: ApiInternalMatchDetailResponse; + manifest: DdragonManifestData; + scoreboard: ReactNode; +}) { + if (activeTab === "scoreboard") { + return <>{scoreboard}; + } + + if (activeTab === "build") { + return ( + + ); + } + + return ( + + ); +} diff --git a/apps/web/src/components/ItemTooltip.tsx b/apps/web/src/components/ItemTooltip.tsx new file mode 100644 index 00000000..1fae4133 --- /dev/null +++ b/apps/web/src/components/ItemTooltip.tsx @@ -0,0 +1,406 @@ +import type { CSSProperties, ReactNode, RefObject } from "react"; +import { useEffect, useId, useRef, useState } from "react"; +import { createPortal } from "react-dom"; +import type { DdragonManifest } from "../api/types"; +import { + itemDetails, + itemDisplayName, + itemIconUrl, + runeDetails, + runeIconUrl, + runeStyleDetails, + runeStyleIconUrl, + safeDdragonDescriptionHtml, + summonerSpellDetails, + summonerSpellIconUrl, +} from "../lib/ddragon"; + +type TooltipPosition = { + left: number; + top: number; + width: number; + placement: "top" | "bottom"; +}; + +type ItemIconProps = { + itemId: number; + manifest: DdragonManifest | null | undefined; + className?: string; + imageClassName?: string; + trinket?: boolean; +}; + +type TooltipIconProps = { + active: boolean; + label: string; + emptyLabel: string; + icon: string | null; + className: string; + imageClassName: string; + slotClassName: string; + children: ReactNode; +}; + +type ManifestIconProps = { + manifest: DdragonManifest | null | undefined; + className?: string; + imageClassName?: string; + slotClassName?: string; +}; + +const VIEWPORT_MARGIN = 8; +const TOOLTIP_GAP = 8; +const TOOLTIP_WIDTH = 320; + +export function ItemIcon({ + itemId, + manifest, + className = "h-6 w-6", + imageClassName = "scale-[1.18]", + trinket = false, +}: ItemIconProps) { + const icon = itemIconUrl(manifest, itemId); + const hasItem = itemId > 0; + const itemName = itemDisplayName(manifest, itemId) ?? `아이템 ${itemId}`; + const slotTone = trinket + ? "border-primary/25 bg-base-content/[0.04]" + : "border-base-content/5 bg-base-content/8"; + + return ( + + + + ); +} + +export function SummonerSpellIcon({ + spellId, + manifest, + className = "h-5 w-5", + imageClassName = "", + slotClassName = "border border-base-content/5 bg-base-content/10", +}: ManifestIconProps & { spellId: number }) { + const spell = summonerSpellDetails(manifest, spellId); + const spellName = spell?.name ?? `스펠 ${spellId}`; + + return ( + 0} + label={spellName} + emptyLabel="빈 스펠 슬롯" + icon={summonerSpellIconUrl(manifest, spellId)} + className={className} + imageClassName={imageClassName} + slotClassName={slotClassName} + > + + + ); +} + +export function RuneIcon({ + runeId, + manifest, + className = "h-5 w-5", + imageClassName = "", + slotClassName = "border border-base-content/5 bg-base-content/10", +}: ManifestIconProps & { runeId: number | undefined }) { + const rune = runeDetails(manifest, runeId); + const runeName = rune?.name ?? (runeId ? `룬 ${runeId}` : "룬"); + + return ( + + + + ); +} + +export function RuneStyleIcon({ + styleId, + manifest, + className = "h-5 w-5", + imageClassName = "", + slotClassName = "border border-base-content/5 bg-base-content/10", +}: ManifestIconProps & { styleId: number | undefined }) { + const style = runeStyleDetails(manifest, styleId); + const styleName = style?.name ?? (styleId ? `룬 ${styleId}` : "룬"); + + return ( + + + + ); +} + +function TooltipIcon({ + active, + label, + emptyLabel, + icon, + className, + imageClassName, + slotClassName, + children, +}: TooltipIconProps) { + const anchorRef = useRef(null); + const tooltipId = useId(); + const [open, setOpen] = useState(false); + + return ( + setOpen(false)} + onFocus={() => active && setOpen(true)} + onMouseEnter={() => active && setOpen(true)} + onMouseLeave={() => setOpen(false)} + > + + {active && open ? ( + + {children} + + ) : null} + + ); +} + +function TooltipPortal({ + id, + anchorRef, + children, +}: { + id: string; + anchorRef: RefObject; + children: ReactNode; +}) { + const [position, setPosition] = useState(null); + + useEffect(() => { + function updatePosition() { + const anchor = anchorRef.current; + if (!anchor) return; + + const rect = anchor.getBoundingClientRect(); + const width = Math.min( + TOOLTIP_WIDTH, + window.innerWidth - VIEWPORT_MARGIN * 2, + ); + const left = clamp( + rect.left + rect.width / 2 - width / 2, + VIEWPORT_MARGIN, + window.innerWidth - width - VIEWPORT_MARGIN, + ); + const placement = rect.top > 260 ? "top" : "bottom"; + setPosition({ + left, + top: + placement === "top" + ? rect.top - TOOLTIP_GAP + : rect.bottom + TOOLTIP_GAP, + width, + placement, + }); + } + + updatePosition(); + window.addEventListener("resize", updatePosition); + window.addEventListener("scroll", updatePosition, true); + return () => { + window.removeEventListener("resize", updatePosition); + window.removeEventListener("scroll", updatePosition, true); + }; + }, [anchorRef]); + + if (typeof document === "undefined" || !position) return null; + + const style: CSSProperties = { + left: position.left, + top: position.top, + width: position.width, + transform: + position.placement === "top" ? "translateY(-100%)" : undefined, + }; + + return createPortal( + , + document.body, + ); +} + +function SummonerSpellTooltipContent({ + spellId, + manifest, +}: { + spellId: number; + manifest: DdragonManifest | null | undefined; +}) { + const spell = summonerSpellDetails(manifest, spellId); + const descriptionHtml = spell?.description + ? safeDdragonDescriptionHtml(spell.description) + : ""; + + return ( +
+
+ {spell?.name ?? `스펠 ${spellId}`} +
+ {descriptionHtml ? ( +
+ ) : ( +
+ 스펠 상세 정보를 불러오는 중입니다. +
+ )} +
+ ); +} + +function RuneTooltipContent({ + runeId, + manifest, +}: { + runeId: number | undefined; + manifest: DdragonManifest | null | undefined; +}) { + const rune = runeDetails(manifest, runeId); + const descriptionHtml = rune?.longDesc + ? safeDdragonDescriptionHtml(rune.longDesc) + : ""; + + return ( +
+
+ {rune?.name ?? (runeId ? `룬 ${runeId}` : "룬")} +
+ {rune?.shortDesc ? ( +
{rune.shortDesc}
+ ) : null} + {descriptionHtml ? ( +
+ ) : ( +
룬 상세 정보를 불러오는 중입니다.
+ )} +
+ ); +} + +function RuneStyleTooltipContent({ + styleId, + manifest, +}: { + styleId: number | undefined; + manifest: DdragonManifest | null | undefined; +}) { + const style = runeStyleDetails(manifest, styleId); + + return ( +
+
+ {style?.name ?? (styleId ? `룬 ${styleId}` : "룬")} +
+
룬 스타일
+
+ ); +} + +function ItemTooltipContent({ + itemId, + manifest, +}: { + itemId: number; + manifest: DdragonManifest | null | undefined; +}) { + const item = itemDetails(manifest, itemId); + const descriptionHtml = item?.description + ? safeDdragonDescriptionHtml(item.description) + : ""; + + return ( +
+
+ {item?.name ?? `아이템 ${itemId}`} +
+ {item?.plaintext ? ( +
{item.plaintext}
+ ) : null} + {descriptionHtml ? ( +
+ ) : ( +
+ 아이템 상세 정보를 불러오는 중입니다. +
+ )} + {item?.gold.total ? ( +
+ 가격: + {item.gold.total}{" "} + + ({item.gold.base || item.gold.total}) + +
+ ) : null} +
+ ); +} + +function clamp(value: number, min: number, max: number) { + if (max < min) return min; + return Math.min(Math.max(value, min), max); +} diff --git a/apps/web/src/components/competition/CompetitionAdminControls.tsx b/apps/web/src/components/competition/CompetitionAdminControls.tsx new file mode 100644 index 00000000..607a0779 --- /dev/null +++ b/apps/web/src/components/competition/CompetitionAdminControls.tsx @@ -0,0 +1,763 @@ +import { useMemo, useRef, useState } from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import type { + CompetitionCommandResponse, + CompetitionDetailResponse, + SeriesAdjudicationDecision, + SeriesProjection, + SeriesReversalMode, + SeriesReversalPreviewResponse, + TeamId, +} from "@lolympus/contracts"; +import { + useAdjudicateCompetitionSeries, + usePreviewCompetitionSeriesReversal, + useReverseCompetitionSeries, +} from "../../api/hooks"; +import { ApiError } from "../../lib/api"; + +type AdjudicationType = SeriesAdjudicationDecision["type"]; + +const ADJUDICATION_LABELS: Record = { + walkover: "부전승", + forfeit: "몰수패", + administrative: "운영자 판정", + "administrative-draw": "운영자 무승부", +}; + +export function CompetitionAdminControls({ + competition, + communityId, + canManage, +}: { + competition: CompetitionDetailResponse; + communityId: string; + canManage: boolean; +}) { + const queryClient = useQueryClient(); + const series = competition.projection.series; + const defaultSeries = + series.find( + (item) => item.status === "ready" || item.status === "in-progress", + ) ?? + series.find((item) => item.status === "completed") ?? + series[0]; + const [selectedSeriesId, setSelectedSeriesId] = useState( + defaultSeries?.seriesId ?? "", + ); + const [adjudicationType, setAdjudicationType] = + useState("walkover"); + const [winnerTeamId, setWinnerTeamId] = useState(""); + const [adjudicationReason, setAdjudicationReason] = useState(""); + const [reversalMode, setReversalMode] = + useState("strict"); + const [reversalReason, setReversalReason] = useState(""); + const [reversalPreview, setReversalPreview] = + useState(null); + const [impactConfirmed, setImpactConfirmed] = useState(false); + const [notice, setNotice] = useState(null); + const adjudicationIdempotencyKeyRef = useRef(null); + const reversalIdempotencyKeyRef = useRef(null); + const adjudicationMutation = useAdjudicateCompetitionSeries(communityId); + const previewMutation = usePreviewCompetitionSeriesReversal(communityId); + const reversalMutation = useReverseCompetitionSeries(communityId); + + const selectedSeries = + series.find((item) => item.seriesId === selectedSeriesId) ?? defaultSeries; + const teamById = useMemo( + () => new Map(competition.teams.map((team) => [team.teamId, team])), + [competition.teams], + ); + const eligibleTeams = selectedSeries + ? selectedSeries.entries.flatMap((entry) => + entry.teamId ? [teamById.get(entry.teamId)] : [], + ) + : []; + const selectedSeriesGames = selectedSeries + ? competition.projection.games.filter( + (game) => game.seriesId === selectedSeries.seriesId, + ) + : []; + const drawAllowed = Boolean( + selectedSeries?.rule.type === "fixed-games" && + selectedSeries.rule.drawPolicy === "allow", + ); + const canAdjudicate = Boolean( + selectedSeries && + (selectedSeries.status === "ready" || + selectedSeries.status === "in-progress"), + ); + const canReverse = selectedSeries?.status === "completed"; + const previewIsCurrent = Boolean( + reversalPreview && reversalPreview.sourceRevision === competition.revision, + ); + const effectiveSelectedSeriesId = selectedSeries?.seriesId ?? ""; + const effectiveWinnerTeamId = eligibleTeams.some( + (team) => team?.teamId === winnerTeamId, + ) + ? winnerTeamId + : (eligibleTeams.find(Boolean)?.teamId ?? ""); + const effectiveAdjudicationType = + adjudicationType === "administrative-draw" && !drawAllowed + ? "administrative" + : adjudicationType === "walkover" && selectedSeriesGames.length > 0 + ? "forfeit" + : adjudicationType; + + if (!canManage || series.length === 0) return null; + + async function invalidateCompetitionCaches( + response?: CompetitionCommandResponse, + ) { + const matchId = String(competition.matchId); + if (response) { + queryClient.setQueryData( + ["competition", communityId, matchId], + response.competition, + ); + } + await Promise.all([ + queryClient.invalidateQueries({ + queryKey: ["competition", communityId, matchId], + }), + queryClient.invalidateQueries({ + queryKey: ["competition-team", communityId, matchId], + }), + queryClient.invalidateQueries({ + queryKey: ["match", communityId, matchId], + }), + queryClient.invalidateQueries({ + queryKey: ["matches", communityId], + }), + queryClient.invalidateQueries({ + queryKey: ["matches-page", communityId], + }), + ]); + } + + function resetCommandFeedback() { + setNotice(null); + adjudicationMutation.reset(); + previewMutation.reset(); + reversalMutation.reset(); + } + + function handleSelectedSeriesChange(nextSeriesId: string) { + const nextSeries = series.find((item) => item.seriesId === nextSeriesId); + const nextHasGames = competition.projection.games.some( + (game) => game.seriesId === nextSeries?.seriesId, + ); + setSelectedSeriesId(nextSeriesId); + setWinnerTeamId(""); + setAdjudicationType(nextHasGames ? "forfeit" : "walkover"); + setAdjudicationReason(""); + setReversalMode("strict"); + setReversalReason(""); + setReversalPreview(null); + setImpactConfirmed(false); + adjudicationIdempotencyKeyRef.current = null; + reversalIdempotencyKeyRef.current = null; + resetCommandFeedback(); + } + + function handleAdjudicationSubmit(event: React.FormEvent) { + event.preventDefault(); + if (!selectedSeries || !canAdjudicate || !adjudicationReason.trim()) { + return; + } + if ( + effectiveAdjudicationType !== "administrative-draw" && + !effectiveWinnerTeamId + ) { + return; + } + + const decision: SeriesAdjudicationDecision = + effectiveAdjudicationType === "administrative-draw" + ? { type: "administrative-draw" } + : { + type: effectiveAdjudicationType, + winnerTeamId: effectiveWinnerTeamId as TeamId, + }; + const idempotencyKey = + adjudicationIdempotencyKeyRef.current ?? + `adjudicate:${selectedSeries.seriesId}:${crypto.randomUUID()}`; + adjudicationIdempotencyKeyRef.current = idempotencyKey; + resetCommandFeedback(); + adjudicationMutation.mutate( + { + matchId: String(competition.matchId), + seriesId: selectedSeries.seriesId, + revision: competition.revision, + idempotencyKey, + request: { + decision, + reason: adjudicationReason.trim(), + }, + }, + { + onSuccess: async (response) => { + adjudicationIdempotencyKeyRef.current = null; + setNotice("Series 판정을 기록했습니다."); + setAdjudicationReason(""); + await invalidateCompetitionCaches(response); + }, + }, + ); + } + + function handlePreviewSubmit(event: React.FormEvent) { + event.preventDefault(); + if (!selectedSeries || !canReverse || !reversalReason.trim()) return; + + resetCommandFeedback(); + setReversalPreview(null); + setImpactConfirmed(false); + previewMutation.mutate( + { + matchId: String(competition.matchId), + seriesId: selectedSeries.seriesId, + revision: competition.revision, + request: { + mode: reversalMode, + reason: reversalReason.trim(), + }, + }, + { + onSuccess: (preview) => { + reversalIdempotencyKeyRef.current = null; + setReversalPreview(preview); + setImpactConfirmed(false); + }, + }, + ); + } + + function handleReverse() { + if ( + !selectedSeries || + !reversalPreview || + !previewIsCurrent || + !impactConfirmed || + !reversalReason.trim() + ) { + return; + } + + const idempotencyKey = + reversalIdempotencyKeyRef.current ?? + `reverse:${selectedSeries.seriesId}:${crypto.randomUUID()}`; + reversalIdempotencyKeyRef.current = idempotencyKey; + resetCommandFeedback(); + reversalMutation.mutate( + { + matchId: String(competition.matchId), + seriesId: selectedSeries.seriesId, + revision: reversalPreview.sourceRevision, + idempotencyKey, + request: { + mode: reversalMode, + reason: reversalReason.trim(), + impactHash: reversalPreview.impactHash, + }, + }, + { + onSuccess: async (response) => { + reversalIdempotencyKeyRef.current = null; + setNotice("Series 결과를 되돌렸습니다."); + setReversalPreview(null); + setImpactConfirmed(false); + setReversalReason(""); + await invalidateCompetitionCaches(response); + }, + }, + ); + } + + const commandError = + adjudicationMutation.error ?? + previewMutation.error ?? + reversalMutation.error; + const commandErrorCode = competitionCommandErrorCode(commandError); + const staleCommand = + (commandError instanceof ApiError && commandError.status === 412) || + commandErrorCode === "REVERSAL_PREVIEW_STALE"; + const commandPending = + adjudicationMutation.isPending || + previewMutation.isPending || + reversalMutation.isPending; + + return ( +
+
+
+

+ Owner / Admin +

+

+ 공식 결과 관리 +

+
+ + revision {competition.revision} + +
+ + + + {notice && ( +

+ {notice} +

+ )} + + {commandError && ( +
+

{competitionCommandErrorMessage(commandError)}

+ {staleCommand && ( + + )} +
+ )} + + {canAdjudicate ? ( +
+

Series 판정

+
+ + + {effectiveAdjudicationType !== "administrative-draw" && ( + + )} +
+ +