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